text stringlengths 10 2.72M |
|---|
package com.crutchclothing.orders.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Type;
import org.hibernate.loader.custom.Return;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import com.crutchclothing.users.model.Address;
import com.crutchclothing.users.model.User;
@Entity
@Table(name="orders", catalog="crutch")
public class Order implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private final static double TAX_RATE = 8.25;
private Integer id;
private String username;
private Integer orderNumber;
private LocalDate shipDate;
private DateTime orderDate;
private double salesTax;
private double orderTotal;
private String orderStatus;
private String shippingCompany;
private String trackingNumber;
private User user;
//private Set<Product> products = new HashSet<>();
private Set<OrderLine> orderLines = new HashSet<OrderLine>();
private Address billingAddress;
private Address shippingAddress;
public Order() {
}
//@GeneratedValue
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "order_id")
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "order_number", unique = true, nullable = false)
public Integer getOrderNumber() {
return this.orderNumber;
}
public void setOrderNumber(Integer orderNumber) {
this.orderNumber = orderNumber;
}
@Columns(columns = { @Column(name = "ship_date", nullable = false) })
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
public LocalDate getShipDate() {
return this.shipDate;
}
public void setShipDate(LocalDate shipDate) {
this.shipDate = shipDate;
}
@Columns(columns = { @Column(name = "order_date_time", nullable = false),
@Column(name = "order_date_time_zone", nullable = false) })
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTimeWithZone")
public DateTime getOrderDate() {
return this.orderDate;
}
public void setOrderDate(DateTime orderDate) {
this.orderDate = orderDate;
}
@Column(name = "order_sales_tax", nullable = true)
public double getSalesTax() {
//if(user.getPrimaryAddress().getState().equalsIgnoreCase("california")) {
double orderTotal = getOrderTotal();
return (this.salesTax = orderTotal * (TAX_RATE/100));
//return (this.salesTax = 0);
}
public void setSalesTax(double salesTax) {
this.salesTax = salesTax;
}
@Column(name = "order_total", nullable = true)
public double getOrderTotal() {
List<OrderLine> oLines = new ArrayList<OrderLine>(this.orderLines);
for(int i = 0; i < oLines.size(); i++){
this.orderTotal += oLines.get(i).getSubtotal();
}
return this.orderTotal;
}
public void setOrderTotal(double orderTotal) {
this.orderTotal = orderTotal;
}
@Column(name = "order_status", nullable = true)
public String getOrderStatus() {
return this.orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
@Column(name = "shipping_co", nullable = true)
public String getShippingCompany() {
return this.shippingCompany;
}
public void setShippingCompany(String shippingCompany) {
this.shippingCompany = shippingCompany;
}
@Column(name = "tracking_number", nullable = true)
public String getTrackingNumber() {
return this.trackingNumber;
}
public void setTrackingNumber(String trackingNumber) {
this.trackingNumber = trackingNumber;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "username", nullable = false)
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
/*
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(name = "order_products",
joinColumns = { @JoinColumn(name = "order_id") },
inverseJoinColumns = { @JoinColumn(name = "product_id") })
public Set<Product> getProducts() {
return this.products;
}
*/
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "order")
public Set<OrderLine> getOrderLines() {
return this.orderLines;
}
public void setOrderLines(Set<OrderLine> orderLines) {
this.orderLines = orderLines;
}
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "billing_address_id")
public Address getBillingAddress() {
return this.billingAddress;
}
public void setBillingAddress(Address billingAddress) {
this.billingAddress = billingAddress;
}
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "shipping_address_id")
public Address getShippingAddress() {
return this.shippingAddress;
}
public void setShippingAddress(Address shippingAddress) {
this.shippingAddress = shippingAddress;
}
/*
public void addProduct(Product product) {
products.add(product);
}
*/
/*
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((orderPk == null) ? 0 : orderPk.hashCode());
return result;
}
/**
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
/*
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Order)) {
return false;
}
Order other = (Order) obj;
if (orderPk == null) {
if (other.orderPk != null) {
return false;
}
} else if (!orderPk.equals(other.orderPk)) {
return false;
}
return true;
}
*/
}
|
package com.lambton.note_javadocjuveniles_android;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.lambton.note_javadocjuveniles_android.Adapter.notesAdapter;
import com.lambton.note_javadocjuveniles_android.Models.Notes;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
TextView txt_title;
ImageView search_icon,drawer_txt,new_note;
EditText search;
RelativeLayout createnote,no_note;
RecyclerView recyclerView;
notesAdapter madapter;
NotesDatabase notesDatabase;
List<Notes> listNotes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer_txt=(ImageView) findViewById(R.id.drawer_icon);
txt_title=(TextView)findViewById(R.id.txt_title);
new_note=(ImageView) findViewById(R.id.new_note);
search=(EditText) findViewById(R.id.search_txt);
createnote=(RelativeLayout) findViewById(R.id.createnote);
no_note=(RelativeLayout) findViewById(R.id.no_notes);
search_icon=(ImageView) findViewById(R.id.search_icon);
recyclerView=(RecyclerView) findViewById(R.id.note_recycler);
drawer_txt.setVisibility(View.GONE);
new_note.setVisibility(View.GONE);
txt_title.setText("Notes");
notesDatabase = NotesDatabase.getInstance(com.lambton.note_javadocjuveniles_android.MainActivity.this);
listNotes = NotesDatabase.getInstance(com.lambton.note_javadocjuveniles_android.MainActivity.this).getNoteDao().getAll();
if(listNotes.size()==0){
no_note.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
}else {
no_note.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
createnote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),NewNoteActivity.class);
i.putExtra("from","new");
startActivity(i);
}
});
search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
madapter = new notesAdapter(this,listNotes,NotesDatabase.getInstance(com.lambton.note_javadocjuveniles_android.MainActivity.this).getSubjectDao().getAll()) {
@Override
public void deleteAddress(final int pos) {
final AlertDialog.Builder mainDialog = new AlertDialog.Builder(com.lambton.note_javadocjuveniles_android.MainActivity.this);
LayoutInflater inflater = (LayoutInflater)getApplicationContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.alert_dialog, null);
mainDialog.setView(dialogView);
final Button cancel = (Button) dialogView.findViewById(R.id.cancel);
final Button save = (Button) dialogView.findViewById(R.id.save);
final ImageView cross=(ImageView) dialogView.findViewById(R.id.cross);
final AlertDialog alertDialog = mainDialog.create();
alertDialog.show();
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
notesDatabase.getNoteDao().delete(listNotes.get(pos));
listNotes.remove(pos);
recyclerView.getAdapter().notifyDataSetChanged();
alertDialog.dismiss();
}
});
cross.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}
};
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(madapter);
}
private void filter(String text) {
listNotes = NotesDatabase.getInstance(com.lambton.note_javadocjuveniles_android.MainActivity.this).getNoteDao().getAll();
List<Notes> temp = new ArrayList();
for (Notes n :listNotes) {
if(n.getTitle().toLowerCase().contains(text.toLowerCase()) || n.getDescription().toLowerCase().contains(text.toLowerCase())){
temp.add(n);
}
}
madapter.notes = temp;
recyclerView.getAdapter().notifyDataSetChanged();
}
}
|
package org.aksw.autosparql.commons.nlp.pos;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import com.aliasi.tag.Tagging;
import edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TextAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.util.CoreMap;
import edu.stanford.nlp.util.logging.JavaUtilLoggingAdaptor.RedwoodHandler;
import edu.stanford.nlp.util.logging.Redwood.RedwoodChannels;
import edu.stanford.nlp.util.logging.Redwood;
import edu.stanford.nlp.util.logging.RedwoodConfiguration;
public class StanfordPartOfSpeechTagger implements PartOfSpeechTagger{
/** if you only use it single threadedly just use the singleton to save initialization time */
public static final StanfordPartOfSpeechTagger INSTANCE = new StanfordPartOfSpeechTagger();
private StanfordCoreNLP pipeline;
protected StanfordPartOfSpeechTagger(){
// shut off the annoying intialization messages
RedwoodConfiguration.empty().captureStderr().apply();
Properties props = new Properties();
props.put("annotators", "tokenize, ssplit, pos");
pipeline = new StanfordCoreNLP(props);
// enable stderr again
RedwoodConfiguration.current().clear().apply();
}
@Override
public String getName() {
return "Stanford POS Tagger";
}
@Override
public String tag(String text) {
String out = "";
// create an empty Annotation just with the given text
Annotation document = new Annotation(text);
// run all Annotators on this text
pipeline.annotate(document);
// these are all the sentences in this document
// a CoreMap is essentially a Map that uses class objects as keys and has values with custom types
List<CoreMap> sentences = document.get(SentencesAnnotation.class);
for(CoreMap sentence: sentences) {
for (CoreLabel token: sentence.get(TokensAnnotation.class)) {
// this is the text of the token
String word = token.get(TextAnnotation.class);
// this is the POS tag of the token
String pos = token.get(PartOfSpeechAnnotation.class);
out += " " + word + "/" + pos;
}
}
return out.trim();
}
@Override
public List<String> tagTopK(String sentence) {
return Collections.singletonList(tag(sentence));
}
public List<String> getTags(String text){
List<String> tags = new ArrayList<String>();
// create an empty Annotation just with the given text
Annotation document = new Annotation(text);
// run all Annotators on this text
pipeline.annotate(document);
// these are all the sentences in this document
// a CoreMap is essentially a Map that uses class objects as keys and has values with custom types
List<CoreMap> sentences = document.get(SentencesAnnotation.class);
for(CoreMap sentence: sentences) {
for (CoreLabel token: sentence.get(TokensAnnotation.class)) {
// this is the text of the token
String word = token.get(TextAnnotation.class);
// this is the POS tag of the token
String pos = token.get(PartOfSpeechAnnotation.class);
tags.add(pos);
}
}
return tags;
}
@Override
public Tagging<String> getTagging(String text){
List<String> tokenList = new ArrayList<String>();
List<String> tagList = new ArrayList<String>();
// create an empty Annotation just with the given text
Annotation document = new Annotation(text);
// run all Annotators on this text
pipeline.annotate(document);
// these are all the sentences in this document
// a CoreMap is essentially a Map that uses class objects as keys and has values with custom types
List<CoreMap> sentences = document.get(SentencesAnnotation.class);
for(CoreMap sentence: sentences) {
for (CoreLabel token: sentence.get(TokensAnnotation.class)) {
// this is the text of the token
String word = token.get(TextAnnotation.class);
// this is the POS tag of the token
String pos = token.get(PartOfSpeechAnnotation.class);
tokenList.add(word);
tagList.add(pos);
}
}
return new Tagging<String>(tokenList, tagList);
}
}
|
/*
* 功能:短信来了获取剩余条数示例
* 版本:1.3
* 日期:2016-07-01
* 说明:
* 以下代码只是为了方便客户测试而提供的样例代码,客户可以根据自己网站的需要,按照技术文档自行编写,并非一定要使用该代码。
* 该代码仅供学习和研究使用,只是提供一个参考。
* 网址:http://www.laidx.com
*/
package com.gome.manager.sms;
import java.util.HashMap;
public class SMSNumDemo {
public static void main(String[] args) {
String address = "120.24.161.220";//远程地址:不带http://
int port = 8800;//远程端口
String account = "";//账户
String token = "";//token
short rType = 0;//响应类型 0 json类型,1 xml类型
KXTSmsSDK kxtsms = new KXTSmsSDK();
kxtsms.init(address, port, account, token);
String result = kxtsms.smsNum(rType);
HashMap<String, Object> hashMap = null;
if(rType == 0)
{
//json
hashMap = CommonUtils.jsonToMap(result);
}
if(rType == 1)
{
//xml
hashMap = CommonUtils.xmlToMap(result);
}
if(hashMap != null)
{
//写自己的业务逻辑代码
//hashMap.get("Code");
}
}
}
|
package com.codigo.smartstore.sdk.core.structs.iterate.array;
import static com.codigo.smartstore.sdk.core.constans.Default.zero;
import java.util.Iterator;
/**
* Interfejs deklaruje kontrakt opisujący mechanizm iterowania po elementach
* kolekcji typu tablica
*
* @author andrzej.radziszewski
* @version 1.0.0.0
* @since 2018
* @category iterator
*
* @param <E> Parametr typu generycznego, który określa typ elementów kolekcji
*/
public interface ArrayIterable<E>
extends Iterator<E> {
/**
* Stała klasy określa rozmiar pustej tablicy
*/
int EMPTY_TABLE = zero(int.class);
/**
* Stała klasy określa początkowy numer indeksu tablicy
*/
int ZERO_BASED_INDEX = zero(int.class);
/**
* Właściwość określa indeks początkowego elementu zakresu iteratora kolekcji
*
* @return Indeks pierwszego elementu zakresu kolekcji
*/
int getBeginIndex();
/**
* Właściwość określa indeks bieżącego elementu zakresu iteratora kolekcji
*
* @return Indeks bieżącego elementu zakresu kolekcji
*/
int getCurrentIndex();
/**
* Właściwość określa indeks ostatniego elementu zakresu iteratora kolekcji
*
* @return Indeks ostatniego elementu zakresu kolekcji
*/
int getLastIndex();
/**
* Właściwość określa ilość elementów iteratora kolekcji
*
* @return Ilość elementów kolekcji
*/
int getCount();
/**
* Właściwość określa ilość elementów iteratora z zakresu kolekcji
*
* @return Ilość elementów z zakresu kolekcji
*/
int getCountFromRange();
/**
* Właściwość określa ilość elmentów, które były odczytane/odwiedzone
*
* @return Ilość odczytanych elementów kolekcji
*/
int getCountVisited();
/**
* Właściwość określa ilość elementów, które były nie zostały
* odczytane/odwiedzone
*
* @return Ilość nieodczytanych elementów kolekcji
*/
int getCountRemaining();
/**
* Metoda wykonuje restart iteracji kolekcji. Iteracja rozpoczyna się od indeksu
* początkowego
*/
void reset();
}
|
package vo;
import models.MenuInfo;
import java.math.BigDecimal;
/**
* Created by guxuelong on 2014/12/27.
*/
public class MenuInfoVo {
private Long id;
private String foodId;
private String foodName;
private String foodType;
private String source;
private String priceScope;
private BigDecimal price;
private BigDecimal count;
private String picture;
public MenuInfoVo () {
}
public MenuInfoVo (MenuInfo menuInfo) {
inMenuInfoVo(menuInfo);
}
public void inMenuInfoVo (MenuInfo menuInfo) {
this.setFoodId(menuInfo.getFoodId());
this.setFoodName(menuInfo.getFoodName());
this.setFoodType(menuInfo.getFoodType());
this.setSource(menuInfo.getSource());
this.setPrice(menuInfo.getPrice());
this.setCount(menuInfo.getCount());
this.setPicture(menuInfo.getPicture());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFoodId() {
return foodId;
}
public void setFoodId(String foodId) {
this.foodId = foodId;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getFoodType() {
return foodType;
}
public void setFoodType(String foodType) {
this.foodType = foodType;
}
public String getPriceScope() {
return priceScope;
}
public void setPriceScope(String priceScope) {
this.priceScope = priceScope;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public BigDecimal getCount() {
return count;
}
public void setCount(BigDecimal count) {
this.count = count;
}
public String getPriceStr() {
return price.toPlainString();
}
public void setPriceStr(String priceStr) {
this.price = new BigDecimal(priceStr);
}
public String getCountStr() {
return count.toPlainString();
}
public void setCountStr(String countStr) {
this.count = new BigDecimal(countStr);
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
}
|
package com.netcrest.pado.ui.swing.pado.hazelcast;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.TransferHandler;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.hazelcast.addon.util.OrderBy;
import org.hazelcast.demo.nw.data.Order;
import com.gemstone.gemfire.cache.query.Struct;
import com.hazelcast.core.IMap;
import com.hazelcast.query.PagingPredicate;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.Predicates;
import com.hazelcast.query.SqlPredicate;
import com.netcrest.commandspace.CommandDescriptor;
import com.netcrest.commandspace.CommandPost;
import com.netcrest.commandspace.ICommandProvider;
import com.netcrest.commandspace.ReturnDataObject;
import com.netcrest.pado.data.KeyMap;
import com.netcrest.pado.data.KeyType;
import com.netcrest.pado.data.KeyTypeManager;
import com.netcrest.pado.index.service.IScrollableResultSet;
import com.netcrest.pado.info.PathInfo;
import com.netcrest.pado.info.ServerInfo;
import com.netcrest.pado.internal.util.StringUtil;
import com.netcrest.pado.ui.swing.GridFrame;
import com.netcrest.pado.ui.swing.beans.ButtonTabComponentAdd;
import com.netcrest.pado.ui.swing.beans.ButtonTabComponentRemove;
import com.netcrest.pado.ui.swing.pado.gemfire.LuceneInputPanel;
import com.netcrest.pado.ui.swing.pado.gemfire.OqlInputPanel;
import com.netcrest.pado.ui.swing.pado.gemfire.PadoInfoExplorer;
import com.netcrest.pado.ui.swing.pado.gemfire.ServerInputPanel;
import com.netcrest.pado.ui.swing.pado.gemfire.info.BucketDisplayInfo;
import com.netcrest.pado.ui.swing.pado.hazelcast.GridTableModel.ResultType;
import com.netcrest.pado.ui.swing.pado.hazelcast.info.ItemSelectionInfo;
import com.netcrest.pado.ui.swing.pado.hazelcast.query.MapNotFoundException;
import com.netcrest.pado.ui.swing.pado.hazelcast.query.QueryResultSet;
import com.netcrest.pado.ui.swing.pado.hazelcast.query.SimpleQueryParser;
import com.netcrest.pado.ui.swing.table.ObjectTreeFrame;
import com.netcrest.pado.ui.swing.table.ObjectTreePanel;
import com.netcrest.ui.swing.table.RowNumberTable;
import com.netcrest.ui.swing.util.RowHeaderTable;
import com.netcrest.ui.swing.util.SwingUtil;
import com.netcrest.ui.swing.util.TableSorter;
/**
* @author dpark
*
*/
@SuppressWarnings({ "rawtypes", "unchecked", "static-access" })
public class PageTablePanel extends JPanel implements Externalizable {
private static final long serialVersionUID = 1L;
private static CommandDescriptor commandDescriptors[] = {
new CommandDescriptor(ICommandNames.CS_PADO_INFO.COMMAND_onMapItem,
"Listens on IMap notifications and refreshes itself.") };
private PadoInfoExplorer explorer;
private HashMap<String, ResultPanel> resultPanelMap = new HashMap(20);
private int processedRow = -1;
private JTabbedPane tpane;
private ObjectTreeFrame objectTreeFrame = null;
private QueryControlPanel queryControlPanel;
private JSplitPane mainSplitPane;
private JSplitPane splitPane;
private OqlInputPanel oqlInputPanel;
private LuceneInputPanel luceneInputPanel;
private ServerInputPanel serverInputPanel;
private JPanel resultPanel;
private JPanel topControlPanel;
private JPanel mainPanel;
private JTabbedPane bottomTabbedPane;
private ObjectTreePanel objectTreePanel;
private JPanel inputPanel;
private JTabbedPane inputTabbedPane;
private CommandPost commandPost = new CommandPost();
public PageTablePanel() {
preInit();
setLayout(new BorderLayout(0, 0));
initAllUI();
setTabComponentAdd(0);
}
protected void preInit() {
PageTablePanelCommandProvider commandProvider = new PageTablePanelCommandProvider();
commandPost.setInternTopicEnabled(true);
commandPost.addCommandProvider(commandProvider);
commandPost.addCommandProvider(ICommandNames.CS_PADO_INFO.TOPIC, commandProvider);
}
private void initOqlUI() {
oqlInputPanel = new OqlInputPanel();
inputTabbedPane.addTab("OQL", null, oqlInputPanel, null);
oqlInputPanel.setMinimumSize(new Dimension(0, 0));
oqlInputPanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String queryString = e.getActionCommand();
String resultName = getOqlResultName("hazelcast", queryString);
executeWorkerQuery(resultName, "hazelcast", queryString);
} catch (Throwable th) {
SwingUtil.showErrorMessageDialog(PageTablePanel.this, th);
}
}
});
}
private void initLuceneUI() {
luceneInputPanel = new LuceneInputPanel();
luceneInputPanel.setMinimumSize(new Dimension(0, 0));
luceneInputPanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String gridId = luceneInputPanel.getSelectedGridId();
String regionPath = luceneInputPanel.getSelectedFullPath();
String queryString = e.getActionCommand();
String resultName = getLucentResultName(regionPath, queryString);
executeWorkerQuery(resultName, gridId, queryString);
}
});
// inputTabbedPane.addTab("Lucene", null, luceneInputPanel, null);
}
protected void initMainUI() {
mainPanel = new JPanel();
add(mainPanel, BorderLayout.CENTER);
mainPanel.setLayout(new BorderLayout(0, 0));
mainSplitPane = new JSplitPane();
mainSplitPane.setOneTouchExpandable(true);
mainSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
mainPanel.add(mainSplitPane, BorderLayout.CENTER);
splitPane = new JSplitPane();
splitPane.setResizeWeight(1.0);
inputPanel = new JPanel();
inputPanel.setMinimumSize(new Dimension(0, 0));
inputPanel.setLayout(new BorderLayout(0, 0));
inputTabbedPane = new JTabbedPane(JTabbedPane.TOP);
inputTabbedPane.setMinimumSize(new Dimension(0, 0));
inputPanel.add(inputTabbedPane, BorderLayout.CENTER);
mainSplitPane.setLeftComponent(inputPanel);
mainSplitPane.setRightComponent(splitPane);
splitPane.setOneTouchExpandable(true);
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
bottomTabbedPane = new JTabbedPane(JTabbedPane.TOP);
bottomTabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
bottomTabbedPaneChanged();
}
});
bottomTabbedPane.setMinimumSize(new Dimension(0, 0));
objectTreePanel = new ObjectTreePanel();
bottomTabbedPane.addTab("Value", null, objectTreePanel, null);
splitPane.setRightComponent(bottomTabbedPane);
resultPanel = new JPanel();
resultPanel.setMinimumSize(new Dimension(0, 0));
splitPane.setLeftComponent(resultPanel);
// add(centerPanel, BorderLayout.CENTER);
resultPanel.setLayout(new BorderLayout(0, 0));
tpane = new JTabbedPane();
tpane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
updateSatellitePanels();
}
});
resultPanel.add(tpane, BorderLayout.CENTER);
tpane.add("", new JLabel(""));
topControlPanel = new JPanel();
FlowLayout flowLayout = (FlowLayout) topControlPanel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
resultPanel.add(topControlPanel, BorderLayout.NORTH);
queryControlPanel = new QueryControlPanel();
queryControlPanel.addKeyTypeComboBoxItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
keyTypeSelected((QueryControlPanel.KeyTypeItem) e.getItem());
}
}
});
queryControlPanel.addPageSpinnerActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
page(queryControlPanel.getPage());
}
});
queryControlPanel.addRefreshButtonActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
refresh();
}
});
topControlPanel.add(queryControlPanel);
GridBagLayout gridBagLayout = (GridBagLayout) queryControlPanel.getLayout();
gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
queryControlPanel.addPlayButtonActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
play();
}
});
queryControlPanel.addNextButtonActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nextPage();
}
});
queryControlPanel.addPreviousButtonActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
previousPage();
}
});
queryControlPanel.addLastButtonActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lastPage();
}
});
queryControlPanel.addFirstButtonActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstPage();
}
});
queryControlPanel.setBorder(new EmptyBorder(2, 2, 0, 2));
splitPane.setDividerLocation(200);
mainSplitPane.setDividerLocation(240);
}
private void initAllUI() {
initMainUI();
initOqlUI();
// No Lucene. Use TemporalUI instead.
initLuceneUI();
}
private ResultPanel getSelectedResultPanel() {
Component component = tpane.getSelectedComponent();
if (component instanceof ResultPanel == false) {
return null;
}
return (ResultPanel) component;
}
private PageTableModel getSelectedTableModel() {
ResultPanel resultPanel = getSelectedResultPanel();
if (resultPanel == null) {
return null;
}
return resultPanel.getTableModel();
}
private ResultPanel getResultPanel(String resultName) {
return resultPanelMap.get(resultName);
}
private void setTabComponentRemove(int index) {
tpane.setTabComponentAt(index, new ButtonTabComponentRemove(tpane));
}
protected void setTabComponentAdd(int index) {
tpane.setTabComponentAt(index, new ButtonTabComponentAdd(tpane));
}
private String getLucentResultName(String regionPath, String queryString) {
return "lucene:/" + regionPath + "/" + queryString;
}
private String getOqlResultName(String gridId, String queryString) {
return "oql://" + gridId + "/" + queryString;
}
private RowHeaderTable getPrimitiveType(List objList) throws Exception {
Class c = objList.get(0).getClass();
String className = StringUtil.getShortClassName(c.getName());
// columns
String columnNames[] = new String[] { "Row", className };
PageTableModel model = new PageTableModel();
model.setColumnNames(columnNames);
// rows
Object rowData[];
for (int i = 0; i < objList.size(); i++) {
rowData = new Object[3];
rowData[0] = new Integer(i + 1);
Object obj = objList.get(i);
rowData[1] = obj;
// user data
rowData[2] = obj;
model.addRow(rowData);
}
RowHeaderTable table = new RowHeaderTable();
table.setTableSorter(model);
table.resetColumnCellRenderers();
return table;
}
private int getPublicMemberCount(List objList) {
int count = 0;
if (objList == null || objList.size() == 0) {
return count;
}
Field[] fields = objList.get(0).getClass().getDeclaredFields();
Method[] methods = objList.get(0).getClass().getMethods();
// scan fields
for (int i = 0; i < fields.length; i++) {
int modifiers = fields[i].getModifiers();
if (!Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) {
count++;
}
}
// scan methods
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
int modifiers = method.getModifiers();
String methodName = methods[i].getName();
if (!Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers) && methodName.startsWith("get")
&& (method.getParameterTypes().length == 0) && !methodName.equals("getClass")) {
count++;
}
}
return count;
}
private int getPublicMemberNMethodCount(Object obj) {
int count = 0;
Field[] fields = obj.getClass().getDeclaredFields();
Method[] methods = obj.getClass().getMethods();
// scan fields
for (int i = 0; i < fields.length; i++) {
int modifiers = fields[i].getModifiers();
if (!Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) {
count++;
}
}
// scan methods
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
int modifiers = method.getModifiers();
String methodName = methods[i].getName();
if (!Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers) && methodName.startsWith("get")
&& (method.getParameterTypes().length == 0) && !methodName.equals("getClass")) {
count++;
}
}
return count;
}
private void reset() {
processedRow = -1;
}
private void rowSelected(RowHeaderTable table, boolean forceUpdate) {
if (table == null) {
return;
}
int row = table.getSelectedRow();
if (row < 0 || row >= table.getRowCount() || (!forceUpdate && row == processedRow)) {
return;
}
processedRow = row;
TableSorter model = (TableSorter) table.getModel();
PageTableModel tableModel = ((PageTableModel) model.getTableModel());
Object value = tableModel.getUserData(model.modelIndex(row));
setObjectValue(value);
}
private void bottomTabbedPaneChanged() {
// Temporal list
if (bottomTabbedPane.getSelectedIndex() == 1) {
if (getSelectedResultPanel() != null) {
rowSelected(getSelectedResultPanel().getTable(), true);
}
}
}
private void setObjectValue(Object value) {
objectTreePanel.setObject(value);
objectTreePanel.expandRow(1);
}
private void openObjectTreeTable(Object object) {
if (object == null) {
return;
}
if (objectTreeFrame == null) {
objectTreeFrame = new ObjectTreeFrame();
objectTreeFrame.setLocationRelativeTo((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this));
// SwingUtil.centerFrame((Frame)
// SwingUtilities.getAncestorOfClass(Frame.class, this),
// objectTreeFrame);
}
objectTreeFrame.setObject(object);
objectTreeFrame.setState(Frame.NORMAL);
objectTreeFrame.setVisible(true);
}
private void firstPage() {
queryControlPanel.setPage(1);
pageChanged();
}
private void lastPage() {
PageTableModel tableModel = getSelectedTableModel();
if (tableModel == null) {
return;
}
queryControlPanel.setPage(((QueryResultSet)tableModel.getResultSet()).getLargestPageVisted());
pageChanged();
}
private void previousPage() {
int page = queryControlPanel.getPage() - 1;
page(page);
}
private void nextPage() {
int page = queryControlPanel.getPage() + 1;
page(page);
PageTableModel tableModel = getSelectedTableModel();
if (tableModel == null) {
return;
}
if (((QueryResultSet)tableModel.getResultSet()).isLastPage()) {
queryControlPanel.setMaximumPage(((QueryResultSet)tableModel.getResultSet()).getLargestPageVisted());
}
}
private void page(int page) {
try {
PageTableModel tableModel = getSelectedTableModel();
if (tableModel == null) {
return;
}
// if the fetch size has been changed then refresh (start from the beginning)
if (tableModel.getResultSet().getFetchSize() != queryControlPanel.getFetchSize()) {
refresh();
return;
}
boolean pageChanged = tableModel.page(page, queryControlPanel.getFetchSize());
ResultPanel resultPanel = getSelectedResultPanel();
resultPanel.table.resetColumnCellRenderers();
resultPanel.rowTable.setFirstRowNumber(tableModel.getFirstRowNumber());
if (pageChanged) {
queryControlPanel.setPage(tableModel.getPage());
}
// queryControlPanel.setMaximumPage(tableModel.getPageCount());
} catch (Exception ex) {
SwingUtil.showErrorMessageDialog(this, ex);
}
}
private void pageChanged() {
page(queryControlPanel.getPage());
}
private void play() {
try {
if (inputTabbedPane.getSelectedComponent() == oqlInputPanel) {
String queryString = oqlInputPanel.getQuery();
String gridId = oqlInputPanel.getSelectedGridId();
executeWorkerQuery(getOqlResultName(gridId, queryString), gridId, queryString);
} else if (inputTabbedPane.getSelectedComponent() == luceneInputPanel) {
String regionPath = luceneInputPanel.getSelectedFullPath();
String queryString = luceneInputPanel.getQuery();
executeWorkerQuery(getLucentResultName(regionPath, queryString), luceneInputPanel.getSelectedGridId(),
queryString);
}
} catch (Exception ex) {
SwingUtil.showErrorMessageDialog(this, ex);
}
}
private void refresh() {
queryControlPanel.resetMaximumPage();
ResultPanel resultPanel = getSelectedResultPanel();
if (resultPanel == null) {
return;
}
resultPanel.refresh();
}
private void keyTypeSelected(QueryControlPanel.KeyTypeItem keyTypeItem) {
PageTableModel tableModel = getSelectedTableModel();
if (tableModel == null) {
return;
}
IScrollableResultSet resultSet = tableModel.getResultSet();
try {
tableModel.reset(resultSet.getStartIndex() + resultSet.getViewStartIndex() + 1, resultSet, null,
keyTypeItem.getKeyType());
} catch (Exception ex) {
SwingUtil.showErrorMessageDialog(this, ex);
}
}
private IScrollableResultSet executeOql(String resultName, String gridId, String queryString) {
// Predicate allPredicate = Predicates.alwaysTrue();
SimpleQueryParser parser = new SimpleQueryParser(queryString);
IMap map = HazelcastSharedCache.getSharedCache().getMap(parser.getPath());
if (map == null) {
throw new MapNotFoundException(parser.getPath() + ": " + queryString);
}
Predicate queryPredicate;
if (parser.isWhereClause()) {
queryPredicate = new SqlPredicate(parser.getWhereClause());
} else {
queryPredicate = Predicates.alwaysTrue();
}
OrderBy orderBy = new OrderBy(parser.getOrderBy());
PagingPredicate<String, Order> pagingPredicate = new PagingPredicate<String, Order>(queryPredicate, orderBy,
queryControlPanel.getFetchSize());
Set<Map.Entry<?, ?>> entries = map.entrySet(pagingPredicate);
return new QueryResultSet(map, entries, pagingPredicate);
}
// private IScrollableResultSet executeLucene(String resultName, String gridId, String regionPath, String queryString)
// {
// IGridQueryService qs = GridQueryService.getGridQueryService();
// GridQuery criteria = GridQueryFactory.createGridQuery();
// criteria.setId(resultName);
// criteria.setAscending(true);
// criteria.setFetchSize(queryControlPanel.getFetchSize());
// criteria.setLimit(getResultLimit());
// criteria.setOrdered(true);
// criteria.setQueryString(queryString);
// criteria.setSortField(null);
// criteria.setForceRebuildIndex(chckbxForceIndex.isSelected());
// criteria.setGridIds(gridId);
// criteria.setGridService(SharedCache.getSharedCache().getPado().getCatalog().getGridService());
// criteria.setFullPath(regionPath);
// criteria.setProviderKey(Constants.PQL_PROVIDER_KEY);
// IScrollableResultSet rs = (IScrollableResultSet) qs.query(criteria);
// return rs;
// }
public void clear() {
tpane.removeAll();
tpane.add(new JLabel());
setTabComponentAdd(0);
updateSatellitePanels();
resultPanelMap.clear();
}
private void updateObjectTreePanel() {
ResultPanel resultPanel = getSelectedResultPanel();
if (resultPanel != null) {
RowHeaderTable table = resultPanel.getTable();
if (table != null) {
int row = table.getSelectedRow();
if (row != -1) {
rowSelected(table, false);
return;
}
}
}
objectTreePanel.clear();
}
public void executeWorkerGridPath(String resultName, String gridId, String gridPath) {
try {
if (gridPath == null) {
return;
}
ResultPanel resultPanel = getResultPanel(resultName);
boolean newPanel = resultPanel == null;
if (newPanel) {
resultPanel = new ResultPanel(resultName, gridId, gridPath);
resultPanelMap.put(resultName, resultPanel);
}
// if the panel already exists then select its tab and return
// JTabbedPane allows only one same component.
int index = tpane.getSelectedIndex();
if (tpane.indexOfComponent(resultPanel) != -1) {
tpane.setSelectedIndex(tpane.indexOfComponent(resultPanel));
return;
}
setResultPanelAt(resultName, resultPanel, index);
} catch (Exception ex) {
SwingUtil.showErrorMessageDialog(this, ex);
}
}
public void executeWorkerQuery(String resultName, String gridId, String queryString) {
try {
ResultPanel resultPanel = getResultPanel(resultName);
boolean newPanel = resultPanel == null;
if (newPanel) {
if (inputTabbedPane.getSelectedComponent() == oqlInputPanel) {
resultPanel = new ResultPanel(resultName, gridId, queryString);
} else {
// lucene
String gridPath = luceneInputPanel.getSelectedFullPath();
resultPanel = new ResultPanel(resultName, gridId, gridPath, queryString);
}
resultPanelMap.put(resultName, resultPanel);
} else {
if (inputTabbedPane.getSelectedComponent() == oqlInputPanel) {
// oql
resultPanel.setType(ResultPanel.OQL);
resultPanel.setQueryString(queryString);
} else {
// lucene
resultPanel.setType(ResultPanel.LUCENE);
resultPanel.setQueryString(queryString);
resultPanel.setRegionPath(luceneInputPanel.getSelectedFullPath());
}
resultPanel.refresh();
}
// unselect tree node
if (getPadoInfoExplorer() != null) {
getPadoInfoExplorer().firePropertyChange("querySelected", false, true);
}
// if the panel already exists then select its tab and return
// JTabbedPane allows only one same component.
int index = tpane.getSelectedIndex();
if (tpane.indexOfComponent(resultPanel) != -1) {
tpane.setSelectedIndex(tpane.indexOfComponent(resultPanel));
return;
}
setResultPanelAt(resultName, resultPanel, index);
} catch (Exception ex) {
SwingUtil.showErrorMessageDialog(this, ex);
}
}
public PadoInfoExplorer getPadoInfoExplorer() {
if (explorer == null) {
explorer = (PadoInfoExplorer) SwingUtilities.getAncestorOfClass(PadoInfoExplorer.class, this);
}
return explorer;
}
private void setResultPanelAt(String resultName, ResultPanel resultPanel, int index) {
if (index >= 0) {
tpane.remove(index);
} else {
index = 0;
}
reset();
tpane.insertTab(resultName, null, resultPanel, null, index);
setTabComponentRemove(index);
// Add "+" tab
// if (tpane.getTabCount() == 1) {
// tpane.add("", new JLabel(""));
// setTabComponentAdd(1);
// }
// workaround to the tab "+" button
int lastIndex = tpane.getTabCount() - 1;
Component comp = tpane.getComponentAt(lastIndex);
if (comp instanceof JLabel == false) {
tpane.add("", new JLabel(""));
setTabComponentAdd(lastIndex + 1);
}
tpane.setSelectedIndex(index);
updateSatellitePanels();
this.validate();
}
private void updateSatellitePanels() {
updateObjectTreePanel();
updateControlPanel();
}
private void updateControlPanel() {
ResultPanel resultPanel = getSelectedResultPanel();
if (resultPanel == null) {
if (queryControlPanel != null) {
queryControlPanel.setTotalSize(0);
queryControlPanel.setPage(1);
// queryControlPanel.setMaximumPage(1);
}
return;
}
IScrollableResultSet rs = resultPanel.getResultSet();
PageTableModel tableModel = resultPanel.getTableModel();
if (rs == null) {
if (tableModel == null) {
queryControlPanel.setTotalSize(0);
queryControlPanel.setPage(1);
// queryControlPanel.setMaximumPage(1);
} else {
queryControlPanel.setTotalSize(tableModel.getRowCount());
queryControlPanel.setPage(1);
// queryControlPanel.setMaximumPage(1);
}
return;
}
queryControlPanel.setFetchSize(rs.getFetchSize());
queryControlPanel.setTotalSize(rs.getTotalSize());
queryControlPanel.setPage(rs.getSetNumber());
// queryControlPanel.setMaximumPage(rs.getSetCount());
KeyType[] keyTypes = null;
if (tableModel != null) {
if (tableModel.isKeyMap()) {
Class[] classes = tableModel.getKeyTypeClasses();
if (classes.length > 0) {
keyTypes = KeyTypeManager.getAllRegisteredVersions(classes[0]);
}
}
}
queryControlPanel.setKeyTypes(keyTypes);
queryControlPanel.setKeyTypeComboBoxVisible(tableModel != null && tableModel.isKeyMap());
}
private String getResultName(String gridId, HazelcastSharedCache.MapItem item) {
if (item == null) {
return "";
} else if (gridId != null) {
return "path://" + gridId + item.getFullPath();
} else {
return "path://" + item.getFullPath();
}
}
class RemoteWorker extends SwingWorker<IScrollableResultSet, String> {
String resultName;
String gridId;
String queryString;
String args[];
RemoteWorker(String resultName, String gridId, String queryString) {
this.resultName = resultName;
this.gridId = gridId;
this.queryString = queryString;
}
protected IScrollableResultSet doInBackground() throws Exception {
publish("Retrieving data...");
return executeOql(resultName, gridId, queryString);
}
protected void process(List<String> chunks) {
ResultPanel resultPanel = getResultPanel(resultName);
if (resultPanel != null) {
resultPanel.setProgress(chunks.get(0));
}
}
protected void done() {
try {
ResultPanel resultPanel = getResultPanel(resultName);
if (resultPanel == null) {
return;
}
IScrollableResultSet resultSet = get();
resultPanel.updateTable(resultSet);
updateSatellitePanels();
if (resultPanel.table != null) {
resultPanel.table.resetColumnCellRenderers();
}
} catch (Exception ex) {
SwingUtil.showErrorMessageDialog(PageTablePanel.this, ex);
}
}
}
public class ResultPanel extends JPanel {
private static final long serialVersionUID = 1L;
final static byte REGION = 0;
final static byte OQL = 1;
final static byte LUCENE = 2;
final static byte SERVER = 3;
final static byte BUCKET_INFO = 4;
final static byte BUCKET_ID = 5;
final static byte TEMPORAL = 6;
final static byte VIRTUAL_PATH = 7;
private String gridId;
private PathInfo regionInfo;
private ServerInfo serverInfo;
private BucketDisplayInfo bucketDisplayInfo;
private int routingBucketId;
private int bucketId;
private String resultName;
private String queryString;
private String gridPath;
private String fullPath;
private String virtualPathQueryString;
private String virtualPath;
private KeyMap vpd;
private String[] args;
private byte type = REGION;
private Date validAt;
private Date asOf;
private RowHeaderTable table;
private PageTableModel tableModel;
private JTextPane textPane;
private JScrollPane scrollPane;
private RowNumberTable rowTable;
public ResultPanel(String resultName, String gridId, String queryString) throws Exception {
this.resultName = resultName;
this.gridId = gridId;
this.queryString = queryString;
SimpleQueryParser parser = new SimpleQueryParser(queryString);
this.gridPath = parser.getPath();
this.type = OQL;
initUI();
refresh();
}
public ResultPanel(String resultName, String gridId, String regionPath, String queryString) throws Exception {
this.gridId = gridId;
this.resultName = resultName;
this.gridPath = regionPath;
this.queryString = queryString;
this.type = LUCENE;
initUI();
refresh();
}
private void initUI() {
setLayout(new BorderLayout(0, 0));
textPane = new JTextPane();
textPane.setEditable(false);
scrollPane = new JScrollPane(textPane);
add(scrollPane, BorderLayout.CENTER);
}
public void refresh() {
refresh(this.gridId);
}
public void refresh(String gridId) {
this.gridId = gridId;
if (tableModel != null) {
tableModel.clearAll();
}
switch (type) {
case OQL:
(new RemoteWorker(resultName, gridId, queryString)).execute();
break;
case LUCENE:
break;
}
}
public String getGridId() {
return gridId;
}
public PathInfo getRegionInfo() {
return regionInfo;
}
public String getResultName() {
return resultName;
}
public String getQueryString() {
return queryString;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public void setVirtualPathDefinition(KeyMap vpd) {
this.vpd = vpd;
}
public KeyMap getVirtualPathDefinition() {
return vpd;
}
public void setVirtualPath(String virtualPath) {
this.virtualPath = virtualPath;
}
public String getVirtualPath() {
return virtualPath;
}
public void setFullPath(String fullPath) {
this.fullPath = fullPath;
}
public String getFullPath() {
return fullPath;
}
public void setVirtualPathQueryString(String virtualPathQueryString) {
this.virtualPathQueryString = virtualPathQueryString;
}
public String getVirtualPathQueryString() {
return virtualPathQueryString;
}
public void setArgs(String... args) {
this.args = args;
}
public String[] getArgs() {
return args;
}
public String getRegionPath() {
return gridPath;
}
public void setRegionPath(String regionPath) {
this.gridPath = regionPath;
}
public Date getValidAt() {
return validAt;
}
public void setValidAt(Date validAt) {
this.validAt = validAt;
}
public Date getAsOf() {
return asOf;
}
public void setAsOf(Date asOf) {
this.asOf = asOf;
}
public byte getType() {
return type;
}
public void setType(byte type) {
this.type = type;
}
public void updateTable(IScrollableResultSet resultSet) throws Exception {
if (resultSet == null || resultSet.getTotalSize() <= 0) {
if (table != null) {
table.removeAll();
scrollPane.removeAll();
scrollPane = new JScrollPane(textPane);
removeAll();
add(scrollPane, BorderLayout.CENTER);
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textPane.setText("No rows returned.");
}
});
return;
}
table = createTable(resultSet, ResultType.KEY_VALUE);
table.setCellSelectionEnabled(true);
scrollPane.setViewportView(table);
rowTable = new RowNumberTable(table);
scrollPane.setRowHeaderView(rowTable);
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowTable.getTableHeader());
TableSorter model = (TableSorter) table.getModel();
tableModel = ((PageTableModel) model.getTableModel());
reset();
}
private RowHeaderTable createEmptyTable() {
PageTableModel model = new PageTableModel();
RowHeaderTable table = new RowHeaderTable();
table.setTableSorter(model);
table.resetColumnCellRenderers();
return table;
}
private RowHeaderTable createTable(IScrollableResultSet resultSet, ResultType resultType) throws Exception {
if (resultSet == null) {
return createEmptyTable();
}
List objList = resultSet.toList();
if (objList == null || objList.size() == 0) {
return createEmptyTable();
}
Class c = objList.get(0).getClass();
RowHeaderTable table = null;
// System.out.println("class = " + c.getName());
if (c.isPrimitive() || c.isArray() || c == Integer.class || c == Short.class || c == Long.class
|| c == Byte.class || c == Character.class || c == Float.class || c == Double.class
|| c == Boolean.class || c == String.class || getPublicMemberCount(objList) == 0) {
table = getPrimitiveType(objList);
} else {
boolean isStruct = false;
Class interfaces[] = c.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (interfaces[i] == Struct.class) {
isStruct = true;
break;
}
}
table = createObjectTable(resultSet, resultType);
}
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// copy feature
ActionMap map = table.getActionMap();
map.put(TransferHandler.getCopyAction().getValue(Action.NAME), TransferHandler.getCopyAction());
final RowHeaderTable table2 = table;
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
if (e.getClickCount() == 2) {
int row = table2.getSelectedRow();
if (row >= 0) {
PageTableModel tableModel = (PageTableModel) table2.getTableModel();
TableSorter tableSorter = (TableSorter) table2.getModel();
int modelRow = tableSorter.modelIndex(row);
Object object = tableModel.getUserData(modelRow);
openObjectTreeTable(object);
}
}
}
});
return table;
}
private RowHeaderTable createObjectTable(IScrollableResultSet resultSet, ResultType resultType)
throws Exception {
PageTableModel tableModel = new PageTableModel(resultType);
QueryResultSet qrs = (QueryResultSet)resultSet;
String resultName = qrs.getResultName();
ResultPanel resultPanel = resultPanelMap.get(resultName);
tableModel.reset(resultSet.getStartIndex() + +resultSet.getViewStartIndex() + 1, resultSet, null);
KeyType[] keyTypes = null;
if (tableModel.isKeyMap()) {
Class[] classes = tableModel.getKeyTypeClasses();
if (classes.length > 0) {
keyTypes = KeyTypeManager.getAllRegisteredVersions(classes[0]);
}
}
queryControlPanel.setKeyTypes(keyTypes);
queryControlPanel.setKeyTypeComboBoxVisible(tableModel.isKeyMap());
final RowHeaderTable table = new RowHeaderTable();
table.setTableSorter(tableModel);
// table.resetColumnCellRenderers();
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(MouseEvent e) {
rowSelected(table, false);
}
});
table.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(KeyEvent e) {
rowSelected(table, false);
}
});
table.setDragEnabled(true);
table.repaint();
return table;
}
public PageTableModel getTableModel() {
return tableModel;
}
public RowHeaderTable getTable() {
return table;
}
public void setProgress(final String progressMessage) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textPane.setText(progressMessage);
}
});
}
public IScrollableResultSet getResultSet() {
if (tableModel == null) {
return null;
}
return tableModel.getResultSet();
}
}
public static void main(String[] args) throws Exception {
GridFrame.main(new String[] { PageTablePanel.class.getName() });
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
HashMap map = new HashMap(3);
map.put("mainSplitPane.DividerLocation", mainSplitPane.getDividerLocation());
map.put("splitPane.DividerLocation", splitPane.getDividerLocation());
out.writeObject(map);
oqlInputPanel.writeExternal(out);
luceneInputPanel.writeExternal(out);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
HashMap map = (HashMap) in.readObject();
if (map.containsKey("mainSplitPane.DividerLocation")) {
mainSplitPane.setDividerLocation((Integer) map.get("mainSplitPane.DividerLocation"));
}
if (map.containsKey("splitPane.DividerLocation")) {
splitPane.setDividerLocation((Integer) map.get("splitPane.DividerLocation"));
}
oqlInputPanel.readExternal(in);
luceneInputPanel.readExternal(in);
}
public class PageTablePanelCommandProvider implements ICommandProvider
{
public ReturnDataObject onMapItem(String topic, String sourceInternTopic,
ItemSelectionInfo itemSelectionInfo)
{
ReturnDataObject retObj = new ReturnDataObject(this, null);
String resultName = getResultName(itemSelectionInfo.getGridId(), itemSelectionInfo.getItem());
String query = "select * from " + itemSelectionInfo.getItem().getFullPath();
executeWorkerQuery(resultName, itemSelectionInfo.getGridId(), query);
return retObj;
}
public CommandDescriptor[] getCommandDescriptors() {
return commandDescriptors;
}
}
}
|
package com.fanfte.algorithm.base;
public class LC125ValidPalindrome {
public static void main(String[] args) {
System.out.println(new LC125ValidPalindrome().isPalindrome("A man, a plan, a canal: Panama"));
}
public boolean isPalindrome(String s) {
char[] chars = s.toLowerCase().toCharArray();
int l = 0;
int r = chars.length - 1;
while(l < r) {
if(!Character.isLetterOrDigit(chars[l])) {
l++;
}else if(!Character.isLetterOrDigit(chars[r])) {
r--;
}else {
if(chars[l] == chars[r]) {
l++;
r--;
} else {
return false;
}
}
}
return true;
}
}
|
package com.kh.jd.lecture;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository("LDao")
public class LectureDao {
@Autowired
private SqlSession sqlSession;
public int addLecture(Lecture lecture) {
int result = 0;
try {
result = sqlSession.insert("Lecture.addLecture", lecture);
System.out.println("인서트 들어옴");
} catch (Exception e) {
System.out.println("오류4");
e.printStackTrace();
}
return result;
}
public List<Lecture> listLecture(int teacher_number){
return sqlSession.selectList("Lecture.listLecture", teacher_number);
}
public int removeLecture(String lecture_no) {
int result = 0;
result = sqlSession.delete("Lecture.removeLecture", lecture_no);
return result;
}
public Lecture viewLecture(String lecture_no) {
return sqlSession.selectOne("Lecture.viewLecture",lecture_no);
}
public int editLecture(Lecture lecture) {
return sqlSession.update("Lecture.editLecture", lecture);
}
public List<Lecture> listLectureClass(){
return sqlSession.selectList("Lecture.listLectureClass");
}
public Lecture viewLectureClass(Lecture lecture) {
return sqlSession.selectOne("Lecture.viewLectureClass", lecture);
}
public int checkLectureClass(int lecture_no) {
return sqlSession.update("Lecture.checkLectureClass", lecture_no);
}
public void scheduleState() {
sqlSession.selectOne("Lecture.scheduleState");
}
public Lecture addLecturePlan(Lecture lecture) {
return sqlSession.selectOne("Lecture.addLecturePlan", lecture);
}
public List<Lecture> listTeacherVideo(int teacher_number) {
return sqlSession.selectList("Lecture.listTeacherVideo", teacher_number);
}
public List<Lecture> listStudentVideo(int student_number) {
return sqlSession.selectList("Lecture.listStudentVideo", student_number);
}
}
|
package z2.tests;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static z2.task3.numberer.PerfectNumber.isPerfectNumber;
public class PerfectNumberTest {
@Test
public void isPerfectNumber_Int6_expectedTRUE()
{
boolean expected = true;
boolean actual = isPerfectNumber(6);
assertEquals(expected, actual);
}
@Test
public void isPerfectNumber_Int28_expectedTRUE()
{
boolean expected = true;
boolean actual = isPerfectNumber(28);
assertEquals(expected, actual);
}
@Test
public void isPerfectNumber_Int496_expectedTRUE()
{
boolean expected = true;
boolean actual = isPerfectNumber(496);
assertEquals(expected, actual);
}
@Test
public void isPerfectNumber_Int8128_expectedTRUE()
{
boolean expected = true;
boolean actual = isPerfectNumber(8128);
assertEquals(expected, actual);
}
@Test
public void isPerfectNumber_Int9_expectedFALSE()
{
boolean expected = false;
boolean actual = isPerfectNumber(9);
assertEquals(expected, actual);
}
}
|
package com.ramonmr95.app.resources;
import java.util.UUID;
import javax.ws.rs.core.Response;
import com.ramonmr95.app.dtos.CountryDto;
import com.ramonmr95.app.entities.Country;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
public interface ICountryResource {
/**
*
* Gets a list with all of the {@link Country} entities.
*
* @return response Response that contains the {@link List<Country>} with
* all of the countries.
*/
@Operation(summary = "Get all countries", responses = {
@ApiResponse(responseCode = "200", description = "Gets all the countries", content = @Content(mediaType = "application/json", schema = @Schema(implementation = CountryDto.class))) })
public Response getAllCountries();
/**
*
* Gets a {@link CountryDto} given its id.
*
* @param id Id of the country as string fullfilling the {@link UUID} format.
* @return response Response that contains either the country if it exists in
* the Database or status code 404 if it does not.
*/
@Operation(summary = "Get country by id", responses = {
@ApiResponse(responseCode = "200", description = "Gets the country related to an specific id", content = @Content(mediaType = "application/json", schema = @Schema(implementation = CountryDto.class))),
@ApiResponse(responseCode = "404", description = "There is not any country with the given id") })
public Response getCountryById(@Parameter(description = "Country id", required = true) String id);
/**
*
* Creates a {@link CountryDto} received from the request body.
*
* @param country {@link CountryDto} to create.
* @return response Response that contains either the created {@link CountryDto}
* and status code 201 if there are not any validation errors or the
* validations errors and status code 400 if there are any validation
* errors.
*/
@Operation(summary = "Create a country", responses = {
@ApiResponse(responseCode = "201", description = "Country created", content = @Content(mediaType = "application/json", schema = @Schema(implementation = CountryDto.class))),
@ApiResponse(responseCode = "400", description = "Invalid country"), })
public Response createCountry(
@RequestBody(description = "Country to create", required = true, content = @Content(schema = @Schema(implementation = CountryDto.class))) CountryDto countryDto);
/**
*
* Updates a {@link CountryDto} given its id and the {@link CountryDto} from the
* request body.
*
* @param id Id of the country as string fullfilling the {@link UUID}
* format.
* @param country {@link CountryDto} to update.
* @return response Response that if there are not any {@link Country}
* validation errors contains the updated {@link Country} and the status
* code 200. If the {@link Country} contains validation errors the
* response will contain the status code 400. If the given id does not
* match any {@link Country} from the Database, the response will
* contain the status code 404.
*/
@Operation(summary = "Update a country", responses = {
@ApiResponse(responseCode = "200", description = "Country updated", content = @Content(mediaType = "application/json", schema = @Schema(implementation = CountryDto.class))),
@ApiResponse(responseCode = "400", description = "Invalid country"),
@ApiResponse(responseCode = "404", description = "There is not any country with the given id") })
public Response updateCountry(@Parameter(description = "Country id", required = true) String id,
@RequestBody(description = "Updated Country", required = true, content = @Content(schema = @Schema(implementation = CountryDto.class))) CountryDto countryDto);
/**
*
* Deletes a {@link Country} from the database given its id.
*
* @param id Id of the country as string fullfilling the {@link UUID} format.
* @return response Response that if the given id matches any {@link Country} of
* the database will return a status code of 204. If the id does not
* match any id the status code will be 404.
*/
@Operation(summary = "Delete a country", responses = {
@ApiResponse(responseCode = "204", description = "The country was deleted"),
@ApiResponse(responseCode = "404", description = "There is not any country with the given id") })
public Response deleteCountry(@Parameter(description = "Country id", required = true) String id);
}
|
package Collection;
import java.util.Map;
import java.util.TreeMap;
public class Map_Mul_Key {
public static void main(String[] args) {
Map <String,String>m=new TreeMap<String,String>();
m.put("as","Ashok");
m.put("as","laxman");
m.put("as","rajesh");
for(Map.Entry r: m.entrySet()){
Object key = r.getKey();
Object value = r.getValue();
System.out.println(key);
System.out.println(value);
}
}}
|
package com.hello;
public class Dog {
public void doing() {
// TODO Auto-generated method stub
System.out.println("RRRRR");
}
}
|
package com.yc.education.service.impl.account;
import com.github.pagehelper.PageHelper;
import com.yc.education.mapper.account.AccountReceiptMapper;
import com.yc.education.mapper.account.AccountSaleInvoiceMapper;
import com.yc.education.model.account.AccountReceipt;
import com.yc.education.model.account.AccountSaleInvoice;
import com.yc.education.service.account.IAccountReceiptService;
import com.yc.education.service.account.IAccountSaleInvoiceService;
import com.yc.education.service.impl.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Description
* @Author BlueSky
* @Date 2019-01-09 11:52
*/
@Service
public class AccountSaleInvoiceServiceImpl extends BaseService<AccountSaleInvoice> implements IAccountSaleInvoiceService {
@Autowired
AccountSaleInvoiceMapper mapper;
@Override
public List<AccountSaleInvoice> listAccountSaleInvoiceByCustomer(String cusotmerNo) {
try {
return mapper.listAccountSaleInvoiceByCustomer(cusotmerNo);
}catch (Exception e){
return null;
}
}
@Override
public List<AccountSaleInvoice> listNotRushAccountSaleInvoice(String customerNo) {
try {
return mapper.listNotRushAccountSaleInvoice(customerNo);
}catch (Exception e){
return null;
}
}
@Override
public String getMaxOrderNo() {
try {
return mapper.getMaxOrderNo();
}catch (Exception e){
return null;
}
}
@Override
public List<AccountSaleInvoice> listOrderNoLike(String orderNo) {
try {
return mapper.listOrderNoLike(orderNo);
}catch (Exception e){
return null;
}
}
@Override
public List<AccountSaleInvoice> listAccountSaleInvoice() {
try {
return mapper.listAccountSaleInvoice("");
}catch (Exception e){
return null;
}
}
@Override
public AccountSaleInvoice getByOrderNo(String orderno) {
try {
return mapper.getByOrderNo(orderno);
}catch (Exception e){
return null;
}
}
@Override
public List<AccountSaleInvoice> listAccountSaleInvoice(String text,int page, int rows) {
try {
PageHelper.startPage(page, rows);
return mapper.listAccountSaleInvoice(text);
}catch (Exception e){
return null;
}
}
@Override
public List<AccountSaleInvoice> listAccountSaleInvoiceNotSh() {
try {
return mapper.listAccountSaleInvoiceNotSh();
}catch (Exception e){
return null;
}
}
}
|
package utils;
import com.github.javafaker.Faker;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class TestData {
static Faker faker = new Faker();
static String[] genderList = {"Male", "Female", "Other"};
static Random random = new Random();
public String firstName = faker.name().firstName();
public String lastName = faker.name().lastName();
public String cellPhone = "1234567890";
public String emailAddress = faker.internet().emailAddress();
public String gender = genderList[random.nextInt(genderList.length-1)];
public String[] dateOfBirth = ("30 April 2001").split(" ");
public String[] subjects = {"Maths", "Chemistry"};
public String[] hobbys = {"Sports", "Music"};
public String picPath = "pic.png";
public String currentAddress = faker.address().fullAddress();
public String state = "NCR";
public String city = "Noida";
public Map<String,String> expectedData = new HashMap<String,String>()
{{
put("Student Name", firstName + " " + lastName);
put("Student Email", emailAddress);
put("Gender", gender);
put("Mobile", cellPhone);
put("Date of Birth", dateOfBirth[0] + " " + dateOfBirth[1] +"," + dateOfBirth[2]);
put("Subjects", subjects[0] +", " + subjects[1]);
put("Hobbies", hobbys[0] + ", " + hobbys[1]);
put("Picture", picPath);
put("Address", currentAddress);
put("State and City", state + " " + city);
}};
} |
package baek8958;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {//완료
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int how = Integer.parseInt(br.readLine());
for (int j = 0; j < how; j++) {
String str = br.readLine(); //이건 한번딱 받아서 하는거 인풋으로 몇번 받을지 받는 식도 만들자
int count = 0;
int temp = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'O') {
count++;
temp += count;
} else if (str.charAt(i) == 'X') {
count = 0;
}
}
System.out.println(temp);
}
}
}
|
package com.uog.miller.s1707031_ct6039.servlets.homework;
import com.uog.miller.s1707031_ct6039.beans.CalendarItemBean;
import com.uog.miller.s1707031_ct6039.beans.HomeworkBean;
import com.uog.miller.s1707031_ct6039.beans.SubmissionBean;
import com.uog.miller.s1707031_ct6039.oracle.CalendarConnections;
import com.uog.miller.s1707031_ct6039.oracle.HomeworkConnections;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.log4j.Logger;
@MultipartConfig
@WebServlet(name = "SubmitHomework")
public class SubmitHomework extends HttpServlet
{
static final Logger LOG = Logger.getLogger(SubmitHomework.class);
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
LOG.debug("Attempting to Submit Homework (child upload homework) for Class");
String email = request.getParameter("email");
String homeworkId = request.getParameter("homeworkId");
String dateSubmitted = request.getParameter("today");
try
{
Part filePart = request.getPart("homeworkFile");
String filename = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
InputStream inputStream = filePart.getInputStream();
HomeworkConnections connections = new HomeworkConnections();
SubmissionBean bean = new SubmissionBean();
bean.setEmail(email);
bean.setEventId(homeworkId);
bean.setSubmissionDate(dateSubmitted);
String result = connections.submitHomeworkTask(bean, inputStream, filename);
//Remove calendar event for child after submitting
HomeworkBean homeworkBean = connections.getHomeworkTaskFromId(homeworkId);
CalendarConnections calendarConnections = new CalendarConnections();
List<CalendarItemBean> allCalendarItemsForUser = calendarConnections.getAllCalendarItemsForUser(email);
for (CalendarItemBean calendarItemBean : allCalendarItemsForUser)
{
if(calendarItemBean.getEventName().equals("HW: "+homeworkBean.getName()))
{
calendarConnections.deleteEvent(calendarItemBean.getEventId());
}
}
//Remove alerts and redirect after submitting to DB
removeAlerts(request);
//Repopulate Homework and submissions
List<HomeworkBean> allHomeworkForChild = connections.getAllHomeworkForChild(email);
List<SubmissionBean> allHomeworkSubmissionsForChild = connections.getAllHomeworkSubmissionsForChild(email);
if(!allHomeworkForChild.isEmpty())
{
request.getSession(true).setAttribute("allHomeworks", allHomeworkForChild);
}
if(!allHomeworkSubmissionsForChild.isEmpty())
{
request.getSession(true).setAttribute("allSubmissions", allHomeworkSubmissionsForChild);
}
redirectAfterSubmission(response, request, result);
}
catch (IOException | ServletException e)
{
LOG.error("Error retrieving uploaded file", e);
redirectAfterSubmissionFailure(response, request);
}
}
private void redirectAfterSubmission(HttpServletResponse response, HttpServletRequest request, String result)
{
request.getSession(true).setAttribute("formSuccess", result);
try
{
response.sendRedirect(request.getContextPath() + "/jsp/actions/homework/viewhomework.jsp");
}
catch (IOException e)
{
LOG.error(result,e);
}
}
private void redirectAfterSubmissionFailure(HttpServletResponse response, HttpServletRequest request)
{
request.getSession(true).setAttribute("formError", "Unknown error");
try
{
response.sendRedirect(request.getContextPath() + "/jsp/actions/homework/uploadhomework.jsp");
}
catch (IOException e)
{
LOG.error("Unknown error",e);
}
}
private void removeAlerts(HttpServletRequest request)
{
request.getSession(true).removeAttribute("formErrors");
request.getSession(true).removeAttribute("formSuccess");
}
} |
/*
* Copyright (c) 2020 Markus Neifer
* Licensed under the MIT License.
* See file LICENSE in parent directory of project root.
*/
/**
* Package with code examples.
*/
package de.mneifercons.examples;
|
package fr.eni.cach.clinique.bo;
public class Admin extends Personnel {
public Admin() {
// TODO Auto-generated constructor stub
}
public Admin(int codePersonnel, String nom, String motPasse, String role, boolean archive) {
super(codePersonnel, nom, motPasse, role, archive);
// TODO Auto-generated constructor stub
}
public Admin(String nom, String motPasse, String role, boolean archive) {
super(nom, motPasse, role, archive);
// TODO Auto-generated constructor stub
}
}
|
public class FirstFigure {
public static void main(String[] args){
int sizeFig = 9; //Write your own size(3,5,7,9...)
for(int i=0; i < sizeFig; i++) {
for(int k = 0; k < sizeFig; k++) {
if( k == sizeFig - (sizeFig/2) - i - 1 || k == (sizeFig/2) + i ||
(i > (sizeFig/2) - 1 && k == sizeFig + (sizeFig/2) - i - 1 ) ||
(i > (sizeFig/2) - 1 && k == (sizeFig/2) - sizeFig + i + 1) )
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
|
package com.mindstatus.module;
import java.util.List;
import com.mindstatus.module.MsUser;
public interface IMsUserDao
{
List<MsUser> findByUserName(String userName);
void saveOrUpdate(MsUser msUser);
void delete(MsUser msUser);
}
|
package com.ipincloud.iotbj.srv.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Date;
import java.sql.Timestamp;
import com.alibaba.fastjson.annotation.JSONField;
//(Role)角色
//generate by redcloud,2020-07-24 19:59:20
public class Role implements Serializable {
private static final long serialVersionUID = 46L;
// 自增ID
private Long id ;
// 角色名称
private String title ;
// 是否编辑
@JSONField(name = "is_edit")
private String isEdit ;
// 排序
private Integer sort ;
// 角色描述
private String memo ;
// 版本锁
private Integer version ;
// 添加时间
private Long addtime ;
// 是否启用
private String enable ;
private String thirdUUID;
public Long getId() {
return id ;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title ;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsEdit() {
return isEdit ;
}
public void setIsEdit(String isEdit) {
this.isEdit = isEdit;
}
public Integer getSort() {
return sort ;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public String getMemo() {
return memo ;
}
public void setMemo(String memo) {
this.memo = memo;
}
public Integer getVersion() {
return version ;
}
public void setVersion(Integer version) {
this.version = version;
}
public Long getAddtime() {
return addtime ;
}
public void setAddtime(Long addtime) {
this.addtime = addtime;
}
public String getEnable() {
return enable ;
}
public void setEnable(String enable) {
this.enable = enable;
}
public String getThirdUUID(){
return thirdUUID;
}
public void setThirdUUID(String thirdUUId){
this.thirdUUID = thirdUUID;
}
}
|
package com.jaren.easytranslate.service;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.jaren.easytranslate.R;
public class UiService extends Service {
private static final String TAG = "UiService";
private WindowManager windowManager;
private WindowManager.LayoutParams wmParams;
private LinearLayout linearLayout;
private int layoutHeight = 0;
private int layoutWidth = 0;
private int wmXMin = 0;
private int wmXMax = 0;
private int wmYMin = 0;
private int wmYMax = 0;
private int imgWidth = 0;
private int imgHeight = 0;
private float touchX = 0;
private float touchY = 0;
ImageView imageView = null;
// 状态栏的高度
private int statusBarHeight = 56;//wonder how to get statusbar's height!!!
private boolean getSize = false;
public UiService() {
}
@Override
public void onCreate() {
super.onCreate();
createWindow();
if (imageView != null){
setImgTouchListener();
}
}
private void setImgTouchListener() {
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN: {
Log.d(TAG, "imageView get touch down!");
imageView.setBackgroundResource(R.mipmap.ic_light);
}
break;
case MotionEvent.ACTION_MOVE: {
Log.d(TAG, "imageView get touch move!");
updateWinManager(event);
}
break;
case MotionEvent.ACTION_UP: {
Log.d(TAG, "imageView get touch up!");
imageView.setBackgroundResource(R.mipmap.ic_mask);
}
break;
default: {
Log.e(TAG, "imageview get unkown touch event!");
}
break;
}
return true;
}
});
}
private void updateWinManager(MotionEvent event) {
//x---48
//y
//|
//|
//48
//new axes, 向量运算
// let the image always behind finger
// solution 1.
this.touchX = (event.getRawX() - imgWidth / 2) + wmXMin;
this.touchY = (event.getRawY() - imgHeight / 2) + wmYMin;
wmParams.x = (int) this.touchX;
wmParams.y = (int) this.touchY;
// solution 2.
// float imgX = event.getX();
// float imgY = event.getY();
// wmParams.x = (int) (wmParams.x + (imgX - imgWidth/2));
// wmParams.y = (int) (wmParams.y + (imgY - imgHeight/2));
//how about out of phone player size?
// if using solution 2, this control must have
// if (wmParams.x < wmXMin){
// wmParams.x = wmXMin;
// }else if (wmParams.x > wmXMax){
// wmParams.x = wmXMax;
// }
// if (wmParams.y < wmYMin){
// wmParams.y = wmYMin;
// }else if (wmParams.y > wmYMax){
// wmParams.y = wmYMax;
// }
windowManager.updateViewLayout(linearLayout, wmParams);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Toast.makeText(this,"toast on service: service on startCommand!",Toast.LENGTH_LONG).show();
return START_REDELIVER_INTENT;
}
private void createWindow() {
windowManager = (WindowManager) getApplicationContext().getSystemService(getApplicationContext().WINDOW_SERVICE);
wmParams = new WindowManager.LayoutParams();
wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
wmParams.format = PixelFormat.RGBA_8888;
// get screen size of phone, and set the right place of window
Display defDisplay = windowManager.getDefaultDisplay();
final DisplayMetrics metrics = new DisplayMetrics();
defDisplay.getMetrics(metrics);
layoutHeight = metrics.heightPixels;
layoutWidth = metrics.widthPixels;
LayoutInflater inflater = LayoutInflater.from(getApplication());
linearLayout = (LinearLayout) inflater.inflate(R.layout.window_main,null);
// get window measure
imageView = (ImageView) linearLayout.findViewById(R.id.ic_win);
imageView.setBackgroundResource(R.mipmap.ic_mask);
// this listener will be called two times when windows create, and I don't know why.
imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (getSize == false){
imgHeight = imageView.getWidth();
imgWidth = imageView.getHeight();
Log.d(TAG, "onGlobalLayout: " + "layoutWidth==" + layoutWidth + " layoutHeight==" + layoutHeight );
wmXMin = -layoutWidth/2 + imgWidth/2;
wmXMax = layoutWidth/2 - imgWidth/2;
wmYMin = (-layoutHeight - statusBarHeight)/2 + imgHeight/2;
wmYMax = (layoutHeight - statusBarHeight)/2 - imgHeight/2;
getSize = true;
}
}
});
// here is right & middle of the phone screen
wmParams.x = Gravity.END;
// wmParams.y = (wmYMax + wmYMin)/2;//middle position
windowManager.addView(linearLayout, wmParams);
// how can I get the move event?
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
|
package org.usfirst.frc.team226.robot.subsystems;
import org.usfirst.frc.team226.robot.RobotMap;
import org.usfirst.frc.team226.robot.commands.WinchServoDoNothing;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
*/
public class WinchServo extends Subsystem {
Servo servo = new Servo(RobotMap.WINCH_SERVO);
public boolean toggle = false;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
setDefaultCommand(new WinchServoDoNothing());
}
public void doNothing() {
servo.setAngle(servo.getAngle());
}
public void forward(){
servo.setAngle(90);
}
public void reverse() {
servo.setAngle(0);
}
public double getAngle() {
return servo.getAngle();
}
}
|
package com.example.elearning.rest;
public class formateurRestController {
//TODO Controller's Mapping and Service Methodes
}
|
package Utilities;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class FileReader{
public static void main(String[] args) throws IOException {
Properties configValues = new Properties();
Properties demoInputControlsAndValues = new Properties();
InputStream config = FileReader.class.getClassLoader().
getResourceAsStream("Config.properties");
InputStream demoInputControlsAndValuesStream = FileReader.class.getClassLoader().
getResourceAsStream("DemoInputControlsAndValues.properties");
configValues.load(config);
demoInputControlsAndValues.load(demoInputControlsAndValuesStream);
}
} |
package com.codigo.smartstore.sdk.core.constans;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Klasa dostarcza wartości domyślne dla podstawowych typów klas dostępnych na23
* platformie JVM.
*
* @author andrzej.radziszewski
* @version 1.0.0.0
* @since 2017
* @category constant
*/
public final class Default {
/**
* Definicja domyślnych wartości dla typów klas platforny JVM.
*/
private static final Map<Class<?>, Object> DEFAULTS;
/**
* Domyślny statyczny konstruktor obiektu klasy <code>Default</code>.
*/
static {
DEFAULTS = new HashMap<>();
DEFAULTS.put(
Boolean.class, Boolean.valueOf(false));
DEFAULTS.put(
boolean.class, false);
DEFAULTS.put(
Character.class, '\u0000');
DEFAULTS.put(
char.class, '\u0000');
DEFAULTS.put(
String.class, Default.EMPTY);
DEFAULTS.put(
Byte.class, Byte.valueOf((byte) 0));
DEFAULTS.put(
byte.class, (byte) 0);
DEFAULTS.put(
Short.class, Short.valueOf((short) 0));
DEFAULTS.put(
short.class, 0);
DEFAULTS.put(
Integer.class, Integer.valueOf(0));
DEFAULTS.put(
int.class, 0);
DEFAULTS.put(
BigInteger.class, BigInteger.valueOf(0));
DEFAULTS.put(
Long.class, Long.valueOf(0));
DEFAULTS.put(
long.class, 0L);
DEFAULTS.put(
Float.class, Float.valueOf(0));
DEFAULTS.put(
float.class, .0);
DEFAULTS.put(
Double.class, Double.valueOf(.0));
DEFAULTS.put(
double.class, .0);
DEFAULTS.put(
BigDecimal.class, BigDecimal.valueOf(0));
DEFAULTS.put(
Enum.class, Enum.valueOf(DefaultEnum.class, "ZERO"));
DEFAULTS.put(
Object.class, Default.NULL);
}
/**
* Definicja domyślnego typu klasy Enum.
*/
private enum DefaultEnum {
ZERO
}
/**
* Domyślna wartość dla typów ciągu znaków
*/
private static final String EMPTY = "";
/**
* Domyślna wartość dla obiektów bez instancji
*/
private static final Object NULL = null;
/**
* Metoda dostarcza domyślną wartość dla wskazanego typu obiektu klasy.
*
* @param <T> Generyczna klasa typu
* @param type Klasa typu danych
*
* @return Domyślna wartość obiektu danej klasy
*/
public static <T> T zero(@NonNull final Class<T> type) {
@SuppressWarnings("unchecked")
final T instance = (type.isPrimitive()) ? (T) DEFAULTS.get(type) : type.cast(DEFAULTS.get(type));
return instance;
}
}
|
package com.javaee.ebook1.service.impl;
import com.javaee.ebook1.common.exception.OpException;
import com.javaee.ebook1.mybatis.vo.BookVO;
import com.javaee.ebook1.service.FileService;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import static org.junit.jupiter.api.Assertions.*;
class FileServiceImplTest {
@Autowired
FileService fileservice;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@Before
public void setUp(){
request = new MockHttpServletRequest();
request.setCharacterEncoding("UTF-8");
response = new MockHttpServletResponse();
}
@Test
void getPDF() {
}
@Test
void getLog() {
}
@Test
void addBook() throws OpException {
BookVO book = new BookVO();
book.setDescr("aa");
book.setBookName("bb");
book.setBid(1);
book.setAuthor("CC");
fileservice.addBook(book, request);
}
} |
package cn.mldn.eusplatform.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import cn.mldn.eusplatform.vo.Schedule;
import cn.mldn.util.dao.IBaseDAO;
public interface IScheduleDAO extends IBaseDAO<Long, Schedule> {
/**
* 获得指定sid 的ecount
* @param sid
* @return
* @throws SQLException
*/
public boolean increaseEcount(Long sid)throws SQLException;
/**
* 增加调度的雇员
* @param meid 调度申请的ID
* @param eid 需要调度的人
* @param sid 调度编号
* @return 增加成功返回true
* @throws SQLException
*/
public boolean doCreateEmpIntoSchedule(String eid,Long sid)throws SQLException;
/**
* 修改调度申请
* @param vo
* @return
* @throws SQLException
*/
public boolean doEditScheduleBySidAndSeid(Schedule vo)throws SQLException;
/**
* 根据Sid和 seid 查找申请调度;
* @param sid
* @param eid
* @return
* @throws SQLException
*/
public Schedule findBySidAndSeid(long sid,String eid)throws SQLException;
public List<Schedule> findAllById(String eid)throws SQLException;
/**
* 根据申请人eid 获得所有的调度申请
* @param currentPage
* @param lineSize
* @param eid
* @return
* @throws SQLException
*/
public List<Schedule> findAllById(Long currentPage, Integer lineSize,String eid) throws SQLException;
/**
* 根据申请人eid 查找 分页
* @param column
* @param keyWord
* @param currentPage
* @param lineSize
* @param eid
* @return
* @throws SQLException
*/
public List<Schedule> findSplitById(String column, String keyWord, Long currentPage, Integer lineSize,String eid)
throws SQLException;
/**
* 根据申请人eid 获得数据量
* @param eid
* @return
* @throws SQLException
*/
public Long getAllCountById(String eid) throws SQLException ;
/**
* 根据申请人eid 获得分页数量
* @param column
* @param keyWord
* @param eid
* @return
* @throws SQLException
*/
public Long getSplitCountById(String column, String keyWord,String eid) throws SQLException;
/**
* 根据Sid和 seid 删除 调度申请
* @param sid 调度申请编号
* @param seid 调度申请雇员编号
* @return 修改成功 返回true
* @throws SQLException
*/
public boolean doRemoveBySidAndSeid(long sid,String seid) throws SQLException;
/**
* 进行调度申请的提交
* 状态由 0 (未提交)改变成3(待审核)
*/
public boolean doEditAuditBySidAndSeid(long sid,String seid) throws SQLException;
public List<Schedule> findAllByAuditAndSid(Set<Long> sid,Set<Integer> ids) throws SQLException ;
/**
* 根据审核标记和sid列出所有的调度安排并分页
* @param currentPage 当前页
* @param lineSize 每页的行数
* @param sid 以set集合保存的sid表示的是该雇员的调度安排
* @param ids 审核标记id,以set集合保存
* @return 调度安排集合
* @throws SQLException SQL
*/
public List<Schedule> findAllByAuditAndSid(Long currentPage, Integer lineSize,Set<Long> sid,Set<Integer> ids) throws SQLException ;
/**
* 根据审核标记和sid列出所有的调度安排并模糊分页
* @param column 模糊查询的列
* @param keyWord 模糊查询的关键字
* @param currentPage 当前页
* @param lineSize 每页的行数
* @param sid 以set集合保存的sid表示的是该雇员的调度安排
* @param ids 审核标记id,以set集合保存
* @return 调度安排集合
* @throws SQLException SQL
*/
public List<Schedule> findSplitByAuditAndSid(String column, String keyWord, Long currentPage, Integer lineSize,Set<Long> sid,Set<Integer> ids) throws SQLException ;
/**
* 根据审核标记和sid取得该标记下的所有记录数
* @param sid 以set集合保存的sid表示的是该雇员的调度安排
* @param ids 审核标记id,以set集合保存
* @return 记录数
* @throws Exception SQL
*/
public Long getAllCount(Set<Long> sid,Set<Integer> ids) throws Exception ;
/**
* 根据审核标记、sid和模糊查询取得所有记录数
* @param column 模糊查询的行
* @param keyWord 模糊查询的关键字
* @param sid 以set集合保存的sid表示的是该雇员的调度安排
* @param ids 审核标记id,以set集合保存
* @return 记录数
* @throws Exception SQL
*/
public Long getSplitCount(String column,String keyWord,Set<Long> sid,Set<Integer> ids) throws Exception ;
/**
* 根据编号修改状态,将本来是未报告的改为已完成
* 状态由 1 (任务进行中)改变成4(待提交报告)//rll ReportServiceBackImpl add()方法
* 状态由 4 (待提交报告)改变成5(任务已完成)//hh SchedulePersonalTaskAction prepare()方法
* @param sid 编号状态
* @return 修改成功返回true,否则返回false
* @throws Exception SQL
*/
public boolean editAuditBySid(Long sid,Integer audit) throws Exception ;
}
|
package com.example.vmac.WatBot;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import org.jsoup.Jsoup;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import static android.content.ContentValues.TAG;
public class FileViewer extends AppCompatActivity {
private String pdfUrl;
public String fileData;
TextToSpeech t1;
Context mcontext;
public void speakUp(String txt) {
t1=new TextToSpeech(mcontext, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.UK);
}
}
});
String toSpeak = txt;
Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_viewer);
mcontext = getApplicationContext();
pdfUrl = getIntent().getExtras().getString("url");
WebView webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.setWebViewClient(new Callback());
webView.loadUrl(
"http://docs.google.com/gview?embedded=true&url=" + pdfUrl);
String myUrl = "http://10.0.2.2:5000/";
String result;
HttpGetRequest getRequest = new HttpGetRequest();
try {
result = getRequest.execute(myUrl).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
private class Callback extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(
WebView view, String url) {
return (false);
}
}
}
class HttpGetRequest extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
@Override
protected String doInBackground(String... params){
String stringUrl = params[0];
String result;
String inputLine;
try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
//Create a connection
HttpURLConnection connection =(HttpURLConnection)
myUrl.openConnection();
//Set methods and timeouts
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
//Connect to our url
connection.connect();
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
//Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
//Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
//Set our result equal to our stringBuilder
result = stringBuilder.toString();
Log.i(TAG,result+"sasasasa");
}
catch(IOException e){
e.printStackTrace();
result = null;
}
return result;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
|
package examples.basic;
/**
* Created by ceruleanhu on 5/15/14.
*/
public enum StreamingEventType {
PUBLIC_TICK, PUBLIC_ORDER_BOOK, PUBLIC_TRADES, PRIVATE;
public static String getEventName(StreamingEventType streamingEventType){
String eventName="";
switch (streamingEventType){
case PUBLIC_TICK:
eventName = "public/tick/";
break;
case PUBLIC_ORDER_BOOK:
eventName = "public/orderBook/";
break;
case PUBLIC_TRADES:
eventName = "public/trades/";
break;
case PRIVATE:
eventName = "private";
break;
}
return eventName;
}
}
|
package com.projectapi.thermometerapi;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Created by s161473 on 22-6-2017.
*/
public class WeekProgram implements Serializable {
public static final String DEFAULT_NAME = "New Weekprogram";
public WeekProgram() {
this.name = DEFAULT_NAME;
}
public WeekProgram(String name) {
this.name = name;
}
public String name;
public double dayTemperature, nightTemperature;
public Map<WeekDay, Switch[]> weekDaySwitchMap = new HashMap<>();
public void setName(String Name) { name = Name;}
public String getName(){return name;}
public WeekProgram getCopy() {
WeekProgram copy = new WeekProgram(name);
copy.dayTemperature = dayTemperature;
copy.nightTemperature = nightTemperature;
copy.weekDaySwitchMap = new HashMap<>();
for(WeekDay day : weekDaySwitchMap.keySet()) {
Switch[] oldSwitches = weekDaySwitchMap.get(day);
Switch[] newSwitches = new Switch[oldSwitches.length];
for(int i = 0; i < oldSwitches.length; i++) {
newSwitches[i] = oldSwitches[i].getCopy();
}
copy.weekDaySwitchMap.put(day, newSwitches);
}
return copy;
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
|
package com.amplify.ap.domain;
public enum TemplateInstanceStatus {
CREATING, READY, FAILED, DELETING, DELETED
}
|
package com.tntdjs.midi.actions;
public class MidiActionTypes {
public static final String bridge = "play";
public static final String audio = "midicc";
public static final String cmd = "cmd";
public static final String key = "key";
}
|
package com.zqs.web.user;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zqs.model.user.UserInfo;
import com.zqs.service.user.IUserService;
import com.zqs.utils.json.JacksonUtils;
@Controller
@RequestMapping(value="user")
public class UserController {
@Autowired
private IUserService userService;
/**
* 登录页面
*
* @return String
*/
@RequestMapping(value="/login",method=RequestMethod.GET)
public String login(){
return "user/login";
}
/**
* 登录认证
*
* @param 用户名、密码
* @return String
*/
@RequestMapping(value="/signin",method=RequestMethod.POST)
@ResponseBody
public String signin(@RequestBody String parameters){
UserInfo user = (UserInfo)JacksonUtils.json2object(parameters, UserInfo.class);
return userService.signin(user);
}
/**
* 退出登录
*
* @return String
*/
@RequestMapping(value="/logout",method=RequestMethod.GET)
public String logout(){
Subject subject = SecurityUtils.getSubject();
if(subject.isAuthenticated()){
subject.logout();
}
return "redirect:/index/";
}
}
|
package Service_Layer;
public class LogAndExitController extends LogicManagement{
//יש לבדוק בכל שלב שה-Current עם השם משתמש והסיסמא הנכונים
public boolean Login(String arg_user_name, String arg_password){
// בדיקה אם המנוי קיים ואם כן לחבר אותו למערכת
//עדכון ה-Current
return true;
}
public boolean Exit(String arg_user_name, String arg_password){
Current = null;
return true;
}
public boolean remove_all_subscription(){
// צריך לבדוק שהיוזר הוא מנהל מערכת
return true;
}
}
|
package com.rednovo.libs.net.okhttp.utils;
public class Exceptions {
public static void illegalArgument(String msg) {
throw new IllegalArgumentException(msg);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ArRadioButtonsScratch;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
/**
*
* @author burtm5944
*/
public class PanMain extends JPanel {
JRadioButton[] radioButton = new JRadioButton[4];
public PanMain() {
radioButton[0] = new JRadioButton("Question A");
radioButton[1] = new JRadioButton("Question B");
radioButton[2] = new JRadioButton("Question C");
radioButton[3] = new JRadioButton("Question D");
ButtonGroup bG = new ButtonGroup();
for (int i = 0; i < radioButton.length;i++){
bG.add(radioButton[i]);
this.add(radioButton[i]);
}
}
}
|
package com.jfluent.function.composite;
import com.jfluent.container.Result;
/**
* Created by nestorsokil on 17.04.2017.
*/
@FunctionalInterface
public interface OneToResult<T, R> {
Result<R> apply(T t);
}
|
package com.eegeo.mapapi.services.routing;
import java.util.List;
import java.util.ArrayList;
import com.eegeo.mapapi.geometry.LatLng;
/**
* A set of parameters for a RoutingQuery.
*/
public final class RoutingQueryOptions {
class Waypoint {
public final LatLng latLng;
public final boolean isIndoors;
public final int indoorFloorId;
public Waypoint(final LatLng latLng, boolean isIndoors, int indoorFloorId) {
this.latLng = latLng;
this.isIndoors = isIndoors;
this.indoorFloorId = indoorFloorId;
}
}
private List<Waypoint> m_waypoints = new ArrayList<Waypoint>();
private OnRoutingQueryCompletedListener m_onRoutingQueryCompletedListener = null;
private TransportationMode m_transportationMode = TransportationMode.Walking;
/**
* Add an outdoor waypoint to the route.
*
* @param latLng A LatLng this route should pass through.
* @return This RoutingQueryOptions object.
*/
public RoutingQueryOptions addWaypoint(LatLng latLng) {
m_waypoints.add(new Waypoint(latLng, false, 0));
return this;
}
/**
* Add an indoor waypoint to the route.
*
* @param latLng A LatLng this route should pass through.
* @param indoorFloorId The ID of the floor this point lies on.
* @return This RoutingQueryOptions object.
*/
public RoutingQueryOptions addIndoorWaypoint(LatLng latLng, int indoorFloorId) {
m_waypoints.add(new Waypoint(latLng, true, indoorFloorId));
return this;
}
/**
* Set which mode of transport this route should use, e.g Walking, Driving.
* Driving routes are available for limited areas. Please contact support@wrld3d.com for details.
* @param transportationMode The desired transportation mode.
* @return This RoutingQueryOptions object.
*/
public RoutingQueryOptions setTransportationMode(TransportationMode transportationMode)
{
m_transportationMode = transportationMode;
return this;
}
TransportationMode getTransportationMode() { return m_transportationMode; }
List<Waypoint> getWaypoints() {
return m_waypoints;
}
/**
* Sets a listener to receive routing results when the query completes.
*
* @param onRoutingQueryCompletedListener A listener implementing the OnRoutingQueryCompletedListener interface.
* @return This RoutingQueryOptions object.
*/
public RoutingQueryOptions onRoutingQueryCompletedListener(OnRoutingQueryCompletedListener onRoutingQueryCompletedListener) {
this.m_onRoutingQueryCompletedListener = onRoutingQueryCompletedListener;
return this;
}
OnRoutingQueryCompletedListener getOnRoutingQueryCompletedListener() {
return m_onRoutingQueryCompletedListener;
}
}
|
package buscarenmatriz;
import javax.swing.JOptionPane;
public class BuscarEnMatriz {
public static void main(String[] args)throws Exception {
int tamaño = Integer.parseInt(JOptionPane.showInputDialog("Ingresa el tamaño del arreglo cuadrado: ", null));
int arreglo[][] = new int[tamaño][tamaño];
int i, j, iteracion = 1;
for (i = 0; i < tamaño; i++) {
for (j = 0; j < tamaño; j++) {
arreglo[i][j] = Leer.entero(iteracion);
iteracion++;
}
}
int buscado = Integer.parseInt(JOptionPane.showInputDialog("¿Que numero seseas Buscar?", null));
String coincidencias="";
for (i = 0; i < tamaño; i++) {
for (j = 0; j < tamaño; j++) {
if(arreglo[i][j] == buscado){
coincidencias = coincidencias + "["+(i)+"],["+(j)+"]\n";
}
}
}
JOptionPane.showMessageDialog(null, "Buscado esta en la(s) pocicio(es): \n"+coincidencias);
}
}
|
import java.util.*;
public class ArrayPairSum
{
public static int arrayPairSum(int[] nums)
{
Arrays.sort(nums);
int sum = 0;
for(int i = 0 ; i < nums.length-1; i= i+2){
sum = sum+nums[i];
}
return sum;
}
public static void main()
{
Scanner sc= new Scanner (System.in);
System.out.println("Enter the value of n");
int n=sc.nextInt();
int arr[]=new int[2*n];
System.out.println("Enter the 2Xn elements into the array");
for(int i=0;i<5;i++)
{
arr[i]=sc.nextInt();
}
System.out.println(arrayPairSum(arr));
}
}
|
package ProjecteProblemas;
public class Game {
Board b = new Board();
Keyboard k = new Keyboard();
void setBoard(Board board) {
b=board;
}
void setKeyboard(Keyboard keyboard) {
k=keyboard;
}
/*
public static void main(String[] args) {
Board b = new Board();
}
*/
public void gameStart(int i)
{
b.generateRandomMines();
System.out.print(b.mines_position.size());
b.calculateValue();
b.drawBoard();
while(!b.gameOver() && !b.loseGame())
{
playSquare();
b.drawBoard();
}
}
public void playSquare()
{
System.out.println("Choose: 1 -> Open Square || 2 -> Put/Remove Flag");
int typeMove = k.getInput_Gametype(b.size);
System.out.println("Enter coordinates");
Pair e = k.getPositions(b.size);
if(typeMove==1) // Open Square
{
b.openSquare(e.x-1, e.y-1);
b.recursiveOpenSquare(e.x-1, e.y-1);
}
else // Put/Remove Flag
{
b.putFlag(e.x-1, e.y-1);
}
}
public void initializeBoard(int difficult)
{
b.setBoard(difficult);
}
}
|
class Anonymous
{
void show()
{
System.out.println("Super class method");
}
}
interface A
{
public Anonymous get();
}
class B implements A
{
public Anonymous get()
{
return new Anonymous()
{
void show()
{
System.out.println("Overridden method");
}
};
}
}
public class Problem
{
public static void main(String[] args) {
new B().get().show();
}
}
|
package ru.job4j.mathfunc;
/**
* Интерфейс свойств математической функции.
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 2018-09-12
* @since 2018-09-12
*/
public interface IFuncProps {
/**
* Получает значение свойства математической функции.
* @param name имя совйства математической функции.
* @return значение свойства математической функции.
*/
double getProp(String name);
/**
* Устанавливает свойство математической функции.
* @param name имя свойства математической функции.
* @param value значение свойства математической функции.
*/
void setProp(String name, Double value);
}
|
package by.academy.tasks.oop;
import java.util.ArrayList;
public class StudentApplication {
public static void main(String[] args) {
ArrayList <Student> students = new ArrayList <Student> ();
ArrayList <Aspirant> aspirants = new ArrayList <Aspirant> ();
students.add(new Student ("Ivan","Ivanov", 3, 5));
students.add(new Student ("Petr", "Petrov", 3, 2));
students.add(new Student ("Sidr", "Sidorov", 3, 4));
aspirants.add(new Aspirant ("Ivan","Ivanov", 3, 5, "N1"));
aspirants.add(new Aspirant ("Petr","Petrov", 3, 2, "N2"));
aspirants.add(new Aspirant ("Sidr", "Sidorov", 3, 4, "N3"));
for (int i=0; i<students.size(); i++) {
System.out.println("Размер стипендии студента " + students.get(i).lastName + ": " + students.get(i).getScholarship());
}
for (int i=0; i<aspirants.size(); i++) {
System.out.println("Размер стипендии аспиранта " + aspirants.get(i).lastName + ": " + aspirants.get(i).getScholarship());
}
}
}
|
package net.kkolyan.elements.engine.utils;
import java.io.*;
/**
* @author nplekhanov
*/
public class IOUtils {
public static String readResourceContent(String resource, String charset) {
try (InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource)) {
if (stream == null) {
throw new FileNotFoundException("can't find classpath resource: "+resource);
}
return readStreamContent(stream, charset);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private static String readStreamContent(InputStream stream, String charset) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
while (true) {
int n = stream.read(bytes);
if (n < 0) {
break;
}
buffer.write(bytes, 0, n);
}
return buffer.toString(charset);
}
public static String readFileContent(File file, String charset) {
try (InputStream stream = new BufferedInputStream(new FileInputStream(file))) {
return readStreamContent(stream, charset);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
|
package fi.hh.swd22.HHkysely;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class HhKyselyApplicationTests {
@Test
void contextLoads() {
}
}
|
package p0736;
import java.util.ArrayList;
import java.util.Collection;
public class Boat {
private ArrayList<Integer> positions;
public Boat(int start, int size) {
positions = new ArrayList<>();
for (int i = 0; i < size; i++) {
positions.add(start+i);
}
}
public boolean checkYourself(Integer position) {
return positions.remove(position);
}
public boolean isAlive() {
return !positions.isEmpty();
// return positions.size() > 0;
}
public Collection<Integer> getPositions() {
return positions;
}
}
|
package com.icanit.app_v2.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.icanit.app_v2.R;
import com.icanit.app_v2.common.IConstants;
import com.icanit.app_v2.util.AppUtil;
import com.icanit.app_v2.util.DialogUtil;
import com.icanit.app_v2.util.SharedPreferencesUtil;
public class LoginActivity extends Activity implements OnClickListener {
private int resId = R.layout.activity_login;
private Button phoneNumDisposer, passwordDisposer, register, login;
private ImageButton backButton;
private EditText phoneNum, password;
private TextView retrievePassword;
private CheckedTextView autoLogin;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(resId);
init();
bindListeners();
}
public void onResume() {
super.onResume();
restoreSetup();
}
private void init() {
phoneNumDisposer = (Button) findViewById(R.id.button1);
passwordDisposer = (Button) findViewById(R.id.button2);
register = (Button) findViewById(R.id.button3);
login = (Button) findViewById(R.id.button4);
backButton = (ImageButton) findViewById(R.id.imageButton1);
phoneNum = (EditText) findViewById(R.id.editText1);
password = (EditText) findViewById(R.id.editText2);
retrievePassword = (TextView) findViewById(R.id.textView1);
autoLogin = (CheckedTextView) findViewById(R.id.checkedTextView1);
}
private void bindListeners() {
AppUtil.bindBackListener(backButton);
AppUtil.bindEditTextNtextDisposer(phoneNum, phoneNumDisposer);
AppUtil.bindEditTextNtextDisposer(password, passwordDisposer);
retrievePassword.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(LoginActivity.this,
RetrievePasswordActivity1.class));
AppUtil.putIntoApplication(
IConstants.DESTINATION_AFTER_RETRIEVEPASSWORD,
LoginActivity.class);
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this,
RegisterActivity.class);
startActivity(intent);
AppUtil.putIntoApplication(
IConstants.DESTINATION_AFTER_REGISTER,
LoginActivity.class);
}
});
login.setOnClickListener(this);
AppUtil.setOnClickListenerForCheckedTextView(autoLogin);
}
@Override
protected void onNewIntent(Intent intent) {
if (AppUtil.getLoginUser() != null)
finish();
}
private void restoreSetup() {
phoneNum.setText(null);
SharedPreferencesUtil share = AppUtil
.getSharedPreferencesUtilInstance();
String phone = share.getReservedUserInfo(IConstants.PHONE);
String password = share.getReservedUserInfo(IConstants.PASSWORD);
String autoLogin = share.getReservedUserInfo(IConstants.AUTO_LOGIN);
if (phone != null)
this.phoneNum.setText(phone);
if (password != null && autoLogin != null && "true".equals(autoLogin)) {
this.password.setText(password);
this.autoLogin.setChecked(true);
}
}
private void saveSetup(String phone, String pwd, boolean autoLogin) {
AppUtil.getSharedPreferencesUtilInstance().saveLoginUserInfo(phone,
pwd, autoLogin);
}
@Override
public void onClick(View v) {
final String phoneTx = phoneNum.getText().toString();
final String passwordTx = password.getText().toString();
if (!AppUtil.isPhoneNum(phoneTx)) {
Toast.makeText(this, "无效格式号码", Toast.LENGTH_LONG).show();
return;
} else if (!AppUtil.isPassword(passwordTx)) {
Toast.makeText(this, "密码格式错误", Toast.LENGTH_LONG).show();
return;
}
DialogUtil.loginFlow(LoginActivity.this, phoneTx, passwordTx, autoLogin.isChecked(), new Runnable(){
public void run(){
setResult(12, new Intent().putExtra("key", "loginActivity"));
LoginActivity.this.finish();
}
});
}
}
|
package com.planificateurvoyage.ui.activite;
import java.awt.Font;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
public class ActiviteCreationVoyagePanel extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
public ActiviteCreationVoyagePanel() {
setLayout(null);
JLabel lblTitre = new JLabel("Création d'une activité");
lblTitre.setBounds(125, 5, 200, 25);
lblTitre.setFont(new Font("Tahoma", Font.PLAIN, 20));
add(lblTitre);
JLabel lblNewLabel = new JLabel("categorie");
lblNewLabel.setBounds(28, 50, 70, 14);
add(lblNewLabel);
JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Transport", "H\u00E9bergement", "Restauration", "Loisir"}));
comboBox.setBounds(108, 41, 109, 22);
add(comboBox);
JLabel lblNewLabel_1 = new JLabel("libell\u00E9");
lblNewLabel_1.setBounds(28, 75, 70, 14);
add(lblNewLabel_1);
textField = new JTextField();
textField.setBounds(108, 72, 86, 20);
add(textField);
textField.setColumns(10);
JLabel lblNewLabel_2 = new JLabel("adresse");
lblNewLabel_2.setBounds(28, 100, 70, 14);
add(lblNewLabel_2);
textField_1 = new JTextField();
textField_1.setBounds(108, 97, 241, 20);
add(textField_1);
textField_1.setColumns(10);
JLabel lblNewLabel_3 = new JLabel("cout");
lblNewLabel_3.setBounds(28, 125, 70, 14);
add(lblNewLabel_3);
textField_2 = new JTextField();
textField_2.setBounds(108, 122, 86, 20);
add(textField_2);
textField_2.setColumns(10);
JLabel lblNewLabel_4 = new JLabel("Euros");
lblNewLabel_4.setBounds(203, 125, 46, 14);
add(lblNewLabel_4);
JLabel lblNewLabel_5 = new JLabel("Description");
lblNewLabel_5.setBounds(28, 150, 70, 14);
add(lblNewLabel_5);
JTextArea textArea = new JTextArea();
textArea.setBounds(108, 153, 241, 68);
add(textArea);
JLabel lblNewLabel_6 = new JLabel("Date d\u00E9but");
lblNewLabel_6.setBounds(28, 240, 70, 14);
add(lblNewLabel_6);
textField_3 = new JTextField();
textField_3.setBounds(108, 237, 124, 20);
add(textField_3);
textField_3.setColumns(10);
JButton btnNewButton_2 = new JButton("D");
btnNewButton_2.setBounds(242, 236, 27, 23);
add(btnNewButton_2);
JLabel lblNewLabel_7 = new JLabel("Date fin");
lblNewLabel_7.setBounds(28, 265, 46, 14);
add(lblNewLabel_7);
textField_4 = new JTextField();
textField_4.setBounds(108, 268, 124, 20);
add(textField_4);
textField_4.setColumns(10);
JButton btnNewButton_3 = new JButton("D");
btnNewButton_3.setBounds(242, 269, 27, 18);
add(btnNewButton_3);
JButton btnNewButton = new JButton("Valider");
btnNewButton.setBounds(160, 328, 89, 23);
add(btnNewButton);
JButton btnNewButton_1 = new JButton("Annuler");
btnNewButton_1.setBounds(259, 328, 89, 23);
add(btnNewButton_1);
JCheckBox chckbxNewCheckBox = new JCheckBox("forfaitaire");
chckbxNewCheckBox.setBounds(242, 121, 97, 23);
add(chckbxNewCheckBox);
}
}
|
package com.javatutorial.MethodOverloading;
public class FeetInchToCentimeterConverter {
static final double FOOTTOINCH = 12.00;
static final double INCHTOCENT = 2.54;
public static void main(String[] args) {
System.out.println(calcFeetAndInchesToCentimeter(6,0));
System.out.println(calcFeetAndInchesToCentimeter(72));
}
public static double calcFeetAndInchesToCentimeter(double feet, double inches){
if(feet<0 || inches<0 || inches>12){
return -1;
}
double totalInches = feet*FOOTTOINCH+inches;
double result = totalInches*INCHTOCENT;
return result;
}
public static double calcFeetAndInchesToCentimeter(double inches){
if(inches<0){
return -1;
}
double totalFeet = (int)(inches/FOOTTOINCH);
double totalInches = inches%FOOTTOINCH;
System.out.println("Total Feet = "+totalFeet);
System.out.println("Total Inches = "+totalInches);
double result = calcFeetAndInchesToCentimeter(totalFeet,totalInches);
return result;
}
}
|
package android.support.v4.app;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompatBase.Action;
import android.support.v4.app.NotificationCompatBase.Action.Factory;
import android.support.v4.app.RemoteInputCompatBase.RemoteInput;
import android.util.SparseArray;
import android.widget.RemoteViews;
import java.util.ArrayList;
import java.util.List;
@RequiresApi(19)
class NotificationCompatKitKat {
public static class Builder implements NotificationBuilderWithBuilderAccessor, NotificationBuilderWithActions {
private android.app.Notification.Builder b;
private List<Bundle> mActionExtrasList = new ArrayList();
private RemoteViews mBigContentView;
private RemoteViews mContentView;
private Bundle mExtras;
public Builder(Context context, Notification notification, CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3, RemoteViews remoteViews, int i, PendingIntent pendingIntent, PendingIntent pendingIntent2, Bitmap bitmap, int i2, int i3, boolean z, boolean z2, boolean z3, int i4, CharSequence charSequence4, boolean z4, ArrayList<String> arrayList, Bundle bundle, String str, boolean z5, String str2, RemoteViews remoteViews2, RemoteViews remoteViews3) {
PendingIntent pendingIntent3;
Notification notification2 = notification;
ArrayList<String> arrayList2 = arrayList;
Bundle bundle2 = bundle;
String str3 = str;
String str4 = str2;
boolean z6 = false;
boolean z7 = true;
android.app.Notification.Builder deleteIntent = new android.app.Notification.Builder(context).setWhen(notification2.when).setShowWhen(z2).setSmallIcon(notification2.icon, notification2.iconLevel).setContent(notification2.contentView).setTicker(notification2.tickerText, remoteViews).setSound(notification2.sound, notification2.audioStreamType).setVibrate(notification2.vibrate).setLights(notification2.ledARGB, notification2.ledOnMS, notification2.ledOffMS).setOngoing((notification2.flags & 2) != 0 ? z7 : z6).setOnlyAlertOnce((notification2.flags & 8) != 0 ? z7 : z6).setAutoCancel((notification2.flags & 16) != 0 ? z7 : z6).setDefaults(notification2.defaults).setContentTitle(charSequence).setContentText(charSequence2).setSubText(charSequence4).setContentInfo(charSequence3).setContentIntent(pendingIntent).setDeleteIntent(notification2.deleteIntent);
if ((notification2.flags & 128) != 0) {
pendingIntent3 = pendingIntent2;
z6 = z7;
} else {
pendingIntent3 = pendingIntent2;
}
r0.b = deleteIntent.setFullScreenIntent(pendingIntent3, z6).setLargeIcon(bitmap).setNumber(i).setUsesChronometer(z3).setPriority(i4).setProgress(i2, i3, z);
r0.mExtras = new Bundle();
if (bundle2 != null) {
r0.mExtras.putAll(bundle2);
}
if (!(arrayList2 == null || arrayList.isEmpty())) {
r0.mExtras.putStringArray("android.people", (String[]) arrayList2.toArray(new String[arrayList.size()]));
}
if (z4) {
r0.mExtras.putBoolean("android.support.localOnly", z7);
}
if (str3 != null) {
r0.mExtras.putString("android.support.groupKey", str3);
if (z5) {
r0.mExtras.putBoolean("android.support.isGroupSummary", z7);
} else {
r0.mExtras.putBoolean("android.support.useSideChannel", z7);
}
}
if (str4 != null) {
r0.mExtras.putString("android.support.sortKey", str4);
}
r0.mContentView = remoteViews2;
r0.mBigContentView = remoteViews3;
}
public void addAction(Action action) {
this.mActionExtrasList.add(NotificationCompatJellybean.writeActionAndGetExtras(this.b, action));
}
public android.app.Notification.Builder getBuilder() {
return this.b;
}
public Notification build() {
SparseArray buildActionExtrasMap = NotificationCompatJellybean.buildActionExtrasMap(this.mActionExtrasList);
if (buildActionExtrasMap != null) {
this.mExtras.putSparseParcelableArray("android.support.actionExtras", buildActionExtrasMap);
}
this.b.setExtras(this.mExtras);
Notification build = this.b.build();
if (this.mContentView != null) {
build.contentView = this.mContentView;
}
if (this.mBigContentView != null) {
build.bigContentView = this.mBigContentView;
}
return build;
}
}
NotificationCompatKitKat() {
}
public static Action getAction(Notification notification, int i, Factory factory, RemoteInput.Factory factory2) {
Notification.Action action = notification.actions[i];
SparseArray sparseParcelableArray = notification.extras.getSparseParcelableArray("android.support.actionExtras");
return NotificationCompatJellybean.readAction(factory, factory2, action.icon, action.title, action.actionIntent, sparseParcelableArray != null ? (Bundle) sparseParcelableArray.get(i) : null);
}
}
|
package dsp;
public class MyHashTable {
MyLList[] llists = new MyLList[100];
int count = 0;
MyHashTable() {
for (int i = 0; i < llists.length; i++) {
llists[i] = new MyLList();
}
}
int getHashIndex(int key) {
return key;
}
void insert(int key) {
int idx = getHashIndex(key);
llists[idx].insert(key);
}
boolean isPresentKey(int key) {
for(MyLList ll : llists) {
if(ll.isPresentKey(key) == true)
return true;
}
return false;
}
void print() {
for(MyLList ll : llists) {
ll.print();
}
}
}
|
package classes;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class Liste {
@Autowired
private PersonneRepository rp;
@GetMapping("/liste")
public String accueil(@RequestParam(name = "name", required = false, defaultValue = "World") String name,
Model model, HttpSession session) {
model.addAttribute("pers", this.listAll());
return "liste";
}
public List<Personne> listAll() {
List<Personne> pers = new ArrayList<>();
this.rp.findAll().forEach(pers::add);
return pers;
}
}
|
package com;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LogoutServlet
*/
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LogoutServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<h1>Dashboard</h1>");
out.print("Welcome " + request.getParameter("username") + "<br/>" + "Login Successful at " + new Date()
+ "<br/>");
out.print("<a href=\"index.html\">Logout</a>");
}
}
|
package com.jxtb.test.controller;
import com.jxtb.test.entity.BaseResponse;
import com.jxtb.test.entity.UploadBondPos;
import com.jxtb.test.entity.UploadPosLog;
import com.jxtb.test.entity.UploadStockPos;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import jxl.write.Number;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 17-8-5
* Time: 上午8:40
* To change this template use File | Settings | File Templates.
*/
public class ExcelUtil {
public static void exportData(List<HashMap<String, Object>> list, String path) {
String[] title = {"编号", "姓名", "密码"};
//1.创建一个工作簿对象
WritableWorkbook wb = null;
String fileName = path;
File file = new File(fileName);
try {
wb = Workbook.createWorkbook(file);
//2.创建工作表对象
WritableSheet sheet = wb.createSheet("学生统计表", 0);
//3.生成表头
Label label = null;
for (int i = 0; i < title.length; i++) {
label = new Label(i, 0, title[i]);
sheet.addCell(label);
}
//4.追加数据
Label label1 = null;
HashMap<String, Object> map = null;
for (int i = 0; i < list.size(); i++) {
map = list.get(i);
//王第i+1行的第一列格子里追加数据
label1 = new Label(0, i + 1, String.valueOf(map.get("id")));
sheet.addCell(label1);
label1 = new Label(1, i + 1, String.valueOf(map.get("name")));
sheet.addCell(label1);
label1 = new Label(2, i + 1, String.valueOf(map.get("pwd")));
sheet.addCell(label1);
}
//写入数据
wb.write();
//关闭工作簿
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param args
* @throws Exception
* @author
* @createtime 2015-7-31 上午09:58:41
*/
public static void main(String[] args) throws Exception {
//createExcel();
//copeExcel();
// readExcel();
//read_excel();
}
public static void createExcel() throws Exception {
String url = "D:\\excel\\javaExcel.xls";
//创建文件
OutputStream os = new FileOutputStream(url);
WritableWorkbook wwb = Workbook.createWorkbook(os);
//创建第一张sheet
WritableSheet ws = wwb.createSheet("sheet1", 0);
//添加label对象
Label label = new Label(0, 0, "label cell");
ws.addCell(label);
//添加带有字型的label对象
WritableFont wf = new WritableFont(WritableFont.TIMES, 18, WritableFont.BOLD, true);
WritableCellFormat wcf = new WritableCellFormat(wf);
Label labelwf = new Label(0, 1, "label cell 0 1", wcf);
ws.addCell(labelwf);
//添加带有字体颜色的label对象
WritableFont wfc = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.RED);
WritableCellFormat wcfc = new WritableCellFormat(wfc);
Label labelwcfc = new Label(0, 2, "label cell 0 2", wcfc);
ws.addCell(labelwcfc);
//添加number,还有其他类型没有写
Number labelN = new Number(0, 3, 2.1);
ws.addCell(labelN);
wwb.write();
wwb.close();
}
public static void copeExcel() throws Exception {
String url = "D:\\excel\\javaExcel1.xls";
//创建文件
OutputStream os = new FileOutputStream(url);
WritableWorkbook wwb = Workbook.createWorkbook(os);
//输入流文件路径读取
InputStream in = new FileInputStream("D:\\excel\\javaExcel.xls");
//构建workbook
Workbook workBook = Workbook.getWorkbook(in);
//获取读取文件的sheet数
int sheet = workBook.getNumberOfSheets();
for (int i = 0; i < sheet; i++) {
//获取读取文件的sheet对象
Sheet st = workBook.getSheet(i);
//复制文件创建sheet对象
WritableSheet ws = wwb.createSheet("sheet" + (i + 1), i);
for (int j = 0; j < st.getColumns(); j++) {//循环读取文件的列
for (int j2 = 0; j2 < st.getRows(); j2++) {//循环读取文件的行
Label label = new Label(j, j2, st.getCell(j, j2).getContents());//获取读取文件的值创建label
ws.addCell(label);//将label添加的复杂文件中
}
}
}
wwb.write();//写入
wwb.close();//关闭
}
public static void readExcel() throws Exception {
//输入流文件路径读取
InputStream in = new FileInputStream("D:\\excel\\javaExcel.xls");
//构建workbook
Workbook workBook = Workbook.getWorkbook(in);
//读取第一张sheet表
Sheet st = workBook.getSheet(0);
//读取第一行第一列
Cell cell = st.getCell(0, 0);
//将读取的excel数据转换成字符串
String cellStr = cell.getContents();
//读取第二行第一列
Cell cell1 = st.getCell(st.getColumns() - 1 > 1 ? 1 : st.getColumns() - 1, 0);
String cellStr1 = cell1.getContents();
//读取第一行第二列
Cell cell01 = st.getCell(0, st.getRows() - 1 > 1 ? 1 : st.getRows() - 1);
String cellStr01 = cell01.getContents();
System.out.println(cellStr + "|" + cellStr1 + "|" + cellStr01);
//打印读取到的excel数据类型
System.out.println(cell.getType());
//获取sheet个数
int sheetNumber = workBook.getNumberOfSheets();
//获取sheet对象数组
Sheet[] sheetArr = workBook.getSheets();
//获取sheet的名称
String sheetName = st.getName();
//获取sheet表中的总列数
int sheetColumn = st.getColumns();
//获取某一列的单元格,返回数组对象
Cell[] cellColumnArr = st.getColumn(0);
//获取行数
int sheetRow = st.getRows();
//获取行下的单元格
Cell[] cellRowArr = st.getRow(0);
//操作完成关闭对象,释放占用的内存
workBook.close();
}
public static void read_excel() {
int i;
Sheet sheet;
Workbook book;
Cell cell1, cell2, cell3;
try {
//t.xls为要读取的excel文件名
book = Workbook.getWorkbook(new File("D:\\excel\\student.xls"));
//获得第一个工作表对象(ecxel中sheet的编号从0开始,0,1,2,3,....)
sheet = book.getSheet(0);
//获取左上角的单元格
cell1 = sheet.getCell(0, 0);
System.out.println("标题:" + cell1.getContents());
i = 1;
while (true) {
//获取每一行的单元格
cell1 = sheet.getCell(0, i);//(列,行)
cell2 = sheet.getCell(1, i);
cell3 = sheet.getCell(2, i);
if ("".equals(cell1.getContents()) == true) //如果读取的数据为空
break;
System.out.println(cell1.getContents() + "\t" + cell2.getContents() + "\t" + cell3.getContents());
i++;
}
book.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//读取xlsx文件
public static List readExcelXlsx(FileInputStream filestream) throws Exception{
boolean flag=false;
List<UploadStockPos> uploadStockPosList=new ArrayList<>();
List<UploadBondPos> uploadBondPosList=new ArrayList<>();
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(filestream);
XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(xssfWorkbook);
// 获取每一个工作薄
// 循环行Row
for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
if (xssfSheet == null) {
continue;
}
// 循环行Row
for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
UploadPosLog uploadPosLog=new UploadPosLog();
uploadPosLog.setGroup1(getXlsxValue(xssfRow.getCell(41), evaluator));
if("Common Stock".equals(uploadPosLog.getGroup1())){
UploadStockPos uploadStockPos=new UploadStockPos();
uploadStockPos.setEnt_time(getXlsxValue(xssfRow.getCell(40), evaluator));
uploadStockPosList.add(uploadStockPos);
flag=true;
}else{
UploadBondPos uploadBondPos=new UploadBondPos();
uploadBondPos.setEnt_time(getXlsxValue(xssfRow.getCell(40), evaluator));
uploadBondPosList.add(uploadBondPos);
flag=false;
}
}
}
if(flag){
return uploadStockPosList;
}else{
return uploadBondPosList;
}
}
//读取xls文件
public static BaseResponse readExcelXls(FileInputStream filestream,BaseResponse baseResponse) throws Exception{
List<UploadStockPos> uploadStockPosList=new ArrayList<>();
List<UploadBondPos> uploadBondPosList=new ArrayList<>();
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(filestream);
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(hssfWorkbook);
// 获取每一个工作薄
// 循环行Row
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
// 循环行Row
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
baseResponse.setParam(hssfRow);
baseResponse.setParam(evaluator);
/* UploadPosLog uploadPosLog=new UploadPosLog();
uploadPosLog.setGroup1(getXlsValue(hssfRow.getCell(41), evaluator));
if(uploadPosLog.getGroup1().indexOf("Stock")!=-1){
UploadStockPos uploadStockPos=new UploadStockPos();
uploadStockPos.setEnt_time(getXlsValue(hssfRow.getCell(40),evaluator));
uploadStockPosList.add(uploadStockPos);
}else{
UploadBondPos uploadBondPos=new UploadBondPos();
uploadBondPos.setEnt_time(getXlsValue(hssfRow.getCell(40),evaluator));
uploadBondPosList.add(uploadBondPos);
}*/
}
}
return baseResponse;
}
//转换xlsx数据格式
private static String getXlsxValue(XSSFCell cell,FormulaEvaluator evaluator) {
if(cell==null){
return "" ;
}
String value = "";
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: //数值型
if (HSSFDateUtil.isCellDateFormatted(cell)) { //如果是时间类型
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
value = format.format(cell.getDateCellValue());
} else { //纯数字
value = String.valueOf(cell.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_STRING: //字符串型
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: //布尔
value = " " + cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK: //空值
value = "";
break;
case HSSFCell.CELL_TYPE_ERROR: //故障
value = "";
break;
case HSSFCell.CELL_TYPE_FORMULA: //公式型
try {
CellValue cellValue;
cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellType()) { //判断公式类型
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN:
value = String.valueOf(cellValue.getBooleanValue());
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC:
// 处理日期
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date date = cell.getDateCellValue();
value = format.format(date);
} else {
value = String.valueOf(cellValue.getNumberValue());
}
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING:
value = cellValue.getStringValue();
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BLANK:
value = "";
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_ERROR:
value = "";
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_FORMULA:
value = "";
break;
}
} catch (Exception e) {
value = cell.getStringCellValue().toString();
cell.getCellFormula();
}
break;
default:
value = cell.getStringCellValue().toString();
break;
}
return value;
}
// 转换xls数据格式
private static String getXlsValue(HSSFCell cell,FormulaEvaluator evaluator) throws Exception{
if(cell==null){
return "" ;
}
String value = "";
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: //数值型
if (HSSFDateUtil.isCellDateFormatted(cell)) { //如果是时间类型
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
value = format.format(cell.getDateCellValue());
} else { //纯数字
value = String.valueOf(cell.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_STRING: //字符串型
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: //布尔
value = " " + cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK: //空值
value = "";
break;
case HSSFCell.CELL_TYPE_ERROR: //故障
value = "";
break;
case HSSFCell.CELL_TYPE_FORMULA: //公式型
try {
CellValue cellValue;
cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellType()) { //判断公式类型
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN:
value = String.valueOf(cellValue.getBooleanValue());
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC:
// 处理日期
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date date = cell.getDateCellValue();
value = format.format(date);
} else {
value = String.valueOf(cellValue.getNumberValue());
}
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING:
value = cellValue.getStringValue();
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BLANK:
value = "";
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_ERROR:
value = "";
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_FORMULA:
value = "";
break;
}
} catch (Exception e) {
value = cell.getStringCellValue().toString();
cell.getCellFormula();
}
break;
default:
value = cell.getStringCellValue().toString();
break;
}
return value;
}
}
|
package edu.fudan.nlp.cn.tag;
import java.util.ArrayList;
import edu.fudan.ml.classifier.struct.inf.ConstraintViterbi;
import edu.fudan.ml.classifier.struct.inf.LinearViterbi;
import edu.fudan.ml.types.Dictionary;
import edu.fudan.ml.types.Instance;
import edu.fudan.nlp.cn.Sentenizer;
import edu.fudan.nlp.cn.tag.format.FormatCWS;
import edu.fudan.nlp.pipe.Pipe;
import edu.fudan.nlp.pipe.SeriesPipes;
import edu.fudan.nlp.pipe.seq.DictLabel;
import edu.fudan.nlp.pipe.seq.DictMultiLabel;
import edu.fudan.nlp.pipe.seq.String2Sequence;
import edu.fudan.util.MyCollection;
import edu.fudan.util.exception.LoadModelException;
import gnu.trove.set.hash.THashSet;
/**
* 中文分词器
*
* @author xpqiu
* @version 1.0
* @since FudanNLP 1.0
*/
public class CWSTagger extends AbstractTagger {
// 考虑不同CWStagger可能使用不同dict,所以不使用静态
private DictLabel dictPipe = null;
private Pipe oldfeaturePipe = null;
/**
* 是否对英文单词进行预处理
*/
private boolean isEnFilter = true;
/**
* 是否对英文单词进行预处理,将连续的英文字母看成一个单词
*
* @param b
*/
public void setEnFilter(boolean b) {
isEnFilter = b;
prePipe = new String2Sequence(isEnFilter);
}
/**
* 构造函数,使用LinearViterbi解码
*
* @param str
* 模型文件名
* @throws LoadModelException
*/
public CWSTagger(String str, boolean classpath) throws LoadModelException {
super(str, classpath);
prePipe = new String2Sequence(isEnFilter);
// DynamicViterbi dv = new DynamicViterbi(
// (LinearViterbi) cl.getInferencer(),
// cl.getAlphabetFactory().buildLabelAlphabet("labels"),
// cl.getAlphabetFactory().buildFeatureAlphabet("features"),
// false);
// dv.setDynamicTemplets(DynamicTagger.getDynamicTemplet("example-data/structure/template_dynamic"));
// cl.setInferencer(dv);
}
public CWSTagger(String file) throws LoadModelException {
this(file, false);
}
private void initDict(Dictionary dict) {
// prePipe = new String2SimpleSequence(false);
if (dict.isAmbiguity()) {
dictPipe = new DictMultiLabel(dict, labels);
} else {
dictPipe = new DictLabel(dict, labels);
}
oldfeaturePipe = featurePipe;
featurePipe = new SeriesPipes(new Pipe[] { dictPipe, featurePipe });
LinearViterbi dv = new ConstraintViterbi(
(LinearViterbi) cl.getInferencer());
cl.setInferencer(dv);
}
/**
* 构造函数,使用ConstraintViterbi解码
*
* @param str
* 模型文件名
* @param dict
* 外部词典资源
* @throws Exception
*/
public CWSTagger(String str, Dictionary dict) throws Exception {
this(str);
initDict(dict);
}
/**
* 设置词典
*
* @param dict
* 词典
*/
public void setDictionary(Dictionary dict) {
if (dictPipe == null) {
initDict(dict);
} else {
dictPipe.setDict(dict);
}
}
/**
* 设置词典
*
* @param newset
*/
public void setDictionary(THashSet<String> newset) {
if (newset.size() == 0)
return;
ArrayList<String> al = new ArrayList<String>();
MyCollection.TSet2List(newset, al);
Dictionary dict = new Dictionary();
dict.addSegDict(al);
setDictionary(dict);
}
/**
* 移除词典
*/
public void removeDictionary() {
if (oldfeaturePipe != null) {
featurePipe = oldfeaturePipe;
}
LinearViterbi dv = new LinearViterbi((LinearViterbi) cl.getInferencer());
cl.setInferencer(dv);
dictPipe = null;
oldfeaturePipe = null;
}
@Override
public String tag(String src) {
if (src == null || src.length() == 0)
return src;
String[] sents = Sentenizer.split(src);
String tag = "";
try {
for (int i = 0; i < sents.length; i++) {
Instance inst = new Instance(sents[i]);
String[] preds = _tag(inst);
String s = FormatCWS.toString(inst, preds, delim);
tag += s;
if (i < sents.length - 1)
tag += delim;
}
} catch (Exception e) {
e.printStackTrace();
}
return tag;
}
/**
* 先进行断句,得到每句的分词结果,返回List[]数组
*
* @param src
* 字符串
* @return String[][] 多个句子数组
*/
public String[][] tag2DoubleArray(String src) {
if (src == null || src.length() == 0)
return null;
String[] sents = Sentenizer.split(src);
String[][] words = new String[sents.length][];
for (int i = 0; i < sents.length; i++) {
words[i] = tag2Array(sents[i]);
}
return words;
}
/**
* 得到分词结果 List,不进行断句
*
* @param src
* 字符串
* @return ArrayList<String> 词数组,每个元素为一个词
*/
public ArrayList<String> tag2List(String src) {
if (src == null || src.length() == 0)
return null;
ArrayList<String> res = null;
try {
Instance inst = new Instance(src);
String[] preds = _tag(inst);
res = FormatCWS.toList(inst, preds);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
/**
* 得到分词结果 String[],不进行断句
*
* @param src
* 字符串
* @return String[] 词数组,每个元素为一个词
*/
public String[] tag2Array(String src) {
ArrayList<String> words = tag2List(src);
return (String[]) words.toArray(new String[words.size()]);
}
}
|
package com.aftermoonest.tell_me_something_important.view;
import com.aftermoonest.tell_me_something_important.components.ItemList;
import com.aftermoonest.tell_me_something_important.repository.Controller;
import com.aftermoonest.tell_me_something_important.repository.ControllerImpl;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
@Route("list")
public class PageView extends VerticalLayout {
Controller controller = new ControllerImpl();
VerticalLayout itemsLayout;
public PageView() {
setDefaultHorizontalComponentAlignment(Alignment.CENTER);
ItemList list = new ItemList();
itemsLayout = list.show(controller.get());
add(itemsLayout);
}
}
|
/*
* Welcome to use the TableGo Tools.
*
* http://vipbooks.iteye.com
* http://blog.csdn.net/vipbooks
* http://www.cnblogs.com/vipbooks
*
* Author:bianj
* Email:edinsker@163.com
* Version:5.8.0
*/
package com.lenovohit.hwe.mobile.core.model;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.lenovohit.hwe.base.model.AuditableModel;
/**
* APP_LABORATORY
*
* @author redstar
* @version 1.0.0 2017-12-14
*/
@Entity
@Table(name = "APP_VACCINE")
public class Vaccine extends AuditableModel implements java.io.Serializable {
/** 版本号 */
private static final long serialVersionUID = 5123120272341522921L;
/** vaccineID id */
private String vaccineId;
/** vaccineName 名称 */
private String vaccineName;
/** vaccinePinYin 拼音 */
private String vaccinePinyin;
/** abbreviation */
private String abbreviation;
/** disease 相关疾病 */
private String disease;
/** inoculationSite 注射地方 */
private String inoculationSite;
/** way 注射方式 */
private String way;
/** inoculationTimes 时间 */
private String inoculationTime;
/** dose 规格 */
private String dose;
/** remark 备注 */
private String remark;
/** dayBirth 注射方式 */
private String dayBirth;
public String getVaccineId() {
return vaccineId;
}
public void setVaccineId(String vaccineId) {
this.vaccineId = vaccineId;
}
public String getVaccineName() {
return vaccineName;
}
public void setVaccineName(String vaccineName) {
this.vaccineName = vaccineName;
}
public String getVaccinePinyin() {
return vaccinePinyin;
}
public void setVaccinePinyin(String vaccinePinyin) {
this.vaccinePinyin = vaccinePinyin;
}
public String getAbbreviation() {
return abbreviation;
}
public void setAbbreviation(String abbreviation) {
this.abbreviation = abbreviation;
}
public String getDisease() {
return disease;
}
public void setDisease(String disease) {
this.disease = disease;
}
public String getInoculationSite() {
return inoculationSite;
}
public void setInoculationSite(String inoculationSite) {
this.inoculationSite = inoculationSite;
}
public String getWay() {
return way;
}
public void setWay(String way) {
this.way = way;
}
public String getInoculationTime() {
return inoculationTime;
}
public void setInoculationTime(String inoculationTime) {
this.inoculationTime = inoculationTime;
}
public String getDose() {
return dose;
}
public void setDose(String dose) {
this.dose = dose;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getDayBirth() {
return dayBirth;
}
public void setDayBirth(String dayBirth) {
this.dayBirth = dayBirth;
}
} |
package functionalinterface;
import java.util.function.Supplier;
public class _Supplier {
public static void main(String[] args) {
//normal java
System.out.println( getDbConnectionUrl());
//functional java
System.out.println(getDbUrl.get());
}
//normal java function for getting stuff
static String getDbConnectionUrl() {
return "jdbc//localhost:3243/users";
}
//Supplier function interface does the same it suplies stuff
static Supplier<String> getDbUrl = () -> "jdbc//localhost:3243/users";
}
|
package cinemaapp.java;
import java.util.ArrayList;
import java.util.List;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
//how i understand the model class is that when i create, update and delete inside this java application the model class contains everything that changes the java application
public class Model {
private static Model instance = null;
public static synchronized Model getInstance() {
if (instance ==null) {
instance = new Model();
}
return instance;
}
private List<Screen> screens;
private ScreenTableGateway gateway;
private Model(){
try {
Connection conn = DBConnection.getInstance();
this.gateway = new ScreenTableGateway(conn);
this.screens = gateway.getScreens();
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
}
catch (SQLException ex) {
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<Screen> getScreens() {
return new ArrayList<Screen>(this.screens);
}
public void addScreen(Screen s) {
try {
int id = this.gateway.insertScreen(s.getSeatNumbers(), s.getFireExits());
s.setId(id);
this.screens.add(s);
}
catch (SQLException ex){
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
}
}
public boolean removeScreen(Screen s){
boolean removed = false;
try{
removed = this.gateway.deleteScreen(s.getId());
if(removed){
removed = this.screens.remove(s);
}
}
catch (SQLException ex){
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex );
}
return removed;
}
public Screen findScreenByID(int id) {
Screen s = null;
int i = 0;
boolean found = false;
while (i < this.screens.size() && !found) {
s = this.screens.get(i);
if (s.getId() == id) {
found = true;
} else {
i++;
}
}
if (!found) {
s = null;
}
return s;
}
boolean updateScreen(Screen s) {
boolean updated = false;
try{
updated = this.gateway.updateScreen(s);
}
catch (SQLException ex){
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex );
}
return updated;
}
}
|
package com.example.auth.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Document
@NoArgsConstructor
public class User {
@Id
private String username;
private String password;
private String type;
}
|
package com.example.paindairy.viewmodel;
import android.app.Application;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.example.paindairy.entity.PainRecord;
import com.example.paindairy.repository.PainRecordRepository;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class PainRecordViewModel extends AndroidViewModel {
private PainRecordRepository painRecordRepository;
private LiveData<List<PainRecord>> allPainRecords;
public PainRecordViewModel(@NonNull Application application) {
super(application);
painRecordRepository = new PainRecordRepository(application);
allPainRecords = painRecordRepository.getAllPainRecords();
}
@RequiresApi(api = Build.VERSION_CODES.N)
public CompletableFuture<PainRecord> findByIDFuture(final int painRecordId) {
return painRecordRepository.findByIDFuture(painRecordId);
}
public LiveData<List<PainRecord>> getAllPainRecords() {
return allPainRecords;
}
public void insert(PainRecord painRecord) {
painRecordRepository.insert(painRecord);
}
public void deleteAll() {
painRecordRepository.deleteAll();
}
public void update(PainRecord painRecord) {
painRecordRepository.updatePainRecord(painRecord);
}
public LiveData<PainRecord> getByDate(Date date) {
return painRecordRepository.getByDate(date);
}
public LiveData<Integer> getLastId(String emailid) {
return painRecordRepository.getLastId(emailid);
}
public LiveData<PainRecord> getLastUpdatedDate(String emailid) {
return painRecordRepository.getLastUpdatedDate(emailid);
}
}
|
package storage;
import config.Config;
public class SqlStorageTest extends AbstractStorageTest {
public SqlStorageTest() {
super(Config.getInstance().getStorage());
}
} |
package API;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class MyBufferedReader {
public static void main(String[] args){
FileReader fr = null;
BufferedReader br = null;
String path1 = "C:/Users/Karina/Documents/file01.txt";
String path2 = "C:\\Users\\Karina\\Documents\\file01.txt";
try {
fr = new FileReader(path1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
//File-reader is sub-class of Reader class
//BufferedReader can take Sub-Class Of Reader-class
//Reader-class has few Sub-class..those are File-Reader, BufferedReader
br = new BufferedReader (fr);
String text = "";
try {
while ((text = br.readLine())!=null){
System.out.println(text);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
#include<stdio.h>
int main()
{
//Type your code here
int x,y,z,sum,avg;
scanf("%d%d%d",&x,&y,&z);
sum=x+y+z;
avg=sum/3;
printf("%d",avg);
return 0;
} |
public class Solution{
public static void sortAnagrams1(String[] array){
Arrays.sort(array,new AnagramComparator());
}
public class AnagramComparator implements Comparator<String>{
@override
public int compare(String s1,String s2){
return sortString(s1).compareTo(sortString(s2))
}
private static String sortString(String str){
char[] ch = str.toCharArray();
Arrays.sort(ch);
return new String(ch);
}
}
public static void sortAnagrams2(String[] array){
if(array==null){return null;}
HashMap<String,ArrayList<String>> map = new HashMap<>();
for(String each : array){
String key = sortString(each);
if(map.containsKey(key)){
ArrayList<String> list = map.get(key);
list.add(each);
}else{
ArrayList<String> list = new ArrayList<>();
list.add(each);
map.put(key,list);
}
}
int index = 0;
for(String key : map.keySet()){
ArrayList<String> list = map.get(key);
for(String each : list){
array[index] = each;
index++;
}
}
}
private static String sortString(String str){
char[] ch = str.toCharArray();
Arrays.sort(ch);
return new String(ch);
}
} |
package my.edu.tarc.assignment;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class ShowVoucherDetailsActivity extends AppCompatActivity {
private TextView textViewVoucherInfo, textViewVoucherCode, textViewVoucherExpiryDate, textViewRedeemMethod;
private ImageView imageViewVoucherLogo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_voucher_details);
String vouchertype, voucheramount, vouchercode, expirydate;
String redeemMethod = "";
textViewVoucherInfo = (TextView) findViewById(R.id.textViewVoucherTitle);
textViewVoucherCode = (TextView) findViewById(R.id.textViewVoucherCode);
textViewVoucherExpiryDate = (TextView) findViewById(R.id.textViewVoucherExpiryDate);
textViewRedeemMethod = (TextView) findViewById(R.id.textViewRedeemMethod);
imageViewVoucherLogo = (ImageView) findViewById(R.id.imageViewVoucherLogo);
//to get the voucher info from last activity
Intent intent = getIntent();
vouchertype = intent.getStringExtra(MainActivity.VOUCHER_TYPE);
voucheramount = intent.getStringExtra(MainActivity.VOUCHER_AMOUNT);
vouchercode = intent.getStringExtra(MainActivity.VOUCHER_CODE);
expirydate = intent.getStringExtra(MainActivity.VOUCHER_EXPIRYDATE);
textViewVoucherCode.setText(vouchercode);
textViewVoucherInfo.setText(getString(R.string.balance) + voucheramount + " " + vouchertype);
textViewVoucherExpiryDate.setText("Expiry on " + expirydate);
//to get the correct voucher type
if (vouchertype.equalsIgnoreCase("Garena Shells")) {
imageViewVoucherLogo.setImageResource(R.drawable.logo_garena);
redeemMethod = "1. Go to your Garena Account\n" +
"2. Click \"Add Shells\"\n" +
"3. Click \"Redeem a Garena Shells Code\"\n" +
"4. Enter your Garena Shells Code\n" +
"5. Click \"Continue\" ";
} else if (vouchertype.equalsIgnoreCase("PSN Digital Code")) {
imageViewVoucherLogo.setImageResource(R.drawable.logo_psn);
redeemMethod = "1. Go to your PSD Account\n" +
"2. Click \"Add funds to your PSD Wallet\"\n" +
"3. Click \"Redeem a PSD Digital Code\"\n" +
"4. Enter your PSD Digital Code\n" +
"5. Click \"Continue\" ";
} else if (vouchertype.equalsIgnoreCase("Steam Wallet Code")) {
imageViewVoucherLogo.setImageResource(R.drawable.logo_steam);
redeemMethod = "1. Go to your Steam Account\n" +
"2. Click \"Add funds to your Steam Wallet\"\n" +
"3. Click \"Redeem a Steam Wallet Code\"\n" +
"4. Enter your Steam Wallet Code\n" +
"5. Click \"Continue\" ";
}
textViewRedeemMethod.setText(redeemMethod);
}
}
|
/*
Copyright (c) 2014, Student group C in course TNM082 at Linköpings University
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.example.kartela;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.content.Context;
import android.graphics.Point;
import android.text.format.Time;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class StartscreenListAdapter extends ArrayAdapter<String> {
private static final int HOURS_IN_MS = 3600000;
private static final int WORK_TIME_PER_DAY = 8;
private static final int PADDING = 120;
private final Context context;
private final ArrayList<String> weekdaysArray;
private final List<String> projects;
private double total;
private final TimelogDataSource datasource;
private Time time = new Time();
private WindowManager wm;
private Display display;
private Point size;
private int multiple;
// temp variables
private double temp_ratio, hours, total_day, minutes;
private double[] temp_sum;
private TextView temp_view;
private String temp_name, str;
private int temp_id;
private Calendar calendar;
private String date;
public StartscreenListAdapter(Context context, ArrayList<String> weekdaysArray, int currentWeeknumber, int currentYear, List<String> projects, TimelogDataSource datasource) {
super(context, R.layout.day_row_layout, weekdaysArray);
this.context = context;
this.weekdaysArray = weekdaysArray;
this.projects = projects;
this.datasource = datasource;
time.setToNow();
wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
display = wm.getDefaultDisplay();
size = new Point();
display.getSize(size);
multiple = size.x - PADDING;
calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, currentYear);
calendar.set(Calendar.WEEK_OF_YEAR, currentWeeknumber);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.day_row_layout, parent, false);
TextView dayTitle = (TextView) convertView.findViewById(R.id.day_title);
dayTitle.setText(weekdaysArray.get(position));
date = weekdaysArray.get(position);
date = date.split("\\s+")[1];
total = HOURS_IN_MS*WORK_TIME_PER_DAY;
updateProgressBar(convertView);
return convertView;
}
public void updateProgressBar(View convertView) {
temp_sum = new double[projects.size()];
temp_ratio = 0;
total_day = 0;
for (int i=0; i<projects.size(); i++) {
temp_sum[i] = datasource.getWorkTimeByNameDate(projects.get(i), date);
total_day += temp_sum[i];
}
for (int i=0; i<projects.size(); i++) {
temp_name = "progress_" + projects.get(i);
temp_id = context.getResources().getIdentifier(temp_name, "id", context.getPackageName());
temp_view = (TextView) convertView.findViewById(temp_id);
if (total < total_day) total = total_day;
if (temp_sum[i] != 0) {
temp_ratio = (temp_sum[i]/total)*100;
// update project textview
hours = (double)temp_sum[i]/HOURS_IN_MS;
//str = String.format("%1.2f", Math.floor(hours)); GAMMALT
minutes = (hours - Math.floor(hours))*60;
int min = (int)minutes;
int h = (int)hours;
//strMin = String.format("%1.2f", min); GAMMALT
if(min==0 && h!=0){
temp_view.setText(h + "h ");
temp_view.getLayoutParams().height = 50;
temp_view.setPadding(5, 5, 0, 0);
temp_view.getLayoutParams().width = ((int)(temp_ratio*multiple/100));
}
else if(h==0){
h=1;
temp_view.getLayoutParams().height = 50;
temp_view.setPadding(5, 5, 0, 0);
temp_view.getLayoutParams().width = ((int)(temp_ratio*multiple/100));
}
else{
temp_view.setText(h + "h "+min+"m");
temp_view.setPadding(5, 5, 0, 0);
temp_view.getLayoutParams().height = 50;
temp_view.getLayoutParams().width = ((int)(temp_ratio*multiple/100));
}
temp_view.getLayoutParams().height = 50;
temp_view.setPadding(5, 5, 0, 0);
temp_view.getLayoutParams().width = ((int)(temp_ratio*multiple/100));
if((int)(temp_ratio*multiple/100) > 80 && (min==0 && h!=0)){
temp_view.setText(h + "h ");
} else if((int)(temp_ratio*multiple/100) > 120) {
temp_view.setText(h + "h "+min+"m");
}
} else {
temp_view.getLayoutParams().width = 0;
}
}
}
}
|
package com.bharath.jdbc.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class AccountDAO {
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "test");
Statement statement = connection.createStatement();
System.out.println(connection);
// statement.executeUpdate("insert into account
// values(1,'thippireddy','bharath',10000)");
// System.out.println(result+" rows got inserted");
// int result =
// statement.executeUpdate("update account set bal=50000 where accno=1");
// System.out.println(result+" rows got updated");
// int result =
// statement.executeUpdate("delete from account where accno=1");
// System.out.println(result+" rows got deleted");
ResultSet rs = statement.executeQuery("select * from account");
while (rs.next()) {
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println(rs.getInt(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
package com.yzp.controller;
import com.google.gson.JsonObject;
import com.yzp.model.Users;
import com.yzp.service.TestService;
import com.yzp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping(value = "/user")
public class UserController{
@Autowired
private UserService userService;
@Autowired
private TestService testService;
/**
* @param userId
* @return
*/
//返回json格式数据,形式1
@RequestMapping(value = "/getUserJson1",method = RequestMethod.GET)
@ResponseBody
public List<Users> getUsers2(@RequestParam Integer userId) {
//调用service方法得到用户列表
List<Users> users = userService.selectUsersAll();
for (Users user : users) {
System.out.println(user.getId()+","+user.getName());
}
return users;
}
@RequestMapping("/testSave")
@ModelAttribute
public void saveTestData(){
Map<String,Object> params = new HashMap<String,Object>();
testService.insertTest(params);
}
//返回json格式数据,形式1
@RequestMapping(value = "/getUserJson2",method = RequestMethod.GET)
@ResponseBody
public List<Map<String,Object>> getUsers3(@RequestParam Integer userId) {
//调用service方法得到用户列表
List<Map<String,Object>> users = userService.userMap();
return users;
}
} |
package com.seidlserver.cmd;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.Executors;
/*
Created by: Jonas Seidl
Date: 23.03.2021
Time: 14:58
*/
/***
* This class is used for executing a command
*/
public class CommandExecutor {
/***
* Executes a command
* @param args Command with its args
* @return Stdout of the command
* @throws IOException
* @throws InterruptedException
*/
public static String execute(String... args) throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder();
builder.command(args);
Process process = builder.start();
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
//Stdout
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while((line = br.readLine()) != null){
output.append(line+"\n");
}
//Stderror
br = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
line = null;
while((line = br.readLine()) != null){
error.append(line);
}
int exitVal = process.waitFor();
if(exitVal == 0){
return output.toString();
}else{
throw new IOException("\nStderror:\n"+error.toString()+"Stdout:\n"+output);
}
}
}
|
package com.git.cloud.resmgt.common.service.impl;
import com.git.cloud.resmgt.common.service.IVmManageSoftWareService;
public class VmManageSoftWareServiceImpl implements IVmManageSoftWareService {
}
|
package me.kpali.wolfflow.sample.cluster;
import com.fasterxml.jackson.databind.ObjectMapper;
import me.kpali.wolfflow.core.exception.TaskFlowLogException;
import me.kpali.wolfflow.core.exception.TaskLogException;
import me.kpali.wolfflow.core.logger.ITaskFlowLogger;
import me.kpali.wolfflow.core.logger.ITaskLogger;
import me.kpali.wolfflow.core.model.TaskFlowLog;
import me.kpali.wolfflow.core.model.TaskLog;
import me.kpali.wolfflow.core.model.TaskLogResult;
import me.kpali.wolfflow.core.scheduler.ITaskFlowScheduler;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class WolfFlowSampleClusterApplicationTests {
private static final Logger logger = LoggerFactory.getLogger(WolfFlowSampleClusterApplicationTests.class);
@Autowired
ITaskFlowScheduler taskFlowScheduler;
@Autowired
ITaskFlowLogger taskFlowLogger;
@Autowired
ITaskLogger taskLogger;
@Test
public void taskFlowExecuteTest() {
ObjectMapper objectMapper = new ObjectMapper();
try {
long taskFlowLogId1 = taskFlowScheduler.executeTo(100L, 5L, null);
logger.info(">>>>>>>>>> Task flow log id: " + taskFlowLogId1);
//Thread.sleep(1000);
//taskFlowScheduler.stop(taskFlowLogId1);
this.waitDoneAndPrintLog(taskFlowLogId1);
List<TaskLog> taskStatusList1 = taskLogger.listTaskStatus(100L);
logger.info(">>>>>>>>>> Finished, status of tasks: ");
logger.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(taskStatusList1));
long taskFlowLogId2 = taskFlowScheduler.executeTo(100L, 6L, null);
logger.info(">>>>>>>>>> Task flow log id: " + taskFlowLogId2);
this.waitDoneAndPrintLog(taskFlowLogId2);
List<TaskLog> taskStatusList2 = taskLogger.listTaskStatus(100L);
logger.info(">>>>>>>>>> Finished, status of tasks: ");
logger.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(taskStatusList2));
} catch (Exception e) {
e.printStackTrace();
}
}
private void waitDoneAndPrintLog(long taskFLowLogId) throws TaskFlowLogException, TaskLogException {
while (true) {
TaskFlowLog taskFlowLog = taskFlowLogger.get(taskFLowLogId);
if (!taskFlowLogger.isInProgress(taskFlowLog)) {
List<TaskLog> taskLogList = taskLogger.list(taskFLowLogId);
for (TaskLog taskLog : taskLogList) {
TaskLogResult taskLogResult = taskLogger.query(taskLog.getLogFileId(), 1);
if (taskLogResult != null) {
logger.info(">>>>>>>>>> Task [" + taskLog.getTaskId() + "] log contents: ");
logger.info(taskLogResult.getLogContent());
}
}
break;
}
}
}
}
|
package evolutionYoutube;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.navigator.Navigator;
import com.vaadin.navigator.View;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Grid;
import com.vaadin.ui.UI;
import database.Usuario_Administrador;
import database.Usuario_registrado;
import database.Videos;
/**
* This UI is the application entry point. A UI may either represent a browser window
* (or tab) or some part of an HTML page where a Vaadin application is embedded.
* <p>
* The UI is initialized using {@link #init(VaadinRequest)}. This method is intended to be
* overridden to add component to the user interface and initialize non-component functionality.
*/
@Theme("mytheme")
public class MyUI extends UI implements View{
/**
*
*/
private static final long serialVersionUID = 1L;
public static Usuario_registrado usuario;
public static Grid<database.Categorias> grid;
public static Grid<database.Usuario_registrado> gridListaUsuarios;
public static Usuario_Administrador admin;
@Override
protected void init(VaadinRequest vaadinRequest) {
setNavigator(new Navigator(this, this));
getNavigator().addView("", new Invitado());
}
public static Usuario_registrado getUsuarioLogged() {
return usuario;
}
public static void setUsuarioLogged(Usuario_registrado user) {
usuario = user;
}
public static database.Categorias getCategoria(){
return grid.getSelectionModel().getFirstSelectedItem().get();
}
public static Usuario_Administrador getAdminLogged() {
return admin;
}
public static void setAdminLogged(Usuario_Administrador administrador) {
admin = administrador;
}
public static void setGrid(Grid<database.Categorias> tabla) {
grid=tabla;
}
public static void setGridListaUsuarios(Grid<database.Usuario_registrado> tabla) {
gridListaUsuarios=tabla;
}
public static database.Usuario_registrado getUsuario(){
return gridListaUsuarios.getSelectionModel().getFirstSelectedItem().get();
}
public void registrarse() {
getNavigator().addView("Registro", new Registrarse());
getNavigator().navigateTo("Registro");
}
public void iniciar_sesion() {
getNavigator().addView("Iniciar Sesion", new Iniciar_Sesion());
getNavigator().navigateTo("Iniciar Sesion");
}
public void invitado() {
getNavigator().addView("Invitado", new Invitado());
getNavigator().navigateTo("Invitado");
}
public void usuario_registrado() {
getNavigator().addView("Usuario Registrado", new Usuario_Registrado());
getNavigator().navigateTo("Usuario Registrado");
}
public void videos_subidos() {
getNavigator().addView("Videos Subidos", new Videos_subidos());
getNavigator().navigateTo("Videos Subidos");
}
public void mis_listas() {
getNavigator().addView("Mis Listas", new Listas_de_reproduccion());
getNavigator().navigateTo("Mis Listas");
}
public void suscripciones() {
getNavigator().addView("Suscripciones", new Suscripciones());
getNavigator().navigateTo("Suscripciones");
}
public void subir_video() {
getNavigator().addView("Subir video", new Subir_video());
getNavigator().navigateTo("Subir video");
}
public void mi_perfil_registrado() {
getNavigator().addView("Mi perfil registrado", new Mi_perfil());
getNavigator().navigateTo("Mi perfil registrado");
}
public void modificar_datos_personales() {
getNavigator().addView("Modificar datos personales", new Modificar_datos_personales());
getNavigator().navigateTo("Modificar datos personales");
}
public void modificar_video(Videos vide) {
getNavigator().addView("Modificar video", new Modificar_video(vide));
getNavigator().navigateTo("Modificar video");
}
public void aniadir_categoria() {
getNavigator().addView("Aniadir categoria", new Aniadir_Categoria());
getNavigator().navigateTo("Aniadir categoria");
}
public void administrador() {
getNavigator().addView("Administrador", new Administrador());
getNavigator().navigateTo("Administrador");
}
public void buscador(List<?> busqueda, String string) {
getNavigator().addView("Buscador", new Buscador_videos(busqueda,string));
getNavigator().navigateTo("Buscador");
}
public void perfil_administrador() {
getNavigator().addView("Mi perfil Admin", new Mi_perfil_Admin());
getNavigator().navigateTo("Mi perfil Admin");
}
public void recordarContrasenia() {
getNavigator().addView("Recordar Contrasenia", new Recordar_Contrasenia());
getNavigator().navigateTo("Recordar Contrasenia");
}
public void ver_perfil_usuario(Usuario_registrado seguidor) {
getNavigator().addView("Ver_perfil_usuario", new Ver_perfil_usuario(seguidor));
getNavigator().navigateTo("Ver_perfil_usuario");
}
public void ver_perfil_registrado(Usuario_registrado seguidor) {
getNavigator().addView("Ver_perfil_usuario", new Vista_perfil_Registrado(seguidor));
getNavigator().navigateTo("Ver_perfil_usuario");
}
public void ver_perfil_admin(Usuario_registrado seguidor) {
getNavigator().addView("Ver_perfil_usuario", new Vista_perfil_administrador(seguidor));
getNavigator().navigateTo("Ver_perfil_usuario");
}
public void visualizar_video_creador(Videos vide) {
getNavigator().addView("Visualizar video creador", new Visualizacion_video_creador(vide));
getNavigator().navigateTo("Visualizar video creador");
}
public void visualizar_video(Videos vide) {
getNavigator().addView("Visualizar video", new Visualizacion_video(vide));
getNavigator().navigateTo("Visualizar video");
}
public void visualizar_video_registrado(Videos vide) {
getNavigator().addView("Visualizar video registrado", new Visualizacion_video_registrado(vide));
getNavigator().navigateTo("Visualizar video registrado");
}
public void visualizar_video_admin(Videos vide) {
getNavigator().addView("Visualizar video admin", new Visualizacion_video_administrador(vide));
getNavigator().navigateTo("Visualizar video admin");
}
public void visualizar_video_comentarios(Videos vide) {
getNavigator().addView("Visualizar video comentarios", new Visualizacion_video_comentarios_deshabilitados(vide));
getNavigator().navigateTo("Visualizar video comentarios");
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
}
public void modificar_datos_Admin() {
getNavigator().addView("Modificar datos admin", new Modificar_Datos_Admin());
getNavigator().navigateTo("Modificar datos admin");
}
public void Mi_perfil_Admin() {
getNavigator().addView("perfil admin", new Mi_perfil_Admin());
getNavigator().navigateTo("perfil admin");
}
public void listausuarios() {
getNavigator().addView("lista usuarios", new Lista_Usuarios());
getNavigator().navigateTo("lista usuarios");
}
public void Categorias() {
getNavigator().addView("categorias", new Categorias());
getNavigator().navigateTo("categorias");
}
public void Lista_Video_Usuario(Usuario_registrado usuario_registrado) {
getNavigator().addView("lista video usuario", new Lista_Video_Usuario(usuario_registrado));
getNavigator().navigateTo("lista video usuario");
}
public void Lista_Usuarios() {
getNavigator().addView("lista usuarios", new Lista_Usuarios());
getNavigator().navigateTo("lista usuarios");
}
public void crearcategoria() {
getNavigator().addView("crear categoria", new Aniadir_Categoria());
getNavigator().navigateTo("crear categoria");
}
public void editarcategoria(database.Categorias categorias) {
getNavigator().addView("editar categoria", new Editar_Categoria(categorias));
getNavigator().navigateTo("editar categoria");
}
public void cambiarnombre(database.Listas_de_reproduccion listas_de_reproduccion) {
getNavigator().addView("cambiar nombre", new Cambiar_nombre(listas_de_reproduccion));
getNavigator().navigateTo("cambiar nombre");
}
public void Editar_lista(database.Listas_de_reproduccion listas_de_reproduccion) {
getNavigator().addView("editar lista", new Editar_lista(listas_de_reproduccion));
getNavigator().navigateTo("editar lista");
}
}
|
package model;
public class InterestVO {
private int seq_PID;
private int audience;
private int interest;
public int getSeq_PID() {
return seq_PID;
}
public void setSeq_PID(int seq_PID) {
this.seq_PID = seq_PID;
}
public int getAudience() {
return audience;
}
public void setAudience(int audience) {
this.audience = audience;
}
public int getInterest() {
return interest;
}
public void setInterest(int interest) {
this.interest = interest;
}
}
|
package it.bibliotecaweb.dao;
import java.util.Set;
import javax.persistence.EntityManager;
public interface IBaseDAO<T> {
public Set<T> list() throws Exception;
public T findById(int id) throws Exception;
public void update(T input) throws Exception;
public void insert(T input) throws Exception;
public void delete(T input) throws Exception;
public void setEntityManager(EntityManager entityManager);
public Set<T> findByExample(T input);
}
|
package pageObjec;
public class shigur {
}
|
package com.qiyewan.crm_joint.service;
import com.qiyewan.crm_joint.domain.Customer;
import java.util.List;
public interface CustomerService {
List<Customer> getCustomers(String phone);
}
|
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.DataLine.Info;
public class AudioIndexer {
public AudioIndexer(int numFrames,String AudioIndexPath) {
String filePath = AudioIndexPath;
File[] files = new File(filePath).listFiles();
String audioPath = null;
for (File file : files) {
if (file.isFile()) {
if(getFileExtension(file).equalsIgnoreCase(".wav")){
audioPath = file.getPath();
}
}
}
try {
AudioFormat audioFormat;
AudioInputStream audioInputStream = null;
Info info;
SourceDataLine dataLine;
int bufferSize;
int readBytes = 0;
byte[] audioBuffer;
String fileType = getParentPath(AudioIndexPath);
FileWriter fw = new FileWriter(fileType+".audioindex",true);
BufferedWriter bw = new BufferedWriter(fw);
FileInputStream inputStream;
File file = new File(audioPath);
bw.write("" + getcurrentName(AudioIndexPath) + " ");
int audiolen = (int)file.length();
bufferSize = (int) Math.round((double) audiolen * 42.0 / 30000.0);
int oneFrameSize = audiolen/numFrames;
System.out.println("audio: " + AudioIndexPath);
System.out.println("oneFrameSize: " + oneFrameSize);
System.out.println("audiolen: " + audiolen);
System.out.println("bufferSize: " + bufferSize);
audioBuffer = new byte[audiolen];
inputStream = new FileInputStream(file);
InputStream bufferedIn = new BufferedInputStream(inputStream);
audioInputStream = AudioSystem.getAudioInputStream(bufferedIn);
// Obtain the information about the AudioInputStream
audioFormat = audioInputStream.getFormat();
//System.out.println(audioFormat);
info = new Info(SourceDataLine.class, audioFormat);
// opens the audio channel
dataLine = null;
try {
dataLine = (SourceDataLine) AudioSystem.getLine(info);
dataLine.open(audioFormat, bufferSize);
} catch (LineUnavailableException e1) {
System.out.println(e1);
//throw new PlayWaveException(e1);
}
readBytes = audioInputStream.read(audioBuffer, 0, audioBuffer.length);
int temp[] = new int[oneFrameSize];
int index = 0;
int count = 0;
int tempMax = 0;
for (int audioByte = 0; audioByte < audioBuffer.length;)
{
//for (int channel = 0; channel < nbChannels; channel++)
//{
// Do the byte to sample conversion.
int low = (int) audioBuffer[audioByte];
audioByte++;
if (audioByte < audioBuffer.length) {
int high = (int) audioBuffer[audioByte];
audioByte++;
// .wav 16bits
int sample = (high << 8) + (low & 0x00ff);
temp[count] = sample;
//bw.write("" + sample + " ");
}
//System.out.println(sample);
//toReturn[index] = sample;
//}
count++;
if ((audioByte) % oneFrameSize == 0 || (audioByte + 1) % oneFrameSize == 0) {
count = 0;
int maxVal = maxValue(temp);
if (maxVal > tempMax)
tempMax = maxVal;
//System.out.println(maxVal);
bw.write("" + maxVal/1024 + " ");
}
index++;
}
System.out.println(tempMax);
bw.write("\n");
bw.close();
} catch (UnsupportedAudioFileException e1) {
System.out.println(e1);
} catch (IOException e1) {
System.out.println(e1);
} catch (Exception e) {
e.printStackTrace();
}
}
public int maxValue(int[] chars) {
int max = chars[0];
for (int ktr = 0; ktr < chars.length; ktr++) {
if (chars[ktr] > max) {
max = chars[ktr];
}
}
return max;
}
public int averageValue(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
return sum / nums.length;
}
public int[] getUnscaledAmplitude(byte[] eightBitByteArray)
{
int[] toReturn = new int[eightBitByteArray.length / 2];
int index = 0;
for (int audioByte = 0; audioByte < eightBitByteArray.length;)
{
//for (int channel = 0; channel < nbChannels; channel++)
//{
// Do the byte to sample conversion.
int low = (int) eightBitByteArray[audioByte];
audioByte++;
int high = (int) eightBitByteArray[audioByte];
audioByte++;
int sample = (high << 8) + (low & 0x00ff);
//System.out.println(sample);
toReturn[index] = sample;
//}
index++;
}
return toReturn;
}
private String getFileExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf(".");
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf);
}
private String getParentPath(String pathName) {
String name = pathName;
int lastIndexOf = name.lastIndexOf("\\");
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(0,lastIndexOf);
}
private String getcurrentName(String pathName) {
String name = pathName;
int lastIndexOf = name.lastIndexOf("\\");
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf+1);
}
} |
@javax.xml.bind.annotation.XmlSchema(namespace = "http://sis.gob.pe/", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package pe.gob.sis;
|
package fr.cea.nabla.interpreter.nodes.expression;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.VirtualFrame;
import fr.cea.nabla.interpreter.runtime.NablaNull;
public abstract class NablaReadArgumentNode extends NablaExpressionNode {
private final int index;
protected final FrameSlot[] sizeSlots;
public NablaReadArgumentNode(int index) {
this.index = index;
this.sizeSlots = null;
}
/*
* FIXME: is this used?
*/
public NablaReadArgumentNode(int index, FrameSlot[] sizeSlots) {
this.index = index;
this.sizeSlots = sizeSlots;
}
@Specialization(guards = "sizeSlots == null")
public Object doBasic(VirtualFrame frame) {
Object[] args = frame.getArguments();
if (index+2 < args.length) {
return args[index+2];
} else {
return NablaNull.SINGLETON;
}
}
}
|
///* Vladimir Ventura
// 00301144
// CIS252 - Data Structures
// Problem Set 2 Point 3 - Test
//
// This main class is only for testing the Custom Array List class*///
public class Main {
public static void main(String[] args) {
// write your code here
CustomArrayList<Integer> cal = new CustomArrayList<>();
for (int x = 0; x < 100; x++){
cal.insert(x);
cal.next();
}
cal.shout();
System.out.println(cal.currentPosition());
System.out.println(cal.get());
cal.moveToEnd();
System.out.println("After");
for (int x = 0; x < 100; x++){
cal.previous();
cal.remove();
}
cal.shout();
}
}
|
package frame;
import core.graph.Graph;
import core.path.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class MainFrame {
private enum TaleType {
TALE_TYPE_NONE,
TALE_TYPE_START,
TALE_TYPE_END,
TALE_TYPE_WALL,
TALE_TYPE_PATH
}
private final JFrame frame;
private static final int BUTTON_LEFT = 1;
private static final int BUTTON_RIGHT= 2;
private static int TALE_SIZE = 25;
private static final int BORDER_SIZE = 1;
private static int HEIGHT = 20;
private static int WIDTH = 20;
private static final int CANVAS_OFFSET = 60;
private final AtomicInteger clicked;
private TaleType[][] grid;
private final Map<TaleType, Color> colorMap;
private final Map<ButtonModel, TaleType> radioButtonMap;
private final Map<String, PathFindingAlgorithm> comboBoxMap;
private final ButtonGroup buttonGroup;
private JComboBox<String> combo;
private JTextArea resultField;
private JCheckBox checkBox;
private final Point startPoint;
private final Point endPoint;
private int tempWidth;
private int tempHeight;
private int tempTaleSize;
private final PathCanvasMouseHandler mouseHandler;
private class PathCanvas extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int xOff = 0;
int yOff = 0;
g.setColor(Color.lightGray);
g.fillRect(0, 0, super.getWidth(), super.getHeight());
for (int i = 0; i < MainFrame.HEIGHT; i++) {
for (int j = 0; j < MainFrame.WIDTH; j++) {
g.setColor(colorMap.get(grid[i][j]));
g.fillRect(xOff, yOff, TALE_SIZE - BORDER_SIZE, TALE_SIZE - BORDER_SIZE);
xOff += TALE_SIZE;
}
xOff = 0;
yOff += TALE_SIZE;
}
}
}
private class PathCanvasMouseHandler implements MouseMotionListener, MouseListener {
private PathCanvas canvas;
public void setCanvas(PathCanvas canvas){
this.canvas = null;
this.canvas = canvas;
}
@Override
public void mouseClicked(MouseEvent e) { }
@Override
public void mousePressed(MouseEvent e) {
boolean flag = true;
switch (e.getButton()) {
case MouseEvent.BUTTON1:
clicked.set(BUTTON_LEFT);
break;
case MouseEvent.BUTTON3:
clicked.set(BUTTON_RIGHT);
break;
default:
flag = false;
break;
}
if (flag && setTaleByMouseEvent(e, false))
canvas.repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1 || e.getButton() == MouseEvent.BUTTON3)
clicked.set(0);
}
@Override
public void mouseEntered(MouseEvent e) { }
@Override
public void mouseExited(MouseEvent e) { }
@Override
public void mouseDragged(MouseEvent e) {
if (clicked.get() > 0 && setTaleByMouseEvent(e, true))
canvas.repaint();
}
@Override
public void mouseMoved(MouseEvent e) { }
}
public MainFrame() {
tempWidth = 0;
tempHeight = 0;
tempTaleSize = 0;
mouseHandler = new PathCanvasMouseHandler();
clicked = new AtomicInteger(0);
colorMap = new HashMap<>();
radioButtonMap = new HashMap<>();
comboBoxMap = new LinkedHashMap<>();
buttonGroup = new ButtonGroup();
startPoint = new Point();
endPoint = new Point();
colorMap.put(TaleType.TALE_TYPE_NONE, Color.white);
colorMap.put(TaleType.TALE_TYPE_START, Color.green);
colorMap.put(TaleType.TALE_TYPE_END, Color.red);
colorMap.put(TaleType.TALE_TYPE_WALL, Color.black);
colorMap.put(TaleType.TALE_TYPE_PATH, Color.blue);
comboBoxMap.put("DFS", new DFS());
comboBoxMap.put("BFS", new BFS());
comboBoxMap.put("Dijkstra", new Dijkstra());
comboBoxMap.put("BellmanFord", new BellmanFord());
frame = new JFrame();
frame.setTitle("Path Finding");
setFrameSize();
frame.setFocusable(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
startPoint.setLocation(2 ,2);
endPoint.setLocation(4 , 4);
initialize();
frame.setVisible(true);
}
private void setFrameSize(){
int w = (TALE_SIZE * WIDTH) + 125;
int h = (TALE_SIZE * HEIGHT) + CANVAS_OFFSET + 60;
frame.setSize(Integer.max(w, 480), Integer.max(h, 320));
}
private void validatePoint(Point p, int defaultValue){
if (p.x > WIDTH || p.x < 0)
p.x = defaultValue;
if (p.y > HEIGHT || p.y < 0)
p.y = defaultValue;
}
private void initGrid(){
for (TaleType[] taleArr : grid){
Arrays.fill(taleArr, TaleType.TALE_TYPE_NONE);
}
validatePoint(startPoint, 0);
validatePoint(endPoint, Integer.min(WIDTH, HEIGHT) - 1);
grid[startPoint.y][startPoint.x] = TaleType.TALE_TYPE_START;
grid[endPoint.y][endPoint.x] = TaleType.TALE_TYPE_END;
}
private void applyFrameChange(JPanel panel){
if (tempWidth == 0 && tempHeight == 0 && tempTaleSize == 0)
return;
WIDTH = tempWidth == 0 ? WIDTH : tempWidth;
HEIGHT = tempHeight == 0 ? HEIGHT : tempHeight;
TALE_SIZE = tempTaleSize == 0 ? TALE_SIZE : tempTaleSize;
tempWidth = tempHeight = tempTaleSize = 0;
frame.remove(panel);
initialize();
setFrameSize();
}
private void addSpinnerExplanationText(String text, int x, int y, JPanel panel){
JTextArea textArea = new JTextArea(text);
textArea.setFont(new Font(textArea.getFont().getName(), Font.PLAIN, 12));
textArea.setBounds(x, y, 80, 18);
textArea.setOpaque(false);
textArea.setEditable(false);
panel.add(textArea);
}
private void addTaleTypeRadioButton(String text, int x, TaleType type, JPanel panel){
JRadioButton temp = new JRadioButton(text);
temp.setBounds(x, 5, 60, 25);
panel.add(temp);
buttonGroup.add(temp);
radioButtonMap.put(temp.getModel(), type);
buttonGroup.setSelected(temp.getModel(), true);
}
private void initialize() {
JPanel panel = new JPanel();
grid = new TaleType[HEIGHT][WIDTH];
initGrid();
// Add top shelf components
String[] keys = comboBoxMap.keySet().toArray(new String[0]);
combo = new JComboBox<>(keys);
combo.setBounds(5, 5, 100, 25);
panel.add(combo);
addTaleTypeRadioButton("Start", 110, TaleType.TALE_TYPE_START, panel);
addTaleTypeRadioButton("End", 170, TaleType.TALE_TYPE_END, panel);
addTaleTypeRadioButton("Wall", 230, TaleType.TALE_TYPE_WALL, panel);
resultField = new JTextArea();
resultField.setBounds(5, 30, frame.getWidth()-10, 25);
resultField.setEditable(false);
resultField.setOpaque(false);
resultField.setFont(new Font(resultField.getFont().getName(), Font.PLAIN, 20));
panel.add(resultField);
int spinnerX = (WIDTH * TALE_SIZE) + 15;
addSpinnerExplanationText("Width", spinnerX,60, panel);
addSpinnerExplanationText("Height", spinnerX, 110, panel);
addSpinnerExplanationText("Tale Size", spinnerX, 160, panel);
JSpinner widthSpinner = new JSpinner(new SpinnerNumberModel(WIDTH, 5, 75, 1));
widthSpinner.addChangeListener(e -> tempWidth = (int) widthSpinner.getValue());
widthSpinner.setBounds(spinnerX, 80, 80, 25);
panel.add(widthSpinner);
JSpinner heightSpinner = new JSpinner(new SpinnerNumberModel(HEIGHT, 5, 75, 1));
heightSpinner.addChangeListener(e -> tempHeight = (int) heightSpinner.getValue());
heightSpinner.setBounds(spinnerX, 130, 80, 25);
panel.add(heightSpinner);
JSpinner taleSizeSpinner = new JSpinner(new SpinnerNumberModel(TALE_SIZE, 10, 25, 1));
taleSizeSpinner.addChangeListener(e -> tempTaleSize = (int) taleSizeSpinner.getValue());
taleSizeSpinner.setBounds(spinnerX, 180, 80, 25);
panel.add(taleSizeSpinner);
JButton applyButton = new JButton("Apply");
applyButton.setBounds(spinnerX, 240, 80, 40);
applyButton.addActionListener(e -> applyFrameChange(panel));
panel.add(applyButton);
PathCanvas canvas = new PathCanvas();
canvas.setBounds(5, CANVAS_OFFSET, WIDTH * TALE_SIZE, HEIGHT * TALE_SIZE);
panel.add(canvas);
this.mouseHandler.setCanvas(canvas);
// Add panel to frame
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
// Add listeners
panel.addMouseMotionListener(this.mouseHandler);
panel.addMouseListener(this.mouseHandler);
// Add buttons
JButton pathButton = new JButton("Find");
pathButton.setBounds(290, 5, 80, 25);
pathButton.addActionListener(e -> {
findPath();
canvas.repaint();
});
panel.add(pathButton);
JButton clearButton = new JButton("Clear");
clearButton.setBounds(380, 5, 80, 25);
clearButton.addActionListener(e -> {
initGrid();
resultField.setText("");
canvas.repaint();
});
panel.add(clearButton);
checkBox = new JCheckBox("Diagonal Move");
checkBox.setBounds(475, 5, 180, 25);
checkBox.setSelected(false);
panel.add(checkBox);
}
private boolean addTale(int x, int y, TaleType type, boolean drag){
boolean ret = false;
if (drag){
if (type == TaleType.TALE_TYPE_WALL){
grid[y][x] = type;
ret = true;
}
} else {
if (type == TaleType.TALE_TYPE_START){
grid[startPoint.y][startPoint.x] = TaleType.TALE_TYPE_NONE;
startPoint.setLocation(x, y);
validatePoint(startPoint, 0);
} else if (type == TaleType.TALE_TYPE_END){
grid[endPoint.y][endPoint.x] = TaleType.TALE_TYPE_NONE;
endPoint.setLocation(x, y);
validatePoint(endPoint, Integer.min(WIDTH, HEIGHT) - 1);
}
grid[y][x] = type;
ret = true;
}
return ret;
}
private boolean removeTale(int x, int y){
if (grid[y][x] == TaleType.TALE_TYPE_WALL || grid[y][x] == TaleType.TALE_TYPE_PATH){
grid[y][x] = TaleType.TALE_TYPE_NONE;
return true;
}
return false;
}
private boolean setTaleByMouseEvent(MouseEvent e, boolean drag){
int x = e.getX();
int y = e.getY() - CANVAS_OFFSET;
boolean inBounds = (x >= 0 && x < WIDTH * TALE_SIZE) && (y >= 0 && y < HEIGHT * TALE_SIZE);
if (inBounds) {
x = x / TALE_SIZE;
y = y / TALE_SIZE;
if (clicked.get() == BUTTON_LEFT){
if (grid[y][x] == TaleType.TALE_TYPE_NONE || grid[y][x] == TaleType.TALE_TYPE_PATH) {
TaleType type = radioButtonMap.get(buttonGroup.getSelection());
return addTale(x, y, type, drag);
}
} else {
return removeTale(x, y);
}
}
return false;
}
private void clearPrevPath(){
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == TaleType.TALE_TYPE_PATH)
grid[i][j] = TaleType.TALE_TYPE_NONE;
}
}
}
private void findPath() {
clearPrevPath();
// Copy current grid information as boolean grid
boolean[][] tempGrid = new boolean[HEIGHT][WIDTH];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] != TaleType.TALE_TYPE_WALL)
tempGrid[i][j] = true;
}
}
PathFindingAlgorithm algo = comboBoxMap.get(String.valueOf(combo.getSelectedItem()));
startAlgorithm(algo, tempGrid);
}
private void startAlgorithm(PathFindingAlgorithm algo, boolean[][] grid) {
int start = (startPoint.y * WIDTH) + startPoint.x;
int end = (endPoint.y * WIDTH) + endPoint.x;
Graph g = new Graph(grid, checkBox.isSelected());
algo.solve(g, start);
if (algo.checkPath(end)) {
List<Integer> backtrace = algo.getBacktrace(start, end);
markPath(backtrace);
resultField.setForeground(Color.black);
resultField.setText("Path has been found and marked. Path distance: " + backtrace.size());
} else {
resultField.setForeground(Color.red);
resultField.setText("NO PATH FOUND");
}
}
private void markPath(List<Integer> path){
for (int point : path){
int x = point % WIDTH;
int y = point / WIDTH;
grid[y][x] = TaleType.TALE_TYPE_PATH;
}
}
} |
package org.kemal.controller;
import org.kemal.daoimpl.UserDao;
import org.kemal.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class IslemlerController {
@Autowired
private UserDao userdao;
@RequestMapping(value="/",method=RequestMethod.GET)
public String anasayfa(Model model)
{
return "welcome";
}
@RequestMapping(value="/loginpage",method=RequestMethod.GET)
public String loginPage()
{
return "loginpage";
}
@RequestMapping(value="/search",method=RequestMethod.GET)
public String showSearchPage()
{
return "search";
}
@RequestMapping(value="/newaccount",method=RequestMethod.GET)
public String showRegisterPage()
{
return "register";
}
@RequestMapping(value="/createaccount" , method=RequestMethod.POST)
public String createAccount(User user)
{
user.setEnabled(true);
user.setAuthority("ROLE_USER");
userdao.create(user);
return "accountcreated";
}
@RequestMapping(value="/controlpage",method=RequestMethod.GET)
public String showControlPage()
{
return "controlpage";
}
}
|
package com.ps.chatrooms.repository;
import com.ps.chatrooms.model.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findAllByActiveIsTrue();
Optional<User> findUserByUsernameAndActiveIsTrue(String username);
Optional<User> findByIdAndActiveIsTrue(Long id);
}
|
package Model;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.Group;
public class Model {
private ElectionRound election2020;
private static Set<Citizen> allCitizens = new Set<Citizen>();
private String name;
private int ID;
private int year;
private boolean inQur;
//private boolean isSoldier;
private boolean hasWeapon;
private String ballotType;
public Model() {
election2020 = new ElectionRound(9,2020);
addFirst(election2020);
}
public void draw(Group root) {
// ElectionRound.draw(root);
}
public static boolean addFirst(ElectionRound election2020) {
Ballot<Citizen> bRegular = new Ballot<Citizen>("Haglima 7", new Citizen());
Ballot<SickCitizen> bCorona = new Ballot<SickCitizen>("Haketer 3", new SickCitizen());
Ballot<Candidate> bCandidate = new Ballot<Candidate>("Star Center", new Candidate());
Ballot<SickCandidate> bCandidateCorona = new Ballot<SickCandidate>("The White House", new SickCandidate());
Ballot<Soldier> bSoldier = new Ballot<Soldier>("Base 7", new Soldier());
Ballot<SickSoldier> bSoldierCorona = new Ballot<SickSoldier>("Assuta Hospital", new SickSoldier());
// adding 6 Ballot
election2020.getCitizenBallots().add(bRegular);
election2020.getSickCitizenBallots().add(bCorona);
election2020.getCandidateBallots().add(bCandidate);
election2020.getSickCandidateBallots().add(bCandidateCorona);
election2020.getSoldierBallots().add(bSoldier);
election2020.getSickSoldierBallots().add(bSoldierCorona);
// adding 6 Citizen
Citizen c1 = new Citizen("Moshe", 287462123, 1994, false, bRegular);
election2020.addCitizen(c1);
allCitizens.add(c1);
SickCitizen c2 = new SickCitizen("Yehuda", 587462123, 1992, true, bCorona);
election2020.addCitizen(c2);
allCitizens.add(c2);
Soldier c3 = new Soldier("Yoni", 123456789, 1999, false, bSoldier, true);
election2020.addCitizen(c3);
allCitizens.add(c3);
Soldier c4 = new Soldier("Dan", 589475682, 2001, false, bSoldier, false);
election2020.addCitizen(c4);
allCitizens.add(c4);
Citizen c5 = new Citizen("Assaf", 320254213, 1991, false, bRegular);
election2020.addCitizen(c5);
allCitizens.add(c5);
SickSoldier c6 = new SickSoldier("Eldar", 215468957, 2001, true, bSoldierCorona, true);
election2020.addCitizen(c6);
allCitizens.add(c6);
// adding citizen to ballot happens in election2020 when we add citizen to vote
// list
// adding 3 Party
Party p1 = new Party("Licod", "right", 05, 12, 1973);
election2020.addParty(p1);
Party p2 = new Party("Havoda", "left", 01, 01, 2020);
election2020.addParty(p2);
Party p3 = new Party("Yesh-Atid", "center", 05, 12, 2010);
election2020.addParty(p3);
election2020.setWinParty(p1);
// adding 2 candidate to each party
Candidate cd1 = new Candidate("Benni", 123456789, 1970, false, bCandidate, 1, p1);
SickCandidate cd2 = new SickCandidate("Israel", 365842789, 1980, true, bCandidateCorona, 3, p1);
Candidate cd3 = new Candidate("Amir", 875421563, 1976, false, bCandidate, 1, p2);
Candidate cd4 = new Candidate("Orly", 547821356, 1986, false, bCandidate, 2, p2);
Candidate cd5 = new Candidate("Yair", 365478925, 1978, false, bCandidate, 1, p3);
SickCandidate cd6 = new SickCandidate("Moshe", 658742359, 1974, true, bCandidateCorona, 2, p3);
allCitizens.add(cd1);
allCitizens.add(cd2);
allCitizens.add(cd3);
allCitizens.add(cd4);
allCitizens.add(cd5);
allCitizens.add(cd6);
election2020.addCitizen(cd1);
election2020.addCitizen(cd2);
election2020.addCitizen(cd3);
election2020.addCitizen(cd4);
election2020.addCitizen(cd5);
election2020.addCitizen(cd6);
election2020.getCandidateParties().get(0).addCandidate(cd1);
election2020.getCandidateParties().get(0).addCandidate(cd2);
election2020.getCandidateParties().get(1).addCandidate(cd3);
election2020.getCandidateParties().get(1).addCandidate(cd4);
election2020.getCandidateParties().get(2).addCandidate(cd5);
election2020.getCandidateParties().get(2).addCandidate(cd6);
// add all Ballots to the same List
election2020.setAllBallotsInList();
return true;
}
public void updateBallot(String address,String type) {
if(type == "Regular") {
Ballot<Citizen> newBallot = new Ballot<Citizen>(address,new Citizen());
election2020.getCitizenBallots().add(newBallot);
}else if(type == "Military") {
Ballot<Soldier> newBallot = new Ballot<Soldier>(address, new Soldier());
election2020.getSoldierBallots().add(newBallot);
}else if(type == "Quarantined") {
Ballot<SickCitizen> newBallot = new Ballot<SickCitizen>(address, new SickCitizen());
election2020.getSickCitizenBallots().add(newBallot);
}else if(type == "Military Quarantined") {
Ballot<SickSoldier> newBallot = new Ballot<SickSoldier>(address, new SickSoldier());
election2020.getSickSoldierBallots().add(newBallot);
}else if(type == "Candidate") {
Ballot<Candidate> newBallot = new Ballot<Candidate>(address, new Candidate());
election2020.getCandidateBallots().add(newBallot);
}else {
Ballot<SickCandidate> newBallot = new Ballot<SickCandidate>(address, new SickCandidate());
election2020.getSickCandidateBallots().add(newBallot);
}
}
public boolean updateCitizen(String ballotAddress) {
Ballot<?> tempBallot;
Citizen newCitizen ;
if(ballotType == "Citizen") {
tempBallot = getBallot("Regular", ballotAddress);
newCitizen = new Citizen(name, ID, year, inQur, tempBallot);
}else if(ballotType == "Sick Citizen"){
tempBallot = getBallot("Corona", ballotAddress);
newCitizen = new SickCitizen(name, ID, year, inQur, tempBallot);
}else if(ballotType == "Soldier") {
tempBallot = getBallot("Military", ballotAddress);
newCitizen = new Soldier(name, ID, year, inQur, tempBallot,hasWeapon);
}else {
tempBallot = getBallot("Military Quarantined", ballotAddress);
newCitizen = new SickSoldier(name, ID, year, inQur, tempBallot,hasWeapon);
}
if(allCitizens.add(newCitizen)) {
if(election2020.addCitizen(newCitizen))
return true;
}
return false;
}
public boolean updateCandidate(String ballotAddress,String party,int rank) {
Ballot<?> tempBallot;
Citizen newCitizen ;
Party tempParty = new Party();
int index = 0;
for (int i = 0; i < election2020.getCandidateParties().size(); i++) {
if (party == election2020.getCandidateParties().get(i).getName()) {
tempParty = election2020.getCandidateParties().get(i);
index= i;
}
}
if(ballotType == "Candidate") {
tempBallot = getBallot("Candidate", ballotAddress);
newCitizen = new Candidate(name, ID, year, inQur, tempBallot,rank,tempParty);
election2020.getCandidateParties().get(index).addCandidate((Candidate)newCitizen);
}else {
tempBallot = getBallot("Corona Candidate", ballotAddress);
newCitizen = new SickCandidate(name, ID, year, inQur, tempBallot,rank,tempParty);
election2020.getCandidateParties().get(index).addCandidate((SickCandidate)newCitizen);
}
if(allCitizens.add(newCitizen)) {
if(election2020.addCitizen(newCitizen))
return true;
}
return false;
}
public String findTypeOfCitizen(int year,boolean inQur) {
year = 2020-year;
//check if is soldier or sick soldier
if(year>=18 && year<=21) {
if(inQur) {
return "Sick Soldier";
}
return "Soldier";
}
//check if citizen or sick citizen
if(inQur) {
return "Sick Citizen";
}
return "Citizen";
}
public String findTypeOfCandidate(boolean inQur) {
if(inQur)
return "Sick Candidate";
else
return "Candidate";
}
public Ballot<?> getBallot(String bType, String ballotddress) {
List<Ballot<?>> tempList = new ArrayList<Ballot<?>>();
switch (bType) {
case "Regular":
tempList.addAll(election2020.getCitizenBallots());
break;
case "Military Quarantined":
tempList.addAll(election2020.getSickSoldierBallots());
break;
case "Military":
tempList.addAll(election2020.getSoldierBallots());
break;
case "Corona":
tempList.addAll(election2020.getSickCitizenBallots());
break;
case "Candidate":
tempList.addAll(election2020.getCandidateBallots());
break;
case "Corona Candidate":
tempList.addAll(election2020.getSickCandidateBallots());
break;
}
for (int i = 0; i < tempList.size(); i++) {
if (ballotddress == tempList.get(i).getBoxAdress())
return tempList.get(i);
}
return null;
}
public void sendCitizenInfo(String name,String id,int year,boolean inQur,boolean hasSuit,boolean hasWeapon,String ballotType) {
this.name = name;
this.ID = Integer.decode(id);
this.year = year;
this.inQur = inQur;
this.hasWeapon = hasWeapon;
this.ballotType = ballotType;
}
public void sendCandidateInfo(String name, String id, int year, boolean inQur, String ballotType) {
this.name = name;
this.ID = Integer.decode(id);
this.year = year;
this.inQur = inQur;
this.ballotType = ballotType;
}
public void updateParty(String name,String wing,int day,int month,int year) {
Party newParty = new Party(name,wing,day,month,year);
election2020.addParty(newParty);
}
public ElectionRound getElection() {
return election2020;
}
}
|
package org.apache.helix.zookeeper.impl.client;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.apache.helix.msdcommon.datamodel.MetadataStoreRoutingData;
import org.apache.helix.msdcommon.exception.InvalidRoutingDataException;
import org.apache.helix.zookeeper.api.client.ChildrenSubscribeResult;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
import org.apache.helix.zookeeper.impl.factory.DedicatedZkClientFactory;
import org.apache.helix.zookeeper.util.HttpRoutingDataReader;
import org.apache.helix.zookeeper.zkclient.DataUpdater;
import org.apache.helix.zookeeper.zkclient.IZkChildListener;
import org.apache.helix.zookeeper.zkclient.IZkDataListener;
import org.apache.helix.zookeeper.zkclient.IZkStateListener;
import org.apache.helix.zookeeper.zkclient.ZkConnection;
import org.apache.helix.zookeeper.zkclient.callback.ZkAsyncCallbacks;
import org.apache.helix.zookeeper.zkclient.serialize.BasicZkSerializer;
import org.apache.helix.zookeeper.zkclient.serialize.PathBasedZkSerializer;
import org.apache.helix.zookeeper.zkclient.serialize.ZkSerializer;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Op;
import org.apache.zookeeper.OpResult;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implements and supports all ZK operations defined in interface {@link RealmAwareZkClient},
* except for session-aware operations such as creating ephemeral nodes, for which
* an {@link UnsupportedOperationException} will be thrown.
* <p>
* It acts as a single ZK client but will automatically route read/write/change subscription
* requests to the corresponding ZkClient with the help of metadata store directory service.
* It could connect to multiple ZK addresses and maintain a {@link ZkClient} for each ZK address.
* <p>
* Note: each Zk realm has its own event queue to handle listeners. So listeners from different ZK
* realms could be handled concurrently because listeners of a ZK realm are handled in its own
* queue. The concurrency of listeners should be aware of when implementing listeners for different
* ZK realms. The users should use thread-safe data structures if they wish to handle change
* callbacks.
*/
public class FederatedZkClient implements RealmAwareZkClient {
private static final Logger LOG = LoggerFactory.getLogger(FederatedZkClient.class);
private static final String FEDERATED_ZK_CLIENT = FederatedZkClient.class.getSimpleName();
private static final String DEDICATED_ZK_CLIENT_FACTORY =
DedicatedZkClientFactory.class.getSimpleName();
private final MetadataStoreRoutingData _metadataStoreRoutingData;
private final RealmAwareZkClient.RealmAwareZkConnectionConfig _connectionConfig;
private final RealmAwareZkClient.RealmAwareZkClientConfig _clientConfig;
// ZK realm -> ZkClient
private final Map<String, ZkClient> _zkRealmToZkClientMap;
private volatile boolean _isClosed;
private PathBasedZkSerializer _pathBasedZkSerializer;
// TODO: support capacity of ZkClient number in one FederatedZkClient and do garbage collection.
public FederatedZkClient(RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig,
RealmAwareZkClient.RealmAwareZkClientConfig clientConfig)
throws IOException, InvalidRoutingDataException {
if (connectionConfig == null) {
throw new IllegalArgumentException("RealmAwareZkConnectionConfig cannot be null!");
}
if (clientConfig == null) {
throw new IllegalArgumentException("RealmAwareZkClientConfig cannot be null!");
}
// Attempt to get MetadataStoreRoutingData
String msdsEndpoint = connectionConfig.getMsdsEndpoint();
if (msdsEndpoint == null || msdsEndpoint.isEmpty()) {
_metadataStoreRoutingData = HttpRoutingDataReader.getMetadataStoreRoutingData();
} else {
_metadataStoreRoutingData = HttpRoutingDataReader.getMetadataStoreRoutingData(msdsEndpoint);
}
_isClosed = false;
_connectionConfig = connectionConfig;
_clientConfig = clientConfig;
_pathBasedZkSerializer = clientConfig.getZkSerializer();
_zkRealmToZkClientMap = new ConcurrentHashMap<>();
}
@Override
public List<String> subscribeChildChanges(String path, IZkChildListener listener) {
return getZkClient(path).subscribeChildChanges(path, listener);
}
@Override
public ChildrenSubscribeResult subscribeChildChanges(String path, IZkChildListener listener,
boolean skipWatchingNodeNotExist) {
return getZkClient(path).subscribeChildChanges(path, listener, skipWatchingNodeNotExist);
}
@Override
public void unsubscribeChildChanges(String path, IZkChildListener listener) {
getZkClient(path).unsubscribeChildChanges(path, listener);
}
@Override
public void subscribeDataChanges(String path, IZkDataListener listener) {
getZkClient(path).subscribeDataChanges(path, listener);
}
@Override
public boolean subscribeDataChanges(String path, IZkDataListener listener,
boolean skipWatchingNodeNotExist) {
return getZkClient(path).subscribeDataChanges(path, listener, skipWatchingNodeNotExist);
}
@Override
public void unsubscribeDataChanges(String path, IZkDataListener listener) {
getZkClient(path).unsubscribeDataChanges(path, listener);
}
@Override
public void subscribeStateChanges(IZkStateListener listener) {
throwUnsupportedOperationException();
}
@Override
public void unsubscribeStateChanges(IZkStateListener listener) {
throwUnsupportedOperationException();
}
@Override
public void subscribeStateChanges(
org.apache.helix.zookeeper.zkclient.deprecated.IZkStateListener listener) {
throwUnsupportedOperationException();
}
@Override
public void unsubscribeStateChanges(
org.apache.helix.zookeeper.zkclient.deprecated.IZkStateListener listener) {
throwUnsupportedOperationException();
}
@Override
public void unsubscribeAll() {
_zkRealmToZkClientMap.values().forEach(ZkClient::unsubscribeAll);
}
@Override
public void createPersistent(String path) {
createPersistent(path, false);
}
@Override
public void createPersistent(String path, boolean createParents) {
createPersistent(path, createParents, ZooDefs.Ids.OPEN_ACL_UNSAFE);
}
@Override
public void createPersistent(String path, boolean createParents, List<ACL> acl) {
getZkClient(path).createPersistent(path, createParents, acl);
}
@Override
public void createPersistent(String path, Object data) {
create(path, data, CreateMode.PERSISTENT);
}
@Override
public void createPersistent(String path, Object data, List<ACL> acl) {
create(path, data, acl, CreateMode.PERSISTENT);
}
@Override
public String createPersistentSequential(String path, Object data) {
return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL);
}
@Override
public String createPersistentSequential(String path, Object data, List<ACL> acl) {
return create(path, data, acl, CreateMode.PERSISTENT_SEQUENTIAL);
}
@Override
public void createEphemeral(String path) {
create(path, null, CreateMode.EPHEMERAL);
}
@Override
public void createEphemeral(String path, String sessionId) {
createEphemeral(path, null, sessionId);
}
@Override
public void createEphemeral(String path, List<ACL> acl) {
create(path, null, acl, CreateMode.EPHEMERAL);
}
@Override
public void createEphemeral(String path, List<ACL> acl, String sessionId) {
create(path, null, acl, CreateMode.EPHEMERAL, sessionId);
}
@Override
public String create(String path, Object data, CreateMode mode) {
return create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, mode);
}
@Override
public String create(String path, Object data, List<ACL> acl, CreateMode mode) {
return create(path, data, acl, mode, null);
}
@Override
public void createEphemeral(String path, Object data) {
create(path, data, CreateMode.EPHEMERAL);
}
@Override
public void createEphemeral(String path, Object data, String sessionId) {
create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, sessionId);
}
@Override
public void createEphemeral(String path, Object data, List<ACL> acl) {
create(path, data, acl, CreateMode.EPHEMERAL);
}
@Override
public void createEphemeral(String path, Object data, List<ACL> acl, String sessionId) {
create(path, data, acl, CreateMode.EPHEMERAL, sessionId);
}
@Override
public String createEphemeralSequential(String path, Object data) {
return create(path, data, CreateMode.EPHEMERAL_SEQUENTIAL);
}
@Override
public String createEphemeralSequential(String path, Object data, List<ACL> acl) {
return create(path, data, acl, CreateMode.EPHEMERAL_SEQUENTIAL);
}
@Override
public String createEphemeralSequential(String path, Object data, String sessionId) {
return create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL,
sessionId);
}
@Override
public String createEphemeralSequential(String path, Object data, List<ACL> acl,
String sessionId) {
return create(path, data, acl, CreateMode.EPHEMERAL_SEQUENTIAL, sessionId);
}
@Override
public List<String> getChildren(String path) {
return getZkClient(path).getChildren(path);
}
@Override
public int countChildren(String path) {
return getZkClient(path).countChildren(path);
}
@Override
public boolean exists(String path) {
return getZkClient(path).exists(path);
}
@Override
public Stat getStat(String path) {
return getZkClient(path).getStat(path);
}
@Override
public boolean waitUntilExists(String path, TimeUnit timeUnit, long time) {
return getZkClient(path).waitUntilExists(path, timeUnit, time);
}
@Override
public void deleteRecursively(String path) {
getZkClient(path).deleteRecursively(path);
}
@Override
public boolean delete(String path) {
return getZkClient(path).delete(path);
}
@Override
@SuppressWarnings("unchecked")
public <T> T readData(String path) {
return (T) readData(path, false);
}
@Override
public <T> T readData(String path, boolean returnNullIfPathNotExists) {
return getZkClient(path).readData(path, returnNullIfPathNotExists);
}
@Override
public <T> T readData(String path, Stat stat) {
return getZkClient(path).readData(path, stat);
}
@Override
public <T> T readData(String path, Stat stat, boolean watch) {
return getZkClient(path).readData(path, stat, watch);
}
@Override
public <T> T readDataAndStat(String path, Stat stat, boolean returnNullIfPathNotExists) {
return getZkClient(path).readData(path, stat, returnNullIfPathNotExists);
}
@Override
public void writeData(String path, Object object) {
writeData(path, object, -1);
}
@Override
public <T> void updateDataSerialized(String path, DataUpdater<T> updater) {
getZkClient(path).updateDataSerialized(path, updater);
}
@Override
public void writeData(String path, Object data, int expectedVersion) {
writeDataReturnStat(path, data, expectedVersion);
}
@Override
public Stat writeDataReturnStat(String path, Object data, int expectedVersion) {
return getZkClient(path).writeDataReturnStat(path, data, expectedVersion);
}
@Override
public Stat writeDataGetStat(String path, Object data, int expectedVersion) {
return writeDataReturnStat(path, data, expectedVersion);
}
@Override
public void asyncCreate(String path, Object data, CreateMode mode,
ZkAsyncCallbacks.CreateCallbackHandler cb) {
getZkClient(path).asyncCreate(path, data, mode, cb);
}
@Override
public void asyncSetData(String path, Object data, int version,
ZkAsyncCallbacks.SetDataCallbackHandler cb) {
getZkClient(path).asyncSetData(path, data, version, cb);
}
@Override
public void asyncGetData(String path, ZkAsyncCallbacks.GetDataCallbackHandler cb) {
getZkClient(path).asyncGetData(path, cb);
}
@Override
public void asyncExists(String path, ZkAsyncCallbacks.ExistsCallbackHandler cb) {
getZkClient(path).asyncExists(path, cb);
}
@Override
public void asyncDelete(String path, ZkAsyncCallbacks.DeleteCallbackHandler cb) {
getZkClient(path).asyncDelete(path, cb);
}
@Override
public void watchForData(String path) {
getZkClient(path).watchForData(path);
}
@Override
public List<String> watchForChilds(String path) {
return getZkClient(path).watchForChilds(path);
}
@Override
public long getCreationTime(String path) {
return getZkClient(path).getCreationTime(path);
}
@Override
public List<OpResult> multi(Iterable<Op> ops) {
throwUnsupportedOperationException();
return null;
}
@Override
public boolean waitUntilConnected(long time, TimeUnit timeUnit) {
throwUnsupportedOperationException();
return false;
}
@Override
public String getServers() {
throwUnsupportedOperationException();
return null;
}
@Override
public long getSessionId() {
// Session-aware is unsupported.
throwUnsupportedOperationException();
return 0L;
}
@Override
public void close() {
if (isClosed()) {
return;
}
_isClosed = true;
synchronized (_zkRealmToZkClientMap) {
Iterator<Map.Entry<String, ZkClient>> iterator = _zkRealmToZkClientMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, ZkClient> entry = iterator.next();
String zkRealm = entry.getKey();
ZkClient zkClient = entry.getValue();
// Catch any exception from ZkClient's close() to avoid that there is leakage of
// remaining unclosed ZkClient.
try {
zkClient.close();
} catch (Exception e) {
LOG.error("Exception thrown when closing ZkClient for ZkRealm: {}!", zkRealm, e);
}
iterator.remove();
}
}
LOG.info("{} is successfully closed.", FEDERATED_ZK_CLIENT);
}
@Override
public boolean isClosed() {
return _isClosed;
}
@Override
public byte[] serialize(Object data, String path) {
return getZkClient(path).serialize(data, path);
}
@Override
public <T> T deserialize(byte[] data, String path) {
return getZkClient(path).deserialize(data, path);
}
@Override
public void setZkSerializer(ZkSerializer zkSerializer) {
_pathBasedZkSerializer = new BasicZkSerializer(zkSerializer);
_zkRealmToZkClientMap.values()
.forEach(zkClient -> zkClient.setZkSerializer(_pathBasedZkSerializer));
}
@Override
public void setZkSerializer(PathBasedZkSerializer zkSerializer) {
_pathBasedZkSerializer = zkSerializer;
_zkRealmToZkClientMap.values().forEach(zkClient -> zkClient.setZkSerializer(zkSerializer));
}
@Override
public PathBasedZkSerializer getZkSerializer() {
return _pathBasedZkSerializer;
}
@Override
public RealmAwareZkConnectionConfig getRealmAwareZkConnectionConfig() {
return _connectionConfig;
}
@Override
public RealmAwareZkClientConfig getRealmAwareZkClientConfig() {
return _clientConfig;
}
private String create(final String path, final Object dataObject, final List<ACL> acl,
final CreateMode mode, final String expectedSessionId) {
if (mode.isEphemeral()) {
throwUnsupportedOperationException();
}
// Create mode is not session-aware, so the node does not have to be created
// by the expectedSessionId.
return getZkClient(path).create(path, dataObject, acl, mode);
}
private ZkClient getZkClient(String path) {
// If FederatedZkClient is closed, should not return ZkClient.
checkClosedState();
String zkRealm = getZkRealm(path);
// Use this zkClient reference to protect the returning zkClient from being null because of
// race condition. Once we get the reference, even _zkRealmToZkClientMap is cleared by closed(),
// this zkClient is not null which guarantees the returned value not null.
ZkClient zkClient = _zkRealmToZkClientMap.get(zkRealm);
if (zkClient == null) {
// 1. Synchronized to avoid creating duplicate ZkClient for the same ZkRealm.
// 2. Synchronized with close() to avoid creating new ZkClient when all ZkClients are
// being closed and _zkRealmToZkClientMap is being cleared.
synchronized (_zkRealmToZkClientMap) {
// Because of potential race condition: thread B to get ZkClient could be blocked by this
// synchronized, while thread A is executing closed() in its synchronized block. So thread B
// could still enter this synchronized block once A completes executing closed() and
// releases the synchronized lock.
// Check closed state again to avoid creating a new ZkClient after FederatedZkClient
// is already closed.
checkClosedState();
if (!_zkRealmToZkClientMap.containsKey(zkRealm)) {
zkClient = createZkClient(zkRealm);
_zkRealmToZkClientMap.put(zkRealm, zkClient);
} else {
zkClient = _zkRealmToZkClientMap.get(zkRealm);
}
}
}
return zkClient;
}
private String getZkRealm(String path) {
String zkRealm;
try {
zkRealm = _metadataStoreRoutingData.getMetadataStoreRealm(path);
} catch (NoSuchElementException ex) {
throw new NoSuchElementException("Cannot find ZK realm for the path: " + path);
}
if (zkRealm == null || zkRealm.isEmpty()) {
throw new NoSuchElementException("Cannot find ZK realm for the path: " + path);
}
return zkRealm;
}
private ZkClient createZkClient(String zkAddress) {
LOG.debug("Creating ZkClient for realm: {}.", zkAddress);
return new ZkClient(new ZkConnection(zkAddress), (int) _clientConfig.getConnectInitTimeout(),
_clientConfig.getOperationRetryTimeout(), _pathBasedZkSerializer,
_clientConfig.getMonitorType(), _clientConfig.getMonitorKey(),
_clientConfig.getMonitorInstanceName(), _clientConfig.isMonitorRootPathOnly());
}
private void checkClosedState() {
if (isClosed()) {
throw new IllegalStateException(FEDERATED_ZK_CLIENT + " is closed!");
}
}
private void throwUnsupportedOperationException() {
throw new UnsupportedOperationException(
"Session-aware operation is not supported by " + FEDERATED_ZK_CLIENT
+ ". Instead, please use " + DEDICATED_ZK_CLIENT_FACTORY
+ " to create a dedicated RealmAwareZkClient for this operation.");
}
}
|
package com.japaricraft.japaricraftmod.render;
import com.japaricraft.japaricraftmod.mob.RoyalPenguin;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.math.MathHelper;
import org.lwjgl.opengl.GL11;
public class ModelRoyalPenguin extends ModelBase {
public ModelRenderer body;
public ModelRenderer hand_r;
public ModelRenderer bre_r;
public ModelRenderer ear_l;
public ModelRenderer head_ex;
public ModelRenderer hand_l;
public ModelRenderer body_l;
public ModelRenderer head;
public ModelRenderer bre_l;
public ModelRenderer body_p;
public ModelRenderer leg_r;
public ModelRenderer leg_l;
public ModelRenderer ear_r;
public ModelRenderer head_ex3;
public ModelRenderer twin_1;
public ModelRenderer twin_2;
public ModelRenderer ear_r2;
public ModelRenderer earr_3;
public ModelRenderer twin1_ex;
public ModelRenderer twin2_ex;
public ModelRenderer ear_l2;
public ModelRenderer ear_l3;
public ModelRoyalPenguin() {
this.textureWidth = 128;
this.textureHeight = 64;
this.leg_r = new ModelRenderer(this, 67, 26);
this.leg_r.setRotationPoint(-1.4F, 1.6F, 0.5F);
this.leg_r.addBox(-1.5F, 0.0F, -1.5F, 2, 8, 2, 0.0F);
this.setRotateAngle(leg_r, -0.048869219055841226F, 0.0F, -0.10471975511965977F);
this.twin2_ex = new ModelRenderer(this, 96, 43);
this.twin2_ex.setRotationPoint(0.0F, 3.5F, 0.0F);
this.twin2_ex.addBox(-2.0F, 0.0F, -0.5F, 4, 11, 1, 0.0F);
this.setRotateAngle(twin2_ex, 0.0F, 0.0F, -0.47123889803846897F);
this.ear_l3 = new ModelRenderer(this, 24, 12);
this.ear_l3.setRotationPoint(-1.0F, -3.0F, 0.0F);
this.ear_l3.addBox(0.0F, -1.5F, -1.0F, 2, 3, 2, 0.0F);
this.hand_l = new ModelRenderer(this, 14, 20);
this.hand_l.setRotationPoint(2.5F, 0.3F, 0.0F);
this.hand_l.addBox(0.0F, 0.0F, -1.0F, 2, 10, 2, 0.0F);
this.setRotateAngle(hand_l, 0.061086523819801536F, 0.0F, -0.08726646259971647F);
this.earr_3 = new ModelRenderer(this, 24, 27);
this.earr_3.setRotationPoint(0.0F, -3.0F, 0.0F);
this.earr_3.addBox(-1.0F, -1.5F, -1.0F, 2, 3, 2, 0.0F);
this.body = new ModelRenderer(this, 50, 12);
this.body.setRotationPoint(0.0F, 0.0F, 0.1F);
this.body.addBox(-2.5F, 0.0F, -1.5F, 5, 6, 3, 0.0F);
this.setRotateAngle(body, -0.05235987755982988F, 0.0F, 0.0F);
this.twin_1 = new ModelRenderer(this, 118, 43);
this.twin_1.setRotationPoint(2.5F, -4.0F, 3.0F);
this.twin_1.addBox(-0.5F, 0.0F, -0.5F, 1, 4, 1, 0.0F);
this.setRotateAngle(twin_1, 0.0F, 0.0F, -0.6981317007977318F);
this.ear_r2 = new ModelRenderer(this, 34, 21);
this.ear_r2.setRotationPoint(-0.5F, 0.5F, 0.5F);
this.ear_r2.addBox(-1.0F, -1.5F, -1.5F, 1, 2, 2, 0.0F);
this.head_ex = new ModelRenderer(this, 96, 20);
this.head_ex.setRotationPoint(0.0F, 0.0F, 0.0F);
this.head_ex.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.0F);
this.head = new ModelRenderer(this, 96, 0);
this.head.setRotationPoint(0.0F, 0.0F, 0.0F);
this.head.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.0F);
this.setRotateAngle(head, 0.05235987755982988F, 0.0F, 0.0F);
this.twin1_ex = new ModelRenderer(this, 107, 43);
this.twin1_ex.setRotationPoint(0.0F, 3.5F, 0.0F);
this.twin1_ex.addBox(-2.0F, 0.0F, -0.5F, 4, 11, 1, 0.0F);
this.setRotateAngle(twin1_ex, 0.0F, 0.0F, 0.47123889803846897F);
this.bre_l = new ModelRenderer(this, 33, 0);
this.bre_l.setRotationPoint(1.3F, 1.26F, -0.73F);
this.bre_l.addBox(-1.0F, -1.0F, -2.0F, 2, 2, 2, 0.0F);
this.setRotateAngle(bre_l, 0.8726646259971648F, -0.08726646259971647F, 0.0F);
this.head_ex3 = new ModelRenderer(this, 5, 34);
this.head_ex3.setRotationPoint(0.0F, -10.0F, -3.5F);
this.head_ex3.addBox(-6.0F, -3.0F, -0.5F, 12, 6, 1, 0.0F);
this.ear_l = new ModelRenderer(this, 24, 5);
this.ear_l.setRotationPoint(4.0F, -4.0F, 0.0F);
this.ear_l.addBox(0.0F, -1.5F, -1.5F, 1, 3, 3, 0.0F);
this.body_p = new ModelRenderer(this, 50, 30);
this.body_p.setRotationPoint(0.0F, 2.0F, 0.2F);
this.body_p.addBox(-2.5F, 0.0F, -1.5F, 5, 3, 3, 0.0F);
this.setRotateAngle(body_p, 0.048869219055841226F, 0.0F, 0.0F);
this.twin_2 = new ModelRenderer(this, 118, 50);
this.twin_2.setRotationPoint(-2.5F, -4.0F, 3.0F);
this.twin_2.addBox(-0.5F, 0.0F, -0.5F, 1, 4, 1, 0.0F);
this.setRotateAngle(twin_2, 0.0F, 0.0F, 0.6981317007977318F);
this.bre_r = new ModelRenderer(this, 24, 0);
this.bre_r.setRotationPoint(-1.2F, 1.2F, -0.7F);
this.bre_r.addBox(-1.0F, -1.0F, -2.0F, 2, 2, 2, 0.0F);
this.setRotateAngle(bre_r, 0.8726646259971648F, 0.08726646259971647F, 0.0F);
this.body_l = new ModelRenderer(this, 50, 23);
this.body_l.setRotationPoint(0.0F, 5.5F, 0.0F);
this.body_l.addBox(-2.0F, 0.0F, -1.0F, 4, 3, 2, 0.0F);
this.setRotateAngle(body_l, 0.05235987755982988F, 0.0F, 0.0F);
this.ear_l2 = new ModelRenderer(this, 34, 7);
this.ear_l2.setRotationPoint(0.5F, 0.5F, 0.5F);
this.ear_l2.addBox(0.0F, -1.5F, -1.5F, 1, 2, 2, 0.0F);
this.hand_r = new ModelRenderer(this, 5, 20);
this.hand_r.setRotationPoint(-4.5F, 0.3F, 0.0F);
this.hand_r.addBox(0.0F, 0.0F, -1.0F, 2, 10, 2, 0.0F);
this.setRotateAngle(hand_r, -0.061086523819801536F, 0.0F, 0.08726646259971647F);
this.leg_l = new ModelRenderer(this, 76, 26);
this.leg_l.setRotationPoint(2.4F, 1.7F, 0.5F);
this.leg_l.addBox(-1.5F, 0.0F, -1.5F, 2, 8, 2, 0.0F);
this.setRotateAngle(leg_l, -0.048869219055841226F, 0.0F, 0.10471975511965977F);
this.ear_r = new ModelRenderer(this, 24, 19);
this.ear_r.setRotationPoint(-4.0F, -4.0F, 0.0F);
this.ear_r.addBox(-1.0F, -1.5F, -1.6F, 1, 3, 3, 0.0F);
this.body_p.addChild(this.leg_r);
this.twin_2.addChild(this.twin2_ex);
this.ear_l.addChild(this.ear_l3);
this.body.addChild(this.hand_l);
this.ear_r.addChild(this.earr_3);
this.head.addChild(this.twin_1);
this.ear_r.addChild(this.ear_r2);
this.body.addChild(this.head);
this.twin_1.addChild(this.twin1_ex);
this.body.addChild(this.bre_l);
this.head.addChild(this.head_ex3);
this.body_l.addChild(this.body_p);
this.head.addChild(this.twin_2);
this.body.addChild(this.body_l);
this.ear_l.addChild(this.ear_l2);
this.body_p.addChild(this.leg_l);
this.head.addChild(this.ear_r);
this.head.addChild(this.ear_l);
}
@Override
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) {
this.body.render(f5);
GlStateManager.pushMatrix();
GlStateManager.translate(this.head_ex.offsetX, this.head_ex.offsetY, this.head_ex.offsetZ);
GlStateManager.translate(this.head_ex.rotationPointX * f5, this.head_ex.rotationPointY * f5, this.head_ex.rotationPointZ * f5);
GlStateManager.scale(1.1D, 1.1D, 1.1D);
GlStateManager.translate(-this.head_ex.offsetX, -this.head_ex.offsetY, -this.head_ex.offsetZ);
GlStateManager.translate(-this.head_ex.rotationPointX * f5, -this.head_ex.rotationPointY * f5, -this.head_ex.rotationPointZ * f5);
this.head_ex.render(f5);
GlStateManager.popMatrix();
this.bre_r.render(f5);
this.hand_r.render(f5);
}
//下は特殊なモデルを動かすのに必須
public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn) {
if (!(entityIn instanceof RoyalPenguin)) {
return;
}
RoyalPenguin entity = (RoyalPenguin) entityIn;
boolean flag = entityIn instanceof EntityLivingBase && ((EntityLivingBase) entityIn).getTicksElytraFlying() > 4;
this.head.rotateAngleY = netHeadYaw * 0.017453292F;
this.head_ex.rotateAngleY = netHeadYaw * 0.017453292F;
if (flag) {
this.head.rotateAngleX = -((float) Math.PI / 4F);
this.head_ex.rotateAngleX = -((float) Math.PI / 4F);
} else {
this.head.rotateAngleX = headPitch * 0.017453292F;
this.head_ex.rotateAngleX = headPitch * 0.017453292F;
}
this.body.rotateAngleY = 0.0F;
float f = 1.0F;
if (flag) {
f = (float) (entityIn.motionX * entityIn.motionX + entityIn.motionY * entityIn.motionY + entityIn.motionZ * entityIn.motionZ);
f = f / 0.2F;
f = f * f * f;
}
if (f < 1.0F) {
f = 1.0F;
}
this.hand_r.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + (float) Math.PI) * 2.0F * limbSwingAmount * 0.5F / f;
this.hand_l.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 2.0F * limbSwingAmount * 0.5F / f;
this.hand_r.rotateAngleZ = 0.0F;
this.hand_l.rotateAngleZ = 0.0F;
this.leg_r.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount / f;
this.leg_l.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + (float) Math.PI) * 1.4F * limbSwingAmount / f;
this.leg_r.rotateAngleY = 0.0F;
this.leg_l.rotateAngleY = 0.0F;
this.leg_r.rotateAngleZ = 0.0F;
this.leg_l.rotateAngleZ = 0.0F;
if (entity.isSitting() || this.isRiding) {
this.leg_r.rotateAngleX = -1.4137167F;
this.leg_r.rotateAngleY = ((float) Math.PI / 10F);
this.leg_r.rotateAngleZ = 0.07853982F;
this.leg_l.rotateAngleX = -1.4137167F;
this.leg_l.rotateAngleY = -((float) Math.PI / 10F);
this.leg_l.rotateAngleZ = -0.07853982F;
} else {
this.leg_r.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount / f;
this.leg_l.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + (float) Math.PI) * 1.4F * limbSwingAmount / f;
this.leg_r.rotateAngleY = 0.0F;
this.leg_l.rotateAngleY = 0.0F;
this.leg_r.rotateAngleZ = 0.0F;
this.leg_l.rotateAngleZ = 0.0F;
}
this.hand_r.rotateAngleY = 0.0F;
this.hand_r.rotateAngleZ = 0.0F;
this.hand_r.rotateAngleZ += MathHelper.cos(ageInTicks * 0.09F) * 0.05F + 0.05F;
this.hand_l.rotateAngleZ -= MathHelper.cos(ageInTicks * 0.09F) * 0.05F + 0.05F;
this.hand_r.rotateAngleX += MathHelper.sin(ageInTicks * 0.067F) * 0.05F;
this.hand_l.rotateAngleX -= MathHelper.sin(ageInTicks * 0.067F) * 0.05F;
GL11.glTranslatef(0F, 0.4F, 0F);
}
/**
* This is a helper function from Tabula to set the rotation of model parts
*/
public void setRotateAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
}
|
package de.niklaskiefer.bnclWeb;
import de.niklaskiefer.bnclCore.BnclToXmlWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class);
@RequestMapping(value = "/api/convert", method = RequestMethod.POST)
public String convert(@RequestBody String bncl) throws Exception {
return convertBnclToXML(bncl);
}
private String convertBnclToXML(String bncl) throws Exception {
BnclToXmlWriter writer = new BnclToXmlWriter();
return writer.convertBnclToXML(bncl);
}
}
|
package be.kdg.fastrada.model;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;
import static org.junit.Assert.assertEquals;
/**
* Test for the password reset tokens.
*/
public class TestPasswordResetToken {
private PasswordResetToken token;
private PasswordResetToken token2;
@Before
public void setUp() {
token = new PasswordResetToken("token1");
token2 = new PasswordResetToken("token2");
token.setExpiryDate(new Date());
token.addOneDay();
token.setToken("token3");
token.setTokenId("3");
token2.setExpiryDate(new Date());
}
@Test
public void testExpiryDate() {
Date temp = new Date();
token2.getExpiryDate().setTime(temp.getTime() + 86400000);
assertEquals(token2.getExpiryDate(), token.getExpiryDate());
}
@Test
public void testToken() {
assertEquals("token3", token.getToken());
}
@Test
public void testTokenId() {
assertEquals("3", token.getTokenId());
}
}
|
/**
* 湖北安式软件有限公司
* Hubei Anssy Software Co., Ltd.
* FILENAME : PasswdVo.java
* PACKAGE : com.anssy.inter.base.vo
* CREATE DATE : 2016-8-13
* AUTHOR : make it
* MODIFIED BY :
* DESCRIPTION :
*/
package com.anssy.inter.base.vo;
/**
* @author make it
* @version SVN #V1# #2016-8-13#
* 用户信息接口参数辅助类
*/
public class PasswdVo {
/**
* 老密码
*/
private String oldPasswd;
/**
* 新密码
*/
private String newPasswd;
public String getOldPasswd() {
return oldPasswd;
}
public void setOldPasswd(String oldPasswd) {
try {
// oldPasswd=BASE64.decryptBASE64(oldPasswd).toString();
} catch (Exception e) {
}
this.oldPasswd = oldPasswd;
}
public String getNewPasswd() {
return newPasswd;
}
public void setNewPasswd(String newPasswd) {
try {
// newPasswd=BASE64.decryptBASE64(newPasswd).toString();
} catch (Exception e) {
}
this.newPasswd = newPasswd;
}
} |
package Models;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.annotations.Expose;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
public abstract class Person implements Serializable {
protected String directory;
protected File dir;
protected File info;
protected File[] files;
@Expose
protected String username;
@Expose
protected String password;
protected Person(String directory) {
this.directory = directory;
this.dir = new File(this.directory);
this.files = dir.listFiles();
}
public abstract boolean login(String username, String password) throws FileNotFoundException, IOException;
protected boolean findAccount(String username, String password) throws IOException {
boolean found = false;
for (int i = 0; i < this.files.length && !found; i++) {
if (this.files[i].getName().equals(username + ".json")) {
this.info = this.files[i];
found = true;
}
}
if(!found){
return false;
}
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader(this.directory + this.info.getName()));
JsonObject jsonObject = (JsonObject) obj;
if (password.equals((String) jsonObject.get("password").getAsString())) {
return true;
}
return false;
}
public boolean isUsernameFree(String username) {
username = username + ".json";
File[] filesCid = new File("DataBase/ClientsDataBase").listFiles();
File[] filesProtec = new File("DataBase/WorkersDataBase").listFiles();
for (File file : filesCid) {
if (username.equals(file.getName())) {
return false;
}
}
for (File file : filesProtec) {
if (username.equals(file.getName())) {
return false;
}
}
return true;
}
public String getUsername(){
return this.username;
}
}
|
package control;
import java.util.ArrayList;
import java.util.Scanner;
import model.Jogador;
import model.Time;
public class Programa {
public static void main(String[] args) {
Scanner leia = new Scanner(System.in);
System.out.println("Cadastro de Time");
System.out.print("Digite a sigla: ");
String sigla = leia.next();
System.out.print("Digite a Descrição: ");
String descricao = leia.next();
Time time = new Time(sigla, descricao);
System.out.println("CADASTRO DE JOGADOR");
char resposta = 'S';
int numero;
String nome, posicao;
do {
System.out.print("Digite o numero: ");
numero = leia.nextInt();
System.out.print("Digite o nome: ");
nome = leia.next();
System.out.print("Digite posição: ");
posicao = leia.next();
Jogador jog = new Jogador(numero, nome, posicao);
time.adJogador(jog);
System.out.print("Deseja conmtinuar? <S/N> ");
resposta = leia.next().toUpperCase().charAt(0);
}while(resposta == 'S');
System.out.println("DADOS DO TIME");
System.out.println("Sigla: " + time.getSigla());
System.out.println("Descrição: " + time.getDescricao());
ArrayList<Jogador> lista = time.getListaJog();
System.out.println("Lista de Jogadores");
for(Jogador jogTemp : lista) {
System.out.println(jogTemp.getNumero() + ". " + jogTemp.getNome() + " - " + jogTemp.getPosicao());
}
}
}
|
package com.ctgu.lan.manage.dao;
import com.ctgu.lan.manage.model.Pharmacy;
import java.util.List;
public interface PharmacyMapper {
int deleteByPrimaryKey(Integer id);
int insert(Pharmacy record);
Pharmacy selectByPrimaryKey(Integer id);
List<Pharmacy> selectAll();
int updateByPrimaryKey(Pharmacy record);
} |
package com.ibisek.outlanded.utils;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import android.util.Base64;
import android.util.Log;
import com.ibisek.outlanded.net.HttpResponseHandler;
import com.ibisek.outlanded.net.MyHttpClient;
import com.ibisek.outlanded.net.ParsedHttpResponse;
public class CompetitionModeLocationSender implements HttpResponseHandler {
private final static String TAG = CompetitionModeLocationSender.class.getSimpleName();
/**
* Shares landing location on the server.
*
* @param competitionNo
* @param registrationNo
* @param latitude in degrees
* @param longitude in degrees
* @param nearestPoi
*/
public void sendToServer(String competitionNo, String registrationNo, double latitude, double longitude, String nearestPoi) {
if (competitionNo != null && !"".equals(competitionNo)) {
// format GPS position:
String lat = String.format("%.4f", latitude);
String lon = String.format("%.4f", longitude);
// message format: "AF;OK-9000;timestamp-in-seconds;latitude;longitude"
String message = String.format("%s;%s;%s;%s;%s;%s", competitionNo, registrationNo, new Date().getTime() / 1000, lat, lon, nearestPoi);
Log.d(TAG, "Message to node0 queue: " + message);
Map<String, String> params = new HashMap<String, String>();
params.put("topic", Configuration.getNode0Topic());
params.put("message", Base64.encodeToString(message.getBytes(Charset.forName("utf-8")), Base64.DEFAULT));
params.put("msgType", "REGULAR");
new MyHttpClient().doPost(Configuration.getOutlandedQueueUrl(), params, this);
}
}
@Override
public Object handleResponse(ParsedHttpResponse httpResponse) {
if (httpResponse != null && httpResponse.getStatus() != 200) {
// nix
}
return null;
}
}
|
package kiki.AccountCal.Beta;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
/**统计表**/
public class Statistic extends Activity {
//数据库标签
private KikiDB DbAssistant;
private Cursor mDbCursor;
private TextView calDisplay; //显示合计
private TextView mTimeDisplay; //显示开始日期
private TextView mETimeDisplay; //显示结束日期
private Button mPickTime; //开始日期控制按钮
private Button mEPickTime; //结束日期控制按钮
//设定开始时间
private int mYear;
private int mMonth;
private int mDay;
//设定结束时间
private int mEYear;
private int mEMonth;
private int mEDay;
//DatePicker
static final int DATE_DIALOG_ID=0;
static final int DATE_END_DIALOG_ID=1;
//显示查询结果
private ListView itemStaList;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.statistic);
//初始化
staViewIni();
}
//设置菜单
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0,0,0,"生成统计");
menu.add(0,1,1,"存档");
return super.onCreateOptionsMenu(menu);
}
//响应设置菜单
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case 0:break;
case 1:
try {
save();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent=new Intent();
intent.setClass(this, Statistic.class);
this.finish();
startActivity(intent);
break;
default:break;
}
return super.onOptionsItemSelected(item);
}
//设定显示列表
private void itemListSetup(){
}
//该Activity的时间显示
private void updateTime() {
mTimeDisplay.setText(
new StringBuilder().append(pad(mYear))
.append("-")
.append(pad(mMonth))
.append("-")
.append(pad(mDay))
);
mETimeDisplay.setText(
new StringBuilder().append(pad(mEYear))
.append("-")
.append(pad(mEMonth))
.append("-")
.append(pad(mEDay))
);
}
//初始化界面
private void staViewIni(){
mTimeDisplay=(TextView)findViewById(R.id.sta_beginTime); //开始时间对话框
mETimeDisplay=(TextView)findViewById(R.id.sta_endTime); //结束时间对话框
itemStaList=(ListView)findViewById(R.id.staList); //统计列表
mPickTime=(Button)findViewById(R.id.pickTime); //时间控制按钮
mEPickTime=(Button)findViewById(R.id.pickEndTime); //结束时间控制按钮
calDisplay=(TextView)findViewById(R.id.staText);
//监听
mPickTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DATE_DIALOG_ID);
}
});
mEPickTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DATE_END_DIALOG_ID);
}
});
final Calendar c=Calendar.getInstance();
//初始化开始时间
mYear=c.get(Calendar.YEAR);
mMonth=c.get(Calendar.MONTH)+1;
mDay=c.get(Calendar.DAY_OF_MONTH);
//初始化结束时间
mEYear=c.get(Calendar.YEAR);
mEMonth=c.get(Calendar.MONTH)+1;
mEDay=c.get(Calendar.DAY_OF_MONTH);
updateTime(); //更新日期显示
// getData();
}
//将设定参数转换为Date格式
private Long dateConvert(int year,int month,int day){
Calendar mDate=Calendar.getInstance();
mDate.set(year, month-1, day,0,0,0);
return mDate.getTime().getTime();
}
//日期补零
private String pad(int c){
if(c>=10){
return String.valueOf(c);
}else{
return "0"+String.valueOf(c);
}
}
//callback Date Dialog 设定开始时间
private DatePickerDialog.OnDateSetListener mSetDateListener=new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
mYear=year;
mMonth=monthOfYear+1;
mDay=dayOfMonth;
updateTime();
getData();
}
};
//设定结束时间
private DatePickerDialog.OnDateSetListener mSetEndDateListener=new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
mEYear=year;
mEMonth=monthOfYear+1;
mEDay=dayOfMonth;
updateTime();
getData();
}
};
//响应createDialog,根据id判断
protected Dialog onCreateDialog(int id){
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mSetDateListener,
mYear,mMonth-1,mDay);
case DATE_END_DIALOG_ID:
return new DatePickerDialog(this,
mSetEndDateListener,
mEYear,mEMonth-1,mEDay);
}
return null;
}
/**
*
//将记录读出并输出到textView中
private void tryRead(){
try {
String testText=read();
if(testText!=null){
mTimeDisplay.setText(testText);
}else{
mTimeDisplay.setText("have no text in the file or file not exist");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
* */
//将记录存档
void save() throws IOException{
DbAssistant=new KikiDB(this);
DbAssistant.open();
//mDbCursor=DbAssistant.getSomething(); //取得数据
mDbCursor=DbAssistant.getAll();
int rowCount=mDbCursor.getCount();
int columnCount=mDbCursor.getColumnCount();
//将记录存在手机ROM中
/*
String fileName="test.txt";
FileOutputStream fos=Statistic.this.openFileOutput(fileName, Context.MODE_PRIVATE);
for(int i=0;i<rowCount;i++){
mDbCursor.moveToPosition(i);
StringBuffer sb=new StringBuffer();
for(int j=0;j<columnCount;j++){
sb.append(mDbCursor.getString(j));
sb.append("|");
}
sb.append("\n");
fos.write(sb.toString().getBytes());
}
fos.close();
*/
Log.v("", "开始存档");
//将记录存在手机SD卡中
String sdStatus=Environment.getExternalStorageState();
if(!sdStatus.equals(Environment.MEDIA_MOUNTED)){
//没有检测到SD卡,退出
Log.v("", "SD卡不存在,退出");
return;
}
try{
// String pathName="/mnt/sdcard/test/";
String saveFileName="/sdcard/test.txt";
// File path=new File(pathName);
File file=new File(saveFileName);
// if(!path.exists()){
//建立存档目录
// Log.v("", "建立目录");
// try{
// path.mkdir();
// }catch(Exception e){
// Log.v("", e.toString());
// }
// }
if(!file.exists()){
//建立文件
Log.v("", "建立文件");
try{
file.createNewFile();
}catch(Exception e){
Log.v("", e.toString());
}
}
//写文件
FileOutputStream fos=new FileOutputStream(file);
for(int i=0;i<rowCount;i++){
mDbCursor.moveToPosition(i);
StringBuffer sb=new StringBuffer();
for(int j=0;j<columnCount;j++){
sb.append(mDbCursor.getString(j));
sb.append("|");
}
sb.append("\n");
fos.write(sb.toString().getBytes());
}
fos.close();
}catch(Exception e){
Log.v("", e.toString());
}
}
//取出记录
String read() throws IOException{
FileInputStream fis=Statistic.this.openFileInput("test.txt");
ByteArrayOutputStream outs=new ByteArrayOutputStream();
byte buffer[]=new byte[1024];
int len=0;
while((len=fis.read(buffer))!=-1){
outs.write(buffer, 0, len);
}
fis.close();
outs.close();
return outs.toString();
}
//根据时间参数进行记录查询(使用另一种listView),嵌套textView
private void getData(){
DbAssistant=new KikiDB(this);
DbAssistant.open();
Long tmlBeginTime=dateConvert(mYear, mMonth, mDay);
Long tmlEndTime=dateConvert(mEYear, mEMonth, mEDay+1);
mDbCursor=DbAssistant.getSomething(tmlBeginTime,tmlEndTime);
int rowCount=mDbCursor.getCount();
int columnCount=mDbCursor.getColumnCount();
double incomeCal=0;
double paymentCal=0;
ArrayList<HashMap<String, String>> resultList=new ArrayList<HashMap<String,String>>();
for(int i=0;i<rowCount;i++){
mDbCursor.moveToPosition(i);
/**
* 范例
mDbCursor.getString(1); //获取时间
mDbCursor.getString(2); //获取类型
mDbCursor.getString(3); //数据内容
mDbCursor.getString(4); //金额
* */
HashMap<String, String> map=new HashMap<String, String>();
Date recDate=new Date();
recDate.setTime(Long.parseLong(mDbCursor.getString(1)));
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String tmldate=dateFormat.format(recDate);
map.put("staItemTitle", mDbCursor.getString(3));
map.put("staItemText", mDbCursor.getString(4));
map.put("staItemTextAdd", tmldate);
if(mDbCursor.getString(2).equals("income")){
map.put("staItemTextType", "收入");
incomeCal+=Double.parseDouble(mDbCursor.getString(4));
}else if(mDbCursor.getString(2).equals("payment")){
map.put("staItemTextType", "支出");
paymentCal+=Double.parseDouble(mDbCursor.getString(4));
}
resultList.add(map);
}
SimpleAdapter adapter=new SimpleAdapter(this,resultList,R.layout.stalistitem,new String[]{"staItemTitle","staItemText","staItemTextAdd","staItemTextType"},new int[]{R.id.staItemTitle,R.id.staItemText,R.id.staItemTextAdd,R.id.staItemTextType});
itemStaList.setAdapter(adapter);
calDisplay.setText("收入总计: "+String.valueOf(incomeCal)+" 支出总计:"+String.valueOf(paymentCal));
}
}
|
package com.appunite.ffmpeg;
import android.annotation.TargetApi;
import android.os.Build.VERSION;
import android.view.View;
import android.view.View.MeasureSpec;
import com.yuneec.flightmode15.Utilities;
public class ViewCompat {
public static final int MEASURED_SIZE_MASK = 16777215;
public static final int MEASURED_STATE_MASK = -16777216;
public static final int MEASURED_STATE_TOO_SMALL = 16777216;
public static int resolveSize(int size, int measureSpec) {
if (VERSION.SDK_INT >= 11) {
return View.resolveSize(size, measureSpec);
}
return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
}
@TargetApi(11)
public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
if (VERSION.SDK_INT >= 11) {
return View.resolveSizeAndState(size, measureSpec, childMeasuredState);
}
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case Utilities.FLAG_HOMEKEY_DISPATCHED /*-2147483648*/:
if (specSize >= size) {
result = size;
break;
}
result = specSize | MEASURED_STATE_TOO_SMALL;
break;
case 0:
result = size;
break;
case 1073741824:
result = specSize;
break;
}
return (MEASURED_STATE_MASK & childMeasuredState) | result;
}
}
|
package registration;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientConnection {
private PrintWriter out;
private Socket socket;
private boolean connected;
public ClientConnection() {
connected = false;
}
public boolean tryToConnect(String ipAddress, int port, int timeout) {
//TODO use of timeout
if(!connected) {
System.out.println("Attemping to connect to host " + ipAddress + " on port " + port + ".");
try {
socket = new Socket(ipAddress, port);
out = new PrintWriter(socket.getOutputStream(), true);
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + ipAddress);
return false;
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: " + ipAddress);
return false;
}
connected = true;
}
return true;
}
public boolean disconnect() {
if(connected) {
try{
out.close();
socket.close();
connected = false;
return true;
} catch(IOException e) {
System.err.println("Failed to disconnect.");
return false;
}
}
return false;
}
public boolean isConnected() {
return connected;
}
public void sendData(String data) {
out.println(data);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.