text stringlengths 10 2.72M |
|---|
package com.tuitaking.tree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
*
* 示例:
*
* 输入: [1,2,3,null,5,null,4]
* 输出: [1, 3, 4]
* 解释:
*
* 1 <---
* / \
* 2 3 <---
* \ \
* 5 4 <---
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/binary-tree-right-side-view
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class RightSideView_199 {
/**
* 解法1的想法,就是按照当前的深度来,然后由左到右。
*/
Map<TreeNode,Integer> depthMap=new HashMap<>();
public List<Integer> rightSideView(TreeNode root) {
if(root==null){
return Collections.emptyList();
}
int depth=depth(root,0);
List<Integer> res=new ArrayList<>(depth);
for(int i = 0 ;i< depth;i++){
res.add(-1);
}
answer(root,res);
return res;
}
public void answer(TreeNode root,List<Integer> res){
if(root==null){
return;
}
answer(root.left,res);
answer(root.right,res);
res.set(depthMap.get(root),root.val);
}
public int depth(TreeNode node,int depth){
if(node==null){
return depth;
}
depthMap.put(node,depth);
int left=depth(node.left,depth+1);
int right=depth(node.right,depth+1);
return Math.max(left,right);
}
public List<Integer> rightSideView_v2(TreeNode root) {
List<Integer> res=new ArrayList<>();
helper(root,res,0);
return res;
}
public void helper(TreeNode root,List<Integer> res,int depth){
if(root==null){
return;
}
if(res.size()==depth){
res.add(root.val);
}
helper(root.right,res,depth+1);
helper(root.left,res,depth+1);
}
public static void main(String[] args) {
TreeNode node=TreeUtils.generateArrayToTree(new Integer[]{1,2,3,null,5,null,4});
RightSideView_199 rightSideView_199=new RightSideView_199();
List<Integer> res=rightSideView_199.rightSideView_v2(node);
System.out.println("hello");
}
}
|
package com.trantienptit.sev_user.chatbot23.bubble;
/**
* Created by SEV_USER on 9/20/2016.
*/
public interface OnInitializedCallback {
void onInitialized();
} |
/*
* 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 safeflyeu.view;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import safeflyeu.controller.ObradaAvioKompanija;
import safeflyeu.controller.ObradaKorisnik;
import safeflyeu.controller.ObradaZaposlenik;
import safeflyeu.model.AvioKompanija;
import safeflyeu.model.Korisnik;
import safeflyeu.model.Osiguranje;
import safeflyeu.model.Zaposlenik;
import safeflyeu.pomocno.SafeFlyEUException;
/**
*
* @author labak
*/
public class Zaposlenici extends javax.swing.JFrame {
private final ObradaZaposlenik obradaEntitet;
private static DefaultComboBoxModel<AvioKompanija> modelAvioKompanija;
public Zaposlenici() {
initComponents();
obradaEntitet = new ObradaZaposlenik();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btnDodaj = new javax.swing.JButton();
btnPromjena = new javax.swing.JButton();
btnBrisanje = new javax.swing.JButton();
txtOib = new javax.swing.JTextField();
txtEmail = new javax.swing.JTextField();
txtPrezime = new javax.swing.JTextField();
txtIme = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
lstEntiteti = new javax.swing.JList<>();
jButton1 = new javax.swing.JButton();
txtUvjet = new javax.swing.JTextField();
chbLimitator = new javax.swing.JCheckBox();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
txtBrojMobitela = new javax.swing.JTextField();
txtBrojUgovora = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setUndecorated(true);
btnDodaj.setText("Dodaj");
btnDodaj.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDodajActionPerformed(evt);
}
});
btnPromjena.setText("Promjena");
btnPromjena.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPromjenaActionPerformed(evt);
}
});
btnBrisanje.setText("Brisanje");
btnBrisanje.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBrisanjeActionPerformed(evt);
}
});
jLabel1.setText("Ime");
jLabel2.setText("Prezime");
jLabel3.setText("Email");
jLabel4.setText("Oib");
lstEntiteti.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
lstEntitetiValueChanged(evt);
}
});
jScrollPane1.setViewportView(lstEntiteti);
jButton1.setText("Exit");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
txtUvjet.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txtUvjetKeyReleased(evt);
}
});
chbLimitator.setSelected(true);
chbLimitator.setText("Limitiraj na 50 rezultata");
jLabel6.setFont(new java.awt.Font("Aharoni", 1, 18)); // NOI18N
jLabel6.setText("Zaposlenici");
jLabel7.setText("Broj mobitela");
jLabel8.setText("Broj ugovora");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnDodaj)
.addGap(18, 18, 18)
.addComponent(btnPromjena)
.addGap(18, 18, 18)
.addComponent(btnBrisanje, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtUvjet, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(chbLimitator))
.addGroup(layout.createSequentialGroup()
.addGap(53, 53, 53)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel3)
.addComponent(jLabel2)
.addComponent(txtIme)
.addComponent(jLabel1)
.addComponent(txtEmail)
.addComponent(txtPrezime, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(139, 139, 139))
.addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtBrojUgovora, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txtOib, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtBrojMobitela, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(chbLimitator)
.addComponent(txtUvjet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnDodaj)
.addComponent(btnPromjena)
.addComponent(btnBrisanje)
.addComponent(jButton1)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtIme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtPrezime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtOib, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7)
.addGap(9, 9, 9)
.addComponent(txtBrojMobitela, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtBrojUgovora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(52, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btnDodajActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDodajActionPerformed
Zaposlenik z = new Zaposlenik();
preuzmiVrijednosti(z);
try {
obradaEntitet.save(z);
ocistiPolja();
ucitajPodatke();
} catch (SafeFlyEUException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
ucitajPodatke();
ocistiPolja();
}//GEN-LAST:event_btnDodajActionPerformed
private void btnPromjenaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPromjenaActionPerformed
Zaposlenik z = lstEntiteti.getSelectedValue();
if (z == null) {
JOptionPane.showConfirmDialog(null, "Prvo odaberite zaposlenika");
}
preuzmiVrijednosti(z);
try {
obradaEntitet.save(z);
} catch (SafeFlyEUException e) {
JOptionPane.showConfirmDialog(null, e.getMessage());
return;
}
ucitajPodatke();
ocistiPolja();
}//GEN-LAST:event_btnPromjenaActionPerformed
private void btnBrisanjeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrisanjeActionPerformed
Zaposlenik z = lstEntiteti.getSelectedValue();
if (z == null) {
JOptionPane.showConfirmDialog(null, "Prvo odaberite korisnika");
}
try {
obradaEntitet.obrisi(z);
ucitajPodatke();
ocistiPolja();
} catch (SafeFlyEUException e) {
JOptionPane.showMessageDialog(null, "Ne mogu obrisati");
}
}//GEN-LAST:event_btnBrisanjeActionPerformed
private void lstEntitetiValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstEntitetiValueChanged
if (evt.getValueIsAdjusting()) {
return;
}
ocistiPolja();
Zaposlenik z = lstEntiteti.getSelectedValue();
if (z == null) {
return;
}
txtIme.setText(z.getIme());
txtPrezime.setText(z.getPrezime());
txtEmail.setText(z.getEmail());
txtBrojMobitela.setText(z.getBrojMobitela());
txtBrojUgovora.setText(z.getBrojUgovora());
// cmbAvioKompanije.setSelectedItem(z.getAvioKompanija());
txtOib.setText(z.getOib());
// modelAvioKompanija = (DefaultComboBoxModel<AvioKompanija>) cmbAvioKompanije.getModel();
// for (int i = 0; i < modelAvioKompanija.getSize(); i++) {
// if (modelAvioKompanija.getElementAt(i).getId() == z.getAvioKompanija().getId()) {
// cmbAvioKompanije.setSelectedIndex(i);
// break;
// }
// }
}//GEN-LAST:event_lstEntitetiValueChanged
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
dispose();
}//GEN-LAST:event_jButton1ActionPerformed
private void txtUvjetKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUvjetKeyReleased
//if(evt.getKeyCode()==KeyEvent.VK_ENTER){
ucitajPodatke();
// }
}//GEN-LAST:event_txtUvjetKeyReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnBrisanje;
private javax.swing.JButton btnDodaj;
private javax.swing.JButton btnPromjena;
private javax.swing.JCheckBox chbLimitator;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JList<Zaposlenik> lstEntiteti;
private javax.swing.JTextField txtBrojMobitela;
private javax.swing.JTextField txtBrojUgovora;
private javax.swing.JTextField txtEmail;
private javax.swing.JTextField txtIme;
private javax.swing.JTextField txtOib;
private javax.swing.JTextField txtPrezime;
private javax.swing.JTextField txtUvjet;
// End of variables declaration//GEN-END:variables
private void ocistiPolja() {
txtIme.setText("");
txtPrezime.setText("");
txtEmail.setText("");
txtOib.setText("");
txtBrojUgovora.setText("");
txtBrojMobitela.setText("");
// cmbAvioKompanije.setSelectedIndex(0);
}
private Zaposlenik preuzmiVrijednosti(Zaposlenik z) {
z.setIme(txtIme.getText());
z.setPrezime(txtPrezime.getText());
z.setEmail(txtEmail.getText());
z.setOib(txtOib.getText());
z.setBrojMobitela(txtBrojMobitela.getText());
z.setBrojUgovora(txtBrojUgovora.getText());
return z;
}
private void ucitajPodatke() {
DefaultListModel<Zaposlenik> m = new DefaultListModel<>();
obradaEntitet.getLista().forEach((z) -> {
m.addElement(z);
});
lstEntiteti.setModel(m);
}
}
|
package com.rc.portal.vo;
public class TGoodsImages {
private Long id;
private String titel;
private String artworkUrl;
private String imageUrl;
private Integer sort;
private Integer userType;
private Integer isdefault;
private Long goodsid;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitel() {
return titel;
}
public void setTitel(String titel) {
this.titel = titel;
}
public String getArtworkUrl() {
return artworkUrl;
}
public void setArtworkUrl(String artworkUrl) {
this.artworkUrl = artworkUrl;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public Integer getIsdefault() {
return isdefault;
}
public void setIsdefault(Integer isdefault) {
this.isdefault = isdefault;
}
public Long getGoodsid() {
return goodsid;
}
public void setGoodsid(Long goodsid) {
this.goodsid = goodsid;
}
} |
package com.example.world.repository.orm;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.example.world.entity.City;
import com.example.world.repository.CityRepository;
/**
*
* @author Binnur Kurt <binnur.kurt@gmail.com>
*/
@Repository
public class CityJpaRepository implements CityRepository {
@PersistenceContext(unitName = "worldPU")
private EntityManager entityManager;
@Override
@Transactional
public City add(City country) {
entityManager.persist(country);
return country;
}
@Override
public City update(City country) {
return entityManager.merge(country);
}
@Override
@Transactional
public Optional<City> remove(Long id) {
City city = entityManager.find(City.class, id);
if (Objects.nonNull(city)) {
entityManager.remove(city);
return Optional.of(city);
}
return Optional.empty();
}
@Override
@Transactional(propagation = Propagation.MANDATORY)
public Optional<City> findOne(Long id) {
City city = entityManager.find(City.class, id);
if (Objects.nonNull(city))
return Optional.of(city);
return Optional.empty();
}
@Override
public Collection<City> findAll() {
List<City> cities = entityManager.createNamedQuery("fromCity.all", City.class).getResultList();
return cities;
}
@Override
public Collection<City> findByCountryCode(String code) {
List<City> cities = entityManager.createNamedQuery("fromCity.byCountry", City.class).setParameter("code", code)
.getResultList();
return cities;
}
}
|
package am.data.enums;
import am.main.data.enums.logger.LoggerLevels;
import am.main.spi.AMPhase;
/**
* Created by ahmed.motair on 2/9/2018.
*/
public class ALP extends AMPhase {
private static final String AM_LOG = "AML";
public static final ALP BUSINESS_LOG = new ALP(AM_LOG, "Business");
public static final ALP FILE_LOG = new ALP(AM_LOG, "File");
public static final ALP FUNCTION_LOG = new ALP(AM_LOG, "Function");
public ALP(String CATEGORY, String NAME) {
super(CATEGORY, NAME, LoggerLevels.ST_DEBUG);
}
}
|
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ArbeitsvorgangTypType;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ERHITZENSolldatenType;
import java.io.StringWriter;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
public class ERHITZENSolldatenTypeBuilder
{
public static String marshal(ERHITZENSolldatenType eRHITZENSolldatenType)
throws JAXBException
{
JAXBElement<ERHITZENSolldatenType> jaxbElement = new JAXBElement<>(new QName("TESTING"), ERHITZENSolldatenType.class , eRHITZENSolldatenType);
StringWriter stringWriter = new StringWriter();
return stringWriter.toString();
}
private Boolean geaendertKz;
private ArbeitsvorgangTypType arbeitsvorgang;
public ERHITZENSolldatenTypeBuilder setGeaendertKz(Boolean value)
{
this.geaendertKz = value;
return this;
}
public ERHITZENSolldatenTypeBuilder setArbeitsvorgang(ArbeitsvorgangTypType value)
{
this.arbeitsvorgang = value;
return this;
}
public ERHITZENSolldatenType build()
{
ERHITZENSolldatenType result = new ERHITZENSolldatenType();
result.setGeaendertKz(geaendertKz);
result.setArbeitsvorgang(arbeitsvorgang);
return result;
}
} |
package com.days.moment.miniboard.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ReplyDTO {
private Long mbReNo;
private Long mbNo;
private String mbReWriter;
private String mbReContent;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime mbReRegDate;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime mbReModDate;
private Long originReNo;
private Long reDepth;
}
|
/*
* 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 AAPA.Entity;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
/**
*
* @author amine
*/
@Entity
@NamedQuery(name = "Files.findAllByOrderByfileNameAsc", query="select u from Files u order by u.fileName")
public class Files {
@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private Long idFile;
private String fileName;
private String fileDate;
private String adress;
private String observation;
@OneToMany
private List<Childrens> childrens;
@OneToMany
private List<Alarm> alarms;
@OneToOne(optional = true)
private Beneficiary beneficiary;
@OneToOne(optional = true)
private Compagnon compagnon;
public Files () {
}
Files (String fileName, String fileDate,String adress, String observation) {
this.fileDate=fileDate;
this.fileName=fileName;
this.adress=adress;
this.observation=observation;
}
Files (String fileName, String fileDate,String adress, String observation, Beneficiary beneficiary) {
this.fileDate=fileDate;
this.fileName=fileName;
this.adress=adress;
this.observation=observation;
this.beneficiary=beneficiary;
}
Files (String fileName, String fileDate,String adress, String observation, Beneficiary beneficiary, Compagnon compagnon) {
this.fileDate=fileDate;
this.fileName=fileName;
this.adress=adress;
this.observation=observation;
this.beneficiary=beneficiary;
this.compagnon=compagnon;
}
Files (String fileName, String fileDate,String adress, String observation,
Beneficiary beneficiary, Compagnon compagnon, List<Childrens> childrens) {
this.fileDate=fileDate;
this.fileName=fileName;
this.adress=adress;
this.observation=observation;
this.beneficiary=beneficiary;
this.compagnon=compagnon;
this.childrens=childrens;
}
public Beneficiary getBeneficiary() {
return beneficiary;
}
public void setBeneficiary(Beneficiary beneficiary) {
this.beneficiary = beneficiary;
}
public Compagnon getCompagnon() {
return compagnon;
}
public void setCompagnon(Compagnon compagnon) {
this.compagnon = compagnon;
}
public List<Childrens> getChildrens() {
return childrens;
}
public List<Alarm> getAlarms() {
return alarms;
}
public Long getIdFile (){
return idFile;
}
public String getFileName (){
return fileName;
}
public String getFileDate (){
return fileDate;
}
public String getAdress (){
return adress;
}
public String getObservation (){
return observation;
}
public void setIdFile (Long idFile){
this.idFile=idFile;
}
public void setFileName (String fileName){
this.fileName=fileName;
}
public void setFileDate (String fileDate ){
this.fileDate=fileDate;
}
public void setAdress (String adress ){
this.adress=adress;
}
public void setObservation (String observation){
this.observation=observation;
}
public void setChildrens(List<Childrens> childrens) {
this.childrens = childrens;
}
public void setAlarms(List<Alarm> alarms) {
this.alarms = alarms;
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 notXX
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.customface;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import edu.tsinghua.lumaqq.ecore.face.FaceConstant;
import edu.tsinghua.lumaqq.ecore.face.FaceGroup;
import edu.tsinghua.lumaqq.qq.Util;
import edu.tsinghua.lumaqq.ui.helper.FileTool;
/**
* QQ自定义表情CFC格式文件的导入器,CFC文件是一个比较简单的文件格式,它比EIP要简单很多,
* 缺点是CFC文件不能支持表情分组。
* <p>
* CFC文件的格式是一系列连续的块,每个块是一个GIF和BMP文件,BMP文件是GIF的微缩图,我们
* 知道QQ在选择自定义表情的时候都会把它们的微缩图显示出来给我们选。LumaQQ只关心GIF,BMP
* 暂且用不上。
* </p>
* <p>
* CFC文件没有文件头,也没有文件尾,它就是一系列连续的块组成的,所以下面介绍块的格式,我们
* 要注意的是,这个文件里面的整数都是little-endian格式.
* </p>
* <p>
* 1. md5的字符串形式长度,4个字节,这个一般都是0x00000020,因为MD5是16字节
* 2. 快捷键长度,4字节
* 3. 表情名称长度,4字节
* 4. 表情文件名长度,4字节,加上".GIF",所以这个字段一般都是0x00000024
* 5. 表情文件长度,4字节
* 6. 微缩图文件名长度,4字节,因为微缩图一般都是MD5 + "fixed.bmp",所以这个字段一般都是0x00000029
* 7. 微缩文件长度,4字节
* 8. 表情文件帧数,4字节,因为表情文件可能是动画,动画自然是多帧的
* 9. 图片md5的字符串形式
* 10. 快捷键
* 11. 表情名称
* 12. 表情文件名
* 13. 微缩图文件名
* 14. 表情文件内容
* 15. 微缩图内容
* </p>
*
* @author luma
*/
public class CFCImporter {
private FaceEntry entry;
private String destDir;
private FaceGroup group;
private RandomAccessFile cfcFile;
private long nextEntryOffset;
private long cfcFileLength;
private byte[] buffer;
private int md5Length;
private int shortcutLength;
private int nameLength;
private int fileNameLength;
private int fileLength;
private int thumbFileNameLength;
private int thumbFileLength;
/**
* 创建一个CFC文件导入器
*
* @param file
* CFC文件路径
* @param destDir
* 保存图片的目的路径
* @param g
* 保存到的组
*/
public CFCImporter(String file, String destDir, FaceGroup g) {
this.destDir = destDir;
nextEntryOffset = 0;
buffer = new byte[10000];
entry = new FaceEntry();
group = g;
try {
cfcFile = new RandomAccessFile(file, "r");
cfcFileLength = cfcFile.length();
} catch (IOException e) {
cfcFileLength = -1;
}
}
/**
* 释放资源
*/
public void dispose() {
buffer = null;
try {
cfcFile.close();
} catch (IOException e) {
}
}
/**
* @return
* 下一个表情项内容,如果为null,表示没有更多项了
*/
public FaceEntry getNextEntry() {
if(nextEntryOffset >= cfcFileLength)
return null;
boolean success = readEntry();
while(nextEntryOffset < cfcFileLength && !success)
success = readEntry();
return success ? entry : null;
}
/**
* 从offset位置读取4个字节为一个long,因为java为big-endian格式,所以没办法
* 用了这么一个函数来做转换
* @param offset
* @return 读取的long值,返回-1表示读取文件失败
*/
private int readInt4(long offset) {
int ret = 0;
try {
cfcFile.seek(offset);
ret |= (cfcFile.readByte() & 0xFF);
ret |= ((cfcFile.readByte() << 8) & 0xFF00);
ret |= ((cfcFile.readByte() << 16) & 0xFF0000);
ret |= ((cfcFile.readByte() << 24) & 0xFF000000);
return ret;
} catch (IOException e) {
return -1;
}
}
/**
* 从指定位置读取一个指定长度的字符串
*
* @param offset
* 起始偏移
* @param length
* 字符串长度
* @return
* 字符串,失败返回null
*/
private String readString(long offset, int length) {
try {
byte[] buf = new byte[length];
cfcFile.seek(offset);
cfcFile.readFully(buf);
return Util.getString(buf);
} catch (IOException e) {
return null;
}
}
/**
* 从指定位置读取一段内容
*
* @param offset
* 起始偏移
* @param length
* 读取长度
* @return
* true表示成功
*/
private boolean readBytes(long offset, int length) {
if(length > buffer.length)
expandBuffer(length);
try {
cfcFile.seek(offset);
cfcFile.read(buffer, 0, length);
return true;
} catch (IOException e) {
return false;
}
}
/**
* 读取下一个face entry。读取完毕后,nextEntryOffset将被置为下一个entry的偏移
*
* @return
* true表示读取成功
*/
private boolean readEntry() {
long offset = nextEntryOffset;
md5Length = readInt4(offset);
offset += 4;
shortcutLength = readInt4(offset);
offset += 4;
nameLength = readInt4(offset);
offset += 4;
fileNameLength = readInt4(offset);
offset += 4;
fileLength = readInt4(offset);
offset += 4;
thumbFileNameLength = readInt4(offset);
offset += 4;
thumbFileLength = readInt4(offset);
offset += 4;
// 读取md5
offset += 4;
entry.md5 = readString(offset, md5Length);
offset += md5Length;
// shortcut
entry.shortcut = readString(offset, shortcutLength);
offset += shortcutLength;
// 名称
entry.name = readString(offset, nameLength);
offset += nameLength;
// 文件名
entry.filename = readString(offset, fileNameLength);
offset += fileNameLength;
// 读取文件内容
offset += thumbFileNameLength;
if(!readBytes(offset, fileLength)) {
nextEntryOffset = offset + fileLength + thumbFileLength;
return false;
}
nextEntryOffset = offset + fileLength + thumbFileLength;
return true;
}
/**
* 保存这个块中的图片文件到目标目录
*
* @return
* true表示保存成功
*/
public boolean saveEntry() {
if(group.getId() == FaceConstant.CUSTOM_HEAD_GROUP_ID)
return saveCustomHead();
else {
// 保存表情文件
String filename = destDir + group.getId() + '/' + entry.filename;
if(!FileTool.saveFile(buffer, 0, fileLength, filename))
return false;
// 保存缩略图
try {
ImageLoader loader = new ImageLoader();
loader.load(filename);
ImageData data = loader.data[0].scaledTo(20, 20);
loader = new ImageLoader();
loader.data = new ImageData[] { data };
loader.save(destDir + group.getId() + '/' + entry.md5 + "fixed.bmp", SWT.IMAGE_BMP);
} catch (SWTException e) {
return false;
}
return true;
}
}
/**
* 保存文件为自定义头像
*
* @return
* true表示保存成功
*/
private boolean saveCustomHead() {
try {
// 生成ImageData
ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 0, fileLength);
ImageData origin = new ImageData(bais);
ImageData data = origin.scaledTo(40, 40);
// save 40x40 bmp
ImageLoader saveLoader = new ImageLoader();
saveLoader.data = new ImageData[] { data };
saveLoader.save(destDir + group.getId() + '/' + entry.md5 + ".bmp", SWT.IMAGE_BMP);
// save 20x20 bmp
data = origin.scaledTo(20, 20);
saveLoader = new ImageLoader();
saveLoader.data = new ImageData[] { data };
saveLoader.save(destDir + group.getId() + '/' + entry.md5 + "fixed.bmp", SWT.IMAGE_BMP);
return true;
} catch(SWTException e) {
return false;
}
}
/**
* 扩展缓冲区
*/
private void expandBuffer(int length) {
buffer = new byte[length];
}
}
|
package cr.ulacit.dto;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="menuDishDTO")
public class MenuDishDTO {
private int id_menudish;
public int getId_menudish() {
return id_menudish;
}
public void setId_menudish(int id_menudish) {
this.id_menudish = id_menudish;
}
@Override
public String toString() {
return "MenuDishDTO [id_menudish=" + id_menudish + "]";
}
} |
package com.company;
import java.util.Scanner;
public class Refresher_Challenge {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Your name: ");
String name=scanner.next();
System.out.println();
int times=10;
if(name.equals("mitchell")){
times=5;
}
for(int i=1; i<=times; i++){
System.out.println(name);
}
}
}
|
package org.seckill.seckill.dao;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.seckill.seckill.entity.Seckill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SeckillDaoTest {
@Autowired
private SeckillDao seckillDao;
@Test
public void reduceNumber() throws Exception {
int updateCount = seckillDao.reduceNumber(1000L, new Date());
System.out.println("updateCount="+updateCount);
}
@Test
public void queryById() throws Exception {
int id = 1000;
Seckill seckill = seckillDao.queryById(id);
System.out.println(seckill);
Assert.assertNotNull(seckill);
}
@Test
public void queryAll() throws Exception {
/**
* nested exception is org.apache.ibatis.binding.BindingException:
* Parameter 'offset' not found. Available parameters are [arg1, arg0, param1, param2]
* java 没有保存形参的记录 queryAll(int offset,int limit);
*/
List<Seckill> seckill = seckillDao.queryAll(0,10);
Assert.assertNotNull(seckill);
}
} |
package leecode.dfs;
import com.sun.org.apache.bcel.internal.generic.FADD;
public class 岛屿的最大面积_695 {
//对比lee200
// 并查集只需要走右,走下 方向 即{1,0},{0,1}
static int[][]dirs=new int[][]{{1,0},{0,1},{0,-1},{-1,0}};//表示上下左右搜索,{1,-1}表示斜着搜索
public static int maxAreaOfIsland(int[][]grid){
int m=grid.length;
int n=grid[0].length;
union union=new union(m*n);
for (int i = 0; i <m ; i++) {
for (int j = 0; j <n ; j++) {
System.out.println("2222 i="+i+"j= "+j+" ");
if(grid[i][j]==1){
for (int[]dir:dirs){
int x=i+dir[0];
int y=j+dir[1];
if(bound(x,y,grid)&&grid[x][y]==1){
union.merge(i*n+j,x*n+y);
}
}
}
}
}
int max=0;
for (int i = 0; i <m ; i++) {
for (int j = 0; j < n; j++) {
if(grid[i][j]==1){
System.out.println("234"+size[i*n+j]+" "+i+" "+j);
max=Math.max(size[i*n+j],max);
}
}
}
return max;
}
public static boolean bound(int x,int y,int[][]grid){
return x>=0&&x<grid.length&&y>=0&&y<grid[0].length;
}
//思路:并查集看每个树的size
static int[]size;
static class union{
private int[]parent;
// private int[]size;
private int count;
public union(int n){
parent=new int[n];
size=new int[n];
this.count=n;
for (int i = 0; i <n ; i++) {
parent[i]=i;
size[i]=1;
}
}
public void merge(int node1,int node2){
int father1=findFather(node1);
int father2=findFather(node2);
if(father1==father2){
return;
}
//怎么的到各自的size?
if(size[father1]>size[father2]){//小放在大
parent[father2]=father1;
size[father1]+=size[father2];
}else {
parent[father1]=father2;
size[father2]+=size[father1];
}
count--;//记得这个
}
public boolean isConnected(int node1,int node2){
return findFather(node1)==findFather(node2);
}
public int findFather(int node){
// int father=parent[node];
while (parent[node]!=node){ //写成while(father!=node)就错了,因为while里面father不更新
parent[node]=parent[parent[node]];
node=parent[node];
}
return node;
}
}
//dfs
// public static int max=0;
public static int maxAreaOfIsland2(int[][]grid) {
int max=0;
boolean[][]visit=new boolean[grid.length][grid[0].length];
for (int i = 0; i <grid.length ; i++) {
for (int j = 0; j <grid[0].length ; j++) {
if(grid[i][j]==1&&!visit[i][j]){//dfs里没有先对visit进行判断,所以这里加上,如果先判断(dfs2函数),则不用加
int temp=maxAreaOfIslandwithdfs(grid,i,j,visit);
// System.out.println("i="+i+"j="+j+"temp="+temp);
max=Math.max(max,temp);//max一定要写到if里面
}
}
}
return max;
}
/*
dfs每个点都可以进行dfs时候,dfs就需要返回值!!因为每个点进行dfs的结果
需要去更新我们最后要的结果,因为java不能传引用,所以每次拿返回值来更新
每个点都需要dfs时候就需要visit数组!!
遍历完成之后 visit[i][j]重新变成false就错了!!!,
maxAreaOfIslandwithdfs2可以看下不传引用怎么改变值
*/
public static int maxAreaOfIslandwithdfs(int[][] grid, int i, int j, boolean[][] visit) {
visit[i][j] = true;
int count = 1;//设为1.如果设为0永远是0
for (int[] dir : dirs) {
int x = i + dir[0];
int y = j + dir[1];
if (bound(x, y, grid)&&grid[x][y]==1&&!visit[x][y]) {//dfs指针移动到下一个点时,满足不越界,为1(说明有边),未dfs过
int temp = maxAreaOfIslandwithdfs(grid, x, y, visit);
System.out.println("x=" + x + "y=" + y + "temp=" + temp);
count = count + temp;
}
}
// visit[i][j]=false; //加上这个就不对
return count;
}
public int dfs2(int[][] grid,int i,int j,boolean[][]visit){
//将visit[i][j]条件移到这里也可以,注意return 0
if(visit[i][j]==true){
return 0;
}
visit[i][j]=true;
int count=1;
for (int k = 0; k <4 ; k++) {
int x=i+dirs[k][0];
int y=j+dirs[k][1];
if(bound(x,y,grid)&&grid[x][y]==1){
count=count+dfs2(grid,x,y,visit);
}
}
return count;
}
//直接传入count不太容易理解
public static int maxAreaOfIslandwithdfs2(int[][]grid,int i,int j,boolean[][]visit,int count) {
if(!bound(i,j,grid)||visit[i][j]||grid[i][j]==0){
return count;
}
visit[i][j]=true;
for(int[]dir:dirs){
int x=i+dir[0];
int y=j+dir[1];
count=maxAreaOfIslandwithdfs2(grid,x,y,visit,count);//这里传入的count没有加1!!
}
visit[i][j]=false;//加上这个就不对
return count+1;
}
public static void main(String[] args) {
int[][]grid=new int[][]{
{1,1,0,0,0},
{1,1,0,0,0},
{0,0,0,1,1},
{0,0,0,1,1}
};
// System.out.println(maxAreaOfIsland(grid));
System.out.println(maxAreaOfIsland2(grid));
}
}
|
import com.zsl.web.common.dao.IBaseDao;
import com.zsl.web.common.dao.IOperations;
/**
* note
* @author gq
*
*/
public interface IModelDao extends IOperations<Model>,IBaseDao<Model> {
}
|
package com.FCI.SWE.Models;
import static org.testng.Assert.assertEquals;
import java.util.ArrayList;
import org.testng.annotations.Test;
public class PageTest {
/*** Failed ***/
@Test
public void getPage() {
boolean found = false;
if(Page.getPage(2) != null)
found = true;
assertEquals( found , true);
assertEquals( Page.getPage(11) , null);
}
/*** Passed ***/
@Test
public void savePage() {
Post post = new Post(7, "osama", "7azenFa45", "public" , "Koko Lolo Dodo Bobo",
5, "a");
ArrayList<Post> posts = new ArrayList<>();
posts.add(post);
UserEntity a = UserEntity.getUser("a", "a");
UserEntity b = UserEntity.getUser("b","b");
ArrayList<UserEntity> users = new ArrayList<UserEntity>();
users.add(a);
users.add(b);
Page page = new Page(4, "3abelo we edelo", users, posts, "a", "social");
assertEquals( page.savePage() , true);
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
/**
* J4WorkflowParaId generated by hbm2java
*/
public class J4WorkflowParaId implements java.io.Serializable {
private BigDecimal id;
private String processname;
private String taskname;
private String paraName;
private String paraValue;
private String objectName;
private String objectType;
public J4WorkflowParaId() {
}
public J4WorkflowParaId(BigDecimal id) {
this.id = id;
}
public J4WorkflowParaId(BigDecimal id, String processname, String taskname, String paraName, String paraValue,
String objectName, String objectType) {
this.id = id;
this.processname = processname;
this.taskname = taskname;
this.paraName = paraName;
this.paraValue = paraValue;
this.objectName = objectName;
this.objectType = objectType;
}
public BigDecimal getId() {
return this.id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public String getProcessname() {
return this.processname;
}
public void setProcessname(String processname) {
this.processname = processname;
}
public String getTaskname() {
return this.taskname;
}
public void setTaskname(String taskname) {
this.taskname = taskname;
}
public String getParaName() {
return this.paraName;
}
public void setParaName(String paraName) {
this.paraName = paraName;
}
public String getParaValue() {
return this.paraValue;
}
public void setParaValue(String paraValue) {
this.paraValue = paraValue;
}
public String getObjectName() {
return this.objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
public String getObjectType() {
return this.objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof J4WorkflowParaId))
return false;
J4WorkflowParaId castOther = (J4WorkflowParaId) other;
return ((this.getId() == castOther.getId())
|| (this.getId() != null && castOther.getId() != null && this.getId().equals(castOther.getId())))
&& ((this.getProcessname() == castOther.getProcessname())
|| (this.getProcessname() != null && castOther.getProcessname() != null
&& this.getProcessname().equals(castOther.getProcessname())))
&& ((this.getTaskname() == castOther.getTaskname()) || (this.getTaskname() != null
&& castOther.getTaskname() != null && this.getTaskname().equals(castOther.getTaskname())))
&& ((this.getParaName() == castOther.getParaName()) || (this.getParaName() != null
&& castOther.getParaName() != null && this.getParaName().equals(castOther.getParaName())))
&& ((this.getParaValue() == castOther.getParaValue()) || (this.getParaValue() != null
&& castOther.getParaValue() != null && this.getParaValue().equals(castOther.getParaValue())))
&& ((this.getObjectName() == castOther.getObjectName()) || (this.getObjectName() != null
&& castOther.getObjectName() != null && this.getObjectName().equals(castOther.getObjectName())))
&& ((this.getObjectType() == castOther.getObjectType())
|| (this.getObjectType() != null && castOther.getObjectType() != null
&& this.getObjectType().equals(castOther.getObjectType())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getId() == null ? 0 : this.getId().hashCode());
result = 37 * result + (getProcessname() == null ? 0 : this.getProcessname().hashCode());
result = 37 * result + (getTaskname() == null ? 0 : this.getTaskname().hashCode());
result = 37 * result + (getParaName() == null ? 0 : this.getParaName().hashCode());
result = 37 * result + (getParaValue() == null ? 0 : this.getParaValue().hashCode());
result = 37 * result + (getObjectName() == null ? 0 : this.getObjectName().hashCode());
result = 37 * result + (getObjectType() == null ? 0 : this.getObjectType().hashCode());
return result;
}
}
|
package com.example.usersessionmanagement;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Register extends AppCompatActivity {
EditText et,add,mob,em,pw;
Button b3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
et=findViewById(R.id.editText3);
add=findViewById(R.id.editText4);
mob=findViewById(R.id.editText5);
em=findViewById(R.id.editText6);
pw=findViewById(R.id.editText7);
b3=findViewById(R.id.button3);
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name=et.getText().toString();
String address=add.getText().toString();
String mobile=mob.getText().toString();
String email=em.getText().toString();
String password=pw.getText().toString();
UserPref up=new UserPref(Register.this);
up.addData("Name",name);
up.addData("Address",address);
up.addData("Mobile",mobile);
up.addData("Email",email);
up.addData("Password",password);
Toast.makeText(Register.this, "Data Stored successfully", Toast.LENGTH_SHORT).show();
Intent i=new Intent(Register.this,MainActivity.class);
startActivity(i);
finish();
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent i=new Intent(Register.this,MainActivity.class);
startActivity(i);
finish();
}
}
|
package com.zpjr.cunguan.view.setting;
import com.zpjr.cunguan.common.base.IBaseView;
/**
* Description: 描述
* Autour: LF
* Date: 2017/8/22 11:45
*/
public interface ICMSWebView extends IBaseView{
//设置webview内容
void webViewInitial(String content);
}
|
package Record;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Scanner;
/**
* Created by Sega on 03.08.2017.
*/
public class Parser {
public static void parseRecords(String servletContext, ArrayList<Record> records) {
Scanner scanner = new Scanner(servletContext);
while (scanner.hasNextLine()) {
String string = scanner.nextLine();
if (string.length() == 0) continue;
if ((string.contains("[INFO ]"))) {
Record record = new Record();
String stringSplit[] = string.split(" ");
record.setTime(parseTime(stringSplit));
record.setEventType(parseEventType(stringSplit));
if (!Objects.equals(parseEventType(stringSplit), null)) {
//Take string with content "Body =..."
string = scanner.nextLine();
if (string.length() == 6) record.setMessage("");
else {
record.setMessage(string.substring(7));
}
}
records.add(record);
}
}
}
private static String parseTime(String stringSplit[]) {
return stringSplit[0];
}
private static String parseEventType(String stringSplit[]) {
for (String aStringSplit : stringSplit) {
if (aStringSplit.equals("START")
|| (aStringSplit.equals("PROCESS_ACTION"))
|| (aStringSplit.equals("PROCESS_EVENT"))
|| (aStringSplit.equals("FINISH"))) {
return aStringSplit;
}
}
return null;
}
}
|
package gov.virginia.dmas.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import gov.virginia.dmas.entity.ElectedOfficialRequestInternalEntity;
public interface ElectedOfficialRequestInternalRepository extends JpaRepository<ElectedOfficialRequestInternalEntity, Long>{
}
|
package com.williamchik;
import android.view.View;
import android.widget.TextView;
/**
* view holder of AutoFitViewGroup's item, like RecyclerView's ViewHolder class
*
* @author WilliamChik on 15/9/26.
*/
public class AutoFitViewGroupItemViewHolder extends AutoFitViewGroup.ViewHolder {
public TextView demoGroupItemTv;
public AutoFitViewGroupItemViewHolder(View itemView) {
super(itemView);
demoGroupItemTv = (TextView) itemView.findViewById(R.id.tv_demo_group_item);
}
}
|
package com.example.android.miwok;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
/**
* Class which represents the business logic for the FamilyFragment of the MainActivity.
*
* <p>
* Author: William Walsh
* Version: 2.0 (Fragments)
* Date: 18-05-18
*/
public class FamilyFragment extends Fragment {
// AudioManager responsible for getting and abandoning AudioFocus
private AudioManager audioManager;
// MediaPlayer which can play mp3 and mp4
private MediaPlayer mediaPlayer;
public FamilyFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.activity_list_view, container, false);
// Collection of words to store the list element data
final ArrayList<Word> familyMembers = new ArrayList<Word>();
// Adding members to the Collection
familyMembers.add(new Word("father", "әpә", R.drawable.family_father, R.raw.family_father));
familyMembers.add(new Word("mother", "әṭa", R.drawable.family_mother, R.raw.family_mother));
familyMembers.add(new Word("son", "angsi", R.drawable.family_son, R.raw.family_son));
familyMembers.add(new Word("daughter", "tune", R.drawable.family_daughter, R.raw.family_daughter));
familyMembers.add(new Word("older brother", "taachi", R.drawable.family_older_brother, R.raw.family_older_brother));
familyMembers.add(new Word("younger brother", "chalitti", R.drawable.family_younger_brother, R.raw.family_younger_brother));
familyMembers.add(new Word("older sister", "teṭe", R.drawable.family_older_sister, R.raw.family_older_sister));
familyMembers.add(new Word("younger sister", "kolliti", R.drawable.family_younger_sister, R.raw.family_younger_sister));
familyMembers.add(new Word("grandmother", "ama", R.drawable.family_grandmother, R.raw.family_grandmother));
familyMembers.add(new Word("grandfather", "paapa", R.drawable.family_grandfather, R.raw.family_grandfather));
// Create ArrayAdapter Point it to context, familyMember ArrayList & list element color
WordAdapter adapter = new WordAdapter(getActivity(), familyMembers, R.color.category_family);
// Get ListView.xml ref
ListView listView = (ListView) rootView.findViewById(R.id.list);
// Associate adapter to ListView
listView.setAdapter(adapter);
// Set an Item Click listener
// Pass in an anonymous concrete class
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Get AudioManager
audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
// Request AudioFocus using the local audioManager instance
// pass in the AudioFocusChangeListener, Stream type and AudioFocus Type
int result = audioManager.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE);
// If the AudioFocus request is granted
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// Release mediaPlayer before playing another song
releaseMediaPlayer();
// Get the data associated with the list element selected using the position index
Word word = familyMembers.get(position);
// register media buttons
// Create MediaPlayer
mediaPlayer = MediaPlayer.create(getActivity(), word.getMusicRef());
// Set the onCompletionListener
mediaPlayer.setOnCompletionListener(mpCompletionListener);
// start playing audio
mediaPlayer.start();
}
}
});
return rootView;
}
// Concrete class to implement the OnCompletionListener interface
private MediaPlayer.OnCompletionListener mpCompletionListener = new MediaPlayer.OnCompletionListener() {
// Upon completion of music playback on MediaPlayer
@Override
public void onCompletion(MediaPlayer mp) {
// Release the MediaPlayer resource
releaseMediaPlayer();
}
};
// Listener which listens for an AudioFocusChange event
public AudioManager.OnAudioFocusChangeListener afChangeListener = new AudioManager.OnAudioFocusChangeListener() {
// Interface method to be implemented to deal with changes in AudioFocus
@Override
public void onAudioFocusChange(int i) {
if (i == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || i == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// If the AudioFocus is lost temporarily or when its lost yet ducking is allowed
// Pause the media player
mediaPlayer.pause();
// Change playback to beginning
mediaPlayer.seekTo(0);
} else if (i == AudioManager.AUDIOFOCUS_GAIN) {
// If you gain the audiofocus
// Resume playing music
mediaPlayer.start();
} else if (i == AudioManager.AUDIOFOCUS_LOSS) {
// When audioFocus is lost long term
// Stop Audio playback
mediaPlayer.stop();
// Release the MediaPlayer resource
releaseMediaPlayer();
}
}
};
/**
* Clean up the media player by releasing its resources.
*/
private final void releaseMediaPlayer() {
// If the media player is not null, then it may be currently playing a sound.
if (mediaPlayer != null) {
// Regardless of the current state of the media player, release its resources
// because we no longer need it.
mediaPlayer.release();
// Set the media player back to null. For our code, we've decided that
// setting the media player to null is an easy way to tell that the media player
// is not configured to play an audio file at the moment.
mediaPlayer = null;
// Release audioFocus when playback is complete
audioManager.abandonAudioFocus(afChangeListener);
}
}
}
|
package com.example.changelogerror.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @author madengbo
* @create 2018-11-06 14:09
* @desc
* @Version 1.0
**/
@Slf4j
@Component
public class LogTest {
public void testInfo(){
log.info("service info test");
log.error("service error test");
log.debug("service bug test");
}
}
|
package round.first.linkedList;
//https://www.lintcode.com/problem/reorder-list/description
public class ReorderList {
/**
* @param head: The head of linked list.
* @return: nothing
*/
public void reorderList(ListNode head) {
// write your code here
if (head == null || head.next == null || head.next.next == null) {
return;
}
ListNode middle = findMiddle(head);
ListNode tail = reverseList(middle.next);
middle.next = null;
merge(head, tail);
}
private ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}
private void merge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(0);
ListNode head = dummy;
int index = 0;
while (head1 != null && head2 != null) {
if (index % 2 == 0) {
head.next = head1;
head1 = head1.next;
} else {
head.next = head2;
head2 = head2.next;
}
head = head.next;
index++;
}
if (head1 != null) {
head.next = head1;
} else {
head.next = head2;
}
head1 = dummy.next;
}
}
|
package chc;
import shared.LogOptions;
import shared.Inducer;
import id3.ID3Inducer;
import nb.NaiveBayesInd;
import java.io.IOException;
/** CHC is a genetic algorithm used with mlj inducers to find the
* best possible combination of attributes for testing data samples.
* The combinations, called hypothesis, are intialized randomly for
* the first generation and crossed in a logical order for future
* generations. The process of crossing two hypothesis is called
* breeding. Inducer algorithms from MLJ are then used with the
* hypothesis combinations to determine the fitness of the given
* hypothesis. The hypothses with the highest fitness
* survive to the next generation where they will breed to
* produce more combinations of hypotheses.
* The process repeats itself for a designated number of
* generations with a designated population size. */
public class CHC {
/** The inducer used to test hypothesis. */
private Inducer inducer;
/** The object that keeps the instances used for training and testing. */
private DataDistributor dist;
/** The population where all the hypothesis are stored, bred and tested. */
private Population currentpopulation;
/** used with dist. The new system of data distribution is used if
* this is true. */
private boolean newsystem = false;
/** Stores the newline character "\n" */
public static final String ENDL = "\n";
public static final String NAIVE = "naive";
public static final String ID3 = "id3";
public static final String C45 = "c45";
public static final int DEFAULTMAXPOP = 10;
public static final int DEFAULTMINPOP = 2;
public static final boolean DEFAULTUSEPOPBOUNDARIES = false;
public static final String GENERATIONPRINTING = "generation";
public static final String TOTALPRINTING = "total";
private boolean usepopboundaries;
private int minpopulation = 2;
Options options = null;
/** Takes the argument string array and breaks it into the options
* which govern the operations of chc.
* @param args - the String array containing the options for chc. */
public CHC(String[] args) throws IOException {
options = new Options();
//This section sorts through the command line arguments and pulls out
//only valuable information typing invaluable information does not
//necessarily crash the program. Any information obtained here automatically
//overides information extracted from the MLJ-Options.file.
for (int i=1; i<args.length;i++) {
if (args[i].length() >= 8 ) {
if (args[i].substring(0,8).toLowerCase().equals("inducer=")) {
try {
options.optioninducer = args[i].substring(8, args[i].length());
System.out.println(options.optioninducer);
}
catch (Exception e) {
}
}
}
if (args[i].length() >= 16 ) {
if (args[i].substring(0,16).toLowerCase().equals("finalgeneration=")) {
int xyz = 0;
for (int k=16;k<args[i].length();k++) {
try {
xyz = xyz*10 + Integer.valueOf(args[i].substring(k,k+1)).intValue();
}
catch (Exception e) {
}
}
options.finalgeneration = xyz;
}
}
if (args[i].length() >= 15) {
if (args[i].substring(0,15).toLowerCase().equals("populationsize=")) {
int xyz = 0;
for (int k=15;k<args[i].length();k++) {
try {
xyz = xyz*10 + Integer.valueOf(args[i].substring(k,k+1)).intValue();
}
catch (Exception e) {
}
}
options.populationsize=xyz;
}
}
if (args[i].toLowerCase().equals("f")) {
newsystem = true;
}
if (args[i].length() >= 8) {
if (args[i].substring(0,8).toLowerCase().equals("bitmask=")) {
options.setBitMask(args[i].substring(8));
System.out.println("Setting bitmask");
}
}
}
inducer = CHC.determineInducer(options.optioninducer);
options.setDistributor(args[0], true);
System.out.println(options.getBitMaskDisplayString());
Options.LOG(3, " Population Size = "+options.populationsize+"."+CHC.ENDL);
Options.LOG(3, " Number of Attributes = "+options.getDist().getattrselectionsize()+"."+CHC.ENDL);
Options.LOG(3, " Final Generation = "+options.finalgeneration+"."+CHC.ENDL);
Options.LOG(3, " Option Inducer = "+options.optioninducer+"."+CHC.ENDL);
}
/** This method determines which inducer will be used and prepares it
* for testing data samples. Soft means the program will not be
* terminated if the inducer is not found.
* @param ind - a String of the name of the inducer.
* @return the inducer to use for this chc run. */
public static Inducer determineInducerSoft(String ind) {
Inducer result = null;
if (ind.toLowerCase ().equals (CHC.ID3)) {
result = new ID3Inducer(CHC.ID3);
}
else if (ind.toLowerCase().equals(CHC.NAIVE)) {
result = new NaiveBayesInd(CHC.NAIVE);
}
else if (ind.toLowerCase().equals(CHC.C45)) {
result = new ID3Inducer(CHC.C45);
((ID3Inducer)result).prune(true);
}
else {
result = null;
}
return result;
}
/** Same as determineInducerSoft except if the inducer is not
* found the error is treated as fatal and the program exits.
* @param ind - the string name of the inducer.
* @return the inducer to use for this chc run. */
public static Inducer determineInducer(String ind) {
Inducer result = null;
result = determineInducerSoft(ind);
if (result == null) {
LogOptions.GLOBLOG(0, "Cannot find Inducer " + ind+CHC.ENDL);
LogOptions.GLOBLOG(0, "Possible options are: "+ CHC.ID3 + ", " + CHC.NAIVE + ", " + CHC.C45 + CHC.ENDL);
LogOptions.GLOBLOG(0, "Exit status 1"+CHC.ENDL);
System.exit(1);
}
return result;
}
/** getAttrSelectionSize return the number of attributes all instances
* of this data run will contain.
* @return the attribute selection size which is equal to the number
* of attributes in this data set. */
public int getAttrSelectionSize() { return dist.getattrselectionsize(); }
// public int getCurrentTheshhold() { return currentpopulation2.getCurrentThreshhold(); }
/** runGA starts the CHC process. The Population class holds all hypothesis
* information and has all the algorithms needed to complete a generation.
* This method tells it to start and also tells it to print results.
* @param type - a string which specifies which version of population
* to use. The old type is now obsolete but hasn't been
* removed yet. */
public void runGA(String type) {
if (type.equals("old")) {
}
else if (type.equals("new")) {
currentpopulation = new Population(inducer, options);
currentpopulation.spawnPopulation();
while (currentpopulation.getGenerationNumber() <= options.finalgeneration) {
currentpopulation.nextGeneration();
}
if (options.getMask("print_all_hypothesis")) {
System.out.println("All hypothesis of this run");
currentpopulation.displayPopulation(CHC.TOTALPRINTING);
}
currentpopulation.displayFinalHypothesisFitness(options.getMask("best_overall_hypotheses"));
currentpopulation.displayAverageFitnessPerGeneration(options.getMask("average_fitness_per_generation"));
currentpopulation.displayBestSpawnedOfGeneration(options.getMask("best_Spawned_Hypothesis_of_generation"));
}
}
/** This method sorts an array of hypotheses by their fitness in
* Descending fitness order. This means the lowest fitness is first
* in the array and the highest fitness is last.
* @param hypo - the array of Hypotheses to sort.
* @return the sorted array in Descending fitness order. */
public static Hypothesis[] sortDescendingFitness(Hypothesis[] hypo) {
int indexoflowest = 0;
double lowestvalue;
if (hypo == null) {
LogOptions.GLOBLOG(0, "Invalid Array argument for Population2.sortDescendingFitness()"+CHC.ENDL);
}
else {
for (int i=0; i<hypo.length; i++) {
if (hypo[i] == null) {
}
else {
lowestvalue = hypo[i].getFitness();
indexoflowest = i;
for (int j = i; j<hypo.length; j++) {
if (hypo[j] == null ) {
}
else {
if (hypo[j].getFitness() < lowestvalue) {
lowestvalue = hypo[j].getFitness();
indexoflowest = j;
}
}
}
}
Hypothesis temp = hypo[i];
hypo[i] = hypo[indexoflowest];
hypo[indexoflowest] = temp;
}
}
return hypo;
}
/** addHypo takes an array of Hypothesis and adds to it another
* array of Hypothesis returning a single array. The Hypothesis
* are inserted in the first available slot and if none available
* the array will be enlarged by increment.
* @param hypoarray - the array to be increased
* @param addition - the array to be added to hypoarray
* @param increment - the size the array will be increased if necessary
* @return an array with the added hypos */
public static Hypothesis[] addHypo(Hypothesis[] hypoarray,
Hypothesis[] addition, int increment) {
if (increment < 1) {
increment = 1;
}
if (addition == null) {
return hypoarray;
}
else {
for (int i = 0; i < addition.length; i++) {
if (addition[i] != null) {
hypoarray = CHC.addHypo(hypoarray, addition[i], increment);
}
}
return hypoarray;
}
}
/** addHypo takes an array of Hypothesis and adds to it a single
* Hypothesis returning a single array. The Hypothesis is inserted
* in the first available slot and if none available the array
* will be enlarged by increment.
* @param hypoarray - the array to be increased
* @param addition - the Hypothesis to be added to hypoarray
* @param increment - the size the array will be increased if necessary
* @return an array with the added hypo */
public static Hypothesis[] addHypo(Hypothesis[] hypoarray,
Hypothesis addition, int increment) {
boolean hasnulls = false;
int firstnull = -1;
if ( increment < 1 ) { increment = 1; }
if (hypoarray == null) {
Hypothesis[] result = new Hypothesis[increment];
result[0] = addition;
return result;
}
else {
for (int i = 0; i < hypoarray.length; i++) {
if ( (hypoarray[i] == null) && (firstnull < 0) ) {
firstnull = i;
}
}
if (firstnull >= 0) {
hypoarray[firstnull] = addition;
return hypoarray;
}
else {
Options.LOG(7, "Increasing Hypo array size" + CHC.ENDL);
Hypothesis[] temparray = new Hypothesis[hypoarray.length + increment];
for (int j = 0; j < hypoarray.length; j++) {
temparray[j] = hypoarray[j];
}
temparray[hypoarray.length] = addition;
return temparray;
}
}
}
/** addString takes an array of Strings and adds to it a single
* String returning a single array. The String is inserted in
* the first available slot and if none available the array
* will be enlarged by increment.
* @param strarray - the array to be increased
* @param addition - the Hypothesis to be added to hypoarray
* @param increment - the size the array will be increased if necessary
* @return an array with the added hypo */
public static String[] addString(String[] strarray,
String addition, int increment) {
boolean hasnulls = false;
int firstnull = -1;
if ( increment < 1) { increment = 1; }
if (strarray == null) {
String[] result = new String[increment];
result[0] = addition;
return result;
}
else {
for (int i = 0; i < strarray.length; i++) {
if ( (strarray[i] == null) && (firstnull < 0) ) {
firstnull = i;
}
}
if (firstnull >= 0) {
strarray[firstnull] = addition;
return strarray;
}
else {
String[] temparray = new String[strarray.length + increment];
for (int j = 0; j < strarray.length; j++) {
temparray[j] = strarray[j];
}
temparray[strarray.length] = addition;
return temparray;
}
}
}
/** cleanHypo removes all null values within the given hypo so future method
* calls will not result in an accidental NullPointerExceptionError.
* @param hypo - the Hypothesis[] to be cleaned
* @return an array with the same information but no null values */
public static Hypothesis[] cleanHypo(Hypothesis[] hypo) {
int count = 0;
if (hypo == null) {
return new Hypothesis[0];
}
else {
for ( int i = 0; i < hypo.length; i++) {
if (hypo[i] == null) {
}
else {
count++;
}
}
int marker = 0;
Hypothesis[] temphypo = new Hypothesis[count];
for ( int i = 0; i < hypo.length; i++) {
if (hypo[i] == null) {
}
else {
temphypo[marker++] = hypo[i];
}
}
return temphypo;
}
}
/** this methods prepares an array of Hypos for the next stage of testing.
* @param h - an array of hypos. */
public static void prepForTest(Hypothesis[] h) {
if (h != null) {
for (int i = 0; i < h.length; i++) {
h[i].nextStage();
}
}
}
/** Because I can never remember the order of this manuver I
* went ahead and wrote it down in a single method call. */
public static int sTI(String str) {
return Integer.valueOf(str).intValue();
}
/** Same as above. */
public static double sTD(String str) {
return Double.valueOf(str).doubleValue();
}
/** Same as above. */
public static boolean sTB(String str) {
return Boolean.valueOf(str).booleanValue();
}
/** Same as above. */
public static String iTS(int i) {
return String.valueOf(i);
}
/** Same as above. */
public static String dTS(double d) {
return String.valueOf(d);
}
/** Same as above. */
public static String bTS(boolean b) {
return String.valueOf(b);
}
}
|
package dev.etna.jabberclient.fragments;
import android.app.Fragment;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.packet.Message;
import java.util.Observable;
import java.util.Observer;
import dev.etna.jabberclient.R;
import dev.etna.jabberclient.manager.ChatManager;
import dev.etna.jabberclient.manager.ContactManager;
import dev.etna.jabberclient.manager.DataManager;
import dev.etna.jabberclient.model.Contact;
import dev.etna.jabberclient.xmpp.XMPPChat;
public class ChatFragment extends Fragment
implements Observer, View.OnClickListener {
///////////////////////////////////////////////////////////////////////////
// PRIVATE ATTRIBUTES
///////////////////////////////////////////////////////////////////////////
private Button sendButton;
private EditText editText;
private TextView textView;
private Contact contact;
private XMPPChat chat;
private LinearLayout chatLayout;
private RelativeLayout relativeLayout;
private String mainLogin;
private RelativeLayout.LayoutParams layoutParams;
///////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
///////////////////////////////////////////////////////////////////////////
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
View view;
view = this.getView();
this.sendButton = (Button) view.findViewById(R.id.button);
this.editText = (EditText) view.findViewById(R.id.editText);
this.chatLayout = (LinearLayout) view.findViewById(R.id.chatLayout);
this.contact = ContactManager.getInstance().getCurrentChatContact();
this.chat = ChatManager.getInstance().getChat(contact);
this.mainLogin = ContactManager.getInstance().getMainUser().getLogin();
addListeners();
getActivity().setTitle(contact.getUsername());
loadPreviousConversation();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_chat, container, false);
}
@Override
public void update(Observable observable, Object o) {
Cursor cursor;
cursor = DataManager.getInstance().getMessageListByContact(contact);
cursor.moveToLast();
updateChatView(getMessage(cursor));
}
@Override
public void onClick(View view)
{
Message message = new Message();
message.setBody(editText.getText().toString());
try {
chat.sendMessage(message);
} catch (SmackException.NotConnectedException e) {
Log.i("ERR", "Error Delivering block");
}
editText.setText(null);
}
///////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
///////////////////////////////////////////////////////////////////////////
private void updateChatView(Message message) {
Context context;
context = this.getView().getContext();
relativeLayout = new RelativeLayout(context);
textView = new TextView(context);
layoutParams = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
formatTextViewChat(message.getTo().equals(mainLogin));
textView.setText(message.getBody());
relativeLayout.addView(textView, layoutParams);
this.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
chatLayout.addView(relativeLayout);
}
});
}
private void formatTextViewChat(boolean isMainUser) {
Context context;
context = this.getView().getContext();
if (isMainUser) {
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
textView.setBackgroundColor(ContextCompat.getColor(context,
R.color.colorLightGrey));
} else {
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textView.setBackgroundColor(ContextCompat.getColor(context,
R.color.colorLightShaded));
}
}
private void addListeners() {
this.sendButton.setOnClickListener(this);
this.chat.addObserver(this);
}
private Message getMessage(Cursor cursor) {
Message message;
message = new Message();
message.setFrom(cursor.getString(1));
message.setTo(cursor.getString(2));
message.setBody(cursor.getString(3));
return message;
}
private void loadPreviousConversation() {
Cursor cursor;
cursor = DataManager.getInstance().getMessageListByContact(contact);
cursor.moveToFirst();
while (cursor.moveToNext()) {
updateChatView(getMessage(cursor));
}
}
}
|
package util;
import model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
/**
* IDE : IntelliJ IDEA
* Created by minho on 2018. 9. 29..
*/
public class UserUtils {
private static final Logger log = LoggerFactory.getLogger(UserUtils.class);
public static boolean checkPassword(User user, User userFromDB) {
return user.getPassword().equals(userFromDB.getPassword());
}
public static boolean checkEmptyItem(User user) {
return user.getName() != null &&
user.getPassword() != null &&
user.getUserId() != null &&
user.getEmail() != null;
}
public static User user(Map<String, String> params) {
User user = new User();
params.keySet()
.forEach(key -> callSetter(user, key, params.get(key)));
return user;
}
private static void callSetter(User user, String paramKey, String paramValue) {
Arrays.stream(user.getClass().getMethods())
.filter(method -> method.getName().startsWith("set"))
.filter(method -> method.getName().substring(3).toLowerCase().equals(paramKey.toLowerCase()))
.findFirst()
.ifPresent(method -> call(method, user, paramValue));
}
private static void call(Method method, Object object, String param) {
try {
method.invoke(object, param);
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
|
package fr.lteconsulting.servlet.vue;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import fr.lteconsulting.servlet.DataAccessServlet;
import fr.lteconsulting.servlet.Rendu;
public class ListeCartesServlet extends DataAccessServlet
{
private static final long serialVersionUID = 1L;
protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
String nomUtilisateur = (String) request.getSession().getAttribute( "nom" );
if( nomUtilisateur == null )
{
response.sendRedirect( "home" );
return;
}
Rendu.listeCartes( "Liste des cartes à jouer", getData().getCartes(), true, true, getServletContext(), request, response );
}
}
|
package com.example.demo.controller;
import com.example.demo.dto.*;
import com.example.demo.entity.*;
import com.example.demo.exception.CustomException;
import com.example.demo.repository.*;
import com.example.demo.security.TokenProvider;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;
@RestController
public class APIController extends AuthorizedResource{
@Autowired
private TokenProvider tokenProvider;
@Autowired
private UserService userService;
@Autowired
private GroupRepository groupRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private ServiceRepository serviceRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private TeamRepository teamRepository;
@Autowired
private TeamHistoryRepository teamHistoryRepository;
@Autowired
private TeamTestRepository teamTestRepository;
@Autowired
private TeamHistoryTestRepository teamHistoryTestRepository;
@GetMapping(path = "/")
public String welcome() {
Optional<Team> team = teamRepository.findById(1L);
Team team1 = new Team("test");
teamRepository.save(team1);
TeamHistory teamHistory = new TeamHistory(team1, "test");
teamHistoryRepository.save(teamHistory);
return "welcome";
}
@GetMapping(path = "/test")
public String welcomeTest() {
Optional<TeamTest> team = teamTestRepository.findById(1L);
TeamTest team1 = new TeamTest("test");
teamTestRepository.save(team1);
TeamHistoryTest teamHistoryTest = new TeamHistoryTest(team1, "test");
teamHistoryTestRepository.save(teamHistoryTest);
team1.setTeamHistoryTestId(teamHistoryTest.getId());
teamTestRepository.save(team1);
return "welcome";
}
@PostMapping(path = "/api/users/signup")
public ResponseEntity signup(@RequestBody SignupRequest signupRequest) {
User user = new User();
user.setEmail(signupRequest.getEmail());
user.setName(signupRequest.getName());
user.setPassword(signupRequest.getPassword());
user.setUsername(signupRequest.getUsername());
userService.signup(user);
String token = tokenProvider.generateAccessToken(user.getUsername()).getTokenValue();
String refreshToken = tokenProvider.generateRefreshToken(user.getUsername()).getTokenValue();
HttpHeaders responseHeaders = new HttpHeaders();
HttpCookie httpTokenCookie = ResponseCookie.from("accessToken", token).maxAge(Duration.ofSeconds(TokenProvider.tokenExpirationMsec / 1000)).httpOnly(true).path("/").build();
HttpCookie httpRefreshTokenCookie = ResponseCookie.from("refreshToken", refreshToken).maxAge(Duration.ofSeconds(TokenProvider.refreshTokenExpirationMsec / 1000)).httpOnly(true).path("/").build();
responseHeaders.add(HttpHeaders.SET_COOKIE, httpTokenCookie.toString());
responseHeaders.add(HttpHeaders.SET_COOKIE, httpRefreshTokenCookie.toString());
Map response = new HashMap<String, String>();
response.put("accessToken", token);
response.put("refreshToken", refreshToken);
return ResponseEntity.ok().headers(responseHeaders).body(response);
}
@PostMapping(path = "/api/users/login")
public ResponseEntity login(@RequestBody LoginRequest loginRequest) {
System.out.println(loginRequest.getUsername());
System.out.println(loginRequest.getPassword());
System.out.println(passwordEncoder.encode(loginRequest.getPassword()));
userService.signin(loginRequest.getUsername(), loginRequest.getPassword());
String token = tokenProvider.generateAccessToken(loginRequest.getUsername()).getTokenValue();
String refreshToken = tokenProvider.generateRefreshToken(loginRequest.getUsername()).getTokenValue();
HttpHeaders responseHeaders = new HttpHeaders();
HttpCookie httpTokenCookie = ResponseCookie.from("accessToken", token).maxAge(Duration.ofSeconds(TokenProvider.tokenExpirationMsec / 1000)).httpOnly(true).path("/").build();
HttpCookie httpRefreshTokenCookie = ResponseCookie.from("refreshToken", refreshToken).maxAge(Duration.ofSeconds(TokenProvider.refreshTokenExpirationMsec / 1000)).httpOnly(true).path("/").build();
responseHeaders.add(HttpHeaders.SET_COOKIE, httpTokenCookie.toString());
responseHeaders.add(HttpHeaders.SET_COOKIE, httpRefreshTokenCookie.toString());
Map response = new HashMap<String, String>();
response.put("accessToken", token);
response.put("refreshToken", refreshToken);
response.put("status", "ok");
return ResponseEntity.ok().headers(responseHeaders).body(response);
}
@PostMapping(path ="/api/users/token/refresh")
public ResponseEntity tokenRefresh(@RequestBody RefreshTokenRequest refreshTokenRequest) {
String refreshToken = userService.refresh(refreshTokenRequest.getToken());
String token = tokenProvider.generateAccessToken(tokenProvider.getUsernameFromToken(refreshToken)).getTokenValue();
HttpHeaders responseHeaders = new HttpHeaders();
HttpCookie httpTokenCookie = ResponseCookie.from("accessToken", token).maxAge(Duration.ofSeconds(TokenProvider.tokenExpirationMsec / 1000)).httpOnly(true).path("/").build();
HttpCookie httpRefreshTokenCookie = ResponseCookie.from("refreshToken", refreshToken).maxAge(Duration.ofSeconds(TokenProvider.refreshTokenExpirationMsec / 1000)).httpOnly(true).path("/").build();
responseHeaders.add(HttpHeaders.SET_COOKIE, httpTokenCookie.toString());
responseHeaders.add(HttpHeaders.SET_COOKIE, httpRefreshTokenCookie.toString());
Map response = new HashMap<String, String>();
response.put("accessToken", token);
response.put("refreshToken", refreshToken);
return ResponseEntity.ok().headers(responseHeaders).body(response);
}
@GetMapping(path ="/api/currentUser")
public ResponseEntity me(HttpServletRequest req) {
Map response = new HashMap<String, String>();
User user = userService.me(req);
List<Map> groups = new ArrayList<>();
for (Group group : user.getGroups()) {
Map groupData = new HashMap<String, String>();
groupData.put("id", group.getId());
groupData.put("name", group.getName());
groupData.put("description", group.getDescription());
groups.add(groupData);
}
response.put("name", user.getName());
response.put("email", user.getEmail());
response.put("roles", user.getRoles());
response.put("groups", groups);
return ResponseEntity.ok().body(response);
}
@GetMapping(path ="/api/groups")
public ResponseEntity groups(Authentication auth) {
CustomUserDetails customUserDetails = (CustomUserDetails) auth.getPrincipal();
User user = userRepository.findById(customUserDetails.getUser().getId()).orElseThrow(() -> new CustomException("Invalid token", HttpStatus.UNAUTHORIZED));
List<Long> ids = user.getGroups().stream().map(item -> item.getId()).collect(Collectors.toList());
List<Group> groups = groupRepository.findByIdIn(ids).orElseThrow(() -> new CustomException("Invalid token", HttpStatus.UNAUTHORIZED));
List<Group> srGroups = groupRepository.findAllByServiceRequest().orElseThrow(() -> new CustomException("Invalid token", HttpStatus.UNAUTHORIZED));
System.out.println(srGroups.size());
System.out.println(srGroups.get(0).getServices());
return ResponseEntity.ok().body("");
}
@GetMapping(path ="/api/groups/{groupId}/services")
public ResponseEntity groupService(@PathVariable Long groupId, Authentication auth) {
CustomUserDetails customUserDetails = (CustomUserDetails) auth.getPrincipal();
User user = userRepository.findById(customUserDetails.getUser().getId()).orElseThrow(() -> new CustomException("Invalid token", HttpStatus.UNAUTHORIZED));
List<Group> groups = user.getGroups().stream().filter(item -> item.getId().equals(groupId)).collect(Collectors.toList());
if (groups.size() == 0) {
throw new CustomException("Resource Not found", HttpStatus.NOT_FOUND);
}
List<Map> services = new ArrayList<>();
for (Service service : groups.get(0).getServices()) {
Map serviceData = new HashMap<String, String>();
serviceData.put("id", service.getId());
serviceData.put("accessUri", service.getAccessUri());
serviceData.put("isActivated", service.getIsActivated());
services.add(serviceData);
}
Map response = new HashMap<String, String>();
response.put("id", groups.get(0).getId());
response.put("name", groups.get(0).getName());
response.put("description", groups.get(0).getDescription());
response.put("services", services);
return ResponseEntity.ok().body(response);
}
@PostMapping(path ="/api/groups/{id}/services")
@Transactional
public ResponseEntity createService(@PathVariable Long id, Authentication auth) {
//service 추가
//group_service 추가
Group group = groupRepository.findById(id).orElseThrow(() -> new CustomException("Resource Not found", HttpStatus.NOT_FOUND));
Service service = new Service("test", 1);
group.addService(service);
//serviceRepository.save(service);
//group.addService(service);
groupRepository.save(group);
return ResponseEntity.ok().body("");
}
@GetMapping(path ="/api/groups/{groupId}/services/{serviceId}")
public ResponseEntity getService(@PathVariable Long groupId, @PathVariable Long serviceId, Authentication auth) {
CustomUserDetails customUserDetails = (CustomUserDetails) auth.getPrincipal();
User user = userRepository.findById(customUserDetails.getUser().getId()).orElseThrow(() -> new CustomException("Invalid token", HttpStatus.UNAUTHORIZED));
Group group = user.getGroups().stream().filter(item -> item.getId().equals(groupId)).findFirst().orElseThrow(() -> new CustomException("Invalid token", HttpStatus.UNAUTHORIZED));
Service service = group.getServices().stream().filter(item -> item.getId().equals(serviceId)).findFirst().orElseThrow(() -> new CustomException("Invalid token", HttpStatus.UNAUTHORIZED));
System.out.println(service.getGroups());
List<Service> services = serviceRepository.findByGroupsIn(user.getGroups().stream().collect(Collectors.toList()));
System.out.println(services.size());
return ResponseEntity.ok().body("");
}
@GetMapping(path ="/api/test")
public String test() {
return "good";
}
}
|
package pl.finsys.springJpa;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
@Repository("carDao")
public class CarDaoImpl implements CarDao {
protected EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public List<Car> getCars() throws DataAccessException {
Query query = getEntityManager().createQuery("select c from Car c");
List<Car> resultList = query.getResultList();
return resultList;
}
public Car getCar(Long carId) throws DataAccessException {
return getEntityManager().find(Car.class, carId);
}
@Transactional()
@Override
public void save(Car car) throws DataAccessException {
entityManager.persist(car);
}
} |
package bootcamp.test.filereaders.excelreader;
public class TestcaseBO {
private String name;
private String pageName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
@Override
public String toString() {
return "TestcaseBO [name=" + name + ", pageName=" + pageName + "]";
}
}
|
package com.alexkirillov.alitabot.models.logging;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
//TODO !!!Test Concept!!!
public class MessageLog {
private final String messageDate;
private final String user_name;
private final long telegram_user_id;
private final String user_first_name;
private final String user_last_name;
private final String message_in;
private final String response;
public MessageLog(String user_name, long telegram_user_id, String user_first_name, String user_last_name, String message_in, String response) {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
this.messageDate = dateFormat.format(new Date());
this.user_name = user_name;
this.telegram_user_id = telegram_user_id;
this.user_first_name = user_first_name;
this.user_last_name = user_last_name;
this.message_in = message_in;
this.response = response;
}
public String getMessageDate() {
return messageDate;
}
public String getUser_name() {
return user_name;
}
public long getUser_id() {
return telegram_user_id;
}
public String getUser_first_name() {
return user_first_name;
}
public String getUser_last_name() {
return user_last_name;
}
public String getMessage_in() {
return message_in;
}
public String getResponse() {
return response;
}
@Override
public String toString(){
return "-----------------------------------"+ messageDate + "From: "+user_name+", ID: "+telegram_user_id
+"Cred: "+ user_first_name+" "+user_last_name
+ "User's Message: '"+message_in+"'"+"Bot Response Code: '"+response+"'";
}
public DBObject toDBObject(){
return new BasicDBObject("messageDate", messageDate).append("username", user_name)
.append("userid", telegram_user_id).append("firstname", user_first_name)
.append("lastname", user_last_name);
}
}
|
package bartender.bardatabase;
public class BarStorageInfo {
/**
* An object which represents information about a single type of shoe in the store
*/
private String item;
private int amountOnStorage;
private int discountedAmount;
/**
*
* @param shoeType the type of the shoe
* @param amountOnStorage the number of shoes of shoeType currently on the storage
* @param discountedAmount amount of shoes in this storage that can be sale in a discounted price
*/
public BarStorageInfo(String item, int amountOnStorage, int discountedAmount) {
this.item = item;
this.amountOnStorage = amountOnStorage;
this.discountedAmount = discountedAmount;
}
public String getItem() {
return item;
}
public int getAmountOnStorage() {
return amountOnStorage;
}
public int getDiscountedAmount() {
return discountedAmount;
}
public void setDiscountedAmount(int discountedAmount) {
this.discountedAmount = discountedAmount;
}
public void setAmountOnStorage(int AmountOnStorage) {
this.amountOnStorage = AmountOnStorage;
}
public void printDetails(){
System.out.println("shoeType = " + this.item);
System.out.println("amountOnStorage = " + this.amountOnStorage);
System.out.println("discountedAmount = " + this.discountedAmount);
System.out.println();
}
} |
package leetcode_arrays_strings;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Scanner;
import random_generator.Random_String;
/**
* Question 575: Distribute Candies -- Given an integer array with even length,
* where different numbers in this array represent different kinds of candies.
* Each number means one candy of the corresponding kind. You need to distribute
* these candies equally in number to brother and sister. Return the maximum
* number of kinds of candies the sister could gain.
*
* Note: 1. The length of the given array is in range [2, 10,000], and will be
* even. 2. The number in given array is in range [-100,000, 100,000].
*
* @author chenfeng
*
*/
public class DistributeCandies_575 {
public static void main(String[] args) throws IOException {
// int numOfStrings = 10000;
// int numLength = 5;
// String randomNumberFileName = "random_numbers.txt";
//
// // create random number array
// Random_String rs = new Random_String(numOfStrings, numLength,
// Random_String.generateType.NUMERIC,
// randomNumberFileName);
//
// Scanner scanNumber = new Scanner(new File(randomNumberFileName));
// int[] candies = new int[numOfStrings];
// int i = 0;
//
// while (scanNumber.hasNext()) {
// candies[i] = Integer.parseInt(scanNumber.nextLine());
// i++;
// }
// scanNumber.close();
int[] candies = { 1, 1, 6, 6, 6, 6 };
// compute result
int result = distributeCandies(candies);
System.out.println("result is: " + result);
}
public static int distributeCandies(int[] candies) {
HashSet<Integer> hs = new HashSet<>();
for (int c : candies) {
hs.add(c);
}
return Math.min(hs.size(), candies.length / 2);
}
}
|
/*
* *********************************************************
* Copyright (c) 2019 @alxgcrz All rights reserved.
* This code is licensed under the MIT license.
* Images, graphics, audio and the rest of the assets be
* outside this license and are copyrighted.
* *********************************************************
*/
package com.codessus.ecnaris.ambar.fragments;
import android.app.Fragment;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.codessus.ecnaris.ambar.R;
import com.codessus.ecnaris.ambar.activities.MainActivity;
import com.codessus.ecnaris.ambar.dialogs.ComprarItemDialogFragment;
import com.codessus.ecnaris.ambar.dialogs.VenderItemDialogFragment;
import com.codessus.ecnaris.ambar.helpers.AmbarManager;
import com.codessus.ecnaris.ambar.models.XML.Commerce;
import com.codessus.ecnaris.ambar.models.personaje.Equipo;
import com.codessus.ecnaris.ambar.models.personaje.Personaje;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* Pantalla de comercio
*/
public class CommerceFragment extends Fragment {
// NAVEGACIÓN
@BindView(R.id.include_navigation_next)
ImageButton nextImageButton;
// TextView que muestra información general
@BindView(R.id.fragment_commerce_textView_info)
TextView textViewGlobalInfo;
// TABS
@BindViews({R.id.fragment_commerce_img_tab_armor, R.id.fragment_commerce_img_tab_weapons,
R.id.fragment_commerce_img_tab_consumable, R.id.fragment_commerce_img_tab_essencials})
List<ImageButton> tabs;
// Windows
@BindViews({R.id.fragment_commerce_img_tab_mercader, R.id.fragment_commerce_img_tab_inventario})
List<ImageView> windows;
// ITEMS
@BindViews({R.id.fragment_commerce_equipo_0, R.id.fragment_commerce_equipo_1, R.id.fragment_commerce_equipo_2,
R.id.fragment_commerce_equipo_3, R.id.fragment_commerce_equipo_4, R.id.fragment_commerce_equipo_5})
List<ImageButton> itemsGrill;
// Elementos de la descripción
@BindView(R.id.fragment_commerce_textView_name)
TextView textViewItemName;
@BindView(R.id.fragment_commerce_textView_description)
TextView textViewItemDescription;
@BindView(R.id.fragment_commerce_img_item)
ImageView imgItem;
@BindView(R.id.fragment_commerce_textView_status)
TextView textViewStatusItem;
@BindView(R.id.fragment_commerce_textView_actions_price)
TextView priceItem;
@BindView(R.id.fragment_commerce_textView_money)
TextView textViewMoneyPersonaje;
@BindView(R.id.fragment_commerce_textView_actions_text)
TextView textViewactionText;
@BindView(R.id.fragment_commerce_img_mejoras_orbe_1)
ImageView orbeMejorasPrimary;
@BindView(R.id.fragment_commerce_textView_mejoras_value_1)
TextView textViewMejorasPrimary;
@BindView(R.id.fragment_commerce_img_mejoras_orbe_2)
ImageView orbeMejorasSecondary;
@BindView(R.id.fragment_commerce_textView_mejoras_value_2)
TextView textViewMejorasSecondary;
// Botón para realizar acciones sobre los objetos como por ejemplo comprar o vender
//@BindView(R.id.fragment_commerce_button_actions)
//Button buttonActions;
@BindView(R.id.fragment_commerce_layout_actions)
LinearLayout layoutAction;
// Paginación
@BindView(R.id.fragment_commerce_img_navegation_left)
ImageView arrowLeftNav;
@BindView(R.id.fragment_commerce_img_navegation_right)
ImageView arrowRightNav;
private Unbinder unbinder;
// Variables para gestionar la pantalla
private ArrayList<Equipo> equipamientoPorTipo;
private HashMap<Integer, ArrayList<Equipo>> equipamientoPorTipoPaginado;
private View currentTab;
private View currentWindowTab;
private View rootView;
private int currentPage;
private Equipo currentItemSelected;
// Page que contiene los datos
private Commerce page;
// Personaje
private Personaje personaje;
// --- CONSTRUCTOR --- //
public CommerceFragment() {
// Required empty public constructor
}
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState ) {
// Inflate the layout for this fragment
rootView = inflater.inflate( R.layout.fragment_commerce, container, false );
// Inyectar las Views
unbinder = ButterKnife.bind( this, rootView );
// Mostrar el botón 'NEXT'
nextImageButton.setVisibility( View.VISIBLE );
// Recuperar el personaje
personaje = AmbarManager.instance().getPersonaje();
//Recuperar la página
if ( personaje != null ) {
page = (Commerce) AmbarManager.instance().readPage( personaje.getPage() );
// Dinero del personaje
textViewMoneyPersonaje.setText( String.valueOf( personaje.getMonedasTotales() ) );
}
// Por defecto seleccionamos la ventada del 'MERCADER'
View mercaderWindowTab = rootView.findViewById( R.id.fragment_commerce_img_tab_mercader );
if ( mercaderWindowTab != null ) {
windowSelected( mercaderWindowTab );
}
return rootView;
}
/**
* Método llamado cuando el usuario cambie de window entre la pantalla de compra de items
* y la pantalla de venta de items
*
* @param window selected
*/
@OnClick({R.id.fragment_commerce_img_tab_mercader, R.id.fragment_commerce_img_tab_inventario})
public void windowSelected( View window ) {
// Window seleccionada
currentWindowTab = window;
// Animación de la pestaña
for ( ImageView elem : windows ) {
elem.setSelected( elem.getId() == window.getId() );
elem.animate().translationY( elem.isSelected() ? -30f : 0f ).setDuration( 400 ).start();
}
// Por defecto seleccionamos la primera tab 'ARMOR' independientemente de la window en que nos encontremos
View armorTab = rootView.findViewById( R.id.fragment_commerce_img_tab_armor );
if ( armorTab != null ) {
tabSelected( armorTab );
}
}
/**
* Método que se ejecuta cuando el usuario seleccione una pestaña o al cargar por primera vez el
* inventario. Se encarga de resetear lo que hubiera en pantalla, recuperar los items que tiene
* el personaje y rellenar la parrilla.
*
* @param tab selected
*/
@OnClick({R.id.fragment_commerce_img_tab_armor, R.id.fragment_commerce_img_tab_weapons,
R.id.fragment_commerce_img_tab_consumable, R.id.fragment_commerce_img_tab_essencials})
public void tabSelected( View tab ) {
// Tab seleccionada
currentTab = tab;
// Animación de la pestaña
for ( ImageButton elem : tabs ) {
elem.setSelected( elem.getId() == tab.getId() );
elem.animate().translationY( elem.isSelected() ? 50f : 0f ).setDuration( 500 ).start();
}
// Previamente a la actualización de la parrilla, se resetea tanto la parrilla como la descripción que hubiera de un item anterior
resetGrill();
resetItemDescription();
// Si el usuario cambia de tab, mostramos la primera página en el caso de tener paginación
currentPage = 1;
// Actualizar parrilla y mostrar mensajes en la parte superior, indicando si hay objetos o no
if ( currentWindowTab.getId() == R.id.fragment_commerce_img_tab_mercader ) {
updateGrillMercader( currentTab, currentPage );
textViewGlobalInfo.setText( R.string.fragment_commerce_textView_global_mercader_items );
} else {
updateGrillInventario( currentTab, currentPage, true );
textViewGlobalInfo.setText( R.string.fragment_commerce_textView_global_inventario );
}
// Mostrar las flechas de paginación
arrowsPaginationVisibility();
// if (equipamientoPorTipoPaginado != null && equipamientoPorTipoPaginado.size() > 1) {
// arrowRightNav.setVisibility(View.VISIBLE);
// }
}
/**
* Método que se ejecuta cuando el usuario selecciona una casilla que contiene un item
*
* @param casilla selected
*/
@OnClick({R.id.fragment_commerce_equipo_0, R.id.fragment_commerce_equipo_1, R.id.fragment_commerce_equipo_2,
R.id.fragment_commerce_equipo_3, R.id.fragment_commerce_equipo_4, R.id.fragment_commerce_equipo_5})
public void itemSelected( View casilla ) {
// Recuperar el item a partir del nombre almacenado en el tag
String tag = (String) casilla.getTag();
// Sólo si tiene tag la marcamos como seleccionada. De esta forma evitamos que se seleccionen casillas que no contienen item,
// ya que al hacer un reset de la parrilla también se eliminan las tags
if ( StringUtils.isNotBlank( tag ) ) {
// Resetear los valores antiguos de la descripción
resetItemDescription();
// Marcamos la casilla como seleccionada, lo que cambiará el fondo
for ( ImageButton elem : itemsGrill ) {
elem.setSelected( elem.getId() == casilla.getId() );
}
// Buscar el item en función de la ventana seleccionada y actualizar la parrilla
Equipo itemSeleccionado;
if ( currentWindowTab.getId() == R.id.fragment_commerce_img_tab_mercader ) {
// Buscar item
itemSeleccionado = this.page.getEquipoEnVenta().get( tag );
// Actualizar la parrilla
updateGrillMercader( currentTab, currentPage );
} else {
// Buscar item
itemSeleccionado = personaje.getInventario().getItemByName( tag );
// Actualizar la parrilla
updateGrillInventario( currentTab, currentPage, false );
}
// Completar la descripción mostrada
if ( itemSeleccionado != null ) {
// Guardar el item seleccionado
currentItemSelected = itemSeleccionado;
// Actualizar el nombre
textViewItemName.setText( itemSeleccionado.getHumanReadableName() );
// Actualizar la descripción
textViewItemDescription.setText( itemSeleccionado.getDescription() );
// Actualizar la imagen
imgItem.setImageDrawable( AmbarManager.instance().getDrawableByName( itemSeleccionado.getImage(), getActivity().getPackageName() ) );
// Actualizar los atributos que mejora
updateEstadisticas( itemSeleccionado );
// Actualizar el botón de acción
if ( currentWindowTab.getId() == R.id.fragment_commerce_img_tab_mercader ) {
if ( personaje.getInventario().isEquipable( itemSeleccionado )
|| currentTab.getId() == R.id.fragment_commerce_img_tab_consumable
|| currentTab.getId() == R.id.fragment_commerce_img_tab_essencials ) {
// Precio de venta del item por parte del vendedor
priceItem.setText( String.valueOf( personaje.getPrecioCompraItem( itemSeleccionado ) ) );
// Acción
textViewactionText.setText( R.string.fragment_commerce_button_actions_comprar );
// Mostrar el layout de la acción
layoutAction.setVisibility( View.VISIBLE );
} else {
textViewStatusItem.setText( R.string.fragment_commerce_textView_status_no_equipable );
}
} else {
if ( !itemSeleccionado.isEsencial() ) {
// Precio de venta del item por parte del pesonaje
priceItem.setText( String.valueOf( personaje.getPrecioVentaItem( itemSeleccionado ) ) );
// Acción
textViewactionText.setText( R.string.fragment_commerce_button_actions_vender );
// Mostrar el layout de la acción
layoutAction.setVisibility( View.VISIBLE );
} else {
textViewStatusItem.setText( R.string.fragment_commerce_textView_status_no_vendible );
}
}
}
}
}
/**
* Método que se ejecuta cuando el usuario pulsa en el botón '[COMPRAR]' o '[VENDER]'
*
* @param button selected
*/
@OnClick(R.id.fragment_commerce_layout_actions)
public void buttonActionSelected( View button ) {
int price = Integer.valueOf( priceItem.getText().toString() );
if ( currentWindowTab.getId() == R.id.fragment_commerce_img_tab_mercader ) {
if ( price > personaje.getMonedasTotales() ) {
Toast.makeText( getActivity().getApplicationContext(), R.string.fragment_commerce_toast_no_money, Toast.LENGTH_SHORT ).show();
} else {
// Ventana de confirmación de la compra. Si el usuario confirma la venta, se ejecuta el método onComprarItemDialogPositiveClick()
ComprarItemDialogFragment dialogFragment = new ComprarItemDialogFragment();
// Nombre del item
Bundle args = new Bundle();
args.putString( "itemName", currentItemSelected.getHumanReadableName() );
args.putInt( "itemPrice", price );
dialogFragment.setArguments( args );
// Mostrar el Dialog
dialogFragment.show( getFragmentManager(), "" );
}
} else {
// Ventana de confirmación de la venta. Si el usuario confirma la venta, se ejecuta el método onVenderItemDialogPositiveClick()
VenderItemDialogFragment dialogFragment = new VenderItemDialogFragment();
// Nombre del item
Bundle args = new Bundle();
args.putString( "itemName", currentItemSelected.getHumanReadableName() );
args.putInt( "itemPrice", price );
dialogFragment.setArguments( args );
// Mostrar el Dialog
dialogFragment.show( getFragmentManager(), "" );
}
}
/**
* El usuario confirma la venta del item
*/
public void onVenderItemDialogPositiveClick() {
// Vender el item
personaje.sellItem( currentItemSelected );
// Actualizar el textView que muestra las monedas
textViewMoneyPersonaje.setText( String.valueOf( personaje.getMonedasTotales() ) );
// Dado que hay un item menos, hay que resetear descripción y parrilla y actualizar la parrilla
resetItemDescription();
resetGrill();
updateGrillInventario( currentTab, currentPage, true );
// Mostrar un Toast de info
String vendido = String.format( getString( R.string.fragment_commerce_toast_vendido ), currentItemSelected.getHumanReadableName(), Integer.valueOf( priceItem.getText().toString() ) );
Toast.makeText( getActivity().getApplicationContext(), vendido, Toast.LENGTH_SHORT ).show();
// Por cortesía volvemos a mostrar el texto global de info
textViewGlobalInfo.setText( R.string.fragment_commerce_textView_global_inventario );
// Actualizar la visibilidad de las flechas de paginación ya que hemos resetado la parrilla
arrowsPaginationVisibility();
}
/**
* El usuario confirma la compra del item
*/
public void onComprarItemDialogPositiveClick() {
// Comprar el item
personaje.buyItem( currentItemSelected );
// Actualizar el textView que muestra las monedas
textViewMoneyPersonaje.setText( String.valueOf( personaje.getMonedasTotales() ) );
// Mostrar un Toast de info
String comprado = String.format( getString( R.string.fragment_commerce_toast_comprado ), currentItemSelected.getHumanReadableName(), Integer.valueOf( priceItem.getText().toString() ) );
Toast.makeText( getActivity().getApplicationContext(), comprado, Toast.LENGTH_SHORT ).show();
}
/**
* Actualiza o completa la grilla de objetos teniendo en cuenta si hubiera o no paginación.
* Para actualizar la grilla recupera los objetos del personaje.
*
* @param currentTab pestaña actual
* @param page to show
*/
private void updateGrillMercader( View currentTab, int page ) {
// Recuperar los items
switch ( currentTab.getId() ) {
case R.id.fragment_commerce_img_tab_weapons:
equipamientoPorTipo = this.page.getAllArmasEnVenta();
break;
case R.id.fragment_commerce_img_tab_consumable:
equipamientoPorTipo = this.page.getAllConsumiblesEnVenta();
break;
case R.id.fragment_commerce_img_tab_essencials:
equipamientoPorTipo = this.page.getAllEsencialesEnVenta();
break;
default:
equipamientoPorTipo = this.page.getAllArmadurasEnVenta();
break;
}
if ( equipamientoPorTipo.size() > 0 ) {
// Paginar los items recuperados
equipamientoPorTipoPaginado = personaje.getInventario().getBolsaPaginada( equipamientoPorTipo );
// Seleccionar la página a mostrar
ArrayList<Equipo> equipamientoPorTipoToShow = equipamientoPorTipoPaginado.get( page );
// Recorremos el array que no contendrá más de 6 items y actualizamos la parrilla
int i = 0;
for ( Equipo equipo : equipamientoPorTipoToShow ) {
// Colocar la imagen del objeto en la parrilla
itemsGrill.get( i ).setImageDrawable( AmbarManager.instance().getDrawableByName( equipo.getImage(), getActivity().getPackageName() ) );
// Para poder determinar que objeto contiene un item de los 6 de que dispone la parrilla, guardamos su name en la tag
// A partir de la tag, podremos recuperar el item buscándolo por ese nombre en todas las bolsas.
itemsGrill.get( i ).setTag( equipo.getName() );
// Colocar la imagen de fondo que se corresponda con el objeto (equipado, no equipado y/o no equipable)
if ( itemsGrill.get( i ).isSelected() ) {
if ( personaje.getInventario().isEquipable( equipo ) || equipo.isConsumible() || equipo.isEsencial() ) {
itemsGrill.get( i ).setBackground( AmbarManager.instance().getDrawable( R.drawable.inventario_fondo_item_selected ) );
} else {
itemsGrill.get( i ).setBackground( AmbarManager.instance().getDrawable( R.drawable.inventario_fondo_item_selected_no_equipable ) );
}
} else {
if ( personaje.getInventario().isEquipable( equipo ) || equipo.isConsumible() || equipo.isEsencial() ) {
itemsGrill.get( i ).setBackground( AmbarManager.instance().getDrawable( R.drawable.inventario_fondo_item ) );
} else {
itemsGrill.get( i ).setBackground( AmbarManager.instance().getDrawable( R.drawable.inventario_fondo_item_no_equipable ) );
}
}
// Actualizar el contador
i++;
}
}
}
/**
* Actualiza o completa la grilla de objetos teniendo en cuenta si hubiera o no paginación.
* Para actualizar la grilla recupera los objetos del personaje.
*
* @param currentTab pestaña actual
* @param page to show
* @param update true para indicar que queremos que recupere los items del personaje o false
* si debe usar los que ya tenemos
*/
private void updateGrillInventario( View currentTab, int page, boolean update ) {
if ( update ) {
equipamientoPorTipo = new ArrayList<>();
equipamientoPorTipoPaginado = new HashMap<>();
// Recuperamos los objetos de la bolsa correspondiente
switch ( currentTab.getId() ) {
case R.id.fragment_commerce_img_tab_weapons:
equipamientoPorTipo = personaje.getInventario().getBolsaArmas();
break;
case R.id.fragment_commerce_img_tab_consumable:
equipamientoPorTipo = personaje.getInventario().getBolsaConsumibles();
break;
case R.id.fragment_commerce_img_tab_essencials:
equipamientoPorTipo = personaje.getInventario().getBolsaEsencialesComerciables();
break;
default:
equipamientoPorTipo = personaje.getInventario().getBolsaArmaduras();
break;
}
}
if ( equipamientoPorTipo.size() > 0 ) {
// Paginar los items recuperados
if ( update ) {
equipamientoPorTipoPaginado = personaje.getInventario().getBolsaPaginada( equipamientoPorTipo );
}
/* Seleccionar la página a mostrar.
Dado que este método puede ser llamado al vender items, existe la posibilidad de que el item vendido sea el último de la pestaña y
por tanto hay que comprobar la page */
ArrayList<Equipo> equipamientoPorTipoAMostrar;
if ( equipamientoPorTipoPaginado.size() < page ) {
// Actualizar la página actual
currentPage = page - 1;
// Coger la pestaña a la que apunta ahora currentPage
equipamientoPorTipoAMostrar = equipamientoPorTipoPaginado.get( currentPage );
} else {
equipamientoPorTipoAMostrar = equipamientoPorTipoPaginado.get( page );
}
// Recorremos el array que no contendrá más de 6 items y actualizamos la parrilla
int i = 0;
for ( Equipo equipo : equipamientoPorTipoAMostrar ) {
// Colocar la imagen del objeto en la parrilla
itemsGrill.get( i ).setImageDrawable( AmbarManager.instance().getDrawableByName( equipo.getImage(), getActivity().getPackageName() ) );
// Para poder determinar que objeto contiene un item de los 6 de que dispone la parrilla, guardamos su name en la tag
// A partir de la tag, podremos recuperar el item buscándolo por ese nombre en todas las bolsas.
itemsGrill.get( i ).setTag( equipo.getName() );
// Colocar la imagen de fondo que se corresponda con el objeto (equipado, no equipado y/o no equipable)
if ( itemsGrill.get( i ).isSelected() ) {
if ( equipo.isEquipado() ) {
itemsGrill.get( i ).setBackground( AmbarManager.instance().getDrawable( R.drawable.inventario_fondo_item_selected_equipado ) );
} else if ( personaje.getInventario().isEquipable( equipo ) || equipo.isConsumible() || equipo.isEsencial() ) {
itemsGrill.get( i ).setBackground( AmbarManager.instance().getDrawable( R.drawable.inventario_fondo_item_selected ) );
} else {
itemsGrill.get( i ).setBackground( AmbarManager.instance().getDrawable( R.drawable.inventario_fondo_item_selected_no_equipable ) );
}
} else {
if ( equipo.isEquipado() ) {
itemsGrill.get( i ).setBackground( AmbarManager.instance().getDrawable( R.drawable.inventario_fondo_item_equipado ) );
} else if ( personaje.getInventario().isEquipable( equipo ) || equipo.isConsumible() || equipo.isEsencial() ) {
itemsGrill.get( i ).setBackground( AmbarManager.instance().getDrawable( R.drawable.inventario_fondo_item ) );
} else {
itemsGrill.get( i ).setBackground( AmbarManager.instance().getDrawable( R.drawable.inventario_fondo_item_no_equipable ) );
}
}
// Actualizar el contador
i++;
}
}
}
/**
* Método que es llamado cuando el usuario pulsa una de las flechas de la paginación
*
* @param arrow clicked
*/
@OnClick({R.id.fragment_commerce_img_navegation_left, R.id.fragment_commerce_img_navegation_right})
public void pageSelected( View arrow ) {
// Resetear la parrilla y la descripción del item
resetItemDescription();
resetGrill();
switch ( arrow.getId() ) {
case R.id.fragment_commerce_img_navegation_left:
currentPage--;
if ( currentWindowTab.getId() == R.id.fragment_commerce_img_tab_mercader ) {
updateGrillMercader( currentTab, currentPage );
} else {
updateGrillInventario( currentTab, currentPage, false );
}
break;
case R.id.fragment_commerce_img_navegation_right:
currentPage++;
if ( currentWindowTab.getId() == R.id.fragment_commerce_img_tab_mercader ) {
updateGrillMercader( currentTab, currentPage );
} else {
updateGrillInventario( currentTab, currentPage, false );
}
break;
}
// Una vez llenada la parrilla, mostramos un texto de info
textViewGlobalInfo.setText( getString( R.string.fragment_inventario_textView_select ) );
// Visibilidad de las arrows
arrowsPaginationVisibility();
}
/**
* <p>Método que resetea la parte superior del inventario que corresponde a la descripción del
* item.</p> <p>Para ello pone cadenas en blanco en el nombre, descripción, etc.. y una imagen
* en blanco para la imagen del item</p>
*/
private void resetItemDescription() {
// Imagen en blanco
Drawable empty = AmbarManager.instance().getDrawable( R.drawable.empty );
// Resetear el nombre del item
textViewItemName.setText( "" );
// Resetear la descripción
textViewItemDescription.setText( "" );
// Ocultar el status
textViewStatusItem.setText( "" );
// Ocultar el layout que hace de botón de acción
layoutAction.setVisibility( View.INVISIBLE );
// Resetear la imagen de la descripción
imgItem.setImageDrawable( empty );
// Resetear los orbes y los valores de las mejoras en atributos
orbeMejorasPrimary.setImageDrawable( empty );
orbeMejorasSecondary.setImageDrawable( empty );
textViewMejorasPrimary.setText( "" );
textViewMejorasSecondary.setText( "" );
// Resetear la etiqueta de info global
textViewGlobalInfo.setText( "" );
}
/**
* Método para resetar la parrilla. Para quita las imágenes de los items y coloca en su lugar
* imágenes en blanco
*/
private void resetGrill() {
Drawable empty = AmbarManager.instance().getDrawable( R.drawable.empty );
// Resetear la parrilla
for ( ImageButton item : itemsGrill ) {
// Cambiamos las imágenes de los itemsGrill por una imagen en blanco
item.setImageDrawable( empty );
// Poner los fondos por defecto en la parrilla
item.setBackground( AmbarManager.instance().getDrawable( R.drawable.inventario_fondo_item ) );
// Marcar el objeto como no seleccionado
item.setSelected( false );
// Reseteamos todas las tags
item.setTag( "" );
}
// Ocultar flechas
arrowLeftNav.setVisibility( View.INVISIBLE );
arrowRightNav.setVisibility( View.INVISIBLE );
}
/**
* Método que oculta/muestra las flechas de paginación
*/
private void arrowsPaginationVisibility() {
// Flecha izquierda
if ( currentPage == 1 ) {
arrowLeftNav.setVisibility( View.INVISIBLE );
} else {
arrowLeftNav.setVisibility( View.VISIBLE );
}
// Flecha derecha
if ( equipamientoPorTipoPaginado != null && equipamientoPorTipoPaginado.size() > 0 ) {
if ( currentPage == equipamientoPorTipoPaginado.size() ) {
arrowRightNav.setVisibility( View.INVISIBLE );
} else {
arrowRightNav.setVisibility( View.VISIBLE );
}
}
}
/**
* Actualiza las estadísticas del objeto que se muestran en la descripción
*
* @param equipo selected
*/
private void updateEstadisticas( Equipo equipo ) {
boolean one = false;
if ( equipo != null ) {
// Ataque
if ( equipo.getAtaque() > 0 ) {
textViewMejorasPrimary.setText( String.valueOf( equipo.getAtaque() ) );
orbeMejorasPrimary.setImageDrawable( AmbarManager.instance().getDrawable( R.drawable.orbe_ataque ) );
one = true;
}
// Defensa
if ( equipo.getDefensa() > 0 ) {
if ( one ) {
textViewMejorasSecondary.setText( String.valueOf( equipo.getDefensa() ) );
orbeMejorasSecondary.setImageDrawable( AmbarManager.instance().getDrawable( R.drawable.orbe_defensa ) );
} else {
textViewMejorasPrimary.setText( String.valueOf( equipo.getDefensa() ) );
orbeMejorasPrimary.setImageDrawable( AmbarManager.instance().getDrawable( R.drawable.orbe_defensa ) );
one = true;
}
}
// Absorcion
if ( equipo.getAbsorcion() > 0 ) {
if ( one ) {
textViewMejorasSecondary.setText( String.valueOf( equipo.getAbsorcion() ) );
orbeMejorasSecondary.setImageDrawable( AmbarManager.instance().getDrawable( R.drawable.orbe_absorcion ) );
} else {
textViewMejorasPrimary.setText( String.valueOf( equipo.getAbsorcion() ) );
orbeMejorasPrimary.setImageDrawable( AmbarManager.instance().getDrawable( R.drawable.orbe_absorcion ) );
one = true;
}
}
// Daño
if ( equipo.getDaño()[0] > 0 || equipo.getDaño()[1] > 0 ) {
int[] damage = equipo.getDaño();
if ( one ) {
textViewMejorasSecondary.setText( damage[0] + "-" + damage[1] );
orbeMejorasSecondary.setImageDrawable( AmbarManager.instance().getDrawable( R.drawable.orbe_damage ) );
} else {
textViewMejorasPrimary.setText( damage[0] + "-" + damage[1] );
orbeMejorasPrimary.setImageDrawable( AmbarManager.instance().getDrawable( R.drawable.orbe_damage ) );
one = true;
}
}
// Vida
if ( equipo.getVida() > 0 ) {
if ( one ) {
textViewMejorasSecondary.setText( equipo.getVida() + "%" );
orbeMejorasSecondary.setImageDrawable( AmbarManager.instance().getDrawable( R.drawable.orbe_vida ) );
} else {
textViewMejorasPrimary.setText( equipo.getVida() + "%" );
orbeMejorasPrimary.setImageDrawable( AmbarManager.instance().getDrawable( R.drawable.orbe_vida ) );
}
}
}
}
/**
* Método que se ejecuta al pulsar en el botón 'NEXT'
*
* @param button clicked
*/
@OnClick(R.id.include_navigation_next)
public void nextFragment( View button ) {
// Próxima página
personaje.setPage( page.getNextPageToLoad() );
// Guardar personaje
AmbarManager.instance().setPersonaje( personaje );
// Cargar el fragment siguiente
((MainActivity) getActivity()).loadNextFragment( button, AmbarManager.instance().getNextFragment( personaje ) );
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
}
|
package com.fixit.ui.activities;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import com.fixit.config.AppConfig;
import com.fixit.controllers.ActivityController;
import com.fixit.app.R;
import com.fixit.general.AnalyticsManager;
import com.fixit.general.PermissionManager;
import com.fixit.rest.APIError;
import com.fixit.rest.callbacks.GeneralServiceErrorCallback;
import com.fixit.ui.fragments.BaseFragment;
import com.fixit.ui.fragments.ErrorFragment;
import com.fixit.utils.Constants;
import com.fixit.utils.GlobalPreferences;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by Kostyantin on 12/21/2016.
*/
public abstract class BaseActivity<C extends ActivityController> extends AppCompatActivity
implements BaseFragment.BaseFragmentInteractionsListener,
GeneralServiceErrorCallback,
ActivityController.UiCallback {
private C mController;
private MaterialDialog mLoaderDialog;
private PermissionManager mPermissionManager;
private Set<OnBackPressListener> mBackPressListeners;
private ActivityBackPressPrompt mBackPressPrompt;
private LoginRequester mLoginRequester;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
mController = createController();
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
if(!isNetworkConnected()) {
showError(ErrorFragment.ErrorType.NO_NETWORK);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Constants.RC_LOGIN) {
boolean success = resultCode == RESULT_OK;
mLoginRequester.loginComplete(success, success ? data.getExtras() : null);
mLoginRequester = null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(!AppConfig.isProduction(this)) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.development_settings, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if(itemId == android.R.id.home) {
onBackPressed();
return true;
} else if(itemId == R.id.open_developer_settings) {
startActivity(new Intent(this, DeveloperSettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public AnalyticsManager getAnalyticsManager() {
return getController().getAnalyticsManager();
}
public abstract C createController();
public C getController() {
return mController;
}
@Override
public void setToolbar(Toolbar toolbar, boolean homeAsUpEnabled) {
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(homeAsUpEnabled);
}
}
public Toolbar findToolbar(@NonNull ViewGroup viewGroup) {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View view = viewGroup.getChildAt(i);
if (view.getClass().getName().equals("android.support.v7.widget.Toolbar")
|| view.getClass().getName().equals("android.widget.Toolbar")) {
return (Toolbar) view;
} else if (view instanceof ViewGroup) {
return findToolbar((ViewGroup) view);
}
}
return null;
}
@Override
public void setToolbarTitle(String title) {
TextView toolbarTitle = (TextView) findViewById(R.id.toolbar_title);
if(toolbarTitle != null) {
toolbarTitle.setText(title);
}
}
public void setToolbarTitleTextSize(float sp) {
TextView toolbarTitle = (TextView) findViewById(R.id.toolbar_title);
if(toolbarTitle != null) {
toolbarTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, sp);
}
}
@Override
public void requestPermissions(boolean explained, PermissionManager.PermissionRequest request, String... permissions) {
if(mPermissionManager == null){
ActivityController controller = getController();
assert controller != null;
mPermissionManager = new PermissionManager(controller.getAnalyticsManager());
}
mPermissionManager.requestPermissions(this, explained, request, permissions);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(mPermissionManager != null) {
mPermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@Override
public void startChrome(String url) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setPackage("com.android.chrome");
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
// Chrome browser presumably not installed so allow user to choose instead
intent.setPackage(null);
try {
startActivity(intent);
} catch(ActivityNotFoundException innerEx) {
// No web browser apps installed.
notifyUser(getString(R.string.no_internet_browser));
}
}
}
@Override
public void hideKeyboard(IBinder windowToken) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(windowToken, 0);
}
@Override
public void copyToClipboard(String label, String text) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(label, text);
clipboard.setPrimaryClip(clip);
notifyUser(getString(R.string.copied_format, label));
}
@Override
public boolean composeEmail(String[] addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
return true;
}
return false;
}
public boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
@Override
public void restartApp(boolean skipSplash) {
Intent intent;
if(skipSplash) {
intent = new Intent(this, SplitSearchActivity.class);
} else {
intent = new Intent(this, SplashActivity.class);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
/**
* Override for enabling/disabling user notifications.
*/
public boolean notifyPossible() {
return true;
}
@Override
public void notifyUser(String msg) {
notifyUser(msg, getWindow().getDecorView());
}
@Override
public void notifyUser(String msg, View v) {
if(notifyPossible()) {
Snackbar snackbar = Snackbar.make(v, msg, Snackbar.LENGTH_LONG);
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(AppConfig.getColor(this, AppConfig.KEY_COLOR_PRIMARY_DARK, Color.BLACK));
TextView textView = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.large_text_size));
textView.setMaxLines(5);
snackbar.show();
}
}
@Override
public void showStaticWebPage(String title, String url) {
Intent intent = new Intent(this, WebActivity.class);
intent.putExtra(Constants.ARG_TITLE, title);
intent.putExtra(Constants.ARG_URL, url);
startActivity(intent);
}
// USER MANAGEMENT
public boolean isUserRegistered() {
return !TextUtils.isEmpty(GlobalPreferences.getUserId(this));
}
@Override
public void requestLogin(@Nullable String message, @Nullable String promptOnBackPressMessage, @Nullable Bundle data, LoginRequester requester) {
mLoginRequester = requester;
Intent intent = new Intent(this, LoginActivity.class);
if(data == null) {
data = new Bundle();
}
if(!TextUtils.isEmpty(message)) {
data.putString(Constants.ARG_LOGIN_MESSAGE, message);
}
if(!TextUtils.isEmpty(promptOnBackPressMessage)) {
data.putBoolean(Constants.ARG_PROMPT_ON_BACK_PRESS_MESSAGE, true);
}
intent.putExtras(data);
startActivityForResult(intent, Constants.RC_LOGIN);
}
public interface LoginRequester {
void loginComplete(boolean success, @Nullable Bundle data);
}
// ERROR HANDLING
// ===========================
@Override
public void onAppServiceError(List<APIError> errors) {
showError(ErrorFragment.ErrorType.GENERAL.createBuilder(this).apiError(errors).build());
}
@Override
public void onServerError() {
showError(ErrorFragment.ErrorType.SERVER_UNAVAILABLE);
}
@Override
public void onUnexpectedErrorOccurred(String msg, Throwable t) {
ErrorFragment.ErrorParamsBuilder builder = ErrorFragment.ErrorType.GENERAL.createBuilder(this).log(msg);
if(t != null) {
builder.cause(t);
}
showError(builder.build());
}
public void showError() {
showError(ErrorFragment.ErrorType.GENERAL);
}
@Override
public void showError(String error) {
showError(ErrorFragment.ErrorType.GENERAL, error);
}
public void showError(ErrorFragment.ErrorType errorType) {
showError(errorType.createBuilder(this).build());
}
public void showError(ErrorFragment.ErrorType errorType, String msg) {
showError(errorType.createBuilder(msg).build());
}
public void showError(ErrorFragment.ErrorParams params) {
if(!isDestroyed()) {
hideLoader();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, ErrorFragment.newInstance(params))
.commitAllowingStateLoss();
}
}
@Override
public void showPrompt(String message) {
showError(ErrorFragment.ErrorType.PROMPT.createBuilder(message).build());
}
@Override
public void showPrompt(String message, Throwable t) {
showError(ErrorFragment.ErrorType.PROMPT.createBuilder(message).cause(t).build());
}
// LOADER
// ==========================
public void showLoader() {
showLoader(getString(R.string.loading));
}
@Override
public void showLoader(String message) {
showLoader(message, false);
}
@Override
public void showLoader(String message, boolean cancelable) {
if(mLoaderDialog == null) {
mLoaderDialog = new MaterialDialog.Builder(this)
.title(R.string.please_wait)
.content(message)
.progress(true, 0)
.progressIndeterminateStyle(true)
.cancelable(cancelable)
.show();
} else {
mLoaderDialog.setContent(message);
mLoaderDialog.show();
}
}
public void hideLoader() {
if(mLoaderDialog != null) {
mLoaderDialog.dismiss();
mLoaderDialog = null;
}
}
// QUESTION PROMPTS
// ============================
public void askQuestion(String question, QuestionResult result) {
askQuestion(question, getString(R.string.yes), getString(R.string.no), result);
}
public void askQuestion(String question, String yesText, String noText, final QuestionResult result) {
new MaterialDialog.Builder(this)
.content(question)
.positiveText(yesText)
.onPositive((dialog, which) -> result.onQuestionAnswered(true))
.negativeText(noText)
.onNegative((dialog, which) -> result.onQuestionAnswered(false))
.cancelListener(dialog -> result.onQuestionCancelled())
.show();
}
public interface QuestionResult {
void onQuestionAnswered(boolean answeredYes);
void onQuestionCancelled();
}
// FRAGMENT INTERACTIONS
// ====================
public void clearFragmentBackStack() {
FragmentManager fm = getSupportFragmentManager();
int backStackEntryCount = fm.getBackStackEntryCount();
for(int i = 0; i < backStackEntryCount; ++i) {
fm.popBackStack();
}
}
@Nullable
public <T extends Fragment> T getFragment(String tag, Class<T> fragmentClass) {
return getFragment(tag, fragmentClass, false, 0);
}
@Nullable
public <T extends Fragment> T getFragment(String tag, Class<T> fragmentClass, boolean createIfNotExist) {
return getFragment(tag, fragmentClass, createIfNotExist, android.R.id.content);
}
@Nullable
@SuppressWarnings("unchecked")
public <T extends Fragment> T getFragment(String tag, Class<T> fragmentClass, boolean createIfNotExist, int containerViewId) {
FragmentManager fm = getSupportFragmentManager();
T fragment = (T) fm.findFragmentByTag(tag);
if(createIfNotExist && fragment == null) {
fragment = (T) Fragment.instantiate(this, fragmentClass.getCanonicalName());
fm.beginTransaction()
.add(containerViewId, fragment, tag)
.commit();
}
return fragment;
}
// BACK PRESS
// ==========================
@Override
public void onBackPressed() {
boolean handled = false;
if(mBackPressListeners != null) {
for(OnBackPressListener backPressListener : mBackPressListeners) {
if(backPressListener.onBackPressed()) {
handled = true;
}
}
}
if(!handled) {
if(mBackPressPrompt == null) {
super.onBackPressed();
} else {
askQuestion(mBackPressPrompt.content, mBackPressPrompt.yesText, mBackPressPrompt.noText, new QuestionResult() {
@Override
public void onQuestionAnswered(boolean answeredYes) {
if(answeredYes) {
BaseActivity.super.onBackPressed();
}
}
@Override
public void onQuestionCancelled() { }
});
}
}
}
public void registerOnBackPressListener(OnBackPressListener listener) {
if(mBackPressListeners == null) {
mBackPressListeners = new HashSet<>();
}
mBackPressListeners.add(listener);
}
public void unregisterOnBackPressListener(OnBackPressListener listener) {
if(mBackPressListeners != null) {
mBackPressListeners.remove(listener);
if(mBackPressListeners.size() == 0) {
mBackPressListeners = null;
}
}
}
public void clearOnBackPressListeners() {
mBackPressListeners = null;
}
public boolean hasBackPressListeners() {
return mBackPressListeners != null && !mBackPressListeners.isEmpty();
}
public void setActivityBackPressPrompt(ActivityBackPressPrompt prompt) {
this.mBackPressPrompt = prompt;
}
public interface OnBackPressListener {
boolean onBackPressed();
}
public static class ActivityBackPressPrompt {
private final String content;
private final String yesText;
private final String noText;
public ActivityBackPressPrompt(String content, String yesText, String noText) {
this.content = content;
this.yesText = yesText;
this.noText = noText;
}
}
}
|
package fr.lteconsulting.formations;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.junit.Assert;
import org.junit.Test;
public class DateParsingTest
{
@Test
public void test()
{
// 01-janv.
SimpleDateFormat format = new SimpleDateFormat( "dd M", Locale.FRENCH );
// Date today = new Date();
// System.out.println( format.format( today ) );
try
{
Calendar.getInstance().set( 2016, 0, 1 );
Date date = Calendar.getInstance().getTime();
System.out.println( DateParser.parse( "01-janv." ) );
// Assert.assertSame( date, format.parse( "01 janv" ) );
}
catch( Exception e )
{
e.printStackTrace();
Assert.fail();
}
}
}
|
package ru.vlad805.mapssharedpoints;
public class IntervalDate {
private int interval;
public IntervalDate (int i) {
interval = i;
}
public int getDays () {
return interval / 60 / 60 / 24;
}
public int getHours () {
return interval / 60 / 60;
}
public int getMinutes () {
return interval / 60 % 60;
}
} |
package round.first.linkedList;
public class RemoveDuplicatesfromSortedList2 {
/**
* @param head: head is the head of the linked list
* @return: head of the linked list
*/
public ListNode deleteDuplicates(ListNode head) {
// write your code here
if(head == null || head.next == null){
return head;
}
ListNode dummy = new ListNode(Integer.MIN_VALUE);
dummy.next = head;
head = dummy;
while(head.next != null && head.next.next != null){
if(head.next.val == head.next.next.val){
int temp = head.next.val;
while(head.next != null && head.next.val == temp){
head.next = head.next.next;
}
}else{
head = head.next;
}
}
return dummy.next;
}
}
|
package com.example.bakingapp;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.example.bakingapp.adapter.RecipeAdapter;
import com.example.bakingapp.model.result;
import com.example.bakingapp.util.Network;
import com.example.bakingapp.util.RecipeClient;
import com.example.bakingapp.util.RecipeService;
import com.google.gson.Gson;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private final String TAG = MainActivity.class.getSimpleName();
public static final String RECIPE_JSON_STATE = "recipe_json_state";
public static final String RECIPE_ARRAYLIST_STATE = "recipe_arraylist_state";
RecipeService mRecipeService;
RecipeAdapter recipeAdapter;
String mJsonResult;
ArrayList<result> mRecipeArrayList = new ArrayList<>();
@BindView(R.id.rv_recipes)
RecyclerView mRecyclerViewRecipes;
private boolean isTablet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
if (findViewById(R.id.recipe_tablet) != null) {
isTablet = true;
} else {
isTablet = false;
}
if (savedInstanceState != null) {
mJsonResult = savedInstanceState.getString(RECIPE_JSON_STATE);
mRecipeArrayList = savedInstanceState.getParcelableArrayList(RECIPE_ARRAYLIST_STATE);
recipeAdapter = new RecipeAdapter(MainActivity.this, mRecipeArrayList, mJsonResult);
RecyclerView.LayoutManager mLayoutManager;
if (isTablet) {
mLayoutManager = new GridLayoutManager(MainActivity.this, 2);
} else {
mLayoutManager = new LinearLayoutManager(MainActivity.this);
}
mRecyclerViewRecipes.setLayoutManager(mLayoutManager);
mRecyclerViewRecipes.setAdapter(recipeAdapter);
} else {
if (Network.isConnected(this)) {
mRecipeService = new RecipeClient().mRecipeService;
new FetchRecipesAsync().execute();
}
}
}
private class FetchRecipesAsync extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
fetchRecipes();
return null;
}
}
// Fetch recipes
private void fetchRecipes() {
Call<ArrayList<result>> call = mRecipeService.getRecipes();
call.enqueue(new Callback<ArrayList<result>>() {
@Override
public void onResponse(Call<ArrayList<result>> call, Response<ArrayList<result>> response) {
mRecipeArrayList = response.body();
mJsonResult = new Gson().toJson(response.body());
recipeAdapter = new RecipeAdapter(MainActivity.this, mRecipeArrayList, mJsonResult);
RecyclerView.LayoutManager mLayoutManager;
if (isTablet) {
mLayoutManager = new GridLayoutManager(MainActivity.this, 2);
} else {
mLayoutManager = new LinearLayoutManager(MainActivity.this);
}
mRecyclerViewRecipes.setLayoutManager(mLayoutManager);
mRecyclerViewRecipes.setAdapter(recipeAdapter);
}
@Override
public void onFailure(Call<ArrayList<result>> call, Throwable t) {
Log.d(TAG, t.toString());
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(RECIPE_JSON_STATE, mJsonResult);
outState.putParcelableArrayList(RECIPE_ARRAYLIST_STATE, mRecipeArrayList);
}
} |
/*
* CS 349 Java Code Examples
*
* ShapeDemo Demo of MyShape class: draw shapes using mouse.
*
*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
import javax.vecmath.*;
import javax.swing.event.MouseInputListener;
import java.awt.event.MouseEvent;
// create the window and run the demo
public class ShapeDemo2 extends JPanel implements MouseInputListener {
MyShape shape;
ShapeDemo2() {
// add listeners
addMouseListener(this);
addMouseMotionListener(this);
}
public static void main(String[] args) {
// create the window
ShapeDemo2 canvas = new ShapeDemo2();
JFrame f = new JFrame("ShapeDemo2"); // jframe is the app window
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 400); // window size
f.setContentPane(canvas); // add canvas to jframe
f.setVisible(true); // show the window
}
// custom graphics drawing
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g; // cast to get 2D drawing methods
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // antialiasing look nicer
RenderingHints.VALUE_ANTIALIAS_ON);
if (shape != null)
shape.paint(g2);
}
@Override
public void mouseClicked(MouseEvent arg0) {
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
shape = new MyShape();
shape.setIsClosed(false);
shape.setIsFilled(false);
shape.setColour(Color.BLUE);
repaint();
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
@Override
public void mouseDragged(MouseEvent arg0) {
shape.addPoint(arg0.getX(), arg0.getY());
repaint();
}
@Override
public void mouseMoved(MouseEvent arg0) {
}
}
|
package com.licenta.server.repository;
import com.licenta.server.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User,Integer> {
User findUserByUsername(String username);
boolean existsUserByUsername(String username);
boolean existsUserByEmail(String email);
}
|
package servlet;
import java.util.ArrayList;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import data.projectLogic;
import data.riskLogic;
import model.risk;
public class ProjectAction extends ActionSupport{
//p
private int selectedprojectid;
private ArrayList<risk> risklist;
private String plan_name;
public int getSelectedprojectid() {
return selectedprojectid;
}
public void setSelectedprojectid(int selectedprojectid) {
this.selectedprojectid = selectedprojectid;
}
public ArrayList<risk> getRisklist() {
return risklist;
}
public void setRisklist(ArrayList<risk> risklist) {
this.risklist = risklist;
}
public String getPlan_name() {
return plan_name;
}
public void setPlan_name(String plan_name) {
this.plan_name = plan_name;
}
public String getProjectRisk(){
riskLogic r=new riskLogic();
if(selectedprojectid>0){
risklist=r.getExistRisk(selectedprojectid);
ActionContext actionContext = ActionContext.getContext();
Map session = actionContext.getSession();
session.put("projectid",selectedprojectid);
}
else{
ActionContext actionContext = ActionContext.getContext();
Map session = actionContext.getSession();
risklist=r.getExistRisk((Integer)session.get("projectid"));
}
setRiskList();
return "success";
}
private void setRiskList(){
for(int i=0;i<risklist.size();i++){
switch(risklist.get(i).getRiskPossibility()){
case 1:
risklist.get(i).setRiskPossibilityStr("��");
break;
case 2:
risklist.get(i).setRiskPossibilityStr("��");
break;
case 3:
risklist.get(i).setRiskPossibilityStr("��");
break;
default:
System.out.println("riskPossibility false");
break;
}
switch(risklist.get(i).getRiskEfficiency()){
case 1:
risklist.get(i).setRiskEfficiencyStr("��");
break;
case 2:
risklist.get(i).setRiskEfficiencyStr("��");
break;
case 3:
risklist.get(i).setRiskEfficiencyStr("��");
break;
default:
System.out.println("riskEfficiencyStr false");
break;
}
}
}
}
|
package de.zarncke.lib.seq;
import java.util.concurrent.atomic.AtomicLong;
/**
* A simple atomic in memory integer sequence.
*
* @author Gunnar Zarncke <gunnar@zarncke.de>
*/
public class SimpleSequence implements Sequence {
private final AtomicLong sequence = new AtomicLong();
public SimpleSequence() {
}
@Override
public long addAndGet(final long delta) {
return this.sequence.addAndGet(delta);
}
@Override
public long incrementAndGet() {
return addAndGet(1);
}
}
|
package org.lvzr.fast.java.patten.struct.proxy;
public interface Sourceable {
public void method();
}
|
package main.java.com.java4beginners.ex4;
public abstract class Animal {
public abstract void hablar();
public void comer(){;
System.out.println("Me gusta comer comida");
}
}
|
package com.tencent.tencentmap.mapsdk.a;
import java.util.ArrayList;
public final class jr extends mf {
static ArrayList<ju> e = new ArrayList();
public ArrayList<ju> a = null;
public String b = "";
public String c = "";
public String d = "";
public jr(ArrayList<ju> arrayList, String str, String str2, String str3) {
this.a = arrayList;
this.b = str;
this.c = str2;
this.d = str3;
}
public final void writeTo(me meVar) {
meVar.a(this.a, 0);
if (this.b != null) {
meVar.a(this.b, 1);
}
if (this.c != null) {
meVar.a(this.c, 2);
}
if (this.d != null) {
meVar.a(this.d, 3);
}
}
static {
e.add(new ju());
}
public final void readFrom(md mdVar) {
this.a = (ArrayList) mdVar.a(e, 0, true);
this.b = mdVar.a(1, false);
this.c = mdVar.a(2, false);
this.d = mdVar.a(3, false);
}
}
|
package problem_solve.shortest_path.dijkstra.baekjoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class BaekJoon6118 {
static int N,M;
static Barn[] barn;
static int[] cost;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
barn = new Barn[N+1];
cost = new int[N+1];
for(int i=0; i < M; i++){
st = new StringTokenizer(br.readLine());
int s = Integer.parseInt(st.nextToken());
int t = Integer.parseInt(st.nextToken());
barn[s] =
new Barn(s, t, barn[s]);
barn[t] = new Barn(t, s, barn[t]);
}
dijkstra(1);
int index = 0;
int t = 1;
for(int i=2; i <= N; i++){
if(cost[index] < cost[i]){
index = i;
t = 1;
} else if(cost[i] == cost[index]){
t++;
}
}
System.out.println(index + " " + cost[index] + " " + t);
br.close();
}
public static void dijkstra(int start){
PriorityQueue<BarnNode> pq = new PriorityQueue<>();
pq.add(new BarnNode(start, 0));
cost[start] = 0;
Barn b;
BarnNode bn;
while(!pq.isEmpty()){
bn = pq.poll();
b = barn[bn.start];
while(b != null){
if(cost[b.B] == 0 || cost[b.B] > cost[b.A] + 1){
cost[b.B] = cost[b.A] + 1;
pq.add(new BarnNode(b.B, cost[b.B]));
}
b = b.N;
}
}
}
}
class BarnNode implements Comparable<BarnNode>{
int start;
int cost;
public BarnNode(int start, int cost) {
this.start = start;
this.cost = cost;
}
@Override
public int compareTo(BarnNode o) {
return this.cost - o.cost;
}
}
class Barn{
int A;
int B;
Barn N;
public Barn(int a, int b, Barn n) {
A = a;
B = b;
N = n;
}
} |
package rouchuan.viewpagerlayoutmanager;
import android.content.Context;
import android.view.WindowManager;
import android.widget.PopupWindow;
/**
* Created by Dajavu on 26/10/2017.
*/
public abstract class SettingPopUpWindow extends PopupWindow {
public SettingPopUpWindow(Context context) {
super(context);
setOutsideTouchable(true);
setWidth(Util.Dp2px(context, 320));
setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
}
}
|
package com.mmr.rabbitmq.work;
import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import sun.applet.resources.MsgAppletViewer;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Send {
private static final String QUEUE_NAME="test_work_queue";
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//获取连接
Connection connection = ConnectionUtils.getConnection();
//获取channel
Channel channel = connection.createChannel();
//声明队列
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
for(int i =0;i<50;i++){
String msg = "hello" + i;
System.out.println("[WQ send]"+msg);
channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
Thread.sleep(1*20);
}
channel.close();
connection.close();
}
public abstract class number{
}
}
|
package com.example.truedevelop;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
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.text.format.DateUtils;
import android.view.MenuItem;
import android.view.View;
import com.example.truedevelop.adapter.TabsFragmentAdapter;
import com.example.truedevelop.dto.RemindDTO;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private final static int LAYOUT = R.layout.activity_main;
private Toolbar toolbar;
private DrawerLayout drawerLayout;
private ViewPager viewPager;
private TabsFragmentAdapter adapter;
DBHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppDefault);
super.onCreate(savedInstanceState);
setContentView(LAYOUT);
initToolbar();
initNavView();
initDB();
initTabs();
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
toolbar.setTitleTextColor(getResources().getColor(R.color.textColor));
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
return false;
}
});
toolbar.inflateMenu(R.menu.menu);
}
private void initNavView() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toogle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.view_navigation_open, R.string.view_navigation_close);
drawerLayout.setDrawerListener(toogle);
toogle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
drawerLayout.closeDrawers();
switch (item.getItemId()){
case R.id.actionNotificationItem:
showNotificationTab();
}
return true;
}
});
}
private void initDB() {
dbHelper = new DBHelper(this);
}
private void initTabs() {
viewPager = (ViewPager) findViewById(R.id.viewPager);
adapter = new TabsFragmentAdapter(this, getSupportFragmentManager());
viewPager.setAdapter(adapter);
new UpdateRemindTask().execute();
//new RemindMeTask().execute();
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
private void showNotificationTab() {
viewPager.setCurrentItem(Constants.TAB_ONE_N);
}
private class RemindMeTask extends AsyncTask<Void, Void, List<RemindDTO>> {
@Override
protected List<RemindDTO> doInBackground(Void... params) {
SQLiteDatabase database = dbHelper.getReadableDatabase();
Cursor cursor = database.query(DBHelper.TABLE_NEWS, null, null, null, null, null, null);
if (cursor.moveToFirst()){
List<RemindDTO> reminders = new ArrayList<>();
int idIndex = cursor.getColumnIndex(DBHelper.KEY_ID);
int titleIndex = cursor.getColumnIndex(DBHelper.KEY_TITLE);
int dateIndex = cursor.getColumnIndex(DBHelper.KEY_DATE);
do {
RemindDTO remindDTO = new RemindDTO();
remindDTO.setId(cursor.getLong(idIndex));
remindDTO.setTitle(cursor.getString(titleIndex));
Date d = new Date(cursor.getString(dateIndex));
remindDTO.setRemindDate(d);
reminders.add(remindDTO);
} while (cursor.moveToNext());
cursor.close();
return reminders;
}
else {
cursor.close();
return null;
}
}
@Override
protected void onPostExecute(List<RemindDTO> reminders) {
if(reminders != null) adapter.setData(reminders);
}
}
private class UpdateRemindTask extends AsyncTask<Void, Void, List<RemindDTO>> {
@Override
protected List<RemindDTO> doInBackground(Void... params) {
RestTemplate template = new RestTemplate();
template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
try{
RemindDTO[] reminders = template.getForObject(Constants.URL.GET_REMINDERS, RemindDTO[].class);
List<RemindDTO> remindersList = Arrays.asList(reminders);
if (remindersList != null) return remindersList;
else return null;
} catch (Exception e) {return null;}
}
@Override
protected void onPostExecute(List<RemindDTO> remindDTO) {
if(remindDTO != null) {
dbHelper.addRemindDTOList(remindDTO, dbHelper);
}
new RemindMeTask().execute();
}
}
public void updateDB(View view){
new UpdateRemindTask().execute();
}
} |
package edu.kit.pse.osip.core.model.base;
import edu.kit.pse.osip.core.SimulationConstants;
import org.junit.Before;
import org.junit.Test;
import java.util.Observable;
import java.util.Observer;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* A class to test the ProductionSite class.
*
* @author David Kahles
* @version 1.0
*/
public class ProductionSiteTest implements Observer {
/**
* ProductionSite used for testing.
*/
private ProductionSite prodSite;
/**
* Indicates if the observer works.
*/
private boolean updated;
/**
* Initializes prodSite.
* */
@Before
public void init() {
prodSite = new ProductionSite();
updated = false;
}
/**
* Checks that all tanks are not null.
*/
@Test
public void notNull() {
assertNotNull(prodSite.getMixTank());
for (TankSelector selector: TankSelector.valuesWithoutMix()) {
assertNotNull(prodSite.getUpperTank(selector));
}
modifyEverything();
prodSite.reset();
assertNotNull(prodSite.getMixTank());
for (TankSelector selector: TankSelector.valuesWithoutMix()) {
assertNotNull(prodSite.getUpperTank(selector));
}
}
/**
* Checks that all tanks have the correct TankSelector assigned.
*/
@Test
public void correctSelector() {
assertEquals(TankSelector.MIX, prodSite.getMixTank().getTankSelector());
for (TankSelector selector: TankSelector.valuesWithoutMix()) {
assertEquals(selector, prodSite.getUpperTank(selector).getTankSelector());
}
modifyEverything();
prodSite.reset();
assertEquals(TankSelector.MIX, prodSite.getMixTank().getTankSelector());
for (TankSelector selector: TankSelector.valuesWithoutMix()) {
assertEquals(selector, prodSite.getUpperTank(selector).getTankSelector());
}
}
/**
* Checks that all tanks have the correct initial color, also after reset().
*/
@Test
public void correctColor() {
assertTrue(TankSelector.MIX.getInitialColor().equals(prodSite.getMixTank().getLiquid().getColor()));
for (TankSelector selector: TankSelector.valuesWithoutMix()) {
assertTrue(selector.getInitialColor().equals(prodSite.getUpperTank(selector).getLiquid().getColor()));
}
modifyEverything();
prodSite.reset();
assertTrue(TankSelector.MIX.getInitialColor().equals(prodSite.getMixTank().getLiquid().getColor()));
for (TankSelector selector: TankSelector.valuesWithoutMix()) {
assertTrue(selector.getInitialColor().equals(prodSite.getUpperTank(selector).getLiquid().getColor()));
}
}
/**
* Checks that all tanks have the correct initial color, also after reset().
*/
@Test
public void correctFillLevel() {
assertTrue(TankSelector.MIX.getInitialColor().equals(prodSite.getMixTank().getLiquid().getColor()));
for (TankSelector selector: TankSelector.valuesWithoutMix()) {
assertTrue(selector.getInitialColor().equals(prodSite.getUpperTank(selector).getLiquid().getColor()));
}
modifyEverything();
prodSite.reset();
assertTrue(TankSelector.MIX.getInitialColor().equals(prodSite.getMixTank().getLiquid().getColor()));
for (TankSelector selector: TankSelector.valuesWithoutMix()) {
assertTrue(selector.getInitialColor().equals(prodSite.getUpperTank(selector).getLiquid().getColor()));
}
}
/**
* Modifies the ProductionSite to test reset().
*/
private void modifyEverything() {
Liquid l = prodSite.getMixTank().getLiquid();
prodSite.getMixTank().setLiquid(modifyLiquid(l));
prodSite.getMixTank().getOutPipe().setValveThreshold((byte) 0);
for (TankSelector selector: TankSelector.valuesWithoutMix()) {
l = prodSite.getUpperTank(selector).getLiquid();
prodSite.getUpperTank(selector).setLiquid(modifyLiquid(l));
prodSite.getUpperTank(selector).getInPipe().setValveThreshold((byte) 0);
prodSite.getUpperTank(selector).getOutPipe().setValveThreshold((byte) 0);
}
}
/**
* Modifies a liquid to test reset().
*
* @param l the liquid for modifying.
* @return the modified liquid.
*/
private Liquid modifyLiquid(Liquid l) {
Color c = l.getColor();
return new Liquid(l.getAmount() + 1, l.getTemperature() + 2, new Color(c.getCyan(),
c.getMagenta(), c.getYellow()));
}
/**
* Checks that the production site is in a stable state, also after reset().
*/
@Test
public void correctState() {
byte equality = prodSite.getMixTank().getOutPipe().getValveThreshold();
assertEquals(0.5, prodSite.getMixTank().getFillLevel(), 0.0001);
for (TankSelector selector: TankSelector.valuesWithoutMix()) {
equality -= prodSite.getUpperTank(selector).getOutPipe().getValveThreshold();
assertEquals(prodSite.getUpperTank(selector).getInPipe().getValveThreshold(),
prodSite.getUpperTank(selector).getOutPipe().getValveThreshold());
assertEquals(0.5, prodSite.getUpperTank(selector).getFillLevel(), 0.0001);
}
assertEquals(0, equality);
modifyEverything();
prodSite.reset();
equality = prodSite.getMixTank().getOutPipe().getValveThreshold();
assertEquals(0.5, prodSite.getMixTank().getFillLevel(), 0.0001);
for (TankSelector selector: TankSelector.valuesWithoutMix()) {
equality -= prodSite.getUpperTank(selector).getOutPipe().getValveThreshold();
assertEquals(prodSite.getUpperTank(selector).getInPipe().getValveThreshold(),
prodSite.getUpperTank(selector).getOutPipe().getValveThreshold());
assertEquals(0.5, prodSite.getUpperTank(selector).getFillLevel(), 0.0001);
}
assertEquals(0, equality);
}
/**
* Tests that the ProductionSite remembers temperatures.
*/
@Test
public void testInputTemperature() {
prodSite.addObserver(this);
assertFalse(updated);
prodSite.setInputTemperature(TankSelector.MIX, SimulationConstants.MIN_TEMPERATURE);
assertEquals(SimulationConstants.MIN_TEMPERATURE, prodSite.getInputTemperature(TankSelector.MIX), 0.0001);
assertTrue(updated);
updated = false;
prodSite.reset();
assertTrue(updated);
}
/**
* Tests that the ProductionSite rejects too low temperatures.
*/
@Test(expected = IllegalArgumentException.class)
public void testTooLowInputTemperature() {
prodSite.setInputTemperature(TankSelector.MIX, SimulationConstants.MIN_TEMPERATURE - 1);
}
/**
* Tests that the ProductionSite rejects too high temperatures.
*/
@Test(expected = IllegalArgumentException.class)
public void testTooHighInputTemperature() {
prodSite.setInputTemperature(TankSelector.MIX, SimulationConstants.MAX_TEMPERATURE + 1);
}
@Override
public void update(Observable o, Object arg) {
updated = true;
}
}
|
package pl.connectis.cschool.client.domain;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.PropertyAccess;
import pl.connectis.cschool.shared.Product;
import pl.connectis.cschool.shared.dto.InvoiceDTO;
/**
* Created by Benia on 2017-06-24.
*/
public interface ProductProperties extends PropertyAccess<Product> {
ModelKeyProvider<Product> id();
ValueProvider<Product, String> productName();
}
|
package com.mx.profuturo.bolsa.web.controller.corporate.notifications;
import com.mx.profuturo.bolsa.model.service.BaseResponseBean;
import com.mx.profuturo.bolsa.model.service.notifications.base.NotificationBase;
import com.mx.profuturo.bolsa.service.notifications.NotificationService;
import com.mx.profuturo.bolsa.util.exception.custom.GenericStatusException;
import com.mx.profuturo.bolsa.web.controller.common.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@RequestMapping(value = "notificaciones")
@Controller("controllerNotifications")
@Scope("request")
@CrossOrigin
public class NotificationControllerImpl extends BaseController {
@Autowired
private NotificationService notificationService;
public @ResponseBody
@RequestMapping(value = "reenviar-notificacion", method = RequestMethod.POST)
BaseResponseBean reSendNotification(@RequestBody NotificationBase request) throws GenericStatusException {
notificationService.resendNotification(request);
return this.buildSuccessResponse();
}
}
|
package com.tencent.mm.plugin.label.ui;
import android.content.Context;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import com.tencent.mm.R;
import com.tencent.mm.ac.m;
import com.tencent.mm.bt.d;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.pluginsdk.ui.a.b;
import com.tencent.mm.pluginsdk.ui.d.j;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.storage.ab;
import com.tencent.mm.ui.AddressView;
import com.tencent.mm.ui.contact.f;
import com.tencent.mm.ui.r;
import java.util.List;
public final class a extends r<f> {
public static final ColorStateList kBs = com.tencent.mm.bp.a.ac(ad.getContext(), R.e.mm_list_textcolor_one);
public static final ColorStateList kBt = com.tencent.mm.bp.a.ac(ad.getContext(), R.e.hint_text_color);
List<String> kBu;
protected static class a {
public AddressView kBx;
public a(View view) {
this.kBx = (AddressView) view.findViewById(R.h.myview);
}
}
public a(Context context) {
super(context, new f());
}
public final int getCount() {
return super.getCount();
}
/* renamed from: rN */
public final f getItem(int i) {
if (qY(i)) {
return (f) aVa();
}
f fVar;
if (this.tlF != null) {
fVar = (f) this.tlF.get(Integer.valueOf(i));
if (fVar != null) {
return fVar;
}
}
if (i < 0 || !getCursor().moveToPosition(i)) {
return null;
}
fVar = a(null, getCursor());
if (this.tlF == null) {
lB(true);
}
if (this.tlF == null) {
return fVar;
}
this.tlF.put(Integer.valueOf(i), fVar);
return fVar;
}
public final View getView(int i, View view, ViewGroup viewGroup) {
a aVar;
String gY;
CharSequence charSequence = null;
ab abVar = getItem(i).guS;
if (view == null || view.getTag() == null) {
view = View.inflate(this.context, R.i.contact_label_member_list_item, null);
aVar = new a(view);
view.setTag(aVar);
} else {
aVar = (a) view.getTag();
}
b.a(aVar.kBx, abVar.field_username);
if (abVar.field_verifyFlag != 0) {
gY = com.tencent.mm.model.am.a.dBt.gY(abVar.field_verifyFlag);
if (gY != null) {
aVar.kBx.setMaskBitmap(m.kU(gY));
} else {
aVar.kBx.setMaskBitmap(null);
}
} else {
aVar.kBx.setMaskBitmap(null);
}
if (abVar.field_deleteFlag == 1) {
aVar.kBx.setNickNameTextColor(kBt);
} else {
aVar.kBx.setNickNameTextColor(kBs);
}
aVar.kBx.updateTextColors();
CharSequence charSequence2 = abVar.sNQ;
if (charSequence2 == null) {
try {
Context context = this.context;
gY = abVar.field_username;
charSequence2 = com.tencent.mm.model.r.gT(abVar.field_username);
String str = "";
if (str.length() > 0 && !str.equals(charSequence2)) {
StringBuilder stringBuilder = new StringBuilder(32);
stringBuilder.append(charSequence2);
stringBuilder.append("(");
stringBuilder.append(str);
stringBuilder.append(")");
charSequence2 = stringBuilder.toString();
}
charSequence = j.a(context, charSequence2, aVar.kBx.getNickNameSize());
} catch (Exception e) {
}
if (charSequence == null) {
charSequence = "";
}
aVar.kBx.setName(charSequence);
abVar.sNQ = charSequence;
} else {
aVar.kBx.setName(charSequence2);
}
aVar.kBx.updatePositionFlag();
return view;
}
public final synchronized void WT() {
Cursor cnR;
Object obj = Looper.myLooper() == Looper.getMainLooper() ? 1 : null;
if (this.kBu == null || this.kBu.size() <= 0) {
cnR = d.cnR();
} else {
au.HU();
cnR = c.FR().dh(this.kBu);
}
if (obj != null) {
l(cnR);
} else {
ah.A(new 1(this, cnR));
}
}
protected final void WS() {
WT();
}
private static f a(f fVar, Cursor cursor) {
if (fVar == null) {
fVar = new f();
}
au.HU();
ab Yb = c.FR().Yb(ab.o(cursor));
if (Yb == null) {
fVar.guS.d(cursor);
au.HU();
c.FR().Q(fVar.guS);
} else {
fVar.guS = Yb;
}
return fVar;
}
public final void l(Cursor cursor) {
aYc();
setCursor(cursor);
notifyDataSetChanged();
}
}
|
package smart.lib.payment;
import smart.cache.SystemCache;
import smart.config.AppConfig;
import smart.util.Helper;
import smart.service.OrderService;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import jakarta.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Map;
public class Alipay implements Payment {
public static final String NAME = "alipay";
public static final String NAME1 = "支付宝";
//中文名称
private String name1;
@Override
public String getName() {
// 英文名称
return NAME;
}
@Override
public String getName1() {
return NAME1;
}
/**
* 获取收款码
*
* @param title 交易标题
* @param orderNo 订单号
* @param amount 订单金额
* @return 收款码
* @throws Exception error
*/
@Override
public String getQRCode(String title, String orderNo, long amount) throws Exception {
AlipayTradePrecreateResponse alipayResponse = Factory.Payment.FaceToFace()
.preCreate(title, orderNo, Helper.priceFormat(amount));
if (ResponseChecker.success(alipayResponse)) {
return alipayResponse.qrCode;
}
throw new Exception(alipayResponse.msg + "," + alipayResponse.subMsg);
}
@Override
public String getSuccessResponse() {
return "SUCCESS";
}
@Override
@Transactional
public boolean notify(Map<String, String> map) {
try {
if (Factory.Payment.Common().verifyNotify(map)
// 需要交易成功状态
&& "TRADE_SUCCESS".equals(map.get("trade_status"))) {
long orderNo = Helper.longValue(map.get("out_trade_no"));
BigDecimal decimal = new BigDecimal(map.get("buyer_pay_amount"));
decimal = decimal.multiply(new BigDecimal("100"));
long payAmount = Helper.longValue(decimal);
OrderService orderService = AppConfig.getContext().getBean(OrderService.class);
if (orderService.pay(orderNo, NAME, payAmount, map.get("trade_no")) == null) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public String refund(long orderNo, long amount) {
try {
AlipayTradeRefundResponse response = Factory.Payment.Common().refund(Long.toString(orderNo), Helper.priceFormat(amount));
if (!response.msg.equals("Success")) {
return response.subMsg;
}
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
return null;
}
@Override
public void setConfig(Map<String, String> map) {
Config config = new Config();
config.protocol = "https";
// 正式 openapi.alipay.com
// 沙箱 openapi.alipaydev.com
config.gatewayHost = "openapi.alipaydev.com";
config.signType = "RSA2";
config.appId = map.get("appId");
config.merchantPrivateKey = map.get("merchantPrivateKey");
config.alipayPublicKey = map.get("alipayPublicKey");
//异步通知接收服务地址(可选)
config.notifyUrl = SystemCache.getUrl() + "/payNotify/" + getName();
// 1. 设置参数(全局只需设置一次)
Factory.setOptions(config);
}
}
|
@Capsule(exportKeyword = TaskAPI.class, friends = { "assemAssist.model.factoryline.workStation",
"assemAssist.model.operations", "assemAssist" })
package assemAssist.model.operations.task;
import capsules.Capsule;
|
package com.quickrant.admin.utils;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
public class TimeUtils {
public static long getNow() {
return System.currentTimeMillis();
}
public static Timestamp getNowTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
public static Timestamp getFutureTimestamp(int offsetInMin) {
return new Timestamp(System.currentTimeMillis() + offsetInMin*60*1000);
}
public static String getFormattedDate(Timestamp timestamp) {
return new SimpleDateFormat("MM/dd/yyyy h:mm a").format(timestamp);
}
}
|
/*
* 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 Aula5;
/**
*
* @author mauricio.moreira
*/
public class Calculadora {
public int somar(int a, int b){
return a + b;
}
public float somar(float a, float b){
return a + b;
}
public double somar(double a, double b) {
return a + b;
}
public int somar(int... valores) {
int total = 0;
for (int v: valores) {
total += v;
}
return total;
}
public static void main(String[] args){
Calculadora calc = new Calculadora();
System.out.println(calc.somar(4.939084938, 4.343424));
System.out.println(calc.somar(1,2,3,4,5,6,7,8,9));
System.err.println(calc.somar(1, 1));
System.err.println(calc.somar(4, 3.3));
}
}
|
package com.rc.portal.service.impl;
import java.sql.SQLException;
import java.util.List;
import com.rc.portal.dao.TMemberThreeBindingDAO;
import com.rc.portal.service.TMemberThreeBindingManager;
import com.rc.portal.vo.TMemberThreeBinding;
import com.rc.portal.vo.TMemberThreeBindingExample;
public class TMemberThreeBindingManagerImpl implements TMemberThreeBindingManager {
private TMemberThreeBindingDAO tmemberthreebindingdao;
public TMemberThreeBindingManagerImpl() {
super();
}
public void setTmemberthreebindingdao(TMemberThreeBindingDAO tmemberthreebindingdao){
this.tmemberthreebindingdao=tmemberthreebindingdao;
}
public TMemberThreeBindingDAO getTmemberthreebindingdao(){
return this.tmemberthreebindingdao;
}
public int countByExample(TMemberThreeBindingExample example) throws SQLException{
return tmemberthreebindingdao. countByExample( example);
}
public int deleteByExample(TMemberThreeBindingExample example) throws SQLException{
return tmemberthreebindingdao. deleteByExample( example);
}
public int deleteByPrimaryKey(Long id) throws SQLException{
return tmemberthreebindingdao. deleteByPrimaryKey( id);
}
public Long insert(TMemberThreeBinding record) throws SQLException{
return tmemberthreebindingdao. insert( record);
}
public Long insertSelective(TMemberThreeBinding record) throws SQLException{
return tmemberthreebindingdao. insertSelective( record);
}
public List selectByExample(TMemberThreeBindingExample example) throws SQLException{
return tmemberthreebindingdao. selectByExample( example);
}
public TMemberThreeBinding selectByPrimaryKey(Long id) throws SQLException{
return tmemberthreebindingdao. selectByPrimaryKey( id);
}
public int updateByExampleSelective(TMemberThreeBinding record, TMemberThreeBindingExample example) throws SQLException{
return tmemberthreebindingdao. updateByExampleSelective( record, example);
}
public int updateByExample(TMemberThreeBinding record, TMemberThreeBindingExample example) throws SQLException{
return tmemberthreebindingdao. updateByExample( record, example);
}
public int updateByPrimaryKeySelective(TMemberThreeBinding record) throws SQLException{
return tmemberthreebindingdao. updateByPrimaryKeySelective( record);
}
public int updateByPrimaryKey(TMemberThreeBinding record) throws SQLException{
return tmemberthreebindingdao. updateByPrimaryKey( record);
}
}
|
package mate.academy.internetshop.web.filter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mate.academy.internetshop.lib.Injector;
import mate.academy.internetshop.model.Role;
import mate.academy.internetshop.model.User;
import mate.academy.internetshop.service.UserService;
import org.apache.log4j.Logger;
public class AuthorizationFilter implements Filter {
private static final String USER_ID = "user_id";
private static final Injector INJECTOR = Injector.getInstance("mate.academy.internetshop");
private static final Logger LOGGER = Logger.getLogger(AuthorizationFilter.class);
private UserService userService = (UserService) INJECTOR.getInstance(UserService.class);
private Map<String, Set<Role.RoleName>> protectedUrls = new HashMap<>();
@Override
public void init(FilterConfig filterConfig) {
protectedUrls.put("/users/all", Set.of(Role.RoleName.ADMIN));
protectedUrls.put("/products/management", Set.of(Role.RoleName.ADMIN));
protectedUrls.put("/products/add", Set.of(Role.RoleName.ADMIN));
protectedUrls.put("/products/delete", Set.of(Role.RoleName.ADMIN));
protectedUrls.put("/orders/new", Set.of(Role.RoleName.USER));
protectedUrls.put("/user/orders", Set.of(Role.RoleName.USER));
protectedUrls.put("/shoppingCart/products/add", Set.of(Role.RoleName.USER));
protectedUrls.put("/shoppingCart/products/delete", Set.of(Role.RoleName.USER));
protectedUrls.put("/shoppingCart/products", Set.of(Role.RoleName.USER));
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String url = req.getServletPath();
if (protectedUrls.get(url) == null) {
chain.doFilter(req, resp);
return;
}
Long userId = (Long) req.getSession().getAttribute(USER_ID);
User user = userService.get(userId);
if (isAuthorized(user, protectedUrls.get(url))) {
chain.doFilter(req, resp);
} else {
LOGGER.warn("User with id " + user.getUserId() + " tried access to: " + url);
req.getRequestDispatcher("/WEB-INF/views/accessDenied.jsp").forward(req, resp);
}
}
@Override
public void destroy() {
}
private boolean isAuthorized(User user, Set<Role.RoleName> authorizedRoles) {
for (Role.RoleName authorizedRole : authorizedRoles) {
for (Role userRole : user.getRoles()) {
if (authorizedRole.equals(userRole.getRoleName())) {
return true;
}
}
}
return false;
}
}
|
package com.angelhack.mapteam.controller;
import com.angelhack.mapteam.api.model.IPtoLocation;
import com.angelhack.mapteam.api.model.ProfileResponse;
import com.angelhack.mapteam.model.MemberCondition;
import com.angelhack.mapteam.model.MemberUser;
import com.angelhack.mapteam.repository.MemberConditionRepository;
import com.angelhack.mapteam.repository.MemberUserRepository;
import com.angelhack.mapteam.specification.MemberUserSpecification;
import com.angelhack.mapteam.util.FacebookToToken;
import com.angelhack.mapteam.util.IPtoLocationJson;
import com.angelhack.mapteam.util.ProfileJson;
import com.angelhack.mapteam.util.distance.FlatEarthDist;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.Version;
import com.restfb.json.JsonObject;
import com.restfb.types.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
public class FacebookCallbackController {
//https://graph.facebook.com/v2.10/oauth/access_token?client_id=368897760172030&redirect_uri=http://localhost:8080/AngelHack/getFBCode&client_secret=921a94223f3f0f147196b46ba1a6761e&code={code-parameter}
//https://www.facebook.com/v2.10/dialog/oauth?client_id=368897760172030&redirect_uri=http://localhost:8080/AngelHack/getFBCode
//EAAFPgrP0FZC4BAGC9QV1bFYXiWn30Ot2aDJE8zulSmS3GtTcXEYBws4vIWG3oBH6wBCyPxyZCtYazUEjz3RZCNMf5x3cfLHgHa3V5t3KeZAhcsAKWaTW356TAwWATaHYedpYusCVrxb9RqTdtEAxqEZAdiInZCmLgZAKTcTicB7eAZDZD
@Autowired
MemberUserRepository memberUserRepository;
@Autowired
MemberConditionRepository memberConditionRepository;
@CrossOrigin(value = "*")
@RequestMapping(value = "/askSignIn", method = RequestMethod.GET, headers = "Accept=application/json")
public String askSignIn(Model model) {
System.out.println("ask signin:");
return "redirect:https://www.facebook.com/v2.10/dialog/oauth?client_id=368897760172030&redirect_uri=http://tommy770221.com:8080/AngelHack/getFBCode&scope=public_profile,email,user_friends";
}
@CrossOrigin(value = "*")
@RequestMapping(value = "/getFBCode", method = RequestMethod.GET, headers = "Accept=application/json")
public String getFacebookCode(Model model, @RequestParam(value = "code")String code) throws IOException {
System.out.println(code+" code ");
FacebookToToken facebookToToken=new FacebookToToken();
String token="";
try {
token= facebookToToken.changeCode(code);
System.out.println("token"+token);
} catch (IOException e) {
e.printStackTrace();
}
FacebookClient facebookClient=new DefaultFacebookClient(token, Version.VERSION_2_8);
JsonObject user = facebookClient.fetchObject("me", JsonObject.class);
ProfileJson profileJson=new ProfileJson();
MemberUser memberUser=new MemberUser();
ProfileResponse profileResponse= profileJson.getProFile(user.get("id").toString(),token);
System.out.println(user.get("name"));
System.out.println(user.get("id"));
System.out.println(profileResponse.getId());
System.out.println(profileResponse.getGender());
System.out.println(profileResponse.getLocale());
System.out.println(profileResponse.getName());
System.out.println(profileResponse.getEmail());
memberUser.setFbId(profileResponse.getId());
memberUser.setName(profileResponse.getName());
memberUser.setGender(profileResponse.getGender());
memberUser.setLocale(profileResponse.getLocale());
memberUser.setEmail(profileResponse.getEmail());
if(profileResponse.getAgeRange()!=null){
System.out.println(profileResponse.getAgeRange().getMin());
memberUser.setAgeRange(String.valueOf(profileResponse.getAgeRange().getMin()));
model.addAttribute("age",String.valueOf(profileResponse.getAgeRange().getMin()));
}
model.addAttribute("memberUser",memberUser);
model.addAttribute("fbId",profileResponse.getId());
model.addAttribute("gender",profileResponse.getGender());
model.addAttribute("name",profileResponse.getName());
model.addAttribute("locale",profileResponse.getLocale());
model.addAttribute("email",profileResponse.getEmail());
MemberUser memberUser1=memberUserRepository.searchByFBID(profileResponse.getId());
if(memberUser1==null) {
memberUser.setCreateDate(new Date());
memberUserRepository.save(memberUser);
}else{
System.out.println("memberUser1 : "+ memberUser1.getName());
}
return "memberDetail";
}
@CrossOrigin(value = "*")
@RequestMapping(value = "/addMember", method = RequestMethod.POST)
public String addMember(@ModelAttribute("memberUser") MemberUser memberUser) {
if(memberUser.getId()!=null || !"".equals(memberUser.getId())) {
// memberUserRepository.save(memberUser);
}
return "redirect:/getAllCountries";
}
@CrossOrigin(value = "*")
@RequestMapping(value = "/updateLoc", method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json; charset=utf-8")
@ResponseBody
public String updateLoc(@RequestParam(value = "email")String email,
@RequestParam(value = "lon")Double lon,
@RequestParam(value = "lat")Double lat,
HttpServletResponse httpResponse) {
try {
MemberUser memberUser=memberUserRepository.searchByEmail(email);
memberUser.setLon(lon);
memberUser.setLat(lat);
memberUser.setUpdateDate(new Date());
memberUserRepository.save(memberUser);
} catch (Exception e) {
e.printStackTrace();
httpResponse.setStatus(500);
return "{\"status\":\"error\"}";
}
return "{\"status\":\"ok\"}";
}
@CrossOrigin(value = "*")
@RequestMapping(value = "/accessCondition",method = {RequestMethod.POST,RequestMethod.GET})
public String searchMember(
@RequestParam(value = "email",required = false)String email,
@RequestParam(value = "gender",required = false)String gender,
@RequestParam(value = "locale",required = false)String locale,
@RequestParam(value = "ageRange",required = false)String ageRange,
@RequestParam(value = "page",required = false)Integer page,
@RequestParam(value = "size",required = false)Integer size,
HttpServletRequest request
) {
System.out.println("search member");
System.out.println(request.getRemoteAddr());
IPtoLocationJson iPtoLocationJson=new IPtoLocationJson();
IPtoLocation iPtoLocation=null;
try {
iPtoLocation=iPtoLocationJson.transIpTolocation(request.getRemoteAddr());
} catch (Exception e) {
e.printStackTrace();
}
MemberCondition memberCondition=new MemberCondition();
MemberUser memberUser=memberUserRepository.searchByEmail(email);
memberCondition.setAgeRange(ageRange);
memberCondition.setGender(gender);
memberCondition.setLocale(locale);
memberCondition.setEmail(email);
if(iPtoLocation !=null && iPtoLocation.getLat()!=null && iPtoLocation.getLon()!=null){
memberCondition.setLon(iPtoLocation.getLon());
memberCondition.setLat(iPtoLocation.getLat());
memberUser.setLat(iPtoLocation.getLat());
memberUser.setLon(iPtoLocation.getLon());
memberUserRepository.save(memberUser);
}
MemberCondition memberConditionExist=memberConditionRepository.searchByEmail(email);
if(memberConditionExist==null){
memberConditionExist=memberConditionRepository.save(memberCondition);
}else{
if(iPtoLocation !=null){
memberCondition.setLon(iPtoLocation.getLon());
memberCondition.setLat(iPtoLocation.getLat());
}
memberConditionExist.setAgeRange(ageRange);
memberConditionExist.setGender(gender);
memberConditionExist.setLocale(locale);
memberConditionExist=memberConditionRepository.save(memberConditionExist);
}
//
// try {
// System.out.println(URLEncoder.encode(name,"utf-8"));
// System.out.println(new String(name.getBytes("utf-8")));
// System.out.println(URLDecoder.decode(name,"utf-8"));
// System.out.println(URLDecoder.decode(name,"big5"));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// Pageable pageable=null;
// if(page!=null && size!=null){
// pageable=new PageRequest(page,size);
// }else{
// pageable=new PageRequest(1,10);
// }
//
// Specification<MemberUser> spec = new MemberUserSpecification(memberUser);
// Page<MemberUser> travels = memberUserRepository.findAll(spec, pageable);
// for(MemberUser memberUser1:travels.getContent()){
// System.out.println(memberUser1.getEmail());
// }
//if null templorlly set some value
if(memberConditionExist.getLon()==null){
memberConditionExist.setLon(new Double("121.4966"));
}
if(memberConditionExist.getLat()==null){
memberConditionExist.setLat(new Double("25.0418"));
}
return "redirect:https://angelhack-449d1.firebaseapp.com/index.html?memberCondition="+memberConditionExist.getId()+"&lon="+memberConditionExist.getLon()+"&lat="+memberConditionExist.getLat()+"&email="+memberUser.getEmail();
}
@CrossOrigin(value = "*")
@RequestMapping(value = "/queryUserLoc",method = {RequestMethod.POST,RequestMethod.GET} ,
produces = "application/json; charset=utf-8")
@ResponseBody
public String queryUserLoc(@RequestParam(value = "id")String id,
HttpServletResponse httpResponse){
try {
MemberCondition memberConditionExist = memberConditionRepository.findOne(id);
MemberUser memberUser=memberUserRepository.searchByEmail(memberConditionExist.getEmail());
List<String> ageRange = new ArrayList<String>();
List<String> gender = new ArrayList<String>();
List<String> locale = new ArrayList<String>();
if (memberConditionExist.getAgeRange() == null || "".equals(memberConditionExist.getAgeRange())) {
ageRange = new ArrayList<String>();
ageRange.add("11");
ageRange.add("21");
ageRange.add("31");
ageRange.add("41");
ageRange.add("51");
ageRange.add("61");
} else {
ageRange.add(memberConditionExist.getAgeRange());
}
if (memberConditionExist.getGender() == null || "".equals(memberConditionExist.getGender())) {
gender = new ArrayList<String>();
gender.add("female");
gender.add("male");
} else {
gender.add(memberConditionExist.getGender());
}
if (memberConditionExist.getLocale() == null || "".equals(memberConditionExist.getLocale())) {
locale = new ArrayList<String>();
locale.add("zh_TW");
locale.add("zh_CN");
locale.add("en_US");
locale.add("fr_FR");
locale.add("it_IT");
locale.add("ja_JP");
locale.add("ko_KR");
} else {
locale.add(memberConditionExist.getLocale());
}
Double lonMin = memberConditionExist.getLon() - new Double("0.20");
Double lonMax = memberConditionExist.getLon() + new Double("0.20");
Double latMin = memberConditionExist.getLat() - new Double("0.20");
Double latMax = memberConditionExist.getLat() + new Double("0.20");
List<MemberUser> memberUserList = memberUserRepository.searchByDistance(lonMin, lonMax, latMin, latMax, ageRange, gender, locale);
for(MemberUser memberUser1:memberUserList){
Double dis=FlatEarthDist.distance(memberUser1.getLat(),memberUser1.getLon(),memberUser.getLat(),memberUser.getLon());
memberUser1.setDistance(dis);
}
ObjectMapper objectMapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
objectMapper.setDateFormat(df);
String memberMessagesStr = null;
memberMessagesStr = objectMapper.writeValueAsString(memberUserList);
System.out.println(memberMessagesStr);
return memberMessagesStr;
}catch (Exception e){
e.printStackTrace();
httpResponse.setStatus(500);
return "{\"status\":\"error\"}";
}
}
}
|
package com.example.afshindeveloper.afshindeveloperandroid.view.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import com.example.afshindeveloper.afshindeveloperandroid.R;
public class AnimationActivity extends AppCompatActivity {
private static final String TAG = "AnimationActivity";
public static final String EXTRA_KEY_ANIMATION_TYPE="animation_type";
private int animationType=0;
public static final int TYPE_ALPHA =0;
public static final int TYPE_TRANSLATE=1;
public static final int TYPE_SCALE=2;
public static final int TYPE_ROTATE=3;
public static final int TYPE_VALUE_ANIMATOR=4;
private ImageView kouroshImage;
private SwitchCompat loadFromXmlSwitch;
private boolean mustLoadFromXml=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animation);
animationType=getIntent().getIntExtra(EXTRA_KEY_ANIMATION_TYPE, TYPE_ALPHA);
Log.i(TAG, "Animation Type Selected: "+animationType);
Button startButton=(Button)findViewById(R.id.button_start);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAnimation();
}
});
kouroshImage=(ImageView)findViewById(R.id.image_kourosh);
loadFromXmlSwitch=(SwitchCompat)findViewById(R.id.switch_load_from_xml);
loadFromXmlSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
mustLoadFromXml=b;
}
});
}
private void showAnimation() {
switch (animationType){
case TYPE_ALPHA:
showAlphaAnimation();
break;
case TYPE_TRANSLATE:
showTranslateAnimation();
break;
case TYPE_SCALE:
showScaleAnimation();
break;
case TYPE_ROTATE:
showRotateAnimation();
break;
case TYPE_VALUE_ANIMATOR:
break;
}
}
private void showAlphaAnimation(){
if (mustLoadFromXml){
AlphaAnimation alphaAnimation= (AlphaAnimation) AnimationUtils.loadAnimation(this,R.anim.sample_alpha);
alphaAnimation.setDuration(2000);
alphaAnimation.setRepeatCount(Animation.INFINITE);
alphaAnimation.setRepeatMode(Animation.REVERSE);
kouroshImage.startAnimation(alphaAnimation);
}else {
AlphaAnimation alphaAnimation=new AlphaAnimation(1.0f,0.5f);
alphaAnimation.setDuration(2000);
alphaAnimation.setFillAfter(true);
kouroshImage.startAnimation(alphaAnimation);
}
}
private void showTranslateAnimation(){
if (mustLoadFromXml){
TranslateAnimation translateAnimation= (TranslateAnimation) AnimationUtils.loadAnimation(this,R.anim.sample_translate);
translateAnimation.setDuration(1000);
translateAnimation.setRepeatCount(Animation.INFINITE);
translateAnimation.setRepeatMode(Animation.REVERSE);
translateAnimation.setInterpolator(new AccelerateInterpolator());
kouroshImage.startAnimation(translateAnimation);
}else {
TranslateAnimation translateAnimation=new TranslateAnimation(
Animation.ABSOLUTE,0,Animation.ABSOLUTE,200,Animation.ABSOLUTE,0,Animation.RELATIVE_TO_PARENT,1.0f);
translateAnimation.setDuration(2000);
translateAnimation.setFillAfter(true);
translateAnimation.setInterpolator(new BounceInterpolator());
kouroshImage.startAnimation(translateAnimation);
}
}
private void showScaleAnimation(){
if (mustLoadFromXml){
ScaleAnimation scaleAnimation= (ScaleAnimation) AnimationUtils.loadAnimation(this,R.anim.sample_scale);
scaleAnimation.setDuration(1000);
scaleAnimation.setRepeatCount(Animation.INFINITE);
scaleAnimation.setRepeatMode(Animation.REVERSE);
scaleAnimation.setInterpolator(new DecelerateInterpolator());
kouroshImage.startAnimation(scaleAnimation);
}else {
ScaleAnimation scaleAnimation=new ScaleAnimation(1.0f,2.0f,1.0f,2.0f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
scaleAnimation.setFillAfter(true);
scaleAnimation.setInterpolator(new AccelerateInterpolator());
scaleAnimation.setDuration(1000);
kouroshImage.startAnimation(scaleAnimation);
}
}
private void showRotateAnimation(){
RotateAnimation rotateAnimation=new RotateAnimation(0,360,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
rotateAnimation.setDuration(2000);
rotateAnimation.setFillAfter(true);
rotateAnimation.setRepeatCount(0);
kouroshImage.startAnimation(rotateAnimation);
}
}
|
package com.redhat.bashburn.fuse.tasks;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import com.redhat.bashburn.taskmanager.ListTasksRequest;
import com.redhat.bashburn.taskmanager.ListTasksResponse;
import com.redhat.bashburn.taskmanager.TasksEndpoint;
@WebService(targetNamespace = "http://taskmanager.bashburn.redhat.com", name = "TasksEndpoint")
public class TasksEndpointImpl implements TasksEndpoint {
@WebResult(name = "listTasksResponse", targetNamespace = "http://taskmanager.bashburn.redhat.com", partName = "out")
@WebMethod(operationName = "ListTasks", action = "http://taskmanager.bashburn.redhat.com/ListTasks")
public ListTasksResponse listTasks(
@WebParam(partName = "in", name = "listTasksRequest", targetNamespace = "http://taskmanager.bashburn.redhat.com")
ListTasksRequest in) {
return new ListTasksResponse();
}
} |
package com.httpclientdemo;
import org.testng.annotations.Test;
/**
* Created by Administrator on 2020/2/5 0005.
*/
public class HttpDemo {
@Test
public void test(){
}
}
|
package com.sun.demo2;
// done merge to Java-Basic
public class Client {
public static void main(String[] args) {
Host host = new Host();
// 1. 每个 代理调用程序:可以动态返回代理类、动态代理方法
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
// 2. ProxyInvacationHandler 需要代理 1个对象
proxyInvocationHandler.setTarget(host);
// 3. 获取 代理的时一个接口
Rent proxy = (Rent) proxyInvocationHandler.getProxy();
// 4. 执行方法。 proxyInvocationHandler invoke 调用相应的方法
proxy.rent();
}
}
|
package com.inalab.dao.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import com.inalab.dao.EmployeeDao;
import com.inalab.model.Employee;
public class EmployeeDaoImpl extends CommonDaoImpl<Employee> implements EmployeeDao {
private BeanPropertyRowMapper<Employee> employeeRowMapper = new BeanPropertyRowMapper<Employee>(Employee.class);
private static final Logger LOG = LoggerFactory.getLogger(EmployeeDaoImpl.class);
@Override
public Employee findEmployee(String firstName, String lastName) {
String getSql = DBQueries.getQuery("employee.getByName");
Employee record = null;
try {
record = getJdbcTemplate().queryForObject(getSql, new Object[] { firstName, lastName }, employeeRowMapper);
}
catch(EmptyResultDataAccessException ex) {
LOG.error("No Record found for " + firstName + " " + lastName);
}
return record;
}
@Override
public List<Employee> getAllEmployees(String matchPattern) {
List<Employee> recordList = null;
String getSql = DBQueries.getQuery("employee.getAllEmployee");
try {
recordList = getJdbcTemplate().query(getSql, new Object[] { '%'+matchPattern +'%', '%'+matchPattern +'%'}, employeeRowMapper);
} catch (EmptyResultDataAccessException ex) {
LOG.error("No Record Found for " + matchPattern + " " + getSql);
}
return recordList;
}
@Override
public String addNewEmployee(String firstName, String lastName, String username, String password, String emailId,
String departmentId) {
// TODO Auto-generated method stub
return null;
}
@Override
public String addEmployeeToDept(String username, String department) {
// TODO Auto-generated method stub
return null;
}
@Override
public String giveKudos(String fromEmployee, String toEmployee) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Employee> findAllEmployeesJoinedByDate(String date) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Employee> findWhoGotKudosToday() {
// TODO Auto-generated method stub
return null;
}
}
|
/**
* Javassonne
* http://code.google.com/p/javassonne/
*
* @author Kyle Prete
* @date Apr 1, 2009
*
* Copyright 2009 Javassonne Team
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.javassonne.algorithms;
import java.awt.Point;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.javassonne.model.Meeple;
import org.javassonne.model.Tile;
import org.javassonne.model.TileBoardGenIterator;
import org.javassonne.model.TileBoardIterator;
import org.javassonne.model.Tile.Quadrant;
import org.javassonne.ui.GameState;
/**
* Calculates Quadrant scores
*
* A QuadCalc should be thrown away if Tiles are being added to board because it
* does not update cached data
*
* TODO: Enforce this by listening for board_changed events?
*/
public class QuadCalc {
public QuadCalc() {
// Initialize data structures
numCastles_ = new HashMap<Point, EnumMap<Tile.Quadrant, Integer>>();
globalMeep_ = new HashMap<Point, EnumMap<Tile.Quadrant, List<Meeple>>>();
}
/*
* External function for calculating farm values for given quadrant and
* connecting quadrants. Delegates most of calculation to private recursive
* function.
*/
public void traverseQuadrant(TileBoardIterator iter, Tile.Quadrant quad) {
// Initialize recursion variables for compounding list of
// tile-quadrants, etc.
HashMap<Point, ArrayList<Tile.Quadrant>> list = new HashMap<Point, ArrayList<Tile.Quadrant>>();
ArrayList<Meeple> meeps = new ArrayList<Meeple>();
// Call recursive function
traverseQuadrant(iter, quad, meeps, list);
int total = 0;
// This is ugly, but we have to calculate how many contiguous regions
// are connected to this quadrant area.
RegionsCalc c = new RegionsCalc();
// For each Tile in our Quadrant area
for (Point p : list.keySet()) {
// Make an iterator to it
TileBoardIterator iterNew = new TileBoardGenIterator(GameState
.getInstance().getBoard(), p);
// For each quadrant on this Tile in our Quadrant area
for (Tile.Quadrant q : list.get(p)) {
for (Tile.Region r : Tile.Region.values()) {
/*
* If the region is not null and it would get points from a
* farm and we have not yet visited it with our RegionsCalc
* (to stop double-counting of regions) and it is adjacent
* to our current quadrant, traverse it in the RegionsCalc
* ...
*/
if (iterNew.current().featureInRegion(r) != null
&& iterNew.current().featureInRegion(r).farmPointValue != 0
&& c.getScoreOfRegion(p, r) == -1
&& r.isAdjacentTo(q)) {
c.traverseRegion(iterNew, r);
// ... and add its points if it is complete
if (c.getRegionCompletion(p, r))
total += iterNew.current().featureInRegion(r).farmPointValue;
}
}
}
}
/*
* Now we update our global data structures This update will do nothing
* if we've already touched the entrance quadrant because the recursive
* function will have returned without modifying list or meeps
*/
for (Point p : list.keySet()) {
// Make sure we don't try to put in a null data structure
if (numCastles_.get(p) == null)
numCastles_.put(p, new EnumMap<Tile.Quadrant, Integer>(
Tile.Quadrant.class));
if (globalMeep_.get(p) == null)
globalMeep_.put(p, new EnumMap<Tile.Quadrant, List<Meeple>>(
Tile.Quadrant.class));
for (Tile.Quadrant q : list.get(p)) {
numCastles_.get(p).put(q, total);
globalMeep_.get(p).put(q, meeps);
}
}
return;
}
// Private recursive function for calculating Quadrant values
private void traverseQuadrant(TileBoardIterator iter, Quadrant quad,
ArrayList<Meeple> meeps, HashMap<Point, ArrayList<Quadrant>> list) {
// Base case 1: off the edge of the board
if (iter.current() == null)
return;
// Base case 2: we've already touched this quadrant
if (getNumCastles(iter.getLocation(), quad) != -1)
return;
// else
// "touch" this quadrant globally...
if (numCastles_.get(iter.getLocation()) == null)
numCastles_.put(iter.getLocation(),
new EnumMap<Tile.Quadrant, Integer>(Tile.Quadrant.class));
numCastles_.get(iter.getLocation()).put(quad, 0);
// ... and locally
if (list.get(iter.getLocation()) == null)
list.put(iter.getLocation(), new ArrayList<Tile.Quadrant>());
list.get(iter.getLocation()).add(quad);
// If there's a merson here, add it to our local list
Meeple current = iter.current().meepleInQuadrant(quad);
if (current != null)
meeps.add(current);
// Temp store walls on the sides of this Tile - see Tile docs for more
// info
boolean leftWall = iter.current().farmWallInRegion(Tile.Region.Left);
boolean upWall = iter.current().farmWallInRegion(Tile.Region.Top);
boolean rightWall = iter.current().farmWallInRegion(Tile.Region.Right);
boolean downWall = iter.current().farmWallInRegion(Tile.Region.Bottom);
// traverse to next Tile(s) from edges of current quadrant
if (quad.equals(Tile.Quadrant.TopLeft)) {
if (!leftWall)
traverseQuadrant(((TileBoardGenIterator) iter).leftCopy(),
Tile.Quadrant.TopRight, meeps, list);
if (!upWall)
traverseQuadrant(((TileBoardGenIterator) iter).upCopy(),
Tile.Quadrant.BottomLeft, meeps, list);
} else if (quad.equals(Tile.Quadrant.TopRight)) {
if (!rightWall)
traverseQuadrant(((TileBoardGenIterator) iter).rightCopy(),
Tile.Quadrant.TopLeft, meeps, list);
if (!upWall)
traverseQuadrant(((TileBoardGenIterator) iter).upCopy(),
Tile.Quadrant.BottomRight, meeps, list);
} else if (quad.equals(Tile.Quadrant.BottomLeft)) {
if (!leftWall)
traverseQuadrant(((TileBoardGenIterator) iter).leftCopy(),
Tile.Quadrant.BottomRight, meeps, list);
if (!downWall)
traverseQuadrant(((TileBoardGenIterator) iter).downCopy(),
Tile.Quadrant.TopLeft, meeps, list);
} else if (quad.equals(Tile.Quadrant.BottomRight)) {
if (!rightWall)
traverseQuadrant(((TileBoardGenIterator) iter).rightCopy(),
Tile.Quadrant.BottomLeft, meeps, list);
if (!downWall)
traverseQuadrant(((TileBoardGenIterator) iter).downCopy(),
Tile.Quadrant.TopRight, meeps, list);
}
// traverse to other quadrants on this Tile that connect to the current
// (See Tile doc for info on quadrant connectivity)
int currentQuad = iter.current().farmInQuadrant(quad);
for (Tile.Quadrant q : Tile.Quadrant.values()) {
if (iter.current().farmInQuadrant(q) == currentQuad)
traverseQuadrant(iter, q, meeps, list);
}
return;
}
/*
* If traverseQuadrant has touched given Quadrant of Tile at given location,
* this function returns the num of regions "fed" by the Quadrant area,
* else, returns -1
*/
public Integer getNumCastles(Point loc, Tile.Quadrant quad) {
Map<Tile.Quadrant, Integer> tileQuadrants = numCastles_.get(loc);
if (tileQuadrants == null)
return -1;
Integer temp = tileQuadrants.get(quad);
if (temp == null)
return -1;
return temp;
}
/*
* If traverseQuadrant has touched given Quadrant of Tile at given location
* and it has a nonempty meeple list claiming it, this function returns the
* list of meeple, else returns empty list
*/
public List<Meeple> getMeepleList(Point loc, Tile.Quadrant quad) {
ArrayList<Meeple> returnVal = new ArrayList<Meeple>();
Map<Tile.Quadrant, List<Meeple>> tileQuadrants = globalMeep_.get(loc);
if (tileQuadrants == null)
return returnVal;
List<Meeple> temp = tileQuadrants.get(quad);
if (temp == null)
return returnVal;
returnVal.addAll(temp);
return returnVal;
}
/*
* Keeps track of touched locations. These store data collected when
* traversing and make it available to the accessors. Also, the recursive
* function can quit if we've already traversed this quadrant with this
* calculator - this saves time if the function is accidentally called twice
* (i.e. easier code to traverse all), but causes problems if the data is
* dirty. Therefore, a QuadCalc should be thrown away if Tiles are being
* added to board.
*/
private HashMap<Point, EnumMap<Tile.Quadrant, Integer>> numCastles_;
private HashMap<Point, EnumMap<Tile.Quadrant, List<Meeple>>> globalMeep_;
}
|
package com.terminal.action;
import java.io.ByteArrayInputStream;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.terminal.utils.SecurityCode;
import com.terminal.utils.SecurityImage;
public class SecurityCodeImageAction extends ActionSupport implements SessionAware{
private static final long serialVersionUID = 1L;
private ByteArrayInputStream imageStream;
private Map<String, Object> session ;
public ByteArrayInputStream getImageStream() {
return imageStream;
}
public void setImageStream(ByteArrayInputStream imageStream) {
this.imageStream = imageStream;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
public String execute() throws Exception {
String securityCode = SecurityCode.getSecurityCode();
imageStream = SecurityImage.getImageAsInputStream(securityCode);
session.put("securityCode", securityCode);
return SUCCESS;
}
}
|
package com.Oovever.esayTool.easyHttp;
import com.Oovever.easyHttp.util.HttpUtil;
import com.Oovever.esayTool.io.file.FileWriter;
import org.junit.Assert;
import org.junit.Test;
/**
* @author OovEver
* 2018/7/18 21:57
*/
public class BaiduSearchTest {
String url = "https://baidu.com";
String qiubai = "https://www.qiushibaike.com/";
//请求百度首页
//注意,这里会自动处理https单向认证, 可以直接请求https
@Test
public void baiduIndexTest(){
String html = HttpUtil.get(url).execute().getString();
System.out.println(html);
Assert.assertTrue(html.contains("百度一下,你就知道"));
}
@Test
public void qiubaiIndexTest(){
String html = HttpUtil.get(qiubai).execute().getString();
FileWriter writer = new FileWriter("E:\\git库\\esayTool\\src\\main\\resources\\test.txt");
writer.write(html);
System.out.println(html);
}
//百度搜索 关键字 alibaba
@Test
public void baiduSearchTest(){
String format = String.format(url + "/s?wd=%s&tn=98012088_5_dg&ch=11", "alibaba");
String html = HttpUtil.get(format).execute().getString();
System.out.println(html);
}
//百度搜索 关键字 alibaba, 并写入文件
@Test
public void baiduSearchWriteFileTest(){
String format = String.format(url + "/s?wd=%s&tn=98012088_5_dg&ch=11", "alibaba");
HttpUtil.get(format).execute().transferTo("d:/baiduSearchResult.html");
}
}
|
package by.bsu.lab6.part1.util;
import by.bsu.lab6.part1.entity.StarSystem;
public class PlanetCounter {
public int countPlanetsInStarSystem(StarSystem starSystem) {
return starSystem.getPlanets().size();
}
}
|
package game.maze;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Random;
import javax.xml.parsers.*;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import math.geom.*;
public class PlayerHandler implements Runnable {
/* Notification from Player:
* posx,posy,posz,movei,movej,movek,shooting,
*
* Send to player:
* Start of game: map,otherPlayerInfo,
* During game: otherPlayers,otherPlayerInfo,damage,
*
*/
Player player = new Player();
// public Point3f pos;
// public Vector3f moveVect;
// public boolean shooting;
Random rand = new Random();
// String name;
boolean connected = false;
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
ArrayList<String> incomingMessages = new ArrayList<String>();
public PlayerHandler(Socket socket, Maze maze) {
clientSocket = socket;
connected = true;
try {
out = new PrintWriter(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
player.name = in.readLine();
// MazeServer.printInfo("Sending map...");
sendMessage(maze.createDataPacket());
// MazeServer.printInfo("Map Sent");
// MazeServer.printInfo("Sending Spawn...");
Point2i p = maze.spawnPoints.get(rand.nextInt(maze.spawnPoints.size()));
sendMessage(p.x + " " + p.y);
} catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<String> getMessages() {
ArrayList<String> list = new ArrayList<String>(incomingMessages);
incomingMessages.clear();
return list;
}
public String getName() {
return player.name;
}
@Override
public void run() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
while(connected) {
// System.out.println("loop");
try {
if(!clientSocket.isConnected()) {connected = false; continue;}
String text = in.readLine();
db = dbf.newDocumentBuilder();
InputSource source = new InputSource();
source.setCharacterStream(new StringReader(text));
Document doc = db.parse(source);
for(int i=0; i<doc.getChildNodes().getLength(); i++) {
switch(doc.getChildNodes().item(i).getNodeName()){
case "player": player = Player.constructPlayer(doc.getChildNodes().item(i)); break;
case "entity": break;
}
}
} catch(IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
/*try {
if(!clientSocket.isConnected()) {connected = false; continue;}
String line = null;
try{line = in.readLine();}catch(SocketException e) {}
if(line == null) {connected = false; continue;}
if(line.split(":")[0].equals("[PI]")) { //Player Info
line = line.split(":")[1];
// incomingMessages.add(line);
// System.out.println(line);
String[] lines = line.split(",");
pos = new Point3f(Float.parseFloat(lines[0]), Float.parseFloat(lines[1]), Float.parseFloat(lines[2]));
moveVect = new Vector3f(Float.parseFloat(lines[3]), Float.parseFloat(lines[4]), Float.parseFloat(lines[5]));
shooting = Boolean.parseBoolean(lines[6]);
System.out.println(pos);
}
else incomingMessages.add(line);
} catch (IOException e) {
e.printStackTrace();
}/**/
}
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String message) {
out.println(message);
out.flush();
}
public void sendData(ArrayList<String> data, String open, String close) {
sendMessage(open);
for(int i=0; i<data.size(); i++) {
sendMessage(data.get(i));
System.out.print(data.get(i) + "; ");
}
System.out.println();
sendMessage(close);
}
}
|
package edu.htu.ap.lesson7;
public class CoffeeMaker_v1 {
//instance varaibles (attributes)
int water;
int coffee;
int sugar;
//methods, functions (actions)
public void boil() {
System.out.println("Boiling water...");
}
public void addCoffee() {
System.out.println("Adding coffee...");
}
public void addSugar() {
System.out.println("Adding sugar...");
}
public void serve() {
System.out.println("Serving coffeee...");
}
}
|
/**
* Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package seava.ad.presenter.impl.scheduler.model;
import java.util.Date;
import seava.ad.domain.impl.scheduler.JobLog;
import seava.j4e.api.annotation.Ds;
import seava.j4e.api.annotation.DsField;
import seava.j4e.api.annotation.SortField;
import seava.j4e.presenter.impl.model.AbstractAuditable_Ds;
@Ds(entity = JobLog.class, sort = {@SortField(field = JobLog_Ds.f_startTime, desc = true)})
public class JobLog_Ds extends AbstractAuditable_Ds<JobLog> {
public static final String ALIAS = "ad_JobLog_Ds";
public static final String f_startTime = "startTime";
public static final String f_endTime = "endTime";
public static final String f_jobContextId = "jobContextId";
public static final String f_jobContext = "jobContext";
public static final String f_jobName = "jobName";
public static final String f_jobTimerId = "jobTimerId";
public static final String f_jobTimer = "jobTimer";
@DsField
private Date startTime;
@DsField
private Date endTime;
@DsField(join = "left", path = "jobContext.id")
private String jobContextId;
@DsField(join = "left", path = "jobContext.name")
private String jobContext;
@DsField(join = "left", path = "jobContext.jobName")
private String jobName;
@DsField(join = "left", path = "jobTimer.id")
private String jobTimerId;
@DsField(join = "left", path = "jobTimer.name")
private String jobTimer;
public JobLog_Ds() {
super();
}
public JobLog_Ds(JobLog e) {
super(e);
}
public Date getStartTime() {
return this.startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return this.endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getJobContextId() {
return this.jobContextId;
}
public void setJobContextId(String jobContextId) {
this.jobContextId = jobContextId;
}
public String getJobContext() {
return this.jobContext;
}
public void setJobContext(String jobContext) {
this.jobContext = jobContext;
}
public String getJobName() {
return this.jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getJobTimerId() {
return this.jobTimerId;
}
public void setJobTimerId(String jobTimerId) {
this.jobTimerId = jobTimerId;
}
public String getJobTimer() {
return this.jobTimer;
}
public void setJobTimer(String jobTimer) {
this.jobTimer = jobTimer;
}
}
|
package javabasico.aula19labs;
import java.util.Scanner;
/**
* @author Kim Tsunoda
* Objetivo Criar um vetor A com 10 elementos inteiros. Escrever um programa que calcule e escreva: a) a soma de elementos armazenados neste vetor que são inferiores a 15;
* b) a quantidade de elementos armazenados no vetor que são iguais a 15; e c) a média dos elementos armazenados no vetor que são superiores a 15.
*/
public class Exercicio16 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int[] vetorA = new int[10];
int somaMenor15=0;
int qtdeIgual15 =0;
int qtdeMaior15 =0;
int somaMaior15 =0;
for (int i=0 ; i < vetorA.length ; i++ ) {
System.out.println("Digite um valor para a posicao " + i);
vetorA[i] = scan.nextInt();
if (vetorA[i] == 15) {
qtdeIgual15++;
} else if (vetorA[i] < 15) {
somaMenor15 += vetorA[i];
} else if (vetorA[i] > 15){
qtdeMaior15++;
somaMaior15 += vetorA[i];
}
}
System.out.print("Vetor A ");
for (int i=0 ; i < vetorA.length ; i++) {
System.out.print(vetorA [i] + " ");
}
System.out.println (" ");
System.out.println ("Soma dos valores menor do que 15: " + somaMenor15);
System.out.println ("Quantidade de valores iguais a 15: " + qtdeIgual15);
System.out.println ("Media dos valores maior do que 15: " + (somaMaior15/qtdeMaior15));
}
} |
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 hybris AG
* All rights reserved.
*
* This software is the confidential and proprietary information of hybris
* ("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 hybris.
*
*
*/
package com.cnk.travelogix.b2c.storefront.controllers.pages;
import de.hybris.platform.acceleratorstorefrontcommons.breadcrumb.ResourceBreadcrumbBuilder;
import de.hybris.platform.acceleratorstorefrontcommons.breadcrumb.impl.ContentPageBreadcrumbBuilder;
import de.hybris.platform.acceleratorstorefrontcommons.controllers.pages.AbstractPageController;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UrlPathHelper;
import com.cnk.travelogix.common.core.captcha.services.CaptchaService;
import com.cnk.travelogix.common.core.enquiry.services.EnquiryService;
import com.cnk.travelogix.common.core.enquiry.services.EnquiryService.EnquiryFlowState;
import com.cnk.travelogix.common.core.model.BaseEnquiryModel;
import com.cnk.travelogix.common.core.model.UserJourneyPhoneModel;
import com.cnk.travelogix.common.facades.product.util.CnkBeanUtil;
import com.cnk.travelogix.common.facades.userjourney.data.BaseEnquiryData;
/**
* Error handler to show a CMS managed error page. This is the catch-all controller that handles all GET requests that
* are not handled by other controllers.
*/
@Controller
@Scope("tenant")
@RequestMapping(value = "/enquiry")
public class EnquiryPageController extends AbstractPageController
{
/**
*
*/
private static final String ENQUIRY_DATA_CLASS_TEMPLATE = "com.cnk.travelogix.common.facades.userjourney.data.Enquiry%sData";
private static final String ENQUIRY_MODEL_CLASS_TEMPLATE = "com.cnk.travelogix.common.core.model.Enquiry%sModel";
private static final Logger LOG = Logger.getLogger(EnquiryPageController.class);
private static final String ERROR_CMS_PAGE = "notFound";
private final UrlPathHelper urlPathHelper = new UrlPathHelper();
@Resource(name = "simpleBreadcrumbBuilder")
private ResourceBreadcrumbBuilder resourceBreadcrumbBuilder;
@Resource(name = "contentPageBreadcrumbBuilder")
private ContentPageBreadcrumbBuilder contentPageBreadcrumbBuilder;
@Resource(name = "enquiryService")
private EnquiryService enquiryService;
@Resource(name = "captchaService")
private CaptchaService captchaService;
@RequestMapping(method =
{ RequestMethod.GET, RequestMethod.POST }, value = "/exec/{service}", produces =
{ MediaType.TEXT_PLAIN_VALUE })
public ResponseEntity<String> doService(@PathVariable("service") final String service, final HttpServletRequest request)
{
if (LOG.isDebugEnabled())
{
LOG.debug("doService(String, HttpServletRequest) - start"); //$NON-NLS-1$
}
// https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
try
{
final List<String> acceptableServiceTypes = Arrays.asList("email", "clickToCall", "chat");
if (acceptableServiceTypes.contains(service))
{
this.createEnquiry(service, request);
final ResponseEntity<String> returnResponseEntity = new ResponseEntity<>(HttpStatus.OK);
if (LOG.isDebugEnabled())
{
LOG.debug("doService(String, HttpServletRequest) - end"); //$NON-NLS-1$
}
return returnResponseEntity;
}
else
{
LOG.error("doService(String, HttpServletRequest - unsupported service is submitted by front-end.");
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
}
catch (final Exception e)
{
final String errorCode = UUID.randomUUID().toString();
LOG.error("doService(String, HttpServletRequest) - error code: " + errorCode, e); //$NON-NLS-1$
return new ResponseEntity<>(errorCode, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private void createEnquiry(final String service, final HttpServletRequest request) throws Exception
{
final String capitalizedServiceChars = StringUtils.capitalize(service);
final String dataClassName = String.format(ENQUIRY_DATA_CLASS_TEMPLATE, capitalizedServiceChars);
final String modelClassName = String.format(ENQUIRY_MODEL_CLASS_TEMPLATE, capitalizedServiceChars);
if (LOG.isDebugEnabled())
{
LOG.debug(String.format("The class [%s] will be loaded.", dataClassName));
}
final Class dataBeanType = Class.forName(dataClassName);
final String enquiryJsonString = request.getParameter("data");
final Object enquiryData = CnkBeanUtil.getBeanFromJson(enquiryJsonString, dataBeanType);
final BaseEnquiryData baseEnquiryData = (BaseEnquiryData) enquiryData;
final String gRecaptchaResponse = baseEnquiryData.getCaptcha();
final boolean verify = captchaService.verify(gRecaptchaResponse, request.getServerName());
if (!verify)
{
LOG.error("Captcha did not pass!");
return;
}
final BaseEnquiryModel enquiryModel = (BaseEnquiryModel) Class.forName(modelClassName).newInstance();
CnkBeanUtil.copyProperties(enquiryData, enquiryModel, UserJourneyPhoneModel.class);
enquiryService.createEnquiry(enquiryModel, EnquiryFlowState.MT_OTHERS);
}
}
|
package com.project.linkedindatabase.repository.model.skill;
import com.project.linkedindatabase.domain.BaseEntity;
import com.project.linkedindatabase.domain.Profile;
import com.project.linkedindatabase.domain.skill.Skill;
import com.project.linkedindatabase.jsonToPojo.SkillPoJo;
import com.project.linkedindatabase.repository.BaseRepository;
import com.project.linkedindatabase.service.model.skill.EndorsementService;
import org.springframework.stereotype.Service;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Service
public class SkillRepository extends BaseRepository<Skill,Long> {
private final EndorsementService endorsementService;
public SkillRepository(EndorsementService endorsementService) throws SQLException {
super(Skill.class);
this.endorsementService = endorsementService;
}
@Override
public void save(Skill object) throws SQLException {
PreparedStatement savePs = this.conn.prepareStatement("INSERT INTO " + this.tableName + "(name, profileId) VALUES(" +
"?, ?)");
savePs.setString(1, object.getName());
savePs.setLong(2, object.getProfileId());
savePs.execute();
}
@Override
public void createTable() throws SQLException {
PreparedStatement createTablePs = this.conn.prepareStatement("CREATE TABLE IF NOT EXISTS " + this.tableName + "(" +
"id BIGINT NOT NULL AUTO_INCREMENT,"+
"name NVARCHAR(255) NOT NULL,"+
"profileId BIGINT NOT NULL," +
"FOREIGN KEY (profileId) REFERENCES " + BaseEntity.getTableName(Profile.class) + "(id),"+
"PRIMARY KEY (id)"+
")"
);
createTablePs.execute();
}
@Override
public Skill convertSql(ResultSet resultSet) throws SQLException {
Skill skill = new Skill();
skill.setId(resultSet.getLong("id"));
skill.setName(resultSet.getString("name"));
skill.setProfileId(resultSet.getLong("profileId"));
return skill;
}
public Skill getById(long id) throws SQLException {
PreparedStatement retrievePs = this.conn.prepareStatement("SELECT * FROM "+ this.tableName +" WHERE id=?",ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
retrievePs.setLong(1, id);
ResultSet resultSet = retrievePs.executeQuery();
resultSet.next();
return this.convertSql(resultSet);
}
public Skill editById(long id, String name, long profileId) throws SQLException {
PreparedStatement updatePs = this.conn.prepareStatement("UPDATE "+this.tableName+" SET name=?, profileId=? " +
"WHERE id=?");
updatePs.setString(1, name);
updatePs.setLong(2, profileId);
updatePs.setLong(3, id);
updatePs.executeUpdate();
return this.getById(id);
}
public void deleteById(long id) throws SQLException {
PreparedStatement deletePs = this.conn.prepareStatement("DELETE FROM "+this.tableName+" WHERE id=?");
deletePs.setLong(1, id);
deletePs.execute();
}
public void update(Skill skill) throws SQLException {
PreparedStatement updatePs = this.conn.prepareStatement("UPDATE "+ this.tableName +" SET " +
"name=?, profileId=? WHERE id=?");
updatePs.setString(1, skill.getName());
updatePs.setLong(2, skill.getProfileId());
updatePs.setLong(3, skill.getId());
updatePs.executeUpdate();
}
public void saveMultipleSkill(List<String> skills,Profile profile) throws SQLException {
Long profileId = profile.getId();
for (String i : skills)
{
Skill skill = new Skill();
skill.setName(i);
skill.setProfileId(profileId);
save(skill);
}
}
public List<SkillPoJo> getAllSkillByProfileJson(Long profileId) throws SQLException {
List<Skill> skills= getAllSkillByProfile(profileId);
List<SkillPoJo> skillPoJos = new ArrayList<>();
for (Skill i : skills)
{
SkillPoJo skillPoJo = SkillPoJo.convertTOJson(i);
var endorsment = endorsementService.getAllBySkillIdJson(skillPoJo.getId());
skillPoJo.setEndorsementList(endorsment);
skillPoJos.add(skillPoJo);
}
return skillPoJos;
}
public List<Skill> getAllSkillByProfile(Long profileId) throws SQLException {
PreparedStatement ps = conn.prepareStatement("select * from "+this.getTableName() +" where profileId = ?");
ps.setLong(1,profileId);
ResultSet resultSet = ps.executeQuery();
List<Skill> allObject = new ArrayList<>();
while (resultSet.next()) {
allObject.add(convertSql(resultSet));
}
return allObject;
}
}
|
package com.enike.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.facebook.shimmer.ShimmerFrameLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ShimmerFrameLayout container =
(ShimmerFrameLayout) findViewById(R.id.shimmer_view_container);
container.startShimmer(); // If auto-start is set to false
}
} |
package com.fixit.ui.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import com.fixit.app.R;
import com.fixit.controllers.SearchController;
import com.fixit.data.Profession;
import com.fixit.ui.adapters.CommonRecyclerAdapter;
import com.fixit.ui.adapters.ProfessionRecyclerAdapter;
import com.fixit.ui.helpers.UITutorials;
import com.fixit.utils.Constants;
import com.fixit.utils.DataUtils;
/**
* Created by Kostyantin on 10/28/2017.
*/
public class ProfessionPickerFragment extends BaseFragment<SearchController> implements CommonRecyclerAdapter.CommonRecyclerViewInteractionListener<Profession>, AdapterView.OnItemClickListener {
private ProfessionSelectionListener mListener;
private ProfessionRecyclerAdapter mAdapter;
private ViewHolder mView;
private static class ViewHolder {
final AutoCompleteTextView actvProfessions;
final RecyclerView rvProfessions;
ViewHolder(View v, AdapterView.OnItemClickListener professionItemClickListener) {
actvProfessions = (AutoCompleteTextView) v.findViewById(R.id.actv_professions);
actvProfessions.setOnItemClickListener(professionItemClickListener);
rvProfessions = (RecyclerView) v.findViewById(R.id.rv_professions);
rvProfessions.requestFocus();
rvProfessions.setLayoutManager(new LinearLayoutManager(v.getContext()));
}
public void updateDefaults(Bundle args) {
if(args != null) {
String defaultProfession = args.getString(Constants.ARG_DEFAULT_PROFESSION);
if(!TextUtils.isEmpty(defaultProfession)) {
actvProfessions.setText(defaultProfession);
}
}
}
}
public static ProfessionPickerFragment newInstance(String defaultProfession) {
ProfessionPickerFragment fragment = new ProfessionPickerFragment();
Bundle args = new Bundle();
args.putString(Constants.ARG_DEFAULT_PROFESSION, defaultProfession);
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profession_picker, container, false);
mView = new ViewHolder(v, this);
setToolbar((Toolbar) v.findViewById(R.id.toolbar));
return v;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SearchController searchController = getController();
assert searchController != null;
Profession[] professions = searchController.getProfessions();
mAdapter = new ProfessionRecyclerAdapter(professions, this);
mView.rvProfessions.setAdapter(mAdapter);
mView.actvProfessions.setAdapter(new ArrayAdapter<>(
getContext(),
android.R.layout.simple_dropdown_item_1line,
android.R.id.text1,
DataUtils.toAutoCompleteList(professions)
));
mView.updateDefaults(getArguments());
if(professions.length > 0 && !UITutorials.isTutorialComplete(UITutorials.TUTORIAL_SEARCH_PROFESSION, getContext())) {
mView.actvProfessions.post(() -> {
UITutorials.create(UITutorials.TUTORIAL_SEARCH_PROFESSION, mView.actvProfessions, getString(R.string.search_predefined_professions))
.and(mView.rvProfessions.findViewHolderForLayoutPosition(0).itemView, getString(R.string.click_to_choose_profession))
.show(getFragmentManager());
});
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof ProfessionSelectionListener) {
mListener = (ProfessionSelectionListener) context;
} else {
throw new IllegalArgumentException("Context must implement "
+ ProfessionSelectionListener.class.getName());
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onItemClick(RecyclerView.ViewHolder vh, Profession item) {
mListener.onProfessionSelected(item);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mListener.onProfessionSelected(mAdapter.getItem(position));
}
public interface ProfessionSelectionListener {
void onProfessionSelected(Profession profession);
}
}
|
package com.propify.challenge.properties.services;
import org.springframework.stereotype.Service;
@Service
public class AlertService implements AlertOperations {
public void sendPropertyDeletedAlert(int id) {
// What this method actually does is not important
}
}
|
import audio.AudioHandler;
import java.awt.*;
import java.util.LinkedList;
public class EnemyHandler {
private LinkedList<Enemy> enemies;
public EnemyHandler(){
enemies = new LinkedList<Enemy>();
}
public void draw(Graphics2D g){
int size = enemies.size();
for (int i = 0; i < size; i++){
enemies.get(i).draw(g);
}
}
public void update(){
for (int i = 0; i < enemies.size(); i++){
enemies.get(i).update();
if (enemies.get(i).isDead()){
Window.panel.particles.addClusterAt(enemies.get(i).getX(),
enemies.get(i).getY(),255,0,0,50);
enemies.remove(i);
AudioHandler.EXPLODE.play();
if (enemies.size()==0){
Game.waveHandler.endWave();
}
}
}
}
public void addEnemy(double x, double y, Enemy enemy){
int index = enemies.size();
if (x == -1){ //randomize the x value
x = (int)(Math.random()*Window.getWidth());
}
enemies.add(enemy);
enemies.get(index).setXY(x,y);
}
public void removeAll(){
int size = size();
for (int i = 0; i < size; i++){
enemies.remove(0);
}
}
public Enemy getEnemyAt(int i){ return enemies.get(i); }
public int size(){ return enemies.size(); }
}
|
/*
* 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 Lab;
import Patients.AdmitPatientView;
import Patients.ViewPatientRecordsView;
import Patients.wardLogs;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
/**
*
* @author HACKER
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
/**
*
* @author HACKER
*/
public class LabManagementTabs extends JPanel{
private static JTabbedPane tabbedPane;
public LabManagementTabs(){
setSize(1300, 700);
setLocation(0, 0);
setBackground(Color.WHITE);
setLayout(null);
tabbedPane = new JTabbedPane();
tabbedPane.setBounds(0,0,700,700);
tabbedPane.add("Fill Lab Request Form", new LabRequestForm());
tabbedPane.add("Lab Request Logs", new LabRequestLogs());
tabbedPane.add("Equipment Inventory", new EquipmentInventory());
add(tabbedPane);
repaint();
}
}
|
package com.dreamcatcher.util;
import java.io.File;
public class FileManager {
public static boolean isExistingDirectory(File file){
boolean flag = false;
if(file.exists() && file.isDirectory())
flag = true;
return flag;
}
public static boolean deleteEmptyDirectory(String path) {
boolean flag = false;
File directory = new File(path);
if( isExistingDirectory(directory)) {
File[] fileArr = directory.listFiles();
if(fileArr.length == 0)
directory.delete();
flag = true;
}
return flag;
}
public static String getParentDirectoryPath(String path){
String parentPath = "";
File currDirectory = new File(path);
File parentDirectory = null;
if (isExistingDirectory(currDirectory)) {
parentDirectory = currDirectory.getParentFile();
parentPath = parentDirectory.getPath();
}
return parentPath;
}
public static boolean deleteFile(String path) {
boolean flag = false;
File file = new File(path);
if(file.exists() && file.isFile()) {
file.delete();
flag = true;
}
return flag;
}
}
|
package com.mideas.rpg.v2.hud.auction;
import com.mideas.rpg.v2.Mideas;
import com.mideas.rpg.v2.utils.Frame;
public class AuctionHouseFrame extends Frame
{
private final Frame browseFrame;
private Frame activeFrame;
private final static short X_FRAME = 19;
private final static short Y_FRAME = 118;
private final static short FRAME_WIDTH = (short)879;
private final static short FRAME_HEIGHT = (short)434;
public AuctionHouseFrame()
{
super("AuctionHouseFrame");
this.x = (short)(X_FRAME * Mideas.getDisplayXFactor());
this.y = (short)(Y_FRAME * Mideas.getDisplayYFactor());
this.width = (short)(FRAME_WIDTH * Mideas.getDisplayXFactor());
this.height = (short)(FRAME_HEIGHT * Mideas.getDisplayYFactor());
this.browseFrame = new AuctionHouseBrowseFrame(this);
this.activeFrame = this.browseFrame;
}
@Override
public void draw()
{
updateSize();
this.activeFrame.draw();
}
@Override
public boolean mouseEvent()
{
if (this.activeFrame.mouseEvent())
return (true);
return (false);
}
@Override
public boolean keyboardEvent()
{
if (this.activeFrame.keyboardEvent())
return (true);
return (false);
}
public void openBrowseFrame()
{
if (this.activeFrame == this.browseFrame)
return;
this.activeFrame.close();
this.activeFrame = this.browseFrame;
this.activeFrame.open();
}
@Override
public void open()
{
}
@Override
public void close()
{
}
@Override
public boolean isOpen()
{
return (false);
}
@Override
public void reset()
{
this.browseFrame.reset();
}
public void updateSize()
{
if (!this.shouldUpdateSize)
return;
this.x = (short)(X_FRAME * Mideas.getDisplayXFactor());
this.y = (short)(Y_FRAME * Mideas.getDisplayYFactor());
this.width = (short)(FRAME_WIDTH * Mideas.getDisplayXFactor());
this.height = (short)(FRAME_HEIGHT * Mideas.getDisplayYFactor());
this.browseFrame.shouldUpdateSize();
this.shouldUpdateSize = false;
}
@Override
public void shouldUpdateSize()
{
this.shouldUpdateSize = true;
}
}
|
package datastructure;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by zhoubo on 2017/5/13.
*/
public class BinaryTreeTest {
@Test
public void search() throws Exception {
BinaryTree<Integer> binaryTree = new BinaryTree<Integer>();
BinaryTreeNode<Integer> binaryTreeNode1 = new BinaryTreeNode<Integer>(1);
BinaryTreeNode<Integer> binaryTreeNode2 = new BinaryTreeNode<Integer>(2);
BinaryTreeNode<Integer> binaryTreeNode3 = new BinaryTreeNode<Integer>(3);
// BinaryTreeNode<Integer> binaryTreeNode4 = new BinaryTreeNode<Integer>(4);
BinaryTreeNode<Integer> binaryTreeNode5 = new BinaryTreeNode<Integer>(5);
BinaryTreeNode<Integer> binaryTreeNode6 = new BinaryTreeNode<Integer>(6);
BinaryTreeNode<Integer> binaryTreeNode7 = new BinaryTreeNode<Integer>(7);
BinaryTreeNode<Integer> binaryTreeNode8 = new BinaryTreeNode<Integer>(8);
BinaryTreeNode<Integer> binaryTreeNode9 = new BinaryTreeNode<Integer>(9);
BinaryTreeNode<Integer> binaryTreeNode0 = new BinaryTreeNode<Integer>(0);
binaryTreeNode5.leftChild = binaryTreeNode2;
binaryTreeNode5.righChild = binaryTreeNode7;
binaryTreeNode2.leftChild = binaryTreeNode1;
binaryTreeNode2.righChild = binaryTreeNode3;
binaryTreeNode7.leftChild = binaryTreeNode6;
binaryTreeNode7.righChild = binaryTreeNode8;
binaryTree.binaryTreeNodeHead = binaryTreeNode5;
BinaryTreeNode<Integer> binaryTreeNode = binaryTree.search(binaryTreeNode0, binaryTree.binaryTreeNodeHead);
BinaryTreeNode<Integer> binaryTreeParentNode = binaryTree.search(binaryTreeNode9, binaryTree.binaryTreeNodeHead, null);
System.out.println("中序遍历:");
binaryTree.inorderTraversal(binaryTree.binaryTreeNodeHead, null);
binaryTree.insertNode(binaryTreeNode9, binaryTree.binaryTreeNodeHead);
System.out.println("中序遍历:");
binaryTree.inorderTraversal(binaryTree.binaryTreeNodeHead, null);
binaryTree.insertNode(binaryTreeNode0, binaryTree.binaryTreeNodeHead);
if (null != binaryTreeNode) {
System.out.println(binaryTreeNode.value);
} else {
System.out.println("not found!");
}
if (null != binaryTreeParentNode) {
System.out.println(binaryTreeParentNode.value);
} else {
System.out.println("not found!");
}
System.out.println("中序遍历:");
binaryTree.inorderTraversal(binaryTree.binaryTreeNodeHead, null);
System.out.println("前序遍历:");
binaryTree.preorderTraversal(binaryTree.binaryTreeNodeHead, null);
System.out.println("后序遍历:");
binaryTree.subsequentTraversal(binaryTree.binaryTreeNodeHead, null);
System.out.println("层序遍历:");
binaryTree.levelOrderTraversal();
}
} |
package com.trashfun;
import android.arch.core.util.Function;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Transformations;
import android.arch.lifecycle.ViewModel;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.protocol.BasicHttpContext;
import cz.msebera.android.httpclient.protocol.HttpContext;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
import com.trashfun.ChallengesActivity;
import com.trashfun.R;
public abstract class GetHTTPData extends AppCompatActivity {
private String tempURL = "https://jsonplaceholder.typicode.com/todos/1";
private TextView fillin = findViewById(R.id.fillinEnrolled);
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in;
StringBuffer out = new StringBuffer();
try {
in = entity.getContent();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
} catch (Exception e) {
System.out.println("LongRunningGetIO failed.");
}
return out.toString();
}
@Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(tempURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
}
}
}
} |
package enthu_l;
interface Flyer{ }
class Bird implements Flyer { }
class Eagle extends Bird { }
class Bat { }
public class e_837 {
public static void main(String[] args) {
Flyer f = new Eagle();
Eagle e = new Eagle();
Bat b = new Bat();
if(f instanceof Bird) System.out.println("f is a Bird");
if(e instanceof Flyer) System.out.println("e is a Flyer");
if(b instanceof Flyer) System.out.println("b is a Flyer");
}
} |
package daggerok;
import config.AuthorizationServerConfig;
import daggerok.account.Account;
import daggerok.account.AccountRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
@Slf4j
@SpringBootApplication
@Import(AuthorizationServerConfig.class)
public class AuthorizationServiceApplication {
@Bean
CommandLineRunner init(AccountRepository accountRepository) {
if (accountRepository.count() > 0) {
return args -> log.info("{} users exists", accountRepository.count());
}
return args -> accountRepository.save(
new Account()
.setActive(true)
.setUsername("test")
.setPassword("test"));
}
public static void main(String[] args) {
SpringApplication.run(AuthorizationServiceApplication.class, args);
}
/*
open rest client:
POST http://localhost:9999/uaa/oauth/token
Headers:
Authentication: Basic aHRtbDpwd2Q= (html:pwd)
Accept: application/json
Request Parameters:
username=test
password=test
client=html
grant_type=password
secret=pwd
scope=openid
or
http --auth html:pwd --form post :9999/uaa/oauth/token username=test password=test client=html grant_type=password secret=pwd scope=openid
{
"access_token":"98ecfa5e-80c0-4b9a-856e-fd74db9b2ad6",
"token_type":"bearer",
"expires_in":42510,
"scope":"openid"
}
*/
}
|
package com.example.radio.Model;
public class CheckModel {
private boolean isChecked;
private String Value;
public CheckModel(boolean isChecked, String value) {
this.isChecked = isChecked;
Value = value;
}
public CheckModel() {
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
}
}
|
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package assignment2task2;
import java.util.Scanner;
import java.util.Random;
/**
*
* @author ramananthirugnanasundaram
*/
public class Assignment2Task2 {
/**
* @param args the command line arguments
*/
static double calcAverageScore (double numb, double divisor) {
return numb/divisor;
}
public static void main(String[] args) {
//Creates scanner and random
Scanner scan = new Scanner(System.in);
System.out.println("How many scores do you want?: ");
int x = scan.nextInt();
System.out.println(x + " scores generated");
Random random = new Random();
int i = 0;
int max = 100;
double numb = 0;
double divisor = 0;
System.out.println("-------");
System.out.println("Scores 40 or over:");
while (i<x){ //While i is less than x, the loop continues
double score = random.nextInt(max); //Generates a random number for every time the loop is executed
i++;
if (score >= 40){ // if score is >= to 40, add score to numb, and increments divisor by 1
numb = score + numb;
divisor++;
System.out.println(score);}
}
double average = calcAverageScore(numb, divisor);
System.out.println("-------");
System.out.println("Average: " + average);
}
}
|
public class NoADMSessionException extends RuntimeException {
public NoADMSessionException() { super(); }
public String to_string() {
return "O administrador do sistema nao esta logado";
}
}
|
package july.akberCollection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
public class Collection_2 {
public static void main(String[] args) {
Collection<Integer>coll = new ArrayList<>(Arrays.asList(3,4,5,2,66,544,31) );
System.out.println(coll);
Iterator<Integer> myItor= coll.iterator();
//hasNext()
System.out.println(myItor.hasNext());
//next();
// System.out.println(myItor.next());//3
// System.out.println(myItor.next());//4
//
// //remove();
// myItor.remove();
// System.out.println(myItor.next());
while (myItor.hasNext()){
Integer each = myItor.next();
System.out.print(each+ " ");
if(each > 10){
myItor.remove();
}
}
System.out.println();
System.out.println( coll );
}
}
|
package com.lingnet.vocs.dao.workorder;
import com.lingnet.common.dao.BaseDao;
import com.lingnet.vocs.entity.AreaResponsible;
/**
* 区域负责人
* @ClassName: AreaResponsibleDao
* @Description: TODO
* @author 薛硕
* @date 2017年6月28日 下午6:09:03
*
*/
public interface AreaResponsibleDao extends BaseDao<AreaResponsible, String>{
}
|
package com.kaldin.test.scheduletest.dao;
import com.kaldin.common.util.PagingBean;
import com.kaldin.test.scheduletest.dto.TestScheduleDTO;
import java.util.Date;
import java.util.List;
public abstract interface ScheduleTestInterface
{
public abstract List<?> getTestList(int paramInt);
public abstract boolean saveScheduleTest(TestScheduleDTO paramTestScheduleDTO);
public abstract Date getEndDate(String paramString, int paramInt);
public abstract List<TestScheduleDTO> getSchduleTestList(int paramInt);
public abstract List<TestScheduleDTO> getSchduleTestUserList(String paramString, Date paramDate1, Date paramDate2, int paramInt);
public abstract List<TestScheduleDTO> getSchduleTestUserList(PagingBean paramPagingBean, int paramInt1, String paramString, Date paramDate1, Date paramDate2, int paramInt2);
public abstract List<TestScheduleDTO> getSchduleTestUserList(String[] paramArrayOfString, int paramInt);
public abstract List<TestScheduleDTO> getSchduleTestUserList1(String[] paramArrayOfString, int paramInt);
public abstract List<TestScheduleDTO> getUnSchduleTestUserList(String[] paramArrayOfString, int paramInt);
public abstract List<TestScheduleDTO> getUnSchduleTestUserList1(String[] paramArrayOfString, int paramInt);
public abstract List<TestScheduleDTO> getSchduleTestUserList(String paramString);
public abstract List<TestScheduleDTO> getSchduleTestUserList(PagingBean paramPagingBean, int paramInt, String paramString);
public abstract Date getStratDate(String paramString, int paramInt);
public abstract List<TestScheduleDTO> getUnSchduleTestUserListByEmailId(String[] paramArrayOfString, int paramInt, String paramString);
}
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.test.scheduletest.dao.ScheduleTestInterface
* JD-Core Version: 0.7.0.1
*/ |
public class defaultconstructor {
void disp()
{
System.out.println("i am sid");
}
public static void main(String[] args) {
defaultconstructor dc = new defaultconstructor();
dc.disp();
}
}
|
/*
* [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.populator;
import static java.util.Arrays.asList;
import static java.util.Optional.ofNullable;
import de.hybris.platform.cms2.model.pages.AbstractPageModel;
import de.hybris.platform.cms2.servicelayer.services.AttributeDescriptorModelHelperService;
import de.hybris.platform.cmsfacades.data.ComponentTypeAttributeData;
import de.hybris.platform.cmsfacades.data.ComponentTypeData;
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.*;
import java.util.stream.Collectors;
import de.hybris.platform.servicelayer.type.TypeService;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Required;
/**
* Populator aimed at setting all necessary information for the receiving end to build a cms item dropdown widget:
* <ul>
* <li>identifies the cmsStructureType as {@link #CMS_ITEM_DROPDOWN}</li>
* <li>marks the dropdown to use {@link #ID_ATTRIBUTE} as idAttribute</li>
* </ul>
*/
public class CMSItemDropdownComponentTypeAttributePopulator implements
Populator<AttributeDescriptorModel, ComponentTypeAttributeData>
{
private static final String MODEL_CLASSES_PATERN = "(.*)Model$";
private TypeService typeService;
private ObjectFactory<ComponentTypeData> componentTypeDataFactory;
private AttributeDescriptorModelHelperService attributeDescriptorModelHelperService;
private I18nComponentTypePopulator i18nComponentTypePopulator;
private static final String ID_ATTRIBUTE = "uuid";
private static final String LABEL_ATTRIBUTE_NAME = "name";
private static final String LABEL_ATTRIBUTE_UID = "uid";
private final String TYPE_CODE = "typeCode";
private final String ITEM_SEARCH_PARAMS_KEY = "itemSearchParams";
private final String PAGE_STATUS = "pageStatus";
private final String ACTIVE = "active";
private static final String CMS_ITEM_DROPDOWN = "CMSItemDropdown";
@Override
public void populate(final AttributeDescriptorModel source, final ComponentTypeAttributeData target)
throws ConversionException
{
target.setCmsStructureType(CMS_ITEM_DROPDOWN);
target.setIdAttribute(ID_ATTRIBUTE);
target.setLabelAttributes(asList(LABEL_ATTRIBUTE_NAME, LABEL_ATTRIBUTE_UID));
final Class<?> type = getAttributeDescriptorModelHelperService().getAttributeClass(source);
final Map<String, String> paramsMap = ofNullable(target.getParams()).orElse(new HashMap<String, String>());
paramsMap.put(TYPE_CODE, type.getSimpleName().replaceAll(MODEL_CLASSES_PATERN, "$1"));
if (AbstractPageModel.class.isAssignableFrom(type))
{
paramsMap.put(ITEM_SEARCH_PARAMS_KEY, PAGE_STATUS + ":" + ACTIVE);
}
target.setParams(paramsMap);
target.setSubTypes(this.getComponentSubTypes(type));
}
/**
* This method retrieves a map of concrete subtypes of the provided type. (If the provided type
* is concrete it will also be included in the map).
* @param type The type for which to retrieve its map of subtypes.
* @return map Map of concrete component subtypes. The key is the code of the sub-type and the value is its
* i18n key.
*/
protected Map<String, String> getComponentSubTypes(final Class<?> type)
{
ComposedTypeModel composedTypeModel = this.getTypeService().getComposedTypeForClass(type);
ArrayList<ComposedTypeModel> supportedSubTypes = new ArrayList<>(composedTypeModel.getAllSubTypes());
if( !composedTypeModel.getAbstract() )
{
// If the original type itself is not abstract it should also be returned as a supported SubType.
supportedSubTypes.add(composedTypeModel);
}
return supportedSubTypes.stream().collect(Collectors.toMap(ComposedTypeModel::getCode,
typeModel -> getComponentTypeI18nKey(typeModel)));
}
/**
* This method retrieves the i18n key of the provided component type.
*
* @param typeModel The type for which to retrieve its map of subtypes.
* @return String The i18n key of the provided component type.
*/
protected String getComponentTypeI18nKey(ComposedTypeModel typeModel)
{
final ComponentTypeData componentTypeData = getComponentTypeDataFactory().getObject();
getI18nComponentTypePopulator().populate(typeModel, componentTypeData);
return componentTypeData.getI18nKey();
}
@Required
public void setAttributeDescriptorModelHelperService(
final AttributeDescriptorModelHelperService attributeDescriptorModelHelperService)
{
this.attributeDescriptorModelHelperService = attributeDescriptorModelHelperService;
}
protected AttributeDescriptorModelHelperService getAttributeDescriptorModelHelperService()
{
return attributeDescriptorModelHelperService;
}
@Required
public void setTypeService(final TypeService typeService)
{
this.typeService = typeService;
}
protected TypeService getTypeService()
{
return this.typeService;
}
@Required
public void setI18nComponentTypePopulator(I18nComponentTypePopulator i18nComponentTypePopulator)
{
this.i18nComponentTypePopulator = i18nComponentTypePopulator;
}
protected I18nComponentTypePopulator getI18nComponentTypePopulator()
{
return i18nComponentTypePopulator;
}
@Required
public void setComponentTypeDataFactory(final ObjectFactory<ComponentTypeData> componentTypeDataFactory)
{
this.componentTypeDataFactory = componentTypeDataFactory;
}
protected ObjectFactory<ComponentTypeData> getComponentTypeDataFactory()
{
return componentTypeDataFactory;
}
}
|
package NewPattern;
import java.io.File;
public class FolderCreat {
public static void main(String[] args) {
String s = "C:/Grid";
File f = new File(s);
try {
if (f.exists() == false) {
f.mkdirs();
System.out.println("Directory created");
} else {
System.out.println("Directory already present");
String sa = "C:/Grid/NewFolder3";
File fa = new File(sa);
fa.mkdir();
System.out.println("New folder is created");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package org.adv25.ADVNTRIP.Clients.Authentication;
import org.adv25.ADVNTRIP.Clients.Client;
public interface Authentication {
boolean start(Client client);
String toString();
}
|
package logging;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Fundamentals Of Security, Assignment 2
* Created by Jacob Dunk
*/
public class StreamLogger implements Logger {
final DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
final PrintStream stdOut, stdError;
final boolean verbose;
final boolean cipherSteps;
public StreamLogger(PrintStream stdOut, PrintStream stdError, boolean verbose, boolean cipherSteps) {
this.stdOut = stdOut;
this.stdError = stdError;
this.verbose = verbose;
this.cipherSteps = cipherSteps;
}
public void Log(LogType type, String message, Object... args) {
if ((verbose || type != LogType.Verbose) && (cipherSteps || type != LogType.Cipher)) {
PrintStream output = (type.IsError()) ? stdError : stdOut;
output.printf("[%s] %s\n", formatter.format(new Date()), message);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.