text
stringlengths 10
2.72M
|
|---|
package com.paragon.sensonic.ui.activities.petdetails;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.DialogFragment;
import com.paragon.sensonic.BR;
import com.paragon.sensonic.R;
import com.paragon.sensonic.databinding.ActivityResidentDetailsBinding;
import com.paragon.sensonic.databinding.RowContactInfoBinding;
import com.paragon.sensonic.databinding.RowIdentificationHolderBinding;
import com.paragon.sensonic.databinding.RowIdentifictionBinding;
import com.paragon.sensonic.databinding.RowResidentInfoBinding;
import com.paragon.sensonic.utils.AppConstant;
import com.paragon.sensonic.utils.CustomItemClickListener;
import com.paragon.sensonic.utils.ProfileMode;
import com.paragon.sensonic.ui.adapters.ProfileFilterAdapter;
import com.paragon.sensonic.ui.fragments.sheets.CalenderBottomDialogFragment;
import com.paragon.sensonic.ui.fragments.sheets.SpinnerBottomDialogFragment;
import com.paragon.brdata.dto.PetsData;
import com.paragon.utils.MultiplePermissionsCallBack;
import com.paragon.utils.RecyclerItemClickListener;
import com.paragon.utils.base.BaseActivity;
import com.paragon.utils.dialogs.DVDialog;
import com.paragon.utils.imagepicker.bundle.PickSetup;
import com.paragon.utils.imagepicker.dialog.PickImageDialog;
import com.karumi.dexter.PermissionToken;
import java.util.Arrays;
import java.util.Objects;
public class PetDetailsActivity extends BaseActivity<ActivityResidentDetailsBinding, PetDetailsViewModel>
implements PetDetailsNavigator {
private final PetDetailsViewModel petDetailsViewModel = new PetDetailsViewModel();
private RowResidentInfoBinding rowResidentInfoBinding;
private RowContactInfoBinding rowContactInfoBinding;
private RowIdentificationHolderBinding rowIdentificationHolderBinding;
private ProfileFilterAdapter filterAdapter;
private PetsData data;
private ProfileMode mode;
private boolean isToolbarItemClick = false;
private SpinnerBottomDialogFragment relationSpinner, occupationSpinner, statusSpinner;
private CalenderBottomDialogFragment calenderBottomDialogFragment;
@Override
public int getBindingVariable() {
return BR.petDetailsVM;
}
@Override
public int getLayoutId() {
return R.layout.activity_resident_details;
}
@Override
public PetDetailsViewModel getViewModel() {
return petDetailsViewModel;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
petDetailsViewModel.setNavigator(this);
petDetailsViewModel.init();
}
@Override
public void init() {
data = (PetsData) getIntent().getSerializableExtra("data");
mode = (ProfileMode) getIntent().getSerializableExtra("mode");
mViewDataBinding.toolbar.toolbarRightImage.setVisibility(View.GONE);
mViewDataBinding.toolbar.toolbarLeftLayout.setOnClickListener(e -> Objects.requireNonNull(this).onBackPressed());
/*add scroll listener on nested scroll*/
final Rect scrollBounds = new Rect();
mViewDataBinding.nestedScroll.getHitRect(scrollBounds);
mViewDataBinding.nestedScroll.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
if (!isToolbarItemClick) {
if (scrollY == 0) {
filterAdapter.setPosition(0);
} else if (mViewDataBinding.container.getChildAt(1) != null) {
if (mViewDataBinding.container.getChildAt(1).getLocalVisibleRect(scrollBounds)) {
if (mViewDataBinding.container.getChildAt(1).getLocalVisibleRect(scrollBounds)
|| scrollBounds.height() > mViewDataBinding.container.getChildAt(1).getHeight()) {
filterAdapter.setPosition(1);
}
}
}
}
});
/*add touch listener*/
mViewDataBinding.nestedScroll.setOnTouchListener((view, motionEvent) -> {
isToolbarItemClick = false;
return false;
});
/*init spinner data resources*/
relationSpinner = new SpinnerBottomDialogFragment(this.getString(R.string.label_relation_to_owner),
Arrays.asList(this.getResources().getStringArray(R.array.label_relation)));
statusSpinner = new SpinnerBottomDialogFragment(this.getString(R.string.label_status),
Arrays.asList(this.getResources().getStringArray(R.array.label_status)));
occupationSpinner = new SpinnerBottomDialogFragment(this.getString(R.string.label_occupation),
Arrays.asList(this.getResources().getStringArray(R.array.label_occupation)));
calenderBottomDialogFragment = new CalenderBottomDialogFragment();
}
@Override
public void setFilterList() {
filterAdapter = new ProfileFilterAdapter(this, Arrays.asList(getResources().getStringArray(R.array.label_filters_pet_details)));
mViewDataBinding.toolbar.toolbarItemList.setAdapter(filterAdapter);
mViewDataBinding.toolbar.toolbarItemList.addOnItemTouchListener(new RecyclerItemClickListener(this, (view, position) -> {
filterAdapter.setPosition(position);
isToolbarItemClick = true;
mViewDataBinding.container.post(() -> {
float y = mViewDataBinding.container.getY() + mViewDataBinding.container.getChildAt(position).getY();
mViewDataBinding.nestedScroll.smoothScrollTo(0, (int) y);
});
}));
}
@Override
public void loadResidentDetailsView() {
rowResidentInfoBinding = DataBindingUtil
.inflate(LayoutInflater.from(this), R.layout.row_resident_info,
mViewDataBinding.container, false);
if (mode.equals(ProfileMode.NEW)) {
mViewDataBinding.toolbar.toolbarTitle.setText(getString(R.string.label_pets));
rowResidentInfoBinding.profileImageView.setImageResource(R.mipmap.ic_friends);
rowResidentInfoBinding.editName.setText(AppConstant.EMPTY);
rowResidentInfoBinding.editPreferredName.setText(AppConstant.EMPTY);
rowResidentInfoBinding.editRelationToOwner.setText(AppConstant.EMPTY);
rowResidentInfoBinding.editStatus.setText(AppConstant.EMPTY);
rowResidentInfoBinding.editOccupation.setText(AppConstant.EMPTY);
rowResidentInfoBinding.editBirthday.setText(AppConstant.EMPTY);
} else {
mViewDataBinding.toolbar.toolbarTitle.setText(data.getName());
rowResidentInfoBinding.profileImageView.setImageResource(R.mipmap.ic_pet_dog);
rowResidentInfoBinding.editName.setText(data.getName());
}
/*image browse*/
rowResidentInfoBinding.rowProfileImage.setOnClickListener(view -> {
requestMultiplePermissions(new MultiplePermissionsCallBack() {
@Override
public void isAllPermissionsGranted() {
PickImageDialog.build(new PickSetup()).setOnPickResult(r -> rowResidentInfoBinding.profileImageView.setImageBitmap(r.getBitmap())).show(getSupportFragmentManager());
}
@Override
public void isAnyPermissionPermanentlyDenied() {
DVDialog.showSettingsDialog(getApplicationContext());
}
@Override
public void somePermissionsDenied() {
showGeneralDialog(getString(R.string.label_alert), getString(R.string.label_denied_permission), getString(R.string.label_ok), null);
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionToken token) {
token.continuePermissionRequest();
}
@Override
public void onError() {
}
}, AppConstant.READ_WRITE_EXTERNAL_STORAGE_AND_CAMERA);
});
mViewDataBinding.container.addView(rowResidentInfoBinding.getRoot());
}
@Override
public void loadContactInfoView() {
rowContactInfoBinding = DataBindingUtil
.inflate(LayoutInflater.from(this), R.layout.row_contact_info,
mViewDataBinding.container, false);
mViewDataBinding.container.addView(rowContactInfoBinding.getRoot());
}
@Override
public void loadIdentificationView() {
rowIdentificationHolderBinding = DataBindingUtil
.inflate(LayoutInflater.from(this), R.layout.row_identification_holder,
mViewDataBinding.container, false);
mViewDataBinding.container.addView(rowIdentificationHolderBinding.getRoot());
}
@Override
public void loadInnerIdentificationItem() {
insertIdentificationRow();
}
@Override
public void onSaveBTNClick() {
}
@Override
public void setRelationshipWithOwnerSpinner() {
rowResidentInfoBinding.rowRelationToOwner.setOnClickListener(view -> {
if (!relationSpinner.isAdded()) {
relationSpinner.setStyle(DialogFragment.STYLE_NORMAL, R.style.TransparentDialog);
relationSpinner.show(getSupportFragmentManager(), null);
/*init click listener*/
relationSpinner.setOnItemClickListener(new CustomItemClickListener() {
@Override
public void onItemClickListener(int position, String value) {
rowResidentInfoBinding.editRelationToOwner.setText(value);
}
});
}
});
}
@Override
public void setBirthdayDatePicker() {
rowResidentInfoBinding.rowBirthday.setOnClickListener(view -> {
if (!calenderBottomDialogFragment.isAdded()) {
calenderBottomDialogFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.TransparentDialog);
calenderBottomDialogFragment.show(getSupportFragmentManager(), null);
/*init click listener*/
calenderBottomDialogFragment.setOnCalendarClickListener(new CustomItemClickListener() {
@Override
public void onItemClickListener(int position, String value) {
rowResidentInfoBinding.editBirthday.setText(value);
}
});
}
});
}
@Override
public void setStatusSpinner() {
rowResidentInfoBinding.rowStatus.setOnClickListener(view -> {
if (!statusSpinner.isAdded()) {
statusSpinner.setStyle(DialogFragment.STYLE_NORMAL, R.style.TransparentDialog);
statusSpinner.show(getSupportFragmentManager(), null);
/*init click listener*/
statusSpinner.setOnItemClickListener(new CustomItemClickListener() {
@Override
public void onItemClickListener(int position, String value) {
rowResidentInfoBinding.editStatus.setText(value);
}
});
}
});
}
@Override
public void setOccupationSpinner() {
rowResidentInfoBinding.rowOccupation.setOnClickListener(view -> {
if (!occupationSpinner.isAdded()) {
occupationSpinner.setStyle(DialogFragment.STYLE_NORMAL, R.style.TransparentDialog);
occupationSpinner.show(getSupportFragmentManager(), null);
/*init click listener*/
occupationSpinner.setOnItemClickListener(new CustomItemClickListener() {
@Override
public void onItemClickListener(int position, String value) {
rowResidentInfoBinding.editOccupation.setText(value);
}
});
}
});
}
@Override
public void setIdTypeSpinner() {
}
/*insert identification items*/
private void insertIdentificationRow() {
RowIdentifictionBinding binding = DataBindingUtil
.inflate(LayoutInflater.from(this), R.layout.row_identifiction,
rowIdentificationHolderBinding.rowHolder, false);
if (mode.equals(ProfileMode.NEW)) {
binding.editIdNumber.setText(AppConstant.EMPTY);
binding.editIdType.setText(AppConstant.EMPTY);
} else {
binding.editIdType.setText(data.getType());
binding.idImageView.setImageResource(R.mipmap.ic_dog_rc);
}
rowIdentificationHolderBinding.rowHolder.addView(binding.getRoot());
}
}
|
package deloitte.forecastsystem_bih.service;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.data.repository.query.Param;
import deloitte.forecastsystem_bih.model.MknnWeekends;
import deloitte.forecastsystem_bih.model.MknnWorkingDays;
public interface MknnWorkingDaysService {
List<MknnWorkingDays> findAll();
Optional<MknnWorkingDays> findById(Long id);
public List<MknnWorkingDays> findByParams(Date p_forecastDate, Integer p_month, Integer p_temp_step, Double p_maxTemperature, Double p_minTemperature);
public List<Double> findLoadByParams(Date p_forecastDate, Integer p_month, Integer p_temp_step, Double p_maxTemperature, Double p_minTemperature);
public List<Date> findByDatesParams(Date p_forecastDate, Integer p_month, Integer p_temp_step, Double p_maxTemperature, Double p_minTemperature);
public List<Date> findDates(Date p_forecastDate);
public List<MknnWorkingDays> findDay(Date p_forecastDate);
public List<Double> findLoadsByDay(Date p_forecastDate);
public List<Double> findLoadsByDay2(Integer p_dan, Integer p_mesec, Integer p_godina);
}
|
package com.myvodafone.android.front.netperform.pojo;
import java.io.Serializable;
/**
* Created by d.alexandrakis on 16/12/2016.
*/
public class SpeedResultItem implements Serializable {
private String uploadSpeed;
private String downloadSpeed;
private String ping;
private String details;
private String networkName;
private String dateString;
private double langt;
private double longt;
public String getUploadSpeed() {
return uploadSpeed;
}
public void setUploadSpeed(String uploadSpeed) {
this.uploadSpeed = uploadSpeed;
}
public String getDownloadSpeed() {
return downloadSpeed;
}
public void setDownloadSpeed(String downloadSpeed) {
this.downloadSpeed = downloadSpeed;
}
public String getPing() {
return ping;
}
public void setPing(String ping) {
this.ping = ping;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getNetworkName() {
return networkName;
}
public void setNetworkName(String networkName) {
this.networkName = networkName;
}
public String getDateString() {
return dateString;
}
public void setDateString(String dateString) {
this.dateString = dateString;
}
public double getLangt() {
return langt;
}
public void setLangt(double langt) {
this.langt = langt;
}
public double getLongt() {
return longt;
}
public void setLongt(double longt) {
this.longt = longt;
}
}
|
package io.github.satr.aws.lambda.bookstore.strategies.intenthandler;
// Copyright © 2020, github.com/satr, MIT License
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import io.github.satr.aws.lambda.bookstore.entity.Book;
import io.github.satr.aws.lambda.bookstore.entity.formatter.BookListFormatter;
import io.github.satr.aws.lambda.bookstore.request.Request;
import io.github.satr.aws.lambda.bookstore.response.Response;
import io.github.satr.aws.lambda.bookstore.services.SearchBookResultService;
import java.util.List;
public class ShowSearchBookResultIntentHandlerStrategy extends AbstractIntentHandlerStrategy {
private final SearchBookResultService searchBookResultService;
public ShowSearchBookResultIntentHandlerStrategy(SearchBookResultService searchBookResultService) {
this.searchBookResultService = searchBookResultService;
}
@Override
public Response handle(Request request, LambdaLogger logger) {
List<Book> bookList = searchBookResultService.getList();
String message = bookList.isEmpty()
? "Last search result is empty."
: BookListFormatter.getShortDescriptionList(bookList, "Last search result:\n");
return getCloseFulfilledLexRespond(request, message);
}
}
|
package org.oa.teach_fragments.app;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
private TextView textView;
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = (TextView) view.findViewById(android.R.id.text1);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle arguments = getArguments();
int index = arguments.getInt("index");
textView.append("\n" + index);
}
}
|
package com.esum.wp.ims.systemconfig.service.impl;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.esum.appframework.service.impl.BaseService;
import com.esum.framework.common.util.SequenceProperties;
import com.esum.framework.common.util.SysUtil;
import com.esum.wp.ims.systemconfig.SystemConfig;
import com.esum.wp.ims.systemconfig.service.ISystemConfigService;
public class SystemConfigService extends BaseService implements ISystemConfigService {
public Object modifyConfig(Object object) {
//TODO : 로직이 맞지 않음.
// SequenceProperties config = new SequenceProperties();
//
// String home = System.getProperty("xtrus.home");
// if (home == null || home.equals("")) {
// try {
// home = System.setProperty("xtrus.home", SysUtil.getEnv("XTRUS_HOME"));
// } catch (Exception e) {};
// }
// if (home == null || home.equals(""))
// return null;
//
// SystemConfig sysConf = (SystemConfig)object;
//
// try {
// config.load(new FileInputStream(home + sysConf.getConfigFile()));
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// return null;
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// return null;
// }
// sysConf.setConfigList(config);
// return sysConf;
return null;
}
}
|
package com.uav.rof.util;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.util.SparseArray;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import com.uav.rof.R;
import com.uav.rof.volley.VolleyUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Utility {
static int errorColor;
public static SpannableStringBuilder getErrorSpannableString(Context context, String msg){
int version = Build.VERSION.SDK_INT;
//Get the defined errorColor from color resource.
if (version >= 23) {
errorColor = ContextCompat.getColor(context, R.color.errorColor);
} else {
errorColor = context.getResources().getColor(R.color.errorColor);
}
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(errorColor);
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(msg);
spannableStringBuilder.setSpan(foregroundColorSpan, 0, msg.length(), 0);
return spannableStringBuilder;
}
public static String imagetostring (Uri mImageUri,Context context){
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
Bitmap bmp= VolleyUtils.grabImage(mImageUri,context);
bmp= Utility.scaleDown(bmp, 1100, true);
if(bmp.getWidth()>bmp.getHeight()){
Matrix matrix =new Matrix();
matrix.postRotate(90);
bmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true);
}
/*Bitmap bmp1= Bitmap.createScaledBitmap(
bitmap, 320, 500, false);*/
bmp.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
byte[] imageBytes =outputStream.toByteArray();
return Base64.encodeToString(imageBytes,Base64.DEFAULT);
}
public static String getStackTrace(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}
//15-1-2019
public static Bitmap ByteArrayToBitmap(byte[] byteArray){
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(byteArray);
Bitmap bitmap = BitmapFactory.decodeStream(arrayInputStream);
return bitmap;
}
public static String currentDateFormat(){
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.SSSSSS");
String currentTimeStamp=dateFormat.format(new Date());
return currentTimeStamp;
}
public static File storeCameraPhotoInSDCard(Bitmap bitmap ,String currentdate){
// File outputFile = new File(Environment.getExternalStorageDirectory(),"photo_"+currentdate);
File direct = new File(Environment.getExternalStorageDirectory() + "/ROF");
if (!direct.exists()) {
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory()+"/"+"ROF/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File(Environment.getExternalStorageDirectory()+"/"+"ROF/"), "photo_"+currentdate+".JPEG");
/*if (file.exists()) {
file.delete();
}*/
try {
FileOutputStream fileOutputStream=new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
public static Bitmap getImageFileFromSDCared(File filename){
Bitmap bitmap=null;
try {
FileInputStream fis=new FileInputStream(filename);
bitmap= BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap;
}
public static String getImageByPincode(Context context,Bitmap bitmap){
TextRecognizer textRecognizer = new TextRecognizer.Builder(context).build();
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> textBlocks = textRecognizer.detect(frame);
StringBuilder stringBuilder = new StringBuilder();
for (int index = 0; index < textBlocks.size(); index++) {
//extract scanned text blocks here
TextBlock item = textBlocks.valueAt(index);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
String value=stringBuilder.toString().replaceAll(" ", "");
String replaceString=value.toString().replaceAll("\n", "");
int i=0;
String nos = "";
List<String> digitsArray = new ArrayList<String>();
while(replaceString.length()>i){
Character ch = replaceString.charAt(i);
if(Character.isDigit(ch)){
nos += ch;
}else if(nos!=""){
digitsArray.add(nos);
nos ="";
}
i++;
}
String pincode=null;
for(String p : digitsArray){
if(p.length()==6){
pincode=p;
break;
}
}
return pincode;
}
public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
boolean filter) {
float ratio = Math.min(
(float) maxImageSize / realImage.getWidth(),
(float) maxImageSize / realImage.getHeight());
int width = Math.round((float) ratio * realImage.getWidth());
int height = Math.round((float) ratio * realImage.getHeight());
Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
height, filter);
return newBitmap;
}
public static void alertDialog(Context context,String title ,String msg , String buttonname){
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(msg);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, buttonname, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
alertDialog.show();
}
}
|
package com.example.administrator.nineoldandroidsdemo;
import android.animation.LayoutTransition;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import butterknife.Bind;
import butterknife.ButterKnife;
public class LayoutAnimaActivity extends AppCompatActivity {
@Bind(R.id.id_container)
LinearLayout idContainer;
private int mVal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout_anima);
ButterKnife.bind(this);
//mAdapter=new ArrayAdapter<View>(this,android.R.layout.simple_list_item_1);
//mListview.setAdapter(mAdapter);
////默认动画全部开启
idContainer.setLayoutTransition(new LayoutTransition());
}
/**
* LayoutTransition.APPEARING 当一个View在ViewGroup中出现时,对此View设置的动画
*
* LayoutTransition.CHANGE_APPEARING 当一个View在ViewGroup中出现时,对此View对其他View位置造成影响,对其他View设置的动画
*
* LayoutTransition.DISAPPEARING 当一个View在ViewGroup中消失时,对此View设置的动画
*
* LayoutTransition.CHANGE_DISAPPEARING 当一个View在ViewGroup中消失时,对此View对其他View位置造成影响,对其他View设置的动画
*
* LayoutTransition.CHANGE 不是由于View出现或消失造成对其他View位置造成影响,然后对其他View设置的动画。
*/
private void test(){
LayoutTransition mTransition=new LayoutTransition();
mTransition.setAnimator(LayoutTransition.APPEARING,mTransition.getAnimator(LayoutTransition.APPEARING));
}
public void addBtn(View view) {
final Button button = new Button(this);
button.setText((++mVal) + "");
idContainer.addView(button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
idContainer.removeView(button);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_layout_anima, menu);
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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
super.onDestroy();
ButterKnife.unbind(this);
}
}
|
package com.qfc.yft.utils;
import org.json.JSONException;
import android.content.Context;
import android.util.Log;
import com.qfc.yft.YftApplication;
import com.qfc.yft.net.HttpReceiver;
public class TestDataTracker {
static final String TAG = "TestDataTracker";
/*public static final String REQUEST_PATH_COMPANY_PRO ="open.api.product.findSeriesByShopIdForIphone"; //获取产品系列
public static final String REQUEST_PATH_COMPANY_SUBPRO ="open.api.product.searchProductByShopIdAndSeriesIdForIphone"; //系列下所有产品
public static final String REQUEST_PATH_RECOMMEND ="open.api.shop.searchShopForIphone"; //企业推荐
public static final String REQUEST_PATH_SEARCH ="open.api.shop.searchShopForIphone"; //企业搜索接口
public static final String REQUEST_PATH_CHECKVERSION ="cn.shop.getIOSVersionConfig"; //检查最新客户端版本
public static final String REQUEST_PATH_LOGIN ="cn.member.sso.pointVerify"; //验证登录
public static final String REQUEST_PATH_MEMBER_INFO ="cn.member.getMemberByUserCode";//获取用户信息
public static final String REQUEST_PATH_COMPANY_INFO ="cn.shop.getShopAndCompanyById";//获取公司信息
// public static final String REQUEST_PATH_SYNC = "cn.motion.basic.parseOffLineData";//同步 1113
public static final String REQUEST_PATH_SYNC = "cn.motion.basic.parseOffLineDataForAndriod";//1122
public static final String REQUEST_PATH_SERIESFORMOTION = "cn.product.series.getSeriesForMotion";//1128
public static final String REQUEST_PATH_PRODUCTFORMOTION = "cn.product.getProductForMotion1";//1128*/
public static String fetchDataString(String dataKey){
String fetch = JackUtils.readFromFile(getContext() , shortenFilename(dataKey));
Log.i(TAG, fetch);
return fetch;
}
private static String shortenFilename(String dataKey){
try {
return dataKey.substring(dataKey.charAt(dataKey.lastIndexOf(".")));
} catch (Exception e) {
return dataKey;
}
}
private static Context getContext(){
return YftApplication.app();
}
public static void simulateConnection(HttpReceiver receiver,String dataKey){
try {
receiver.response("{"+fetchDataString(dataKey));
} catch (JSONException e) {
Log.e(TAG, "simulateConnection json error");
e.printStackTrace();
}
}
public static boolean settleDataString(String dataKey, String content){
return JackUtils.writeToFile(getContext(), shortenFilename(dataKey), content);
}
}
|
package boletin6;
public class Cuenta {
private String nombreCliente;
private String numeroCuenta;
private double saldo;
public Cuenta(String nCliente, String nCuenta, double sal){
nombreCliente = nCliente;
numeroCuenta = nCuenta;
saldo = sal;
}
public Cuenta(){
nombreCliente = "";
numeroCuenta = "";
saldo = 0;
}
public void setSaldo(double sald ){
saldo = sald;
}
public void setNombre(String nom){
nombreCliente = nom;
}
public void setNumero(String num){
numeroCuenta = num;
}
public double getSaldo(){
return saldo;
}
public boolean ingreso(double x){
if (x >= 0){
saldo += x;
return true;
}
else {
System.out.println("Introduce un valor positivo");
return false;
}
}
public boolean reintegro(double x){
if (x >= 0){
saldo -= x;
return true;
}
else {
System.out.println("Introduce un valor positivo");
return false;
}
}
public void enseñar(){
System.out.println("Nombre: " + nombreCliente);
System.out.println("Numero de cuenta: " + numeroCuenta);
System.out.println("Saldo en cuenta: " + saldo + "€");
}
public void transferencia(Cuenta cuentaDestino, double importe){
if (saldo>importe) {
cuentaDestino.ingreso(importe);
saldo -= importe;
}
else System.out.println("La operacion no se puede realizar");
}
}
|
import java.util.Set;
import java.util.HashSet;
public class LinkedList {
private class Node {
Node next;
int value;
public String toString() {
return Integer.toString(value);
}
}
private Node head;
public void insert(int p, int value) throws Exception {
Node node = new Node();
node.value = value;
if(p == 0) {
node.next = head;
head = node;
} else {
Node tmp = head;
int c = 0;
while(tmp != null && c < p - 1) {
c++;
tmp = tmp.next;
}
if(c == p - 1) {
node.next = tmp.next;
tmp.next = node;
} else {
throw new Exception("Out of range!");
}
}
}
public void remove(int p) throws Exception {
if(head == null) {
throw new Exception("Empty!");
} else {
if(p == 0) {
head = head.next;
} else {
Node tmp = head;
for(int i = 0; i < p - 1; i++)
if(tmp != null)
tmp = tmp.next;
else
throw new Exception("Out of range!");
if(tmp != null && tmp.next != null)
tmp.next = tmp.next.next;
else
throw new Exception("Out of range!");
}
}
}
public Node nthNodeFromLast(int n) throws Exception {
Node tmp = head;
while((tmp != null) && n > 0) {
tmp = tmp.next;
n--;
}
if(tmp == null) {
throw new Exception("Out of range!");
} else {
Node nth = head;
while(tmp.next != null) {
tmp = tmp.next;
nth = nth.next;
}
return nth;
}
}
public String toString() {
if(head == null)
return "";
else {
StringBuffer sb = new StringBuffer();
sb.append("[");
Node tmp = head;
while(tmp != null) {
sb.append(tmp.value + ", ");
tmp = tmp.next;
}
sb.setLength(sb.length() - 2);
sb.append("]");
return sb.toString();
}
}
public void insertToSortedList(int value) {
Node node = new Node();
node.value = value;
if(head == null) {
head = node;
} else {
if(head.value > value) {
node.next = head;
head = node;
} else {
Node tmp = head;
while(tmp.next != null && tmp.next.value < value)
tmp = tmp.next;// tmp won't be null;
node.next = tmp.next;
tmp.next = node;
}
}
}
public void reverse() {
this.head = reverseSub(head);
}
public Node reverseSub(Node head) {
// head以下を反転し、headを返す
if(head == null) {
return null;
} else if(head.next == null) {
// 1個
return head;
} else {
Node nextNode = head.next;
Node newHead = reverseSub(nextNode);
head.next = null;
nextNode.next = head;
return newHead;
}
}
public Node findMiddle() {
Node fast = head;
Node slow = head;
while(true) {
if(fast.next == null)
return slow;
else
fast = fast.next;
if(fast.next == null) {
return slow;
} else {
fast = fast.next;
slow = slow.next;
}
}
}
public void printReverse() {
printReverseSub(head);
}
private void printReverseSub(Node head) {
if(head == null) {
return;
} else {
printReverseSub(head.next);
System.out.println(head.value);
}
}
public boolean isOdd() {
boolean res = true;
Node tmp = head;
while(tmp != null) {
tmp = tmp.next;
res = !res;
}
return res;
}
public boolean isEven() {
return !isOdd();
}
public void removeDups() {
if(head == null || head.next == null) {
return;
} else {
Node p = head;
Set<Integer> memo = new HashSet<Integer>();
memo.add(p.value);
while(p.next != null) {
if(memo.contains(p.next.value)) {
p.next = p.next.next;
} else {
memo.add(p.next.value);
p = p.next;
}
}
}
}
public void removeDups2() {
if(head == null || head.next == null) {
return ;
} else {
Node tmp, p;
int v;
p = head;
while(p.next != null) {
tmp = p;
v = tmp.value;
while(tmp.next != null) {
if(tmp.next.value == v)
tmp.next = tmp.next.next;
else
if(tmp.next != null)
tmp = tmp.next;
}
p = p.next;
}
}
}
public Node lastKthNode(int k) throws Exception {
Node p, q;
p = head;
q = head;
while(k > 0 && q.next != null) {
q = q.next;
k--;
}
if(k != 0)
throw new Exception("Out of bound");
while(q != null) {
q = q.next;
p = p.next;
}
return p;
}
public void moveSmallerThan(int n) {
if(head == null)
return;
Node tmp = head;
Node next;
while(tmp.next != null) {
if(tmp.next.value < n) {
next = tmp.next;
tmp.next = next.next;
next.next = head;
head = next;
} else {
if(tmp.next != null)
tmp = tmp.next;
}
}
}
public static void main(String[] args) throws Exception {
LinkedList list = new LinkedList();
System.out.println(list);
list.insert(0, 5);
list.insert(0, 2);
list.insert(0, 3);
list.insert(0, 2);
list.insert(0, 2);
list.insert(0, 4);
System.out.println(list);
list.moveSmallerThan(3);
System.out.println(list);
list.moveSmallerThan(4);
System.out.println(list);
}
}
|
/*
* Origin of the benchmark:
* repo: https://github.com/diffblue/cbmc.git
* branch: develop
* directory: regression/jbmc-strings/StaticCharMethods05
* The benchmark was taken from the repo: 24 January 2018
*/
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int radix = scanner.nextInt();
int choice = scanner.nextInt() % 3;
assert choice>=0 && choice<3;
switch (choice)
{
case 1: // convert digit to character
System.out.println("Enter a digit:");
int digit = scanner.nextInt();
System.out.printf("Convert digit to character: %s\n",
Character.forDigit(digit, radix));
char tmp=Character.forDigit(digit, radix);
assert tmp=='t';
break;
case 2: // convert character to digit
System.out.println("Enter a character:");
char character = scanner.next().charAt(0);
System.out.printf("Convert character to digit: %s\n",
Character.digit(character, radix));
break;
}
}
}
|
package com.domineer.triplebro.mistakebook.controllers;
import android.content.Context;
import com.domineer.triplebro.mistakebook.models.ErrorInfo;
import com.domineer.triplebro.mistakebook.providers.DataBaseProvider;
import java.util.List;
import java.util.Map;
/**
* @author Domineer
* @data 2019/11/17,13:54
* ----------为梦想启航---------
* --Set Sell For Your Dream--
*/
public class HomeController {
private Context context;
private final DataBaseProvider dataBaseProvider;
public HomeController(Context context) {
this.context = context;
dataBaseProvider = new DataBaseProvider(context);
}
public List<ErrorInfo> getAllErrorInfo() {
return null;
}
public int addErrorInfo(String errorContentTitle, int typeId, int user_id) {
return dataBaseProvider.addErrorInfo(errorContentTitle,typeId,user_id);
}
public int addAnswerInfo(String answerContentTitle, int errorId, int user_id) {
return dataBaseProvider.addAnswerInfo(answerContentTitle,errorId,user_id);
}
public Map<String, Integer> getErrorInfoMap(int user_id) {
Map<String, Integer> errorInfoMap = dataBaseProvider.getErrorInfoMap(user_id);
return errorInfoMap;
}
public Map<String, Integer> getTypeInfoMap() {
Map<String, Integer> typeInfoMap = dataBaseProvider.getTypeInfoMap();
return typeInfoMap;
}
public void addErrorImageInfo(int errorInfoId, List<String> data) {
dataBaseProvider.addErrorImageInfo(errorInfoId,data);
}
public void addAnswerImageInfo(int answerInfoId, List<String> data) {
dataBaseProvider.addAnswerImageInfo(answerInfoId,data);
}
}
|
import java.util.Scanner;
public class task1 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Which month you were born?");
String month=scan.nextLine();
String season;
if ((month .equals("January"))|| (month.equals("February")) || (month.equals("December"))) {
season="Winter";}
else if ((month.equals("March"))|| (month.equals("April"))|| (month.equals("May"))) {
season="Spring";}
else if ((month.equals("June"))|| (month.equals("July"))||(month.equals("August"))) {
season="Summer";}
else{ season="Fall";}
System.out.println("The season that you were born is "+ season);
}
}
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package art;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.ref.*;
import java.lang.reflect.*;
import java.util.*;
public class Test1975 {
public static void run() throws Exception {
Redefinition.setTestConfiguration(Redefinition.Config.COMMON_REDEFINE);
doTest();
}
private static final boolean PRINT_NONDETERMINISTIC = false;
public static WeakHashMap<Object, Long> id_nums = new WeakHashMap<>();
public static long next_id = 0;
public static String printGeneric(Object o) {
Long id = id_nums.get(o);
if (id == null) {
id = Long.valueOf(next_id++);
id_nums.put(o, id);
}
if (o == null) {
return "(ID: " + id + ") <NULL>";
}
Class oc = o.getClass();
if (oc.isArray() && oc.getComponentType() == Byte.TYPE) {
return "(ID: "
+ id
+ ") "
+ Arrays.toString(Arrays.copyOf((byte[]) o, 10)).replace(']', ',')
+ " ...]";
} else {
return "(ID: " + id + ") " + o.toString();
}
}
// Since we are adding fields we redefine this class with the Transform1975 class to add new
// field-reads.
public static final class ReadTransformFields implements Runnable {
public void run() {
System.out.println("Read CUR_CLASS field: " + printGeneric(Transform1975.CUR_CLASS));
System.out.println(
"Read REDEFINED_DEX_BYTES field: " + printGeneric(Transform1975.REDEFINED_DEX_BYTES));
}
}
/* Base64 encoded dex file for:
* public static final class ReadTransformFields implements Runnable {
* public void run() {
* System.out.println("Read CUR_CLASS field: " + printGeneric(Transform1975.CUR_CLASS));
* System.out.println("Read REDEFINED_DEX_BYTES field: " + printGeneric(Transform1975.REDEFINED_DEX_BYTES));
* System.out.println("Read NEW_STRING field: " + printGeneric(Transform1975.NEW_STRING));
* }
* }
*/
private static final byte[] NEW_READ_BYTES =
Base64.getDecoder()
.decode(
"ZGV4CjAzNQCHIfWvfkMos9E+Snhux5rSGhnDAbiVJlyYBgAAcAAAAHhWNBIAAAAAAAAAANQFAAAk"
+ "AAAAcAAAAA4AAAAAAQAABQAAADgBAAAEAAAAdAEAAAgAAACUAQAAAQAAANQBAACkBAAA9AEAAO4C"
+ "AAD2AgAAAQMAAAQDAAAIAwAALAMAADwDAABRAwAAdQMAAJUDAACsAwAAvwMAANMDAADpAwAA/QMA"
+ "ABgEAAAsBAAAOAQAAE0EAABlBAAAfgQAAKAEAAC1BAAAxAQAAMcEAADLBAAAzwQAANwEAADkBAAA"
+ "6gQAAO8EAAD9BAAABgUAAAsFAAAVBQAAHAUAAAQAAAAFAAAABgAAAAcAAAAIAAAACQAAAAoAAAAL"
+ "AAAADAAAAA0AAAAOAAAADwAAABcAAAAZAAAAAgAAAAkAAAAAAAAAAwAAAAkAAADgAgAAAwAAAAoA"
+ "AADoAgAAFwAAAAwAAAAAAAAAGAAAAAwAAADoAgAAAgAGAAEAAAACAAkAEAAAAAIADQARAAAACwAF"
+ "AB0AAAAAAAMAAAAAAAAAAwAgAAAAAQABAB4AAAAFAAQAHwAAAAcAAwAAAAAACgADAAAAAAAKAAIA"
+ "GwAAAAoAAAAhAAAAAAAAABEAAAAHAAAA2AIAABYAAADEBQAAowUAAAAAAAABAAEAAQAAAMYCAAAE"
+ "AAAAcBAEAAAADgAFAAEAAgAAAMoCAABVAAAAYgADAGIBAABxEAIAAQAMASICCgBwEAUAAgAaAxIA"
+ "biAGADIAbiAGABIAbhAHAAIADAFuIAMAEABiAAMAYgECAHEQAgABAAwBIgIKAHAQBQACABoDFABu"
+ "IAYAMgBuIAYAEgBuEAcAAgAMAW4gAwAQAGIAAwBiAQEAcRACAAEADAEiAgoAcBAFAAIAGgMTAG4g"
+ "BgAyAG4gBgASAG4QBwACAAwBbiADABAADgAEAA4ABgAOARwPARwPARwPAAABAAAACAAAAAEAAAAH"
+ "AAAAAQAAAAkABjxpbml0PgAJQ1VSX0NMQVNTAAFMAAJMTAAiTGFydC9UZXN0MTk3NSRSZWFkVHJh"
+ "bnNmb3JtRmllbGRzOwAOTGFydC9UZXN0MTk3NTsAE0xhcnQvVHJhbnNmb3JtMTk3NTsAIkxkYWx2"
+ "aWsvYW5ub3RhdGlvbi9FbmNsb3NpbmdDbGFzczsAHkxkYWx2aWsvYW5ub3RhdGlvbi9Jbm5lckNs"
+ "YXNzOwAVTGphdmEvaW8vUHJpbnRTdHJlYW07ABFMamF2YS9sYW5nL0NsYXNzOwASTGphdmEvbGFu"
+ "Zy9PYmplY3Q7ABRMamF2YS9sYW5nL1J1bm5hYmxlOwASTGphdmEvbGFuZy9TdHJpbmc7ABlMamF2"
+ "YS9sYW5nL1N0cmluZ0J1aWxkZXI7ABJMamF2YS9sYW5nL1N5c3RlbTsACk5FV19TVFJJTkcAE1JF"
+ "REVGSU5FRF9ERVhfQllURVMAFlJlYWQgQ1VSX0NMQVNTIGZpZWxkOiAAF1JlYWQgTkVXX1NUUklO"
+ "RyBmaWVsZDogACBSZWFkIFJFREVGSU5FRF9ERVhfQllURVMgZmllbGQ6IAATUmVhZFRyYW5zZm9y"
+ "bUZpZWxkcwANVGVzdDE5NzUuamF2YQABVgACVkwAAltCAAthY2Nlc3NGbGFncwAGYXBwZW5kAARu"
+ "YW1lAANvdXQADHByaW50R2VuZXJpYwAHcHJpbnRsbgADcnVuAAh0b1N0cmluZwAFdmFsdWUAdn5+"
+ "RDh7ImNvbXBpbGF0aW9uLW1vZGUiOiJkZWJ1ZyIsIm1pbi1hcGkiOjEsInNoYS0xIjoiYTgzNTJm"
+ "MjU0ODg1MzYyY2NkOGQ5MDlkMzUyOWM2MDA5NGRkODk2ZSIsInZlcnNpb24iOiIxLjYuMjAtZGV2"
+ "In0AAgMBIhgBAgQCGgQZHBcVAAABAQCBgAT0AwEBjAQAAAAAAAAAAgAAAJQFAACaBQAAuAUAAAAA"
+ "AAAAAAAAAAAAABAAAAAAAAAAAQAAAAAAAAABAAAAJAAAAHAAAAACAAAADgAAAAABAAADAAAABQAA"
+ "ADgBAAAEAAAABAAAAHQBAAAFAAAACAAAAJQBAAAGAAAAAQAAANQBAAABIAAAAgAAAPQBAAADIAAA"
+ "AgAAAMYCAAABEAAAAwAAANgCAAACIAAAJAAAAO4CAAAEIAAAAgAAAJQFAAAAIAAAAQAAAKMFAAAD"
+ "EAAAAgAAALQFAAAGIAAAAQAAAMQFAAAAEAAAAQAAANQFAAA=");
static void ReadFields() throws Exception {
Runnable r = new ReadTransformFields();
System.out.println("Reading with reflection.");
for (Field f : Transform1975.class.getFields()) {
System.out.println(f.toString() + " = " + printGeneric(f.get(null)));
}
System.out.println("Reading normally in same class.");
Transform1975.readFields();
System.out.println("Reading with native.");
readNativeFields(Transform1975.class, getNativeFields(Transform1975.class.getFields()));
System.out.println("Reading normally in other class.");
r.run();
System.out.println("Reading using method handles.");
readMethodHandles(getMethodHandles(Transform1975.class.getFields()));
System.out.println("Doing modification maybe");
Transform1975.doSomething();
System.out.println("Reading with reflection after possible modification.");
for (Field f : Transform1975.class.getFields()) {
System.out.println(f.toString() + " = " + printGeneric(f.get(null)));
}
System.out.println("Reading normally in same class after possible modification.");
Transform1975.readFields();
System.out.println("Reading with native after possible modification.");
readNativeFields(Transform1975.class, getNativeFields(Transform1975.class.getFields()));
System.out.println("Reading normally in other class after possible modification.");
r.run();
System.out.println("Reading using method handles.");
readMethodHandles(getMethodHandles(Transform1975.class.getFields()));
}
public static final class MethodHandleWrapper {
private MethodHandle mh;
private Field f;
public MethodHandleWrapper(MethodHandle mh, Field f) {
this.f = f;
this.mh = mh;
}
public MethodHandle getHandle() {
return mh;
}
public Field getField() {
return f;
}
public Object invoke() throws Throwable {
return mh.invoke();
}
public String toString() {
return mh.toString();
}
}
public static MethodHandleWrapper[] getMethodHandles(Field[] fields) throws Exception {
final MethodHandles.Lookup l = MethodHandles.lookup();
MethodHandleWrapper[] res = new MethodHandleWrapper[fields.length];
for (int i = 0; i < res.length; i++) {
res[i] = new MethodHandleWrapper(l.unreflectGetter(fields[i]), fields[i]);;
}
return res;
}
public static void readMethodHandles(MethodHandleWrapper[] handles) throws Exception {
for (MethodHandleWrapper h : handles) {
try {
System.out.println(printGeneric(h) + " (" + h.getField() + ") = " + printGeneric(h.invoke()));
} catch (Throwable t) {
if (t instanceof Exception) {
throw (Exception)t;
} else if (t instanceof Error) {
throw (Error)t;
} else {
throw new RuntimeException("Unexpected throwable thrown!", t);
}
}
}
}
public static void doTest() throws Exception {
// TODO It would be good to have a test of invoke-custom too but since that requires smali and
// internally we just store the resolved MethodHandle this should all be good enough.
// Grab Field objects from before the transformation.
Field[] old_fields = Transform1975.class.getFields();
for (Field f : old_fields) {
System.out.println("Saving Field object " + printGeneric(f) + " for later");
}
// Grab jfieldIDs from before the transformation.
long[] old_native_fields = getNativeFields(Transform1975.class.getFields());
// Grab MethodHandles from before the transformation.
MethodHandleWrapper[] handles = getMethodHandles(Transform1975.class.getFields());
for (MethodHandleWrapper h : handles) {
System.out.println("Saving MethodHandle object " + printGeneric(h) + " for later");
}
// Grab a 'setter' MethodHandle from before the redefinition.
Field cur_class_field = Transform1975.class.getDeclaredField("CUR_CLASS");
MethodHandleWrapper write_wrapper = new MethodHandleWrapper(MethodHandles.lookup().unreflectSetter(cur_class_field), cur_class_field);
System.out.println("Saving writable MethodHandle " + printGeneric(write_wrapper) + " for later");
// Read the fields in all possible ways.
System.out.println("Reading fields before redefinition");
ReadFields();
// Redefine the transform class. Also change the ReadTransformFields so we don't have to deal
// with annoying compilation stuff.
Redefinition.doCommonStructuralClassRedefinition(
Transform1975.class, Transform1975.REDEFINED_DEX_BYTES);
Redefinition.doCommonClassRedefinition(
ReadTransformFields.class, new byte[] {}, NEW_READ_BYTES);
// Read the fields in all possible ways.
System.out.println("Reading fields after redefinition");
ReadFields();
// Check that the old Field, jfieldID, and MethodHandle objects were updated.
System.out.println("reading reflectively with old reflection objects");
for (Field f : old_fields) {
System.out.println("OLD FIELD OBJECT: " + f.toString() + " = " + printGeneric(f.get(null)));
}
System.out.println("reading natively with old jfieldIDs");
readNativeFields(Transform1975.class, old_native_fields);
// Make sure the fields keep the same id.
System.out.println("reading natively with new jfieldIDs");
long[] new_fields = getNativeFields(Transform1975.class.getFields());
Arrays.sort(old_native_fields);
Arrays.sort(new_fields);
boolean different = new_fields.length == old_native_fields.length;
for (int i = 0; i < old_native_fields.length && !different; i++) {
different = different || new_fields[i] != old_native_fields[i];
}
if (different) {
System.out.println(
"Missing expected fields! "
+ Arrays.toString(new_fields)
+ " vs "
+ Arrays.toString(old_native_fields));
}
// Make sure the old handles work.
System.out.println("Reading with old method handles");
readMethodHandles(handles);
System.out.println("Reading with new method handles");
readMethodHandles(getMethodHandles(Transform1975.class.getFields()));
System.out.println("Writing " + printGeneric(Test1975.class) + " to CUR_CLASS with old method handle");
try {
write_wrapper.getHandle().invokeExact(Test1975.class);
} catch (Throwable t) {
throw new RuntimeException("something threw", t);
}
System.out.println("Reading changed value");
System.out.println("CUR_CLASS is now " + printGeneric(Transform1975.CUR_CLASS));
}
private static void printNativeField(long id, Field f, Object value) {
System.out.println(
"Field" + (PRINT_NONDETERMINISTIC ? " " + id : "") + " " + f + " = " + printGeneric(value));
}
public static native long[] getNativeFields(Field[] fields);
public static native void readNativeFields(Class<?> field_class, long[] sfields);
}
|
package com.example.jobs.senior1;
/**
* Created by jobs on 09-Jan-17.
*/
import android.accounts.Account;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ContactListAdapter extends BaseAdapter {
Context mContext;
// List<ContactListResponse> list;
private static final String TAG = "ContactListAdapter";
private static ArrayList<CardListResponse> card;
public ContactListAdapter(Context context, ArrayList<CardListResponse> card) {
this.mContext = context;
// this.list = list;
this.card = card;
Log.d(TAG, "Contact size:" + card.size());
}
@Override
public int getCount() {
return card.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
public String getId(int position) {
return card.get(position).getId();
}
public View getView(int position, View view, ViewGroup parent) {
Log.d(TAG,"Index:"+position+" "+card.get(position).getFname());
if(position!=0&&card.get(position-1).getFname().charAt(0)==card.get(position).getFname().charAt(0)) {
LayoutInflater mInflater =
(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// if (view == null)
view = mInflater.inflate(R.layout.contact_list_row, parent, false);
return getCard(position, view);
}
else{
LayoutInflater mInflater =
(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// if (view == null)
view = mInflater.inflate(R.layout.contact_list_section, parent, false);
TextView header = (TextView) view.findViewById(R.id.header);
header.setText((""+card.get(position).getFname().charAt(0)).toUpperCase());
return getCard(position, view);
}
}
private View getCard(final int position, final View view) {
String fname = card.get(position).getFname();
String lname = card.get(position).getLname();
String companyName = card.get(position).getComp();
String note = card.get(position).getNote();
ImageView iv = (ImageView) view.findViewById(R.id.profile);
//
Picasso.with(mContext).cancelRequest(iv);
Picasso.with(mContext).load(R.drawable.default_profile).transform(new CircleTransform()).into(iv);
Picasso.with(mContext).load(card.get(position).getpImage()).transform(new CircleTransform()).into(iv);
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(fname + " " + lname);
//
TextView comp = (TextView) view.findViewById(R.id.company);
comp.setText(companyName);
TextView noteV = (TextView) view.findViewById(R.id.note);
if(note=="") noteV.setVisibility(View.GONE);
else noteV.setText(note);
return view;
}
@Override
public void notifyDataSetChanged() {
//do your sorting here
super.notifyDataSetChanged();
}
}
|
package com.udacity.gradle.builditbigger;
import android.app.Application;
import android.content.Context;
import android.os.AsyncTask;
import android.test.ApplicationTestCase;
import android.view.View;
import android.widget.Toast;
import com.example.chyupa.myapplication.backend.myApi.MyApi;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
private CountDownLatch signal;
private String joke;
public ApplicationTest() {
super(Application.class);
}
@Override
protected void setUp() throws Exception{
super.setUp();
signal = new CountDownLatch(1);
}
@Override
protected void tearDown() throws Exception {
signal.countDown();
}
public void testAsyncTask() throws Exception {
EndpointsAsyncTask endpointsAsyncTask = new EndpointsAsyncTask();
endpointsAsyncTask.setListener(new EndpointsAsyncTask.JsonGetTaskListener() {
@Override
public void onComplete(String jsonString, Exception e) {
joke = jsonString;
signal.countDown();
}
})
.execute();
signal.await();
assertTrue(!joke.isEmpty());
}
}
class EndpointsAsyncTask extends AsyncTask<Context, Void, String> {
private JsonGetTaskListener mListener = null;
private MyApi myApiService = null;
private Exception mError = null;
public EndpointsAsyncTask setListener(JsonGetTaskListener listener) {
this.mListener = listener;
return this;
}
public static interface JsonGetTaskListener {
public void onComplete(String jsonString, Exception e);
}
@Override
protected String doInBackground(Context... params) {
if (myApiService == null) { // Only do this once
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end options for devappserver
myApiService = builder.build();
}
try {
return myApiService.getJoke().execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
/**
* @param result
*/
@Override
protected void onPostExecute(String result) {
if (this.mListener != null)
this.mListener.onComplete(result, mError);
}
}
|
package com.ivet.whatineed.entity.models;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity(name = "stufftable")
public class Whatineed implements Serializable{
private static final long serialVersionUID = 1L;
public Whatineed() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //GenerationType.Identity es para codificar de una manera el Id que le viene bien a MySQL
private Long id;
private String name;
private String color;
private Double price;
private Long quantity;
public Whatineed(Long id, String name, String color, Double price, Long quantity) {
super();
this.id = id;
this.name = name;
this.color = color;
this.price = price;
this.quantity = quantity;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
/**
* Package for junior.pack1.p4.ch2.task2 #110062 Список адресов.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 2018-03-11
* @since 2018-03-11
*/
package ru.job4j.addresses;
|
package com.miyatu.tianshixiaobai.custom;
import android.graphics.Rect;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
/**
* create by: wangchao
* 邮箱: 1064717519@qq.com
*/
public class GridItemDecoration extends RecyclerView.ItemDecoration {
private int itemCount;
private int space;
private boolean isStaggred;
public GridItemDecoration(int itemCount, int space) {
this.space = space;
this.itemCount = itemCount;
}
public GridItemDecoration(int itemCount, int space, boolean isStaggred) {
this.space = space;
this.itemCount = itemCount;
this.isStaggred = isStaggred;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (!isStaggred) {
int pos = parent.getChildAdapterPosition(view);
int column = (pos) % itemCount + 1;// 计算这个child 处于第几列
//注意这里一定要先乘 后除 先除数因为小于1然后强转int后会为0
outRect.left = (column - 1) * space / itemCount; //左侧为(当前条目数-1)/总条目数*divider宽度
outRect.right = (itemCount - column) * space / itemCount;//右侧为(总条目数-当前条目数)/总条目数*divider宽度
if (pos + 1 > itemCount) {
outRect.top = space;
}
} else {
int pos = parent.getChildLayoutPosition(view);
if (pos % itemCount == 0) {
outRect.left = space;
outRect.right = space/2;
outRect.top = space;
}
if (pos % itemCount == 1) {
outRect.left = space/2;
outRect.right = space;
outRect.top = space;
}
// outRect.top = 20;
/**
* 不相等时说明是Grid形式显示的
* 然后判断是左边还有右边显示,分别设置间距为15
*/
// if (spanSize!=manager.getSpanCount()){
// switch (spanIndex){
// case 0:
// outRect.left = convertDpToPixel(15);
// break;
// case 1:
// outRect.left = convertDpToPixel(7);
// outRect.right = convertDpToPixel(7);
// break;
// case 2:
// outRect.right = convertDpToPixel(15);
// break;
// }
// }
// else {
//// outRect.left = space / 2;
// outRect.left = space;
// }
}
}
}
|
package leetCode;
import java.util.LinkedList;
import java.util.List;
public class PascalsTriangle {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> resultList = new LinkedList<List<Integer>>();
if (numRows >= 1) {
List<Integer> list = new LinkedList<Integer>();
list.add(1);
resultList.add(list);
}
if (numRows >= 2) {
List<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(1);
resultList.add(list);
}
if (numRows >= 3) {
int index = 0;
do {
index++;
List<Integer> list = new LinkedList<Integer>();
list.add(1);
for (int i = 0; i < index; i++) {
List<Integer> l1 = resultList.get(index);
list.add(l1.get(i) + l1.get(i + 1));
}
list.add(1);
resultList.add(list);
} while (index <= numRows - 3);
}
return resultList;
}
}
|
package implementation;
import java.util.Objects;
/**
* Represents a single course taken by an ACU student. Maintains data for
* <ul>
* <li>course subject</li>
* <li>course number</li>
* <li>course section</li>
* <li>course year</li>
* <li>course term</li>
* <li>current grade</li>
* <li>whether student course is active</li>
* </ul>
*
* <p>
* Courses and CourseDescriptions will be able to reference one another
* through their subjects and numbers. CourseDescription is presently
* capable of equating itself with a Course object by use of the default
* equals method.
* </p>
*
* @author Kevin Shurtz
* @version 1.0
*/
public class Course
{
// Course characteristics
private String courseNumber; // Coures number (101, 102, etc)
private String courseSubject; // Course subject (ACCT, IT, CS, etc)
private String courseTitle; // Course title (Data Structures, Computer Organization, etc)
private String courseSection; // Course section (1, 2, H2, etc)
// Time characteristics
private int courseYear; // Year course is taken
private Term courseTerm; // Term during which course is taken
// Student data
private String courseGrade; // Student's grade in course (from 0.0 to 100.0)
private boolean inCourseNow; // Whether the student is in the course now
/**
* Constructs a Course object to represent a student's course. Course
* delegates the instantiation of instance variables to method setCourse.
*
* @param subject course subject, such ACCT, CS, IT, etc
* @param number course number, such as 101, 102, 374, etc
* @param title course title, such as 'Software Engineering', 'Data Structures', etc
* @param section course section, such as 01, H1, etc
* @param year year the course is taking place in
* @param cTerm term the coures is taking place in
* @param grade current grade for the course out of 100 points
* @param now whether the course is being actively taken
* @see Course#setCourse(int, String, int, Term, double, boolean)
*/
public Course(String subject, String number, String title, String section, int year, Term cTerm, double grade, boolean now)
{
setCourse(subject, number, title, section, year, cTerm, grade, now);
}
/**
* Constructs a Course object to represent a student's course. Course
* delegates the instantiation of instance variables to method setCourse.
*
* @param subject course subject, such ACCT, CS, IT, etc
* @param number course number, such as 101, 102, 374, etc
* @param title course title, such as 'Software Engineering', 'Data Structures', etc
* @param section course section, such as 01, H1, etc
* @param year year the course is taking place in
* @param cTerm term the coures is taking place in
* @param grade current grade for the course as a letter (A, B, etc)
* @param now whether the course is being actively taken
* @see Course#setCourse(int, String, int, Term, double, boolean)
*/
public Course(String subject, String number, String title, String section, int year, Term cTerm, String grade, boolean now)
{
setCourse(subject, number, title, section, year, cTerm, grade, now);
}
/**
* Assigns values to Course instance variables. The function
* delegate assignment to each of the assignment functions
* for each instance variable, many of which validate the input.
*
* @param subject course subject, such ACCT, CS, IT, etc
* @param number course number, such as 101, 102, 374, etc
* @param title course title, such as 'Software Engineering', 'Data Structures', etc
* @param section course section, such as 01, H1, etc
* @param year year the course is taking place in
* @param cTerm term the coures is taking place in
* @param grade current grade for the course out of 100 points
* @param now whether the course is being actively taken
* @throws IllegalArgumentException If one of the arguements provided
* was unacceptable
*/
public void setCourse(String subject, String number, String title, String section, int year, Term cTerm, double grade, boolean now)
{
setCourseSubject(subject); // Assign course subject
setCourseNumber(number); // Assign course number
setCourseTitle(title); // Assign course title
setCourseSection(section); // Assign course section
setCourseYear(year); // Assign course year
setCourseTerm(cTerm); // Assign course term
setCourseGrade(grade); // Assign course grade
setInCourseNow(now); // Assign if in course now
}
/**
* Assigns values to Course instance variables. The function
* delegate assignment to each of the assignment functions
* for each instance variable, many of which validate the input.
*
* @param subject course subject, such ACCT, CS, IT, etc
* @param number course number, such as 101, 102, 374, etc
* @param title course title, such as 'Software Engineering', 'Data Structures', etc
* @param section course section, such as 01, H1, etc
* @param year year the course is taking place in
* @param cTerm term the coures is taking place in
* @param grade current grade for the course as a letter (A, B, etc)
* @param now whether the course is being actively taken
* @throws IllegalArgumentException If one of the arguements provided
* was unacceptable
*/
public void setCourse(String subject, String number, String title, String section, int year, Term cTerm, String grade, boolean now)
{
setCourseSubject(subject); // Assign course subject
setCourseNumber(number); // Assign course number
setCourseTitle(title); // Assign course title
setCourseSection(section); // Assign course section
setCourseYear(year); // Assign course year
setCourseTerm(cTerm); // Assign course term
setCourseGrade(grade); // Assign course grade
setInCourseNow(now); // Assign if in course now
}
/**
* Assigns the course subject. Examples include 'ACCT', 'IT', etc.
* This value is part of a course's unique identifier, in conjunction
* with the course number.
*
* @param subject the course subject, such as 'ACCT', 'IT', etc
*/
public void setCourseSubject(String subject)
{
courseSubject = subject;
}
/**
* Assigns the course number. Examples include '101', 102', etc.
* This value is part of the unique identifier, in conjunction with
* the course subject.
*
* @param number the course number, such as '101', '102', etc
*/
public void setCourseNumber(String number)
{
courseNumber = number;
}
/**
* Sets the course title.
*
* @param title the course title (Data Structures, Computer Organization, etc)
*/
public void setCourseTitle(String title)
{
courseTitle = title;
}
/**
* Assigns the course section. Examples include '01', '02', and 'H2'.
* The full identifier for a course can be created by concatenating the
* course number with its extension, joined by a '.'. For example,
* 101.H1
*
* @param ext course section
*/
public void setCourseSection(String section)
{
courseSection = section;
}
/**
* Assigns the year in which the course is taken. Validation insures that the
* year is a reasonable input.
*
* @param year the year in which the course is being taken
* @throws IllegalArgumentException If the year is from before 1906,
* more than four characters, or
* less than four characters
*/
public void setCourseYear(int year)
{
// If the year is from before ACU was founded
if (year < 1906)
throw new IllegalArgumentException("Invalid year (before 1906)");
// If a typo has rendered a year with more than four characters
if (Integer.toString(year).length() > 4)
throw new IllegalArgumentException("Invalid year (more than 4 characters)");
// If a typo has rendered a year with less than four characters
if (Integer.toString(year).length() < 4)
throw new IllegalArgumentException("Invalid year (less than 4 characters");
courseYear = year;
}
/**
* Assigns the term in which a course is taken. The term is represented as
* a Term enum, which can assume one of several predefined values. Term exists
* independently of the Course object.
*
* @param cTerm the term in which a course is taken
* @see Term
*/
public void setCourseTerm(Term cTerm)
{
courseTerm = cTerm;
}
/**
* Assigns the grade a student has in a course. The grade cannot be above
* a 100.0 or below a 0.0. This grade is converted into a letter grade.
*
* @param grade the grade a student has in an instance of Course
* @throws IllegalArgumentException If a student is assigned a value above 100.0 or
* if a student is assigned a value below 0.0.
*/
public void setCourseGrade(double grade)
{
// Check for exceptions
if (grade > 100.0)
throw new IllegalArgumentException("Grade above 100% not possible");
if (grade < 0.0)
throw new IllegalArgumentException("Grade below 0% not possible");
// Assign grades
if (grade >= 90)
courseGrade = "A";
else if (grade >= 80)
courseGrade = "B";
else if (grade >= 70)
courseGrade = "C";
else if (grade >= 60)
courseGrade = "D";
else
courseGrade = "F";
}
/**
* Assigns the course grade. The grade must be a letter grade,
* such as (A, B, C, D, F, P, S, U, CR, NC, NG, AU, W, WF, I, or IP).
*
* 'W' signifies 'withdraw', and means a student did not finish a course. This does not
* affect a student's GPA. 'WF' is a 'withdraw' that does affect a student's GPA. 'F' is
* just a typical failure.
*
* 'IP' is primarily for graduate students and means 'in progress'. 'I' means 'incomplete', and is also
* more common for graduate students.
*
* 'P' is for 'pass', and is exclusive to pass/fail courses. Similarly, 'NP' stands for 'no pass'
*
* 'CR' stands for 'credit', and is for students who sign up for a course on a credit/no credit basis.
* Similarly, 'NC' stands for 'no credit'.
*
* 'AU' represents a 'course audit', and typically results in no course credit.
*
* 'NG' stands for 'no grade', and typically represents a course in progress.
*
* 'S' stands for 'satisfactory', and 'U' for 'unsatisfactory'.
*
* @param grade the grade a student has in an instance of Course
* @throws IllegalArgumentException If a student is assigned something besides (A, B, C, D, F, P, S, U, CR, NC, NG, AU, W, WF, I, or IP).
*/
public void setCourseGrade(String grade)
{
grade = grade.toUpperCase();
// Check for exceptions
if (!(grade.equals("A") ||
grade.equals("B") ||
grade.equals("C") ||
grade.equals("D") ||
grade.equals("F") ||
grade.equals("P") ||
grade.equals("S") ||
grade.equals("U") ||
grade.equals("NP") ||
grade.equals("CR") ||
grade.equals("NC") ||
grade.equals("NG") ||
grade.equals("AU") ||
grade.equals("W") ||
grade.equals("WF") ||
grade.equals("I") ||
grade.equals("IP")))
throw new IllegalArgumentException("Grade must be 'A', 'B', 'C', 'D', 'F', " +
"'P', 'S', 'U', 'NP', 'CR', 'NC', 'NG', 'AU', 'W', 'WF', 'I', or 'IP'; Invalid Argument: " + grade);
// Assign grade
courseGrade = grade;
}
/**
* Assigns boolean regarding whether a student is actively taking the course.
* There is no validation that can occur in the function. This value is
* used to differentiate between past and current courses.
*
* @param now whether a student is actively taking the course
*/
public void setInCourseNow(boolean now)
{
inCourseNow = now;
}
/**
* Returns the course section. Courses often have extensions
* for their course numbers to differentiate different instances of the
* course, represented by a mixture of digits and characters. Examples
* include '01', '02', 'H2', etc.
*
* Often, the full course identifier is presented as the subject, course
* number and course section, ajoined by a period. For example,
* BIBL 101.H2. At ACU, this represnts Bible 101 Jesus: Life and Teachings.
* The H2 signifies that this is the "Honors 2" class.
*
* @return the course section
*/
public String getCourseSection() {
return courseSection;
}
/**
* Returns the course year. Examples include, 2012, 2014, 2016, etc.
*
* @return the course year
*/
public int getCourseYear() {
return courseYear;
}
/**
* Returns the course Term, represented by an enum.
*
* Course terms are limited in number. Thus, they have been represented as
* enumerated types to insure strong typing. Exmamples include FALL,
* SPRING, JAN_SHORT (January Short), and MAY (Maymester).
*
* @return the course term
*/
public Term getCourseTerm()
{
return courseTerm;
}
/**
* Returns the course grade. This represents the final letter grade for
* the course, or the ongoing grade as an active semester progresses.
*
* @return the course grade
*/
public String getCourseGrade()
{
return courseGrade;
}
/**
* Returns whether the course is actively being taken by a student.
*
* @return whether the course is actively being taken by a student
*/
public boolean isInCourseNow() {
return inCourseNow;
}
/**
* Returns the course subject by sending a request to the DataModule.
* This infomration is stored in a single CourseDescription object.
*
* @return the course subject
*/
public String getCourseSubject()
{
return courseSubject;
}
/**
* Returns the course title.
*
* @return the course title
*/
public String getCourseTitle()
{
return courseTitle;
}
/**
* Returns the course number by sending a request to the DataModule.
* This infomration is stored in a single CourseDescription object.
*
* @return the course number.
*/
public String getCourseNumber()
{
return courseNumber;
}
/**
* Determines if the Course is equal to another or Course or CourseDescription.
* This function delegates the equals operation to one of the two private equals
* functions in Course.
*
* @param other either a CourseDescription or Course object
* @return whether the Course is equal to the other object
*/
@Override
public boolean equals(Object other)
{
if (other == null)
return false;
if (other == this)
return true;
if (other instanceof Course)
return equals((Course)other);
if (other instanceof CourseDescription)
return equals((CourseDescription)other);
if (other instanceof Prereq)
return equals((Prereq)other);
return false;
}
/**
* Returns true if two Courses have the same subject, number,
* and are taken at the same time.
*
* @param other the other Course
* @return whether the Courses are the same
*/
private boolean equals(Course other)
{
if (!getCourseSubject().equals(other.getCourseSubject()))
return false;
if (!getCourseNumber().equals(other.getCourseNumber()))
return false;
if (!getCourseTitle().equals(other.getCourseTitle()))
return false;
if (getCourseYear() != other.getCourseYear())
return false;
if (!getCourseTerm().equals(other.getCourseTerm()))
return false;
return true;
}
/**
* Returns true if a Course can be related to a CourseDescription
* via its subject and number.
*
* @param other the CourseDescription being compared
* @return whether the Course relates to the CourseDescription
*/
private boolean equals(CourseDescription other)
{
if (!getCourseSubject().equals(other.getCourseSubject()))
return false;
if (!getCourseNumber().equals(other.getCourseNumber()))
return false;
return true;
}
/**
* Returns true if a Course can be related to a Prereq
* via its subject and number.
*
* @param other the Prereq being compared
* @return whether the Course relates to the Prereq
*/
private boolean equals(Prereq other)
{
if (!getCourseSubject().equals(other.getPrereqSubject()))
return false;
if (!getCourseNumber().equals(other.getPrereqNumber()))
return false;
if (getCourseGrade().compareTo(other.getPrereqGrade()) >= 0)
return false;
return true;
}
/**
* Returns a hash for Course. The hash utilizes the Objects library hash function,
* and uses the course subject and number to generate the hash.
*
* CourseDescription should hash to the same value.
*
* @return a hash for Course
*/
@Override
public int hashCode()
{
return Objects.hash(getCourseSubject(), getCourseNumber());
}
}
|
package stpt.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import stpt.entities.Routes;
import java.util.List;
public interface RouteRepository extends JpaRepository<Routes,String> {
@Query("SELECT routeShortName " +
"FROM Routes routes " +
"WHERE routeLongName IN (:long_name)")
List<String> findByRouteLongName(@Param("long_name") String long_name);
}
|
package com.application.db;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.sqlite.SQLiteConfig;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class DB {
private static final Logger logger = Logger.getLogger(DB.class);
private static HikariDataSource datasource;
public static Connection connect() throws SQLException, PropertyVetoException {
SQLiteConfig config = new SQLiteConfig();
config.enforceForeignKeys(true);
Connection conn = null;
try {
conn = getDataSource().getConnection();
return conn;
} catch (Exception e) {
logger.error("Sqlite connection failed", e);
}
return null;
}
public static DataSource getDataSource() {
if (datasource == null) {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:sqlite:file:./resources/db/imgdb.db");
config.setMaximumPoolSize(100);
config.setAutoCommit(true);
config.setConnectionTimeout(20000);
config.setIdleTimeout(300000);
config.setMinimumIdle(5);
config.setMaxLifetime(1200000);
config.setConnectionInitSql("PRAGMA foreign_keys=1");
datasource = new HikariDataSource(config);
}
return datasource;
}
public static void setup() {
List<String> creates =
Arrays.asList(
"CREATE TABLE if not exists images (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, image BLOB NOT NULL UNIQUE, directory TEXT NOT NULL, name TEXT NOT NULL );",
"CREATE TABLE if not exists tags (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE , tags TEXT NOT NULL UNIQUE);",
"Create Table if not exists directories (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, directory TEXT NOT NULL UNIQUE, is_active INTEGER DEFAULT 0 NOT NULL);",
"CREATE TABLE if not exists image_tags (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, record_id INTEGER NOT NULL, tag_id INTEGER NOT NULL,FOREIGN KEY(record_id) REFERENCES images(id) ON DELETE CASCADE, FOREIGN KEY(tag_id) REFERENCES tags(id) ON DELETE CASCADE );",
"VACUUM main");
try (Connection con = connect();
Statement stmt = con.createStatement()) {
creates.forEach(
sql -> {
try {
stmt.execute(sql);
} catch (Exception e) {
logger.error("Db setup failed", e);
}
});
con.close();
} catch (Exception e) {
logger.error("Db setup failed", e);
}
}
}
|
package org.shiro.demo.controller.app.exception;
/**
* 加密错误
* @author Christy
*
*/
public class EncryptWrongExcetion extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 4592104116878389251L;
public EncryptWrongExcetion() {
super();
}
public EncryptWrongExcetion(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public EncryptWrongExcetion(String message, Throwable cause) {
super(message, cause);
}
public EncryptWrongExcetion(String message) {
super(message);
}
public EncryptWrongExcetion(Throwable cause) {
super(cause);
}
}
|
package com.zxt.compplatform.validationrule.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import com.zxt.compplatform.validationrule.entity.ValidationRule;
import com.zxt.compplatform.validationrule.service.IValidationRuleService;
import com.zxt.framework.common.util.RandomGUID;
public class ValidationRuleAction {
private IValidationRuleService validationRuleService;
private ValidationRule validationRule;
/**
* 列表入口
* @return
*/
public String toList(){
return "list";
}
/**
* 列表
* @return
*/
public String list(){
HttpServletResponse res = ServletActionContext.getResponse();
HttpServletRequest req = ServletActionContext.getRequest();
int page = 1;
if(req.getParameter("page") != null && !req.getParameter("page").equals("")){
page = Integer.parseInt(req.getParameter("page"));
}
int rows = 0;
if(req.getParameter("rows") != null && !req.getParameter("rows").equals("")){
rows = Integer.parseInt(req.getParameter("rows"));
}
int totalRows = validationRuleService.findTotalRows();
List validationRuleList = validationRuleService.findAllByPage(page,rows);
Map map = new HashMap();
if(validationRuleList != null){
map.put("rows", validationRuleList);
map.put("total", new Integer(totalRows));
}
String dataJson = JSONObject.fromObject(map).toString();
try {
res.getWriter().write(dataJson);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 跳转添加页面
* @return
*/
public String toAdd(){
return "toadd";
}
/**
* 添加
* @return
*/
public String add(){
HttpServletResponse res = ServletActionContext.getResponse();
if(validationRule.getId() == null || validationRule.getId().equals("")){
validationRule.setId(RandomGUID.geneGuid());
}
try {
if(validationRuleService.isExist(validationRule.getId(),validationRule.getName())){
res.getWriter().write("exist");
}else{
validationRuleService.insert(validationRule);
res.getWriter().write("success");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 跳转修改页面
* @return
*/
public String toUpdate(){
HttpServletRequest req = ServletActionContext.getRequest();
String validationRuleId = req.getParameter("validationRuleId");
if(validationRuleId!= null && !validationRuleId.equals("")){
validationRule = validationRuleService.findById(validationRuleId);
}
return "toupdate";
}
/**
* 修改
* @return
*/
public String update(){
HttpServletResponse res = ServletActionContext.getResponse();
try {
if(validationRuleService.isExistUpdate(validationRule.getId(),validationRule.getName())){
res.getWriter().write("exist");
}else{
validationRuleService.update(validationRule);
res.getWriter().write("success");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 删除
* @return
*/
public String delete(){
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
String validationRuleId = req.getParameter("validationRuleId");
String validationRuleIds = req.getParameter("validationRuleIds");
try {
if(validationRuleId!= null && !validationRuleId.equals("")){
validationRuleService.deleteById(validationRuleId);
res.getWriter().write("success");
}
if(validationRuleIds!= null && !validationRuleIds.equals("")){
validationRuleService.deleteAll(validationRuleService.findAllByIds(validationRuleIds));
res.getWriter().write("success");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void setValidationRuleService(IValidationRuleService validationRuleService) {
this.validationRuleService = validationRuleService;
}
public ValidationRule getValidationRule() {
return validationRule;
}
public void setValidationRule(ValidationRule validationRule) {
this.validationRule = validationRule;
}
}
|
package com.github.ofofs.jca.count;
import com.github.ofofs.jca.annotation.Count;
/**
* @author kangyonggan
* @since 6/27/18
*/
public class CountTest {
/**
* 10秒内同一个name最多调用5次,否则触发回调方法
*
* @param name name
* @return username
*/
@Count(value = "user:${name}", during = 10000, count = 5, violate = "getUsernameViolate")
public String getUsername(String name) {
return name;
}
/**
* 10秒内同一个ip最多调用5次,否则触发回调方法
*
* @param name name
* @return username
*/
@Count(key = "getKey", during = 10000, count = 5, violate = "getUsernameViolate")
public String getUsername2(String name) {
return name;
}
/**
* 10秒内同一个ip最多调用5次,否则触发回调方法
*
* @param name name
*/
@Count(value = "user:${name}", during = 10000, count = 5, violate = "getUsernameViolate")
public void getUsername3(String name) {
if ("".equals(name)) {
System.out.println(name);
return;
}
System.out.println("xx");
}
/**
* 10秒内同一个ip最多调用5次,否则触发回调方法
*
* @param name name
*/
@Count(key = "getKey2", during = 10000, count = 5, violate = "getUsernameViolate")
public static void getUsername4(String name) {
if ("".equals(name)) {
System.out.println(name);
return;
}
System.out.println("xx");
}
public static String getUsernameViolate(String name) {
return "error";
}
public String getKey(String name) {
return "ip";
}
public static String getKey2(String name) {
return "ip";
}
}
|
package ctries2;
// TODO this can go to Scala files
public final class GenOld {
}
|
package cc.ipotato.io;
import java.io.*;
class Person implements Serializable{
private transient String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class SerializableTest {
public static void main(String[] args) throws Exception {
Person p = new Person("Helson", 22);
ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(
new File("TestFile" + File.separator + "person.per")));
oo.writeObject(p);
oo.close();
readObject();
}
public static void readObject() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
new File("TestFile" + File.separator + "person.per")));
System.out.println(ois.readObject());
ois.close();
}
}
|
/**
*
*/
package de.hofuniversity.io.xml.util;
/**
* @author Michael Jahn
*
*/
public class PlayerNameEqualizer {
/**
*
*/
public PlayerNameEqualizer() {
}
public boolean equalsName(String playerName0, String playerName1) {
if (playerName0 == null) {
throw new IllegalArgumentException("Cannot equals a NULL name string.");
}
playerName0 = playerName0.trim();
if (playerName0.isEmpty()) {
throw new IllegalArgumentException("Cannot equals an empty name string.");
}
if (playerName1 == null) {
throw new IllegalArgumentException("Cannot equals to a NULL name string.");
}
playerName1 = playerName1.trim();
if (playerName1.isEmpty()) {
throw new IllegalArgumentException("Cannot equals to an empty name string.");
}
// String[] playerName0StringArray = playerName0.split(" ");
// String[] playerName1StringArray = playerName1.split(" ");
//
// String playerName0String = playerName0StringArray[playerName0StringArray.length - 1];
// String playerName1String = playerName1StringArray[playerName1StringArray.length - 1];
//
// return playerName0String.equalsIgnoreCase(playerName1String);
return playerName0.equalsIgnoreCase(playerName1);
}
}
|
package com.SearchHouse.pojo;
import java.util.Date;
public class Comment {
private Integer commentId;// 评论id
private UserInfo user1;// 用户编号
private UserInfo user2;// 户主编号
private String auditName;// 审核人姓名
private House house;// 房屋
private String auditStatus;// 审核状态
private Date auditTime;// 审核时间
public Comment() {
}
public Comment(Integer commentId, UserInfo user1, UserInfo user2, String auditName, House house, String auditStatus,
Date auditTime) {
super();
this.commentId = commentId;
this.user1 = user1;
this.user2 = user2;
this.auditName = auditName;
this.house = house;
this.auditStatus = auditStatus;
this.auditTime = auditTime;
}
public Integer getCommentId() {
return commentId;
}
public void setCommentId(Integer commentId) {
this.commentId = commentId;
}
public UserInfo getUser1() {
return user1;
}
public void setUser1(UserInfo user1) {
this.user1 = user1;
}
public UserInfo getUser2() {
return user2;
}
public void setUser2(UserInfo user2) {
this.user2 = user2;
}
public String getAuditName() {
return auditName;
}
public void setAuditName(String auditName) {
this.auditName = auditName;
}
public House getHouse() {
return house;
}
public void setHouse(House house) {
this.house = house;
}
public String getAuditStatus() {
return auditStatus;
}
public void setAuditStatus(String auditStatus) {
this.auditStatus = auditStatus;
}
public Date getAuditTime() {
return auditTime;
}
public void setAuditTime(Date auditTime) {
this.auditTime = auditTime;
}
@Override
public String toString() {
return "Comment [commentId=" + commentId + ", user1=" + user1 + ", user2=" + user2 + ", auditName=" + auditName
+ ", house=" + house + ", auditStatus=" + auditStatus + ", auditTime=" + auditTime + "]";
}
}
|
package com.auro.scholr.home.presentation.view.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.auro.scholr.R;
import com.auro.scholr.core.common.CommonCallBackListner;
import com.auro.scholr.databinding.CartWalletItemLayoutBinding;
import com.auro.scholr.home.data.model.WalletResponseAmountResModel;
import java.util.ArrayList;
import java.util.List;
public class WalletAdapter extends RecyclerView.Adapter<WalletAdapter.WalletHolder> {
List<WalletResponseAmountResModel> mValues;
Context mContext;
CartWalletItemLayoutBinding binding;
CommonCallBackListner listner;
public WalletAdapter(Context context, List<WalletResponseAmountResModel> values, CommonCallBackListner listner) {
mValues = values;
mContext = context;
this.listner = listner;
}
public void updateList(ArrayList<WalletResponseAmountResModel> values) {
mValues = values;
notifyDataSetChanged();
}
public class WalletHolder extends RecyclerView.ViewHolder {
CartWalletItemLayoutBinding binding;
public WalletHolder(CartWalletItemLayoutBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
public void setData(WalletResponseAmountResModel resModel, int position) {
binding.backgroundBox.setBackground(resModel.getDrawable());
binding.amountcost.setText(resModel.getAmount());
binding.textTitle.setText(resModel.getText());
/* if (resModel.isSelect()) {
binding.selectImg.setImageDrawable(AuroApp.getAppContext().getResources().getDrawable(R.drawable.ic_check));
} else {
binding.selectImg.setImageDrawable(AuroApp.getAppContext().getResources().getDrawable(R.drawable.ic_uncheck));
}
//resModel.setCertificateImage("https://image.slidesharecdn.com/b1c107f5-eaf4-4dd9-8acc-df180578c33c-160501092731/95/ismail-british-council-certificate-1-638.jpg?cb=1462094874");
ImageUtil.loadNormalImage(binding.certificateImg, resModel.getCertificateImage());*/
}
}
@Override
public WalletAdapter.WalletHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
binding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()),
R.layout.cart_wallet_item_layout, viewGroup, false);
return new WalletAdapter.WalletHolder(binding);
}
@Override
public void onBindViewHolder(WalletAdapter.WalletHolder Vholder, int position) {
Vholder.setData(mValues.get(position), position);
}
@Override
public int getItemCount() {
return mValues.size();
}
private void updateData() {
}
}
|
package Study3;
import java.util.Scanner;
public class S2{
static int h = 5, w = 10;
static String [][] rooms = new String[5][10];
public static void main(String[] args){
Scanner s = new Scanner(System.in);
while (true){
System.out.println("Please Enter: i(in) o(out) s(search) q(quit): ");
String temp = s.next();
int number = 0;
if ("i".equals(temp)){
System.out.println("Please enter number you want: ");
number = s.nextInt();
System.out.println("Please enter your name: ");
String name = s.next();
in(number,name);
}
if ("o".equals(temp)){
System.out.println("Please enter number you want: ");
number = s.nextInt();
System.out.println("Please enter your name: ");
String name = s.next();
out(number,name);
}
if ("s".equals(temp)){
System.out.println("Please enter number you want: (enter'-1' can search all)");
number = s.nextInt();
search(number);
}
if ("q".equals(temp)){
break;
}
}
}
private static boolean search (int number){
if (number == -1){
for (int i=0; i<h; i++){
for (int j=0; j<w; j++){
int num1 = (i + 1)* 100 + j + 1;
System.out.print(num1 + "\t\t");
}
System.out.println();
for (int k=0; k<w; k++){
System.out.print(rooms[i][k] == null ? "empty" + "\t": rooms[i][k] + "\t");
}
System.out.println();
System.out.println();
}
return true;
}else {
int r = (number / 100 ) -1;
int k = (number % 100 ) -1;
if (r<0 || r>=h || k<0 || k>=w){
System.out.println("number ERROR.");
return false;
}else{
System.out.print(rooms[r][k] == null ? "empty" : rooms[r][k] + "\t");
System.out.println();
return true;
}
}
}
private static boolean in (int number, String name){
int r = (number / 100 ) -1;
int k = (number % 100 ) -1;
if (r<0 || r>=h || k<0 || k>=w) {
System.out.println("number ERROR.");
return false;
}else if (rooms[r][k] != null){
System.out.println("Sorry,this room can't be checked in.");
return false;
}else if (rooms[r][k] == null){
rooms[r][k] = name;
System.out.println("in done.");
System.out.println();
return true;
}
return false;
}
private static boolean out (int number,String name){
int r = (number / 100 ) -1;
int k = (number % 100 ) -1;
if (r<0 || r>=h || k<0 || k>=w) {
System.out.println("number ERROR.");
return false;
}
if (rooms[r][k] == null || "".equals(rooms[r][k])){
System.out.println("Sorry,this room can't be checked out for it's empty.");
return false;
}
if ("".equals(rooms[r][k]) != "".equals(name)){
System.out.println("Sorry,your name is not signed in this room.");
return false;
}
rooms[r][k] = null;
System.out.println("out done.");
System.out.println();
return true;
}
}
|
package id.co.blog.json;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.JSONObject;
@Path("/dig")
public class ServerJson {
@POST
@Path("/json")
@Produces(MediaType.APPLICATION_JSON)
public Response getResponseJson(InputStream incomingData) {
JSONObject job = new JSONObject();
StringBuilder crunchifyBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
crunchifyBuilder.append(line);
}
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
System.out.println("Data Received: " + crunchifyBuilder.toString()); // -> data from client
job.put("responseCode", "00");
job.put("describtionCode", "Trx Success !!");
return Response.status(200).entity(job.toString()).build();
}
}
|
package com.wangzhu.spring.registrar;
import com.wangzhu.service.SelfBeanService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Created by wang.zhu on 2020-06-12 14:20.
**/
public class SelfBeanTest {
public static void main(String[] args) {
final AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(SelfBeanConfig.class);
final String[] beanNames = applicationContext.getBeanDefinitionNames();
for (String beanName : beanNames) {
System.out.println(beanName);
}
System.out.println();
final SelfBeanService selfBeanService = (SelfBeanService)applicationContext.getBean("selfBeanService");
selfBeanService.print();
}
}
|
package sign.com.biz.group.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sign.com.biz.base.service.impl.BaseServiceImpl;
import sign.com.biz.group.dto.MemberShipsDto;
import sign.com.biz.group.dto.UserGroupDto;
import sign.com.biz.group.mapper.MemberShipsMapper;
import sign.com.biz.group.mapper.UserGroupMapper;
import sign.com.biz.group.service.MemberShipsService;
import sign.com.biz.group.service.UserGroupService;
import sign.com.biz.user.dto.SignUserDto;
import sign.com.common.BizException;
import sign.com.common.PageDto;
import sign.com.common.enumType.RoleType;
import tk.mybatis.mapper.entity.Example;
import java.util.*;
import java.util.function.Function;
import static java.util.stream.Collectors.*;
/**
* create by luolong on 2018/5/16
*/
@Service
public class UserGroupSerivceImpl extends BaseServiceImpl<UserGroupDto> implements UserGroupService {
@Autowired
MemberShipsService memberShipsService;
@Autowired
UserGroupMapper userGroupMapper;
@Autowired
MemberShipsMapper memberShipsMapper;
@Override
@Transactional
public boolean saveMember(UserGroupDto userGroupDto) {
if (userGroupDto == null) {
return false;
}
int insert = 0;
log.info("用户对象参数为:"+userGroupDto);
insert = userGroupMapper.insert(userGroupDto);
log.info("saveMember的insert为:"+insert);
boolean saveState = saveBacthMemberList(userGroupDto);
if (insert > 0 && saveState) {
return true;
}
return false;
}
@Override
@Transactional
public boolean updateMember(UserGroupDto userGroupDto) {
log.info("updateMember对象参数为:"+userGroupDto);
//标识这个分组下的用户关系为删除
memberShipsMapper.updateEabledByIdGroup(userGroupDto.getIdGroup());
//增加关系数据
boolean saveState = saveBacthMemberList(userGroupDto);
userGroupDto.setCreatedBy(null);
userGroupDto.setCreatedDate(null);
//修改组信息
int i = userGroupMapper.updateGroupByPrimaryKey(userGroupDto);
log.info("用户组修改条数为:"+i);
if (saveState && i > 0) {
return true;
} else {
throw new BizException(10000L, "错误的更新");
}
}
@Override
@Transactional
public boolean deleteMember(UserGroupDto userGroupDto) {
log.info("deleteMember对象参数为:"+userGroupDto);
//将group表的enabled改为false
userGroupDto.setEnabled(false);
int i = userGroupMapper.updateGroupByPrimaryKey(userGroupDto);
log.info("删除条数为:"+i);
//将该group的关系表中对应的关系都改为false
Example memberShip = new Example(MemberShipsDto.class);
memberShip.createCriteria().andEqualTo("idGroup", userGroupDto.getIdGroup());
MemberShipsDto memberShipsDto = new MemberShipsDto() {{
setEnabled(false);
setUpdateDate(new Date());
}};
memberShipsMapper.updateByExampleSelective(memberShipsDto, memberShip);
if (i > 0) {
return true;
}
return false;
}
@Override
public List<SignUserDto> selectUserByName(String name) {
return userGroupMapper.selectUserByName(name);
}
@Override
public PageDto selectGroupList(Integer userId, Integer pageIndex, Integer pageSize) {
log.info("userId为"+userId+",pageIndex为"+pageIndex+",pageSize为"+pageSize);
//查询出该用户涉及到的组的分页list
//PageHelper.startPage(pageIndex, pageSize);
PageDto pageDto = new PageDto();
pageDto.getParams().put("idUser",userId);
PageDto userGroupDtos = userGroupMapper.selectGroupList(pageDto);
// PageInfo<UserGroupDto> pageInfo = new PageInfo(userGroupDtos);
List<UserGroupDto> newList = userGroupDtos.getList();
//遍历用户组列表 查询每一组列表中的成员
if (newList != null && newList.size() > 0) {
newList = newList.stream().map(x -> {
//查询每一个用户组的用户关系列表
List<MemberShipsDto> memberShipsDtos = memberShipsService.selectUserByGroupId(x.getIdGroup());
Map<Integer, List<SignUserDto>> listByidRole = new HashMap<>();
if (memberShipsDtos != null) {
//按角色id分组 然后将对象转化为user对象
listByidRole = memberShipsDtos.stream().filter(u->!u.getIdUser().equals(x.getCreatedBy())).collect(
groupingBy(MemberShipsDto::getIdRole, mapping(u -> {
return new SignUserDto() {{
setUserId(u.getIdUser());
setUserName(u.getUserName());
setEmail(u.getEmail());
}};
}, toList())));
}
x.setLabelMemberList(listByidRole.get(RoleType.LABEL.getIdRole()));
x.setAuditMemberList(listByidRole.get(RoleType.AUDIT.getIdRole()));
x.setUploadMemberList(listByidRole.get(RoleType.UPLOAD.getIdRole()));
x.setUpdate(userId.equals(x.getCreatedBy())?true:false);
x.setEnabled(null);
x.setCreatedBy(null);
return x;
}).collect(toList());
}
pageDto.setList(newList);
return pageDto;
}
@Override
public List<UserGroupDto> selectGroupName(Integer userId) {
return userGroupMapper.selectGroupList(userId);
}
private boolean saveBacthMemberList(UserGroupDto userGroupDto) {
List<Integer> labelMember = userGroupDto.getLabelMember();
List<Integer> uploadMember = userGroupDto.getUploadMember();
List<Integer> auditMember = userGroupDto.getAuditMember();
labelMember.add(userGroupDto.getCreatedBy());
uploadMember.add(userGroupDto.getCreatedBy());
auditMember.add(userGroupDto.getCreatedBy());
Map<String, Object> labelMap = buliderMap(labelMember, userGroupDto, RoleType.LABEL);
Map<String, Object> uploadMap = buliderMap(uploadMember, userGroupDto, RoleType.UPLOAD);
Map<String, Object> auditMap = buliderMap(auditMember, userGroupDto, RoleType.AUDIT);
int labelCount = memberShipsMapper.savebatchList(labelMap);
int uploadCount = memberShipsMapper.savebatchList(uploadMap);
int auditCount = memberShipsMapper.savebatchList(auditMap);
if (labelCount < labelMember.size() || uploadCount < labelMember.size() || auditCount < auditMember.size()) {
return false;
}
return true;
}
public Map<String, Object> buliderMap(List<Integer> list, UserGroupDto userGroupDto, RoleType roleType) {
HashMap<String, Object> map = new HashMap<>();
map.put("list", list);
map.put("idRole", roleType.getIdRole());
map.put("createdBy", userGroupDto.getCreatedBy());
map.put("idGroup", userGroupDto.getIdGroup());
return map;
}
//保存处理动作
private Function<Integer, Integer> saveMemberShip(UserGroupDto userGroupDto, Integer idRole) {
return x -> {
return memberShipsService.save(new MemberShipsDto() {{
setIdRole(idRole);
setIdUser(x);
setCreatedDate(new Date());
setCreatedBy(userGroupDto.getCreatedBy());
setIdGroup(userGroupDto.getIdGroup());
}});
};
}
//get处理条数
private long getHandleCount(List<Integer> list, Function<Integer, Integer> objHandle) {
return list.stream().map(x -> objHandle.apply(x)).filter(x -> x > 0).count();
}
private boolean saveMemberList(UserGroupDto userGroupDto) {
List<Integer> labelMember = userGroupDto.getLabelMember();
List<Integer> uploadMember = userGroupDto.getUploadMember();
List<Integer> auditMember = userGroupDto.getAuditMember();
long lableCount = getHandleCount(labelMember, saveMemberShip(userGroupDto, RoleType.LABEL.getIdRole()));
long uploadCount = getHandleCount(uploadMember, saveMemberShip(userGroupDto, RoleType.UPLOAD.getIdRole()));
long auditCount = getHandleCount(auditMember, saveMemberShip(userGroupDto, RoleType.AUDIT.getIdRole()));
if (lableCount < labelMember.size() || uploadCount < uploadMember.size() || auditCount < auditMember.size()) {
return false;
}
return true;
}
}
|
package com.fwo.hp.fwo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Recharge extends AppCompatActivity {
Button btn_scratch,btn_recharge;
TextView txt1,txt2;
boolean check = false;
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recharge);
btn_scratch=(Button)findViewById(R.id.button6);
btn_recharge=(Button)findViewById(R.id.button7);
txt1=(TextView) findViewById(R.id.textView7);
txt2=(TextView)findViewById(R.id.textView8);
/* relativeLayout=(RelativeLayout)findViewById(R.id.activity_recharge);
relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(check==false) {
check = true;
txt1.setText("اہم نوٹ");
txt2.setText("آپ کی فراہم کردہ تمام معلومات درست ہو جائیں گے یا پھر ہوشیار موٹر ویز آپ کے ایم ٹی اکاؤنٹ کو بلاک کریں.");
}
else {
txt1.setText("Important Note");
txt2.setText("All the information you provided will be correct otherwise smart motorways block your M.Tag account.");
check=false;
}
}
});*/
btn_scratch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(Recharge.this,"All above services will be shortly available.",Toast.LENGTH_LONG).show();
/* Intent intent=new Intent(getApplicationContext(),Scratch.class);
startActivity(intent);*/
}
});
btn_recharge.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(Recharge.this,"All above services will be shortly available.",Toast.LENGTH_LONG).show();
/* Intent intent=new Intent(getApplicationContext(),Webview.class);
startActivity(intent);*/
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_navigation_drawer, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_dua:
Intent aboutIntent = new Intent(Recharge.this, safar.class);
startActivity(aboutIntent);
break;
}
return super.onOptionsItemSelected(item);
}
}
|
package first.basic.字符串转整数;
public class Solution {
public int myAtoi(String str) {
long result = 0;
boolean isNeg = false;
int i = 0;
while (i < str.length()) {
if (str.charAt(i) != ' ')
break;
else i++;
}
if (i < str.length()) {
if (str.charAt(i) == '+'){
isNeg = false;
i++;
}
else if (str.charAt(i) == '-'){
isNeg = true;
i++;
}
else if (!Character.isDigit(str.charAt(i)))return 0;
}
while (i < str.length()) {
if (result > Integer.MAX_VALUE && !isNeg) return Integer.MAX_VALUE;
if (result > Integer.MAX_VALUE && isNeg) return Integer.MIN_VALUE;
if (Character.isDigit(str.charAt(i))) {
result = result * 10 + (str.charAt(i) - '0');
// System.out.println(str.charAt(i) + ":" + result + ";" + (str.charAt(i) - '0'));
i++;
}else break;
}
// System.out.println(result);
if (isNeg) result = -result;
if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE;
return (int)result;
}
public static void main(String[] args) {
Solution solution = new Solution();
int i = solution.myAtoi("-9223372036854775809");
System.out.println(i);
}
}
|
package com.capitalone.demo.repository;
import java.util.Date;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.capitalone.demo.domain.Expense;
import com.capitalone.demo.domain.User;
public interface ExpenseRepository extends MongoRepository<Expense, String> {
public List<Expense> findById(String id);
public List<Expense> findByUser(User user);
public List<Expense> findByType(String type);
public List<Expense> findByExpenseDate(Date expenseDate);
}
|
package gov.nih.mipav.model.algorithms.utilities;
import gov.nih.mipav.model.algorithms.*;
import gov.nih.mipav.model.file.*;
import gov.nih.mipav.model.structures.*;
import gov.nih.mipav.view.*;
import java.io.*;
import java.text.*;
/**
* This algorithm is used to insert averaged slices where slices have been removed -If slices were removed at the
* beginning of the original movie, these slices will not be replaced. - Slices are only inserted between the first and
* last kept slices
*
* @author Ben Link
*/
public class AlgorithmReplaceRemovedSlices extends AlgorithmBase {
//~ Instance fields ------------------------------------------------------------------------------------------------
/** DOCUMENT ME! */
private boolean destFlag = false;
/** DOCUMENT ME! */
private float imageMin;
/** If true, insert a blank rather than a weighted average. */
private boolean insertBlank;
/** DOCUMENT ME! */
private boolean isDicom;
/** DOCUMENT ME! */
private boolean isSplit = false;
/**
* every false value in the array corresponds to a slice within the movie passed in. true values represent removed
* slices
*/
private boolean[] removedSlices = null; // shows which slices were removed from the original.
/** DOCUMENT ME! */
private ModelImage resultImage;
//~ Constructors ---------------------------------------------------------------------------------------------------
/**
* Constructor for algorithm.
*
* @param srcImage the source image
* @param removedSlices an array showing which slices were removed
* @param isSplit DOCUMENT ME!
* @param destFlag DOCUMENT ME!
* @param insertBlank If true, insert a blank rather than a weighted average
*/
public AlgorithmReplaceRemovedSlices(ModelImage srcImage, boolean[] removedSlices, boolean isSplit,
boolean destFlag, boolean insertBlank) {
super(null, srcImage);
this.removedSlices = removedSlices;
this.isSplit = isSplit;
this.destFlag = destFlag;
this.insertBlank = insertBlank;
}
//~ Methods --------------------------------------------------------------------------------------------------------
/**
* Local cleanup.
*/
public void disposeLocal() {
// resultImage = null;
removedSlices = null;
System.gc();
}
/**
* Prepares this class for destruction.
*/
public void finalize() {
disposeLocal();
super.finalize();
}
/**
* Retrieves the result image.
*
* @return resultImage the new image
*/
public ModelImage getResultImage() {
return resultImage;
}
/**
* Function called by thread to run the algorithm.
*/
public void runAlgorithm() {
int i, j, k, m, p;
float[] newOrg2;
int consecutiveRemove;
float deltaOrg2;
float[][] imagePositionCoords = null;
float deltaPos;
DecimalFormat nf;
Object obj;
String s;
float[] sliceLocation = null;
float deltaSliceLoc;
boolean ignoreSliceLocation = false;
boolean ignoreImagePositionCoords = false;
if (srcImage == null) {
displayError("AlgorithmReplaceRemovedSlices.run(): Source Image is null");
return;
} else if (srcImage.getExtents().length != 3) {
displayError("Image must be 3 dimensional");
return;
}
if (srcImage.getFileInfo()[0].getFileFormat() == FileUtility.DICOM) {
isDicom = true;
} else {
isDicom = false;
}
nf = new DecimalFormat("##0.000000");
int[] destExtents = new int[3];
destExtents[0] = srcImage.getExtents()[0];
destExtents[1] = srcImage.getExtents()[1];
srcImage.calcMinMax();
imageMin = (float) srcImage.getMin();
// System.err.println("Length of removedSlices array: " + removedSlices.length);
if (!isSplit) {
// for (int i = 0; i < removedSlices.length; i++) {
// System.err.println(i + "th slice was removed: " + removedSlices[i]);
// }
int firstSlice = -1;
int lastSlice = -1;
boolean foundStart = false;
// find the first good and last good (kept) slices
for (i = 0; i < removedSlices.length; i++) {
if (!foundStart && (removedSlices[i] == false)) {
foundStart = true;
firstSlice = i;
} else if (foundStart && (removedSlices[i] == false)) {
lastSlice = i;
}
}
if ((firstSlice == -1) || (lastSlice == -1)) {
System.err.println("Could not find first/last slices");
setCompleted(false);
notifyListeners(this);
return;
}
// System.err.println("first slice from removedSlices[] " + (firstSlice+1) + " last slice " + (lastSlice+1));
// determine new # of slices: only replace slices found after the first good (unremoved)
// slice from the original image
destExtents[2] = (lastSlice - firstSlice) + 1;
// System.err.println("New extents for " + srcImage.getImageName() + ": " + destExtents[2]);
newOrg2 = new float[destExtents[2]];
if (isDicom) {
imagePositionCoords = new float[destExtents[2]][3];
sliceLocation = new float[destExtents[2]];
}
consecutiveRemove = 0;
for (i = firstSlice, j = 0, m = 0; i <= lastSlice; i++, j++) {
if (!removedSlices[i]) {
newOrg2[j] = srcImage.getFileInfo()[m].getOrigin()[2];
if (isDicom) {
imagePositionCoords[j] = convertIntoFloat(((FileInfoDicom) srcImage.getFileInfo(m))
.parseTagValue("0020,0032"));
if (imagePositionCoords[j] == null) {
ignoreImagePositionCoords = true;
}
obj = ((FileInfoDicom) (srcImage.getFileInfo(m))).getTagTable().getValue("0020,1041");
if (obj != null) {
s = ((String) obj).trim();
try {
sliceLocation[j] = Float.valueOf(s).floatValue();
} catch (NumberFormatException e) {
Preferences.debug("Number format error: slice location " + (i + 1) + " = " + s + "\n",
Preferences.DEBUG_ALGORITHM);
}
} // if (obj != null)
else {
ignoreSliceLocation = true;
}
}
m++;
if (consecutiveRemove > 0) {
deltaOrg2 = (newOrg2[j] - newOrg2[j - consecutiveRemove - 1]) / (consecutiveRemove + 1.0f);
for (k = 0; k < consecutiveRemove; k++) {
newOrg2[j - consecutiveRemove + k] = newOrg2[j - consecutiveRemove - 1] +
((k + 1) * deltaOrg2);
}
if (isDicom) {
if (!ignoreImagePositionCoords) {
for (p = 0; p < 3; p++) {
deltaPos = (imagePositionCoords[j][p] -
imagePositionCoords[j - consecutiveRemove - 1][p]) /
(consecutiveRemove + 1.0f);
for (k = 0; k < consecutiveRemove; k++) {
imagePositionCoords[j - consecutiveRemove + k][p] = imagePositionCoords[j -
consecutiveRemove -
1][p] +
((k + 1) * deltaPos);
}
}
} // if (!ignoreImagePositionCoords)
if (!ignoreSliceLocation) {
deltaSliceLoc = (sliceLocation[j] - sliceLocation[j - consecutiveRemove - 1]) /
(consecutiveRemove + 1.0f);
for (k = 0; k < consecutiveRemove; k++) {
sliceLocation[j - consecutiveRemove + k] = sliceLocation[j - consecutiveRemove - 1] +
((k + 1) * deltaSliceLoc);
}
} // if (!ignoreLocationLocation)
} // (isDicom)
consecutiveRemove = 0;
} // if (consecutiveRemove > 0)
} else {
consecutiveRemove++;
}
} // for (i = firstSlice, j = 0, m = 0; i <= lastSlice; i++, j++)
resultImage = new ModelImage(srcImage.getType(), destExtents, srcImage.getImageName() + "_replaced_slices");
int sliceArea = destExtents[0] * destExtents[1];
float[] imageBuffer = null, imageBuffer2 = null;
int colorFactor = 1;
if (srcImage.isColorImage()) {
colorFactor = 4;
}
else if (srcImage.isComplexImage()) {
colorFactor = 2;
}
// create two image buffers to hold a slice each
imageBuffer = new float[colorFactor * sliceArea];
imageBuffer2 = new float[imageBuffer.length];
int srcIndex = 0;
int resultIndex = 0;
if (insertBlank) {
fireProgressStateChanged(resultImage.getImageName(), "Inserting Blank Slice...");
} else {
fireProgressStateChanged(resultImage.getImageName(), "Inserting Weighted Averaged Slice...");
}
fireProgressStateChanged(0);
int length = resultImage.getExtents()[2];
// copy in all the unaveraged slices into their correct positions
for (int x = firstSlice; x <= lastSlice; x++, resultIndex++) {
if (removedSlices[x] == false) {
// System.err.println("Copying in from srcIndex: " + srcIndex + " to resultIndex: " + resultIndex);
try {
srcImage.exportData(srcIndex * imageBuffer.length, imageBuffer.length, imageBuffer);
resultImage.importData(resultIndex * imageBuffer.length, imageBuffer, false);
} catch (Exception ex) {
System.err.println("Error copying in original slices into result image: " + ex.toString());
}
srcIndex++;
}
fireProgressStateChanged((int) ((((float) resultIndex + 1.0f) / (float) length) * 50.0f));
}
// System.err.println("finished copying original slices into result image");
foundStart = false;
int start = 0;
resultIndex = 0;
// now run through and insert the averaged slices
for (int x = firstSlice; x <= lastSlice; x++, resultIndex++) {
if (!foundStart && (removedSlices[x] == true)) {
foundStart = true;
start = resultIndex - 1;
// System.err.println("start slice for insertion found: " + (start+1));
} else if (foundStart && (removedSlices[x] == false)) {
// System.err.println("end slice for insertion found: " + (resultIndex+1));
if (insertBlank) {
insertBlankSlices(imageBuffer, start, resultIndex);
} else {
insertAveragedSlices(imageBuffer, imageBuffer2, start, resultIndex);
}
foundStart = false;
}
fireProgressStateChanged((int) ((((float) resultIndex + 1.0f) / (float) length) * 50.0f) + 50);
}
imageBuffer = null;
imageBuffer2 = null;
} else {
// image was previously split so keep the same extents and copy first good slice into previous slices
// and last good slice into next slices
int firstSlice = -1;
int lastSlice = -1;
boolean foundStart = false;
// find the first good and last good (kept) slices
for (i = 0; i < removedSlices.length; i++) {
if (!foundStart && (removedSlices[i] == false)) {
foundStart = true;
firstSlice = i;
} else if (foundStart && (removedSlices[i] == false)) {
lastSlice = i;
}
}
int[] extents = srcImage.getExtents();
extents[2] = removedSlices.length;
// System.err.println("ExtentsZ: " + extents[2]);
newOrg2 = new float[extents[2]];
if (isDicom) {
imagePositionCoords = new float[extents[2]][3];
sliceLocation = new float[extents[2]];
}
for (i = 0; i < firstSlice; i++) {
newOrg2[i] = srcImage.getFileInfo()[0].getOrigin()[2];
if (isDicom) {
imagePositionCoords[i] = convertIntoFloat(((FileInfoDicom) srcImage.getFileInfo(0)).parseTagValue("0020,0032"));
if (imagePositionCoords[i] == null) {
ignoreImagePositionCoords = true;
}
obj = ((FileInfoDicom) (srcImage.getFileInfo(0))).getTagTable().getValue("0020,1041");
if (obj != null) {
s = ((String) obj).trim();
try {
sliceLocation[i] = Float.valueOf(s).floatValue();
} catch (NumberFormatException e) {
Preferences.debug("Number format error: slice location 1 = " + s + "\n", Preferences.DEBUG_ALGORITHM);
}
} // if (obj != null)
else {
ignoreSliceLocation = true;
}
}
}
consecutiveRemove = 0;
for (i = firstSlice, m = 0; i <= lastSlice; i++) {
if (!removedSlices[i]) {
newOrg2[i] = srcImage.getFileInfo()[m].getOrigin()[2];
if (isDicom) {
imagePositionCoords[i] = convertIntoFloat(((FileInfoDicom) srcImage.getFileInfo(m))
.parseTagValue("0020,0032"));
if (imagePositionCoords[i] == null) {
ignoreImagePositionCoords = true;
}
obj = ((FileInfoDicom) (srcImage.getFileInfo(m))).getTagTable().getValue("0020,1041");
if (obj != null) {
s = ((String) obj).trim();
try {
sliceLocation[i] = Float.valueOf(s).floatValue();
} catch (NumberFormatException e) {
Preferences.debug("Number format error: slice location " + (i + 1) + " = " + s + "\n",
Preferences.DEBUG_ALGORITHM);
}
} else {
ignoreSliceLocation = true;
}
}
m++;
if (consecutiveRemove > 0) {
deltaOrg2 = (newOrg2[i] - newOrg2[i - consecutiveRemove - 1]) / (consecutiveRemove + 1.0f);
for (k = 0; k < consecutiveRemove; k++) {
newOrg2[i - consecutiveRemove + k] = newOrg2[i - consecutiveRemove - 1] +
((k + 1) * deltaOrg2);
}
if (isDicom) {
if (!ignoreImagePositionCoords) {
for (p = 0; p < 3; p++) {
deltaPos = (imagePositionCoords[i][p] -
imagePositionCoords[i - consecutiveRemove - 1][p]) /
(consecutiveRemove + 1.0f);
for (k = 0; k < consecutiveRemove; k++) {
imagePositionCoords[i - consecutiveRemove + k][p] = imagePositionCoords[i -
consecutiveRemove -
1][p] +
((k + 1) * deltaPos);
}
}
} // if (!ignoreImagePositionCoords)
if (!ignoreSliceLocation) {
deltaSliceLoc = (sliceLocation[i] - sliceLocation[i - consecutiveRemove - 1]) /
(consecutiveRemove + 1.0f);
for (k = 0; k < consecutiveRemove; k++) {
sliceLocation[i - consecutiveRemove + k] = sliceLocation[i - consecutiveRemove - 1] +
((k + 1) * deltaSliceLoc);
}
} // if (!ignoreSliceLocation)
} // (isDicom)
consecutiveRemove = 0;
} // if (consecutiveRemove > 0)
} else {
consecutiveRemove++;
}
} // for (i = firstSlice, j = 0, m = 0; i <= lastSlice; i++, j++)
for (i = lastSlice + 1; i < extents[2]; i++) {
newOrg2[i] = srcImage.getFileInfo()[srcImage.getExtents()[2] - 1].getOrigin()[2];
if (isDicom) {
imagePositionCoords[i] = convertIntoFloat(((FileInfoDicom)
srcImage.getFileInfo(srcImage.getExtents()[2] - 1))
.parseTagValue("0020,0032"));
if (imagePositionCoords[i] == null) {
ignoreImagePositionCoords = true;
}
obj = ((FileInfoDicom) (srcImage.getFileInfo(srcImage.getExtents()[2] - 1))).getTagTable().getValue("0020,1041");
if (obj != null) {
s = ((String) obj).trim();
try {
sliceLocation[i] = Float.valueOf(s).floatValue();
} catch (NumberFormatException e) {
Preferences.debug("Number format error: slice location " + (srcImage.getExtents()[2] - 1) +
" = " + s + "\n", Preferences.DEBUG_ALGORITHM);
}
} // if (obj != null)
else {
ignoreSliceLocation = true;
}
}
}
resultImage = new ModelImage(srcImage.getType(), extents, srcImage.getImageName() + "_replaced_slices");
if (insertBlank) {
fireProgressStateChanged(resultImage.getImageName(), "Inserting Blank Slice...");
} else {
fireProgressStateChanged(resultImage.getImageName(), "Inserting Weighted Averaged Slice...");
}
fireProgressStateChanged(0);
int sliceArea = extents[0] * extents[1];
float[] imageBuffer = null, imageBuffer2 = null;
int colorFactor = 1;
if (srcImage.isColorImage()) {
colorFactor = 4;
}
else if (srcImage.isComplexImage()) {
colorFactor = 2;
}
// create two image buffers to hold a slice each
imageBuffer = new float[colorFactor * sliceArea];
imageBuffer2 = new float[imageBuffer.length];
int length = resultImage.getExtents()[2];
int srcIndex = 0;
// copy in all unaveraged slices into their correct positions
for (int x = 0; x < extents[2]; x++) {
if ((removedSlices[x] == true) && (x < firstSlice)) {
// copy in the first good slice into the previous slices
try {
srcImage.exportData(srcIndex * imageBuffer.length, imageBuffer.length, imageBuffer);
resultImage.importData(x * imageBuffer.length, imageBuffer, false);
} catch (Exception ex) {
System.err.println("Error copying in original slices into previous slices: " + ex.toString());
}
} else if (removedSlices[x] == false) {
try {
srcImage.exportData(srcIndex * imageBuffer.length, imageBuffer.length, imageBuffer);
resultImage.importData(x * imageBuffer.length, imageBuffer, false);
} catch (Exception ex) {
System.err.println("Error copying in original slices into result image: " + ex.toString());
}
srcIndex++;
} else if ((removedSlices[x] == true) && (x > lastSlice)) {
try {
srcImage.exportData((srcIndex - 1) * imageBuffer.length, imageBuffer.length, imageBuffer);
resultImage.importData(x * imageBuffer.length, imageBuffer, false);
} catch (Exception ex) {
System.err.println("Error copying in original slices into next slices: " + ex.toString());
}
}
fireProgressStateChanged((int) ((((float) x + 1.0f) / (float) length) * 50.0f));
}
foundStart = false;
int start = 0;
// now run through and insert the averaged slices
for (int x = firstSlice; x <= lastSlice; x++) {
if (!foundStart && (removedSlices[x] == true)) {
foundStart = true;
start = x - 1;
// System.err.println("start slice for insertion found: " + (start+1));
} else if (foundStart && (removedSlices[x] == false)) {
// System.err.println("end slice for insertion found: " + (resultIndex+1));
if (insertBlank) {
insertBlankSlices(imageBuffer, start, x);
} else {
insertAveragedSlices(imageBuffer, imageBuffer2, start, x);
}
foundStart = false;
}
fireProgressStateChanged((int) ((((float) x + 1.0f) / (float) length) * 50.0f) + 50);
}
imageBuffer = null;
imageBuffer2 = null;
}
if (isDicom) {
FileInfoDicom fileInfoBuffer;
// fix the fileinfos to match
for (i = 0; i < resultImage.getExtents()[2]; i++) {
fileInfoBuffer = (FileInfoDicom) srcImage.getFileInfo()[0].clone();
fileInfoBuffer.setOrigin(newOrg2[i], 2);
if (!ignoreImagePositionCoords) {
fileInfoBuffer.getTagTable().setValue("0020,0032",
imagePositionCoords[i][0] + "\\" + imagePositionCoords[i][1] +
"\\" + imagePositionCoords[i][2],
fileInfoBuffer.getTagTable().get("0020,0032").getLength());
}
// Image slice numbers start at 1; index starts at 0, so
// compensate by adding 1
fileInfoBuffer.getTagTable().setValue("0020,0013", String.valueOf(i + 1),
fileInfoBuffer.getTagTable().get("0020,0013").getLength());
if (!ignoreSliceLocation) {
s = nf.format(sliceLocation[i]);
fileInfoBuffer.getTagTable().setValue("0020,1041", s, s.length());
}
resultImage.setFileInfo(fileInfoBuffer, i);
}
} else { // not DICOM
// fix the fileinfos to match
for (i = 0; i < resultImage.getExtents()[2]; i++) {
resultImage.getFileInfo()[i].setUnitsOfMeasure(srcImage.getFileInfo()[0].getUnitsOfMeasure());
resultImage.getFileInfo()[i].setModality(srcImage.getFileInfo()[0].getModality());
resultImage.getFileInfo()[i].setImageOrientation(srcImage.getFileInfo()[0].getImageOrientation());
resultImage.getFileInfo()[i].setAxisOrientation(srcImage.getFileInfo()[0].getAxisOrientation());
resultImage.getFileInfo()[i].setOrigin(srcImage.getFileInfo()[0].getOrigin());
resultImage.getFileInfo()[i].setOrigin(newOrg2[i], 2);
resultImage.getFileInfo()[i].setSliceThickness(srcImage.getFileInfo()[0].getSliceThickness());
}
} // else not DICOM
resultImage.calcMinMax();
// put it back into the srcImage if no result image wanted
if (!destFlag) {
// System.err.println("importing result back into srcImage (calcInPlace)");
srcImage.changeExtents(resultImage.getExtents());
System.err.println("new extents: " + resultImage.getExtents()[0] + ", " + resultImage.getExtents()[1] +
", " + resultImage.getExtents()[2]);
srcImage.recomputeDataSize();
// import the result buffer from the resultImage into the srcImage
// do this a slice at a time to conserve memory
float[] resultBuffer = null;
int colorFactor = 1;
if (srcImage.isColorImage()) {
colorFactor = 4;
}
else if (srcImage.isComplexImage()) {
colorFactor = 2;
}
int resultSize = resultImage.getSliceSize() * colorFactor;
int numSlices = 1;
int numTimes = 1;
numSlices = destExtents[2];
fireProgressStateChanged("Importing Image Data...");
try {
if (resultBuffer != null) {
resultBuffer = null;
System.gc();
}
resultBuffer = new float[resultSize];
int index = 0;
for (int time = 0; time < numTimes; time++) {
for (int slice = 0; slice < numSlices; slice++) {
resultImage.exportDataNoLock(index, resultSize, resultBuffer);
srcImage.importData(index, resultBuffer, false);
// increment the index by the amount of data exported/imported
index += resultSize;
}
}
srcImage.calcMinMax();
} catch (OutOfMemoryError e) {
resultBuffer = null;
resultImage = null;
System.gc();
displayError("Algorithm Replace Removed Slices reports: Out of memory getting results.");
srcImage.releaseLock();
setCompleted(false);
return;
} catch (IOException e2) {
resultBuffer = null;
resultImage = null;
System.gc();
displayError(e2.getMessage());
srcImage.releaseLock();
setCompleted(false);
return;
}
if (isDicom) {
FileInfoDicom fileInfoBuffer;
// fix the fileinfos to match
for (i = 0; i < resultImage.getExtents()[2]; i++) {
fileInfoBuffer = (FileInfoDicom) resultImage.getFileInfo()[i].clone();
srcImage.setFileInfo(fileInfoBuffer, i);
}
} else if (srcImage.getFileInfo()[0].getFileFormat() == FileUtility.MINC) {
FileInfoMinc fileInfoBuffer;
// fix the fileinfos to match
for (i = 0; i < resultImage.getExtents()[2]; i++) {
fileInfoBuffer = (FileInfoMinc) resultImage.getFileInfo()[i].clone();
srcImage.setFileInfo(fileInfoBuffer, i);
}
} else if (srcImage.getFileInfo()[0].getFileFormat() == FileUtility.AFNI) {
FileInfoAfni fileInfoBuffer;
// fix the fileinfos to match
for (i = 0; i < resultImage.getExtents()[2]; i++) {
fileInfoBuffer = (FileInfoAfni) resultImage.getFileInfo()[i].clone();
srcImage.setFileInfo(fileInfoBuffer, i);
}
} else if (srcImage.getFileInfo()[0].getFileFormat() == FileUtility.NIFTI) {
FileInfoNIFTI fileInfoBuffer;
// fix the fileinfos to match
for (i = 0; i < resultImage.getExtents()[2]; i++) {
fileInfoBuffer = (FileInfoNIFTI) resultImage.getFileInfo()[i].clone();
srcImage.setFileInfo(fileInfoBuffer, i);
}
} else if (srcImage.getFileInfo()[0].getFileFormat() == FileUtility.ANALYZE) {
FileInfoAnalyze fileInfoBuffer;
// fix the fileinfos to match
for (i = 0; i < resultImage.getExtents()[2]; i++) {
fileInfoBuffer = (FileInfoAnalyze) resultImage.getFileInfo()[i].clone();
srcImage.setFileInfo(fileInfoBuffer, i);
}
} else if (srcImage.getFileInfo()[0].getFileFormat() == FileUtility.XML) {
FileInfoXML fileInfoBuffer;
// fix the fileinfos to match
for (i = 0; i < resultImage.getExtents()[2]; i++) {
fileInfoBuffer = (FileInfoXML) resultImage.getFileInfo()[i].clone();
srcImage.setFileInfo(fileInfoBuffer, i);
}
} else {
FileInfoBase fileInfoBuffer;
// fix the fileinfos to match
for (i = 0; i < resultImage.getExtents()[2]; i++) {
fileInfoBuffer = (FileInfoBase) resultImage.getFileInfo()[i].clone();
srcImage.setFileInfo(fileInfoBuffer, i);
}
}
// Clean up and let the calling dialog know that algorithm did its job
srcImage.releaseLock();
resultImage.disposeLocal();
}
System.gc();
setCompleted(true);
}
/**
* Insert weighted averaged slices between the two indices.
*
* @param buffer1 empty buffer to hold the first slice
* @param buffer2 empty buffer to hold the last slice
* @param start start index
* @param end end index
*/
private void insertAveragedSlices(float[] buffer1, float[] buffer2, int start, int end) {
float factor = 1.0f / ((float) (end - start));
float firstFactor, secondFactor; // weights for first and last slices in the group
float[] newSliceBuffer = new float[buffer1.length];
int numToAdd = end - start - 1;
// System.err.println("Adding " + numToAdd + " slices between slice " + (start+1) + " and " + (end+1));
try {
resultImage.exportData(start * buffer1.length, buffer1.length, buffer1);
resultImage.exportData(end * buffer2.length, buffer2.length, buffer2);
for (int i = 0; i < numToAdd; i++) {
secondFactor = factor * (i + 1);
firstFactor = 1.0f - secondFactor;
// System.err.println("First factor is: " + firstFactor + " second factor is: " + secondFactor);
for (int x = 0; x < buffer1.length; x++) {
newSliceBuffer[x] = (buffer1[x] * firstFactor) + (buffer2[x] * secondFactor);
}
resultImage.importData((start + i + 1) * newSliceBuffer.length, newSliceBuffer, false);
}
} catch (Exception ex) {
System.err.println("Caught exception: " + ex.toString());
}
newSliceBuffer = null;
}
/**
* Insert blank slices between the two indices.
*
* @param buffer1 empty buffer to hold the minimum value
* @param start start index
* @param end end index
*/
private void insertBlankSlices(float[] buffer1, int start, int end) {
int i;
int numToAdd = end - start - 1;
// System.err.println("Adding " + numToAdd + " slices between slice " + (start+1) + " and " + (end+1));
try {
for (i = 0; i < buffer1.length; i++) {
buffer1[i] = imageMin;
}
for (i = 0; i < numToAdd; i++) {
resultImage.importData((start + i + 1) * buffer1.length, buffer1, false);
}
} catch (Exception ex) {
System.err.println("Caught exception: " + ex.toString());
}
}
}
|
package com.mandroid.MAndroidApp;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
public class DisplayMessageActivity extends Activity {
private ImageView image;
@Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.MESSAGE);
googleSearch(message);
// image = (ImageView) findViewById(R.id.imageView);
// image.setImageResource(R.drawable.piratey);
//
// TextView mesgText = (TextView) findViewById(R.id.mesgTextView);
// mesgText.setText(message);
// mesgText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 33);
// mesgText.setTextColor(Color.YELLOW);
} catch (Exception e) {
e.printStackTrace();
}
}
public void googleSearch(String query) {
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, query); // query contains search string
startActivity(intent);
}
}
|
package org.spring.management.member.model;
public class UserPaging {
private int currentPage = 1;
private int countPerPage = 10;
private int maxPage = 1;
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getCountPerPage() {
return countPerPage;
}
public void setCountPerPage(int countPerPage) {
this.countPerPage = countPerPage;
}
public int getMaxPage() {
return maxPage;
}
public void setMaxPage(int maxPage) {
this.maxPage = maxPage;
}
}
|
package cn.tedu.reivew;
//本类用于复习代码块
public class TestBlock {
public static void main(String[] args) {
Person p=new Person();
Person p1=new Person("早上好");
p.a();
}
}
class Person{
{
System.out.println("我是一个构造代码块");
}
public Person(){
System.out.println("我是无参构造");
}
public Person(String s){
System.out.println("我是含参构造"+s);
}
public void a(){
System.out.println("我是普通方法");
{
int i=100;
System.out.println("我是一个局部代码块:"+i);
}
// System.out.println(i);//不可以使用,因为在局部代码块中,超出了变量i的范围
}
}
|
/*
* ### Copyright (C) 2007-2011 Michael Fuchs ###
* ### All Rights Reserved. ###
*
* Author: Michael Fuchs
* E-Mail: michael.fuchs@dbdoclet.org
* URL: http://www.michael-a-fuchs.de
*/
package org.dbdoclet.tidbit.common;
import java.awt.Frame;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import org.dbdoclet.jive.dialog.ExceptionBox;
import org.dbdoclet.jive.model.LabelItem;
import org.dbdoclet.jive.model.Settings;
import org.dbdoclet.service.FileServices;
import org.dbdoclet.service.JvmServices;
import org.dbdoclet.service.StringServices;
import org.dbdoclet.tidbit.project.Project;
public class Context {
private Project project;
private Settings settings;
private String tidbitUserPath;
public Context() {
File file;
String fileName;
try {
tidbitUserPath = System.getProperty("user.home");
tidbitUserPath = FileServices.appendPath(tidbitUserPath,
".tidbit.d");
FileServices.createPath(tidbitUserPath);
Properties defProperties = new Properties();
if (JvmServices.isWindows()) {
defProperties.put("browser", "cmd /c %u");
defProperties.put("fo-viewer", "cmd /c \"%f\"");
defProperties.put("pdf-viewer", "cmd /c \"%f\"");
defProperties.put("ps-viewer", "cmd /c \"%f\"");
defProperties.put("rtf-viewer", "cmd /c \"%f\"");
defProperties.put("wml-viewer", "cmd /c \"%f\"");
} else {
defProperties.put("browser", "firefox %u");
defProperties.put("fo-viewer", "gnome-open \"%f\"");
defProperties.put("pdf-viewer", "gnome-open \"%f\"");
defProperties.put("ps-viewer", "gnome-open \"%f\"");
defProperties.put("rtf-viewer", "oowriter \"%f\"");
defProperties.put("wml-viewer", "oowriter \"%f\"");
}
fileName = FileServices.appendFileName(tidbitUserPath,
"tidbit.properties");
file = new File(fileName);
settings = new Settings(file, defProperties);
if (file.exists()) {
settings.load();
}
} catch (IOException oops) {
ExceptionBox ebox = new ExceptionBox(oops);
ebox.setVisible(true);
}
}
public ArrayList<LabelItem> getAvailableJdkList() {
if (settings == null) {
throw new IllegalStateException(
"The field settings must not be null!");
}
String name;
String value;
LabelItem item;
String namespace = "java.jdk.";
ArrayList<LabelItem> itemList = new ArrayList<LabelItem>();
Enumeration<?> nameList = settings.propertyNames();
while (nameList.hasMoreElements()) {
name = (String) nameList.nextElement();
if (name.startsWith(namespace)) {
value = settings.getProperty(name);
name = StringServices.cutPrefix(name, namespace);
item = new LabelItem(name, value);
itemList.add(item);
}
}
return itemList;
}
public Frame getDialogOwner() {
return StaticContext.getDialogOwner();
}
public Project getProject() {
return project;
}
public Settings getSettings() {
return settings;
}
public String getXsltPath() {
String path = FileServices.appendPath(StaticContext.getHome(), "xslt");
return path;
}
public ResourceBundle getResourceBundle() {
return StaticContext.getResourceBundle();
}
public String getHome() {
return StaticContext.getHome();
}
public void setProject(Project project) {
this.project = project;
}
public Locale getLocale() {
return StaticContext.getLocale();
}
}
|
package com.webstore.order;
import java.util.List;
import java.util.Map;
public class ProcessOrder {
/**
* Method to calculate total basket cost.
*
* @param storeItems
* @param customerItems
* @return
*/
public Double calculateBasketCost(Map<String, Double> storeItems, List<BasketItems> customerItems) {
Double totalBasketCost = 0.0;
if (!(null == storeItems) && !(null == customerItems)) {
for (BasketItems customerBasket : customerItems) {
if (storeItems.containsKey(customerBasket.getItemName())) {
totalBasketCost = totalBasketCost
+ (storeItems.get(customerBasket.getItemName()) * customerBasket.getItemCount());
}
}
}
return totalBasketCost;
}
}
|
package com.god.gl.vaccination.util;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* 日志工具类
*/
public class LogX {
private static final String TAG = "LogX";
private static boolean isOpen = true;
private static boolean isLogError = isOpen;
private static boolean isDebug = isOpen;
private static boolean isLogFile = isOpen;
private static boolean isLogTime = isOpen;
private static boolean isLogPrint = isOpen;
private static boolean isLogSystem = isOpen;
public static void initLog(Context context) {
isOpen = isApkDebugable(context);
isLogError = isOpen;
isDebug = true;
isLogFile = isOpen;
isLogTime = isOpen;
isLogPrint = isOpen;
isLogSystem = isOpen;
}
public static void e(String msg) {
e(TAG, msg);
}
public static void e(String tag, String msg) {
if (isLogError) {
Log.e(tag, msg);
}
}
public static void d(String msg) {
d(TAG, msg);
}
public static void d(String tag, String msg) {
if (isDebug) {
Log.d(tag, msg);
}
}
public static void println(String msg) {
if (isLogSystem) {
System.out.println(msg);
}
}
public static void time(String tag, String msg) {
if (isLogTime) {
Log.i(tag, msg + " : " + System.currentTimeMillis());
}
}
public static void logFile(String fileName, String msg) {
if (isLogFile) {
d(fileName, msg);
File fileDir = new File(Environment.getExternalStorageDirectory(),
"/mlogs/");
File logFile = new File(fileDir, fileName);
FileWriter fileOutputStream = null;
try {
if (!fileDir.exists()) {
if (!fileDir.mkdirs()) {
return;
}
}
if (!logFile.exists()) {
if (!logFile.createNewFile()) {
return;
}
}
fileOutputStream = new FileWriter(logFile, true);
fileOutputStream.write(msg);
fileOutputStream.flush();
} catch (Exception e) {
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
}
}
}
}
}
public static void printStackTrace(Exception e) {
if (isLogPrint) {
e.printStackTrace();
}
}
/**
* 是否为debug
*
* @param context
* @return
*/
public static boolean isApkDebugable(Context context) {
try {
ApplicationInfo info = context.getApplicationInfo();
return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
} catch (Exception e) {
}
return false;
}
}
|
package com.mycompany.apirestfulservice.services;
import com.mycompany.apirestfulservice.exceptions.RecordNotFoundException;
import com.mycompany.apirestfulservice.modelo.Autor;
import com.mycompany.apirestfulservice.repositories.AutorRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AutorService {
@Autowired
AutorRepository repository;
public List<Autor> getAllAutor() {
List<Autor> autorList = repository.findAll();
if (autorList.size() > 0) {
return autorList;
} else {
return new ArrayList<>();
}
}
public Autor getAutorById(Long id) throws RecordNotFoundException {
Optional<Autor> autor = repository.findById(id);
if (autor.isPresent()) {
return autor.get();
} else {
throw new RecordNotFoundException("No author record exist for given id", id);
}
}
public Autor createAutor(Autor entity) {
entity = repository.save(entity);
return entity;
}
public Autor updateAutor(Autor entity) throws RecordNotFoundException {
if (entity.getId() != null) {
Optional<Autor> autor = repository.findById(entity.getId());
if (autor.isPresent()) {
Autor newEntity = autor.get();
newEntity.setNombre(entity.getNombre());
newEntity.setLibros(entity.getLibros());
newEntity = repository.save(newEntity);
return newEntity;
} else {
throw new RecordNotFoundException("author not found", entity.getId());
}
} else {
throw new RecordNotFoundException("No id of author given", 0l);
}
}
public void deleteAutorById(Long id) throws RecordNotFoundException {
Optional<Autor> autor = repository.findById(id);
if (autor.isPresent()) {
repository.deleteById(id);
} else {
throw new RecordNotFoundException("No Author record exist for given id", id);
}
}
}
|
package movies;
public class Movie {
private String name;
private String category;
// // constructor
public Movie() {
}
// constructor
public Movie(String name, String category){
this.name = name;
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public static String allMovie() {
Movie[] allMovies = MoviesArray.findAll();
String allMovie = "";
for (Movie m : allMovies) {
allMovie += m.getName() + " - - - " + m.getCategory() +" \n";
}
return allMovie;
}
public static String animateMovie() {
Movie[] animateMovies = MoviesArray.findAll();
String animateMovie = "";
for (Movie m : animateMovies) {
if (m.getCategory() == "animated")
animateMovie += m.getName() +" \n";
}
return animateMovie;
}
public static String dramaMovie() {
Movie[] dramaMovies = MoviesArray.findAll();
String dramaMovie = "";
for (Movie m : dramaMovies) {
if (m.getCategory() == "drama")
dramaMovie += m.getName() +" \n";
}
return dramaMovie;
}
public static String horrorMovie() {
Movie[] horrorMovies = MoviesArray.findAll();
String horrorMovie = "";
for (Movie m : horrorMovies) {
if (m.getCategory() == "horror")
horrorMovie += m.getName() +" \n";
}
return horrorMovie;
}
public static String scifiMovie() {
Movie[] scifiMovies = MoviesArray.findAll();
String scifiMovie = "";
for (Movie m : scifiMovies) {
if (m.getCategory() == "horror")
scifiMovie += m.getName() +" \n";
}
return scifiMovie;
}
public static String comedyMovie(){
Movie[] comedyMovies = MoviesArray.findAll();
String comedyMovie = "";
for (Movie m : comedyMovies) {
if(m.getCategory() == "comedy")
comedyMovie += m.getName() + " \n";
}
return comedyMovie;
}
public static String musicMovie(){
Movie[] musicMovies = MoviesArray.findAll();
String musicMovie = "";
for (Movie m : musicMovies){
if(m.getCategory() == "musical")
musicMovie += m.getName() + " \n";
}
return musicMovie;
}
// public static Movie[] addMovie(Movie[] allMovies, Movie new){
// Movie[] arrayCopy = Arrays.copyOf(movies, movies.length + 1);
//// System.out.println(arrayCopy[arrayCopy.length - 1]);
//// System.out.println(arrayCopy);
// arrayCopy[arrayCopy.length - 1] = movie;
//// System.out.println(person.getName());
//
// return arrayCopy;
// }
}
|
package be.mxs.common.util.pdf.general.oc.examinations;
import java.sql.Timestamp;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import be.mxs.common.model.vo.healthrecord.ItemVO;
import be.mxs.common.model.vo.healthrecord.TransactionVO;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.pdf.general.PDFGeneralBasic;
import be.mxs.common.util.system.Debug;
import be.mxs.common.util.system.ScreenHelper;
import be.openclinic.adt.Encounter;
import be.openclinic.medical.Diagnosis;
import be.openclinic.medical.ReasonForEncounter;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPCell;
/**
* User: ssm
* Date: 18-jul-2007
*/
public class PDFColonoscopyProtocol extends PDFGeneralBasic {
//--- ADD CONTENT -----------------------------------------------------------------------------
protected void addContent(){
try{
if(transactionVO.getItems().size() >= minNumberOfItems){
contentTable = new PdfPTable(1);
table = new PdfPTable(5);
//*********************************************************************************
//*** PART 1 - REGULAR-ITEMS ******************************************************
//*********************************************************************************
// motive
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_COLONOSCOPY_PROTOCOL_MOTIVE");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","motive"),itemValue);
}
// premedication
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_COLONOSCOPY_PROTOCOL_PREMEDICATION");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","premedication"),itemValue);
}
// endoscopy_type
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_COLONOSCOPY_PROTOCOL_ENDOSCOPY_TYPE");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","endoscopy_type"),itemValue);
}
// examination_description
itemValue = getItemValue(IConstants_PREFIX+"v");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","examination_description"),itemValue);
}
//*** investigations_done (BIOSCOPY) ***
String investigations = "";
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_COLONOSCOPY_PROTOCOL_BIOSCOPY");
if(itemValue.equalsIgnoreCase("medwan.common.true")){
if(investigations.length() > 0) investigations+= ", ";
investigations+= getTran("openclinic.chuk","bioscopy");
}
/*
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PROCOTOLOGY_PROTOCOL_BIOSCOPY2");
if(itemValue.equalsIgnoreCase("medwan.common.true")){
if(investigations.length() > 0) investigations+= ", ";
investigations+= getTran("openclinic.chuk","bioscopy2");
}
*/
if(investigations.length() > 0){
addItemRow(table,getTran("openclinic.chuk","investigations_done"),investigations);
}
// conclusion
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_COLONOSCOPY_PROTOCOL_CONCLUSION");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","conclusion"),itemValue);
}
// remarks
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_COLONOSCOPY_PROTOCOL_REMARKS");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","remarks"),itemValue);
}
// add table
if(table.size() > 0){
contentTable.addCell(createCell(new PdfPCell(table),1,PdfPCell.ALIGN_CENTER,PdfPCell.BOX));
tranTable.addCell(new PdfPCell(contentTable));
}
// add transaction to doc
addTransactionToDoc();
//*********************************************************************************
//*** PART 2 - CODE-ITEMS *********************************************************
//*********************************************************************************
addDiagnosisEncoding();
// add transaction to doc
addTransactionToDoc();
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
|
package com.hhdb.csadmin.plugin.table_space;
import java.awt.Component;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import com.hh.frame.swingui.base.AbstractPlugin;
import com.hh.frame.swingui.event.CmdEvent;
import com.hh.frame.swingui.event.ErrorEvent;
import com.hh.frame.swingui.event.EventTypeEnum;
import com.hh.frame.swingui.event.HHEvent;
import com.hhdb.csadmin.common.util.EventUtil;
public class TableSpace extends AbstractPlugin {
public final String PLUGIN_ID = this.getClass().getPackage().getName();
@Override
public HHEvent receEvent(HHEvent event) {
HHEvent replyE=EventUtil.getReplyEvent(TableSpace.class, event);
if(event.getType().equals(EventTypeEnum.CMD.name())){
CmdEvent cmd = (CmdEvent)event;
//添加事件
if(cmd.getCmd().equals("add")){
TableSpaceHandle tablespace = new TableSpaceHandle();
tablespace.TablesSpaceHandle(this);
String toId = "com.hhdb.csadmin.plugin.tabpane";
CmdEvent sequenceEvent = new CmdEvent(PLUGIN_ID,toId,"AddPanelEvent");
sequenceEvent.addProp("TAB_TITLE", "添加表空间");
sequenceEvent.addProp("COMPONENT_ID","addTableSpace");
sequenceEvent.addProp("ICO", "addtabspace.png");
sequenceEvent.setObj(tablespace.getJPanel());
sendEvent(sequenceEvent);
}
//删除事件
if(cmd.getCmd().equals("del")){
String tablespacename =cmd.getValue("tablespace");
TableSpaceHandle tablespace = new TableSpaceHandle();
tablespace.delTableSpace(this,tablespacename);
}
}
return replyE;
}
@Override
public Component getComponent() {
return null;
}
/***
* 发送查询事件给conn
* @param sql
* @return
*/
@SuppressWarnings("unchecked")
public List<Map<String, Object>> FindData(String sql){
CmdEvent getcfEvent = new CmdEvent(PLUGIN_ID, "com.hhdb.csadmin.plugin.conn", "ExecuteListMapBySqlEvent");
getcfEvent.addProp("sql_str", sql);
HHEvent ev = sendEvent(getcfEvent);
if(ev instanceof ErrorEvent){
throw new RuntimeException(((ErrorEvent) ev).getErrorMessage());
}
return (List<Map<String, Object>>) ev.getObj();
}
/**
* 发送事件保存
*/
public boolean SaveData(String sql){
CmdEvent getcfEvent = new CmdEvent(PLUGIN_ID, "com.hhdb.csadmin.plugin.conn", "ExecuteUpdateBySqlEvent");
getcfEvent.addProp("sql_str", sql);
HHEvent ev = sendEvent(getcfEvent);
if(ev instanceof ErrorEvent){
JOptionPane.showMessageDialog(null, ((ErrorEvent) ev).getErrorMessage());
return false;
}
return true;
}
/**
* 刷新节点
*/
public void refreshData(){
CmdEvent refreshData = new CmdEvent(PLUGIN_ID, "com.hhdb.csadmin.plugin.tree", "RefreshAddTreeNodeEvent");
refreshData.addProp("treenode_type", "tablespace");
HHEvent ev = sendEvent(refreshData);
if(ev instanceof ErrorEvent){
JOptionPane.showMessageDialog(null, "请刷新表空间集合信息");
}
}
}
|
package OOP.LAB09_INTERFACES_AND_ABSTRACTION.L02_CarShopExtended;
public interface Sellable {
Double getPrice();
}
|
package com.melodygram.utils;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import com.melodygram.constants.GlobalState;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by LALIT on 15-06-2016.
*/
public class FileUtil {
public static void createFolder(String folderNameInit) {
if (!(new File(folderNameInit)).exists()) {
File f = new File(folderNameInit);
f.mkdir();
}
}
public static void createVideoFolder() {
File f = new File(GlobalState.VIDEO_COMPRESS_DIR_NAME);
f.mkdirs();
f = new File(GlobalState.VIDEO_COMPRESS_DIR_NAME+GlobalState.VIDEO_COMPRESSED_VIDEOS_DIR);
f.mkdirs();
f = new File(GlobalState.VIDEO_COMPRESS_DIR_NAME
+ GlobalState.VIDEO_COMPRESS_TEMP_DIR);
f.mkdirs();
try {
File noMediaFile = new File(GlobalState.VIDEO_COMPRESS_DIR_NAME+GlobalState.VIDEO_COMPRESSED_VIDEOS_DIR, ".nomedia");
if (!noMediaFile.isFile())
noMediaFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package telas;
import componentes.MeuCampoCodigo;
import componentes.MeuCampoComboBox;
import componentes.MeuJTextField;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
public class TelaCadastroCidade extends TelaCadastro{
public String[][] argumentos = {
{"","São Paulo"},
{"","Paraná"}
};
public static TelaCadastroCidade telaCidade;
private MeuCampoCodigo campoCodigo = new MeuCampoCodigo(false, "Código", 3, false, false);
private MeuJTextField campoNomeCidade = new MeuJTextField (true, "Nome da Cidade", 30,"[^A-Z|^ ]");
private MeuCampoComboBox campoComboBox = new MeuCampoComboBox(true, "Estado", argumentos, true);
public TelaCadastroCidade (){
super ("Cadastro de Cidade");
montarTela();
IconeFrame ("/icone/Cidade.png");
minimoTamanhoTela();
}
public void montarTela (){
adicionaComponentes(1, 1, 1, 1, campoCodigo);
adicionaComponentes(1, 3, 1, 1, campoNomeCidade);
adicionaComponentes(3, 1, 1, 1, campoComboBox);
pack();
habilitaComponentes (false);
}
public static TelaCadastro getTela() { //Estático para poder ser chamado de outras classes sem a necessidade de ter criado um objeto anteriormente.
if (telaCidade == null) { //Tela não está aberta, pode criar uma nova tela
telaCidade = new TelaCadastroCidade();
telaCidade.addInternalFrameListener(new InternalFrameAdapter() { //Adiciona um listener para verificar quando a tela for fechada, fazendo assim a remoção da mesma junto ao JDesktopPane da TelaSistema e setando a variável tela = null para permitir que a tela possa ser aberta novamente em outro momento. Basicamente o mesmo controle efetuado pela tela de pesquisa, porém de uma forma um pouco diferente.
@Override
public void internalFrameClosed(InternalFrameEvent e) {
TelaSistema.jdp.remove(telaCidade);
telaCidade = null;
}
});TelaSistema.jdp.add(telaCidade);
}
//Depois do teste acima, independentemente dela já existir ou não, ela é selecionada e movida para frente
TelaSistema.jdp.setSelectedFrame(telaCidade);
TelaSistema.jdp.moveToFront(telaCidade);
return telaCidade;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author jeferson
*/
public class ControladorGrupos {
public int registrarGrupo(String nombre, String siglas, String tipoUnidad, String nombreUnidad, String ubicacion,
String fecha, String codigoGruplav, String clasificado, String categoria, String email,
String nombreDpto, String director) throws IOException, JSONException {
HttpClient httpClient = HttpClients.createDefault();
NameValuePair nom = new BasicNameValuePair("nombre", nombre);
NameValuePair sig = new BasicNameValuePair("sigla", siglas);
NameValuePair unidad = new BasicNameValuePair("id_unidad", nombreUnidad);
// NameValuePair value2 = new BasicNameValuePair("nombre", nombreUnidad);
NameValuePair ubi = new BasicNameValuePair("ubicacion", ubicacion);
NameValuePair fechaC = new BasicNameValuePair("fecha_creacion", fecha);
NameValuePair codigoG = new BasicNameValuePair("codigo_colciencias", codigoGruplav);
NameValuePair clasifi = new BasicNameValuePair("clasificado", clasificado);
NameValuePair cat = new BasicNameValuePair("id_categoria", categoria);
NameValuePair correo = new BasicNameValuePair("correo", email);
NameValuePair dir = new BasicNameValuePair("director_grupo", director);
RequestBuilder requestBuilder = RequestBuilder.post().setUri("https://productividadufps.herokuapp.com/api/v1/grupo");
requestBuilder.addParameter(nom);
requestBuilder.addParameter(sig);
requestBuilder.addParameter(unidad);
requestBuilder.addParameter(ubi);
requestBuilder.addParameter(fechaC);
requestBuilder.addParameter(codigoG);
requestBuilder.addParameter(clasifi);
requestBuilder.addParameter(cat);
requestBuilder.addParameter(correo);
requestBuilder.addParameter(dir);
HttpUriRequest uriRequest = requestBuilder.build();
HttpResponse httpResponse = httpClient.execute(uriRequest);
String source = EntityUtils.toString(httpResponse.getEntity());
System.out.println(source);
if ( httpResponse.getStatusLine().getStatusCode() == 200 || httpResponse.getStatusLine().getStatusCode() == 201 ) {
JSONObject obj = new JSONObject(source);
System.out.println("id " + obj.getInt("id"));
return obj.getInt("id");
}
return -1;
}
public JSONObject consultarGrupo(String id_grupo, String token) throws IOException, JSONException {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://productividadufps.herokuapp.com/api/v1/paginaPrincipal/"+id_grupo);
HttpResponse httpResponse = httpClient.execute(httpGet);
JSONObject json = null;
String source = "";
System.out.println("id " + id_grupo);
if ( httpResponse.getStatusLine().getStatusCode() == 200 || httpResponse.getStatusLine().getStatusCode() == 201 ) {
source = EntityUtils.toString(httpResponse.getEntity());
json = new JSONObject(source);
}
System.out.println(source);
return json;
}
public JSONObject listarGrupos(String id) throws IOException, JSONException {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://productividadufps.herokuapp.com/api/v1/grupoCategoriaDirector/"+id);
HttpResponse httpResponse = httpClient.execute(httpGet);
JSONObject jsonObj = null;
if ( httpResponse.getStatusLine().getStatusCode() == 200 || httpResponse.getStatusLine().getStatusCode() == 201 ) {
String source = EntityUtils.toString(httpResponse.getEntity());
jsonObj = new JSONObject(source);
System.out.println(source);
}
return jsonObj;
}
public JSONObject cargarInfoRegistroGrupos(String token) throws IOException, JSONException {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://productividadufps.herokuapp.com/api/v1/datosCrearGrupo");
HttpResponse httpResponse = httpClient.execute(httpGet);
JSONObject json = null;
String source = "";
if ( httpResponse.getStatusLine().getStatusCode() == 200 || httpResponse.getStatusLine().getStatusCode() == 201 ) {
source = EntityUtils.toString(httpResponse.getEntity());
json = new JSONObject(source);
}
System.out.println(source);
return json;
}
public boolean eliminarGrupo(String idDel, String token) throws IOException, JSONException {
HttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete("https://productividadufps.herokuapp.com/api/v1/grupo/"+idDel);
HttpResponse httpResponse = httpClient.execute(httpDelete);
String source = EntityUtils.toString(httpResponse.getEntity());
System.out.println(source);
return ( httpResponse.getStatusLine().getStatusCode() == 200 || httpResponse.getStatusLine().getStatusCode() == 201 );
}
public JSONObject listarGruposCategorias() throws IOException, JSONException {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://productividadufps.herokuapp.com/api/v1/categoriaGrupo");
HttpResponse httpResponse = httpClient.execute(httpGet);
JSONObject json = null;
String source = "";
if ( httpResponse.getStatusLine().getStatusCode() == 200 || httpResponse.getStatusLine().getStatusCode() == 201 ) {
source = EntityUtils.toString(httpResponse.getEntity());
json = new JSONObject(source);
}
System.out.println(source);
return json;
}
public JSONObject listarGruposVisitante() throws IOException, JSONException {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://productividadufps.herokuapp.com/api/v1/grupo");
HttpResponse httpResponse = httpClient.execute(httpGet);
JSONObject jsonObj = null;
if ( httpResponse.getStatusLine().getStatusCode() == 200 || httpResponse.getStatusLine().getStatusCode() == 201 ) {
String source = EntityUtils.toString(httpResponse.getEntity());
jsonObj = new JSONObject(source);
System.out.println(source);
}
return jsonObj;
}
}
|
package com.dokyme.alg4.sorting.priorityqueue;
import edu.princeton.cs.algs4.StdOut;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by intellij IDEA.But customed by hand of Dokyme.
* 2.4.25
*
* @author dokym
* @date 2018/5/15-20:16
* Description:
*/
public class CubeSum {
public static void main(String[] args) {
findAllPerfactCubes();
}
public static void findAllPerfactCubes() {
int N = 100;
List<Tuple> tuples = new ArrayList<>();
MinHeap<Tuple> ab = new MinHeap<>(N);
for (int i = 0; i < N; i++) {
ab.insert(new Tuple(i, 0));
}
while (!ab.isEmpty()) {
Tuple t = ab.delMin();
if (tuples.size() != 0 && tuples.get(0).cubeSum == t.cubeSum) {
tuples.add(t);
} else {
for (Tuple tup : tuples) {
StdOut.println("\t" + tup);
}
if (tuples.size() != 0) {
StdOut.println(tuples.get(0).cubeSum);
}
tuples.clear();
tuples.add(t);
}
if (t.j < N) {
ab.insert(new Tuple(t.i, t.j + 1));
}
}
}
public static void printAllCubes() {
int N = 1000000;
MinHeap<Tuple> ab = new MinHeap<>(N);
for (int i = 0; i < N; i++) {
ab.insert(new Tuple(i, 0));
}
while (!ab.isEmpty()) {
Tuple t = ab.delMin();
StdOut.println(t.fomular());
if (t.j < N) {
ab.insert(new Tuple(t.i, t.j + 1));
}
}
}
}
class Tuple implements Comparable<Tuple> {
public int i;
public int j;
public long cubeSum;
public Tuple(int i, int j) {
this.i = i;
this.j = j;
cubeSum = (long) i * i * i + (long) j * j * j;
}
public String fomular() {
return this.toString() + " = " + cubeSum;
}
@Override
public String toString() {
return i + "^3 + " + j + "^3";
}
@Override
public boolean equals(Object obj) {
Tuple o = (Tuple) obj;
return i == o.i && j == o.j && cubeSum == o.cubeSum;
}
@Override
public int compareTo(Tuple o) {
if (cubeSum < o.cubeSum) {
return -1;
} else if (cubeSum == o.cubeSum) {
return 0;
} else {
return 1;
}
}
}
|
package com.login;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "Login", urlPatterns = {"/Login"})
public class Login extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String unm=request.getParameter("user");
String pass=request.getParameter("password");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/openeye","root","pruu");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from adminpanel where user='"+unm+"' and password='"+pass+"'");
while(rs.next())
{
if(unm.equals("")||pass.equals(""))
{
response.sendRedirect("admin.jsp");
}
else if(unm.equals(rs.getString("user"))&&pass.equals(rs.getString("password")))
{
HttpSession s=request.getSession();
s.setAttribute("user",unm);
response.sendRedirect("admindashbord.jsp");
}
else{
response.sendRedirect("admin.jsp");
}
}
}
catch(Exception ex)
{
out.println("somthing gona wrong");
}
}
}
|
package portfolio.sda.view;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import portfolio.sda.ultil.PathSetting;
/**
* @author Gilvanei e Kelvin
*/
public class ImageBuilder {
// Define o caminho da imagem de fundo usadas nas imagens des posts.
private static final String BACKGROUND_PATH = PathSetting.IMAGE_PATH + "back.png";
//Define nomeclatiras padrão para os tipos de imagens.
private static final String IMAGE_DEFAULT = "default";
private static final String THUMBNAIL_IMAGE = "thumbnail";
//Define as dimenções das imagens quadradas (1x1) usadas como thumbs.
private final int thumbnailDimensions = 120;
// Recebe as dimensões para cada redimencionamento de imagem.
private double imageResizingWidth = 0;
private double imageResizingHeight = 0;
private double backgroundResizingWidth = 0;
private double backgroundResizingHeight = 0;
private final double wDefault = 700.000;
private final double hDefault = 400.000;
/**
* ******************* VERIFICAR FUNCIONAMENTO E DEPOIS COMENTAR
*/
public void createDefaultImage(File frontImage) throws IOException {
if (frontImage == null) {
throw new IOException("Não foi definida uma imagem para uso!");
}
BufferedImage bckgBufferedImage = ImageIO.read(new File(BACKGROUND_PATH));
BufferedImage frontBufferedImage = ImageIO.read(frontImage);
calculateBackgroundDimensions(frontBufferedImage);
calculateImageResizing(frontBufferedImage);
bckgBufferedImage = resizingImage(bckgBufferedImage, backgroundResizingWidth, backgroundResizingHeight, Image.SCALE_DEFAULT);
frontBufferedImage = resizingImage(frontBufferedImage, imageResizingWidth, imageResizingHeight, Image.SCALE_DEFAULT);
double offsetx = (backgroundResizingWidth - imageResizingWidth) / 2;
double offsety = (backgroundResizingHeight - imageResizingHeight) / 2;
Graphics g = bckgBufferedImage.getGraphics();
//offsetx = ((int) offsetx < 0 ? offsetx * (-1) : offsetx);
//offsety = ((int) offsety < 0 ? offsety * (-1) : offsety);
g.drawImage(frontBufferedImage, (int) offsetx, (int) offsety, null);
//g.drawString("Portylou", 2 * w_fi - 70, 2 * h_fi - 20);
g.dispose();
bckgBufferedImage = resizingImage(bckgBufferedImage, wDefault, hDefault, Image.SCALE_DEFAULT);
imageSaver(bckgBufferedImage, IMAGE_DEFAULT);
}
/**
* Recebe uma imagem qualque e a corda nas borda salvando uma nova imagem no
* formato 1x1, com as dimensões especificada pela constante
* thumbnailDimensions.
*
* @param fileImage Image
* @throws IOException
*/
public void createThumbnail(File fileImage) throws IOException {
BufferedImage img = ImageIO.read(fileImage);
int start_x = 0, start_y = 0, width = 0, height = 0;
// Recumpera as dimensões da imagem recebida.
int w_up = img.getWidth();
int h_up = img.getHeight();
// Setam as variavéis start_x, start_y, width e height de acordo as
// dimensões da imagem recebida, definindo a região de corte desta.
if (w_up == h_up) {
// Altura e largira não precisam serem alteradas.
width = w_up;
height = h_up;
} else if (w_up > h_up) {
// Define a posição de corte no eixo x, eixo y não precisa, e faz
// a altura e largura igual a menor dimensão da imagem recebida,
// no caso a altura, tornando a imagem 1x1.
start_x = (w_up - h_up) / 2;
start_y = 0;
width = h_up;
height = h_up;
} else if (w_up < h_up) {
// Define a posição de corte no eixo y, eixo x não precisa, e faz
// a altura e largura igual a menor dimensão da imagem recebida,
// no caso a larguratornando a imagem 1x1.
start_x = 0;
start_y = (h_up - w_up) / 2;
width = w_up;
height = w_up;
}
try {
// Cria a imagem nas especificações acima apartir da imagem recebida,
// faz o redicionamento da mesma e salva no caminho desejado.
BufferedImage newImage = img.getSubimage(start_x, start_y, width, height);
newImage = resizingImage(newImage, thumbnailDimensions, thumbnailDimensions, Image.SCALE_DEFAULT);
imageSaver(newImage, THUMBNAIL_IMAGE);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/**
* Salva as novas imagens criadas em diretórios específicos, criando todo o
* diretório se for necessário.
*
* @param bufferedImage
* @param imageType
* @throws IOException
*/
private void imageSaver(BufferedImage bufferedImage, String imageType) throws IOException {
File imagesDefaultDir = new File(PathSetting.PATH_IMG_PROFILE);
File imagesThumbnailDir = new File(PathSetting.PATH_IMG_THUMB);
// Verifica a existencia da pasta e, caso não exista, cria todas as pastas
// usadas no diretória de salvamento.
if (!imagesDefaultDir.exists() || !imagesThumbnailDir.exists()) {
imagesDefaultDir.mkdirs();
imagesThumbnailDir.mkdirs();
}
// Determina o diretório de salvamento apartir do tipo da imagem.
switch (imageType) {
case IMAGE_DEFAULT:
ImageIO.write(bufferedImage, "PNG", new File(
PathSetting.PATH_IMG_PROFILE + "IMG-" + imageRename() + ".png"));
System.out.println("Imagem IMG-" + imageRename() + ".png salva com sucesso!");
break;
case THUMBNAIL_IMAGE:
ImageIO.write(bufferedImage, "PNG", new File(
PathSetting.PATH_IMG_THUMB + "thumb-" + imageRename() + ".png"));
break;
}
}
/**
* Cria um novo nome para a imagem carregada baseada na data e horário
* atuais. Formatando a data e hora para o tipo: ddMMyyyyHHmmss que irá
* compor o nome da imagem
*
* @return String new name
*/
public String imageRename() {
Date currentDate = new Date();
String date = new SimpleDateFormat("ddMMyyyy").format(currentDate);
String hour = new SimpleDateFormat("HHmmss").format(currentDate);
return date + hour;
}
/**
* Redimenciona uma imagem para qualquer dimensão desejada, não cortando a
* imagem original.
*
* @param img
* @param initWidth
* @param initHeight
* @param modo
* @return
*/
private BufferedImage resizingImage(BufferedImage img, double initWidth, double initHeight, int mode) {
// Cria uma imagem temporária com as dimensões desejadas.
Image temp = img.getScaledInstance((int) initWidth, (int) initHeight, mode);
int width = temp.getWidth(null);
int height = temp.getHeight(null);
// Converte a nova imagem para o formato BufferedImage (objeto desejado).
BufferedImage newImagem = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics graphic = newImagem.createGraphics();
graphic.drawImage(temp, 0, 0, null);
graphic.dispose();
return newImagem;
}
public void calculateBackgroundDimensions(BufferedImage img) {
backgroundResizingHeight = img.getHeight();
backgroundResizingWidth = img.getHeight() / (hDefault / wDefault);
}
public void calculateImageResizing(BufferedImage img) {
double myProp = ((img.getHeight() + 0.000) / (img.getWidth() + 0.000));
if(img.getWidth() > (int) backgroundResizingWidth && img.getHeight() == (int) backgroundResizingHeight){
//hf = h * id
//wf = w
imageResizingWidth = img.getWidth();
imageResizingHeight = img.getHeight() * myProp;
}else if(img.getWidth() < (int) backgroundResizingWidth && img.getHeight() == (int) backgroundResizingHeight){
//hf = h
//wf = w
imageResizingWidth = img.getWidth();
imageResizingHeight = img.getHeight();
}else if(img.getWidth() > (int) backgroundResizingWidth && img.getHeight() > (int) backgroundResizingHeight){
tieBreaker(myProp, img.getWidth(), img.getHeight());
}else if(img.getWidth() > (int) backgroundResizingWidth && img.getHeight() < (int) backgroundResizingHeight){
//wf = wb
//hf = h * id
imageResizingWidth = backgroundResizingWidth;
imageResizingHeight = img.getHeight() * myProp;
}else if(img.getWidth() < (int) backgroundResizingWidth && img.getHeight() > backgroundResizingHeight){
//hf = hb
//wf = w * id
imageResizingWidth = img.getWidth() * myProp;
imageResizingHeight = backgroundResizingHeight;
}else if(img.getWidth() < (int) backgroundResizingWidth && img.getHeight() < backgroundResizingHeight){
tieBreaker(myProp, img.getWidth(), img.getHeight());
}
/*if (myProp < (hDefault / wDefault)) {
imageResizingWidth = backgroundResizingWidth;
imageResizingHeight = img.getHeight() * myProp;
} else if(myProp > (hDefault / wDefault)) {
imageResizingHeight = backgroundResizingHeight;
imageResizingWidth = img.getWidth() * myProp + (myProp * 100);
}else{
imageResizingHeight = backgroundResizingHeight;
imageResizingWidth = backgroundResizingWidth;
}*/
}
private void tieBreaker(double p, double width, double height){
if (p < (hDefault / wDefault)) {
imageResizingWidth = backgroundResizingWidth;
imageResizingHeight = height* p;
} else if(p > (hDefault / wDefault)) {
imageResizingHeight = backgroundResizingHeight;
imageResizingWidth = width * p;
}else{
imageResizingHeight = backgroundResizingHeight;
imageResizingWidth = backgroundResizingWidth;
}
}
}
|
package cn.edu.cust.pkmAudit.search;
import java.util.HashMap;
import java.util.Map;
import cn.edu.cust.common.search.ColumnType;
import cn.edu.cust.common.search.Search;
public class DairySearch extends Search {
private static Map<String, ColumnType> columnsSet;
static {
columnsSet = new HashMap<String, ColumnType>();
/**
* 根据每个列的类型添加 hashmap的key是列名,value 是列类型,列类型用ColumnType的常量
*/
columnsSet.put("-", ColumnType.STRING);
columnsSet.put("name", ColumnType.STRING);
columnsSet.put("check", ColumnType.INT);
}
@Override
protected Map<String, ColumnType> getColumnsSet() {
return columnsSet;
}
@Override
protected String getType() {
return "Dairy";
}
@Override
protected String getProjections() {
return null;
}
}
|
package com.lab.shopCart.shopcartms.interfaces.rest.dto.order;
import com.lab.shopCart.shopcartms.domain.model.GoodEntity;
import com.lab.shopCart.shopcartms.interfaces.rest.dto.goods.GoodReqDto;
import com.lab.shopCart.shopcartms.interfaces.rest.vo.goods.GoodVo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OrderResDto {
private String orderId;
private String customerName;
private Integer totalAmount;
private List<GoodVo> goods;
}
|
package com.example.springdemo.utility.response;
public enum StatusCode {
OK(200),
CREATE(201),
NO_CONTENT(204),
BAD_REQUEST(400),
UNAUTHORIZED(401),
FORBIDDEN(403),
NOT_FOUND(404),
INTERNAL_SERVER_ERROR(500),
DB_ERROR(600);
StatusCode(int code) {
this.code = code;
}
public int code;
}
|
package org.sunshinelibrary.turtle.syncservice;
/**
* User: fxp
* Date: 10/14/13
* Time: 8:58 PM
*/
public abstract class SyncListener {
public abstract void onEventArrive(SyncEvent evt);
}
|
package com.allan.adbtool;
import java.util.ArrayList;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class SharedPreferenceHelper {
private SharedPreferences spPreferences;
private Editor editor;
private int top = 10; // top顶层 大于总数0~9
private static final String NAME = "cmd"; // 加上一个数字就是存储的位置
private ArrayList<String> cmdList = new ArrayList<String>();
/**
* 最多保存10份
*
* @param context
*/
public SharedPreferenceHelper(Context context) {
spPreferences = context.getSharedPreferences("mine",
Context.MODE_PRIVATE);
editor = spPreferences.edit();
top = 10;
for (int i = 0; i < 10; i++) {
cmdList.add(spPreferences.getString(NAME + i, ""));
}
}
public void writeInto(String cmd) {
top = 10;
for (int i = 0; i < 9; i++) {
editor.putString(NAME + i, cmdList.get(i + 1)).commit();
cmdList.set(i, cmdList.get(i + 1));
}
editor.putString(NAME + "9", cmd).commit();
cmdList.set(9, cmd);
}
public void writeLevel(int lev) {
editor.putInt("logLevel", lev).commit();
}
public int getLevel() {
return spPreferences.getInt("logLevel", 0);
}
public void writeScreenshotSleepTime(int second) {
editor.putInt("screenshot_time", second).commit();
}
public int getScreenshotSleepTime() {
return spPreferences.getInt("screenshot_time", 6);
}
public void writeTag(String tag) {
editor.putString("logTag", tag).commit();
}
public String getTag() {
return spPreferences.getString("logTag", "");
}
public boolean getTimeChecked() {
return spPreferences.getBoolean("logTime", false);
}
public void writeTimeChecked(boolean isChecked) {
editor.putBoolean("logTime", isChecked).commit();
}
public String getPrev() {
if (top > 0) {
top--;
}
return cmdList.get(top);
}
public String getNext() {
if (top < 9) {
top++;
} else {
top = 9;
}
return cmdList.get(top);
}
}
|
package edu.cb.songlist.rhodes.maddux;
import java.util.*;
import edu.jenks.dist.cb.songlist.*;
public class MusicDownloads extends AbstractMusicDownloads{
public MusicDownloads() {
}
public static void main(String[] args) {
List<DownloadInfo> list = new ArrayList<DownloadInfo>();
list.add(new DownloadInfo("tu madre", 2));
list.add(new DownloadInfo("tu padre", 1));
list.add(new DownloadInfo("tu hermano", 4));
list.add(new DownloadInfo("tu hermana", 17));
MusicDownloads test = new MusicDownloads();
test.setDownloadList(list);
test.toArray(list);
//DownloadInfo s = test.getDownloadInfo("tu hermana");
//list.add(s);
//test.toArray(list);
List<String> listTitle = new ArrayList<String>();
listTitle.add("soul sister");
listTitle.add("tu padre");
listTitle.add("tu madre");
listTitle.add("meet the monster");
test.updateDownloads(listTitle);
test.toArray(list);
}
public DownloadInfo getDownloadInfo(String title) {
List<DownloadInfo> list = getDownloadList();
for(DownloadInfo d : list) {
if(d.getTitle().equals(title)) {
return d;
}
}
return null;
}
public void updateDownloads(List<String> titles) {
for(String s : titles) {
DownloadInfo thing = getDownloadInfo(s);
if(thing != null) {
thing.incrementTimesDownloaded();
}else {
DownloadInfo newObj = new DownloadInfo(s);
getDownloadList().add(newObj);
}
}
}
public void toArray(List<DownloadInfo> arr) {
System.out.print("[" + arr.get(0));
for(int i = 1; i < arr.size(); i++) {
System.out.print(", " + arr.get(i));
}
System.out.print("]");
System.out.println();
}
}
|
package fun.modelbook.boxssoserver.constant;
/**
* @author jory
* @date 2019-03-15
*/
public interface TokenConstant {
/**
* 令牌名称
*/
String TOKEN_NAME = "token";
String BACK_URL_TOKEN_NAME = "__box_token__";
/**
* 令牌有效时间,单位秒,默认一天
*/
int TOKEN_TIMEOUT = 60 * 60 * 24;
/**
* 问号
*/
String QUESTION_MARK = "?";
/**
* and符
*/
String AND_MARK = "&";
}
|
package service;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import control.ClientContext;
import entity.EntityContext;
import entity.ExamInfo;
import entity.Question;
import entity.QuestionInfo;
import entity.User;
/**
* 考试逻辑类
*
* 主要功能:创建试卷、改卷、找错题、算分数等和考试有关的操作
*
* */
public class ExamService {
ClientContext clientContext;
/**
* 控制器注入
* */
public void setClientContext(ClientContext clientContext) {
this.clientContext = clientContext;
}
EntityContext entityContext;
/**
* 数据注入
* */
public void setEntityContext(EntityContext entityContext) {
this.entityContext = entityContext;
}
ExamInfo examInfo;
/**
* 考试相关注入
* */
public void setExamInfo(ExamInfo examInfo) {
this.examInfo = examInfo;
}
QuestionInfo questionInfo;
public void setQuestionInfo(QuestionInfo questionInfo) {
this.questionInfo = questionInfo;
}
/**
* 获取全部考试规则
*
* @return 考试规则
*
* */
public String getRules() {
return this.entityContext.getRules();
}
List<QuestionInfo> paper = new ArrayList<QuestionInfo>();
/**
* 新建试卷
*
* 选择试卷类型
*
* 从每个等级里面各抽取两道题加入试卷,产生试卷
*
* @param subject
* 试卷类型
* */
private void createPaper(String subject) {
this.entityContext.loadQuestions(subject);
Random random = new Random();
int i = 1;
for (int level = Question.LEVEL1; level <= Question.LEVEL10; level++) {
Question q;
q = this.entityContext.getQuestions().get(level).remove(
random.nextInt(this.entityContext.getQuestions().get(level)
.size()));
this.paper.add(new QuestionInfo(i++, q));
q = this.entityContext.getQuestions().get(level).remove(
random.nextInt(this.entityContext.getQuestions().get(level)
.size()));
this.paper.add(new QuestionInfo(i++, q));
}
this.examInfo.setPaper(paper);
}
/**
* 保存答案
*
* @Param list 传进来的List<Integer> 代表一个用户答案集合
*
* */
public void saveAnswer(List<Integer> list) {
this.examInfo.getPaper().get(count).setUserAnswers(list);
}
/**
* paper里面的题目编号
* */
int count = 0;
/**
* 开始考试,获得第一道题目
* */
public String startTest() {
return this.examInfo.getPaper().get(count).toString();
}
/**
* 获取当前用户信息
*
* @param User
* 某个用户
*
* @return 用户信息
*
* */
public String getMsg(User user) {
return this.examInfo.toString();
}
/**
* 考试初始化,获取考试所需要的各种信息:时间、科目、试卷
*
* @param user
* 试卷所属者
*
* @param type
* 考试类型
*
* */
public void startExam(User user, String type) {
this.createPaper(type);
this.examInfo.setQuestionAmount(this.entityContext.getQuestionAmount());
this.examInfo.setTime(this.entityContext.getTimeLimit());
this.examInfo.setTitle(this.entityContext.getExamTitle(type));
this.examInfo.setUser(user);
}
/**
* 获取题目编号,显示在examFrame
* */
public int getIdx() {
return this.count + 1;
}
/**
* 显示上一题
*
* @return 上个题目信息
*
* */
public String prev() {
if (count <= 0)
return null;
return this.examInfo.getPaper().get(--count).toString();
}
/**
* 显示下一题
*
* @return 下个题目信息
*
* */
public String next() {
if (count >= this.examInfo.getPaper().size())
return null;
return this.examInfo.getPaper().get(++count).toString();
}
/**
* 设置"下一题"按钮状态
*
* @return boolean 用于表示按钮是否可用
*
* */
public boolean setNext() {
return count < this.examInfo.getPaper().size() - 1 ? true : false;
}
/**
* 设置"上一题"按钮状态
*
* @return boolean 用于表示按钮是否可用
*
* */
public boolean setPrev() {
return count > 0 ? true : false;
}
/**
* 获取当前题的用户答案
*
* @return List<Integer>代表用户某题的答案
*
* */
public List<Integer> getAnswer() {
return this.paper.get(count).getUserAnswers();
}
/**
* 改卷子
*
* examFrame里面的sent按钮会调用到
*
* 用于把分数存进examInfo里面
* */
public void checkPaper() {
List<Integer> userAnswer;
List<Integer> questionAnswer;
for (int i = 0; i < this.examInfo.getPaper().size(); i++) {
userAnswer = this.examInfo.getPaper().get(i).getUserAnswers();
questionAnswer = this.examInfo.getPaper().get(i).getAnswers();
if (userAnswer == null)
continue;
if (userAnswer.equals(questionAnswer)) {
this.examInfo.setScore(this.examInfo.getScore()
+ this.examInfo.getPaper().get(i).getScore());
}
}
}
/**
* 获取分数
*
* @return 最终得分
*
* */
public int getScore() {
return this.examInfo.getScore();
}
/**
* 获取错题
*
* 流程:把用户答案和标准答案比较,如果相同则continue,否则记录下题目到错题集
*
* @return String 用户成绩+所有错题集合+答案比较
*
* */
public String getWrongQuestion() {
List<Integer> userAnswer;
List<Integer> questionAnswer;
StringBuffer sb = new StringBuffer();
sb.append("你的成绩是:" + this.getScore() + "\r\n");
for (int i = 0; i < this.examInfo.getPaper().size(); i++) {
userAnswer = this.examInfo.getPaper().get(i).getUserAnswers();
questionAnswer = this.examInfo.getPaper().get(i).getAnswers();
if (questionAnswer.equals(userAnswer))
continue;
sb.append("\r\n");
sb.append(this.examInfo.getPaper().get(i).toString() + "\r\n");
sb.append("正确答案:" + anyAnswer(questionAnswer) + "\r\n");
sb.append("你的答案:" + anyAnswer(userAnswer) + "\r\n");
}
return sb.toString();
}
/**
* 原始答案分析,把List<Integer>转换成了List<Character>
*
* @param list
* 某个答案记录 用户答案或者标准答案
*
* @return String 转换后的答案,例如:[A,B]
*
* */
private String anyAnswer(List<Integer> list) {
if (list == null || list.isEmpty())
return "没有选择答案!";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < list.size(); i++) {
sb.append((char) ('A' + list.get(i)));
}
return sb.toString();
}
/**
* 获取考试时间
*
* @return 考试时间,以分钟计算
*
* */
public int getTimeLimt() {
return this.examInfo.getTime();
}
/**
* 获取考试记录
*
* @return 考试历史记录
* */
public String[][] getTestInfo() {
return this.entityContext.getTestInfo();
}
}
|
/*
* 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 rs.ac.bg.fon.ps.view.forms;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
/**
*
* @author Mr OLOGIZ
*/
public class FrmTerminCRUD extends javax.swing.JDialog {
/**
* Creates new form FrmTerminCRUD
*/
public FrmTerminCRUD(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* 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() {
panelBackGround = new javax.swing.JPanel();
lblidTermina = new javax.swing.JLabel();
lblDatum = new javax.swing.JLabel();
lblvremePocetka = new javax.swing.JLabel();
lblVremeKraja = new javax.swing.JLabel();
lbTrajanje = new javax.swing.JLabel();
lblBrojClanova = new javax.swing.JLabel();
txtId = new javax.swing.JTextField();
txtVremePocetka = new javax.swing.JTextField();
txtTrajanje = new javax.swing.JTextField();
txtVremeKraja = new javax.swing.JTextField();
lblMaxBrojClanova = new javax.swing.JLabel();
btnObrisiTermin = new javax.swing.JButton();
btnPotvrdiIzmene = new javax.swing.JButton();
btnOmoguciIzmene = new javax.swing.JButton();
lblErrorMessage = new javax.swing.JLabel();
txtBrojClanova = new javax.swing.JTextField();
txtMaxBrClanova = new javax.swing.JTextField();
lblGrupaTermina = new javax.swing.JLabel();
txtGrupaa = new javax.swing.JTextField();
panelGrupe = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tblGrupe = new javax.swing.JTable();
lblUlogovanTrener = new javax.swing.JLabel();
txtUlogovanTrener = new javax.swing.JTextField();
txtDatum = new javax.swing.JTextField();
panelDatum = new javax.swing.JPanel();
dateChooser = new datechooser.beans.DateChooserCombo();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
panelBackGround.setBackground(new java.awt.Color(0, 0, 0));
lblidTermina.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblidTermina.setForeground(new java.awt.Color(255, 255, 255));
lblidTermina.setText("id:");
lblDatum.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblDatum.setForeground(new java.awt.Color(255, 255, 255));
lblDatum.setText("datum:");
lblvremePocetka.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblvremePocetka.setForeground(new java.awt.Color(255, 255, 255));
lblvremePocetka.setText("vreme početka:");
lblVremeKraja.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblVremeKraja.setForeground(new java.awt.Color(255, 255, 255));
lblVremeKraja.setText("vreme kraja:");
lbTrajanje.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lbTrajanje.setForeground(new java.awt.Color(255, 255, 255));
lbTrajanje.setText("trajanje:");
lblBrojClanova.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblBrojClanova.setForeground(new java.awt.Color(255, 255, 255));
lblBrojClanova.setText("broj članova:");
txtId.setBackground(new java.awt.Color(0, 0, 0));
txtId.setForeground(new java.awt.Color(255, 255, 255));
txtId.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
txtVremePocetka.setBackground(new java.awt.Color(0, 0, 0));
txtVremePocetka.setForeground(new java.awt.Color(255, 255, 255));
txtVremePocetka.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
txtTrajanje.setBackground(new java.awt.Color(0, 0, 0));
txtTrajanje.setForeground(new java.awt.Color(255, 255, 255));
txtTrajanje.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
txtVremeKraja.setBackground(new java.awt.Color(0, 0, 0));
txtVremeKraja.setForeground(new java.awt.Color(255, 255, 255));
txtVremeKraja.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
lblMaxBrojClanova.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblMaxBrojClanova.setForeground(new java.awt.Color(255, 255, 255));
lblMaxBrojClanova.setText("maksimalan broj članova:");
btnObrisiTermin.setBackground(new java.awt.Color(255, 255, 255));
btnObrisiTermin.setFont(new java.awt.Font("Microsoft YaHei", 1, 11)); // NOI18N
btnObrisiTermin.setText("Obriši termin");
btnPotvrdiIzmene.setBackground(new java.awt.Color(255, 255, 255));
btnPotvrdiIzmene.setFont(new java.awt.Font("Microsoft YaHei", 1, 11)); // NOI18N
btnPotvrdiIzmene.setText("Potvrdi promene");
btnOmoguciIzmene.setBackground(new java.awt.Color(255, 255, 255));
btnOmoguciIzmene.setFont(new java.awt.Font("Microsoft YaHei", 1, 11)); // NOI18N
btnOmoguciIzmene.setText("Omogući promene");
lblErrorMessage.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblErrorMessage.setForeground(new java.awt.Color(255, 0, 51));
txtBrojClanova.setBackground(new java.awt.Color(0, 0, 0));
txtBrojClanova.setForeground(new java.awt.Color(255, 255, 255));
txtBrojClanova.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
txtMaxBrClanova.setBackground(new java.awt.Color(0, 0, 0));
txtMaxBrClanova.setForeground(new java.awt.Color(255, 255, 255));
txtMaxBrClanova.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
lblGrupaTermina.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblGrupaTermina.setForeground(new java.awt.Color(255, 255, 255));
lblGrupaTermina.setText("Grupa termina:");
txtGrupaa.setBackground(new java.awt.Color(0, 0, 0));
txtGrupaa.setForeground(new java.awt.Color(255, 255, 255));
txtGrupaa.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
panelGrupe.setBackground(new java.awt.Color(0, 0, 0));
panelGrupe.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Grupe ulogovanog trenera", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Microsoft YaHei", 1, 12), new java.awt.Color(255, 255, 255))); // NOI18N
panelGrupe.setOpaque(false);
tblGrupe.setBackground(new java.awt.Color(0, 0, 0));
tblGrupe.setFont(new java.awt.Font("Microsoft YaHei", 0, 11)); // NOI18N
tblGrupe.setForeground(new java.awt.Color(255, 255, 255));
tblGrupe.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tblGrupe.setGridColor(new java.awt.Color(255, 255, 255));
jScrollPane1.setViewportView(tblGrupe);
lblUlogovanTrener.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblUlogovanTrener.setForeground(new java.awt.Color(255, 255, 255));
lblUlogovanTrener.setText("Ulogovan trener:");
txtUlogovanTrener.setBackground(new java.awt.Color(0, 0, 0));
txtUlogovanTrener.setForeground(new java.awt.Color(255, 255, 255));
txtUlogovanTrener.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
javax.swing.GroupLayout panelGrupeLayout = new javax.swing.GroupLayout(panelGrupe);
panelGrupe.setLayout(panelGrupeLayout);
panelGrupeLayout.setHorizontalGroup(
panelGrupeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelGrupeLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelGrupeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 628, Short.MAX_VALUE)
.addGroup(panelGrupeLayout.createSequentialGroup()
.addComponent(lblUlogovanTrener)
.addGap(82, 82, 82)
.addComponent(txtUlogovanTrener, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
panelGrupeLayout.setVerticalGroup(
panelGrupeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelGrupeLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelGrupeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblUlogovanTrener)
.addComponent(txtUlogovanTrener, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
.addContainerGap())
);
txtDatum.setBackground(new java.awt.Color(0, 0, 0));
txtDatum.setForeground(new java.awt.Color(255, 255, 255));
txtDatum.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
panelDatum.setBackground(new java.awt.Color(0, 0, 0));
panelDatum.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "unesiDatum", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Microsoft YaHei", 1, 11), new java.awt.Color(255, 255, 255))); // NOI18N
dateChooser.setCurrentView(new datechooser.view.appearance.AppearancesList("Swing",
new datechooser.view.appearance.ViewAppearance("custom",
new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
new java.awt.Color(0, 0, 0),
new java.awt.Color(0, 0, 255),
false,
true,
new datechooser.view.appearance.swing.ButtonPainter()),
new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
new java.awt.Color(0, 0, 0),
new java.awt.Color(0, 0, 255),
true,
true,
new datechooser.view.appearance.swing.ButtonPainter()),
new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
new java.awt.Color(0, 0, 255),
new java.awt.Color(0, 0, 255),
false,
true,
new datechooser.view.appearance.swing.ButtonPainter()),
new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
new java.awt.Color(128, 128, 128),
new java.awt.Color(0, 0, 255),
false,
true,
new datechooser.view.appearance.swing.LabelPainter()),
new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
new java.awt.Color(0, 0, 0),
new java.awt.Color(0, 0, 255),
false,
true,
new datechooser.view.appearance.swing.LabelPainter()),
new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
new java.awt.Color(0, 0, 0),
new java.awt.Color(255, 0, 0),
false,
false,
new datechooser.view.appearance.swing.ButtonPainter()),
(datechooser.view.BackRenderer)null,
false,
true)));
dateChooser.setCalendarBackground(new java.awt.Color(0, 0, 0));
dateChooser.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED,
(java.awt.Color)null,
(java.awt.Color)null,
(java.awt.Color)null,
(java.awt.Color)null));
dateChooser.setCalendarPreferredSize(new java.awt.Dimension(250, 150));
dateChooser.setFieldFont(new java.awt.Font("Microsoft YaHei", java.awt.Font.PLAIN, 12));
dateChooser.setNavigateFont(new java.awt.Font("Microsoft YaHei", java.awt.Font.PLAIN, 12));
javax.swing.GroupLayout panelDatumLayout = new javax.swing.GroupLayout(panelDatum);
panelDatum.setLayout(panelDatumLayout);
panelDatumLayout.setHorizontalGroup(
panelDatumLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelDatumLayout.createSequentialGroup()
.addGap(0, 8, Short.MAX_VALUE)
.addComponent(dateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
);
panelDatumLayout.setVerticalGroup(
panelDatumLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelDatumLayout.createSequentialGroup()
.addComponent(dateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 21, Short.MAX_VALUE))
);
javax.swing.GroupLayout panelBackGroundLayout = new javax.swing.GroupLayout(panelBackGround);
panelBackGround.setLayout(panelBackGroundLayout);
panelBackGroundLayout.setHorizontalGroup(
panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelBackGroundLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelGrupe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblidTermina)
.addComponent(lblErrorMessage)
.addGroup(panelBackGroundLayout.createSequentialGroup()
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtDatum, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(panelBackGroundLayout.createSequentialGroup()
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblMaxBrojClanova)
.addComponent(lblGrupaTermina)
.addComponent(lblBrojClanova)
.addComponent(lbTrajanje)
.addComponent(lblVremeKraja)
.addComponent(lblvremePocetka))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtVremePocetka, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtVremeKraja, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtTrajanje, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtBrojClanova, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtGrupaa, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtMaxBrClanova, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(lblDatum)
.addComponent(panelDatum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnPotvrdiIzmene, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnOmoguciIzmene, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnObrisiTermin, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelBackGroundLayout.setVerticalGroup(
panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelBackGroundLayout.createSequentialGroup()
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelBackGroundLayout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(lblidTermina))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBackGroundLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtId, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnOmoguciIzmene, javax.swing.GroupLayout.Alignment.TRAILING))))
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelBackGroundLayout.createSequentialGroup()
.addGap(7, 7, 7)
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblDatum)
.addComponent(txtDatum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelDatum, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(13, 13, 13)
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblvremePocetka)
.addComponent(txtVremePocetka, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblVremeKraja)
.addComponent(txtVremeKraja, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbTrajanje)
.addComponent(txtTrajanje, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblBrojClanova)
.addComponent(txtBrojClanova, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblMaxBrojClanova)
.addComponent(txtMaxBrClanova, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(panelBackGroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblGrupaTermina)
.addComponent(txtGrupaa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(25, 25, 25)
.addComponent(lblErrorMessage)
.addGap(294, 294, 294))
.addGroup(panelBackGroundLayout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(btnObrisiTermin)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnPotvrdiIzmene)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(panelGrupe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelBackGround, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelBackGround, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnObrisiTermin;
private javax.swing.JButton btnOmoguciIzmene;
private javax.swing.JButton btnPotvrdiIzmene;
private datechooser.beans.DateChooserCombo dateChooser;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lbTrajanje;
private javax.swing.JLabel lblBrojClanova;
private javax.swing.JLabel lblDatum;
private javax.swing.JLabel lblErrorMessage;
private javax.swing.JLabel lblGrupaTermina;
private javax.swing.JLabel lblMaxBrojClanova;
private javax.swing.JLabel lblUlogovanTrener;
private javax.swing.JLabel lblVremeKraja;
private javax.swing.JLabel lblidTermina;
private javax.swing.JLabel lblvremePocetka;
private javax.swing.JPanel panelBackGround;
private javax.swing.JPanel panelDatum;
private javax.swing.JPanel panelGrupe;
private javax.swing.JTable tblGrupe;
private javax.swing.JTextField txtBrojClanova;
private javax.swing.JTextField txtDatum;
private javax.swing.JTextField txtGrupaa;
private javax.swing.JTextField txtId;
private javax.swing.JTextField txtMaxBrClanova;
private javax.swing.JTextField txtTrajanje;
private javax.swing.JTextField txtUlogovanTrener;
private javax.swing.JTextField txtVremeKraja;
private javax.swing.JTextField txtVremePocetka;
// End of variables declaration//GEN-END:variables
public void klikNaTabeluAddActionListener(MouseListener ml){
tblGrupe.addMouseListener(ml);
}
public void OmoguciIzmeneTerminaAddActionListener(ActionListener actionListener) {
btnOmoguciIzmene.addActionListener(actionListener);
}
public void ObrisiTerminAddActionListener(ActionListener actionListener) {
btnObrisiTermin.addActionListener(actionListener);
}
public void IzmeniTerminAddActionListener(ActionListener actionListener) {
btnPotvrdiIzmene.addActionListener(actionListener);
}
public javax.swing.JButton getBtnObrisiTermin() {
return btnObrisiTermin;
}
public void setBtnObrisiTermin(javax.swing.JButton btnObrisiTermin) {
this.btnObrisiTermin = btnObrisiTermin;
}
public javax.swing.JButton getBtnOmoguciIzmene() {
return btnOmoguciIzmene;
}
public void setBtnOmoguciIzmene(javax.swing.JButton btnOmoguciIzmene) {
this.btnOmoguciIzmene = btnOmoguciIzmene;
}
public javax.swing.JButton getBtnPotvrdiIzmene() {
return btnPotvrdiIzmene;
}
public void setBtnPotvrdiIzmene(javax.swing.JButton btnPotvrdiIzmene) {
this.btnPotvrdiIzmene = btnPotvrdiIzmene;
}
public javax.swing.JLabel getLblErrorMessage() {
return lblErrorMessage;
}
public void setLblErrorMessage(javax.swing.JLabel lblErrorMessage) {
this.lblErrorMessage = lblErrorMessage;
}
public javax.swing.JTextField getTxtBrojClanova() {
return txtBrojClanova;
}
public void setTxtBrojClanova(javax.swing.JTextField txtBrojClanova) {
this.txtBrojClanova = txtBrojClanova;
}
public javax.swing.JTextField getTxtGrupaTermina() {
return txtUlogovanTrener;
}
public void setTxtGrupaTermina(javax.swing.JTextField txtGrupaTermina) {
this.txtUlogovanTrener = txtGrupaTermina;
}
public javax.swing.JTextField getTxtId() {
return txtId;
}
public void setTxtId(javax.swing.JTextField txtId) {
this.txtId = txtId;
}
public javax.swing.JTextField getTxtMaxBrClanova() {
return txtMaxBrClanova;
}
public void setTxtMaxBrClanova(javax.swing.JTextField txtMaxBrClanova) {
this.txtMaxBrClanova = txtMaxBrClanova;
}
public javax.swing.JTextField getTxtTrajanje() {
return txtTrajanje;
}
public void setTxtTrajanje(javax.swing.JTextField txtTrajanje) {
this.txtTrajanje = txtTrajanje;
}
public javax.swing.JTextField getTxtVremeKraja() {
return txtVremeKraja;
}
public void setTxtVremeKraja(javax.swing.JTextField txtVremeKraja) {
this.txtVremeKraja = txtVremeKraja;
}
public javax.swing.JTextField getTxtVremePocetka() {
return txtVremePocetka;
}
public void setTxtVremePocetka(javax.swing.JTextField txtVremePocetka) {
this.txtVremePocetka = txtVremePocetka;
}
public javax.swing.JTable getTblGrupe() {
return tblGrupe;
}
public void setTblGrupe(javax.swing.JTable tblGrupe) {
this.tblGrupe = tblGrupe;
}
public javax.swing.JTextField getTxtUlogovanTrener() {
return txtUlogovanTrener;
}
public void setTxtUlogovanTrener(javax.swing.JTextField txtUlogovanTrener) {
this.txtUlogovanTrener = txtUlogovanTrener;
}
public javax.swing.JTextField getTxtGrupaa() {
return txtGrupaa;
}
public void setTxtGrupaa(javax.swing.JTextField txtGrupaa) {
this.txtGrupaa = txtGrupaa;
}
public javax.swing.JTextField getTxtDatum() {
return txtDatum;
}
public void setTxtDatum(javax.swing.JTextField txtDatum) {
this.txtDatum = txtDatum;
}
public datechooser.beans.DateChooserCombo getDateChooser() {
return dateChooser;
}
public void setDateChooser(datechooser.beans.DateChooserCombo dateChooser) {
this.dateChooser = dateChooser;
}
public javax.swing.JPanel getPanelDatum() {
return panelDatum;
}
public void setPanelDatum(javax.swing.JPanel panelDatum) {
this.panelDatum = panelDatum;
}
}
|
/*
* 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 com.victuxbb.javatest.model.user;
import com.victuxbb.javatest.model.role.RoleEnum;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author victux
*/
public class InMemoryUserRepository implements UserRepositoryInterface
{
private List<User> users;
public InMemoryUserRepository()
{
this.users = new ArrayList<User>();
User user_pag_1 = new User(1,"usuario_pag_1","pag_1",RoleEnum.PAG_1);
User user_pag_2 = new User(1,"usuario_pag_2","pag_2",RoleEnum.PAG_2);
User user_pag_3 = new User(1,"usuario_pag_3","pag_3",RoleEnum.PAG_3);
User user_pag_4 = new User(1,"usuario_pag_12","pag_12",RoleEnum.PAG_1);
user_pag_4.addRole(RoleEnum.PAG_2);
this.users.add(user_pag_1);
this.users.add(user_pag_2);
this.users.add(user_pag_3);
this.users.add(user_pag_4);
}
public User findUserByUsernameAndPassword(String username,String password) throws UserNotFoundException
{
for (User user : this.users) {
if(user.getUsername().equals(username) && user.getPassword().equals(password)) return user;
}
throw new UserNotFoundException("User not found!");
}
}
|
package pkgHelper;
//Comments to make the git submission work
import pkgEnum.ePuzzleViolation;
public class PuzzleViolation {
private int iValue;
private ePuzzleViolation ePuzzleViolation;
public PuzzleViolation(pkgEnum.ePuzzleViolation ePuzzleViolation, int iValue) {
this.ePuzzleViolation = ePuzzleViolation;
this.iValue = iValue;
}
public ePuzzleViolation getePuzzleViolation() {
return ePuzzleViolation;
}
public int getiValue() {
return iValue;
}
}
|
package com.sims.bo.impl;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sims.bo.RODetailsBo;
import com.sims.dao.RODetailsDao;
import com.sims.model.RODetails;
import com.sims.model.ROHeader;
/**
*
* @author dward
*
*/
@Service
public class RODetailsBoImpl implements RODetailsBo{
private final static Logger logger = Logger.getLogger(RODetailsBoImpl.class);
@Autowired
RODetailsDao rODetailsDao;
public void setRODetailsDao(RODetailsDao rODetailsDao){
this.rODetailsDao = rODetailsDao;
}
@Override
@Transactional
public boolean save(RODetails entity) {
logger.info("Save: " + entity.toString());
return rODetailsDao.save(entity);
}
@Override
@Transactional
public boolean update(RODetails entity) {
RODetails model = rODetailsDao.findById(entity.getId());
model.setItem(entity.getItem());
model.setQty(entity.getQty());
model.setPrice(entity.getPrice());
model.setAmount(entity.getAmount());
logger.info("Update: " + model.toString());
return rODetailsDao.update(model);
}
@Override
@Transactional
public boolean delete(RODetails entity) {
logger.info("Delete: id = " + entity.getId());
return rODetailsDao.delete(entity);
}
@Override
public RODetails findById(int id) {
return rODetailsDao.findById(id);
}
@Override
public List<RODetails> getListByROHeader(ROHeader roHeader) {
return rODetailsDao.getListByROHeader(roHeader);
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.hint;
import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.springframework.lang.Nullable;
/**
* Gather the need for Java serialization at runtime.
*
* @author Stephane Nicoll
* @since 6.0
* @see Serializable
*/
public class SerializationHints {
private final Set<JavaSerializationHint> javaSerializationHints;
public SerializationHints() {
this.javaSerializationHints = new LinkedHashSet<>();
}
/**
* Return the {@link JavaSerializationHint java serialization hints} for types
* that need to be serialized using Java serialization at runtime.
* @return a stream of {@link JavaSerializationHint java serialization hints}
*/
public Stream<JavaSerializationHint> javaSerializationHints() {
return this.javaSerializationHints.stream();
}
/**
* Register that the type defined by the specified {@link TypeReference}
* need to be serialized using java serialization.
* @param type the type to register
* @param serializationHint a builder to further customize the serialization
* @return {@code this}, to facilitate method chaining
*/
public SerializationHints registerType(TypeReference type, @Nullable Consumer<JavaSerializationHint.Builder> serializationHint) {
JavaSerializationHint.Builder builder = new JavaSerializationHint.Builder(type);
if (serializationHint != null) {
serializationHint.accept(builder);
}
this.javaSerializationHints.add(builder.build());
return this;
}
/**
* Register that the type defined by the specified {@link TypeReference}
* need to be serialized using java serialization.
* @param type the type to register
* @return {@code this}, to facilitate method chaining
*/
public SerializationHints registerType(TypeReference type) {
return registerType(type, null);
}
/**
* Register that the specified type need to be serialized using java
* serialization.
* @param type the type to register
* @param serializationHint a builder to further customize the serialization
* @return {@code this}, to facilitate method chaining
*/
public SerializationHints registerType(Class<? extends Serializable> type, @Nullable Consumer<JavaSerializationHint.Builder> serializationHint) {
return registerType(TypeReference.of(type), serializationHint);
}
/**
* Register that the specified type need to be serialized using java
* serialization.
* @param type the type to register
* @return {@code this}, to facilitate method chaining
*/
public SerializationHints registerType(Class<? extends Serializable> type) {
return registerType(type, null);
}
}
|
package pl.pmisko.mypetclinic.services;
import pl.pmisko.mypetclinic.model.Vet;
public interface VetService extends CrudService<Vet, Long> {
}
|
package upm.tdd.training;
public class Frame {
private int firstThrow;
private int secondThrow;
public Frame(int firstThrow, int secondThrow){
this.firstThrow = firstThrow;
this.secondThrow = secondThrow;
}
//
//the score of a single frame
public int score(){
int frameScore;
frameScore = firstThrow + secondThrow;
return 0;
}
//returns whether the frame is a strike or not
public boolean isStrike(){ //10 pins in one throws
int strike, nextOneThrows = 0, nextSecondThrow = 0;
boolean isStrike;
firstThrow = 10;
if (isStrike = true){
strike = firstThrow + nextOneThrows + nextSecondThrow;
}
return false;
}
//return whether a frame is a spare or not
public boolean isSpare(){ //10 pins in two throws
int spare, nextOneThrows = 0;
boolean isSpare;
if (isSpare = true){
spare = firstThrow + secondThrow + nextOneThrows;
}
return false;
}
//return whether this is the last frame of the match
public boolean isLastFrame(){
boolean lastFrame, bonusSpare, bonusStrike;
int scoreFinal;
if(lastFrame = true){
score();
if( bonusSpare = true) {
isSpare();
}
if ( bonusStrike = true){
isStrike();
}
}
return false;
}
//bonus throws
public int bonus(){
int strikeBonus = firstThrow + secondThrow;
int spareBonus = firstThrow;
return 0;
}
}
|
package deloitte.forecastsystem_bih.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="df_holiday_schedule")
public class HolidaySchedule implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8850057350668821149L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID", nullable=false, updatable = true)
private Long id;
@Column(name="Holiday_fk")
private Integer holiday;
@Column(name="Start_date")
private Date startDate;
@Column(name="End_date")
private Date endDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getHoliday() {
return holiday;
}
public void setHoliday(Integer holiday) {
this.holiday = holiday;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}
|
package com.yjn.haoba.services;
import com.yjn.haoba.domain.User;
import com.yjn.haoba.domain.UserExample;
import com.yjn.haoba.persistence.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created with IntelliJ IDEA.
* User: yjn
* Date: 13-3-8
* Time: 下午8:51
* To change this template use File | Settings | File Templates.
*/
@Service
public class UserService {
@Autowired
protected UserMapper userMapper;
public int login(User user) {
User user1 = null;
UserExample userExample = new UserExample();
userExample.createCriteria()
.andEmailEqualTo(user.getEmail())
.andPasswdEqualTo(user.getPasswd());
int result = userMapper.countByExample(userExample);
return result;
}
public int insert(User user){
return userMapper.insert(user);
}
}
|
package fourth.task.android.utils;
import java.io.Serializable;
import java.util.Arrays;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import fourth.task.android.ListViewFragment;
import fourth.task.android.R;
import fourth.task.android.cities.City;
/**
* FragmentDialog representing add/edit city view.
*/
public class DialogFragmentAddEdit extends DialogFragment {
private final String REGEX_FOR_SIGNED_DOUBLE_NUMBERS = "-?\\d+(.\\d+)?";
private boolean isViewInitialized;
private Activity activity;
private AlertDialog alertDialog;
private City currentCity;
private View dialogView;
private EditText nameEditText;
private EditText latitudeEditText;
private EditText longitudeEditText;
private Button okButton;
private Button cancelButton;
private Spinner spinnerCityColor;
/* The activity that creates an instance of this dialog fragment must
* implement this interface in order to receive event callback. Each method
* passes the DialogFragment in case the host needs to query it. */
public interface NoticeDialogListener extends Serializable {
void onDialogPositiveClick(City newCity, City oldCity);
}
// Use this instance of the interface to deliver action events
NoticeDialogListener mListener;
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
@Override public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = activity;
this.mListener = (ListViewFragment) getFragmentManager().findFragmentById(R.id.fragment_container);
}
@Override public Dialog onCreateDialog(Bundle savedInstanceState) {
// Initialize particular views if not initialized yet
if (!isViewInitialized) {
dialogView = activity.getLayoutInflater().inflate(R.layout.fragment_add_dialog, null);
nameEditText = (EditText) dialogView.findViewById(R.id.EditTextCityName);
latitudeEditText = (EditText) dialogView.findViewById(R.id.EditTextCityLatitude);
longitudeEditText = (EditText) dialogView.findViewById(R.id.EditTextCityLongitude);
okButton = (Button) dialogView.findViewById(R.id.buttonOkAlertDialog);
okButton.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
onOkButtonClick();
}
});
cancelButton = (Button) dialogView.findViewById(R.id.buttonCancelAlertDialog);
cancelButton.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
onCancelButtonClick();
}
});
spinnerCityColor = (Spinner) dialogView.findViewById(R.id.SpinnerCityColor);
isViewInitialized = true;
}
currentCity = getCurrentCity();
if (currentCity != null) {
nameEditText.setText(currentCity.getName());
nameEditText.selectAll();
latitudeEditText.setText(String.valueOf(currentCity.getLatitude()));
longitudeEditText.setText(String.valueOf(currentCity.getLongitude()));
spinnerCityColor.setSelection(Arrays.asList(getResources().getStringArray(R.array.colors)).indexOf(
currentCity.getColor().toUpperCase()));
}
// Build custom alert dialog, create it and return as a result
alertDialog = new AlertDialog.Builder(activity).setTitle(R.string.label_manageCity).setView(dialogView)
.create();
return alertDialog;
}
private City getCurrentCity() {
City currentCity = null;
Bundle cityBundle = getArguments();
if (cityBundle != null) {
currentCity = (City) cityBundle.getSerializable(ListViewFragment.STRING_CURRENT_CITY);
}
return currentCity;
}
public void onOkButtonClick() {
if (!isInputDataValid()) {
Toast.makeText(activity, R.string.alert_data_not_valid, Toast.LENGTH_SHORT).show();
}
else {
if (mListener != null) {
mListener.onDialogPositiveClick(
new City(nameEditText.getText().toString(), Double.valueOf(latitudeEditText.getText().toString()),
Double.valueOf(longitudeEditText.getText().toString()), currentCity.getTemperature(),
spinnerCityColor.getSelectedItem().toString(), currentCity.getBitmapArray()), currentCity);
}
onCancelButtonClick();
}
}
public void onCancelButtonClick() {
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
}
/**
* Validates if provided data in EditTexts and Spinner is correct. Name
* should be non zero-length string, Latitude and Longitude must be positive
* or negative float numbers between <-90,90> and <-180, 180> respectively.
*
* @return validating result
*/
private boolean isInputDataValid() {
if (nameEditText.getText().toString().length() == 0) return false;
String latitudeString = latitudeEditText.getText().toString();
String longitudeString = longitudeEditText.getText().toString();
if (latitudeString.length() == 0 || !latitudeString.matches(REGEX_FOR_SIGNED_DOUBLE_NUMBERS)) return false;
if (longitudeString.length() == 0 || !longitudeString.matches(REGEX_FOR_SIGNED_DOUBLE_NUMBERS)) return false;
float latitudeFloat = Float.parseFloat(longitudeString);
float longitudeFloat = Float.parseFloat(longitudeString);
if (latitudeFloat > 90 || latitudeFloat < -90) return false;
if (longitudeFloat > 180 || longitudeFloat < -180) return false;
return spinnerCityColor.getSelectedItemPosition() != 0;
}
}
|
package com.deepakm.java.eventdelegation;
import java.util.Observable;
import java.util.Observer;
/**
* Created by dmarathe on 10/30/16.
*/
public class WeatherWatcher implements Observer {
@Override
public void update(Observable o, Object arg) {
if (o instanceof WeatherForecaster) {
WeatherChangeEvent event = (WeatherChangeEvent) arg;
System.out.println(event);
}
}
}
|
package io.jrevolt.sysmon.rest;
import java.net.URI;
/**
* @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a>
*/
public class Service {
URI uri;
ServiceStatus status;
public URI getUri() {
return uri;
}
public void setUri(URI uri) {
this.uri = uri;
}
public ServiceStatus getStatus() {
return status;
}
public void setStatus(ServiceStatus status) {
this.status = status;
}
}
|
package Fragments.FrondFragments;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.hasan.fragments_with_navigator.R;
import Fragments.Abstract.AFrondFrag;
public class FrondFragMode extends AFrondFrag {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_mode, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView tvMode = getActivity().findViewById(R.id.tvMode);
tvMode.setOnClickListener(this);
}
}
|
package exercices;
public class Projet {
Binome b;
String titre;
float note;
public Projet() {
super();
}
public Projet(Binome b, String titre, float note) {
super();
this.b = b;
this.titre = titre;
this.note = note;
}
@Override
public String toString() {
return "Projet [b=" + b + ", titre=" + titre + ", note=" + note + "]";
}
}
|
package bib;
import bib.iterateurs.IterateurLexique;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
/**
* Created by Gauthier on 20/03/2017.
*/
public class Lexique implements Iterable<String> {
private int nbMots;
private String[] lexique;
public Lexique(int capacite){
lexique= new String[capacite];
nbMots = 0;
}
public void ajouter(String mot){
lexique[nbMots]=new String(mot);
nbMots++;
}
public int nbMots(){
return nbMots;
}
public int getCapacite(){
return lexique.length;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append("Le lexique contient les mots :");
for (int i = 0; i < nbMots; i++) {
s.append("\n"+lexique[i] );
}
return s.toString();
}
public Iterator<String> iterator() {
ArrayList<String> listemot = new ArrayList<>(nbMots);
for (int i = 0; i < nbMots; i++) {
listemot.add(lexique[i]);
}
return listemot.iterator();
}
public IterateurLexique iterator2() {
return new IterateurLexique(lexique,nbMots);
}
}
|
package library.daos;
import java.util.ArrayList;
import java.util.List;
import library.interfaces.daos.IBookDAO;
import library.interfaces.daos.IBookHelper;
import library.interfaces.entities.IBook;
public class BookDAO implements IBookDAO
{
private IBookHelper helper_;
private ArrayList<IBook> bookList_ = new ArrayList<IBook>();
private int nextBookId;
public BookDAO(IBookHelper helper)
{
if (helper == null) {
throw new IllegalArgumentException("Helper cannot null.");
}
this.helper_ = helper;
this.bookList_ = new ArrayList<>();
this.nextBookId = 1;
}
@Override
public IBook addBook(String author, String title, String callNo)
{
int bookId = getNextBookId();
IBook book = this.helper_.makeBook(author, title, callNo, bookId);
this.bookList_.add(book);
return book;
}
@Override
public IBook getBookByID(int id)
{
for (IBook book : bookList_) {
if (book.getID() == id) {
return book;
}
}
return null;
}
@Override
public List<IBook> listBooks()
{
return bookList_;
}
@Override
public List<IBook> findBooksByAuthor(String author)
{
if ((author == null) || (author.isEmpty())) {
throw new IllegalArgumentException("Author cannot be "
+ "blank or null.");
}
List<IBook> books = new ArrayList<>();
for (IBook book : books) {
if (author.equals(book.getAuthor())) {
books.add(book);
}
}
return books;
}
@Override
public List<IBook> findBooksByTitle(String title)
{
if ((title == null) || (title.isEmpty())) {
throw new IllegalArgumentException("Title cannot be "
+ "blank or null.");
}
List<IBook> books = new ArrayList<>();
for (IBook book : books) {
if (title.equals(book.getTitle())) {
books.add(book);
}
}
return books;
}
@Override
public List<IBook> findBooksByAuthorTitle(String author, String title)
{
if ((author == null) || (author.isEmpty()) || (title == null) || (title.isEmpty())) {
throw new IllegalArgumentException("Author and Title cannot be "
+ "blank or null.");
}
List<IBook> books = new ArrayList<>();
for (IBook book : books) {
if ((author.equals(book.getAuthor())) && (title.equals(book.getTitle()))) {
books.add(book);
}
}
return books;
}
private int getNextBookId()
{
return this.nextBookId++;
}
}
|
package de.wiltherr.ws2812fx.serial.communication;
public class SerialPacketCommunicatorClosingException extends IllegalStateException {
public SerialPacketCommunicatorClosingException(String message) {
}
}
|
package be.odisee.pajotter.domain;
import java.util.List;
import javax.persistence.*;
@Entity
@DiscriminatorValue("Koper")
public class Koper extends Rol {
public Koper(){}
public Koper(String status, String usernaam, Partij partij){
super(status,usernaam,partij);
}
public Koper(int id, String status, String usernaam, Partij partij){
super(id,status,usernaam,partij);
}
@Override
public String getType() {
return "Koper";
}
}
|
package com.arthur.bishi.ali.ali0507;
/**
* @title: No2
* @Author ArthurJi
* @Date: 2021/5/7 19:30
* @Version 1.0
*/
import java.util.*;
public class No2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
// 构建二叉树
TreeNode root = buildTree(nums);
// 移动二叉树
moveTree(root, k);
}
private static void moveTree(TreeNode root, int k) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
// 队列访问
while (!queue.isEmpty()) {
List<TreeNode> list = new ArrayList<>();
int size = queue.size();
while (size > 0) {
TreeNode node = queue.remove();
list.add(node);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
size--;
}
int len = k % list.size();
// 循环左移
List<Integer> tempList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
tempList.add(list.get((i + len) % list.size()).val);
}
for (int i = 0; i < list.size(); i++) {
TreeNode node = list.get(i);
node.val = tempList.get(i);
}
}
}
private static TreeNode buildTree(int[] nums) {
TreeNode root = new TreeNode(nums[0]);
for (int i = 1; i < nums.length; i++) {
createTreeNode(root, nums[i]);
}
return root;
}
private static void createTreeNode(TreeNode node, int val) {
if (val < node.val) {
if (node.left == null) {
node.left = new TreeNode(val);
} else {
createTreeNode(node.left, val);
}
} else {
if (node.right == null) {
node.right = new TreeNode(val);
} else {
createTreeNode(node.right, val);
}
}
}
}
class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.support;
import java.util.Hashtable;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
/**
* Helper class for the creation of {@link javax.management.ObjectName} instances.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 1.2
* @see javax.management.ObjectName#getInstance(String)
*/
public final class ObjectNameManager {
private ObjectNameManager() {
}
/**
* Retrieve the {@link ObjectName} instance corresponding to the supplied name.
* @param name the name in {@code ObjectName} or {@code String} format
* @return the {@code ObjectName} instance
* @throws MalformedObjectNameException in case of an invalid object name specification
* @see ObjectName#ObjectName(String)
* @see ObjectName#getInstance(String)
*/
public static ObjectName getInstance(Object name) throws MalformedObjectNameException {
if (name instanceof ObjectName objectName) {
return objectName;
}
if (!(name instanceof String text)) {
throw new MalformedObjectNameException("Invalid ObjectName value type [" +
name.getClass().getName() + "]: only ObjectName and String supported.");
}
return getInstance(text);
}
/**
* Retrieve the {@code ObjectName} instance corresponding to the supplied name.
* @param objectName the {@code ObjectName} in {@code String} format
* @return the {@code ObjectName} instance
* @throws MalformedObjectNameException in case of an invalid object name specification
* @see ObjectName#ObjectName(String)
* @see ObjectName#getInstance(String)
*/
public static ObjectName getInstance(String objectName) throws MalformedObjectNameException {
return ObjectName.getInstance(objectName);
}
/**
* Retrieve an {@code ObjectName} instance for the specified domain and a
* single property with the supplied key and value.
* @param domainName the domain name for the {@code ObjectName}
* @param key the key for the single property in the {@code ObjectName}
* @param value the value for the single property in the {@code ObjectName}
* @return the {@code ObjectName} instance
* @throws MalformedObjectNameException in case of an invalid object name specification
* @see ObjectName#ObjectName(String, String, String)
* @see ObjectName#getInstance(String, String, String)
*/
public static ObjectName getInstance(String domainName, String key, String value)
throws MalformedObjectNameException {
return ObjectName.getInstance(domainName, key, value);
}
/**
* Retrieve an {@code ObjectName} instance with the specified domain name
* and the supplied key/name properties.
* @param domainName the domain name for the {@code ObjectName}
* @param properties the properties for the {@code ObjectName}
* @return the {@code ObjectName} instance
* @throws MalformedObjectNameException in case of an invalid object name specification
* @see ObjectName#ObjectName(String, java.util.Hashtable)
* @see ObjectName#getInstance(String, java.util.Hashtable)
*/
public static ObjectName getInstance(String domainName, Hashtable<String, String> properties)
throws MalformedObjectNameException {
return ObjectName.getInstance(domainName, properties);
}
}
|
package controller.core;
import webserver.http.request.HttpRequest;
import webserver.http.response.HttpResponse;
import java.io.IOException;
import java.net.URISyntaxException;
public interface Controller {
void service(HttpRequest httpRequest, HttpResponse response) throws IOException, URISyntaxException;
}
|
package mainpkg;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import lotto.Lotto;
public class KajaLottomain {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext2.xml");
Lotto lo1 = (Lotto)ac.getBean("lotto1");
lo1.kajaLotto("print!!!! >>>> ");
lo1.kajaLotto("print!!!! >>>> ");
lo1.kajaLotto("print!!!! >>>> ");
lo1.kajaLotto("print!!!! >>>> ");
lo1.kajaLotto("print!!!! >>>> ");
lo1.kajaLotto("print!!!! >>>> ");
lo1.kajaLotto("print!!!! >>>> ");
}
}
|
package com.equipo12.retobc.model.commons;
import lombok.Getter;
public class BalanceAndMovementException extends RuntimeException{
private static final long serialVersionUID = 1L;
@Getter
private String code;
public BalanceAndMovementException(String message) {
super(message);
}
public BalanceAndMovementException(String message, String code) {
super(message);
this.code = code;
}
}
|
package au.com.mayi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RefreshScope
@RestController
class MessageRestController {
@Autowired
private TestProperties testProperties;
@Value("${message:Hello default}")
private String message;
@RequestMapping("/message")
String getMessage() {
return this.message + " -- " + testProperties.getMessage();
}
}
|
package com.itcia.itgoo;
import java.security.Principal;
import java.util.List;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.itcia.itgoo.dto.Activity;
import com.itcia.itgoo.dto.Auction;
import com.itcia.itgoo.dto.Reservation;
import com.itcia.itgoo.dto.SmallMeeting;
import com.itcia.itgoo.dto.Test;
import com.itcia.itgoo.service.AuctionManagement;
import com.itcia.itgoo.service.ClientManagement;
import com.itcia.itgoo.service.TestManagement;
@Secured("ROLE_USER")
@Controller
public class Client2Controller {
ModelAndView mav = new ModelAndView();
@Autowired
private TestManagement tm;
@Autowired
private AuctionManagement am;
@Autowired
private ClientManagement cm;
@PreAuthorize("isAuthenticated()")
@GetMapping("/testpaper")
public ModelAndView testPaper(int dogid) {
mav = tm.testPaper(dogid);
return mav;
}
@PreAuthorize("isAuthenticated()")
@PostMapping("/testpapersubmit")
public ModelAndView testPaperSubmit(String test, Principal p) {
System.out.println("===================test====================");
System.out.println(test);
mav = tm.testPaperSubmit(test, p);
return mav;
}
@PreAuthorize("isAuthenticated()")
@GetMapping("/auctionfrm")
public ModelAndView auctionFrm() {
mav.setViewName("client/AuctionFrm");
return mav;
}
@PostMapping("/addauction")
public ModelAndView addAuction(Principal p, Auction a, MultipartFile f, String srcJson) {
mav = am.addAuction(p, a, f, srcJson);
return mav;
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/auctionlist", method = RequestMethod.GET)
public ModelAndView auctionList() {
mav = am.auctionList();
return mav;
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/auctionattend", method = RequestMethod.GET)
public ModelAndView auctionAttend(int auctionnum, Principal p) {
mav = am.auctionAttend(auctionnum, p);
return mav;
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/auctiondetail", method = RequestMethod.GET)
public ModelAndView auctionDetail(int auctionnum) {
mav = am.auctionDetail(auctionnum);
return mav;
}
@RequestMapping(value = "/puppysmall", method = RequestMethod.GET)
public String puppysmall(Locale locale, Model model) {
return "client/puppySmall";
}
@RequestMapping(value = "/smalllist", method = RequestMethod.GET)
public ModelAndView smalllist(SmallMeeting sm) {
ModelAndView mav = new ModelAndView();
mav = cm.smalllist(sm);
return mav;
}
@RequestMapping(value = "/joinsmallmeeting", method = RequestMethod.GET)
public ModelAndView joinsmallmeeting(Principal p, SmallMeeting sm) {
mav=cm.joinsmallmeeting(p,sm);
return mav;
}
@RequestMapping(value = "/smalljoincancle", method = RequestMethod.GET)
public ModelAndView smalljoincancle(Principal p, int smallnumber) {
mav=cm.smalljoincancle(p,smallnumber);
return mav;
}
@RequestMapping(value = "/smalldetail" , method = RequestMethod.GET)
public ModelAndView smalldetail(Principal p,Integer smallnumber) { //null 값도 받으려고
mav= cm.smalldetail(smallnumber,p);
return mav;
}
@RequestMapping(value = "/regipuppysmall", method = RequestMethod.GET)
public String regipuppysmall(Locale locale, Model model) {
return "client/regiPuppySmall";
}
@RequestMapping(value = "/mysmallmeeting", method = RequestMethod.GET)
public ModelAndView mysmallmeeting(Principal p, SmallMeeting sm) {
ModelAndView mav = new ModelAndView();
mav = cm.myrecruitsmall(p, sm);
return mav;
}
@RequestMapping(value = "/myenrollsmallmeeting", method = RequestMethod.GET)
public ModelAndView myenrollsmallmeeting(Principal p, SmallMeeting sm) {
ModelAndView mav = new ModelAndView();
mav = cm.myenrollsmall(p, sm);
return mav;
}
@RequestMapping(value = "/delmysmallmeeting")
public ModelAndView delmysmallmeeting(Principal p, SmallMeeting sm, RedirectAttributes attr) {
ModelAndView mav = new ModelAndView();
mav = cm.delmysmallmeeting(p, sm, attr);
attr.addFlashAttribute("sm", sm);
return mav;
}
@RequestMapping(value = "/myauction", method = RequestMethod.GET)
public ModelAndView myauction(Principal p) {
ModelAndView mav = new ModelAndView();
mav = cm.myauction(p.getName());
return mav;
}
@RequestMapping(value = "/completesmall")
public ModelAndView completesmall(SmallMeeting sm, RedirectAttributes attr) { // null 값도 받으려고
mav = cm.completesmall(sm, attr);
attr.addFlashAttribute("sm", sm);
return mav;
}
@RequestMapping(value = "/cancelsmall")
public ModelAndView cancelsmall(SmallMeeting sm, RedirectAttributes attr) { // null 값도 받으려고
mav = cm.cancelsmall(sm, attr);
attr.addFlashAttribute("sm", sm);
return mav;
}
@RequestMapping(value = "/mysmallmeetingdetail", method = RequestMethod.GET)
public ModelAndView mysmallmeetingdetail(Principal p, SmallMeeting sm, int smallnumber) { // null 값도 받으려고
System.out.println("여기 있어요");
mav = cm.mysmallmeetingdetail(p, sm, smallnumber);
return mav;
}
}
|
package jp.co.softem.apps.core;
import java.util.List;
import java.util.Map;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.GlobalTransaction;
import org.slim3.datastore.ModelMeta;
import org.slim3.util.BeanUtil;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;
public abstract class BaseService<T> {
protected static final int MAXIMUM = 1000;
protected ModelMeta<T> baseMeta;
public BaseService(ModelMeta<T> meta) {
this.baseMeta = meta;
}
public T get(Key key, Long version) {
return (T) Datastore.get(baseMeta, key, version);
}
public List<T> getAll() {
return Datastore.query(baseMeta).asList();
}
public List<T> list(int offset, int limit) {
return Datastore.query(baseMeta).offset(offset).limit(limit).asList();
}
public int count() {
return Datastore.query(baseMeta).count();
}
public void insert(T entity) {
GlobalTransaction gtx = Datastore.beginGlobalTransaction();
gtx.put(entity);
gtx.commit();
}
public T update(Key key, Long version, Map<String, Object> input) {
GlobalTransaction gtx = Datastore.beginGlobalTransaction();
T entity = gtx.get(baseMeta, key, version);
BeanUtil.copy(input, entity);
gtx.put(entity);
gtx.commit();
return entity;
}
public void delete(Key key, Long version) {
GlobalTransaction gtx = Datastore.beginGlobalTransaction();
gtx.get(baseMeta, key, version);
gtx.delete(key);
gtx.commit();
}
public void deleteAll() {
Transaction tx = Datastore.beginTransaction();
while (true) {
List<Key> keyList =
Datastore.query(baseMeta).offset(0).limit(MAXIMUM).asKeyList();
if (keyList.size() < 1) {
break;
}
Datastore.delete(keyList);
// TODO: 逐次コミット?
}
tx.commit();
}
}
|
package com.imdongh.mvpdemo01.base;
public class BasePresenter<V extends BaseView> {
private V mView;
public BasePresenter() {
this.mView = mView;
}
public void attachView(V mView) {
this.mView = mView;
}
public void detachView() {
this.mView = null;
}
public boolean isViewAttached() {
return mView != null;
}
public V getView() {
return mView;
}
}
|
/**
* Server-side classes for use with standard JSR-356 WebSocket endpoints.
*/
@NonNullApi
@NonNullFields
package org.springframework.web.socket.server.standard;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package com.ggw.vem;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class PayPwdFind extends Activity {
String mailbox;
String userID;
String userid;
boolean issuc=false;
Button fsub,ret;
EditText mal,que;
TextView byQuestion;
public ProgressDialog dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_pwd_find);
getuserid();
init();
setListener();
}
private void getuserid(){
Bundle bundle = this.getIntent().getExtras();
userid=bundle.getString("userID",null);
}
public void init(){
fsub=(Button)findViewById(R.id.paysub);
mal=(EditText)findViewById(R.id.paymail);
byQuestion = (TextView)findViewById(R.id.paybyanswer);
ret=(Button)findViewById(R.id.payback);
}
public void findPasswordByMail(){
dialog = ProgressDialog.show(PayPwdFind.this, "请稍等片刻", "正在发送中...",true);
new Thread() {
@Override
public void run() {
try {
String url = "http://222.205.47.11/server/index.php/server/resetPayPwdByEmail/"+ mailbox;
HttpJsonGet requestSent = new HttpJsonGet(url);
JSONObject jsonTemp = requestSent.getJsonObject();
if(jsonTemp==null){
Message msg = new Message();
Bundle data = new Bundle();
data.putInt("result", 3);
msg.setData(data);
handler.sendMessage(msg);
//Toast.makeText(PayPwdFind.this, "网络异常", Toast.LENGTH_SHORT).show();
}
else{
issuc = jsonTemp.getBoolean("result");
Log.v("TestActivity", "result:" + issuc);
if(issuc){
jum(true);
Message msg = new Message();
Bundle data = new Bundle();
data.putInt("result", 2);
msg.setData(data);
handler.sendMessage(msg);
//Toast.makeText(Login.this, "账号和密码已经成功发送到您的邮箱!!!", Toast.LENGTH_SHORT).show();
}
else{
Message msg = new Message();
Bundle data = new Bundle();
data.putInt("result", 1);
msg.setData(data);
handler.sendMessage(msg);
//Toast.makeText(Login.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
}
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
}
dialog.dismiss();
}
}.start();
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
int val = data.getInt("result");
switch(val){
case 1:Toast.makeText(PayPwdFind.this, "您输入的邮箱不存在", Toast.LENGTH_SHORT).show();break;
case 2:Toast.makeText(PayPwdFind.this, "账号及随机密码已经成功发送到您的邮箱", Toast.LENGTH_SHORT).show();break;
case 3:Toast.makeText(PayPwdFind.this, "网络异常!!!!", Toast.LENGTH_SHORT).show();break;
}
}
};
public void jum(boolean is){
if(is){
Intent intent =new Intent();
intent.setClass(PayPwdFind.this,ManagePwd.class);
intent.putExtra("userID",userid);
startActivity(intent);
PayPwdFind.this.finish();
overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
}
}
private void setListener(){
fsub.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mailbox=mal.getText().toString();
if(!mailbox.trim().equals("")){
findPasswordByMail();
}
else {
Toast.makeText(PayPwdFind.this, "请输入邮箱或者账号!", Toast.LENGTH_SHORT).show();
}
}
});
ret.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
jum(true);
}
});
byQuestion.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
Intent intent =new Intent();
intent.setClass(PayPwdFind.this,FindPayPwdQuestion.class);
intent.putExtra("userID",userid);
startActivity(intent);
PayPwdFind.this.finish();
overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
}
});
}
}
|
package com.example.movieapp;
public interface PopularListener {
void onSuccessResponse(JsonResponse data);
void onErrorResponse(String data);
}
|
package com.seedo.ligerui.action.movie;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import com.seedo.movie.model.MvTsFilmDiscount;
import com.seedo.platform.action.struts.LigerJsonHelperAction;
import com.seedo.platform.config.ConfigFactory;
import com.seedo.platform.dataobject.PageResultInfo;
import com.seedo.platform.model.BasTsParameter;
import com.seedo.platform.service.base.ParameterService;
import com.seedo.platform.utils.MessageUtil;
import com.seedo.platform.utils.MutexBeanProperties;
import com.seedo.service.movie.PreferentialMealManagementService;
public class PreferentialMealManagementAction extends LigerJsonHelperAction{
/*
* 获取系统参数表的记录的儿童折扣id
*/
String paramId=ConfigFactory.getDefaultProvider().getProperty("paramId","configs-application-parameter.properties");
/*
* 获取系统参数表的记录的学生折扣id
*/
String studentId=ConfigFactory.getDefaultProvider().getProperty("studentId","configs-application-parameter.properties");
private String ids;
public String getIds() {
return ids;
}
public void setIds(String ids) {
this.ids = ids;
}
@Autowired
private PreferentialMealManagementService ps;
private MvTsFilmDiscount mvTsFilmDiscount;
@Autowired
private ParameterService pl;
/*
* 修改影片优惠设置界面(edit-discount.jsp)的工作日折扣,节假日折扣,黄金时段折扣三个字段未修改过的值
*/
private boolean oldSpecialAvailableFlag;
public boolean isOldSpecialAvailableFlag() {
return oldSpecialAvailableFlag;
}
public void setOldSpecialAvailableFlag(boolean oldSpecialAvailableFlag) {
this.oldSpecialAvailableFlag = oldSpecialAvailableFlag;
}
public String getOldCommonDiscount() {
return oldCommonDiscount;
}
public void setOldCommonDiscount(String oldCommonDiscount) {
this.oldCommonDiscount = oldCommonDiscount;
}
public String getOldHolidayDiscount() {
return oldHolidayDiscount;
}
public void setOldHolidayDiscount(String oldHolidayDiscount) {
this.oldHolidayDiscount = oldHolidayDiscount;
}
public String getOldSpecialTimeDiscount() {
return oldSpecialTimeDiscount;
}
public void setOldSpecialTimeDiscount(String oldSpecialTimeDiscount) {
this.oldSpecialTimeDiscount = oldSpecialTimeDiscount;
}
private String oldCommonDiscount;
private String oldHolidayDiscount;
private String oldSpecialTimeDiscount;
/*
* 定义要传到add-discount界面的系统参数表
*/
private BasTsParameter studentParam;
private BasTsParameter childParam;
public BasTsParameter getStudentParam() {
return studentParam;
}
public void setStudentParam(BasTsParameter studentParam) {
studentParam = studentParam;
}
public BasTsParameter getChildParam() {
return childParam;
}
public void setChildParam(BasTsParameter childParam) {
this.childParam = childParam;
}
public MvTsFilmDiscount getMvTsFilmDiscount() {
return mvTsFilmDiscount;
}
public void setMvTsFilmDiscount(MvTsFilmDiscount mvTsFilmDiscount) {
this.mvTsFilmDiscount = mvTsFilmDiscount;
}
/**
* listGrid表格需要的数据,显示电影折扣优惠列表
*/
@Action("ajax-preferential-meal-management")
public String viewDiscountList()
{
System.out.println("hdhhdhhhd");
PageResultInfo<MvTsFilmDiscount> l= ps.doFindMvTsFilmDiscount(mvTsFilmDiscount, page, pagesize);
String[] names=new String[]{"id","filmsName","childDiscount","commonDiscount","specialTimeDiscount","holidayDiscount","studentDiscount","specialAvailableFlag"};
MutexBeanProperties mbp=new MutexBeanProperties(MvTsFilmDiscount.class, false, names);
/* BasTsParameter param = pl.doGetById(paramId);
mvTsFilmDiscount.setChildDiscount(param.getValue());
Iterator it= l.getContent().iterator();
while(it.hasNext()){
((MvTsFilmDiscount)it.next()).setChildDiscount(param.getValue());
}*/
return queryResultToGrid(l,mbp,null);
}
/**
* Combobox需要的数据,显示电影名称列表
*/
@Action("ajax-preferential-meal-management1")
public String viewDiscountList1()
{
System.out.println("hdhhdhhhd");
PageResultInfo<MvTsFilmDiscount> l= ps.doFindMvTsFilmDiscount(mvTsFilmDiscount, page, pagesize);
String[] names=new String[]{"id","filmsName","threedDiscount","childDiscount","commonDiscount","vipDiscount","specialTimeDiscount","holidayDiscount","studentDiscount","specialAvailableFlag"};
MutexBeanProperties mbp=new MutexBeanProperties(MvTsFilmDiscount.class, false, names);
return queryResultToJson(l.getContent(), mbp);//返回json数据返回给combobox或tree
}
/**
* @return新增电影折扣优惠记录
*/
@Action(value="save-discount",results={@Result(location="add-discount.jsp")})
public String saveDiscount()
{
/*
* 刷新表格作用
* "listGrid"==》表格Id
*/
setRefreshGridId("discountList");//将值传到电影优惠设置jsp界面,接着刷新界面
/*
* 获取basTsParameter系统参数表中的学生和儿童的具体折扣
*/
childParam = pl.doGetById(paramId);
studentParam = pl.doGetById(studentId);
mvTsFilmDiscount.setChildDiscount(childParam.getValue());
mvTsFilmDiscount.setStudentDiscount(studentParam.getValue());
ps.doSaveFilmDiscount(mvTsFilmDiscount);
/*
* 刷新表格作用
* "listGrid"==》表格Id
*/
setRefreshGridId("discountList");//将值传到电影优惠设置jsp界面,接着刷新界面
return SUCCESS;
}
/**
* @return 修改电影折扣优惠,更新电影折扣优惠记录
*/
@Action(value="update-discount",results={@Result(location="edit-discount.jsp")})
public String updateDiscount()
{
/*
* 刷新表格作用
* "listGrid"==》表格Id
*/
setRefreshGridId("discountList");//将值传到jsp界面,接着刷新界面
ps.doUpdateFilmDiscount(mvTsFilmDiscount);
return SUCCESS;
}
/**
* @return修改电影优惠折扣
*/
@Action("edit-discount")
public String editDiscount()
{
/*
* 修改操作
*/
mvTsFilmDiscount=ps.doGetById(mvTsFilmDiscount.getId());
return SUCCESS;
}
/**
* @return新增电影优惠折扣
*/
@Action("add-discount")
public String addDiscount()
{
/*
* 新增操作
*/
mvTsFilmDiscount=null;
/*
* 获取系统参数表的记录的儿童折扣id
*/
String paramId=ConfigFactory.getDefaultProvider().getProperty("paramId","configs-application-parameter.properties");
/*
* 获取系统参数表的记录的学生折扣id
*/
String studentId=ConfigFactory.getDefaultProvider().getProperty("studentId","configs-application-parameter.properties");
/*
* 获取basTsParameter系统参数表中的学生和儿童的具体折扣
*/
childParam = pl.doGetById(paramId);
studentParam = pl.doGetById(studentId);
return SUCCESS;
}
/**
* @return删除电影优惠折扣
*/
@Action(value="ajax-del-discount")
public String deleteDiscount()
{
/*
* 建议用action名称命名规范来取代callJson=true;,命名规范只要在action名称含有“ajax”字符即可.
* 如:
* @Action("ajax-get-sub-params")
*/
ajaxCall=true;
ps.doDeleteFilmDiscount(ids);
MessageUtil.addMessage("删除电影优惠成功!");//只有a jax的删除方法才能提示改错误信息
return writeJson2Client(null);
}
}
|
package cn.edu.gdmec.s07131020.demo_loader;
public class Book {
private String _id;
private String name;
private float price;
private String publisher;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Book(String _id, String name, float price, String publisher) {
super();
this._id = _id;
this.name = name;
this.price = price;
this.publisher = publisher;
}
public Book() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Book [_id=" + _id + ", name=" + name + ", price=" + price
+ ", publisher=" + publisher + "]";
}
}
|
import java.util.*;
import java.io.*;
class fibonacci
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int num=kb.nextInt();
if(num>2)
{
int a=1;
int b=1;
System.out.print(a+" "+b+" ");
int c;
num=num-2;
while(num!=0)
{
c=a+b;
System.out.print(c+" ");
a=b;
b=c;
num--;
}
System.out.println();
}
else
{
if(num==1)
{
System.out.println("1");
}
else
{
System.out.println("1 1");
}
}
}
}
|
package man.frechet.demo.actuator.boot.jmxresource;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@ManagedResource
@Component
public class TraceCountResource {
private Map<String, Long> count = new HashMap<>();
@ManagedOperation
public Map<String, Long> getCount() {
return count;
}
}
|
package expansion.neto.com.mx.jefeapp.sorted.autoriza;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import java.util.Comparator;
import expansion.neto.com.mx.jefeapp.databinding.ItemAutorizaPeatonalPrickerBinding;
import expansion.neto.com.mx.jefeapp.modelView.autorizaModel.Peatonal;
import expansion.neto.com.mx.jefeapp.sorted.SortedListAdapter;
/**
* Clase que implementa el adaptador de los Recycler View
* Created by Kevin on 26/6/2017.
*/
public class AdapterAutorizaPeatonal extends SortedListAdapter<Peatonal> {
AutorizaHolderPeatonal.Listener listener;
Context context;
public AdapterAutorizaPeatonal(Context context, Comparator<Peatonal> comparator, AutorizaHolderPeatonal.Listener listener) {
super(context, Peatonal.class, comparator);
this.listener = listener;
this.context = context;
}
@Override
protected ViewHolder<? extends Peatonal> onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {
final ItemAutorizaPeatonalPrickerBinding binding = ItemAutorizaPeatonalPrickerBinding.inflate(inflater, parent, false);
binding.setListener(listener);
return new AutorizaHolderPeatonal(binding, listener);
}
@Override
protected boolean areItemsTheSame(Peatonal item1, Peatonal item2) {
return false;
}
@Override
protected boolean areItemContentsTheSame(Peatonal oldItem, Peatonal newItem) {
return false;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.