text
stringlengths 10
2.72M
|
|---|
package com.scnuweb.service;
import java.util.List;
import java.util.Map;
import com.scnuweb.dao.ExamItemDAO;
import com.scnuweb.entity.Exam;
import com.scnuweb.entity.ExamItem;
import com.scnuweb.entity.User;
public interface ExamItemService extends BaseService<ExamItemDAO>{
public List<ExamItem> getAllExamItems();
public List<ExamItem> getExamItemsByParams(Map<String, Object> params);
public List<ExamItem> getExamItemsByExam(Long examId);
public ExamItem addExamItem(ExamItem examItem);
public ExamItem updateExamItem(ExamItem examItem);
public void delete(Long examItemId);
public ExamItem getExamItemById(Long examItemId);
}
|
package kata2;
import java.util.HashMap;
public class Kata2 {
public static void main(String[] args) {
Person javi = new Person("Javi", 20);
Person carlos = new Person("Carlos", 22);
Person alvaro = new Person("Alvaro", 18);
Person adan = new Person("Adan", 21);
Person dani = new Person("Dani", 20);
Person jose = new Person("Jose", 19);
System.out.println("Tengo: "+javi.getAge());
System.out.println("Mi nombre es: "+javi.getName());
javi.setName("Javier");
System.out.println("Me cambie el nombre a: "+javi.getName());
System.out.println("Javi es un: "+Person.getType());
Person[] people = {javi, carlos, alvaro, adan, dani, jose};
Person[] preguntas = {carlos, adan, dani, adan, jose, adan, jose};
HashMap <Person,Integer> histogram = new HashMap();
for (int i = 0; i < people.length; i++) {
histogram.put(people[i],0);
}
System.out.println("Adan ha preguntado: "+histogram.get(adan));
System.out.println("Alvaro esta en clase? "+histogram.containsKey(alvaro));
System.out.println("Adan esta en clase? "+histogram.containsKey(adan));
System.out.println(Person.getFrecuency(histogram, preguntas));
}
}
|
package com.team6.app.quiz;
import java.util.Date;
import java.util.List;
import org.springframework.data.annotation.Id;
public class Quiz {
public Quiz(String name, List<Question> questions) {
this.name = name;
this.questions = questions;
this.difficulty = 1;
this.creationTime = new Date();
}
@Id
private String id;
private String name;
private String description;
private String creatorId;
private String categoryId;
private List<Question> questions;
private Integer difficulty;
private Date creationTime;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getCreatorId() {
return creatorId;
}
public String getCategoryId() {
return categoryId;
}
public List<Question> getQuestions() {
return questions;
}
public Integer getDifficulty() {
return difficulty;
}
public Date getCreationTime() {
return creationTime;
}
}
|
package src;
public class Token {
private TokenType type;
private String identStr;
private double numVal;
private char unknownChar;
public Token(TokenType type) {
this.type = type;
}
public void setIdentStr(String identStr) {
if (type == TokenType.IDENTFIFIER)
this.identStr = identStr;
}
public void setNumVal(double numVal) {
if (type == TokenType.NUMBER)
this.numVal = numVal;
}
public void setUnknownChar(char unknownChar) {
if (type == TokenType.UNKNOWN)
this.unknownChar = unknownChar;
}
public TokenType getType() {
return type;
}
public String getIdentStr() {
return identStr;
}
public double getNumVal() {
return numVal;
}
public char getUnknownChar() {
return unknownChar;
}
public String toString() {
if (type == TokenType.IDENTFIFIER)
return type + ": " + identStr;
if (type == TokenType.NUMBER)
return type + ": " + numVal;
if (type == TokenType.UNKNOWN)
return type + ": " + unknownChar;
return type.toString();
}
}
|
package com.darkania.darkers.utilidades;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.FurnaceRecipe;
import org.bukkit.inventory.ItemStack;
public class CrafteosHorno {
public static void iniciar() {
FurnaceRecipe beef = new FurnaceRecipe(new ItemStack(Material.COOKED_BEEF), Material.ROTTEN_FLESH);
Bukkit.getServer().addRecipe(beef);
}
}
|
package com.mycom.calculator;
import java.awt.event.ActionListener;
public class ClipboardMenuItem extends AbstractMenuItem {
//-----
public ClipboardMenuItem(String tooltip, String title, int keycode, int mask, Mediator mediator, ActionListener al) {
super(title, keycode, mask, mediator, al);
setToolTipText(tooltip);
}
//-----
public void execute() {
String command = getActionCommand();
System.out.println("ClipboardMenuItem.execute() - " + getActionCommand());
if (command.equals("Copy")) {
mediator.copyContentsToClipboard();
} else if (command.equals("Paste")) {
mediator.pasteFromClipboard();
}
}
}
|
package com.udogan.magazayonetimi.ui;
import javax.swing.JPanel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import com.udogan.magazayonetimi.models.Beden;
import com.udogan.magazayonetimi.models.Marka;
import com.udogan.magazayonetimi.models.Musteri;
import com.udogan.magazayonetimi.models.Urun;
import com.udogan.magazayonetimi.models.enums.Bedenler;
import com.udogan.magazayonetimi.models.enums.Cinsiyetler;
import com.udogan.magazayonetimi.models.enums.Renkler;
import com.udogan.magazayonetimi.utils.dao.DbServicessBase;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import static javax.swing.JOptionPane.showMessageDialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingConstants;
public class UrunIslemleriPaneli extends JPanel {
private JPanel pnlDetay;
private JPanel pnlTablo;
private JTable table;
private JScrollPane scrollPane;
private JComboBox cmbCinsiyet;
private JTextField txtFiyat;
private JTextField txtIsim;
private JComboBox cmbMarka;
private JTextField txtModel;
private JComboBox cmbRenk;
private JLabel lblCinsiyet;
private JLabel lblFiyat;
private JLabel lblIsim;
private JLabel lblMarka;
private JLabel lblModel;
private JLabel lblRenk;
private JButton btnKaydet;
public MainFrame parentFrame;
private JLabel lblBeden;
private JComboBox cmbBeden;
public UrunIslemleriPaneli(MainFrame parentFrame) {
this.parentFrame = parentFrame;
setSize(1000, 532);
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
.addComponent(getPnlTablo(), Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(getPnlDetay(), Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 795, Short.MAX_VALUE))
.addContainerGap(205, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(getPnlDetay(), GroupLayout.PREFERRED_SIZE, 276, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(getPnlTablo(), GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE))
);
setLayout(groupLayout);
tabloyuDoldur();
combolariDoldur();
}
public void tabloyuDoldur() {
try {
DbServicessBase<Urun> dao = new DbServicessBase<Urun>();
Urun temp = new Urun();
List<Urun> urunListesi = dao.getAllRows(temp);
String[] columnNames = { "id", "Cinsiyet", "Marka", "Model", "İsim", "Renk", "Beden", "Fiyat" };
Object[][] data = new Object[urunListesi.size()][columnNames.length];
for (int i = 0; i < urunListesi.size(); i++) {
data[i][0] = ((Urun) urunListesi.get(i)).getId();
data[i][1] = ((Urun) urunListesi.get(i)).getCinsiyet();
long urunMarkasi = ((Urun) urunListesi.get(i)).getMarkaId();
DbServicessBase<Marka> dao2 = new DbServicessBase<Marka>();
Marka marka = new Marka();
marka.setId(urunMarkasi);
List<Marka> markaListesi = dao2.getAllRows(marka);
data[i][2] = markaListesi.get(0).getIsim();
data[i][3] = ((Urun) urunListesi.get(i)).getModel();
data[i][4] = ((Urun) urunListesi.get(i)).getIsim();
data[i][5] = ((Urun) urunListesi.get(i)).getRenk();
data[i][6] = ((Urun) urunListesi.get(i)).getBeden();
data[i][7] = ((Urun) urunListesi.get(i)).getFiyat();
}
table.setModel(new DefaultTableModel(data, columnNames));
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
TableColumnModel tcm = table.getColumnModel();
tcm.removeColumn(tcm.getColumn(0));
} catch (Exception e) {
showMessageDialog(null, e.getMessage());
}
}
private void combolariDoldur() {
DbServicessBase<Marka> dao = new DbServicessBase<Marka>();
Marka temp = new Marka();
List<Marka> markaListesi = dao.getAllRows(temp);
cmbMarka.setModel(new DefaultComboBoxModel(markaListesi.toArray()));
cmbMarka.setSelectedIndex(-1);
cmbCinsiyet.setModel(new DefaultComboBoxModel(Cinsiyetler.values()));
cmbCinsiyet.setSelectedIndex(-1);
cmbRenk.setModel(new DefaultComboBoxModel(Renkler.values()));
cmbRenk.setSelectedIndex(-1);
cmbBeden.setModel(new DefaultComboBoxModel(Bedenler.values()));
cmbBeden.setSelectedIndex(-1);
}
private JPanel getPnlDetay() {
if (pnlDetay == null) {
pnlDetay = new JPanel();
pnlDetay.setLayout(null);
pnlDetay.add(getCmbCinsiyet());
pnlDetay.add(getTxtFiyat());
pnlDetay.add(getTxtIsim());
pnlDetay.add(getCmbMarka());
pnlDetay.add(getTxtModel());
pnlDetay.add(getCmbRenk());
pnlDetay.add(getLblCinsiyet());
pnlDetay.add(getLblFiyat());
pnlDetay.add(getLblIsim());
pnlDetay.add(getLblMarka());
pnlDetay.add(getLblModel());
pnlDetay.add(getLblRenk());
pnlDetay.add(getBtnKaydet());
pnlDetay.add(getLblBeden());
pnlDetay.add(getCmbBeden());
}
return pnlDetay;
}
private JPanel getPnlTablo() {
if (pnlTablo == null) {
pnlTablo = new JPanel();
pnlTablo.setLayout(new BorderLayout(0, 0));
pnlTablo.add(getScrollPane());
}
return pnlTablo;
}
private JTable getTable() {
if (table == null) {
table = new JTable();
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int secilenSatir = table.getSelectedRow();
Urun degistirilecekUrun = new Urun();
degistirilecekUrun.setId(Long.parseLong(table.getModel().getValueAt(secilenSatir, 0).toString()));
String temp = table.getModel().getValueAt(secilenSatir, 1).toString();
if (temp.equals("erkek")) {
degistirilecekUrun.setCinsiyet(Cinsiyetler.erkek);
} else if (temp.equals("kadin")) {
degistirilecekUrun.setCinsiyet(Cinsiyetler.kadin);
} else if (temp.equals("unisex")) {
degistirilecekUrun.setCinsiyet(Cinsiyetler.unisex);
}
DbServicessBase<Marka> dao = new DbServicessBase<Marka>();
Marka marka = new Marka();
marka.setIsim(table.getModel().getValueAt(secilenSatir, 2).toString());
List<Marka> markaListesi = dao.getAllRows(marka);
degistirilecekUrun.setMarkaId(marka.getId());
degistirilecekUrun.setModel(table.getModel().getValueAt(secilenSatir, 3).toString());
degistirilecekUrun.setIsim(table.getModel().getValueAt(secilenSatir, 4).toString());
temp = table.getModel().getValueAt(secilenSatir, 5).toString();
if (temp.equals("çok_renkli")) {
degistirilecekUrun.setRenk(Renkler.çok_renkli);
}else if (temp.equals("abanoz")) {
degistirilecekUrun.setRenk(Renkler.abanoz);
}else if (temp.equals("abbak")) {
degistirilecekUrun.setRenk(Renkler.abbak);
}else if (temp.equals("abbağ")) {
degistirilecekUrun.setRenk(Renkler.abbağ);
}else if (temp.equals("acı")) {
degistirilecekUrun.setRenk(Renkler.acı);
}else if (temp.equals("ak")) {
degistirilecekUrun.setRenk(Renkler.ak);
}else if (temp.equals("al")) {
degistirilecekUrun.setRenk(Renkler.al);
}else if (temp.equals("ala")) {
degistirilecekUrun.setRenk(Renkler.ala);
}else if (temp.equals("alaca")) {
degistirilecekUrun.setRenk(Renkler.alaca);
}else if (temp.equals("apak")) {
degistirilecekUrun.setRenk(Renkler.apak);
}else if (temp.equals(" açık_gri")) {
degistirilecekUrun.setRenk(Renkler. açık_gri);
}else if (temp.equals("açık_kestane")) {
degistirilecekUrun.setRenk(Renkler.açık_kestane);
}else if (temp.equals("aşı_taşı")) {
degistirilecekUrun.setRenk(Renkler.aşı_taşı);
}else if (temp.equals("baklakırı")) {
degistirilecekUrun.setRenk(Renkler.baklakırı);
}else if (temp.equals("balköpüğü")) {
degistirilecekUrun.setRenk(Renkler.balköpüğü);
}else if (temp.equals("bembeyaz")) {
degistirilecekUrun.setRenk(Renkler.bembeyaz);
}else if (temp.equals("beniz")) {
degistirilecekUrun.setRenk(Renkler.beniz);
}else if (temp.equals("camgöbeği")) {
degistirilecekUrun.setRenk(Renkler.camgöbeği);
}else if (temp.equals("ceviz")) {
degistirilecekUrun.setRenk(Renkler.ceviz);
}else if (temp.equals("çivit")) {
degistirilecekUrun.setRenk(Renkler.çivit);
}else if (temp.equals("dalgalı")) {
degistirilecekUrun.setRenk(Renkler.dalgalı);
}else if (temp.equals("deniz_mavisi")) {
degistirilecekUrun.setRenk(Renkler.deniz_mavisi);
}else if (temp.equals("dore")) {
degistirilecekUrun.setRenk(Renkler.dore);
}else if (temp.equals("duman_rengi")) {
degistirilecekUrun.setRenk(Renkler.duman_rengi);
}else if (temp.equals("ebruli")) {
degistirilecekUrun.setRenk(Renkler.ebruli);
}else if (temp.equals("eflatun")) {
degistirilecekUrun.setRenk(Renkler.eflatun);
}else if (temp.equals("eflatuni")) {
degistirilecekUrun.setRenk(Renkler.eflatuni);
}else if (temp.equals("erguvani")) {
degistirilecekUrun.setRenk(Renkler.erguvani);
}else if (temp.equals("esmer")) {
degistirilecekUrun.setRenk(Renkler.esmer);
}else if (temp.equals("firuze")) {
degistirilecekUrun.setRenk(Renkler.firuze);
}else if (temp.equals("fıstık")) {
degistirilecekUrun.setRenk(Renkler.fıstık);
}else if (temp.equals("füme")) {
degistirilecekUrun.setRenk(Renkler.füme);
}else if (temp.equals("gri")) {
degistirilecekUrun.setRenk(Renkler.gri);
}else if (temp.equals("gök")) {
degistirilecekUrun.setRenk(Renkler.gök);
}else if (temp.equals("gök_kır")) {
degistirilecekUrun.setRenk(Renkler.gök_kır);
}else if (temp.equals("gökçül")) {
degistirilecekUrun.setRenk(Renkler.gökçül);
}else if (temp.equals("gülkurusu")) {
degistirilecekUrun.setRenk(Renkler.gülkurusu);
}else if (temp.equals("gümüş")) {
degistirilecekUrun.setRenk(Renkler.gümüş);
}else if (temp.equals("güvez")) {
degistirilecekUrun.setRenk(Renkler.güvez);
}else if (temp.equals("haki")) {
degistirilecekUrun.setRenk(Renkler.haki);
}else if (temp.equals("hardal")) {
degistirilecekUrun.setRenk(Renkler.hardal);
}else if (temp.equals("kahverengi")) {
degistirilecekUrun.setRenk(Renkler.kahverengi);
}else if (temp.equals("kara")) {
degistirilecekUrun.setRenk(Renkler.kara);
}else if (temp.equals("karagök")) {
degistirilecekUrun.setRenk(Renkler.karagök);
}else if (temp.equals("kavuniçi")) {
degistirilecekUrun.setRenk(Renkler.kavuniçi);
}else if (temp.equals("kestane")) {
degistirilecekUrun.setRenk(Renkler.kestane);
}else if (temp.equals("kına")) {
degistirilecekUrun.setRenk(Renkler.kına);
}else if (temp.equals("kır")) {
degistirilecekUrun.setRenk(Renkler.kır);
}else if (temp.equals("kiremit_kırmızısı")) {
degistirilecekUrun.setRenk(Renkler.kiremit_kırmızısı);
}else if (temp.equals("kırmızı")) {
degistirilecekUrun.setRenk(Renkler.kırmızı);
}else if (temp.equals("kızıl")) {
degistirilecekUrun.setRenk(Renkler.kızıl);
}else if (temp.equals("konur")) {
degistirilecekUrun.setRenk(Renkler.konur);
}else if (temp.equals("koyu_gri")) {
degistirilecekUrun.setRenk(Renkler.koyu_gri);
}else if (temp.equals("koyu_mavi")) {
degistirilecekUrun.setRenk(Renkler.koyu_mavi);
}else if (temp.equals("kurşun_rengi")) {
degistirilecekUrun.setRenk(Renkler.kurşun_rengi);
}else if (temp.equals("kurşuni")) {
degistirilecekUrun.setRenk(Renkler.kurşuni);
}
temp = table.getModel().getValueAt(secilenSatir, 6).toString();
if (temp.equals("XS")) {
degistirilecekUrun.setBeden(Bedenler.XS);
}else if (temp.equals("S")) {
degistirilecekUrun.setBeden(Bedenler.S);
}else if (temp.equals("M")) {
degistirilecekUrun.setBeden(Bedenler.M);
}else if (temp.equals("L")) {
degistirilecekUrun.setBeden(Bedenler.L);
}else if (temp.equals("XL")) {
degistirilecekUrun.setBeden(Bedenler.XL);
}else if (temp.equals("XXL")) {
degistirilecekUrun.setBeden(Bedenler.XXL);
}else if (temp.equals("XXXL")) {
degistirilecekUrun.setBeden(Bedenler.XXXL);
}else if (temp.equals("XXXXL")) {
degistirilecekUrun.setBeden(Bedenler.XXXXL);
}else if (temp.equals("XXXXXL")) {
degistirilecekUrun.setBeden(Bedenler.XXXXXL);
}
degistirilecekUrun.setFiyat(Double.parseDouble(table.getModel().getValueAt(secilenSatir, 7).toString()));
UrunDegistirme frame = new UrunDegistirme(e, degistirilecekUrun);
parentFrame.setEnabled(false);
frame.setVisible(true);
}
});
}
return table;
}
private JScrollPane getScrollPane() {
if (scrollPane == null) {
scrollPane = new JScrollPane();
scrollPane.setViewportView(getTable());
}
return scrollPane;
}
private JComboBox getCmbCinsiyet() {
if (cmbCinsiyet == null) {
cmbCinsiyet = new JComboBox();
cmbCinsiyet.setBounds(80, 12, 228, 20);
}
return cmbCinsiyet;
}
private JTextField getTxtFiyat() {
if (txtFiyat == null) {
txtFiyat = new JTextField();
txtFiyat.setBounds(80, 44, 228, 20);
txtFiyat.setColumns(10);
}
return txtFiyat;
}
private JTextField getTxtIsim() {
if (txtIsim == null) {
txtIsim = new JTextField();
txtIsim.setBounds(80, 76, 228, 20);
txtIsim.setColumns(10);
}
return txtIsim;
}
private JComboBox getCmbMarka() {
if (cmbMarka == null) {
cmbMarka = new JComboBox();
cmbMarka.setBounds(80, 108, 228, 20);
}
return cmbMarka;
}
private JTextField getTxtModel() {
if (txtModel == null) {
txtModel = new JTextField();
txtModel.setText("");
txtModel.setBounds(80, 140, 228, 20);
txtModel.setColumns(10);
}
return txtModel;
}
private JComboBox getCmbRenk() {
if (cmbRenk == null) {
cmbRenk = new JComboBox();
cmbRenk.setBounds(80, 172, 228, 20);
}
return cmbRenk;
}
private JLabel getLblCinsiyet() {
if (lblCinsiyet == null) {
lblCinsiyet = new JLabel("Cinsiyet :");
lblCinsiyet.setHorizontalAlignment(SwingConstants.RIGHT);
lblCinsiyet.setLabelFor(getCmbCinsiyet());
lblCinsiyet.setBounds(10, 12, 60, 20);
}
return lblCinsiyet;
}
private JLabel getLblFiyat() {
if (lblFiyat == null) {
lblFiyat = new JLabel("Fiyat :");
lblFiyat.setHorizontalAlignment(SwingConstants.RIGHT);
lblFiyat.setLabelFor(getTxtFiyat());
lblFiyat.setBounds(10, 44, 60, 20);
}
return lblFiyat;
}
private JLabel getLblIsim() {
if (lblIsim == null) {
lblIsim = new JLabel("\u0130sim :");
lblIsim.setHorizontalAlignment(SwingConstants.RIGHT);
lblIsim.setLabelFor(getTxtIsim());
lblIsim.setBounds(10, 76, 60, 20);
}
return lblIsim;
}
private JLabel getLblMarka() {
if (lblMarka == null) {
lblMarka = new JLabel("Marka :");
lblMarka.setHorizontalAlignment(SwingConstants.RIGHT);
lblMarka.setLabelFor(getCmbMarka());
lblMarka.setBounds(10, 108, 60, 20);
}
return lblMarka;
}
private JLabel getLblModel() {
if (lblModel == null) {
lblModel = new JLabel("Model :");
lblModel.setHorizontalAlignment(SwingConstants.RIGHT);
lblModel.setLabelFor(getTxtModel());
lblModel.setBounds(10, 140, 60, 20);
}
return lblModel;
}
private JLabel getLblRenk() {
if (lblRenk == null) {
lblRenk = new JLabel("Renk :");
lblRenk.setHorizontalAlignment(SwingConstants.RIGHT);
lblRenk.setLabelFor(getCmbRenk());
lblRenk.setBounds(10, 172, 60, 20);
}
return lblRenk;
}
private JButton getBtnKaydet() {
if (btnKaydet == null) {
btnKaydet = new JButton("Kaydet");
btnKaydet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DbServicessBase<Urun> dao = new DbServicessBase<Urun>();
Urun eklenecekUrun = new Urun();
eklenecekUrun.setCinsiyet((Cinsiyetler) cmbCinsiyet.getSelectedItem());
eklenecekUrun.setFiyat(Double.parseDouble(txtFiyat.getText()));
eklenecekUrun.setRenk((Renkler) cmbRenk.getSelectedItem());
eklenecekUrun.setIsim(txtIsim.getText());
eklenecekUrun.setMarkaId(((Marka)cmbMarka.getSelectedItem()).getId());
eklenecekUrun.setModel(txtModel.getText());
eklenecekUrun.setBeden((Bedenler)cmbBeden.getSelectedItem());
if (dao.save(eklenecekUrun)) {
tabloyuDoldur();
txtFiyat.setText("");
txtIsim.setText("");
txtModel.setText("");
cmbMarka.setSelectedIndex(-1);
cmbBeden.setSelectedIndex(-1);
cmbCinsiyet.setSelectedIndex(-1);
cmbRenk.setSelectedIndex(-1);
} else {
showMessageDialog(null, "Kaydetme İşlemi Başarısız Oldu!");
}
}
});
btnKaydet.setBounds(219, 245, 89, 20);
}
return btnKaydet;
}
private JLabel getLblBeden() {
if (lblBeden == null) {
lblBeden = new JLabel("Beden :");
lblBeden.setHorizontalAlignment(SwingConstants.RIGHT);
lblBeden.setLabelFor(getCmbBeden());
lblBeden.setBounds(24, 203, 46, 20);
}
return lblBeden;
}
private JComboBox getCmbBeden() {
if (cmbBeden == null) {
cmbBeden = new JComboBox();
cmbBeden.setBounds(80, 203, 228, 20);
}
return cmbBeden;
}
}
|
package com.josie.annotation.aop;
import java.lang.annotation.*;
/**
* Created by xiaoqin on 2018/10/5.
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Aspect {
String pointCut() default "";
}
|
import javax.swing.JOptionPane;
public class LerCincoNumeros {
public static void main(String [] agrs) {
double soma = 0;
double maior = 0;
double [] listaNum = new double[5];
for (int k=0; k<listaNum.length; k++) {
listaNum[k] = Double.parseDouble(JOptionPane.showInputDialog("Digite a nota do índice ("+k+"):"));
}
for (int k=0; k<listaNum.length; k++) {
soma += listaNum[k];
}
for (int k=0; k<listaNum.length; k++) {
if (listaNum[k] >= maior) {
maior = listaNum[k];
}
}
JOptionPane.showMessageDialog(null, "A soma das notas é igual a: " + soma +
" e maior nota foi: " + maior);
}
}
|
package com.ydl.iec.iec104.server.master.handler;
import com.ydl.iec.iec104.core.CachedThreadPool;
import com.ydl.iec.iec104.core.ControlManageUtil;
import com.ydl.iec.iec104.core.Iec104ThreadLocal;
import com.ydl.iec.iec104.core.ScheduledTaskPool;
import com.ydl.iec.iec104.message.MessageDetail;
import com.ydl.iec.iec104.server.handler.ChannelHandlerImpl;
import com.ydl.iec.iec104.server.handler.DataHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Iec104ClientHandler extends SimpleChannelInboundHandler<MessageDetail> {
private DataHandler dataHandler;
public Iec104ClientHandler(DataHandler dataHandler) {
this.dataHandler = dataHandler;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// 启动成功后一直发启动链路命令
Iec104ThreadLocal.setScheduledTaskPool(new ScheduledTaskPool(ctx));
Iec104ThreadLocal.getScheduledTaskPool().sendStatrFrame();
Iec104ThreadLocal.setControlPool(new ControlManageUtil(ctx).setFrameAmountMax(Iec104ThreadLocal.getIec104Conig().getFrameSumMax()));
Iec104ThreadLocal.getControlPool().startSendFrameTask();
if (dataHandler != null) {
CachedThreadPool.getCachedThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
dataHandler.handlerAdded(new ChannelHandlerImpl(ctx));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
@Override
public void channelRead0(ChannelHandlerContext ctx, MessageDetail ruleDetail104) throws IOException {
if (dataHandler != null) {
CachedThreadPool.getCachedThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
dataHandler.channelRead(new ChannelHandlerImpl(ctx), ruleDetail104);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}
|
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/api")
public class IndexController {
@GetMapping("/test")
public Object getJson(HttpServletRequest request){
String localAddr = request.getLocalAddr();
String remoteAddr = request.getRemoteAddr();
System.out.println("localAddr"+localAddr);
System.out.println("remoteAddr"+remoteAddr);
return localAddr;
}
}
|
package com.example.topics.delete.lambdaauthorizer.infra;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.example.topics.core.TopicRepository;
import com.example.topics.core.User;
import com.example.topics.delete.lambdaauthorizer.core.AuthorizationDecider;
import com.example.topics.infra.EnvironmentVariables;
import com.example.topics.infra.TopicRepositoryFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.utils.StringUtils;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class DeleteAuthorizerHandler implements RequestHandler<Map<String, Object>, Map<String, Object>> {
private ObjectMapper mapper = new ObjectMapper();
private JwtUserMapper jwtUserMapper;
private AuthorizationDecider authorizationDecider;
private TopicRepository topicRepository;
public DeleteAuthorizerHandler() {
topicRepository = TopicRepositoryFactory.getInstance().buildTopicRepositoryFactory();
authorizationDecider = new AuthorizationDecider();
jwtUserMapper = new JwtUserMapper();
}
@SneakyThrows
@Override
public Map<String, Object> handleRequest(Map<String, Object> request, Context context) {
log.info(mapper.writeValueAsString(request));
JsonNode requestJsonNode = mapper.valueToTree(request);
String authorizationToken = getAuthorizationToken(requestJsonNode);
String topicName = requestJsonNode.at("/pathParameters/topic").asText();
User user = jwtUserMapper.getUserFromJwt(authorizationToken);
// if topic does not exist, the deletion method still can be called, but will return http404
boolean isAuthorized = topicRepository.get(topicName)
.map(topic -> authorizationDecider.isDeletionAuthorized(user, topic))
.orElse(true);
String authorizationResponse = isAuthorized ? "Allow" : "Deny";
String methodArn = requestJsonNode.get("methodArn").asText();
String response = "{\"principalId\":\"abc123\",\"policyDocument\":{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"execute-api:Invoke\",\"Resource\":[\"" + methodArn + "\"],\"Effect\":\"" + authorizationResponse + "\"}]}}";
return mapper.readValue(response, new TypeReference<HashMap<String, Object>>() {
});
}
private String getAuthorizationToken(JsonNode request) {
return request.at("/headers/Authorization").asText();
}
}
|
package com.example.billage.frontend.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import com.example.billage.R;
import com.example.billage.backend.common.Utils;
import com.example.billage.frontend.data.UsageList;
import com.example.billage.frontend.ui.addUsage.AddUsage;
import com.example.billage.frontend.ui.home.subView.usage.UsageFragment;
import java.util.List;
public class UsageAdapter extends ArrayAdapter<UsageList> {
private Activity mActivity;
private Context context;
private List mList;
private ListView mListView;
static class UserViewHolder {
public TextView date;
public TextView cost;
public TextView destination;
public TextView time;
public ImageView type_image;
public TextView bank_name;
public CardView cardView;
}
public UsageAdapter(Context context, List<UsageList> list, ListView listview, Activity activity) {
super(context, 0, list);
this.context = context;
this.mList = list;
this.mListView = listview;
this.mActivity = activity;
}
// ListView의 한 줄(row)이 렌더링(rendering)될 때 호출되는 메소드로 row를 위한 view를 리턴.
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parentViewGroup) {
View rowView = convertView;
UserViewHolder viewHolder;
String Status;
if (rowView == null) {
// 레이아웃을 정의한 XML 파일(R.layout.list_item)을 읽어서 계층 구조의 뷰 객체(rowView)로 변환.
// rowView 객체는 3개의 TextView로 구성.
// rowView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parentViewGroup, false);
LayoutInflater layoutInflater = LayoutInflater.from(context);
rowView = layoutInflater.inflate(R.layout.group_list, parentViewGroup, false);
// view holder의 구성 요소의 값과 한 줄을 구성하는 레이아웃을 연결함.
//
// rowView(=R.layout.list_item)에서 주어진 ID(R.id.textview_list_english)를 가진 뷰 찾기.
viewHolder = new UserViewHolder();
viewHolder.date = (TextView) rowView.findViewById(R.id.date);
viewHolder.cost = (TextView) rowView.findViewById(R.id.cost);
viewHolder.destination = (TextView) rowView.findViewById(R.id.destination);
viewHolder.time = (TextView) rowView.findViewById(R.id.time);
viewHolder.type_image= (ImageView) rowView.findViewById(R.id.type_image);
viewHolder.bank_name = (TextView) rowView.findViewById(R.id.bank_name);
viewHolder.cardView = (CardView) rowView.findViewById(R.id.cardview);
rowView.setTag(viewHolder);
Status = "created";
} else {
viewHolder = (UserViewHolder) rowView.getTag();
Status = "reused";
}
// 태그 분석을 위한 코드 시작
String Tag = rowView.getTag().toString();
int idx = Tag.indexOf("@");
String tag = Tag.substring(idx + 1);
UsageList usage = (UsageList) mList.get(position);
if(position == 0){
rowView.findViewById(R.id.divider).setVisibility(View.VISIBLE);
rowView.findViewById(R.id.date).setVisibility(View.VISIBLE);
}
else{
if(isNewGroupTitle(position)){
rowView.findViewById(R.id.divider).setVisibility(View.VISIBLE);
rowView.findViewById(R.id.date).setVisibility(View.VISIBLE);
}
else{
rowView.findViewById(R.id.divider).setVisibility(View.GONE);
rowView.findViewById(R.id.date).setVisibility(View.GONE);
}
}
if(usage.getDate().equals(Utils.transformDate(Utils.getDate()))){
viewHolder.date.setText(usage.getDate()+" (오늘)");
}
else{
viewHolder.date.setText(usage.getDate());
}
viewHolder.cost.setText(usage.getCost());
viewHolder.destination.setText(usage.getDestination());
viewHolder.time.setText(usage.getTime().substring(0,5));
// 추후 수정
viewHolder.bank_name.setText(usage.getBank_name());
if(usage.getUsage_type().equals("입금")){
viewHolder.cost.setText("+ "+usage.getCost()+"원");
viewHolder.type_image.setImageResource(R.drawable.deposit);
}else {
viewHolder.cost.setText("- "+usage.getCost()+"원");
viewHolder.type_image.setImageResource(R.drawable.withdarw);
}
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent (mActivity, AddUsage.class);
intent.putExtra("cardTypeInfo",usage.getUsage_type());
intent.putExtra("cardCostInfo",usage.getCost());
intent.putExtra("cardDateInfo",usage.getDate());
intent.putExtra("cardTimeInfo",usage.getTime());
intent.putExtra("cardDestInfo",usage.getDestination());
intent.putExtra("cardMemoInfo",usage.getMemo());
intent.putExtra("cardTransTypeInfo",usage.getType());
intent.putExtra("cardId",usage.getId());
intent.putExtra("cardBankCode",usage.getBank_code());
mActivity.startActivity(intent);
}
});
rowView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return true;
}
});
return rowView;
}
private boolean isNewGroupTitle(int position)
{
//현재의 타이틀을 판단
UsageList nowUsageList = (UsageList) mList.get(position);
String nowDate = nowUsageList.getDate();
UsageList preUsageList = (UsageList) mList.get(position-1);
String preDate = preUsageList.getDate();
if(nowDate.equals(preDate)){
return false;
}
return true;
}
}
|
package br.org.funcate.glue.model.request;
public enum GoogleEnum {
MAP {
public String toString() {
return "canvas.request.google.map";
}
},
HYBRID {
public String toString() {
return "";
}
},
SATELLITE {
public String toString() {
return "canvas.request.google.satellite";
}
},
TERRAIN {
public String toString() {
return "canvas.request.google.terrain";
}
},
STREET {
public String toString() {
return "canvas.request.google.street";
}
}
}
|
package com.hjtech.base.base;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.hjtech.base.R;
import com.hjtech.base.utils.ActivityManager;
import com.hjtech.base.utils.SharePreUtils;
import java.util.Locale;
/*
* 项目名: EasyPark
* 包名 com.hjtech.easypark.common.base
* 文件名: BaseActivity
* 创建者: ZJB
* 创建时间: 2017/6/20 on 14:15
* 描述: TODO
*/
public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements BaseView {
protected P presenter;
public Context context;
private TextView tv_title;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
context = this;
ActivityManager.getAppInstance().addActivity(this);
presenter = initPresenter();
selectLanguage(SharePreUtils.getString(this, "language", "zh"));
}
@Override
protected void onResume() {
/**
* 设置为横屏
*/
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
super.onResume();
}
protected void fullScreen() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
@Override
protected void onDestroy() {
ActivityManager.getAppInstance().removeActivity(this);
if (presenter != null) {
presenter.detach();
}
super.onDestroy();
}
public abstract P initPresenter();
/**
* 沉浸式状态栏
*/
public void transStatus() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明导航栏
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
}
/**
* 初始化ToolBar
*
* @param title ToolBar中间的标题
* @param isBack 是否显示左边返回箭头
* @return Toolbar
*/
public Toolbar initToolBar(final AppCompatActivity activity, boolean isBack, String title) {
Toolbar toolbar = activity.findViewById(R.id.tool_bar);
toolbar.setTitle("");
activity.setSupportActionBar(toolbar);
tv_title = activity.findViewById(R.id.tool_bar_title);
tv_title.setText(title);
if (isBack) {
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// toolbar.setNavigationOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// activity.finish();
// }
// });
}
return toolbar;
}
public void setToolbarTitle(String title) {
if (tv_title != null) {
tv_title.setText(title);
}
}
@Override
public void showLoadingDialog(String msg) {
}
@Override
public void dimissLoadingDialog() {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
public void setStatusBar(int color, boolean isLight) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
View decorView = getWindow().getDecorView();
int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
decorView.setSystemUiVisibility(option);
//根据上面设置是否对状态栏单独设置颜色
if (color != -1) {
getWindow().setStatusBarColor(getResources().getColor(color));
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
if (isLight) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
}
}
protected boolean checkPermission(int requestCode, String permissions) {
if (ContextCompat.checkSelfPermission(context, permissions) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{permissions}, requestCode);
}
return false;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "拒绝权限", Toast.LENGTH_SHORT).show();
}
}
/*
将状态栏字体颜色设为深色
*/
private void setStatusBarTextColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
public void selectLanguage(String language) {
//设置语言类型
Resources resources = getResources();
Configuration configuration = resources.getConfiguration();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
switch (language) {
case "en":
configuration.locale = Locale.ENGLISH;
break;
case "zh":
configuration.locale = Locale.SIMPLIFIED_CHINESE;
break;
case "ft":
configuration.locale = Locale.JAPANESE;
break;
default:
configuration.locale = Locale.getDefault();
break;
}
resources.updateConfiguration(configuration, displayMetrics);
//保存设置语言的类型
SharePreUtils.putString(this, "language", language);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package loc.error;
/**
*
* @author hi
*/
public class CouponError {
private String codeID, codeName, createDate, expireDate, amount;
public CouponError() {
}
public CouponError(String codeID, String codeName, String createDate, String expireDate, String amount) {
this.codeID = codeID;
this.codeName = codeName;
this.createDate = createDate;
this.expireDate = expireDate;
this.amount = amount;
}
public String getCodeID() {
return codeID;
}
public void setCodeID(String codeID) {
this.codeID = codeID;
}
public String getCodeName() {
return codeName;
}
public void setCodeName(String codeName) {
this.codeName = codeName;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public String getExpireDate() {
return expireDate;
}
public void setExpireDate(String expireDate) {
this.expireDate = expireDate;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
|
//import org.junit.Test;
//import sandbox.StringUtils;
//
//import static org.assertj.core.api.Assertions.assertThat;
//
///**
// * mstodo: Header
// *
// * @author Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
// * <br>
// * Date: 8/6/18
// */
//public class StringUtilsTest { // mstodo copy to TT
// @Test
// public void shouldGenerateProperLength() {
// String generated = StringUtils.randomAlphabetic(13);
// assertThat(generated).hasSize(13);
// }
//
// @Test
// public void shouldGenerateAlphabetic() {
// String generated = StringUtils.randomAlphabetic(200);
// for (int i = 0; i < generated.length(); i++) {
// assertThat(generated.charAt(i)).isBetween('a', 'z');
// }
// }
//}
|
import javax.swing.JPanel;
import java.awt.*;
import java.awt.geom.*;
public class Cat {
// drawing constants are private - noone needs to know what we're doing
// pick a head dimension
private static final int HEAD_DIMENSION = 500;
// eyes will be about 1/4 from top of head and 1/4 from left
private static final int EYE_Y = (HEAD_DIMENSION - 50)/2;
private static final int EYE_X = (HEAD_DIMENSION + 50)/3;
private static final int EYE_SEPARATION = HEAD_DIMENSION/2;
// pick eye dimensions
private static final int EYE_HEIGHT = HEAD_DIMENSION/10;
private static final int EYE_WIDTH = HEAD_DIMENSION/10;
// pick mouth height, width is based on head dimension
private static final int MOUTH_HEIGHT = 17;
private static final int MOUTH_WIDTH = HEAD_DIMENSION/4;
// mouth starts about 40% from left edge of head
private static final int MOUTH_X = HEAD_DIMENSION/5 * 2;
private static final int MOUTH_Y = HEAD_DIMENSION/5 * 3;
// draw will render the Cat on the Graphics object
public void draw(Graphics g, int catX, int catY)
{
Graphics2D g2 = (Graphics2D) g;
int x=catX;
int y=catY;
// draw background black rectangle
g2.setColor(Color.black);
g2.fillOval(x, y, (int)(1.1*HEAD_DIMENSION), (int)(1.1*HEAD_DIMENSION));
// Draw the head
g2.setColor(Color.white);
g2.fillOval((int)(2*x), (int)(2*y), HEAD_DIMENSION, HEAD_DIMENSION);
// Draw the eyes
g2.setColor(Color.red);
x = catX + EYE_X;
y = catY + EYE_Y;
g2.fillOval(x, y, EYE_WIDTH, EYE_HEIGHT);
x += EYE_SEPARATION;
g2.fillOval(x, y, EYE_WIDTH, EYE_HEIGHT);
// Draw the mouth
g2.setColor(Color.orange);
x = catX + MOUTH_X;
y = catY + MOUTH_Y;
g2.fillOval(x, y, MOUTH_WIDTH, MOUTH_HEIGHT);
g2.setColor(Color.blue);
// Meow text appears below cat head, +10 places below
// so it doesn't overlap the drawing
g2.drawString("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", catX, catY+(int)(1.5*HEAD_DIMENSION)+10);
}
}
|
package com.allisonmcentire.buildingtradesandroid;
/**
* Created by allisonmcentire on 12/5/17.
*/
class FirebaseError {
}
|
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
public class VerySimpleChatServer {
ArrayList clientObjectOutputStreams;
Alexa alexa;
public class ClientHandler implements Runnable {
ObjectOutputStream writer;
ObjectInputStream reader;
Socket sock;
public ClientHandler(Socket socket, ObjectOutputStream objectoutputstream){
try {
writer = objectoutputstream;
sock = socket;
reader = new ObjectInputStream(sock.getInputStream());
} catch(Exception exception) {
System.out.println((new StringBuilder()).append("Exce Servidor reader ").append(exception).toString());
exception.printStackTrace();
}
}
public void run(){
try {
while(true) {
Object obj = reader.readObject();
if(obj instanceof String){
String preguntaCliente= (String) obj;
writer.writeObject(alexa.responder(preguntaCliente));
writer.flush();
}
}
}
catch(Exception exception) {
exception.printStackTrace();
}
}
}
public VerySimpleChatServer(){}
public
static void main(String args[]){
(new VerySimpleChatServer()).go();
}
public void go(){
alexa = new Alexa();
clientObjectOutputStreams = new ArrayList();
try {
ServerSocket serversocket = new ServerSocket(5000);
do {
Socket socket = serversocket.accept();
ObjectOutputStream objectoutputstream = new ObjectOutputStream(socket.getOutputStream());
clientObjectOutputStreams.add(objectoutputstream);
Thread thread = new Thread(new ClientHandler(socket, objectoutputstream));
thread.start();
System.out.println("got a conexion");
} while(true);
}
catch(Exception exception){
exception.printStackTrace();
}
}
public void tellEveryone(Object obj, ObjectOutputStream objectoutputstream){
Iterator iterator = clientObjectOutputStreams.iterator();
do {
if(!iterator.hasNext())
break;
try {
ObjectOutputStream objectoutputstream1 = (ObjectOutputStream)iterator.next();
if(!objectoutputstream1.equals(objectoutputstream)){
objectoutputstream1.writeObject(obj);
objectoutputstream1.flush();
}
} catch(Exception exception) {
exception.printStackTrace();
}
} while(true);
}
}
|
package com.example.apo.quizfinal;
import android.content.Intent;
import android.os.Bundle;
import android.preference.TwoStatePreference;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.List;
public class FinalScreen extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_screen);
final Button retrybtn = (Button) findViewById(R.id.retrybtn);
Intent myGotofinalscreen = getIntent();
final Boolean multiplayer = myGotofinalscreen.getBooleanExtra("multiplayer", false);
final Boolean atplayertwo = myGotofinalscreen.getBooleanExtra("atplayertwo", false);
final String[] userdta = myGotofinalscreen.getStringArrayExtra("userone");
String[] userone = new String[3];
final int score = myGotofinalscreen.getIntExtra("score", 0);
final User user = (User) myGotofinalscreen.getSerializableExtra("user");
final TextView scrollview = (TextView) findViewById(R.id.scrollview);
final TextView prevscore = (TextView) findViewById(R.id.prevscore);
final TextView winner = (TextView) findViewById(R.id.winner);
final TextView prevscoreone = (TextView) findViewById(R.id.prevscoreone);
final TextView prevscoretwo = (TextView) findViewById(R.id.prevscoretwo);
final TextView prev = (TextView) findViewById(R.id.prev);
scrollview.setMovementMethod(new ScrollingMovementMethod());
prevscoreone.setMovementMethod(new ScrollingMovementMethod());
prevscoretwo.setMovementMethod(new ScrollingMovementMethod());
final DatabaseHandler db = new DatabaseHandler(this);
final TextView scoreview = (TextView) findViewById(R.id.scoreview);
db.addScore(user, score);
Log.d("Insert: ", "Inserting ..");
if(multiplayer==true){
userone[0] = user.getName();
userone[1] = Integer.toString(score);
userone[2] = String.valueOf(user.getID());
if(atplayertwo == false){
Intent gotoentrypoint = new Intent(FinalScreen.this, EntryPoint.class);
gotoentrypoint.putExtra("multiplayer", true);
gotoentrypoint.putExtra("atplayertwo", true);
gotoentrypoint.putExtra("userone", userone);
startActivity(gotoentrypoint);}
if(atplayertwo ==true){
scoreview.setText("Score for "+ userdta[0] + " is "+ userdta[1] + "\nScore for "+ user.getName()+" is "+ score);
String win;
if (Integer.parseInt(userdta[1]) > score){
win = userdta[0];
}
else if (Integer.parseInt(userdta[1]) == score) {
win = "nobody. It's a tie";
} else {
win = user.getName();
}
List<Score> scoresforplayer = db.getScore(user.getID());
scrollview.setText("");
prevscoretwo.setText("");
for (int i = 0; i < scoresforplayer.size(); i++) {
Score sc = scoresforplayer.get(i);
String log = sc.getScore() + " ,at time " + sc.getDatetime() + " \n\n";
// Writing to TextView;
prevscoretwo.append(log);
}
List<Score> scoresforplaye = db.getScore(Integer.parseInt(userdta[2]));
prevscoreone.setText("");
for (int i = 0; i < scoresforplaye.size(); i++) {
Score sc = scoresforplaye.get(i);
String log = sc.getScore() + " ,at time " + sc.getDatetime() + " \n\n";
// Writing to TextView;
prevscoreone.append(log);
}
prev.setText("Past scores for \t\t\t\tPast scores for \n" + userdta[0]+"\t\t\t\t\t\t\t\t\t\t\t"+ user.getName());
winner.setText("The winner is " + win + "!");
}
}
if (multiplayer == false){
List<Score> scoresforplayer = db.getScore(user.getID());
scrollview.setText("");
winner.setText("");
prevscoreone.setText("");
prevscoretwo.setText("");
prev.setText("");
scoreview.setText("Score for you is: " + score);
prevscore.setText("Your previous scores are:");
for (int i = 0; i < scoresforplayer.size(); i++) {
Score sc = scoresforplayer.get(i);
String log = sc.getScore() + " ,at time " + sc.getDatetime() + " \n\n";
// Writing to TextView;
scrollview.append(log);
}
}
retrybtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent gotoentrypoint = new Intent(FinalScreen.this, PlayerSelect.class);
startActivity(gotoentrypoint);
}
});
}
}
|
package com.zmji.ambassador;
import lombok.extern.slf4j.Slf4j;
/**
* @Description: 一个简单的服务器
* @Author: zhongmou.ji
* @Date: 2021/9/1 下午6:14
**/
@Slf4j
public class Client {
private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador();
/**
* 供其他方 调用的方法
* @param value 参数
* @return 返回值
*/
long useService(int value) {
long result = serviceAmbassador.doRemoteFunction(value);
log.info("Service result: {}", result);
return result;
}
}
|
public class Solution {
public static int lastIndex(int input[], int x) {
return lastIndex(input,x,input.length-1);
}
public static int lastIndex(int[] input , int x, int index)
{
if(index==-1)
return -1;
if(input[index] == x)
return index;
return lastIndex(input, x, index-1);
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.types.service.populator;
import de.hybris.platform.cms2.common.annotations.HybrisDeprecation;
import de.hybris.platform.cmsfacades.types.service.ComponentTypeAttributeStructure;
import de.hybris.platform.cmsfacades.types.service.ComponentTypeStructureRegistry;
import de.hybris.platform.cmsfacades.types.service.impl.DefaultComponentTypeAttributeStructure;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.core.model.type.AttributeDescriptorModel;
import de.hybris.platform.core.model.type.ComposedTypeModel;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import java.util.Optional;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Required;
import com.google.common.collect.Sets;
/**
* Populator that lookup for populators defined in the registry for a given attribute and its enclosing type.
* @deprecated since 6.5
*/
@Deprecated
@HybrisDeprecation(sinceVersion = "6.5")
public class ComponentTypeStructureAttributeRegistryPopulator implements Populator<AttributeDescriptorModel, DefaultComponentTypeAttributeStructure>
{
private ComponentTypeStructureRegistry componentTypeStructureRegistry;
@Override
public void populate(final AttributeDescriptorModel attributeDescriptor,
final DefaultComponentTypeAttributeStructure componentTypeAttributeStructure) throws ConversionException
{
final ComposedTypeModel composedType = attributeDescriptor.getEnclosingType();
final Set<ComponentTypeAttributeStructure> attributesOnRegistry = Optional //
.ofNullable(getComponentTypeStructureRegistry().getComponentTypeStructure(composedType.getCode())) //
.map(componentTypeStructure -> componentTypeStructure.getAttributes()) //
.orElse(Sets.newHashSet());
// add extra populators defined on the registry
attributesOnRegistry //
.stream() //
.filter(attributeOnRegistry -> StringUtils.equals(attributeDescriptor.getQualifier(), attributeOnRegistry.getQualifier())) //
.map(ComponentTypeAttributeStructure::getPopulators) //
.findFirst() //
.ifPresent(populatorsOnRegistry -> componentTypeAttributeStructure.getPopulators().addAll(populatorsOnRegistry));
}
protected ComponentTypeStructureRegistry getComponentTypeStructureRegistry()
{
return componentTypeStructureRegistry;
}
@Required
public void setComponentTypeStructureRegistry(final ComponentTypeStructureRegistry componentTypeStructureRegistry)
{
this.componentTypeStructureRegistry = componentTypeStructureRegistry;
}
}
|
package com.zinnaworks.nxpgtool.entity;
import lombok.Data;
@Data
public class ServerInfo {
public String type;
public String url;
}
|
package com.flutterwave.raveandroid.rave_presentation.account;
import com.flutterwave.raveandroid.rave_core.models.Bank;
public class BankAccount {
Bank bank;
private String bvn;
private String accountNumber;
private String dateOfBirth;
public BankAccount(Bank bank, String accountNumber) {
this.bank = bank;
this.accountNumber = accountNumber;
}
public String getBvn() {
return bvn;
}
public void setBvn(String bvn) {
this.bvn = bvn;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
|
package com.sprmvc.web.ch5.exc;
public class SpitterExceptionRest extends RuntimeException {
}
|
package client.by.epam.fullparser.bean;
import entity.ParserType;
import java.io.FileInputStream;
public class FileAskRequest extends Request {
private ParserType parserType;
private long fileLength;
private FileInputStream fileInputStream;
public FileAskRequest(){}
public ParserType getParserType() {
return parserType;
}
public void setParserType(ParserType parserType) {
this.parserType = parserType;
}
public long getFileLength() {
return fileLength;
}
public void setFileLength(long fileLength) {
this.fileLength = fileLength;
}
public FileInputStream getFileInputStream() {
return fileInputStream;
}
public void setFileInputStream(FileInputStream fileInputStream) {
this.fileInputStream = fileInputStream;
}
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$fn extends g {
public c$fn() {
super("openUrlByExtBrowser", "open_url_by_ext_browser", 55, false);
}
}
|
package com.navin.melalwallet.webservice;
import com.navin.melalwallet.models.Category;
import com.navin.melalwallet.models.Product;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import io.reactivex.Single;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface IService {
@FormUrlEncoded
@POST("register.php")
Call<ResponseBody> register(@Field("username") String user, @Field("password") String pass);
@FormUrlEncoded
@POST("login.php")
Call<ResponseBody> login(@Field("username") String user, @Field("password") String pass);
@GET("getCategories.php")
Call<List<Category>> getCategories();
//RX Method
@FormUrlEncoded
@POST("login.php")
Single<ResponseBody> loginUser(@Field("username") String user, @Field("password") String pass);
@GET("getAnnouncements.php")
Call<List<Product>> getAnnouncements();
@GET("getBestApplications.php")
Call<List<Product>> getBestProducts();
@GET("getNewApplications.php")
Call<List<Product>> getNewApplications();
// CompletableFuture
}
|
package com.tencent.mm.plugin.qqmail.b;
import com.tencent.mm.a.e;
import com.tencent.mm.bt.h;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.ar;
import com.tencent.mm.model.au;
import com.tencent.mm.model.bd;
import com.tencent.mm.model.bs;
import com.tencent.mm.model.c;
import com.tencent.mm.protocal.d;
import com.tencent.mm.sdk.b.a;
import java.io.File;
import java.util.HashMap;
public final class w implements ar {
private p mdW;
private b mdX = new b();
private v mdu;
private static w bov() {
au.HN();
w wVar = (w) bs.iK("plugin.qqmail");
if (wVar != null) {
return wVar;
}
wVar = new w();
au.HN().a("plugin.qqmail", wVar);
return wVar;
}
public static p bow() {
g.Eg().Ds();
if (bov().mdW == null) {
bov().mdW = new p(d.qVN, d.DEVICE_TYPE);
}
return bov().mdW;
}
public static v box() {
g.Eg().Ds();
if (bov().mdu == null) {
bov().mdu = new v();
}
return bov().mdu;
}
public final void onAccountRelease() {
p pVar = bov().mdW;
if (pVar != null) {
pVar.reset();
}
a.sFg.c(this.mdX);
}
public final HashMap<Integer, h.d> Ci() {
return null;
}
public final void gi(int i) {
if ((i & 1) != 0) {
boy();
}
}
public static void boy() {
bd.iE("qqmail");
au.HU();
c.FW().Yp("qqmail");
p bow = bow();
au.HU();
e.k(new File(c.Gh()));
bow.reset();
}
public final void bn(boolean z) {
a.sFg.b(this.mdX);
au.Em().H(new 1(this));
}
public final void bo(boolean z) {
}
}
|
package MobileAutomationPrerequisite.desktop.pages;
import MobileAutomationPrerequisite.desktop.get_property.PdpGetProperty;
import MobileAutomationPrerequisite.desktop.get_property.ProductsGetProperty;
import base.PageObject;
import global.Global;
import net.bytebuddy.implementation.bytecode.Throw;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.testng.Assert;
import java.io.IOException;
import java.util.List;
public class Products_Check_Page extends PageObject {
public static String page_url = Global.getConfig().getString("member.url") + "/user/profile";
public String digitalProduct = "Will be sent to your email address";
@FindBy(id = "q")
public WebElement searchBar;
@FindBy(xpath = "//button[text()='SEARCH']")
public WebElement searchButton;
@FindBy(css = ".c2prKC .c1ZEkM")
public List<WebElement> productslst;
@FindBy(xpath = "//span[text()='Chat Now']")
public List <WebElement> chatNowlnktxt;
@FindBy (css = ".sku-variable-size")
public List <WebElement> skuSizebtn;
@FindBy (css = ".has-arrow")
public List <WebElement> tagNamelbl;
@FindBy (xpath = "//*[@class='next-icon next-icon-close next-icon-small']")
public WebElement overSeasPopupClosebtn;
@FindBy (css = "span[class='pdp-mod-product-badge-title']")
public WebElement productNamelbl;
public By searchBarBy = By.id("q");
public By searchButtonBy = By.xpath("//button[text()='SEARCH']");
public By productslstBy = By.cssSelector(".c2prKC .c1ZEkM");
public By productTitleBy = By.cssSelector("span[class='pdp-mod-product-badge-title']");
public By outOfStockBy = By.cssSelector("span[class='quantity-content-warning']");
public By chatNowlnktxtBy = By.xpath("//span[text()='Chat Now']");
public By tagNamelblBy = By.cssSelector(".has-arrow");
public By overSeasPopupClosebtnBy = By.xpath("//*[@class='next-icon next-icon-close next-icon-small']");
private String promotionLabel = "Min. spend";
ProductsGetProperty productsGetProperty = new ProductsGetProperty();
PdpGetProperty pdpGetProperty = new PdpGetProperty();
public void productCheck(int productNumber, String productFile) throws IOException {
if (page_url.contains(".pk")) {
// waitUntilPageReady();
waitUntilClickable(searchBarBy);
if (productFile.equalsIgnoreCase("Product")) {
sendKeysWithoutException(searchBar, productsGetProperty.pkProducts().get(productNumber-1));
}
else if (productFile.equalsIgnoreCase("Pdp"))
{
sendKeysWithoutException(searchBar, pdpGetProperty.productPK().get(productNumber-1));
}
}
else if (page_url.contains(".bd")) {
// waitUntilPageReady();
waitUntilClickable(searchBarBy);
if (productFile.equalsIgnoreCase("Product")) {
sendKeysWithoutException(searchBar, productsGetProperty.bdProducts().get(productNumber-1));
}
else if (productFile.equalsIgnoreCase("Pdp"))
{
sendKeysWithoutException(searchBar, pdpGetProperty.productBD().get(productNumber-1));
}
}
else if (page_url.contains(".lk")) {
// waitUntilPageReady();
waitUntilClickable(searchBarBy);
if (productFile.equalsIgnoreCase("Product")) {
sendKeysWithoutException(searchBar, productsGetProperty.lkProducts().get(productNumber-1));
}
else if (productFile.equalsIgnoreCase("Pdp"))
{
sendKeysWithoutException(searchBar, pdpGetProperty.productLK().get(productNumber-1));
}
}
else if (page_url.contains(".np")) {
// waitUntilPageReady();
waitUntilClickable(searchBarBy);
if (productFile.equalsIgnoreCase("Product")) {
sendKeysWithoutException(searchBar, productsGetProperty.npProducts().get(productNumber-1));
}
else if (productFile.equalsIgnoreCase("Pdp"))
{
sendKeysWithoutException(searchBar, pdpGetProperty.productNP().get(productNumber-1));
}
}
else if (page_url.contains(".mm")) {
// waitUntilPageReady();
waitUntilClickable(searchBarBy);
if (productFile.equalsIgnoreCase("Product")) {
sendKeysWithoutException(searchBar, productsGetProperty.mmProducts().get(productNumber-1));
}
else if (productFile.equalsIgnoreCase("Pdp"))
{
sendKeysWithoutException(searchBar, pdpGetProperty.productMM().get(productNumber-1));
}
}
else
throw new RuntimeException("Venture does not exist!");
waitUntilPresentOfElementBy(searchButtonBy);
searchButton.click();
}
public void goToProduct ()
{
try {
waitUntilPresentOfElementBy(productslstBy);
waitUntilClickable(productslstBy);
clickWithoutExceptionForElements(productslst);
waitUntilPresentOfElementBy(productTitleBy);
} catch (Exception e) {
// e.printStackTrace();
throw new RuntimeException("The product is not active or searchable!");
}
}
public boolean verifyTheOutOfStock ()
{
return isExist(outOfStockBy);
}
public boolean verifyTheExistenceOfChatFeatureOnPdp()
{
return isExist(chatNowlnktxtBy);
}
public void selectTheLaskSku()
{
skuSizebtn.get(skuSizebtn.size()-1).click();
}
public boolean verifyTheExistenceOfPromotion(String promotionName)
{
return isExistByTextContains(promotionName);
}
public boolean verifyforDigitalItem()
{
return isExistByTextContains(digitalProduct);
}
public boolean verifyForTheSellerVoucher(String voucherType)
{
int tries = 5;
try {
waitUntilVisibility(tagNamelblBy);
if (booleanwaitUntilPresentOfElementBy(overSeasPopupClosebtnBy,10))
overSeasPopupClosebtn.click();
waitUntilClickable(tagNamelblBy);
do {
tagNamelbl.get(0).click();
if (isExistedByButtonText(voucherType))
return true;
tries++;
}
while(tries < 5 && isExistedByButtonText(voucherType));
return false;
} catch (Exception e) {
throw new RuntimeException("Seller voucher is not existed on this product");
}
}
public boolean verifyTheApostrphieSignInTheProductName()
{
return productNamelbl.getText().contains("'");
}
}
|
package adp.group10.roomates.activities;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.internal.ForegroundLinearLayout;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import adp.group10.roomates.R;
import adp.group10.roomates.backend.FirebaseHandler;
import adp.group10.roomates.backend.model.AvailableItem;
import adp.group10.roomates.backend.model.ShoppingListEntry;
import adp.group10.roomates.fragments.AddItemsFragment;
import adp.group10.roomates.fragments.ShoppingListFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
ShoppingListFragment.OnFragmentInteractionListener,
AddItemsFragment.OnFragmentInterActionListener {
public DataSnapshot latestAvailableItemSnapshot;
public DataSnapshot latestShoppingListSnapshot;
@Override
protected void onStart() {
super.onStart();
if (LoginActivity.currentGroup == null )
{
startActivity(new Intent(this, SelectGroupActivity.class));
}
else
{
// Navigation View
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View header = navigationView.getHeaderView(0);
TextView tvUserName = (TextView) header.findViewById(R.id.tvUserName);
TextView tvGroupName = (TextView) header.findViewById(R.id.tvGroupName);
final TextView tvUserBalance = (TextView) header.findViewById(R.id.tvUserBalance);
tvUserName.setText(LoginActivity.currentuser);
tvGroupName.setText("Group: " + LoginActivity.currentGroup);
DatabaseReference balanceRef = FirebaseDatabase.getInstance().getReference(
FirebaseHandler.KEY_GROUPUSER + "/" + LoginActivity.currentGroup + "/"
+ LoginActivity.currentuser + "/" + "BALANCE");
balanceRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
double balance = Double.parseDouble(dataSnapshot.getValue().toString());
String result = String.format("%.2f", balance);
tvUserBalance.setText("Balance:" + result + "~");
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference availableItemRef = database.getReference(
FirebaseHandler.KEY_AVAILABLE_LIST + "/" + LoginActivity.currentGroup);
DatabaseReference shoppingListRef = database.getReference(
FirebaseHandler.KEY_SHOPPING_LIST + "/" + LoginActivity.currentGroup);
availableItemRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
latestAvailableItemSnapshot = dataSnapshot;
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
shoppingListRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
latestShoppingListSnapshot = dataSnapshot;
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
ShoppingListFragment fragment =
(ShoppingListFragment) getSupportFragmentManager().findFragmentById(
R.id.fShoppingList);
fragment.updateUI();
AddItemsFragment fragment1 =
(AddItemsFragment) getSupportFragmentManager().findFragmentById(
R.id.fAddItemsFragment);
fragment1.updateUI();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ActionBar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// App Drawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// Navigation View
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportActionBar().setTitle(R.string.app_name);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
int id = item.getItemId();
switch (item.getItemId()) {
case R.id.nav_group_join:
startActivity(new Intent(this, JoinGroupActivity.class));
break;
case R.id.nav_group_choose:
startActivity(new Intent(this, SelectGroupActivity.class));
break;
case R.id.nav_group_create:
startActivity(new Intent(this, CreateGroupActivity.class));
break;
case R.id.nav_account_update:
startActivity(new Intent(this, UpdateUserAccountActivity.class));
break;
case R.id.nav_settlement_request:
startActivity(new Intent(this, SettlementActivity.class));
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onFragmentInteraction(Uri uri) {
// TODO Implement interaction between ShoppingListFragment and AddItemsFragment
}
/**
* Opens a dialog to add a new item to the shopping list
*/
public void onClick_fabAddCustomItem(View view) {
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog_add_item, null);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView);
builder.setTitle("Add your own item");
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EditText etNewItem = (EditText) dialogView.findViewById(R.id.etNewItem);
String name = etNewItem.getText().toString().trim(); // TODO Check for length==0
AvailableItem item = new AvailableItem(name);
ShoppingListEntry shoppingListItem = new ShoppingListEntry(name,
1); // TODO check for duplicate
DatabaseReference shoppingListRef = FirebaseDatabase.getInstance().getReference(
FirebaseHandler.KEY_SHOPPING_LIST + "/" + LoginActivity.currentGroup);
DatabaseReference availableItemsRef = FirebaseDatabase.getInstance().getReference(
FirebaseHandler.KEY_AVAILABLE_LIST + "/" + LoginActivity.currentGroup);
if(!isDuplicateName(item.getName(), latestShoppingListSnapshot))
shoppingListRef.push().setValue(shoppingListItem);
else
incrementShoppingCartItem(item.getName(), 1);
if(!isDuplicateName(item.getName(), latestAvailableItemSnapshot))
availableItemsRef.push().setValue(item);
}
});
builder.show();
}
//For AvailableItems only
public boolean isDuplicateName(String item, DataSnapshot snapShot) {
for (DataSnapshot snap : snapShot.getChildren()) {
String currentIteratingItem = snap.getValue(AvailableItem.class).getName();
if (currentIteratingItem.equals(item)) {
return true;
}
}
return false;
}
public void incrementShoppingCartItem(String Name, int increment) {
for (DataSnapshot snap : latestShoppingListSnapshot.getChildren()) {
ShoppingListEntry currentIteratingItem = snap.getValue(ShoppingListEntry.class);
Log.v("Iteration", currentIteratingItem.getName());
if (currentIteratingItem.getName().equals(Name)) {
if (currentIteratingItem.getAmount() + increment <= 0){
snap.getRef().removeValue();
}
else{
currentIteratingItem.setAmount(currentIteratingItem.getAmount() + increment);
snap.getRef().setValue(currentIteratingItem);
}
return;
}
}
return;
}
@Override
public void onClickAvailableItem(AvailableItem item) {
// TODO Increment in ShoppingListFragment
ShoppingListFragment fragment =
(ShoppingListFragment) getSupportFragmentManager().findFragmentById(
R.id.fShoppingList);
fragment.onClickAvailableItem(item);
}
}
|
package com.nikvay.saipooja_patient.model;
public class AppoinmentDateFilterModel {
String patient_id;
String appointment_id;
String service_id;
String label;
String comment;
String time;
String date;
String s_name;
String service_cost;
String service_time;
String description;
String name;
public AppoinmentDateFilterModel(String patient_id, String appointment_id, String service_id, String label, String comment,
String time, String date, String s_name, String service_cost,
String service_time, String description, String name) {
this.patient_id = patient_id;
this.appointment_id = appointment_id;
this.service_id = service_id;
this.label = label;
this.comment = comment;
this.time = time;
this.date = date;
this.s_name = s_name;
this.service_cost = service_cost;
this.service_time = service_time;
this.description = description;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPatient_id() {
return patient_id;
}
public void setPatient_id(String patient_id) {
this.patient_id = patient_id;
}
public String getAppointment_id() {
return appointment_id;
}
public void setAppointment_id(String appointment_id) {
this.appointment_id = appointment_id;
}
public String getService_id() {
return service_id;
}
public void setService_id(String service_id) {
this.service_id = service_id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getS_name() {
return s_name;
}
public void setS_name(String s_name) {
this.s_name = s_name;
}
public String getService_cost() {
return service_cost;
}
public void setService_cost(String service_cost) {
this.service_cost = service_cost;
}
public String getService_time() {
return service_time;
}
public void setService_time(String service_time) {
this.service_time = service_time;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
package fall2018.csc2017.gamelauncher;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import java.util.Map;
import fall2018.csc2017.R;
import fall2018.csc2017.common.SaveAndLoadFiles;
import fall2018.csc2017.common.SaveAndLoadGames;
import fall2018.csc2017.scoring.LeaderBoardActivity;
import fall2018.csc2017.slidingtiles.SlidingBoardManager;
import fall2018.csc2017.slidingtiles.SlidingGameActivity;
import fall2018.csc2017.users.User;
public class SlidingFragment extends Fragment implements SaveAndLoadFiles, SaveAndLoadGames {
/**
* The name of the game.
*/
public static final String GAME_TITLE = "Sliding Tiles";
/**
* The main save file.
*/
public static final String TEMP_SAVE_FILENAME = "st_save_file.ser";
/**
* The name of the current logged in user.
*/
private User currentUser;
/**
* The board manager.
*/
private SlidingBoardManager slidingBoardManager;
/**
* A HashMap of all the Users created. The key is the username, the value is the User object.
*/
private Map<String, User> userAccounts;
/**
* String to signify Game Start
*/
private String startMessage = "Game Start";
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_slidingtiles, container, false);
userAccounts = loadUserAccounts();
currentUser = userAccounts.get(loadCurrentUsername());
addLeaderBoardListener(view);
addLaunchGame3Listener(view);
addLaunchGame4Listener(view);
addLaunchGame5Listener(view);
addLoadButtonListener(view);
return view;
}
/**
* Activate the Sliding Tiles 3x3 button.
*/
private void addLaunchGame3Listener(View view) {
Button launchGame3Button = view.findViewById(R.id.LaunchGame3);
launchGame3Button.setOnClickListener(v -> {
slidingBoardManager = new SlidingBoardManager(3);
createToast(startMessage);
switchToSlidingTileGameActivity();
});
}
/**
* Activate the Sliding Tiles 4x4 button.
*/
private void addLaunchGame4Listener(View view) {
Button launchGame4Button = view.findViewById(R.id.LaunchGame4);
launchGame4Button.setOnClickListener(v -> {
slidingBoardManager = new SlidingBoardManager(4);
createToast(startMessage);
switchToSlidingTileGameActivity();
});
}
/**
* Activate the Sliding Tiles 5x5 button.
*/
private void addLaunchGame5Listener(View view) {
Button launchGame5Button = view.findViewById(R.id.LaunchGame5);
launchGame5Button.setOnClickListener(v -> {
slidingBoardManager = new SlidingBoardManager(5);
createToast(startMessage);
switchToSlidingTileGameActivity();
});
}
/**
* Activate the load button.
*/
private void addLoadButtonListener(View view) {
Button loadButton = view.findViewById(R.id.LoadButton);
final boolean saveFileExists = currentUser.getSaves().containsKey(GAME_TITLE);
loadButton.setOnClickListener(v -> {
createToast("Game Loaded");
slidingBoardManager =
(SlidingBoardManager) currentUser.getSaves().get(GAME_TITLE);
switchToSlidingTileGameActivity();
});
loadButton.setAlpha(saveFileExists ? 1.0f : 0.5f);
loadButton.setClickable(saveFileExists);
}
/**
* Activate the scoreboard of top scores button.
*/
private void addLeaderBoardListener(View view) {
Button scoreBoardButton = view.findViewById(R.id.LeaderBoardButton);
scoreBoardButton.setOnClickListener(v -> switchToLeaderBoardActivity());
}
/**
* Switch to the SlidingTilesGameActivity view
*/
private void switchToSlidingTileGameActivity() {
Intent tmp = new Intent(getActivity(), SlidingGameActivity.class);
saveGameToFile(TEMP_SAVE_FILENAME, slidingBoardManager);
startActivity(tmp);
}
/**
* Switch to the LeaderBoard view
*/
private void switchToLeaderBoardActivity() {
Intent tmp = new Intent(getActivity(), LeaderBoardActivity.class);
tmp.putExtra("frgToLoad", 0);
startActivity(tmp);
FragmentActivity o = getActivity();
if (o != null) {
o.finish();
}
}
@SuppressWarnings("ConstantConditions")
@Override
public void onResume() {
super.onResume();
userAccounts = loadUserAccounts();
currentUser = userAccounts.get(loadCurrentUsername());
addLoadButtonListener(getView());
}
/**
* @param msg The message to be displayed in the Toast.
*/
private void createToast(String msg) {
Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
}
}
|
package cn.canlnac.onlinecourse.domain;
import java.util.List;
/**
* 评论.
*/
public class Comment {
private int id;
private long date;
private SimpleUser author;
private String content;
private List<String> pictureUrls;
private int likeCount;
private int replyCount;
private List<Reply> replies;
private boolean isLike;
private boolean isReply;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public SimpleUser getAuthor() {
return author;
}
public void setAuthor(SimpleUser author) {
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<String> getPictureUrls() {
return pictureUrls;
}
public void setPictureUrls(List<String> pictureUrls) {
this.pictureUrls = pictureUrls;
}
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(int likeCount) {
this.likeCount = likeCount;
}
public int getReplyCount() {
return replyCount;
}
public void setReplyCount(int replyCount) {
this.replyCount = replyCount;
}
public List<Reply> getReplies() {
return replies;
}
public void setReplies(List<Reply> replies) {
this.replies = replies;
}
public boolean isLike() {
return isLike;
}
public void setLike(boolean like) {
isLike = like;
}
public boolean isReply() {
return isReply;
}
public void setReply(boolean reply) {
isReply = reply;
}
}
|
package com.herz.prg3.sudoku.model;
public class SudokuMatrix {
private static final int SUDOKU_MATRIX_SIZE = 9;
private static final int MATRIX_SIZE = 3;
private NumberMatrix mSudokuMatrix;
private NumberMatrix[][] mMatrix;
public SudokuMatrix(int[][] matrix) {
this.mSudokuMatrix = new NumberMatrix(SudokuMatrix.SUDOKU_MATRIX_SIZE, matrix);
this.mMatrix = new NumberMatrix[SudokuMatrix.MATRIX_SIZE][SudokuMatrix.MATRIX_SIZE];
this.fillMatrix();
this.setMatrix(matrix);
}
private void setMatrix(int[][] matrix) {
for(int e = 0; e < 3; e++) {
for (int i = 0; i < 9; i++) {
int position = 3 * e;
System.arraycopy(this.mSudokuMatrix.getNumberRow(i),
position,
this.mMatrix[i / 3][e].getNumberRow(i % 3),
0, 3);
}
}
}
private void fillMatrix() {
for (int i = 0; i < this.mMatrix.length; i++) {
for (int e = 0; e < this.mMatrix.length; e++) {
this.mMatrix[i][e] = new NumberMatrix(3, new int[][]{});
this.mMatrix[i][e].fill();
}
}
}
public class MatrixValidator {
public boolean validate(int number, int row, int column) {
// Number[][] matrix = getSudokuMatrix();
// if (getSudokuMatrix()[row][column].getIsFixed()) {
// return false;
// } else {
// return this.checkMatrix(number, matrix, row, column);
// }
return false;
}
private boolean checkMatrix(int number, Number[][] matrix, int row, int column) {
for (int e = 0; e < SudokuMatrix.SUDOKU_MATRIX_SIZE; e++) {
if (matrix[row][e].getNumber() == number) {
return false;
}
}
for (int e = 0; e < SudokuMatrix.SUDOKU_MATRIX_SIZE; e++) {
if (matrix[e][column].getNumber() == number) {
return false;
}
}
int a = column % 3;
int rowCounter = 0;
int columnCounter = 0;
for (int i = a; i < 3; i++) {
for (int e = column + (rowCounter % 3); rowCounter < 9; e++) {
if (matrix[row][e].getNumber() == number) {
return false;
} else {
a++;
if (a == 2) {
e -= 3;
}
}
rowCounter++;
}
}
return false;
}
}
}
|
package org.training.issuetracker.services;
import java.util.List;
import org.training.issuetracker.dao.entities.Project;
public interface ProjectService {
/**
* @return List of all projects
*/
public List<Project> getProjects();
/**
* Returns Project object with stated projectId
* @param projectId
* @return Project
*/
public Project getProjectById(int projectId);
/**
* Defines the unique project's Id by the name
* @param firstName
* @return String projectId
*/
public Integer getProjectIdByName(String name);
/**
* Adds new project in a data storage
* @param Project
* @return boolean - true, if it was successful
*/
public boolean createProject(Project project);
/**
* Update the project's data
* @param Project
* @return boolean - true, if it was successful
*/
public boolean updateProject(Project project);
/**
* Delete project from a data storage by the unique projectId
* @param projectId
* @return boolean - true, if it was successful
*/
public boolean deleteProject(int projectId);
}
|
package com.gcipriano.katas.salestaxes.receipt;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
public class BulletPointReceiptBuilderTest
{
private BulletPointReceiptBuilder receipt;
@Before
public void setUp() throws Exception
{
receipt = new BulletPointReceiptBuilder();
}
@Test
public void oneProductReceipt() throws Exception
{
receipt.addProduct(new PresentableProduct("PRODUCT_NAME", "PRODUCT_PRICE"));
receipt.total("TOTAL");
receipt.taxTotal("TAX_TOTAL");
assertThat(receipt.render(), is("1 PRODUCT_NAME: PRODUCT_PRICE\n"
+ "Sales Taxes: TAX_TOTAL\n"
+ "Total: TOTAL"));
}
@Test
public void twoProductReceipt() throws Exception
{
receipt.addProduct(new PresentableProduct("PRODUCT_NAME", "PRODUCT_PRICE"));
receipt.addProduct(new PresentableProduct("ANOTHER_PRODUCT_NAME", "ANOTHER_PRODUCT_PRICE"));
receipt.total("TOTAL");
receipt.taxTotal("TAX_TOTAL");
assertThat(receipt.render(), is("1 PRODUCT_NAME: PRODUCT_PRICE\n"
+"1 ANOTHER_PRODUCT_NAME: ANOTHER_PRODUCT_PRICE\n"
+ "Sales Taxes: TAX_TOTAL\n"
+ "Total: TOTAL"));
}
}
|
package tchat;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
public class Historique {
String data;
InetAddress addrhist;
File monfichier;
public void Historique(InetAddress addrhist) throws IOException
{
this.addrhist=addrhist;
monfichier = new File("/home/sbesnard/Bureau/tchat/"+addrhist.getHostAddress());
if(monfichier.exists())
{
BufferedReader br = new BufferedReader(new FileReader(monfichier));
String line;
while ((line = br.readLine()) != null) {
data = data + line + "\n";
}
br.close();
}
else
{
monfichier.createNewFile();
}
}
public String get_data()
{
return data;
}
public void set_data(String moredata) throws IOException
{
FileWriter writer = new FileWriter(monfichier);
PrintWriter printWriter = new PrintWriter(writer);
printWriter.print(moredata);
writer.flush();
writer.close();
}
}
|
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.annotation.WebServlet;
/**
* Created by Bhuvie on 3/26/2017.
*/
@WebServlet("/checkperfrds")
public class checkperfrds extends javax.servlet.http.HttpServlet {
private static final String url = "jdbc:mysql://bhuviedbi.cwyiughlbpf0.us-west-2.rds.amazonaws.com:3306/bhuviedb";
private static final String user = "bhuvie93";
private static final String pass = "###############";
//Statement DataBaseStatement;
Connection con;
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
//ArrayList<String> teamlist =new ArrayList<String>();
String noqtimes=request.getParameter("txtquerytimesrds");
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, pass);
//DataBaseStatement = con.createStatement();
PreparedStatement ps = con.prepareStatement("select * from bhuviedb.networktraffic" );
//ps.setString(1,"");
ResultSet rs;
long timebefore=System.currentTimeMillis();
for (int i = 0; i < Integer.parseInt(noqtimes); i++) {
rs = ps.executeQuery();
String arr = "";
while (rs.next()) {
arr = arr+rs.getString("date");
System.out.println(arr);
}
}
long timeafter=System.currentTimeMillis();
long timetaken=timeafter-timebefore;
con.close();
PrintWriter pw = response.getWriter().append(Long.toString(timetaken));
pw.close();
// while(rs.next())
// {
// String tname=rs.getString("teamname");
// teamlist.add(tname);
// }
} catch (ClassNotFoundException e) {
e.printStackTrace();
// PrintWriter pw = response.getWriter().append(e.toString());
// pw.close();
} catch (SQLException e) {
e.printStackTrace();
// PrintWriter pw = response.getWriter().append(e.toString());
// pw.close();
}
catch (Exception e) {
e.printStackTrace();
// PrintWriter pw = response.getWriter().append(e.toString());
// pw.close();
}
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doPost(request,response);
}
}
|
package net.floodlightcontroller.dpkmconfigurewg;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* REST API for compromising a switch to simulate the behaviour of some security
* system and begin the revocation procedure. </br>
* Takes json data from UI and deserializes, executing corresponding function.
*
* @author Luke Hengstenberg
* @version 1.0
*/
public class DpkmCompromiseNodeResource extends ServerResource {
protected static Logger log =
LoggerFactory.getLogger(DpkmConfigureWGResource.class);
/**
* Compromise the switch with matching info in the given fmJson. </br>
* Calls compromiseNode with the id which ends all communication with the
* switch and sets it as "COMPROMISED".
* @param fmJson Json structure containing switch information.
* @return String status either success or error.
* @see DpkmConfigureWGResource#jsonToDpkmSwitch(String)
* @see DpkmConfigureWG#compromiseNode(int)
*/
@Post
public String compromise(String fmJson) {
IDpkmConfigureWGService configureWG =
(IDpkmConfigureWGService)getContext().getAttributes()
.get(IDpkmConfigureWGService.class.getCanonicalName());
DpkmSwitch node = DpkmConfigureWGResource.jsonToDpkmSwitch(fmJson);
String status = null;
if (node == null) {
status = "Error! Could not parse switch info, see log for details.";
log.error(status);
return ("{\"status\" : \"" + status + "\"}");
}
configureWG.compromiseNode(node.id);
status = "Node has been compromised.";
return ("{\"status\" : \"" + status + "\"}");
}
}
|
package com.globomart.catalog.models;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@StaticMetamodel(Product.class)
public class Product_ {
public static volatile SingularAttribute<Product, String> productName;
public static volatile SingularAttribute<Product, String> productDescription;
}
|
package com.smxknife.java2.thread.executorservice.demo01;
import lombok.*;
/**
* @author smxknife
* 2019/8/28
*/
@AllArgsConstructor
@NoArgsConstructor
@Getter@Setter
@ToString
public class UserInfo {
private String username;
private String password;
}
|
package com.yida.design.abstractfactory.abs;
import com.yida.design.abstractfactory.Human;
/**
*********************
* @author yangke
* @version 1.0
* @created 2018年4月20日 下午3:17:47
***********************
*/
public abstract class AbstractYellowHuman implements Human {
@Override
public void getColor() {
System.out.println("黄色人种的皮肤颜色是黄色的!");
}
@Override
public void talk() {
System.out.println("黄色人种会说话,一般说的都是双字节。");
}
}
|
package com.dreamorbit.scripts;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import java.util.concurrent.TimeUnit;
import org.testng.AssertJUnit;
import org.testng.Reporter;
import org.testng.annotations.Test;
import com.dreamorbit.generic.BaseTest;
import com.dreamorbit.generic.Commons;
import com.dreamorbit.pages.LabelPage;
import com.dreamorbit.pages.ParticipantListPage;
import com.dreamorbit.pages.ParticipantPage;
import com.dreamorbit.pages.SymmetricKeyPage;
public class JsonDownloadValidSkeyTest extends BaseTest
{
@Test(priority = 4, enabled = true)
public void jsonDownloadCheck() throws InterruptedException
{
Commons commons= new Commons();
BaseTest baseTest= new BaseTest();
LabelPage studypage= new LabelPage(driver);
ParticipantListPage participantListPage = new ParticipantListPage(driver);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
commons.login(driver);
commons.studiesScreenWait(driver);
Thread.sleep(3000);
studypage.particpantLabelClick();
Thread.sleep(3000);
participantListPage.clickUploads();
Thread.sleep(2000);
commons.downloadJson(driver,false);
/*
* participantPage.fileJsonClick();
* symmetricKeyPage.sendSymmetricKey(validSKEY); symmetricKeyPage.sK_clickOk();
*/
String actualDownlaodSuccessToast= commons.getToastMSG(driver);
AssertJUnit.assertEquals(actualDownlaodSuccessToast, "File downloaded successfully");
Reporter.log("Json Download testcase with valid symmetric key is passed");
}
}
|
package com.android.adapter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.android.demo.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class CartListAdapter extends BaseAdapter {
List<Map<String,Object>> list ;
LayoutInflater inflater ;
private Context mContext;
public void setData(List<Map<String,Object>> data){
this.list = data ;
}
public CartListAdapter(Context context) {
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>() ;
inflater = LayoutInflater.from(context) ;
mContext = context;
}
@Override
public int getCount() {
return list.size() ;
}
@Override
public Object getItem(int position) {
return list.get(position) ;
}
@Override
public long getItemId(int position) {
return position ;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vhHolder ;
if(convertView == null){
vhHolder = new ViewHolder() ;
convertView = inflater.inflate(R.layout.cart_item, null) ;
vhHolder.tv0 = (TextView) convertView.findViewById(R.id.textView3) ;
vhHolder.tv1 = (TextView) convertView.findViewById(R.id.textView1) ;
vhHolder.tv2 = (TextView) convertView.findViewById(R.id.textView2) ;
vhHolder.tv3 = (TextView) convertView.findViewById(R.id.textView4) ;
convertView.findViewById(R.id.imageView1).setBackgroundDrawable(new BitmapDrawable(readBitMap(mContext, R.drawable.address_one)));
convertView.findViewById(R.id.imageView2).setBackgroundDrawable(new BitmapDrawable(readBitMap(mContext, R.drawable.company)));
vhHolder.imgbtn0 = (ImageButton) convertView.findViewById(R.id.imageButton1) ;
convertView.setTag(vhHolder) ;
}else{
vhHolder = (ViewHolder) convertView.getTag() ;
}
vhHolder.tv1.setText(list.get(position).get("id")+" M") ;
vhHolder.tv0.setText(list.get(position).get("address").toString()) ;
vhHolder.tv2.setText("¥ "+list.get(position).get("money")) ;
vhHolder.tv3.setText(list.get(position).get("company").toString()) ;
return convertView ;
}
static class ViewHolder{
TextView tv0 ;
TextView tv1 ;
TextView tv2 ;
TextView tv3 ;
ImageView img0;
ImageView img1;
ImageButton imgbtn0;
}
public static Bitmap readBitMap(Context context, int resId){
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
opt.inSampleSize = computeSampleSize(opt, -1, 128*128); //计算出图片使用的inSampleSize
opt.inJustDecodeBounds = false;
//获取资源图片
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is,null,opt);
}
public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,maxNumOfPixels);
int roundedSize;
if (initialSize <= 8 ) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 :
(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 :
(int) Math.min(Math.floor(w / minSideLength),
Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) &&
(minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
}
|
package pe.gob.trabajo.web.rest;
import pe.gob.trabajo.LiquidacionesApp;
import pe.gob.trabajo.domain.Tippersona;
import pe.gob.trabajo.repository.TippersonaRepository;
import pe.gob.trabajo.repository.search.TippersonaSearchRepository;
import pe.gob.trabajo.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the TippersonaResource REST controller.
*
* @see TippersonaResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LiquidacionesApp.class)
public class TippersonaResourceIntTest {
private static final String DEFAULT_V_DESTIPPER = "AAAAAAAAAA";
private static final String UPDATED_V_DESTIPPER = "BBBBBBBBBB";
private static final Integer DEFAULT_N_USUAREG = 1;
private static final Integer UPDATED_N_USUAREG = 2;
private static final Instant DEFAULT_T_FECREG = Instant.ofEpochMilli(0L);
private static final Instant UPDATED_T_FECREG = Instant.now().truncatedTo(ChronoUnit.MILLIS);
private static final Boolean DEFAULT_N_FLGACTIVO = false;
private static final Boolean UPDATED_N_FLGACTIVO = true;
private static final Integer DEFAULT_N_SEDEREG = 1;
private static final Integer UPDATED_N_SEDEREG = 2;
private static final Integer DEFAULT_N_USUAUPD = 1;
private static final Integer UPDATED_N_USUAUPD = 2;
private static final Instant DEFAULT_T_FECUPD = Instant.ofEpochMilli(0L);
private static final Instant UPDATED_T_FECUPD = Instant.now().truncatedTo(ChronoUnit.MILLIS);
private static final Integer DEFAULT_N_SEDEUPD = 1;
private static final Integer UPDATED_N_SEDEUPD = 2;
@Autowired
private TippersonaRepository tippersonaRepository;
@Autowired
private TippersonaSearchRepository tippersonaSearchRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restTippersonaMockMvc;
private Tippersona tippersona;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final TippersonaResource tippersonaResource = new TippersonaResource(tippersonaRepository, tippersonaSearchRepository);
this.restTippersonaMockMvc = MockMvcBuilders.standaloneSetup(tippersonaResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Tippersona createEntity(EntityManager em) {
Tippersona tippersona = new Tippersona()
.vDestipper(DEFAULT_V_DESTIPPER)
.nUsuareg(DEFAULT_N_USUAREG)
.tFecreg(DEFAULT_T_FECREG)
.nFlgactivo(DEFAULT_N_FLGACTIVO)
.nSedereg(DEFAULT_N_SEDEREG)
.nUsuaupd(DEFAULT_N_USUAUPD)
.tFecupd(DEFAULT_T_FECUPD)
.nSedeupd(DEFAULT_N_SEDEUPD);
return tippersona;
}
@Before
public void initTest() {
tippersonaSearchRepository.deleteAll();
tippersona = createEntity(em);
}
@Test
@Transactional
public void createTippersona() throws Exception {
int databaseSizeBeforeCreate = tippersonaRepository.findAll().size();
// Create the Tippersona
restTippersonaMockMvc.perform(post("/api/tippersonas")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tippersona)))
.andExpect(status().isCreated());
// Validate the Tippersona in the database
List<Tippersona> tippersonaList = tippersonaRepository.findAll();
assertThat(tippersonaList).hasSize(databaseSizeBeforeCreate + 1);
Tippersona testTippersona = tippersonaList.get(tippersonaList.size() - 1);
assertThat(testTippersona.getvDestipper()).isEqualTo(DEFAULT_V_DESTIPPER);
assertThat(testTippersona.getnUsuareg()).isEqualTo(DEFAULT_N_USUAREG);
assertThat(testTippersona.gettFecreg()).isEqualTo(DEFAULT_T_FECREG);
assertThat(testTippersona.isnFlgactivo()).isEqualTo(DEFAULT_N_FLGACTIVO);
assertThat(testTippersona.getnSedereg()).isEqualTo(DEFAULT_N_SEDEREG);
assertThat(testTippersona.getnUsuaupd()).isEqualTo(DEFAULT_N_USUAUPD);
assertThat(testTippersona.gettFecupd()).isEqualTo(DEFAULT_T_FECUPD);
assertThat(testTippersona.getnSedeupd()).isEqualTo(DEFAULT_N_SEDEUPD);
// Validate the Tippersona in Elasticsearch
Tippersona tippersonaEs = tippersonaSearchRepository.findOne(testTippersona.getId());
assertThat(tippersonaEs).isEqualToComparingFieldByField(testTippersona);
}
@Test
@Transactional
public void createTippersonaWithExistingId() throws Exception {
int databaseSizeBeforeCreate = tippersonaRepository.findAll().size();
// Create the Tippersona with an existing ID
tippersona.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restTippersonaMockMvc.perform(post("/api/tippersonas")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tippersona)))
.andExpect(status().isBadRequest());
// Validate the Tippersona in the database
List<Tippersona> tippersonaList = tippersonaRepository.findAll();
assertThat(tippersonaList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkvDestipperIsRequired() throws Exception {
int databaseSizeBeforeTest = tippersonaRepository.findAll().size();
// set the field null
tippersona.setvDestipper(null);
// Create the Tippersona, which fails.
restTippersonaMockMvc.perform(post("/api/tippersonas")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tippersona)))
.andExpect(status().isBadRequest());
List<Tippersona> tippersonaList = tippersonaRepository.findAll();
assertThat(tippersonaList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checknUsuaregIsRequired() throws Exception {
int databaseSizeBeforeTest = tippersonaRepository.findAll().size();
// set the field null
tippersona.setnUsuareg(null);
// Create the Tippersona, which fails.
restTippersonaMockMvc.perform(post("/api/tippersonas")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tippersona)))
.andExpect(status().isBadRequest());
List<Tippersona> tippersonaList = tippersonaRepository.findAll();
assertThat(tippersonaList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checktFecregIsRequired() throws Exception {
int databaseSizeBeforeTest = tippersonaRepository.findAll().size();
// set the field null
tippersona.settFecreg(null);
// Create the Tippersona, which fails.
restTippersonaMockMvc.perform(post("/api/tippersonas")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tippersona)))
.andExpect(status().isBadRequest());
List<Tippersona> tippersonaList = tippersonaRepository.findAll();
assertThat(tippersonaList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checknFlgactivoIsRequired() throws Exception {
int databaseSizeBeforeTest = tippersonaRepository.findAll().size();
// set the field null
tippersona.setnFlgactivo(null);
// Create the Tippersona, which fails.
restTippersonaMockMvc.perform(post("/api/tippersonas")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tippersona)))
.andExpect(status().isBadRequest());
List<Tippersona> tippersonaList = tippersonaRepository.findAll();
assertThat(tippersonaList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checknSederegIsRequired() throws Exception {
int databaseSizeBeforeTest = tippersonaRepository.findAll().size();
// set the field null
tippersona.setnSedereg(null);
// Create the Tippersona, which fails.
restTippersonaMockMvc.perform(post("/api/tippersonas")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tippersona)))
.andExpect(status().isBadRequest());
List<Tippersona> tippersonaList = tippersonaRepository.findAll();
assertThat(tippersonaList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllTippersonas() throws Exception {
// Initialize the database
tippersonaRepository.saveAndFlush(tippersona);
// Get all the tippersonaList
restTippersonaMockMvc.perform(get("/api/tippersonas?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(tippersona.getId().intValue())))
.andExpect(jsonPath("$.[*].vDestipper").value(hasItem(DEFAULT_V_DESTIPPER.toString())))
.andExpect(jsonPath("$.[*].nUsuareg").value(hasItem(DEFAULT_N_USUAREG)))
.andExpect(jsonPath("$.[*].tFecreg").value(hasItem(DEFAULT_T_FECREG.toString())))
.andExpect(jsonPath("$.[*].nFlgactivo").value(hasItem(DEFAULT_N_FLGACTIVO.booleanValue())))
.andExpect(jsonPath("$.[*].nSedereg").value(hasItem(DEFAULT_N_SEDEREG)))
.andExpect(jsonPath("$.[*].nUsuaupd").value(hasItem(DEFAULT_N_USUAUPD)))
.andExpect(jsonPath("$.[*].tFecupd").value(hasItem(DEFAULT_T_FECUPD.toString())))
.andExpect(jsonPath("$.[*].nSedeupd").value(hasItem(DEFAULT_N_SEDEUPD)));
}
@Test
@Transactional
public void getTippersona() throws Exception {
// Initialize the database
tippersonaRepository.saveAndFlush(tippersona);
// Get the tippersona
restTippersonaMockMvc.perform(get("/api/tippersonas/{id}", tippersona.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(tippersona.getId().intValue()))
.andExpect(jsonPath("$.vDestipper").value(DEFAULT_V_DESTIPPER.toString()))
.andExpect(jsonPath("$.nUsuareg").value(DEFAULT_N_USUAREG))
.andExpect(jsonPath("$.tFecreg").value(DEFAULT_T_FECREG.toString()))
.andExpect(jsonPath("$.nFlgactivo").value(DEFAULT_N_FLGACTIVO.booleanValue()))
.andExpect(jsonPath("$.nSedereg").value(DEFAULT_N_SEDEREG))
.andExpect(jsonPath("$.nUsuaupd").value(DEFAULT_N_USUAUPD))
.andExpect(jsonPath("$.tFecupd").value(DEFAULT_T_FECUPD.toString()))
.andExpect(jsonPath("$.nSedeupd").value(DEFAULT_N_SEDEUPD));
}
@Test
@Transactional
public void getNonExistingTippersona() throws Exception {
// Get the tippersona
restTippersonaMockMvc.perform(get("/api/tippersonas/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateTippersona() throws Exception {
// Initialize the database
tippersonaRepository.saveAndFlush(tippersona);
tippersonaSearchRepository.save(tippersona);
int databaseSizeBeforeUpdate = tippersonaRepository.findAll().size();
// Update the tippersona
Tippersona updatedTippersona = tippersonaRepository.findOne(tippersona.getId());
updatedTippersona
.vDestipper(UPDATED_V_DESTIPPER)
.nUsuareg(UPDATED_N_USUAREG)
.tFecreg(UPDATED_T_FECREG)
.nFlgactivo(UPDATED_N_FLGACTIVO)
.nSedereg(UPDATED_N_SEDEREG)
.nUsuaupd(UPDATED_N_USUAUPD)
.tFecupd(UPDATED_T_FECUPD)
.nSedeupd(UPDATED_N_SEDEUPD);
restTippersonaMockMvc.perform(put("/api/tippersonas")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedTippersona)))
.andExpect(status().isOk());
// Validate the Tippersona in the database
List<Tippersona> tippersonaList = tippersonaRepository.findAll();
assertThat(tippersonaList).hasSize(databaseSizeBeforeUpdate);
Tippersona testTippersona = tippersonaList.get(tippersonaList.size() - 1);
assertThat(testTippersona.getvDestipper()).isEqualTo(UPDATED_V_DESTIPPER);
assertThat(testTippersona.getnUsuareg()).isEqualTo(UPDATED_N_USUAREG);
assertThat(testTippersona.gettFecreg()).isEqualTo(UPDATED_T_FECREG);
assertThat(testTippersona.isnFlgactivo()).isEqualTo(UPDATED_N_FLGACTIVO);
assertThat(testTippersona.getnSedereg()).isEqualTo(UPDATED_N_SEDEREG);
assertThat(testTippersona.getnUsuaupd()).isEqualTo(UPDATED_N_USUAUPD);
assertThat(testTippersona.gettFecupd()).isEqualTo(UPDATED_T_FECUPD);
assertThat(testTippersona.getnSedeupd()).isEqualTo(UPDATED_N_SEDEUPD);
// Validate the Tippersona in Elasticsearch
Tippersona tippersonaEs = tippersonaSearchRepository.findOne(testTippersona.getId());
assertThat(tippersonaEs).isEqualToComparingFieldByField(testTippersona);
}
@Test
@Transactional
public void updateNonExistingTippersona() throws Exception {
int databaseSizeBeforeUpdate = tippersonaRepository.findAll().size();
// Create the Tippersona
// If the entity doesn't have an ID, it will be created instead of just being updated
restTippersonaMockMvc.perform(put("/api/tippersonas")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tippersona)))
.andExpect(status().isCreated());
// Validate the Tippersona in the database
List<Tippersona> tippersonaList = tippersonaRepository.findAll();
assertThat(tippersonaList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteTippersona() throws Exception {
// Initialize the database
tippersonaRepository.saveAndFlush(tippersona);
tippersonaSearchRepository.save(tippersona);
int databaseSizeBeforeDelete = tippersonaRepository.findAll().size();
// Get the tippersona
restTippersonaMockMvc.perform(delete("/api/tippersonas/{id}", tippersona.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate Elasticsearch is empty
boolean tippersonaExistsInEs = tippersonaSearchRepository.exists(tippersona.getId());
assertThat(tippersonaExistsInEs).isFalse();
// Validate the database is empty
List<Tippersona> tippersonaList = tippersonaRepository.findAll();
assertThat(tippersonaList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void searchTippersona() throws Exception {
// Initialize the database
tippersonaRepository.saveAndFlush(tippersona);
tippersonaSearchRepository.save(tippersona);
// Search the tippersona
restTippersonaMockMvc.perform(get("/api/_search/tippersonas?query=id:" + tippersona.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(tippersona.getId().intValue())))
.andExpect(jsonPath("$.[*].vDestipper").value(hasItem(DEFAULT_V_DESTIPPER.toString())))
.andExpect(jsonPath("$.[*].nUsuareg").value(hasItem(DEFAULT_N_USUAREG)))
.andExpect(jsonPath("$.[*].tFecreg").value(hasItem(DEFAULT_T_FECREG.toString())))
.andExpect(jsonPath("$.[*].nFlgactivo").value(hasItem(DEFAULT_N_FLGACTIVO.booleanValue())))
.andExpect(jsonPath("$.[*].nSedereg").value(hasItem(DEFAULT_N_SEDEREG)))
.andExpect(jsonPath("$.[*].nUsuaupd").value(hasItem(DEFAULT_N_USUAUPD)))
.andExpect(jsonPath("$.[*].tFecupd").value(hasItem(DEFAULT_T_FECUPD.toString())))
.andExpect(jsonPath("$.[*].nSedeupd").value(hasItem(DEFAULT_N_SEDEUPD)));
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Tippersona.class);
Tippersona tippersona1 = new Tippersona();
tippersona1.setId(1L);
Tippersona tippersona2 = new Tippersona();
tippersona2.setId(tippersona1.getId());
assertThat(tippersona1).isEqualTo(tippersona2);
tippersona2.setId(2L);
assertThat(tippersona1).isNotEqualTo(tippersona2);
tippersona1.setId(null);
assertThat(tippersona1).isNotEqualTo(tippersona2);
}
}
|
package client.by.epam.fullparser.controller.command;
import client.by.epam.fullparser.controller.command.impl.DisconnectCommand;
import client.by.epam.fullparser.controller.command.impl.ConnectCommand;
import client.by.epam.fullparser.controller.command.impl.FileAskCommand;
import java.util.HashMap;
public class CommandHelper {
private final HashMap<String, Command> commands;
public CommandHelper() {
commands = new HashMap<>();
commands.put("CONNECT", new ConnectCommand());
commands.put("PARSE_FILE", new FileAskCommand());
commands.put("DISCONNECT", new DisconnectCommand());
}
public Command getCommand(String commandName) {
return commands.get(commandName);
}
}
|
package com.mrlittlenew.sevice.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.mrlittlenew.dao.SysRoleDao;
import com.mrlittlenew.dao.UserInfoDao;
import com.mrlittlenew.domain.SysRole;
import com.mrlittlenew.domain.UserInfo;
import com.mrlittlenew.sevice.UserInfoService;
import com.mrlittlenew.util.PasswordHelper;
@Service
public class UserInfoServiceImpl implements UserInfoService {
@Resource
private UserInfoDao userInfoDao;
@Resource
private SysRoleDao sysRoleDao;
@Override
public UserInfo findByUsername(String username) {
System.out.println("UserInfoServiceImpl.findByUsername()");
return userInfoDao.findByUsername(username);
}
@Override
public boolean registerData(String username, String password) {
try{
long count = userInfoDao.count();
int uid = Long.valueOf(count).intValue()+1;
String saltStr=PasswordHelper.getCode(username);
String passwordCode=PasswordHelper.getCode(password,saltStr);
UserInfo user=new UserInfo();
user.setUid(uid);
user.setName(username);
user.setPassword(passwordCode);
user.setSalt(saltStr);
user.setUsername(username);
byte i=0;
user.setState(i);
List<SysRole> roleList = sysRoleDao.findByRole("vip");
user.setRoleList(roleList);
userInfoDao.save(user);
return true;
}catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
|
package com.project.auth.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
@Configuration
@EnableAuthorizationServer
public class JWTAuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Value("${check-user-scopes}")
private Boolean checkUserScopes;
@Autowired
JwtKeyStoreConfig jwtKeyStoreConfig;
@Autowired
private DataSource dataSource;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private ClientDetailsService clientDetailsService;
@Bean
public TokenStore tokenStore() {
return jwtKeyStoreConfig.tokenStore();
}
@Bean
public DefaultTokenServices tokenServices(final TokenStore tokenStore, final ClientDetailsService clientDetailsService)
{
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore);
tokenServices.setClientDetailsService(clientDetailsService);
tokenServices.setAuthenticationManager(this.authenticationManager);
return tokenServices;
}
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception
{
clients.jdbc( this.dataSource ).passwordEncoder( passwordEncoder );
}
@Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer)
{
oauthServer.passwordEncoder( this.passwordEncoder )
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints)
{
endpoints.authenticationManager(this.authenticationManager)
.accessTokenConverter( jwtKeyStoreConfig.accessTokenConverter() )
.tokenStore( jwtKeyStoreConfig.tokenStore() )
.userDetailsService( userDetailsService );
// Need more understanding why this one needed.
if (checkUserScopes)
endpoints.requestFactory(requestFactory());
}
@Bean
public OAuth2RequestFactory requestFactory() {
CustomOauth2RequestFactory requestFactory = new CustomOauth2RequestFactory(clientDetailsService);
requestFactory.setCheckUserScopes(true);
return requestFactory;
}
}
|
/**
* @Title: MispDataAccessService.java
* @Package cn.fuego.misp.service
* @Description: TODO
* @author Tang Jun
* @date 2015-5-22 上午9:21:37
* @version V1.0
*/
package cn.fuego.misp.webservice.json;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* @ClassName: MispDataAccessService
* @Description: TODO
* @author Tang Jun
* @date 2015-5-22 上午9:21:37
*
*/
@Path("/basic")
@Produces("application/json")
@Consumes("application/json")
public interface MispDataAccessRest
{
@POST
@Path("/ComDataAccess!Create.action")
MispBaseRspJson Create(MispComDataAccessReqJson req);
@POST
@Path("/ComDataAccess!Modify.action")
MispBaseRspJson Modify(MispComDataAccessReqJson req);
@POST
@Path("/ComDataAccess!Delete.action")
MispBaseRspJson Delete(MispComDataAccessReqJson req);
}
|
package com.jlgproject.model.newDebt;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import com.jlgproject.adapter.newDebt.BaseAdapter_jl;
import com.jlgproject.model.*;
import com.jlgproject.model.AssetNew;
import java.io.Serializable;
import java.util.List;
/**
* @author 王锋 on 2017/8/21.
*/
public class StoreMode implements Serializable {
private List<com.jlgproject.model.newDebt.AssetNew> list;
private LinearLayout linearLayout;
private BaseAdapter_jl adapter_jl;
public StoreMode(List<com.jlgproject.model.newDebt.AssetNew> list, LinearLayout linearLayout, BaseAdapter_jl adapter_jl) {
this.list = list;
this.linearLayout = linearLayout;
this.adapter_jl = adapter_jl;
}
public List<com.jlgproject.model.newDebt.AssetNew> getList() {
return list;
}
public void setList(List<com.jlgproject.model.newDebt.AssetNew> list) {
this.list = list;
}
public LinearLayout getLinearLayout() {
return linearLayout;
}
public void setLinearLayout(LinearLayout linearLayout) {
this.linearLayout = linearLayout;
}
public BaseAdapter_jl getAdapter_jl() {
return adapter_jl;
}
public void setAdapter_jl(BaseAdapter_jl adapter_jl) {
this.adapter_jl = adapter_jl;
}
}
|
package edu.uic.ids561;
//import statements
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class Mapper1 extends Mapper<LongWritable, Text, Text, Text>
{
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException
{
Node node = new Node(value.toString());
if(node.getColor() == Node.Color.GRAY)
{
for(String neighbor : node.getEdges())
{
Node adjacentNode = new Node();
adjacentNode.setId(neighbor);
adjacentNode.setDist(node.getDist() + 1);
adjacentNode.setColor(Node.Color.GRAY);
adjacentNode.setParent(node.getId());
context.write(new Text(adjacentNode.getId()), new Text(adjacentNode.getNodeInfo()));
}
node.setColor(Node.Color.BLACK);
}
context.write(new Text(node.getId()), new Text(node.getNodeInfo()));
}
}
|
package com.example.device;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.example.device.widget.TurnSurfaceView;
/**
* Created by ouyangshen on 2017/11/4.
*/
public class TurnSurfaceActivity extends AppCompatActivity implements OnCheckedChangeListener {
private TurnSurfaceView tfv_circle; // 声明一个转动表面视图
private CheckBox ck_control;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_turn_surface);
// 从布局文件中获取名叫tfv_circle的转动表面视图
tfv_circle = findViewById(R.id.tfv_circle);
ck_control = findViewById(R.id.ck_control);
ck_control.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.getId() == R.id.ck_control) {
if (isChecked) {
ck_control.setText("停止");
tfv_circle.start(); // 转动表面视图开始转动
} else {
ck_control.setText("转动");
tfv_circle.stop(); // 转动表面视图停止转动
}
}
}
}
|
package com.spring.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.spring.dao.SizeDAO;
import com.spring.dto.SizeDTO;
@Service
public class SizeServiceImpl implements SizeService{
@Resource
private SizeDAO sdao;
@Override
public List<SizeDTO> selectList(SizeDTO sdto) throws Exception {
// TODO Auto-generated method stub
return sdao.selectList(sdto);
}
@Override
public int insert(SizeDTO sdto) throws Exception {
return sdao.insert(sdto);
}
@Override
public int delete(String code,String size) throws Exception {
SizeDTO sdto = new SizeDTO();
sdto.setCode(code);
sdto.setSize(size);
return sdao.delete(sdto);
}
@Override
public SizeDTO selectOne(String code, String size,String qty) throws Exception {
SizeDTO sdto = new SizeDTO();
sdto.setCode(code);
sdto.setSize(size);
sdto.setQty(qty);
return sdao.selectOne(sdto);
}
@Override
public int update(SizeDTO sdto) throws Exception {
return sdao.update(sdto);
}
@Override
public int selectCnt(String code) throws Exception {
// TODO Auto-generated method stub
return sdao.selectCnt(code);
}
@Override
public List<String> selectSize(String code) throws Exception {
// TODO Auto-generated method stub
return sdao.selectSize(code);
}
}
|
/**
* Exception class
* Bad quantity refers to net shares of stock owned falling under 0
*/
package stockorganizer;
public class BadQuantityException extends Exception {
public BadQuantityException(String arg) {
super(arg);
}
}
|
package algorithm.DataProcessing;
public class BitOperation {
/**
* 获取最后一位1
*/
public static int getTrailingOne(int x){
return x&(-x);
}
/**
* 获取最前一位1
*/
public static int getLeadingOne(int x){
return Integer.highestOneBit(x);
}
/**
* 最后一位0变为1,其他位为0
*/
public static int getTrailingZero(int x){
return ~x&(x+1);
}
/**
* 翻转最后一位1
*/
public static int flipTrailingOne(int x){
return x&(x-1);
}
/**
* 翻转最后一位0
*/
public static int flipTrailingZero(int x){
return x|(x+1);
}
/**
* 前导0个数
*/
public static int LeadingZerosNum(int x){
return Integer.numberOfLeadingZeros(x);
}
/**
* 尾部0个数
*/
public static int TrailingZerosNum(int x){
return Integer.numberOfTrailingZeros(x);
}
/**
* x中1的个数
*/
public static int bitCount(int x){
return Integer.bitCount(x);
}
/**
* 获取最前一位1的位置(0-base),没有1返回-1
*/
public static int LeadingOnePos(int x){
return 31-Integer.numberOfLeadingZeros(x);
}
/**
* 将x前导0以外所有位填充为1
*/
public static int fillOne(int x){
x |= x >>> 1;
x |= x >>> 2;
x |= x >>> 4;
x |= x >>> 8;
x |= x >>> 16;
return x;
}
/**
* x是否全为1(除前导0),0为true
* @param x
* @return
*/
public static boolean AllOne(int x){
return (x&(x+1))==0;
}
/**
* x是否只有一个1
* @param x
* @return
*/
public static boolean SingleOne(int x){
if(x==0)return false;
return (x&(x-1))==0;
}
/**
* 按位逆序
*/
public static int reverse(int x){
return Integer.reverse(x);
}
/**
* 按字节逆序
*/
public static int reverseBytes(int x){
return Integer.reverseBytes(x);
}
/**
* 翻转01
*/
public static int flip(int x){
return ~x;
}
/**
* 循环左移
*/
public static int rotateLeft(int x,int d){
return Integer.rotateLeft(x,d);
}
/**
* 循环右移
*/
public static int rotateRight(int x,int d){
return Integer.rotateRight(x,d);
}
}
|
package com.tencent.mm.app.plugin;
import android.content.Intent;
import android.os.Bundle;
import com.tencent.mm.app.plugin.URISpanHandlerSet.BaseUriSpanHandler;
import com.tencent.mm.app.plugin.URISpanHandlerSet.a;
import com.tencent.mm.bg.d;
import com.tencent.mm.pluginsdk.s;
import com.tencent.mm.pluginsdk.ui.applet.m;
import com.tencent.mm.pluginsdk.ui.d.g;
@a
class URISpanHandlerSet$CardUriSpanHandler extends BaseUriSpanHandler {
final /* synthetic */ URISpanHandlerSet bAt;
URISpanHandlerSet$CardUriSpanHandler(URISpanHandlerSet uRISpanHandlerSet) {
this.bAt = uRISpanHandlerSet;
super(uRISpanHandlerSet);
}
final m db(String str) {
return null;
}
final int[] vB() {
return new int[0];
}
final boolean a(m mVar, g gVar) {
return false;
}
final boolean a(String str, boolean z, s sVar, Bundle bundle) {
if (!str.startsWith("wxcard://cardjumptype=1")) {
return false;
}
String str2 = null;
if (sVar != null) {
str2 = sVar.cbm().toString();
}
Intent intent = new Intent();
intent.putExtra("user_name", str2);
intent.putExtra("view_type", 1);
d.b(URISpanHandlerSet.a(this.bAt), "card", ".ui.CardViewUI", intent);
return true;
}
}
|
/*
* CursOnDate.java
* This file was last modified at 2018.12.03 20:05 by Victor N. Skurikhin.
* $Id$
* This is free and unencumbered software released into the public domain.
* For more information, please refer to <http://unlicense.org>
*/
package ru.otus.rest.cbr;
import ru.otus.adapters.soap.GetCursOnDateXMLAdapter;
import ru.otus.models.cbr.Currency;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.bind.JsonbConfig;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
@Path("/curs")
@Produces(MediaType.APPLICATION_JSON)
public class CursOnDate
{
@GET
@Path("/ondate/{value1}")
public Response onDate(@PathParam("value1") String value1) {
try {
XMLGregorianCalendar date = ru.otus.utils.Calendar.parseStringToXMLGregorian(value1);
List<Currency> list = new GetCursOnDateXMLAdapter(date).getList();
JsonbConfig config = new JsonbConfig().withFormatting(true);
Jsonb jsonb = JsonbBuilder.create(config);
String result = jsonb.toJson(list);
return Response.status(200).type(MediaType.APPLICATION_JSON_TYPE).entity(result).build();
}
catch (ParseException | DatatypeConfigurationException e) {
e.printStackTrace(); // TODO LOGGER
throw new WebApplicationException(
Response.status(Response.Status.BAD_REQUEST)
.entity(e.getMessage())
.type(MediaType.TEXT_PLAIN)
.build()
);
}
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
package DPI.service;
import java.util.List;
import DPI.entity.Doctor;
public interface DoctorService {
List<Doctor> loadAllDoctor();
Doctor loadDoctorById(int id);
}
|
package JZOF;
/**
* Created by yang on 2017/3/15.
*/
/*
请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
*/
public class RelaceBlank {
public String replaceSpace(StringBuffer str) {
if(str==null){
return null;
}
int numOfBlank = 0;
int originLength = str.length();
for(int i =0;i<originLength;i++){
if(str.charAt(i)==' '){
numOfBlank++;
}
}
int lenghth = str.length()+2*numOfBlank;
for (int i = originLength;i<lenghth;i++){
str.append('0');
}
for(int i=originLength,j=lenghth;i>0&&j>0;i--,j--){
if(str.charAt(i-1)!=' ') {
char temp = str.charAt(i-1);
str.setCharAt(j-1,temp );
}
else{
str.setCharAt(j-1,'0');
j--;
str.setCharAt(j-1,'2');
j--;
str.setCharAt(j-1,'%');
}
}
return str.toString();
}
public static void main(String[] args) {
RelaceBlank a = new RelaceBlank();
StringBuffer sb = new StringBuffer("I am a student");
String b = a.replaceSpace(sb);
System.out.println(b);
}
}
|
package com.zlzkj.app.model.form;
import com.zlzkj.app.model.cargo.Cargo;
import java.util.List;
public class BindingForm {
private String description;
private List<Cargo> cargos;
public List<Cargo> getCargos() {
return cargos;
}
public void setCargos(List<Cargo> cargos) {
this.cargos = cargos;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
package com.nikogalla.tripbook.models;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.firebase.database.Exclude;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Nicola on 2017-01-27.
*/
public class Comment implements Parcelable {
public static final String COMMENTS_TABLE_NAME = "comments";
public String key;
public String createdAt;
public String text;
public String userId;
public String userName;
public String userPictureUrl;
private Comment(Parcel in) {
createdAt = in.readString();
text = in.readString();
userId = in.readString();
userName = in.readString();
userPictureUrl = in.readString();
}
public Comment() {
}
public static final Parcelable.Creator<Comment> CREATOR
= new Parcelable.Creator<Comment>() {
public Comment createFromParcel(Parcel in) {
return new Comment(in);
}
public Comment[] newArray(int size) {
return new Comment[size];
}
};
public Comment(String createdAt, String text, String userId, String userName, String userPictureUrl) {
this.createdAt = createdAt;
this.text = text;
this.userId = userId;
this.userName = userName;
this.userPictureUrl = userPictureUrl;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(createdAt);
out.writeString(text);
out.writeString(userId);
out.writeString(userName);
out.writeString(userPictureUrl);
}
@Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("createdAt", createdAt);
result.put("text", text);
result.put("userId", userId);
result.put("userName", userName);
result.put("userPictureUrl", userPictureUrl);
return result;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
|
package Praktikum;
/**
*
* @author Master
*/
public class Main {
public static void main(String[] args) {
Pegawai pegawai = new Pegawai("12345", "Syaifuddin", "Pasuruan");
Dosen dosen = new Dosen("18123", "Zuhri", "Malang");
dosen.setSKS(6);
DaftarGaji daftarGaji = new DaftarGaji(2);
daftarGaji.addPegawai(pegawai);
daftarGaji.addPegawai(dosen);
daftarGaji.printSemuaGaji();
}
}
|
package org.browsexml.timesheetjob.web;
import java.beans.PropertyEditorSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.browsexml.timesheetjob.model.Awards;
import org.browsexml.timesheetjob.service.AwardManager;
public class AwardsPropertyEditor extends PropertyEditorSupport {
private static Log log = LogFactory.getLog(AwardsPropertyEditor.class);
private AwardManager awardMgr = null;
public AwardsPropertyEditor() throws Exception {
}
public AwardsPropertyEditor(AwardManager awardMgr) {
this.awardMgr = awardMgr;
}
public void setAsText(String text) {
log.debug("set value: " + text);
Awards x = awardMgr.getAwards(text);
setValue(x);
}
public String getAsText() {
Awards value = (Awards) getValue();
if (value == null) {
log.debug("get value: " + "NULL");
return "";
}
log.debug("get value: (department) '" + value.getAwardCode() + "' ");
return value.getAwardCode();
}
}
|
import java.util.Scanner;
public class javaTutorial3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int height;
int age;
System.out.println("How toll are you in inches?");
height=in.nextInt();
System.out.println("What in your age i years?");
age=in.nextInt();
if ((height >= 52)&&(age >= 9))
System.out.println("You can ride!");
else
System.out.println("You can't ride!");
in.close();
}
}
|
package com.s24.redjob.worker.json;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.s24.redjob.worker.Execution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.GenericTypeResolver;
import javax.annotation.PostConstruct;
import java.util.List;
/**
* Jackson module with all serializers needed for {@link Execution} and containing classes.
*/
public class ExecutionModule extends SimpleModule {
/**
* All serializer beans.
*/
@Autowired
private List<JsonSerializer<?>> serializers;
/**
* All deserializer beans.
*/
@Autowired
private List<JsonDeserializer<?>> deserializers;
/**
* Constructor.
*/
public ExecutionModule() {
super("Execution module");
}
/**
* Register all serializer and deserializer of this package.
*/
@PostConstruct
public void afterPropertiesSet() {
addAllOf(ExecutionModule.class.getPackage());
}
/**
* Add all {@link JsonSerializer} and {@link JsonDeserializer} beans of the given package.
*/
protected void addAllOf(Package p) {
serializers.stream()
.filter(serializer -> serializer.getClass().getPackage().equals(p))
.forEach(this::addTypedSerializer);
deserializers.stream()
.filter(deserializer -> deserializer.getClass().getPackage().equals(p))
.forEach(this::addTypedDeserializer);
}
/**
* Extract type from serializer and register it.
*/
@SuppressWarnings("unchecked")
protected <T> void addTypedSerializer(JsonSerializer<T> serializer) {
addSerializer(
(Class<? extends T>) GenericTypeResolver.resolveTypeArgument(serializer.getClass(), JsonSerializer.class),
serializer);
}
/**
* Extract type from deserializer and register it.
*/
@SuppressWarnings("unchecked")
protected <T> void addTypedDeserializer(JsonDeserializer<? extends T> deserializer) {
addDeserializer(
(Class<T>) GenericTypeResolver.resolveTypeArgument(deserializer.getClass(), JsonDeserializer.class),
deserializer);
}
}
|
package com.top.demo.component;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.top.demo.common.response.CommonCode;
import com.top.demo.exception.ExceptionCast;
import com.top.demo.modules.pojo.UserDO;
import com.top.demo.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 登陆检查,
*/
@Configuration
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 获取token
String token = request.getHeader("Authorization");
if(!StringUtils.isEmpty(token)) {
// 不为空,说明不是登录,就判断是否挤下线
UserDO loginUser = ShiroUtils.getLoginUser();
if(loginUser == null) {
// 未登录,放行
return true;
}
String username = loginUser.getuUserName();
// 获取redis中的token
String redisToken = redisTemplate.opsForValue().get(username) + "";
if(!token.equals(redisToken)) {
// 不相同,说明有人在别处登录,挤下线
ExceptionCast.cast(CommonCode.LOGOUT);
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
|
package com.example.carparkapplication.controller;
import com.example.carparkapplication.repository.CarRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.Assert;
import java.util.Arrays;
import java.util.List;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@SpringBootTest
public class CarParkControllerTest {
@InjectMocks
CarParkController carParkController;
@Mock
CarRepository carRepository;
@BeforeEach
void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@AfterEach
void tearDown() throws Exception {
}
@Test
final void testGetSlotNumberByRegistrationNumber() {
String registration_number = "KA-HH-9999";
int slot_number_allocated = 3;
when(carRepository.getSlotNumberByRegistrationNumber(anyString())).thenReturn(slot_number_allocated);
int slot_number = carParkController.getSlotNumberForRegistrationNumber(registration_number);
Assert.isTrue(slot_number == slot_number_allocated, "getSlotNumberForRegistrationNumber returns a slotnumber");
Assert.notNull(slot_number, "slot_number returned is not null");
}
@Test
final void testGetSlotNumberIfRegistrationNumberDoesNotExist() {
String registration_number = "KA-HH-9999";
int slot_number_allocated = 0;
when(carRepository.getSlotNumberByRegistrationNumber(anyString())).thenReturn(0);
int slot_number = carParkController.getSlotNumberForRegistrationNumber(registration_number);
Assert.isTrue(slot_number == slot_number_allocated, "getSlotNumberForRegistrationNumber returns 0 when supplied a slot number that does not exist");
Assert.notNull(slot_number, "slot_number returned is not null");
}
@Test
public void testGetSlotNumbersForCarWithColour() {
String colour = "White";
String slot_number = "1, 2";
List<String> empty_list = Arrays.asList(new String[]{"1", "2"});
when(carRepository.findSlotNumbersByColour(anyString())).thenReturn(empty_list);
String message = carParkController.getSlotNumbersForCarWithColour(colour);
Assert.isTrue(message.equals(slot_number), "getSlotNumbersForCarWithColour returns slot_numbers");
Assert.notNull(message, "slot_numbers returned are not null");
}
@Test
public void testGetSlotNumbersForCarWithColourThatDoesNotExist() {
String colour = "Green";
String slot_number = "Not Found";
List<String> empty_list = Arrays.asList(new String[]{"Not Found"});
when(carRepository.findSlotNumbersByColour(anyString())).thenReturn(empty_list);
String message = carParkController.getSlotNumbersForCarWithColour(colour);
Assert.isTrue(message.equals(slot_number), "getSlotNumbersForCarWithColour returns Not Found");
Assert.notNull(message, "slot_numbers returned are not null");
}
@Test
final void testGetRegistrationNumberForCarWithColour() {
String colour = "Blue";
int slot_number_allocated = 0;
when(carRepository.getSlotNumberByRegistrationNumber(anyString())).thenReturn(0);
int slot_number = carParkController.getSlotNumberForRegistrationNumber(colour);
Assert.isTrue(slot_number == slot_number_allocated, "getSlotNumberForRegistrationNumber returns 0 when supplied a slot number that does not exist");
Assert.notNull(slot_number, "slot_number returned is not null");
}
@Test
public void testGetRegistrationNumberForCarWithColourThatDoesNotExist() {
String colour = "asdfasdf";
String slot_number = "1, 2";
List<String> empty_list = Arrays.asList(new String[]{"1", "2"});
when(carRepository.findSlotNumbersByColour(anyString())).thenReturn(empty_list);
String message = carParkController.getSlotNumbersForCarWithColour(colour);
Assert.isTrue(message.equals(slot_number), "getSlotNumbersForCarWithColour returns slot_numbers");
Assert.notNull(message, "slot_numbers returned are not null");
}
}
|
package cn.org.cerambycidae.service;
import cn.org.cerambycidae.pojo.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/*
* ExampleService主要封装对数据库表的基本操作<操作对象,对象主键,对象Example>
*/
public interface ExampleService<T, K, O> {
/* 数据增加 */
//添加一个数据库记录
int insert(T example);
//异步添加一个数据库记录
int insertSelective(T example);
/* 数据修改 */
//异步更新数据
int updateByExampleSelective(@Param("example") T example, @Param("eexample") O eexample);
//更新数据
int updateByExample(@Param("example") T example, @Param("eexample") O eexample);
//按照主键异步更新数据
int updateByPrimaryKeySelective(T example);
//按照主键更新数据
int updateByPrimaryKey(T example);
/* 数据查询 */
//删除数据集
int deleteByExample(O eexample);
//通过主键删除数据
int deleteByPrimaryKey(K id);
/* 数据删除 */
//查询数据
List<T> selectByExample(O eexample);
//通过主键查询数据
T selectByPrimaryKey(K id);
/* 统计数据 */
long countByExample(O eexample);
}
|
package com.tencent.mm.plugin.appbrand.compat;
import android.view.View;
import com.tencent.mapsdk.raster.model.LatLng;
import com.tencent.mapsdk.raster.model.Marker;
import com.tencent.mm.plugin.appbrand.compat.a.b.f;
import com.tencent.mm.plugin.appbrand.compat.a.b.h;
final class g extends m<Marker> implements h {
final Marker foD;
g(Marker marker) {
super(marker);
this.foD = marker;
}
public final boolean isInfoWindowShown() {
return this.foD != null && this.foD.isInfoWindowShown();
}
public final void showInfoWindow() {
if (this.foD != null) {
this.foD.showInfoWindow();
}
}
public final void hideInfoWindow() {
if (this.foD != null) {
this.foD.hideInfoWindow();
}
}
public final f adI() {
return this.foD == null ? new 1(this) : new f(this.foD.getPosition());
}
public final void b(f fVar) {
if (this.foD == null) {
return;
}
if (fVar instanceof f) {
this.foD.setPosition(((f) fVar).foC);
} else {
this.foD.setPosition(new LatLng(fVar.adG(), fVar.adH()));
}
}
public final float getRotation() {
return this.foD == null ? 0.0f : this.foD.getRotation();
}
public final void setRotation(float f) {
if (this.foD != null) {
this.foD.setRotation(f);
}
}
public final Object getTag() {
return this.foD == null ? null : this.foD.getTag();
}
public final View getMarkerView() {
return this.foD == null ? null : this.foD.getMarkerView();
}
public final void set2Top() {
if (this.foD != null) {
this.foD.set2Top();
}
}
}
|
package com.mundo.core.support;
/**
* Constant
*
* @author maodh
* @since 27/05/2018
*/
public interface Constant {
interface Arrays {
boolean[] BOOLEANS = new boolean[0];
char[] CHARS = new char[0];
byte[] BYTES = new byte[0];
short[] SHORTS = new short[0];
int[] INTS = new int[0];
long[] LONGS = new long[0];
float[] FLOATS = new float[0];
double[] DOUBLES = new double[0];
Object[] OBJECTS = new Object[0];
String[] STRINGS = new String[0];
}
interface Strings {
String EMPTY = "";
String SPACE = " ";
String COMMA = ",";
String LT = "<";
String GT = ">";
}
}
|
package mips;
public class Procedure {
public String name;
public int param1;
public int param2;
public int param3;
public Procedure(String name, int param1, int param2, int param3)
throws Exception {
this.name = name;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
}
// If the procedure has <=4 parameters, then it returns zero.
// Else it returns the number of parameters minus four.
//
private int getSpilledArgsNum() {
return (param1>4 ? param1-4 : 0)*4;
}
// Returns the number of words needed in stack for this procedure
//
public int getStackMove() {
return (param2 + 1)*4 - getSpilledArgsNum();
}
}
|
package com.kingbbode.bot.common.base.api;
import com.kingbbode.bot.common.enums.BrainResponseType;
/**
* Created by YG on 2017-01-26.
*/
public interface ApiData {
BrainResponseType response();
}
|
package br.udesc.model.entidade;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
/**
* Entidade Disciplina
* @author PIN2
*/
@Entity
@SequenceGenerator(name = "disciplina_id", initialValue = 1, allocationSize = 1)
public class Disciplina implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "disciplina_id")
@Column(name = "id_disciplina")
private Long id;
@Column(name = "nome_disciplina")
private String nome;
@Column(name = "codigo_disciplina")
private String codigo;
@Column(name = "creditos_disciplina")
private int creditos;
@Column(name = "fase_disciplina")
private String fase;
@Column(name = "qtdAlunos_disciplina")
private int qtdAlunos;
@OneToMany(mappedBy = "disciplina")
private List<RestricaoDisciplina> listaRestricaoDisciplina;
@ManyToOne
@JoinColumn(name = "id_curso")
private Curso curso;
@OneToMany(mappedBy = "disciplina")
private List<SalaHorario> listaSalaHorario;
@ManyToOne
@JoinColumn(name = "id_professor", nullable = true)
private Professor professor;
@ManyToOne
@JoinColumn(name = "id_sala", nullable = true)
private Sala sala;
public Disciplina() {
listaRestricaoDisciplina = new ArrayList<>();
listaSalaHorario = new ArrayList<>();
}
public Disciplina(String nome, String codigo, int creditos, String fase, int qtdAlunos, Curso curso, Professor professor, Sala sala) {
this.nome = nome;
this.codigo = codigo;
this.creditos = creditos;
this.fase = fase;
this.qtdAlunos = qtdAlunos;
this.curso = curso;
this.professor = professor;
this.sala = sala;
listaRestricaoDisciplina = new ArrayList<>();
listaSalaHorario = new ArrayList<>();
}
public void addListaRestricao(RestricaoDisciplina rd){
listaRestricaoDisciplina.add(rd);
}
public void setListaRestricaoDisciplina(List<RestricaoDisciplina> listaRestricaoDisciplina) {
this.listaRestricaoDisciplina = listaRestricaoDisciplina;
}
public Sala getSala() {
return sala;
}
public void setSala(Sala sala) {
this.sala = sala;
}
public List<RestricaoDisciplina> getListaRestricaoDisciplina() {
return listaRestricaoDisciplina;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public Professor getProfessor() {
return professor;
}
public void setProfessor(Professor professor) {
this.professor = professor;
}
public List<SalaHorario> getListaSalaHorario() {
return listaSalaHorario;
}
public void setListaSalaHorario(List<SalaHorario> listaSalaHorario) {
this.listaSalaHorario = listaSalaHorario;
}
public Curso getCurso() {
return curso;
}
public void setCurso(Curso curso) {
this.curso = curso;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getCreditos() {
return creditos;
}
public void setCreditos(int creditos) {
this.creditos = creditos;
}
public String getFase() {
return fase;
}
public void setFase(String fase) {
this.fase = fase;
}
public int getQtdAlunos() {
return qtdAlunos;
}
public void setQtdAlunos(int qtdAlunos) {
this.qtdAlunos = qtdAlunos;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Disciplina)) {
return false;
}
Disciplina other = (Disciplina) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Disciplina: " + nome
+ "\nCurso: " + curso.getNome()
+ "\nCódigo: " + codigo
+ "\nProfessor: " + professor
+ "\nCreditos: " + creditos
+ "\nFase:" + fase
+ "\nQuantidade Máxima de Alunos: " + qtdAlunos
+ "\nLista de Horários: " + listaSalaHorario.size();
}
}
|
package test;
/**
* @author yinyiyun
* @date 2018/7/6 10:42
*/
public interface TestInterface2 {
void test0();
void test1();
default void test2() {
System.out.println("测试接口默认实现2");
}
static void test3() {
System.out.println("测试接口静态方法2");
}
}
|
package com.udogan.magazayonetimi.utils.dao.ui;
import com.udogan.magazayonetimi.models.Kullanici;
import com.udogan.magazayonetimi.utils.dao.DbServicessBase;
public class KullaniciDAO extends DbServicessBase<Kullanici> {
}
|
package com.pgssoft.httpclient;
import java.net.URI;
import java.net.http.HttpRequest;
import static java.net.http.HttpRequest.BodyPublishers.noBody;
import static java.net.http.HttpRequest.newBuilder;
class TestRequests {
static public HttpRequest post(String url) {
return newBuilder(URI.create(url)).POST(noBody()).build();
}
static public HttpRequest get(String url) {
return newBuilder(URI.create(url)).GET().build();
}
}
|
package com.itheima.core.service;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.core.OrderService;
import com.itheima.core.dao.item.ItemDao;
import com.itheima.core.dao.log.PayLogDao;
import com.itheima.core.dao.order.OrderDao;
import com.itheima.core.dao.order.OrderItemDao;
import com.itheima.core.pojo.Cart;
import com.itheima.core.pojo.item.Item;
import com.itheima.core.pojo.log.PayLog;
import com.itheima.core.pojo.order.Order;
import com.itheima.core.pojo.order.OrderItem;
import com.itheima.core.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderDao orderDao;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private ItemDao itemDao;
@Autowired
private OrderItemDao orderItemDao;
@Autowired
private PayLogDao payLogDao;
@Autowired
private IdWorker idWorker;
@Override
public void add(Order order) {
double totalPay = 0;
List<String> ids = new ArrayList<>();
List<Cart> cartList = (List<Cart>) redisTemplate.boundHashOps("CART").get(order.getUserId());
for (Cart cart : cartList) {
double totalPrice = 0;
// 封装order
order.setSellerId(cart.getSellerId());
long id = idWorker.nextId();
ids.add(String.valueOf(id));
order.setOrderId(id);
order.setCreateTime(new Date());
order.setUpdateTime(new Date());
order.setPaymentType("1");
order.setStatus("1");
order.setSourceType("2");
List<OrderItem> orderItemList = cart.getOrderItemList();
for (OrderItem orderItem : orderItemList) {
// 接下来封装orderItem,并保存到数据库表中
orderItem.setId(idWorker.nextId());
orderItem.setOrderId(order.getOrderId());
Item item = itemDao.selectByPrimaryKey(orderItem.getItemId());
orderItem.setGoodsId(item.getGoodsId());
orderItem.setTitle(item.getTitle());
orderItem.setPrice(item.getPrice());
orderItem.setTotalFee(new BigDecimal(item.getPrice().doubleValue()*orderItem.getNum()));
orderItem.setSellerId(order.getSellerId());
orderItem.setPicPath(orderItem.getPicPath());
totalPrice +=orderItem.getTotalFee().doubleValue();
orderItemDao.insertSelective(orderItem);
}
order.setPayment(new BigDecimal(totalPrice));
totalPay += totalPrice;
orderDao.insertSelective(order);
}
// 删除缓存中的相应的订单
redisTemplate.boundHashOps("CART").delete(order.getUserId());
// 将两张订单合并, 并生成银行流水, 支付日志表
PayLog payLog = new PayLog();
payLog.setCreateTime(new Date());
payLog.setUserId(order.getUserId());
payLog.setTradeState("0");
payLog.setTotalFee((long)totalPay*100);
payLog.setOutTradeNo(String.valueOf(order.getOrderId()));
// 订单集合, 比较特别
payLog.setOrderList(ids.toString().replace("[","").replace("]",""));
payLogDao.insertSelective(payLog);
redisTemplate.boundHashOps("payLog").put(order.getUserId(),payLog); // 最后一步放在缓存中
}
}
|
package com.ygrik.currencyrate.app.mvp.presenter.abstractPresenters;
import com.ygrik.currencyrate.app.mvp.view.CurrencyRateView;
import com.ygrik.currencyrate.app.network.models.CurrencyRate;
public abstract class CurrencyRatePresenter extends Presenter<CurrencyRateView>{
abstract public void onCurrencyReceived(CurrencyRate currencyRate);
}
|
package com.facebook.react.modules.network;
import g.f;
import g.h;
import g.l;
import g.q;
import g.z;
import java.io.IOException;
import okhttp3.af;
import okhttp3.w;
public class ProgressResponseBody extends af {
private h mBufferedSource;
public final ProgressListener mProgressListener;
public final af mResponseBody;
public long mTotalBytesRead;
public ProgressResponseBody(af paramaf, ProgressListener paramProgressListener) {
this.mResponseBody = paramaf;
this.mProgressListener = paramProgressListener;
}
private z source(z paramz) {
return (z)new l(paramz) {
public long read(f param1f, long param1Long) throws IOException {
boolean bool;
long l1 = super.read(param1f, param1Long);
ProgressResponseBody progressResponseBody = ProgressResponseBody.this;
long l2 = progressResponseBody.mTotalBytesRead;
if (l1 != -1L) {
param1Long = l1;
} else {
param1Long = 0L;
}
progressResponseBody.mTotalBytesRead = l2 + param1Long;
ProgressListener progressListener = ProgressResponseBody.this.mProgressListener;
param1Long = ProgressResponseBody.this.mTotalBytesRead;
l2 = ProgressResponseBody.this.mResponseBody.contentLength();
if (l1 == -1L) {
bool = true;
} else {
bool = false;
}
progressListener.onProgress(param1Long, l2, bool);
return l1;
}
};
}
public long contentLength() {
return this.mResponseBody.contentLength();
}
public w contentType() {
return this.mResponseBody.contentType();
}
public h source() {
if (this.mBufferedSource == null)
this.mBufferedSource = q.a(source((z)this.mResponseBody.source()));
return this.mBufferedSource;
}
public long totalBytesRead() {
return this.mTotalBytesRead;
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\modules\network\ProgressResponseBody.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.assignment3.question1;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestCalculator {
@Test
public void UTC01_01() {
int expected = 15;
int actual = Calculator.add(10, 5);
assertEquals(expected,actual,0);
}
@Test
public void UTC01_02() {
int expected = 25;
int actual = Calculator.subtract(50, 25);
assertEquals(expected,actual,0);
}
@Test
public void UTC01_03() {
int expected = 196;
int actual = Calculator.multiply(28, 7);
assertEquals(expected,actual,0);
}
@Test
public void UTC01_04() {
int expected = 9;
double actual = Calculator.divide(45, 5);
assertEquals(expected,actual,0);
}
@Test(expected = ArithmeticException.class)
public void UTC01_05() {
Calculator.divide(45, 0);
}
}
|
package opmap.model.application;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import opmap.model.application.OPRole;
import opmap.model.architecture.EXNode;
public class OPNode implements Comparable<OPNode>, Serializable {
private static final long serialVersionUID = -8266724889784176862L;
private int id;
private OPRole role;
private String name;
private Function<Double, Double> transformation;
private int resources;
private double speed;
private double flowIn;
private double flowOut;
private Set<Integer> pinnables;
private boolean alwaysPinnable;
public OPNode(final int id, final OPRole role, final String name, final Function<Double, Double> transformation,
final int resources, final double speed) {
this.setId(id);
this.setRole(role);
this.setName(name);
this.setTransformation(transformation);
this.setResources(resources);
this.setSpeed(speed);
this.setPinnables(new HashSet<Integer>());
this.setAlwaysPinnable(true);
if (this.isSource())
this.setFlowOut(this.getTransformation().apply(0.0));
else if (this.isSink())
this.setFlowOut(0);
}
public int getId() {
return this.id;
}
private void setId(final int id) {
this.id = id;
}
public OPRole getRole() {
return this.role;
}
private void setRole(final OPRole role) {
this.role = role;
}
public String getName() {
return this.name;
}
private void setName(final String name) {
this.name = name;
}
public Function<Double, Double> getTransformation() {
return this.transformation;
}
private void setTransformation(final Function<Double, Double> transformation) {
this.transformation = transformation;
}
public int getResources() {
return this.resources;
}
public void setResources(final int resources) {
this.resources = resources;
}
public double getSpeed() {
return this.speed;
}
public void setSpeed(final double speed) {
this.speed = speed;
}
public double getFlowIn() {
return this.flowIn;
}
public void setFlowIn(final double flowIn) {
this.flowIn = flowIn;
this.flowOut = this.transformation.apply(this.flowIn);
}
public double getFlowOut() {
return this.flowOut;
}
public void setFlowOut(final double flowOut) {
this.flowOut = flowOut;
}
public Set<Integer> getPinnables() {
return this.pinnables;
}
public void setPinnables(final Set<Integer> pinnables) {
this.pinnables = pinnables;
}
public boolean addPinnable(final int exnodeid) {
this.alwaysPinnable = false;
return this.pinnables.add(exnodeid);
}
public boolean addPinnable(final EXNode exnode) {
return this.addPinnable(exnode.getId());
}
public void setAlwaysPinnable(final boolean alwaysPinnable) {
this.alwaysPinnable = alwaysPinnable;
}
public boolean isSource() {
return this.getRole().equals(OPRole.SRC);
}
public boolean isSink() {
return this.getRole().equals(OPRole.SNK);
}
public boolean isPipe() {
return this.getRole().equals(OPRole.PIP);
}
public boolean isAlwaysPinnable() {
return this.alwaysPinnable;
}
public void addFlowIn(final double flow) {
this.setFlowIn(this.getFlowIn() + flow);
}
public boolean isPinnableOn(final EXNode exnode) {
if (this.isAlwaysPinnable())
return true;
else
return this.pinnables.contains(exnode.getId());
}
@Override
public boolean equals(Object obj) {
if (this.getClass() != obj.getClass())
return false;
OPNode other = (OPNode) obj;
return (this.getId() == other.getId());
}
@Override
public int compareTo(OPNode other) {
return Integer.valueOf(this.getId()).compareTo(other.getId());
}
public String toPrettyString() {
String str = String.format("#opnode# id:%d|opr:%s|role:%s|resources:%d|speed:%.5f:fIn:%.5f|fOut:%.5f|pinnables:%s",
this.getId(),
this.getName(),
this.getRole(),
this.getResources(),
this.getSpeed(),
this.getFlowIn(),
this.getFlowOut(),
this.isAlwaysPinnable()?"every":this.getPinnables());
return str;
}
@Override
public String toString() {
String str = String.format("OPNode(id:%d|opr:%s|role:%s|resources:%d|speed:%f:fIn:%f|fOut:%f|pinnables:%s)",
this.getId(),
this.getName(),
this.getRole(),
this.getResources(),
this.getSpeed(),
this.getFlowIn(),
this.getFlowOut(),
this.isAlwaysPinnable()?"every":this.getPinnables());
return str;
}
@Override
public int hashCode() {
return Objects.hash(this.getId());
}
}
|
package com.example.healthmanage.dialog;
import android.app.Dialog;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.bumptech.glide.Glide;
import com.example.healthmanage.R;
public class SelectTaskReceiverDialog extends Dialog implements View.OnClickListener {
Context context;
public String receiverName;
public String receiverAvatar;
public String taskContent;
public OnEditTextDialogClickListener getOnEditTextDialogClickListener() {
return onEditTextDialogClickListener;
}
public void setOnEditTextDialogClickListener(OnEditTextDialogClickListener onEditTextDialogClickListener) {
this.onEditTextDialogClickListener = onEditTextDialogClickListener;
}
private OnEditTextDialogClickListener onEditTextDialogClickListener;
public SelectTaskReceiverDialog(@NonNull Context context, String receiverName,
String receiverAvatar, String taskContent) {
super(context, R.style.EditTextDialogStyle);
this.context = context;
this.receiverAvatar = receiverAvatar;
this.receiverName = receiverName;
this.taskContent = taskContent;
initView();
}
public void initView() {
View view = LayoutInflater.from(context).inflate(R.layout.dialog_select_task_receiver,
null);
ImageView imageView = view.findViewById(R.id.iv_receiver_avatar);
TextView textView = view.findViewById(R.id.tv_receiver_name);
TextView textView1 = view.findViewById(R.id.tv_task_content);
Glide.with(context).load(receiverAvatar).into(imageView);
textView.setText(receiverName);
textView1.setText(taskContent);
super.setContentView(view);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_send:
onEditTextDialogClickListener.doCreate();
break;
case R.id.tv_cancel:
this.dismiss();
break;
}
}
public interface OnEditTextDialogClickListener {
void doCreate();
}
}
|
package org.starter.rxjava;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.Test;
public class Starter01 {
@Test
public void z001() throws InterruptedException, ExecutionException {
ExecutorService threadPool = Executors.newFixedThreadPool(8);
List<String> batches = new ArrayList<>();
Callable<String> t = new Callable<String>() {
@Override
public String call() throws Exception {
synchronized(batches) {
String s = "abc";
batches.add(s);
return s;
}
}
};
Future<String> f = threadPool.submit(t);
String result = f.get();
System.out.println(result);
}
}
|
package com.company;
import java.io.File;
import java.io.IOException;
import java.util.*;
// find min of 日
public class FindMinStepOfRi {
public static void main(String[] args) throws IOException {
// Scanner sc = new Scanner(System.in);
Scanner sc = new Scanner(
new File("/Users/sunyindong/workspace/TestJava/Leetcode/src/main/resources/input.txt"));
while (sc.hasNext()) {
count = -1;
queue = new LinkedList<>();
int w = sc.nextInt();
int h = sc.nextInt();
sc.nextLine();
char[][] board = new char[w][h];
int tmpW = 0;
while ( tmpW < w){
board[tmpW] = sc.nextLine().toCharArray();
tmpW++;
}
int Hx=0, Hy=0;
int Tx=-1, Ty=-1;
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if(board[i][j]=='H'){
Hx=i;
Hy=j;
continue;
}
if(board[i][j]=='T'){
Tx=i;
Ty=j;
continue;
}
if(Hx!=-1 && Tx!=-1) break;
}
}
queue.add(new int[]{Hx, Hy});
while (!queue.isEmpty()){
int sz = queue.size();
count++; // ask
while ( (sz--) > 0){
int[] point = queue.poll();
int i = point[0], j = point[1];
if(findTarget(board, i, j)){
break;
}
if(i>=1 && i<w && j>=0 && j<h && board[i-1][j]!='#') {
queue.add( new int[]{ i-2, j-1} );
queue.add(new int[] {i-2, j+1});
}
if(i<w-1 && i>=0 && j<h && j>=0 && board[i+1][j]!='#') {
queue.add( new int[]{ i+2, j-1 } );
queue.add(new int[] { i+2, j+1 });
}
if( i>=0 && i<w && j<h && j>=1 && board[i][j-1]!='#' ) {
queue.add( new int[]{ i-1, j-2 } );
queue.add(new int[] { i+1, j-2});
}
if( i>=0 && i<w && j>=0 && j<h-1 && board[i][j+1]!='#') {
queue.add( new int[]{ i+1, j+2 } );
queue.add(new int[] { i-1, j+2});
}
}
}
System.out.println(count);
}
}
public static Queue<int[]> queue;
public static int count;
public static boolean findTarget(char[][] board, int i, int j){
if(board==null || board.length==0 || board[0].length==0 || i< 0 || i>=board.length || j<0 || j>=board[0].length
|| board[i][j] == '#') { //
return false;
}
if(board[i][j]=='T'){
return true;
}
board[i][j] = '#';
return false;
}
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
}
|
package pl.finapi.paypal;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.List;
import org.apache.commons.io.IOUtils;
public class CharsetTest1 {
public static void main(String[] args) throws FileNotFoundException, IOException {
// String csvFilePath1 = "C:/Documents and Settings/maciek/Desktop/Pobierz-2012.01.csv";
// String csvFilePath2 = "src/test/resources/paypal/wrzesien-marzec2012-PL.csv";
String csvFilePath3 = "src/test/resources/paypal/Pobierz-2012.03.16.csv";
String charsetName1 = "windows-1250";
// String charsetName2 = "UTF-8";
// String charsetName3 = "windows-1252";
for (Charset charset : Charset.availableCharsets().values()) {
String headerLine = readLines(csvFilePath3, charset.name()).get(0);
if (headerLine.contains("Imię")) {
//System.out.println(headerLine);
System.out.println(charset);
}
}
// print(csvFilePath1, charsetName1);
// print(csvFilePath2, charsetName2);
print(csvFilePath3, charsetName1);
// print(csvFilePath3, charsetName2);
// print(csvFilePath3, charsetName3);
}
private static void print(String csvFilePath, String charsetName) throws FileNotFoundException, IOException {
List<String> lines = readLines(csvFilePath, charsetName);
System.out.println(lines);
}
private static List<String> readLines(String csvFilePath, String charsetName) throws FileNotFoundException, IOException {
FileInputStream in = new FileInputStream(csvFilePath);
Reader reader = new InputStreamReader(in, Charset.forName(charsetName));
List<String> lines = IOUtils.readLines(reader);
return lines;
}
}
|
package com.tt.option.f;
import android.app.Activity;
import com.tt.option.a;
import java.util.HashMap;
public final class a extends a<c> implements c {
public final void startFaceLive(Activity paramActivity, HashMap<String, String> paramHashMap, b paramb) {
if (inject()) {
((c)this.defaultOptionDepend).startFaceLive(paramActivity, paramHashMap, paramb);
return;
}
if (paramb != null)
paramb.onResult(-1, "feature not support now");
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\option\f\a.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package org.art.soft.tasks.photocollection;
import java.util.List;
public interface PhotoOrganize {
List<Photo> organize();
}
|
package org.scottrager.appfunding;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.flurry.android.FlurryAgent;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
public class ChoosePaymentOptionActivity extends Activity {
public final String TAG = "choosepaymentoption";
private DBAdapter db;
private int coupon_book_id;
private int coupon_book_cost;
private String seller_id;
static final int VALID_CASH_CODE = 1;
static final int VALID_CREDIT_CARD = 1;
ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_choose_payment_option);
Intent i = getIntent();
Bundle b = i.getExtras();
coupon_book_id = b.getInt("couponBookId");
coupon_book_cost = b.getInt("couponBookCost");
seller_id = b.getString("sellerId");
db = new DBAdapter(this);
}
@Override
public void onStart() {
Log.d(TAG, "In onStart");
super.onStart();
FlurryAgent.onStartSession(this, "J9WHX3VYHPRX8K756WTJ");
}
@Override
public void onStop() {
super.onStop();
FlurryAgent.onEndSession(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_choose_payment_option, menu);
return true;
}
public void onChooseCreditCardPay( View view ) {
Log.d(TAG, "chose to pay with credit card");
if( !IsConnected() )
{
DisplayNoConnectionToast();
return;
}
Intent intent = new Intent( this, EnterCreditCardInfoDialog.class );
intent.putExtra("couponBookCost", coupon_book_cost);
intent.putExtra("sellerId", seller_id);
startActivityForResult(intent, VALID_CREDIT_CARD);
}
public void onChooseCashPay( View view ) {
Log.d(TAG, "chose to pay with cash");
Log.d(TAG, "coupon book cost = "+coupon_book_cost);
Log.d(TAG, "seller id = "+seller_id);
if( !IsConnected() )
{
DisplayNoConnectionToast();
return;
}
Intent intent = new Intent( this, EnterCashCodeDialog.class );
intent.putExtra("couponBookCost", coupon_book_cost);
intent.putExtra("sellerId", seller_id);
startActivityForResult(intent, VALID_CASH_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == VALID_CASH_CODE || requestCode == VALID_CREDIT_CARD) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user entered a valid cash code
new addCoupons().execute();
}
}
}
private boolean IsConnected() {
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conMgr.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
private void DisplayNoConnectionToast() {
Toast.makeText(getApplicationContext(), "No network connection detected.\nPlease try again later.", Toast.LENGTH_LONG).show();
}
private class addCoupons extends AsyncTask<String, Integer, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
SharedPreferences prefs = getSharedPreferences( MainActivity.PREFS_FILE, 0);
String username = prefs.getString(MainActivity.USERNAME, "");
db.open();
Log.d(TAG, "Trying to get coupons for book = "+coupon_book_id+", user="+username);
try {
// need to send json object "user" to server
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost("http://166.78.251.32/gnt/get_coupons_for_book.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("couponBookId", String.valueOf(coupon_book_id)));
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedInputStream in;
if( is != null )
{
Log.d(TAG, "got input stream from urlConnection");
in = new BufferedInputStream(is);
}
else
{
Log.d(TAG, "urlConnection.getInputStream() failed");
return null;
}
Log.d(TAG, "got input stream");
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while( (current = in.read()) != -1 ) {
baf.append((byte) current);
//Log.d(TAG, "byte = "+current);
}
in.close();
Log.d(TAG, "BAF: "+baf.toString());
JSONObject json = new JSONObject(new String(baf.toByteArray(), "utf-8"));
if( json.getString("error").equals("none") )
{
JSONArray coupons = null;
try {
Log.d(TAG, "No error returned from json call");
coupons = json.getJSONArray("coupons");
// looping through All Coupons
for(int i = 0; i < coupons.length(); i++){
JSONObject c = coupons.getJSONObject(i);
Log.d(TAG, "Trying to insert coupon: event_id="+c.getInt("event_id")
+", company_id="+c.getInt("company_id")+", coupon_id="+c.getInt("coupon_id"));
// first we make sure we have the info for all of the coupons in the book
// if not, we try to fill that info into the local database from the web server
int company_id = c.getInt("company_id");
int location_id = c.getInt("location_id");
int coupon_id = c.getInt("coupon_id");
if( !db.companyInDatabase( company_id ) )
{
if( !getCompany( company_id ) )
{
Log.d(TAG, "getCompany() returned false...Error retreiving JSON");
}
}
if( !db.locationInDatabase( company_id, location_id ) )
if( !getLocation( company_id, location_id ) )
{
Log.d(TAG, "getLocation() returned false...Error retreiving JSON");
}
if( !db.couponInDatabase(coupon_id) )
if( !getCoupon( coupon_id ) )
{
Log.d(TAG, "getCoupon() returned false...Error retreiving JSON");
}
// public int insertCouponEvent( int event_id, int coupon_id )
db.insertCouponEvent( c.getInt("event_id"), c.getInt("coupon_id"));
// db.insertCouponEvent(c.getInt("event_id"), c.getString("coupon_name"), c.getString("coupon_details"),
// c.getString("exp_date"), c.getString("file_url"), 40.780, -77.855);
}
db.close();
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
else
{
Log.d(TAG, "JSON request returned the following error: "+json.getString("error"));
FlurryAgent.onError("JSON_Error", json.getString("error"), "Internet_Error");
}
//String result = EntityUtils.toString(entity);
//Log.d(TAG, "Read from server:" + result);
}
else
{
Log.d(TAG, "Entity was null");
}
} catch (Throwable t) {
Log.d(TAG, "Error in the Http Request somewhere.");
t.printStackTrace();
return false;
}
goToBrowseCoupons();
return true;
}
@Override
protected void onPreExecute()
{
dialog= new ProgressDialog(ChoosePaymentOptionActivity.this);
dialog.setIndeterminate(true);
// dialog.setIndeterminateDrawable(getResources().getDrawable(R.anim.progress_dialog_anim));
dialog.setCancelable(false);
dialog.setMessage("Downloading Coupons...");
dialog.show();
}
@Override
protected void onPostExecute( Boolean result )
{
dialog.dismiss();
if( !result )
{
Toast.makeText(getApplicationContext(), "An unknown error has occurred.\nPlease try again.", Toast.LENGTH_LONG).show();
}
}
}
private void goToBrowseCoupons() {
Intent intent = new Intent( this, BrowseCouponsActivity.class );
startActivity(intent);
this.setResult(RESULT_OK);
finish();
}
private boolean getCoupon( int coupon_id )
{
//TODO::Need to make sure arguments are safe
Log.d(TAG, "Trying to get coupon with id = "+coupon_id);
try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost("http://166.78.251.32/gnt/get_coupon_with_id.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("couponId", String.valueOf(coupon_id)));
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedInputStream in;
if( is != null )
{
Log.d(TAG, "got input stream from urlConnection");
in = new BufferedInputStream(is);
}
else
{
Log.d(TAG, "urlConnection.getInputStream() failed");
return false;
}
Log.d(TAG, "got input stream");
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while( (current = in.read()) != -1 ) {
baf.append((byte) current);
//Log.d(TAG, "byte = "+current);
}
in.close();
Log.d(TAG, "BAF: "+baf.toString());
JSONObject json = new JSONObject(new String(baf.toByteArray(), "utf-8"));
if( json.getString("error").equals("none") )
{
try {
Log.d(TAG, "No error returned from json call");
db.insertCoupon( coupon_id, json.getInt("company_id"), json.getString("coupon_details"), json.getString("exp_date"), json.getInt("favorite"));
// db.close();
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
else
{
Log.d(TAG, "JSON request returned the following error: "+json.getString("error"));
}
//String result = EntityUtils.toString(entity);
//Log.d(TAG, "Read from server:" + result);
}
else
{
Log.d(TAG, "Entity was null");
}
} catch (Throwable t) {
Log.d(TAG, "Error in the Http Request somewhere.");
t.printStackTrace();
return false;
}
return true;
}
private boolean getCompany( int company_id )
{
//TODO::Need to make sure arguments are safe
Log.d(TAG, "Trying to get company with id = "+company_id);
try {
// need to send json object "user" to server
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost("http://166.78.251.32/gnt/get_company_with_id.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("companyId", String.valueOf(company_id)));
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedInputStream in;
if( is != null )
{
Log.d(TAG, "got input stream from urlConnection");
in = new BufferedInputStream(is);
}
else
{
Log.d(TAG, "urlConnection.getInputStream() failed");
return false;
}
Log.d(TAG, "got input stream");
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while( (current = in.read()) != -1 ) {
baf.append((byte) current);
//Log.d(TAG, "byte = "+current);
}
in.close();
Log.d(TAG, "BAF: "+baf.toString());
JSONObject json = new JSONObject(new String(baf.toByteArray(), "utf-8"));
if( json.getString("error").equals("none") )
{
try {
Log.d(TAG, "Trying to insert company: company_id="+company_id+
"company_name="+json.getString("company_name") );
// public int insertCompany( int company_id, String company_name, String file_url)
db.insertCompany( company_id, json.getString("company_name"), json.getString("file_url"));
// db.close();
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
else
{
Log.d(TAG, "JSON request returned the following error: "+json.getString("error"));
}
//String result = EntityUtils.toString(entity);
//Log.d(TAG, "Read from server:" + result);
}
else
{
Log.d(TAG, "Entity was null");
}
} catch (Throwable t) {
Log.d(TAG, "Error in the Http Request somewhere.");
t.printStackTrace();
return false;
}
return true;
}
private boolean getLocation( int company_id, int location_id )
{
//TODO::Need to make sure arguments are safe
Log.d(TAG, "Trying to get location with id = "+location_id);
try {
// need to send json object "user" to server
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost("http://166.78.251.32/gnt/get_location_with_id.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("companyId", String.valueOf(company_id)));
nameValuePairs.add(new BasicNameValuePair("locationId", String.valueOf(location_id)));
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedInputStream in;
if( is != null )
{
Log.d(TAG, "got input stream from urlConnection");
in = new BufferedInputStream(is);
}
else
{
Log.d(TAG, "urlConnection.getInputStream() failed");
return false;
}
Log.d(TAG, "got input stream");
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while( (current = in.read()) != -1 ) {
baf.append((byte) current);
//Log.d(TAG, "byte = "+current);
}
in.close();
Log.d(TAG, "BAF: "+baf.toString());
JSONObject json = new JSONObject(new String(baf.toByteArray(), "utf-8"));
if( json.getString("error").equals("none") )
{
try {
Log.d(TAG, "Trying to insert location: location_id="+location_id );
//public int insertLocation( int company_id, int location_id, String addr_line_1,
// String addr_line_2, double latitude, double longitude )
if( db.insertLocation( company_id, location_id, json.getString("addr_line_1"),
json.getString("addr_line_2"), json.getDouble("latitude"), json.getDouble("longitude") ) == -1 )
{
Log.d(TAG, "Error inserting location into database.");
}
// db.close();
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
else
{
Log.d(TAG, "JSON request returned the following error: "+json.getString("error"));
}
//String result = EntityUtils.toString(entity);
//Log.d(TAG, "Read from server:" + result);
}
else
{
Log.d(TAG, "Entity was null");
}
} catch (Throwable t) {
Log.d(TAG, "Error in the Http Request somewhere.");
t.printStackTrace();
return false;
}
return true;
}
}
|
public class Solution {
public boolean exist(char[][] board, String word) {
if(board.length == 0 || board[0].length == 0)
return false;
char[] wordSplit = word.toCharArray();
int m = board.length;
int n = board[0].length;
boolean visited[][] = new boolean[m][n];
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[i].length; j++){
visited[i][j] = false;
}
}
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(searchDFS(board, wordSplit, 0, i, j, visited))
return true;
}
}
return false;
}
public boolean searchDFS(char[][] board, char[] wordSplit, int idx, int i, int j, boolean[][] visited){
if(idx == wordSplit.length)
return true;
if(i < 0 || j < 0 || i >= board.length || j >= board[i].length || visited[i][j] || board[i][j] != wordSplit[idx])
return false;
visited[i][j] = true;
boolean res = searchDFS(board, wordSplit, idx + 1, i + 1, j, visited)
|| searchDFS(board, wordSplit, idx + 1, i, j + 1, visited)
||searchDFS(board, wordSplit, idx + 1, i - 1, j, visited)
||searchDFS(board, wordSplit, idx + 1, i, j - 1, visited);
visited[i][j] = false;
return res;
}
}
|
package com.project.cm.repository;
import com.project.cm.CmApplicationTests;
import com.project.cm.model.entity.Category;
import com.project.cm.model.entity.Item;
import com.project.cm.model.entity.User;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringRunner;
import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.Optional;
public class UserRepositoryTest extends CmApplicationTests {
@Autowired
private UserRepository userRepository;
@Test
public void create() {
String account = "Test5";
String password = "Test5";
String status = "Res";
String email = "Test@com";
String phoneNumber = "010-3333-3333";
LocalDateTime registeredAt = LocalDateTime.now();
LocalDateTime createdAt = LocalDateTime.now();
String createdBy = "Admin";
User user = new User();
user.setAccount(account);
user.setPassword(password);
user.setStatus(status);
user.setEmail(email);
user.setPhoneNumber(phoneNumber);
user.setRegisteredAt(registeredAt);
User u = User.builder().account(account).password(password).status(status).email(email).build();
User newUser = userRepository.save(user);
Assert.assertNotNull(newUser);
}
@Test
@Transactional
public void read() {
User user = userRepository.findFirstByPhoneNumberOrderByIdDesc("010-3333-2222");
if(user != null){
user.setEmail("a").setPhoneNumber("a").setStatus("a");
user.getOrderGroupList().stream().forEach(orderGroup -> {
System.out.println("---------------------주문");
System.out.println(orderGroup.getTotalPrice());
System.out.println(orderGroup.getTotalQuantity());
System.out.println(orderGroup.getRevName());
System.out.println("---------------------상세");
orderGroup.getOrderDetailList().forEach(orderDetail -> {
System.out.println("파트너사 이름 : " + orderDetail.getItem().getPartner().getName());
System.out.println("카테고리 : " + orderDetail.getItem().getPartner().getCategory().getTitle());
System.out.println("주문상태 : " + orderDetail.getStatus());
System.out.println("주문도착 : " + orderDetail.getArrivalDate());
System.out.println(orderDetail.getItem().getName());
System.out.println(orderDetail.getItem().getPartner().getCallCenter());
});
});
Assert.assertNotNull(user);
}
}
@Test
public void update() {
}
@Test
@Transactional
public void delete() {
}
}
|
/**
*
*/
package com.mengdo.gameframework.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @Title: CheckExist.java
* @Package com.mengdo.gameframework.annotation
* @Description:
* @Company:leiyoo
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.FIELD})
public @interface CheckExist {
Class<?> clazz();
String exclude();
}
|
package latihan;
public class HelloTelkom {
public static void main(String[] args) {
System.out.println("Hello");
System.out.println("Selamat Belajar di progam Java");
}
}
|
package com.feng.test;
import com.feng.fundation.mod.annonation.AvailableWork;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* Created by Feng
*/
@AvailableWork(name = "测试工作类",description = "日志打印测试工作工作")
public class TestWork implements Job {
private final Logger logger= LoggerFactory.getLogger(this.getClass());
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println(new Date() + "测试工作1");
}
}
|
package ru.netology.domain;
public class AttachmentsInfo {
// Video, audio, links info
}
|
package com.kh.member.model.vo;
public class Profile {
private String Id;
private String intro;
private int height;
private String blood;
private String job;
private String hobby;
private int heart;
private String religion;
private String smoke;
private String city;
public Profile() {
super();
// TODO Auto-generated constructor stub
}
public Profile(String id, String intro, int height, String blood, String job, String hobby, int heart,
String religion, String smoke, String city) {
super();
Id = id;
this.intro = intro;
this.height = height;
this.blood = blood;
this.job = job;
this.hobby = hobby;
this.heart = heart;
this.religion = religion;
this.smoke = smoke;
this.city = city;
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getBlood() {
return blood;
}
public void setBlood(String blood) {
this.blood = blood;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public int getHeart() {
return heart;
}
public void setHeart(int heart) {
this.heart = heart;
}
public String getReligion() {
return religion;
}
public void setReligion(String religion) {
this.religion = religion;
}
public String getSmoke() {
return smoke;
}
public void setSmoke(String smoke) {
this.smoke = smoke;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
|
/* Calculate and predict expenses for college student
.
Note: was able to get graph to run properly, but will not compile with the addition of the nested loop for unacceptable values,
additional dysfunctional code is blocked out as a comment*/
import java.util.Scanner;//import scanner
public class BarGraph{//public class
public static void main(String []args){//main method
Scanner myScanner = new Scanner (System.in);//define scanner
System.out.println("Expenses for Monday: ");//accept input for each day
double expenseMonday = myScanner.nextDouble();//store input as a double value
System.out.println("Expenses for Tuesday: ");
double expenseTuesday = myScanner.nextDouble();
System.out.println("Expenses for Wednesday: ");
double expenseWednesday = myScanner.nextDouble();
System.out.println("Expenses for Thursday: ");
double expenseThursday = myScanner.nextDouble();
System.out.println("Expenses for Friday: ");
double expenseFriday = myScanner.nextDouble();
System.out.println("Expenses for Saturday: ");
double expenseSaturday = myScanner.nextDouble();
System.out.println("Expenses for Sunday: ");
double expenseSunday = myScanner.nextDouble();
//nested loop for values which are not originally appropriate//
/* if (expenseSunday<0||expenseMonday<0||expenseTuesday<0||expenseWednesday<0||expenseThursday<0||expenseFriday<0||expenseSaturday<0){
Scanner myScannerRedo = new Scanner (System.in);
System.out.println("Please enter positive values for your daily expenses: ");
double expenseSundayRedo = myScannerRedo.nextDouble();
double expenseMondayRedo = myScannerRedo.nextDouble();
double expenseTuesdayRedo = myScannerRedo.nextDouble();
double expenseWednesdayRedo = myScannerRedo.nextDouble();
double expenseThursdayRedo = myScannerRedo.nextDouble();
double expenseFridayRedo = myScannerRedo.nextDouble();
double expenseSaturdayRedo = myScannerRedo.nextDouble();//Check that all value are acceptable, and if not, redo input with appropriate values
int expenseRoundMonday = (int) expenseMondayRedo;//Convert values to integers for graph
int expenseRoundTuesday = (int) expenseTuesdayRedo;//Conversion must be done explicitly as values are originally doubles
int expenseRoundWednesday = (int) expenseWednesdayRedo;
int expenseRoundThursday = (int) expenseThursdayRedo;
int expenseRoundFriday = (int) expenseFridayRedo;
int expenseRoundSaturday = (int) expenseSaturdayRedo;
int expenseRoundSunday = (int) expenseSundayRedo;
System.out.print("Mon: ");
while (expenseRoundMondayRedo>0){/*print the day and a number of stars based upon the number iterations of the loop,
determined by original value of expense and postdecrement*/
/*System.out.print('*');
expenseRoundMondayRedo--;
}
System.out.println(" ");
System.out.print("Tue: ");
while (expenseRoundTuesdayRedo>0){
System.out.print('*');
expenseRoundTuesdayRedo--;
}
System.out.println(" ");
System.out.print("Wed: ");
while (expenseRoundWednesdayRedo>0){
System.out.print('*');
expenseRoundWednesdayRedo--;
}
System.out.println(" ");
System.out.print("Thur: ");
while (expenseRoundThursdayRedo>0){
System.out.print('*');
expenseRoundThursdayRedo--;
}
System.out.println(" ");
System.out.print("Fri: ");
while (expenseRoundFridayRedo>0){
System.out.print('*');
expenseRoundFridayRedo--;
}
System.out.println(" ");
System.out.print("Sat: ");
while (expenseRoundSaturdayRedo>0){
System.out.print('*');
expenseRoundSaturdayRedo--;
}
System.out.println(" ");
System.out.print("Sun: ");
while (expenseRoundSundayRedo>0){
System.out.print('*');
expenseRoundSundayRedo--;
}
System.out.println(" ");
double avgDailyExpenses=(expenseFridayRedo+expenseMondayRedo+expenseTuesdayRedo+expenseWednesdayRedo+expenseThursdayRedo+expenseSaturdayRedo+expenseSundayRedo)/7;
avgDailyExpenses*=10;//calculate average expenses and convert to dollar value using
int avgDailyExpensesRound = (int) avgDailyExpenses;
avgDailyExpensesRound=avgDailyExpensesRound/10;
double avgDailyExpensesFinal = avgDailyExpensesRound;
System.out.print("Your average daily expenses are: $");
System.out.println(avgDailyExpensesFinal);
}
else{
*/
int expenseRoundMonday = (int) expenseMonday;//convert all from double to int for use in the graph
int expenseRoundTuesday = (int) expenseTuesday;//conversion must be done explicitly due to loss of precision
int expenseRoundWednesday = (int) expenseWednesday;
int expenseRoundThursday = (int) expenseThursday;
int expenseRoundFriday = (int) expenseFriday;
int expenseRoundSaturday = (int) expenseSaturday;
int expenseRoundSunday = (int) expenseSunday;
System.out.print("Mon: ");/*print out day followed by a series of stars, the amount corresponding to the number of times the dollar value
needs to be decremented by 1*/
while (expenseRoundMonday>0){
System.out.print('*');
expenseRoundMonday--;
}
System.out.println(" ");
System.out.print("Tue: ");
while (expenseRoundTuesday>0){//conditional
System.out.print('*');//print stars
expenseRoundTuesday--;//postdecrement
}
System.out.println(" ");//print space for the purpose of using println to move to next line
System.out.print("Wed: ");//must be on same line as stars
while (expenseRoundWednesday>0){
System.out.print('*');
expenseRoundWednesday--;
}
System.out.println(" ");
System.out.print("Thur: ");
while (expenseRoundThursday>0){
System.out.print('*');
expenseRoundThursday--;
}
System.out.println(" ");
System.out.print("Fri: ");
while (expenseRoundFriday>0){
System.out.print('*');
expenseRoundFriday--;
}
System.out.println(" ");
System.out.print("Sat: ");
while (expenseRoundSaturday>0){
System.out.print('*');
expenseRoundSaturday--;
}
System.out.println(" ");
System.out.print("Sun: ");
while (expenseRoundSunday>0){
System.out.print('*');
expenseRoundSunday--;
}
System.out.println(" ");
double avgDailyExpenses=(expenseFriday+expenseMonday+expenseTuesday+expenseWednesday+expenseThursday+expenseSaturday+expenseSunday)/7;
avgDailyExpenses*=10;//find average expenses per day and multiply by ten to prepare for conversion to double
//this will cause the value to be displayed as a dollar amount with the appropriate # of dec points
int avgDailyExpensesRound = (int) avgDailyExpenses;//convert back into integer explicitly
avgDailyExpensesRound=avgDailyExpensesRound/10;//divide this rounded value by 10 to obtain 2 digits on right side
double avgDailyExpensesFinal = avgDailyExpensesRound;//convert back to double
System.out.print("Your average daily expenses are: $");//print average daily expenses with dollar sign
System.out.println(avgDailyExpensesFinal);
}
}
|
package com.theoffice.moneysaver.utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import androidx.core.content.FileProvider;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cloudinary.android.MediaManager;
import com.cloudinary.android.callback.ErrorInfo;
import com.cloudinary.android.callback.UploadCallback;
import com.theoffice.moneysaver.R;
import com.theoffice.moneysaver.data.model.Goal;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import jp.wasabeef.glide.transformations.BlurTransformation;
public class MyFileUtils {
private static String photoPath;
private static Activity stActivity;
public static void blurImage(Context context, ImageView view, Goal goal){
//TODO Trabajando en transformar la imagen
Glide.with(context)
.load(goal.getGoalPhotoPath()).apply(RequestOptions.bitmapTransform(new BlurTransformation(25 - (calculatePercentage(goal) / 4), 1)))
.placeholder(R.drawable.money_icon)
.error(R.drawable.error_icon)
.into(view);
}
private static int calculatePercentage(Goal goal) {
int cost = goal.getGoalCost();
int actual = goal.getGoalActualMoney();
return (actual * 100) / cost;
}
public static String takeGoalPhoto(Activity activity){
stActivity = activity;
String photoPath = "";
Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (photoIntent.resolveActivity(stActivity.getPackageManager()) != null){
File photoFile = null;
try{
photoFile = createImageFile();
photoPath = photoFile.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null){
Uri photoURI = FileProvider.getUriForFile(stActivity,
"com.theoffice.moneysaver.fileprovider",
photoFile);
photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
stActivity.startActivityForResult(photoIntent, AppConstants.REQUEST_IMAGE_CAPTURE);
}
}
return photoPath;
}
private static File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = stActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
photoPath = image.getAbsolutePath();
return image;
}
public static String compressImage(String goalPhotoPath, Context context, int photoType) {
try {
File file = new File(goalPhotoPath);
// BitmapFactory options to downsize the image
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inSampleSize = 6;
// factor of downsizing the image
FileInputStream inputStream = new FileInputStream(file);
//Bitmap selectedBitmap = null;
BitmapFactory.decodeStream(inputStream, null, o);
inputStream.close();
// The new size we want to scale to
final int REQUIRED_SIZE=60;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while(o.outWidth / scale / 2 >= REQUIRED_SIZE &&
o.outHeight / scale / 2 >= REQUIRED_SIZE) {
scale *= 2;
}
Matrix matrix = new Matrix();
matrix.postRotate(90);
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
inputStream = new FileInputStream(file);
Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2);
inputStream.close();
// here i override the original image file
//file.createNewFile();
File.createTempFile(file.getName().substring(0, file.getName().lastIndexOf('.')),
file.getName().substring(file.getName().lastIndexOf('.')), context.getCacheDir());
File newFile = new File(context.getCacheDir().getPath() + file.getName());
FileOutputStream outputStream = new FileOutputStream(newFile);
selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 100 , outputStream);
if (photoType == 0) {
return rotateImage(newFile.getAbsolutePath());
}else if (photoType == 1){
return newFile.getAbsolutePath();
}
return newFile.getAbsolutePath();
} catch (Exception e) {
Log.e("Error", e.getMessage());
return null;
}
}
public static String rotateImage(String photoPath){
File file = new File(photoPath);
Bitmap bmp = BitmapFactory.decodeFile(photoPath);
Matrix matrix = new Matrix();
matrix.postRotate(90);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
return file.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
public static void deleteFile(String photoPath){
new File(photoPath).delete();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.