text stringlengths 10 2.72M |
|---|
package com.springapp.mvc.core.database;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import java.io.Serializable;
import java.util.List;
/**
* Created by max.lu on 2015/10/19.
*/
public class HibernateAccess {
SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
public <T> List<T> find(HibernateQuery hibernateQuery, Object... params) {
Query query = hibernateQuery.createQuery(currentSession(), params);
return (List<T>) query.list();
}
public <T> List<T> find(String hql, Object... params) {
return find(new HibernateQuery(hql, null, null), params);
}
public <T> List<T> find(String hql, Integer firstResult, Integer maxResults, Object... params) {
return find(new HibernateQuery(hql, firstResult, maxResults), params);
}
@SuppressWarnings("unchecked")
public <T> List<T> find(DetachedCriteria detachedCriteria, Integer firstResult, Integer maxResults) {
Criteria criteria = detachedCriteria.getExecutableCriteria(currentSession());
if (firstResult != null) criteria.setFirstResult(firstResult);
if (maxResults != null) criteria.setMaxResults(maxResults);
return criteria.list();
}
public <T> List<T> find(DetachedCriteria detachedCriteria) {
return find(detachedCriteria, null, null);
}
@SuppressWarnings("unchecked")
public <T> T findUniqueResult(String hql, Object... params) {
Query query = currentSession().createQuery(hql);
for (int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
return (T) query.uniqueResult();
}
@SuppressWarnings("unchecked")
public <T> T findUniqueResult(DetachedCriteria detachedCriteria) {
Criteria criteria = detachedCriteria.getExecutableCriteria(currentSession());
return (T) criteria.uniqueResult();
}
public void persist(Object entity) {
currentSession().persist(entity);
}
public void save(Object entity) {
currentSession().save(entity);
}
public void update(Object entity) {
currentSession().update(entity);
}
@SuppressWarnings("unchecked")
public <T> T get(Class<T> entityClass, Serializable id) {
return (T) currentSession().get(entityClass, id);
}
public void delete(Object entity) {
currentSession().delete(entity);
}
public int execute(String hql, Object... params) {
Query query = new HibernateQuery(hql, null, null).createQuery(currentSession(), params);
return query.executeUpdate();
}
public Session currentSession() {
return sessionFactory.getCurrentSession();
// return sessionFactory.openSession();
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
|
package com.yashas003.newstoday.Utils;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.yashas003.newstoday.Activities.DeveloperActivity;
import com.yashas003.newstoday.R;
public class BottomSheetDialog extends BottomSheetDialogFragment {
private TextView version;
private Dialog termsDialog;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.support_bottom_sheet, container, false);
version = v.findViewById(R.id.app_version);
setAppVersion(v);
ImageView share = v.findViewById(R.id.share);
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
shareApp(v);
}
});
ImageView dev = v.findViewById(R.id.dev);
dev.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openDevActivity(v);
}
});
ImageView terms = v.findViewById(R.id.terms);
terms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showTerms(v);
}
});
ImageView rate = v.findViewById(R.id.rate);
rate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rateApp(v);
}
});
ImageView close = v.findViewById(R.id.close_support);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
return v;
}
@SuppressLint("SetTextI18n")
private void setAppVersion(View v) {
PackageManager packageManager = v.getContext().getPackageManager();
String packageName = v.getContext().getPackageName();
String myVersionName = "Version";
try {
myVersionName = packageManager.getPackageInfo(packageName, 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
version.setText("Ver " + myVersionName);
}
private void shareApp(View v) {
String appPackageName = v.getContext().getPackageName();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=" + appPackageName);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share using"));
}
private void openDevActivity(View v) {
Intent devIntent = new Intent(v.getContext(), DeveloperActivity.class);
startActivity(devIntent);
dismiss();
}
private void showTerms(View v) {
termsDialog = new Dialog(v.getContext());
termsDialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_background);
termsDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
termsDialog.setContentView(R.layout.terms_and_conditions);
termsDialog.show();
dismiss();
TextView agree = termsDialog.findViewById(R.id.agree);
agree.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
termsDialog.dismiss();
}
});
}
private void rateApp(View v) {
Uri uri = Uri.parse("market://details?id=" + v.getContext().getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + v.getContext().getPackageName())));
}
dismiss();
}
}
|
package com.cinema.biz.model.base;
import java.util.Date;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name="sim_duty_reg")
public class TSimDutyReg {
@Id
private String dutyRegId;
private String dutyTaskId;
private String dutyContent;
private String faultReg;
private String repairReg;
private Date createTime;
private String creator;
private Date updateTime;
private String updator;
public String getDutyRegId() {
return dutyRegId;
}
public void setDutyRegId(String dutyRegId) {
this.dutyRegId = dutyRegId == null ? null : dutyRegId.trim();
}
public String getDutyTaskId() {
return dutyTaskId;
}
public void setDutyTaskId(String dutyTaskId) {
this.dutyTaskId = dutyTaskId == null ? null : dutyTaskId.trim();
}
public String getDutyContent() {
return dutyContent;
}
public void setDutyContent(String dutyContent) {
this.dutyContent = dutyContent == null ? null : dutyContent.trim();
}
public String getFaultReg() {
return faultReg;
}
public void setFaultReg(String faultReg) {
this.faultReg = faultReg == null ? null : faultReg.trim();
}
public String getRepairReg() {
return repairReg;
}
public void setRepairReg(String repairReg) {
this.repairReg = repairReg == null ? null : repairReg.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator == null ? null : creator.trim();
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUpdator() {
return updator;
}
public void setUpdator(String updator) {
this.updator = updator == null ? null : updator.trim();
}
} |
package com.arthur.bishi.wangyi0821;
import java.util.Scanner;
/**
* @description:
* @author: arthurji
* @date: 2021/8/21 14:32
* @modifiedBy:
* @version: 1.0
*/
public class No1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] s = scanner.nextLine().split(" ");
int[] nums = new int[s.length];
for (int i = 0; i < s.length; i++) {
nums[i] = Integer.valueOf(s[i]);
}
int M = scanner.nextInt();
int ans = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if(nums[i] + nums[j] <= M) {
ans++;
}
}
}
System.out.println(ans);
}
}
|
package com.yunsi.oop.test;
import java.util.Scanner;
import com.yunsi.oop.bean.sub.Student;
import com.yunsi.oop.bean.sub.Teacher;
import com.yunsi.oop.service.Hr;
public class Test {
static int iid = -1;
static Scanner scanner = new Scanner(System.in);
static Hr hr = new Hr();
public static void main(String[] args) {
int sid = 0;
int tid = 0;
int n;
do {
System.out.println("=====================");
System.out.println("1.插入人员信息");
System.out.println("2.设置人员班级");
System.out.println("3.设置人员年龄");
System.out.println("4.设置老师科目,所教班级");
System.out.println("5.学生班级信息修改");
System.out.println("6.根据ID查询");
System.out.println("7.删除学生");
System.out.println("8.打印表格");
System.out.println("0.退出");
System.out.println("=====================");
System.out.println("请输入您的选择");
// n=获取数字;
n = scanner.nextInt();
System.out.println("=====================");
switch (n) {
case 1: {
// addhuman();
System.out.println("1.学生");
System.out.println("2.教师");
System.out.println("3.厨师");
System.out.println("请选择添加的职业");
int x = scanner.nextInt();
System.out.println("请输入名字:");
String name = scanner.next();
System.out.println("请输入年龄:");
int age = scanner.nextInt();
switch (x) {
case 1: {
Student s = new Student(name, age);
sid++;
s.setId(sid + 10000);
hr.add(s);
System.out.println("学生" + s.getName() + "已添加,学号:" + s.getId());
break;
}
case 2: {
Teacher t = new Teacher(name, age);
tid++;
t.setId(tid + 20000);
hr.add(t);
System.out.println("老师" + t.getName() + "已添加,学号:" + t.getId());
break;
}
case 3: {
break;
}
}
break;
}
case 2: {
// inputclass();
iid = getid();
int c;
if (iid == -1) {
break;
}
System.out.println("请输入学生班级 1班 2班");
c = scanner.nextInt();
hr.inputClass(iid, c);
break;
}
case 3: {
// changeage();
iid = getid();
if (iid == -1) {
break;
}
System.out.println("请输入年龄");
int age = scanner.nextInt();
hr.setage(iid, age);
break;
}
case 4: {
// tsetsbj();
iid = getid();
if(!(hr.getPeoples().get(iid) instanceof Teacher)){
System.out.println("您输入的不是教师的学号");
break;
}
System.out.println("请输入所教科目");
String sbj = scanner.next();
System.out.println("请输入所教班级");
int c = scanner.nextInt();
hr.tsetclass(iid, sbj, c);
break;
}
case 5: {
// csclassroom();
iid = getid();
if (iid == -1 || iid > 10000) {
break;
}
System.out.println("请输入新加入的班级");
int c = scanner.nextInt();
hr.changeclass(iid, c);
break;
}
case 6: {
// search();
iid = getid();
if (iid==-1){
break;
}
hr.query(iid);
break;
}
case 7: {
// deletep();
iid = getid();
if (iid == -1) {
break;
}
hr.deletestudents(iid);
break;
}
case 8: {
// printform();
System.out.println("1.打印所有学生信息");
System.out.println("2.打印所有教师信息");
System.out.println("3.打印某班学生信息");
System.out.println("按 0 键返回上一层");
int print = scanner.nextInt();
if (print==0){
break;
}
switch (print) {
case 1: {
for (int i = 0; i < hr.getPeoplenum(); i++) {
hr.printstudent(i);
}
break;
}
case 2: {
for (int i = 0; i < hr.getPeoplenum(); i++) {
hr.printteacher(i);
}
break;
}
case 3: {
}
}
break;
}
}
} while (n != 0);
}
// 查找学号对应人员
private static int getid() {
iid = -1;
if (hr.getPeoples().size() == 0) {
System.out.println("人员总数为0");
return -1;
}
System.out.println("请输入学号/或按0返回");
while (iid == -1) {
int id = scanner.nextInt();
if (id == 0) {
return -1;
}
iid = hr.searchid(id, iid);
if (iid == -1)
System.out.println("输入不正确,请再次输入/或按0返回");
}
return iid;
}
public static int getIid() {
return iid;
}
public static void setIid(int iid) {
Test.iid = iid;
}
}
|
/**
*
*/
package com.hotel.booking;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.hotel.dto.BaseDTO;
import com.hotel.master.customer.CustomerDTO;
import com.hotel.rooms.RoomsDTO;
/**
* @author User
*
*/
public class BookingDTO extends BaseDTO {
private Integer id;
private Date arrivalDate;
private Date depatureDate;
private String name;
private String address;
private String telephone;
private String bookingType;
private String billingInstructions;
private Float depositAmount;
private String bookingConfirmedBy;
private String bookingTakenBy;
private Integer noOfGuest;
private RoomsDTO room;
private CustomerDTO customer;
public BookingDTO() {
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the arrivalDate
*/
public Date getArrivalDate() {
return arrivalDate;
}
/**
* @param arrivalDate the arrivalDate to set
*/
public void setArrivalDate(Date arrivalDate) {
this.arrivalDate = arrivalDate;
}
/**
* @return the depatureDate
*/
public Date getDepatureDate() {
return depatureDate;
}
/**
* @param depatureDate the depatureDate to set
*/
public void setDepatureDate(Date depatureDate) {
this.depatureDate = depatureDate;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @return the telephone
*/
public String getTelephone() {
return telephone;
}
/**
* @param telephone the telephone to set
*/
public void setTelephone(String telephone) {
this.telephone = telephone;
}
/**
* @return the bookingType
*/
public String getBookingType() {
return bookingType;
}
/**
* @param bookingType the bookingType to set
*/
public void setBookingType(String bookingType) {
this.bookingType = bookingType;
}
/**
* @return the billingInstructions
*/
public String getBillingInstructions() {
return billingInstructions;
}
/**
* @param billingInstructions the billingInstructions to set
*/
public void setBillingInstructions(String billingInstructions) {
this.billingInstructions = billingInstructions;
}
/**
* @return the depositAmount
*/
public Float getDepositAmount() {
return depositAmount;
}
/**
* @param depositAmount the depositAmount to set
*/
public void setDepositAmount(Float depositAmount) {
this.depositAmount = depositAmount;
}
/**
* @return the bookingConfirmedBy
*/
public String getBookingConfirmedBy() {
return bookingConfirmedBy;
}
/**
* @param bookingConfirmedBy the bookingConfirmedBy to set
*/
public void setBookingConfirmedBy(String bookingConfirmedBy) {
this.bookingConfirmedBy = bookingConfirmedBy;
}
/**
* @return the bookingTakenBy
*/
public String getBookingTakenBy() {
return bookingTakenBy;
}
/**
* @param bookingTakenBy the bookingTakenBy to set
*/
public void setBookingTakenBy(String bookingTakenBy) {
this.bookingTakenBy = bookingTakenBy;
}
/**
* @return the noOfGuest
*/
public Integer getNoOfGuest() {
return noOfGuest;
}
/**
* @param noOfGuest the noOfGuest to set
*/
public void setNoOfGuest(Integer noOfGuest) {
this.noOfGuest = noOfGuest;
}
/**
* @return the room
*/
public RoomsDTO getRoom() {
return room;
}
/**
* @param room the room to set
*/
public void setRoom(RoomsDTO room) {
this.room = room;
}
/**
* @return the customer
*/
public CustomerDTO getCustomer() {
return customer;
}
/**
* @param customer the customer to set
*/
public void setCustomer(CustomerDTO customer) {
this.customer = customer;
}
}
|
package ru.yandex.yamblz.ui.recyclerstuff;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import ru.yandex.yamblz.R;
/**
* Created by dalexiv on 8/6/16.
*/
public class BorderItemDecorator extends RecyclerView.ItemDecoration {
private static final double BORDER_RATIO = 0.05;
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDrawOver(c, parent, state);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(ContextCompat.getColor(parent.getContext(), R.color.colorPrimaryDark));
paint.setStyle(Paint.Style.FILL_AND_STROKE);
for (int i = 0; i < parent.getChildCount(); ++i) {
View view = parent.getChildAt(i);
if (parent.getChildAdapterPosition(view) % 2 == 0)
continue;
parent.getAdapter();
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
Rect viewBounds = new Rect(view.getLeft() + params.leftMargin,
view.getTop() + params.topMargin,
view.getRight() + params.rightMargin,
view.getBottom() + params.bottomMargin);
int BOUND_WIDTH = (int) (view.getWidth() * BORDER_RATIO);
c.drawRect(viewBounds.left, viewBounds.top, viewBounds.right,
viewBounds.top + BOUND_WIDTH, paint);
c.drawRect(viewBounds.left, viewBounds.top, viewBounds.left + BOUND_WIDTH,
viewBounds.bottom, paint);
c.drawRect(viewBounds.right - BOUND_WIDTH, viewBounds.top, viewBounds.right,
viewBounds.bottom, paint);
c.drawRect(viewBounds.left, viewBounds.bottom - BOUND_WIDTH,
viewBounds.right, viewBounds.bottom, paint);
}
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webadmin.identities;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.exceptions.AuthorizationException;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.server.api.AttributesManagement;
import pl.edu.icm.unity.server.api.GroupsManagement;
import pl.edu.icm.unity.server.utils.Log;
import pl.edu.icm.unity.server.utils.UnityMessageSource;
import pl.edu.icm.unity.types.basic.GroupContents;
import pl.edu.icm.unity.types.basic.GroupMembership;
import pl.edu.icm.unity.webadmin.attribute.AttributeChangedEvent;
import pl.edu.icm.unity.webadmin.credentials.CredentialDefinitionChangedEvent;
import pl.edu.icm.unity.webadmin.credreq.CredentialRequirementChangedEvent;
import pl.edu.icm.unity.webadmin.groupbrowser.GroupChangedEvent;
import pl.edu.icm.unity.webadmin.identities.AddAttributeColumnDialog.Callback;
import pl.edu.icm.unity.webui.WebSession;
import pl.edu.icm.unity.webui.bus.EventListener;
import pl.edu.icm.unity.webui.bus.EventsBus;
import pl.edu.icm.unity.webui.common.ErrorComponent;
import pl.edu.icm.unity.webui.common.ErrorComponent.Level;
import pl.edu.icm.unity.webui.common.Images;
import pl.edu.icm.unity.webui.common.Styles;
import pl.edu.icm.unity.webui.common.Toolbar;
import pl.edu.icm.unity.webui.common.safehtml.HtmlTag;
import pl.edu.icm.unity.webui.common.safehtml.SafePanel;
import com.vaadin.data.Container;
import com.vaadin.data.Container.Filter;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.filter.Or;
import com.vaadin.data.util.filter.SimpleStringFilter;
import com.vaadin.event.FieldEvents.TextChangeEvent;
import com.vaadin.event.FieldEvents.TextChangeListener;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.shared.ui.Orientation;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
/**
* Component wrapping {@link IdentitiesTable}. Allows to configure its mode,
* feeds it with data to be visualised etc.
* @author K. Benedyczak
*/
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class IdentitiesComponent extends SafePanel
{
private static final Logger log = Log.getLogger(Log.U_SERVER_WEB, IdentitiesComponent.class);
private static final List<Long> EMPTY_LIST = new ArrayList<Long>(0);
private UnityMessageSource msg;
private VerticalLayout main;
private GroupsManagement groupsManagement;
private IdentitiesTable identitiesTable;
private HorizontalLayout filtersBar;
private Or fastSearchFilter;
@Autowired
public IdentitiesComponent(final UnityMessageSource msg, GroupsManagement groupsManagement,
final AttributesManagement attrsMan, final IdentitiesTable identitiesTable)
{
this.msg = msg;
this.groupsManagement = groupsManagement;
this.identitiesTable = identitiesTable;
main = new VerticalLayout();
main.addStyleName(Styles.visibleScroll.toString());
CssLayout topBar = new CssLayout();
final CheckBox mode = new CheckBox(msg.getMessage("Identities.mode"));
mode.setImmediate(true);
mode.setValue(IdentitiesComponent.this.identitiesTable.isGroupByEntity());
mode.addStyleName(Styles.vSmall.toString());
mode.addStyleName(Styles.verticalAlignmentMiddle.toString());
mode.addStyleName(Styles.horizontalMarginSmall.toString());
final CheckBox showTargeted = new CheckBox(msg.getMessage("Identities.showTargeted"));
showTargeted.setImmediate(true);
showTargeted.setValue(IdentitiesComponent.this.identitiesTable.isShowTargeted());
showTargeted.addStyleName(Styles.vSmall.toString());
showTargeted.addStyleName(Styles.verticalAlignmentMiddle.toString());
showTargeted.addStyleName(Styles.horizontalMarginSmall.toString());
Toolbar toolbar = new Toolbar(identitiesTable.getValueChangeNotifier(), Orientation.HORIZONTAL);
toolbar.addStyleName(Styles.floatRight.toString());
toolbar.addStyleName(Styles.verticalAlignmentMiddle.toString());
toolbar.addStyleName(Styles.horizontalMarginSmall.toString());
filtersBar = new HorizontalLayout();
filtersBar.addComponent(new Label(msg.getMessage("Identities.filters")));
filtersBar.setVisible(false);
Button addAttributes = new Button();
addAttributes.setDescription(msg.getMessage("Identities.addAttributes"));
addAttributes.setIcon(Images.addColumn.getResource());
addAttributes.addClickListener(new ClickListener()
{
@Override
public void buttonClick(ClickEvent event)
{
new AddAttributeColumnDialog(IdentitiesComponent.this.msg,
attrsMan, new Callback()
{
@Override
public void onChosen(String attributeType, String group)
{
IdentitiesComponent.this.identitiesTable.
addAttributeColumn(attributeType, group);
}
}).show();
}
});
Button removeAttributes = new Button();
removeAttributes.setDescription(msg.getMessage("Identities.removeAttributes"));
removeAttributes.setIcon(Images.removeColumn.getResource());
removeAttributes.addClickListener(new ClickListener()
{
@Override
public void buttonClick(ClickEvent event)
{
Set<String> alreadyUsedRoot =
IdentitiesComponent.this.identitiesTable.getAttributeColumns(true);
Set<String> alreadyUsedCurrent =
IdentitiesComponent.this.identitiesTable.getAttributeColumns(false);
new RemoveAttributeColumnDialog(IdentitiesComponent.this.msg, alreadyUsedRoot,
alreadyUsedCurrent, IdentitiesComponent.this.identitiesTable.getGroup(),
new RemoveAttributeColumnDialog.Callback()
{
@Override
public void onChosen(String attributeType, String group)
{
IdentitiesComponent.this.identitiesTable.
removeAttributeColumn(group, attributeType);
}
}).show();
}
});
Button addFilter = new Button();
addFilter.setDescription(msg.getMessage("Identities.addFilter"));
addFilter.setIcon(Images.addFilter.getResource());
addFilter.addClickListener(new ClickListener()
{
@Override
public void buttonClick(ClickEvent event)
{
Collection<?> props = IdentitiesComponent.this.identitiesTable.getContainerPropertyIds();
new AddFilterDialog(IdentitiesComponent.this.msg, props,
new AddFilterDialog.Callback()
{
@Override
public void onConfirm(Filter filter, String description)
{
addFilterInfo(filter, description);
}
}).show();
}
});
Button savePreferences = new Button();
savePreferences.setDescription(msg.getMessage("Identities.savePreferences"));
savePreferences.setIcon(Images.save.getResource());
savePreferences.addClickListener(new ClickListener()
{
@Override
public void buttonClick(ClickEvent event)
{
IdentitiesComponent.this.identitiesTable.savePreferences();
}
});
HorizontalLayout searchWrapper = new HorizontalLayout();
searchWrapper.setSpacing(true);
searchWrapper.setMargin(false);
searchWrapper.addStyleName(Styles.verticalAlignmentMiddle.toString());
searchWrapper.addStyleName(Styles.horizontalMarginSmall.toString());
Label searchL = new Label(msg.getMessage("Identities.searchCaption"));
Label spacer = new Label();
spacer.setWidth(4, Unit.EM);
final TextField searchText = new TextField();
searchText.addStyleName(Styles.vSmall.toString());
searchText.setColumns(8);
searchWrapper.addComponents(spacer, searchL, searchText);
searchWrapper.setComponentAlignment(searchL, Alignment.MIDDLE_RIGHT);
searchWrapper.setComponentAlignment(searchText, Alignment.MIDDLE_LEFT);
searchText.setImmediate(true);
searchText.addTextChangeListener(new TextChangeListener()
{
@Override
public void textChange(TextChangeEvent event)
{
Collection<?> props = IdentitiesComponent.this.identitiesTable
.getContainerPropertyIds();
ArrayList<Container.Filter> filters = new ArrayList<Container.Filter>();
String searchText = event.getText();
if (fastSearchFilter != null)
identitiesTable.removeFilter(fastSearchFilter);
if (searchText.isEmpty())
return;
for (Object colIdRaw : props)
{
String colId = (String) colIdRaw;
if (IdentitiesComponent.this.identitiesTable.isColumnCollapsed(colId))
continue;
Filter filter = new SimpleStringFilter(colId, searchText, true, false);
filters.add(filter);
}
if (filters.size() < 1)
return;
Filter[] orFillters = filters.toArray(new Filter[filters.size()]);
fastSearchFilter = new Or(orFillters);
identitiesTable.addFilter(fastSearchFilter);
}
});
toolbar.addActionHandlers(identitiesTable.getActionHandlers());
toolbar.addSeparator();
toolbar.addButtons(addFilter, addAttributes, removeAttributes, savePreferences);
topBar.addComponents(mode, showTargeted, searchWrapper, toolbar);
topBar.setWidth(100, Unit.PERCENTAGE);
mode.addValueChangeListener(new ValueChangeListener()
{
@Override
public void valueChange(ValueChangeEvent event)
{
IdentitiesComponent.this.identitiesTable.setMode(mode.getValue());
}
});
showTargeted.addValueChangeListener(new ValueChangeListener()
{
@Override
public void valueChange(ValueChangeEvent event)
{
try
{
IdentitiesComponent.this.identitiesTable.setShowTargeted(showTargeted.getValue());
} catch (EngineException e)
{
setIdProblem(IdentitiesComponent.this.identitiesTable.getGroup(), e);
}
}
});
main.addComponents(topBar, filtersBar, identitiesTable);
main.setExpandRatio(identitiesTable, 1.0f);
main.setSpacing(true);
main.setSizeFull();
setSizeFull();
setContent(main);
setStyleName(Styles.vPanelLight.toString());
setCaption(msg.getMessage("Identities.caption"));
EventsBus bus = WebSession.getCurrent().getEventBus();
bus.addListener(new EventListener<GroupChangedEvent>()
{
@Override
public void handleEvent(GroupChangedEvent event)
{
setGroup(event.getGroup());
}
}, GroupChangedEvent.class);
bus.addListener(new EventListener<CredentialRequirementChangedEvent>()
{
@Override
public void handleEvent(CredentialRequirementChangedEvent event)
{
setGroup(IdentitiesComponent.this.identitiesTable.getGroup());
}
}, CredentialRequirementChangedEvent.class);
bus.addListener(new EventListener<CredentialDefinitionChangedEvent>()
{
@Override
public void handleEvent(CredentialDefinitionChangedEvent event)
{
if (event.isUpdatedExisting())
setGroup(IdentitiesComponent.this.identitiesTable.getGroup());
}
}, CredentialDefinitionChangedEvent.class);
bus.addListener(new EventListener<AttributeChangedEvent>()
{
@Override
public void handleEvent(AttributeChangedEvent event)
{
Set<String> interestingCurrent =
IdentitiesComponent.this.identitiesTable.getAttributeColumns(false);
String curGroup = IdentitiesComponent.this.identitiesTable.getGroup();
if (interestingCurrent.contains(event.getAttributeName()) && curGroup.equals(event.getGroup()))
{
setGroup(curGroup);
return;
}
if (curGroup.equals("/") && curGroup.equals(event.getGroup()))
{
Set<String> interestingRoot =
IdentitiesComponent.this.identitiesTable.getAttributeColumns(true);
if (interestingRoot.contains(event.getAttributeName()))
{
setGroup(curGroup);
return;
}
}
}
}, AttributeChangedEvent.class);
setGroup(null);
}
private void addFilterInfo(Filter filter, String description)
{
identitiesTable.addFilter(filter);
filtersBar.addComponent(new FilterInfo(description, filter));
filtersBar.setVisible(true);
}
private void setGroup(String group)
{
if (group == null)
{
try
{
identitiesTable.setInput(null, EMPTY_LIST);
} catch (EngineException e)
{
//ignored, shouldn't happen anyway
}
setProblem(msg.getMessage("Identities.noGroupSelected"), Level.warning);
return;
}
try
{
GroupContents contents = groupsManagement.getContents(group, GroupContents.MEMBERS);
List<Long> entities = contents.getMembers().stream().
map(GroupMembership::getEntityId).
collect(Collectors.toList());
identitiesTable.setInput(group, entities);
identitiesTable.setVisible(true);
setCaption(msg.getMessage("Identities.caption", group));
setContent(main);
} catch (AuthorizationException e)
{
setProblem(msg.getMessage("Identities.noReadAuthz", group), Level.error);
} catch (Exception e)
{
setIdProblem(group, e);
}
}
private void setIdProblem(String group, Exception e)
{
log.error("Problem retrieving group contents of " + group, e);
setProblem(msg.getMessage("Identities.internalError", e.toString()), Level.error);
}
private void setProblem(String message, Level level)
{
ErrorComponent errorC = new ErrorComponent();
errorC.setMessage(message, level);
setCaption(msg.getMessage("Identities.captionNoGroup"));
setContent(errorC);
}
private class FilterInfo extends HorizontalLayout
{
public FilterInfo(String description, final Filter filter)
{
Label info = new Label(description);
Button remove = new Button();
remove.addStyleName(Styles.vButtonLink.toString());
remove.setIcon(Images.delete.getResource());
remove.addClickListener(new ClickListener()
{
@Override
public void buttonClick(ClickEvent event)
{
identitiesTable.removeFilter(filter);
filtersBar.removeComponent(FilterInfo.this);
if (filtersBar.getComponentCount() == 1)
filtersBar.setVisible(false);
}
});
addComponents(info, HtmlTag.hspaceEm(1), remove);
setMargin(new MarginInfo(false, false, false, true));
}
}
}
|
package com.gsccs.sme.freemark.tag;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import com.gsccs.sme.api.domain.DeclareTopic;
import com.gsccs.sme.api.domain.base.Datagrid;
import com.gsccs.sme.api.exception.ApiException;
import com.gsccs.sme.api.service.DeclareServiceI;
import com.gsccs.sme.api.service.SclassServiceI;
import freemarker.core.Environment;
import freemarker.ext.beans.ArrayModel;
import freemarker.ext.beans.BeanModel;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
*
* Title: DeclarePageTag.java
*
* Description: 项目申报分页标签
*
* 参数 classid分类编码:"0":所有; 参数 subclassid子分类编码:"0":所有; 参数 city地域 空字符串:所有;
* 参数keyword关键字;
*
* 返回值 sneedlist 服务项对象 index 索引
*
* 使用示例
*
* <@sme_declare_page scode="${scode}" num="6"
* page="${page}" pagenum="${pagenum!0}" titlelen="48" dateFormat="yyyy-MM-dd";
* actList,pager>
*
* <#list declareList as act> </#list>
*
* </@sme_declare_page>
*
* @author x.d zhang
* @version 1.0
*
*/
@Component("declareTopicPageTag")
public class DeclareTopicPageTag extends BaseDirective implements
TemplateDirectiveModel {
@Resource
private DeclareServiceI declareAPI;
public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) {
//标题长度
Integer titlen = getParamInt(params, "titlelen",0);
String dateformat = getParam(params, "dateformat");
// 关键字
String keyword = getParam(params, "keyword");
// 服务机构
Long svgid = getParamLong(params, "svgid",0);
// 显示数量
int num = getParamInt(params, "num", 10);
// 排序
String order = getParam(params, "order", "1");
// 当前第几页
int page = getParamInt(params, "page", 1);
// 最多显示页数
int pagenum = getParamInt(params, "pagenum", 0);
if (body != null) {
// 设置循环变量
if (loopVars != null && loopVars.length > 0) {
DeclareTopic declareTopic = new DeclareTopic();
// 参数
Map<String, String> urlParams = new HashMap<String, String>();
if (StringUtils.isNotEmpty(keyword)) {
declareTopic.setTitle(keyword);
urlParams.put("keyword", keyword);
}
if (StringUtils.isNotEmpty(dateformat)){
//declareTopic.setDateformat(dateformat);
}
if (null != titlen && titlen>0){
//activity.setTitlelen(titlen);
}
if (null != svgid && svgid != 0){
declareTopic.setSvgid(svgid);
}
try {
Datagrid datagrid = declareAPI.queryTopicList(
declareTopic, order, page, num);
// 获取总数
int count = 0;
if (null != datagrid ){
count =datagrid.getTotal().intValue();
}
FreemarkerPager pager = new FreemarkerPager();
pager.setCurrPage(page);
pager.setTotalCount(count);
pager.setPageSize(num);
pager.setUrl("/declare.html");
pager.setParams(urlParams);
// 如果总页数大于最多显示页数,则设置总页数为最多显示页数
if (pagenum > 0 && pagenum < pager.getTotalPage()) {
pager.setTotalPage(pagenum);
}
List<DeclareTopic> list = null;
if (null != datagrid && null !=datagrid.getRows()){
list = (List<DeclareTopic>) datagrid.getRows();
}
if (null != list && list.size() > 0) {
loopVars[0] = new ArrayModel(list.toArray(),
new BeansWrapper());
if (loopVars.length > 1) {
loopVars[1] = new BeanModel(pager,
new BeansWrapper());
}
body.render(env.getOut());
}
} catch (ApiException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
package io.electrum.sdk.masking2;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Use this annotation to mark fields in a bean property class that should be masked when traced.
* <p>
* For example:
*
* <pre>
* public class MyMessage {
* @Masked(MaskPan.class)
* String cardNumber;
* @ShortDescriptionField
* String messageId;
* String someOtherField;
* ...
* </pre>
*
* The above snippet will ensure that pan is masked (eg: 123456******1234) in trace messages
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Masked {
Class<? extends Masker> value() default MaskAll.class;
}
|
package miniProgram;
import java.util.Random;
import java.util.Scanner;
import miniProgram.omok.Board;
import miniProgram.omok.GraphicOmock;
import miniProgram.omok.Stone;
import miniProgram.omok.Exception.InvalidSpace;
import miniProgram.omok.Exception.SelectedSpace;
public class RunOmok {
public static void main(String[] args) {
Board board = new Board();
Random rand = new Random();
Scanner sc = new Scanner(System.in);
//흑돌부터
boolean turn = false;
while(true) {
String player = turn? "백돌":"흑돌";
System.out.println(player+" 차례입니다. 좌표를 입력하세요: ");
int x = rand.nextInt(board.BOARD_ROW);
int y = rand.nextInt(board.BOARD_COLUMN);
Stone stone = new Stone(x,y,turn);
try {
board.putStone(stone);
GraphicOmock.printOmock(board);
} catch (InvalidSpace e) {
System.out.println("좌표 선택이 잘못되었습니다.");
continue;
} catch (SelectedSpace e) {
System.out.println("이미 선택된 좌표입니다.");
continue;
}
if(board.isFiveStone(stone)) {
break;
}
turn = !turn;
}
}
}
|
package cn.tedu.test;
public class TestDay01 {
/**
* 1:输出字符串"HelloWorld"的字符串长度
* 2:输出"HelloWorld"中"o"的位置
* 3:输出"HelloWorld"中从下标5出开始第一次出现"o"的位置
* 4:截取"HelloWorld"中的"Hello"并输出
* 5:截取"HelloWorld"中的"World"并输出
* 6:将字符串" Hello "中两边的空白去除后输出
* 7:输出"HelloWorld"中第6个字符"W"
* 8:输出"HelloWorld"是否是以"h"开头和"ld"结尾的。
* 9:将"HelloWorld"分别转换为全大写和全小写并输出。
* @author Xiloer
*
*/
public static void main(String[] args) {
String str = "HelloWorld";
test1(str);
test2(str);
test3(str);
test4(str);
test5(str);
test6(str);
test7(str);
test8(str);
test9(str);
}
private static void test9(String str) {
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
}
private static void test8(String str) {
System.out.println(str.indexOf("h"));
System.out.println(str.lastIndexOf("ld"));
}
private static void test7(String str) {
System.out.println(str.charAt(5));
}
private static void test6(String str) {
String str1 = " Hello ";
System.out.println(str1.trim());
}
private static void test5(String str) {
System.out.println(str.substring(5));
}
private static void test4(String str) {
System.out.println(str.substring(0,5));
}
private static void test3(String str) {
System.out.println(str.indexOf("o"));
}
private static void test2(String str) {
System.out.println(str.indexOf("o"));
}
private static void test1(String str) {
System.out.println(str.length());
}
}
|
package login;
import varTypes.Dueno;
public class Sesion {
protected Dueno p;
private Sesion() {
}
private static Sesion instance;
public static Sesion getInstance() {
if (instance == null)
instance = new Sesion();
return instance;
}
public void setUsuario(Dueno p) {
this.p = p;
}
public Dueno getUsuario() {
return p;
}
}
|
package org.notice.beans;
import java.io.Serializable;
public class Skill implements Serializable
{
private static final long serialVersionUID = 1L;
private int skillID = 0;
private String skillName = null;
public Skill()
{
}
public Skill(int skillID, String skillName)
{
super();
this.skillID = skillID;
this.skillName = skillName;
}
public int getSkillID()
{
return skillID;
}
public void setSkillID(int skillID)
{
this.skillID = skillID;
}
public String getSkillName()
{
return skillName;
}
public void setSkillName(String skillName)
{
this.skillName = skillName;
}
public static long getSerialversionuid()
{
return serialVersionUID;
}
}
|
package by.bytechs.xfs.deviceStatus.idcStatus;
import at.o2xfs.xfs.idc.RetainBin;
import by.bytechs.xml.entity.deviceStatus.ComponentXml;
/**
* @author Romanovich Andrei
*/
public enum IDCRetainBinStatus {
BINOK(1, "Хранилище задержанных карт в работоспособном состоянии"),
NOTSUPP(2, "Хранилище задержанных карт отсутствует"),
BINFULL(3, "Хранилище задержанных карт заполнено"),
BINHIGH(4, "Хранилище задержанных карт почти заполнено"),
BINMISSING(5, "Удерживающий лоток модуля карты отсутствует"),
UNKNOWN_STATUS(150, "Неизвестное сотояние устройства");
final int code;
final String description;
IDCRetainBinStatus(final int code, final String description) {
this.code = code;
this.description = description;
}
public static ComponentXml getDescription(RetainBin retainBinStatus) {
if (retainBinStatus != null) {
for (IDCRetainBinStatus status : IDCRetainBinStatus.values()) {
if (status.name().equals(retainBinStatus.name())) {
return new ComponentXml(status.code, status.description, "retainbin");
}
}
}
return new ComponentXml(UNKNOWN_STATUS.code, UNKNOWN_STATUS.description, "retainbin");
}
} |
package ru.job4j.control;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import ru.job4j.forum.Main;
import ru.job4j.forum.model.Post;
import ru.job4j.forum.service.PostService;
import java.util.Optional;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
@SpringBootTest(classes = Main.class)
@AutoConfigureMockMvc
public class PostControlTest {
@MockBean
private PostService posts;
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser
public void shouldReturnPost() throws Exception {
when(posts.findById(1)).thenReturn(Optional.of(Post.of("New Post")));
this.mockMvc.perform(get("/post?id=1"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("post"));
}
@Test
@WithMockUser
public void shouldReturn404ForPost() throws Exception {
this.mockMvc.perform(get("/post?id=1"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("404"));
}
@Test
@WithMockUser
public void shouldReturnNewPost() throws Exception {
this.mockMvc.perform(get("/new"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("new"));
}
@Test
@WithMockUser
public void shouldReturnEditPost() throws Exception {
when(posts.findById(1)).thenReturn(Optional.of(Post.of("New Post")));
this.mockMvc.perform(get("/post/edit?id=1"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("edit"));
}
@Test
@WithMockUser
public void shouldReturn404ForEditPost() throws Exception {
this.mockMvc.perform(get("/post/edit?id=1"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("404"));
}
@Test
@WithMockUser
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(post("/create")
.param("name", "Куплю ладу-грант. Дорого."))
.andDo(print())
.andExpect(status().is3xxRedirection());
ArgumentCaptor<Post> argument = ArgumentCaptor.forClass(Post.class);
verify(posts).save(argument.capture());
assertThat(argument.getValue().getName(), is("Куплю ладу-грант. Дорого."));
}
@Test
@WithMockUser
public void shouldReturnUpdatedOkPost() throws Exception {
when(posts.findById(1)).thenReturn(Optional.of(Post.of("New Post")));
this.mockMvc.perform(post("/post/update?id=1")
.param("name", "Updated Post"))
.andDo(print())
.andExpect(status().is3xxRedirection());
ArgumentCaptor<Post> argument = ArgumentCaptor.forClass(Post.class);
verify(posts).save(argument.capture());
assertThat(argument.getValue().getName(), is("Updated Post"));
}
@Test
@WithMockUser
public void shouldReturnUpdatedFailPost() throws Exception {
when(posts.findById(1)).thenReturn(Optional.empty());
this.mockMvc.perform(post("/post/update?id=1"))
.andDo(print())
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/post/edit?id=1"));
}
@Test
@WithMockUser
public void shouldDeletePost() throws Exception {
this.mockMvc.perform(post("/post/delete?id=1"))
.andDo(print())
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/"));
}
}
|
package ua.cn.stu.cs.oop.lab;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
public class Array {
public static void main(String[] args){
//Вводимо довжину масиву
Scanner scan = new Scanner(System.in);
System.out.println("Введіть довжину масиву");
int size = scan.nextInt();
scan.close();
//Формуємо масив
double[] arr = new double[size];
//Заносимо випадкові числа
for(int i = 0; i < arr.length; i++)
{
arr[i] = Math.random()*100;
}
//Сортуємо масив
Arrays.sort(arr);
//Виводимо масив за допомогою foreach
System.out.println("Ось числа масиву: ");
for(double d : arr)
{
System.out.printf("%6.2f", d);
}
System.out.println();
}
}
|
package com.karya.model;
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="trialbalance001mb")
public class TrialBalance001MB {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name="account")
private String account;
@Column(name="openingcr")
private int openingcr;
@Column(name="openingdr")
private int openingdr;
@Column(name="closingdr")
private int closingdr;
@Column(name="closingcr")
private int closingcr;
@Column(name="credit")
private int credit;
@Column(name="debit")
private int debit;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public int getOpeningcr() {
return openingcr;
}
public void setOpeningcr(int openingcr) {
this.openingcr = openingcr;
}
public int getOpeningdr() {
return openingdr;
}
public void setOpeningdr(int openingdr) {
this.openingdr = openingdr;
}
public int getClosingdr() {
return closingdr;
}
public void setClosingdr(int closingdr) {
this.closingdr = closingdr;
}
public int getClosingcr() {
return closingcr;
}
public void setClosingcr(int closingcr) {
this.closingcr = closingcr;
}
public int getCredit() {
return credit;
}
public void setCredit(int credit) {
this.credit = credit;
}
public int getDebit() {
return debit;
}
public void setDebit(int debit) {
this.debit = debit;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
package com.trump.auction.trade.constant;
/**
* Created by Administrator on 2018/1/25.
*/
public class SysContant {
public static final Integer PAGE_VIEW = 10;
public static final Integer COLLECTION_COUNT = 10;
/**
* 不同应用市场不同版本返币规则
*/
public final static String APP_COIN_RULE ="app_coin_rule";
}
|
import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.LinkedList;
import javax.swing.*;
import java.util.Random;
public class ClockWindow implements IWindow{
private JFrame window;
private JLabel timer;
private JLabel date;
protected JLabel quote;
private ITime time;
private ITime quoteTimer;
private TimeObserver observer;
private Thread timerThread;
private LinkedList<String> quotesList;
private String[] quotes;
private QuoteObserver observer1;
public ClockWindow(TimeObserver obs, QuoteObserver obs1)
{
observer = obs;
obs.RegisterObserver(this);
QuoteLoader loader = new QuoteLoader();
try {
quotesList = loader.LoadQuotes();
}
catch(IOException i)
{
i.printStackTrace();
}
quotes = GetQuoteArray();
observer1 = obs1;
observer1.RegisterObserver(this);
}
@Override
public void Show() {
// TODO Auto-generated method stub
window = new JFrame();
window.setLayout(null);
window.setExtendedState(JFrame.MAXIMIZED_BOTH);
window.setVisible(true);
AddControls(window);
setCloseActions(window);
}
@Override
public void Show(String title) {
// TODO Auto-generated method stub
window = new JFrame();
window.setExtendedState(JFrame.MAXIMIZED_BOTH);
window.setVisible(true);
window.setTitle(title);
AddControls(window);
setCloseActions(window);
}
@Override
public void Close() {
// TODO Auto-generated method stub
window.setVisible(false);
time.Stop();
timerThread.interrupt();
timerThread = null;
time = null;
}
private void setCloseActions(JFrame window)
{
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void AddControls(JFrame window)
{
date = new JLabel();
//label.setHorizontalAlignment(JLabel.CENTER);
date.setSize(1000, 75);
date.setFont(new Font("Arial", Font.BOLD,52));
date.setText("");
date.setLocation((window.getWidth() / 2) - 450 , 50);
date.setForeground(Color.white);
date.setVisible(true);
window.add(date);
JLabel label1 = new JLabel();
//label.setHorizontalAlignment(JLabel.CENTER);
label1.setSize(700, 75);
label1.setFont(new Font("Arial", Font.BOLD,72));
label1.setText("The current time is:");
label1.setForeground(Color.white);
label1.setLocation(625 , (window.getHeight() / 2) - 150);
label1.setVisible(true);
window.add(label1);
//Timer Label
timer = new JLabel();
//label.setHorizontalAlignment(JLabel.CENTER);
timer.setSize(700, 75);
timer.setFont(new Font("Arial", Font.BOLD,100));
timer.setText("00:00");
timer.setLocation(650 , (window.getHeight() / 2) - 30);
timer.setForeground(Color.white);
timer.setVisible(true);
window.add(timer);
quote = new JLabel();
quote.setSize(70000, 100);
quote.setFont(new Font("Arial", Font.BOLD,100));
quote.setText("00:00");
quote.setForeground(Color.white);
quote.setVisible(true);
window.add(quote);
}
public void StartClock()
{
if(observer != null && observer1 != null)
{
time = new Time(observer, true);
quoteTimer = new QuoteTimer(observer1,true);
}
else
{
throw new IllegalArgumentException("An observer is required.");
}
StartQuote();
Thread quoteThread = new Thread((Runnable)quoteTimer);
quoteThread.start();
Thread timerThread = new Thread(((Runnable)time));
timerThread.start();
}
public void Callback()
{
date.setText(((Time) time).getDay());
timer.setText(time.toString());
setImage(((Time)time).getHour());
}
private void StartQuote()
{
quote.setLocation(window.getWidth(), (window.getHeight() / 2) + 100);
//quote.add(timer);
SelectQuote();
}
private void SelectQuote()
{
Random rand = new Random();
int index = rand.nextInt(quotes.length);
String str = quotes[index];
quote.setText(str);
}
private void EndQuote()
{
//System.out.println(quote.getX());
if(quote.getX() < -10000)
{
StartQuote();
}
}
public void MoveQuote()
{
quote.setLocation(quote.getX()-1, quote.getY());
EndQuote();
window.repaint();
}
private String[] GetQuoteArray()
{
String[] quote = new String[quotesList.size()];
int i = 0;
for(String str : quotesList)
{
quote[i++] = str;
}
quotesList = null;
return quote;
}
private void setImage(int h)
{
int hour = h;
ClassLoader loader = this.getClass().getClassLoader();
URL input = null;
if(hour <= 6 || hour >= 19)
{
input = loader.getResource("nightTimeCity.jpg");
}
else
{
input = loader.getResource("daytimeCityscape.jpg");
}
JLabel image = new JLabel();
image.setIcon(new ImageIcon(input));
image.setLocation(0,0);
image.setSize(window.getWidth(), window.getHeight());
image.setVisible(true);
window.add(image);
window.getContentPane().setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
//window.setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
}
}
|
package io.vepo.access.lang;
public interface HelloService {
public String sayHello(String username);
}
|
package com.fomin.push.util;
import android.util.Log;
/**
* Created by Fomin on 2018/10/25.
*/
public class LogUtil {
public static boolean isDebug = false;
private static final String TAG = "PushTag";
public static void d(String msg) {
if (isDebug)
Log.d(TAG, msg);
}
public static void i(String msg) {
if (isDebug)
Log.d(TAG, msg);
}
public static void e(String msg) {
Log.e(TAG, msg);
}
public static void e(String msg, Throwable t) {
Log.e(TAG, msg, t);
}
}
|
/*
MIT License
Copyright (c) 2016 Kent Randall
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.point85.domain.schedule;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import org.point85.domain.i18n.DomainLocalizer;
import org.point85.domain.plant.KeyedObject;
/**
* Class Named represents a named object such as a Shift or Team.
*
* @author Kent Randall
*
*/
@MappedSuperclass
public abstract class Named extends KeyedObject {
// name
@Column(name = "NAME")
private String name;
// description
@Column(name = "DESCRIPTION")
private String description;
protected Named() {
}
protected Named(String name, String description) {
this.name = name;
this.description = description;
}
/**
* Get name
*
* @return Name
*/
public String getName() {
return name;
}
/**
* Set name
*
* @param name Name
* @throws Exception exception
*/
public void setName(String name) throws Exception {
if (name == null) {
throw new Exception(DomainLocalizer.instance().getErrorString("name.not.defined"));
}
this.name = name;
}
/**
* Get description
*
* @return Description
*/
public String getDescription() {
return description;
}
/**
* Set description
*
* @param description Description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Compare this named object to another named object
*
* @return true if equal
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof Named)) {
return false;
}
return getName().equals(((Named) other).getName());
}
/**
* Get the hash code
*
* @return hash code
*/
@Override
public int hashCode() {
return Objects.hashCode(getName());
}
/**
* Get a string representation of a named object
*/
@Override
public String toString() {
return getName() + " (" + getDescription() + ")";
}
}
|
/**
* PARA DOCUMENTAR QUE CONTIENE ESTE PACJKAGE
* EJERCICIOS PARA APRENDER EL USO DE EXCEPTION (Cap.9)
*/
/**
* @author Administrador
*
*/
package com.ipartek.formacion.javalibro.excepciones; |
package com.soa.display;
import com.soa.ws.category.WSCave;
import com.soa.ws.category.WSForest;
import com.soa.ws.category.WSTower;
import com.soa.ws.hero.WSDragon;
import com.soa.ws.hero.WSElf;
import com.soa.ws.hero.WSMag;
public interface Displayer {
void display(WSCave[] wsCaves);
void display(WSForest[] wsForests);
void display(WSTower[] wsTowers);
void display(WSCave wsCave);
void display(WSForest wsForest);
void display(WSTower wsTower);
void display(WSDragon[] wsDragons);
void display(WSElf[] wsElves);
void display(WSMag[] wsMags);
void display(WSDragon wsDragon);
void display(WSElf wsElves);
void display(WSMag wsMag);
}
|
package com.ethan.df.singleton_pattern;
import java.io.ObjectStreamException;
/**
* 懒汉单例模式2:DCL懒汉单例模式 [不推荐]
* DCL: 两次判空+锁
* 缺点:高并发情况下存在缺陷,存在DCL失效问题,发生概率极小;
*/
public class DclSingleton {
/**
* volatile
* 1. 保证主内存共享变量的可见性,每次线程X本地内存的读写都会刷入主内存中,并使其它线程本地内存的缓存失效
* 2. 禁止指令重排,保证mInstance要么是null,要么是完整的对象;
*/
private volatile static DclSingleton mInstance;
private DclSingleton() {}
public static DclSingleton getInstance() {
// 第一次判空,避免不必要的同步
if(mInstance == null) {
synchronized(DclSingleton.class) {
if(mInstance == null) {
mInstance = new DclSingleton();
}
}
}
return mInstance;
}
/**
* 反序列化钩子函数
* 防止反序列化时重新创建实例的现象
*/
private Object readResolve() throws ObjectStreamException {
return mInstance;
}
}
|
package v2;
public class LevelStrategy {
int level;
double fitness;
char[] init_strategy;
char[] balance_strategy;
char[] bandwagon_strategy;
public LevelStrategy(int level, char[] init_strategy, char[] balance_strategy,
char[] bandwagon_strategy) {
this.level = level;
this.init_strategy = init_strategy;
this.balance_strategy = balance_strategy;
this.bandwagon_strategy = bandwagon_strategy;
checkErrors();
}
public LevelStrategy(int level, char[] init_strategy) {
this.level = level;
this.init_strategy = init_strategy;
checkErrors();
}
private void checkErrors() {
if (level < 2 || level > MasterVariables.MAXSYSTEM || init_strategy == null
|| (balance_strategy == null && level > 2) || (bandwagon_strategy == null && level > 2)) {
System.out.println("LevelStrategy class erorr!!!!");
System.exit(0);
}
}
}
|
package br.com.douglastuiuiu.biometricengine.integration.creddefense.dto.response.viewdata;
import java.io.Serializable;
import java.util.List;
/**
* @author douglas
* @since 31/03/2017
*/
public class ViewDataCol3DTO implements Serializable {
private static final long serialVersionUID = 273431933760233099L;
private List<ViewDataCol3CreditRequestSimilarsDTO> creditrequest_similars;
private List<ViewDataCol3CustomerSimilarsDTO> customer_similars;
public List<ViewDataCol3CreditRequestSimilarsDTO> getCreditrequest_similars() {
return creditrequest_similars;
}
public void setCreditrequest_similars(List<ViewDataCol3CreditRequestSimilarsDTO> creditrequest_similars) {
this.creditrequest_similars = creditrequest_similars;
}
public List<ViewDataCol3CustomerSimilarsDTO> getCustomer_similars() {
return customer_similars;
}
public void setCustomer_similars(List<ViewDataCol3CustomerSimilarsDTO> customer_similars) {
this.customer_similars = customer_similars;
}
}
|
class Bola
{
int r;
public double volume()
{
return 4/3 * Lingkaran.PI * r * r * r;
}
}
class BangunRuang
{
public static void main(String[] args)
{
Bola bolaKasti = new Bola();
Bola bolaKaki = new Bola();
bolaKasti.r = 7;
bolaKaki.r = 28;
System.out.println("Volume Bola Kasti ialah " + bolaKasti.volume());
System.out.println("Volume Bola Kaki ialah " + bolaKaki.volume());
}
} |
/*
* 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 prj_cadusu;
/**
*
* @author ddamaceno
*/
public class Prj_CadUsu {
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.agent;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.ResourceBundle;
import java.util.function.Function;
import java.util.function.Predicate;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.TypeReference;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import static org.springframework.aot.hint.predicate.RuntimeHintsPredicates.reflection;
import static org.springframework.aot.hint.predicate.RuntimeHintsPredicates.resource;
/**
* Java method that is instrumented by the {@link RuntimeHintsAgent}.
*
* <p>All {@linkplain RecordedInvocation invocations are recorded} by the agent
* at runtime. We can then verify that the {@link RuntimeHints} configuration
* {@linkplain #matcher(RecordedInvocation) matches} the runtime behavior of the
* codebase.
*
* @author Brian Clozel
* @since 6.0
* @see RuntimeHintsPredicates
*/
enum InstrumentedMethod {
/*
* Reflection calls
*/
/**
* {@link Class#forName(String)} and {@link Class#forName(String, boolean, ClassLoader)}.
*/
CLASS_FORNAME(Class.class, "forName", HintType.REFLECTION,
invocation -> {
String className = invocation.getArgument(0);
return reflection().onType(TypeReference.of(className));
}),
/**
* {@link Class#getClasses()}.
*/
CLASS_GETCLASSES(Class.class, "getClasses", HintType.REFLECTION,
invocation -> {
Class<?> thisClass = invocation.getInstance();
return reflection().onType(TypeReference.of(thisClass))
.withAnyMemberCategory(MemberCategory.DECLARED_CLASSES, MemberCategory.PUBLIC_CLASSES);
}
),
/**
* {@link Class#getConstructor(Class[])}.
*/
CLASS_GETCONSTRUCTOR(Class.class, "getConstructor", HintType.REFLECTION,
invocation -> {
Constructor<?> constructor = invocation.getReturnValue();
if (constructor == null) {
return runtimeHints -> false;
}
return reflection().onConstructor(constructor).introspect();
}
),
/**
* {@link Class#getConstructors()}.
*/
CLASS_GETCONSTRUCTORS(Class.class, "getConstructors", HintType.REFLECTION,
invocation -> {
Class<?> thisClass = invocation.getInstance();
return reflection().onType(TypeReference.of(thisClass)).withAnyMemberCategory(
MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS, MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
),
/**
* {@link Class#getDeclaredClasses()}.
*/
CLASS_GETDECLAREDCLASSES(Class.class, "getDeclaredClasses", HintType.REFLECTION,
invocation -> {
Class<?> thisClass = invocation.getInstance();
return reflection().onType(TypeReference.of(thisClass)).withMemberCategory(MemberCategory.DECLARED_CLASSES);
}
),
/**
* {@link Class#getDeclaredConstructor(Class[])}.
*/
CLASS_GETDECLAREDCONSTRUCTOR(Class.class, "getDeclaredConstructor", HintType.REFLECTION,
invocation -> {
Constructor<?> constructor = invocation.getReturnValue();
if (constructor == null) {
return runtimeHints -> false;
}
TypeReference thisType = invocation.getInstanceTypeReference();
return reflection().onType(thisType).withMemberCategory(MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS)
.or(reflection().onConstructor(constructor).introspect());
}
),
/**
* {@link Class#getDeclaredConstructors()}.
*/
CLASS_GETDECLAREDCONSTRUCTORS(Class.class, "getDeclaredConstructors", HintType.REFLECTION,
invocation -> {
Class<?> thisClass = invocation.getInstance();
return reflection().onType(TypeReference.of(thisClass))
.withAnyMemberCategory(MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}),
/**
* {@link Class#getDeclaredField(String)}.
*/
CLASS_GETDECLAREDFIELD(Class.class, "getDeclaredField", HintType.REFLECTION,
invocation -> {
Field field = invocation.getReturnValue();
if (field == null) {
return runtimeHints -> false;
}
TypeReference thisType = invocation.getInstanceTypeReference();
return reflection().onType(thisType).withMemberCategory(MemberCategory.DECLARED_FIELDS)
.or(reflection().onField(field));
}
),
/**
* {@link Class#getDeclaredFields()}.
*/
CLASS_GETDECLAREDFIELDS(Class.class, "getDeclaredFields", HintType.REFLECTION,
invocation -> {
Class<?> thisClass = invocation.getInstance();
return reflection().onType(TypeReference.of(thisClass)).withMemberCategory(MemberCategory.DECLARED_FIELDS);
}
),
/**
* {@link Class#getDeclaredMethod(String, Class[])}.
*/
CLASS_GETDECLAREDMETHOD(Class.class, "getDeclaredMethod", HintType.REFLECTION,
invocation -> {
Method method = invocation.getReturnValue();
if (method == null) {
return runtimeHints -> false;
}
TypeReference thisType = invocation.getInstanceTypeReference();
return reflection().onType(thisType)
.withAnyMemberCategory(MemberCategory.INTROSPECT_DECLARED_METHODS, MemberCategory.INVOKE_DECLARED_METHODS)
.or(reflection().onMethod(method).introspect());
}
),
/**
* {@link Class#getDeclaredMethods()}.
*/
CLASS_GETDECLAREDMETHODS(Class.class, "getDeclaredMethods", HintType.REFLECTION,
invocation -> {
Class<?> thisClass = invocation.getInstance();
return reflection().onType(TypeReference.of(thisClass))
.withAnyMemberCategory(MemberCategory.INTROSPECT_DECLARED_METHODS, MemberCategory.INVOKE_DECLARED_METHODS);
}
),
/**
* {@link Class#getField(String)}.
*/
CLASS_GETFIELD(Class.class, "getField", HintType.REFLECTION,
invocation -> {
Field field = invocation.getReturnValue();
if (field == null) {
return runtimeHints -> false;
}
TypeReference thisType = invocation.getInstanceTypeReference();
return reflection().onType(thisType).withMemberCategory(MemberCategory.PUBLIC_FIELDS)
.and(runtimeHints -> Modifier.isPublic(field.getModifiers()))
.or(reflection().onType(thisType).withMemberCategory(MemberCategory.DECLARED_FIELDS))
.or(reflection().onField(invocation.getReturnValue()));
}),
/**
* {@link Class#getFields()}.
*/
CLASS_GETFIELDS(Class.class, "getFields", HintType.REFLECTION,
invocation -> {
Class<?> thisClass = invocation.getInstance();
return reflection().onType(TypeReference.of(thisClass))
.withAnyMemberCategory(MemberCategory.PUBLIC_FIELDS, MemberCategory.DECLARED_FIELDS);
}
),
/**
* {@link Class#getMethod(String, Class[])}.
*/
CLASS_GETMETHOD(Class.class, "getMethod", HintType.REFLECTION,
invocation -> {
Method method = invocation.getReturnValue();
if (method == null) {
return runtimeHints -> false;
}
TypeReference thisType = invocation.getInstanceTypeReference();
return reflection().onType(thisType).withAnyMemberCategory(MemberCategory.INTROSPECT_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_METHODS)
.and(runtimeHints -> Modifier.isPublic(method.getModifiers()))
.or(reflection().onType(thisType).withAnyMemberCategory(MemberCategory.INTROSPECT_DECLARED_METHODS, MemberCategory.INVOKE_DECLARED_METHODS))
.or(reflection().onMethod(method).introspect())
.or(reflection().onMethod(method).invoke());
}
),
/**
* {@link Class#getMethods()}.
*/
CLASS_GETMETHODS(Class.class, "getMethods", HintType.REFLECTION,
invocation -> {
Class<?> thisClass = invocation.getInstance();
return reflection().onType(TypeReference.of(thisClass)).withAnyMemberCategory(
MemberCategory.INTROSPECT_PUBLIC_METHODS, MemberCategory.INTROSPECT_DECLARED_METHODS,
MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_DECLARED_METHODS);
}
),
/**
* {@link ClassLoader#loadClass(String)}.
*/
CLASSLOADER_LOADCLASS(ClassLoader.class, "loadClass", HintType.REFLECTION,
invocation -> {
Class<?> klass = invocation.getReturnValue();
if (klass == null) {
return runtimeHints -> false;
}
return reflection().onType(klass);
}),
/**
* {@link Constructor#newInstance(Object...)}.
*/
CONSTRUCTOR_NEWINSTANCE(Constructor.class, "newInstance", HintType.REFLECTION,
invocation -> reflection().onConstructor(invocation.getInstance()).invoke()),
/**
* {@link Method#invoke(Object, Object...)}.
*/
METHOD_INVOKE(Method.class, "invoke", HintType.REFLECTION,
invocation -> reflection().onMethod(invocation.getInstance()).invoke()),
/**
* {@link Field#get(Object)}.
*/
FIELD_GET(Field.class, "get", HintType.REFLECTION,
invocation -> reflection().onField(invocation.getInstance())),
/**
* {@link Field#set(Object, Object)}.
*/
FIELD_SET(Field.class, "set", HintType.REFLECTION,
invocation -> reflection().onField(invocation.getInstance())),
/*
* Resource bundle calls
*/
/**
* {@link java.util.ResourceBundle#getBundle(String)}.
*/
RESOURCEBUNDLE_GETBUNDLE(ResourceBundle.class, "getBundle", HintType.RESOURCE_BUNDLE,
invocation -> {
String bundleName = invocation.getArgument(0);
return resource().forBundle(bundleName);
}),
/*
* Resource pattern calls
*/
/**
* {@link Class#getResource(String)}.
*/
CLASS_GETRESOURCE(Class.class, "getResource", HintType.RESOURCE_PATTERN,
invocation -> {
Class<?> thisClass = invocation.getInstance();
String resourceName = invocation.getArgument(0);
return resource().forResource(TypeReference.of(thisClass), resourceName);
}),
/**
* {@link Class#getResourceAsStream(String)}.
*/
CLASS_GETRESOURCEASSTREAM(Class.class, "getResourceAsStream", HintType.RESOURCE_PATTERN,
CLASS_GETRESOURCE.hintsMatcherGenerator),
/**
* {@link java.lang.ClassLoader#getResource(String)}.
*/
CLASSLOADER_GETRESOURCE(ClassLoader.class, "getResource", HintType.RESOURCE_PATTERN,
invocation -> {
String resourceName = invocation.getArgument(0);
return resource().forResource(resourceName);
}),
/**
* {@link java.lang.ClassLoader#getResourceAsStream(String)}.
*/
CLASSLOADER_GETRESOURCEASSTREAM(ClassLoader.class, "getResourceAsStream", HintType.RESOURCE_PATTERN,
CLASSLOADER_GETRESOURCE.hintsMatcherGenerator),
/**
* {@link java.lang.ClassLoader#getResources(String)}.
*/
CLASSLOADER_GETRESOURCES(ClassLoader.class, "getResources", HintType.RESOURCE_PATTERN,
CLASSLOADER_GETRESOURCE.hintsMatcherGenerator),
/**
* {@link java.lang.Module#getResourceAsStream(String)}.
*/
MODULE_GETRESOURCEASSTREAM(Module.class, "getResourceAsStream", HintType.RESOURCE_PATTERN,
CLASSLOADER_GETRESOURCE.hintsMatcherGenerator),
/**
* {@link java.lang.ClassLoader#resources(String)}.
*/
CLASSLOADER_RESOURCES(ClassLoader.class, "resources", HintType.RESOURCE_PATTERN,
CLASSLOADER_GETRESOURCE.hintsMatcherGenerator),
/*
* JDK Proxy calls
*/
/**
* {@link Proxy#newProxyInstance(ClassLoader, Class[], InvocationHandler)}.
*/
PROXY_NEWPROXYINSTANCE(Proxy.class, "newProxyInstance", HintType.JDK_PROXIES,
invocation -> {
Class<?>[] classes = invocation.getArgument(1);
return RuntimeHintsPredicates.proxies().forInterfaces(classes);
});
private final MethodReference methodReference;
private final HintType hintType;
private final Function<RecordedInvocation, Predicate<RuntimeHints>> hintsMatcherGenerator;
InstrumentedMethod(Class<?> klass, String methodName, HintType hintType, Function<RecordedInvocation, Predicate<RuntimeHints>> hintsMatcherGenerator) {
this.methodReference = MethodReference.of(klass, methodName);
this.hintType = hintType;
this.hintsMatcherGenerator = hintsMatcherGenerator;
}
/**
* Return a {@link MethodReference reference} to the method being instrumented.
*/
MethodReference methodReference() {
return this.methodReference;
}
/**
* Return the type of {@link RuntimeHints hint} needed ofr the current instrumented method.
*/
HintType getHintType() {
return this.hintType;
}
/**
* Return a predicate that matches if the current invocation is covered by the given hints.
* <p>A runtime invocation for reflection, resources, etc. can be backed by different hints.
* For example, {@code MyClass.class.getMethod("sample", null)} can be backed by a reflection
* hint on this method only, or a reflection hint on all public/declared methods of the class.
* @param invocation the current invocation of the instrumented method
*/
Predicate<RuntimeHints> matcher(RecordedInvocation invocation) {
return this.hintsMatcherGenerator.apply(invocation);
}
}
|
package xyz.umng.freelance;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
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.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import butterknife.Bind;
import butterknife.ButterKnife;
public class WorkActivity extends AppCompatActivity {
private static final String TAG = "WorkActivity";
ProgressDialog pd;
@Bind(R.id.input_firstName) EditText _firstNameText;
@Bind(R.id.input_lastName) EditText _lastNameText;
@Bind(R.id.input_email) EditText _emailText;
@Bind(R.id.input_phone) EditText _phoneText;
@Bind(R.id.input_stream) EditText _streamText;
@Bind(R.id.input_work_do) EditText _workDoText;
@Bind(R.id.input_more_about_you) EditText _moreAboutYouText;
@Bind(R.id.btn_submit_work) Button _submitButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work);
ButterKnife.bind(this);
_submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pd = new ProgressDialog(WorkActivity.this,
R.style.AppTheme_Dark_Dialog);
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.setMessage("Submitting...");
pd.show();
submit();
}
});
}
public void submit() {
Log.d(TAG, "WorkActivity");
if (!validate()) {
onSubmitFailed();
return;
}
_submitButton.setEnabled(false);
String firstName = _firstNameText.getText().toString().trim();
String lastName = _lastNameText.getText().toString().trim();
String email = _emailText.getText().toString().trim();
String phone = _phoneText.getText().toString().trim();
String stream = _streamText.getText().toString().trim();
String workDo = _workDoText.getText().toString().trim();
String moreAboutYou = _moreAboutYouText.getText().toString().trim();
ParseObject work = new ParseObject("Work");
work.put("firstName", firstName);
work.put("lastName", lastName);
work.put("email", email);
work.put("phone", phone);
work.put("stream", stream);
work.put("workDo", workDo);
work.put("moreAboutYou", moreAboutYou);
work.saveInBackground(new SaveCallback() {
public void done(com.parse.ParseException e) {
if (e == null) {
onSubmitSuccess();
} else {
onSubmitFailed();
Toast.makeText(WorkActivity.this, "Error\nPlease try again later", Toast.LENGTH_LONG).show();
}
}
});
}
public void onSubmitSuccess() {
_submitButton.setEnabled(true);
pd.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(WorkActivity.this);
builder.setMessage("Your response has been successfully recorded. We will contact you soon.");
builder.setCancelable(false);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
finish();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
public void onSubmitFailed() {
_submitButton.setEnabled(true);
pd.dismiss();
}
public boolean validate() {
boolean valid = true;
String firstName = _firstNameText.getText().toString().trim();
String lastName = _lastNameText.getText().toString().trim();
String email = _emailText.getText().toString().trim();
String phone = _phoneText.getText().toString().trim();
String stream = _streamText.getText().toString().trim();
String workDo = _workDoText.getText().toString().trim();
String moreAboutYou = _moreAboutYouText.getText().toString().trim();
if (firstName.isEmpty() || firstName.length() < 3) {
_firstNameText.setError("at least 3 characters");
valid = false;
} else {
_firstNameText.setError(null);
}
if (lastName.isEmpty() || lastName.length() < 3) {
_lastNameText.setError("at least 3 characters");
valid = false;
} else {
_lastNameText.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (phone.isEmpty() || phone.length() < 4 || phone.length() > 10) {
_phoneText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_phoneText.setError(null);
}
if (stream.isEmpty() || stream.length() < 3) {
_streamText.setError("at least 3 characters");
valid = false;
} else {
_streamText.setError(null);
}
if (workDo.isEmpty() || workDo.length() < 3) {
_workDoText.setError("at least 3 characters");
valid = false;
} else {
_workDoText.setError(null);
}
if (moreAboutYou.isEmpty() || moreAboutYou.length() < 10) {
_moreAboutYouText.setError("at least 10 characters");
valid = false;
} else {
_moreAboutYouText.setError(null);
}
return valid;
}
}
|
package gov.nih.mipav.view;
import gov.nih.mipav.model.file.*;
import gov.nih.mipav.model.structures.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
/**
* DOCUMENT ME!
*/
public class ViewDICOMDoubleListPanel extends ViewSelectableDoubleListPanel {
//~ Static fields/initializers -------------------------------------------------------------------------------------
/** Use serialVersionUID for interoperability. */
private static final long serialVersionUID = 3583232599838861716L;
//~ Instance fields ------------------------------------------------------------------------------------------------
/** DOCUMENT ME! */
protected JButton btnMoveDown;
/** DOCUMENT ME! */
protected JButton btnMoveUp;
/** DOCUMENT ME! */
protected SortingTableModel leftTableModel;
/** DOCUMENT ME! */
protected TableSorter leftTableSorter;
/** DOCUMENT ME! */
protected SortingTableModel rightTableModel;
/** DOCUMENT ME! */
protected TableSorter rightTableSorter;
//~ Constructors ---------------------------------------------------------------------------------------------------
/**
* Creates a new ViewDICOMDoubleListPanel object.
*
* @param leftTable DOCUMENT ME!
* @param rightTable DOCUMENT ME!
*/
public ViewDICOMDoubleListPanel(JTable leftTable, JTable rightTable) {
super(leftTable, rightTable);
rightTableSorter = (TableSorter) rightTable.getModel();
leftTableSorter = (TableSorter) leftTable.getModel();
rightTableModel = (SortingTableModel) rightTableSorter.getTableModel();
leftTableModel = (SortingTableModel) leftTableSorter.getTableModel();
rightTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
}
//~ Methods --------------------------------------------------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @param event DOCUMENT ME!
*/
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("add")) {
int[] selectedRows = leftTable.getSelectedRows();
for (int i = 0; i < selectedRows.length; i++) {
Vector<Object> dicomRowVector = leftTableModel.getRow(leftTableSorter.modelIndex(selectedRows[i]));
Object object = dicomRowVector.elementAt(0);
if (object instanceof FileDicomKey) {
FileDicomKey dicomKey = (FileDicomKey) dicomRowVector.elementAt(0);
dicomRowVector.setElementAt(dicomKey.getKey(), 0); // change the key from a FileDicomKey to a String
} else {
dicomRowVector.setElementAt(object, 0); // should be String, namely the CUSTOM tag
}
rightTableModel.addRow(dicomRowVector);
}
leftTable.clearSelection();
} else if (command.equals("remove")) {
int[] selectedRows = rightTable.getSelectedRows();
// todo: explain what happening here: why reverse counter loop?
for (int i = selectedRows.length - 1; i >= 0; i--) {
Vector<Object> row = rightTableModel.getRow(rightTableSorter.modelIndex(selectedRows[i]));
String tagName = (String) row.elementAt(0);
if (tagName.equals("Instance (formerly Image) Number")) {
MipavUtil.displayInfo("Can't remove 'Instance (formerly Image) Number' column.");
continue;
}
rightTableModel.removeRow(rightTableSorter.modelIndex(selectedRows[i]));
}
} else if (command.equals("move up") || command.equals("move down")) {
/**
* This is an ugly algorithm, but I don't know any other way of doing it. The problem is that the
* TableSorter blah blah blah todo:finish this explanation
*
*/
// save current row order into vector
Vector<Object> currentRowOrder = getCurrentRowOrder(rightTableSorter);
int[] selectedRows = rightTable.getSelectedRows();
if ((selectedRows.length < 1) || (currentRowOrder.size() <= 1)) {
return;
}
if (command.equals("move up")) {
// reorder the elements that need reordering
for (int i = 0; i < selectedRows.length; i++) {
if ((selectedRows[i] - 1) >= 0) {
Object moveObject = currentRowOrder.elementAt(selectedRows[i]);
currentRowOrder.removeElementAt(selectedRows[i]);
currentRowOrder.insertElementAt(moveObject, selectedRows[i] - 1);
}
}
} else if (command.equals("move down")) {
for (int i = selectedRows.length - 1; i >= 0; i--) {
if ((selectedRows[i] + 1) < currentRowOrder.size()) {
Object moveObject = currentRowOrder.elementAt(selectedRows[i]);
currentRowOrder.removeElementAt(selectedRows[i]);
currentRowOrder.insertElementAt(moveObject, selectedRows[i] + 1);
}
}
}
// remove all rows from current table
rightTableModel.removeAllRows();
// set the table sorting status to "unsorted"
rightTableSorter.setSortingStatus(0, TableSorter.NOT_SORTED);
// re-add the reordered rows
for (int i = 0; i < currentRowOrder.size(); i++) {
rightTableModel.addRow((Vector<Object>)currentRowOrder.elementAt(i));
}
// re-select previously selected rows
if (command.equals("move up")) {
int selection0 = Math.max(0, (selectedRows[0] - 1));
int selection1 = Math.max(0, (selectedRows[selectedRows.length - 1] - 1));
rightTable.setRowSelectionInterval(selection0, selection1);
} else if (command.equals("move down")) {
int selection0 = Math.min(rightTableModel.getRowCount() - 1, (selectedRows[0] + 1));
int selection1 = Math.min(rightTableModel.getRowCount() - 1,
(selectedRows[selectedRows.length - 1] + 1));
rightTable.setRowSelectionInterval(selection0, selection1);
}
}
}
/**
* DOCUMENT ME!
*/
public void buildGUI() {
super.buildGUI();
btnMoveUp = new JButton("Move up >");
btnMoveUp.setActionCommand("move up");
btnMoveUp.addActionListener(this);
gbConstraints.gridy = 2;
gbConstraints.gridwidth = 3;
gbConstraints.gridheight = 1;
gbConstraints.weightx = 0;
gbConstraints.weighty = 0;
gbConstraints.gridx = 11;
gbLayout.setConstraints(btnMoveUp, gbConstraints);
add(btnMoveUp);
btnMoveDown = new JButton("Move down >");
btnMoveDown.setActionCommand("move down");
btnMoveDown.addActionListener(this);
gbConstraints.gridy = 3;
gbLayout.setConstraints(btnMoveDown, gbConstraints);
add(btnMoveDown);
}
/**
* DOCUMENT ME!
*
* @param tableSorter DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@SuppressWarnings("unchecked")
protected static Vector<Object> getCurrentRowOrder(TableSorter tableSorter) {
SortingTableModel tableModel = (SortingTableModel) tableSorter.getTableModel();
Vector<Object> currentOrder = new Vector<Object>();
for (int i = 0; i < tableModel.getRowCount(); i++) {
Vector<Object> row = tableModel.getRow(tableSorter.modelIndex(i));
currentOrder.addElement(row);
}
return currentOrder;
}
}
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
/**
*
* @author Kimberly (Kacey) Coffey
*
*/
public class main {
public static void main(String[] args) throws FileNotFoundException {
String fileName = "inputText.txt"; //file name containing words to count
File inputFile = new File(fileName);
Scanner fileScanner = new Scanner(inputFile);
Map<String, Integer> m = findUniqueWords(fileScanner);
TreeMap<String, Integer> mSorted = sortMapByValues(m);
printWordsAndCounts(mSorted);
fileScanner.close();
}
/**
* Given a Scanner for a text file, finds each unique word and its count of occurrences in text file.
* @param s Scanner for input text file
* @return a Map containing <word, count> pairs of all unique words from input file
*/
public static Map<String, Integer> findUniqueWords(Scanner s) {
Map<String, Integer> m = new HashMap<String, Integer>(); //contain <word, count> pairs
while (s.hasNext()) {
String currentWord = s.next();
currentWord = formatWord(currentWord);
if (m.containsKey(currentWord)) { //if word is already in map, increase its count by 1
int count = (Integer) m.get(currentWord);
count++;
m.replace(currentWord, count);
} else { //otherwise, word needs to be added to map with a count of 1
m.put(currentWord, 1);
}
}
return m;
}
/**
* Given a string, removes any leading or trailing non-alphanumeric characters from string and converts it to lower-case.
* @param s String to format
* @return s as a lower-case String after having removed any leading or trailing non-alphanumeric characters
*/
public static String formatWord(String s) {
int beginningIndex = 0;
while (!Character.isLetterOrDigit(s.charAt(beginningIndex))) { //remove any leading punctuation marks
beginningIndex++;
}
int endingIndex = s.length();
while (!Character.isLetterOrDigit(s.charAt(endingIndex - 1))) { //remove any trailing punctuation marks
endingIndex--;
}
s = s.substring(beginningIndex, endingIndex);
return s.toLowerCase(); //convert all words to lower case
}
/**
* Given a map of <String, Integer> pairs, sorts the map by descending value values.
* @param m Map containing all <word, count> pairs from text file
* @return a TreeMap containing all pairs from m sorted by descending values
*/
public static TreeMap<String, Integer> sortMapByValues(Map<String, Integer> m) {
Comparator<String> comparator = new ValueComparator(m);
TreeMap<String, Integer> t = new TreeMap<String, Integer>(comparator);
t.putAll(m);
return t;
}
/**
* Given a sorted map, prints each pair in given order
* @param m sorted map
*/
public static void printWordsAndCounts(TreeMap<String, Integer> m) {
System.out.println("Word Count");
System.out.println("-----------------------");
while (!m.isEmpty()) {
Map.Entry<String, Integer> pair = m.firstEntry();
String word = pair.getKey();
int count = pair.getValue();
System.out.print(word);
for (int i = word.length(); i < 18; i++) {
System.out.print(" ");
}
System.out.println(count);
m.remove(word);
}
}
}
|
package algorithms.demo;
import algorithms.maze.Position;
/**
* @author Tuval Lifshitz
* This class is a Vertex class,
* each object has a value Position, and a father,
* that is his previous Vertex.
*
*/
public class Vertex {
/**
* the Position of the Vertex
*/
private Position p;
/**
* The vertex that is the father of the Vertex
*/
private Vertex father;
/**
* Contractor for Vertex
* @param self - the position of Vertex
* @param father - the father of the Vertex
*/
public Vertex(Position self, Vertex father) {
this.p = self;
this.father = father;
}
/**
* @return - the position of the Vertex
*/
public Position getP() {
return p;
}
/**
* @param p - sets the Position of the Vertex
*/
public void setP(Position p) {
this.p = p;
}
/**
* @returns the fatehr of the Vertex
*/
public Vertex getFather() {
return father;
}
/**
* @param father - sets the father of the Vertex
*/
public void setFather(Vertex father) {
this.father = father;
}
}
|
package com.partiel_android_boucher.activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.partiel_android_boucher.R;
import com.partiel_android_boucher.classes.Album;
import com.partiel_android_boucher.classes.Artist;
import com.partiel_android_boucher.classes.Track;
import com.partiel_android_boucher.classes.adapters.TracksAdapter;
import com.partiel_android_boucher.classes.realm_classes.RealmAlbum;
import com.partiel_android_boucher.classes.realm_classes.RealmArtist;
import com.partiel_android_boucher.classes.realm_classes.RealmTrack;
import com.partiel_android_boucher.controllers.TrackController;
import com.partiel_android_boucher.tools.RealmConfig;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class AlbumDetailsActivity extends AppCompatActivity {
ImageView albumImage;
TextView albumName, artistName, nbTracks, duration;
ListView trackList;
Album album;
Artist artist;
ArrayList<Track> tracks;
int aid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_album_details);
aid = getIntent().getExtras().getInt("aid");
getAlbumDetails();
TrackController.downloadTracksWithAid(this, aid);
}
@Override
protected void onResume() {
super.onResume();
setUpAlbumDetails();
setUpTracks();
}
private void getAlbumDetails(){
album = RealmAlbum.getAlbumByPid(RealmConfig.realm, aid);
artist = RealmArtist.getArtistByPid(RealmConfig.realm, album.getArtist());
tracks = RealmTrack.getAllTracks(RealmConfig.realm);
}
private void setUpAlbumDetails() {
albumImage = (ImageView) findViewById(R.id.albumDetailsImage);
albumName = (TextView) findViewById(R.id.albumDetailsName);
artistName = (TextView) findViewById(R.id.albumDetailsArtist);
nbTracks = (TextView) findViewById(R.id.albumDetailsNbTracks);
duration = (TextView) findViewById(R.id.albumDetailsDuration);
Picasso.with(this).load(album.getPhotoUrl()).resize(100, 100).centerCrop().into(albumImage);
albumName.setText(album.getTitle());
artistName.setText(artist.toString());
}
private void setUpTracks() {
trackList = (ListView) findViewById(R.id.listTracks);
TracksAdapter tracksAdapter = new TracksAdapter(this, tracks);
trackList.setAdapter(tracksAdapter);
}
}
|
package com.mod.loan.model.DTO;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
/**
* 规则处理结果
*
* @author lijing
* @date 2017/11/7 0007
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class RuleResDTO implements Serializable {
/** 执行结果代码 */
@JsonProperty("code")
private String code;
/** 执行结果描述 */
@JsonProperty("desc")
private String desc;
/** 规则id */
@JsonProperty("score")
private String score;
/** 规则描述 */
@JsonProperty("labelValue")
private Boolean labelValue;
@JsonProperty("isDefaultVal")
private String isDefaultVal;
/** 规则得分 */
@JsonProperty("rule_name")
private String rule_name;
/** 规则得分 */
@JsonProperty("rule_id")
private String rule_id;
}
|
package Multithreading_in_java8;
public class define_run_method_by_method_Reference {
public static void print(){
System.out.println("printing");
}
public static void main(String[] args) {
new Thread(()->print()).start();
}
}
|
package controller;
import hu.alkfejl.model.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
@WebServlet("/AddReservation")
public class AddReservation extends HttpServlet {
List<Screening> screeningList = new ArrayList<>();
List<Integer> seatList = new ArrayList<>();
List<Integer> dimensions = new ArrayList<>();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
User user = (User) req.getSession().getAttribute("currentUser");
if (user == null) {
resp.sendRedirect("pages/login.jsp");
return;
}
List<Movie> movies = WebController.getInstance().getAllMovies();
req.getSession().setAttribute("movies", movies);
if (screeningList.size() > 0) {
req.getSession().setAttribute("screenings", screeningList);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
if (req.getParameter("movie") != null) {
List<Movie> temp = (ArrayList<Movie>) req.getSession().getAttribute("movies");
int movieIndex = Integer.parseInt(req.getParameter("movie"));
req.getSession().setAttribute("movieIndex", movieIndex);
screeningList = WebController.getInstance().screeningsByMovieId(temp.get(movieIndex).getId());
System.out.println(screeningList);
req.getSession().setAttribute("movieId",temp.get(movieIndex).getId());
req.getSession().setAttribute("screenings", screeningList);
resp.sendRedirect("pages/add_reservation.jsp");
} else {
return;
}
if (req.getParameter("screening") != null) {
int screeningIndex = Integer.parseInt(req.getParameter("screening"));
req.getSession().setAttribute("screeningIndex", screeningIndex);
seatList = WebController.getInstance().seatsByScreeningId(screeningList.get(screeningIndex).getId());
dimensions = WebController.getInstance().roomDimensionsByScreeningId(screeningList.get(screeningIndex).getId());
req.getSession().setAttribute("screeningId",screeningList.get(screeningIndex).getId());
req.getSession().setAttribute("rows", dimensions.get(0));
req.getSession().setAttribute("cols", dimensions.get(1));
req.getSession().setAttribute("rowsArr", IntStream.range(1, dimensions.get(0) + 1).toArray());
req.getSession().setAttribute("colsArr", IntStream.range(1, dimensions.get(1) + 1).toArray());
req.getSession().setAttribute("seats", seatList);
} else {
return;
}
if (req.getParameter("seatsIn").length()>0 && req.getParameter("seatsIn").matches("^[\\d+,]+$")) {
List<Integer> givenSeats = (List<Integer>) req.getSession().getAttribute("seats");
for(String s : req.getParameter("seatsIn").split(",")){
if(givenSeats.contains(Integer.parseInt(s))){
System.out.println("seat error");
return;
}
}
User user = (User) req.getSession().getAttribute("currentUser");
Reservation res = new Reservation(0,Integer.parseInt(req.getSession().getAttribute("screeningId").toString()),user.getUsername());
WebController.getInstance().addReservation(res);
for(String a : req.getParameter("seatsIn").split(",")){
WebController.getInstance().addSeat(new Seat(WebController.getInstance().lastReservationId(),Integer.parseInt(a)));
}
resp.sendRedirect("pages/list_reservation.jsp");
}
}
}
|
package br.com.sgcraft.playerlogger.config;
import br.com.sgcraft.playerlogger.*;
import java.util.*;
public class config
{
playerlogger plugin;
public config(final playerlogger instance) {
this.plugin = instance;
}
public static void LoadConfiguration() {
final List<String> words = new ArrayList<String>();
words.add("7");
words.add("46");
words.add("57");
final List<String> cmds = new ArrayList<String>();
cmds.add("/login");
cmds.add("/changepassword");
cmds.add("/register");
final String path1 = "Log.PlayerJoins";
final String path2 = "Log.PlayerQuit";
final String path3 = "Log.PlayerChat";
final String path4 = "Log.PlayerCommands";
final String path5 = "Log.PlayerDeaths";
final String path6 = "Log.PlayerEnchants";
final String path7 = "Log.PlayerBucketPlace";
final String path8 = "Log.PlayerSignText";
final String path9 = "Log.Pvp";
final String path10 = "Log.ConsoleCommands";
final String path11 = "Log.DateFormat";
final String path12 = "BlackList.LogBlackListedBlocks";
final String path13 = "BlackList.Blocks";
final String path14 = "Commands.BlackListCommands";
final String path15 = "Commands.BlackListCommandsForMySQL";
final String path16 = "Commands.CommandsToBlock";
final String path17 = "Log.SeparateFolderforStaff";
final String path18 = "Log.PlayerNamestoLowerCase";
final String path19 = "File.LogToFiles";
final String path20 = "Log.LogOnlyStaff";
final String path21 = "MySQL.Enabled";
final String path22 = "MySQL.Server";
final String path23 = "MySQL.Database";
final String path24 = "MySQL.User";
final String path25 = "MySQL.Password";
playerlogger.plugin.getConfig().addDefault("File.LogToFiles", (Object)true);
playerlogger.plugin.getConfig().addDefault("Log.PlayerJoins", (Object)true);
playerlogger.plugin.getConfig().addDefault("Log.PlayerQuit", (Object)true);
playerlogger.plugin.getConfig().addDefault("Log.PlayerChat", (Object)true);
playerlogger.plugin.getConfig().addDefault("Log.PlayerCommands", (Object)true);
playerlogger.plugin.getConfig().addDefault("Log.PlayerDeaths", (Object)true);
playerlogger.plugin.getConfig().addDefault("Log.PlayerEnchants", (Object)true);
playerlogger.plugin.getConfig().addDefault("Log.Pvp", (Object)true);
playerlogger.plugin.getConfig().addDefault("Log.PlayerBucketPlace", (Object)true);
playerlogger.plugin.getConfig().addDefault("Log.ConsoleCommands", (Object)true);
playerlogger.plugin.getConfig().addDefault("Log.DateFormat", (Object)"MM-dd-yyyy HH:mm:ss");
playerlogger.plugin.getConfig().addDefault("BlackList.LogBlackListedBlocks", (Object)true);
playerlogger.plugin.getConfig().addDefault("BlackList.Blocks", (Object)words);
playerlogger.plugin.getConfig().addDefault("Log.PlayerSignText", (Object)true);
playerlogger.plugin.getConfig().addDefault("Commands.BlackListCommands", (Object)false);
playerlogger.plugin.getConfig().addDefault("Commands.BlackListCommandsForMySQL", (Object)false);
playerlogger.plugin.getConfig().addDefault("Commands.CommandsToBlock", (Object)cmds);
playerlogger.plugin.getConfig().addDefault("Log.SeparateFolderforStaff", (Object)true);
playerlogger.plugin.getConfig().addDefault("Log.PlayerNamestoLowerCase", (Object)false);
playerlogger.plugin.getConfig().addDefault("Log.LogOnlyStaff", (Object)false);
playerlogger.plugin.getConfig().addDefault("MySQL.Enabled", (Object)false);
playerlogger.plugin.getConfig().addDefault("MySQL.Server", (Object)"Server Address eg.Localhost");
playerlogger.plugin.getConfig().addDefault("MySQL.Database", (Object)"Place Database name here");
playerlogger.plugin.getConfig().addDefault("MySQL.User", (Object)"Place User of MySQL Database here");
playerlogger.plugin.getConfig().addDefault("MySQL.Password", (Object)"Place User password here");
playerlogger.plugin.getConfig().options().copyDefaults(true);
playerlogger.plugin.saveConfig();
}
}
|
package ru.malichenko.market.services;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import ru.malichenko.market.entities.ProfileEntity;
import ru.malichenko.market.repositories.ProfileRepository;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class ProfileService {
private final ProfileRepository profileRepository;
public void save(ProfileEntity profileEntity) {
profileRepository.save(profileEntity);
}
public Optional<ProfileEntity> findByUserId(Long id) {
return profileRepository.findByUserEntityId(id);
}
public boolean existsById(Long id) {
return profileRepository.existsById(id);
}
public ProfileEntity saveOrUpdate(ProfileEntity p) {
return profileRepository.save(p);
}
public Optional<ProfileEntity> findById(Long id) {
return profileRepository.findById(id);
}
public Optional<ProfileEntity> findByUsername(String name) {
return profileRepository.findByUsername(name);
}
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package interfazGrafica;
import logico.*;
import sIstemaLogin.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
*
* @author Oscar
* Esta clase se encarga de gestionar la ventana de login
*/
public class MenuLogin extends Ventana {
private JPasswordField contraseña;
private JTextField nombreUsuario;
private JLabel textoContraseña, textoEncabezado, textoUsuario;
private JButton botonAceptar, botonCancelar;
private SIVU sivu;
/**
* El constructor inicializa la ventana del login y crea al objeto SIVU
*
*/
public MenuLogin() {
super("SIVU", 500, 400);
this.sivu= new SIVU();
this.sivu.cargarArchivos();
generarElementosVentana();
}
private void generarElementosVentana() {
generarCamposTexto();
generarBotones();
generarTexto();
repaint();
}
private void generarCamposTexto() {
this.nombreUsuario = super.generarJTextField(200, 120, 150, 20);
this.add(this.nombreUsuario);
this.contraseña = super.generarJPasswordField(200, 200, 150, 20);
this.add(this.contraseña);
}
private void generarBotones() {
this.botonAceptar = super.generarBoton("Aceptar", 300, 300, 150, 20);
this.add(this.botonAceptar);
this.botonAceptar.addActionListener(this);
this.botonCancelar = super.generarBoton("Cancelar", 50, 300, 150, 20);
this.add(this.botonCancelar);
this.botonCancelar.addActionListener(this);
}
private void generarTexto() {
super.generarJLabel(this.textoContraseña, "Contraseña:", 20, 200, 150, 20);
super.generarJLabelEncabezado(this.textoEncabezado, "Inicio de sesión", 150, 20, 250, 20);
super.generarJLabel(this.textoUsuario, "Usuario:", 20, 120, 150, 20);
}
private void verificarDatosVendedor() {
String nombreVendedor= this.nombreUsuario.getText();
String contraseña= this.contraseña.getText();
Login login= new Login();
boolean condicion = login.verificarLoginVendedor(nombreVendedor, contraseña);
if (condicion == true) {
JOptionPane.showMessageDialog(this, "Ha iniciado correctamente");
MenuVendedorIniciarDia menu = new MenuVendedorIniciarDia(this.sivu,nombreVendedor);
this.dispose();
} else {
JOptionPane.showMessageDialog(this, "Datos erróneos, intentelo nuevamente");
}
}
private void verificarDatosAdministrador() {
String nombreUsuario= this.nombreUsuario.getText();
String contraseña= this.contraseña.getText();
Login login= new Login();
boolean condicion = login.verificarLoginAdmin(nombreUsuario, contraseña);
if (condicion == true) {
JOptionPane.showMessageDialog(this, "Ha iniciado correctamente");
MenuAdministrador menu = new MenuAdministrador(this.sivu,nombreUsuario);
this.dispose();
} else {
JOptionPane.showMessageDialog(this, "Datos erróneos, intentelo nuevamente");
}
}
/**
* Este método gestiona los eventos de la ventana login
* @param e
*/
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.botonAceptar) {
if (this.nombreUsuario.getText().length() == 0 || this.contraseña.getText().length() == 0) {
JOptionPane.showMessageDialog(this, "Ingrese todos los datos");
} else {
if (this.nombreUsuario.getText().equals("admin")) {
verificarDatosAdministrador();
}
else{
verificarDatosVendedor();
}
}
}
if (e.getSource() == this.botonCancelar) {
Bienvenida bienvenida = new Bienvenida();
}
}
}
|
package com.example.restful.response;
/**
* 公共响应体
*/
public class CommonResponse {
/**
* 响应码
*/
private Integer ResultCode;
/**
* 响应信息
*/
private String Message;
public CommonResponse(){}
public CommonResponse(Integer ResultCode,String Message){
this.ResultCode = ResultCode;
this.Message = Message;
}
public Integer getResultCode() {
return ResultCode;
}
public void setResultCode(Integer resultCode) {
ResultCode = resultCode;
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
}
|
package my.yrzy.trade.model;
import com.google.common.base.Objects;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* Created by yangzefeng on 14/12/2
*/
@Data
public class Order implements Serializable {
private static final long serialVersionUID = 6438326501297062850L;
private Long id;
private Integer status; //订单状态
private Long shopId; //店铺id
private String shopName; //店铺名称
private Long sellerId; //卖家id
private String sellerName; //卖家名称
private Long buyerId; //买家id
private String buyerName; //买家名称
private Long businessId; //生意id
private String businessName; //生意名称
private Date createdAt;
private Date updatedAt;
public static enum Status {
INIT(0), OK(1), FAIL(-2);
private final int value;
private Status(int value) {
this.value = value;
}
public int value() {
return value;
}
public static Status from(Integer value) {
for (Status status : Status.values()) {
if (Objects.equal(status.value, value)) {
return status;
}
}
return null;
}
}
}
|
package com.ideaheap.logic;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class LogicSentence {
private final SlrParser parser = new SlrParser();
private final LogicReducer reducer = new LogicReducer();
private final Op logic;
private final Map<String, Boolean> entailed = new HashMap<String, Boolean>();
private Set<String> variables = null;
public LogicSentence (String sentence) throws ConverterException{
// Task: tokenize
List<String> atoms = Arrays.asList(sentence
.replaceAll("\\(", " ( ")
.replaceAll("\\)", " ) ")
.replaceAll("=>", " => ")
.replaceAll("<=>", " <=> ")
.replaceAll(",", " , ")
.split(" "));
Queue<String> tokens = new LinkedList<String>(atoms);
while(tokens.contains(""))
tokens.remove("");
logic = parser.parse(tokens);
entailed.put("True", true);
entailed.put("False", false);
for (String s : getVariables()) {
entail(s, null);
}
}
public Boolean isEntailed(String key) {
return entailed.containsKey(key) && entailed.get(key) != null;
}
public Boolean getEntailedValue(String key) {
return entailed.get(key);
}
public void entail(String symbol, Boolean value) throws ConverterException {
if(entailed.containsKey(symbol)) {
if (value != null && entailed.get(symbol) != value) {
throw new ConverterException(symbol + " is in contradiction with " + value);
}
}
else {
entailed.put(symbol, value);
}
}
public boolean isTrue() {
boolean valid = true;
for (String v : variables) {
if (entailed.get(v) == null || entailed.get(v) == false) {
valid = false;
break;
}
}
return valid;
}
public Set<String> getVariables() {
if (variables == null)
variables = getVariables(logic);
return variables;
}
private Set<String> getVariables(Op oper) {
Set<String> variables;
if (oper == null) return new HashSet<String>();
switch(oper.symbol) {
case LITERAL:
variables = new HashSet<String>();
variables.add(oper.symbolName);
break;
default:
variables = getVariables(oper.left);
variables.addAll(getVariables(oper.right));
}
return variables;
}
public Op getLogic() {
return logic;
}
}
|
package com.worldchip.bbpaw.bootsetting.view;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.worldchip.bbpaw.bootsetting.R;
public class MyTosat extends Toast {
public MyTosat(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public static Toast makeText(Context context, int resId, int duration) {
Toast toast = new Toast(context);
//获取LayoutInflater对象
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//由layout文件创建一个View对象
View view = inflater.inflate(R.layout.custom_toast_layout, null);
TextView messge = (TextView)view.findViewById(R.id.toast_messge);
messge.setText(resId);
toast.setView(view);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(duration);
return toast;
}
}
|
package com.smartlead.common.vo;
public class TaskInfoVO {
private int pending;
private int total;
public int getPending() {
return pending;
}
public void setPending(int pending) {
this.pending = pending;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
|
package com.betabeers.storm;
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.StormSubmitter;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.tuple.Fields;
import backtype.storm.utils.Utils;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
public class Launcher {
private static final String[] TRACK_MUNDIAL = {"mundial"};
private static final double[][] LOCATION_PENINSULA = {{-9.17, 36.00}, {3.19, 43.47}};
public static void main(String[] args) {
TopologyBuilder builder = new TopologyBuilder();
Config conf = new Config();
conf.setNumWorkers(3);
conf.setNumAckers(1);
conf.setMessageTimeoutSecs(10);
builder.setSpout("twitter", new TwitterSpout(TRACK_MUNDIAL, LOCATION_PENINSULA));
builder.setSpout("commit", new CommitSpout());
builder.setBolt("splitter", new SplitterBolt())
.shuffleGrouping("twitter");
builder.setBolt("counter", new CounterBolt())
.fieldsGrouping("splitter", new Fields("word"))
.allGrouping("commit");
boolean localMode = true;
if (localMode) {
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("NRT", conf, builder.createTopology());
Utils.sleep(60000);
cluster.killTopology("NRT");
cluster.shutdown();
} else {
// If you want to run that on a cluster you would need to mark storm maven dependency to <scope>provided</scope>
try {
StormSubmitter.submitTopology("worldCup", conf, builder.createTopology());
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
}
|
package com.stk123.model.constant;
public class DictConstant {
}
|
package studentRecordsBackup.bst;
import java.util.ArrayList;
import studentRecordsBackup.util.EvenFilterImpl;
import studentRecordsBackup.util.OddEvenFilterI;
import studentRecordsBackup.util.OddFilterImpl;
/**
* @author Hari
*
* Node class that has the details of Node viz. Right Node, Left Node, Max Value.
* And also this class is both Observer and Subject
*/
public class Node implements SubjectI, ObserverI {
private int bNumber;
private String description;
private Node left;
private Node right;
private boolean maxValue = false;
public int getbNumber() {
return bNumber;
}
public void setbNumber(int bNumber) {
this.bNumber = bNumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public boolean isMaxValue() {
return maxValue;
}
public void setMaxValue(boolean isMaxValue) {
this.maxValue = isMaxValue;
}
private ArrayList<Node> observers = new ArrayList<Node>();
private int update;
public int getUpdate() {
return update;
}
public void setUpdate(int updateValue) {
this.update = updateValue;
notifyAllTheRegisteredObservers(updateValue);
}
/**
* @return All the registered observers for a specific node
*/
public ArrayList<Node> getObservers() {
return observers;
}
public void setObservers(ArrayList<Node> observers) {
this.observers = observers;
}
/**
* @param Update value passed from the command line
* @return No return value but update method of Node is called to do the update
*/
public void notifyAllTheRegisteredObservers(int updateValue) {
update(updateValue);
}
/**
* @param List of observers
* Add the given observer to the array list of observers
*/
public void registerObserver(Node observer) {
observers.add(observer);
}
/**
* This method registers a filter and calls the appropriate filter
* @param Update value by which each node has to be updated
* @return No return value but sets the Bnumber with incremented value.
*/
public void update(int updateValue) {
int updateValueReturnedByFilter = 0;
if (updateValue % 2 == 0) {
OddEvenFilterI evenFilter = new EvenFilterImpl();
updateValueReturnedByFilter = evenFilter.oddEvenFilterImplementation(updateValue, observers.get(0).getbNumber());
observers.get(0).setbNumber(updateValueReturnedByFilter);
} else {
OddEvenFilterI oddFilter = new OddFilterImpl();
updateValueReturnedByFilter = oddFilter.oddEvenFilterImplementation(updateValue, observers.get(1).getbNumber());
observers.get(1).setbNumber(updateValueReturnedByFilter);
}
}
}
|
package oop.Interface;
/**
* Interfaces are pure abstract classes, which means that they're a 100% abstract. All the methods or members defined inside
* an interface are abstract and don't need a body. An interface needs to be implemented by a class using the "implements"
* keyword.
*
* EXAMPLE: If we have an interface named "Vehicle" and class named "Car", and if Car implements Vehicle interface, in that
* case, Car has to implement all the methods of the Vehicle class because Vehicle is an interface.
*
* An interface is like a contract to the class that implements that interface. An interface never contains any body for any
* method, it only contains method signatures of the abstract methods.
*/
interface Vehicle {
int x = 100; // by default interface variables are public static final.
// by default, all the methods inside an interface are abstract.
void noOfWheels(); // same as: public abstract void noOfWheels()
void speed(); // by default interface methods are public and abstract
}
class Car implements Vehicle {
@Override
public void noOfWheels() {
System.out.println("Number of wheels: 4");
}
@Override
public void speed() {
System.out.println("120 km/h");
}
}
class InterfaceExample {
public static void main(String[] args) {
Car c = new Car();
c.noOfWheels(); // Number of wheels: 4
c.speed(); // 120 km/h
// c.x = 500; // Compilation Error: The final Vehicle.x cannot be assigned
// Vehicle v = new Vehicle(); // This is illegal because an interface has only pure abstract methods/attributes, and so, we cannot make an object of Vehicle interface
Vehicle v = new Car(); // legal, because an interface
v.noOfWheels(); // Number of wheels: 4
v.speed(); // 120 km/h
// v.x = 500; // Same error as in line 42
}
}
/**
* One final advantage of using interface is that, a class can only extend one class at a time, but a class can implement
* more than 1 interface at a time. Which is the concept of Multiple Inheritance in Java.
*/ |
package com.hqzmss.strategy;
public class TestClass {
public static void main(String[] args) {
Context context = new Context(new ConcreteStrategyTwo());
context.print();
}
}
|
package br.edu.com.dados.repositories;
import java.util.List;
import br.edu.com.entities.Atividade;
public interface IRepositoryAtividade {
public boolean salvarAtividade(Atividade atividade);
public boolean atualizarAtividade(Atividade atividade);
public boolean inativarAtividade(Atividade atividade);
public List<Atividade> listarAtividade();
public List<Atividade> procurarAtividade(String query);
}
|
/*
* 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 tecnicassimulacion;
import static java.awt.image.ImageObserver.WIDTH;
import java.text.DecimalFormat;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
/**
*
* @author steve
*/
public class ModeloB extends javax.swing.JFrame {
JComboBox combo = new JComboBox();
String F1B = "Utilizacion promedio del sistema";
String F2B = "Probabilidad de que cero clientes esten en el sistema";
String F3B = "Probabilidad de que haya n clientes estén en el sistema";
String F4B = "Numero promedio de clientes en la fila de espera";
String F5B = "Tiempo promedio de espera en la fila";
String F6B = "Tiempo promedio transcurrido en el sistema, incluido el servicio";
String F7B = "Tiempo promedio de clientes en el sistema de servicio";
Icon iF1B = new ImageIcon(getClass().getResource("/Imagenes/MODB1.PNG"));
Icon iF2B = new ImageIcon(getClass().getResource("/Imagenes/MODB2.PNG"));
Icon iF3B = new ImageIcon(getClass().getResource("/Imagenes/MODB3.PNG"));
Icon iF4B = new ImageIcon(getClass().getResource("/Imagenes/MODB4.PNG"));
Icon iF5B = new ImageIcon(getClass().getResource("/Imagenes/MODB5.PNG"));
Icon iF6B = new ImageIcon(getClass().getResource("/Imagenes/MODB6.PNG"));
Icon iF7B = new ImageIcon(getClass().getResource("/Imagenes/MODB7.PNG"));
/**
* Creates new form ModeloB
*/
public ModeloB() {
initComponents();
setLocationRelativeTo(null);
jComboBox1.addItem("Seleccione una opcion");
jComboBox1.addItem(F1B);
jComboBox1.addItem(F2B);
jComboBox1.addItem(F3B);
jComboBox1.addItem(F4B);
jComboBox1.addItem(F5B);
jComboBox1.addItem(F6B);
jComboBox1.addItem(F7B);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jComboBox1 = new javax.swing.JComboBox<>();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(101, 146, 191));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tempus Sans ITC", 0, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Seleccione lo que desea calcular:");
jLabel1.setFont(new java.awt.Font("Stencil", 0, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("CALCULO DE FORMULAS MODELO B");
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/atras.png"))); // NOI18N
jButton1.setBorder(null);
jButton1.setBorderPainted(false);
jButton1.setContentAreaFilled(false);
jButton1.setFocusPainted(false);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(90, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(76, 76, 76))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(27, 27, 27)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
.addComponent(jButton1))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
// TODO add your handling code here:
String datos = (String) jComboBox1.getSelectedItem();
if (datos.equals(F1B)) {
String landa = (String) JOptionPane.showInputDialog(null, "Ingrese valor de λ", "MODELO A ", WIDTH, iF1B, null, "");
String mu = (String) JOptionPane.showInputDialog(null, "Ingrese valor de μ", "MODELO A ", WIDTH, iF1B, null, "");
if (landa != null && mu != null) {
if (!landa.isEmpty() && !mu.isEmpty()) {
double vlanda = Double.valueOf(landa);
double vmu = Double.valueOf(mu);
double p = vlanda / vmu;
JOptionPane.showMessageDialog(null, "El promedio del sistema es = " + p);
}
}else
JOptionPane.showMessageDialog(null, "valores nulos");
}
if (datos.equals(F2B)) {
String p = (String) JOptionPane.showInputDialog(null, "Ingrese valor de P", "MODELO B ", WIDTH, iF2B, null, "");
String s = (String) JOptionPane.showInputDialog(null, "Ingrese valor de limite superior (s)", "MODELO B ", WIDTH, iF2B, null, "");
String landa = (String) JOptionPane.showInputDialog(null, "Ingrese valor de λ", "MODELO B ", WIDTH, iF2B, null, "");
String mu = (String) JOptionPane.showInputDialog(null, "Ingrese valor de μ", "MODELO B ", WIDTH, iF2B, null, "");
if (s != null && landa != null && mu != null) {
if (!s.isEmpty() && !landa.isEmpty() && !mu.isEmpty()) {
double vp = Double.valueOf(p);
int vn = 0;
int vs = Integer.parseInt(s);
int vlanda = Integer.parseInt(landa);
int vmu = Integer.parseInt(mu);
//nuevos
//***
int vs2 = vs;
int vs3 = vs;
int vs4 = vs - 1;
//****
int Factorial1 = 1;
int Factorial2 = 1;
int valorResta = 0;
//primer factorial de N!
// int contador2 = 0;
double resultadoDiv1;
double resultadoDiv2 = 1;
double resultadoDiv3;
double resultadoDiv4;
double resultadoMulti;
double resultadoExpo1;
double resultadoExpo2;
double resultadoSuma = 0;
double resultadoSuma2 = 0;
double resultadoSuma3 = 0;
double resultadoFinal;
//factorial de s
while (vs2 != 0) {
Factorial1 = Factorial1 * vs2;
vs2--;
}
if (vn == 0) {
Factorial2 = 1;
vn++;
}
while (vn <= vs4) {
Factorial2 = Factorial2 * vn;
resultadoDiv1 = (double) vlanda / vmu;
resultadoExpo1 = Math.pow(resultadoDiv1, vn);
resultadoDiv3 = resultadoExpo1 / Factorial2;
resultadoDiv2 = (double) vlanda / vmu;
resultadoExpo2 = Math.pow(resultadoDiv2, vs);
resultadoDiv4 = resultadoExpo2 / Factorial1;
resultadoSuma = resultadoDiv3 + resultadoDiv4;
resultadoSuma2 = resultadoSuma2 + resultadoSuma;
vn++;
}
resultadoSuma3 = resultadoSuma2 + (1 / (1 - vp));
resultadoFinal = 1 / resultadoSuma3;
DecimalFormat formato = new DecimalFormat("#.###");
JOptionPane.showMessageDialog(null, "El resultado de la formula es: " + formato.format(resultadoFinal));
// System.out.println("factorial de n" + Factorial2);
}
}else
JOptionPane.showMessageDialog(null, "valores nulos");
}
if (datos.equals(F3B)) {
{
String landa = (String) JOptionPane.showInputDialog(null, "Ingrese valor de λ", "MODELO B ", WIDTH, iF3B, null, "");
String mu = (String) JOptionPane.showInputDialog(null, "Ingrese valor de μ", "MODELO B ", WIDTH, iF3B, null, "");
String n = (String) JOptionPane.showInputDialog(null, "Ingrese valor de n", "MODELO B ", WIDTH, iF3B, null, "");
String p0 = (String) JOptionPane.showInputDialog(null, "Ingrese valor de P0", "MODELO B ", WIDTH, iF3B, null, "");
if (landa != null && mu != null && n != null && p0 != null) {
if (!landa.isEmpty() && !mu.isEmpty() && !n.isEmpty() && !p0.isEmpty()) {
double vlanda = Double.valueOf(landa);
double vmu = Double.valueOf(mu);
double vp0 = Double.valueOf(p0);
double vn = Double.valueOf(n);
int fact = 1;
for (int i = 1; i <= vn; i++) {
fact = fact * i;
}
double ej3 = (((Math.pow((vlanda / vmu), vn)) / fact) * vp0);
JOptionPane.showMessageDialog(null, "Pobabilidad de que haya n clientes estén en el sistema es de = " + ej3);
}
}else
JOptionPane.showMessageDialog(null, "valores nulos");
}
}
if (datos.equals(F4B)) {
String landa = (String) JOptionPane.showInputDialog(null, "Ingrese valor de λ", "MODELO B ", WIDTH, iF4B, null, "");
String mu = (String) JOptionPane.showInputDialog(null, "Ingrese valor de μ", "MODELO B ", WIDTH, iF4B, null, "");
String p0 = (String) JOptionPane.showInputDialog(null, "Ingrese valor de P0", "MODELO B ", WIDTH, iF4B, null, "");
String s = (String) JOptionPane.showInputDialog(null, "Ingrese valor de s", "MODELO B ", WIDTH, iF4B, null, "");
String p = (String) JOptionPane.showInputDialog(null, "Ingrese valor de p", "MODELO B ", WIDTH, iF4B, null, "");
if (landa != null && mu != null && p0 != null && s != null && p != null) {
if (!landa.isEmpty() && !mu.isEmpty() && !p0.isEmpty() && !s.isEmpty() && !p.isEmpty()) {
double vlanda = Double.valueOf(landa);
double vmu = Double.valueOf(mu);
double vp0 = Double.valueOf(p0);
double vs = Double.valueOf(s);
double vp = Double.valueOf(p);
int fact = 1;
for (int i = 1; i <= vs; i++) {
fact = fact * i;
}
double ej4 = ((vp0 * (Math.pow((vlanda / vmu), vs)) * vp)) / (fact * (Math.pow((1 - vp), 2)));
JOptionPane.showMessageDialog(null, "Número promedio de clientes en la fila de espera = " + ej4);
}
}else
JOptionPane.showMessageDialog(null, "valores nulos");
}
if (datos.equals(F5B)) {
String Lq = (String) JOptionPane.showInputDialog(null, "Ingrese valor de Lq", "MODELO B ", WIDTH, iF5B, null, "");
String landa = (String) JOptionPane.showInputDialog(null, "Ingrese valor de λ", "MODELO B ", WIDTH, iF5B, null, "");
if (Lq != null && landa != null) {
if (!Lq.isEmpty() && !landa.isEmpty()) {
double vLq = Double.valueOf(Lq);
double vlanda = Double.valueOf(landa);
double LLq = vLq / vlanda;
JOptionPane.showMessageDialog(null, "Tiempo promedio de espera en la fila = " + LLq);
}
}else
JOptionPane.showMessageDialog(null, "valores nulos");
}
if (datos.equals(F6B)) {
String Wq = (String) JOptionPane.showInputDialog(null, "Ingrese valor de Wq", "MODELO B ", WIDTH, iF6B, null, "");
String μ = (String) JOptionPane.showInputDialog(null, "Ingrese valor de μ", "MODELO B ", WIDTH, iF6B, null, "");
if (Wq != null && μ != null) {
if (!Wq.isEmpty() && !μ.isEmpty()) {
double vWq = Double.valueOf(Wq);
double vμ = Double.valueOf(μ);
double w = vWq * (1 / vμ);
JOptionPane.showMessageDialog(null, "Tiempo promedio transcurrido en el sistema, incluido el servicio = " + w);
}
}
JOptionPane.showMessageDialog(null, "valores nulos");
}
if (datos.equals(F7B)) {
String landa = (String) JOptionPane.showInputDialog(null, "Ingrese valor de λ", "MODELO B ", WIDTH, iF7B, null, "");
String aW = (String) JOptionPane.showInputDialog(null, "Ingrese valor de W", "MODELO B ", WIDTH, iF7B, null, "");
if (landa != null && aW != null) {
if (!landa.isEmpty() && !aW.isEmpty()) {
double vλ = Double.valueOf(landa);
double vw = Double.valueOf(aW);
double w = vλ * vw;
JOptionPane.showMessageDialog(null, "Tiempo promedio de clientes en el sistema de servicio = " + w);
}
}else
JOptionPane.showMessageDialog(null, "valores nulos");
}
}//GEN-LAST:event_jComboBox1ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
Principal p = new Principal();
p.setVisible(true);
dispose();
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ModeloB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ModeloB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ModeloB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ModeloB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ModeloB().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
|
package com.lmx.jredis.core;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.net.HostAndPort;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.SerializationUtil;
import redis.clients.jedis.Jedis;
import redis.netty4.Command;
import redis.netty4.ErrorReply;
import redis.netty4.Reply;
import redis.util.BytesKey;
import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @author : lucas
* @Description: redis 调用器
* @date Date : 2019/01/01 16:03
*/
@Slf4j
@Component
public class RedisCommandInvoker {
private static final byte LOWER_DIFF = 'a' - 'A';
private RedisCommandProcessor rs;
private static final Map<BytesKey, Wrapper> methods = new ConcurrentHashMap<>();
private LinkedBlockingQueue<Command> repQueue = new LinkedBlockingQueue<>(2 << 16);
@Value("${replication.mode:master}")
private String replicationMode;
private List<Jedis> slaverHostList = Lists.newArrayList();
@Value("${slaver.of:127.0.0.1:16379}")
private String slaverOf;
@Autowired
private PubSubHelper pubSubHelper;
public static final String repKey = "replication";
private boolean isInitSubscriber;
private Thread asyncTask = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
Command command = null;
try {
command = repQueue.take();
byte[] data = SerializationUtil.serialize(command);
ByteBuf byteBuf = Unpooled.buffer(4 + data.length);
byteBuf.writeInt(data.length);
byteBuf.writeBytes(data);
publish(byteBuf);
} catch (Exception e) {
log.error("", e);
try {
Thread.sleep(5000L);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (command != null) {
repQueue.offer(command);
}
}
}
}
});
private Thread syncTask = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000L);
System.err.println(String.format("sync data start"));
//connect to master
HostAndPort master = HostAndPort.fromString(slaverOf);
Jedis jedis = new Jedis(master.getHostText(), master.getPort(), 60 * 1000, 60 * 1000);
//send slaveof cmd
String resp = jedis.slaveof(System.getProperty("server.host"), Integer.parseInt(System.getProperty("server.port")));
System.err.println(String.format("sync data end,state=%s", resp));
jedis.close();
} catch (Exception e) {
log.error("", e);
}
}
});
@PostConstruct
public void initThread() {
if (replicationMode.equals("master")) {
asyncTask.setName("asyncReplicationTask");
asyncTask.start();
} else {
syncTask.setName("syncReplicationTask");
syncTask.start();
}
}
public interface Wrapper {
Reply execute(Command command, ChannelHandlerContext ch) throws RedisException;
}
public void init(RedisCommandProcessor rss) {
this.rs = rss;
final Class<? extends RedisCommandProcessor> aClass = rs.getClass();
for (final Method method : aClass.getMethods()) {
final Class<?>[] parameterTypes = method.getParameterTypes();
final String mName = method.getName();
methods.put(new BytesKey(mName.getBytes()), new Wrapper() {
@Override
public Reply execute(Command command, ChannelHandlerContext ch) {
Object[] objects = new Object[parameterTypes.length];
long start = System.currentTimeMillis();
try {
command.toArguments(objects, parameterTypes);
//check param length
if (command.getObjects().length - 1 < parameterTypes.length) {
throw new RedisException("wrong number of arguments for '" + mName + "' command");
}
rs.setChannelHandlerContext(ch);
if (ch != null && rs.hasOpenTx() && command.isInternal()) {
return rs.handlerTxOp(command);
} else {
replication(mName, ch, command);
return (Reply) method.invoke(rs, objects);
}
} catch (Exception e) {
log.error("", e);
if (e instanceof InvocationTargetException)
return new ErrorReply("ERR " + ((InvocationTargetException) e).getTargetException().getMessage());
else
return new ErrorReply("ERR " + e.getMessage());
} finally {
log.info("method {},cost {}ms", method.getName(), (System.currentTimeMillis() - start));
}
}
});
}
}
public Reply handlerEvent(ChannelHandlerContext ctx, Command msg) throws RedisException {
byte[] name = msg.getName();
for (int i = 0; i < name.length; i++) {
byte b = name[i];
if (b >= 'A' && b <= 'Z') {
name[i] = (byte) (b + LOWER_DIFF);
}
}
Wrapper wrapper = methods.get(new BytesKey(name));
Reply reply;
if (wrapper == null) {
reply = new ErrorReply("unknown command '" + new String(name, Charsets.US_ASCII) + "'");
//if started tx,then invoker discard method and setErrorMsg
if (rs.hasOpenTx()) {
rs.discard();
rs.setTXError();
}
} else {
reply = wrapper.execute(msg, ctx);
}
return reply;
}
boolean isWriteCMD(String cmd) {
return cmd.matches("set|lpush|rpush|expire|hset|select");
}
void replication(String mName, ChannelHandlerContext ch, Command command) {
if (replicationMode.equals("master")) {
if (isWriteCMD(mName)) {
repQueue.offer(command);
}
} else {
if (mName.equals("publish") && !isInitSubscriber) {
System.err.println("register subscriber ok");
pubSubHelper.regSubscriber(ch, repKey.getBytes());
isInitSubscriber = true;
}
}
}
public void startAsyncReplication(String slaverHost) {
HostAndPort hostAndPort = HostAndPort.fromString(slaverHost);
Jedis jedis = new Jedis(hostAndPort.getHostText(), hostAndPort.getPort(), 60 * 1000, 60 * 1000);
jedis.ping();
slaverHostList.add(jedis);
}
public void publish(ByteBuf byteBuf) {
for (int i = 0; i < slaverHostList.size(); i++) {
Jedis jedis = slaverHostList.get(i);
try {
jedis.publish(repKey.getBytes(), byteBuf.array());
} catch (Exception e) {
log.error("", e);
slaverHostList.remove(jedis);
}
}
}
}
|
//вывести матрицу того же размера,
// где каждый элемент в положении , (i, j)равен сумме элементов первой матрицы
// на позициях (i-1, j)(i+1, j)(i, j-1), (i, j+1)
//для квадратной матрицы
package Array;
import java.util.ArrayList;
import java.util.Scanner;
public class array_22 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = "0";
int aInt = 0;
double num = 0;
ArrayList<Integer> arrayList = new ArrayList<>();
while(!"end".equals(a)){
a = scanner.next();
if(a.matches("-*[0-9]+")){
aInt = Integer.parseInt(a);
arrayList.add(aInt);
}
num++;
//System.out.print(a + " ");
}
double n = Math.sqrt(num - 1);
int m = (int)n;
//System.out.println(num);
//System.out.println(n);
int [][] arr = new int [m][m];
int k = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < m; j++){
arr[i][j] = arrayList.get(k);
k++;
//System.out.print(arr[i][j] + " ");
}
//System.out.println();
}
int [][] arr2 = new int [m][m];
for(int i = 0; i < m; i++){
for(int j = 0; j < m; j++){
if(m == 1){
arr2[i][j] = arr[i][j] * 4;
}
else {
if (j == 0) {
if (i == 0) {
arr2[i][j] = arr[m - 1][j] + arr[i + 1][j] + arr[i][m - 1] + arr[i][j + 1];
} else {
if (i == m - 1) {
arr2[i][j] = arr[i - 1][j] + arr[0][j] + arr[i][m - 1] + arr[i][j + 1];
} else {
arr2[i][j] = arr[i - 1][j] + arr[i + 1][j] + arr[i][m - 1] + arr[i][j + 1];
}
}
} else {
if (j == m - 1) {
if (i == 0) {
arr2[i][j] = arr[m - 1][j] + arr[i + 1][j] + arr[i][j - 1] + arr[i][0];
} else {
if (i == m - 1) {
arr2[i][j] = arr[i - 1][j] + arr[0][j] + arr[i][j - 1] + arr[i][0];
} else {
arr2[i][j] = arr[i - 1][j] + arr[i + 1][j] + arr[i][j - 1] + arr[i][0];
}
}
} else {
if (i == 0) {
arr2[i][j] = arr[m - 1][j] + arr[i + 1][j] + arr[i][j - 1] + arr[i][j + 1];
} else {
if (i == m - 1) {
arr2[i][j] = arr[i - 1][j] + arr[0][j] + arr[i][j - 1] + arr[i][j + 1];
} else {
arr2[i][j] = arr[i - 1][j] + arr[i + 1][j] + arr[i][j - 1] + arr[i][j + 1];
}
}
}
}
}
System.out.print(arr2[i][j] + " ");
}
System.out.println();
}
}
}
|
public class ComboDriver
{
public static void main(String[] args)
{
Combination lock = new Combination(4, 6, 5, 2);
System.out.println("Trying to open with wrong combo: ");
System.out.println(lock.open(4, 6, 5, 1));
System.out.println("Trying to open with right combo: ");
System.out.println(lock.open(4,6,5,2));
System.out.println("changing lock.. ");
System.out.println(lock.changeCombo(1, 2, 3, 4));
System.out.println("Opening new lock with wrong combo");
System.out.println(lock.open(4,6,5,2));
System.out.println("Trying to open with right combo: ");
System.out.println(lock.open(1, 2, 3, 4));
}
} |
package com.zevzikovas.aivaras.terraria.activities.descriptions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import com.zevzikovas.aivaras.terraria.R;
import com.zevzikovas.aivaras.terraria.models.Yoyos;
import com.zevzikovas.aivaras.terraria.repositories.RepositoryManager;
public class YoyosDescriptionActivity extends Activity {
RepositoryManager repositoryManager = new RepositoryManager(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yoyos_description);
Intent i = getIntent();
Yoyos yoyos = repositoryManager.YoyosRepository.getYoyo(i.getIntExtra("yoyosId", 0));
TextView yoyosDamage = findViewById(R.id.yoyosDamage);
TextView yoyosKnockback = findViewById(R.id.yoyosKnockback);
TextView yoyosCritical_chance = findViewById(R.id.yoyosCritical_chance);
TextView yoyosUse_time = findViewById(R.id.yoyosUse_time);
TextView yoyosVelocity = findViewById(R.id.yoyosVelocity);
TextView yoyosGrants_buff = findViewById(R.id.yoyosGrants_buff);
TextView yoyosInflicts_debuff = findViewById(R.id.yoyosInflicts_debuff);
TextView yoyosRarity = findViewById(R.id.yoyosRarity);
TextView yoyosBuy_price = findViewById(R.id.yoyosBuy_price);
TextView yoyosSell_price = findViewById(R.id.yoyosSell_price);
yoyosDamage.setText(Integer.toString(yoyos.damage));
yoyosKnockback.setText((yoyos.knockback));
yoyosCritical_chance.setText((yoyos.critical_chance));
yoyosUse_time.setText((yoyos.use_time));
yoyosVelocity.setText((yoyos.velocity));
yoyosGrants_buff.setText((yoyos.grants_buff));
yoyosInflicts_debuff.setText((yoyos.inflicts_debuff));
yoyosRarity.setText((yoyos.rarity));
yoyosBuy_price.setText((yoyos.buy_price));
yoyosSell_price.setText((yoyos.sell_price));
}
} |
package com.bicjo.sample.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class FooController {
private final Logger LOG = LoggerFactory.getLogger(getClass());
@GetMapping(value = "/login")
public String login() {
LOG.debug(">>> foo-login <<<");
return "foo/login";
}
} |
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class Main {
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static boolean isOK (String query) {
boolean OK = true;
for (int i = 1; i < query.length() && OK; i++) {
if (Math.abs(query.charAt(i) - query.charAt(i - 1)) == 1) OK = false;
}
return OK;
}
static void solve (String query) {
if (isOK(query)) {
out.println(query);
} else {
char[] querryArray = query.toCharArray();
ArrayList<Character> even = new ArrayList<>();
ArrayList<Character> odd = new ArrayList<>();
for (int i = 0; i < querryArray.length; i++) {
if (querryArray[i] % 2 == 0) even.add(querryArray[i]);
else odd.add(querryArray[i]);
}
Collections.sort(even);
Collections.sort(odd);
if (Math.abs(even.get(0) - odd.get(odd.size() - 1)) != 1) {
odd.addAll(even);
out.println(getStringRepresentation(odd));
} else if (Math.abs(odd.get(0) - even.get(even.size() - 1)) != 1) {
even.addAll(odd);
out.println(getStringRepresentation(even));
}
else out.println("No answer");
}
}
public static void main(String[] args) {
int T = in.nextInt();
for (int i = 0; i < T; i++) {
solve(in.next());
}
out.close();
}
static String getStringRepresentation(ArrayList<Character> list)
{
StringBuilder builder = new StringBuilder(list.size());
for(Character ch: list)
{
builder.append(ch);
}
return builder.toString();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong () {
return Long.parseLong(next());
}
public char nextChar () {
return next().charAt(0);
}
}
} |
/*接口也支持泛型*/
package dao;
import charactor.Hero;
public interface Stack<T> { //自定义一个栈接口,先进后出
public void push(T t); //把英雄推入到最后位置
public T pull(); //把最后一个英雄取出来
public T peek(); //查看最后一个英雄
}
|
package pl.basistam.zad3.books;
import pl.basistam.Book;
import pl.basistam.XmlBuilder;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class XmlBuilderImpl implements XmlBuilder {
public void save(Book newBook) {
try {
BookXml bookXml = BookXml.fromBook(newBook);
System.out.println("Zapisuje");
JAXBContext context = JAXBContext.newInstance(Books.class);
final File outputFile = new File("books.xml");
Unmarshaller um = context.createUnmarshaller();
if (!outputFile.exists()) {
try {
outputFile.createNewFile();
initFile(outputFile);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
Books books = (Books) um.unmarshal(outputFile);
List<BookXml> bookList = books.getBooks();
if (bookList == null) bookList = new ArrayList<>();
bookList.add(bookXml);
books.setBooks(bookList);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(books, outputFile);
} catch (JAXBException e) {
e.printStackTrace();
}
}
private void initFile(File file) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.write("<books>\n");
writer.write("</books>");
writer.close();
}
}
|
package com.gamzat;
public class Main {
public static void main(String[] args) {
int Homer = 40;
//++Homer;
Homer /= 2;
System.out.println(Homer);
}
}
|
package com.meehoo.biz.mobile.controller.basic;
import com.meehoo.biz.common.util.BaseUtil;
import com.meehoo.biz.common.util.MD5Encrypt;
import com.meehoo.biz.common.util.StringUtil;
import com.meehoo.biz.core.basic.dao.security.IUserOrganizationDao;
import com.meehoo.biz.core.basic.domain.security.Admin;
import com.meehoo.biz.core.basic.domain.security.Role;
import com.meehoo.biz.core.basic.domain.security.User;
import com.meehoo.biz.core.basic.domain.security.UserOrganization;
import com.meehoo.biz.core.basic.handler.UserManager;
import com.meehoo.biz.core.basic.param.HttpResult;
import com.meehoo.biz.core.basic.param.PageResult;
import com.meehoo.biz.core.basic.ro.IdRO;
import com.meehoo.biz.core.basic.ro.bos.PageRO;
import com.meehoo.biz.core.basic.ro.bos.SearchConditionListRO;
import com.meehoo.biz.core.basic.ro.security.*;
import com.meehoo.biz.core.basic.service.security.IAdminService;
import com.meehoo.biz.core.basic.service.security.IOrganizationService;
import com.meehoo.biz.core.basic.service.security.IUserService;
import com.meehoo.biz.core.basic.util.UserContextUtil;
import com.meehoo.biz.core.basic.vo.security.OrganizationWithUserVO;
import com.meehoo.biz.core.basic.vo.security.RoleVO;
import com.meehoo.biz.core.basic.vo.security.UserOrganizationVO;
import com.meehoo.biz.core.basic.vo.security.UserVO;
import com.meehoo.biz.mobile.handler.FileUtil;
import com.meehoo.biz.mobile.param.TokenRO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
/**
* 用户管理
* Created by CZ on 2017/10/20.
*/
@Api(tags = "用户管理")
@RestController
@RequestMapping("/security/user")
public class UserController {
private final IUserService userService;
private final IUserOrganizationDao userOrganizationDao;
private final IAdminService adminService;
private final IOrganizationService organizationService;
@Autowired
public UserController(IUserService userService,IUserOrganizationDao userOrganizationDao,IAdminService adminService,IOrganizationService organizationService) {
super();
this.userService = userService;
this.userOrganizationDao = userOrganizationDao;
this.adminService = adminService;
this.organizationService = organizationService;
}
@ApiOperation("获得当前登录用户")
@PostMapping("getCurrentUser")
public HttpResult<UserVO> getCurrentUser(@RequestBody TokenRO ro) throws Exception{
User user = UserManager.getCurrentUser();
return HttpResult.success(new UserVO(user));
}
@ApiOperation("查询人员,并按机构分类")
@PostMapping("getListByOrg")
public HttpResult<Map<String,List<OrganizationWithUserVO>>> getListByOrg() throws Exception {
return HttpResult.success(userService.classifyByOrganization());
}
@RequestMapping(value = "getCurrLoginUser", method = RequestMethod.POST)
public HttpResult<UserVO> getCurrLoginUser(@RequestBody AuthenticationRO authenticationRO) throws Exception {
// ControllerMessage controllerMessage = new ControllerMessage();
User user = (User) SecurityUtils.getSubject().getPrincipal();
UserVO userVO = new UserVO(user);
// controllerMessage.setData(user == null ? "" : new UserVO(user));
// 查询所属机构的子机构
// List<OrganizationVO> subOrgList = organizationService.getSubOrgList(user.getOrgId());
// Organization organization = organizationService.queryById(user.getOrgId());
// subOrgList.add(new OrganizationVO(organization));
// UserVO userVO = new UserVO(user);
// userVO.setOrganizationVOList(subOrgList);
return HttpResult.success(userVO);
}
/**
* 新建用户信息
*
* @param userRO
* @return
* @throws Exception
*/
@RequestMapping(value = "create", method = RequestMethod.POST)
public HttpResult<String> create(@RequestBody UserRO userRO) throws Exception {
return HttpResult.success(userService.createSaveUser(userRO));
}
/**
* 新建/修改用户信息
*
* @param userRO
* @return
* @throws Exception
*/
@RequestMapping(value = "update", method = RequestMethod.POST)
public HttpResult<String> update(@RequestBody UserRO userRO) throws Exception {
String msg = userService.updateSaveUser(userRO);
return HttpResult.success(msg);
}
@RequestMapping(value = "saveOrgAndRole", method = RequestMethod.POST)
public HttpResult saveOrgAndRole(@RequestBody OrganizationRoleRO organizationRoleRO) throws Exception {
// if (controllerMessage.isNotSuccessMsg()){
// return controllerMessage.toMap();
// }
User user = userService.queryById(User.class, organizationRoleRO.getUserId());
Role role = userService.queryById(Role.class, organizationRoleRO.getRoleIdList().get(0));
user.setRoleId(role.getId());
user.setRoleName(role.getName());
userService.update(user);
// userService.saveOrganizationRoleLink(organizationRoleRO);
return HttpResult.success();
}
/**
* 查询用户所属的机构列表
*
* @param idRO
* @return
* @throws Exception
*/
@RequestMapping(value = "getUserOrgList", method = RequestMethod.POST)
public HttpResult<UserVO> getUserOrgList(@RequestBody IdRO idRO) throws Exception {
if (StringUtil.stringIsNull(idRO.getId())) {
throw new RuntimeException("用户id不能为空");
}
UserVO userOrgList = userService.getUserOrgList(idRO.getId());
return HttpResult.success(userOrgList);
}
/**
* 查询用户所属的机构及其对应的角色
*
* @param idRO
* @return
* @throws Exception
*/
@RequestMapping(value = "getUserOrgAndRoleList", method = RequestMethod.POST)
public HttpResult< List<UserOrganizationVO>> getUserOrgAndRoleList(@RequestBody IdRO idRO) throws Exception {
if (StringUtil.stringIsNull(idRO.getId())) {
throw new RuntimeException("用户id不能为空");
}
List<UserOrganizationVO> userOrgAndRoleList = userService.getUserOrgAndRoleList(idRO.getId());
return HttpResult.success(userOrgAndRoleList);
}
// @RequestMapping(value = "list", method = RequestMethod.POST)
// public HttpResult<PageResult<UserVO>> list(@RequestBody PageRO pagePO) throws Exception {
// PageResult<UserVO> userVOPageResult = userService.listPage(pagePO);
// return HttpResult.success(userVOPageResult);
// }
@PostMapping("listAll")
public HttpResult<List<UserVO>> listAll(@RequestBody SearchConditionListRO searchConditionListRO) throws Exception {
List<UserVO> userVOS = userService.listAll(searchConditionListRO);
return HttpResult.success(userVOS);
}
@RequestMapping(value = "getById", method = RequestMethod.POST)
public HttpResult<UserVO> getById(@RequestBody IdRO idRO) throws Exception {
if (StringUtil.stringIsNull(idRO.getId())) {
throw new RuntimeException("请选择要查询的用户");
}
UserVO userVO = userService.getById(idRO.getId());
return HttpResult.success(userVO);
}
/**
* 查询用户在某个机构里拥有的角色
*
* @param userOrganizationRO
* @return
* @throws Exception
*/
@RequestMapping(value = "getUserHasRoleList", method = RequestMethod.POST)
public HttpResult<List<RoleVO>> getUserHasRoleList(@RequestBody UserOrganizationRO userOrganizationRO) throws Exception {
List<RoleVO> userHasRoleList = userService.getUserHasRoleList(userOrganizationRO.getUserId(), userOrganizationRO.getOrganizationId());
return HttpResult.success(userHasRoleList);
}
/**
* 重置密码
*/
@PostMapping("resetPassword")
public HttpResult<String> resetPassword(@RequestBody IdRO idPO) throws Exception {
User user = userService.queryById(User.class, idPO.getId());
if (BaseUtil.objectNotNull(user)) {
user.setPassword(MD5Encrypt.EncryptPassword("123456"));
userService.update(user);
return HttpResult.success("操作成功,密码已被重置为123456");
} else {
throw new RuntimeException("未查询到当前用户");
}
}
/**
* 修改密码
*
* @param modifyPasswordRO
* @return
*/
@PostMapping(value = "modifyPassword")
public HttpResult<String> modifyPassword(ModifyPasswordRO modifyPasswordRO) throws Exception{
User user = userService.queryById(User.class, modifyPasswordRO.getId());
if (MD5Encrypt.CheckEncryptPassword(modifyPasswordRO.getOldPw(), user.getPassword())) {
// 密码正确,修改密码
return judgeUser(user, modifyPasswordRO.getNewPw(), modifyPasswordRO.getConfirmNewPw());
}else{
// 密码错误,提示
throw new RuntimeException("原密码错误!");
}
}
private HttpResult<String> judgeUser(User user, String password, String confirmPassword)throws Exception{
if(password.equals(confirmPassword)){
user.setPassword(password);
userService.update(user);
return HttpResult.success("修改成功");
}else{
throw new RuntimeException("两次密码必须一致");
}
}
private HttpResult<String> judgeAdmin(Admin admin, String password, String confirmPassword)throws Exception{
if(password.equals(confirmPassword)){
admin.setPassword(MD5Encrypt.EncryptPassword(password));
adminService.update(admin);
return HttpResult.success("修改成功");
}else{
throw new RuntimeException("两次密码必须一致");
}
}
// @ApiOperation("检查用户名是否重复")
// @PostMapping("checkUserName")
// public HttpResult<String> checkUserName(@RequestBody NameRO nameRO) throws Exception {
// String userName = nameRO.getName();
// if (BaseUtil.stringNotNull(userName)) {
// User user = userService.getUserByName(userName);
// if (user == null) {
// return HttpResult.success("用户名可用");
// } else {
// throw new RuntimeException("用户名已被使用");
// }
// } else {
// throw new RuntimeException("用户名不能为空");
// }
// }
public HttpResult delete(@RequestBody IdRO idRO) throws Exception {
// 先删除与机构的中间表数据
List<UserOrganization> userOrganizationList = userOrganizationDao.findByUserId(idRO.getId());
if (userOrganizationList.size()>0)
userService.batchDelete(userOrganizationList);
userService.delete(idRO);
return HttpResult.success();
}
@RequestMapping(value = "uploadIcon",method = RequestMethod.POST)
@ApiOperation("上传头像")
public HttpResult<String> uploadIcon(MultipartFile fileUpload, String empNo) throws Exception{
User employee = userService.getUserByNumber(empNo);
String url = FileUtil.uploadFile(fileUpload);
employee.setHeadImgUrl(url);
userService.update(employee);
return HttpResult.success(url);
}
}
|
package edu.neu.ccs.cs5010;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.sun.tools.doclets.internal.toolkit.util.DocPath.parent;
public abstract class CandyTree<T> {
private Node<T> root;
public CandyTree(T rootData) {
root = new Node<T>();
root.data = rootData;
root.children = new ArrayList<Node<T>>();
}
public void inputchild(Node child, Node parent){
}
public static class Node<T> {
private T data;
private Node<T> parent;
protected List<Node<T>> children;
}
/*Node neignborhood = new Node<String>();
{
neignborhood.children.add(new Mansion());
neignborhood.children.add(new DetachedHouse());
neignborhood.children.add(new Duplexe());
neignborhood.children.add(new TownHome());
for(Node housenode :neignborhood.children){
}
}
*/
}
|
package com.parkinglot.demo.core.test;
import com.parkinglot.demo.core.domain.ParkingLot;
import com.parkinglot.demo.core.ParkingLotFactory;
import com.parkinglot.demo.core.domain.parking.Parking;
import com.parkinglot.demo.core.domain.vehicle.Vehicle;
import com.parkinglot.demo.core.domain.vehicle.VehicleType;
import com.parkinglot.demo.core.exception.NoParkingSpotException;
import com.parkinglot.demo.core.exception.TicketNotPaidException;
import org.junit.Assert;
import org.junit.Test;
import java.time.LocalDateTime;
public class ParkingLotTest {
@Test
public void factoryCanBuildParkingLot() {
ParkingLot parkingLot = ParkingLotFactory.build(5);
Assert.assertNotNull(parkingLot);
}
@Test
public void canParkCars() throws NoParkingSpotException {
ParkingLot parkingLot = ParkingLotFactory.build(5);
Vehicle vehicle = new Vehicle();
vehicle.setVehicleType(VehicleType.van);
Parking parking = parkingLot.enter(vehicle, LocalDateTime.now());
Assert.assertNotNull(parking);
Assert.assertNotNull(parking.getTicket());
}
@Test(expected = NoParkingSpotException.class)
public void parkingHasLimit() throws NoParkingSpotException {
ParkingLot parkingLot = ParkingLotFactory.build(1);
int carNums = 1000;
while (carNums-- > 0) {
Vehicle vehicle = new Vehicle();
vehicle.setVehicleType(VehicleType.van);
parkingLot.enter(vehicle, LocalDateTime.now());
}
}
@Test(expected = TicketNotPaidException.class)
public void cannotExitUnlessPaid() throws NoParkingSpotException, TicketNotPaidException {
ParkingLot parkingLot = ParkingLotFactory.build(5);
Vehicle vehicle = new Vehicle();
vehicle.setVehicleType(VehicleType.van);
Parking parking = parkingLot.enter(vehicle, LocalDateTime.now());
Vehicle car = parkingLot.exit(parking, LocalDateTime.now().plusHours(3));
}
}
|
package pro.likada.dao.daoImpl;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pro.likada.dao.DocumentDAO;
import pro.likada.model.Document;
import pro.likada.util.HibernateUtil;
import javax.inject.Named;
import javax.transaction.Transactional;
import java.util.List;
/**
* Created by bumur on 29.01.2017.
*/
@SuppressWarnings("unchecked")
@Named("documentDAO")
@Transactional
public class DocumentDAOImpl implements DocumentDAO{
private static final Logger LOGGER = LoggerFactory.getLogger(DocumentDAOImpl.class);
@Override
public Document findById(long id) {
LOGGER.info("Get Document with an ID: {}", id);
Session session = HibernateUtil.getSessionFactory().openSession();
Document document = (Document) session.createCriteria(Document.class).add(Restrictions.idEq(id)).uniqueResult();
session.close();
return document;
}
@Override
public List<Document> getAllDocuments() {
LOGGER.info("Get All Documents");
Session session = HibernateUtil.getSessionFactory().openSession();
List<Document> documents = (List<Document>) session.createCriteria(Document.class).list();
session.close();
return documents;
}
@Override
public void save(Document document) {
LOGGER.info("Saving a new Document: {}", document);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(document);
transaction.commit();
session.flush();
session.close();
}
@Override
public void deleteById(long id) {
LOGGER.info("Delete Document with an id:" + id);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.delete(findById(id));
transaction.commit();
session.flush();
session.close();
}
@Override
public List<Document> findByParentTypeId(Long id, String parentType) {
LOGGER.info("Get Document with Parent Type id: {}", id);
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Document.class);
criteria.add(Restrictions.and(Restrictions.eq("parent_id",id),Restrictions.eq("parent_type",parentType)));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List<Document> documents = (List<Document>) criteria.list();
session.close();
return documents;
}
}
|
/**
*
*/
package com.imooc.security.config;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import com.imooc.security.order.OrderInfo;
/**
* @author jojo
*
*/
public class Test {
/**
*
* @author jojo
* 2019年10月7日
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.set("Authorization", "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzIwNzcwMTMsInVzZXJfbmFtZSI6Impvam8iLCJhdXRob3JpdGllcyI6WyJST0xFX0FETUlOIl0sImp0aSI6ImQyNjU0OGY3LWViYjUtNDk3My1iZWY3LTQwMTBjOWNiMGJhZCIsImNsaWVudF9pZCI6ImFkbWluIiwic2NvcGUiOlsicmVhZCIsIndyaXRlIl19.Svx3Z6ev-YuNkgku8yLdAhnT9ZhoKCjleIlgyBz_2j5j27f4c5wOMJcTl23PR3y77GUH3vWKj8j0tiohyBZT1m6CCUYL00CCkZ0u1po0sJtz7CxwWxkmsq7qq5IfXDgHVHur11kj-CLlKb_9wWTnWUvxPnDqByyjmpzEeT13Cgm0UJzkoV3bHe2f6JG5ktyqBi-5siUAF48V3Vuqxlcf_3KcqDsUtpmGSjHJS6_x1wbFixdewE6unOA06CL9lP2byktZz7xd_9xZtWcY3WK5N8kFbUa0NnD3dPB19AAoSuRfVw-Y_EqrxNDIG15GPtOmjOFs97al54Kz2Eqh6S86jQ");
OrderInfo info = new OrderInfo();
info.setProductId(123L);
HttpEntity<OrderInfo> entity = new HttpEntity<OrderInfo>(info, headers);
while (true) {
try {
restTemplate.exchange("http://order.imooc.com:9082/orders", HttpMethod.POST, entity, String.class);
} catch (Exception e) {
}
// Thread.sleep(100);
}
}
}
|
/*
* 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 quicksort;
/**
*
* @author RolfMoikjær
*/
public class QuickSortImpl {
public static void sort(int[] list) {
sort(list, 0, list.length);
}
private static void swap(int[] list, int i, int j) {
int t = list[i];
list[i] = list[j];
list[j] = t;
}
private static void sort(int[] list, int start, int end) {
if (end - start <= 1) {
return;
}
if (end - start == 2) {
if (list[end -1] < list[start]) {
swap(list, start, end -1);
}
return;
}
int pivot = split(list, start, end);
sort(list, start, pivot);
sort(list, pivot + 1, end);
}
private static int split(int[] list, int start, int end) {
int pivot = end - 1;
int value = list[pivot];
while(start < pivot){
while (list[start] < value) {
start++;
}
if(start == pivot){
return pivot;
}
list[pivot] = list[start];
list[start] = list[pivot-1];
list[pivot-1] = value;
pivot--;
}
return pivot;
}
}
|
package info.datacluster.crawler.utils;
public class UrlUtils {
public static String getDomain(String url){
int index = 0;
int protocolLength = 0;
if (url.startsWith("https://")){
protocolLength = "https://".length();
}else if (url.startsWith("http://")){
protocolLength = "https://".length();
}
index = url.substring(protocolLength).indexOf("/");
if (index == -1){
return url;
}
index = protocolLength + index;
return url.substring(0, index);
}
}
|
package com.yc.education.model.check;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
/**
* @ClassName CheckOrderEmployeeProperty
* @Description TODO 申请人
* @Author QuZhangJing
* @Date 2019/2/15 17:50
* @Version 1.0
*/
public class CheckOrderEmployeeProperty {
private SimpleLongProperty id = new SimpleLongProperty();
private SimpleStringProperty emporder = new SimpleStringProperty();
private SimpleStringProperty empname = new SimpleStringProperty();
public CheckOrderEmployeeProperty() {
}
public CheckOrderEmployeeProperty(long id, String emporder, String empname) {
setId(id);
setEmporder(emporder);
setEmpname(empname);
}
public CheckOrderEmployeeProperty( String emporder, String empname) {
setEmporder(emporder);
setEmpname(empname);
}
public long getId() {
return id.get();
}
public SimpleLongProperty idProperty() {
return id;
}
public void setId(long id) {
this.id.set(id);
}
public String getEmporder() {
return emporder.get();
}
public SimpleStringProperty emporderProperty() {
return emporder;
}
public void setEmporder(String emporder) {
this.emporder.set(emporder);
}
public String getEmpname() {
return empname.get();
}
public SimpleStringProperty empnameProperty() {
return empname;
}
public void setEmpname(String empname) {
this.empname.set(empname);
}
}
|
package com.skilldistillery.gamebored.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name= "board_game")
public class Boardgame {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String description;
@Column(name= "min_players")
private int minPlayers;
@Column(name= "max_players")
private Integer maxPlayers;
@Column(name= "play_time_minutes")
private Integer playTimeMinutes;
private Double cost;
@ManyToOne
@JoinColumn(name="genre_id")
private Genre genre;
@ManyToOne
@JoinColumn(name="category_id")
private Category category;
@ManyToOne
@JoinColumn(name="publisher_id")
private Publisher publisher;
@Column(name= "logo_url")
private String logoUrl;
@Column(name= "box_art_url")
private String boxArtUrl;
@OneToMany(mappedBy = "boardgame")
private List<BoardGameComment> boardGameComments;
@ManyToMany(mappedBy= "favorites")
private List<User> userWithFavs;
@ManyToMany(mappedBy= "owned")
private List<User> userWithOwned;
public Boardgame() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getMinPlayers() {
return minPlayers;
}
public void setMinPlayers(int minPlayers) {
this.minPlayers = minPlayers;
}
public Integer getMaxPlayers() {
return maxPlayers;
}
public void setMaxPlayers(Integer maxPlayers) {
this.maxPlayers = maxPlayers;
}
public Integer getPlayTimeMinutes() {
return playTimeMinutes;
}
public void setPlayTimeMinutes(Integer playTimeMinutes) {
this.playTimeMinutes = playTimeMinutes;
}
public Double getCost() {
return cost;
}
public void setCost(Double cost) {
this.cost = cost;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
public String getBoxArtUrl() {
return boxArtUrl;
}
public void setBoxArtUrl(String boxArtUrl) {
this.boxArtUrl = boxArtUrl;
}
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public List<BoardGameComment> getBoardGameComments() {
return boardGameComments;
}
public void setBoardGameComments(List<BoardGameComment> boardGameComments) {
this.boardGameComments = boardGameComments;
}
public List<User> getUserWithFavs() {
return userWithFavs;
}
public void setUserWithFavs(List<User> userWithFavs) {
this.userWithFavs = userWithFavs;
}
public List<User> getUserWithOwned() {
return userWithOwned;
}
public void setUserWithOwned(List<User> userWithOwned) {
this.userWithOwned = userWithOwned;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Boardgame [id=");
builder.append(id);
builder.append(", name=");
builder.append(name);
builder.append(", description=");
builder.append(description);
builder.append(", minPlayers=");
builder.append(minPlayers);
builder.append(", maxPlayers=");
builder.append(maxPlayers);
builder.append(", playTimeMinutes=");
builder.append(playTimeMinutes);
builder.append(", cost=");
builder.append(cost);
builder.append(", logoUrl=");
builder.append(logoUrl);
builder.append(", boxArtUrl=");
builder.append(boxArtUrl);
builder.append("]");
return builder.toString();
}
public void addBoardgameComment(BoardGameComment comment) {
if(boardGameComments == null) boardGameComments = new ArrayList<BoardGameComment>();
if(!boardGameComments.contains(comment)) {
boardGameComments.add(comment);
if(comment.getBoardgame() != null) {
comment.getBoardgame().getBoardGameComments().remove(comment);
}
comment.setBoardgame(this);
}
}
public void removeBoardgameComment(BoardGameComment comment) {
comment.setBoardgame(null);
if(boardGameComments != null) {
boardGameComments.remove(comment);
}
}
public void addUserWithFav(User user) {
if(userWithFavs == null) {userWithFavs = new ArrayList<User>();}
if(!userWithFavs.contains(user)) {
userWithFavs.add(user);
user.addFavorite(this);
}
}
public void removeUserWithFav(User user) {
if(userWithFavs != null && userWithFavs.contains(user)) {
userWithFavs.remove(user);
user.removeFavorite(this);
}
}
public void addUserWithOwned(User user) {
if(userWithOwned == null) {userWithOwned = new ArrayList<User>();}
if(!userWithOwned.contains(user)) {
userWithOwned.add(user);
user.addOwned(this);
}
}
public void removeUserWithOwned(User user) {
if(userWithOwned != null && userWithOwned.contains(user)) {
userWithOwned.remove(user);
user.removeOwned(this);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Boardgame other = (Boardgame) obj;
if (id != other.id)
return false;
return true;
}
}
|
package com.loading.graphqldemo.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import lombok.Data;
import org.hibernate.annotations.Proxy;
/**
* desc:
*
* @author Lo_ading
* @version 1.0.0
* @date 2021/9/14
*/
@Data
@Proxy(lazy = false)
@Entity
public class CompanyEntity {
@Id
private String id;
private String name;
private String partnerCompanyIds;
public CompanyEntity(){
}
public CompanyEntity(String id, String name, String partnerCompanyIds){
this.id = id;
this.name = name;
this.partnerCompanyIds = partnerCompanyIds;
}
}
|
/*
* Copyright (c) 2020.
* Kamalita's coding
*/
package RegularProgramming;
public class InheritenceExample extends Parent implements IParent{
void check(){
System.out.println("child");
}
public static void main(String[] args) {
Parent product=new InheritenceExample();
// Not possible as compile time error
//product.check();
IParent iParent=new InheritenceExample();
//Compile time error
//iParent.testIParent();
}
}
class Parent{
void test(){
System.out.println("parent");
synchronized(this) {
System.out.println("Iparent");
}
}
}
interface IParent{
// Not possible Compile time error
//static void testIParent();
static void testIParent(){
System.out.println("Iparent");
}
}
|
/*
* 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.http.converter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import kotlinx.serialization.KSerializer;
import kotlinx.serialization.SerializationException;
import kotlinx.serialization.StringFormat;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.util.StreamUtils;
/**
* Abstract base class for {@link HttpMessageConverter} implementations that
* defer to Kotlin {@linkplain StringFormat string serializers}.
*
* @author Andreas Ahlenstorf
* @author Sebastien Deleuze
* @author Juergen Hoeller
* @author Iain Henderson
* @author Arjen Poutsma
* @since 6.0
* @param <T> the type of {@link StringFormat}
*/
public abstract class KotlinSerializationStringHttpMessageConverter<T extends StringFormat>
extends AbstractKotlinSerializationHttpMessageConverter<T> {
/**
* Construct an {@code KotlinSerializationStringHttpMessageConverter} with format and supported media types.
*/
protected KotlinSerializationStringHttpMessageConverter(T format, MediaType... supportedMediaTypes) {
super(format, supportedMediaTypes);
}
@Override
protected Object readInternal(KSerializer<Object> serializer, T format, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
Charset charset = charset(inputMessage.getHeaders().getContentType());
String s = StreamUtils.copyToString(inputMessage.getBody(), charset);
try {
return format.decodeFromString(serializer, s);
}
catch (SerializationException ex) {
throw new HttpMessageNotReadableException("Could not read " + format + ": " + ex.getMessage(), ex,
inputMessage);
}
}
@Override
protected void writeInternal(Object object, KSerializer<Object> serializer, T format,
HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
try {
String s = format.encodeToString(serializer, object);
Charset charset = charset(outputMessage.getHeaders().getContentType());
outputMessage.getBody().write(s.getBytes(charset));
outputMessage.getBody().flush();
}
catch (SerializationException ex) {
throw new HttpMessageNotWritableException("Could not write " + format + ": " + ex.getMessage(), ex);
}
}
private static Charset charset(@Nullable MediaType contentType) {
if (contentType != null && contentType.getCharset() != null) {
return contentType.getCharset();
}
return StandardCharsets.UTF_8;
}
}
|
package com.zxt.compplatform.indexgenerate.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.lang.StringUtils;
import com.zxt.compplatform.indexgenerate.dao.PageDao;
import com.zxt.compplatform.indexgenerate.entity.PageUnit;
import com.zxt.compplatform.indexgenerate.service.PageService;
import com.zxt.compplatform.indexgenerate.util.PageXmlUtil;
import com.zxt.framework.common.util.RandomGUID;
public class PageServiceImpl implements PageService {
private PageDao pagedao;
public Map load_Index(String subSystemId) {
// 1. 验证是否存在子系统 不存在返回null
PageUnit unit = pagedao.findById(subSystemId);
String xml =null;
if (unit!=null) {
xml= unit.getPagexml();
}else {
return new HashMap();
}
if (StringUtils.isEmpty(xml))
return new HashMap();
// 2.将查找的xml配置解析成List结果
return PageXmlUtil.xmlToPage(xml);
}
public Map update_Index(String subSystemId) {
PageUnit unit = pagedao.findById(subSystemId);
String xml = unit.getPagexml();
if (xml == null)
return null;
return PageXmlUtil.xmlToPage(xml);
}
public void delete_Index(String subSystemId) {
}
public void add(PageUnit page) {
pagedao.create(page);
}
public void delete(String subSystemId) {
PageUnit pu = new PageUnit();
pu.setId(subSystemId);
pagedao.delete(pu);
}
public void update(String subSystemId, String xmlparam) {
PageUnit pu = pagedao.findById(subSystemId);
if (pu==null) {
pu=new PageUnit();
//pu.setId(RandomGUID.geneGuid());
}
pu.setPagexml(xmlparam);
pagedao.update(pu);
}
public List findAllByIds(String ids) {
return null;
}
public void update(PageUnit pageunit) {
PageUnit pu = pagedao.findById(pageunit.getId());
pu.setName(pageunit.getName());
pu.setDescription(pageunit.getDescription());
pagedao.update(pu);
}
public int findTotalRows() {
return pagedao.findTotal();
}
public List listPage(int page, int rows) {
return pagedao.listPage(page, rows);
}
public String findtemplateurl(String subSystemId) {
PageUnit pu = pagedao.findById(subSystemId);
if (pu != null)
return pu.getDescription();
return null;
}
public PageUnit findById(String subSystemId) {
return pagedao.findById(subSystemId);
}
public String fillDefaultModel(String keyword,int num) {
//查找系统下的模块
List list=pagedao.findmodel(keyword,num);
//生成xml
Map map=new HashMap();
int size=list.size();
if(list!=null&&size>0){
int j=0;
for (int i = 0; i < num; i++) {
//要判断模块数少于要显示的模块数的情况
if(j>=size)
j-=size;
map.put("node"+(i+1), list.get(j));
j++;
}
}
String str = PageXmlUtil.PageToxml(map);
return str;
}
// -------------getter and setter-----------------------\\
public PageDao getPagedao() {
return pagedao;
}
public void setPagedao(PageDao pagedao) {
this.pagedao = pagedao;
}
}
|
package com.demo;
import com.demo.aws.LaunchEc2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RunController {
@Autowired
private LaunchEc2 launchEc2;
@GetMapping("/launch")
private String launch()
{
launchEc2.launch();
return "Scalable EC2 instances launched!";
}
}
|
package servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Excepions.UsersNotFound;
import javafx.util.Pair;
import models.Utente;
import persistence.DatabaseManager;
/**
* Servlet implementation class viewProfile
*/
@WebServlet("/viewProfile")
public class viewProfile extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public viewProfile() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
String first = (String)request.getSession().getAttribute("email");
String second = request.getParameter("email");
Utente u = DatabaseManager.getInstance().getDaoFactory().getUtenteDao().getUtenteforTransaction(second);
request.setAttribute("nomeUs", u.getNome());
request.setAttribute("cognomeUs", u.getCognome());
request.setAttribute("emailUs", second);
String image=DatabaseManager.getInstance().getDaoFactory().getUtenteDao().getImage(second);
Pair<Integer,String> check = DatabaseManager.getInstance().getDaoFactory().getAmiciziaDao().checkRelation(first, second);
request.setAttribute("status",check.getValue());
request.setAttribute("imageUs", image);
request.setAttribute("number", check.getKey());
} catch (UsersNotFound e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestDispatcher rd = request.getRequestDispatcher("user.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package com.ihq.capitalpool.ssoserver.ServiceImpl;
import com.alibaba.fastjson.JSONObject;
import com.ihq.capitalpool.common.RestException;
import com.ihq.capitalpool.common.RestResult;
import com.ihq.capitalpool.common.ResultStatusEnum;
import com.ihq.capitalpool.ssoserver.Service.PasswordTokenService;
import com.ihq.capitalpool.ssoserver.Service.SsoService;
import com.ihq.capitalpool.ssoserver.Service.UserServiceRemote;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class SsoServiceImpl implements SsoService {
@Autowired
private UserServiceRemote userServiceRemote;
@Autowired
private PasswordTokenService passwordTokenService;
@Value("${QH.PublicKey}")
private String qhPublicKey;
@Override
public Map<String, String> generatorToken(String username, String password) {
RestResult restResult = userServiceRemote.selectByUsernamePassword(username, password);
if (restResult.getStatus() != 200) {
throw new RestException(restResult);
}
if (restResult.getData() == null) {
throw new RestException(ResultStatusEnum.PasswordError);
}
HashMap res = restResult.getHashMapData();
HashMap<String, Object> map = new HashMap<>();
map.put("uuid", res.get("uuid"));
map.put("username", res.get("username"));
map.put("name", res.get("name"));
map.put("email", res.get("email"));
map.put("phone", res.get("phone"));
map.put("status", res.get("status"));
return passwordTokenService.generator(String.valueOf(res.get("uuid")), JSONObject.toJSONString(map), qhPublicKey);
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.oxm.support;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.ContentHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.springframework.lang.Nullable;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.oxm.XmlMappingException;
import org.springframework.util.Assert;
import org.springframework.util.xml.StaxUtils;
/**
* Abstract implementation of the {@code Marshaller} and {@code Unmarshaller} interface.
* This implementation inspects the given {@code Source} or {@code Result}, and
* delegates further handling to overridable template methods.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
*/
public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
private static final EntityResolver NO_OP_ENTITY_RESOLVER =
(publicId, systemId) -> new InputSource(new StringReader(""));
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
private boolean supportDtd = false;
private boolean processExternalEntities = false;
@Nullable
private DocumentBuilderFactory documentBuilderFactory;
private final Object documentBuilderFactoryMonitor = new Object();
/**
* Indicate whether DTD parsing should be supported.
* <p>Default is {@code false} meaning that DTD is disabled.
*/
public void setSupportDtd(boolean supportDtd) {
this.supportDtd = supportDtd;
}
/**
* Return whether DTD parsing is supported.
*/
public boolean isSupportDtd() {
return this.supportDtd;
}
/**
* Indicate whether external XML entities are processed when unmarshalling.
* <p>Default is {@code false}, meaning that external entities are not resolved.
* Note that processing of external entities will only be enabled/disabled when the
* {@code Source} passed to {@link #unmarshal(Source)} is a {@link SAXSource} or
* {@link StreamSource}. It has no effect for {@link DOMSource} or {@link StAXSource}
* instances.
* <p><strong>Note:</strong> setting this option to {@code true} also
* automatically sets {@link #setSupportDtd} to {@code true}.
*/
public void setProcessExternalEntities(boolean processExternalEntities) {
this.processExternalEntities = processExternalEntities;
if (processExternalEntities) {
this.supportDtd = true;
}
}
/**
* Return whether XML external entities are allowed.
* @see #createXmlReader()
*/
public boolean isProcessExternalEntities() {
return this.processExternalEntities;
}
/**
* Build a new {@link Document} from this marshaller's {@link DocumentBuilderFactory},
* as a placeholder for a DOM node.
* @see #createDocumentBuilderFactory()
* @see #createDocumentBuilder(DocumentBuilderFactory)
*/
protected Document buildDocument() {
try {
DocumentBuilder documentBuilder;
synchronized (this.documentBuilderFactoryMonitor) {
if (this.documentBuilderFactory == null) {
this.documentBuilderFactory = createDocumentBuilderFactory();
}
documentBuilder = createDocumentBuilder(this.documentBuilderFactory);
}
return documentBuilder.newDocument();
}
catch (ParserConfigurationException ex) {
throw new UnmarshallingFailureException("Could not create document placeholder: " + ex.getMessage(), ex);
}
}
/**
* Create a {@code DocumentBuilder} that this marshaller will use for creating
* DOM documents when passed an empty {@code DOMSource}.
* <p>The resulting {@code DocumentBuilderFactory} is cached, so this method
* will only be called once.
* @return the DocumentBuilderFactory
* @throws ParserConfigurationException if thrown by JAXP methods
*/
protected DocumentBuilderFactory createDocumentBuilderFactory() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
factory.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities());
return factory;
}
/**
* Create a {@code DocumentBuilder} that this marshaller will use for creating
* DOM documents when passed an empty {@code DOMSource}.
* <p>Can be overridden in subclasses, adding further initialization of the builder.
* @param factory the {@code DocumentBuilderFactory} that the DocumentBuilder should be created with
* @return the {@code DocumentBuilder}
* @throws ParserConfigurationException if thrown by JAXP methods
*/
protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory)
throws ParserConfigurationException {
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
if (!isProcessExternalEntities()) {
documentBuilder.setEntityResolver(NO_OP_ENTITY_RESOLVER);
}
return documentBuilder;
}
/**
* Create an {@code XMLReader} that this marshaller will when passed an empty {@code SAXSource}.
* @return the XMLReader
* @throws SAXException if thrown by JAXP methods
* @throws ParserConfigurationException if thrown by JAXP methods
*/
protected XMLReader createXmlReader() throws SAXException, ParserConfigurationException {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true);
saxParserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
saxParserFactory.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities());
SAXParser saxParser = saxParserFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
if (!isProcessExternalEntities()) {
xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
}
return xmlReader;
}
/**
* Determine the default encoding to use for marshalling or unmarshalling from
* a byte stream, or {@code null} if none.
* <p>The default implementation returns {@code null}.
*/
@Nullable
protected String getDefaultEncoding() {
return null;
}
// Marshalling
/**
* Marshals the object graph with the given root into the provided {@code javax.xml.transform.Result}.
* <p>This implementation inspects the given result, and calls {@code marshalDomResult},
* {@code marshalSaxResult}, or {@code marshalStreamResult}.
* @param graph the root of the object graph to marshal
* @param result the result to marshal to
* @throws IOException if an I/O exception occurs
* @throws XmlMappingException if the given object cannot be marshalled to the result
* @throws IllegalArgumentException if {@code result} if neither a {@code DOMResult},
* a {@code SAXResult}, nor a {@code StreamResult}
* @see #marshalDomResult(Object, javax.xml.transform.dom.DOMResult)
* @see #marshalSaxResult(Object, javax.xml.transform.sax.SAXResult)
* @see #marshalStreamResult(Object, javax.xml.transform.stream.StreamResult)
*/
@Override
public final void marshal(Object graph, Result result) throws IOException, XmlMappingException {
if (result instanceof DOMResult domResult) {
marshalDomResult(graph, domResult);
}
else if (StaxUtils.isStaxResult(result)) {
marshalStaxResult(graph, result);
}
else if (result instanceof SAXResult saxResult) {
marshalSaxResult(graph, saxResult);
}
else if (result instanceof StreamResult streamResult) {
marshalStreamResult(graph, streamResult);
}
else {
throw new IllegalArgumentException("Unknown Result type: " + result.getClass());
}
}
/**
* Template method for handling {@code DOMResult}s.
* <p>This implementation delegates to {@code marshalDomNode}.
* @param graph the root of the object graph to marshal
* @param domResult the {@code DOMResult}
* @throws XmlMappingException if the given object cannot be marshalled to the result
* @throws IllegalArgumentException if the {@code domResult} is empty
* @see #marshalDomNode(Object, org.w3c.dom.Node)
*/
protected void marshalDomResult(Object graph, DOMResult domResult) throws XmlMappingException {
if (domResult.getNode() == null) {
domResult.setNode(buildDocument());
}
marshalDomNode(graph, domResult.getNode());
}
/**
* Template method for handling {@code StaxResult}s.
* <p>This implementation delegates to {@code marshalXMLSteamWriter} or
* {@code marshalXMLEventConsumer}, depending on what is contained in the
* {@code StaxResult}.
* @param graph the root of the object graph to marshal
* @param staxResult a JAXP 1.4 {@link StAXSource}
* @throws XmlMappingException if the given object cannot be marshalled to the result
* @throws IllegalArgumentException if the {@code domResult} is empty
* @see #marshalDomNode(Object, org.w3c.dom.Node)
*/
protected void marshalStaxResult(Object graph, Result staxResult) throws XmlMappingException {
XMLStreamWriter streamWriter = StaxUtils.getXMLStreamWriter(staxResult);
if (streamWriter != null) {
marshalXmlStreamWriter(graph, streamWriter);
}
else {
XMLEventWriter eventWriter = StaxUtils.getXMLEventWriter(staxResult);
if (eventWriter != null) {
marshalXmlEventWriter(graph, eventWriter);
}
else {
throw new IllegalArgumentException("StaxResult contains neither XMLStreamWriter nor XMLEventConsumer");
}
}
}
/**
* Template method for handling {@code SAXResult}s.
* <p>This implementation delegates to {@code marshalSaxHandlers}.
* @param graph the root of the object graph to marshal
* @param saxResult the {@code SAXResult}
* @throws XmlMappingException if the given object cannot be marshalled to the result
* @see #marshalSaxHandlers(Object, org.xml.sax.ContentHandler, org.xml.sax.ext.LexicalHandler)
*/
protected void marshalSaxResult(Object graph, SAXResult saxResult) throws XmlMappingException {
ContentHandler contentHandler = saxResult.getHandler();
Assert.notNull(contentHandler, "ContentHandler not set on SAXResult");
LexicalHandler lexicalHandler = saxResult.getLexicalHandler();
marshalSaxHandlers(graph, contentHandler, lexicalHandler);
}
/**
* Template method for handling {@code StreamResult}s.
* <p>This implementation delegates to {@code marshalOutputStream} or {@code marshalWriter},
* depending on what is contained in the {@code StreamResult}
* @param graph the root of the object graph to marshal
* @param streamResult the {@code StreamResult}
* @throws IOException if an I/O Exception occurs
* @throws XmlMappingException if the given object cannot be marshalled to the result
* @throws IllegalArgumentException if {@code streamResult} does neither
* contain an {@code OutputStream} nor a {@code Writer}
*/
protected void marshalStreamResult(Object graph, StreamResult streamResult)
throws XmlMappingException, IOException {
if (streamResult.getOutputStream() != null) {
marshalOutputStream(graph, streamResult.getOutputStream());
}
else if (streamResult.getWriter() != null) {
marshalWriter(graph, streamResult.getWriter());
}
else {
throw new IllegalArgumentException("StreamResult contains neither OutputStream nor Writer");
}
}
// Unmarshalling
/**
* Unmarshals the given provided {@code javax.xml.transform.Source} into an object graph.
* <p>This implementation inspects the given result, and calls {@code unmarshalDomSource},
* {@code unmarshalSaxSource}, or {@code unmarshalStreamSource}.
* @param source the source to marshal from
* @return the object graph
* @throws IOException if an I/O Exception occurs
* @throws XmlMappingException if the given source cannot be mapped to an object
* @throws IllegalArgumentException if {@code source} is neither a {@code DOMSource},
* a {@code SAXSource}, nor a {@code StreamSource}
* @see #unmarshalDomSource(javax.xml.transform.dom.DOMSource)
* @see #unmarshalSaxSource(javax.xml.transform.sax.SAXSource)
* @see #unmarshalStreamSource(javax.xml.transform.stream.StreamSource)
*/
@Override
public final Object unmarshal(Source source) throws IOException, XmlMappingException {
if (source instanceof DOMSource domSource) {
return unmarshalDomSource(domSource);
}
else if (StaxUtils.isStaxSource(source)) {
return unmarshalStaxSource(source);
}
else if (source instanceof SAXSource saxSource) {
return unmarshalSaxSource(saxSource);
}
else if (source instanceof StreamSource streamSource) {
return unmarshalStreamSource(streamSource);
}
else {
throw new IllegalArgumentException("Unknown Source type: " + source.getClass());
}
}
/**
* Template method for handling {@code DOMSource}s.
* <p>This implementation delegates to {@code unmarshalDomNode}.
* If the given source is empty, an empty source {@code Document}
* will be created as a placeholder.
* @param domSource the {@code DOMSource}
* @return the object graph
* @throws XmlMappingException if the given source cannot be mapped to an object
* @throws IllegalArgumentException if the {@code domSource} is empty
* @see #unmarshalDomNode(org.w3c.dom.Node)
*/
protected Object unmarshalDomSource(DOMSource domSource) throws XmlMappingException {
if (domSource.getNode() == null) {
domSource.setNode(buildDocument());
}
try {
return unmarshalDomNode(domSource.getNode());
}
catch (NullPointerException ex) {
if (!isSupportDtd()) {
throw new UnmarshallingFailureException("NPE while unmarshalling. " +
"This can happen on JDK 1.6 due to the presence of DTD " +
"declarations, which are disabled.", ex);
}
throw ex;
}
}
/**
* Template method for handling {@code StaxSource}s.
* <p>This implementation delegates to {@code unmarshalXmlStreamReader} or
* {@code unmarshalXmlEventReader}.
* @param staxSource the {@code StaxSource}
* @return the object graph
* @throws XmlMappingException if the given source cannot be mapped to an object
*/
protected Object unmarshalStaxSource(Source staxSource) throws XmlMappingException {
XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(staxSource);
if (streamReader != null) {
return unmarshalXmlStreamReader(streamReader);
}
else {
XMLEventReader eventReader = StaxUtils.getXMLEventReader(staxSource);
if (eventReader != null) {
return unmarshalXmlEventReader(eventReader);
}
else {
throw new IllegalArgumentException("StaxSource contains neither XMLStreamReader nor XMLEventReader");
}
}
}
/**
* Template method for handling {@code SAXSource}s.
* <p>This implementation delegates to {@code unmarshalSaxReader}.
* @param saxSource the {@code SAXSource}
* @return the object graph
* @throws XmlMappingException if the given source cannot be mapped to an object
* @throws IOException if an I/O Exception occurs
* @see #unmarshalSaxReader(org.xml.sax.XMLReader, org.xml.sax.InputSource)
*/
protected Object unmarshalSaxSource(SAXSource saxSource) throws XmlMappingException, IOException {
if (saxSource.getXMLReader() == null) {
try {
saxSource.setXMLReader(createXmlReader());
}
catch (SAXException | ParserConfigurationException ex) {
throw new UnmarshallingFailureException("Could not create XMLReader for SAXSource", ex);
}
}
if (saxSource.getInputSource() == null) {
saxSource.setInputSource(new InputSource());
}
try {
return unmarshalSaxReader(saxSource.getXMLReader(), saxSource.getInputSource());
}
catch (NullPointerException ex) {
if (!isSupportDtd()) {
throw new UnmarshallingFailureException("NPE while unmarshalling. " +
"This can happen on JDK 1.6 due to the presence of DTD " +
"declarations, which are disabled.");
}
throw ex;
}
}
/**
* Template method for handling {@code StreamSource}s.
* <p>This implementation delegates to {@code unmarshalInputStream} or {@code unmarshalReader}.
* @param streamSource the {@code StreamSource}
* @return the object graph
* @throws IOException if an I/O exception occurs
* @throws XmlMappingException if the given source cannot be mapped to an object
*/
protected Object unmarshalStreamSource(StreamSource streamSource) throws XmlMappingException, IOException {
if (streamSource.getInputStream() != null) {
if (isProcessExternalEntities() && isSupportDtd()) {
return unmarshalInputStream(streamSource.getInputStream());
}
else {
InputSource inputSource = new InputSource(streamSource.getInputStream());
inputSource.setEncoding(getDefaultEncoding());
return unmarshalSaxSource(new SAXSource(inputSource));
}
}
else if (streamSource.getReader() != null) {
if (isProcessExternalEntities() && isSupportDtd()) {
return unmarshalReader(streamSource.getReader());
}
else {
return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getReader())));
}
}
else {
return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getSystemId())));
}
}
// Abstract template methods
/**
* Abstract template method for marshalling the given object graph to a DOM {@code Node}.
* <p>In practice, {@code node} is a {@code Document} node, a {@code DocumentFragment} node,
* or a {@code Element} node. In other words, a node that accepts children.
* @param graph the root of the object graph to marshal
* @param node the DOM node that will contain the result tree
* @throws XmlMappingException if the given object cannot be marshalled to the DOM node
* @see org.w3c.dom.Document
* @see org.w3c.dom.DocumentFragment
* @see org.w3c.dom.Element
*/
protected abstract void marshalDomNode(Object graph, Node node)
throws XmlMappingException;
/**
* Abstract template method for marshalling the given object to a StAX {@code XMLEventWriter}.
* @param graph the root of the object graph to marshal
* @param eventWriter the {@code XMLEventWriter} to write to
* @throws XmlMappingException if the given object cannot be marshalled to the DOM node
*/
protected abstract void marshalXmlEventWriter(Object graph, XMLEventWriter eventWriter)
throws XmlMappingException;
/**
* Abstract template method for marshalling the given object to a StAX {@code XMLStreamWriter}.
* @param graph the root of the object graph to marshal
* @param streamWriter the {@code XMLStreamWriter} to write to
* @throws XmlMappingException if the given object cannot be marshalled to the DOM node
*/
protected abstract void marshalXmlStreamWriter(Object graph, XMLStreamWriter streamWriter)
throws XmlMappingException;
/**
* Abstract template method for marshalling the given object graph to a SAX {@code ContentHandler}.
* @param graph the root of the object graph to marshal
* @param contentHandler the SAX {@code ContentHandler}
* @param lexicalHandler the SAX2 {@code LexicalHandler}. Can be {@code null}.
* @throws XmlMappingException if the given object cannot be marshalled to the handlers
*/
protected abstract void marshalSaxHandlers(
Object graph, ContentHandler contentHandler, @Nullable LexicalHandler lexicalHandler)
throws XmlMappingException;
/**
* Abstract template method for marshalling the given object graph to a {@code OutputStream}.
* @param graph the root of the object graph to marshal
* @param outputStream the {@code OutputStream} to write to
* @throws XmlMappingException if the given object cannot be marshalled to the writer
* @throws IOException if an I/O exception occurs
*/
protected abstract void marshalOutputStream(Object graph, OutputStream outputStream)
throws XmlMappingException, IOException;
/**
* Abstract template method for marshalling the given object graph to a {@code Writer}.
* @param graph the root of the object graph to marshal
* @param writer the {@code Writer} to write to
* @throws XmlMappingException if the given object cannot be marshalled to the writer
* @throws IOException if an I/O exception occurs
*/
protected abstract void marshalWriter(Object graph, Writer writer)
throws XmlMappingException, IOException;
/**
* Abstract template method for unmarshalling from a given DOM {@code Node}.
* @param node the DOM node that contains the objects to be unmarshalled
* @return the object graph
* @throws XmlMappingException if the given DOM node cannot be mapped to an object
*/
protected abstract Object unmarshalDomNode(Node node) throws XmlMappingException;
/**
* Abstract template method for unmarshalling from a given Stax {@code XMLEventReader}.
* @param eventReader the {@code XMLEventReader} to read from
* @return the object graph
* @throws XmlMappingException if the given event reader cannot be converted to an object
*/
protected abstract Object unmarshalXmlEventReader(XMLEventReader eventReader)
throws XmlMappingException;
/**
* Abstract template method for unmarshalling from a given Stax {@code XMLStreamReader}.
* @param streamReader the {@code XMLStreamReader} to read from
* @return the object graph
* @throws XmlMappingException if the given stream reader cannot be converted to an object
*/
protected abstract Object unmarshalXmlStreamReader(XMLStreamReader streamReader)
throws XmlMappingException;
/**
* Abstract template method for unmarshalling using a given SAX {@code XMLReader}
* and {@code InputSource}.
* @param xmlReader the SAX {@code XMLReader} to parse with
* @param inputSource the input source to parse from
* @return the object graph
* @throws XmlMappingException if the given reader and input source cannot be converted to an object
* @throws IOException if an I/O exception occurs
*/
protected abstract Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource)
throws XmlMappingException, IOException;
/**
* Abstract template method for unmarshalling from a given {@code InputStream}.
* @param inputStream the {@code InputStreamStream} to read from
* @return the object graph
* @throws XmlMappingException if the given stream cannot be converted to an object
* @throws IOException if an I/O exception occurs
*/
protected abstract Object unmarshalInputStream(InputStream inputStream)
throws XmlMappingException, IOException;
/**
* Abstract template method for unmarshalling from a given {@code Reader}.
* @param reader the {@code Reader} to read from
* @return the object graph
* @throws XmlMappingException if the given reader cannot be converted to an object
* @throws IOException if an I/O exception occurs
*/
protected abstract Object unmarshalReader(Reader reader)
throws XmlMappingException, IOException;
}
|
package tool.calendar;
import java.time.Duration;
import java.util.Calendar;
/**
* lenient 模式 每个时间字段可接受超出它允许的范围的值(默认)
* non-lenient 模式 每个时间字段不可接受超出它允许的范围的值
*/
public class CalendarTest
{
public static void main(String[] args)
{
// Calendar 介绍
Calendar calendar = Calendar.getInstance();
// 年
System.out.println("年 : " + calendar.get(Calendar.YEAR));
// 月
System.out.println("月 : " + calendar.get(Calendar.MONTH));
// 日
System.out.println("日 : " + calendar.get(Calendar.DATE));
System.out.println(calendar.getTime());
// 设置,年、月、日、时、分、秒
calendar.set(2003, 10, 23, 12, 32, 23); // 设置时间后,之后获取的时间,都是设置的时间
System.out.println(calendar.getTime());
// 推一年,add功能比roll功能强大
calendar.add(Calendar.MONTH, 10);
System.out.println(calendar.getTime());
// 推8个月
calendar.roll(Calendar.YEAR, 1);
System.out.println(calendar.getTime());
System.out.println("\n其它时间类*****************************************************start");
test_java_time_package();
System.out.println("其它时间类*****************************************************end");
}
private static void test_java_time_package()
{
// clock
java.time.Clock clock = java.time.Clock.systemUTC();
System.out.println("当前时刻的毫秒数:" + clock.millis());
System.out.println("当前时刻的毫秒数:" + System.currentTimeMillis());
// duration
Duration duration = Duration.ofSeconds(6000);
System.out.println("6000秒 = " + duration.toMinutes() + "分");
System.out.println("6000秒 = " + duration.toHours() + "时");
System.out.println("6000秒 = " + duration.toDays() + "天");
// instant
System.out.println("工具类有:\n"
+ "时间类(日期、时区):Clock,Duration,Instant,LocalData,LocalTime,LocalDateTime,MonthDay,Year,YearMonth,ZonedDateTime \n"
+ "枚举类:DayOfWeek,Month");
}
}
|
package com.xh.util;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.provider.Settings.Secure;
public class GpsManage {
private Context context;
/**
* <p>GPS开关
* <p>当前若关则打开
* <p>当前若开则关闭
*/
private void toggleGPS() {
Intent gpsIntent = new Intent();
gpsIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
gpsIntent.setData(Uri.parse("custom:3"));
try {
PendingIntent.getBroadcast(context, 0, gpsIntent, 0).send();
} catch (CanceledException e) {
e.printStackTrace();
}
}
//获取Gps开启或关闭状态
private boolean getGpsStatus(Context context)
{
boolean status = Secure.isLocationProviderEnabled(context.getContentResolver(),
LocationManager.GPS_PROVIDER);
return status;
}
//打开或关闭Gps
private void setGpsStatus(Context context, boolean enabled)
{
Secure.setLocationProviderEnabled(context.getContentResolver(),
LocationManager.GPS_PROVIDER, enabled);
}
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
// <uses-permission android:name="android.permission.WRITE_SETTINGS" />
// <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
}
|
package sch.frog.test;
public interface ICaseObject {
String content();
}
|
package com.teaboot.web.session;
import java.lang.reflect.Field;
import com.teaboot.context.anno.AutoDi;
import com.teaboot.context.beans.BeanCollections;
import com.teaboot.context.common.PropertiesManager;
import com.teaboot.context.entity.EntityType;
import com.teaboot.context.utils.StringUtil;
public class ServerContext implements Context{
@Override
public int getSessionTimeout() {
return -1;
}
public static String getServerPath(){
String serverName = PropertiesManager.get("server.name");
if(StringUtil.isEmpty(serverName)){
return "/";
}
if(!serverName.startsWith("/"))serverName = "/" + serverName;
if(!serverName.endsWith("/"))serverName = serverName + "/";
return serverName;
}
public static String getServerName(){
String serverName = PropertiesManager.get("server.name");
if(StringUtil.isEmpty(serverName)){
return "/";
}
if(serverName.equals("/"))return serverName;
if(serverName.startsWith("/"))serverName = serverName.substring(1);
if(serverName.endsWith("/"))serverName = serverName.substring(0,serverName.length()-1);
return serverName;
}
public static void registerFilter(Class... filters) {
for (Class clazz : filters) {
Object obj = null;
try {
obj = clazz.newInstance();
} catch (Exception e) {
continue;
}
String valueClass = obj.getClass().getSimpleName();
BeanCollections.getInstance().addFilter(valueClass, obj);
registerFields(obj);
}
}
public static void registerFields(Object obj) {
BeanCollections bc = BeanCollections.getInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (int j = 0; j < fields.length; j++) {
try {
Field field = fields[j];
field.setAccessible(true);
if (field.getAnnotation(AutoDi.class) == null)
continue;
Class fc = field.getType();
if (fc.isPrimitive()) {
continue;
}
String fieldName = field.getType().getSimpleName();
if (bc.get(fieldName) != null) {
field.set(obj, bc.get(fieldName).getObj());
continue;
}
EntityType entityType = bc.getInherit(fc);
if (entityType != null) {
field.set(obj, entityType.getObj());
continue;
}
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
}
|
package deloitte.forecastsystem_bih;
import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import deloitte.forecastsystem_bih.loadforecast.similarday.SimilarDayService;
import deloitte.forecastsystem_bih.model.Country;
import deloitte.forecastsystem_bih.model.LoadForecastSimilarDay;
import deloitte.forecastsystem_bih.model.PreparedDataLoadHours;
import deloitte.forecastsystem_bih.model.communication.PreparedDataLoadHoursRecord;
import deloitte.forecastsystem_bih.service.CountryService;
import deloitte.forecastsystem_bih.service.LoadForecastSimilarDayService;
import deloitte.forecastsystem_bih.service.PreparedDataLoadHoursService;
//@SpringBootApplication(scanBasePackages={"deloitte.*"})
public class PartialSimilarDayService implements CommandLineRunner {
@Autowired
CountryService countryService;
@Autowired
SimilarDayService similarDayService;
@Autowired
LoadForecastSimilarDayService loadForecastSimilarDayService;
@Autowired
PreparedDataLoadHoursService preparedDataLoadHoursService;
public static void main(String[] args) {
SpringApplication.run(PartialSimilarDayService.class, args);
}
@Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("PARTIAL SIMILAR DAY SERVICE: ");
Country con = countryService.findById(2L);
LoadForecastSimilarDay lfsd = new LoadForecastSimilarDay();
//Long start = 25059L;
long[] ids = preparedDataLoadHoursService.getAllIdsLoadHoursByCountry(con);
Long startId = preparedDataLoadHoursService.getMinIndexForPartialData(con);
Long endId = preparedDataLoadHoursService.getMaxIndexForPartialData(con);
if (startId == null) {
System.out.println("No data for update...");
return;
}
Long startPos = -1L;
for (int i=0; i<ids.length; i++) {
if (ids[i] == startId) {
startPos = Long.valueOf(i);
break;
}
}
System.out.println("Start position: " + startPos);
System.out.println("Id interval: " + startId + "," + endId);
similarDayService.set(con, startPos);
similarDayService.normalizeData();
// for (Long number = 25059L; number < endPos; number++) {
for (Long number = startId; number <= endId; number++) {
PreparedDataLoadHours recData = preparedDataLoadHoursService.findById(number).get();
similarDayService.set(con, startPos);
startPos++;
//similarDayService.set(con, start);
//start++;
PreparedDataLoadHoursRecord rec = new PreparedDataLoadHoursRecord(number, recData.getMaxTemperature4() , recData.getMinTemperature4() , recData.getAvgLoadRealData4(),
recData.getMaxTemperature3() , recData.getMinTemperature3() , recData.getAvgLoadRealData3(),
recData.getMaxTemperature2() , recData.getMinTemperature2() , recData.getAvgLoadRealData2(),
recData.getAvgLoadRealData());
similarDayService.calculateDistance(rec);
lfsd.setCountry(con);
lfsd.setId(0L);
Calendar c = Calendar.getInstance();
lfsd.setForecastDate(c.getTime());
c.set(recData.getGodina(), recData.getMesec()-1, recData.getDan(), 0, 0, 0);
lfsd.setLoadDate(c.getTime());
lfsd.setLoadForecastSimilarDay(similarDayService.getForecast());
lfsd.setLoadHour(recData.getLoadHour());
lfsd.setLoadMinute(0);
loadForecastSimilarDayService.save(lfsd);
System.out.println(recData.getAvgLoadRealData() + "," + similarDayService.getForecast());
} // number
System.out.println("....... END .......");
}
}
|
package model;
public enum State{
Active,Inactive;
} |
/**
*
*/
package com.smartech.course.racing;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.smartech.course.racing.exception.CreatingVehicleException;
import com.smartech.course.racing.vehicle.Bus;
import com.smartech.course.racing.vehicle.Car;
import com.smartech.course.racing.vehicle.Movable;
import com.smartech.course.racing.vehicle.Truck;
/**
* Racing Simulator application
* @author Alexey Solomatin
*
*/
public class RacingSimulator {
/**
* Entry point to the application
* @param args command line arguments
*/
public static void main(String[] args) {
/*
* 1) Show the information about the application.
* 2) Create racers from the console.
* 3) Create a race.
* 4) Run simulation.
* 5) Print results to the screen.
*/
try {
Collection<Movable> vehicles = createVehicles();
Racing racing = createRacing();
RacingSimulation simulation = new RacingSimulation(racing, 1);
vehicles.stream().forEach(simulation::register);
simulation.run();
} catch (Exception e) {
e.printStackTrace();
}
}
private static Collection<Movable> createVehicles() throws CreatingVehicleException {
List<Movable> vehicles = new ArrayList<>();
// 700 kg, 50 m/s, 10 m/s^2
Car car = new Car("Car", 700, 50, 10);
vehicles.add(car);
// 1000 kg, 30 m/s, 5 m/s^2, 0/40 passengers
Bus bus = new Bus("Bus", 1000, 30, 5, 40, 0);
vehicles.add(bus);
// 1500 kg, 40 m/s, 7 m/s^2, 0/500 kg
Truck truck = new Truck("Truck", 1500, 40, 7, 500, 0);
vehicles.add(truck);
return vehicles;
}
private static Racing createRacing() {
return new Racing("Racing #1", 500);
}
}
|
package Tests.TestNGTests.DemoTests;
import Tests.TestNGTests.BaseCLass;
import Utils.ConstantsUtils;
import org.testng.Assert;
import org.testng.annotations.*;
public class TestNgClasses extends BaseCLass {
@Test
public void test01(){
System.out.println("My very first TestNG test!");
double a = 1.05;
double b = 2.01;
double sum = a+b;
Assert.assertEquals(sum, 3.06, 0.1, "Equalls!");
driver.get(ConstantsUtils.URL_BASE2);
}
@Test
public void test02(){
System.out.println("Test 02");
driver.get(ConstantsUtils.URL_BASE2);
}
}
|
package com.example.hellostudiotesting;
/**
* Created by ian on 2016-07-13.
*/
public class DataModel {
public String getName() {
return "Robin Good";
}
}
|
/*
2021-10-15
[Programmers][DfsBfs][Lv2] 네트워크
check) 단방향 네트워크
1->2->3
3->2
=> 각각 네트워크 2개인 상황임.
*/
package DfsBfs;
public class Network {
boolean[] visited;
public int solution(int n, int[][] computers) {
int answer = 0;
visited = new boolean[n];
for(int i=0; i<n; i++) {
if ( visited[i]==false ) {
dfs(i, n, computers);
answer++;
}
}
return answer;
}
private void dfs(int k, int n, int[][] computers) {
System.out.println("k : " + k + " visited[k] : " + visited[k]);
visited[k] = true;
// fail
// if ( k>=n-1 ) {
// return;
// }
for(int i=0; i<n; i++) {
if ( k==i ) continue;
if ( computers[k][i] == 1 && visited[i] == false ) {
// visited[i] = true; // fail - 여기서 체크 하면 solutoin() 에서 처음 dfs 진입할 때 visited check 안됨.
dfs(i, n, computers);
}
}
}
public static void main(String[] args) {
Network network=new Network();
int n=3;
// int[][] computers = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}};
// int[][] computers = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
// n=4;
// int[][] computers = {{1, 1, 1, 0}, {1, 1, 1, 0}, {1, 1, 1, 0}, {0, 0, 0, 1}};
n=5;
// int[][] computers = {{1, 1, 1, 1,0}, {1, 1, 1, 0,0}, {1, 1, 1, 0,0}, {1, 0, 0, 1,0}, {0, 0, 0, 0, 1}};
// int[][] computers = {{1, 1, 0, 0,1}, {1, 1, 1, 0,0}, {0, 1, 1, 1,0}, {0, 0, 1, 1,0}, {1, 0, 0, 0, 1}};
n=1;
// int[][] computers = {{1}};
n=2;
// int[][] computers = {{1,0}, {0,1}};
n=4;
// int[][] computers = {{1, 1, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0,0,0,1}};
n=3;
// int[][] computers = {{1, 0, 0}, {1, 1, 0}, {1, 0, 1}};
n=5;
int[][] computers = {{1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0,0,1,0,0}, {0, 0, 0, 1,0}, {1, 0, 0, 0, 1}};
System.out.println(network.solution(n, computers));
}
}
|
package adtpackage;
import generalpackage.*;
/**
*
* @author Zbyněk Stara
*/
public class HashSet extends HashTable implements Set {
public HashSet(int dimension) {
super(dimension);
}
public <T extends Printable> ReturnCode add(T data, double key) {
int checkCounter = 0;
boolean positionFound = false;
ReturnCode additionResult = ReturnCode.UNDEFINED;
int hashValue = hashCalculation(key);
while (checkCounter < dataArray.length) {
if (dataArray[hashValue] == null) {
dataArray[hashValue] = new TableElement(data, key);
positionFound = true;
size += 1;
arrayChanged = true;
additionResult = ReturnCode.SUCCESS;
break;
} else if (dataArray[hashValue].key == key) {
positionFound = true;
additionResult = ReturnCode.SKIP;
break;
} else {
checkCounter += 1;
hashValue += 1;
if (hashValue == dataArray.length) hashValue = 0;
}
}
if (!positionFound) additionResult = ReturnCode.OVERFLOW;
return additionResult;
}
public Object remove(double key) { // will return null if it doesn't exist
return delete(key);
}
public boolean contains(double key) {
return search(key) != null;
}
}
|
/*
* 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 pooPractica.Personas;
/**
*
* @author RadW
*/
public class Persona implements java.io.Serializable{
private String nombre;
private String nif;
private int tlf;
}
|
package com.tt.rendezvous.core.algorithms;
import java.util.HashMap;
import java.util.List;
public abstract class AlgorithmWords {
public AlgorithmWords(){
}
public abstract double calculateSimilarity(List<String> words1, List<String> words2);
public abstract double calculateSimilarityTaxonomy(List<String> words1, List<String> words2, HashMap<String,Double> taxonomy);
public abstract double calculateSimilarityTaxonomy(List<String> words1, List<String> words2, HashMap<String,Double> taxonomy, HashMap<String,Double> ontology);
}
|
package com.yg.schedule;
import com.yg.service.EmpManagerService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import javax.annotation.Resource;
public class PayJob extends QuartzJobBean {
//判断作业是否执行的旗标
private boolean isRunning = false;
@Resource(name = "EmpManagerService")
private EmpManagerService empMgr;
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
if(!isRunning){
System.out.println("开始调度自动结算工资");
isRunning = true;
empMgr.autoPay();
isRunning = false;
}
}
}
|
package base.obj;
import base.abst.Object_test;
public class Ts extends Object_test{
public Ts(String name, int id, boolean repeat, int NumRepeat) {
super(name, id, repeat, NumRepeat);
// TODO Auto-generated constructor stub
}
}
|
/*
* 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 PA165.language_school_manager.Entities;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* @author Matúš Sedlák
*/
@Entity
public class Lecture {
public void setId(Long id) {
this.id = id;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//@NotNull
private LocalDateTime time;
@ManyToOne
@NotNull
private Course course;
private String topic;
@ManyToOne
@NotNull
private Lecturer lecturer;
@ManyToMany(mappedBy = "lectures", cascade = CascadeType.REMOVE)
private Set<Person> persons = new HashSet<Person>();
public void addPerson(Person student) {
this.persons.add(student);
}
public Set<Person> getPersons() {
return Collections.unmodifiableSet(persons);
}
public Lecture() {
}
public Lecture(String topic){
this.topic = topic;
}
/*public Lecture(long id) {
this.id = id;
}*/
public Long getId() {
return id;
}
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public Lecturer getLecturer() {
return lecturer;
}
public void setLecturer(Lecturer lecturer) {
this.lecturer = lecturer;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((time == null) ? 0 : time.hashCode());
result = prime * result + ((course == null) ? 0 : course.hashCode());
result = prime * result + ((topic == null) ? 0 : topic.hashCode());
result = prime * result + ((lecturer == null) ? 0 : lecturer.hashCode());
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Lecture)) return false;
Lecture lecture = (Lecture) o;
if (time != null ? !time.equals(lecture.time) : lecture.time != null) return false;
if (course != null ? !course.equals(lecture.course) : lecture.course != null) return false;
if (topic != null ? !topic.equals(lecture.topic) : lecture.topic != null) return false;
return lecturer != null ? lecturer.equals(lecture.lecturer) : lecture.lecturer == null;
}
}
|
package aop.test;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Service;
@Service
@Aspect
public class MyAspect {
//@After("execution(* aop.test.*.setAge(..))")
public void checkAge(JoinPoint joinPoint) {
//System.out.println(joinPoint.getTarget());
//System.out.println(joinPoint.getThis());
//System.out.println(Arrays.toString(joinPoint.getArgs()));
Object[] args = joinPoint.getArgs();
int age = (Integer)args[0];
if( age > 20) {
System.out.println("미성년입니다.");
}else {
System.out.println("성년입니다.");
}
}
//@Around("execution(* aop.test.*.setAge(..))") // 일단 가져와서 내가 시점 설정가능
public void checkAdult2(ProceedingJoinPoint joinPoint) throws Throwable{
/*joinPoint.proceed();// After : setAge를 수행 후 공통코드 수행
System.out.println("checkAdult2"); // = 공통코드
joinPoint.proceed();// Before : 공통코드 수행 후 setAge수행
// joinPoint.proceed(); = 핵심코드
*/
//Before
joinPoint.proceed();
Object[] args = joinPoint.getArgs();
int age = (Integer)args[0];
if( age > 20) {
System.out.println("미성년입니다.");
}else {
System.out.println("성년입니다.");
}
}
@AfterThrowing(pointcut="execution(* aop.test.*.setAge(..))", throwing="ex")
public void error(JoinPoint joinPoint, Throwable ex) {
System.out.println("예외처리 : "+ ex.toString());
}
}
|
/*
* 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 ppro.modelo;
import java.io.Serializable;
import java.util.Collection;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author casa
*/
@Entity
@Table(name = "ppro_entidad_financiera")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "PproEntidadFinanciera.findAll", query = "SELECT p FROM PproEntidadFinanciera p"),
@NamedQuery(name = "PproEntidadFinanciera.findByEntFinId", query = "SELECT p FROM PproEntidadFinanciera p WHERE p.entFinId = :entFinId"),
@NamedQuery(name = "PproEntidadFinanciera.findByEntFinNombre", query = "SELECT p FROM PproEntidadFinanciera p WHERE p.entFinNombre = :entFinNombre"),
@NamedQuery(name = "PproEntidadFinanciera.findByEntFinCodigo", query = "SELECT p FROM PproEntidadFinanciera p WHERE p.entFinCodigo = :entFinCodigo"),
@NamedQuery(name = "PproEntidadFinanciera.findByEntFinEstado", query = "SELECT p FROM PproEntidadFinanciera p WHERE p.entFinEstado = :entFinEstado")})
@ManagedBean
@SessionScoped
public class PproEntidadFinanciera implements Serializable {
@OneToMany(mappedBy = "provEntFinanciera")
private Collection<PproProveedor> pproProveedorCollection;
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ent_fin_id")
private Integer entFinId;
@Size(max = 255)
@Column(name = "ent_fin_nombre")
private String entFinNombre;
@Size(max = 255)
@Column(name = "ent_fin_codigo")
private String entFinCodigo;
@Column(name = "ent_fin_estado")
private Integer entFinEstado;
public PproEntidadFinanciera() {
}
public PproEntidadFinanciera(Integer entFinId) {
this.entFinId = entFinId;
}
public Integer getEntFinId() {
return entFinId;
}
public void setEntFinId(Integer entFinId) {
this.entFinId = entFinId;
}
public String getEntFinNombre() {
return entFinNombre;
}
public void setEntFinNombre(String entFinNombre) {
this.entFinNombre = entFinNombre;
}
public String getEntFinCodigo() {
return entFinCodigo;
}
public void setEntFinCodigo(String entFinCodigo) {
this.entFinCodigo = entFinCodigo;
}
public Integer getEntFinEstado() {
return entFinEstado;
}
public void setEntFinEstado(Integer entFinEstado) {
this.entFinEstado = entFinEstado;
}
@Override
public int hashCode() {
int hash = 0;
hash += (entFinId != null ? entFinId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PproEntidadFinanciera)) {
return false;
}
PproEntidadFinanciera other = (PproEntidadFinanciera) object;
if ((this.entFinId == null && other.entFinId != null) || (this.entFinId != null && !this.entFinId.equals(other.entFinId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "ppro.modelo.PproEntidadFinanciera[ entFinId=" + entFinId + " ]";
}
@XmlTransient
public Collection<PproProveedor> getPproProveedorCollection() {
return pproProveedorCollection;
}
public void setPproProveedorCollection(Collection<PproProveedor> pproProveedorCollection) {
this.pproProveedorCollection = pproProveedorCollection;
}
}
|
package uz.pdp.appcodingbat.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import uz.pdp.appcodingbat.entity.Answer;
import uz.pdp.appcodingbat.entity.User;
import uz.pdp.appcodingbat.payload.AnswerDto;
import uz.pdp.appcodingbat.payload.Result;
import uz.pdp.appcodingbat.payload.UserDto;
import uz.pdp.appcodingbat.service.AnswerService;
import uz.pdp.appcodingbat.service.UserService;
import java.util.List;
@RestController
@RequestMapping("/api/answer")
public class AnswerController {
@Autowired
AnswerService answerService;
/**
* GET ANSWER LIST
*
* @return ANSWER LIST
*/
@GetMapping
public ResponseEntity<List<Answer>> get() {
List<Answer> answers = answerService.get();
return ResponseEntity.ok(answers);
}
/**
* GET ONE ANSWER BY ID
*
* @param id INTEGER
* @return ONE ANSWER
*/
@GetMapping("/{id}")
public ResponseEntity<Answer> getById(@PathVariable Integer id) {
Answer answer = answerService.getById(id);
return ResponseEntity.status(answer != null ? 200 : 409).body(answer);
}
/**
* DELETE ANSWER BY ID
*
* @param id INTEGER
* @return RESULT
*/
@DeleteMapping("/{id}")
public ResponseEntity<Result> delete(@PathVariable Integer id) {
Result result = answerService.delete(id);
return ResponseEntity.status(result.isSuccess() ? 200 : 405).body(result);
}
/**
* ADD ANSWER
*
* @param answerDto USER ID (Integer), TASK ID (Integer), CORRECT (Boolean)
* @return RESULT
*/
@PostMapping
public ResponseEntity<Result> add(@RequestBody AnswerDto answerDto) {
Result result = answerService.add(answerDto);
return ResponseEntity.status(result.isSuccess() ? 201 : 409).body(result);
}
/**
* EDIT ANSWER BY ID
*
* @param id INTEGER
* @param answerDto USER ID (Integer), TASK ID (Integer), CORRECT (Boolean)
* @return RESULT
*/
@PutMapping("/{id}")
public ResponseEntity<Result> edit(@PathVariable Integer id, @RequestBody AnswerDto answerDto) {
Result result = answerService.edit(id, answerDto);
return ResponseEntity.status(result.isSuccess() ? 202 : 409).body(result);
}
}
|
package kr.co.mghan.view;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ExcelPrint
{
public void setXls() {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet hs = wb.createSheet();
HSSFRow hr = hs.createRow(0);
HSSFCell hc;
hc = hr.createCell(0);
hc.setCellValue("1번째 행에 첫번째 셀");
hc = hr.createCell(1);
hc.setCellValue(1234.567);
hr = hs.createRow(1);
hc = hr.createCell(0);
hc.setCellValue("2번째 행에 첫번째 셀");
hc = hr.createCell(1);
hc.setCellValue(98786.5432);
File file = new File("c:/Test/TestExcel.xls");
if(file.exists()) {
try
{
file.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(file);
wb.write(fos);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try
{
wb.close();
fos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.