text stringlengths 10 2.72M |
|---|
package com.ruenzuo.sabisukatto.settings;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ruenzuo.sabisukatto.R;
import java.util.List;
/**
* Created by ruenzuo on 18/03/2017.
*/
public class SettingsAdapter extends RecyclerView.Adapter<SettingsAdapter.SettingViewHolder> {
private List<Setting> dataSet;
private Context context;
public SettingsAdapter(Context context, List<Setting> dataSet) {
this.context = context;
this.dataSet = dataSet;
}
public void setDataSet(List<Setting> dataSet) {
this.dataSet = dataSet;
}
@Override
public SettingsAdapter.SettingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.view_setting, parent, false);
SettingViewHolder viewHolder = new SettingViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(SettingsAdapter.SettingViewHolder viewHolder, int position) {
Setting setting = dataSet.get(position);
viewHolder.textViewTitle.setText(setting.getTitle());
if (setting.getValue() != null) {
viewHolder.textViewValue.setText(setting.getValue());
} else {
viewHolder.textViewValue.setText("");
}
}
@Override
public int getItemCount() {
return dataSet.size();
}
public static class SettingViewHolder extends RecyclerView.ViewHolder {
public TextView textViewTitle;
public TextView textViewValue;
public SettingViewHolder(View root) {
super(root);
this.textViewTitle = (TextView) root.findViewById(R.id.text_view_title);
this.textViewValue = (TextView) root.findViewById(R.id.text_view_value);
}
}
}
|
package com.jd.jarvisdemonim.ui.testadapteractivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.jd.jarvisdemonim.R;
import com.jd.jarvisdemonim.entity.RetrofitTestBean;
import com.jd.jarvisdemonim.ui.controller.RetrofitTestImpl;
import com.jd.jdkit.elementkit.activity.DBaseActivity;
import com.jd.jdkit.elementkit.utils.system.ToastUtils;
import com.jd.jdkit.okhttp.IOnHttpListener;
import com.lzy.okhttputils.model.HttpParams;
import butterknife.Bind;
import okhttp3.Response;
/**
* Auther: Jarvis Dong
* Time: on 2017/2/17 0017
* Name:
* OverView: 测试retrofit下载;
* Usage:
* @see RetrofitTestBean
*/
public class NormalTestRetrofitActivity extends DBaseActivity implements View.OnClickListener {
@Bind(R.id.txt_net)
TextView txtNet;
@Bind(R.id.btn_net)
Button btn;
RetrofitTestImpl testImpl;
private HttpParams mParams;
@Override
public int getContentViewId() {
return R.layout.activity_retrofit;
}
@Override
protected void initView(Bundle savedInstanceState) {
testImpl = new RetrofitTestImpl();
}
@Override
protected void initVariable() {
// mParams = new HttpParams();
// mParams.put("api", "search");
// mParams.put("action", "search");
// mParams.put("page", "1");
// mParams.put("pageSize", "3");
// mParams.put("order", "C_Time");
// mParams.put("sqlText", "Title=\"图书\"");
// mParams.put("content", "图书");
}
@Override
protected void processLogic(Bundle savedInstanceState) {
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
testImpl.getModel(new IOnHttpListener() {
@Override
public void onSuccess(Object o) {
if (o instanceof RetrofitTestBean) {
RetrofitTestBean bean = (RetrofitTestBean) o;
txtNet.setText(bean.getData().get(0).getName() + "\n" + bean.toString());
}
}
@Override
public void onError(Response response, Exception e) {
ToastUtils.showToast("下载出错");
}
@Override
public void onCache(Object o) {
}
@Override
public void onAfter() {
dismissDialog();
}
@Override
public void onBefore() {
showDialog();
}
}, "search","search","1","3","C_Time","Title=\"图书\"","图书");
}
}
|
package com.poly.dotsave;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.StringRequestListener;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.android.material.textfield.TextInputEditText;
import com.google.gson.Gson;
import com.poly.dotsave.adapter.ImageAdapter;
import com.poly.dotsave.adapter.VideoAdapter;
import com.poly.dotsave.gson.Image;
import com.poly.dotsave.gson.Response;
import com.poly.dotsave.gson.Video;
import com.poly.dotsave.model.History;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TextInputEditText edtText;
private Button btnLoad;
private VideoAdapter videoAdapter;
private List<Video> videos;
private TextView tvTitle, tvDescription;
private ImageAdapter imageAdapter;
private List<Image> images;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtText = findViewById(R.id.edtText);
btnLoad = findViewById(R.id.btnLoad);
tvTitle = findViewById(R.id.tvTitle);
tvDescription = findViewById(R.id.tvDescription);
btnLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String test = edtText.getText().toString();
try {
URL url = new URL(test);
requestLink(url.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
edtText.setError(getString(R.string.notify_empty));
Toast.makeText(MainActivity.this, getString(R.string.notify_empty), Toast.LENGTH_SHORT).show();
return;
}
btnLoad.setEnabled(false);
btnLoad.setText(getString(R.string.loading));
}
});
RecyclerView lvListVideos = findViewById(R.id.lvListVideos);
RecyclerView lvListImage = findViewById(R.id.lvListImage);
videos = new ArrayList<>();
videoAdapter = new VideoAdapter(MainActivity.this, videos);
lvListVideos.setAdapter(videoAdapter);
lvListVideos.setLayoutManager(new LinearLayoutManager(MainActivity.this));
images = new ArrayList<>();
imageAdapter = new ImageAdapter(MainActivity.this, images);
lvListImage.setAdapter(imageAdapter);
lvListImage.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
public void requestLink(String url) {
AndroidNetworking.get("https://dotsave.app/")
.addQueryParameter("url", url)
.addQueryParameter("mobile", "3")
.setPriority(Priority.HIGH)
.build()
.getAsString(new StringRequestListener() {
@Override
public void onResponse(String response) {
btnLoad.setEnabled(true);
btnLoad.setText(getString(R.string.btn_load));
Gson gson = new Gson();
Response res = gson.fromJson(response, Response.class);
if (videos.size() > 0) {
videos = new ArrayList<>();
videoAdapter = new VideoAdapter(MainActivity.this, videos);
}
videoAdapter.setTitle(res.getBody().getTitle());
videoAdapter.setDescription(res.getBody().getDescription());
videos.addAll(res.getBody().getVideos());
videoAdapter.notifyDataSetChanged();
SqliteHelper sqliteHelper = new SqliteHelper(MainActivity.this);
sqliteHelper.insert(new History(res.getBody().getVideos().get(0).getUrl(), String.valueOf(System.currentTimeMillis()),
res.getBody().getTitle(), res.getBody().getVideos().get(0).getThumbnail()));
// imageAdapter.setTitle(res.getBody().getTitle());
// imageAdapter.setDescription(res.getBody().getDescription());
// images.addAll(res.getBody().getImages());
// imageAdapter.notifyDataSetChanged();
tvTitle.setText(res.getBody().getTitle());
tvDescription.setText(res.getBody().getDescription());
}
@Override
public void onError(ANError anError) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.option, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.history:
startActivity(new Intent(MainActivity.this, HistoryActivity.class));
break;
case R.id.home:
String url = "https://dotsave.app/privacy";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
break;
case R.id.about:
String home = "https://www.facebook.com/dotsave";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(home));
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
} |
package cn.e3mall.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.e3mall.common.EasyUITreeNode;
import cn.e3mall.service.ItemCatService;
@Controller
public class ItemCatController {
@Autowired
private ItemCatService itemCatService;
@RequestMapping("/item/cat/list")
@ResponseBody
private List<EasyUITreeNode> getItemCatList(@RequestParam(value = "id", defaultValue = "0") Long parentId) {
List<EasyUITreeNode> list = itemCatService.getItemCatList(parentId);
return list;
}
//显示商品类目的时候,由id找到其数据
@RequestMapping("/item/cat/showItemCat")
@ResponseBody
private EasyUITreeNode showItemCat(Long id){
EasyUITreeNode node = itemCatService.showItemCat(id);
return node;
}
}
|
package com.example.suneel.musicapp.Adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.suneel.musicapp.Fragments.Album;
import com.example.suneel.musicapp.Fragments.Artist;
import com.example.suneel.musicapp.R;
import com.example.suneel.musicapp.Utils.ImageNicer;
import com.example.suneel.musicapp.models.SongModel;
import java.util.List;
/**
* Created by suneel on 12/4/18.
*/
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.SongListHolder> {
private Context context;
private List<SongModel> songList;
private Artist mFragment;
public GridAdapter(Context context, List<SongModel> songList, Artist artist) {
this.context = context;
this.songList = songList;
this.mFragment = artist;
}
@Override
public SongListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.cardviewartist, null);
return new GridAdapter.SongListHolder(view);
}
@Override
public void onBindViewHolder(SongListHolder holder, final int position) {
Glide.with(context).load(songList.get(position).getImage()).into(holder.gridImage);
holder.gridArtist.setText(songList.get(position).getTitle());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mFragment != null && mFragment instanceof Artist)
((Artist) mFragment).setGenresList(songList.get(position).getTitle());
}
});
}
@Override
public int getItemCount() {
return songList.size();
}
public class SongListHolder extends RecyclerView.ViewHolder {
ImageView gridImage;
TextView gridArtist;
public SongListHolder(View itemView) {
super(itemView);
gridImage = (ImageView) itemView.findViewById(R.id.ivImage);
gridArtist = (TextView) itemView.findViewById(R.id.tvartist);
}
}
public void addSongs(List<SongModel> songs) {
for (SongModel sm : songs) {
songList.add(sm);
}
notifyDataSetChanged();
}
}
|
package com.kwik.service.category;
import java.util.Collection;
import java.util.List;
import com.kwik.models.Category;
public interface CategoryService {
Collection<Category> listAll();
void add(Category category);
Category findBy(Long id);
void associate(Category category, List<Long> ids);
void destroy(Category category);
}
|
package com.shilong.jysgl.service;
import java.util.List;
import java.util.Map;
import com.shilong.jysgl.pojo.po.Awardtea;
import com.shilong.jysgl.pojo.vo.AwardTeaCustom;
import com.shilong.jysgl.pojo.vo.AwardTeaQueryVo;
public interface AwardTeaService {
public void insertAwardTea(AwardTeaQueryVo awardTeaQueryVo,String teaid) throws Exception;//添加获奖信息
public void updateAwardTea(String id,AwardTeaQueryVo awardTeaQueryVo) throws Exception;//修改获奖信息
public Awardtea getAwardTeaById(String id) throws Exception;//根据id查询获奖信息
public void deleteAwardTeaById(String id) throws Exception;//根据id删除获奖信息
public List<AwardTeaCustom> findAwardTeaList(AwardTeaQueryVo awardTeaQueryVo) throws Exception;//获奖信息列表
public int findAwardTeaCount(AwardTeaQueryVo awardTeaQueryVo) throws Exception;
public List<Map> analysisAwardTeaJbInfo(AwardTeaQueryVo awardTeaQueryVo);
public List<Map> analysisAwardTeaYearInfo(AwardTeaQueryVo awardTeaQueryVo);
}
|
package pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.aventstack.extentreports.Status;
import base.BasePage;
public class LoginPage extends BasePage
{
@FindBy(name="txtUsername") static WebElement username;
@FindBy(name="txtPassword") static WebElement password;
@FindBy(name="Submit") static WebElement signin;
@FindBy(id="spanMessage") static WebElement errmsg;
@FindBy(xpath="//h1[text()='Dashboard']") static WebElement dashboard;
@FindBy(id="welcome") static WebElement welcome;
@FindBy(linkText="Logout") static WebElement signout;
public void init()
{
PageFactory.initElements(driver,this);
}
public void openurl()
{
driver.get(prop.getProperty("url"));
}
public void validate_loginpage()
{
String title=driver.getTitle();
if(title.matches("OrangeHRM"))
{
testlog=ext.createTest("LoginPage");
testlog.log(Status.PASS, "login page is displayed");
takescreenshot("loginpage.png");
}
else
{
testlog=ext.createTest("LoginPage");
testlog.log(Status.FAIL, "login page NOT displayed");
takescreenshot("loginpage.png");
}
}
public void validlogin()
{
username.sendKeys(prop.getProperty("username"));
password.sendKeys(prop.getProperty("password"));
signin.click();
try {Thread.sleep(5000);}catch(Exception e) {}
}
public void validatedashboardpage()
{
if(dashboard.isDisplayed())
{
testlog=ext.createTest("DashBoardPage");
testlog.log(Status.PASS, "DashBoardPage is displayed");
takescreenshot("dashboard.png");
}
else
{
testlog=ext.createTest("DashBoardPage");
testlog.log(Status.FAIL, "DashBoardPage NOT displayed");
takescreenshot("dashboard.png");
}
}
public void logout()
{
try
{
if(welcome.isDisplayed())
{
welcome.click();
try {Thread.sleep(2000);}catch(Exception e) {}
signout.click();
try {Thread.sleep(3000);}catch(Exception e) {}
}
}catch(Exception e) {System.out.println("Not is dashboard page to logout");}
}
public void invalidlogin(String userid,String pwd)
{
username.sendKeys(userid);
password.sendKeys(pwd);
signin.click();
try {Thread.sleep(2000);}catch(Exception e) {}
if(errmsg.isDisplayed())
{
testlog=ext.createTest("InvalidLogin");
testlog.log(Status.INFO, "Login is Failed");
takescreenshot("loginfail.png");
}
else
{
validatedashboardpage();
logout();
}
}
public void errorMessage() {
String message = errmsg.getText();
System.out.println(message);
}
}
|
/**
*
*/
package solo;
import it.unimi.dsi.fastutil.doubles.Double2ObjectSortedMap;
import it.unimi.dsi.fastutil.doubles.DoubleSortedSet;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectArrays;
import java.awt.geom.AffineTransform;
import java.util.Arrays;
import com.graphbuilder.geom.Geom;
/**
* @author kokichi3000
*
*/
public class CurveCoordinate {
Double2ObjectSortedMap<Vector2D> lMap;
private static final double ANGLEACCURACY =100.0d;
double[] allLengths;
Vector2D[] allPoints;
double width;
int len;
public CurveCoordinate() {
// TODO Auto-generated constructor stub
}
CurveCoordinate(Vector2D[] allPoints,double[] allLengths){
this.allPoints = allPoints;
this.allLengths = allLengths;
len = allPoints.length;
}
/**
* Copy Constructor
*
* @param curveCoordinate a <code>CurveCoordinate</code> object
*/
public CurveCoordinate(CurveCoordinate curveCoordinate)
{
this.lMap = curveCoordinate.lMap;
this.len = curveCoordinate.len;
this.allLengths = curveCoordinate.allLengths;
this.allPoints = curveCoordinate.allPoints;
// if (lMap!=null) {
// len = lMap.size();
// allLengths = new double[len];
//// allLengths = lMap.keySet().toDoubleArray();
//// lMap.values().toArray(allPoints);
// DoubleSortedSet ds = lMap.keySet();
// allPoints = new Vector2D[len];
// int i=0;
// for (double d:ds){
// allLengths[i] = d;
// allPoints[i++] = lMap.get(d);
// }
// }
this.width = curveCoordinate.width;
}
public CurveCoordinate( Double2ObjectSortedMap<Vector2D> map, double width) {
lMap = map;
if (lMap!=null) {
len = lMap.size();
DoubleSortedSet ds = lMap.keySet();
allLengths = new double[len];
allPoints = new Vector2D[len];
int i=0;
for (double d:ds){
allLengths[i] = d;
allPoints[i++] = lMap.get(d);
}
}
this.width = width;
}
public double lengthToPoint(Vector2D p){
if (p==null) return -1;
int i=0;
int j = 0;
int len = allPoints.length;
double min = Double.MAX_VALUE;
for (i=0;i<len;++i){
double dist = allPoints[i].distance(p);
if (dist<min){
min = dist;
j = i;
}
}
return allLengths[j];
}
public int insertionPos(double len){
int index = Arrays.binarySearch(allLengths, len);
if (index>=0) return index;
return -index-1;
}
public double lengthToPointAtHeight(double h){
if (h<=0) return 0;
int i=0;
int len = allPoints.length;
for (i=0;i<len;++i)
if (allPoints[i].y>=h)
break;
if (allPoints[i].y==h){
return allLengths[i];
}
Vector2D t = allPoints[i].minus(allPoints[i-1]).normalized();
h -= allPoints[i-1].y;
return allLengths[i-1]+allPoints[i-1].distance(t.times(h/t.y));
}
public Vector2D locatePointAtHeight(double h){
if (h<0) return null;
int i=0;
int len = allPoints.length;
for (i=0;i<len;++i)
if (allPoints[i].y>=h)
break;
if (allPoints[i].y==h){
return allPoints[i];
}
if (i==0) return allPoints[0];
Vector2D t = allPoints[i].minus(allPoints[i-1]).normalized();
h -= allPoints[i-1].y;
return allPoints[i-1].plus(t.times(h/t.y));
}
public Vector2D locatePointAtDistance(double distance){
if (len<2) return null;
Vector2D o = new Vector2D(0,0);
Vector2D[] allPoints = this.allPoints;
if (allPoints[0].distance(o)>distance)
return null;
int i=0;
for (i=len-1;i>=0;--i){
if (allPoints[i].distance(o)==distance)
return allPoints[i];
else if (allPoints[i].distance(o)<distance)
break;
}
double l = allPoints[i].distance(o);
Vector2D p = allPoints[i];
Vector2D t = (i>=len-1 && len>=2) ? p.minus(allPoints[i-1]).normalized() : allPoints[i+1].minus(p).normalized();
Vector2D dummy = p.plus(t.times(Math.abs(distance-l)));
double[] rs = Geom.getLineCircleIntersection(p.x, p.y, dummy.x, dummy.y, o.x, o.y, distance);
if (rs.length==2) return new Vector2D(rs[0],rs[1]);
Vector2D p1 = new Vector2D(rs[0],rs[1]);
if (p1.minus(p).dot(t)>=0) return p1;
return new Vector2D(rs[2],rs[3]);
}
public static Vector2D locatePointAtLength(double length,Vector2D[] allPoints,double[] allLengths){
if (allPoints==null || allLengths==null) return null;
int index = Arrays.binarySearch(allLengths, length);
int len = allLengths.length;
if (len<2) return null;
if (index>0)
return allPoints[index];
if (index<0) index = -index+1;
Vector2D t = null;
Vector2D p = null;
if (index>=len){
t = allPoints[len-1].minus(allPoints[len-2]).normalized();
p = allPoints[len-1];
} else {
t = allPoints[index].minus(allPoints[index-1]).normalized();
p = allPoints[index-1];
}
return p.plus(t.times(length-allLengths[index-1]));
}
//return the coordinates of the point at distance = length from the origin in the curve axis
public Vector2D[] locatePointAtLength(double length,Vector2D p,Vector2D t,Vector2D n){
if (p==null || allLengths==null)
return null;
int index = Arrays.binarySearch(allLengths, length);
if (index>0){
p.copy(allPoints[index]);
if (index<len-1){
if (t!=null) t.copy(allPoints[index+1].minus(p).normalized());
} else {
if (t!=null) t.copy(p.minus(allPoints[index-1]).normalized());
}
if (n!=null) n.copy(t.orthogonal());
return ObjectArrays.copy(allPoints, index, len-index);
}
if (index<0) index = -index;
if (index>=len){
if (len>0) p.copy(allPoints[len-1]);
if (t ==null) t = new Vector2D(0,0);
t.copy(p.minus(allPoints[len-2]).normalized());
p.copy(p.plus(t.times(length-allLengths[len-1])));
return null;
}
p.copy(allPoints[index]);
if (index<len-1){
if (t!=null)
t.copy(allPoints[index+1].minus(p).normalized());
else t = allPoints[index+1].minus(p).normalized();
} else {
if (t!=null)
t.copy(p.minus(allPoints[index-1]).normalized());
else t = p.minus(allPoints[index-1]).normalized();
}
if (n!=null) n.copy(t.orthogonal());
p.copy(p.plus(t.times(length-allLengths[index])));
Vector2D[] rs = new Vector2D[len-index];
rs[0]=p;
for (int i=1;i<rs.length;++i){
rs[i] = allPoints[index+i];
}
return rs;
}
public static Vector2D intersects(Vector2D x,Vector2D y,Vector2D[] v,ObjectArrayList<Vector2D> theRest){
if (v==null)
return null;
int len = v.length;
double[] rs = new double[3];
Vector2D point = null;
int i=0;
for (i=0;i<len-1;++i){
if (Geom.getLineSegIntersection(x.x, x.y, y.x, y.y, v[i].x, v[i].y, v[i+1].x, v[i+1].y,rs) == Geom.INTERSECT){
point = new Vector2D(rs[0],rs[1]);
break;
}
}
if (point==null || theRest==null) return point;
theRest.add(point);
for (int j=i+1;j<len;++j)
theRest.add(new Vector2D(v[j].x,v[j].y));
return point;
}
public static Vector2D[] convertToCarPerspective(Vector2D[] v,Vector2D t){
if (v==null) return null;
double angle = Vector2D.angle(new Vector2D(0,1), t);
AffineTransform at =new AffineTransform();
at.rotate(angle);
at.translate(-v[0].x, -v[0].y);
Vector2D[] rs = v.clone();
at.transform(v, 0, rs, 0, v.length);
return rs;
}
public static Vector2D[] convertToCarPerspective(ObjectArrayList<Vector2D> v,Vector2D t){
if (v==null) return null;
Vector2D[] vv = new Vector2D[v.size()];
vv = v.toArray(vv);
double angle = Vector2D.angle(new Vector2D(0,1), t);
AffineTransform at =new AffineTransform();
at.rotate(angle);
Vector2D p = v.get(0);
at.translate(-p.x, -p.y);
Vector2D[] rs = new Vector2D[v.size()];
ObjectArrays.fill(rs, new Vector2D(0,0));
at.transform(vv, 0, rs, 0, v.size());
return rs;
}
public static AffineTransform getTransformMatrixToCarPerspective(ObjectArrayList<Vector2D> v,Vector2D t){
if (v==null) return null;
double angle = Vector2D.angle(new Vector2D(0,1), t);
AffineTransform at =new AffineTransform();
at.rotate(angle);
Vector2D p = v.get(0);
at.translate(-p.x, -p.y);
return at;
}
public static AffineTransform getTransformMatrixToCarPerspective(Vector2D[] v,Vector2D p,Vector2D t){
if (v==null) return null;
// System.out.println(t);
// t = v[1].minus(v[0]);
AffineTransform at =new AffineTransform();
if (Math.abs(t.y)>0.98) {
at.translate(-p.x, -p.y);
return at;
}
double angle = -Vector2D.angle(new Vector2D(0,1),t);
angle=Math.round(angle*ANGLEACCURACY)/ANGLEACCURACY;
System.out.println(angle+" "+t);
if (angle!=0)
System.out.println(new ObjectArrayList<Vector2D>(v));
at.rotate(angle);
at.translate(-p.x, -p.y);
return at;
}
/**
* @return the x
*/
/**
* @return the lMap
*/
public Double2ObjectSortedMap<Vector2D> getLMap() {
return lMap;
}
/**
* @param map the lMap to set
*/
public void setLMap(Double2ObjectSortedMap<Vector2D> map) {
lMap = map;
}
/**
* @return the width
*/
public double getWidth() {
return width;
}
/**
* @param width the width to set
*/
public void setWidth(double width) {
this.width = width;
}
/**
* Constructs a <code>String</code> with all attributes
* in name = value format.
*
* @return a <code>String</code> representation
* of this object.
*/
@Override
public String toString()
{
final String TAB = " ";
String retValue = "";
retValue = "CurveCoordinate ( "
+ super.toString() + TAB
+ "lMap = " + this.lMap + TAB
+ "width = " + this.width + TAB
+ " )";
return retValue;
}
}
|
package com.neusoft.issure.util.lang;
/**
* @Title: StrUtil.java
* @Description: (用一句话描述该文件做什么)
* @author: jetty
* @date: 2019/3/11 11:59
* @version V1.0
*/
public class StrUtil {
private static final char CHAR_UPPER_A = 'A';
private static final char CHAR_UPPER_Z = 'Z';
private static final char CHAR_LOWER_A = 'a';
private static final char CHAR_LOWER_Z = 'z';
protected StrUtil() {
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
public static boolean isEmpty(String str) {
return str == null || "".equals(str);
}
public static String replaceOnce(String text, String searchString, String replacement) {
return replace(text, searchString, replacement, 1);
}
public static String replace(String text, String searchString, String replacement) {
return replace(text, searchString, replacement, -1);
}
public static String replace(String text, String searchString, String replacement, int max) {
if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
return text;
}
int start = 0;
int end = text.indexOf(searchString, start);
if (end == -1) {
return text;
}
int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = increase >= 0 ? increase : 0;
increase *= max >= 0 ? max <= 64 ? max : 64 : 16;
StringBuilder buf = new StringBuilder(text.length() + increase);
do {
if (end == -1) {
break;
}
buf.append(text, start, end).append(replacement);
start = end + replLength;
if (--max == 0) {
break;
}
end = text.indexOf(searchString, start);
} while (true);
buf.append(text.substring(start));
return buf.toString();
}
public static String substring(String text, int beginIndex) {
if (text == null) {
return null;
}
return text.substring(beginIndex);
}
public static String substring(String text, int beginIndex, int endIndex) {
if (text == null) {
return null;
}
return text.substring(beginIndex, endIndex);
}
public static String lastSubstring(String text, int lastBeginIndex) {
if (text == null) {
return null;
}
return text.substring(text.length() - lastBeginIndex);
}
public static String firstCharToLowerCase(String str) {
char firstChar = str.charAt(0);
if (firstChar >= CHAR_UPPER_A && firstChar <= CHAR_UPPER_Z) {
char[] arr = str.toCharArray();
arr[0] += (CHAR_LOWER_A - CHAR_UPPER_A);
return new String(arr);
}
return str;
}
public static String firstCharToUpperCase(String str) {
char firstChar = str.charAt(0);
if (firstChar >= CHAR_LOWER_A && firstChar <= CHAR_LOWER_Z) {
char[] arr = str.toCharArray();
arr[0] -= (CHAR_LOWER_A - CHAR_UPPER_A);
return new String(arr);
}
return str;
}
}
|
package scrap.heap.refactor;
import party.birthday.order.ballon.builder.Ballon;
import party.birthday.order.ballon.model.BallonColor;
import party.birthday.order.ballon.model.BallonMaterial;
import party.birthday.order.cake.builder.Cake;
import party.birthday.order.cake.model.CakeColor;
import party.birthday.order.cake.model.CakeFlavor;
import party.birthday.order.cake.model.CakeFrostingFlavor;
import party.birthday.order.cake.model.CakeShape;
import party.birthday.order.cake.model.CakeSize;
import party.birthday.order.request.BallonRequest;
import party.birthday.order.request.CakeRequest;
import party.birthday.order.request.PartyRequest;
public class App {
public String getGreeting() {
return "Hello world.";
}
public static void main(String[] args) {
// Place birthday party orders
order(new PartyRequest(new BallonRequest(BallonColor.Red, BallonMaterial.Mylar, 4),
new CakeRequest(CakeFlavor.Chocolate, CakeFrostingFlavor.Chocolate, CakeShape.Circle, CakeSize.Large,
CakeColor.Brown)));
order(new PartyRequest(new BallonRequest(BallonColor.Blue, BallonMaterial.latex, 7),
new CakeRequest(CakeFlavor.Vanilla, CakeFrostingFlavor.Chocolate, CakeShape.Square, CakeSize.Medium,
CakeColor.Brown)));
order(new PartyRequest(new BallonRequest(BallonColor.Red, BallonMaterial.Mylar, 4),
new CakeRequest(CakeFlavor.Chocolate, CakeFrostingFlavor.Chocolate, CakeShape.Circle, CakeSize.Large,
CakeColor.Brown)));
}
private static void order(final PartyRequest partyRequest) {
orderBalloons(partyRequest.getBallonRequest());
orderCake(partyRequest.getCakeRequest());
}
private static void orderBalloons(final BallonRequest request) {
// for the purposes of this exercise, pretend this method works and adds
// balloons to the order
Ballon ballon = Ballon.newBuilder(request.getNumber()).withColor(BallonColor.Blue)
.withMaterial(BallonMaterial.latex).build();
System.out.println("Balloons ordered; " + ballon.getColor().name() + ", " + ballon.getMaterial().name() + ", "
+ ballon.getCount());
}
private static void orderCake(final CakeRequest request) {
// for the purposes of this exercise, pretend that this method adds a cake to
// the order
Cake cake = Cake.newBuilder(CakeFlavor.Chocolate).withFrostingFlavor(CakeFrostingFlavor.Vanilla)
.withShape(CakeShape.Circle).ofSize(CakeSize.Medium).withColor(CakeColor.Brown).build();
System.out.println("cake ordered; " + cake.getFlavor().name() + ", " + cake.getFrostingFlavor().name() + ", "
+ cake.getShape().name() + ", " + cake.getSize().name() + ", " + cake.getColor().name());
}
}
|
package com.sbs.sbsattend;
import java.util.List;
import com.sbs.sbsattend.model.Leave;
import com.sbs.sbsattend.model.Logic;
import com.sbs.tool.LayOut;
import com.sbs.tool.MySignal;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ReivewLeaveActivity extends Activity {
private ListView lv;
private List<Leave> les;
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.reviewleave);
bt = (Button) findViewById(R.id.leavecommit);
lv = (ListView) findViewById(R.id.lv);
les = Logic.query_leavetime();
if(les == null)
{
bt.setText("无审批信息,点此退出");
}
MyAdapter mAdapter = new MyAdapter(this);// 得到一个MyAdapter对象
lv.setAdapter(mAdapter); //为ListView绑定Adapter
LayOut.setListViewHeightBasedOnChildren(lv);
}
public void commit(View v)
{
int count = 0;
if(les == null)
{
Toast.makeText(ReivewLeaveActivity.this,"无可审批信息,退出!", Toast.LENGTH_LONG).show();
this.finish();
return;
}
for(Leave l : les)
{
count = count + Logic.approve_leavetime(l);
}
if(count == les.size())
{
Toast.makeText(ReivewLeaveActivity.this,"批量提交成功!", Toast.LENGTH_LONG).show();
}else
{
StringBuilder temp = new StringBuilder();
temp.append(les.size()-count);
Toast.makeText(ReivewLeaveActivity.this,"本次操作有"+ temp.toString() +"行提交失败", Toast.LENGTH_LONG).show();
}
finish();
}
/*
* 新建一个类继承BaseAdapter,实现视图与数据的绑定
*/
private class MyAdapter extends BaseAdapter
{
private LayoutInflater mInflater;// 得到一个LayoutInfalter对象用来导入布局
/*构造函数*/
public MyAdapter(Context context) {
this.mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
if(les != null)
return les.size();// 返回数组的长度;
else
return 0;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.leaveitem, null);
holder = new ViewHolder();
/* 得到各个控件的对象 */
holder.name = (TextView) convertView.findViewById(R.id.staff_name);
holder.start = (TextView) convertView.findViewById(R.id.starttime);
holder.end = (TextView) convertView.findViewById(R.id.endtime);
holder.res = (TextView) convertView.findViewById(R.id.reason);
holder.cb = (CheckBox) convertView.findViewById(R.id.ifagree);
convertView.setTag(holder);// 绑定ViewHolder对象
}else {
holder = (ViewHolder) convertView.getTag();// 取出ViewHolder对象
}
/* 设置TextView显示的内容,即我们存放在动态数组中的数据 */
holder.name.setText(les.get(position).getName());
holder.start.setText(les.get(position).getStarttime().substring(0, 10)+" "+ les.get(position).getOriginweek()+ "\n"+les.get(position).getOriginshift());
holder.end.setText(les.get(position).getEndtime().substring(0, 10)+" " + les.get(position).getCurrentweek()+ "\n" +les.get(position).getCurrentshift());
holder.res.setText(les.get(position).getReason());
//默认审批不通过
les.get(position).setApprove(MySignal.NOTAPPROVE);
holder.cb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(holder.cb.isChecked())
{
les.get(position).setApprove(MySignal.APPROVE); //如果被选中,则approve置为4
}
else
{
les.get(position).setApprove(MySignal.NOTAPPROVE); //如果未中,则approve置为5
}
}
});
int[] colors = { Color.WHITE, Color.rgb(219, 238, 244) };//RGB颜色
convertView.setBackgroundColor(colors[position % 2]);// 每隔item之间颜色不同
return convertView;
}
}
/* 存放控件 */
public final class ViewHolder {
public TextView name;
public TextView start;
public TextView end;
public TextView res;
public CheckBox cb;
}
}
|
/*
* work_wx
* wuhen 2020/2/4.
* Copyright (c) 2020 jianfengwuhen@126.com All Rights Reserved.
*/
package com.work.wx.controller.modle.subChatItem;
import com.work.wx.controller.modle.BaseModel;
public class ChatModelNews extends BaseModel {
private String url; // 图文消息点击跳转地址。String类型
private String picurl; // 图文消息配图的url。String类型
private String title; // 图文消息标题。String类型
private String description;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPicurl() {
return picurl;
}
public void setPicurl(String picurl) {
this.picurl = picurl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
package com.li.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class ClientChannel {
public static void main(String[] args) {
try {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.bind(new InetSocketAddress("180.73.237.73", 8761));
ByteBuffer allocate = ByteBuffer.allocate(512);
allocate.put("123".getBytes("utf-8"));
allocate.flip();
while (allocate.hasRemaining()) {
socketChannel.write(allocate);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
|
package br.pucrs.arq.model;
import lombok.Data;
import org.springframework.data.annotation.Id;
/**
* by Thiago Carreira A. Nascimento
**/
@Data
public class Carta extends Midia {
@Id
private Integer id;
public Carta(){super();}
}
|
/*
* Copyright 2002-2018 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.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Profiles;
/**
* Indicates that a component is eligible for registration when one or more
* {@linkplain #value specified profiles} are active.
*
* <p>A <em>profile</em> is a named logical grouping that may be activated
* programmatically via {@link ConfigurableEnvironment#setActiveProfiles} or declaratively
* by setting the {@link AbstractEnvironment#ACTIVE_PROFILES_PROPERTY_NAME
* spring.profiles.active} property as a JVM system property, as an
* environment variable, or as a Servlet context parameter in {@code web.xml}
* for web applications. Profiles may also be activated declaratively in
* integration tests via the {@code @ActiveProfiles} annotation.
*
* <p>The {@code @Profile} annotation may be used in any of the following ways:
* <ul>
* <li>as a type-level annotation on any class directly or indirectly annotated with
* {@code @Component}, including {@link Configuration @Configuration} classes</li>
* <li>as a meta-annotation, for the purpose of composing custom stereotype annotations</li>
* <li>as a method-level annotation on any {@link Bean @Bean} method</li>
* </ul>
*
* <p>If a {@code @Configuration} class is marked with {@code @Profile}, all of the
* {@code @Bean} methods and {@link Import @Import} annotations associated with that class
* will be bypassed unless one or more of the specified profiles are active. A profile
* string may contain a simple profile name (for example {@code "p1"}) or a profile
* expression. A profile expression allows for more complicated profile logic to be
* expressed, for example {@code "p1 & p2"}. See {@link Profiles#of(String...)} for more
* details about supported formats.
*
* <p>This is analogous to the behavior in Spring XML: if the {@code profile} attribute of
* the {@code beans} element is supplied e.g., {@code <beans profile="p1,p2">}, the
* {@code beans} element will not be parsed unless at least profile 'p1' or 'p2' has been
* activated. Likewise, if a {@code @Component} or {@code @Configuration} class is marked
* with {@code @Profile({"p1", "p2"})}, that class will not be registered or processed unless
* at least profile 'p1' or 'p2' has been activated.
*
* <p>If a given profile is prefixed with the NOT operator ({@code !}), the annotated
* component will be registered if the profile is <em>not</em> active — for example,
* given {@code @Profile({"p1", "!p2"})}, registration will occur if profile 'p1' is active
* or if profile 'p2' is <em>not</em> active.
*
* <p>If the {@code @Profile} annotation is omitted, registration will occur regardless
* of which (if any) profiles are active.
*
* <p><b>NOTE:</b> With {@code @Profile} on {@code @Bean} methods, a special scenario may
* apply: In the case of overloaded {@code @Bean} methods of the same Java method name
* (analogous to constructor overloading), an {@code @Profile} condition needs to be
* consistently declared on all overloaded methods. If the conditions are inconsistent,
* only the condition on the first declaration among the overloaded methods will matter.
* {@code @Profile} can therefore not be used to select an overloaded method with a
* particular argument signature over another; resolution between all factory methods
* for the same bean follows Spring's constructor resolution algorithm at creation time.
* <b>Use distinct Java method names pointing to the same {@link Bean#name bean name}
* if you'd like to define alternative beans with different profile conditions</b>;
* see {@code ProfileDatabaseConfig} in {@link Configuration @Configuration}'s javadoc.
*
* <p>When defining Spring beans via XML, the {@code "profile"} attribute of the
* {@code <beans>} element may be used. See the documentation in the
* {@code spring-beans} XSD (version 3.1 or greater) for details.
*
* @author Chris Beams
* @author Phillip Webb
* @author Sam Brannen
* @since 3.1
* @see ConfigurableEnvironment#setActiveProfiles
* @see ConfigurableEnvironment#setDefaultProfiles
* @see AbstractEnvironment#ACTIVE_PROFILES_PROPERTY_NAME
* @see AbstractEnvironment#DEFAULT_PROFILES_PROPERTY_NAME
* @see Conditional
* @see org.springframework.test.context.ActiveProfiles
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ProfileCondition.class)
public @interface Profile {
/**
* The set of profiles for which the annotated component should be registered.
*/
String[] value();
}
|
/*
* 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 tema02;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.*;
/**
*
* @author andre
*/
public class FereastraCautare extends JDialog implements ActionListener{
private String numeProd;
private String categorieProd;
private String taraProd;
private double pretProd;
private Gestiune g;
private final Vector<String> tari;
private final Vector<String> categorii;
private final JLabel numeLabel;
private final JLabel categLabel;
private final JLabel taraLabel;
private final JLabel pretLabel;
private final JTextField numeField;
private final JComboBox categField;
private final JComboBox taraField;
private final JTextField pretField;
private final ArrayList<Produs> listaProduse;
private boolean flag;
public FereastraCautare(Frame parinte, ArrayList<Produs> produse){
super(parinte, "Cautare Produs", true);
listaProduse = produse;
tari = new Vector<>();
categorii = new Vector<>();
for(Iterator itr = produse.iterator(); itr.hasNext();){
Produs aux = (Produs) itr.next();
if(!tari.contains(aux.getTaraOrigine()))
tari.add(aux.getTaraOrigine());
if(!categorii.contains(aux.getCategorie()))
categorii.add(aux.getCategorie());
}
JPanel panel1 = new JPanel(new FlowLayout());
JPanel panel2 = new JPanel(new FlowLayout());
JPanel panel3 = new JPanel(new FlowLayout());
JPanel panel4 = new JPanel(new FlowLayout());
JPanel panel5 = new JPanel(new FlowLayout());
numeLabel = new JLabel("Nume:");
categLabel = new JLabel("Categ:");
taraLabel = new JLabel("Tara:");
pretLabel = new JLabel("Pret:");
numeField = new JTextField(10);
categField = new JComboBox(categorii);
taraField = new JComboBox(tari);
pretField = new JTextField(10);
JButton cautare = new JButton("Cautare");
JButton cancel = new JButton("Cancel");
cautare.addActionListener(this);
cancel.addActionListener(this);
panel1.add(numeLabel);
panel1.add(numeField);
panel2.add(categLabel);
panel2.add(categField);
panel3.add(taraLabel);
panel3.add(taraField);
panel4.add(pretLabel);
panel4.add(pretField);
panel5.add(cautare);
panel5.add(cancel);
setLayout(new FlowLayout());
getContentPane().add(panel1);
getContentPane().add(panel2);
getContentPane().add(panel3);
getContentPane().add(panel4);
getContentPane().add(panel5);
getRootPane().setDefaultButton(cautare);
setSize(280,210);
setResizable(false);
setLocationRelativeTo(parinte);
}
@Override
public void actionPerformed(ActionEvent e){
String nume = e.getActionCommand();
if(nume.equals("Cautare")){
if(numeField.getText().isEmpty() || pretField.getText().isEmpty()){
JOptionPane.showMessageDialog(null,
"Nu au fost completate toate campurile!","Atentie", JOptionPane.WARNING_MESSAGE);
}
else{
numeProd = numeField.getText();
categorieProd = categField.getSelectedItem().toString();
taraProd = taraField.getSelectedItem().toString();
pretProd = Double.parseDouble(pretField.getText());
for(Iterator itr = listaProduse.iterator();itr.hasNext();){
Produs p = (Produs) itr.next();
if(p.getDenumire().equals(numeProd) && p.getCategorie().equals(categorieProd)
&& p.getTaraOrigine().equals(taraProd) && p.getPret() == pretProd)
flag = true;
}
if(flag){
JOptionPane.showMessageDialog(null,
"Produsul a fost gasit!","Succes", JOptionPane.INFORMATION_MESSAGE);
dispose();
}else{
JOptionPane.showMessageDialog(null,
"Produsul nu a fost gasit!","Warning", JOptionPane.WARNING_MESSAGE);
dispose();
}
}
} else if(nume.equals("Cancel")){
dispose();
}
}
}
|
package com.grupo.proyecto_pet.business.service;
import com.grupo.proyecto_pet.persistence.entity.Rol;
import com.grupo.proyecto_pet.persistence.entity.Usuario;
import com.grupo.proyecto_pet.persistence.repository.UsuarioRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Franco on 07/29/2017.
*/
@Service
public class CustomUserDetailsService implements UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
@Autowired
private UsuarioRepository usuarioRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
logger.info("Intentando login con usuario: {}...", email);
Usuario user = usuarioRepository.findByEmail(email);
if (user == null) {
logger.error("Usuario no encontrado por mail {}", email);
throw new UsernameNotFoundException("Credenciales incorrectas");
}
user.setRoles(new ArrayList<>());
user.getRoles().add(new Rol("USUARIO"));
List<SimpleGrantedAuthority> roles = user.getRoles().stream().map(rol -> new SimpleGrantedAuthority(rol.getNombre())).collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), roles);
}
} |
package com.javarush.test.level08.lesson11.bonus01;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/* Номер месяца
Программа вводит с клавиатуры имя месяца и выводит его номер на экран в виде: «May is 5 month».
Используйте коллекции.
*/
public class Solution
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String month = reader.readLine();
switch (month) {
case "January" :
System.out.println("January is 1 month");
break;
case "February" :
System.out.println("February is 2 month");
break;
case "March" :
System.out.println("March is 3 month");
break;
case "April" :
System.out.println("April is 4 month");
break;
case "May" :
System.out.println("May is 5 month");
break;
case "June" :
System.out.println("June is 6 month");
break;
case "July" :
System.out.println("July is 7 month");
break;
case "Augest" :
System.out.println("August is 8 month");
break;
case "September" :
System.out.println("September is 9 month");
break;
case "October" :
System.out.println("October is 10 month");
break;
case "November" :
System.out.println("November is 11 month");
break;
case "December" :
System.out.println("December is 12 month");
break;
}
//напишите тут ваш код
}
}
|
package org.apache.hadoop.hdfs;
import java.io.IOException;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.UnresolvedPathException;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo;
import org.apache.hadoop.hdfs.server.blockmanagement.InvalidatedBlock;
import org.apache.hadoop.hdfs.server.blockmanagement.PendingBlockInfo;
import org.apache.hadoop.hdfs.server.blockmanagement.ReplicaUnderConstruction;
import org.apache.hadoop.hdfs.server.blockmanagement.UnderReplicatedBlock;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils;
import org.apache.hadoop.hdfs.server.namenode.INode;
import org.apache.hadoop.hdfs.server.namenode.lock.INodeUtil;
import org.apache.hadoop.hdfs.server.namenode.lock.TransactionLockAcquirer;
import org.apache.hadoop.hdfs.server.namenode.lock.TransactionLockManager;
import org.apache.hadoop.hdfs.server.namenode.persistance.EntityManager;
import org.apache.hadoop.hdfs.server.namenode.persistance.PersistanceException;
import org.apache.hadoop.hdfs.server.namenode.persistance.storage.StorageException;
import org.apache.hadoop.hdfs.server.protocol.DatanodeProtocol;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.hdfs.server.protocol.ReceivedDeletedBlockInfo;
import org.apache.hadoop.io.EnumSetWritable;
import org.apache.hadoop.security.UserGroupInformation;
import org.junit.Test;
/**
*
* @author Hooman <hooman@sics.se>
*/
public class TestTransactionalOperations {
static final int blockSize = 8192;
static final int numBlocks = 2;
static final int bufferSize = 4096;
private static final long SHORT_LEASE_PERIOD = 300L;
private static final long LONG_LEASE_PERIOD = 3600000L;
private final int seed = 28;
static private String fakeUsername = "fakeUser1";
static private String fakeGroup = "supergroup";
@Test
public void testMkdirs() throws IOException {
Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();
try {
DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();
Path exPath = new Path("/e1/e2");
dfs.mkdirs(exPath);
assert dfs.exists(exPath) : String.format("The path %s is not created.", exPath.toString());
Path newPath = new Path(exPath.toString() + "/n3/n4");
dfs.mkdirs(newPath);
assert dfs.exists(newPath) : String.format("The path %s is not created.", newPath.toString());
} finally {
cluster.shutdown();
}
}
/**
* Tries different possible scenarios on startFile operation.
* @throws IOException
* @throws InterruptedException
*/
@Test
public void testStartFile() throws IOException, InterruptedException {
Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();
try {
DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();
DFSClient client = dfs.getDefaultDFSClient();
Path exPath = new Path("/e1/e2");
// Creates a path
dfs.mkdirs(exPath, FsPermission.getDefault());
assert dfs.exists(exPath) : String.format("Path %s does not exist.", exPath.toString());
//Creates a file on an existing path
Path f1 = new Path(exPath.toString() + "/f1");
FSDataOutputStream stm = dfs.create(f1, true, bufferSize, (short) 2, blockSize);
assert dfs.exists(f1) : String.format("Path %s does not exist.", f1.toString());
stm.close();
//Creates a file on a non-existing path
Path f2 = new Path(exPath.toString() + "/e3/e4/f2");
stm = dfs.create(f2, true, bufferSize, (short) 2, blockSize);
assert dfs.exists(f2) : String.format("Path %s does not exist.", f2.toString());
// This writes some blocks to the file and removes the last block in order to keep the lease on the file plus
// to have all the blocks as complete blocks.
writeFile(stm, numBlocks * blockSize);
stm.hflush();
// Scenario "finalizeInodeFileUnderConstruction": Here we try to abandon the last block in order to have only complete blocks
LocatedBlocks blocks = client.getNamenode().getBlockLocations(f2.toString(), 0, numBlocks * blockSize);
ExtendedBlock lastBlock = blocks.getLastLocatedBlock().getBlock();
client.getNamenode().abandonBlock(lastBlock, f2.toString(), client.getClientName());
waitLeaseRecovery(cluster, SHORT_LEASE_PERIOD, LONG_LEASE_PERIOD);
DistributedFileSystem dfs2 = (DistributedFileSystem) getFSAsAnotherUser(conf, fakeUsername, fakeGroup);
// rewrite f2
FSDataOutputStream stm2 = dfs2.create(f2, true, bufferSize, (short) 2, blockSize);
assert dfs2.exists(f2) : String.format("Path %s does not exist.", f2.toString());
//Scenario4: This time the file is under-cosntruction but the soft-lease of the holder expires and another
//client tries to overwrite the file. Since the last block is under-construction, This makes the namennode to runs
//block-recovery for this file in place of making the file a complete file.
writeFile(stm2, numBlocks * blockSize);
stm2.hflush();
waitLeaseRecovery(cluster, SHORT_LEASE_PERIOD, LONG_LEASE_PERIOD);
try {
dfs.create(f2, true, bufferSize, (short) 2, blockSize);
assert false : "It must through RecoveryInProgressException.";
} catch (IOException e) {
// Good
}
} finally {
cluster.shutdown();
}
}
@Test
public void testCompleteFile() throws IOException {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1");
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
try {
// Here we create a file with 3 replications while we have 2 datanode and min replication is 1.
// This shouldn't make any problem. But this makes the namenode to add the block to the
// under-replicated blocks list.
DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();
Path f1 = new Path("/ed1/ed2/testCompleteFile");
dfs.mkdirs(f1.getParent(), FsPermission.getDefault());
assert dfs.exists(f1.getParent()) : String.format("The path %s does not exist.", f1.getParent().toString());
FSDataOutputStream stm = dfs.create(f1, false, bufferSize, (short) 3, blockSize);
writeFile(stm, blockSize);
stm.close();
} finally {
cluster.shutdown();
}
}
@Test
public void testBlockReceivedAndDeleted() throws IOException {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1");
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
try {
DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();
NamenodeProtocols namenode = cluster.getNameNodeRpc();
DatanodeProtocol dnp = cluster.getNameNodeRpc();
List<DataNode> dns = cluster.getDataNodes();
Path f1 = new Path("/ed1/ed2/f1");
Path f2 = new Path("/ed1/ed2/f2");
dfs.mkdirs(f1.getParent(), FsPermission.getDefault());
assert dfs.exists(f1.getParent()) : String.format("The path %s does not exist.", f1.getParent().toString());
// Create two files, for one we report both replicas removed and for the other one we report one replica removed
// so we expect for the first file the blockinfo to be removed and for the latter the block-info be added to under-replicated blocks.
DFSClient client = dfs.getDefaultDFSClient();
namenode.create(f1.toString(), FsPermission.getDefault(), client.getClientName(),
new EnumSetWritable<CreateFlag>(EnumSet.of(CreateFlag.CREATE)), true, (short) 2, blockSize);
namenode.create(f2.toString(), FsPermission.getDefault(), client.getClientName(),
new EnumSetWritable<CreateFlag>(EnumSet.of(CreateFlag.CREATE)), true, (short) 2, blockSize);
LocatedBlock b1 = namenode.addBlock(f1.toString(), client.getClientName(), null,
new DatanodeInfo[]{new DatanodeInfo(dns.get(1).getDatanodeId())});
String bpId = cluster.getNamesystem().getBlockPoolId();
dnp.blockReceivedAndDeleted(DataNodeTestUtils.getDNRegistrationForBP(dns.get(0), bpId), bpId,
new ReceivedDeletedBlockInfo[]{new ReceivedDeletedBlockInfo(b1.getBlock().getLocalBlock(), "")});
LocatedBlock b2 = namenode.addBlock(f1.toString(), client.getClientName(), b1.getBlock(),
new DatanodeInfo[]{new DatanodeInfo(dns.get(1).getDatanodeId())});
dnp.blockReceivedAndDeleted(DataNodeTestUtils.getDNRegistrationForBP(dns.get(0), bpId), bpId,
new ReceivedDeletedBlockInfo[]{new ReceivedDeletedBlockInfo(b2.getBlock().getLocalBlock(), "")});
Thread.sleep(300L);
namenode.complete(f1.toString(), client.getClientName(), b2.getBlock());
dnp.blockReceivedAndDeleted(DataNodeTestUtils.getDNRegistrationForBP(dns.get(1), bpId), bpId,
new ReceivedDeletedBlockInfo[]{new ReceivedDeletedBlockInfo(b1.getBlock().getLocalBlock(), "")});
dnp.blockReceivedAndDeleted(DataNodeTestUtils.getDNRegistrationForBP(dns.get(2), bpId), bpId,
new ReceivedDeletedBlockInfo[]{new ReceivedDeletedBlockInfo(b1.getBlock().getLocalBlock(), "")});
dnp.blockReceivedAndDeleted(DataNodeTestUtils.getDNRegistrationForBP(dns.get(1), bpId), bpId,
new ReceivedDeletedBlockInfo[]{new ReceivedDeletedBlockInfo(b2.getBlock().getLocalBlock(), "")});
namenode.reportBadBlocks(new LocatedBlock[]{new LocatedBlock(b1.getBlock(),
new DatanodeInfo[]{new DatanodeInfo(dns.get(2).getDatanodeId())})});
LocatedBlock b3 = namenode.addBlock(f2.toString(), client.getClientName(),
null, new DatanodeInfo[]{new DatanodeInfo(dns.get(1).getDatanodeId())}); //FIXME [H]: Create a scenario in which b3 is commited and completes in the receivedAndDeletedBlocks
dnp.blockReceivedAndDeleted(DataNodeTestUtils.getDNRegistrationForBP(dns.get(0), bpId), bpId,
new ReceivedDeletedBlockInfo[]{new ReceivedDeletedBlockInfo(b3.getBlock().getLocalBlock(), "")});
namenode.addBlock(f2.toString(), client.getClientName(), b3.getBlock(), null); // to make the b3 commited
// We expect to send an excessive replica here.
dnp.blockReceivedAndDeleted(DataNodeTestUtils.getDNRegistrationForBP(dns.get(2), bpId), bpId,
new ReceivedDeletedBlockInfo[]{new ReceivedDeletedBlockInfo(b1.getBlock().getLocalBlock(), "-"),
new ReceivedDeletedBlockInfo(b2.getBlock().getLocalBlock(), ""),
new ReceivedDeletedBlockInfo(b3.getBlock().getLocalBlock(), "")});
} catch (InterruptedException ex) {
Logger.getLogger(TestTransactionalOperations.class.getName()).log(Level.SEVERE, null, ex);
} finally {
cluster.shutdown();
}
}
@Test
public void testGetFileInfoAndContentSummary() throws IOException {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1");
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
try {
DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();
Path f1 = new Path("/ed1/ed2/f1");
dfs.mkdirs(f1.getParent(), FsPermission.getDefault());
assert dfs.exists(f1.getParent()) : String.format("The path %s does not exist.", f1.getParent().toString());
DFSTestUtil.createFile(dfs, f1, 2 * blockSize, (short) 2, 28L);
assert dfs.exists(f1) : String.format("The file %s does not exist.", f1.toString());
dfs.getFileStatus(f1);
dfs.getContentSummary(f1);
} finally {
cluster.shutdown();
}
}
@Test
public void testGetBlockLocations() throws IOException {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1");
conf.set(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, "1"); // To make the access time percision expired by default it is one hour
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
try {
DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();
Path f1 = new Path("/ed1/ed2/f1");
dfs.mkdirs(f1.getParent(), FsPermission.getDefault());
assert dfs.exists(f1.getParent()) : String.format("The path %s does not exist.",
f1.getParent().toString());
FSDataOutputStream stm = dfs.create(f1, false, bufferSize, (short) 2, blockSize);
writeFile(stm, 2 * blockSize);
stm.hflush();
assert dfs.getDefaultDFSClient().getBlockLocations(f1.toString(), 0, 2 * blockSize).length == 2;
} finally {
cluster.shutdown();
}
}
/**
* In this test case we create two files f1 (replication factor 3) and f2 (replication factor 2). There
* two datanodes. We make the lease-manager for f1 to finalize the file. and for f2 to reassign the lease
* for it.
* @throws IOException
*/
@Test
public void testLeaseManagerMonitor() throws IOException {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1");
conf.set(DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, "1"); // To make the access time percision expired by default it is one hour
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
try {
try {
// We create three dfs for three different user names.
DistributedFileSystem dfs1 = (DistributedFileSystem) cluster.getFileSystem();
DistributedFileSystem dfs2 = (DistributedFileSystem) getFSAsAnotherUser(conf, "fake1", fakeGroup);
Path f1 = new Path("/ed1/ed2/f1");
Path f2 = new Path("/ed1/ed2/f2");
dfs1.mkdirs(f1.getParent(), FsPermission.getDefault());
NamenodeProtocols namenode = cluster.getNameNodeRpc();
String bpId = cluster.getNamesystem().getBlockPoolId();
namenode.create(f1.toString(), FsPermission.getDefault(), dfs1.getDefaultDFSClient().getClientName(),
new EnumSetWritable<CreateFlag>(EnumSet.of(CreateFlag.CREATE)), true, (short) 3, blockSize);
namenode.create(f2.toString(), FsPermission.getDefault(), dfs2.getDefaultDFSClient().getClientName(),
new EnumSetWritable<CreateFlag>(EnumSet.of(CreateFlag.CREATE)), true, (short) 2, blockSize);
List<DataNode> dns = cluster.getDataNodes();
LocatedBlock b1 = namenode.addBlock(f1.toString(), dfs1.getDefaultDFSClient().getClientName(),
null, null);
namenode.blockReceivedAndDeleted(DataNodeTestUtils.getDNRegistrationForBP(dns.get(0), bpId), fakeGroup,
new ReceivedDeletedBlockInfo[]{new ReceivedDeletedBlockInfo(b1.getBlock().getLocalBlock(), "")});
namenode.blockReceivedAndDeleted(DataNodeTestUtils.getDNRegistrationForBP(dns.get(1), bpId), fakeGroup,
new ReceivedDeletedBlockInfo[]{new ReceivedDeletedBlockInfo(b1.getBlock().getLocalBlock(), "")});
LocatedBlock b2 = namenode.addBlock(f1.toString(), dfs1.getDefaultDFSClient().getClientName(),
b1.getBlock(), null);
namenode.abandonBlock(b2.getBlock(), f1.toString(), dfs1.getDefaultDFSClient().getClientName());
LocatedBlock b3 = namenode.addBlock(f2.toString(), dfs2.getDefaultDFSClient().getClientName(),
null, null);
namenode.blockReceivedAndDeleted(DataNodeTestUtils.getDNRegistrationForBP(dns.get(0), bpId), fakeGroup,
new ReceivedDeletedBlockInfo[]{new ReceivedDeletedBlockInfo(b3.getBlock().getLocalBlock(), "")});
// expire the hard-lease
waitLeaseRecovery(cluster, SHORT_LEASE_PERIOD, SHORT_LEASE_PERIOD);
} catch (InterruptedException ex) {
assert false : ex.getMessage();
}
} finally {
cluster.shutdown();
}
}
@Test
public void testTransactionLockManager() throws IOException, InterruptedException {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1");
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
try {
DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();
DistributedFileSystem dfs2 = (DistributedFileSystem) getFSAsAnotherUser(conf, fakeUsername, fakeGroup);
Path f1 = new Path("/ed1/ed2/f1");
Path f2 = new Path("/ed1/ed2/f2");
Path f3 = new Path("/ed1/ed2/f3");
Path f4 = new Path("/ed1/ed2/ed3/f4");
Path f5 = new Path("/ed1/ed2/ed4/f5");
Path f6 = new Path("/ed1/ed2/ed4/ed5/f6");
Path f7 = new Path("/ed1/ed2/ed4/ed5/f7");
dfs.mkdirs(f1.getParent(), FsPermission.getDefault());
dfs.mkdirs(f7.getParent(), FsPermission.getDefault());
assert dfs.exists(f1.getParent()) : String.format("The path %s does not exist.",
f1.getParent().toString());
FSDataOutputStream stm = dfs.create(f1, false, bufferSize, (short) 2, blockSize);
writeFile(stm, 2 * blockSize);
stm.hflush();
stm = dfs.create(f2, false, bufferSize, (short) 2, blockSize);
writeFile(stm, 2 * blockSize);
stm.hflush();
stm = dfs.create(f3, false, bufferSize, (short) 2, blockSize);
writeFile(stm, 2 * blockSize);
stm.hflush();
assert dfs.getDefaultDFSClient().getBlockLocations(f1.toString(), 0, 2 * blockSize).length == 2;
FSDataOutputStream stm2 = dfs2.create(f4, false, bufferSize, (short) 2, blockSize);
writeFile(stm, 2 * blockSize);
stm2.hflush();
stm2 = dfs2.create(f5, false, bufferSize, (short) 2, blockSize);
writeFile(stm, 2 * blockSize);
stm2.hflush();
stm2 = dfs2.create(f6, false, bufferSize, (short) 2, blockSize);
writeFile(stm, 2 * blockSize);
stm2.hflush();
stm2 = dfs2.create(f7, false, bufferSize, (short) 2, blockSize);
writeFile(stm, 2 * blockSize);
stm2.hflush();
// Acquire locks for the getAdditionalBlocks
try {
// GetAdditionalBlock
EntityManager.begin();
TransactionLockManager tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.WRITE,
new String[]{f1.toString()});
tla.addBlock(TransactionLockManager.LockType.WRITE).
addLease(TransactionLockManager.LockType.READ).
addCorrupt(TransactionLockManager.LockType.WRITE).
addExcess(TransactionLockManager.LockType.WRITE).
addReplicaUc(TransactionLockManager.LockType.WRITE).
acquire();
EntityManager.commit();
// Complete
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.WRITE,
new String[]{f1.toString()});
tla.addBlock(TransactionLockManager.LockType.WRITE).
addLease(TransactionLockManager.LockType.WRITE).
addLeasePath(TransactionLockManager.LockType.WRITE).
addReplica(TransactionLockManager.LockType.READ).
addCorrupt(TransactionLockManager.LockType.READ).
addExcess(TransactionLockManager.LockType.READ).
addReplicaUc(TransactionLockManager.LockType.WRITE).
acquire();
EntityManager.commit();
// GetFileInfo and GetContentSummary
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.READ,
new String[]{f1.toString()});
tla.addBlock(TransactionLockManager.LockType.READ).
acquire();
EntityManager.commit();
// GetBlockLocations
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.WRITE, new String[]{f1.toString()});
tla.addBlock(TransactionLockManager.LockType.READ).
addReplica(TransactionLockManager.LockType.READ).
addCorrupt(TransactionLockManager.LockType.READ).
addExcess(TransactionLockManager.LockType.READ).
addReplicaUc(TransactionLockManager.LockType.READ).
acquire();
EntityManager.commit();
// recoverLease
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.WRITE,
new String[]{f1.toString()});
tla.addBlock(TransactionLockManager.LockType.WRITE).
addLease(TransactionLockManager.LockType.WRITE, "IamAnotherHolder").
addLeasePath(TransactionLockManager.LockType.WRITE).
addReplica(TransactionLockManager.LockType.READ).
addCorrupt(TransactionLockManager.LockType.READ).
addExcess(TransactionLockManager.LockType.READ).
addReplicaUc(TransactionLockManager.LockType.READ).
addUnderReplicatedBlock(TransactionLockManager.LockType.WRITE).
acquire();
EntityManager.commit();
//RenewLease
EntityManager.begin();
tla = new TransactionLockManager();
tla.addLease(TransactionLockManager.LockType.WRITE, "IamAHolder").
acquire();
EntityManager.commit();
// GetAdditionalDataNode
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.READ,
new String[]{f1.toString()}).
addLease(TransactionLockManager.LockType.READ).
acquire();
EntityManager.commit();
// Set_Permission, Set_Owner, SET_TIMES
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.WRITE,
new String[]{f1.toString()}).
addBlock(TransactionLockManager.LockType.READ).
acquire();
EntityManager.commit();
// GET_PREFFERED_BLOCK_SIZE
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.READ,
new String[]{f1.toString()}).
acquire();
EntityManager.commit();
//Append_file
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.WRITE,
new String[]{f1.toString()});
tla.addBlock(TransactionLockManager.LockType.WRITE).
addLease(TransactionLockManager.LockType.WRITE, "IamAnotherHolder").
addLeasePath(TransactionLockManager.LockType.WRITE).
addReplica(TransactionLockManager.LockType.READ).
addCorrupt(TransactionLockManager.LockType.READ).
addExcess(TransactionLockManager.LockType.READ).
addReplicaUc(TransactionLockManager.LockType.READ).
addUnderReplicatedBlock(TransactionLockManager.LockType.WRITE).
addInvalidatedBlock(TransactionLockManager.LockType.WRITE).
acquire();
EntityManager.commit();
// SET_QUOTA
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.WRITE,
new String[]{f1.toString()}).
acquire();
EntityManager.commit();
// SET_REPLICATION
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.WRITE_ON_PARENT,
new String[]{f1.toString()}).
addBlock(TransactionLockManager.LockType.WRITE).
addReplica(TransactionLockManager.LockType.READ).
addExcess(TransactionLockManager.LockType.READ).
addCorrupt(TransactionLockManager.LockType.READ).
addUnderReplicatedBlock(TransactionLockManager.LockType.WRITE).
acquire();
EntityManager.commit();
// CONCAT
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH,
TransactionLockManager.INodeLockType.WRITE_ON_PARENT,
new String[]{f1.toString(), f2.toString(), f3.toString()}).
addBlock(TransactionLockManager.LockType.WRITE).
acquire();
EntityManager.commit();
// GET_LISTING
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.PATH_AND_IMMEDIATE_CHILDREN,
TransactionLockManager.INodeLockType.READ,
new String[]{f1.getParent().toString()}).
addBlock(TransactionLockManager.LockType.READ).
addReplica(TransactionLockManager.LockType.READ).
addExcess(TransactionLockManager.LockType.READ).
addCorrupt(TransactionLockManager.LockType.READ).
addReplicaUc(TransactionLockManager.LockType.READ).
acquire();
EntityManager.commit();
// DELETE
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.PATH_AND_ALL_CHILDREN_RECURESIVELY,
TransactionLockManager.INodeLockType.WRITE,
new String[]{f1.getParent().toString()}).
addLease(TransactionLockManager.LockType.WRITE, "ZzZzZz").
addLeasePath(TransactionLockManager.LockType.WRITE).
addBlock(TransactionLockManager.LockType.WRITE).
addReplica(TransactionLockManager.LockType.WRITE).
addCorrupt(TransactionLockManager.LockType.WRITE).
addReplicaUc(TransactionLockManager.LockType.WRITE).
acquire();
EntityManager.commit();
// MKDIR , CREATE_SYM_LINK
Path f8 = new Path(f1.getParent().toString() + "/nd1/nd2/f8");
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH_WITH_UNKNOWN_HEAD,
TransactionLockManager.INodeLockType.WRITE,
new String[]{f8.getParent().toString()}).
acquire();
EntityManager.commit();
// START_FILE
EntityManager.begin();
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeResolveType.ONLY_PATH_WITH_UNKNOWN_HEAD,
TransactionLockManager.INodeLockType.WRITE_ON_PARENT,
new String[]{f7.toString()}).
addBlock(TransactionLockManager.LockType.WRITE).
addLease(TransactionLockManager.LockType.WRITE, "1234Holder").
addLeasePath(TransactionLockManager.LockType.WRITE).
addReplica(TransactionLockManager.LockType.WRITE).
addCorrupt(TransactionLockManager.LockType.WRITE).
addExcess(TransactionLockManager.LockType.READ).
addReplicaUc(TransactionLockManager.LockType.WRITE).
acquire();
EntityManager.commit();
LocatedBlocks locatedBlocks = cluster.getNameNodeRpc().getBlockLocations(f1.toString(), 0, blockSize);
assert locatedBlocks.getLocatedBlocks().size() > 0;
// BLOCK_RECEIVED_AND_DELETED
long bid = locatedBlocks.getLocatedBlocks().get(0).getBlock().getBlockId();
EntityManager.begin();
long inodeId = INodeUtil.findINodeIdByBlock(bid);
tla = new TransactionLockManager();
tla.addINode(TransactionLockManager.INodeLockType.WRITE).
addBlock(TransactionLockManager.LockType.WRITE, bid).
addReplica(TransactionLockManager.LockType.WRITE).
addExcess(TransactionLockManager.LockType.WRITE).
addCorrupt(TransactionLockManager.LockType.WRITE).
addUnderReplicatedBlock(TransactionLockManager.LockType.WRITE).
addPendingBlock(TransactionLockManager.LockType.WRITE).
addReplicaUc(TransactionLockManager.LockType.WRITE).
addInvalidatedBlock(TransactionLockManager.LockType.READ).
acquireByBlock(inodeId);
EntityManager.commit();
// HANDLE_HEARTBEAT
EntityManager.begin();
TransactionLockAcquirer.acquireLockList(TransactionLockManager.LockType.READ_COMMITTED, ReplicaUnderConstruction.Finder.ByBlockId, bid);
TransactionLockAcquirer.acquireLockList(TransactionLockManager.LockType.READ_COMMITTED, UnderReplicatedBlock.Finder.All);
TransactionLockAcquirer.acquireLockList(TransactionLockManager.LockType.READ_COMMITTED, PendingBlockInfo.Finder.All);
TransactionLockAcquirer.acquireLockList(TransactionLockManager.LockType.READ_COMMITTED, BlockInfo.Finder.All);
TransactionLockAcquirer.acquireLockList(TransactionLockManager.LockType.READ_COMMITTED, InvalidatedBlock.Finder.All);
EntityManager.commit();
// LEASE_MANAGER
EntityManager.begin();
SortedSet<String> leasePaths = INodeUtil.findPathsByLeaseHolder(dfs.getDefaultDFSClient().clientName);
TransactionLockManager tlm = new TransactionLockManager();
tlm.addINode(TransactionLockManager.INodeLockType.WRITE).
addBlock(TransactionLockManager.LockType.WRITE).
addLease(TransactionLockManager.LockType.WRITE, dfs.getDefaultDFSClient().clientName).
addLeasePath(TransactionLockManager.LockType.WRITE).
addReplica(TransactionLockManager.LockType.READ).
addCorrupt(TransactionLockManager.LockType.READ).
addExcess(TransactionLockManager.LockType.READ).
addReplicaUc(TransactionLockManager.LockType.READ).
acquireByLease(leasePaths);
EntityManager.commit();
} catch (PersistanceException ex) {
Logger.getLogger(TestTransactionalOperations.class.getName()).log(Level.SEVERE, null, ex);
assert false : ex.getMessage();
}
} finally {
cluster.shutdown();
}
}
@Test
public void testTransactionLockAcquirer() throws IOException, StorageException, UnresolvedPathException, PersistanceException {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1");
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();
try {
DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();
Path p1 = new Path("/ed1/ed2/");
Path p2 = new Path("/ed1/ed2/ed3/ed4");
dfs.mkdirs(p2, FsPermission.getDefault());
assert dfs.exists(p2);
EntityManager.begin();
// first get write lock on ed2
LinkedList<INode> lockedINodes = TransactionLockAcquirer.acquireInodeLockByPath(
TransactionLockManager.INodeLockType.WRITE,
p1.toString(),
true);
assert lockedINodes != null;
assert lockedINodes.size() == 2; // first two path components
lockedINodes = TransactionLockAcquirer.acquireLockOnRestOfPath(TransactionLockManager.INodeLockType.WRITE,
lockedINodes.getLast(), p2.toString(), p1.toString(), true);
assert lockedINodes != null && lockedINodes.size() == 2; // the other two
EntityManager.commit();
EntityManager.begin();
// The same thing with write on parent
lockedINodes = TransactionLockAcquirer.acquireInodeLockByPath(
TransactionLockManager.INodeLockType.WRITE_ON_PARENT,
p1.toString(),
true);
assert lockedINodes != null;
assert lockedINodes.size() == 2; // first two path components
lockedINodes = TransactionLockAcquirer.acquireLockOnRestOfPath(TransactionLockManager.INodeLockType.WRITE_ON_PARENT,
lockedINodes.getLast(), p2.toString(), p1.toString(), true);
assert lockedINodes != null && lockedINodes.size() == 2; // the other two
EntityManager.commit();
} finally {
cluster.shutdown();
}
}
@Test
public void testConcurrentWriteLocksOnTheSameRow() throws IOException, InterruptedException, PersistanceException {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1");
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();
try {
final NamenodeProtocols nameNodeProto = cluster.getNameNodeRpc();
final DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();
int numThreads = 100;
Thread[] threads = new Thread[numThreads];
final CyclicBarrier barrier = new CyclicBarrier(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
// create file on the root
Runnable fileCreator = new Runnable() {
@Override
public void run() {
String name = "/" + Thread.currentThread().getName();
try {
barrier.await(); // to make all threads starting at the same time
nameNodeProto.create(name, FsPermission.getDefault(),
dfs.getDefaultDFSClient().clientName,
new EnumSetWritable<CreateFlag>(EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE)), true, (short) 2, blockSize);
latch.countDown();
} catch (Exception ex) {
latch.countDown();
ex.printStackTrace();
}
}
};
for (int i = 0; i < numThreads; i++) {
threads[i] = new Thread(fileCreator);
threads[i].start();
}
latch.await();
String root = "/";
System.out.println("root = " + root);
DirectoryListing list = nameNodeProto.getListing(root, new byte[]{}, false);
assert list.getPartialListing().length == numThreads; // root must have 100 children
} finally {
cluster.shutdown();
}
}
//
// writes specified bytes to file.
//
public void writeFile(FSDataOutputStream stm, int size) throws IOException {
byte[] buffer = AppendTestUtil.randomBytes(seed, size);
stm.write(buffer, 0, size);
}
void waitLeaseRecovery(MiniDFSCluster cluster, long softPeriod, long hardPeriod) {
cluster.setLeasePeriod(softPeriod, hardPeriod);
// wait for the lease to expire
try {
Thread.sleep(2 * 3000); // 2 heartbeat intervals
} catch (InterruptedException e) {
}
}
private FileSystem getFSAsAnotherUser(final Configuration c, String username, String group)
throws IOException, InterruptedException {
return FileSystem.get(FileSystem.getDefaultUri(c), c,
UserGroupInformation.createUserForTesting(username,
new String[]{group}).getUserName());
}
}
|
package com.ecej.nove.hbase.config;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* 配置异步任务分发
*
* @author QIANG
*
*/
@Configuration
@EnableAsync
@EnableConfigurationProperties(HbaseProperties.class)
public class HbaseExecutorConfig {
public static final Logger LOG = LoggerFactory.getLogger(HbaseExecutorConfig.class);
@Resource
private HbaseProperties hbaseProperties;
@Bean(name = "hbaseAsync")
public Executor mailAsync() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(hbaseProperties.getCorePoolSize());
executor.setMaxPoolSize(hbaseProperties.getMaxPoolSize());
executor.setQueueCapacity(hbaseProperties.getQueueCapacity());
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setThreadNamePrefix("HBaseExecutor-");
executor.initialize();
LOG.info("创建Hbase异步消费线程池,核心线程数为:[{}],最大线程数为:[{}],默认队列为LinkedBlockingQueue,其队列深度为:[{}],拒绝策略为:CallerRunsPolicy",
hbaseProperties.getCorePoolSize(), hbaseProperties.getMaxPoolSize(),
hbaseProperties.getQueueCapacity());
return executor;
}
}
|
package com.nextLevel.hero.mngVacation.model.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.nextLevel.hero.mngVacation.model.dto.AnnualVacationControlDTO;
import com.nextLevel.hero.mngVacation.model.dto.AnnualVacationDTO;
import com.nextLevel.hero.mngVacation.model.dto.MngHolidayDTO;
import com.nextLevel.hero.workattitude.model.dto.EmployeeVacationDTO;
@Mapper
public interface MngVacationMapper {
/* 휴일 조회 */
List<MngHolidayDTO> listHoliday(int companyNo);
/* 휴일 생성 */
int insertPublicHoliday(MngHolidayDTO mngHolidayDTO);
/* 휴일 삭제 */
int holidayDelete(int companyNo, int holidayNo);
/* 인사관리자가 직원의 연차 조회 */
List<AnnualVacationDTO> listAnnualVacation(int companyNo);
/* 연차 지급 */
int updateAnnualVacationDate(String idNo, String selectedVacationType);
/* 직원 휴가 */
List<EmployeeVacationDTO> selectVacationList(int companyNo);
/* 직원 휴가 신청에 대한 승인 */
int confirmVacationY(String requestNo);
/* 직원 휴가 신청에 대한 반려*/
int confirmVacationN(String requestNo);
/* 일괄 조정 연차 조회 */
List<AnnualVacationControlDTO> listAnnualVacationControl();
/* 일괄 조정 연차 수정 */
int updateControl(Map<String, String> map);
// List<Map<String, String>> listAnnualVacationControl(Map<String, String> map);
}
|
package filamentengine.editor;
import filamentengine.content.Entity;
import filamentengine.content.Scene;
public interface EditorExtension {
String getExtensionName();
void initializeExtension(EditorStateManager manager);
void entitySelected(Entity entity);
void sceneChanged(Scene scene);
void update(int delta);
}
|
package com.logzc.webzic.generic;
import com.logzc.common.converter.ResolvableType;
import com.logzc.webzic.generic.model.*;
import com.logzc.common.util.ReflectionUtil;
import org.junit.Assume;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>User: Zhang Kaitao
* <p>Date: 13-12-18
* <p>Version: 1.0
*/
public class GenricInjectTest {
private Service<A, B> abService;
private Service<C, D> cdService;
private List<List<String>> list;
private Map<String, Map<String, Integer>> map;
private List<String>[] array;
public GenricInjectTest() {
}
@Test
public void testGenericAPI() {
// ParameterizedType parameterizedType = (ParameterizedType) ABService.class.getGenericInterfaces()[0];
// Type genericType = parameterizedType.getActualTypeArguments()[1];
//得到类型上的泛型 如果你的类可能被代理 可以通过ClassUtils.getUserClass(ABService.class)得到原有的类型
ResolvableType resolvableType = ResolvableType.forClass(ABService.class);
//resolvableType1.getSuperType(); 得到父类
//以下是得到接口上的
ResolvableType[] interfaces = resolvableType.getInterfaces();
ResolvableType inter = interfaces[0];
ResolvableType generic = inter.getGeneric(1);
Type type = generic.resolve();
System.out.println(type);
Assume.assumeTrue(type == B.class);
//转换为某个类型(父类/实现的接口) 还提供了简便方法 asMap() /asCollection
resolvableType = ResolvableType.forClass(ABService.class);
resolvableType = resolvableType.as(Service.class);
generic = resolvableType.getGeneric(1);
type = generic.resolve();
System.out.println(type);
//这里表明依旧持有泛型类型。
Assume.assumeTrue(type == B.class);
resolvableType = ResolvableType.forClass(Service.class);;
generic = resolvableType.getGeneric(1);
type = generic.resolve();
System.out.println(type);
//此处表明泛型已经弱化为了Object.
Assume.assumeTrue(type == Object.class);
///得到字段的
ResolvableType resolvableType2 =
ResolvableType.forField(ReflectionUtil.findField(GenricInjectTest.class, "cdService"));
System.out.println(resolvableType2.getGeneric(0).resolve()); //得到某个位置的 如<C, D> 0就是C 1就是D
//嵌套的
ResolvableType resolvableType3 =
ResolvableType.forField(ReflectionUtil.findField(GenricInjectTest.class, "list"));
System.out.println(resolvableType3.getGeneric(0).getGeneric(0).resolve());
//Map嵌套
ResolvableType resolvableType4 =
ResolvableType.forField(ReflectionUtil.findField(GenricInjectTest.class, "map"));
System.out.println(resolvableType4.getGeneric(1).getGeneric(1).resolve());
System.out.println(resolvableType4.getGeneric(1, 1).resolve());
//方法返回值
// ResolvableType resolvableType5 =
// ResolvableType.forMethodReturnType(ReflectionUtil.findMethod(GenricInjectTest.class, "method"));
// System.out.println(resolvableType5.getGeneric(1, 0).resolve());
//构造器参数
// ResolvableType resolvableType6 =
// ResolvableType.forConstructorParameter(ReflectionUtil.findConstructor(Const.class,List.class, Map.class), 1);
// System.out.println(resolvableType6.getGeneric(1, 0).resolve());
//数组
ResolvableType resolvableType7 =
ResolvableType.forField(ReflectionUtil.findField(GenricInjectTest.class, "array"));
System.out.println(resolvableType7.isArray());
ResolvableType componentType = resolvableType7.getComponentType();
System.out.println(componentType.getGeneric(0).resolve());
/*
//自定义一个泛型数组 List<String>[]
ResolvableType resolvableType8 = ResolvableType.forClassWithGenerics(List.class, String.class);
ResolvableType resolvableType9 = ResolvableType.forArrayComponent(resolvableType8);
System.out.println(resolvableType9.getComponentType().getGeneric(0).resolve());
//比较两个泛型是否可以赋值成功
System.out.println(resolvableType7.isAssignableFrom(resolvableType9));
ResolvableType resolvableType10 = ResolvableType.forClassWithGenerics(List.class, Integer.class);
ResolvableType resolvableType11 = ResolvableType.forArrayComponent(resolvableType10);
System.out.println(resolvableType11.getComponentType().getGeneric(0).resolve());
System.out.println(resolvableType7.isAssignableFrom(resolvableType11));
*/
}
private HashMap<String, List<String>> method() {
return null;
}
static class Const {
public Const(List<List<String>> list, Map<String, Map<String, Integer>> map) {
}
}
}
|
Using DFS
Base case: the last row is done. row == N
Recursive rule: if the position(i, j) is valid, go to the next row(i + 1)
Using the list to store current result.
Using check func to check the validality of assignment.
public class Solution {
public List<List<Integer>> nqueens(int n) {
List<List<Integer>> list = new ArrayList<>();
if (n == 0) {
return list;
}
List<Integer> cur = new ArrayList<>();
dfs(list, cur, n);
return list;
}
private void dfs(List<List<Integer>> list, List<Integer> cur, int n) {
if (cur.size() == n) {
list.add(new ArrayList(cur));
return;
}
for (int i = 0; i < n; i++) {
if (check(cur, i)) {
cur.add(i);
dfs(list, cur, n);
cur.remove(cur.size() - 1);
}
}
}
private boolean check(List<Integer> cur, int n) {
for (int i = 0; i < cur.size(); i++) {
if (cur.get(i) == n || Math.abs(cur.get(i) - n) == cur.size() - i) {
return false;
}
}
return true;
}
}
|
package com.clinic.dentist.controllers;
import com.clinic.dentist.api.service.IPatientService;
import com.clinic.dentist.date.DateSystem;
import com.clinic.dentist.date.TimeConverter;
import com.clinic.dentist.models.*;
import com.clinic.dentist.services.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Controller
public class AdminController {
@Autowired
@Qualifier("patientService")
private IPatientService patientService;
@Autowired
@Qualifier("appointmentService")
private AppointmentService appointmentService;
@Autowired
@Qualifier("maintenanceService")
private MaintenanceService maintenanceService;
@Autowired
@Qualifier("dentistService")
private DentistService dentistService;
@Autowired
@Qualifier("clinicService")
private ClinicService clinicService;
@Autowired
@Qualifier("typeServicesService")
private TypeServicesService typeServicesService;
// @GetMapping("/admin")
// public String greeting(Model model) {
// return "admin";
// }
@GetMapping("/admin/patients")
public String getPatientView(Model model) {
List<Patient> patients = patientService.getRegisteredPatients();
model.addAttribute("patients", patients);
return "patient";
}
@GetMapping("/admin/patients/register")
public String getUnregisteredPatientView(Model model) {
List<Patient> patients = patientService.getUnregisteredPatients();
model.addAttribute("patients", patients);
return "unregisteredPatients";
}
@GetMapping("/admin/patients/register/{id}")
public String getUnregisteredPatientView(@PathVariable(value = "id") long id, Model model) {
patientService.registeredPatient(id);
List<Patient> patients = patientService.getUnregisteredPatients();
model.addAttribute("patients", patients);
return "unregisteredPatients";
}
@GetMapping("/admin/patients/{id}/orders")
public String getPatientOrders(@PathVariable(value = "id") long id, Model model) {
Patient patient = patientService.findById(id);
List<Appointment> appointments = appointmentService.getAppointmentsWithActiveForPatient(patient.getId());
Collections.reverse(appointments);
model.addAttribute("patient", patient);
model.addAttribute("orders", appointments);
return "ordersPatients";
}
@GetMapping("/admin/patients/{id}/orders/remove/{id1}")
public String getUnregisteredPatientView(@PathVariable(value = "id") long id, @PathVariable(value = "id1") long id1, Model model) {
appointmentService.deleteAppointment(id1);
Patient patient = patientService.findById(id);
List<Appointment> appointments = appointmentService.getAppointmentsWithActiveForPatient(patient.getId());
Collections.reverse(appointments);
model.addAttribute("orders", appointments);
model.addAttribute("patient", patient);
return "ordersPatients";
}
@GetMapping("/admin/services")
public String getService(Model model) {
List<Maintenance> maintenances = maintenanceService.sortByName();
model.addAttribute("services", maintenances);
return ("servicesAdmin");
}
@GetMapping("/admin/dentists")
public String showDentists(Model model) {
List<Dentist> dentists = dentistService.sortbyAlphabet();
model.addAttribute("dentists", dentists);
return ("doctors");
}
@GetMapping("/admin/dentists/{id}/remove")
public String removeDentist(@PathVariable(value = "id") long id, Model model) {
if (!dentistService.checkExist(id)) {
return "redirect:/admin/dentists";
}
boolean delete = dentistService.deleteEntity(id);
if (!delete) {
return "redirect:/admin/dentists/" + id + "/remove";
}
return "redirect:/admin/dentists";
}
private Dentist den;
@PostMapping("/admin/dentists/{id}/appointments")
public String getAppointmentDentistDate(@PathVariable(value = "id") long id, Model model, @RequestParam String Date) {
if (!dentistService.checkExist(id)) {
return "redirect:/admin/dentists";
}
List<Appointment> appointments = null;
Dentist dentist = dentistService.findById(id);
model.addAttribute(dentist);
if (DateSystem.checkWeekend(Date)) {
appointments = appointmentService.getActualAppointmentsForDoctor(dentist, DateSystem.NextDay());
model.addAttribute("dates", DateSystem.NextDay());
model.addAttribute("norm_date", TimeConverter.getDate2(DateSystem.NextDay()));
} else {
appointments = appointmentService.getActualAppointmentsForDoctor(dentist, Date);
model.addAttribute("dates", Date);
model.addAttribute("norm_date", Date);
}
Collections.sort(appointments);
model.addAttribute("orders", appointments);
return "adminDentistAppointment";
}
@GetMapping("/admin/dentists/{id}/appointments")
public String getAppointment(@PathVariable(value = "id") long id, Model model) {
if (!dentistService.checkExist(id)) {
return "redirect:/admin/dentists";
}
Date thisDay = new Date();
SimpleDateFormat formatForDateNow = new SimpleDateFormat("yyyy-MM-dd");
String dat = formatForDateNow.format(thisDay);
List<Appointment> appointments;
Dentist dentist = dentistService.findById(id);
model.addAttribute(dentist);
if (DateSystem.checkWeekend(dat)) {
appointments = appointmentService.getActualAppointmentsForDoctor(dentist, DateSystem.NextDay());
model.addAttribute("dates", DateSystem.NextDay());
model.addAttribute("norm_date", TimeConverter.getDate2(DateSystem.NextDay()));
} else {
appointments = appointmentService.getActualAppointmentsForDoctor(dentist, dat);
model.addAttribute("dates", dat);
model.addAttribute("norm_date", dat);
}
Collections.sort(appointments);
model.addAttribute("orders", appointments);
return "adminDentistAppointment";
}
@GetMapping("/admin/{id}/dentist/add")
public String createDentist(@PathVariable(value = "id") long id, Model model) {
model.addAttribute("dentist", new Dentist());
model.addAttribute("clinicId", id);
return "createDentist";
}
@PostMapping("/admin/{id}/dentist/add")
public String getDentist(@ModelAttribute(name = "dentist") Dentist dentist, @PathVariable(value = "id") long id, Model model) {
den = null;
if (dentist.getFirstName().trim().equals("")) {
model.addAttribute("firstNameError", "Имя не введено");
model.addAttribute("clinicId", id);
return "createDentist";
} else if (dentist.getLastName().trim().equals("")) {
model.addAttribute("lastNameError", "Фамилия не введена");
model.addAttribute("clinicId", id);
return "createDentist";
} else if (dentist.getPatronymic().trim().equals("")) {
model.addAttribute("patronymicError", "Отчество не введено");
model.addAttribute("clinicId", id);
return "createDentist";
} else if (dentist.getPhoneNumber().trim().equals("")) {
model.addAttribute("clinicId", id);
model.addAttribute("phoneNumberError", "Номер телефона не введен");
return "createDentist";
}
Pattern pattern = Pattern.compile("^(375)[0-9]{9}$");
Matcher matcher = pattern.matcher(dentist.getPhoneNumber().trim());
if (!matcher.matches()) {
model.addAttribute("clinicId", id);
model.addAttribute("phoneNumberError", "Номер телефона введен не корректно");
return "createDentist";
} else if (dentistService.findDentistByPhoneNumber(dentist.getPhoneNumber().trim())) {
model.addAttribute("phoneNumberError", "Врач с данным номером телефона зарегистрирован");
model.addAttribute("clinicId", id);
return "createDentist";
}
try {
dentist.setFirstName(dentist.getFirstName().trim());
dentist.setLastName(dentist.getLastName().trim());
dentist.setPhoneNumber(dentist.getPhoneNumber().trim());
dentist.setPatronymic(dentist.getPatronymic().trim());
dentist.setClinic(clinicService.findById(id));
} catch (RuntimeException ex) {
model.addAttribute("clinicId", id);
return "createDentist";
}
den = dentist;
return "redirect:/admin/{id}/dentist/add/services";
}
@GetMapping("/admin/{id}/dentist/add/services")
public String getServices(Model model, @PathVariable(value = "id") long id) {
Iterable<Maintenance> maintenanceList = clinicService.findMaintenancesByClinic(den.getClinic().getId());
model.addAttribute("services", maintenanceList);
model.addAttribute("clinicId", id);
if (den != null) {
model.addAttribute("dentist", den);
}
return "chooseServicesForDentist";
}
@PostMapping("/admin/{id}/dentist/add/services")
public String finishCreateDentist1(@RequestParam(required = false) String[] services, @PathVariable(value = "id") long id, Model model) {
if (services == null) {
Iterable<Maintenance> maintenanceList = clinicService.findMaintenancesByClinic(den.getClinic().getId());
model.addAttribute("services", maintenanceList);
model.addAttribute("servicesError", "Услуги не выбраны");
model.addAttribute("dentist", den);
model.addAttribute("clinicId", id);
return "chooseServicesForDentist";
}
den.setMaintenances(maintenanceService.getSetFromArrayMaintenance(services));
dentistService.addEntity(den);
den = null;
return "redirect:/admin";
}
@GetMapping("/admin/services/add")
public String createService(Model model) {
List<Clinic> clinics = clinicService.findAll();
List<TypeServices> typeServices = typeServicesService.getAll();
model.addAttribute("service", new Maintenance());
return "createMaintenance";
}
@PostMapping("/admin/services/add")
public String getService(@ModelAttribute(name = "service") Maintenance service, Model model) {
// if (service.getName().trim().equals("")) {
// model.addAttribute("nameError", "Название не введено");
//
// return "createService";
// } else if (service.getDescription().trim().equals("")) {
//
// model.addAttribute("descriptionError", "Описание не введено");
//
// return "createService";
// }
service.setName(service.getName().trim());
service.setDescription(service.getDescription().trim());
if (maintenanceService.checkHaveThisMaintenance(service)) {
model.addAttribute("nameError", "Услуга с таким названием уже существует");
}
maintenanceService.addMaintenance(service);
return "redirect:/admin/services";
}
@GetMapping("/admin")
public String getClinics(Model model) {
List<Clinic> clinics = clinicService.findAll();
model.addAttribute("clinics", clinics);
return "admin";
}
@GetMapping("/admin/{id}/dentists")
public String getDentistsClinics(@PathVariable(value = "id") long id, Model model) {
List<Dentist> dentists = clinicService.findDentistsByClinic(id);
model.addAttribute("dentists", dentists);
return ("doctors");
}
@GetMapping("/admin/{id}/services")
public String getServicesClinics(@PathVariable(value = "id") long id, Model model) {
Iterable<Maintenance> services = clinicService.findMaintenancesByClinic(id);
model.addAttribute("services", services);
return ("servicesAdmin");
}
@PostMapping("/admin/{id}/appointments")
public String getAppointmentClinicDate(@PathVariable(value = "id") long id, Model model, @RequestParam String Date) {
if (!clinicService.checkExist(id)) {
return "redirect:/admin";
}
List<Appointment> appointments = null;
Clinic clinic = clinicService.findById(id);
model.addAttribute(clinic);
if (DateSystem.checkWeekend(Date)) {
appointments = appointmentService.getActualAppointmentsForClinic(clinic, DateSystem.NextDay());
model.addAttribute("dates", DateSystem.NextDay());
model.addAttribute("norm_date", TimeConverter.getDate2(DateSystem.NextDay()));
} else {
appointments = appointmentService.getActualAppointmentsForClinic(clinic, Date);
model.addAttribute("dates", Date);
model.addAttribute("norm_date", Date);
}
Collections.sort(appointments);
model.addAttribute("id", id);
model.addAttribute("orders", appointments);
return "clinicAppointment";
}
@PostMapping("/admin/patients/{id}/edit")
public String clientEdit2(@PathVariable(value = "id") long id, @RequestParam String Username, Model model) {
Patient patient = patientService.findById(id);
if (Username.trim().equals("")) {
model.addAttribute(patient);
model.addAttribute("phoneError", "Новый номер не введен");
return ("changeNumber");
}
Pattern pattern = Pattern.compile("^(375)[0-9]{9}$");
Matcher matcher = pattern.matcher(Username.trim());
if (!matcher.matches()) {
model.addAttribute(patient);
model.addAttribute("phoneError", "Номер телефона введен не корректно");
return ("changeNumber");
}
if (patientService.checkPatient(Username.trim())) {
model.addAttribute(patient);
model.addAttribute("phoneError", "Данный номер занят");
return ("changeNumber");
}
patient.setUsername(Username.trim());
patientService.save(patient);
return "redirect:/admin/patients";
}
@GetMapping("/admin/{id}/appointments")
public String getAppointmentForClinic(@PathVariable(value = "id") long id, Model model) {
if (!clinicService.checkExist(id)) {
return "redirect:/admin";
}
Date thisDay = new Date();
SimpleDateFormat formatForDateNow = new SimpleDateFormat("yyyy-MM-dd");
String dat = formatForDateNow.format(thisDay);
List<Appointment> appointments;
Clinic clinic = clinicService.findById(id);
model.addAttribute(clinic);
if (DateSystem.checkWeekend(dat)) {
appointments = appointmentService.getActualAppointmentsForClinic(clinic, DateSystem.NextDay());
model.addAttribute("dates", DateSystem.NextDay());
model.addAttribute("norm_date", TimeConverter.getDate2(DateSystem.NextDay()));
} else {
appointments = appointmentService.getActualAppointmentsForClinic(clinic, dat);
model.addAttribute("dates", dat);
model.addAttribute("norm_date", dat);
}
Collections.sort(appointments);
model.addAttribute("id", id);
model.addAttribute("orders", appointments);
return "clinicAppointment";
}
@GetMapping("/admin/patients/{id}/edit")
public String showTemplateToEditPatientPhoneNumber(@PathVariable(value = "id") long id, Model model) {
Patient patient = patientService.findById(id);
model.addAttribute("patient", patient);
return "changeNumber";
}
@GetMapping("/admin/patients/register/{id}/delete")
public String deletePatient(@PathVariable(value = "id") long id, Model model) {
if (!patientService.checkExist(id)) {
return "redirect:/admin/patients/register";
}
Patient patient = patientService.findById(id);
patientService.delete(patient);
return "redirect:/admin/patients/register";
}
}
|
package android.support.v4.graphics;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.RequiresApi;
import android.support.annotation.RestrictTo;
import android.support.annotation.RestrictTo.Scope;
import android.util.Log;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
@RestrictTo({Scope.LIBRARY_GROUP})
public class TypefaceCompatUtil {
private static final String CACHE_FILE_PREFIX = ".font";
private static final String TAG = "TypefaceCompatUtil";
private TypefaceCompatUtil() {
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public static java.io.File getTempFile(android.content.Context r5) {
/*
r0 = new java.lang.StringBuilder;
r0.<init>();
r1 = ".font";
r0.append(r1);
r1 = android.os.Process.myPid();
r0.append(r1);
r1 = "-";
r0.append(r1);
r1 = android.os.Process.myTid();
r0.append(r1);
r1 = "-";
r0.append(r1);
r0 = r0.toString();
r1 = 0;
L_0x0027:
r2 = 100;
if (r1 >= r2) goto L_0x004d;
L_0x002b:
r2 = new java.io.File;
r3 = r5.getCacheDir();
r4 = new java.lang.StringBuilder;
r4.<init>();
r4.append(r0);
r4.append(r1);
r4 = r4.toString();
r2.<init>(r3, r4);
r3 = r2.createNewFile(); Catch:{ IOException -> 0x004a }
if (r3 == 0) goto L_0x004a;
L_0x0049:
return r2;
L_0x004a:
r1 = r1 + 1;
goto L_0x0027;
L_0x004d:
r5 = 0;
return r5;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v4.graphics.TypefaceCompatUtil.getTempFile(android.content.Context):java.io.File");
}
@RequiresApi(19)
private static ByteBuffer mmap(File file) {
Throwable th;
Throwable th2;
ByteBuffer byteBuffer = null;
try {
FileInputStream fileInputStream = new FileInputStream(file);
try {
FileChannel channel = fileInputStream.getChannel();
ByteBuffer map = channel.map(MapMode.READ_ONLY, 0, channel.size());
if (fileInputStream != null) {
fileInputStream.close();
}
return map;
} catch (Throwable th22) {
Throwable th3 = th22;
th22 = th;
th = th3;
}
throw th;
if (fileInputStream != null) {
if (th22 != null) {
try {
fileInputStream.close();
} catch (Throwable th4) {
th22.addSuppressed(th4);
}
} else {
fileInputStream.close();
}
}
throw th;
} catch (IOException unused) {
return byteBuffer;
}
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
@android.support.annotation.RequiresApi(19)
public static java.nio.ByteBuffer mmap(android.content.Context r8, android.os.CancellationSignal r9, android.net.Uri r10) {
/*
r8 = r8.getContentResolver();
r0 = 0;
r1 = "r";
r8 = r8.openFileDescriptor(r10, r1, r9); Catch:{ IOException -> 0x0063 }
r9 = new java.io.FileInputStream; Catch:{ Throwable -> 0x004c, all -> 0x0049 }
r10 = r8.getFileDescriptor(); Catch:{ Throwable -> 0x004c, all -> 0x0049 }
r9.<init>(r10); Catch:{ Throwable -> 0x004c, all -> 0x0049 }
r1 = r9.getChannel(); Catch:{ Throwable -> 0x0032, all -> 0x002f }
r5 = r1.size(); Catch:{ Throwable -> 0x0032, all -> 0x002f }
r2 = java.nio.channels.FileChannel.MapMode.READ_ONLY; Catch:{ Throwable -> 0x0032, all -> 0x002f }
r3 = 0;
r10 = r1.map(r2, r3, r5); Catch:{ Throwable -> 0x0032, all -> 0x002f }
if (r9 == 0) goto L_0x0029;
L_0x0026:
r9.close(); Catch:{ Throwable -> 0x004c, all -> 0x0049 }
L_0x0029:
if (r8 == 0) goto L_0x002e;
L_0x002b:
r8.close(); Catch:{ IOException -> 0x0063 }
L_0x002e:
return r10;
L_0x002f:
r10 = move-exception;
r1 = r0;
goto L_0x0038;
L_0x0032:
r10 = move-exception;
throw r10; Catch:{ all -> 0x0034 }
L_0x0034:
r1 = move-exception;
r7 = r1;
r1 = r10;
r10 = r7;
L_0x0038:
if (r9 == 0) goto L_0x0048;
L_0x003a:
if (r1 == 0) goto L_0x0045;
L_0x003c:
r9.close(); Catch:{ Throwable -> 0x0040, all -> 0x0049 }
goto L_0x0048;
L_0x0040:
r9 = move-exception;
r1.addSuppressed(r9); Catch:{ Throwable -> 0x004c, all -> 0x0049 }
goto L_0x0048;
L_0x0045:
r9.close(); Catch:{ Throwable -> 0x004c, all -> 0x0049 }
L_0x0048:
throw r10; Catch:{ Throwable -> 0x004c, all -> 0x0049 }
L_0x0049:
r9 = move-exception;
r10 = r0;
goto L_0x0052;
L_0x004c:
r9 = move-exception;
throw r9; Catch:{ all -> 0x004e }
L_0x004e:
r10 = move-exception;
r7 = r10;
r10 = r9;
r9 = r7;
L_0x0052:
if (r8 == 0) goto L_0x0062;
L_0x0054:
if (r10 == 0) goto L_0x005f;
L_0x0056:
r8.close(); Catch:{ Throwable -> 0x005a }
goto L_0x0062;
L_0x005a:
r8 = move-exception;
r10.addSuppressed(r8); Catch:{ IOException -> 0x0063 }
goto L_0x0062;
L_0x005f:
r8.close(); Catch:{ IOException -> 0x0063 }
L_0x0062:
throw r9; Catch:{ IOException -> 0x0063 }
L_0x0063:
return r0;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v4.graphics.TypefaceCompatUtil.mmap(android.content.Context, android.os.CancellationSignal, android.net.Uri):java.nio.ByteBuffer");
}
@RequiresApi(19)
public static ByteBuffer copyToDirectBuffer(Context context, Resources resources, int i) {
File tempFile = getTempFile(context);
ByteBuffer byteBuffer = null;
if (tempFile == null) {
return byteBuffer;
}
try {
if (!copyToFile(tempFile, resources, i)) {
return byteBuffer;
}
ByteBuffer mmap = mmap(tempFile);
tempFile.delete();
return mmap;
} finally {
tempFile.delete();
}
}
public static boolean copyToFile(File file, InputStream inputStream) {
IOException e;
StringBuilder stringBuilder;
Throwable th;
boolean z = false;
Closeable closeable = null;
try {
Closeable fileOutputStream = new FileOutputStream(file, z);
try {
byte[] bArr = new byte[1024];
while (true) {
int read = inputStream.read(bArr);
if (read != -1) {
fileOutputStream.write(bArr, z, read);
} else {
boolean z2 = true;
closeQuietly(fileOutputStream);
return z2;
}
}
} catch (IOException e2) {
e = e2;
closeable = fileOutputStream;
try {
stringBuilder = new StringBuilder();
stringBuilder.append("Error copying resource contents to temp file: ");
stringBuilder.append(e.getMessage());
Log.e("TypefaceCompatUtil", stringBuilder.toString());
closeQuietly(closeable);
return z;
} catch (Throwable th2) {
th = th2;
closeQuietly(closeable);
throw th;
}
} catch (Throwable th3) {
th = th3;
closeable = fileOutputStream;
closeQuietly(closeable);
throw th;
}
} catch (IOException e3) {
e = e3;
stringBuilder = new StringBuilder();
stringBuilder.append("Error copying resource contents to temp file: ");
stringBuilder.append(e.getMessage());
Log.e("TypefaceCompatUtil", stringBuilder.toString());
closeQuietly(closeable);
return z;
}
}
public static boolean copyToFile(File file, Resources resources, int i) {
Throwable th;
Closeable openRawResource;
try {
openRawResource = resources.openRawResource(i);
try {
boolean copyToFile = copyToFile(file, openRawResource);
closeQuietly(openRawResource);
return copyToFile;
} catch (Throwable th2) {
th = th2;
closeQuietly(openRawResource);
throw th;
}
} catch (Throwable th3) {
th = th3;
openRawResource = null;
closeQuietly(openRawResource);
throw th;
}
}
public static void closeQuietly(java.io.Closeable r0) {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.JadxRuntimeException: Exception block dominator not found, method:android.support.v4.graphics.TypefaceCompatUtil.closeQuietly(java.io.Closeable):void, dom blocks: []
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.searchTryCatchDominators(ProcessTryCatchRegions.java:89)
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.process(ProcessTryCatchRegions.java:45)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.postProcessRegions(RegionMakerVisitor.java:63)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.visit(RegionMakerVisitor.java:58)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:27)
at jadx.core.dex.visitors.DepthTraversal.lambda$1(DepthTraversal.java:14)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:14)
at jadx.core.ProcessClass.process(ProcessClass.java:32)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:286)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$0(JadxDecompiler.java:201)
*/
/*
if (r0 == 0) goto L_0x0005;
L_0x0002:
r0.close(); Catch:{ IOException -> 0x0005 }
L_0x0005:
return;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v4.graphics.TypefaceCompatUtil.closeQuietly(java.io.Closeable):void");
}
}
|
package com.testFileUpload.pojo;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import java.io.Serializable;
@Data
@TableName(value = "user_role")
public class UserRole implements Serializable {
private int id;
private int uid;
private int rid;
}
|
/*
* 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.
*/
import java.util.UUID;
public class User {
private String id;
private String name;
private String email;
private String bizname;
private String website;
public User(String name, String email, String bizname, String website) {
//this.id = UUID.randomUUID().toString();
this.name = name;
this.email = email;
this.bizname = bizname;
this.website = website;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBizName() {
return bizname;
}
public void setBizName(String bizname) {
this.bizname = bizname;
}
public String website() {
return website;
}
public void website(String website) {
this.website = website;
}
}
|
package com.kheirallah.inc.strings;
//Easy
/*
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘, and ‘]’, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets
2. Open brackets must be closed in the correct order
Note that an empty string is also considered valid.
Example 1: Input: “()”
Output: true
Example 2: Input: “()[]{}”
Output: true
Example 3: Input: “(]”
Output: false
Example 4: Input: “([)]”
Output: false
Example 5: Input: “{[]}”
Output: true
*/
import java.util.Stack;
public class ValidParenthesis {
public static void main(String[] args) {
String input = "{()}";
System.out.println(isValidParenthesis(input));
}
//Time Complexity O(n)
//Space Complexity O(n), for new stack
//{[]}
//
private static boolean isValidParenthesis(String input) {
Stack<Character> characters = new Stack<>();
for (char c : input.toCharArray()) {
if (c == '{') {
characters.push('}');
} else if (c == '[') {
characters.push(']');
} else if (c == '(') {
characters.push(')');
} else if (characters.isEmpty() || characters.pop() != c) {
return false;
}
}
return characters.isEmpty();
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s): ActiveEon Team - http://www.activeeon.com
*
* ################################################################
* $$ACTIVEEON_CONTRIBUTOR$$
*/
package functionaltests.nodesource;
import java.io.File;
import java.net.InetAddress;
import java.net.URL;
import org.ow2.proactive.resourcemanager.common.event.RMEventType;
import org.ow2.proactive.resourcemanager.nodesource.infrastructure.GCMCustomisedInfrastructure;
import org.ow2.proactive.resourcemanager.nodesource.policy.TimeSlotPolicy;
import org.ow2.proactive.utils.FileToBytesConverter;
import functionaltests.RMTHelper;
/**
*
* Test checks the correct behavior of node source consisted of GCM infrastructure manager
* and time slot acquisition policy.
*
* This test may failed by timeout if the machine is too slow, so gcm deployment takes more than 15 secs
*
* NOTE: The way how customized GCM infrastructure is used here is not quite correct. It uses local host
* to deploy several nodes so it wont be able to remove them correctly one by one. But for the scenario
* in this test it's not required.
*
*/
public class TestGCMCustomizedInfrastructureTimeSlotPolicy extends TestLocalInfrastructureTimeSlotPolicy {
protected byte[] emptyGCMD;
protected byte[] GCMDeploymentData;
protected byte[] hostsListData;
/** timeout for node acquisition */
private static final int TIMEOUT = 60 * 1000;
@Override
protected void init() throws Exception {
URL oneNodeescriptor = TestGCMCustomizedInfrastructureTimeSlotPolicy.class
.getResource("/functionaltests/nodesource/1node.xml");
GCMDeploymentData = FileToBytesConverter.convertFileToByteArray((new File(oneNodeescriptor.toURI())));
URL emptyNodeDescriptor = TestGCMCustomizedInfrastructureTimeSlotPolicy.class
.getResource("/functionaltests/nodesource/empty_gcmd.xml");
emptyGCMD = FileToBytesConverter.convertFileToByteArray((new File(emptyNodeDescriptor.toURI())));
// overriding gcma file
RMTHelper.getResourceManager(new File(RMTHelper.class.getResource(
"/functionaltests/config/functionalTRMPropertiesForCustomisedIM.ini").toURI())
.getAbsolutePath());
hostsListData = InetAddress.getLocalHost().getHostName().getBytes();
}
@Override
protected void createEmptyNodeSource(String sourceName) throws Exception {
RMTHelper.getResourceManager().createNodeSource(
sourceName,
// first parameter of im is rm url, empty means default
GCMCustomisedInfrastructure.class.getName(),
new Object[] { "", emptyGCMD, hostsListData, TIMEOUT }, TimeSlotPolicy.class.getName(),
getPolicyParams());
RMTHelper.waitForNodeSourceEvent(RMEventType.NODESOURCE_CREATED, sourceName);
}
@Override
protected void createDefaultNodeSource(String sourceName) throws Exception {
// creating node source
RMTHelper.getResourceManager().createNodeSource(sourceName,
GCMCustomisedInfrastructure.class.getName(),
// first parameter of im is rm url, empty means default
new Object[] { "", GCMDeploymentData, hostsListData, TIMEOUT },
TimeSlotPolicy.class.getName(), getPolicyParams());
RMTHelper.waitForNodeSourceEvent(RMEventType.NODESOURCE_CREATED, sourceName);
for (int i = 0; i < descriptorNodeNumber; i++) {
//deploying node added
RMTHelper.waitForAnyNodeEvent(RMEventType.NODE_ADDED);
//deploying node removed
RMTHelper.waitForAnyNodeEvent(RMEventType.NODE_REMOVED);
//node added
RMTHelper.waitForAnyNodeEvent(RMEventType.NODE_ADDED);
//we eat the configuring to free event
RMTHelper.waitForAnyNodeEvent(RMEventType.NODE_STATE_CHANGED);
}
}
}
|
package news.model.business;
import java.util.List;
import javax.ejb.Local;
import news.model.NewsPortal;
@Local
public interface NewsPortalFacadeLocal {
public NewsPortal searchByArticle(String body);
public NewsPortal search(String title, String body);
public List<NewsPortal> getAllNews();
void create(NewsPortal newsPortal);
void edit(NewsPortal newsPortal);
void remove(NewsPortal newsPortal);
NewsPortal find(Object id);
List<NewsPortal> findAll();
List<NewsPortal> findRange(int[] range);
int count();
}
|
package com.base.widget.message;
import org.json.JSONObject;
import com.base.danmaku.DanmakuItem;
import com.base.danmaku.DanmakuView;
import com.base.danmaku.DanmakuView.OnItemClickListener;
import com.base.host.BaseFragment;
import com.base.http.ErrorCode;
import com.base.http.JSONResponse;
import com.heihei.dialog.UserDialog;
import com.heihei.fragment.live.widget.LiveBottom;
import com.heihei.logic.UserMgr;
import com.heihei.logic.present.LivePresent;
import com.heihei.model.LiveInfo;
import com.heihei.model.User;
import com.wmlives.heihei.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.view.ViewGroup;
public class DanmakuViewFragment extends BaseFragment implements OnClickListener {
private DanmakuView mDanmakuView;
private View fl_danmu_contentview;
private ImageView iv_live_righttip;
@Override
protected void loadContentView() {
setContentView(R.layout.fragment_information);
}
@Override
protected void viewDidLoad() {
fl_danmu_contentview = findViewById(R.id.fl_danmu_contentview);
fl_danmu_contentview.setVisibility(View.VISIBLE);
iv_live_righttip = (ImageView) findViewById(R.id.iv_live_righttip);
mDanmakuView = (DanmakuView) findViewById(R.id.danmakuview);
mDanmakuView.setVisibility(View.VISIBLE);
mDanmakuView.setOnClickListener(this);
mDanmakuView.setOnItemClickListener(mDanmakuItemClickListener);
}
private boolean isShow;
public void showhttip(boolean isShow) {
this.isShow = isShow;
}
@Override
protected void refresh() {
if (iv_live_righttip == null)
return;
if (isShow)
iv_live_righttip.setVisibility(View.VISIBLE);
else
iv_live_righttip.setVisibility(View.GONE);
}
private OnItemClickListener mDanmakuItemClickListener = new OnItemClickListener() {
@Override
public void OnItemClick(DanmakuItem item) {
if (item.type == DanmakuItem.TYPE_SYSTEM) {
return;
}
if (UserMgr.getInstance().getUid().equals(item.userId)) {
return;
}
User user = new User();
user.uid = item.userId;
user.nickname = item.userName;
user.gender = item.gender;
user.birthday = item.birthday;
if (mLiveInfo != null && UserMgr.getInstance().getUid().equals(mLiveInfo.creator.uid)) {
UserDialog ud = new UserDialog(getContext(), user, liveId, true, UserDialog.USERDIALOG_OPENTYPE_ANCHOR);
ud.show();
} else {
UserDialog ud = new UserDialog(getContext(), user, liveId, false, UserDialog.USERDIALOG_OPENTYPE_AUDIENCE);
ud.show();
}
}
@Override
public void onItemLongClick(DanmakuItem item) {
if (item.type == DanmakuItem.TYPE_SYSTEM) {
return;
}
if (UserMgr.getInstance().getUid().equals(item.userId)) {
return;
}
mLiveBottom.atUser(item.userName);
}
};
public void hintTtipView() {
if (iv_live_righttip != null)
iv_live_righttip.setVisibility(View.GONE);
}
public void setDanmakuPause() {
if (mDanmakuView != null)
mDanmakuView.pause();
}
public void setDanmakuResume() {
if (mDanmakuView != null)
mDanmakuView.resume();
}
public void setDanmakuStop() {
if (mDanmakuView != null)
mDanmakuView.stop();
}
public void putDanmakuItem(DanmakuItem item) {
if (mDanmakuView != null)
mDanmakuView.addDanmakuItem(item);
}
private LiveBottom mLiveBottom;
private String liveId;
private ScrollViewFragment mScrollViewFragment;
private LiveInfo mLiveInfo;
public void setLiveBottom(LiveBottom bottom, LiveInfo info, ScrollViewFragment mScrollViewFragment) {
this.mLiveBottom = bottom;
this.liveId = info.liveId;
this.mLiveInfo = info;
this.mScrollViewFragment = mScrollViewFragment;
}
private int likeCount = 0;
private long firstClickTime = 0l;
private int LIKE_TIME_INTERVAL = 5000;
private boolean hasOneLike = false;
private boolean hasTwoLike = false;
private boolean hasThreeLike = false;
public static final int LIKE_ONE = 1;// 点亮了
public static final int LIKE_AGAIN = 2;// 又点亮了
public static final int LIKE_AGAIN_AND_AGAIN = 3;// 疯狂的点亮
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.danmakuview:
if (mLiveBottom != null)
mLiveBottom.hideKeyboard();
long nowTime = System.currentTimeMillis();
if (nowTime - firstClickTime > 1000 * 60 * 5) {// 距离上一次点击超过5分钟了
firstClickTime = 0l;
hasOneLike = false;
hasTwoLike = false;
hasThreeLike = false;
}
if (firstClickTime == 0l)// 表示第一次点击
{
if (!hasOneLike) {
like(LIKE_ONE);
hasOneLike = true;
}
firstClickTime = nowTime;
likeCount++;
return;
}
if (nowTime - firstClickTime <= LIKE_TIME_INTERVAL) {
likeCount++;
if (likeCount == 3) {
if (!hasTwoLike) {
like(LIKE_AGAIN);
hasTwoLike = true;
}
} else if (likeCount == 14) {
if (!hasThreeLike) {
like(LIKE_AGAIN_AND_AGAIN);
hasThreeLike = true;
}
}
} else {
firstClickTime = nowTime;
likeCount = 0;
}
break;
}
}
/**
* 点亮
*/
private void like(final int type) {
mLivePresent.like(liveId, type, new JSONResponse() {
@Override
public void onJsonResponse(JSONObject json, int errCode, String msg, boolean cached) {
if (errCode == ErrorCode.ERROR_OK) {
DanmakuItem item = new DanmakuItem();
item.userName = UserMgr.getInstance().getLoginUser().nickname;
item.gender = UserMgr.getInstance().getLoginUser().gender;
item.birthday = UserMgr.getInstance().getLoginUser().birthday;
item.type = DanmakuItem.TYPE_LIKE;
item.userId = UserMgr.getInstance().getUid();
switch (type) {
case LIKE_ONE:
item.text = getString(R.string.like_one_tip);
break;
case LIKE_AGAIN:
item.text = getString(R.string.like_two_tip);
break;
case LIKE_AGAIN_AND_AGAIN:
item.text = getString(R.string.like_three_tip);
break;
}
putDanmakuItem(item);
mScrollViewFragment.updateSelfMessage(item);
}
}
});
}
private LivePresent mLivePresent = new LivePresent();
@Override
public String getCurrentFragmentName() {
// TODO Auto-generated method stub
return "DanmakuViewFragment";
}
}
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.neuron.mytelkom.fragment;
import android.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.neuron.mytelkom.adapter.MyTicketAdapter;
import com.neuron.mytelkom.base.BaseFragment;
import com.neuron.mytelkom.model.Ticket;
import com.neuron.mytelkom.utils.Preference;
import com.neuron.mytelkom.utils.Utils;
import java.util.LinkedList;
import org.apache.http.Header;
import org.json.JSONObject;
// Referenced classes of package com.neuron.mytelkom.fragment:
// DetilTicketFragment
public class MyTicketFragment extends BaseFragment
{
public static String FRAGMENT_TAG = "MyTicketFragment";
private String ProductName;
private ProgressBar indicator;
private LinkedList listItem;
private ListView lvItem;
private String tglDari;
private String tglHingga;
private TextView txtTitle;
public MyTicketFragment()
{
}
private void closeFragment()
{
FragmentTransaction fragmenttransaction = getFragmentManager().beginTransaction();
fragmenttransaction.remove(this);
fragmenttransaction.commit();
getFragmentManager().popBackStack();
}
public String getProductName()
{
return ProductName;
}
public String getTglDari()
{
return tglDari;
}
public String getTglHingga()
{
return tglHingga;
}
public void initializeActions()
{
super.initializeActions();
lvItem.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
final MyTicketFragment this$0;
public void onItemClick(AdapterView adapterview, View view, int i, long l)
{
toDetilTicket(i);
}
{
this$0 = MyTicketFragment.this;
super();
}
});
}
public void initializeLibs()
{
super.initializeLibs();
listItem = new LinkedList();
}
public void initializeRequest()
{
super.initializeRequest();
indicator.setVisibility(0);
lvItem.setVisibility(8);
try
{
JSONObject jsonobject = new JSONObject();
jsonobject.put("telkomID", preference.getUsername());
jsonobject.put("productType", getProductName());
jsonobject.put("dateStart", getTglDari());
jsonobject.put("dateEnd", getTglHingga());
String s = jsonobject.toString();
Utils.printLog(s);
RequestParams requestparams = new RequestParams();
requestparams.put("param", s);
asyncHttpClient.post("https://my.telkom.co.id/api/MobileMyTicket.php?api=", requestparams, new AsyncHttpResponseHandler() {
final MyTicketFragment this$0;
public void onFailure(int i, Header aheader[], byte abyte0[], Throwable throwable)
{
super.onFailure(i, aheader, abyte0, throwable);
lvItem.setVisibility(8);
indicator.setVisibility(8);
}
public void onSuccess(int i, Header aheader[], byte abyte0[])
{
super.onSuccess(i, aheader, abyte0);
lvItem.setVisibility(0);
indicator.setVisibility(8);
Utils.printLog(new String(abyte0));
listItem = Ticket.getListTicket(new String(abyte0));
if (listItem != null)
{
MyTicketAdapter myticketadapter = new MyTicketAdapter(getActivity(), listItem);
lvItem.setAdapter(myticketadapter);
return;
} else
{
txtTitle.setText("No data available");
return;
}
}
{
this$0 = MyTicketFragment.this;
super();
}
});
return;
}
catch (Exception exception)
{
return;
}
}
public void onActivityCreated(Bundle bundle)
{
super.onActivityCreated(bundle);
setToView();
initializeRequest();
initializeActions();
}
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
initializeLibs();
}
public void onCreateOptionsMenu(Menu menu, MenuInflater menuinflater)
{
super.onCreateOptionsMenu(menu, menuinflater);
menuinflater.inflate(0x7f090004, menu);
}
public View onCreateView(LayoutInflater layoutinflater, ViewGroup viewgroup, Bundle bundle)
{
View view = layoutinflater.inflate(0x7f03002a, viewgroup, false);
lvItem = (ListView)view.findViewById(0x7f0a00c3);
indicator = (ProgressBar)view.findViewById(0x7f0a0065);
txtTitle = (TextView)view.findViewById(0x7f0a00c2);
getActivity().getActionBar().setDisplayUseLogoEnabled(false);
getActivity().getActionBar().setDisplayShowHomeEnabled(true);
getActivity().getActionBar().setIcon(0x7f020045);
getActivity().getActionBar().setTitle("");
getActivity().getActionBar().setHomeButtonEnabled(true);
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
setHasOptionsMenu(true);
return view;
}
public boolean onOptionsItemSelected(MenuItem menuitem)
{
if (menuitem.getItemId() == 0x7f0a0100)
{
if (indicator.getVisibility() != 0)
{
initializeRequest();
}
return true;
}
if (menuitem.getItemId() == 0x102002c)
{
getActivity().finish();
return true;
} else
{
return super.onOptionsItemSelected(menuitem);
}
}
public void setProductName(String s)
{
ProductName = s;
}
public void setTglDari(String s)
{
tglDari = s;
}
public void setTglHingga(String s)
{
tglHingga = s;
}
public void setToView()
{
super.setToView();
txtTitle.setText((new StringBuilder("Dari : ")).append(getTglDari()).append(" hingga ").append(getTglHingga()).toString());
}
protected void toDetilTicket(int i)
{
DetilTicketFragment detilticketfragment = new DetilTicketFragment();
detilticketfragment.setTicket((Ticket)listItem.get(i));
FragmentTransaction fragmenttransaction = getFragmentManager().beginTransaction();
fragmenttransaction.hide((MyTicketFragment)getFragmentManager().findFragmentByTag(FRAGMENT_TAG));
fragmenttransaction.add(0x7f0a004c, detilticketfragment, DetilTicketFragment.FRAGMENT_TAG);
fragmenttransaction.addToBackStack(null);
fragmenttransaction.commit();
}
}
|
package com.skp.test.string;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Test;
public class AlphabetCountTest {
@Test
public void test() {
String strings = "strings";
AlphabetCount sut = new AlphabetCount(strings);
Map<String, Integer> result = sut.toMap();
assertEquals(2, result.get("s").intValue());
assertEquals(1, result.get("t").intValue());
assertEquals(1, result.get("r").intValue());
assertEquals(1, result.get("i").intValue());
assertEquals(1, result.get("n").intValue());
assertEquals(1, result.get("g").intValue());
Set<Entry<String, Integer>> entrySet = result.entrySet();
for (Entry<String, Integer> entry : entrySet) {
System.out.println(entry);
}
}
}
|
/*
* 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.core.test.tools;
import java.io.File;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link SourceFile}.
*
* @author Phillip Webb
* @author Scott Frederick
*/
class SourceFileTests {
private static final String HELLO_WORLD = """
package com.example.helloworld;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
""";
@Test
void ofWhenContentIsEmptyThrowsException() {
assertThatIllegalStateException().isThrownBy(() -> SourceFile.of("")).withMessage(
"WritableContent did not append any content");
}
@Test
void ofWhenSourceDefinesNoClassThrowsException() {
assertThatIllegalStateException().isThrownBy(
() -> SourceFile.of("package com.example;")).withMessageContaining(
"Unable to parse").havingCause().withMessage(
"Source must define a single class");
}
@Test
void ofWhenSourceDefinesMultipleClassesThrowsException() {
assertThatIllegalStateException().isThrownBy(() -> SourceFile.of(
"public class One {}\npublic class Two{}")).withMessageContaining(
"Unable to parse").havingCause().withMessage(
"Source must define a single class");
}
@Test
void ofWhenSourceCannotBeParsedThrowsException() {
assertThatIllegalStateException().isThrownBy(
() -> SourceFile.of("well this is broken {")).withMessageContaining(
"Unable to parse source file content");
}
@Test
void ofWithoutPathDeducesPath() {
SourceFile sourceFile = SourceFile.of(HELLO_WORLD);
assertThat(sourceFile.getPath()).isEqualTo(
"com/example/helloworld/HelloWorld.java");
}
@Test
void ofWithPathUsesPath() {
SourceFile sourceFile = SourceFile.of("com/example/DifferentPath.java",
HELLO_WORLD);
assertThat(sourceFile.getPath()).isEqualTo("com/example/DifferentPath.java");
}
@Test
void forClassWithClassUsesClass() {
SourceFile sourceFile = SourceFile.forClass(new File("src/test/java"), SourceFileTests.class);
assertThat(sourceFile.getPath()).isEqualTo("org/springframework/core/test/tools/SourceFileTests.java");
assertThat(sourceFile.getClassName()).isEqualTo("org.springframework.core.test.tools.SourceFileTests");
}
@Test
void forTestClassWithClassUsesClass() {
SourceFile sourceFile = SourceFile.forTestClass(SourceFileTests.class);
assertThat(sourceFile.getPath()).isEqualTo("org/springframework/core/test/tools/SourceFileTests.java");
assertThat(sourceFile.getClassName()).isEqualTo("org.springframework.core.test.tools.SourceFileTests");
}
@Test
void getContentReturnsContent() {
SourceFile sourceFile = SourceFile.of(HELLO_WORLD);
assertThat(sourceFile.getContent()).isEqualTo(HELLO_WORLD);
}
@Test
@SuppressWarnings("deprecation")
void assertThatReturnsAssert() {
SourceFile sourceFile = SourceFile.of(HELLO_WORLD);
assertThat(sourceFile.assertThat()).isInstanceOf(SourceFileAssert.class);
}
@Test
void createFromJavaPoetStyleApi() {
JavaFile javaFile = new JavaFile(HELLO_WORLD);
SourceFile sourceFile = SourceFile.of(javaFile::writeTo);
assertThat(sourceFile.getContent()).isEqualTo(HELLO_WORLD);
}
@Test
void getClassNameFromSimpleRecord() {
SourceFile sourceFile = SourceFile.of("""
package com.example.helloworld;
record HelloWorld(String name) {
}
""");
assertThat(sourceFile.getClassName()).isEqualTo("com.example.helloworld.HelloWorld");
}
@Test
void getClassNameFromMoreComplexRecord() {
SourceFile sourceFile = SourceFile.of("""
package com.example.helloworld;
public record HelloWorld(String name) {
String getFoo() {
return name();
}
}
""");
assertThat(sourceFile.getClassName()).isEqualTo("com.example.helloworld.HelloWorld");
}
@Test
void getClassNameFromAnnotatedRecord() {
SourceFile sourceFile = SourceFile.of("""
package com.example;
public record RecordProperties(
@org.springframework.lang.NonNull("test") String property1,
@org.springframework.lang.NonNull("test") String property2) {
}
""");
assertThat(sourceFile.getClassName()).isEqualTo("com.example.RecordProperties");
}
/**
* JavaPoet style API with a {@code writeTo} method.
*/
static class JavaFile {
private final String content;
JavaFile(String content) {
this.content = content;
}
void writeTo(Appendable out) throws IOException {
out.append(this.content);
}
}
}
|
/*
* Copyright (C) 2014 Vasilis Vryniotis <bbriniotis at datumbox.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.datumbox.common.dataobjects;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
*
* @author bbriniotis
*/
public final class TransposeDataCollection extends DataStructureMap<Map<Object, FlatDataCollection>> {
public TransposeDataCollection() {
internalData = new HashMap<>();
}
public TransposeDataCollection(Map<Object, FlatDataCollection> internalData) {
super(internalData);
}
public final FlatDataCollection remove(Object key) {
return internalData.remove(key);
}
public final FlatDataCollection get(Object key) {
return internalData.get(key);
}
public final FlatDataCollection put(Object key, FlatDataCollection value) {
return internalData.put(key, value);
}
public final Set<Map.Entry<Object, FlatDataCollection>> entrySet() {
return internalData.entrySet();
}
public final Set<Object> keySet() {
return internalData.keySet();
}
public final Collection<FlatDataCollection> values() {
return internalData.values();
}
@Override
public boolean equals(Object o) {
if ( this == o ) return true;
if ( !(o instanceof TransposeDataCollection) ) return false;
/*
TransposeDataCollection otherObject = ((TransposeDataCollection)o);
if(internalData.size() != otherObject.internalData.size()) {
return false;
}
//first ensure that the keys are the same. IMPORTANT: we ignore order since we use sets here
if(internalData.keySet().equals(otherObject.internalData.keySet())==false) {
return false;
}
//now compare the FlatDataCollections if they are equal
for(Object key : internalData.keySet()) {
if(internalData.get(key).equals(otherObject.internalData.get(key))==false) {
return false;
}
}
return true;
*/
return internalData.equals(((TransposeDataCollection)o).internalData);
}
@Override
public int hashCode() {
return internalData.hashCode();
}
}
|
package exercicio02;
import exercicio01.Lampada;
public class LampadaFlouro extends Lampada
{
private int cnt;
LampadaFlouro(int valorAjuste, int watss, int cnt)
{
super(valorAjuste, watss);
this.cnt=cnt;
// TODO Auto-generated constructor stub
}
}
|
package com.junyoung.searchwheretogoapi.filter;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import com.junyoung.searchwheretogoapi.model.data.User;
import com.junyoung.searchwheretogoapi.repository.UserRepository;
import com.junyoung.searchwheretogoapi.service.auth.JwtService;
import com.junyoung.searchwheretogoapi.util.TestDataUtil;
import java.io.IOException;
import java.util.Optional;
import javax.servlet.ServletException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
@SpringBootTest
class JwtTokenFilterTest {
@MockBean private UserRepository userRepository;
@MockBean private JwtService jwtService;
@Autowired private JwtTokenFilter jwtTokenFilter;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockFilterChain filterChain;
@BeforeEach
void setUp() {
SecurityContextHolder.getContext().setAuthentication(null);
given(jwtService.getUserIdFromToken(anyString()))
.willReturn(Optional.of(TestDataUtil.createToken()));
given(userRepository.findById(anyString())).willReturn(Optional.of(TestDataUtil.createUser()));
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
filterChain = new MockFilterChain();
}
@Test
void test_authenticated_user_filtering() throws ServletException, IOException {
request.addHeader(HttpHeaders.AUTHORIZATION, TestDataUtil.createToken());
jwtTokenFilter.doFilterInternal(request, response, filterChain);
UsernamePasswordAuthenticationToken authenticationToken =
(UsernamePasswordAuthenticationToken)
SecurityContextHolder.getContext().getAuthentication();
assertTrue(authenticationToken.getPrincipal() instanceof User);
}
@Test
void test_unauthorized_user_empty_auth_header() throws ServletException, IOException {
jwtTokenFilter.doFilterInternal(request, response, filterChain);
UsernamePasswordAuthenticationToken authenticationToken =
(UsernamePasswordAuthenticationToken)
SecurityContextHolder.getContext().getAuthentication();
assertNull(authenticationToken);
}
@Test
void test_unauthorized_user_wrong_token() throws ServletException, IOException {
request.addHeader(HttpHeaders.AUTHORIZATION, "wrong_token");
jwtTokenFilter.doFilterInternal(request, response, filterChain);
UsernamePasswordAuthenticationToken authenticationToken =
(UsernamePasswordAuthenticationToken)
SecurityContextHolder.getContext().getAuthentication();
assertNull(authenticationToken);
}
}
|
package com.example.gauravbharti.garagebluetooth;
import android.content.Context;
import android.content.SharedPreferences;
import org.json.JSONArray;
/**
* Created by gauravbharti on 09/03/17.
*/
public class SessionManager
{ SharedPreferences.Editor editor;
SharedPreferences pref;
Context _context;
int PRIVATE_MODE=0;
private static final String PREF_NAME = "Garage";
public static final String name="name";
public static final String address="address";
public SessionManager(Context context)
{
this._context=context;
pref=_context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
editor=pref.edit();
}
public void add_details(JSONArray jsonArray)
{
}
public void get_details()
{
}
}
|
package en05;
/**
* Created by C0116289 on 2017/05/15.
*/
public class Ex01 {
public static void main(String[] args) {
String istr="School of Computer Science.";
String ostr;
ostr = istr.replaceAll("oo","-");
System.out.println(ostr);
ostr= istr.replaceAll("[o ]","*");
System.out.println(ostr);
ostr= istr.replaceAll("\\.","?");
System.out.println(ostr);
String istr2="[30/Apr/2014:21:37:38 +0900] GET /favicon.ico HTTP/1.1";
ostr=istr2.replaceAll("\\d","");
System.out.println(ostr);
ostr=istr2.replaceAll("[\\w/]","?");
System.out.println(ostr);
ostr= istr2.replaceAll("\\s.","--");
System.out.println(ostr);
String istr3="ac, abc, abbc, abbbc, abbbbc, abbbbbc";
ostr=istr3.replaceAll(".+c","@");
System.out.println(ostr);
ostr=istr3.replaceAll(".+?c","#");
System.out.println(ostr);
String istr4=" Hello!! Hello!!";
ostr=istr4.replaceAll("^ ","");
System.out.println(ostr);
ostr=istr4.replaceAll("$Hello!!","World ");
System.out.println(ostr);
}
}
|
/*
* 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.expression.spel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.testresources.Inventor;
import org.springframework.expression.spel.testresources.Person;
import org.springframework.expression.spel.testresources.RecordPerson;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Unit tests for property access.
*
* @author Andy Clement
* @author Juergen Hoeller
* @author Joyce Zhan
* @author Sam Brannen
*/
public class PropertyAccessTests extends AbstractExpressionTests {
@Test
void simpleAccess01() {
evaluate("name", "Nikola Tesla", String.class);
}
@Test
void simpleAccess02() {
evaluate("placeOfBirth.city", "SmilJan", String.class);
}
@Test
void simpleAccess03() {
evaluate("stringArrayOfThreeItems.length", "3", Integer.class);
}
@Test
void nonExistentPropertiesAndMethods() {
// madeup does not exist as a property
evaluateAndCheckError("madeup", SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE, 0);
// name is ok but foobar does not exist:
evaluateAndCheckError("name.foobar", SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE, 5);
}
/**
* The standard reflection resolver cannot find properties on null objects but some
* supplied resolver might be able to - so null shouldn't crash the reflection resolver.
*/
@Test
void accessingOnNullObject() {
SpelExpression expr = (SpelExpression) parser.parseExpression("madeup");
EvaluationContext context = new StandardEvaluationContext(null);
assertThatExceptionOfType(SpelEvaluationException.class)
.isThrownBy(() -> expr.getValue(context))
.extracting(SpelEvaluationException::getMessageCode).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL);
assertThat(expr.isWritable(context)).isFalse();
assertThatExceptionOfType(SpelEvaluationException.class)
.isThrownBy(() -> expr.setValue(context, "abc"))
.extracting(SpelEvaluationException::getMessageCode).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL);
}
@Test
// Adding a new property accessor just for a particular type
void addingSpecificPropertyAccessor() {
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
// Even though this property accessor is added after the reflection one, it specifically
// names the String class as the type it is interested in so is chosen in preference to
// any 'default' ones
ctx.addPropertyAccessor(new StringyPropertyAccessor());
Expression expr = parser.parseRaw("new String('hello').flibbles");
Integer i = expr.getValue(ctx, Integer.class);
assertThat((int) i).isEqualTo(7);
// The reflection one will be used for other properties...
expr = parser.parseRaw("new String('hello').CASE_INSENSITIVE_ORDER");
Object o = expr.getValue(ctx);
assertThat(o).isNotNull();
SpelExpression flibbleexpr = parser.parseRaw("new String('hello').flibbles");
flibbleexpr.setValue(ctx, 99);
i = flibbleexpr.getValue(ctx, Integer.class);
assertThat((int) i).isEqualTo(99);
// Cannot set it to a string value
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
flibbleexpr.setValue(ctx, "not allowed"));
// message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property
// 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String''
// System.out.println(e.getMessage());
}
@Test
void addingAndRemovingAccessors() {
StandardEvaluationContext ctx = new StandardEvaluationContext();
// reflective property accessor is the only one by default
assertThat(ctx.getPropertyAccessors()).hasSize(1);
StringyPropertyAccessor spa = new StringyPropertyAccessor();
ctx.addPropertyAccessor(spa);
assertThat(ctx.getPropertyAccessors()).hasSize(2);
List<PropertyAccessor> copy = new ArrayList<>(ctx.getPropertyAccessors());
assertThat(ctx.removePropertyAccessor(spa)).isTrue();
assertThat(ctx.removePropertyAccessor(spa)).isFalse();
assertThat(ctx.getPropertyAccessors()).hasSize(1);
ctx.setPropertyAccessors(copy);
assertThat(ctx.getPropertyAccessors()).hasSize(2);
}
@Test
void accessingPropertyOfClass() {
Expression expression = parser.parseExpression("name");
Object value = expression.getValue(new StandardEvaluationContext(String.class));
assertThat(value).isEqualTo("java.lang.String");
}
@Test
void shouldAlwaysUsePropertyAccessorFromEvaluationContext() {
SpelExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("name");
StandardEvaluationContext context = new StandardEvaluationContext();
context.addPropertyAccessor(new ConfigurablePropertyAccessor(Collections.singletonMap("name", "Ollie")));
assertThat(expression.getValue(context)).isEqualTo("Ollie");
context = new StandardEvaluationContext();
context.addPropertyAccessor(new ConfigurablePropertyAccessor(Collections.singletonMap("name", "Jens")));
assertThat(expression.getValue(context)).isEqualTo("Jens");
}
@Test
void standardGetClassAccess() {
assertThat(parser.parseExpression("'a'.class.name").getValue()).isEqualTo(String.class.getName());
}
@Test
void noGetClassAccess() {
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
parser.parseExpression("'a'.class.name").getValue(context));
}
@Test
void propertyReadOnly() {
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
Expression expr = parser.parseExpression("name");
Person target = new Person("p1");
assertThat(expr.getValue(context, target)).isEqualTo("p1");
target.setName("p2");
assertThat(expr.getValue(context, target)).isEqualTo("p2");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
parser.parseExpression("name='p3'").getValue(context, target));
}
@Test
void propertyReadOnlyWithRecordStyle() {
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
Expression expr = parser.parseExpression("name");
RecordPerson target1 = new RecordPerson("p1");
assertThat(expr.getValue(context, target1)).isEqualTo("p1");
RecordPerson target2 = new RecordPerson("p2");
assertThat(expr.getValue(context, target2)).isEqualTo("p2");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
parser.parseExpression("name='p3'").getValue(context, target2));
}
@Test
void propertyReadWrite() {
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
Expression expr = parser.parseExpression("name");
Person target = new Person("p1");
assertThat(expr.getValue(context, target)).isEqualTo("p1");
target.setName("p2");
assertThat(expr.getValue(context, target)).isEqualTo("p2");
parser.parseExpression("name='p3'").getValue(context, target);
assertThat(target.getName()).isEqualTo("p3");
assertThat(expr.getValue(context, target)).isEqualTo("p3");
expr.setValue(context, target, "p4");
assertThat(target.getName()).isEqualTo("p4");
assertThat(expr.getValue(context, target)).isEqualTo("p4");
}
@Test
void propertyReadWriteWithRootObject() {
Person rootObject = new Person("p1");
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().withRootObject(rootObject).build();
assertThat(context.getRootObject().getValue()).isSameAs(rootObject);
Expression expr = parser.parseExpression("name");
assertThat(expr.getValue(context)).isEqualTo("p1");
rootObject.setName("p2");
assertThat(expr.getValue(context)).isEqualTo("p2");
parser.parseExpression("name='p3'").getValue(context, rootObject);
assertThat(rootObject.getName()).isEqualTo("p3");
assertThat(expr.getValue(context)).isEqualTo("p3");
expr.setValue(context, "p4");
assertThat(rootObject.getName()).isEqualTo("p4");
assertThat(expr.getValue(context)).isEqualTo("p4");
}
@Test
void propertyAccessWithoutMethodResolver() {
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
Person target = new Person("p1");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
parser.parseExpression("name.substring(1)").getValue(context, target));
}
@Test
void propertyAccessWithInstanceMethodResolver() {
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().withInstanceMethods().build();
Person target = new Person("p1");
assertThat(parser.parseExpression("name.substring(1)").getValue(context, target)).isEqualTo("1");
}
@Test
void propertyAccessWithInstanceMethodResolverAndTypedRootObject() {
Person rootObject = new Person("p1");
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().
withInstanceMethods().withTypedRootObject(rootObject, TypeDescriptor.valueOf(Object.class)).build();
assertThat(parser.parseExpression("name.substring(1)").getValue(context)).isEqualTo("1");
assertThat(context.getRootObject().getValue()).isSameAs(rootObject);
assertThat(context.getRootObject().getTypeDescriptor().getType()).isSameAs(Object.class);
}
@Test
void propertyAccessWithArrayIndexOutOfBounds() {
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
Expression expression = parser.parseExpression("stringArrayOfThreeItems[3]");
assertThatExceptionOfType(SpelEvaluationException.class)
.isThrownBy(() -> expression.getValue(context, new Inventor()))
.extracting(SpelEvaluationException::getMessageCode).isEqualTo(SpelMessage.ARRAY_INDEX_OUT_OF_BOUNDS);
}
// This can resolve the property 'flibbles' on any String (very useful...)
private static class StringyPropertyAccessor implements PropertyAccessor {
int flibbles = 7;
@Override
public Class<?>[] getSpecificTargetClasses() {
return new Class<?>[] {String.class};
}
@Override
public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
if (!(target instanceof String)) {
throw new RuntimeException("Assertion Failed! target should be String");
}
return (name.equals("flibbles"));
}
@Override
public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
if (!(target instanceof String)) {
throw new RuntimeException("Assertion Failed! target should be String");
}
return (name.equals("flibbles"));
}
@Override
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
if (!name.equals("flibbles")) {
throw new RuntimeException("Assertion Failed! name should be flibbles");
}
return new TypedValue(flibbles);
}
@Override
public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException {
if (!name.equals("flibbles")) {
throw new RuntimeException("Assertion Failed! name should be flibbles");
}
try {
flibbles = (Integer) context.getTypeConverter().convertValue(newValue,
TypeDescriptor.forObject(newValue), TypeDescriptor.valueOf(Integer.class));
}
catch (EvaluationException ex) {
throw new AccessException("Cannot set flibbles to an object of type '" + newValue.getClass() + "'");
}
}
}
private static class ConfigurablePropertyAccessor implements PropertyAccessor {
private final Map<String, Object> values;
ConfigurablePropertyAccessor(Map<String, Object> values) {
this.values = values;
}
@Override
public Class<?>[] getSpecificTargetClasses() {
return null;
}
@Override
public boolean canRead(EvaluationContext context, Object target, String name) {
return true;
}
@Override
public TypedValue read(EvaluationContext context, Object target, String name) {
return new TypedValue(this.values.get(name));
}
@Override
public boolean canWrite(EvaluationContext context, Object target, String name) {
return false;
}
@Override
public void write(EvaluationContext context, Object target, String name, Object newValue) {
}
}
}
|
package fr.unice.polytech.isa.polyevent;
import fr.unice.polytech.isa.polyevent.entities.DemandePrestataire;
import fr.unice.polytech.isa.polyevent.entities.Evenement;
import fr.unice.polytech.isa.polyevent.entities.Prestataire;
import fr.unice.polytech.isa.polyevent.entities.Prestation;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;
@Stateless
public class DemandePrestation implements DemanderPrestation {
@EJB
private EnvoyerMail envoyerMail;
@PersistenceContext
EntityManager entityManager;
@Override
public boolean ajouterService(Evenement evenement, List<DemandePrestataire> demandePrestataires) {
for (DemandePrestataire demandePrestataire: demandePrestataires) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Prestataire> criteria = builder.createQuery(Prestataire.class);
Root<Prestataire> root = criteria.from(Prestataire.class);
criteria.select(root).where(builder.equal(root.get("typeService"), demandePrestataire.getTypeService()));
TypedQuery<Prestataire> query = entityManager.createQuery(criteria);
Prestataire prestataire;
List<Prestataire> prestataires = query.getResultList();
if (prestataires.isEmpty())
return false;
prestataire = prestataires.get(0);
envoyerMail.envoieMail(prestataire, demandePrestataire.getDateDebut(), demandePrestataire.getDateFin(), evenement);
Prestation prestation = new Prestation(demandePrestataire.getDateDebut(), demandePrestataire.getDateFin(), prestataire, evenement);
entityManager.persist(prestation);
prestataire.getPrestations().add(prestation);
}
return true;
}
}
|
public class BuyAndSellStock1 {
// public static int maxProfit(int[] prices) {
//
// int n = prices.length;
//
// int max = 0;
// for(int i = 0; i < n; i++){
// for(int j = i+1; j < n; j++){
// if (prices[j] - prices[i] >0 && prices[j]-prices[i]> max)
// max = prices[j] - prices[i];
// }
// }
//
// return max;
// }
public static int maxProfit(int[] prices) {
int n = prices.length;
int minPrice = Integer.MAX_VALUE;
int maxprofit = 0;
for (int i = 0; i < n; i++) {
if (prices[i] < minPrice)
minPrice = prices[i];
else if (prices[i] - minPrice > maxprofit)
maxprofit = prices[i] - minPrice;
}
return maxprofit;
}
public static void main(String args[]) {
}
}
|
package sample;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;
import java.util.*;
public class indexController extends Main implements Initializable {
@FXML
private ComboBox<String> playerCombobox = new ComboBox<String>();
ObservableList<String> list = FXCollections.observableArrayList();
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
playerCombobox.setItems(list);
}
// Event listener for combobox: playerid
public void gettingValue(){
}
Connection connection = null;
ResultSet resultSet = null;
String query;
String q;
{
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment?autoReconnect=true&useSSL=false", "root", "");
Statement statement = connection.createStatement();
//Statement stmt = connection.createStatement();
query = "SELECT * FROM player";
// int value = Integer.parseInt(this.playerCombobox.getSelectionModel().getSelectedItem());
// q = "Select * from player WHERE player_id = value";
resultSet = statement.executeQuery(query);
// ResultSet rs = stmt.executeQuery(q);
while (resultSet.next()) {
list.add(resultSet.getString("player_id"));
playerCombobox.getItems().addAll(list);
}
}
catch(SQLException exception)
{
exception.printStackTrace();
}
}
// Events of buttons...
public void ProfileClickAction(ActionEvent actionEvent) throws IOException {
CreateNewProfile createNewProfile = new CreateNewProfile();
createNewProfile.testingMethod();
}
public void DisplaydataAction(ActionEvent actionEvent) throws IOException {
// ShowData showData = new ShowData();
// showData.DisplayData();
try {
//
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment?autoReconnect=true&useSSL=false", "root", "");
int value = Integer.parseInt(this.playerCombobox.getSelectionModel().getSelectedItem());
q = "Select * from player WHERE player_id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(q);
preparedStatement.setInt(1 , value);
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()){
System.out.println("Player Id: " +rs.getInt("player_id") + "-" +
"First Name: " + rs.getString("first_name") + "-" +
"Last Name: " + rs.getString("last_name") + "-" +
"Address: " + rs.getString("address") + " - " +
"Postal code: " + rs.getString("postal_code") + "-" +
"Province: " + rs.getString("province") +"-" +
"phone Number:" +rs.getString("phone_number"));
Parent displayplayers = FXMLLoader.load(getClass().getResource("ShowData.fxml"));
Stage displayStage = new Stage();
displayStage.setTitle("Show player Data");
VBox layout = new VBox();
displayStage.setScene(new Scene(layout, 300,300));
Label idLabel = new Label("Player Id: " +rs.getInt("player_id"));
Label fnameLabel = new Label("First Name: " + rs.getString("first_name"));
Label lnameLabel = new Label("Last Name: " + rs.getString("last_name"));
Label addressLabel = new Label("Address: " + rs.getString("address"));
Label postalcodeLabel = new Label("Postal code: " + rs.getString("postal_code"));
Label provinceLabel = new Label("Province: " + rs.getString("province"));
Label contactNumberLabel = new Label("Contact Number: " + rs.getString("phone_number"));
layout.getChildren().addAll(idLabel, fnameLabel,lnameLabel,addressLabel,postalcodeLabel,provinceLabel,contactNumberLabel);
displayStage.showAndWait();
}
}
catch (SQLException e){
e.printStackTrace();
}
}
public void UpdateButtonAction(ActionEvent actionEvent) throws IOException {
EditData edit = new EditData();
edit.Editfields();
}
} |
import java.util.*;
class subpalindrome
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter l and n");
int l=sc.nextInt();
int m=sc.nextInt();
System.out.println("Enter string");
String s=sc.next();
if(s.length()==l)
{
String arr[][]=new String[m][3];
System.out.println("Enter operations");
for(int i=0;i<m;i++)
{
for(int j=0;j<3;j++)
{
arr[i][j]=sc.next();
}
}
for(int i=0;i<m;i++)
{
int a=Integer.parseInt(arr[i][1]);
if(Integer.parseInt(arr[i][0])==1)
{
s=s.replaceFirst(Character.toString(s.charAt(a-1)),arr[i][2]);
System.out.println(s);
}
else if(Integer.parseInt(arr[i][0])==2)
{
int b=Integer.parseInt(arr[i][2]);
String check="";
for(int j=a-1;j<b;j++)
{
check=check+s.charAt(j);
}
String reverse="";
for(int j=b-1;j>=a-1;j--)
{
reverse=reverse+s.charAt(j);
}
if(check.equalsIgnoreCase(reverse)==true)
{
System.out.println(check);
System.out.println("YES");
}
else
System.out.println("NO");
}
}
}
else
System.out.println("WRONG INPUT STRING");
}
}
|
/* Compilatudo.java */
/* Generated By:JavaCC: Do not edit this line. Compilatudo.java */
package CCompiler;
import java.io.*;
import java.util.Scanner;
import recovery.*;
public class Compilatudo implements CompilatudoConstants {
public static boolean debug_messages = true;
public static boolean debug_recovery = true;
int countParseError = 0;
public static void main(String[] args) throws ParseException {
Scanner scan = new Scanner(System.in);
String nome_arquivo;
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
System.out.println("Entre com o nome do Arquivo ");
Compilatudo parser = null;
// nome_arquivo = scan.nextLine();
nome_arquivo = "entrada.c";
try {
parser = new Compilatudo(new java.io.FileInputStream(nome_arquivo));
} catch(java.io.FileNotFoundException e) {
if(debug_messages)
System.out.println(e.getMessage());
}
try {
if (parser != null) {
parser.program();
}
}
catch(ParseEOFException e) {
System.out.println(e.getMessage());
} finally {
if (parser != null && debug_messages) {
if(parser.token_source.foundLexError() != 0) {
System.out.println("Total de erros lexicos: " + parser.token_source.foundLexError());
} else {
System.out.println("Sem erros lexicos!");
}
if(parser.countParseError != 0) {
System.out.println("Total de erros sintaticos: " + parser.countParseError);
} else {
System.out.println("Sem erros sintaticos!");
}
}
}
scan.close();
}
static public String im(int x) {
int k;
String s;
s = tokenImage[x];
k = s.lastIndexOf("\"");
try {
s = s.substring(1, k);
} catch(StringIndexOutOfBoundsException e) {
if(debug_messages)
System.out.println(e.getMessage());
}
return s;
}
boolean eof = false;
void consumeUntil(RecoverySet g, ParseException e, String met) throws ParseEOFException, ParseException {
Token tok;
if (debug_recovery) { // informa????o sobre a recupera????o
System.out.println();
System.out.println("***" + met + "***");
System.out.println( " sincronizando conjunto: " + g);
}
if (g == null) throw e; // se o conjunto for nulo, propaga a exce????o
tok = getToken(1); // pega o token corrente
while (!eof) {// se n??o chegou ao fim do arquivo
if(g.contains(tok.kind) ) {// achou o token conjunto
if (debug_recovery)
System.out.println ("\tAchou o token de sincroniza\ufffd\ufffd\ufffd\ufffdo : " + im(tok.kind));
break;
}
if (debug_recovery)
System.out.println(" ignorando token : " + im(tok.kind));
getNextToken();
tok = getToken(1);
if (debug_recovery)
System.out.println(" token atual : " + im(tok.kind));
if (tok.kind == EOF && g.contains(EOF)) // fim da entrada
eof = true;
}
if(debug_messages)
System.out.println(e.getMessage());
countParseError++; // incrementa o numero de erros
if (eof) throw new ParseEOFException("EOF achado prematuramente.");
}
final public void program() throws ParseException, ParseEOFException { try {
RecoverySet g = First.program;
try {
label_1:
while (true) {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case INT:
case FLOAT:
case VOID:
case CHAR:
case DOUBLE:
case HASHTAG:{
;
break;
}
default:
jj_la1[0] = jj_gen;
break label_1;
}
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case HASHTAG:{
preprocessor(g);
break;
}
default:
jj_la1[1] = jj_gen;
if (jj_2_1(3)) {
func_decl();
} else {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case INT:
case FLOAT:
case CHAR:
case DOUBLE:{
var_decl();
break;
}
default:
jj_la1[2] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
}
}
jj_consume_token(0);
} catch (ParseException e) {
consumeUntil(g, e, "program");
}
} finally {
trace_return("program");
}
}
final public void preprocessor(RecoverySet g) throws ParseException, ParseEOFException { try {
try {
if (jj_2_2(3)) {
jj_consume_token(HASHTAG);
jj_consume_token(INCLUDE);
jj_consume_token(LT);
jj_consume_token(ID);
jj_consume_token(DOT);
jj_consume_token(ID);
jj_consume_token(GT);
} else if (jj_2_3(3)) {
jj_consume_token(HASHTAG);
jj_consume_token(INCLUDE);
jj_consume_token(70);
jj_consume_token(ID);
jj_consume_token(DOT);
jj_consume_token(ID);
jj_consume_token(70);
} else if (jj_2_4(2)) {
jj_consume_token(HASHTAG);
jj_consume_token(DEFINE);
jj_consume_token(ID);
jj_consume_token(ID);
} else {
jj_consume_token(-1);
throw new ParseException();
}
} catch (ParseException e) {
consumeUntil(g, e, "preprocessor");
} finally {
System.out.print("}");
}
} finally {
trace_return("preprocessor");
}
}
final public void func_decl() throws ParseException { try {
func_type();
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case ID:{
jj_consume_token(ID);
break;
}
case MAIN:{
jj_consume_token(MAIN);
break;
}
default:
jj_la1[3] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
jj_consume_token(LPAREN);
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case INT:
case FLOAT:
case CHAR:
case DOUBLE:{
parameter_list();
break;
}
default:
jj_la1[4] = jj_gen;
;
}
jj_consume_token(RPAREN);
jj_consume_token(LBRACE);
body();
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case RETURN:{
return_val();
break;
}
default:
jj_la1[5] = jj_gen;
;
}
jj_consume_token(RBRACE);
} finally {
trace_return("func_decl");
}
}
final public void func_type() throws ParseException { try {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case INT:{
jj_consume_token(INT);
break;
}
case DOUBLE:{
jj_consume_token(DOUBLE);
break;
}
case CHAR:{
jj_consume_token(CHAR);
break;
}
case FLOAT:{
jj_consume_token(FLOAT);
break;
}
case VOID:{
jj_consume_token(VOID);
break;
}
default:
jj_la1[6] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} finally {
trace_return("func_type");
}
}
final public void parameter_list() throws ParseException { try {
var_type();
jj_consume_token(ID);
label_2:
while (true) {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case COMMA:{
;
break;
}
default:
jj_la1[7] = jj_gen;
break label_2;
}
jj_consume_token(COMMA);
var_type();
jj_consume_token(ID);
}
} finally {
trace_return("parameter_list");
}
}
final public void body() throws ParseException { try {
label_3:
while (true) {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case INT:
case IF:
case FLOAT:
case WHILE:
case CHAR:
case FOR:
case DOUBLE:
case PLUS:
case MINUS:
case INC:
case DEC:
case LPAREN:
case int_constant:
case float_constant:
case char_constant:
case string_constant:
case ID:{
;
break;
}
default:
jj_la1[8] = jj_gen;
break label_3;
}
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case INT:
case FLOAT:
case CHAR:
case DOUBLE:{
decl();
break;
}
case PLUS:
case MINUS:
case INC:
case DEC:
case LPAREN:
case int_constant:
case float_constant:
case char_constant:
case string_constant:
case ID:{
comando();
break;
}
case IF:
case WHILE:
case FOR:{
desvio();
break;
}
default:
jj_la1[9] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
} finally {
trace_return("body");
}
}
final public void decl() throws ParseException { try {
var_decl();
} finally {
trace_return("decl");
}
}
final public void comando() throws ParseException { try {
expr_value();
jj_consume_token(SEMICOLON);
} finally {
trace_return("comando");
}
}
final public void desvio() throws ParseException { try {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case IF:{
if_cond();
break;
}
case WHILE:{
while_cond();
break;
}
case FOR:{
for_cond();
break;
}
default:
jj_la1[10] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} finally {
trace_return("desvio");
}
}
final public void var_attr() throws ParseException { try {
jj_consume_token(ID);
jj_consume_token(ASSIGN);
expr_value();
} finally {
trace_return("var_attr");
}
}
final public void func_call() throws ParseException { try {
jj_consume_token(ID);
jj_consume_token(LPAREN);
expr_list();
jj_consume_token(RPAREN);
} finally {
trace_return("func_call");
}
}
final public void expr_list() throws ParseException { try {
expr_value();
label_4:
while (true) {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case COMMA:{
;
break;
}
default:
jj_la1[11] = jj_gen;
break label_4;
}
jj_consume_token(COMMA);
expr_value();
}
} finally {
trace_return("expr_list");
}
}
final public void var_type() throws ParseException { try {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case INT:{
jj_consume_token(INT);
break;
}
case DOUBLE:{
jj_consume_token(DOUBLE);
break;
}
case CHAR:{
jj_consume_token(CHAR);
break;
}
case FLOAT:{
jj_consume_token(FLOAT);
break;
}
default:
jj_la1[12] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} finally {
trace_return("var_type");
}
}
final public void while_cond() throws ParseException { try {
jj_consume_token(WHILE);
jj_consume_token(LPAREN);
expr_value();
jj_consume_token(RPAREN);
jj_consume_token(LBRACE);
body();
jj_consume_token(RBRACE);
} finally {
trace_return("while_cond");
}
}
final public void for_cond() throws ParseException { try {
jj_consume_token(FOR);
jj_consume_token(LPAREN);
expr_list();
jj_consume_token(SEMICOLON);
expr_list();
jj_consume_token(SEMICOLON);
expr_list();
jj_consume_token(RPAREN);
jj_consume_token(LBRACE);
body();
jj_consume_token(RBRACE);
} finally {
trace_return("for_cond");
}
}
final public void num_const() throws ParseException { try {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case PLUS:
case MINUS:{
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case PLUS:{
jj_consume_token(PLUS);
break;
}
case MINUS:{
jj_consume_token(MINUS);
break;
}
default:
jj_la1[13] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
}
default:
jj_la1[14] = jj_gen;
;
}
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case int_constant:{
jj_consume_token(int_constant);
break;
}
case float_constant:{
jj_consume_token(float_constant);
break;
}
case char_constant:{
jj_consume_token(char_constant);
break;
}
default:
jj_la1[15] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} finally {
trace_return("num_const");
}
}
final public void expr_value() throws ParseException { try {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case INC:
case DEC:{
unary_operator();
break;
}
default:
jj_la1[16] = jj_gen;
;
}
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case PLUS:
case MINUS:
case int_constant:
case float_constant:
case char_constant:{
num_const();
break;
}
default:
jj_la1[17] = jj_gen;
if (jj_2_5(2)) {
var_attr();
} else if (jj_2_6(2)) {
func_call();
} else {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case ID:{
jj_consume_token(ID);
break;
}
case string_constant:{
jj_consume_token(string_constant);
break;
}
case char_constant:{
jj_consume_token(char_constant);
break;
}
case LPAREN:{
jj_consume_token(LPAREN);
expr_value();
jj_consume_token(RPAREN);
break;
}
default:
jj_la1[18] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
}
if (jj_2_7(2)) {
unary_operator();
} else {
;
}
if (jj_2_8(2)) {
binary_operator();
expr_value();
} else {
;
}
} finally {
trace_return("expr_value");
}
}
final public void var_decl() throws ParseException { try {
var_type();
if (jj_2_9(2)) {
var_attr();
} else {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case ID:{
jj_consume_token(ID);
break;
}
default:
jj_la1[19] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
label_5:
while (true) {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case COMMA:{
;
break;
}
default:
jj_la1[20] = jj_gen;
break label_5;
}
jj_consume_token(COMMA);
if (jj_2_10(2)) {
var_attr();
} else {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case ID:{
jj_consume_token(ID);
break;
}
default:
jj_la1[21] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
}
jj_consume_token(SEMICOLON);
} finally {
trace_return("var_decl");
}
}
final public void binary_operator() throws ParseException { try {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case PLUS:{
jj_consume_token(PLUS);
break;
}
case MINUS:{
jj_consume_token(MINUS);
break;
}
case MULTIPLY:{
jj_consume_token(MULTIPLY);
break;
}
case DIVIDE:{
jj_consume_token(DIVIDE);
break;
}
case MOD:{
jj_consume_token(MOD);
break;
}
case PLUS_EQ:{
jj_consume_token(PLUS_EQ);
break;
}
case MINUS_EQ:{
jj_consume_token(MINUS_EQ);
break;
}
case MULTIPLY_EQ:{
jj_consume_token(MULTIPLY_EQ);
break;
}
case DIVIDE_EQ:{
jj_consume_token(DIVIDE_EQ);
break;
}
case MOD_EQ:{
jj_consume_token(MOD_EQ);
break;
}
case LEFT_SHIFT:{
jj_consume_token(LEFT_SHIFT);
break;
}
case RIGHT_SHIFT:{
jj_consume_token(RIGHT_SHIFT);
break;
}
case GT:{
jj_consume_token(GT);
break;
}
case LT:{
jj_consume_token(LT);
break;
}
case EQ:{
jj_consume_token(EQ);
break;
}
case LE:{
jj_consume_token(LE);
break;
}
case GE:{
jj_consume_token(GE);
break;
}
case NE:{
jj_consume_token(NE);
break;
}
case AND:{
jj_consume_token(AND);
break;
}
case OR:{
jj_consume_token(OR);
break;
}
default:
jj_la1[22] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} finally {
trace_return("binary_operator");
}
}
final public void if_cond() throws ParseException { try {
jj_consume_token(IF);
jj_consume_token(LPAREN);
expr_value();
jj_consume_token(RPAREN);
jj_consume_token(LBRACE);
body();
jj_consume_token(RBRACE);
} finally {
trace_return("if_cond");
}
}
final public void return_val() throws ParseException { try {
jj_consume_token(RETURN);
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case PLUS:
case MINUS:
case INC:
case DEC:
case LPAREN:
case int_constant:
case float_constant:
case char_constant:
case string_constant:
case ID:{
expr_value();
break;
}
default:
jj_la1[23] = jj_gen;
;
}
jj_consume_token(SEMICOLON);
} finally {
trace_return("return_val");
}
}
final public void unary_operator() throws ParseException { try {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case INC:{
jj_consume_token(INC);
break;
}
case DEC:{
jj_consume_token(DEC);
break;
}
default:
jj_la1[24] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} finally {
trace_return("unary_operator");
}
}
private boolean jj_2_1(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return (!jj_3_1()); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(0, xla); }
}
private boolean jj_2_2(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return (!jj_3_2()); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(1, xla); }
}
private boolean jj_2_3(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return (!jj_3_3()); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(2, xla); }
}
private boolean jj_2_4(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return (!jj_3_4()); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(3, xla); }
}
private boolean jj_2_5(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return (!jj_3_5()); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(4, xla); }
}
private boolean jj_2_6(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return (!jj_3_6()); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(5, xla); }
}
private boolean jj_2_7(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return (!jj_3_7()); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(6, xla); }
}
private boolean jj_2_8(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return (!jj_3_8()); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(7, xla); }
}
private boolean jj_2_9(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return (!jj_3_9()); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(8, xla); }
}
private boolean jj_2_10(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return (!jj_3_10()); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(9, xla); }
}
private boolean jj_3_4()
{
if (jj_scan_token(HASHTAG)) return true;
if (jj_scan_token(DEFINE)) return true;
return false;
}
private boolean jj_3_3()
{
if (jj_scan_token(HASHTAG)) return true;
if (jj_scan_token(INCLUDE)) return true;
if (jj_scan_token(70)) return true;
return false;
}
private boolean jj_3R_7()
{
if (!jj_rescan) trace_call("var_attr(LOOKING AHEAD...)");
if (jj_scan_token(ID)) { if (!jj_rescan) trace_return("var_attr(LOOKAHEAD FAILED)"); return true; }
if (jj_scan_token(ASSIGN)) { if (!jj_rescan) trace_return("var_attr(LOOKAHEAD FAILED)"); return true; }
{ if (!jj_rescan) trace_return("var_attr(LOOKAHEAD SUCCEEDED)"); return false; }
}
private boolean jj_3_8()
{
if (jj_3R_10()) return true;
if (jj_3R_11()) return true;
return false;
}
private boolean jj_3R_15()
{
if (jj_scan_token(LPAREN)) return true;
return false;
}
private boolean jj_3_7()
{
if (jj_3R_9()) return true;
return false;
}
private boolean jj_3_2()
{
if (jj_scan_token(HASHTAG)) return true;
if (jj_scan_token(INCLUDE)) return true;
if (jj_scan_token(LT)) return true;
return false;
}
private boolean jj_3_5()
{
if (jj_3R_7()) return true;
return false;
}
private boolean jj_3R_14()
{
if (jj_3R_16()) return true;
return false;
}
private boolean jj_3R_13()
{
if (jj_3R_9()) return true;
return false;
}
private boolean jj_3R_11()
{
if (!jj_rescan) trace_call("expr_value(LOOKING AHEAD...)");
Token xsp;
xsp = jj_scanpos;
if (jj_3R_13()) jj_scanpos = xsp;
xsp = jj_scanpos;
if (jj_3R_14()) {
jj_scanpos = xsp;
if (jj_3_5()) {
jj_scanpos = xsp;
if (jj_3_6()) {
jj_scanpos = xsp;
if (jj_scan_token(58)) {
jj_scanpos = xsp;
if (jj_scan_token(57)) {
jj_scanpos = xsp;
if (jj_scan_token(56)) {
jj_scanpos = xsp;
if (jj_3R_15()) { if (!jj_rescan) trace_return("expr_value(LOOKAHEAD FAILED)"); return true; }
}
}
}
}
}
}
{ if (!jj_rescan) trace_return("expr_value(LOOKAHEAD SUCCEEDED)"); return false; }
}
private boolean jj_3_1()
{
if (jj_3R_6()) return true;
return false;
}
private boolean jj_3R_9()
{
if (!jj_rescan) trace_call("unary_operator(LOOKING AHEAD...)");
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(39)) {
jj_scanpos = xsp;
if (jj_scan_token(40)) { if (!jj_rescan) trace_return("unary_operator(LOOKAHEAD FAILED)"); return true; }
}
{ if (!jj_rescan) trace_return("unary_operator(LOOKAHEAD SUCCEEDED)"); return false; }
}
private boolean jj_3R_17()
{
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(26)) {
jj_scanpos = xsp;
if (jj_scan_token(28)) return true;
}
return false;
}
private boolean jj_3R_16()
{
if (!jj_rescan) trace_call("num_const(LOOKING AHEAD...)");
Token xsp;
xsp = jj_scanpos;
if (jj_3R_17()) jj_scanpos = xsp;
xsp = jj_scanpos;
if (jj_scan_token(53)) {
jj_scanpos = xsp;
if (jj_scan_token(54)) {
jj_scanpos = xsp;
if (jj_scan_token(56)) { if (!jj_rescan) trace_return("num_const(LOOKAHEAD FAILED)"); return true; }
}
}
{ if (!jj_rescan) trace_return("num_const(LOOKAHEAD SUCCEEDED)"); return false; }
}
private boolean jj_3_6()
{
if (jj_3R_8()) return true;
return false;
}
private boolean jj_3_9()
{
if (jj_3R_7()) return true;
return false;
}
private boolean jj_3_10()
{
if (jj_3R_7()) return true;
return false;
}
private boolean jj_3R_12()
{
if (!jj_rescan) trace_call("func_type(LOOKING AHEAD...)");
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(6)) {
jj_scanpos = xsp;
if (jj_scan_token(18)) {
jj_scanpos = xsp;
if (jj_scan_token(16)) {
jj_scanpos = xsp;
if (jj_scan_token(8)) {
jj_scanpos = xsp;
if (jj_scan_token(15)) { if (!jj_rescan) trace_return("func_type(LOOKAHEAD FAILED)"); return true; }
}
}
}
}
{ if (!jj_rescan) trace_return("func_type(LOOKAHEAD SUCCEEDED)"); return false; }
}
private boolean jj_3R_8()
{
if (!jj_rescan) trace_call("func_call(LOOKING AHEAD...)");
if (jj_scan_token(ID)) { if (!jj_rescan) trace_return("func_call(LOOKAHEAD FAILED)"); return true; }
if (jj_scan_token(LPAREN)) { if (!jj_rescan) trace_return("func_call(LOOKAHEAD FAILED)"); return true; }
{ if (!jj_rescan) trace_return("func_call(LOOKAHEAD SUCCEEDED)"); return false; }
}
private boolean jj_3R_10()
{
if (!jj_rescan) trace_call("binary_operator(LOOKING AHEAD...)");
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(26)) {
jj_scanpos = xsp;
if (jj_scan_token(28)) {
jj_scanpos = xsp;
if (jj_scan_token(30)) {
jj_scanpos = xsp;
if (jj_scan_token(32)) {
jj_scanpos = xsp;
if (jj_scan_token(34)) {
jj_scanpos = xsp;
if (jj_scan_token(27)) {
jj_scanpos = xsp;
if (jj_scan_token(29)) {
jj_scanpos = xsp;
if (jj_scan_token(31)) {
jj_scanpos = xsp;
if (jj_scan_token(33)) {
jj_scanpos = xsp;
if (jj_scan_token(35)) {
jj_scanpos = xsp;
if (jj_scan_token(37)) {
jj_scanpos = xsp;
if (jj_scan_token(38)) {
jj_scanpos = xsp;
if (jj_scan_token(20)) {
jj_scanpos = xsp;
if (jj_scan_token(21)) {
jj_scanpos = xsp;
if (jj_scan_token(22)) {
jj_scanpos = xsp;
if (jj_scan_token(23)) {
jj_scanpos = xsp;
if (jj_scan_token(24)) {
jj_scanpos = xsp;
if (jj_scan_token(25)) {
jj_scanpos = xsp;
if (jj_scan_token(41)) {
jj_scanpos = xsp;
if (jj_scan_token(42)) { if (!jj_rescan) trace_return("binary_operator(LOOKAHEAD FAILED)"); return true; }
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
{ if (!jj_rescan) trace_return("binary_operator(LOOKAHEAD SUCCEEDED)"); return false; }
}
private boolean jj_3R_6()
{
if (!jj_rescan) trace_call("func_decl(LOOKING AHEAD...)");
if (jj_3R_12()) { if (!jj_rescan) trace_return("func_decl(LOOKAHEAD FAILED)"); return true; }
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(58)) {
jj_scanpos = xsp;
if (jj_scan_token(11)) { if (!jj_rescan) trace_return("func_decl(LOOKAHEAD FAILED)"); return true; }
}
if (jj_scan_token(LPAREN)) { if (!jj_rescan) trace_return("func_decl(LOOKAHEAD FAILED)"); return true; }
{ if (!jj_rescan) trace_return("func_decl(LOOKAHEAD SUCCEEDED)"); return false; }
}
/** Generated Token Manager. */
public CompilatudoTokenManager token_source;
SimpleCharStream jj_input_stream;
/** Current token. */
public Token token;
/** Next token. */
public Token jj_nt;
private int jj_ntk;
private Token jj_scanpos, jj_lastpos;
private int jj_la;
private int jj_gen;
final private int[] jj_la1 = new int[25];
static private int[] jj_la1_0;
static private int[] jj_la1_1;
static private int[] jj_la1_2;
static {
jj_la1_init_0();
jj_la1_init_1();
jj_la1_init_2();
}
private static void jj_la1_init_0() {
jj_la1_0 = new int[] {0x58140,0x0,0x50140,0x800,0x50140,0x400,0x58140,0x0,0x140741c0,0x140741c0,0x24080,0x0,0x50140,0x14000000,0x14000000,0x0,0x0,0x14000000,0x0,0x0,0x0,0x0,0xfff00000,0x14000000,0x0,};
}
private static void jj_la1_init_1() {
jj_la1_1 = new int[] {0x100000,0x100000,0x0,0x4000000,0x0,0x0,0x0,0x40000,0x7600980,0x7600980,0x0,0x40000,0x0,0x0,0x0,0x1600000,0x180,0x1600000,0x7000800,0x4000000,0x40000,0x4000000,0x66f,0x7600980,0x180,};
}
private static void jj_la1_init_2() {
jj_la1_2 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,};
}
final private JJCalls[] jj_2_rtns = new JJCalls[10];
private boolean jj_rescan = false;
private int jj_gc = 0;
{
enable_tracing();
}
/** Constructor with InputStream. */
public Compilatudo(java.io.InputStream stream) {
this(stream, null);
}
/** Constructor with InputStream and supplied encoding */
public Compilatudo(java.io.InputStream stream, String encoding) {
try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source = new CompilatudoTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 25; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream) {
ReInit(stream, null);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream, String encoding) {
try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 25; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Constructor. */
public Compilatudo(java.io.Reader stream) {
jj_input_stream = new SimpleCharStream(stream, 1, 1);
token_source = new CompilatudoTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 25; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Reinitialise. */
public void ReInit(java.io.Reader stream) {
if (jj_input_stream == null) {
jj_input_stream = new SimpleCharStream(stream, 1, 1);
} else {
jj_input_stream.ReInit(stream, 1, 1);
}
if (token_source == null) {
token_source = new CompilatudoTokenManager(jj_input_stream);
}
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 25; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Constructor with generated Token Manager. */
public Compilatudo(CompilatudoTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 25; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Reinitialise. */
public void ReInit(CompilatudoTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 25; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
if (++jj_gc > 100) {
jj_gc = 0;
for (int i = 0; i < jj_2_rtns.length; i++) {
JJCalls c = jj_2_rtns[i];
while (c != null) {
if (c.gen < jj_gen) c.first = null;
c = c.next;
}
}
}
trace_token(token, "");
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
}
@SuppressWarnings("serial")
static private final class LookaheadSuccess extends java.lang.Error { }
final private LookaheadSuccess jj_ls = new LookaheadSuccess();
private boolean jj_scan_token(int kind) {
if (jj_scanpos == jj_lastpos) {
jj_la--;
if (jj_scanpos.next == null) {
jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();
} else {
jj_lastpos = jj_scanpos = jj_scanpos.next;
}
} else {
jj_scanpos = jj_scanpos.next;
}
if (jj_rescan) {
int i = 0; Token tok = token;
while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }
if (tok != null) jj_add_error_token(kind, i);
} else {
trace_scan(jj_scanpos, kind);
}
if (jj_scanpos.kind != kind) return true;
if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;
return false;
}
/** Get the next Token. */
final public Token getNextToken() {
if (token.next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
jj_gen++;
trace_token(token, " (in getNextToken)");
return token;
}
/** Get the specific Token. */
final public Token getToken(int index) {
Token t = token;
for (int i = 0; i < index; i++) {
if (t.next != null) t = t.next;
else t = t.next = token_source.getNextToken();
}
return t;
}
private int jj_ntk_f() {
if ((jj_nt=token.next) == null)
return (jj_ntk = (token.next=token_source.getNextToken()).kind);
else
return (jj_ntk = jj_nt.kind);
}
private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>();
private int[] jj_expentry;
private int jj_kind = -1;
private int[] jj_lasttokens = new int[100];
private int jj_endpos;
private void jj_add_error_token(int kind, int pos) {
if (pos >= 100) {
return;
}
if (pos == jj_endpos + 1) {
jj_lasttokens[jj_endpos++] = kind;
} else if (jj_endpos != 0) {
jj_expentry = new int[jj_endpos];
for (int i = 0; i < jj_endpos; i++) {
jj_expentry[i] = jj_lasttokens[i];
}
for (int[] oldentry : jj_expentries) {
if (oldentry.length == jj_expentry.length) {
boolean isMatched = true;
for (int i = 0; i < jj_expentry.length; i++) {
if (oldentry[i] != jj_expentry[i]) {
isMatched = false;
break;
}
}
if (isMatched) {
jj_expentries.add(jj_expentry);
break;
}
}
}
if (pos != 0) {
jj_lasttokens[(jj_endpos = pos) - 1] = kind;
}
}
}
/** Generate ParseException. */
public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[71];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 25; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
if ((jj_la1_1[i] & (1<<j)) != 0) {
la1tokens[32+j] = true;
}
if ((jj_la1_2[i] & (1<<j)) != 0) {
la1tokens[64+j] = true;
}
}
}
}
for (int i = 0; i < 71; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
jj_endpos = 0;
jj_rescan_token();
jj_add_error_token(0, 0);
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
}
private int trace_indent = 0;
private boolean trace_enabled;
/** Trace enabled. */
final public boolean trace_enabled() {
return trace_enabled;
}
/** Enable tracing. */
final public void enable_tracing() {
trace_enabled = true;
}
/** Disable tracing. */
final public void disable_tracing() {
trace_enabled = false;
}
protected void trace_call(String s) {
if (trace_enabled) {
for (int i = 0; i < trace_indent; i++) { System.out.print(" "); }
System.out.println("Call: " + s);
}
trace_indent = trace_indent + 2;
}
protected void trace_return(String s) {
trace_indent = trace_indent - 2;
if (trace_enabled) {
for (int i = 0; i < trace_indent; i++) { System.out.print(" "); }
System.out.println("Return: " + s);
}
}
protected void trace_token(Token t, String where) {
if (trace_enabled) {
for (int i = 0; i < trace_indent; i++) { System.out.print(" "); }
System.out.print("Consumed token: <" + tokenImage[t.kind]);
if (t.kind != 0 && !tokenImage[t.kind].equals("\"" + t.image + "\"")) {
System.out.print(": \"" + TokenMgrError.addEscapes(t.image) + "\"");
}
System.out.println(" at line " + t.beginLine + " column " + t.beginColumn + ">" + where);
}
}
protected void trace_scan(Token t1, int t2) {
if (trace_enabled) {
for (int i = 0; i < trace_indent; i++) { System.out.print(" "); }
System.out.print("Visited token: <" + tokenImage[t1.kind]);
if (t1.kind != 0 && !tokenImage[t1.kind].equals("\"" + t1.image + "\"")) {
System.out.print(": \"" + TokenMgrError.addEscapes(t1.image) + "\"");
}
System.out.println(" at line " + t1.beginLine + " column " + t1.beginColumn + ">; Expected token: <" + tokenImage[t2] + ">");
}
}
private void jj_rescan_token() {
jj_rescan = true;
for (int i = 0; i < 10; i++) {
try {
JJCalls p = jj_2_rtns[i];
do {
if (p.gen > jj_gen) {
jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;
switch (i) {
case 0: jj_3_1(); break;
case 1: jj_3_2(); break;
case 2: jj_3_3(); break;
case 3: jj_3_4(); break;
case 4: jj_3_5(); break;
case 5: jj_3_6(); break;
case 6: jj_3_7(); break;
case 7: jj_3_8(); break;
case 8: jj_3_9(); break;
case 9: jj_3_10(); break;
}
}
p = p.next;
} while (p != null);
} catch(LookaheadSuccess ls) { }
}
jj_rescan = false;
}
private void jj_save(int index, int xla) {
JJCalls p = jj_2_rtns[index];
while (p.gen > jj_gen) {
if (p.next == null) { p = p.next = new JJCalls(); break; }
p = p.next;
}
p.gen = jj_gen + xla - jj_la;
p.first = token;
p.arg = xla;
}
static final class JJCalls {
int gen;
Token first;
int arg;
JJCalls next;
}
}
|
package df.client;
import df.bo.BusinessObject;
import df.repository.entry.moniker.Moniker;
public class BdfModifyClient<V extends BusinessObject> {
private BdfModifyClient() {
}
public void publishCorrection(Moniker moniker, V value) {
return;
}
public BdfModifyClient<V> instance() {
return new BdfModifyClient();
}
}
|
package entity;
import org.codehaus.jackson.annotate.JsonAnySetter;
/**
* Date: 25.12.2012
* Time: 22:38
*/
public class FurnitureItem {
private String id;
private Integer x;
private Integer y;
private Integer width;
private Integer height;
@JsonAnySetter
public void handleUnknown(String key, Object value) {
System.out.println(key + " " + value.toString());
}
public FurnitureItem(String id, Integer x, Integer y, Integer width, Integer height) {
this.height = height;
this.id = id;
this.width = width;
this.x = x;
this.y = y;
}
public FurnitureItem(){}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getX() {
return x;
}
public void setX(Integer x) {
this.x = x;
}
public Integer getY() {
return y;
}
public void setY(Integer y) {
this.y = y;
}
@Override
public String toString() {
return "{" + id + "," + x + "," + y + "," + width + "," + height + "}";
}
}
|
package testTasks.Model;
import java.util.ArrayList;
import java.util.List;
// playground class contains card pack and players list
public class Playground {
private List<Player> players = new ArrayList<>();
private Pack pack;
public List<Player> getPlayers() {
return players;
}
public Pack getPack() {
return pack;
}
public void setPack(Pack pack) {
this.pack = pack;
}
public Playground(Pack pack) {
this.pack = pack;
}
public void openAllCards() {
players.forEach(p -> {
for (Card card : p.getHand()) card.setClosed(false);
});
}
} |
package alien4cloud.it;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(features = { "classpath:alien/rest/application-version" }, format = { "pretty", "html:target/cucumber/application-version",
"json:target/cucumber/cucumber-application-version.json" })
public class RunApplicationVersionIT {
}
|
package com.xinhua.api.domain.refOrder;
import com.apsaras.aps.increment.domain.AbstractIncRequest;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import javax.validation.constraints.Size;
import java.io.Serializable;
/**
* Created by ning on 15/7/21.
* 当日撤单 请求
*
*/
public class RefOrderRequest extends AbstractIncRequest implements Serializable {
/**
*交易日期
*/
private String transExeDate;
/**
*交易时间
*/
private String transExeTime;
/**
*银行代码
*/
@Size(min=2,max=8,message="1asdfadsfasdf")
private String bankCode;
/**
*地区代码
*/
private String regionCode;
/**
*网点代码
*/
private String branch;
/**
*柜员代码
*/
private String teller;
/**
*授权柜员代码
*/
private String authTellerNo;
/**
*邮编
*/
private String postCode;
/**
*交易类型
*/
private String cate;
/**
*交易科目
*/
private String subject;
/**
*待冲正交易流水号
*/
private String corTransrNo;
/**
*交易码
*/
private String functionFlag;
/**
*交易流水号
*/
private String transRefGUID;
/**
*原银行交易流水号
*/
private String originalTransRefGUID;
/**
*原交易流水号
*/
private String originalTranNo;
/**
*处理标志
*/
private String transType;
/**
*请求中心代码
*/
private String ask;
/**
*交易模式
*/
private String transMode;
/**
*处理中心代码
*/
private String proc;
/**
*保险公司代码
*/
private String carrierCode;
/**
*原交易保险公司流水号
*/
private String bkOthOldSeq;
/**
*请求方交易流水号
*/
private String bkPlatSeqNo;
/**
*交易渠道代号
*/
private String bkChnlNo;
/**
*原始请求方机构代码
*/
private String bkBrchNo;
/**
*原始请求方机构名称
*/
private String bkBrchName;
/**
*银行交易流水号
*/
private String transNo;
/**
*保险公司流水号
*/
private String bkOthSeq;
/**
*交易发起方
*/
private String transSide;
/**
*委托方式
*/
private String entrustWay;
/**
*省市代码
*/
private String provCode;
/**
*投保书号
*/
private String hOAppFormNumber;
/**
*保单号码
*/
private String polNumber;
/**
*总保费
*/
private String grossPremAmt;
/**
*保单密码
*/
private String password;
/**
*首期保费
*/
private String paymentAmt;
/**
*撤单金额
*/
private String undoSum;
/**
*交易金额
*/
private String prem;
/**
*当日撤单原因
*/
private String reason;
/**
*备注
*/
private String remark;
/**
*险种代码
*/
private String productCode;
/**
*冲正操作类型
*/
private String operationType;
/**
*银行交易渠道
*/
@NotNull
private String channel;
/**
*批单号
*/
private String originalFormName;
/**
*银行付款帐户代码
*/
private String accountNumber;
/**
*保险费
*/
private String premium;
/**
*产品代码
*/
private String prodCode;
/**
*缴费账户
*/
private String payAccount;
/**
*投保人名称
*/
private String tbrName;
/**
*投保人证件类型
*/
private String tbrIdType;
/**
*投保人证件号码
*/
private String tbrIdNo;
/**
*单证名称
*/
private String formName;
public String getTransExeDate() {
return transExeDate;
}
public void setTransExeDate(String transExeDate) {
this.transExeDate = transExeDate;
}
public String getTransExeTime() {
return transExeTime;
}
public void setTransExeTime(String transExeTime) {
this.transExeTime = transExeTime;
}
public String getBankCode() {
return bankCode;
}
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getRegionCode() {
return regionCode;
}
public void setRegionCode(String regionCode) {
this.regionCode = regionCode;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getTeller() {
return teller;
}
public void setTeller(String teller) {
this.teller = teller;
}
public String getAuthTellerNo() {
return authTellerNo;
}
public void setAuthTellerNo(String authTellerNo) {
this.authTellerNo = authTellerNo;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getCate() {
return cate;
}
public void setCate(String cate) {
this.cate = cate;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getCorTransrNo() {
return corTransrNo;
}
public void setCorTransrNo(String corTransrNo) {
this.corTransrNo = corTransrNo;
}
public String getFunctionFlag() {
return functionFlag;
}
public void setFunctionFlag(String functionFlag) {
this.functionFlag = functionFlag;
}
public String getTransRefGUID() {
return transRefGUID;
}
public void setTransRefGUID(String transRefGUID) {
this.transRefGUID = transRefGUID;
}
public String getOriginalTransRefGUID() {
return originalTransRefGUID;
}
public void setOriginalTransRefGUID(String originalTransRefGUID) {
this.originalTransRefGUID = originalTransRefGUID;
}
public String getOriginalTranNo() {
return originalTranNo;
}
public void setOriginalTranNo(String originalTranNo) {
this.originalTranNo = originalTranNo;
}
public String getTransType() {
return transType;
}
public void setTransType(String transType) {
this.transType = transType;
}
public String getAsk() {
return ask;
}
public void setAsk(String ask) {
this.ask = ask;
}
public String getTransMode() {
return transMode;
}
public void setTransMode(String transMode) {
this.transMode = transMode;
}
public String getProc() {
return proc;
}
public void setProc(String proc) {
this.proc = proc;
}
public String getCarrierCode() {
return carrierCode;
}
public void setCarrierCode(String carrierCode) {
this.carrierCode = carrierCode;
}
public String getBkOthOldSeq() {
return bkOthOldSeq;
}
public void setBkOthOldSeq(String bkOthOldSeq) {
this.bkOthOldSeq = bkOthOldSeq;
}
public String getBkPlatSeqNo() {
return bkPlatSeqNo;
}
public void setBkPlatSeqNo(String bkPlatSeqNo) {
this.bkPlatSeqNo = bkPlatSeqNo;
}
public String getBkChnlNo() {
return bkChnlNo;
}
public void setBkChnlNo(String bkChnlNo) {
this.bkChnlNo = bkChnlNo;
}
public String getBkBrchNo() {
return bkBrchNo;
}
public void setBkBrchNo(String bkBrchNo) {
this.bkBrchNo = bkBrchNo;
}
public String getBkBrchName() {
return bkBrchName;
}
public void setBkBrchName(String bkBrchName) {
this.bkBrchName = bkBrchName;
}
public String getTransNo() {
return transNo;
}
public void setTransNo(String transNo) {
this.transNo = transNo;
}
public String getBkOthSeq() {
return bkOthSeq;
}
public void setBkOthSeq(String bkOthSeq) {
this.bkOthSeq = bkOthSeq;
}
public String getTransSide() {
return transSide;
}
public void setTransSide(String transSide) {
this.transSide = transSide;
}
public String getEntrustWay() {
return entrustWay;
}
public void setEntrustWay(String entrustWay) {
this.entrustWay = entrustWay;
}
public String getProvCode() {
return provCode;
}
public void setProvCode(String provCode) {
this.provCode = provCode;
}
public String gethOAppFormNumber() {
return hOAppFormNumber;
}
public void sethOAppFormNumber(String hOAppFormNumber) {
this.hOAppFormNumber = hOAppFormNumber;
}
public String getPolNumber() {
return polNumber;
}
public void setPolNumber(String polNumber) {
this.polNumber = polNumber;
}
public String getGrossPremAmt() {
return grossPremAmt;
}
public void setGrossPremAmt(String grossPremAmt) {
this.grossPremAmt = grossPremAmt;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPaymentAmt() {
return paymentAmt;
}
public void setPaymentAmt(String paymentAmt) {
this.paymentAmt = paymentAmt;
}
public String getUndoSum() {
return undoSum;
}
public void setUndoSum(String undoSum) {
this.undoSum = undoSum;
}
public String getPrem() {
return prem;
}
public void setPrem(String prem) {
this.prem = prem;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getOperationType() {
return operationType;
}
public void setOperationType(String operationType) {
this.operationType = operationType;
}
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getOriginalFormName() {
return originalFormName;
}
public void setOriginalFormName(String originalFormName) {
this.originalFormName = originalFormName;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getPremium() {
return premium;
}
public void setPremium(String premium) {
this.premium = premium;
}
public String getProdCode() {
return prodCode;
}
public void setProdCode(String prodCode) {
this.prodCode = prodCode;
}
public String getPayAccount() {
return payAccount;
}
public void setPayAccount(String payAccount) {
this.payAccount = payAccount;
}
public String getTbrName() {
return tbrName;
}
public void setTbrName(String tbrName) {
this.tbrName = tbrName;
}
public String getTbrIdType() {
return tbrIdType;
}
public void setTbrIdType(String tbrIdType) {
this.tbrIdType = tbrIdType;
}
public String getTbrIdNo() {
return tbrIdNo;
}
public void setTbrIdNo(String tbrIdNo) {
this.tbrIdNo = tbrIdNo;
}
public String getFormName() {
return formName;
}
public void setFormName(String formName) {
this.formName = formName;
}
@Override
public String toString() {
return "RefOrderRequest{" +
"transExeDate='" + transExeDate + '\'' +
", transExeTime='" + transExeTime + '\'' +
", bankCode='" + bankCode + '\'' +
", regionCode='" + regionCode + '\'' +
", branch='" + branch + '\'' +
", teller='" + teller + '\'' +
", authTellerNo='" + authTellerNo + '\'' +
", postCode='" + postCode + '\'' +
", cate='" + cate + '\'' +
", subject='" + subject + '\'' +
", corTransrNo='" + corTransrNo + '\'' +
", functionFlag='" + functionFlag + '\'' +
", transRefGUID='" + transRefGUID + '\'' +
", originalTransRefGUID='" + originalTransRefGUID + '\'' +
", originalTranNo='" + originalTranNo + '\'' +
", transType='" + transType + '\'' +
", ask='" + ask + '\'' +
", transMode='" + transMode + '\'' +
", proc='" + proc + '\'' +
", carrierCode='" + carrierCode + '\'' +
", bkOthOldSeq='" + bkOthOldSeq + '\'' +
", bkPlatSeqNo='" + bkPlatSeqNo + '\'' +
", bkChnlNo='" + bkChnlNo + '\'' +
", bkBrchNo='" + bkBrchNo + '\'' +
", bkBrchName='" + bkBrchName + '\'' +
", transNo='" + transNo + '\'' +
", bkOthSeq='" + bkOthSeq + '\'' +
", transSide='" + transSide + '\'' +
", entrustWay='" + entrustWay + '\'' +
", provCode='" + provCode + '\'' +
", hOAppFormNumber='" + hOAppFormNumber + '\'' +
", polNumber='" + polNumber + '\'' +
", grossPremAmt='" + grossPremAmt + '\'' +
", password='" + password + '\'' +
", paymentAmt='" + paymentAmt + '\'' +
", undoSum='" + undoSum + '\'' +
", prem='" + prem + '\'' +
", reason='" + reason + '\'' +
", remark='" + remark + '\'' +
", productCode='" + productCode + '\'' +
", operationType='" + operationType + '\'' +
", channel='" + channel + '\'' +
", originalFormName='" + originalFormName + '\'' +
", accountNumber='" + accountNumber + '\'' +
", premium='" + premium + '\'' +
", prodCode='" + prodCode + '\'' +
", payAccount='" + payAccount + '\'' +
", tbrName='" + tbrName + '\'' +
", tbrIdType='" + tbrIdType + '\'' +
", tbrIdNo='" + tbrIdNo + '\'' +
", formName='" + formName + '\'' +
'}';
}
}
|
package cn.itheima.day_07.homework.animals;
public class Test {
public static void main(String[] args) {
Cat cat = new Cat("蓝","英国短毛");
Dog dog = new Dog();
dog.setColor("白");
dog.setBreed("博美犬");
cat.eat();
cat.work();
cat.bark();
System.out.println("------------");
dog.eat();
dog.work();
dog.bark();
}
}
|
package uchet.service.units;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import uchet.models.Unit;
import uchet.repository.UnitRepository;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class UnitServiceImpl implements UnitService {
private UnitRepository unitRepository;
@Override
public List<Unit> getAll() {
List<Unit> units = (List<Unit>) unitRepository.findAll();
return sortUnits(units);
}
private List<Unit> sortUnits(List<Unit> units) {
return units.stream().sorted(Comparator.comparing(Unit::getUnit)).collect(Collectors.toList());
}
@Autowired
public void setUnitRepository(UnitRepository unitRepository) {
this.unitRepository = unitRepository;
}
}
|
package f.star.iota.milk.ui.moe005tv.moe;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import java.util.ArrayList;
import java.util.List;
import f.star.iota.milk.Net;
import f.star.iota.milk.base.PagerFragment;
import f.star.iota.milk.base.TitlePagerAdapter;
import f.star.iota.milk.util.MessageBar;
public class MOE005TVPagerFragment extends PagerFragment {
public static final int ACG = 1;
public static final int COS = 2;
public static MOE005TVPagerFragment newInstance(int type) {
MOE005TVPagerFragment fragment = new MOE005TVPagerFragment();
Bundle bundle = new Bundle();
bundle.putInt("type", type);
fragment.setArguments(bundle);
return fragment;
}
@Override
protected TitlePagerAdapter getPagerAdapter() {
List<String> titles = new ArrayList<>();
List<Fragment> fragments = new ArrayList<>();
int type = getArguments().getInt("type");
if (type == ACG) {
titles.add("萌图");
titles.add("电脑壁纸");
titles.add("手机壁纸");
fragments.add(MOE005TVFragment.newInstance(Net.MOE005TV_MT));
fragments.add(MOE005TVFragment.newInstance(Net.MOE005TV_DNBZ));
fragments.add(MOE005TVFragment.newInstance(Net.MOE005TV_SJBZ));
} else if (type == COS) {
titles.add("COSER介绍");
titles.add("写真图集");
fragments.add(MOE005TVFragment.newInstance(Net.MOE005TV_COSER));
fragments.add(MOE005TVFragment.newInstance(Net.MOE005TV_COS));
} else {
MessageBar.create(mContext, "获取数据错误,请稍候重试");
}
return new TitlePagerAdapter(getChildFragmentManager(), fragments, titles);
}
@Override
protected int setTabMode() {
return TabLayout.MODE_FIXED;
}
}
|
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ResourceBundle;
/*
*
* @author Matt Ping & Matt Bucci
*
*/
public class NewsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private NewsMethods newsMethods;
private ResourceBundle bundle;
private String message;
private int aid = -1;
private int tid = -1;
private int nid = -1;
private int rating = -1;
private String uid = "";
private String news_source = "";
private String news_url = "";
private boolean editMode = false;
private boolean addMode = false;
private boolean saveMode = false;
public void init() throws ServletException {
bundle = ResourceBundle.getBundle("OraBundle");
newsMethods = new NewsMethods();
message = newsMethods.openDBConnection(bundle.getString("dbUser"), bundle.getString("dbPass"), bundle.getString("dbSID"),
bundle.getString("dbHost"), Integer.parseInt(bundle.getString("dbPort")));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
resetValues();
// Get possible variables for the News Servlet
String queryString = request.getQueryString();
if (queryString != null && !queryString.trim().equals("")) {
String[] qString = queryString.split("&");
for (int i = 0; i < qString.length; i++) {
String[] tempString = qString[i].split("=");
try {
if (tempString[0].equals("aid"))
aid = Integer.parseInt(tempString[1]);
else if (tempString[0].equals("nid"))
nid = Integer.parseInt(tempString[1]);
else if (tempString[0].equals("tid"))
tid = Integer.parseInt(tempString[1]);
else if (tempString[0].equals("uid"))
uid = tempString[1];
else if (tempString[0].equals("save"))
saveMode = Boolean.valueOf(tempString[1]).booleanValue();
else if (tempString[0].equals("edit"))
editMode = Boolean.valueOf(tempString[1]).booleanValue();
else if (tempString[0].equals("add"))
addMode = Boolean.valueOf(tempString[1]).booleanValue();
else if (tempString[0].equals("news_source"))
news_source = HTMLUtils.cleanQString(tempString[1]);
else if (tempString[0].equals("news_url"))
news_url = HTMLUtils.cleanQString(tempString[1]);
else if (tempString[0].equals("rating"))
rating = Integer.parseInt(tempString[1]);
} catch (Exception ex) {
out.println("<h2>Error parsing query string</h2>");
}
}
}
out.println(HTMLUtils.renderHeader("News", uid, "NewsServlet"));
if (!message.equalsIgnoreCase("servus")) {
out.println("\t\t<h1>Oracle connection failed " + message + "</h1>");
}
else {
if (saveMode) {
News news = new News(nid, aid, news_source, news_url);
if (editMode)
news = newsMethods.updateNews(news);
else if (addMode)
news = newsMethods.addNews(news);
renderNews(out, news);
}
else if (addMode) {
renderNewsTextBoxes(out, null);
}
else if (editMode) {
if (nid > -1) {
News editNews = newsMethods.getNews(nid);
renderNewsTextBoxes(out, editNews);
}
else {
out.println("<p><b>Bad News ID</b></p>");
}
}
else {
if (nid > -1)
renderNews(out, newsMethods.getNews(nid));
}
}
out.println(HTMLUtils.renderClosingTags());
}
private void renderNewsTextBoxes(PrintWriter out, News newsToUpdate) {
if (newsToUpdate != null) {
out.println("\t\t<form action=\"NewsServlet\" method=\"get\">");
out.println("\t\t\t<input type=\"hidden\" name=\"nid\" value=\"" + newsToUpdate.getNID() + "\" />");
out.println("\t\t\t<input type=\"hidden\" name=\"aid\" value=\"" + aid + "\" />");
out.println("\t\t\t<input type=\"hidden\" name=\"uid\" value=\"" + uid + "\" />");
out.println("\t\t\t<input type=\"hidden\" name=\"save\" value=\"true\" />");
out.println("\t\t\t<input type=\"hidden\" name=\"edit\" value=\"true\" />");
out.println("\t\t\t<div>News Source: <input type=\"text\" name=\"news_source\" value=\"" + newsToUpdate.getNewsSource() + "\" /></div>");
out.println("\t\t\t<div>News URL: <input type=\"text\" name=\"news_url\" value=\"" + newsToUpdate.getNewsURL() + "\" /></div>");
out.println("\t\t\t<input type=\"submit\" value=\"Save\"> <a href=\"NewsServlet?nid=" + newsToUpdate.getNID() +
"&aid=" + aid + "&uid=" + uid + "\">Cancel</a>");
out.println("\t\t</form>");
}
else {
out.println("\t\t<form action=\"NewsServlet\" method=\"get\">");
out.println("\t\t\t<input type=\"hidden\" name=\"aid\" value=\"" + aid + "\" />");
out.println("\t\t\t<input type=\"hidden\" name=\"uid\" value=\"" + uid + "\" />");
out.println("\t\t\t<input type=\"hidden\" name=\"save\" value=\"true\" />");
out.println("\t\t\t<input type=\"hidden\" name=\"add\" value=\"true\" />");
out.println("\t\t\t<div>News Source: <input type=\"text\" name=\"news_source\" /></div>");
out.println("\t\t\t<div>News Url: <input type=\"text\" name=\"news_url\" /></div>");
if (nid > -1)
out.println("\t\t\t<input type=\"submit\" value=\"Save\"> <a href=\"NewsServlet?nid=" + newsToUpdate.getNID() +
"&aid=" + aid + "&uid=" + uid + "\">Cancel</a>");
else
out.println("\t\t\t<input type=\"submit\" value=\"Save\"> <a href=\"NewsServlet?aid=" + aid + "&uid=" + uid + "\">Cancel</a>");
out.println("\t\t</form>");
}
}
private void renderNews(PrintWriter out, News displayNews) {
if (!uid.equals("")) {
out.println("\t\t<div style=\"text-align:right\"><a href=\"NewsServlet?uid=" + uid + "&nid=" + nid + "&tid=" + tid + "&add=true\">Add</a> " +
"<a href=\"NewsServlet?uid=" + uid + "&nid=" + nid + "&aid=" + aid + "&edit=true\">Edit</a></div>\n");
}
out.println("<div><b>News Source: </b> " + displayNews.getNewsSource() + "</div>");
out.println("<div><b>News URL: </b> " + displayNews.getNewsURL() + "</div>");
if (uid.equals(""))
out.println("<div><a href=\"ActorServlet?aid=" + aid + "\">Back to Actor Page</a></div>");
else
out.println("<div><a href=\"ActorServlet?aid=" + aid + "&uid=" + uid + "\">Back to Actor Page</a></div>");
}
private void resetValues() {
aid = -1;
tid = -1;
nid = -1;
rating = -1;
uid = "";
news_source = "";
news_url = "";
editMode = false;
addMode = false;
saveMode = false;
}
public void doPost(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException {
doGet(inRequest, outResponse);
}
public void destroy() {
newsMethods.closeDBConnection();
}
} |
/*
* Created on 2004-11-26
*
*/
package com.aof.component.helpdesk.kb;
/**
* @author nicebean
*
*/
public class KnowledgeBase extends SimpleKnowledgeBase {
private String solution;
public String getSolution() {
return solution;
}
public void setSolution(String solution) {
this.solution = solution;
}
public boolean equals(Object obj) {
if (obj == null) return false;
if (this == obj) return true;
if (!(obj instanceof KnowledgeBase)) return false;
KnowledgeBase that = (KnowledgeBase)obj;
if (this.getId() != null) {
return this.getId().equals(that.getId());
}
return that.getId() == null;
}
}
|
/*
* Copyright (C) 2015 Piotr Wittchen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pwittchen.reactivenetwork.app;
import android.app.Activity;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.github.pwittchen.reactivenetwork.R;
import com.github.pwittchen.reactivenetwork.library.ConnectivityStatus;
import com.github.pwittchen.reactivenetwork.library.ReactiveNetwork;
import com.github.pwittchen.reactivenetwork.library.WifiSignalLevel;
import java.util.ArrayList;
import java.util.List;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
public class MainActivity extends Activity {
private static final String TAG = "ReactiveNetwork";
private static final String WIFI_SIGNAL_LEVEL_MESSAGE = "WiFi signal level: ";
private TextView tvConnectivityStatus;
private TextView tvWifiSignalLevel;
private ListView lvAccessPoints;
private ReactiveNetwork reactiveNetwork;
private Subscription wifiSubscription;
private Subscription connectivitySubscription;
private Subscription signalLevelSubscription;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvConnectivityStatus = (TextView) findViewById(R.id.connectivity_status);
lvAccessPoints = (ListView) findViewById(R.id.access_points);
tvWifiSignalLevel = (TextView) findViewById(R.id.wifi_signal_level);
}
@Override protected void onResume() {
super.onResume();
reactiveNetwork = new ReactiveNetwork();
connectivitySubscription = reactiveNetwork.observeConnectivity(getApplicationContext())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<ConnectivityStatus>() {
@Override public void call(final ConnectivityStatus status) {
Log.d(TAG, status.toString());
tvConnectivityStatus.setText(status.description);
final boolean isOffline = status == ConnectivityStatus.OFFLINE;
final boolean isMobileConnected = status == ConnectivityStatus.MOBILE_CONNECTED;
if (isOffline || isMobileConnected) {
final String description = WifiSignalLevel.NO_SIGNAL.description;
tvWifiSignalLevel.setText(WIFI_SIGNAL_LEVEL_MESSAGE.concat(description));
}
}
});
signalLevelSubscription = reactiveNetwork.observeWifiSignalLevel(getApplicationContext())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<WifiSignalLevel>() {
@Override public void call(final WifiSignalLevel level) {
Log.d(TAG, level.toString());
final String description = level.description;
tvWifiSignalLevel.setText(WIFI_SIGNAL_LEVEL_MESSAGE.concat(description));
}
});
wifiSubscription = reactiveNetwork.observeWifiAccessPoints(getApplicationContext())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<ScanResult>>() {
@Override public void call(final List<ScanResult> scanResults) {
displayAccessPoints(scanResults);
}
});
}
private void displayAccessPoints(List<ScanResult> scanResults) {
final List<String> ssids = new ArrayList<>();
for (ScanResult scanResult : scanResults) {
ssids.add(scanResult.SSID);
}
int itemLayoutId = android.R.layout.simple_list_item_1;
lvAccessPoints.setAdapter(new ArrayAdapter<>(this, itemLayoutId, ssids));
}
@Override protected void onPause() {
super.onPause();
safelyUnsubscribe(connectivitySubscription);
safelyUnsubscribe(wifiSubscription);
safelyUnsubscribe(signalLevelSubscription);
}
private void safelyUnsubscribe(Subscription subscription) {
if (subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
}
|
package org.mike.organization.events.source;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mike.organization.events.models.OrganizationChangeModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
@Component
public class SimpleSourceBean {
private Source source;
private static final Logger log = LogManager.getLogger(SimpleSourceBean.class);
@Autowired
public SimpleSourceBean(Source source) {
this.source = source;
}
public void publishOrgChange(String action, String orgId) {
log.info("### SENDING KAFKA MESSAGE: {} for Organization Id: {}", action, orgId);
OrganizationChangeModel change = new OrganizationChangeModel(
OrganizationChangeModel.class.getTypeName(),
action,
orgId,
""
);
source.output().send(MessageBuilder.withPayload(change).build());
}
}
|
package com.youma.his.dao;
import com.youma.his.vo.Role;
import java.util.List;
/**
* 角色表操作接口
*
* @author Administrator
*/
public interface RoleDao {
/**
* 角色添加操作
*
* @param role 角色
* @return 影响行数
*/
public int roleAdd(Role role);
/**
* 修改角色信息操作
*
* @param role 角色
* @return 影响行数
*/
public int updateRole(Role role);
/**
* 删除角色操作
*
* @param id 角色id
* @return 影响行数
*/
public int delRole(int id);
/**
* 查询所有角色
*
* @return 角色集合
*/
public List<Role> findAllRole();
/**
* 查找指定角色
*
* @param id 角色id
* @return 指定角色信息
*/
public Role findRole(int id);
}
|
package com.trump.auction.order.api.impl;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import com.trump.auction.order.api.PaymentStubService;
import com.trump.auction.order.model.PaymentInfoModel;
import com.trump.auction.order.service.PaymentService;
import java.util.Map;
@Service(version = "1.0.0")
public class PaymentStubServiceImpl implements PaymentStubService {
@Autowired
private PaymentService paymentService ;
@Override
public PaymentInfoModel getPaymentInfoByOrderId(String orderId) {
return paymentService.getPaymentInfoByOrderId(orderId);
}
@Override
public PaymentInfoModel selectById(Integer id) {
return paymentService.selectById(id);
}
@Override
public Integer createPaymentInfo(PaymentInfoModel paymentInfoModel) {
return paymentService.createPaymentInfo(paymentInfoModel);
}
@Override
public Integer updatePaymentInfoStatusSuc(PaymentInfoModel paymentInfoModel) {
return paymentService.updatePaymentInfoStatusSuc(paymentInfoModel);
}
@Override
public Boolean queryIsPaidByBatchNo(String batchNo) {
return paymentService.queryIsPaidByBatchNo(batchNo);
}
/**
* 查询未支付的信息并更新状态
*/
@Override
public void queryUnpaidInfoAndUpdate(Map<String,Object> map){
paymentService.queryUnpaidInfoAndUpdate(map);
}
@Override
public Boolean queryIsPaidByPreId(String preId) {
return paymentService.queryIsPaidByPreId(preId);
}
@Override
public PaymentInfoModel getPaymentInfoBySerialNo(String serialNo) {
return paymentService.getPaymentInfoBySerialNo(serialNo);
}
}
|
package xtrus.user.apps.routing.parser;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import com.esum.comp.xtr.process.TransInfo;
import com.esum.framework.core.component.ComponentException;
import com.esum.framework.core.component.code.ComponentCode;
import com.esum.framework.core.component.rule.processor.IRuleProcessor;
import com.esum.framework.core.event.message.DataInfo;
import com.esum.framework.core.event.message.Message;
import com.esum.framework.core.event.message.MessageEvent;
import com.esum.framework.core.event.message.Payload;
public class SendTestParser implements IRuleProcessor {
public Object preProcess(Object[] params) throws ComponentException {
try {
MessageEvent messageEvent = (MessageEvent) params[0];
Message message = messageEvent.getMessage();
parsePayload(message.getPayload());
return messageEvent;
} catch (Exception e) {
throw new ComponentException(ComponentCode.ERROR_PROCESS_RULE, "preProcess()", e.getMessage(), e);
}
}
public void parsePayload(Payload payload) throws Exception {
// BufferedReader reader = null;
// String header = null;
// try {
// reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(payload.getData())));
// header = reader.readLine();
// } finally {
// if (reader != null) {
// reader.close();
// }
// }
//
// int index = header.indexOf("|");
//
// String headerLine = header.substring(index+1, header.length());
String sender = "Park";
String receiver = "FileServer";
String doc_name = "ARRANT";
String doc_version = "1.0";
String doc_number = "12345678";
DataInfo dataInfo = payload.getDataInfo();
dataInfo.setSender(sender);
dataInfo.setReceiver(receiver);
dataInfo.setDocumentName(doc_name);
dataInfo.setDocumentVersion(doc_version);
dataInfo.setDocumentNumber(doc_number);
dataInfo.setConversationId(doc_number);
dataInfo.setRefConversationId(doc_number);
}
public Object postProcess(Object[] params) throws ComponentException {
try {
return (TransInfo) params[0];
} catch (Exception e) {
throw new ComponentException(ComponentCode.ERROR_PROCESS_RULE, "postProcess()", e.getMessage(), e);
}
}
public Object splitProcess(Object[] params) throws ComponentException {
try {
List splitList = new ArrayList();
splitList.add((byte[]) params[0]);
return splitList;
} catch (Exception e) {
throw new ComponentException(ComponentCode.ERROR_PROCESS_RULE, "splitProcess()", e.getMessage(), e);
}
}
@Override
public Object responseProcess(Object[] params) throws ComponentException {
return null;
}
}
|
/* https://codeforces.com/contest/723/problem/D
* #dfs #dsu #greedy
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;
public class LakesInBerland {
static boolean isValidLakePoint(int row, int col, char[][] graph) {
if (row < 0 || row > graph.length - 1) return false;
if (col < 0 || col > graph[0].length - 1) return false;
if (graph[row][col] == '*') return false;
return true;
}
static int DFS(Point startPoint, char[][] graph, boolean[][] visitedGraph) {
Deque<Point> queue = new LinkedList<>();
queue.add(startPoint);
int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, -1, 1};
int count = 0;
boolean isValid = true;
visitedGraph[startPoint.x][startPoint.y] = true;
while (!queue.isEmpty()) {
Point p = queue.pollLast();
count++;
if (p.x == 0 || p.x == graph.length - 1 || p.y == 0 || p.y == graph[0].length - 1) {
isValid = false;
}
for (int i = 0; i < dx.length; i++) {
Point temp = new Point(p.x + dx[i], p.y + dy[i]);
if (isValidLakePoint(temp.x, temp.y, graph) && !visitedGraph[temp.x][temp.y]) {
visitedGraph[temp.x][temp.y] = true;
queue.addLast(temp);
}
}
}
if (isValid == false) return -count;
return count;
}
static void fillLand(Point startPoint, char[][] graph) {
Deque<Point> queue = new LinkedList<>();
queue.add(startPoint);
int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, -1, 1};
graph[startPoint.x][startPoint.y] = '*';
while (!queue.isEmpty()) {
Point p = queue.pollLast();
for (int i = 0; i < dx.length; i++) {
if (isValidLakePoint(p.x + dx[i], p.y + dy[i], graph)) {
graph[p.x + dx[i]][p.y + dy[i]] = '*';
queue.addLast(new Point(p.x + dx[i], p.y + dy[i]));
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
char[][] graph = new char[n][m];
for (int row = 0; row < n; row++) {
String str = sc.next();
graph[row] = str.toCharArray();
}
boolean[][] visitedGraph = new boolean[graph.length][graph[0].length];
ArrayList<Lake> lakesResult = new ArrayList<>();
for (int row = 0; row < graph.length; row++) {
for (int col = 0; col < graph[0].length; col++) {
if (isValidLakePoint(row, col, graph) && visitedGraph[row][col] == false) {
int count = DFS(new Point(row, col), graph, visitedGraph);
if (count > 0) {
lakesResult.add(new Lake(new Point(row, col), count));
}
}
}
}
Comparator<Lake> cp =
new Comparator<Lake>() {
public int compare(Lake l1, Lake l2) {
if (l1.size != l2.size) {
return l1.size - l2.size;
} else {
if (l1.startPoint.x != l2.startPoint.x) {
return l1.startPoint.x - l2.startPoint.x;
} else {
return l1.startPoint.y - l2.startPoint.y;
}
}
}
};
Collections.sort(lakesResult, cp);
// result
int result = 0;
int needFill = lakesResult.size() - k;
int count = 0;
for (Lake l : lakesResult) {
if (count >= needFill) {
break;
}
fillLand(l.startPoint, graph);
count++;
result += l.size;
}
System.out.println(result);
for (char[] row : graph) {
for (char c : row) {
System.out.print(c);
}
System.out.println("");
}
}
}
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
class Lake {
Point startPoint;
int size;
Lake(Point s, int si) {
startPoint = s;
size = si;
}
}
|
package com.qrokodial.sparkle.components.ordered;
import com.qrokodial.sparkle.components.SparkleComponent;
public class MovableSparkleComponent<H extends OrderedComponentHolder> extends SparkleComponent<H> implements MovableComponent<H> {
/**
* Moves the component to the specified position in the holder (optional operation). Shifts the element currently
* at that position (if any) and any subsequent elements to the right (adds one to their indices). If the index is
* out of bounds, it corrects it to the closest element.
*
* @param index the target index
* @return the component instance
*/
@Override
public MovableSparkleComponent move(int index) {
getHolder().ifPresent(holder -> holder.moveComponent(getClass(), index));
return this;
}
}
|
package gromcode.main.lesson15.homework15_1;
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
User u1 = new User(1, "User1", "121212");
User u2 = new User(4, "User2", "12143212");
User u3 = new User(34, "User3", "1rfd21212");
User u4 = new User(3, "User4", "121235h212");
User[] userList = {u1, null, u3, u4};
UserRepository rep = new UserRepository(userList);
System.out.println(Arrays.toString(rep.getUserNames()));
System.out.println(Arrays.toString(rep.getUserIds()));
System.out.println(rep.save(u1));
/*
System.out.println("save");
User u5 = new User(9, "User5", "15212");
rep.save(u5);
System.out.println(Arrays.toString(rep.getUserNames()));
System.out.println("update");
User u6 = new User(4, "Updated user", "0000");
System.out.println(rep.update(u6));
System.out.println(Arrays.toString(rep.getUserNames()));
System.out.println("delete");
rep.delete(4);
System.out.println(Arrays.toString(rep.getUserNames()));
System.out.println("find");*/
/*
//--------------------------------------------------------------------------------------
System.out.println("\n\n-------------------------------------------------------------------------------------");
//UserRepository test
System.out.println("UserRepository test");
//method String[] getUserNames()
System.out.println("\nmethod String[] getUserNames()");
//1.nullable users
System.out.println("1. nullable users");
System.out.println(Arrays.toString(new UserRepository(new User[]{null, null}).getUserNames()));
//2.user name == null
System.out.println(Arrays.toString(new UserRepository(new User[]{new User(7, null, "121235h212")}).getUserNames()));
//3.similar user names
System.out.println(Arrays.toString(new UserRepository(new User[]{
new User(7, "A", "121235h212"),
new User(7, "A", "121235h212")
}).getUserNames()));
//method long[] getUserIds()
System.out.println("\nmethod long[] getUserIds()");
//1.nullable users
System.out.println("1. nullable users");
System.out.println(Arrays.toString(new UserRepository(new User[]{null, null}).getUserIds()));
//method String getUserNameById(long id)
System.out.println("\nmethod String getUserNameById(long id)");
//1.id not exists
System.out.println("1.id not exists");
System.out.println(rep.getUserNameById(67));
//2.user name is null
System.out.println("2.user name is null");
u4 = new User(3, null, "121235h212");
userList = new User[]{null, u2, null, u4};
rep = new UserRepository(userList);
System.out.println(rep.getUserNameById(3));
//method User getUserByName(String name)
System.out.println("\nmethod User getUserByName(String name)");
//1.user not exists
System.out.println("1.user not exists");
System.out.println(rep.getUserByName("User22"));
//2.name is null
System.out.println("2.name is null");
System.out.println(new UserRepository(new User[]{u1,u2, u3}).getUserByName(null));
//method User findUser(User user)
System.out.println("\nmethod User findUser(User user)");
//1. user not exists
System.out.println("1. user not exists");
System.out.println(Arrays.toString(rep.getUserNames()));
User uNew = new User(1, "User1", "121212");
System.out.println(rep.findUser(u1));
//2. user is null
System.out.println("2. user is null");
System.out.println(rep.findUser(null));
//method User getUserBySessionId(String session)
System.out.println("\nUser getUserBySessionId(String session)");
//1.session not exists
System.out.println("1.session not exists");
System.out.println(rep.getUserBySessionId("345dfg"));
//2. session null
System.out.println("2. session null");
System.out.println(rep.getUserBySessionId(null));
//method User save(User user)
System.out.println("\nmethod User save(User user)");
//1. save null
System.out.println("1. save null");
System.out.println(Arrays.toString(rep.getUserNames()));
System.out.println(rep.save(null));
System.out.println(Arrays.toString(rep.getUserNames()));
//2. save user with existing id
System.out.println("2. save user with existing id");
System.out.println(rep.save(new User(4, "User2", "12143212")));
//3. overflow array
System.out.println("3. overflow array");
System.out.println(rep.save(new User(41, "User41", "1")));
System.out.println(rep.save(new User(42, "User42", "2")));
System.out.println(rep.save(new User(56, "User56", "3")));
System.out.println(rep.save(new User(77, "User77", "4")));
System.out.println(Arrays.toString(rep.getUserNames()));
//User update(User user)
System.out.println("\nUser update(User user)");
//1. new user is null
System.out.println(rep.update(null));
//method delete(long id)
System.out.println("\nmethod delete(long id)");
//1. id not exists
rep.delete(416);
System.out.println(Arrays.toString(rep.getUserNames()));
*/
}
}
|
package cn.edu.cqut.service.impl;
import cn.edu.cqut.entity.Customer;
import cn.edu.cqut.stats.SimpleCategory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edu.cqut.entity.CustomerService;
import cn.edu.cqut.mapper.ServiceMapper;
import cn.edu.cqut.service.ServiceService;
import java.util.List;
@Service
public class ServiceServiceImpl extends ServiceImpl<ServiceMapper, CustomerService> implements ServiceService{
@Override
public List<SimpleCategory> getServiceComposition(QueryWrapper<Customer> queryWrapper) {
return baseMapper.selectServiceComposition(queryWrapper);
}
}
|
package com.silrait.bookssearch.domain;
public class Book {
private String id;
private String title;
private String author;
private String thumbnail;
private String url;
private Double averageRating;
public Book(){}
public Book(String id, String title, String author, String thumbnail, String url, Double averageRating) {
this.id = id;
this.title = title;
this.author = author;
this.thumbnail = thumbnail;
this.url = url;
this.averageRating = averageRating;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public Double getAverageRating() {
return averageRating;
}
public void setAverageRating(Double averageRating) {
this.averageRating = averageRating;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
package cs3500.animator.view;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import cs3500.animator.model.Animation;
import cs3500.animator.model.ChangeColorAnimation;
import cs3500.animator.model.MoveAnimation;
import cs3500.animator.model.Oval;
import cs3500.animator.model.Rectangle;
import cs3500.animator.model.RotateAnimation;
import cs3500.animator.model.ScaleAnimation;
import cs3500.animator.model.Shape;
/**
* Represents an abstract SVG, to be used by any view with SVG capabilities.
*/
abstract class AbstractSVG extends JFrame {
protected ArrayList<Shape> shapes;
protected int tempo;
/**
* Default constructor.
*/
public AbstractSVG() {
this.tempo = 1;
this.shapes = new ArrayList<>();
}
/**
* Constructor for AbstractSVG.
* @param shapes The shapes for the SVG output
* @param tempo The tempo for the animation
*/
public AbstractSVG(ArrayList<Shape> shapes, int tempo) {
this.shapes = shapes;
this.tempo = tempo;
}
/**
* Converts animations within list into a text description in SVG format.
* @param animations The animations to describe
* @return The SVG text description of the animations
*/
private String animationsToSVG(ArrayList<Animation> animations) {
String toReturn = "";
for (Animation a : animations) {
switch (a.animationType()) {
case "Color Change":
toReturn = toReturn + changeColorToSVG((ChangeColorAnimation) a);
break;
case "Move":
toReturn = toReturn + moveToSVG((MoveAnimation) a);
break;
case "Rotate":
toReturn = toReturn + rotateToSVG((RotateAnimation) a);
break;
case "Scale":
toReturn = toReturn + scaleToSVG((ScaleAnimation) a);
break;
default:
this.showErrorMessage("Animation type incompatible!");
}
}
return toReturn;
}
/**
* Converts the given oval into a text description in SVG format.
* @param oval the oval to describe
* @return The SVG text description of the given Oval
*/
private String ovalToSVG(Oval oval) {
int r = oval.getColor().getRed();
int g = oval.getColor().getGreen();
int b = oval.getColor().getBlue();
String toReturn = "";
toReturn = toReturn + "<ellipse id=\"" + oval.getName() + "\" cx=\"" + oval.getPosnX()
+ "\" cy=\"" + oval.getPosnY() + "\" rx=\"" + oval.getWidth() + "\""
+ " ry=\"" + oval.getHeight() + "\" fill=\"rgb(" + r + "," + g + "," + b
+ ")\" visibility=\"visible\"";
if (!(oval.getAnimationsToExecute().isEmpty())) {
toReturn = toReturn + " >\n";
ArrayList<Animation> animations = oval.getAnimationsToExecute();
Collections.sort(animations);
toReturn = toReturn + this.animationsToSVG(animations);
toReturn = toReturn + "</ellipse>\n";
}
else {
// no animations
toReturn = toReturn + " />\n";
}
return toReturn;
}
/**
* Converts the given rectangle into a text description in SVG format.
* @param rect the rectangle to describe
* @return The SVG text description of the given Rectangle
*/
private String rectToSVG(Rectangle rect) {
int r = rect.getColor().getRed();
int g = rect.getColor().getGreen();
int b = rect.getColor().getBlue();
String toReturn = "";
toReturn = toReturn + "<rect id=\"" + rect.getName() + "\" x=\"" + rect.getPosnX()
+ "\" y=\"" + rect.getPosnY() + "\" width=\"" + rect.getWidth() + "\""
+ " height=\"" + rect.getHeight() + "\" fill=\"rgb(" + r + "," + g + "," + b
+ ")\" visibility=\"visible\"";
if (!(rect.getAnimationsToExecute().isEmpty())) {
toReturn = toReturn + " >\n";
ArrayList<Animation> animations = rect.getAnimationsToExecute();
Collections.sort(animations);
toReturn = toReturn + this.animationsToSVG(animations);
toReturn = toReturn + "</rect>\n";
} else {
// no animations
toReturn = toReturn + " />\n";
}
return toReturn;
}
/**
* Converts the given ChangeColorAnimation into a text description in SVG format.
* @param animation the animation to describe
* @return the SVG text description of the given ChangeColorAnimation
*/
private String changeColorToSVG(ChangeColorAnimation animation) {
double duration = (animation.getEndTime() - animation.getStartTime()) / this.tempo;
String toReturn = " " + "<animate attributeName=\"fill\" attributeType=\"CSS\" "
+ "from=\"rgb(" + animation.getRFrom() + "," + animation.getGFrom() + ","
+ animation.getBFrom() + ")\" " + "to=\"rgb(" + animation.getRTo() + ","
+ animation.getGTo() + "," + animation.getBTo() + ")\""
+ " begin=\"" + (animation.getStartTime() / this.tempo) + "s\" dur=\""
+ duration + "s\""
+ " fill=\"freeze\" />\n";
return toReturn;
}
/**
* Converts the given MoveAnimation into a text description in SVG format.
* @param animation the animation to describe
* @return the SVG text description of the given MoveAnimation
*/
private String moveToSVG(MoveAnimation animation) {
String toReturn = "";
double duration = (animation.getEndTime() - animation.getStartTime()) / this.tempo;
// only add horizontal move description of there is a horizontal move
if (animation.getPosnYFrom() != animation.getPosnYTo()) {
toReturn = toReturn + " " + "<animate attributeName=\"x\" attributeType=\"XML\" "
+ "begin=\"" + (animation.getStartTime() / this.tempo) + "s\" dur=\""
+ duration + "s\""
+ " fill=\"freeze\" from=\"" + animation.getPosnXFrom() + "\" to=\""
+ animation.getPosnXTo() + "\" />\n";
}
if (animation.getPosnXFrom() != animation.getPosnXTo()) {
toReturn = toReturn + " " + "<animate attributeName=\"y\" attributeType=\"XML\" "
+ "begin=\"" + (animation.getStartTime() / this.tempo) + "s\" dur=\""
+ duration + "s\""
+ " fill=\"freeze\" from=\"" + animation.getPosnYFrom() + "\" to=\""
+ animation.getPosnYTo() + "\" />\n";
}
return toReturn;
}
/**
* Converts the given RotateAnimation into a text description in SVG format.
* @param animation the animation to describe
* @return the SVG text description of the given RotateAnimation
*/
private String rotateToSVG(RotateAnimation animation) {
double duration = (animation.getEndTime() - animation.getStartTime()) / this.tempo;
String toReturn = " "
+ "<animateTransform attributeName=\"transform\" attributeType=\"XML\""
+ " type=\"rotate\" from=\"" + animation.getAngleFrom() + "\" to = \""
+ animation.getAngleTo() + "\"" + " begin=\"" + (animation.getStartTime() / this.tempo)
+ "s\" dur=\"" + duration + "s\" fill=\"freeze\" />\n";
return toReturn;
}
/**
* Converts the given ScaleAnimation into a text description in SVG format.
* @param animation the animation to describe
* @return the SVG text description of the given ScaleAnimation
*/
private String scaleToSVG(ScaleAnimation animation) {
String toReturn = "";
double duration = (animation.getStartTime() - animation.getEndTime()) / this.tempo;
if (animation.getChangeHeight() != animation.getFromHeight()) {
toReturn = toReturn + " " + "<animate attributeName=\"x\" attributeType=\"XML\" "
+ "begin=\"" + (animation.getStartTime() / this.tempo) + "s\" dur=\""
+ duration + "s\""
+ " fill=\"freeze\" from=\"" + animation.getFromWidth() + "\" to=\""
+ animation.getChangeWidth() + "\" />\n";
}
if (animation.getChangeWidth() != animation.getFromWidth()) {
toReturn = toReturn + " " + "<animate attributeName=\"y\" attributeType=\"XML\" "
+ "begin=\"" + (animation.getStartTime() / this.tempo) + "s\" dur=\""
+ duration + "s\""
+ " fill=\"freeze\" from=\"" + animation.getFromHeight() + "\" to=\""
+ animation.getChangeHeight() + "\" />\n";
}
return toReturn;
}
/**
* Outputs the SVG format description as a String.
*
* @return the text description of the animation in SVG format as a String.
*/
public String getOutput() {
String result = "";
result = result + "<svg width=\"1000\" height=\"500\" version=\"1.1\" \n"
+ " xmlns=\"http://www.w3.org/2000/svg\">\n";
Collections.sort(shapes);
for (Shape a: shapes) {
if (a.getShapeType().equals("oval")) {
result = result + ovalToSVG((Oval) a);
result = result + "\n";
}
else {
result = result + rectToSVG((Rectangle) a);
result = result + "\n";
}
}
result = result + "</svg>";
return result;
}
/**
* Shows an error message.
* @param error Message to include in error
*/
public void showErrorMessage(String error) {
JOptionPane.showMessageDialog(this,error,
"Error",JOptionPane.ERROR_MESSAGE);
}
/**
* Gets the tempo of the animation.
* @return The tempo
*/
public int getTempo() {
int temp = this.tempo;
return temp;
}
}
|
package org.sayesaman.app9.config;
import android.app.Activity;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.Fullscreen;
import com.googlecode.androidannotations.annotations.NoTitle;
import com.googlecode.androidannotations.annotations.ViewById;
import org.sayesaman.R;
import org.sayesaman.database.dao.ConfigDao;
import org.sayesaman.database.model.Config;
import org.sayesaman.dialog.Statics;
/**
* Created by ameysami on 8/28/13.
*/
@EActivity(R.layout.app9)
@NoTitle
@Fullscreen
public class MyActivity extends Activity {
@Bean
ConfigDao dao;
@ViewById
TextView app9_my_place_;
@ViewById
CheckBox app9_my_place;
@ViewById
TextView app9_local_;
@ViewById
EditText app9_local_part1;
@ViewById
EditText app9_local_part2;
@ViewById
EditText app9_local_part3;
@ViewById
EditText app9_local_part4;
@ViewById
EditText app9_local_port;
@ViewById
TextView app9_web_;
@ViewById
EditText app9_web_part1;
@ViewById
EditText app9_web_part2;
@ViewById
EditText app9_web_part3;
@ViewById
EditText app9_web_part4;
@ViewById
EditText app9_web_port;
@ViewById
Button app9_btn_save;
@ViewById
Button app9_btn_cancel;
@AfterViews
public void after() {
app9_web_.setTypeface(Statics.getFontTypeFace_Titr());
app9_local_.setTypeface(Statics.getFontTypeFace_Titr());
app9_my_place_.setTypeface(Statics.getFontTypeFace_Titr());
app9_btn_save.setTypeface(Statics.getFontTypeFace_Titr());
app9_btn_cancel.setTypeface(Statics.getFontTypeFace_Titr());
// Config address = readDataFromAssets();
Config address = dao.readDataFromSd();
app9_my_place.setChecked(address.getAmIInLocal());
app9_local_part1.setText(address.getLocalPart1());
app9_local_part2.setText(address.getLocalPart2());
app9_local_part3.setText(address.getLocalPart3());
app9_local_part4.setText(address.getLocalPart4());
app9_local_port.setText(address.getLocalPort());
app9_web_part1.setText(address.getWebPart1());
app9_web_part2.setText(address.getWebPart2());
app9_web_part3.setText(address.getWebPart3());
app9_web_part4.setText(address.getWebPart4());
app9_web_port.setText(address.getWebPort());
//app9_my_place.requestFocus();
}
@Click
void app9_btn_save() {
Config address = new Config();
address.setAmIInLocal(app9_my_place.isChecked());
address.setLocalPart1(String.valueOf(app9_local_part1.getText()));
address.setLocalPart2(String.valueOf(app9_local_part2.getText()));
address.setLocalPart3(String.valueOf(app9_local_part3.getText()));
address.setLocalPart4(String.valueOf(app9_local_part4.getText()));
address.setLocalPort(String.valueOf(app9_local_port.getText()));
address.setWebPart1(String.valueOf(app9_web_part1.getText()));
address.setWebPart2(String.valueOf(app9_web_part2.getText()));
address.setWebPart3(String.valueOf(app9_web_part3.getText()));
address.setWebPart4(String.valueOf(app9_web_part4.getText()));
address.setWebPort(String.valueOf(app9_web_port.getText()));
dao.modifyXmlNode(address);
this.finish();
}
@Click
void app9_btn_cancel() {
this.finish();
}
}
|
package net.yustinus.crud.web.base;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import net.yustinus.crud.backend.beans.UserBean;
import net.yustinus.crud.backend.dto.RoleDto;
public class CustomSpringUserDetail implements UserDetails {
/**
*
*/
private static final long serialVersionUID = -4454090092614523090L;
private UserBean userBean;
public CustomSpringUserDetail() {
}
public CustomSpringUserDetail(UserBean userBean) {
this.setUserBean(userBean);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
if (this.userBean.getUserProfile().getRoles() !=null) {
for (RoleDto rd : this.userBean.getUserProfile().getRoles()) {
authorities.add(new SimpleGrantedAuthority(rd.getRoleName()));
}
}
return authorities;
}
@Override
public String getPassword() {
// TODO Auto-generated method stub
return this.userBean.getUserPassword();
}
@Override
public String getUsername() {
// TODO Auto-generated method stub
return this.userBean.getUsername();
}
@Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
}
|
package generator.util.structures;
import generator.visitors.AtomicValueType;
public class FunctionParameter {
private AtomicValueType type;
private String variableName;
public FunctionParameter(String variableName, AtomicValueType type) {
this.type = type;
this.variableName = variableName;
}
public AtomicValueType getType() {
return type;
}
public String getVariableName() {
return variableName;
}
@Override
public String toString() {
return this.variableName + ": " + this.getType();
}
}
|
package com.testyantra.empspringmvc.jaxb.beans;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("employee-response")
public class EmployeeResponse {
@JsonProperty("status-code")
private int statusCode;
private String massage;
private String decription;
private List<EmployeeInfoBean> beans;
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getMassage() {
return massage;
}
public void setMassage(String massage) {
this.massage = massage;
}
public String getDecription() {
return decription;
}
public void setDecription(String decription) {
this.decription = decription;
}
public List<EmployeeInfoBean> getBeans() {
return beans;
}
public void setBeans(List<EmployeeInfoBean> beans) {
this.beans = beans;
}
}
|
package com.share.dao;
import com.share.template.HibernateTemplate;
public class DLResourceDao extends HibernateTemplate {
}
|
package com.jyn.leetcode.base;
/*
* https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
*/
public class ListNode {
int val;
public ListNode first;
public ListNode next;
ListNode(int x) {
val = x;
}
public static ListNode getListNodeTest() {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
ListNode node6 = new ListNode(6);
node1.next = node2;
node2.first = node1;
node2.next = node3;
node3.first = node2;
node3.next = node4;
node4.first = node3;
node4.next = node5;
node5.first = node4;
node5.next = node6;
node6.first = node5;
node6.next = null;
return node1;
}
public static void print(ListNode head) {
while (head != null) {
System.out.print(head.val+" -> ");
head = head.next;
}
System.out.println("null");
}
}
|
public class Truck implements Vehicle {
public Truck() {
}
@Override
public void honk() {
System.out.println("Truck HONK");
}
}
|
package za.co.jehuco.snooker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SnookerApplication {
public static void main(String[] args) {
SpringApplication.run(SnookerApplication.class, args);
}
}
|
package com.github.dongchan.scheduler;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author DongChan
* @date 2020/10/23
* @time 4:03 PM
*/
public class DueExecutionBatch {
private int threadPoolSize;
private final int generationNumber;
private final AtomicInteger executionsLeftInBatch;
private boolean possiblyMoreExecutionsInDb;
public DueExecutionBatch(int threadPoolSize, int generationNumber, int executionsAdded, boolean possiblyMoreExecutionsInDb) {
this.threadPoolSize = threadPoolSize;
this.generationNumber = generationNumber;
this.possiblyMoreExecutionsInDb = possiblyMoreExecutionsInDb;
this.executionsLeftInBatch = new AtomicInteger(executionsAdded);
}
}
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head.next==null)return null;
ArrayList<ListNode> list = new ArrayList<>();
ListNode curr = head;
while(curr!=null){
list.add(curr);
curr=curr.next;
}
if(list.size()-n-1>=0){
list.get(list.size()-n-1).next=list.get(list.size()-n).next;
return head;
}
else return head.next;
}
} |
package payment.domain.service;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import payment.domain.model.Order;
import payment.domain.model.OrderStatus;
/**
* @author claudioed on 26/06/17. Project docker-aws-devry
*/
@Component
public class OrderReceiver {
private final ObjectMapper mapper;
private final AmazonSQS sqs;
private final String orderQueue;
private final PaymentProcessor paymentProcessor;
private final OrderUpdaterDispatcher orderUpdaterDispatcher;
@Autowired
public OrderReceiver(ObjectMapper mapper, AmazonSQS sqs, @Qualifier("orderQueue") String orderQueue,
PaymentProcessor paymentProcessor,
OrderUpdaterDispatcher orderUpdaterDispatcher) {
this.mapper = mapper;
this.sqs = sqs;
this.orderQueue = orderQueue;
this.paymentProcessor = paymentProcessor;
this.orderUpdaterDispatcher = orderUpdaterDispatcher;
}
@Scheduled(fixedRate = 30000)
public void receive(){
final List<Message> newMessages = this.sqs.receiveMessage(this.orderQueue).getMessages();
newMessages.parallelStream().forEach(message -> {
try {
final Order order = mapper.readValue(message.getBody(), Order.class);
final OrderStatus orderStatus = this.paymentProcessor.process(order);
this.orderUpdaterDispatcher.sendUpdate(orderStatus);
this.sqs.deleteMessage(this.orderQueue, message.getReceiptHandle());
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
|
package rest.test.happilyy.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import rest.test.happilyy.dto.CheatCode;
import rest.test.happilyy.dto.CheatCodeCreationRequest;
import rest.test.happilyy.repo.CheatCodeRepository;
@RestController
public class CheatCodeController {
@Autowired
CheatCodeRepository repo;
@RequestMapping("/cheat_code" )
public List<CheatCode> allCheatCodes(@RequestParam(value="name", defaultValue="World") String name) {
return repo.getAllCheatCodes();
}
@RequestMapping(value={"/console/{consoleName}/{gameName}"})
public List<CheatCode> console(@PathVariable String consoleName,@PathVariable String gameName) {
return repo.getCheatCodeByConsoleAndGame(consoleName,gameName);
}
@RequestMapping(value={"/game/{gameName}"})
public List<CheatCode> game(@PathVariable String gameName) {
return repo.getCheatCodeByGame(gameName);
}
@PutMapping(value={"/game"})
public void addCheatCode(@RequestBody CheatCodeCreationRequest request) {
repo.addCheatCode(request.cheatCodeId, request.cheatCodeInput, request.gameName, request.consoleName);
}
} |
package com.jxtb.jdbcrud;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.core.dao.JDBCBaseDao;
import org.apache.log4j.Logger;
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 17-3-27
* Time: 上午11:27
* To change this template use File | Settings | File Templates.
*/
public class TestPreparedStatement {
private static Logger logger = Logger.getLogger(TestPreparedStatement.class.getName());
public static void main(String[] args) {
TestPreparedStatement.update();
}
/**
* 更新
*/
public static void update(){
Connection conn = null;
PreparedStatement pstmt = null;
// 1、加载驱动
try {
// 2、建立连接
conn = JDBCBaseDao.getConnection();
// 3、更新狗狗信息到数据库
String sql="update cbd_test set userPsw=? where userName=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "admin");
pstmt.setString(2, "jxtb");
pstmt.executeUpdate();
logger.info("成功更新狗狗信息!");
System.out.println("成功更新狗狗信息!");
} catch (SQLException e) {
logger.error(e);
} finally {
// 4、关闭Statement和数据库连接
try {
if (null != pstmt) {
pstmt.close();
}
if (null != conn) {
conn.close();
}
} catch (SQLException e) {
logger.error(e);
}
}
}
}
|
package cn.hellohao.dao;
import cn.hellohao.pojo.UploadConfig;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UploadConfigMapper {
UploadConfig getUpdateConfig();
Integer setUpdateConfig(UploadConfig uploadConfig);
}
|
package org.data.persistance.repository;
import org.data.persistance.model.Users;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<Users, Long> , UserRepositoryCustom{
Users findByUsernameAndActive(String name, boolean active);
Users findByEmail(String email);
Users findByUsername(String name);
}
|
package com.xianzaishi.wms.tmscore.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.xianzaishi.wms.tmscore.vo.TimingDistributionWatiSeqVO;
import com.xianzaishi.wms.tmscore.vo.TimingDistributionWatiSeqQueryVO;
import com.xianzaishi.wms.common.exception.BizException;
import com.xianzaishi.wms.tmscore.service.itf.ITimingDistributionWatiSeqService;
import com.xianzaishi.wms.tmscore.manage.itf.ITimingDistributionWatiSeqManage;
public class TimingDistributionWatiSeqServiceImpl implements
ITimingDistributionWatiSeqService {
@Autowired
private ITimingDistributionWatiSeqManage timingDistributionWatiSeqManage = null;
public ITimingDistributionWatiSeqManage getTimingDistributionWatiSeqManage() {
return timingDistributionWatiSeqManage;
}
public void setTimingDistributionWatiSeqManage(
ITimingDistributionWatiSeqManage timingDistributionWatiSeqManage) {
this.timingDistributionWatiSeqManage = timingDistributionWatiSeqManage;
}
public Boolean addTimingDistributionWatiSeqVO(
TimingDistributionWatiSeqVO timingDistributionWatiSeqVO) {
timingDistributionWatiSeqManage
.addTimingDistributionWatiSeqVO(timingDistributionWatiSeqVO);
return true;
}
public List<TimingDistributionWatiSeqVO> queryTimingDistributionWatiSeqVOList(
TimingDistributionWatiSeqQueryVO timingDistributionWatiSeqQueryVO) {
return timingDistributionWatiSeqManage
.queryTimingDistributionWatiSeqVOList(timingDistributionWatiSeqQueryVO);
}
public TimingDistributionWatiSeqVO getTimingDistributionWatiSeqVOByID(
Long id) {
return (TimingDistributionWatiSeqVO) timingDistributionWatiSeqManage
.getTimingDistributionWatiSeqVOByID(id);
}
public Boolean modifyTimingDistributionWatiSeqVO(
TimingDistributionWatiSeqVO timingDistributionWatiSeqVO) {
return timingDistributionWatiSeqManage
.modifyTimingDistributionWatiSeqVO(timingDistributionWatiSeqVO);
}
public Boolean deleteTimingDistributionWatiSeqVOByID(Long id) {
return timingDistributionWatiSeqManage
.deleteTimingDistributionWatiSeqVOByID(id);
}
public boolean assign(
TimingDistributionWatiSeqVO timingDistributionWatiSeqVO) {
return timingDistributionWatiSeqManage
.assign(timingDistributionWatiSeqVO);
}
public boolean assignToNormal(
TimingDistributionWatiSeqVO timingDistributionWatiSeqVO) {
return timingDistributionWatiSeqManage
.assignToNormal(timingDistributionWatiSeqVO);
}
public boolean deleteByDistributionID(Long distributionID) {
return timingDistributionWatiSeqManage
.deleteByDistributionID(distributionID);
}
}
|
/*
* 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.struts2.dao.logindao;
import com.struts2.util.mapping.Onlineaccount;
import com.struts2.util.hibernateUtil.NewHibernateUtil;
import java.util.ArrayList;
import java.util.List;
import com.struts2.model.login.LoginModelClass;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
/**
*
* @author yomal_m
*/
public class LoginDAO {
public int LoginAuth(LoginModelClass model){
int dataAvailable=0;
SessionFactory factory = NewHibernateUtil.getSessionFactory();
Session s = factory.openSession();
List<Onlineaccount> userroleList = new ArrayList<>();
//String sql = "from Hib as u where u.lastName='"+model.getUsername()+"' and u.firstName='"+model.getPassword()+"'";
//Query query = s.createQuery(sql);
String sql = "from Onlineaccount as u where u.userName=:user_name and u.password=:password";
Query query = s.createQuery(sql).setString("user_name", model.getUsername()).setString("password", model.getPassword());
java.util.List list = query.list();
System.out.println("List size : "+list.size());
if(list.size()>0){
return dataAvailable =1;
}else if(list.isEmpty()){
return dataAvailable = 0;
}
return dataAvailable;
}
}
|
package com.karya.model;
import java.io.Serializable;
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="shippingrule001mb")
public class ShippingRule001MB implements Serializable{
private static final long serialVersionUID = -723583058586873479L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "sruleId")
private int sruleId;
@Column(name="sruleName")
private String sruleName;
@Column(name="status")
private String status;
@Column(name="sruleLabel")
private String sruleLabel;
public int getSruleId() {
return sruleId;
}
public void setSruleId(int sruleId) {
this.sruleId = sruleId;
}
public String getSruleName() {
return sruleName;
}
public void setSruleName(String sruleName) {
this.sruleName = sruleName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSruleLabel() {
return sruleLabel;
}
public void setSruleLabel(String sruleLabel) {
this.sruleLabel = sruleLabel;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
package com.trump.auction.trade.api;
import com.trump.auction.trade.model.AuctionRuleModel;
/**
* 拍卖
*
* @author zhangliyan
* @create 2018-01-02 17:48
**/
public interface AuctionRuleStubService {
/**
* 添加
* @param auctionRuleModel
* @return
*/
int insertAuctionRule(AuctionRuleModel auctionRuleModel);
/**
* 更新竞拍规则
* @param auctionRuleModel
* @return
*/
int updateAuctionRule(AuctionRuleModel auctionRuleModel);
/**
* 删除
* @param ids
* @return
*/
int deleteAuctionRule(String[] ids);
/**
* 启用竞拍规则
* @param auctionRuleModel
* @return
*/
int enable(AuctionRuleModel auctionRuleModel) throws Exception;
}
|
/*
* generated by Xtext
*/
package org.yazgel.snow.notation.text;
import org.eclipse.xtext.junit4.IInjectorProvider;
import com.google.inject.Injector;
public class ModuleUiInjectorProvider implements IInjectorProvider {
@Override
public Injector getInjector() {
return org.yazgel.snow.notation.text.ui.internal.ModuleActivator.getInstance().getInjector("org.yazgel.snow.notation.text.Module");
}
}
|
package com.git.cloud.bill.model.vo;
/**
* 购买信息
*/
public class Shopping_lists {
private Parameters parameters;
private String service_id;
private String instance_id;
public void setParameters(Parameters parameters) {
this.parameters = parameters;
}
public Parameters getParameters() {
return parameters;
}
public void setService_id(String service_id) {
this.service_id = service_id;
}
public String getService_id() {
return service_id;
}
public void setInstance_id(String instance_id) {
this.instance_id = instance_id;
}
public String getInstance_id() {
return instance_id;
}
} |
package num.grapecity.lab4;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
private EditText name, pass;
private TextView login_info;
private String user_name, password;
private SQLiteDatabase database;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.user_name);
pass = findViewById(R.id.password);
login_info = findViewById(R.id.info_login);
database = openOrCreateDatabase("mobileLab4",MODE_PRIVATE,null);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
this.user_name = sharedpreferences.getString(Name, "");
name.setText(user_name);
Log.i("Lab4","Хадгалагдсан нэр "+user_name);
// database.execSQL("DROP TABLE IF EXISTS UserInfo");
}
public void login(View view) {
this.user_name = name.getText().toString();
this.password = pass.getText().toString();
try {
@SuppressLint("Recycle") Cursor res = database.rawQuery("Select * from UserInfo where Username = '" + user_name + "' AND Password = '" + password + "';", null);
Log.i("Lab4 ", "Login name: " + user_name + " " + res.getCount());
if (res.getCount() == 1) {
if (res.moveToFirst()) {
Log.i("Lab4", "Amjilttai newterlee. ");
String gender = res.getString(res.getColumnIndex("gender"));
String phone = res.getString(res.getColumnIndex("phone"));
String date = res.getString(res.getColumnIndex("date"));
int age = res.getInt(res.getColumnIndex("age"));
login_info.setText("Амжилттай.");
login_info.setTextColor(Color.GREEN);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, user_name);
editor.apply();
Intent intent = new Intent();
intent.setAction("android.intent.action.UserInfo");
intent.putExtra("name", user_name);
intent.putExtra("gender", gender);
intent.putExtra("phone", phone);
intent.putExtra("date", date);
intent.putExtra("age", age);
intent.putExtra("pass", password);
startActivity(intent);
}
} else {
Log.i("Lab4", "Newtreh ner nuuts ug buruu bna");
login_info.setText("Нэвтрэх нэр эсвэл нууц үг буруу байна.");
login_info.setTextColor(Color.RED);
}
} catch (Exception e) {
Log.e("Lab 4", Objects.requireNonNull(e.getMessage()));
}
}
public void register(View view) {
Log.i("Lab4 ","Burtgel hiigdeh gej bna.");
Intent intent = new Intent(this, SignUp.class);
this.user_name = name.getText().toString();
this.password = pass.getText().toString();
intent.putExtra("name", user_name);
intent.putExtra("password", password);
startActivity(intent);
}
} |
package net.lvcy.card.entity;
public interface CombinSeven extends CombinCard{
}
|
/*
* This code is released under the terms and conditions of the Common Public License Version 1.0.
* You should have received a copy of the license with the code, if you didn't
* you can get it at the quantity project homepage or at
* <a href="http://www.opensource.org/licenses/cpl.php">http://www.opensource.org/licenses/cpl.php</a>
*/
package com.schneide.quantity.mechanicalQuantities.handlers;
import com.schneide.quantity.*;
import com.schneide.quantity.mechanicalQuantities.*;
/**
*
* @author <a href="mailto:matthias.kempka@softwareschneiderei.de">Matthias Kempka</a>, <a href="mailto:anja.hauth@softwareschneiderei.de">Anja Hauth</a>
*/
public class AreaHandler {
/**
* Constructor for AreaHandler.
*/
public AreaHandler() {
super();
}
public static SquareKilometer changeToSquareKilometer(AbstractArea abstractArea) {
SquareKilometer result = new SquareKilometer(0);
result.add(abstractArea);
return result;
}
public static SquareMeter changeToSquareMeter(AbstractArea abstractArea) {
SquareMeter result = new SquareMeter(0);
result.add(abstractArea);
return result;
}
public static SquareMillimeter changeToSquareMillimeter(AbstractArea abstractArea) {
SquareMillimeter result = new SquareMillimeter(0);
result.add(abstractArea);
return result;
}
public static SquareMicrometer changeToSquareMicrometer(AbstractArea abstractArea) {
SquareMicrometer result = new SquareMicrometer(0);
result.add(abstractArea);
return result;
}
public static SquareNanometer changeToSquareNanometer(AbstractArea abstractArea) {
SquareNanometer result = new SquareNanometer(0);
result.add(abstractArea);
return result;
}
public static SquareKilometer changeToSquareKilometer(Quantity quantity) throws WrongUnitException{
Quantity clonedQuantity = (Quantity) quantity.clone();
clonedQuantity.changeToUnit(FrequentlyUsedUnits.getSquareKilometer());
ValueTransfer resultValue = clonedQuantity.getValueWithPower();
SquareKilometer result = new SquareKilometer(resultValue.getValue(), resultValue.getPower());
return result;
}
public static SquareMeter changeToSquareMeter(Quantity quantity) throws WrongUnitException{
Quantity clonedQuantity = (Quantity) quantity.clone();
clonedQuantity.changeToUnit(FrequentlyUsedUnits.getSquareMeter());
ValueTransfer resultValue = clonedQuantity.getValueWithPower();
SquareMeter result = new SquareMeter(resultValue.getValue(), resultValue.getPower());
return result;
}
public static SquareMillimeter changeToSquareMillimeter(Quantity quantity) throws WrongUnitException{
Quantity clonedQuantity = (Quantity) quantity.clone();
clonedQuantity.changeToUnit(FrequentlyUsedUnits.getSquareMillimeter());
ValueTransfer resultValue = clonedQuantity.getValueWithPower();
SquareMillimeter result = new SquareMillimeter(resultValue.getValue(), resultValue.getPower());
return result;
}
public static SquareMicrometer changeToSquareMicrometer(Quantity quantity) throws WrongUnitException{
Quantity clonedQuantity = (Quantity) quantity.clone();
clonedQuantity.changeToUnit(FrequentlyUsedUnits.getSquareMicrometer());
ValueTransfer resultValue = clonedQuantity.getValueWithPower();
SquareMicrometer result = new SquareMicrometer(resultValue.getValue(), resultValue.getPower());
return result;
}
public static SquareNanometer changeToSquareNanometer(Quantity quantity) throws WrongUnitException{
Quantity clonedQuantity = (Quantity) quantity.clone();
clonedQuantity.changeToUnit(FrequentlyUsedUnits.getSquareNanometer());
ValueTransfer resultValue = clonedQuantity.getValueWithPower();
SquareNanometer result = new SquareNanometer(resultValue.getValue(), resultValue.getPower());
return result;
}
}
|
package br.com.douglastuiuiu.biometricengine.job;
import br.com.douglastuiuiu.biometricengine.exception.ServiceException;
import br.com.douglastuiuiu.biometricengine.service.StorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author douglas
* @since 06/04/2017
*/
@Component
public class StoragePurgeJob {
private final static Logger logger = LoggerFactory.getLogger(StoragePurgeJob.class);
@Autowired
private StorageService storageService;
@Scheduled(cron = "${batch.scheduler.storagepurge.cron}")
public void run() {
try {
storageService.purgeAnalyzeExpiredFiles();
} catch (ServiceException e) {
logger.error(e.getMessage(), e);
}
}
}
|
package com.leyton.flow.activator.inter;
import org.springframework.messaging.Message;
public interface HttpActivator {
void print(Message<?> message);
}
|
package rmi.server;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import rmi.libs.NguyenTo;
public class TinhToan extends UnicastRemoteObject implements NguyenTo {
public TinhToan() throws RemoteException {
}
@Override
public boolean KTSNT(int n) throws RemoteException {
if(n < 2)
return false;
else
{
if(n == 2 || n== 3)
return true;
else
{
for (int i = 2; i <= Math.sqrt(n); i++) {
if( n % i ==0 ){
return false;
}
}
}
return true;
}
}
/* @Override
public ArrayList<Integer> KetQua(int n) throws RemoteException {
ArrayList<Integer> arrL = new ArrayList<>();
for (int i = 0; i < n; i++) {
if(KTSNT(i) == true)
arrL.add(i);
}
return arrL;
}
*/
}
|
package cas2xb3_finalprototype;
import java.util.ArrayList;
import java.util.Scanner;
/*
* Sorts all LuggageT objects by claim numbers using ArrayLists.
*/
public class Merge {
private ArrayList<LuggageT> strList;
// Constructor
public Merge(ArrayList<LuggageT> input) {
strList = input;
}
public void sort() {
strList = mergeSort(strList);
}
public ArrayList<LuggageT> mergeSort(ArrayList<LuggageT> whole) {
ArrayList<LuggageT> left = new ArrayList<LuggageT>();
ArrayList<LuggageT> right = new ArrayList<LuggageT>();
int center;
if (whole.size() == 1) {
return whole;
} else {
center = whole.size()/2;
// copy the left half of whole into the left.
for (int i=0; i<center; i++) {
left.add(whole.get(i));
}
//copy the right half of whole into the new arraylist.
for (int i=center; i<whole.size(); i++) {
right.add(whole.get(i));
}
// Sort the left and right halves of the arraylist.
left = mergeSort(left);
right = mergeSort(right);
// Merge the results back together.
merge(left, right, whole);
}
return whole;
}
private void merge(ArrayList<LuggageT> left, ArrayList<LuggageT> right, ArrayList<LuggageT> whole) {
int leftIndex = 0;
int rightIndex = 0;
int wholeIndex = 0;
while (leftIndex < left.size() && rightIndex < right.size()) {
if ( (left.get(leftIndex).getClaimNumber().compareTo(right.get(rightIndex).getClaimNumber())) < 0) {
whole.set(wholeIndex, left.get(leftIndex));
leftIndex++;
} else {
whole.set(wholeIndex, right.get(rightIndex));
rightIndex++;
}
wholeIndex++;
}
ArrayList<LuggageT> rest;
int restIndex;
if (leftIndex >= left.size()) {
rest = right;
restIndex = rightIndex;
} else {
rest = left;
restIndex = leftIndex;
}
// Copy the rest of whichever ArrayList (left or right) was not used up.
for (int i=restIndex; i<rest.size(); i++) {
whole.set(wholeIndex, rest.get(i));
wholeIndex++;
}
}
public void show() {
System.out.println("Sorted:");
for (int i=0; i< strList.size();i++) {
System.out.println(strList.get(i));
}
}
public static void main(String[] args) throws Exception {
ArrayList<LuggageT> input = new ArrayList<LuggageT>();
FileReading a = new FileReading();
input = a.luggage();
Merge test = new Merge(input);
test.sort();
System.out.println(input.get(0).getClaimNumber());
}
} |
public class StringAlgo {
boolean matchExpUtil(char[] exp, char[] str, int i, int j) {
if (i == exp.length && j == str.length) {
return true;
}
if ((i == exp.length && j != str.length) || (i != exp.length && j == str.length)) {
return false;
}
if (exp[i] == '?' || exp[i] == str[j]) {
return matchExpUtil(exp, str, i + 1, j + 1);
}
if (exp[i] == '*') {
return matchExpUtil(exp, str, i + 1, j) || matchExpUtil(exp, str, i, j + 1)
|| matchExpUtil(exp, str, i + 1, j + 1);
}
return false;
}
boolean matchExp(char[] exp, char[] str) {
return matchExpUtil(exp, str, 0, 0);
}
int match(char[] source, char[] pattern) {
int iSource = 0;
int iPattern = 0;
int sourceLen = source.length;
int patternLen = pattern.length;
for (iSource = 0; iSource < sourceLen; iSource++) {
if (source[iSource] == pattern[iPattern]) {
iPattern++;
}
if (iPattern == patternLen) {
return 1;
}
}
return 0;
}
char[] myStrdup(char[] src) {
int index = 0;
char[] dst = new char[src.length];
for (char ch : src) {
dst[index] = ch;
}
return dst;
}
boolean isPrime(int n) {
boolean answer = (n > 1) ? true : false;
for (int i = 2; i * i < n; ++i) {
if (n % i == 0) {
answer = false;
break;
}
}
return answer;
}
int myAtoi(String str) {
int value = 0;
int size = str.length();
for (int i = 0; i < size; i++) {
char ch = str.charAt(i);
value = (value << 3) + (value << 1) + (ch - '0');
}
return value;
}
boolean isUniqueChar(String str) {
int[] bitarr = new int[26];
for (int i = 0; i < 26; i++) {
bitarr[i] = 0;
}
int size = str.length();
for (int i = 0; i < size; i++) {
char c = str.charAt(i);
if ('A' <= c && 'Z' >= c) {
c = (char) (c - 'A');
} else if ('a' <= c && 'z' >= c) {
c = (char) (c - 'a');
} else {
System.out.println("Unknown Char!\n");
return false;
}
if (bitarr[c] != 0) {
System.out.println("Duplicate detected!\n");
return false;
}
}
System.out.println("No duplicate detected!\n");
return true;
}
char ToUpper(char s) {
if (s >= 97 && s <= (97 + 25)) {
s = (char) (s - 32);
}
return s;
}
char ToLower(char s) {
if (s >= 65 && s <= (65 + 25)) {
s = (char) (s + 32);
}
return s;
}
char LowerUpper(char s) {
if (s >= 97 && s <= (97 + 25)) {
s = (char) (s - 32);
} else if (s >= 65 && s <= (65 + 25)) {
s = (char) (s + 32);
}
return s;
}
boolean isPermutation(String s1, String s2) {
int[] count = new int[256];
int length = s1.length();
if (s2.length() != length) {
System.out.println("is permutation return false\n");
return false;
}
for (int i = 0; i < 256; i++) {
count[i] = 0;
}
for (int i = 0; i < length; i++) {
char ch = s1.charAt(i);
count[ch]++;
ch = s2.charAt(i);
count[ch]--;
}
for (int i = 0; i < length; i++) {
if (count[i] != 0) {
System.out.println("is permutation return false\n");
return false;
}
}
System.out.println("is permutation return true\n");
return true;
}
boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j && str.charAt(i) == str.charAt(j)) {
i++;
j--;
}
if (i < j) {
System.out.println("String is not a Palindrome");
return false;
} else {
System.out.println("String is a Palindrome");
return true;
}
}
int pow(int x, int n) {
int value;
if (n == 0) {
return (1);
} else if (n % 2 == 0) {
value = pow(x, n / 2);
return (value * value);
} else {
value = pow(x, n / 2);
return (x * value * value);
}
}
int myStrcmp(String a, String b) {
int index = 0;
int len1 = a.length();
int len2 = b.length();
int minlen = len1;
if (len1 > len2) {
minlen = len2;
}
while (index < minlen && a.charAt(index) == b.charAt(index)) {
index++;
}
if (index == len1 && index == len2) {
return 0;
} else if (len1 == index) {
return -1;
} else if (len2 == index) {
return 1;
} else {
return a.charAt(index) - b.charAt(index);
}
}
void reverseString(char[] a) {
int lower = 0;
int upper = a.length - 1;
char tempChar;
while (lower < upper) {
tempChar = a[lower];
a[lower] = a[upper];
a[upper] = tempChar;
lower++;
upper--;
}
}
void reverseString(char[] a, int lower, int upper) {
char tempChar;
while (lower < upper) {
tempChar = a[lower];
a[lower] = a[upper];
a[upper] = tempChar;
lower++;
upper--;
}
}
void reverseWords(char[] a) {
int length = a.length;
int lower, upper = -1;
lower = 0;
for (int i = 0; i <= length; i++) {
if (a[i] == ' ' || a[i] == '\0') {
reverseString(a, lower, upper);
lower = i + 1;
upper = i;
} else {
upper++;
}
}
reverseString(a, 0, length - 1);
}
void printAnagram(char[] a) {
int n = a.length;
printAnagram(a, n, n);
}
void printAnagram(char[] a, int max, int n) {
if (max == 1) {
System.out.println(a.toString());
}
for (int i = -1; i < max - 1; i++) {
if (i != -1) {
a[i] ^= a[max - 1] ^= a[i] ^= a[max - 1];
}
printAnagram(a, max - 1, n);
if (i != -1) {
a[i] ^= a[max - 1] ^= a[i] ^= a[max - 1];
}
}
}
void shuffle(char[] ar) {
int n = ar.length / 2;
int count = 0;
int k = 1;
char temp = '\0';
for (int i = 1; i < n; i = i + 2) {
temp = ar[i];
k = i;
do {
k = (2 * k) % (2 * n - 1);
temp ^= ar[k] ^= temp ^= ar[k];
count++;
} while (i != k);
if (count == (2 * n - 2)) {
break;
}
}
}
char[] addBinary(char[] first, char[] second) {
int size1 = first.length;
int size2 = second.length;
int totalIndex;
char[] total;
if (size1 > size2) {
total = new char[size1 + 2];
totalIndex = size1;
} else {
total = new char[size2 + 2];
totalIndex = size2;
}
total[totalIndex + 1] = '\0';
int carry = 0;
size1--;
size2--;
while (size1 >= 0 || size2 >= 0) {
int firstValue = (size1 < 0) ? 0 : first[size1] - '0';
int secondValue = (size2 < 0) ? 0 : second[size2] - '0';
int sum = firstValue + secondValue + carry;
carry = sum >> 1;
sum = sum & 1;
total[totalIndex] = (sum == 0) ? '0' : '1';
totalIndex--;
size1--;
size2--;
}
total[totalIndex] = (carry == 0) ? '0' : '1';
return total;
}
} |
package com.fanfte.designPattern.decorator;
/**
* Created by tianen on 2018/9/28
*
* @author fanfte
* @date 2018/9/28
**/
public class Suit extends HeroDecorator {
private Hero decoratedHero;
public Suit(Hero decoratedHero) {
super(decoratedHero);
}
@Override
public void init() {
super.init();
getSkin();
}
private void getSkin() {
System.out.println("Wear a skin.");
}
public static void main(String[] args) {
Victor victor = new Victor();
Suit suit = new Suit(victor);
suit.init();
}
}
|
package com.nextLevel.hero.mnghumanResource.model.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import com.nextLevel.hero.mnghumanResource.model.dao.MngHumanResourceMapper;
import com.nextLevel.hero.mnghumanResource.model.dto.JobDTO;
import com.nextLevel.hero.mnghumanResource.model.dto.MemberListDTO;
import com.nextLevel.hero.mnghumanResource.model.dto.MngHumanResourceDTO;
import com.nextLevel.hero.mnghumanResource.model.dto.RankSalaryStepDTO;
import com.nextLevel.hero.mnghumanResource.model.dto.SalaryStepDTO;
import com.nextLevel.hero.mnghumanResource.model.dto.VacationControlDTO;
@Service("mngHumanResourceService")
public class MngHumanResourceServiceImpl implements MngHumanResourceService {
private MngHumanResourceMapper mngHumanResourceMapper;
@Autowired
public MngHumanResourceServiceImpl(MngHumanResourceMapper mngHumanResourceMapper) {
this.mngHumanResourceMapper = mngHumanResourceMapper;
}
@Override
public int insertMember(MngHumanResourceDTO mngHumanResourceDTO, int companyNo) {
RankSalaryStepDTO rankSalaryStepDTO = new RankSalaryStepDTO();
VacationControlDTO vacationControlDTO = new VacationControlDTO();
int insertEmployeeResult = 0;
int insertMemberCompanyResult = 0;
int insertMilitaryResult = 0;
int insertVeteranResult = 0;
int insertAppointmentResult = 0;
int insertGraduatedResult = 0;
int insertCareerResult = 0;
int insertFamilyResult = 0;
int insertUserAuthResult = 0;
java.sql.Date selectRankSalaryStepResult;
List<VacationControlDTO> selectVacationControlResult;
int insertVacationControlResult = 0;
int insertFamilyUpdateResult = 0;
int insertEmpSalaryStepResult = 0;
int insertEmpSalaryStepUpdateResult = 0;
int insertFourInsuranceDeductResult = 0;
int selectFamilyUpdateResult = 0;
int insertEmpUpdateResult = 0;
int selectEmpSalaryStepResult = 0;
java.sql.Date startDate = null;
MngHumanResourceDTO selectRankResult;
int insertMemberResult = mngHumanResourceMapper.insertMember(mngHumanResourceDTO, companyNo); //Member(유저) 테이블 인서트
int idNo = 0;
if (insertMemberResult > 0 ) {
idNo = mngHumanResourceMapper.selectNewMemberNumber(); //맴버 번호(사번)를 조회
mngHumanResourceDTO.setIdNo(idNo);
insertEmployeeResult = mngHumanResourceMapper.insertEmployee(mngHumanResourceDTO, companyNo); //Employee(회원)테이블 인서트
insertEmpUpdateResult = mngHumanResourceMapper.insertEmpUpdate(mngHumanResourceDTO, companyNo); //EmployeeUpdate(회원)테이블 인서트
}
if (insertEmployeeResult > 0 ) {
insertMemberCompanyResult = mngHumanResourceMapper.insertMemberCompany(mngHumanResourceDTO, companyNo); //MemberCompany테이블 인서트
} if (insertMemberCompanyResult > 0) {
insertMilitaryResult = mngHumanResourceMapper.insertMilitary(mngHumanResourceDTO, companyNo); //MILITARY_SERVICE 테이블 인서트
} if (insertMilitaryResult > 0) {
insertVeteranResult = mngHumanResourceMapper.insertVeteran(mngHumanResourceDTO, companyNo); //Veteran 테이블 인서트
} if (insertVeteranResult > 0) {
insertAppointmentResult = mngHumanResourceMapper.insertAppointment(mngHumanResourceDTO, companyNo); //Appointment 테이블 인서트
} if (insertAppointmentResult > 0) {
insertGraduatedResult = mngHumanResourceMapper.insertGraduated(mngHumanResourceDTO, companyNo); //Graduated 테이블 인서트
} if (insertGraduatedResult > 0) {
insertCareerResult = mngHumanResourceMapper.insertCareer(mngHumanResourceDTO, companyNo); //Career 테이블 인서트
} if (insertCareerResult > 0) {
insertFamilyResult = mngHumanResourceMapper.insertFamily(mngHumanResourceDTO, companyNo); //Family 테이블 인서트
selectFamilyUpdateResult = mngHumanResourceMapper.selectFamilyUpdate(mngHumanResourceDTO, companyNo); //FamilyUpdate테이블 조회
int familyNo = selectFamilyUpdateResult; //familyNo 조회
insertFamilyUpdateResult = mngHumanResourceMapper.insertFamilyUpdate(mngHumanResourceDTO, companyNo, familyNo); //FamilyUpdate테이블 인서트
} if (insertFamilyResult > 0) {
insertUserAuthResult = mngHumanResourceMapper.insertUserAuth(mngHumanResourceDTO, companyNo); //UserAuth 테이블에 인서트
} if (insertUserAuthResult > 0) {
selectVacationControlResult = mngHumanResourceMapper.selectVacationControl(); //VacationControl 테이블 조회
int vacationCode = vacationControlDTO.getVacationCode();
int vacationDays = vacationControlDTO.getVacationDays();
insertVacationControlResult = mngHumanResourceMapper.insertVacation(mngHumanResourceDTO, companyNo, vacationCode, vacationDays); //Vacation 테이블에 인서트
}if (insertVacationControlResult > 0) {
selectRankSalaryStepResult = mngHumanResourceMapper.selectRankSalaryStep(companyNo, mngHumanResourceDTO); //RankSalaryStep 테이블 startDate 조회
startDate = selectRankSalaryStepResult;
selectRankResult = mngHumanResourceMapper.selectRank(companyNo, mngHumanResourceDTO); //RankSalaryStep 테이블 조회
mngHumanResourceDTO.setSalaryStepByRank(selectRankResult.getSalaryStepByRank());
insertEmpSalaryStepResult = mngHumanResourceMapper.insertEmpSalaryStep(mngHumanResourceDTO, companyNo, startDate ); //EmpSalaryStep 테이블에 인서트
selectEmpSalaryStepResult = mngHumanResourceMapper.selectEmpSalaryStep(mngHumanResourceDTO ,companyNo); //EmpSalaryStep 테이블에 조회
int divNo = selectEmpSalaryStepResult;
insertEmpSalaryStepUpdateResult = mngHumanResourceMapper.insertEmpSalaryStepUpdate(mngHumanResourceDTO, companyNo, startDate, divNo); //EmpSalaryStepUpdate 테이블에 인서트
}
if (insertEmpSalaryStepUpdateResult > 0) {
insertFourInsuranceDeductResult = mngHumanResourceMapper.insertFourInsuranceDeduct(mngHumanResourceDTO, companyNo); //FourInsuranceDeduct 테이블 인서트
int deductDivNo = mngHumanResourceMapper.selectFourInsuranceDeduct(mngHumanResourceDTO, companyNo); //FourInsuranceDeduct 테이블 조회
insertEmpUpdateResult = mngHumanResourceMapper.insertFourInsHistory(mngHumanResourceDTO, companyNo, deductDivNo); //FourInsHistory 테이블 인서트
}
return insertEmpUpdateResult;
}
@Override
public List<SalaryStepDTO> selectSalaryStep(int companyNo) { //salaryStep 조회
return mngHumanResourceMapper.selectSalaryStep(companyNo);
}
@Override
public List<JobDTO> selectJobList(int companyNo) { //JobList 조회
return mngHumanResourceMapper.selectJobList(companyNo);
}
@Override
public List<MemberListDTO> selectMemberList(int companyNo) { //memberList 조회
return mngHumanResourceMapper.selectMemberList(companyNo);
}
@Override
public List<MngHumanResourceDTO> selectMemberHistoryList(int companyNo, int idNo) { //memberHistoryList 조회
return mngHumanResourceMapper.selectMemberHistoryList(companyNo, idNo);
}
@Override
public MngHumanResourceDTO selectMemberDetailList(int companyNo, int idNo) { //memberDetailList 조회
return mngHumanResourceMapper.selectMemberDetailList(companyNo, idNo);
}
@Override
public MngHumanResourceDTO selectmemberHistoryDetailList(int companyNo, int idNo) { //memberHistoryDetailList 조회
MngHumanResourceDTO resultMemberHistoryDetailList= mngHumanResourceMapper.selectmemberHistoryDetailList(companyNo, idNo);
return resultMemberHistoryDetailList;
}
@Override
public int memberDetailUpdate(int companyNo, MngHumanResourceDTO mngHumanResourceDTO, int idNo) {
int empUpdateResult = 0;
int miltaryResult = 0;
int veteranResult = 0;
int appointmentResult = 0;
int graduatedResult = 0;
int careerResult = 0;
int familyResult = 0;
int familyNo = 0;
int familyUpdateResult = 0;
int salaryStepByRank = 0;
int salaryStepResult = 0;
int salaryStepNo = 0;
int salaryStepUpdateResult = 0;
int empResult = mngHumanResourceMapper.updateEmp(companyNo, idNo, mngHumanResourceDTO); //TBL_EMPLOYEE 테이블 업데이트
if (empResult > 0) {
empUpdateResult = mngHumanResourceMapper.updateEmpUpdate(companyNo, idNo, mngHumanResourceDTO); //TBL_EMPLOYEEUpdate 테이블 업데이트
}
if (empUpdateResult > 0) {
miltaryResult = mngHumanResourceMapper.updateMilitary(companyNo, idNo, mngHumanResourceDTO); //Military 테이블 업데이트
}
if (miltaryResult > 0) {
veteranResult = mngHumanResourceMapper.updateVeteran(companyNo, idNo, mngHumanResourceDTO); //Veteran 테이블 업데이트
}
if (veteranResult > 0) {
appointmentResult = mngHumanResourceMapper.updateAppointment(companyNo, idNo, mngHumanResourceDTO); //Appointment 테이블 업데이트
}
if (appointmentResult > 0) {
graduatedResult = mngHumanResourceMapper.updateGraduated(companyNo, idNo, mngHumanResourceDTO); //Graduated 테이블 업데이트
}
if (graduatedResult > 0) {
careerResult = mngHumanResourceMapper.updateCareer(companyNo, idNo, mngHumanResourceDTO); //Career 테이블 업데이트
}
if (careerResult > 0) {
familyResult = mngHumanResourceMapper.updateFamily(companyNo, idNo, mngHumanResourceDTO); //Family 테이블 업데이트
familyNo = mngHumanResourceMapper.selectFamilyNo(companyNo, idNo); //Family 테이블 조회
familyUpdateResult = mngHumanResourceMapper.updateFamilyUpdate(companyNo, idNo, mngHumanResourceDTO,familyNo); //FamilyUpdate 테이블 업데이트
}
if (familyUpdateResult > 0) {
salaryStepByRank = mngHumanResourceMapper.selectSalaryStepByRank(companyNo, idNo); //SalaryStepByRank 테이블 조회
salaryStepResult = mngHumanResourceMapper.updateSalaryStep(companyNo, idNo, mngHumanResourceDTO, salaryStepByRank); //SalaryStep 테이블 업데이트
salaryStepNo = mngHumanResourceMapper.selectSalaryStepNo(companyNo, idNo); //SalaryStep 테이블 조회
salaryStepUpdateResult = mngHumanResourceMapper.updateSalaryStepUpdate(companyNo, idNo, salaryStepByRank, salaryStepNo); //SalaryStepUpdate 테이블 업데이트
}
return salaryStepUpdateResult;
}
@Override
public MngHumanResourceDTO selectMemberRankList(int companyNo, int idNo ,MngHumanResourceDTO mngHumanResourceDTO) { //MemberRankList 조회
int salaryStepByRank = mngHumanResourceMapper.selectSalaryStepByRank(companyNo, idNo);
return mngHumanResourceMapper.selectMemberRankList(companyNo, idNo, mngHumanResourceDTO, salaryStepByRank);
}
@Override
public int memberIdNo(int companyNo, MngHumanResourceDTO mngHumanResourceDTO) { //MemberIdNo 조회
int resultMemberIdNo = mngHumanResourceMapper.selectMemberIdNo(companyNo, mngHumanResourceDTO);
return resultMemberIdNo;
}
}
|
package com.eussi._01_jca_jce.cryptopkg;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/**
*
* Created by wangxueming on 2019/4/1.
*/
public class _01_Mac {//安全消息摘要
public static void main(String[] args) {
try {
//待安全摘要信息
byte[] input = "MAC".getBytes();
//初始化KeyGenerator
KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
//产生密钥
SecretKey secretKey = keyGenerator.generateKey();
//获得密钥
byte[] key = secretKey.getEncoded();
System.out.println("生成秘钥HmacMD5:" + Arrays.toString(key));
//获取mac
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
//初始化mac
mac.init(secretKey);
//执行消息摘要
byte[] output = mac.doFinal(input);
System.out.println("test摘要HmacMD5:" + Arrays.toString(output));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.