text stringlengths 10 2.72M |
|---|
package es.maltimor.genericRest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.type.ArrayTypeHandler;
import org.apache.ibatis.type.JdbcType;
public interface GenericServiceMapper {
@Select("Select * FROM dual")
String getTypeVarChar();
@Select("Select * FROM dual")
List<Map<String,Object>> getTypeCursor();
@Select("Select * FROM dual")
Date getTypeDate();
@Select("Select * FROM dual")
List<Map<String,Object>> getTypeNumberic();
@Select("Select * FROM dual")
List<Map<String,Object>> getTypeGeneric();
@Select("Select * FROM dual")
List<Map<String,Object>> getTypeBLOB();
//@Param("user") User user,@Param("table") String table,@Param("info") GenericCrudMapperInfoTable info,@Param("filter") String filter);
@SelectProvider(type=es.maltimor.genericRest.GenericServiceMapperProvider.class, method="cntAll")
public Long cntAll(Map<String,Object> params);
//@Param("user") User user,@Param("table") String table,@Param("info") GenericCrudMapperInfoTable info,@Param("filter") String filter,@Param("limit") Long limit,@Param("offset") Long offset,@Param("orderby") String orderby,@Param("order") String order,@Param("fields") String fields);
@SelectProvider(type=es.maltimor.genericRest.GenericServiceMapperProvider.class, method="getAll")
public List<Map<String, Object>> getAll(Map<String,Object> params);
//@Param("user") User user,@Param("table") String table,@Param("info") GenericCrudMapperInfoTable info,@Param("id") Object id);
@SelectProvider(type=es.maltimor.genericRest.GenericServiceMapperProvider.class, method="getById")
public Map<String, Object> getById(Map<String,Object> params);
//@Param("user") User user,@Param("table") String table,@Param("info") GenericCrudMapperInfoTable info,@Param("data") Map<String, Object> data);
@InsertProvider(type=es.maltimor.genericRest.GenericServiceMapperProvider.class, method="insert")
public void insert(Map<String,Object> params);
//@Param("user") User user,@Param("table") String table,@Param("info") GenericCrudMapperInfoTable info,@Param("id") Object id,@Param("data") Map<String, Object> data);
@UpdateProvider(type=es.maltimor.genericRest.GenericServiceMapperProvider.class, method="update")
public void update(Map<String,Object> params);
//@Param("user") User user,@Param("table") String table,@Param("info") GenericCrudMapperInfoTable info,@Param("id") Object id);
@DeleteProvider(type=es.maltimor.genericRest.GenericServiceMapperProvider.class, method="delete")
public void delete(Map<String,Object> params);
@SelectProvider(type=es.maltimor.genericRest.GenericServiceMapperProvider.class, method="execute")
@Options(statementType = StatementType.CALLABLE)
public Object execute(Map<String,Object> params);
@SelectProvider(type=es.maltimor.genericRest.GenericServiceMapperProvider.class, method="execute")
@Options(resultSets="a,b,c")
// @Results({@Result(property="KK",column="KK",jdbcType=JdbcType.CURSOR,javaType=List.class,typeHandler=GenericResultsetTypeHandler.class)})
// @Results({@Result(property="KK",column="KK")})
public List<Map<String,Object>> executeSQL(Map<String,Object> params);
//@Param("user") User user,@Param("table") String table,@Param("info") GenericCrudMapperInfoTable info,@Param("data") Map<String, Object> data);
@SelectProvider(type=es.maltimor.genericRest.GenericServiceMapperProvider.class, method="getSecuenceValue")
public Map<String, Object> getSecuenceValue(String secuence);
}
|
package com.wework;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.HashMap;
import java.util.Map;
public class WebPage {
private String url;
private Integer rank;
private Integer sessions=0;
private Map<String, String> searchTermExists = new HashMap<String, String>();
private String executedBy;
private String msg;
public WebPage(Integer rank, String url){
this.rank = rank;
this.url = url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public Integer getSessions() {
return sessions;
}
public void setSessions(Integer sessions) {
this.sessions = sessions;
}
public void incrementSession(){
this.sessions++;
}
public Map<String, String> getSearchTermMap() {
return searchTermExists;
}
public void setSearchTermMap(Map<String, String> searchTermExists) {
this.searchTermExists = searchTermExists;
}
public String toString(){
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.setPrettyPrinting().create();
String json = gson.toJson(this);
return json + ",";
}
public String getExecutedBy() {
return executedBy;
}
public void setExecutedBy(String executedBy) {
this.executedBy = executedBy;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
|
package com.dao.impl;
import com.dao.IUserDao;
import com.pojo.User;
import com.util.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserDaoImpl implements IUserDao {
/**
* 查找用户是否存在
* find user exist or not
* @param name 用户名或邮箱 username or Email
* @param password password
* @return 用户 User
*/
@Override
public User find(String name, String password) {
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
try {
conn = JdbcUtil.getConnection();
pst = conn.prepareStatement("select * from user where username = ? and password = ?");
pst.setString(1,name);
pst.setString(2,password);
rs = pst.executeQuery();
while(rs.next()){
User user = new User();
user.setId(rs.getInt(1));
user.setEmail(rs.getString(2));
user.setName(rs.getString(3));
user.setPassword(rs.getString(4));
user.setStatus(rs.getInt(5));
user.setLock(rs.getInt(6));
return user;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtil.Close(conn,rs,pst);
}
return null;
}
/**
* 添加新用户
* add new user
* @param user
* @return 操作是否成功 execute success or not
*/
@Override
public boolean add(User user) {
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
try {
conn = JdbcUtil.getConnection();
pst = conn.prepareStatement("insert into user (email,username,password) value(?,?,?)");
pst.setString(1,user.getEmail());
pst.setString(2,user.getName());
pst.setString(3,user.getPassword());
int i = pst.executeUpdate();
if(i>0){
return true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtil.Close(conn,rs,pst);
}
return false;
}
/**
* 修改用户信息
* update user date
* @param name
* @param password
* @return
*/
@Override
public boolean update(String name , String password) {
Connection conn = null;
PreparedStatement pst = null;
try {
conn = JdbcUtil.getConnection();
pst = conn.prepareStatement("update user set password = ? where username = ? ");
pst.setString(1,password);
pst.setString(2,name);
int i = pst.executeUpdate();
if(i>0){
return true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtil.Close(conn,null,pst);
}
return false;
}
@Override
public List<User> getUserAll() {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
List<User> list = new ArrayList();
User user = null;
try {
conn = JdbcUtil.getConnection();
pst = conn.prepareStatement("select * from user");
rs = pst.executeQuery();
while (rs.next()){
user = new User(rs.getInt(1),rs.getString(2),rs.getString(3),
rs.getString(4),rs.getInt(5),rs.getInt(6));
list.add(user);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtil.Close(conn,rs,pst);
}
return list;
}
}
|
package nyc.c4q.theaulait;
/**
* Created by c4q-vanice on 3/28/15.
*/
import java.util.ArrayList;
public class Dog {
String name;
String breed;
int age;
public Dog(String name, String breed, int age){
this.name = name;
this.breed = breed;
this.age = age;
}
public String getDog() {return this.name;}
public String getBreed() {
return this.breed;
}
public int getAge() {return this.age; }
public String setName(String name) { return this.name; }
public String setBreed(String breed) { return this.breed;}
public int setAge(int age) { return this.age;}
}
|
package com.projeto.view.ingrediente;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import com.projeto.model.models.Ingrediente;
public class TabelaIngredienteModel extends AbstractTableModel{
private static final long serialVersionUID = -5426828834886363335L;
private final String colunas[] = {"Código", "Nome", "Quantidade em Estoque", "Custo Unitário"};
private static final int CODIGO = 0;
private static final int NOME = 1;
private static final int QUANTIDADE_ESTOQUE = 2;
private static final int CUSTO_UNITARIO = 3;
private List<Ingrediente> listaIngrediente;
public List<Ingrediente> getListaIngrediente() {
return listaIngrediente;
}
public void setListaIngrediente(List<Ingrediente> listaIngrediente) {
this.listaIngrediente = listaIngrediente;
}
public Ingrediente getIngrediente(int rowIndex) {
return getListaIngrediente().get(rowIndex);
}
public void saveIngrediente(Ingrediente ingrediente) {
getListaIngrediente().add(ingrediente);
fireTableRowsInserted(getRowCount()-1, getColumnCount()-1);
}
public void updateIngrediente(Ingrediente ingrediente, int rowIndex) {
getListaIngrediente().set(rowIndex, ingrediente);
fireTableRowsInserted(rowIndex, rowIndex);
}
public void removeIngrediente(int rowIndex) {
getListaIngrediente().remove(rowIndex);
fireTableRowsInserted(rowIndex, rowIndex);
}
public void removeAll() {
getListaIngrediente().clear();
fireTableDataChanged();
}
@Override
public int getRowCount() {
return getListaIngrediente().size();
}
@Override
public int getColumnCount() {
return getColunas().length;
}
public String getColumnName(int columnIndex) {
return colunas[columnIndex];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Ingrediente ingrediente = getListaIngrediente().get(rowIndex);
switch(columnIndex) {
case CODIGO:
return ingrediente.getId();
case NOME:
return ingrediente.getNome();
case QUANTIDADE_ESTOQUE:
return ingrediente.getQuantidade_estoque();
case CUSTO_UNITARIO:
return ingrediente.getCusto_unitario();
default:
return ingrediente;
}
}
public Class<?> getColumnClass(int columnIndex){
switch(columnIndex) {
case CODIGO:
return Integer.class;
case NOME:
return String.class;
case QUANTIDADE_ESTOQUE:
return String.class;
case CUSTO_UNITARIO:
return String.class;
default:
return null;
}
}
public String[] getColunas() {
return colunas;
}
}
|
package com.example.huanglisa.nightynight;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by huanglisa on 11/20/16.
*/
public class FriendViewAdapter extends FragmentPagerAdapter {
Context ctxt=null;
public FriendViewAdapter(Context ctxt, FragmentManager mgr) {
super(mgr);
this.ctxt=ctxt;
}
@Override
public int getCount() {
return(10);
}
@Override
public Fragment getItem(int position) {
return(FriendFragment.newInstance(position));
}
} |
package com.test.singtelInterface;
public interface CommonFeaturesForBirdAndButterFly {
public void fly();
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package legaltime.controller;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import legaltime.model.ClientBean;
import legaltime.model.ClientManager;
import legaltime.model.LaborRegisterBean;
import legaltime.model.LaborRegisterManager;
import legaltime.model.Manager;
import legaltime.model.exception.DAOException;
/**
*
* @author bmartin
*/
public class ProcessControllerMonthlyCharges {
public ProcessControllerMonthlyCharges(){
}
public void assessMonthlyRetainers(java.util.Date effectiveDate_){
ClientManager clientManager ;
ClientBean[] clients = null;
clientManager = ClientManager.getInstance();
LaborRegisterBean laborRegisterBean;
LaborRegisterManager laborRegisterManager;
laborRegisterManager = LaborRegisterManager.getInstance();
try {
clients = clientManager.loadByWhere("where bill_type ='MONTHLY' " +
" and monthly_bill_rate >0 and active_yn ='Y'");
} catch (DAOException ex) {
Logger.getLogger(ProcessControllerMonthlyCharges.class.getName()).log(Level.SEVERE, null, ex);
}
Manager manager = Manager.getInstance();
try {
manager.beginTransaction();
for(int ndx =0; ndx<clients.length;ndx++){
laborRegisterBean = laborRegisterManager.createLaborRegisterBean();
laborRegisterBean.setClientId(clients[ndx].getClientId());
laborRegisterBean.setActivityDate(effectiveDate_);
laborRegisterBean.setBillRate(clients[ndx].getMonthlyBillRate());
laborRegisterBean.setMinutes(60);
laborRegisterBean.setDescription("Monthly Retainer Fee");
laborRegisterBean.setInvoiceable(true);
laborRegisterManager.save(laborRegisterBean);
}
manager.endTransaction(true);
} catch (SQLException ex) {
Logger.getLogger(ProcessControllerMonthlyCharges.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
package com.bingo.code.example.design.facade.facadepartfunction;
public interface CModuleApi {
//子系统外部使用
public void c1();
//子系统内部使用
public void c2();
//子系统内部使用
public void c3();
}
|
package iterator;
import chainexception.ChainException;
public class TopNRAJoinException extends ChainException{
public TopNRAJoinException(String s){super(null,s);}
public TopNRAJoinException(Exception prev, String s){ super(prev,s);}
}
|
/**
* 208. Implement Trie (Prefix Tree)
* Medium
* 一开始另写了个TreeNode,要清楚一点,不过要精简的话,代码还可以提取一下就是
*/
class Trie {
public int count;
public Trie[] child;
/** Initialize your data structure here. */
public Trie() {
this.count = 0;
this.child = new Trie[26];
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie p = this; // 这个this是需要记住的
for (char c : word.toCharArray()) {
if (p.child[c - 'a'] == null) {
p.child[c - 'a'] = new Trie();
}
p = p.child[c - 'a'];
}
p.count++;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie p = this;
for (char c : word.toCharArray()) {
if (p.child[c - 'a'] == null) {
return false;
}
p = p.child[c - 'a'];
}
return p.count > 0;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Trie p = this;
for (char c : prefix.toCharArray()) {
if (p.child[c - 'a'] == null) {
return false;
}
p = p.child[c - 'a'];
}
return true;
}
}
public class Solution {
public static void main(String[] args) {
// Your Trie object will be instantiated and called as such:
Trie trie = new Trie();
trie.insert("apple");
System.out.println(trie.search("apple")); // 返回 True
System.out.println(trie.search("app")); // 返回 False
System.out.println(trie.startsWith("app")); // 返回 True
trie.insert("app");
System.out.println(trie.search("app")); // 返回 True
}
}
|
package leetcode;
/**
* @author kangkang lou
*/
public class Main_28 {
public static int strStr(String haystack, String needle) {
if (haystack.length() < needle.length()) {
return -1;
}
if (haystack.equals("") && needle.equals("")) {
return 0;
}
int i = 0;
int j = 0;
int pos = 0;
while (true) {
while (i < haystack.length() && j < needle.length()) {
if (haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
} else {
j = 0;
break;
}
}
if (j == needle.length()) {
break;
}
if (i >= haystack.length()) {
break;
}
i = ++pos;
}
if (j == needle.length()) {
return pos == haystack.length() ? -1 : pos;
} else {
return -1;
}
}
public static void main(String[] args) {
System.out.println(strStr("hello", "ll"));
}
}
|
package com.tencent.mm.plugin.facedetect.ui;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;
import com.tencent.mm.plugin.facedetect.a.b;
import com.tencent.mm.protocal.c.bbt;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class FaceDetectConfirmUI$6 extends ClickableSpan {
final /* synthetic */ FaceDetectConfirmUI iQa;
final /* synthetic */ bbt iQb;
FaceDetectConfirmUI$6(FaceDetectConfirmUI faceDetectConfirmUI, bbt bbt) {
this.iQa = faceDetectConfirmUI;
this.iQb = bbt;
}
public final void onClick(View view) {
if (bi.oW(this.iQb.url)) {
x.e("MicroMsg.FaceDetectConfirmUI", "alvinluo promptInfo url is null");
} else {
FaceDetectConfirmUI.a(this.iQa, this.iQb.url);
}
}
public final void updateDrawState(TextPaint textPaint) {
textPaint.setColor(this.iQa.getResources().getColor(b.link_color));
}
}
|
package io.github.vibrouter.managers;
import android.content.Context;
import com.google.android.gms.maps.model.LatLng;
import java.util.HashSet;
import java.util.Set;
import io.github.vibrouter.hardware.RotationSensor;
import io.github.vibrouter.hardware.SelfLocalizer;
import io.github.vibrouter.models.Coordinate;
public class PositionManager implements RotationSensor.OnRotationChangeListener,
SelfLocalizer.OnLocationChangeListener {
public interface OnPositionChangeListener {
void onPositionChange(Coordinate position);
}
private Coordinate mCurrentPosition = Coordinate.INVALID_COORDINATE;
private RotationSensor mRotationSensor;
private SelfLocalizer mLocalizer;
private Set<OnPositionChangeListener> mListeners = new HashSet<>();
public PositionManager(Context context) {
mRotationSensor = new RotationSensor(context);
mLocalizer = new SelfLocalizer(context);
}
public void registerOnPositionChangeListener(OnPositionChangeListener listener) {
if (mListeners.isEmpty()) {
mRotationSensor.registerOnRotationChangeListener(this);
mRotationSensor.startUpdating();
mLocalizer.registerOnLocationChangeListener(this);
mLocalizer.startUpdating();
}
mListeners.add(listener);
}
public void unregisterOnPositionChangeListener(OnPositionChangeListener listener) {
mListeners.remove(listener);
if (mListeners.isEmpty()) {
mRotationSensor.stopUpdating();
mRotationSensor.unregisterOnRotationChangeListener(this);
mLocalizer.stopUpdating();
mLocalizer.unregisterOnLocationChangeListener(this);
mCurrentPosition = Coordinate.INVALID_COORDINATE;
}
}
@Override
public void onRotationChange(float rotation) {
updateCurrentPosition(mCurrentPosition.getLocation(), rotation);
}
@Override
public void OnLocationChange(LatLng location) {
updateCurrentPosition(location, mCurrentPosition.getRotation());
}
private void updateCurrentPosition(LatLng location, float rotation) {
mCurrentPosition = new Coordinate(location, rotation);
if (mCurrentPosition.getLocation() != null
&& mCurrentPosition.getRotation() != Double.NaN) {
announcePositionChange(mCurrentPosition);
}
}
private void announcePositionChange(Coordinate position) {
for (OnPositionChangeListener listener : mListeners) {
listener.onPositionChange(position);
}
}
}
|
import java.util.Scanner;
import java.io.*;
public class Commission{
public static double Cal(double amt){
double inst=5.5;
double inst1=10.0;
double com=0.0;
if(amt<=50000.90){
com=amt*(inst/100);
}
else{
com=amt*(inst1/100);
}
return com;
}
public static void main(String args[]){
double amt=460.500;
System.out.println(Cal(amt));
}
}
|
package com.mrice.txl.appthree.adapter;
/**
* Created by app on 2017/10/11.
*/
public class FTwoAdapter {
}
|
package com.ryl.framework.jwt;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static com.ryl.framework.jwt.JwtProperties.*;
/**
* @author: ryl
* @description: JWT token 工具类
* @date: 2020-03-03 09:21:07
*/
public class JwtUtil {
/**
* 传userId生成token
* @param userGuid
* @return
*/
public static String generateJwtToken(String userGuid) {
JwtUser jwtUser = new JwtUser();
jwtUser.setUserId(userGuid);
return generateJwtToken(jwtUser);
}
/**
* 传jwtUser生成token
* @param jwtUser
* @return
*/
public static String generateJwtToken(JwtUser jwtUser) {
// expireDate 2小时
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR, EXPIRE_TIME);
Date expireDate = calendar.getTime();
//载荷信息 存放user对象
Map<String, Object> claimsMap = new HashMap<>(1);
claimsMap.put(CLAIMS_KEY, jwtUser);
String jwt = Jwts.builder()
.setClaims(claimsMap)
.setSubject(JWT_SUBJECT)
.setExpiration(expireDate)
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
return jwt;
}
/**
* 传httpRequest获取jwtUser
* @param request
* @return
*/
public static JwtUser getJwtUser(HttpServletRequest request){
//header获取token
String token = request.getHeader(HEADER_KEY);
return getJwtUser(token);
}
/**
* 传token获取jwtUser
* @param token
* @return
*/
public static JwtUser getJwtUser(String token){
//去除前缀 Bearer
token = token.substring(TOKEN_PREFIX_TYPE.length());
Object o = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody()
.get(CLAIMS_KEY);
//转成JwtUser对象
return new ObjectMapper().convertValue(o,JwtUser.class);
}
}
|
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class RegisterPage {
static WebDriver driver;
public RegisterPage(WebDriver driver) {
this.driver = driver;
}
public void preencherIdDinamico() {
WebElement dinamico =driver.findElement(By.xpath(".//label[text() = 'Full Name* ']/following-sibling::div[1]/input"));
dinamico.sendKeys("bruno");
}
}
|
package com.fundwit.sys.shikra.authentication;
import org.junit.Test;
import static org.junit.Assert.*;
public class BearerAuthenticationTokenTest {
@Test
public void test() {
String token = "test_token";
BearerAuthenticationToken authenticationToken = new BearerAuthenticationToken(token);
assertEquals(token, authenticationToken.getCredentials());
assertNull(authenticationToken.getAuthorities());
assertNull(authenticationToken.getName());
assertNull(authenticationToken.getDetails());
assertNull(authenticationToken.getPrincipal());
assertEquals(false, authenticationToken.isAuthenticated());
try {
authenticationToken.setAuthenticated(true);
assertTrue("unexpected status",false);
}catch (IllegalArgumentException e){
}
}
} |
package edu.isi.karma.cleaning.research;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Vector;
import au.com.bytecode.opencsv.CSVReader;
import edu.isi.karma.cleaning.DataRecord;
import edu.isi.karma.cleaning.ProgramRule;
import edu.isi.karma.cleaning.correctness.AdaInspector;
import edu.isi.karma.cleaning.correctness.AdaInspectorTrainer;
class ErrorCnt {
int firstErrorIndex = -1;
int runtimeerror = 0;
int totalerror = 0;
int totalrecord = 0;
int recommand = 0;
int correctrecommand = 0;
double reductionRate = -1.0;
double precsion = 0.0;
}
class FileMetrics {
String fname = "";
int iterationCnt = 0;
double sum_inv_first_index = 0.0;
int correctIterationCnt = 0;
public String reportPerformance() {
String ret = "";
double iterAcc = correctIterationCnt * 1.0 / iterationCnt;
double MRR_excludeLastIter = sum_inv_first_index * 1.0 / (iterationCnt - 1);
ret = String.format("file, %s, iterAcc, %f, MRR_ela, %f ", fname, iterAcc, MRR_excludeLastIter);
return ret;
}
}
public class CollectResultStatistics {
// collect the incorrect but successfully transformed results.
public int all_record_cnt = 0;
public int correct_identified_record_cnt = 0;
public int all_iter_cnt = 0;
public int correct_all_iter_cnt = 0;
public int all_scenario_cnt = 0;
public int correct_all_scenario_cnt = 0;
public int questionable_iteration = 0;
public int questionable_correct_iteration = 0;
public double sum_first_incorrect_inv_indexes = 0;
public AdaInspector inspector = new AdaInspector();
public String collectIncorrects(String fpath, FileMetrics fileInfo) throws IOException {
// read a file
File f = new File(fpath);
fileInfo.fname = f.getName();
String ret = "";
CSVReader cr = new CSVReader(new FileReader(f), ',', '"', '\0');
String[] pair;
ArrayList<DataRecord> allrec = new ArrayList<DataRecord>();
Vector<String[]> allrec_v2 = new Vector<String[]>();
while ((pair = cr.readNext()) != null) {
if (pair == null || pair.length <= 1)
break;
DataRecord tmp = new DataRecord();
tmp.id = pair[0] + "";
tmp.origin = pair[0];
tmp.target = pair[1];
allrec.add(tmp);
allrec_v2.add(pair);
}
cr.close();
assert (!allrec.isEmpty());
Tools tool = new Tools();
tool.init(allrec_v2);
PriorityQueue<DataRecord> wrong = new PriorityQueue<DataRecord>();
wrong.addAll(allrec);
Vector<String[]> examples = new Vector<String[]>();
ArrayList<String> exampleIDs = new ArrayList<String>();
while (!wrong.isEmpty()) {
DataRecord expRec = wrong.poll();
String[] exp = this.generateExample(expRec);
System.out.println("" + Arrays.toString(exp));
examples.add(exp);
exampleIDs.add(expRec.origin);
tool.learnProgramRule(examples);
// System.out.println("error cnt: " + wrong.size());
assignClassLabel(allrec, exampleIDs, tool.getProgramRule());
int runtimeErrorcnt = getFailedCnt(allrec);
ErrorCnt ecnt = new ErrorCnt();
ecnt.runtimeerror = runtimeErrorcnt;
ecnt.totalrecord = allrec.size();
all_iter_cnt++;
fileInfo.iterationCnt++;
wrong.clear();
runtimeErrorcnt = 0;
if (runtimeErrorcnt == 0) {
ArrayList<DataRecord> recmd = new ArrayList<DataRecord>();
inspector.initeInspector(tool.dpp, tool.msger, allrec, exampleIDs, tool.progRule);
for (DataRecord rec : allrec) {
// System.out.println(String.format("%s, %s", rec.origin,
// rec.transformed));
double value = inspector.getActionScore(rec);
rec.value = value;
if (value <= 0) {
recmd.add(rec);
}
if (inspector.getActionLabel(rec) == (rec.target.compareTo(rec.transformed) == 0 ? 1.0 : -1.0)) {
correct_identified_record_cnt++;
}
if (rec.transformed.compareTo(rec.target) != 0 && !exampleIDs.contains(rec.origin)) {
wrong.add(rec);
}
all_record_cnt++;
}
ArrayList<DataRecord> crecmd = getCorrectRecommand(recmd, wrong, ecnt);
System.out.println("" + recmd.size());
ecnt.recommand = recmd.size();
ecnt.correctrecommand = crecmd.size();
ecnt.precsion = ecnt.correctrecommand * 1.0 / ecnt.recommand;
ecnt.reductionRate = ecnt.recommand * 1.0 / ecnt.totalrecord;
boolean isIUI = true;
if (ecnt.correctrecommand > 0 || wrong.size() == 0) {
if(isIUI){
if(ecnt.firstErrorIndex == 1)
{
correct_all_iter_cnt++;
fileInfo.correctIterationCnt++;
}
}
else{
correct_all_iter_cnt++;
fileInfo.correctIterationCnt++;
}
questionable_correct_iteration++;
}
questionable_iteration++;
if (ecnt.firstErrorIndex >= 0) {
this.sum_first_incorrect_inv_indexes += 1.0 / ecnt.firstErrorIndex;
fileInfo.sum_inv_first_index += 1.0 / ecnt.firstErrorIndex;
}
/*if (ecnt.firstErrorIndex > 1 || ecnt.firstErrorIndex <= 0) {
this.sum_first_incorrect_inv_indexes += 0;
} else {
this.sum_first_incorrect_inv_indexes += 1;
}*/
} else {
for (DataRecord rec : allrec) {
rec.value = 0;
if (rec.transformed.compareTo(rec.target) != 0 && !exampleIDs.contains(rec.origin)) {
wrong.add(rec);
}
}
if (wrong.size() != 0) {
ecnt.firstErrorIndex = 1;
this.sum_first_incorrect_inv_indexes += 1;
fileInfo.sum_inv_first_index += 1;
}
correct_all_iter_cnt++;
fileInfo.correctIterationCnt++;
}
ecnt.totalerror = wrong.size();
System.out.println("" + tool.progRule.toString());
ret += printResult(ecnt) + "\n";
}
return ret;
}
public String[] generateExample(DataRecord rec) {
String[] xStrings = { "<_START>" + rec.origin + "<_END>", rec.target };
return xStrings;
}
public PriorityQueue<DataRecord> assignClassLabel(ArrayList<DataRecord> allrec, ArrayList<String> expIds, ProgramRule prog) {
PriorityQueue<DataRecord> ret = new PriorityQueue<DataRecord>();
if (prog.pClassifier != null) {
for (DataRecord record : allrec) {
record.classLabel = prog.pClassifier.getLabel(record.origin);
}
}
for (DataRecord rec : allrec) {
rec.transformed = prog.transform(rec.origin);
if (rec.transformed.compareTo(rec.target) != 0 && !expIds.contains(rec.id)) {
ret.add(rec);
}
}
return ret;
}
public int getFailedCnt(ArrayList<DataRecord> wrong) {
int cnt = 0;
for (DataRecord s : wrong) {
// Prober.CheckSpecificRecord(s);
if (s.transformed.contains("_FATAL_ERROR_")) {
cnt++;
}
}
return cnt;
}
public ArrayList<DataRecord> getCorrectRecommand(ArrayList<DataRecord> recmd, PriorityQueue<DataRecord> wrong, ErrorCnt repo) {
HashSet<String> rawInputs = new HashSet<String>();
for (DataRecord rec : wrong) {
if (!rawInputs.contains(rec.origin)) {
rawInputs.add(rec.origin);
}
}
ArrayList<DataRecord> ret = new ArrayList<DataRecord>();
for (int i = 0; i < recmd.size(); i++) {
DataRecord rec = recmd.get(i);
if (rawInputs.contains(rec.origin)) {
if (repo.firstErrorIndex == -1) {
repo.firstErrorIndex = i + 1;
}
ret.add(rec);
}
}
return ret;
}
public String printResult(ErrorCnt ecnt) {
String s = "";
s += String.format("rt, %d, e,%d,t,%d, r,%d, cr, %d, first, %d, red, %f, pre, %f", ecnt.runtimeerror, ecnt.totalerror, ecnt.totalrecord, ecnt.recommand, ecnt.correctrecommand,
ecnt.firstErrorIndex, ecnt.reductionRate, ecnt.precsion);
/*
* for (String[] e : wrong) { s += String.format("%s, %s, %s ||", e[0],
* e[1], e[2]); }
*/
return s;
}
public double[] parameterSelection(double parameter) {
String dirpath = "/Users/bowu/Research/testdata/TestSingleFile/";
File nf = new File(dirpath);
File[] allfiles = nf.listFiles();
AdaInspectorTrainer.questionablePreference = parameter;
double[] ret = { 0, 0, 0, 0 };
inspector = new AdaInspector();
inspector.initeParameter();
String allFilesInfo = "";
String line = "";
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/Users/bowu/Research/Feedback/result" + parameter + ".txt")));
for (File f : allfiles) {
if (f.getName().indexOf(".csv") == -1 || (f.getName().indexOf(".csv") != (f.getName().length() - 4))) {
continue;
}
bw.write(f.getName() + "\n");
FileMetrics fileInfo = new FileMetrics();
line = collectIncorrects(f.getAbsolutePath(), fileInfo) + "\n";
allFilesInfo += fileInfo.reportPerformance() + "\n";
System.out.println("" + line);
bw.write(line);
}
ret[0] = correct_all_iter_cnt * 1.0 / all_iter_cnt;
ret[1] = questionable_correct_iteration * 1.0 / questionable_iteration;
ret[2] = correct_identified_record_cnt * 1.0 / all_record_cnt;
ret[3] = sum_first_incorrect_inv_indexes * 1.0 / all_iter_cnt;
bw.flush();
bw.close();
System.out.println("" + allFilesInfo);
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
public static void main(String[] args) {
String ret = "";
for (double p = 5; p <= 5; p += 1) {
CollectResultStatistics collect = new CollectResultStatistics();
double[] one = collect.parameterSelection(p);
ret += String.format("%f, a, %f, q, %f, r, %f, avg_first %f", p, one[0], one[1], one[2], one[3]) + "\n";
}
System.out.println("" + ret);
// EmailNotification alert = new EmailNotification();
// alert.notify(true, ret);
}
}
|
package graphana.graphs.visualization.output;
import java.awt.*;
/**
* Implementing class holds a contour color
*
* @author Andreas Fender
*/
public interface GraphOutputContourColor {
public Color getContourColor();
}
|
package com.sudipatcp.tree;
import java.util.ArrayList;
public class ZigZagLevelOrder {
public void printLevelOrder(Node root){
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
int h = height(root);
int i;
ArrayList<Integer> hold;
for (i=1; i <=h; i++){
ArrayList<Integer> tmp = new ArrayList<>();
if(i % 2 != 0){
hold = printGivenLevelOdd(root, i ,tmp);
}else {
hold = printGivenLevelEven(root, i, tmp);
}
ans.add(hold);
}
System.out.println(ans);
}
private ArrayList<Integer> printGivenLevelEven(Node root, int level, ArrayList<Integer> tmp) {
if (root == null)
return null;
if (level == 1){
//System.out.print(root.data + " ");
tmp.add(root.data);
}
else if (level > 1)
{
printGivenLevelEven(root.right, level-1, tmp);
printGivenLevelEven(root.left, level-1, tmp);
}
return tmp;
}
private ArrayList<Integer> printGivenLevelOdd(Node root, int level, ArrayList<Integer> tmp) {
if (root == null)
return null;
if (level == 1){
//System.out.print(root.data + " ");
tmp.add(root.data);
}
else if (level > 1)
{
printGivenLevelOdd(root.left, level-1, tmp);
printGivenLevelOdd(root.right, level-1, tmp);
}
return tmp;
}
public int height(Node root){
if(root == null){
return 0;
}else{
int lHeight = height(root.left);
int rHeight = height(root.right);
if (lHeight > rHeight)
return(lHeight+1);
else
return(rHeight+1);
}
}
public static void main(String[] args) {
ZigZagLevelOrder zg = new ZigZagLevelOrder();
Node bTree = new Node(1);
bTree.left = new Node(2);
bTree.right = new Node(3);
bTree.right.left = new Node(4);
bTree.right.right = new Node(5);
zg.printLevelOrder(bTree);
}
}
|
package com.jhy.reduce;
import com.jhy.entity.TerminalTypeInfo;
import com.jhy.util.MongoUtils;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.bson.Document;
/**
* 用户终端偏好标签Sink
* 将统计的结果数量存到Mongo里
*
* Created by JHy on 2019/05/13
*/
public class TerminalTypeSink implements SinkFunction<TerminalTypeInfo> {
@Override
public void invoke(TerminalTypeInfo value, Context context) throws Exception {
String terminaltype = value.getTerminaltype();
long count = value.getCount();
Document doc = MongoUtils.findoneby("terminaltypestatics","jhyPortrait",terminaltype);
if(doc == null){
doc = new Document();
doc.put("info",terminaltype);
doc.put("count",count);
}else{
Long countpre = doc.getLong("count");
Long total = countpre+count;
doc.put("count",total);
}
MongoUtils.saveorupdatemongo("terminaltypestatics","jhyPortrait",doc);
}
}
|
package com.mx.profuturo.bolsa.service.reports;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import com.mx.profuturo.bolsa.model.reports.vo.ReportVO;
public interface ExcelService {
void downloadXLSXFile(HttpServletResponse response, ReportVO report) throws IOException;
}
|
package com.tencent.rtmp.sharp.jni;
import android.content.Intent;
import java.util.ArrayList;
class TraeAudioManager$2 implements Runnable {
final /* synthetic */ ArrayList a;
final /* synthetic */ String b;
final /* synthetic */ String c;
final /* synthetic */ TraeAudioManager d;
TraeAudioManager$2(TraeAudioManager traeAudioManager, ArrayList arrayList, String str, String str2) {
this.d = traeAudioManager;
this.a = arrayList;
this.b = str;
this.c = str2;
}
public void run() {
Intent intent = new Intent();
intent.setAction("com.tencent.sharp.ACTION_TRAEAUDIOMANAGER_NOTIFY");
intent.putExtra("PARAM_OPERATION", "NOTIFY_DEVICELISTUPDATE");
intent.putExtra("EXTRA_DATA_AVAILABLEDEVICE_LIST", (String[]) this.a.toArray(new String[0]));
intent.putExtra("EXTRA_DATA_CONNECTEDDEVICE", this.b);
intent.putExtra("EXTRA_DATA_PREV_CONNECTEDDEVICE", this.c);
intent.putExtra("EXTRA_DATA_IF_HAS_BLUETOOTH_THIS_IS_NAME", this.d._deviceConfigManager.d());
if (this.d._context != null) {
this.d._context.sendBroadcast(intent);
}
}
}
|
/*
* Copyright (C) 2013 readyState Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.readystatesoftware.systembartint.sample;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import com.readystatesoftware.systembartint.SystemBarTintManager;
public class MatchActionBarActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match_actionbar);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatus(true);
}
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.statusbar_bg);
}
@TargetApi(19)
private void setTranslucentStatus(boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}
|
package com.seemoreinteractive.seemoreinteractive;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Text;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.seemoreinteractive.seemoreinteractive.Model.OrderModel;
import com.seemoreinteractive.seemoreinteractive.Model.SessionManager;
import com.seemoreinteractive.seemoreinteractive.Model.UserOrder;
import com.seemoreinteractive.seemoreinteractive.Utils.Constants;
import com.seemoreinteractive.seemoreinteractive.Utils.FileTransaction;
import com.seemoreinteractive.seemoreinteractive.fancycoverflow.FancyCoverFlow;
import com.seemoreinteractive.seemoreinteractive.helper.Common;
public class OrderConfirmation extends Activity {
String className = this.getClass().getSimpleName();
AQuery aq;
String[] expProdCartArray = null;
FancyCoverFlow fancyCoverFlowForCart;
HashMap<String, String> hashMapProdsWithClient, hashMapClientInfo, hashMapProdInfo;
char priceSymbol;
ArrayList<HashMap<String, String>> arrListHashMapProdsWithClient = new ArrayList<HashMap<String,String>>();
int countFlagForClient = 0, countFlagForClientPds = 0;
public static ArrayList<String> arrListForProdInfo;
public static ArrayList<String> arrForClientIdsUnique = new ArrayList<String>();
public static HashSet<String> hashSetForClientIdsUnique = new HashSet<String>();
ArrayList<String> arrFinalAllClients = new ArrayList<String>();
ArrayList<String> arrFinalClientIds = new ArrayList<String>();
ArrayList<String> arrFinalClientsProducts = new ArrayList<String>();
public ArrayList<String> arrListForProdCount = new ArrayList<String>();
//public static ArrayList<JSONObject> arrListJsonObjMySavedOrders = new ArrayList<JSONObject>();
public static ArrayList<String> arrListJsonObjMySavedOrders = new ArrayList<String>();
JSONObject jsonObjMySavedOrders = new JSONObject();
SessionManager session;
TextView txtvMessgae ;
RelativeLayout shippingLayout;
public String shopFlag ="null",editOrderId="0",addressFlag="true";
FileTransaction file;
public static ArrayList<HashMap<String, String>> arrPdInfoForCartEditList,arrListHashMapForEditClientInfo;
public static ArrayList<String> arrForClientIds;
public static ArrayList<String> arrObjForShippingAddress;
public static String offerDiscountValue= "null",offerDiscountValuType = "null",clientId ="null",offerName="null",offerId="null";
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_confirmation);
try{
session = new SessionManager(getApplicationContext());
aq = new AQuery(OrderConfirmation.this);
txtvMessgae = (TextView) findViewById(R.id.txtvMessgae);
shippingLayout = (RelativeLayout)findViewById(R.id.shippingLayout);
new Common().clientLogoOrTitleWithThemeColorAndBgImgByPassingColor(
this, "ff2600",
"ff2600",
"ff2600",
Common.sessionClientLogo, "Order Confirmation", "");
new Common().headerAndFooterModules(OrderConfirmation.this);
Intent getIntent = getIntent();
if(getIntent.getExtras() != null){
shopFlag = getIntent.getStringExtra("shopFlag");
editOrderId = getIntent.getStringExtra("editOrderId");
Bundle bundle=getIntent.getExtras();
arrPdInfoForCartEditList = (ArrayList<HashMap<String, String>>) bundle.getSerializable("arrPdInfoForCartList");
arrListHashMapForEditClientInfo = (ArrayList<HashMap<String, String>>) bundle.getSerializable("arrListHashMapForClientInfo");
arrForClientIds = (ArrayList<String>) bundle.getSerializable("arrForClientIds");
file = new FileTransaction();
}
for (String item : ProductDetails.arrForClientIds) {
if (!hashSetForClientIdsUnique.contains(item)) {
arrForClientIdsUnique.add(item);
hashSetForClientIdsUnique.add(item);
}
}
if(shopFlag.equals("Edit")){
if(arrPdInfoForCartEditList.size()>0){
for(int i=0; i<arrPdInfoForCartEditList.size(); i++){
hashMapProdsWithClient = new HashMap<String, String>();
hashMapProdsWithClient.put(arrPdInfoForCartEditList.get(i).get("ClientId"), arrPdInfoForCartEditList.get(i).toString());
arrListHashMapProdsWithClient.add(hashMapProdsWithClient);
arrListForProdCount.add(arrPdInfoForCartEditList.get(i).get("ClientId"));
arrObjForShippingAddress = getIntent().getStringArrayListExtra("arrObjForShippingAddress");
//shippingAddressInfoShowingOnLayout(arrObjForShippingAddress, json.getString("statetax"), "");
Log.e("arrObjForShippingAddress",""+arrObjForShippingAddress);
basedOnShippingAddressInfoGetStateTax(arrObjForShippingAddress, "");
}
fancyCoverFlowForShoppingCartInfo(arrListHashMapForEditClientInfo, arrListHashMapProdsWithClient);
}
}else{
Log.e("ProductDetails.arrListHashMapForClientInfo",""+ProductDetails.arrListHashMapForClientInfo.size());
if(ProductDetails.arrPdInfoForCartList.size()>0){
for(int i=0; i<ProductDetails.arrPdInfoForCartList.size(); i++){
hashMapProdsWithClient = new HashMap<String, String>();
hashMapProdsWithClient.put(ProductDetails.arrPdInfoForCartList.get(i).get("ClientId"), ProductDetails.arrPdInfoForCartList.get(i).toString());
arrListHashMapProdsWithClient.add(hashMapProdsWithClient);
arrListForProdCount.add(ProductDetails.arrPdInfoForCartList.get(i).get("ClientId"));
}
fancyCoverFlowForShoppingCartInfo(ProductDetails.arrListHashMapForClientInfo, arrListHashMapProdsWithClient);
}else{
shippingAddressArrListVals = new ArrayList<String>();
shippingLayout.setVisibility(View.INVISIBLE);
txtvShippingAddressChange = (Button) findViewById(R.id.btnShippingAddressChange);
txtvShippingAddressChange.setVisibility(View.INVISIBLE);
txtvMessgae.setText("There are no products in your cart.");
}
}
getDynamicViewForLayout();
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | oncreate | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
private void fancyCoverFlowForShoppingCartInfo(ArrayList<HashMap<String, String>> arrListHashMapForClientInfo2, ArrayList<HashMap<String, String>> arrListHashMapProdsWithClient2) {
try{
fancyCoverFlowForCart = (FancyCoverFlow) findViewById(R.id.fancyCoverFlowForCart);
RelativeLayout.LayoutParams rlFancyCoverFlowCart = (RelativeLayout.LayoutParams) fancyCoverFlowForCart.getLayoutParams();
rlFancyCoverFlowCart.width = android.view.ViewGroup.LayoutParams.MATCH_PARENT;
rlFancyCoverFlowCart.height = (int) (0.5943 * Common.sessionDeviceHeight);
fancyCoverFlowForCart.setLayoutParams(rlFancyCoverFlowCart);
ArrayList<String> arrNewList = new ArrayList<String>();
arrNewList.add(arrListHashMapForClientInfo2.toString());
ArrayList<HashMap<String, String>> arrListHashMapForClientInfo = new ArrayList<HashMap<String, String>>();
for(int j = arrListHashMapForClientInfo2.size() - 1; j >= 0; j--){
arrListHashMapForClientInfo.add(arrListHashMapForClientInfo2.get(j));
}
//Log.e("arrListHashMapForClientInfo new ",""+arrListHashMapForClientInfo);
fancyCoverFlowForCart.setAdapter(renderCoverFlowForShoppingCart(arrListHashMapForClientInfo, arrListHashMapProdsWithClient2));
fancyCoverFlowForCart.setSpacing(-(int)(0.2 * Common.sessionDeviceWidth));
fancyCoverFlowForCart.setMaxRotation(45);
}catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | fancuCoverFlowForShoppingCartInfo | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this,errorMsg);
}
}
TextView txtvSalesTaxPrice, txtvOrderTotalPrice, txtvSubOrderTotalPrice, txtvShippingAddress1, txtvShippingAddress2;
Button txtvShippingAddressChange;
private void getDynamicViewForLayout() {
// TODO Auto-generated method stub
try{
TextView txtShippingAddressTitle = (TextView) findViewById(R.id.txtShippingAddressTitle);
txtShippingAddressTitle.setTextSize((float)(0.04167 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
RelativeLayout.LayoutParams rlForShippingAddressTitle = (RelativeLayout.LayoutParams) txtShippingAddressTitle.getLayoutParams();
rlForShippingAddressTitle.leftMargin = (int) (0.025 * Common.sessionDeviceWidth);
//rlForShippingAddressTitle.topMargin = (int) (0.0154 * Common.sessionDeviceHeight);
//rlForShippingAddressTitle.topMargin = (int) (0.0286 * Common.sessionDeviceHeight);
txtShippingAddressTitle.setLayoutParams(rlForShippingAddressTitle);
txtvShippingAddress1 = (TextView) findViewById(R.id.txtvShippingAddress1);
txtvShippingAddress1.setTextSize((float)(0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
RelativeLayout.LayoutParams rlForShippingAddress1 = (RelativeLayout.LayoutParams) txtvShippingAddress1.getLayoutParams();
rlForShippingAddress1.width = (int) (0.5 * Common.sessionDeviceWidth);
//rlForShippingAddress1.height = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
//rlForShippingAddress1.leftMargin = (int) (0.075 * Common.sessionDeviceWidth);
txtvShippingAddress1.setLayoutParams(rlForShippingAddress1);
txtvShippingAddress2 = (TextView) findViewById(R.id.txtvShippingAddress2);
txtvShippingAddress2.setTextSize((float)(0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
RelativeLayout.LayoutParams rlForShippingAddress2 = (RelativeLayout.LayoutParams) txtvShippingAddress2.getLayoutParams();
rlForShippingAddress2.width = (int) (0.5 * Common.sessionDeviceWidth);
//rlForShippingAddress2.height = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
//rlForShippingAddress2.leftMargin = (int) (0.04 * Common.sessionDeviceWidth);
txtvShippingAddress2.setLayoutParams(rlForShippingAddress2);
if(ProductDetails.arrPdInfoForCartList.size()>0){
shippingButtonText();
}
txtvShippingAddressChange = (Button) findViewById(R.id.btnShippingAddressChange);
RelativeLayout.LayoutParams rlFortxtvShippingAddressChange = (RelativeLayout.LayoutParams) txtvShippingAddressChange.getLayoutParams();
//rlFortxtvShippingAddressChange.leftMargin = (int) (0.0984 * Common.sessionDeviceWidth);
rlFortxtvShippingAddressChange.width = (int) (0.1667 * Common.sessionDeviceWidth);
rlFortxtvShippingAddressChange.height = (int) (0.031 * Common.sessionDeviceHeight);
txtvShippingAddressChange.setLayoutParams(rlFortxtvShippingAddressChange);
txtvShippingAddressChange.setTextSize((float)(0.0334 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
txtvShippingAddressChange.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
//showShippingAddressInfoAsListView();
txtvShippingAddressChange.setEnabled(false);
JSONObject jsonObj = new JSONObject();
jsonObj.put("userId", ""+Common.sessionIdForUserLoggedIn);
Map<String, Object> params = new HashMap<String, Object>();
params.put("json", jsonObj);
params.put("userid", Common.sessionIdForUserLoggedIn);
String productUrl = Constants.Live_Url+"mobileapps/ios/public/stores/usershipping";
aq.ajax(productUrl, params, JSONArray.class, new AjaxCallback<JSONArray>(){
@Override
public void callback(String url, JSONArray json, AjaxStatus status) {
try{
txtvShippingAddressChange.setEnabled(true);
if(json != null){
if(json.length() > 0){
Intent intent = new Intent(getApplicationContext(), ShippingListInfo.class);
intent.putExtra("userShipId", userShipIdForEdit);
if(shopFlag.equals("Edit")){
intent.putExtra("editOrderId", editOrderId);
}
intent.putExtra("jsonArray", json.toString());
int requestCode = 0;
startActivityForResult(intent, requestCode);
overridePendingTransition(R.xml.slide_in_left, R.xml.slide_out_right);
} else {
Intent intent = new Intent(getApplicationContext(), ShippingAddressForm.class);
intent.putExtra("userShipId", userShipIdForEdit);
int requestCode = 0;
startActivityForResult(intent, requestCode);
overridePendingTransition(R.xml.slide_in_left, R.xml.slide_out_right);
}
}
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | aq.ajax showShippingAddressInfoAsListView callback click | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
});
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | shippingAddressChangeAdd onclick | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
});
TextView txtvSalesTaxTitle = (TextView) findViewById(R.id.txtvSalesTaxTitle);
txtvSalesTaxTitle.setTextSize((float)(0.04167 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
//RelativeLayout.LayoutParams rlFortxtvSalesTaxTitle = (RelativeLayout.LayoutParams) txtvSalesTaxTitle.getLayoutParams();
///rlForOrderTotalTitle.bottomMargin = (int) (0.0103 * Common.sessionDeviceHeight);
//rlFortxtvSalesTaxTitle.topMargin = (int) (0.115 * Common.sessionDeviceHeight);
//txtvSalesTaxTitle.setLayoutParams(rlFortxtvSalesTaxTitle);
txtvSalesTaxPrice = (TextView) findViewById(R.id.txtvSalesTaxPrice);
txtvSalesTaxPrice.setTextSize((float)(0.04167 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
TextView txtvOrderTotalTitle = (TextView) findViewById(R.id.txtvOrderTotalTitle);
txtvOrderTotalTitle.setTextSize((float)(0.05 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
RelativeLayout.LayoutParams rlForOrderTotalTitle = (RelativeLayout.LayoutParams) txtvOrderTotalTitle.getLayoutParams();
//rlForOrderTotalTitle.bottomMargin = (int) (0.0205 * Common.sessionDeviceHeight);
//rlForOrderTotalTitle.topMargin = (int) (0.0103 * Common.sessionDeviceHeight);
//txtvOrderTotalTitle.setLayoutParams(rlForOrderTotalTitle);
txtvSubOrderTotalPrice = (TextView) findViewById(R.id.txtvSubOrderTotalPrice);
txtvOrderTotalPrice = (TextView) findViewById(R.id.txtvOrderTotalPrice);
txtvOrderTotalPrice.setTextSize((float)(0.0417 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
RelativeLayout.LayoutParams rlForOrderTotalPrice = (RelativeLayout.LayoutParams) txtvOrderTotalPrice.getLayoutParams();
rlForOrderTotalPrice.width = (int) (0.4334 * Common.sessionDeviceWidth);
rlForOrderTotalPrice.height = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
//rlForOrderTotalPrice.rightMargin = (int) (0.075 * Common.sessionDeviceWidth);
txtvOrderTotalPrice.setLayoutParams(rlForOrderTotalPrice);
Button btnCheckout = (Button) findViewById(R.id.btnCheckout);
RelativeLayout.LayoutParams rlForBtnCheckout = (RelativeLayout.LayoutParams) btnCheckout.getLayoutParams();
rlForBtnCheckout.width = (int) (0.25 * Common.sessionDeviceWidth);
rlForBtnCheckout.height = (int) (0.0615 * Common.sessionDeviceHeight);
//rlForBtnCheckout.topMargin = (int) (0.0052 * Common.sessionDeviceHeight);
// rlForBtnCheckout.bottomMargin = (int) (0.0052 * Common.sessionDeviceHeight);
//rlForBtnCheckout.rightMargin = (int) (0.0417 * Common.sessionDeviceWidth);
btnCheckout.setLayoutParams(rlForBtnCheckout);
btnCheckout.setTextSize((float)(0.0417 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
btnCheckout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
if(Common.isNetworkAvailable(OrderConfirmation.this)){
if(!session.isLoggedIn()){
new Common().getLoginDialog(OrderConfirmation.this, OrderConfirmation.class, "OrderConfirmation", new ArrayList<String>());
} else {
final ArrayList<String> arrFinalAll = new ArrayList<String>();
if(shippingAddressArrListVals.size()==0){
Toast.makeText(getApplicationContext(), "Please add your shipping address and then click on Checkout.", Toast.LENGTH_LONG).show();
} else {
PackageManager manager = OrderConfirmation.this.getPackageManager();
PackageInfo info = manager.getPackageInfo(OrderConfirmation.this.getPackageName(), 0);
final String sessionId = Common.randomString(40);
final JSONObject jsonObjForAnalytics = new JSONObject();
jsonObjForAnalytics.put("session_id", sessionId);
jsonObjForAnalytics.put("device_type", android.os.Build.MODEL);
jsonObjForAnalytics.put("device_os_version", android.os.Build.VERSION.RELEASE);
jsonObjForAnalytics.put("device_os", "ANDROID");
jsonObjForAnalytics.put("device_brand", android.os.Build.BRAND);
jsonObjForAnalytics.put("lat_long", Common.lat+","+Common.lng);
jsonObjForAnalytics.put("device_bundle_version", info.versionName+" ("+info.versionCode+")");
JSONObject jsonObj = new JSONObject();
jsonObj.put("userId", ""+Common.sessionIdForUserLoggedIn);
//jsonObj.put("orderId", 0);
if(shopFlag.equals("null")){
if(arrListJsonObjMySavedOrders.size()==0){
jsonObj.put("orderId", 0);
}else{
jsonObj.put("orderId", arrListJsonObjMySavedOrders.get(0));
}
}else{
jsonObj.put("orderId", editOrderId);
}
jsonObj.put("orderTotal", txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""));
jsonObj.put("salesTax", txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
jsonObj.put("salesTaxValue", txtvSalesTaxPrice.getTag());
jsonObj.put("shippingAddress", jsonObjForShippingAddress);
jsonObj.put("clients", jsonArrayForClients);
jsonObj.put("analytics", jsonObjForAnalytics);
jsonObj.put("session_id", sessionId);
jsonObj.put("userShipId", userShipIdForEdit);
arrFinalAll.add(jsonObj.toString().replace("\\", ""));
Map<String, Object> params = new HashMap<String, Object>();
params.put("json", arrFinalAll.get(0));
params.put("userid", Common.sessionIdForUserLoggedIn);
if(Common.sessionIdForUserLoggedIn!=0){
String orderCreateUrl = Constants.Live_Url+"mobileapps/ios/public/stores/order/create/";
aq.ajax(orderCreateUrl, params, JSONObject.class, new AjaxCallback<JSONObject>(){
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
try{
if(json!=null){
if(json.getString("msg").equals("success")){
arrFinalAll.clear();
JSONObject jsonObj = new JSONObject();
jsonObj.put("userId", ""+Common.sessionIdForUserLoggedIn);
jsonObj.put("orderId", json.getString("orderID"));
jsonObj.put("orderTotal", txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = dateFormat.format(new Date());
jsonObj.put("orderDate", currentDateandTime);
jsonObj.put("salesTax", txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
jsonObj.put("salesTaxValue", txtvSalesTaxPrice.getTag());
jsonObj.put("shippingAddress", jsonObjForShippingAddress);
jsonObj.put("clients", jsonArrayForClients);
jsonObj.put("analytics", jsonObjForAnalytics);
jsonObj.put("session_id", sessionId);
arrFinalAll.add(jsonObj.toString().replace("\\", ""));
/*jsonObjMySavedOrders.put("orderId", json.getString("orderID"));
jsonObjMySavedOrders.put("orderTotal", txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""));
jsonObjMySavedOrders.put("orderDate", currentDateandTime);
arrListJsonObjMySavedOrders.add(jsonObjMySavedOrders);
*/
if(arrListJsonObjMySavedOrders.size() == 0){
arrListJsonObjMySavedOrders.add(json.getString("orderID"));
}
Intent intent = new Intent(getApplicationContext(), ProductsCheckout.class);
int requestCode = 0;
intent.putExtra("orderId", json.getString("orderID"));
intent.putExtra("finalMsg", json.getJSONObject("payment").getString("saveOrderMsg"));
intent.putStringArrayListExtra("arrFinalAll", arrFinalAll);
intent.putExtra("shopFlag", shopFlag);
startActivityForResult(intent, requestCode);
}
//Toast.makeText(getApplicationContext(), "Successfully saved to your Order.", Toast.LENGTH_LONG).show();
/*Intent intent = new Intent(ProductsCheckout.this, ThankYou.class);
intent.putExtra("finalMsg", json.getJSONObject("payment").getString("saveOrderMsg"));
startActivity(intent);
finish();
overridePendingTransition(R.xml.slide_in_left,R.xml.slide_out_left);*/
}
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | btnCheckout callback | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
});
}
}
}
}
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | Checkout button onclick | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
});
Button btnShop = (Button) findViewById(R.id.btnShop);
RelativeLayout.LayoutParams rlForBtnShop= (RelativeLayout.LayoutParams) btnShop.getLayoutParams();
rlForBtnShop.width = (int) (0.25 * Common.sessionDeviceWidth);
rlForBtnShop.height = (int) (0.0615 * Common.sessionDeviceHeight);
btnShop.setLayoutParams(rlForBtnShop);
btnShop.setTextSize((float)(0.0417 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
btnShop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(OrderConfirmation.this, Products.class);
if(shopFlag.equals("Edit")){
Products.prds.finish();
intent.putExtra("shopFlag", "Edit");
intent.putExtra("orderId", editOrderId);
}else{
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
}
startActivity(intent);
overridePendingTransition(R.xml.slide_in_right,R.xml.slide_out_right);
finish();
}
});
Button btnSaveOrder = (Button) findViewById(R.id.btnSaveOrder);
RelativeLayout.LayoutParams rlForbtnSaveOrder= (RelativeLayout.LayoutParams) btnSaveOrder.getLayoutParams();
rlForbtnSaveOrder.width = (int) (0.25 * Common.sessionDeviceWidth);
rlForbtnSaveOrder.height = (int) (0.0615 * Common.sessionDeviceHeight);
rlForbtnSaveOrder.bottomMargin = (int) (0.0103 * Common.sessionDeviceHeight);
btnSaveOrder.setLayoutParams(rlForbtnSaveOrder);
btnSaveOrder.setTextSize((float)(0.0417 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
btnSaveOrder.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try{
if(Common.isNetworkAvailable(OrderConfirmation.this)){
PackageManager manager = OrderConfirmation.this.getPackageManager();
PackageInfo info = manager.getPackageInfo(OrderConfirmation.this.getPackageName(), 0);
final ArrayList<String> arrFinalAll = new ArrayList<String>();
final String sessionId = Common.randomString(40);
final JSONObject jsonObjForAnalytics = new JSONObject();
jsonObjForAnalytics.put("session_id", sessionId);
jsonObjForAnalytics.put("device_type", android.os.Build.MODEL);
jsonObjForAnalytics.put("device_os_version", android.os.Build.VERSION.RELEASE);
jsonObjForAnalytics.put("device_os", "ANDROID");
jsonObjForAnalytics.put("device_brand", android.os.Build.BRAND);
jsonObjForAnalytics.put("lat_long", Common.lat+","+Common.lng);
jsonObjForAnalytics.put("device_bundle_version", info.versionName+" ("+info.versionCode+")");
JSONObject jsonObj = new JSONObject();
jsonObj.put("userId", ""+Common.sessionIdForUserLoggedIn);
if(shopFlag.equals("null"))
if(arrListJsonObjMySavedOrders.size()==0){
jsonObj.put("orderId", 0);
}else{
jsonObj.put("orderId", arrListJsonObjMySavedOrders.get(0));
}
else
jsonObj.put("orderId", editOrderId);
jsonObj.put("orderTotal", txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""));
jsonObj.put("salesTax", txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
jsonObj.put("salesTaxValue", txtvSalesTaxPrice.getTag());
jsonObj.put("shippingAddress", jsonObjForShippingAddress);
jsonObj.put("userShipId", userShipIdForEdit);
jsonObj.put("clients", jsonArrayForClients);
jsonObj.put("analytics", jsonObjForAnalytics);
jsonObj.put("session_id", sessionId);
jsonObj.put("paymentMethod", "Save Order");
jsonObj.put("paymentMethodId", "1");
arrFinalAll.add(jsonObj.toString().replace("\\", ""));
Map<String, Object> params = new HashMap<String, Object>();
params.put("json", arrFinalAll.get(0));
params.put("userid", Common.sessionIdForUserLoggedIn);
Log.e("params",""+params);
if(Common.sessionIdForUserLoggedIn!=0){
if(shippingAddressArrListVals.size()==0){
Toast.makeText(getApplicationContext(), "Please add your shipping address and then save order.", Toast.LENGTH_LONG).show();
}else{
String orderCreateUrl = Constants.Live_Url+"mobileapps/ios/public/stores/order/create/";
aq.ajax(orderCreateUrl, params, JSONObject.class, new AjaxCallback<JSONObject>(){
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
try{
if(json!=null){
if(json.getString("msg").equals("success")){
file = new FileTransaction();
OrderModel getOrders = file.getOrder();
int orderID = Integer.parseInt(json.getString("orderID").toString());
UserOrder existUserOrder = getOrders.getUserOrder(orderID);
Log.e("order client info",""+ProductDetails.arrListHashMapForClientInfo);
if(existUserOrder == null){
UserOrder userOrder = new UserOrder();
userOrder.setId(orderID);
userOrder.setCartClientInfoList(ProductDetails.arrListHashMapForClientInfo);
userOrder.setCartInfoList(ProductDetails.arrPdInfoForCartList);
userOrder.setClientIds(ProductDetails.arrForClientIds);
userOrder.setUserShipId(jsonObjForShippingAddress.get("userShipId").toString());
userOrder.setAddress1(jsonObjForShippingAddress.get("addr1").toString());
userOrder.setAddress2(jsonObjForShippingAddress.get("addr2").toString());
userOrder.setCity(jsonObjForShippingAddress.get("city").toString());
userOrder.setState(jsonObjForShippingAddress.get("state").toString());
userOrder.setZip(jsonObjForShippingAddress.get("zip").toString());
userOrder.setCountry(jsonObjForShippingAddress.get("country").toString());
//userOrder.setJsonObjForShippingAddress(jsonObjForShippingAddress);
userOrder.setOrderTotal(txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""));
userOrder.setSalesTax(txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
userOrder.setSalesTaxValue(txtvSalesTaxPrice.getTag().toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = dateFormat.format(new Date());
userOrder.setCreatedDate(currentDateandTime);
OrderModel orderModel = new OrderModel();
orderModel.add(userOrder);
FileTransaction file = new FileTransaction();
getOrders.mergeWith(orderModel);
file.setOrder(getOrders);
}else{
existUserOrder.setId(orderID);
existUserOrder.setCartClientInfoList(arrListHashMapForEditClientInfo);
existUserOrder.setCartInfoList(arrPdInfoForCartEditList);
existUserOrder.setClientIds(arrForClientIds);
existUserOrder.setUserShipId(jsonObjForShippingAddress.get("userShipId").toString());
existUserOrder.setAddress1(jsonObjForShippingAddress.get("addr1").toString());
existUserOrder.setAddress2(jsonObjForShippingAddress.get("addr2").toString());
existUserOrder.setCity(jsonObjForShippingAddress.get("city").toString());
existUserOrder.setState(jsonObjForShippingAddress.get("state").toString());
existUserOrder.setZip(jsonObjForShippingAddress.get("zip").toString());
existUserOrder.setCountry(jsonObjForShippingAddress.get("country").toString());
//userOrder.setJsonObjForShippingAddress(jsonObjForShippingAddress);
existUserOrder.setOrderTotal(txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""));
existUserOrder.setSalesTax(txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
existUserOrder.setSalesTaxValue(txtvSalesTaxPrice.getTag().toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = dateFormat.format(new Date());
existUserOrder.setCreatedDate(currentDateandTime);
getOrders.update(existUserOrder);
FileTransaction file = new FileTransaction();
file.setOrder(getOrders);
}
if(shopFlag.equals("null")){
ProductDetails.prdsDetail.finish();
ProductDetails.arrPdInfoForCartList.clear();
ProductDetails.arrForClientIds.clear();
ProductDetails.arrListHashMapForClientInfo.clear();
offerDiscountValue= "null";
offerDiscountValuType = "null";
offerName= "null";
offerId ="null";
clientId ="null";
}else{
SaveOrderInformation.saveOrder.finish();
}
Products.prds.finish();
OrderConfirmation.arrListJsonObjMySavedOrders.clear();
Intent intent = new Intent(OrderConfirmation.this, ThankYou.class);
intent.putExtra("finalMsg", json.getJSONObject("payment").getString("saveOrderMsg"));
startActivity(intent);
finish();
overridePendingTransition(R.xml.slide_in_left,R.xml.slide_out_left);
} else {
Toast.makeText(OrderConfirmation.this, "Opps! Your order updation failed. \nPlease contact us for more details.", Toast.LENGTH_SHORT).show();
}
}
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | btnCheckoutConfirm order update callback | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
});
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
});
if(shippingAddressArrListVals.size()>0){
if(shopFlag.equals("null")){
basedOnShippingAddressInfoGetStateTax(shippingAddressArrListVals, "");
}
}
}catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | getDynamicViewForLayout | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this,errorMsg);
}
}
public void shippingButtonText(){
try{
txtvShippingAddressChange = (Button) findViewById(R.id.btnShippingAddressChange);
JSONObject jsonObj = new JSONObject();
jsonObj.put("userId", ""+Common.sessionIdForUserLoggedIn);
Map<String, Object> params = new HashMap<String, Object>();
params.put("json", jsonObj);
params.put("userid", Common.sessionIdForUserLoggedIn);
String productUrl = Constants.Live_Url+"mobileapps/ios/public/stores/usershipping";
aq.ajax(productUrl, params, JSONArray.class, new AjaxCallback<JSONArray>(){
@Override
public void callback(String url, JSONArray json, AjaxStatus status) {
try{
if(json!=null){
if(json.length() > 0){
txtvShippingAddressChange.setText("Change");
if(shippingAddressArrListVals.size()==0){
for(int i=0; i<json.length(); i++){
JSONObject jsonObjForShippingInfo = json.getJSONObject(i);
shippingAddressArrListVals.add(jsonObjForShippingInfo.get("user_ship_addr_id").toString());
shippingAddressArrListVals.add(jsonObjForShippingInfo.get("user_ship_addr1").toString());
shippingAddressArrListVals.add(jsonObjForShippingInfo.get("user_ship_addr2").toString());
shippingAddressArrListVals.add(jsonObjForShippingInfo.get("user_ship_city").toString());
shippingAddressArrListVals.add(jsonObjForShippingInfo.get("user_ship_state").toString());
shippingAddressArrListVals.add(jsonObjForShippingInfo.get("user_ship_zip").toString());
shippingAddressArrListVals.add(jsonObjForShippingInfo.get("user_ship_country").toString());
shippingAddressArrListVals.add(jsonObjForShippingInfo.get("user_ship_status").toString());
shippingAddressArrListVals.add(jsonObjForShippingInfo.get("user_id").toString());
}
basedOnShippingAddressInfoGetStateTax(shippingAddressArrListVals, "");
}
}
else{
shippingAddressArrListVals = new ArrayList<String>();
double txtvSubOrderTotalPriceVal = Common.roundTwoDecimalsByStringCommon(txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, "")) - Common.roundTwoDecimalsByStringCommon(txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
txtvSalesTaxPrice.setText("$0.00");
txtvOrderTotalPrice.setText(""+priceSymbol+Common.roundTwoDecimalsCommon(txtvSubOrderTotalPriceVal));
txtvShippingAddressChange.setText("Add");
txtvShippingAddress1.setText("");
txtvShippingAddress2.setText("");
}
}
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | aq.ajax showShippingAddressInfoAsListView callback click | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
});
}catch(Exception e){
e.printStackTrace();
}
}
public HashMap<String, String> convertToHashMap(String arrayString) {
HashMap<String, String> myHashMap = new HashMap<String, String>();
try {
String str = arrayString.replace("{", "").replace("}", "");
String strNull = "";
String[] strArr = str.split(", ");
for (String str1 : strArr) {
String[] splited = str1.split("=");
if(splited[1].isEmpty()){
strNull = "";
} else {
strNull = splited[1].trim();
}
myHashMap.put(splited[0], strNull);
}
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | convertToHashMap | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
return myHashMap;
}
JSONObject jsonObjForClients;
JSONObject jsonObjForClientsProducts;
JSONArray jsonArrayForClientsProducts = new JSONArray(), jsonArrayForClients = new JSONArray();
double clientWiseTotalPrice = 0;
LinearLayout listViewForProds;
int gridItemLayout = 0;
int countForFlagArrAdp = 0;
ArrayList<String> newListViewArrPdsInfo;
String tempClientId = "";
String tempClientIdForPds = "";
String tempClientIdForClients = "";
String tempClientIdForClientsIds = "";
ArrayAdapter<HashMap<String, String>> aa;
float cartTotalPriceValues = 0;
String cartTotalPriceForAdd = "";
Spinner spinner;
ArrayList<String> spinnerArray, spinnerShipMethodValsArray;
ArrayAdapter<String> spinnerArrayAdapter;
int countForFlagArrAdpNew=0;
String shippingMethodName = "null", shippingMethodDetails = "null",
shippingMethodRateForTitle = "null", shippingMethodRate = "null";
public ArrayAdapter<HashMap<String, String>> renderCoverFlowForShoppingCart(final ArrayList<HashMap<String, String>> arrListHashMapForClientInfo2,
final ArrayList<HashMap<String, String>> arrListHashMapProdsWithClient2){
gridItemLayout = R.layout.coverflow_order_conf_pds_layout;
priceSymbol = '$';
final ArrayList<String> arrClientProdList = new ArrayList<String>();
cartTotalPriceForAdd = "";
aa = new ArrayAdapter<HashMap<String, String>>(this, gridItemLayout, arrListHashMapForClientInfo2){
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
Boolean shippingMethodFlag =false;
float cartTotalPrice = 0;
if(convertView == null){
convertView = getLayoutInflater().inflate(gridItemLayout, parent, false);
}
final View convertViewId = convertView;
countForFlagArrAdp = position;
if(position==countForFlagArrAdp){
final AQuery aq2 = new AQuery(convertView);
RelativeLayout coverflowLlayoutImage = (RelativeLayout)convertView.findViewById(R.id.coverflowLlayoutImage);
LinearLayout.LayoutParams rlForCoverflowLlayoutImage = (LinearLayout.LayoutParams) coverflowLlayoutImage.getLayoutParams();
rlForCoverflowLlayoutImage.width = (int)(0.75 * Common.sessionDeviceWidth);
rlForCoverflowLlayoutImage.height = (int) (0.522* Common.sessionDeviceHeight);
coverflowLlayoutImage.setLayoutParams(rlForCoverflowLlayoutImage);
RelativeLayout bigImageWithName = (RelativeLayout)convertView.findViewById(R.id.bigImageWithName);
RelativeLayout.LayoutParams rlForBigImageWithName = (RelativeLayout.LayoutParams) bigImageWithName.getLayoutParams();
rlForBigImageWithName.width = (int)(0.667 * Common.sessionDeviceWidth);
rlForBigImageWithName.height = (int) (0.461* Common.sessionDeviceHeight);
rlForBigImageWithName.bottomMargin = (int) (0.0205* Common.sessionDeviceHeight);
bigImageWithName.setLayoutParams(rlForBigImageWithName);
ScrollView scrollViewForPdList =(ScrollView)convertView.findViewById(R.id.scrollViewForPdList);
RelativeLayout.LayoutParams rlForScrollViewForPdList = (RelativeLayout.LayoutParams) scrollViewForPdList.getLayoutParams();
rlForScrollViewForPdList.width = (int)(0.667 * Common.sessionDeviceWidth);
rlForScrollViewForPdList.height = (int) (0.235* Common.sessionDeviceHeight);
rlForScrollViewForPdList.topMargin = (int) (0.0102* Common.sessionDeviceHeight);
scrollViewForPdList.setLayoutParams(rlForScrollViewForPdList);
listViewForProds = (LinearLayout) convertView.findViewById(R.id.listViewForProds);
ScrollView.LayoutParams rlForListViewForProds = (ScrollView.LayoutParams) listViewForProds.getLayoutParams();
rlForListViewForProds.height = (int) (0.153* Common.sessionDeviceHeight);
rlForListViewForProds.topMargin = (int) (0.0102* Common.sessionDeviceHeight);
rlForListViewForProds.bottomMargin = (int) (0.0102* Common.sessionDeviceHeight);
rlForListViewForProds.leftMargin = (int) (0.0167* Common.sessionDeviceWidth);
rlForListViewForProds.rightMargin = (int) (0.0167* Common.sessionDeviceWidth);
listViewForProds.setLayoutParams(rlForListViewForProds);
View separator2 =(View)convertView.findViewById(R.id.separator2);
RelativeLayout.LayoutParams rlForSeparator2 = (RelativeLayout.LayoutParams) separator2.getLayoutParams();
rlForSeparator2.width = (int)(0.75 * Common.sessionDeviceWidth);
rlForSeparator2.height = (int) (0.001* Common.sessionDeviceHeight);
rlForSeparator2.topMargin = (int) (0.00205* Common.sessionDeviceHeight);
separator2.setLayoutParams(rlForSeparator2);
TextView txtvCartTotalTitle = (TextView)convertView.findViewById(R.id.txtvCartTotalTitle);
RelativeLayout.LayoutParams rlForTxtvCartTotalTitle = (RelativeLayout.LayoutParams) txtvCartTotalTitle.getLayoutParams();
rlForListViewForProds.topMargin = (int) (0.0102* Common.sessionDeviceHeight);
txtvCartTotalTitle.setLayoutParams(rlForTxtvCartTotalTitle);
txtvCartTotalTitle.setTextSize((float)(0.0334 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
TextView txtvCartTotalPrice = (TextView)convertView.findViewById(R.id.txtvCartTotalPrice);
RelativeLayout.LayoutParams rlForTxtvCartTotalPrice = (RelativeLayout.LayoutParams) txtvCartTotalPrice.getLayoutParams();
rlForTxtvCartTotalPrice.rightMargin = (int) (0.0334 * Common.sessionDeviceWidth);
txtvCartTotalPrice.setLayoutParams(rlForTxtvCartTotalPrice);
txtvCartTotalPrice.setTextSize((float)(0.0334 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
/*TextView txtvShippingMethodTitle = (TextView)convertView.findViewById(R.id.txtvShippingMethodTitle);
RelativeLayout.LayoutParams rlForTxtvShippingMethodTitle= (RelativeLayout.LayoutParams) txtvShippingMethodTitle.getLayoutParams();
rlForTxtvShippingMethodTitle.bottomMargin = (int) (0.0102* Common.sessionDeviceHeight);
rlForTxtvShippingMethodTitle.leftMargin = (int) (0.0167* Common.sessionDeviceWidth);
txtvShippingMethodTitle.setLayoutParams(rlForTxtvShippingMethodTitle);
txtvShippingMethodTitle.setTextSize((float)(0.0334 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));*/
TextView txtvShippingCostTitle = (TextView)convertView.findViewById(R.id.txtvShippingCostTitle);
/*RelativeLayout.LayoutParams rlForTxtvShippingCostTitle= (RelativeLayout.LayoutParams) txtvShippingCostTitle.getLayoutParams();
rlForTxtvShippingCostTitle.rightMargin = (int) (0.0667* Common.sessionDeviceWidth);
txtvShippingCostTitle.setLayoutParams(rlForTxtvShippingCostTitle);*/
txtvShippingCostTitle.setTextSize((float)(0.0334 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
TextView txtvShippingSubTotalTitle = (TextView)convertView.findViewById(R.id.txtvShippingSubTotalTitle);
txtvShippingSubTotalTitle.setTextSize((float)(0.0334 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
TextView txtvShippingCostPrice = (TextView)convertView.findViewById(R.id.txtvShippingCostPrice);
RelativeLayout.LayoutParams rlFortxtvShippingCostPrice = (RelativeLayout.LayoutParams) txtvShippingCostPrice.getLayoutParams();
rlFortxtvShippingCostPrice.rightMargin = (int) (0.0334 * Common.sessionDeviceWidth);
txtvShippingCostPrice.setLayoutParams(rlFortxtvShippingCostPrice);
txtvShippingCostPrice.setTextSize((float)(0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
TextView txtvShippingSubTotalPrice = (TextView)convertView.findViewById(R.id.txtvShippingSubTotalPrice);
RelativeLayout.LayoutParams rlFortxtvShippingSubTotalPrice = (RelativeLayout.LayoutParams) txtvShippingSubTotalPrice.getLayoutParams();
rlFortxtvShippingSubTotalPrice.rightMargin = (int) (0.0334 * Common.sessionDeviceWidth);
txtvShippingSubTotalPrice.setLayoutParams(rlFortxtvShippingSubTotalPrice);
txtvShippingSubTotalPrice.setTextSize((float)(0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
TextView txtvShippingDelivery = (TextView)convertView.findViewById(R.id.txtvShippingDelivery);
RelativeLayout.LayoutParams rlForTxtvShippingDelivery= (RelativeLayout.LayoutParams) txtvShippingDelivery.getLayoutParams();
rlForTxtvShippingDelivery.leftMargin = (int) (0.01667* Common.sessionDeviceWidth);
txtvShippingDelivery.setLayoutParams(rlForTxtvShippingDelivery);
txtvShippingDelivery.setTextSize((float)(0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
TextView txtofferDiscountCost = (TextView)convertView.findViewById(R.id.txtofferDiscountCost);
RelativeLayout.LayoutParams rlFortxtofferDiscountCost = (RelativeLayout.LayoutParams) txtofferDiscountCost.getLayoutParams();
rlFortxtofferDiscountCost.rightMargin = (int) (0.0334 * Common.sessionDeviceWidth);
txtofferDiscountCost.setLayoutParams(rlFortxtofferDiscountCost);
txtofferDiscountCost.setTextSize((float)(0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
final TextView txtvofferName = (TextView)convertView.findViewById(R.id.txtvofferName);
RelativeLayout.LayoutParams rlForTxtvofferName = (RelativeLayout.LayoutParams) txtvofferName.getLayoutParams();
rlForTxtvofferName.width = (int) (0.2 * Common.sessionDeviceWidth);
txtvofferName.setLayoutParams(rlForTxtvofferName);
txtvofferName.setTextSize((float)(0.026667 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
final TextView txtvofferVal = (TextView)convertView.findViewById(R.id.txtvofferVal);
/*RelativeLayout.LayoutParams rlForTxtvofferVal = (RelativeLayout.LayoutParams) txtvofferVal.getLayoutParams();
rlForTxtvofferVal.width = (int) (0.2 * Common.sessionDeviceWidth); */
// txtvofferVal.setLayoutParams(rlForTxtvofferName);
txtvofferVal.setTextSize((float)(0.026667 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
final ImageView imgClose = (ImageView)convertView.findViewById(R.id.imgClose);
RelativeLayout.LayoutParams rlForImgClose = (RelativeLayout.LayoutParams) imgClose.getLayoutParams();
rlForImgClose.width = (int) (0.05 * Common.sessionDeviceWidth);
rlForImgClose.height = (int) (0.03074 * Common.sessionDeviceWidth);
imgClose.setLayoutParams(rlForImgClose);
TextView txtofferDiscountTitle = (TextView)convertView.findViewById(R.id.txtofferDiscountTitle);
txtofferDiscountTitle.setTextSize((float)(0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
/*listViewForProds.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(OrderConfirmation.this, ProductDetails.class);
setResult(1, intent);
finish();
overridePendingTransition(R.xml.slide_in_right,R.xml.slide_out_right);
}
});*/
if(!arrListHashMapForClientInfo2.get(position).isEmpty()){
try{
final HashMap<String, String> hashMapValues = arrListHashMapForClientInfo2.get(position);
TextView btnClientLogoOrName = (TextView) convertView.findViewById(R.id.btnClientLogoOrName);
RelativeLayout.LayoutParams rlpForBtnClientLogo = (RelativeLayout.LayoutParams) btnClientLogoOrName.getLayoutParams();
rlpForBtnClientLogo.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
rlpForBtnClientLogo.width = (int) (0.417 * Common.sessionDeviceWidth);
rlpForBtnClientLogo.height = (int) (0.041 * Common.sessionDeviceHeight);
btnClientLogoOrName.setText(hashMapValues.get("ClientName"));
btnClientLogoOrName.setTextSize((float) (0.0417 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
btnClientLogoOrName.setLayoutParams(rlpForBtnClientLogo);
shippingMethodName = hashMapValues.get("ShippingMethodName");
shippingMethodDetails = hashMapValues.get("ShippingMethodDetails");
shippingMethodRateForTitle = hashMapValues.get("ShippingMethodRateTitle");
shippingMethodRate = hashMapValues.get("ShippingMethodRate");
Log.e("hashMapValues.getofferId)",hashMapValues.get("offer_id"));
if(!hashMapValues.get("offer_id").equals("null")){
offerId = hashMapValues.get("offer_id");
offerName = hashMapValues.get("offer_name");
offerDiscountValue = hashMapValues.get("offer_discount");
offerDiscountValuType = hashMapValues.get("offer_discount_type");
clientId = hashMapValues.get("ClientId");
Log.e("offerDiscountValue",offerDiscountValue);
}
final HashMap<String, String> hashMapValuesNew = hashMapValues;
LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
String prodID = "null";
int l=0;
for(int c=0; c<arrListHashMapProdsWithClient2.size(); c++){
//Log.e("c",""+c);
final int arrIndex = c;
HashMap<String, String> hashMapValuesForListView = arrListHashMapProdsWithClient2.get(c);
if(hashMapValuesForListView.get(hashMapValues.get("ClientId"))!=null){
final HashMap<String, String> hashMapValuesForListViewNew = convertToHashMap(hashMapValuesForListView.get(hashMapValues.get("ClientId")));
arrClientProdList.add(hashMapValuesForListViewNew.get("ClientId"));
final int arrClientIndex = l;
View child = inflater.inflate(R.layout.listview_order_conf_pds_layout_new, null);
AQuery aq3 = new AQuery(child);
prodID = hashMapValuesForListViewNew.get("ProdId");
TextView txtvExpProductName = (TextView)child.findViewById(R.id.txtvExpProductName);
TableRow.LayoutParams rlForTxtvExpProductName = (TableRow.LayoutParams) txtvExpProductName.getLayoutParams();
rlForTxtvExpProductName.width = (int)(0.2167 * Common.sessionDeviceWidth);
txtvExpProductName.setLayoutParams(rlForTxtvExpProductName);
txtvExpProductName.setTextSize((float) (0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
TextView txtvExpProdQuantityWithPrice = (TextView)child.findViewById(R.id.txtvExpProdQuantityWithPrice);
TableRow.LayoutParams rlForTxtvExpProdQuantityWithPrice = (TableRow.LayoutParams) txtvExpProdQuantityWithPrice.getLayoutParams();
rlForTxtvExpProdQuantityWithPrice.width = (int)(0.2167 * Common.sessionDeviceWidth);
// rlForTxtvExpProdQuantityWithPrice.rightMargin = (int)(0.00834 * Common.sessionDeviceWidth);
txtvExpProdQuantityWithPrice.setLayoutParams(rlForTxtvExpProdQuantityWithPrice);
txtvExpProdQuantityWithPrice.setTextSize((float) (0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
TextView txtvExpProdPrice = (TextView)child.findViewById(R.id.txtvExpProdPrice);
TableRow.LayoutParams rlForTxtvExpProdPrice = (TableRow.LayoutParams) txtvExpProdPrice.getLayoutParams();
rlForTxtvExpProdPrice.width = (int)(0.2167 * Common.sessionDeviceWidth);
txtvExpProdPrice.setLayoutParams(rlForTxtvExpProdPrice);
txtvExpProdPrice.setTextSize((float) (0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
ImageView imgvExpProdImage = (ImageView)child.findViewById(R.id.imgvExpProdImage);
LinearLayout.LayoutParams rlForImgvExpProdImage = (LinearLayout.LayoutParams) imgvExpProdImage.getLayoutParams();
rlForImgvExpProdImage.width = (int)(0.1 * Common.sessionDeviceWidth);
rlForImgvExpProdImage.height = (int)(0.0615 * Common.sessionDeviceHeight);
imgvExpProdImage.setLayoutParams(rlForImgvExpProdImage);
RelativeLayout llForColoSize = (RelativeLayout)child.findViewById(R.id.llForColoSize);
LinearLayout.LayoutParams rlForllForColoSize = (LinearLayout.LayoutParams) llForColoSize.getLayoutParams();
rlForllForColoSize.leftMargin = (int)(0.01667 * Common.sessionDeviceWidth);
rlForllForColoSize.topMargin = (int)(0.01513 * Common.sessionDeviceHeight);
llForColoSize.setLayoutParams(rlForllForColoSize);
Button btnExpColorCode =(Button)child.findViewById(R.id.btnExpColorCode);
RelativeLayout.LayoutParams rlForBtnExpColorCode = (RelativeLayout.LayoutParams) btnExpColorCode.getLayoutParams();
rlForBtnExpColorCode.width = (int)(0.0416 * Common.sessionDeviceWidth);
rlForBtnExpColorCode.height = (int)(0.0256 * Common.sessionDeviceHeight);
btnExpColorCode.setLayoutParams(rlForBtnExpColorCode);
TextView txtvExpSizeLabel = (TextView)child.findViewById(R.id.txtvExpSizeLabel);
RelativeLayout.LayoutParams rlForTxtvExpSizeLabel = (RelativeLayout.LayoutParams) txtvExpSizeLabel.getLayoutParams();
rlForTxtvExpSizeLabel.topMargin = (int)(0.01513 * Common.sessionDeviceHeight);
txtvExpSizeLabel.setLayoutParams(rlForTxtvExpSizeLabel);
txtvExpSizeLabel.setTextSize((float) (0.025 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
TextView txtvExpSize = (TextView)child.findViewById(R.id.txtvExpSize);
RelativeLayout.LayoutParams rlForTxtvExpSize = (RelativeLayout.LayoutParams) txtvExpSize.getLayoutParams();
rlForTxtvExpSize.leftMargin = (int)(0.0134 * Common.sessionDeviceWidth);
txtvExpSize.setLayoutParams(rlForTxtvExpSize);
txtvExpSize.setTextSize((float) (0.025 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
LinearLayout llForProdActions = (LinearLayout)child.findViewById(R.id.llForProdActions);
TableRow.LayoutParams rlForllForProdActions = (TableRow.LayoutParams) llForProdActions.getLayoutParams();
rlForllForProdActions.rightMargin = (int)(0.0334 * Common.sessionDeviceWidth);
rlForllForProdActions.topMargin = (int)(0.0102 * Common.sessionDeviceHeight);
llForProdActions.setLayoutParams(rlForllForProdActions);
TextView imgvEditIcon = (TextView)child.findViewById(R.id.imgvEditIcon);
LinearLayout.LayoutParams rlForImgvEditIcon = (LinearLayout.LayoutParams) imgvEditIcon.getLayoutParams();
rlForImgvEditIcon.rightMargin = (int)(0.05 * Common.sessionDeviceWidth);
imgvEditIcon.setLayoutParams(rlForImgvEditIcon);
imgvEditIcon.setTextSize((float) (0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
TextView imgvRemoveIcon = (TextView)child.findViewById(R.id.imgvRemoveIcon);
LinearLayout.LayoutParams rlForImgvRemoveIcon = (LinearLayout.LayoutParams) imgvRemoveIcon.getLayoutParams();
rlForImgvRemoveIcon.height = (int)(0.031 * Common.sessionDeviceHeight);
rlForImgvRemoveIcon.rightMargin = (int)(0.05 * Common.sessionDeviceWidth);
rlForImgvRemoveIcon.topMargin = (int)(0.0102 * Common.sessionDeviceHeight);
rlForImgvRemoveIcon.bottomMargin = (int)(0.0102 * Common.sessionDeviceHeight);
imgvRemoveIcon.setLayoutParams(rlForImgvRemoveIcon);
imgvRemoveIcon.setTextSize((float) (0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
aq3.id(R.id.txtvExpProductName).text(hashMapValuesForListViewNew.get("ProdName"));
aq3.id(R.id.imgvExpProdImage).image(hashMapValuesForListViewNew.get("ProdImage"));
if(!hashMapValuesForListViewNew.get("Size").equals("null")){
aq3.id(R.id.txtvExpSize).visibility(View.VISIBLE);
aq3.id(R.id.txtvExpSize).text(hashMapValuesForListViewNew.get("Size"));
} else {
aq3.id(R.id.txtvExpSizeLabel).visibility(View.GONE);
aq3.id(R.id.txtvExpSize).visibility(View.GONE);
}
if(!hashMapValuesForListViewNew.get("Color").equals("null")){
aq3.id(R.id.btnExpColorCode).visibility(View.VISIBLE);
aq3.id(R.id.btnExpColorCode).backgroundColor(Color.parseColor(hashMapValuesForListViewNew.get("Color")));
} else {
aq3.id(R.id.btnExpColorCode).visibility(View.GONE);
}
aq3.id(R.id.txtvExpProdQuantityWithPrice).text("("+hashMapValuesForListViewNew.get("Quantity")+" X $"+(Common.roundTwoDecimalsByStringCommon(hashMapValuesForListViewNew.get("ProdPrice")))+")");
aq3.id(R.id.txtvExpProdPrice).text("$"+hashMapValuesForListViewNew.get("ProdPrice"));
int convertQunatity = 1;
if(hashMapValuesForListViewNew.get("Quantity").equals("null")){
convertQunatity = 1;
} else {
convertQunatity = Integer.parseInt(hashMapValuesForListViewNew.get("Quantity"));
}
double convertProdPrice = 0;
if(hashMapValuesForListViewNew.get("Quantity").equals("null")){
convertProdPrice = 1;
} else {
convertProdPrice = Common.roundTwoDecimalsByStringCommon(hashMapValuesForListViewNew.get("ProdPrice"));
}
double totalPrice = (convertQunatity)*(convertProdPrice);
aq3.id(R.id.txtvExpProdPrice).text("$"+Common.roundTwoDecimalsByStringCommon(""+totalPrice));
imgvEditIcon.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ProductDetails.editAction = true;
Intent intent = new Intent(OrderConfirmation.this, ProductDetails.class);
if(shopFlag.equals("null")){
//Bundle bundle = new Bundle();
//bundle.putParcelableArrayList("list", (ArrayList<? extends Parcelable>) arrListHashMapProdsWithClient2.get(arrIndex));
//intent.putExtras(bundle);
//intent.putExtra("list", arrListHashMapProdsWithClient2.get(arrIndex));
intent.putExtra("list", hashMapValuesForListViewNew);
intent.putExtra("pos", ""+arrIndex);
setResult(1, intent);
finish();
overridePendingTransition(R.xml.slide_in_right,R.xml.slide_out_right);
}else{
//String[] prodFinalArray =
ArrayList<String> prodResArrays = new ArrayList<String>();
prodResArrays.add(hashMapValuesForListViewNew.get("ProdImage").replaceAll(" ", "%20"));
prodResArrays.add(hashMapValuesForListViewNew.get("ClientId"));
prodResArrays.add(hashMapValuesForListViewNew.get("ProdId"));
prodResArrays.add(hashMapValuesForListViewNew.get("ProdName"));
prodResArrays.add(hashMapValuesForListViewNew.get("ClosetSeleStatus"));// closet selection status value
prodResArrays.add(hashMapValuesForListViewNew.get("ProdIsTryOn"));
prodResArrays.add(hashMapValuesForListViewNew.get("BgColorCode"));
if(!hashMapValuesForListViewNew.get("ClientLogo").equals("")){
prodResArrays.add(hashMapValuesForListViewNew.get("ClientLogo"));
} else{
prodResArrays.add("");
}
prodResArrays.add(hashMapValuesForListViewNew.get("LightBgColorCode"));
prodResArrays.add(hashMapValuesForListViewNew.get("DarkBgColorCode"));
prodResArrays.add(hashMapValuesForListViewNew.get("ProdButtonName"));
prodResArrays.add(hashMapValuesForListViewNew.get("ProdPrice"));
prodResArrays.add(hashMapValuesForListViewNew.get("ClientName"));
prodResArrays.add("0");
prodResArrays.add("null");
prodResArrays.add("null");
prodResArrays.add(hashMapValuesForListViewNew.get("isSeemoreCart"));
String[] prodFinalArray = new String[prodResArrays.size()];
prodFinalArray = prodResArrays.toArray(prodFinalArray);
intent = new Intent(OrderConfirmation.this, ProductDetails.class);
intent.putExtra("prodStrArr", prodFinalArray);
intent.putExtra("editAction", "true");
intent.putExtra("quantity", hashMapValuesForListViewNew.get("Quantity"));
intent.putExtra("orderId", editOrderId);
intent.putExtra("pos", ""+arrIndex);
startActivityForResult(intent, 1);
overridePendingTransition(R.xml.slide_in_left,R.xml.slide_out_left);
}
}
});
imgvRemoveIcon.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try{
LinearLayout listViewForProds = (LinearLayout) convertViewId.findViewById(R.id.listViewForProds);
listViewForProds.removeViewAt(arrClientIndex);
arrListHashMapProdsWithClient2.remove(arrIndex);
arrClientProdList.remove(hashMapValues.get("ClientId"));
arrListForProdCount.remove(hashMapValues.get("ClientId"));
if(shopFlag.equals("null")){
ProductDetails.arrPdInfoForCartList.remove(arrIndex);
Log.e("arrListHashMapForClientInfo2", arrIndex+" "+arrListHashMapForClientInfo2.size()+" "+arrListHashMapForClientInfo2);
Log.e("ProductDetails.arrListHashMapForClientInfo", arrIndex+" "+ProductDetails.arrListHashMapForClientInfo.size()+" "+ProductDetails.arrListHashMapForClientInfo);
}else{
arrPdInfoForCartEditList.remove(arrIndex);
}
//if(!arrClientProdList.contains(hashMapValues.get("ClientId"))){
if(!arrListForProdCount.contains(hashMapValues.get("ClientId"))){
int i=0;
for(int n= arrListHashMapForClientInfo2.size() - 1; n>=0; n--){
HashMap<String, String> hashMapValuesForClient = arrListHashMapForClientInfo2.get(n);
//HashMap<String, String> hashMapValuesForClientInfo = ProductDetails.arrListHashMapForClientInfo.get(n);
if(hashMapValuesForClient.get("ClientId").equals(hashMapValues.get("ClientId"))){
arrListHashMapForClientInfo2.remove(n);
if(shopFlag.equals("null")){
ProductDetails.arrForClientIds.remove(hashMapValues.get("ClientId"));
ProductDetails.arrListHashMapForClientInfo.remove(i);
}else{
arrListHashMapForEditClientInfo.remove(i);
arrForClientIds.remove(hashMapValues.get("ClientId"));
}
}
i++;
/*if(hashMapValuesForClientInfo.get("ClientId").equals(hashMapValues.get("ClientId"))){
ProductDetails.arrListHashMapForClientInfo.remove(n);
}*/
}
}
/*int i=0;
for(int n= arrListHashMapForClientInfo2.size() - 1; n>=0; n--){
HashMap<String, String> hashMapValuesForClient = arrListHashMapForClientInfo2.get(n);
HashMap<String, String> hashMapValuesForClientInfo = ProductDetails.arrListHashMapForClientInfo.get(n);
HashMap<String, String> hashMapValuesForListNewView = arrListHashMapProdsWithClient2.get(i);
if(!hashMapValuesForListNewView.containsKey(hashMapValues.get("ClientId"))){
if(hashMapValuesForClient.get("ClientId").equals(hashMapValues.get("ClientId"))){
Log.e("hashMapValuesForClient.get(",""+hashMapValuesForClient.get("ClientId"));
Log.e("n",""+hashMapValuesForClient.get("ClientId"));
arrListHashMapForClientInfo2.remove(n);
ProductDetails.arrForClientIds.remove(hashMapValues.get("ClientId"));
ProductDetails.arrListHashMapForClientInfo.remove(i);
break;
}
i++;*/
if(arrListHashMapProdsWithClient2.size()==0){
if(shopFlag.equals("null")){
ProductDetails.arrPdInfoForCartList.clear();
offerDiscountValue= "null";
offerDiscountValuType = "null";
offerName ="null";
offerId ="null";
clientId ="null";
}
arrListHashMapForClientInfo2.clear();
Intent intent = new Intent(OrderConfirmation.this, ProductDetails.class);
setResult(1, intent);
finish();
overridePendingTransition(R.xml.slide_in_right,R.xml.slide_out_right);
}
clientWiseTotalPrice =0.00;
countForFlagArrAdpNew =0;
fancyCoverFlowForCart.setAdapter(renderCoverFlowForShoppingCart(arrListHashMapForClientInfo2, arrListHashMapProdsWithClient2));
countForFlagArrAdp =0;
} catch(Exception e){
e.printStackTrace();
}
}
});
cartTotalPrice += Common.roundTwoDecimalsByStringCommon(aq3.id(R.id.txtvExpProdPrice).getText().toString().replace(""+priceSymbol, ""));
cartTotalPriceValues += Common.roundTwoDecimalsByStringCommon(aq3.id(R.id.txtvExpProdPrice).getText().toString().replace(""+priceSymbol, ""));
listViewForProds.addView(child);
JSONObject jsonObjForAttribus = new JSONObject();
if(!hashMapValuesForListViewNew.get("Size").equals("null")){
jsonObjForAttribus.put("size", hashMapValuesForListViewNew.get("Size"));
}
if(!hashMapValuesForListViewNew.get("Color").equals("null")){
jsonObjForAttribus.put("color", hashMapValuesForListViewNew.get("Color"));
}
jsonObjForClientsProducts = new JSONObject();
jsonObjForClientsProducts.put("prodId", hashMapValuesForListViewNew.get("ProdId"));
jsonObjForClientsProducts.put("prodName", hashMapValuesForListViewNew.get("ProdName"));
jsonObjForClientsProducts.put("prodPrice", hashMapValuesForListViewNew.get("ProdPrice"));
jsonObjForClientsProducts.put("prodQuantity", hashMapValuesForListViewNew.get("Quantity"));
jsonObjForClientsProducts.put("attribs", jsonObjForAttribus);
arrFinalClientsProducts.add(jsonObjForClientsProducts.toString().replace("\\", ""));
jsonArrayForClientsProducts.put(jsonObjForClientsProducts);
Log.e("jsonArrayForClientsProducts",""+jsonArrayForClientsProducts);
l++;
}
}
cartTotalPriceForAdd = "$"+cartTotalPrice;
aq2.id(R.id.txtvCartTotalPrice).text("$"+Common.roundTwoDecimalsByStringCommon(""+cartTotalPrice));
String onlyPriceValForCartTotalPrice ="0.00";
String onlyPriceValForShippingCostPrice ="0.00";
Button btnUserOffers = (Button) convertView.findViewById(R.id.btnUserOffers);
RelativeLayout.LayoutParams rlForBtnUserOffers= (RelativeLayout.LayoutParams) btnUserOffers.getLayoutParams();
rlForBtnUserOffers.width = (int) (0.1667* Common.sessionDeviceWidth);
rlForBtnUserOffers.height = (int) (0.0308* Common.sessionDeviceHeight);
rlForBtnUserOffers.leftMargin = (int) (0.035* Common.sessionDeviceWidth);
rlForBtnUserOffers.topMargin = (int) (0.01025* Common.sessionDeviceHeight);
btnUserOffers.setLayoutParams(rlForBtnUserOffers);
btnUserOffers.setTextSize((float)(0.03 * Common.sessionDeviceWidth/Common.sessionDeviceDensity));
btnUserOffers.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try{
Intent intent = new Intent(getApplicationContext(), DiscountOffer.class);
intent.putExtra("clientId", ""+hashMapValues.get("ClientId"));
startActivityForResult(intent, 1);
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | ChangeShippingMethod | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
});
if(!shippingMethodName.equals("null")){
aq2.id(R.id.txtvShippingMethodVal).text(shippingMethodName);
aq2.id(R.id.txtvShippingDelivery).text(shippingMethodDetails);
if(shippingMethodRateForTitle.equals("A")){
aq2.id(R.id.txtvShippingCostPrice).text("$"+Common.roundTwoDecimalsByStringCommon(shippingMethodRate));
} else if(shippingMethodRateForTitle.equals("P")){
double shippingCostForMethod = cartTotalPrice * (Common.roundTwoDecimalsByStringCommon(shippingMethodRate)/100);
aq2.id(R.id.txtvShippingCostPrice).text("$"+shippingCostForMethod);
}
onlyPriceValForShippingCostPrice = aq2.id(R.id.txtvShippingCostPrice).getText().toString().replace(""+priceSymbol, "");
onlyPriceValForCartTotalPrice = cartTotalPriceForAdd.replace(""+priceSymbol, "");
spinner = (Spinner) convertView.findViewById(R.id.spinnerForShippingMethod);
if(shopFlag == "null"){
if(ProductDetails.jsonShippingMethodAttriButes.length()>0){
spinnerArray = new ArrayList<String>();
spinnerShipMethodValsArray = new ArrayList<String>();
for(int s=0; s<ProductDetails.jsonShippingMethodAttriButes.length(); s++){
if(!ProductDetails.jsonShippingMethodAttriButes.optString(s).equals("")){
JSONObject jsonShippingMethod = new JSONObject(ProductDetails.jsonShippingMethodAttriButes.getString(s));
if(!jsonShippingMethod.optString("shipMethodName").equals("")){
spinnerArray.add(jsonShippingMethod.getString("shipMethodName")+" ("+jsonShippingMethod.getString("shipMethodDetails")+")");
}
if(!jsonShippingMethod.optString("shipMethodRate").equals("")){
JSONObject jsonShippingMethodRate = new JSONObject(jsonShippingMethod.getString("shipMethodRate"));
if(jsonShippingMethodRate.optString("A").equals("")){
//spinnerShipMethodValsArray.clear();
double shippingCostForMethod = cartTotalPrice * (Common.roundTwoDecimalsByStringCommon(jsonShippingMethodRate.getString("P"))/100);
spinnerShipMethodValsArray.add(""+Common.roundTwoDecimalsCommon(shippingCostForMethod));
} else if(jsonShippingMethodRate.optString("P").equals("")){
//spinnerShipMethodValsArray.clear();
spinnerShipMethodValsArray.add(""+Common.roundTwoDecimalsCommon(Double.parseDouble(jsonShippingMethodRate.getString("A"))));
}
}
}
}
}
spinnerArrayAdapter = new ArrayAdapter<String>(convertView.getContext(), android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setSelection(0);
}else{
final View newConvertView = convertView;
final float newcartTotalPrice = cartTotalPrice;
String productUrl = Constants.Live_Url+"mobileapps/ios/public/stores/products/"+prodID;
aq.ajax(productUrl, JSONObject.class, new AjaxCallback<JSONObject>(){
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
try{
if(json!=null && !json.optString("shippingMethods").equals("")){
JSONArray jsonShippingMethodAttriButes = new JSONArray(json.getString("shippingMethods"));
if(jsonShippingMethodAttriButes.length()>0){
spinnerArray = new ArrayList<String>();
spinnerShipMethodValsArray = new ArrayList<String>();
for(int s=0; s<jsonShippingMethodAttriButes.length(); s++){
if(!jsonShippingMethodAttriButes.optString(s).equals("")){
JSONObject jsonShippingMethod = new JSONObject(jsonShippingMethodAttriButes.getString(s));
if(!jsonShippingMethod.optString("shipMethodName").equals("")){
spinnerArray.add(jsonShippingMethod.getString("shipMethodName")+" ("+jsonShippingMethod.getString("shipMethodDetails")+")");
}
if(!jsonShippingMethod.optString("shipMethodRate").equals("")){
JSONObject jsonShippingMethodRate = new JSONObject(jsonShippingMethod.getString("shipMethodRate"));
Log.e("jsonShippingMethodRate", ""+jsonShippingMethodRate);
if(jsonShippingMethodRate.optString("A").equals("")){
//spinnerShipMethodValsArray.clear();
double shippingCostForMethod = newcartTotalPrice * (Common.roundTwoDecimalsByStringCommon(jsonShippingMethodRate.getString("P"))/100);
//Log.e("shippingCostForMethod", cartTotalPrice+" "+shippingCostForMethod+" "+Common.roundTwoDecimalsCommon(shippingCostForMethod));
spinnerShipMethodValsArray.add(""+Common.roundTwoDecimalsCommon(shippingCostForMethod));
} else if(jsonShippingMethodRate.optString("P").equals("")){
//spinnerShipMethodValsArray.clear();
spinnerShipMethodValsArray.add(""+Common.roundTwoDecimalsCommon(Double.parseDouble(jsonShippingMethodRate.getString("A"))));
}
}
}
}
spinnerArrayAdapter = new ArrayAdapter<String>(newConvertView.getContext(), android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setSelection(0);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
});
}
ImageView btnChangeShippingMethod = (ImageView) convertView.findViewById(R.id.btnChangeShippingMethod);
RelativeLayout.LayoutParams rlForBtnChangeShippingMethod= (RelativeLayout.LayoutParams) btnChangeShippingMethod.getLayoutParams();
rlForBtnChangeShippingMethod.width = (int) (0.0667* Common.sessionDeviceWidth);
rlForBtnChangeShippingMethod.height = (int) (0.041* Common.sessionDeviceHeight);
btnChangeShippingMethod.setLayoutParams(rlForBtnChangeShippingMethod);
btnChangeShippingMethod.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try{
spinner.performClick();
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | ChangeShippingMethod | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
});
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
try{
double clientWiseTotalPricePrev = Common.roundTwoDecimalsByStringCommon(aq2.id(R.id.txtvShippingSubTotalPrice).getText().toString().replace(""+priceSymbol, ""));
String s =" (";
String q =")";
String w ="";
String strReplaceSymbol = spinner.getSelectedItem().toString().replace(s, "|").replace(q, w);
String[] expShippingSpinnerArray = strReplaceSymbol.split("\\|");
aq2.id(R.id.txtvShippingMethodVal).text(expShippingSpinnerArray[0]);
aq2.id(R.id.txtvShippingDelivery).text(expShippingSpinnerArray[1]);
aq2.id(R.id.txtvShippingCostPrice).text("$"+spinnerShipMethodValsArray.get(position));
String onlyPriceValForShippingCostPrice = aq2.id(R.id.txtvShippingCostPrice).getText().toString().replace(""+priceSymbol, "");
//String onlyPriceValForCartTotalPrice = cartTotalPriceForAdd.replace(""+priceSymbol, "");
String onlyPriceValForCartTotalPrice = aq2.id(R.id.txtvCartTotalPrice).getText().toString().replace(""+priceSymbol, "");
//Log.e(" if onlyPriceValForCartTotalPrice",""+onlyPriceValForCartTotalPrice);
onlyPriceValForShippingCostPrice = onlyPriceValForShippingCostPrice.isEmpty() ? "0" : onlyPriceValForShippingCostPrice;
onlyPriceValForCartTotalPrice = onlyPriceValForCartTotalPrice.isEmpty() ? "0" : onlyPriceValForCartTotalPrice;
//Log.e(" if onlyPriceValForCartTotalPrice",""+onlyPriceValForCartTotalPrice);
Double discountPrice =0.0;
double discountAmt= 0.0;
Log.e("offerDiscountValue if",offerDiscountValue);
if(!offerDiscountValue.equals("null") && !offerDiscountValuType.equals("null") && clientId.equals(hashMapValues.get("ClientId"))){
if(offerDiscountValuType.equals("A")){
Log.e("offerDiscountValue spinner",offerDiscountValue);
aq2.id(R.id.txtofferDiscountCost).text("$"+Common.roundTwoDecimalsByStringCommon(offerDiscountValue));
aq2.id(R.id.txtvofferVal).text("( $"+Common.roundTwoDecimalsByStringCommon(offerDiscountValue)+" off )");
discountAmt = Double.parseDouble(offerDiscountValue);
discountPrice = Double.parseDouble(onlyPriceValForCartTotalPrice) -discountAmt ;
}else{
Log.e("offerDiscountValue spinner",offerDiscountValue);
//aq2.id(R.id.txtofferDiscountCost).text(offerDiscountValue+ "% Off");
discountAmt = (Double.parseDouble(onlyPriceValForCartTotalPrice) *Double.parseDouble(offerDiscountValue))/100;
Log.e("discountAmt spinner",""+discountAmt);
aq2.id(R.id.txtofferDiscountCost).text("$"+Common.roundTwoDecimalsCommon(discountAmt));
aq2.id(R.id.txtvofferVal).text("( "+offerDiscountValue+"% off )");
discountPrice = Double.parseDouble(onlyPriceValForCartTotalPrice) - discountAmt;
}
txtvofferName.setVisibility(View.VISIBLE);
txtvofferVal.setVisibility(View.VISIBLE);
imgClose.setVisibility(View.VISIBLE);
aq2.id(R.id.txtvofferName).text(""+offerName+"");
//hashMapValuesNew = hashMapValues;
hashMapValuesNew.put("offer_id",offerId);
hashMapValuesNew.put("offer_name",offerName);
hashMapValuesNew.put("offer_discount",""+discountAmt);
hashMapValuesNew.put("offer_discount_type",""+offerDiscountValuType);
//arrPdInfoForCartList.set(listPos, hMapForPdInfo);
int i=0;
for(int n= arrListHashMapForClientInfo2.size() - 1; n>=0; n--){
HashMap<String, String> hashMapValuesForClient = arrListHashMapForClientInfo2.get(n);
//HashMap<String, String> hashMapValuesForClientInfo = ProductDetails.arrListHashMapForClientInfo.get(n);
if(hashMapValuesForClient.get("ClientId").equals(hashMapValues.get("ClientId"))){
arrListHashMapForClientInfo2.set(n, hashMapValuesNew);
if(shopFlag.equals("null")){
ProductDetails.arrListHashMapForClientInfo.set(i, hashMapValuesNew);
}else{
arrListHashMapForEditClientInfo.set(i, hashMapValuesNew);
}
}
i++;
}
}else{
discountPrice = Double.parseDouble(onlyPriceValForCartTotalPrice);
}
final double finalDiscountAmt = discountAmt;
double finalPdsTotal = Common.roundTwoDecimalsByStringCommon(onlyPriceValForShippingCostPrice) + (discountPrice);
//Log.e(" if finalPdsTotal",""+finalPdsTotal);
aq2.id(R.id.txtvShippingSubTotalPrice).text(""+priceSymbol+Common.roundTwoDecimalsCommon(finalPdsTotal));
double clientWiseTotalPriceNew = Common.roundTwoDecimalsByStringCommon(aq2.id(R.id.txtvShippingSubTotalPrice).getText().toString().replace(""+priceSymbol, ""));
if(!txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, "").equals("0.00")){
double OrderTotalPricePrev = Common.roundTwoDecimalsByStringCommon(txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""))- Common.roundTwoDecimalsByStringCommon(txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, "")) - clientWiseTotalPricePrev;
double convertToDouble = Common.roundTwoDecimalsByStringCommon(txtvSalesTaxPrice.getTag().toString());
double calculateSalesTaxVal = Common.roundTwoDecimalsCommon(finalPdsTotal * (convertToDouble/100));
txtvSalesTaxPrice.setText(""+priceSymbol+calculateSalesTaxVal);
double OrderTotalPrice = OrderTotalPricePrev + clientWiseTotalPriceNew + Common.roundTwoDecimalsByStringCommon(txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
//txtvSubOrderTotalPrice.setText(""+OrderTotalPrice);
double subTotalPrice = OrderTotalPricePrev + clientWiseTotalPriceNew;
txtvSubOrderTotalPrice.setText(""+subTotalPrice);
txtvOrderTotalPrice.setText(""+priceSymbol+Common.roundTwoDecimalsCommon(OrderTotalPrice));
}else{
double OrderTotalPricePrev = Common.roundTwoDecimalsByStringCommon(txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""))- clientWiseTotalPricePrev;
double OrderTotalPrice = OrderTotalPricePrev + clientWiseTotalPriceNew + Common.roundTwoDecimalsByStringCommon(txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
double subTotalPrice = OrderTotalPricePrev + clientWiseTotalPriceNew;
txtvSubOrderTotalPrice.setText(""+OrderTotalPrice);
txtvOrderTotalPrice.setText(""+priceSymbol+Common.roundTwoDecimalsCommon(OrderTotalPrice));
}
imgClose.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try{
txtvofferVal.setText("");
txtvofferName.setText("");
txtvofferName.setVisibility(View.INVISIBLE);
txtvofferVal.setVisibility(View.INVISIBLE);
imgClose.setVisibility(View.INVISIBLE);
aq2.id(R.id.txtofferDiscountCost).text("$0.0");
aq2.id(R.id.txtvofferName).text("");
double clientWiseTotalPriceNew = Common.roundTwoDecimalsByStringCommon(aq2.id(R.id.txtvShippingSubTotalPrice).getText().toString().replace(""+priceSymbol, ""))+ finalDiscountAmt;
double OrderTotalPricePrev = Common.roundTwoDecimalsByStringCommon(txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""))+ finalDiscountAmt;
double subTotalPrice = Common.roundTwoDecimalsByStringCommon(txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""))+ finalDiscountAmt;
txtvSubOrderTotalPrice.setText(""+subTotalPrice);
txtvOrderTotalPrice.setText(""+priceSymbol+Common.roundTwoDecimalsCommon(OrderTotalPricePrev));
aq2.id(R.id.txtvShippingSubTotalPrice).text(""+priceSymbol+Common.roundTwoDecimalsCommon(clientWiseTotalPriceNew));
}catch(Exception e){
e.printStackTrace();
}
}
});
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}else{
onlyPriceValForShippingCostPrice ="0";
onlyPriceValForCartTotalPrice = ""+cartTotalPrice;
// convertView.findViewById(R.id.txtvShippingMethodTitle).setVisibility(View.INVISIBLE);
convertView.findViewById(R.id.txtvShippingDelivery).setVisibility(View.INVISIBLE);
convertView.findViewById(R.id.btnChangeShippingMethod).setVisibility(View.INVISIBLE);
convertView.findViewById(R.id.txtvShippingCostTitle).setVisibility(View.INVISIBLE);
convertView.findViewById(R.id.txtvShippingCostPrice).setVisibility(View.INVISIBLE);
/*convertView.findViewById(R.id.txtvShippingMethodVal).setVisibility(View.INVISIBLE);
convertView.findViewById(R.id.txtvShippingDelivery).setVisibility(View.INVISIBLE);
convertView.findViewById(R.id.txtvShippingCostPrice).setVisibility(View.INVISIBLE);
convertView.findViewById(R.id.txtvShippingMethodTitle).setVisibility(View.INVISIBLE); */
}
double discountAmt =0.0;
Double discountPrice =0.0;
Log.e("offerDiscountValue else",offerDiscountValue);
if(!offerDiscountValue.equals("null") && !offerDiscountValuType.equals("null") && clientId.equals(hashMapValues.get("ClientId"))){
if(offerDiscountValuType.equals("A")){
Log.e("offerDiscountValue render",offerDiscountValue);
discountAmt = Double.parseDouble(offerDiscountValue);
aq2.id(R.id.txtofferDiscountCost).text("$"+Common.roundTwoDecimalsByStringCommon(offerDiscountValue));
discountPrice = (double) ((int)cartTotalPrice - Double.parseDouble(offerDiscountValue));
aq2.id(R.id.txtvofferVal).text("("+Common.roundTwoDecimalsByStringCommon(offerDiscountValue)+" off )");
}else{
Log.e("offerDiscountValue render",offerDiscountValue);
//aq2.id(R.id.txtofferDiscountCost).text(offerDiscountValue+ "% Off");
discountAmt = (double) (cartTotalPrice * Integer.parseInt(offerDiscountValue)/100);
Log.e("discountAmt render",""+discountAmt);
aq2.id(R.id.txtofferDiscountCost).text("$"+Common.roundTwoDecimalsCommon(discountAmt));
aq2.id(R.id.txtvofferVal).text("( "+offerDiscountValue+"% off )");
discountPrice = (double) (cartTotalPrice - (((double)cartTotalPrice *(Integer.parseInt(offerDiscountValue)))/100));
}
txtvofferName.setVisibility(View.VISIBLE);
txtvofferVal.setVisibility(View.VISIBLE);
imgClose.setVisibility(View.VISIBLE);
aq2.id(R.id.txtvofferName).text(""+offerName+"");
txtvofferName.setVisibility(View.VISIBLE);
txtvofferVal.setVisibility(View.VISIBLE);
imgClose.setVisibility(View.VISIBLE);
//hashMapValuesNew = hashMapValues;
txtvofferName.setVisibility(View.VISIBLE);
txtvofferVal.setVisibility(View.VISIBLE);
imgClose.setVisibility(View.VISIBLE);
//hashMapValuesNew = hashMapValues;
hashMapValuesNew.put("offer_id",offerId);
hashMapValuesNew.put("offer_name",offerName);
hashMapValuesNew.put("offer_discount",""+discountAmt);
hashMapValuesNew.put("offer_discount_type",""+offerDiscountValuType);
//arrPdInfoForCartList.set(listPos, hMapForPdInfo);
int i=0;
for(int n= arrListHashMapForClientInfo2.size() - 1; n>=0; n--){
HashMap<String, String> hashMapValuesForClient = arrListHashMapForClientInfo2.get(n);
//HashMap<String, String> hashMapValuesForClientInfo = ProductDetails.arrListHashMapForClientInfo.get(n);
if(hashMapValuesForClient.get("ClientId").equals(hashMapValues.get("ClientId"))){
arrListHashMapForClientInfo2.set(n, hashMapValuesNew);
if(shopFlag.equals("null")){
ProductDetails.arrListHashMapForClientInfo.set(i, hashMapValuesNew);
}else{
arrListHashMapForEditClientInfo.set(i, hashMapValuesNew);
}
}
i++;
}
}else{
discountPrice = (double) cartTotalPrice;
}
final double finalDiscountAmt = discountAmt;
aq2.id(R.id.txtvCartTotalPrice).text("$"+Common.roundTwoDecimalsByStringCommon(""+cartTotalPrice));
double finalPdsTotal = Common.roundTwoDecimalsByStringCommon(onlyPriceValForShippingCostPrice) + discountPrice;
aq2.id(R.id.txtvShippingSubTotalPrice).text(""+priceSymbol+Common.roundTwoDecimalsCommon(finalPdsTotal));
imgClose.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try{
txtvofferVal.setText("");
txtvofferName.setText("");
txtvofferName.setVisibility(View.INVISIBLE);
txtvofferVal.setVisibility(View.INVISIBLE);
imgClose.setVisibility(View.INVISIBLE);
aq2.id(R.id.txtofferDiscountCost).text("$0.0");
aq2.id(R.id.txtvofferName).text("");
double clientWiseTotalPriceNew = Common.roundTwoDecimalsByStringCommon(aq2.id(R.id.txtvShippingSubTotalPrice).getText().toString().replace(""+priceSymbol, ""))+ finalDiscountAmt;
double OrderTotalPricePrev = Common.roundTwoDecimalsByStringCommon(txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""))+ finalDiscountAmt;
double subTotalPrice = Common.roundTwoDecimalsByStringCommon(txtvOrderTotalPrice.getText().toString().replace(""+priceSymbol, ""))+ finalDiscountAmt;
txtvSubOrderTotalPrice.setText(""+subTotalPrice);
txtvOrderTotalPrice.setText(""+priceSymbol+Common.roundTwoDecimalsCommon(OrderTotalPricePrev));
aq2.id(R.id.txtvShippingSubTotalPrice).text(""+priceSymbol+Common.roundTwoDecimalsCommon(clientWiseTotalPriceNew));
}catch(Exception e){
e.printStackTrace();
}
}
});
if(countForFlagArrAdpNew == position){
clientWiseTotalPrice += Common.roundTwoDecimalsByStringCommon(aq2.id(R.id.txtvShippingSubTotalPrice).getText().toString().replace(""+priceSymbol, ""));
double OrderTotalPrice = clientWiseTotalPrice + Common.roundTwoDecimalsByStringCommon(txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
txtvSubOrderTotalPrice.setText(""+clientWiseTotalPrice);
txtvOrderTotalPrice.setText(""+priceSymbol+Common.roundTwoDecimalsCommon(OrderTotalPrice));
jsonObjForClients = new JSONObject();
jsonObjForClients.put("clientId", hashMapValues.get("ClientId"));
jsonObjForClients.put("clientName", hashMapValues.get("ClientName"));
jsonObjForClients.put("clientTotal", Common.roundTwoDecimalsByStringCommon(aq2.id(R.id.txtvShippingSubTotalPrice).getText().toString().replace(""+priceSymbol, "")));
jsonObjForClients.put("cartTotal", Common.roundTwoDecimalsCommon(cartTotalPrice));
jsonObjForClients.put("shippingMethod", shippingMethodDetails);
jsonObjForClients.put("shippingCost", onlyPriceValForShippingCostPrice);
jsonObjForClients.put("offer_id",hashMapValuesNew.get("offer_id"));
jsonObjForClients.put("offer_discount",""+hashMapValuesNew.get("offer_discount"));
jsonObjForClients.put("products", jsonArrayForClientsProducts);
jsonArrayForClients.put(jsonObjForClients);
arrFinalClientIds.add(jsonObjForClients.toString().replace("\\", ""));
arrFinalClientsProducts.clear();
}
jsonArrayForClientsProducts = new JSONArray();
}catch(Exception e){
e.printStackTrace();
}
countForFlagArrAdpNew++;
}
//countForFlagArrAdpNew++;
Log.e("jsonObjForClients rendre",""+jsonObjForClients);
}
} catch (Exception e){
e.printStackTrace();
String errorMsg = className+" | renderCoverFlowForShoppingCart getView | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this,errorMsg);
}
return convertView;
}
};
return aa;
}
public static ArrayList<String> shippingAddressArrListVals = new ArrayList<String>();
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try{
if(resultCode==2){
if(data!=null){
shippingAddressArrListVals = data.getStringArrayListExtra("arrListForShippingAddressValues");
if(data.getStringExtra("editOrderId") != null){
editOrderId = data.getStringExtra("editOrderId");
shopFlag="Edit";
}
basedOnShippingAddressInfoGetStateTax(shippingAddressArrListVals, "");
}
}
if(requestCode==1){
if(resultCode == 3 ){
clientWiseTotalPrice=0;
txtvSalesTaxPrice.setText("$0.00");
txtvSubOrderTotalPrice.setText("$0.00");
txtvOrderTotalPrice.setText("$0.00");
editOrderId = data.getStringExtra("editOrderId");
shopFlag="Edit";
arrPdInfoForCartEditList = ProductDetails.arrPdInfoForCartList;
countForFlagArrAdp =0;
countForFlagArrAdpNew=0;
arrListHashMapProdsWithClient = new ArrayList<HashMap<String,String>>();
if(arrPdInfoForCartEditList.size()>0){
for(int i=0; i<arrPdInfoForCartEditList.size(); i++){
hashMapProdsWithClient = new HashMap<String, String>();
hashMapProdsWithClient.put(arrPdInfoForCartEditList.get(i).get("ClientId"), arrPdInfoForCartEditList.get(i).toString());
arrListHashMapProdsWithClient.add(hashMapProdsWithClient);
arrListForProdCount.add(arrPdInfoForCartEditList.get(i).get("ClientId"));
/*ArrayList<String> arrObjForShippingAddress = getIntent().getStringArrayListExtra("arrObjForShippingAddress");
//shippingAddressInfoShowingOnLayout(arrObjForShippingAddress, json.getString("statetax"), "");
Log.e("arrObjForShippingAddress",""+arrObjForShippingAddress);
basedOnShippingAddressInfoGetStateTax(arrObjForShippingAddress, "");*/
shippingAddressArrListVals =arrObjForShippingAddress;
basedOnShippingAddressInfoGetStateTax(arrObjForShippingAddress, "");
}
fancyCoverFlowForShoppingCartInfo(arrListHashMapForEditClientInfo, arrListHashMapProdsWithClient);
}
}
}
if(resultCode == 4){
if(data.getStringExtra("offerDiscountValue") != null){
clientWiseTotalPrice=0;
txtvSalesTaxPrice.setText("$0.00");
txtvSubOrderTotalPrice.setText("$0.00");
txtvOrderTotalPrice.setText("$0.00");
countForFlagArrAdp =0;
countForFlagArrAdpNew=0;
offerDiscountValue = data.getStringExtra("offerDiscountValue");
offerDiscountValuType = data.getStringExtra("offerDiscountValuType");
offerName = data.getStringExtra("offerName");
clientId = data.getStringExtra("clientId");
offerId = data.getStringExtra("offerId");
jsonArrayForClients = new JSONArray();
Log.e("offerDiscountValue",offerDiscountValue);
Log.e("offerDiscountValuType",offerDiscountValuType);
fancyCoverFlowForShoppingCartInfo(ProductDetails.arrListHashMapForClientInfo, arrListHashMapProdsWithClient);
if(shippingAddressArrListVals.size()>0){
if(shopFlag.equals("null")){
basedOnShippingAddressInfoGetStateTax(shippingAddressArrListVals, "");
}
}
}
}
shippingButtonText();
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | onActivityResult | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
private void basedOnShippingAddressInfoGetStateTax(final ArrayList<String> shippingAddressArrListVals2, final String strFlagForTax) {
try{
JSONObject jsonObj = new JSONObject();
jsonObj.put("state", shippingAddressArrListVals2.get(4).toString());
jsonObj.put("country", shippingAddressArrListVals2.get(6).toString());
jsonObj.put("zip", shippingAddressArrListVals2.get(5).toString());
Map<String, Object> params = new HashMap<String, Object>();
params.put("json", jsonObj.toString());
if(shopFlag.equals("null"))
params.put("state", shippingAddressArrListVals.get(4).toString());
else
params.put("state", shippingAddressArrListVals2.get(4).toString());
String stateTaxUrl = Constants.Live_Url+"mobileapps/ios/public/stores/statetax/";
aq.ajax(stateTaxUrl, params, JSONObject.class, new AjaxCallback<JSONObject>(){
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
try{
if(json!=null){
shippingAddressInfoShowingOnLayout(shippingAddressArrListVals2, json.getString("statetax"), strFlagForTax);
}
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | basedOnShippingAddressInfoGetStateTax aq.ajax callback | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
});
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | basedOnShippingAddressInfoGetStateTax | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
public static int userShipIdForEdit = 0;
JSONObject jsonObjForShippingAddress;
ArrayList<String> arrFinalShippingAddress;
protected void shippingAddressInfoShowingOnLayout(
ArrayList<String> shippingAddressArrListVals2, String stateTaxByState, String strFlagForTax) {
// TODO Auto-generated method stub
try{
arrFinalShippingAddress = new ArrayList<String>();
double txtvSubOrderTotalPriceVal = Common.roundTwoDecimalsByStringCommon(txtvSubOrderTotalPrice.getText().toString().replace(""+priceSymbol, "")) - Common.roundTwoDecimalsByStringCommon(txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
double convertToDouble = Common.roundTwoDecimalsByStringCommon(stateTaxByState);
double calculateSalesTaxVal = Common.roundTwoDecimalsByStringCommon(txtvSubOrderTotalPrice.getText().toString()) * (convertToDouble/100);
txtvSalesTaxPrice.setText(""+priceSymbol+Common.roundTwoDecimalsByStringCommon(""+calculateSalesTaxVal));
txtvSalesTaxPrice.setTag(Double.parseDouble(stateTaxByState));
TextView txtvShippingSubTotalPrice = (TextView) findViewById(R.id.txtvShippingSubTotalPrice);
//Log.e("shipping total", ""+txtvShippingSubTotalPrice.getText().toString()+" "+txtvOrderTotalPrice.getText().toString());
//double OrderTotalPrice = Common.roundTwoDecimalsByStringCommon(txtvShippingSubTotalPrice.getText().toString().replace(""+priceSymbol, "")) + Common.roundTwoDecimalsByStringCommon(txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
double OrderTotalPrice = Common.roundTwoDecimalsByStringCommon(txtvSubOrderTotalPrice.getText().toString()) + Common.roundTwoDecimalsByStringCommon(txtvSalesTaxPrice.getText().toString().replace(""+priceSymbol, ""));
txtvOrderTotalPrice.setText(""+priceSymbol+Common.roundTwoDecimalsCommon(OrderTotalPrice));
String address1 = (shippingAddressArrListVals2.get(1).isEmpty() ? "" : shippingAddressArrListVals2.get(1));
String address2 = (shippingAddressArrListVals2.get(2).isEmpty() ? "" : ""+shippingAddressArrListVals2.get(2));
String city = (shippingAddressArrListVals2.get(3).isEmpty() ? "" : shippingAddressArrListVals2.get(3));
String state = (shippingAddressArrListVals2.get(4).isEmpty() ? "" : ""+shippingAddressArrListVals2.get(4));
String zipcode = (shippingAddressArrListVals2.get(5).isEmpty() ? "" : ""+shippingAddressArrListVals2.get(5));
String country = (shippingAddressArrListVals2.get(6).isEmpty() ? "" : ""+shippingAddressArrListVals2.get(6));
String address = address2.equals("") ? address1 :address1+"\n"+address2;
txtvShippingAddress1.setText(Common.sessionIdForUserLoggedFname +" "+Common.sessionIdForUserLoggedLname+"\n"+address);
txtvShippingAddress2.setText(city+", "+state+" "+zipcode+"\n"+country);
if(Integer.parseInt(shippingAddressArrListVals2.get(0))!=0){
userShipIdForEdit = Integer.parseInt(shippingAddressArrListVals2.get(0));
}
jsonObjForShippingAddress = new JSONObject();
jsonObjForShippingAddress.put("userShipId", userShipIdForEdit);
jsonObjForShippingAddress.put("addr1", address1);
jsonObjForShippingAddress.put("addr2", address2);
jsonObjForShippingAddress.put("city", city);
jsonObjForShippingAddress.put("state", state);
jsonObjForShippingAddress.put("zip", zipcode);
jsonObjForShippingAddress.put("country", country);
arrFinalShippingAddress.add(jsonObjForShippingAddress.toString());
JSONObject jsonObjForAddAddress = new JSONObject();
jsonObjForAddAddress.put("userId", ""+Common.sessionIdForUserLoggedIn);
jsonObjForAddAddress.put("userShipId", userShipIdForEdit);
jsonObjForAddAddress.put("shippingAddress", jsonObjForShippingAddress);
Map<String, Object> params = new HashMap<String, Object>();
params.put("json", jsonObjForAddAddress.toString());
params.put("userid", Common.sessionIdForUserLoggedIn);
} catch(Exception e){
e.printStackTrace();
String errorMsg = className+" | shippingAddressInfoShowingLayout | " +e.getMessage();
Common.sendCrashWithAQuery(OrderConfirmation.this, errorMsg);
}
}
} |
package com.mahirkole.walkure.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@EqualsAndHashCode(callSuper = true)
@Data
@Entity
public class Country extends CoreModel {
@Id
@GeneratedValue
private Long id;
private String iso_3166_1;
}
|
package com.tencent.mm.plugin.setting.ui.setting;
import android.content.Intent;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.kernel.g;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.x;
class SettingsAliasUI$5 implements e {
final /* synthetic */ SettingsAliasUI mRV;
SettingsAliasUI$5(SettingsAliasUI settingsAliasUI) {
this.mRV = settingsAliasUI;
}
public final void a(final int i, final int i2, String str, final l lVar) {
x.d("MicroMsg.SettingsAliasUI", "onSceneEnd " + i + " errCode " + i2 + " errMsg " + str + " " + lVar.getType());
g.DF().b(255, SettingsAliasUI.g(this.mRV));
ah.A(new Runnable() {
public final void run() {
if (SettingsAliasUI.h(SettingsAliasUI$5.this.mRV) != null) {
SettingsAliasUI.h(SettingsAliasUI$5.this.mRV).dismiss();
SettingsAliasUI.i(SettingsAliasUI$5.this.mRV);
}
SettingsAliasUI.j(SettingsAliasUI$5.this.mRV);
if (lVar.getType() == 255) {
boolean z = (i2 == -3 && i == 4) ? false : true;
Intent intent = new Intent(SettingsAliasUI$5.this.mRV, SettingsAliasResultUI.class);
intent.putExtra("has_pwd", z);
SettingsAliasUI$5.this.mRV.startActivity(intent);
SettingsAliasUI$5.this.mRV.finish();
}
}
});
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* Lagdays generated by hbm2java
*/
public class Lagdays implements java.io.Serializable {
private LagdaysId id;
public Lagdays() {
}
public Lagdays(LagdaysId id) {
this.id = id;
}
public LagdaysId getId() {
return this.id;
}
public void setId(LagdaysId id) {
this.id = id;
}
}
|
package com.tencent.mm.ae;
import android.database.Cursor;
import com.tencent.mm.model.ah;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.platformtools.x;
public final class b extends ah {
public final boolean gV(int i) {
return i != 0 && i < 637735215;
}
public final String getTag() {
return "MicroMsg.App.BizPlaceTopDataTransfer";
}
public final void transfer(int i) {
x.d("MicroMsg.App.BizPlaceTopDataTransfer", "the previous version is %d", new Object[]{Integer.valueOf(i)});
if (gV(i)) {
x.i("MicroMsg.App.BizPlaceTopDataTransfer", "begin biz place to top data transfer.");
long currentTimeMillis = System.currentTimeMillis();
h.mEJ.a(336, 0, 1, true);
au.HU();
com.tencent.mm.bt.h FO = c.FO();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("select conv.username");
stringBuilder.append(" from ");
stringBuilder.append("rconversation");
stringBuilder.append(" as conv, ");
stringBuilder.append("rcontact");
stringBuilder.append(" as ct ");
stringBuilder.append(" where conv.");
stringBuilder.append("parentRef");
stringBuilder.append("='");
stringBuilder.append("officialaccounts");
stringBuilder.append("' and conv.");
stringBuilder.append("username");
stringBuilder.append(" = ct.");
stringBuilder.append("username");
stringBuilder.append(" and ct.");
stringBuilder.append("verifyFlag");
stringBuilder.append(" & ");
stringBuilder.append(8);
stringBuilder.append(" = 0");
x.v("MicroMsg.App.BizPlaceTopDataTransfer", "transfer query sql(%s)", new Object[]{stringBuilder.toString()});
Cursor b = FO.b(r0, null, 2);
if (b == null) {
x.i("MicroMsg.App.BizPlaceTopDataTransfer", "cursor is null.");
return;
}
long currentTimeMillis2 = System.currentTimeMillis();
x.i("MicroMsg.App.BizPlaceTopDataTransfer", "do biz place to top data transfer, query cost : %s msec.", new Object[]{Long.valueOf(currentTimeMillis2 - currentTimeMillis)});
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("update ");
stringBuilder2.append("rconversation");
stringBuilder2.append(" set ");
stringBuilder2.append("parentRef");
stringBuilder2.append("='' where ");
stringBuilder2.append("username");
stringBuilder2.append(" in (");
if (b.moveToFirst()) {
h.mEJ.a(336, 1, 1, true);
stringBuilder2.append("'");
stringBuilder2.append(b.getString(0));
stringBuilder2.append("'");
int i2 = 1;
while (b.moveToNext()) {
stringBuilder2.append(",");
stringBuilder2.append("'");
stringBuilder2.append(b.getString(0));
stringBuilder2.append("'");
i2++;
}
stringBuilder2.append(")");
String stringBuilder3 = stringBuilder2.toString();
x.i("MicroMsg.App.BizPlaceTopDataTransfer", "transfer update count(%d)", new Object[]{Integer.valueOf(i2)});
x.v("MicroMsg.App.BizPlaceTopDataTransfer", "transfer update sql(%s)", new Object[]{stringBuilder3});
b.close();
if (FO.fV("rconversation", stringBuilder2.toString())) {
h.mEJ.a(336, 2, 1, true);
} else {
h.mEJ.a(336, 3, 1, true);
}
long currentTimeMillis3 = System.currentTimeMillis();
x.i("MicroMsg.App.BizPlaceTopDataTransfer", "do biz place to top data transfer, update cost : %s msec, total cost : %s msec.", new Object[]{Long.valueOf(currentTimeMillis3 - currentTimeMillis2), Long.valueOf(currentTimeMillis3 - currentTimeMillis)});
return;
}
b.close();
x.i("MicroMsg.App.BizPlaceTopDataTransfer", "cursor count is 0.");
}
}
}
|
/*
* 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 Gestion.vues.InterfacesGraphiques;
import Gestion.controllers.ClassMetiers.UtilisateurMetier;
import Gestion.passerelle.Passerelle;
import Gestion.vues.Messages.LesDonnees;
import java.awt.Color;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import org.json.simple.JSONObject;
/**
*
* @author christian
*/
public class PageDeLogin extends javax.swing.JFrame {
public static UtilisateurMetier currentUser;
private Passerelle passerelle;
private JSONObject message;
private int action;
private JSONObject requette;
private JSONObject retour;
/**
* Creates new form PageDeLogin
*/
public PageDeLogin() {
initComponents();
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setTitle("CONNECTION");
this.setIconImage(new ImageIcon("Documents/Images/logo.png").getImage());
this.requette = new JSONObject();
this.action = -1;
this.message = new JSONObject();
this.retour = new JSONObject();
currentUser = new UtilisateurMetier();
currentUser.setNom("FKC");
currentUser.setPrenom("LOGEUR");
currentUser.setIdtypeutilisateur(1);
}
/**
* 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() {
container = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
login = new javax.swing.JTextField();
passwd = new javax.swing.JPasswordField();
jButton1 = new javax.swing.JButton();
valider = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
visualMessage = new javax.swing.JTextField();
jPanel1 = new Gestion.utils.Panneau("Documents/Images/logo.png");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Connection");
container.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setFont(new java.awt.Font("Tekton Pro Cond", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(102, 102, 255));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Bienvenu sur Mag&Ges");
jLabel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
login.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
login.setHorizontalAlignment(javax.swing.JTextField.CENTER);
login.setText("admin");
login.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
loginKeyPressed(evt);
}
});
passwd.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
passwd.setHorizontalAlignment(javax.swing.JTextField.CENTER);
passwd.setText("admin");
passwd.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
passwdKeyPressed(evt);
}
});
jButton1.setBackground(new java.awt.Color(255, 255, 255));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Gestion/Images/Icons/Cancel.png"))); // NOI18N
jButton1.setText("Annuler");
jButton1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
valider.setBackground(new java.awt.Color(255, 255, 255));
valider.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
valider.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Gestion/Images/Icons/Ok.png"))); // NOI18N
valider.setText("Valider");
valider.setBorder(javax.swing.BorderFactory.createEtchedBorder());
valider.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
validerActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Magneto", 0, 18)); // NOI18N
jLabel2.setText("Login");
jLabel3.setFont(new java.awt.Font("Magneto", 0, 18)); // NOI18N
jLabel3.setText("Password");
visualMessage.setEditable(false);
visualMessage.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
visualMessage.setHorizontalAlignment(javax.swing.JTextField.CENTER);
visualMessage.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel1.setForeground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 199, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout containerLayout = new javax.swing.GroupLayout(container);
container.setLayout(containerLayout);
containerLayout.setHorizontalGroup(
containerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(containerLayout.createSequentialGroup()
.addContainerGap(63, Short.MAX_VALUE)
.addGroup(containerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(containerLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(containerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(containerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(containerLayout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 119, Short.MAX_VALUE)
.addComponent(valider, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(login, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(passwd, javax.swing.GroupLayout.Alignment.LEADING))
.addGap(7, 7, 7)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, containerLayout.createSequentialGroup()
.addGroup(containerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(visualMessage, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 713, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
containerLayout.setVerticalGroup(
containerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(containerLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(visualMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(16, 16, 16)
.addGroup(containerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(containerLayout.createSequentialGroup()
.addGroup(containerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(login, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(containerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(passwd, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(26, 26, 26)
.addGroup(containerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(valider, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(container, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(container, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
bouttonAnnuler();
}//GEN-LAST:event_jButton1ActionPerformed
private void validerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_validerActionPerformed
bouttonLogin();
}//GEN-LAST:event_validerActionPerformed
private void loginKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_loginKeyPressed
if((evt.getKeyCode()==KeyEvent.VK_ENTER)){
bouttonLogin();
}
}//GEN-LAST:event_loginKeyPressed
private void passwdKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwdKeyPressed
if((evt.getKeyCode()==KeyEvent.VK_ENTER)){
bouttonLogin();
}
}//GEN-LAST:event_passwdKeyPressed
private boolean testLogin(){
int n = 1;
try {
message.put("login",login.getText());
message.put("pass",Gestion.utils.Utils.CrypterUneChaine(passwd.getText(),"SHA-256"));
requette.put("user", currentUser);
requette.put("message",message);
requette.put("action",30);
passerelle = new Passerelle(requette);
retour = passerelle.ForwardQuery();
n = Gestion.utils.Utils.ObjectToInt(retour.get("code"));
return (n==0);
} catch (Exception ex) {
Gestion.utils.Utils.addMessage("PageDeLogin:testLogin: "+ex.toString(),true);
}
return n==0;
}
private void affichemessage(){
visualMessage.setForeground(Color.red);
visualMessage.setText(Gestion.vues.Messages.MessagePasserelle.erreur_connection);
}
private void bouttonAnnuler(){
System.exit(0);
}
private void bouttonLogin(){
if(testLogin()){
retour = (JSONObject)retour.get("message");
currentUser = (UtilisateurMetier)retour.get(0);
LesDonnees.initData(7);
LesDonnees.initData(8);
this.setVisible(false);
new PagePrincipale().setVisible(true);
}else{
affichemessage();
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel container;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField login;
private javax.swing.JPasswordField passwd;
private javax.swing.JButton valider;
private javax.swing.JTextField visualMessage;
// End of variables declaration//GEN-END:variables
}
|
package com.mochasoft.fk.configuration.mapper;
import java.util.List;
import com.mochasoft.fk.configuration.entity.Configuration;
import com.mochasoft.fk.mapper.MyBatisRepository;
@MyBatisRepository
public interface ConfigurationMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table MOCHA_SECU_CONFIGURATION
*
* @mbggenerated Tue Jan 29 17:16:49 CST 2013
*/
int deleteByPrimaryKey(String id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table MOCHA_SECU_CONFIGURATION
*
* @mbggenerated Tue Jan 29 17:16:49 CST 2013
*/
int insert(Configuration record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table MOCHA_SECU_CONFIGURATION
*
* @mbggenerated Tue Jan 29 17:16:49 CST 2013
*/
Configuration selectByPrimaryKey(String id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table MOCHA_SECU_CONFIGURATION
*
* @mbggenerated Tue Jan 29 17:16:49 CST 2013
*/
List<Configuration> selectAll();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table MOCHA_SECU_CONFIGURATION
*
* @mbggenerated Tue Jan 29 17:16:49 CST 2013
*/
int updateByPrimaryKey(Configuration record);
Configuration selectByKey(String key);
int deleteByKey(String key);
} |
package com.projetopadrao.models.resposta;
public class Tarefa {
}
|
/*
* [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.commerceservices.order.hook.impl;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.commerceservices.enums.QuoteAction;
import de.hybris.platform.commerceservices.order.strategies.QuoteUpdateStateStrategy;
import de.hybris.platform.commerceservices.order.strategies.QuoteUserIdentificationStrategy;
import de.hybris.platform.commerceservices.service.data.CommerceCheckoutParameter;
import de.hybris.platform.commerceservices.service.data.CommerceOrderResult;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.core.model.order.QuoteModel;
import de.hybris.platform.core.model.user.UserModel;
import de.hybris.platform.servicelayer.user.UserService;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@Ignore
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class CommercePlaceQuoteOrderMethodHookTest
{
@InjectMocks
private final CommercePlaceQuoteOrderMethodHook commercePlaceQuoteOrderMethodHook = new CommercePlaceQuoteOrderMethodHook();
@Mock
private QuoteUpdateStateStrategy quoteUpdateStateStrategy;
@Mock
private QuoteUserIdentificationStrategy quoteUserIdentificationStrategy;
@Mock
private CommerceOrderResult commerceOrderResult;
@Mock
private OrderModel orderModel;
@Mock
private UserService userService;
@Test
public void shouldSetQuoteAsOrderedForQuoteBasedOrder()
{
final QuoteModel quoteModel = new QuoteModel();
final UserModel userModel = new UserModel();
given(quoteUserIdentificationStrategy.getCurrentQuoteUser()).willReturn(userModel);
given(commerceOrderResult.getOrder()).willReturn(orderModel);
given(orderModel.getQuoteReference()).willReturn(quoteModel);
commercePlaceQuoteOrderMethodHook.afterPlaceOrder(mock(CommerceCheckoutParameter.class), commerceOrderResult);
verify(quoteUpdateStateStrategy).updateQuoteState(QuoteAction.ORDER, quoteModel, userModel);
}
@Test
public void shouldNotTriggerUpdatesOnRegularOrder()
{
given(commerceOrderResult.getOrder()).willReturn(orderModel);
commercePlaceQuoteOrderMethodHook.afterPlaceOrder(mock(CommerceCheckoutParameter.class), commerceOrderResult);
verify(quoteUpdateStateStrategy, never()).updateQuoteState(any(), any(), any());
}
@Test(expected = IllegalArgumentException.class)
public void shouldCheckOrderArgumentAvailability()
{
commercePlaceQuoteOrderMethodHook.afterPlaceOrder(mock(CommerceCheckoutParameter.class), commerceOrderResult);
}
}
|
package com.ml.coupon.web.rest.error;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String error = ex.getParameter() + " parameter is missing";
ApiError apiError =
new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
return new ResponseEntity<Object>(
apiError, new HttpHeaders(), apiError.getStatus());
}
}
|
package academy.devdojo.variaveis;
import java.util.Scanner;
public class CalculadorDiferencaIdade {
public static void main(String[] args) {
int firstAge = 26;
int secondAge = 22;
int ageDifferent = firstAge - secondAge;
System.out.println("A diferença entre as idades é =" + ageDifferent);
/*
Lendo informações com Scanner
*/
Scanner scanner = new Scanner (System.in);
double distanciaPercorrida = scanner.nextDouble ();
scanner.close();
}
}
|
package com.tencent.mm.plugin.music.model.e;
import android.net.Uri;
import android.text.TextUtils;
import com.tencent.mars.smc.IDKey;
import com.tencent.mm.an.d;
import com.tencent.mm.hardcoder.HardCoderJNI;
import com.tencent.mm.plugin.music.c.a.b;
import com.tencent.mm.plugin.music.cache.e;
import com.tencent.mm.plugin.music.model.f;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.qqmusic.mediaplayer.AudioFormat.AudioType;
import com.tencent.qqmusic.mediaplayer.CommonPlayer;
import com.tencent.qqmusic.mediaplayer.PlayerListenerCallback;
import com.tencent.qqmusic.mediaplayer.network.IMediaHTTPService;
import java.net.URL;
import java.util.ArrayList;
public final class g extends a {
int aBN = 0;
AudioType audioType = AudioType.UNSUPPORT;
protected com.tencent.mm.an.a bTF;
int dGs = 0;
public CommonPlayer lwZ;
boolean lxb;
private IMediaHTTPService lxe;
String lxf = "";
private long lxh = 0;
private boolean lxi = false;
private PlayerListenerCallback lxk = new 1(this);
private d lyL;
public boolean lyX = false;
a lzT;
private class a implements Runnable {
boolean isStop;
private a() {
this.isStop = true;
}
/* synthetic */ a(g gVar, byte b) {
this();
}
public final void run() {
x.i("MicroMsg.Music.QQMusicPlayer", "start run play progress task");
while (!this.isStop) {
try {
if (g.this.lwZ != null && g.this.PY()) {
g.this.bhG();
}
} catch (Exception e) {
x.e("MicroMsg.Music.QQMusicPlayer", "PlayProgressTask run exception:" + e.getMessage());
}
try {
Thread.sleep(200);
} catch (InterruptedException e2) {
}
}
}
}
static /* synthetic */ void a(g gVar) {
if (gVar.audioType != null) {
x.i("MicroMsg.Music.QQMusicPlayer", "idKeyReportMusicMimeType audioType:%d, isStatMineType:%b", Integer.valueOf(gVar.audioType.getValue()), Boolean.valueOf(gVar.lxi));
if (!gVar.lxi) {
x.i("MicroMsg.Music.QQMusicPlayer", "idKeyReportMusicMimeType OK");
gVar.lxi = true;
IDKey iDKey = new IDKey();
iDKey.SetID(558);
int value = gVar.audioType.getValue();
value = value == 2 ? 92 : value == 3 ? 93 : value == 4 ? 94 : value == 5 ? 95 : value == 6 ? 96 : value == 7 ? 97 : value == 8 ? 98 : value == 9 ? 99 : 100;
iDKey.SetKey(value);
iDKey.SetValue(1);
ArrayList arrayList = new ArrayList();
arrayList.add(iDKey);
h.mEJ.b(arrayList, true);
Object Il = e.Il(gVar.lxf);
x.i("MicroMsg.Music.QQMusicPlayer", "mineTypeStr:%s", Il);
if (gVar.bTF == null || TextUtils.isEmpty(Il)) {
x.e("MicroMsg.Music.QQMusicPlayer", "music is null or mineTypeStr is empty");
return;
}
int IB = d.IB(Il);
h.mEJ.h(14486, Integer.valueOf(1), Integer.valueOf(gVar.bTF.field_musicType), Integer.valueOf(IB), Il);
}
}
}
public g() {
bir();
com.tencent.mm.plugin.music.b.a.a.biz();
}
public final void j(com.tencent.mm.an.a aVar) {
long currentTimeMillis = System.currentTimeMillis();
long j = currentTimeMillis - this.lxh;
if (this.bTF != null && this.bTF.a(aVar) && j <= 3000) {
this.bTF = aVar;
x.e("MicroMsg.Music.QQMusicPlayer", "startPlay, is playing for music src:%s, don't play again in 3 second, interval:%d", this.lxf, Long.valueOf(j));
} else if (aVar == null) {
x.e("MicroMsg.Music.QQMusicPlayer", "music is null");
} else {
URL url;
f.a(aVar, false);
this.lxh = currentTimeMillis;
this.bTF = aVar;
x.i("MicroMsg.Music.QQMusicPlayer", "startPlay, currentTime:%d, startTime:%d", Long.valueOf(currentTimeMillis), Integer.valueOf(aVar.field_startTime));
if (this.lwZ != null && PY()) {
this.lwZ.stop();
}
this.aBN = 0;
this.dGs = aVar.field_startTime;
this.audioType = null;
this.lxi = false;
x.i("MicroMsg.Music.QQMusicPlayer", "initPlayer");
this.lxf = this.bTF.playUrl;
x.i("MicroMsg.Music.QQMusicPlayer", "mSrc:%s", this.lxf);
x.i("MicroMsg.Music.QQMusicPlayer", "field_songWifiUrl:%s", this.bTF.field_songWifiUrl);
if (this.lxf != null) {
e.Ii(this.lxf);
e.bL(this.lxf, 0);
e.bM(this.lxf, 0);
}
try {
url = new URL(this.lxf);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.Music.QQMusicPlayer", e, "initPlayer", new Object[0]);
x.e("MicroMsg.Music.QQMusicPlayer", "new URL exception:" + e.getMessage());
url = null;
}
if (url == null) {
x.e("MicroMsg.Music.QQMusicPlayer", "initPlayer url is null");
a(this.bTF.PV(), 500);
a(this.bTF, 500);
return;
}
if (this.lwZ == null) {
this.lwZ = new CommonPlayer(this.lxk);
}
this.lwZ.reset();
if (this.lxe == null) {
this.lxe = new b();
}
try {
this.lwZ.setDataSource(this.lxe, Uri.parse(url.toString()));
this.lwZ.prepare();
} catch (Throwable e2) {
x.e("MicroMsg.Music.QQMusicPlayer", "initPlayer exception:" + e2.getMessage());
x.printErrStackTrace("MicroMsg.Music.QQMusicPlayer", e2, "initPlayer", new Object[0]);
a(this.bTF.PV(), HardCoderJNI.SCENE_DB);
a(this.bTF, HardCoderJNI.SCENE_DB);
}
}
}
public final void pause() {
this.lyX = false;
x.i("MicroMsg.Music.QQMusicPlayer", "pause");
if (this.lwZ != null && PY()) {
try {
this.lwZ.pause();
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.Music.QQMusicPlayer", e, "pause", new Object[0]);
a(this.bTF.PV(), 503);
a(this.bTF, 503);
}
}
}
public final void bhB() {
x.i("MicroMsg.Music.QQMusicPlayer", "pauseAndAbandonFocus");
pause();
com.tencent.mm.plugin.music.model.h.big().bhO();
}
public final boolean bho() {
return this.lxb && this.lyX;
}
public final void bhn() {
this.lyX = true;
x.i("MicroMsg.Music.QQMusicPlayer", "passivePause");
if (this.lwZ != null && PY()) {
try {
this.lwZ.pause();
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.Music.QQMusicPlayer", e, "passivePause", new Object[0]);
a(this.bTF.PV(), 503);
a(this.bTF, 503);
}
}
}
public final void resume() {
this.aBN = 0;
x.i("MicroMsg.Music.QQMusicPlayer", "resume, isPreparing:%b, isPlayingMusic:%b", Boolean.valueOf(bhC()), Boolean.valueOf(PY()));
if (this.lwZ != null && !r0 && !r1) {
if (com.tencent.mm.plugin.music.model.h.big().requestFocus()) {
try {
this.lwZ.start();
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.Music.QQMusicPlayer", e, "resume", new Object[0]);
a(this.bTF.PV(), 502);
a(this.bTF, 502);
}
p(com.tencent.mm.plugin.music.model.h.bic().bhS());
} else {
x.e("MicroMsg.Music.QQMusicPlayer", "request focus error");
}
this.lxb = true;
}
}
public final boolean PY() {
if (this.lwZ == null || this.lwZ.getPlayerState() != 4) {
return false;
}
return true;
}
private boolean bhC() {
if (this.lwZ == null || this.lwZ.getPlayerState() != 3) {
return false;
}
return true;
}
public final boolean PZ() {
return this.lxb && !bhC();
}
public final void stopPlay() {
x.i("MicroMsg.Music.QQMusicPlayer", "stopPlay");
try {
if (this.lwZ != null) {
this.lwZ.stop();
}
if (this.lzT != null) {
this.lzT.isStop = true;
this.lzT = null;
}
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.Music.QQMusicPlayer", e, "stopPlay", new Object[0]);
a(this.bTF.PV(), 504);
a(this.bTF, 504);
}
com.tencent.mm.plugin.music.model.h.big().bhO();
this.lxb = false;
this.lyX = false;
}
public final int getDuration() {
if (this.lwZ != null) {
return this.lwZ.getDuration();
}
return -1;
}
public final boolean if(int i) {
int duration = getDuration();
x.i("MicroMsg.Music.QQMusicPlayer", "seekToMusic pos:%d, duration:%d", Integer.valueOf(i), Integer.valueOf(duration));
if (duration < 0 || i > duration) {
x.e("MicroMsg.Music.QQMusicPlayer", "position is invalid, position:%d, duration:%d", Integer.valueOf(i), Integer.valueOf(duration));
stopPlay();
return false;
} else if (this.lwZ == null) {
return true;
} else {
t(this.bTF.PV());
this.lwZ.seekTo(i);
return true;
}
}
public final d bhq() {
int bufferedPercentage;
int i = 0;
int duration = getDuration();
int currentPosition = this.lwZ != null ? (int) this.lwZ.getCurrentPosition() : -1;
boolean PY = PY();
if (this.lwZ != null) {
bufferedPercentage = this.lwZ.getBufferedPercentage();
} else {
bufferedPercentage = 0;
}
if (bufferedPercentage < 0 || bufferedPercentage > 100) {
bufferedPercentage = 0;
}
if (bufferedPercentage < 0) {
bufferedPercentage = 0;
}
if (this.lyL != null) {
d dVar = this.lyL;
if (PY) {
i = 1;
}
dVar.j(duration, currentPosition, i, bufferedPercentage);
} else {
if (PY) {
i = 1;
}
this.lyL = new d(duration, currentPosition, i, bufferedPercentage);
}
this.lyL.bTG = true;
this.lyL.ebh = this.lzq;
return this.lyL;
}
private void a(com.tencent.mm.an.a aVar, int i) {
IDKey iDKey = new IDKey();
iDKey.SetID(558);
iDKey.SetKey(4);
iDKey.SetValue(1);
IDKey iDKey2 = new IDKey();
iDKey2.SetID(558);
int i2 = aVar.field_musicType;
x.i("MicroMsg.Music.MusicPlayIdKeyReport", "getQQMusicPlayerErrIdKeyByMusicType, musicType:" + i2);
switch (i2) {
case 0:
i2 = 49;
break;
case 1:
i2 = 50;
break;
case 4:
i2 = 51;
break;
case 5:
i2 = 52;
break;
case 6:
i2 = 53;
break;
case 7:
i2 = 54;
break;
case 8:
i2 = 55;
break;
case 9:
i2 = 56;
break;
case 10:
i2 = 7;
break;
case 11:
i2 = 8;
break;
default:
i2 = 9;
break;
}
iDKey2.SetKey(i2);
iDKey2.SetValue(1);
IDKey iDKey3 = new IDKey();
iDKey3.SetID(558);
iDKey3.SetKey(d.tG(i));
iDKey3.SetValue(1);
IDKey iDKey4 = new IDKey();
iDKey4.SetID(558);
iDKey4.SetValue(1);
ArrayList arrayList = new ArrayList();
int i3 = 0;
int i4 = 0;
if (i == 80) {
i2 = aVar.field_musicType;
x.i("MicroMsg.Music.MusicPlayIdKeyReport", "getQQMusicPlayerNetworkErrIdKeyByMusicType, musicType:" + i2);
switch (i2) {
case 0:
i2 = 167;
break;
case 1:
i2 = 168;
break;
case 4:
i2 = 169;
break;
case 6:
i2 = 170;
break;
case 7:
i2 = 171;
break;
case 8:
i2 = 172;
break;
case 9:
i2 = 173;
break;
case 10:
i2 = 174;
break;
case 11:
i2 = 175;
break;
default:
i2 = 188;
break;
}
iDKey4.SetKey(i2);
arrayList.add(iDKey4);
i3 = 1;
int Ip = e.Ip(this.lxf);
i2 = e.Iq(this.lxf);
if (e.Ip(this.lxf) == 403) {
IDKey iDKey5 = new IDKey();
iDKey5.SetID(558);
iDKey5.SetValue(1);
iDKey5.SetKey(d.tG(700));
arrayList.add(iDKey5);
i4 = Ip;
} else {
i4 = Ip;
}
} else if (e.Il(this.lxf) == null || !e.Il(this.lxf).contains("text/html")) {
if (i != 70) {
Object obj;
switch (i) {
case 62:
case 63:
case 64:
case 67:
case 74:
obj = 1;
break;
default:
obj = null;
break;
}
if (obj != null) {
IDKey iDKey6 = new IDKey();
iDKey6.SetID(558);
iDKey6.SetValue(1);
i2 = aVar.field_musicType;
x.i("MicroMsg.Music.MusicPlayIdKeyReport", "getQQMusicPlayerDecodeErrIdKeyByMusicType, musicType:" + i2);
switch (i2) {
case 0:
i2 = HardCoderJNI.SCENE_SEND_MSG;
break;
case 1:
i2 = HardCoderJNI.SCENE_SEND_PIC_MSG;
break;
case 4:
i2 = 204;
break;
case 6:
i2 = 205;
break;
case 7:
i2 = 206;
break;
case 8:
i2 = 207;
break;
case 9:
i2 = 208;
break;
case 10:
i2 = 209;
break;
case 11:
i2 = 210;
break;
default:
i2 = 188;
break;
}
iDKey6.SetKey(i2);
arrayList.add(iDKey6);
}
i2 = aVar.field_musicType;
x.i("MicroMsg.Music.MusicPlayIdKeyReport", "getQQMusicPlayerPlayErrIdKeyByMusicType, musicType:" + i2);
switch (i2) {
case 0:
i2 = 178;
break;
case 1:
i2 = 179;
break;
case 4:
i2 = 180;
break;
case 6:
i2 = 181;
break;
case 7:
i2 = 182;
break;
case 8:
i2 = 183;
break;
case 9:
i2 = 184;
break;
case 10:
i2 = 185;
break;
case 11:
i2 = 186;
break;
default:
i2 = 188;
break;
}
iDKey4.SetKey(i2);
arrayList.add(iDKey4);
}
i2 = 0;
} else {
i4 = HardCoderJNI.SCENE_SNS_SCROLL;
IDKey iDKey7 = new IDKey();
iDKey7.SetID(558);
iDKey7.SetValue(1);
iDKey7.SetKey(d.tG(HardCoderJNI.SCENE_SNS_SCROLL));
arrayList.add(iDKey7);
i2 = 0;
}
h.mEJ.h(14777, Integer.valueOf(1), Integer.valueOf(this.bTF.field_musicType), Integer.valueOf(i3), Integer.valueOf(i), Integer.valueOf(i4), Integer.valueOf(i2));
arrayList.add(iDKey);
arrayList.add(iDKey2);
arrayList.add(iDKey3);
h.mEJ.b(arrayList, true);
}
public final void bhG() {
com.tencent.mm.an.a bhR = com.tencent.mm.plugin.music.model.h.bic().bhR();
if (bhR != null && bhR.a(this.bTF) && this.lwZ != null && PY()) {
int currentPosition = (int) this.lwZ.getCurrentPosition();
int duration = this.lwZ.getDuration();
if (currentPosition > 0 && duration > 0 && this.lwX != null) {
this.lwX.co(currentPosition, duration);
}
}
}
public final boolean bhp() {
return true;
}
}
|
package com.trust.demo.code.QuanXian;
import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.trust.demo.R;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
public class QuanXianActivity extends AppCompatActivity {
Context context = QuanXianActivity.this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quan_xian);
getHistoryApps();
}
public void openPermission(View view) {
if (!checkPermission()) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivityForResult(intent, 100);
} else {
Toast.makeText(this, "权限已开启!", Toast.LENGTH_SHORT).show();
}
}
public void openService(View view) {
startService(new Intent(context, MonitorService.class));
Toast.makeText(this, "服务已开启!", Toast.LENGTH_SHORT).show();
}
public void closeService(View view) {
stopService(new Intent(context, MonitorService.class));
Toast.makeText(this, "服务已关闭!", Toast.LENGTH_SHORT).show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
if (!checkPermission()) {
Toast.makeText(this, "权限未开启!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "权限已开启!", Toast.LENGTH_SHORT).show();
}
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private boolean checkPermission() {
AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
int mode;
mode = appOps.checkOpNoThrow("android:get_usage_stats", android.os.Process.myUid(), getPackageName());
return mode == AppOpsManager.MODE_ALLOWED;
}
@TargetApi(Build.VERSION_CODES.N)
private void getHistoryApps() {
Calendar calendar = Calendar.getInstance();
long endTime = calendar.getTimeInMillis();
calendar.add(Calendar.YEAR, -1);
long startTime = calendar.getTimeInMillis();
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
List<UsageStats> usageStatsList = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_YEARLY, startTime, endTime);
if (usageStatsList != null && !usageStatsList.isEmpty()) {
HashSet<String> set = new HashSet<>();
for (UsageStats usageStats : usageStatsList) {
set.add(usageStats.getPackageName());
}
if (!set.isEmpty()) {
Log.e("size", set.size() + "");
}
}
}
}
|
package com.example.wpro.myapp7;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
public class mainController extends AppCompatActivity {
EditText getDateText, getTimeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
// intialize EditText
getDateText = (EditText) findViewById(R.id.getDateEditText);
getTimeText = (EditText) findViewById(R.id.getTimeEditText);
// listen EditText
getDateText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// get current date
Calendar cDate = Calendar.getInstance();
int cYear = cDate.get(Calendar.YEAR);
int cMonth = cDate.get(Calendar.MONTH);
int cDay = cDate.get(Calendar.DAY_OF_MONTH);
// initialize and show DateDialog
new DatePickerDialog(
mainController.this,
// listen DateDialog
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// show selected day in EditText
getDateText.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
}
}, cYear, cMonth, cDay
).show();
}
});
// listen EditText
getTimeText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// get current time
Calendar cTime = Calendar.getInstance();
final int cHour = cTime.get(Calendar.HOUR_OF_DAY);
final int cMinute = cTime.get(Calendar.MINUTE);
// initialize and show TimeDialog
new TimePickerDialog(
mainController.this,
new TimePickerDialog.OnTimeSetListener() {
// listen Time Dialog
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// show selected time in the EditText
getTimeText.setText(new StringBuilder().append(hourOfDay).append(":").append(minute).toString());
}
}, cHour, cMinute, true
).show();
}
}
);
}
}
|
package enthu_f;
public class e_1393 {
public static void main(String[] args) {
String myStr = "good";
char[] myCharArr = { 'g', 'o', 'o', 'd' };
String newStr = "";
for (char ch : myCharArr) {
newStr = newStr + ch;
}
boolean b1 = newStr == myStr;
boolean b2 = newStr.equals(myStr);
System.out.println(b1 + " " + b2);
}
}
|
package com.company;
import java.util.Scanner;
public class Task2_2
{
public static boolean isPalindrome(String text)
{
text = text.replaceAll("\\W",""); ////delete unnecessary symbols
StringBuilder strBuilder = new StringBuilder(text);
strBuilder.reverse(); ////string reverse
String invertedText = strBuilder.toString(); ////assign an inverted string
return text.equalsIgnoreCase(invertedText) ; ////return a comparison of two strings regardless of the register
}
public static void main(String args[])
{
String poly ="";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string");
poly += keyboard.nextLine();
if (isPalindrome(poly))
System.out.println("Polyndrom");
else
System.out.println("Isn't polyndrom");
}
}
|
package Peli;
public class Nappula {
private boolean valkoinen;
public Nappula() {
// TODO Auto-generated constructor stub
}
}
|
package com.wuyan.masteryi.admin.controller;
import com.wuyan.masteryi.admin.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* @Author: Zhao Shuqing
* @Date: 2021/7/7 15:32
* @Description:
*/
@Api(tags="分类管理接口")
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
CategoryService categoryService;
@ApiOperation(value="获取全部分类", notes="获取全部分类")
@PostMapping("/getallcategory")
@Transactional
public Map<String, Object> getAllType(){
return categoryService.getAllType();
}
@ApiOperation(value="添加新分类", notes="添加新分类")
@PostMapping("/addcategory")
public Map<String, Object> addCategory(Integer parentId, String categoryName){
return categoryService.addCategory(parentId, categoryName);
}
@ApiOperation(value="删除分类", notes="删除分类")
@PostMapping("/deletecategory")
public Map<String, Object> deleteCategory(Integer categoryId){
return categoryService.deleteCategory(categoryId);
}
@ApiOperation(value="更改分类名", notes="更改分类名")
@PostMapping("/changecategoryname")
public Map<String, Object> changeCategoryName(Integer categoryId,String newName){
return categoryService.changeCategoryName(categoryId,newName);
}
@ApiOperation(value="获取规格", notes="获取规格")
@PostMapping("/getallattr")
public Map<String, Object> getAllAttr(Integer categoryId){
return categoryService.getAllAttr(categoryId);
}
@ApiOperation(value="添加属性键", notes="添加属性键")
@PostMapping("/addattrkey")
public Map<String, Object> addAttrKey (Integer categoryId, String attrKeyName){
return categoryService.addAttrKey(categoryId, attrKeyName);
}
@ApiOperation(value="添加属性值", notes="添加属性值")
@PostMapping("/addattrvalue")
public Map<String, Object> addAttrValue (Integer attrKeyId, String attrValueName){
return categoryService.addAttrValue(attrKeyId, attrValueName);
}
@ApiOperation(value="删除属性键", notes="删除属性键")
@PostMapping("/deleteattrkey")
@Transactional
public Map<String, Object> deleteAttrKey(Integer attrKeyId,int categoryId){
return categoryService.deleteAttrKey(attrKeyId,categoryId);
}
@ApiOperation(value="删除属性值", notes="删除属性值")
@PostMapping("/deleteattrvalue")
@Transactional
public Map<String, Object> deleteAttrValue(Integer attrValueId){
return categoryService.deleteAttrValue(attrValueId);
}
@ApiOperation(value="更改属性键名字", notes="更改属性键名字")
@PostMapping("/changeattrkey")
public Map<String, Object> changeAttrKey(Integer attrKeyId, String newKeyName){
return categoryService.changeAttrKey(attrKeyId, newKeyName);
}
@ApiOperation(value="更改属性值名字", notes="更改属性值名字")
@PostMapping("/changeattrvalue")
public Map<String, Object> changeAttrValue(Integer attrValueId, String newValueName){
return categoryService.changeAttrValue(attrValueId, newValueName);
}
@ApiOperation(value = "根据key获得属性",notes = "根据key获得属性")
@PostMapping("/getValuesByKey")
public Map<String,Object> getKeyValueMap(int key_id){
return categoryService.getKeyMapValue(key_id);
}
@PostMapping("/addparent")
@ApiOperation(value = "添加新父级分类",notes = "添加新父级分类")
public Map<String,Object> addPrentCate(String cateName){
return categoryService.addParentCate(cateName);
}
}
|
package com.ev.srv.demopai.service;
import com.evo.api.springboot.exception.ApiException;
import java.util.Map;
import com.evo.api.springboot.exception.ApiException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Optional;
/**
* A delegate to be called by the {@link IswhithoutlinksController}}.
* Implement this interface with a {@link org.springframework.stereotype.Service} annotated class.
*/
public interface IswhithoutlinksService {
/**
* Return if a account is without links type.
*
* @return
*/
Map<String, Boolean> isWithoutLinksAccount(String acuerdoBE,String subacuerdo) throws ApiException;
}
|
package com.xujiangjun.archetype.exception;
import com.xujiangjun.archetype.enums.ResponseEnum;
import lombok.Getter;
/**
* 自定义业务异常类
*
* @author xujiangjun
* @since 2018.05.20
*/
public class BusinessException extends RuntimeException {
@Getter
private int code;
public BusinessException(ResponseEnum responseEnum){
super(responseEnum.getMessage());
this.code = responseEnum.getCode();
}
public BusinessException(ResponseEnum responseEnum, String message){
super(message);
this.code = responseEnum.getCode();
}
public BusinessException(int code, String message) {
super(message);
this.code = code;
}
public BusinessException(int code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}
|
package Application;
import java.io.IOException;
import Clustering.FCM_Fast;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
public class Controller_ListaDataSet
{
@FXML
private Label Title;
@FXML
private BorderPane layout;
@FXML
private VBox Lista_Record = null;
@FXML
private Button New_DS = null;
@FXML
private Button Avanti = null;
private int Max_Cluster = 0;
public Controller_ListaDataSet()
{
Lista_Record = new VBox();
}
public void setInit( BorderPane L )
{
layout = L;
TestMain.setCenterLayout(layout);
}
@FXML
void initialize()
{
Title.getStyleClass().add("Title_Page");
New_DS.getStyleClass().add("button_next");
New_DS.setOnAction( e -> NuovoDS() );
Avanti.getStyleClass().add("button_next");
Avanti.setOnAction( e -> Controller_Wait_Clustering.esegui( 3 * Max_Cluster ) );
}
public void InizializzaTable()
{
Lista_Record = new VBox();
Lista_Record.setPrefHeight(40);
Lista_Record.setPrefWidth(80);
Lista_Record.setSpacing(10);
Lista_Record.setPadding(new Insets(70, 0, 10, 10));
layout.getChildren().set( 2, Lista_Record );
Max_Cluster = 0;
TestMain.setCenterLayout(layout);
}
public void addDataSet( String NomeDataSet )
{
Label N = new Label();
Button Modifica = new Button("Modifica");
Button Elimina = new Button("Elimina");
Label Label_Num_Clus = new Label("N Cluster");
TextField Text_Num_Clus = new TextField();
Label Label_Epsilon = new Label("Epsilon");
TextField Text_Epsilon = new TextField();
Label Label_Iter = new Label("Iter");
TextField Text_Iter = new TextField();
HBox Riga = new HBox();
FCM_Fast F_DS = TestMain.getSessione_InCorso().get_FCM(NomeDataSet);
if( Max_Cluster < F_DS.getNum_Cluster() )
Max_Cluster = F_DS.getNum_Cluster();
N.setText(NomeDataSet);
N.getStyleClass().add("Nome_DataSet");
Modifica.getStyleClass().add("button_setting");
Modifica.setOnAction( e -> ModificaDataSet(NomeDataSet) );
Elimina.getStyleClass().add("button_setting");
Elimina.setOnAction( e -> EliminaDataSet(NomeDataSet) );
N.setMinHeight( 40 );
N.setMinWidth( 80 );
Modifica.setMinHeight( 40 );
Elimina.setMinHeight( 40 );
Modifica.setMinWidth( 90 );
Elimina.setMinWidth( 80 );
Label_Num_Clus.getStyleClass().add("Label_Setting");
Label_Num_Clus.setMinHeight( 40 );
Label_Num_Clus.setMinWidth( 90 );
Label_Num_Clus.setFont(Font.font("Amble CN", FontWeight.BOLD, 14));
Label_Num_Clus.setPadding(new Insets(0, 0, 0, 15));
Label_Epsilon.getStyleClass().add("Label_Setting");
Label_Epsilon.setMinHeight( 40 );
Label_Epsilon.setMinWidth( 70 );
Label_Epsilon.setFont(Font.font("Amble CN", FontWeight.BOLD, 14));
Label_Epsilon.setPadding(new Insets(0, 0, 0, 15));
Label_Iter.getStyleClass().add("Label_Setting");
Label_Iter.setMinHeight( 40 );
Label_Iter.setMinWidth( 50 );
Label_Iter.setFont(Font.font("Amble CN", FontWeight.BOLD, 14));
Label_Iter.setPadding(new Insets(0, 0, 0, 15));
Text_Num_Clus.setMinHeight( 30 );
Text_Num_Clus.setMinWidth( 40 );
Text_Num_Clus.setPadding(new Insets(0, 0, 0, 15));
Text_Num_Clus.setText( "" + F_DS.getNum_Cluster() );
Text_Num_Clus.focusedProperty().addListener(new ChangeListener<Boolean>()
{
@Override
public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue)
{
if (!newPropertyValue)
{
try
{
int Num_Clu = Integer.parseInt(Text_Num_Clus.getText());
Double Eps = Double.parseDouble(Text_Epsilon.getText());
int Iter = Integer.parseInt(Text_Iter.getText());
TestMain.getSessione_InCorso().Change_Param_Clust( NomeDataSet, Num_Clu, Eps, Iter );
if( Max_Cluster < Num_Clu )
Max_Cluster = Num_Clu;
FCM_Fast F = TestMain.getSessione_InCorso().get_FCM(NomeDataSet);
Text_Num_Clus.setText("" + F.getNum_Cluster());
Text_Epsilon.setText("" + F.get_Epsilon());
Text_Iter.setText("" + F.getMax_Iter());
}
catch ( NumberFormatException exception )
{
FCM_Fast F = TestMain.getSessione_InCorso().get_FCM(NomeDataSet);
F.InserisciNumClass(2);
Text_Iter.setText("" + F.getMax_Iter());
Text_Num_Clus.setText("" + F.getNum_Cluster());
Text_Epsilon.setText("" + F.get_Epsilon());
}
}
}
});
Text_Epsilon.setMinHeight( 30 );
Text_Epsilon.setMinWidth( 60 );
Text_Epsilon.setPadding(new Insets(0, 0, 0, 15));
Text_Epsilon.setText( "" + F_DS.get_Epsilon() );
Text_Epsilon.focusedProperty().addListener(new ChangeListener<Boolean>()
{
@Override
public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue)
{
if (!newPropertyValue)
{
try
{
int Num_Clu = Integer.parseInt(Text_Num_Clus.getText());
Double Eps = Double.parseDouble(Text_Epsilon.getText());
int Iter = Integer.parseInt(Text_Iter.getText());
TestMain.getSessione_InCorso().Change_Param_Clust( NomeDataSet, Num_Clu, Eps, Iter );
FCM_Fast F = TestMain.getSessione_InCorso().get_FCM(NomeDataSet);
Text_Num_Clus.setText("" + F.getNum_Cluster());
Text_Epsilon.setText("" + F.get_Epsilon());
Text_Iter.setText("" + F.getMax_Iter());
}
catch ( NumberFormatException exception )
{
FCM_Fast F = TestMain.getSessione_InCorso().get_FCM(NomeDataSet);
F.setEpsilon(0.001);
Text_Iter.setText("" + F.getMax_Iter());
Text_Num_Clus.setText("" + F.getNum_Cluster());
Text_Epsilon.setText("" + F.get_Epsilon());
}
}
}
});
Text_Iter.setMinHeight( 30 );
Text_Iter.setMinWidth( 60 );
Text_Iter.setPadding(new Insets(0, 0, 0, 15));
Text_Iter.setText( "" + F_DS.getMax_Iter() );
Text_Iter.focusedProperty().addListener(new ChangeListener<Boolean>()
{
@Override
public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue)
{
if (!newPropertyValue)
{
try
{
int Num_Clu = Integer.parseInt(Text_Num_Clus.getText());
Double Eps = Double.parseDouble(Text_Epsilon.getText());
int Iter = Integer.parseInt(Text_Iter.getText());
TestMain.getSessione_InCorso().Change_Param_Clust( NomeDataSet, Num_Clu, Eps, Iter );
FCM_Fast F = TestMain.getSessione_InCorso().get_FCM(NomeDataSet);
Text_Num_Clus.setText("" + F.getNum_Cluster());
Text_Epsilon.setText("" + F.get_Epsilon());
Text_Iter.setText("" + F.getMax_Iter());
}
catch ( NumberFormatException exception )
{
FCM_Fast F = TestMain.getSessione_InCorso().get_FCM(NomeDataSet);
F.setMaxIter(1000);
Text_Iter.setText("" + F.getMax_Iter());
Text_Num_Clus.setText("" + F.getNum_Cluster());
Text_Epsilon.setText("" + F.get_Epsilon());
}
}
}
});
VBox V1 = new VBox();
V1.getChildren().add( Modifica );
V1.setPadding(new Insets(0, 10, 0, 15));
VBox V2 = new VBox();
V2.getChildren().add( Elimina );
V2.setPadding(new Insets(0, 0, 0, 10));
Riga.getChildren().addAll( N, Label_Num_Clus, Text_Num_Clus, Label_Epsilon, Text_Epsilon, Label_Iter, Text_Iter, V1, V2 );
Lista_Record.getChildren().add( Riga );
layout.getChildren().set( 2, Lista_Record );
TestMain.setCenterLayout(layout);
}
private void ModificaDataSet( String M )
{
try
{
FXMLLoader file_xml = new FXMLLoader();
file_xml.setLocation(getClass().getResource("Modifica_DataSet.fxml"));
BorderPane layout = file_xml.load();
Controller_Modifica_DataSet Mod = file_xml.getController();
Mod.setInit( TestMain.getStage(), layout, M );
}
catch( IOException e )
{
e.printStackTrace();
}
}
public void EliminaDataSet( String E )
{
TestMain.getSessione_InCorso().EliminaDataSet(E);
}
private void NuovoDS()
{
try
{
FXMLLoader file_xml = new FXMLLoader();
file_xml.setLocation(getClass().getResource("Modifica_DataSet.fxml"));
BorderPane layout = file_xml.load();
Controller_Modifica_DataSet Mod = file_xml.getController();
Mod.setInit( TestMain.getStage(), layout, "" );
}
catch( IOException e )
{
e.printStackTrace();
}
}
} |
package com.ientaltsev2.langs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
//=================================================================
// readJSONFeed()
// 10. connect to the specified URL
// 20. read the web server's response
//=================================================================
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
//===================================================
Log.d("a2/readJSONFeed()", "passed the assignments");
//===================================================
//==========================================================
// try to establish a connection to the URL
//==========================================================
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Log.d("a2/readJSONFeed()/try{}", "passed the assignments");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Log.d("a2/readJSONFeed()/try{}", "statusCode: " + statusCode);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//============================================================
// if connection to the URL is a success
// read the response from the web server
//============================================================
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int lineCount = 0;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// see the contents of the line
//Log.d("a2/readJSONFeed()/try{}", "reader.readLine()): " + reader.readLine());
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//==================================
// append one line
//==================================
while ((line = reader.readLine()) != null) {
lineCount +=1;
stringBuilder.append(line);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Log.d("a2/readJSONFeed()/try{}/while()", "lineCount: " + lineCount);
Log.d("a2/readJSONFeed()/try{}", "line: " + line);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//================================================
//================================================
}
//============================================================
// if connection to the URL is a failure
//============================================================
else {
Log.e("JSON", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//=========================================================
// return a string as a result
//=========================================================
return stringBuilder.toString();
}
//======================================================================
// ReadJSONFeedTask : AsyncTask
// to call ReadJSONFeed() asynchronously
//======================================================================
private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
//=================================================================
// doInBackGround()
// call readJSONFeed()
//=================================================================
protected String doInBackground(String... urls) {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Log.d("a2/ReadJSONFeedTask()/doInBackground()", "before return readJSONFeed(urls[0])");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
return readJSONFeed(urls[0]);
}
//=================================================================
// onPostExecute()
// take JSON string you have fetched and
// pass it through this method
//=================================================================
protected void onPostExecute(String result) {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Log.d("a2/ReadJSONFeedTask()/onPostExecute()", "before try{}");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
try {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Log.d("a2/ReadJSONFeedTask()/onPostExecute()/try{}", "entered");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// show long line
Log.d("a2/ReadJSONFeedTask()/onPostExecute()/try{}", "result: " + result);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//=================================================================
// 10. pass it the JSON feed (result)
// and create a JSONArray
//=================================================================
JSONArray jsonArray = new JSONArray(result); // 10
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Log.d("a2/ReadJSONFeedTask()/onPostExecute()/try{}", "jsonArray.length(): " + jsonArray.length());
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//==============================================================
// print out the content of the json feed
// 10. for the number of objects in the JSONArray
// 20. obtain each object from the array
// 30. obtain the value of the key/value pair stored inside the JSON object
// "text" is the key, "created_at" is the key
//==============================================================
for (int i = 0; i < jsonArray.length(); i++) { // 10
JSONObject jsonObject = jsonArray.getJSONObject(i); // 20
/*
Toast.makeText(getBaseContext(), jsonObject.getString("appeId") +
" - " + jsonObject.getString("inputTime"),
Toast.LENGTH_SHORT).show();
*/
Toast.makeText(getBaseContext(), jsonObject.getString("text") +
" - " + jsonObject.getString("created_at"),
Toast.LENGTH_SHORT).show(); // 30
} // for
} catch (Exception e) {
e.printStackTrace();
} // try
} // onPostExecute()
} // ReadJSONFeedTask
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//=======================================================
// make sure the app is alive, i.e. works fine
//=======================================================
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Log.d("a2/onCreate()", "before ReadJSONFeedTask.execute");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//==================================================================================
// the source of the JSON string
// access the JSON feed asynchronously
//==================================================================================
new ReadJSONFeedTask().execute("http://data.gc.ca/data/api/action/package_show?id=7f620ce0-4d40-41c6-8e66-f0771619d256");
//new ReadJSONFeedTask().execute("http://extjs.org.cn/extjs/examples/grid/survey.html");
//new ReadJSONFeedTask().execute("https://twitter.com/statuses/user_timeline/weimenglee.json");
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Log.d("a2/onCreate()", "after ReadJSONFeedTask.execute");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
}
|
package com.herz.sockets.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Random;
public class ClientRunner {
private Socket mSocket;
private DataInputStream mDataInputStream;
private DataOutputStream mDataOutputStream;
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Error, number of parameters invalid.\n"
+ "Just only one parameter for the port number!");
} else {
new ClientRunner(args[0]);
}
}
private ClientRunner(String port) {
this.initializeClient(port);
}
private void initializeClient(String port) {
try {
Random random = new Random();
this.mSocket = new Socket(InetAddress.getLocalHost(), Integer.parseInt(port));
this.mDataInputStream = new DataInputStream(this.mSocket.getInputStream());
this.mDataOutputStream = new DataOutputStream(this.mSocket.getOutputStream());
for (int i = 0; i < 10 + random.nextInt(990); i++) {
this.mDataOutputStream.writeInt(random.nextInt(10000));
System.out.println(this.mDataInputStream.readInt());
}
this.mDataInputStream.close();
this.mDataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package pages;
public class ProductPage extends BasePage {
public String returnTextTabProduct() {
return getVisibleElementById("enterproductdata")
.getText()
.replaceAll("[^A-Za-z- ]", "");
}
public void clickInProductTab() {
getClickableElementById("enterproductdata").click();
}
public void insertStartDate(String date) {
getVisibleElementById("startdate").sendKeys(date);
}
public void selectInsuranceSum(String text) {
selectInComboById("insurancesum", text);
}
public void selectMeritRating(String text){
selectInComboById("meritrating", text);
}
public void selectDamageinsurance(String text){
selectInComboById("damageinsurance", text);
}
public void selectOptionalProductEuroProtection() {
actionById("EuroProtection").click().perform();
}
public void selectCourtesyCar(String text) {
selectInComboById("courtesycar", text);
}
}
|
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(3);
// threadPoolExecutor.schedule(() -> System.out.println("Task"), 5, TimeUnit.SECONDS);
ScheduledFuture<?> future = threadPoolExecutor.scheduleAtFixedRate(() -> System.out.println("Task"), 5, 1, TimeUnit.SECONDS);
threadPoolExecutor.shutdown();
threadPoolExecutor.shutdownNow();
threadPoolExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(true);
threadPoolExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
}
}
|
package lexer;
public class Real extends Token {
public final float value;
public Real(float v){super(Tag.REAL);value=v;}
public String toString (){return ""+value;}
}
|
package com.example.x_b;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.x_b.db.BooleanBeanDao;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
public class Rvadapter extends RecyclerView.Adapter<Rvadapter.ViewHolder> {
private ArrayList<DatasBean> list;
private Context context;
private ArrayList<BooleanBean> booleanBeans;
public Rvadapter(ArrayList<DatasBean> list, Context context, ArrayList<BooleanBean> booleanBeans) {
this.list = list;
this.context = context;
this.booleanBeans = booleanBeans;
}
public Rvadapter(ArrayList<DatasBean> list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View inflate = LayoutInflater.from(context).inflate(R.layout.item, null);
return new ViewHolder(inflate);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.tv.setText(list.get(position).getTitle());
Glide.with(context).load(list.get(position).getEnvelopePic()).into(holder.iv);
//用数据控制页面展示
holder.ck.setChecked(list.get(position).getIsCheckd());
//BooleanBeanDao booleanBeanDao = BaseApp.getInstance().getDaoSession().getBooleanBeanDao();
holder.ck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isPressed()){
list.get(position).setIsCheckd(isChecked);
// DatasBean datasBean = list.get(position);
//插入数据库
// booleanBeanDao.update(new BooleanBean((long) position,true));
EventBus.getDefault().post(new EvenBusBean(position,1));
}else {
//取消插入数据库
// booleanBeanDao.update(new BooleanBean((long) position,false));
EventBus.getDefault().post(new EvenBusBean(position,2));
}
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView iv;
public TextView tv;
public CheckBox ck;
public ViewHolder(@NonNull View itemView) {
super(itemView);
this.iv = (ImageView) itemView.findViewById(R.id.iv);
this.tv = (TextView) itemView.findViewById(R.id.tv);
this.ck = (CheckBox) itemView.findViewById(R.id.ck);
}
}
}
|
package ctci.chap2;
import ctci.ctciLibrary.AssortedMethods;
import ctci.ctciLibrary.LinkedListNode;
public class DeleteMiddleNode{
// Assuming singly linked list
// Can't delete if node is last the list, but could potentially flag as "end" by filling in some dummy data
public static void deleteNode(LinkedListNode node){
if(node == null || node.next == null){ return; }
node.data = node.next.data;
node.next = node.next.next;
}
public static void main(String[] args) {
LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10);
System.out.println(head.printForward());
deleteNode(head.next.next.next.next); // delete node 4
System.out.println(head.printForward());
}
} |
/*
* Copyright (C), 2013-2014, 上海汽车集团股份有限公司
* FileName: ContentType.java
* Author: baowenzhou
* Date: 2015年09月28日 上午11:33:46
* Description: //模块目的、功能描述
* History: //修改记录
* <author> <time> <version> <desc>
* 修改人姓名 修改时间 版本号 描述
*/
package com.xjf.wemall.api.constant;
import com.xjf.wemall.api.constant.api.Code;
/**
* HTTP 请求头信息<br>
* 〈功能详细描述〉
*
* @author baowenzhou
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public enum ContentType implements Code<String> {
SOAP_XML_UTF8("application/soap+xml;charset=UTF-8"),
DEFAULT_FORM("application/x-www-form-urlencoded"),
SOAP_XML_GBK("application/soap+xml;charset=GBK"),
JSON_UTF8("application/json;charset=UTF-8");
/**请求头类型*/
private String code;
private ContentType(String code){
this.code=code;
}
/**
* {@inheritDoc}
*/
@Override
public String code() {
return this.code;
}
}
|
/*
* 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 edu.eci.arsw.webstore.services.product;
import edu.eci.arsw.webstore.model.Product;
import java.util.List;
/**
*
* @author jmvillatei
*/
public interface ProductServices {
/**
* Este metodo permite obtener todos los productos de todos los usuarios
*
* @return Una lista con todos los productos
*/
public List<Product> getAllProducts();
/**
* Este metodo permite obtener todos los productos de un usuario
*
* @param userNickname nickname del usuario
* @return Una lista con todos los productos
*/
public List<Product> getAllProductsOfUserNickname(String userNickname);
/**
* este metodo permite crear un producto de un usuario especifico
*
* @param pr Es el nuevo producto que se agregara.
*/
public void createNewProduct(Product pr);
/**
* Este metodo permite obtener un producto por id de un usuario
*
* @param id id del producto a obtener
* @return El producto que pertenece a ese usuario
*/
public Product getProductByIdOfUserNickname(String id);
/**
* Este metodo permite eliminar un producto de un usuario
*
* @param id Es el id del producto que se va a eliminar
* @param idUser Es el id del usuario dueño del producto.
*/
public void deleteProductByIdOfUserNickname(String id, String idUser);
/**
* Este metodo permite modificar un producto del usuario.
* @param productId Es el id del producto
* @param pd Es el producto que se va a editar.
*/
public void editProductById(String productId, Product pd);
}
|
package com.wt.jiaduo.service;
import org.springframework.data.domain.Page;
import com.wt.jiaduo.dto.jpa.XiaomaiTiaoxiubingHouqi;
public interface XiaomaiTiaoxiubingHouqiService {
public Page<XiaomaiTiaoxiubingHouqi> findAll(Integer pageNum,Integer pageSize);
public XiaomaiTiaoxiubingHouqi saveOne(XiaomaiTiaoxiubingHouqi xiaomaiTiaoxiubingHouqi);
public XiaomaiTiaoxiubingHouqi modify(XiaomaiTiaoxiubingHouqi xiaomaiTiaoxiubingHouqi);
public void delete(Integer id);
public XiaomaiTiaoxiubingHouqi getOne(Integer id);
}
|
package io.github.qyvlik.iostnode.response.tx;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.List;
import java.util.Map;
public class TxReceipt {
public static final String TX_RECEIPT_STATUS_CODE_SUCCESS = "SUCCESS"; // 成功
public static final String TX_RECEIPT_STATUS_CODE_GAS_RUN_OUT = "GAS_RUN_OUT"; // Gas不足
public static final String TX_RECEIPT_STATUS_CODE_BALANCE_NOT_ENOUGH = "BALANCE_NOT_ENOUGH"; // 余额不足
public static final String TX_RECEIPT_STATUS_CODE_WRONG_PARAMETER = "WRONG_PARAMETER"; // 错误参数
public static final String TX_RECEIPT_STATUS_CODE_RUNTIME_ERROR = "RUNTIME_ERROR"; // 运行时错误
public static final String TX_RECEIPT_STATUS_CODE_TIMEOUT = "TIMEOUT"; // 超时
public static final String TX_RECEIPT_STATUS_CODE_WRONG_TX_FORMAT = "WRONG_TX_FORMAT"; // 交易格式错误
public static final String TX_RECEIPT_STATUS_CODE_WRONG_DUPLICATE_SET_CODE = "DUPLICATE_SET_CODE"; // 重复设置set code
public static final String TX_RECEIPT_STATUS_CODE_WRONG_UNKNOWN_ERROR = "UNKNOWN_ERROR"; // 未知错误
@JSONField(name = "tx_hash")
private String txHash; // 交易的hash
@JSONField(name = "gas_usage")
private Double gasUsage; // 交易执行的Gas消耗
@JSONField(name = "ram_usage")
private Map<String, Long> ramUsage; // 交易的RAM消耗,map-key - 账户名,map-value - 使用RAM量
@JSONField(name = "status_code")
private String statusCode; // 交易执行状态,SUCCESS - 成功,GAS_RUN_OUT - Gas不足,BALANCE_NOT_ENOUGH - 余额不足,WRONG_PARAMETER - 错误参数, RUNTIME_ERROR - 运行时错误, TIMEOUT - 超时, WRONG_TX_FORMAT - 交易格式错误, DUPLICATE_SET_CODE - 重复设置set code, UNKNOWN_ERROR - 未知错误
@JSONField(name = "message")
private String message; // status_code的详细描述信息
@JSONField(name = "returns")
private List<String> returns; // 每个Action的返回值
@JSONField(name = "receipts")
private List<Receipt> receipts; // event功能使用
public String getTxHash() {
return txHash;
}
public void setTxHash(String txHash) {
this.txHash = txHash;
}
public Double getGasUsage() {
return gasUsage;
}
public void setGasUsage(Double gasUsage) {
this.gasUsage = gasUsage;
}
public Map<String, Long> getRamUsage() {
return ramUsage;
}
public void setRamUsage(Map<String, Long> ramUsage) {
this.ramUsage = ramUsage;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<String> getReturns() {
return returns;
}
public void setReturns(List<String> returns) {
this.returns = returns;
}
public List<Receipt> getReceipts() {
return receipts;
}
public void setReceipts(List<Receipt> receipts) {
this.receipts = receipts;
}
@Override
public String toString() {
return "TxReceipt{" +
"txHash='" + txHash + '\'' +
", gasUsage=" + gasUsage +
", ramUsage=" + ramUsage +
", statusCode='" + statusCode + '\'' +
", message='" + message + '\'' +
", returns=" + returns +
", receipts=" + receipts +
'}';
}
}
|
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Collection;
import java.util.stream.Stream;
@EnableBinding(Sink.class)
@EnableDiscoveryClient
@SpringBootApplication
public class ReservationServiceApplication {
@Bean
HealthIndicator healthIndicator() {
return () -> Health.status("I <3 Denver!!").build();
}
public static void main(String[] args) {
SpringApplication.run(ReservationServiceApplication.class, args);
}
}
@MessageEndpoint
class ReservationProcessor {
@Autowired
private ReservationRepository reservationRepository;
@ServiceActivator(inputChannel = "input")
public void acceptNewReservation(String reservationName) {
this.reservationRepository.save(new Reservation(reservationName));
}
}
@RestController
@RefreshScope
class MessageRestController {
@Value("${message}")
private String message;
@RequestMapping(method = RequestMethod.GET, value = "/message")
String readMessage() {
return this.message;
}
}
@Component
class DummyCLR implements CommandLineRunner {
@Autowired
private ReservationRepository reservationRepository;
@Override
public void run(String... args) throws Exception {
Stream.of("Lokesh", "Robert", "Josh", "Chad", "Chad", "Sean")
.forEach(name -> reservationRepository.save(new Reservation(name)));
reservationRepository.findAll().forEach(System.out::println);
}
}
@RepositoryRestResource
interface ReservationRepository extends JpaRepository<Reservation, Long> {
// select * from reservations where reservation_name = :rn
@RestResource(path = "by-name")
Collection<Reservation> findByReservationName(@Param("rn") String rn);
}
@Entity
class Reservation { // reservations
@Id
@GeneratedValue
private Long id; // id
@Override
public String toString() {
return "Reservation{" +
"id=" + id +
", reservationName='" + reservationName + '\'' +
'}';
}
Reservation() {// why JPA why???
}
public Reservation(String reservationName) {
this.reservationName = reservationName;
}
public Long getId() {
return id;
}
public String getReservationName() {
return reservationName;
}
private String reservationName; // reservation_name
} |
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.IstAnalyseIdentType;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.IstAnalyseType;
import java.io.StringWriter;
import java.math.BigInteger;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
public class IstAnalyseTypeBuilder
{
public static String marshal(IstAnalyseType istAnalyseType)
throws JAXBException
{
JAXBElement<IstAnalyseType> jaxbElement = new JAXBElement<>(new QName("TESTING"), IstAnalyseType.class , istAnalyseType);
StringWriter stringWriter = new StringWriter();
return stringWriter.toString();
}
private IstAnalyseIdentType istAnalyseIdent;
private BigInteger materialklasse;
private String stahlmarkenKurzbezeichnung;
private String stahlmarkenKurzbezeichnungDFS;
private Double kWert;
public IstAnalyseTypeBuilder setIstAnalyseIdent(IstAnalyseIdentType value)
{
this.istAnalyseIdent = value;
return this;
}
public IstAnalyseTypeBuilder setMaterialklasse(BigInteger value)
{
this.materialklasse = value;
return this;
}
public IstAnalyseTypeBuilder setStahlmarkenKurzbezeichnung(String value)
{
this.stahlmarkenKurzbezeichnung = value;
return this;
}
public IstAnalyseTypeBuilder setStahlmarkenKurzbezeichnungDFS(String value)
{
this.stahlmarkenKurzbezeichnungDFS = value;
return this;
}
public IstAnalyseTypeBuilder setKWert(Double value)
{
this.kWert = value;
return this;
}
public IstAnalyseType build()
{
IstAnalyseType result = new IstAnalyseType();
result.setIstAnalyseIdent(istAnalyseIdent);
result.setMaterialklasse(materialklasse);
result.setStahlmarkenKurzbezeichnung(stahlmarkenKurzbezeichnung);
result.setStahlmarkenKurzbezeichnungDFS(stahlmarkenKurzbezeichnungDFS);
result.setKWert(kWert);
return result;
}
} |
package com.cm4j.registry;
import com.cm4j.registry.registered.IRegistered;
/**
* 注册容器:类型为对象的class,值为对象本身
*
* @author yeas.fun
* @since 2021/1/7
*/
public abstract class AbstractClassRegistry<K, V extends IRegistered> extends AbstractRegistry<K, V> {
/**
* 扫描包进行注册
*
* @param packScan 待扫描的包,有多个包时以","分隔
*/
protected AbstractClassRegistry(String packScan) {
super(packScan);
}
@Override
protected K[] getRegistryKeys(V v) {
K aClass = (K)v.getClass();
return (K[])new Object[] {aClass};
}
}
|
package cl.tesoreria.sae.retenciones.vo;
public class ConvenioJudicialVO {
private String convJuducialId;
private String juzgado;
private String sindico;
private String fechaIngre;
private String rut;
private String dv;
private String nombre;
private String appPat;
private String appMat;
private String fechAprovConv;
private String numExpe;
private String expeYear;
private String folio;
private String observacion;
private String estado;
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getRut() {
return rut;
}
public String getDv() {
return dv;
}
public String getNombre() {
return nombre;
}
public String getAppPat() {
return appPat;
}
public String getAppMat() {
return appMat;
}
public String getFolio() {
return folio;
}
public String getFechaIngre() {
return fechaIngre;
}
public String getObservacion() {
return observacion;
}
public String getConvJuducialId() {
return convJuducialId;
}
public String getJuzgado() {
return juzgado;
}
public String getSindico() {
return sindico;
}
public String getFechAprovConv() {
return fechAprovConv;
}
public String getNumExpe() {
return numExpe;
}
public String getExpeYear() {
return expeYear;
}
public void setRut(String rut) {
this.rut = rut;
}
public void setDv(String dv) {
this.dv = dv;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void setAppPat(String appPat) {
this.appPat = appPat;
}
public void setAppMat(String appMat) {
this.appMat = appMat;
}
public void setFolio(String folio) {
this.folio = folio;
}
public void setFechaIngre(String fechaIngre) {
this.fechaIngre = fechaIngre;
}
public void setObservacion(String observacion) {
this.observacion = observacion;
}
public void setConvJuducialId(String convJuducialId) {
this.convJuducialId = convJuducialId;
}
public void setJuzgado(String juzgado) {
this.juzgado = juzgado;
}
public void setSindico(String sindico) {
this.sindico = sindico;
}
public void setFechAprovConv(String fechAprovConv) {
this.fechAprovConv = fechAprovConv;
}
public void setNumExpe(String numExpe) {
this.numExpe = numExpe;
}
public void setExpeYear(String expeYear) {
this.expeYear = expeYear;
}
}
|
package com.enat.sharemanagement.security;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AuthenticationResponse {
private String token;
private String userId;
private String displayName;
private boolean firstLogin;
}
|
package com.cse308.sbuify.common;
import java.util.Collection;
import com.cse308.sbuify.album.Album;
import com.cse308.sbuify.song.Song;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property="type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Album.class, name = "album"),
@JsonSubTypes.Type(value = Song.class, name = "song")
})
public interface Queueable {
Collection<Song> getItems();
}
|
package file;
import java.io.*;
import java.util.ArrayList;
import entity.*;
public class InputFile {
ArrayList<String> data = new ArrayList<String>();
ArrayList<Contract> contracts = new ArrayList<Contract>();
public void InputFileFunction() {
try {
BufferedReader bis = new BufferedReader(new FileReader("contracts.txt"));
String c = "";
while ((c = bis.readLine()) != null) {
data.add(c);
}
}catch(IOException ex){
System.out.println(ex.getMessage());
}
System.out.println("Ok");
for(String i: data) {
String [] mas = i.split(" ");
Client c = new Client();
c.setInformation("",mas[1]+" "+mas[2]+" "+mas[3]+" ","");
Contract contract = new Contract();
contract.setInform(c, Integer.valueOf(mas[0]), mas[4], mas[5], mas[6], Integer.valueOf(mas[7]));
contracts.add(contract);
System.out.println("Contract was added");
}
for(Contract c: contracts) {
System.out.println(c.getInformation());
}
}
public Contract methodForTest () {
return contracts.get(0);
}
}
|
package org.wuqinghua.server;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
/**
* Created by wuqinghua on 18/2/24.
*/
public class SomeDistributedServer {
private ZooKeeper zk;
public SomeDistributedServer() throws IOException {
//连接zk创建znode
zk = new ZooKeeper("172.16.88.137:2181", 2000, null);
}
//注册服务
public void registerServer(String serverName, String port) throws IOException, KeeperException,
InterruptedException {
//如果父节点不存在,则创建
if (zk.exists("/servers", false) == null) {
zk.create("/servers", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
//注册服务节点
zk.create("/servers/", (serverName + ":" + port).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println("server:" + serverName + " port:" + port + " is online!");
}
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
SomeDistributedServer server = new SomeDistributedServer();
//启动的时候注册服务 服务名和服务端口
server.registerServer(args[0], args[1]);
//处理业务
System.out.println("server:" + args[0] + " start...");
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package dev.televex.fhgcore.listeners;
import dev.televex.fhgcore.core;
import dev.televex.fhgcore.tags;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
/**
* All code Copyright (c) 2015 by Eric_1299. All Rights Reserved.
*/
public class backListener implements Listener {
@EventHandler
public void onTeleport(PlayerTeleportEvent event) {
if (event.getCause() == PlayerTeleportEvent.TeleportCause.COMMAND || event.getCause() == PlayerTeleportEvent.TeleportCause.PLUGIN) {
core.backdata.put(event.getPlayer(), event.getFrom());
}
}
@EventHandler
public void onDie(PlayerDeathEvent event) {
core.backdata.put(event.getEntity(), event.getEntity().getLocation());
event.getEntity().sendMessage(tags.ytag + "Use /back to return to your dead body.");
}
}
|
package stubs;
import java.util.Arrays;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mrunit.mapreduce.MapDriver;
import org.apache.hadoop.mrunit.mapreduce.MapReduceDriver;
import org.apache.hadoop.mrunit.mapreduce.ReduceDriver;
//import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
public class TestAvgWordLength {
/*
* Declare harnesses that let you test a mapper, a reducer, and
* a mapper and a reducer working together.
*/
MapDriver<LongWritable, Text, Text, IntWritable> mapDriver;
ReduceDriver<Text, IntWritable, Text, DoubleWritable> reduceDriver;
MapReduceDriver<LongWritable, Text, Text, IntWritable, Text, DoubleWritable> mapReduceDriver;
/*
* Set up the test. This method will be called before every test.
*/
@Before
public void setUp() {
/*
* Set up the mapper test harness.
*/
LetterMapper mapper = new LetterMapper();
mapDriver = new MapDriver<LongWritable, Text, Text, IntWritable>();
mapDriver.setMapper(mapper);
/*
* Set up the reducer test harness.
*/
AverageReducer reducer = new AverageReducer();
reduceDriver = new ReduceDriver<Text, IntWritable, Text, DoubleWritable>();
reduceDriver.setReducer(reducer);
/*
* Set up the mapper/reducer test harness.
*/
mapReduceDriver = new MapReduceDriver<LongWritable, Text, Text, IntWritable, Text, DoubleWritable>();
mapReduceDriver.setMapper(mapper);
mapReduceDriver.setReducer(reducer);
}
// No now is definitely not the best time
/*
* Test the mapper.
*/
@Test
public void testMapper() {
mapDriver
.withInput(new LongWritable(1), new Text("No now is definitely not the best time"))
.withOutput(new Text("N"), new IntWritable(2))
.withOutput(new Text("n"), new IntWritable(3))
.withOutput(new Text("i"), new IntWritable(2))
.withOutput(new Text("d"), new IntWritable(10))
.withOutput(new Text("n"), new IntWritable(3))
.withOutput(new Text("t"), new IntWritable(3))
.withOutput(new Text("b"), new IntWritable(4))
.withOutput(new Text("t"), new IntWritable(4))
.runTest();
System.out.println("Mapper passed test");
}
/*
* Test the reducer.
*/
@Test
public void testReducer() {
reduceDriver
.withInput(new Text("t"),
Arrays.asList(new IntWritable(2), new IntWritable(2), new IntWritable(3), new IntWritable(2)))
.withOutput(new Text("t"), new DoubleWritable(2.25))
.runTest();
System.out.println("Reducer passed test");
}
/*
* Test the mapper and reducer working together.
*/
@Test
public void testMapReduce() {
mapReduceDriver
.withInput(new LongWritable(1), new Text("No now is definitely not the best time"))
.withOutput(new Text("N"), new DoubleWritable(2))
.withOutput(new Text("b"), new DoubleWritable(4))
.withOutput(new Text("d"), new DoubleWritable(10))
.withOutput(new Text("i"), new DoubleWritable(2))
.withOutput(new Text("n"), new DoubleWritable(3))
.withOutput(new Text("t"), new DoubleWritable(3.5))
.runTest();
System.out.println("MapReduce passed test");
}
}
|
package com.tencent.tencentmap.mapsdk.map;
import com.tencent.mapsdk.raster.model.Marker;
public interface TencentMap$OnMarkerDraggedListener {
void onMarkerDrag(Marker marker);
void onMarkerDragEnd(Marker marker);
void onMarkerDragStart(Marker marker);
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
import java.util.Date;
/**
* PDataDetail generated by hbm2java
*/
public class PDataDetail implements java.io.Serializable {
private PDataDetailId id;
private PDataHeader PDataHeader;
private String partNumber;
private Integer requireNum;
private Integer dataNum;
private String relationOrder;
private String itemDataState;
private String isFinishData;
private Date finalTime;
private Date nextTime;
private Date startTime;
private Date endTime;
private String uniqueid;
private BigDecimal lastDataNum;
private String warehouseid;
public PDataDetail() {
}
public PDataDetail(PDataDetailId id, PDataHeader PDataHeader) {
this.id = id;
this.PDataHeader = PDataHeader;
}
public PDataDetail(PDataDetailId id, PDataHeader PDataHeader, String partNumber, Integer requireNum,
Integer dataNum, String relationOrder, String itemDataState, String isFinishData, Date finalTime,
Date nextTime, Date startTime, Date endTime, String uniqueid, BigDecimal lastDataNum, String warehouseid) {
this.id = id;
this.PDataHeader = PDataHeader;
this.partNumber = partNumber;
this.requireNum = requireNum;
this.dataNum = dataNum;
this.relationOrder = relationOrder;
this.itemDataState = itemDataState;
this.isFinishData = isFinishData;
this.finalTime = finalTime;
this.nextTime = nextTime;
this.startTime = startTime;
this.endTime = endTime;
this.uniqueid = uniqueid;
this.lastDataNum = lastDataNum;
this.warehouseid = warehouseid;
}
public PDataDetailId getId() {
return this.id;
}
public void setId(PDataDetailId id) {
this.id = id;
}
public PDataHeader getPDataHeader() {
return this.PDataHeader;
}
public void setPDataHeader(PDataHeader PDataHeader) {
this.PDataHeader = PDataHeader;
}
public String getPartNumber() {
return this.partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public Integer getRequireNum() {
return this.requireNum;
}
public void setRequireNum(Integer requireNum) {
this.requireNum = requireNum;
}
public Integer getDataNum() {
return this.dataNum;
}
public void setDataNum(Integer dataNum) {
this.dataNum = dataNum;
}
public String getRelationOrder() {
return this.relationOrder;
}
public void setRelationOrder(String relationOrder) {
this.relationOrder = relationOrder;
}
public String getItemDataState() {
return this.itemDataState;
}
public void setItemDataState(String itemDataState) {
this.itemDataState = itemDataState;
}
public String getIsFinishData() {
return this.isFinishData;
}
public void setIsFinishData(String isFinishData) {
this.isFinishData = isFinishData;
}
public Date getFinalTime() {
return this.finalTime;
}
public void setFinalTime(Date finalTime) {
this.finalTime = finalTime;
}
public Date getNextTime() {
return this.nextTime;
}
public void setNextTime(Date nextTime) {
this.nextTime = nextTime;
}
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 getUniqueid() {
return this.uniqueid;
}
public void setUniqueid(String uniqueid) {
this.uniqueid = uniqueid;
}
public BigDecimal getLastDataNum() {
return this.lastDataNum;
}
public void setLastDataNum(BigDecimal lastDataNum) {
this.lastDataNum = lastDataNum;
}
public String getWarehouseid() {
return this.warehouseid;
}
public void setWarehouseid(String warehouseid) {
this.warehouseid = warehouseid;
}
}
|
package edu.wayne.cs.severe.redress2.entity.refactoring.json;
import java.util.List;
public class JSONRefactoring {
private String type;
private List<JSONRefParam> params;
private List<JSONRefactoring> subRefs;
public String getType() {
return type;
}
public List<JSONRefParam> getParams() {
return params;
}
/**
* @return the subRefs
*/
public List<JSONRefactoring> getSubRefs() {
return subRefs;
}
@Override
public String toString() {
return "JSONRefactoring [type=" + type + ", params=" + params
+ ", subRefs=" + subRefs + "]";
}
}
|
package com.timgroup.ahcleak;
import java.net.URI;
public interface Config {
public static final URI SERVER_URI = URI.create("http://localhost:8888/hello");
}
|
package java.String;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FindAndReplacePattern890 {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> result = new ArrayList<>();
for (String word : words) {
if (match(word, pattern)) {
result.add(word);
}
}
return result;
}
private boolean match(String word, String pattern) {
Map<Character, Character> map = new HashMap<>();
Map<Character, Character> map1 = new HashMap<>();
if (word.length() != pattern.length()) {
return false;
}
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
char c1 = pattern.charAt(i);
if (!map.containsKey(c) ) {
map.put(c, c1);
}
if (!map1.containsKey(c1)) {
map1.put(c1, c );
}
if (map.get(c) !=c1 || map1.get(c1) != c){
return false;
}
}
return true;
}
}
|
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import game.arendelle.Chalet;
import game.arendelle.Kingdom;
import game.arendelle.Reachable;
import game.arendelle.SnowPalace;
import game.arendelle.SnowStorm;
import game.arendelle.TrollCave;
import game.items.Gem;
import game.players.Anna;
import game.players.Player;
import game.players.Troll;
import game.utils.Colour;
import game.utils.Position;
public class Test{
private static int scores = 0;
private static Gem diamond, carbon;
private static Gem sapphire, lapisLazuli;
private static Gem ruby, rubyPink;
private static Gem emerald;
private static Gem amethyst;
private static Position p1, p2, p3, p4, p5;
private static AdventureGame aG = new AdventureGame();
public static void main(String[] args) {
testColour();
testGem();
testPosition();
testArendelle();
testPlayer();
testAnna();
testTroll();
testAdventureGame();
testInappropriateBoardSizeException();
System.out.println(scores);
}
private static void testColour() {
assertTrue("The colours are not in the right order.", Colour.COLOURLESS.ordinal() == 0
&& Colour.YELLOW.ordinal() == 1 && Colour.BROWN.ordinal() == 2 && Colour.GREY.ordinal() == 3 && Colour.BLUE.ordinal() == 4 && Colour.RED.ordinal() == 5 && Colour.PINK.ordinal() == 6 && Colour.GREEN.ordinal() == 7 && Colour.PURPLE.ordinal() == 8);
scores += 1;
testColourToString();
}
private static void testColourToString(){
assertEquals(".toString() for colourless is not ok", "colourless", Colour.COLOURLESS.toString());
assertEquals(".toString() for yellow is not ok", "yellow", Colour.YELLOW.toString());
assertEquals(".toString() for brown is not ok", "brown", Colour.BROWN.toString());assertEquals(".toString() for grey is ok", "grey", Colour.GREY.toString());assertEquals(".toString() for blue is not ok", "blue", Colour.BLUE.toString());
assertEquals(".toString() for red is not ok", "red", Colour.RED.toString());
assertEquals(".toString() for pink is not ok", "pink", Colour.PINK.toString());
assertEquals(".toString() for green is ok", "green", Colour.GREEN.toString());
assertEquals(".toString() for purple is not ok", "purple", Colour.PURPLE.toString());
scores += 1;
}
private static void testGem() {
diamond = new Gem("diamond", Colour.COLOURLESS, 50);
carbon = new Gem("diamond", Colour.COLOURLESS, 50);
sapphire = new Gem("sapphire", Colour.BLUE, 20);
lapisLazuli = new Gem("sapphire", Colour.BLUE, 15);
ruby = new Gem("ruby", Colour.RED, 10);
rubyPink = new Gem("ruby", Colour.PINK, 20);
emerald = new Gem("emerald", Colour.GREEN, 40);
amethyst = new Gem("amethyst", Colour.PURPLE, 30);
assertTrue("Parameters for diamond are not valid", diamond != null);
assertTrue("Parameters for carbon are not valid", carbon != null);
assertTrue("Parameters for sapphire are not valid", sapphire != null);
assertTrue("Parameters for lapisLazuli are not valid", lapisLazuli != null);
assertTrue("Parameters for ruby are not valid", ruby != null);
assertTrue("Parameters for rubyPink are not valid", rubyPink != null);
assertTrue("Parameters for emerald are not valid", emerald != null);
assertTrue("Parameters for amethyst are not valid", amethyst != null);
testGemGetName();
testGemGetColour();
testGemGetValue();
testGemToString();
testGemHashCode();
testGemEquals();
testGemComparable();
}
private static void testGemGetName(){
assertEquals("getName() is not ok", "diamond", diamond.getName());
assertEquals("getName() is not ok", "diamond", carbon.getName());
assertEquals("getName() is not ok", "sapphire", sapphire.getName());
assertEquals("getName() is not ok", "sapphire", lapisLazuli.getName());
assertEquals("getName() is not ok", "ruby", ruby.getName());
assertEquals("getName() is not ok", "ruby", rubyPink.getName());
assertEquals("getName() is not ok", "emerald", emerald.getName());
assertEquals("getName() is not ok", "amethyst", amethyst.getName());
}
private static void testGemGetColour(){
assertEquals("getColour() is not ok", Colour.COLOURLESS, diamond.getColour());
assertEquals("getColour() is not ok", Colour.COLOURLESS, carbon.getColour());
assertEquals("getColour() is not ok", Colour.BLUE, sapphire.getColour());
assertEquals("getColour() is not ok", Colour.BLUE, lapisLazuli.getColour());
assertEquals("getColour() is not ok", Colour.RED, ruby.getColour());
assertEquals("getColour() is not ok", Colour.PINK, rubyPink.getColour());
assertEquals("getColour() is not ok", Colour.GREEN, emerald.getColour());
assertEquals("getColour() is not ok", Colour.PURPLE, amethyst.getColour());
}
private static void testGemGetValue(){
assertTrue("getValue() is not ok", diamond.getValue()==50);
assertTrue("getValue() is not ok", carbon.getValue()==50);
assertTrue("getValue() is not ok", sapphire.getValue()==20);
assertTrue("getValue() is not ok", lapisLazuli.getValue()==15);
assertTrue("getValue() is not ok", ruby.getValue()==10);
assertTrue("getValue() is not ok", emerald.getValue()==40);
assertTrue("getValue() is not ok", amethyst.getValue()==30);
}
private static void testGemToString(){
assertEquals(".toString() for diamond is not ok", "The colourless diamond is worth 50 ducats.", diamond.toString());
assertEquals(".toString() for carbon is not ok", "The colourless diamond is worth 50 ducats.", carbon.toString());
assertEquals(".toString() for sapphire is not ok", "The blue sapphire is worth 20 ducats.", sapphire.toString());
assertEquals(".toString() for lapisLazuli is not ok", "The blue sapphire is worth 15 ducats.", lapisLazuli.toString());
assertEquals(".toString() for ruby is not ok", "The red ruby is worth 10 ducats.", ruby.toString());
assertEquals(".toString() for rubyPink is not ok", "The pink ruby is worth 20 ducats.", rubyPink.toString());
assertEquals(".toString() for emerald is not ok", "The green emerald is worth 40 ducats.", emerald.toString());
assertEquals(".toString() for amethyst is not ok", "The purple amethyst is worth 30 ducats.", amethyst.toString());
scores += 1;
}
private static void testGemEquals(){
assertTrue(".equals() for diamond is not ok", diamond.equals(carbon));
assertTrue(".equals() for carbon is not ok", carbon.equals(diamond));
assertTrue(".equals() for sapphire is not ok", !sapphire.equals(lapisLazuli));
assertTrue(".equals() for lapisLazuli is not ok", !lapisLazuli.equals(sapphire));
assertTrue(".equals() for ruby is not ok", !ruby.equals(rubyPink));
assertTrue(".equals() for rubyPink is not ok", !rubyPink.equals(ruby));
assertTrue(".equals() for emerald is not ok", !emerald.equals(amethyst));
assertTrue(".equals() for amethyst is not ok", !amethyst.equals(emerald));
scores += 2;
}
private static void testGemHashCode(){
boolean b = (diamond.hashCode() == carbon.hashCode());
assertTrue(".hashCode() for diamond is not ok", b);
scores += 2;
}
private static void testGemComparable(){
assertTrue("class Gem does not implement interface Comparable<Gem>",
diamond instanceof Comparable<?>);
assertTrue(".compareTo() is not ok", diamond.compareTo(carbon) == 0);
assertTrue(".compareTo() is not ok", sapphire.compareTo(ruby) > 0);
assertTrue(".compareTo() is not ok", amethyst.compareTo(emerald) < 0);
assertTrue(".compareTo() is not ok", sapphire.compareTo(lapisLazuli) > 0);
assertTrue(".compareTo() is not ok", ruby.compareTo(rubyPink) < 0);
scores += 2;
}
private static void testPosition() {
p1 = new Position(1, 1);
p2 = new Position(1, 2);
p3 = new Position(2, 1);
p4 = new Position(2, 2);
p5 = new Position(3, 3);
testPositionConstants();
testPositionGetters();
testPositionSetters();
testPositionIsInside();
testPositionNeighbours();
testPositionToString();
testPositionEquals();
testPositionHashCode();
testPositionComparable();
}
private static void testPositionConstants() {
assertTrue("MIN_X != 1", Position.MIN_X == 1);
assertTrue("MIN_Y != 1", Position.MIN_Y == 1);
assertTrue("MAX_X != 8", Position.MAX_X == 8);
assertTrue("MAX_Y != 8", Position.MAX_Y == 8);
assertTrue("INITIAL_POSITION != (1, 1)", Position.INITIAL_POSITION.equals(new Position(1, 1)));
Position p = Position.WINNING_POSITION;
boolean b = ((!(p.getX()==1 && p.getY()==1)) && (1 <= p.getX()) && (p.getX() <=8) && (1 <= p.getY()) && (p.getY() <=8));
assertTrue("WINNING_POSITION is not ok", b);
scores += 1;
}
private static void testPositionGetters(){
testGetX();
testGetY();
}
private static void testGetX() {
assertTrue(".getX() for p5 is not ok", p5.getX()==3);
}
private static void testGetY() {
assertTrue(".getY() for p5 is not ok", p5.getY()==3);
}
private static void testPositionSetters(){
testSetX();
testSetY();
}
private static void testSetX() {
p5.setX(7);
assertTrue(".setX() for p5 is not ok", p5.getX()==7);
}
private static void testSetY() {
p5.setY(6);
assertTrue(".setY() for p5 is not ok", p5.getY()==6);
}
private static void testPositionIsInside() {
assertTrue(".isInside() is not ok", p4.isInside());
assertTrue(".isInside() is not ok", !new Position(9,9).isInside());
scores += 1;
}
private static void testPositionNeighbours() {
assertTrue("The neighbours of position (2,2) are: (1,2), (2,1), (2,3) and (3,2)",
p4.neighbours().containsAll(Arrays.asList(new Position(1,2),new Position(2,1),new Position(2,3),new Position(3,2))));
assertTrue("The neighbours of position (1,1) are: (1,2) and (2,1)", Position.INITIAL_POSITION.neighbours().containsAll(Arrays.asList(new Position(1,2),new Position(2,1))));
assertTrue("The neighbours of position (2,1) are: (1,1), (2,2) and (3,1)",new Position(2,1).neighbours().containsAll(Arrays.asList(new Position(1,1),new Position(2,2),new Position(3,1))));
assertTrue("Positions (1,2) and (3,2) are not neighbours of position (2,1)", !new Position(2,1).neighbours().removeAll(Arrays.asList(new Position(1,2), new Position(3,2))));
scores += 2;
}
private static void testPositionToString() {
assertEquals(".toString() for INITIAL_POSITION is not ok", "(1,1)", Position.INITIAL_POSITION.toString());
assertEquals(".toString() for position (1,2) is not ok", "(1,2)", p2.toString());
scores += 1;
}
private static void testPositionEquals(){
assertTrue(".equals() for INITIAL_POSITION is not ok", Position.INITIAL_POSITION.equals(p1));
assertTrue(".equals() for p1 is not ok", p1.equals(Position.INITIAL_POSITION));
assertTrue(".equals() for p2 is not ok", !p2.equals(p3));
assertTrue(".equals() for p3 is not ok", !p3.equals(p2));
scores += 1;
}
private static void testPositionHashCode() {
boolean b = (Position.INITIAL_POSITION.hashCode()== p1.hashCode());
assertTrue(".hashCode() for INITIAL_POSITION is not ok", b);
scores += 1;
}
private static void testPositionComparable(){
assertTrue("class Position does not implement interface Comparable<Position>",
p1 instanceof Comparable<?>);
assertTrue(".compareTo() is not ok for (1,1) == (1,1)", p1.compareTo(p1) == 0);
assertTrue(".compareTo() is not ok for (1,1) < (1,2)", p1.compareTo(p2) < 0);
assertTrue(".compareTo() is not ok for (2,1) < (2,2)", p3.compareTo(p4) < 0);
assertTrue(".compareTo() is not ok for (1,2) > (1,1)", p2.compareTo(p1) > 0);
assertTrue(".compareTo() is not ok for (2,2) > (2,1)", p4.compareTo(p3) > 0);
scores += 1;
}
private static void testArendelle() {
testKingdom();
testSnowStorm();
testChalet();
testSnowPalace();
testTrollCave();
}
private static void testKingdom() {
DummyKingdom kd = new DummyKingdom();
assertTrue("Class Kingdom does not implement Reachable.", Reachable.class.isAssignableFrom(Kingdom.class));
scores += 1;
assertTrue("The class is not abstract.", Modifier.isAbstract(Kingdom.class.getModifiers()));
assertEquals(".toString() for Kingdom is not ok", "Welcome...", kd.toString());
scores += 1;
assertEquals(".isReachable() for Kingdom is not ok", false, kd.isReachable());
}
private static void testSnowStorm() {
SnowStorm ss = new SnowStorm();
assertTrue("Class Kingdom is not a superclass of SnowStorm.", SnowStorm.class.getSuperclass().equals(Kingdom.class));
boolean b = ss.isReachable();
if (b){
assertEquals(".isReachable() for SnowStorm is not ok", true, b);
} else {
assertEquals(".isReachable() for SnowStorm is not ok", false, b);
}
scores += 1;
assertEquals(".toString() for SnowStorm is not ok", "A winter storm will move across the region. You had better avoid it.", ss.toString());
scores += 1;
}
private static void testTrollCave() {
TrollCave tc = new TrollCave();
assertTrue("Class Kingdom is not a superclass of TrollCave.", TrollCave.class.getSuperclass().equals(Kingdom.class));
assertEquals(".isReachable() for TrollCave is not ok", true, tc.isReachable());
assertEquals(".toString() for TrollCave is not ok", "Trolls are giant wealth suckers. Steer clear of them.", tc.toString());
scores += 1;
}
private static void testChalet() {
Chalet ch = new Chalet(new ArrayList<Gem>(Arrays.asList(diamond,sapphire,ruby)));
assertTrue("Class Kingdom is not a superclass of Chalet.", Chalet.class.getSuperclass().equals(Kingdom.class));
assertEquals(".isReachable() for Chalet is not ok", true, ch.isReachable());
assertEquals(".getGemList() for Chalet is not ok", new ArrayList<Gem>(Arrays.asList(diamond,sapphire,ruby)), ch.getGemList());
ch.setGemList(new ArrayList<Gem>(Arrays.asList(diamond,carbon,sapphire,ruby,amethyst)));
assertEquals(".setGemList() for Chalet is not ok", new ArrayList<Gem>(Arrays.asList(diamond,carbon,sapphire,ruby,amethyst)), ch.getGemList());
ch.collectItems(2);
assertEquals(".collectItems() for Chalet is not ok", new ArrayList<Gem>(Arrays.asList(sapphire,ruby,amethyst)), ch.getGemList());
ch.collectItems(4);
assertEquals(".collectItems() for Chalet is not ok", new ArrayList<Gem>(Arrays.asList(sapphire,ruby,amethyst)), ch.getGemList());
scores += 1;
assertEquals(".toString() for Chalet is not ok", "Welcome...If you are lucky, you will come across some gems here for Elsa.", ch.toString());
scores += 1;
}
private static void testSnowPalace() {
SnowPalace sp = new SnowPalace();
assertTrue("Class Kingdom is not a superclass of SnowPalace.", SnowPalace.class.getSuperclass().equals(Kingdom.class));
assertEquals(".isReachable() for SnowPalace is not ok", true, sp.isReachable());
assertEquals(".toString() for SnowPalace is not ok", "Welcome...to the Palace. Elsa is waiting for you. You have won the game.", sp.toString());
scores += 1;
}
private static void testPlayer() {
DummyPlayer dPlayer= new DummyPlayer();
assertTrue("The class is not abstract.", Modifier.isAbstract(Player.class.getModifiers()));
assertEquals(".getGemList() for Player is not ok", new ArrayList<Gem>(), dPlayer.getGemList());
assertEquals(".getPosition() for Player is not ok", new Position(1,1), dPlayer.getPosition());
ArrayList<Gem> dPlayerGemList = new ArrayList<Gem>();
dPlayerGemList.add(diamond);
dPlayer.setGemList(dPlayerGemList);
assertEquals(".setGemList() for Player is not ok", new ArrayList<Gem>(Arrays.asList(diamond)), dPlayer.getGemList());
dPlayer.setPosition(new Position(1,2));
assertEquals(".setPosition() for Player is not ok", new Position(1,2), dPlayer.getPosition());
assertEquals(".display() for Player is not ok", "My achievements...", dPlayer.display());
scores += 2;
}
private static void testTroll(){
Troll tr = new Troll(new ArrayList<Gem>(Arrays.asList(diamond,sapphire,carbon,lapisLazuli,ruby,rubyPink, amethyst)), new Position(2,2),3);
assertTrue("Parameters for Troll are not valid", tr != null);
assertTrue("Class Player is not a superclass of Troll.", Troll.class.getSuperclass().equals(Player.class));
assertEquals(".getName() for Troll is not ok", "Troll 3", tr.getName());
scores += 1;
assertEquals(".display() for Troll is not ok", "Hi. My name is " + tr.getName() + ". Nice to meet you, Anna.", tr.display());
scores += 1;
}
private static void testAnna(){
Anna princess = new Anna(new ArrayList<Gem>(Arrays.asList(diamond,sapphire,carbon,lapisLazuli,ruby,rubyPink, amethyst)), new Position(2,2));
assertTrue("Parameters for Anna are not valid", princess != null);
assertTrue("Class Player is not a superclass of Anna.", Anna.class.getSuperclass().equals(Player.class));
assertEquals(".getName() for Anna is not ok", "Princess Anna", princess.getName());
Position pos = princess.getPosition();
princess.move();
Position newPos = princess.getPosition();
assertTrue(".move() for Anna is not ok", pos.neighbours().contains(newPos));
scores += 2;
Troll tr = new Troll(new ArrayList<Gem>(Arrays.asList(diamond,sapphire,carbon,lapisLazuli,ruby,rubyPink, amethyst)), princess.getPosition(),3);
ArrayList<Gem> diff = new ArrayList<Gem>();
diff = princess.getGemList();
princess.fight(tr);
ArrayList<Gem> tmp = new ArrayList<Gem>();
tmp = princess.getGemList();
diff.removeAll(tmp);
assertTrue(".fight() for Anna is not ok", tr.getGemList().containsAll(diff));
scores += 2;
princess.setGemList((new ArrayList<Gem>(Arrays.asList(diamond,sapphire,carbon,lapisLazuli,ruby,rubyPink, amethyst))));
princess.fight();
assertTrue(".fight() for Anna is not ok", princess.getGemList().containsAll(Arrays.asList(diamond,sapphire,carbon,lapisLazuli,ruby,rubyPink)));
princess.setGemList((new ArrayList<Gem>(Arrays.asList(diamond))));
princess.fight();
assertEquals(".fight() for Anna is not ok", new ArrayList<Gem>(), princess.getGemList());
scores += 2;
if (princess.getPosition().equals(Position.WINNING_POSITION)){
assertEquals(".display() for Princess Anna is not ok", "I have won the game.", princess.display());
} else {
assertEquals(".display() for Princess Anna is not ok", "I have lost the game.", princess.display());
}
scores += 1;
}
private static void testAdventureGame(){
testAdventureGameConstants();
assertTrue("Parameters for AdventureGame are valid", aG != null);
scores += 2;
testBuildKingdom();
testInitTrolls();
aG.simulation();
testSimulation();
}
private static void testAdventureGameConstants() {
assertTrue("NUM_OF_TROLL_CAVES is not ok", (AdventureGame.NUM_OF_TROLL_CAVES>=15 && AdventureGame.NUM_OF_TROLL_CAVES<=20));
assertTrue("NUM_OF_SNOW_STORMS is not ok", (AdventureGame.NUM_OF_SNOW_STORMS>=15 && AdventureGame.NUM_OF_SNOW_STORMS<=20));
assertTrue("NUM_OF_CHALETS is not ok", (AdventureGame.NUM_OF_CHALETS>=23 && AdventureGame.NUM_OF_CHALETS<=33));
assertTrue("MAX_NUM_OF_STEPS != 50", AdventureGame.MAX_NUM_OF_STEPS == 50);
}
private static void testBuildKingdom(){
testInitGemPool();
testInitChalets();
int numOfCaves = 0;
int numOfStorms = 0;
int numOfChalets = 0;
int numOfPalace = 0;
for(Map.Entry<Position, Kingdom> boardEntry : aG.getKingdom().entrySet()){
if (boardEntry.getValue().getClass().equals(Chalet.class)) {
numOfChalets++;
}
else if (boardEntry.getValue().getClass().equals(SnowStorm.class)) {
numOfStorms++;
}
else if (boardEntry.getValue().getClass().equals(TrollCave.class)) {
numOfCaves++;
}
else if (boardEntry.getValue().getClass().equals(SnowPalace.class)) {
numOfPalace++;
}
}
assertEquals(".buildPlaces() for AdventureGame is not ok", AdventureGame.NUM_OF_TROLL_CAVES, numOfCaves);
assertEquals(".buildPlaces() for AdventureGame is not ok", AdventureGame.NUM_OF_SNOW_STORMS, numOfStorms);
assertEquals(".buildPlaces() for AdventureGame is not ok", AdventureGame.NUM_OF_CHALETS, numOfChalets);
assertEquals(".buildPlaces() for AdventureGame is not ok", 1, numOfPalace);
scores += 3;
}
private static void testInitGemPool(){
ArrayList<Gem> expected = new ArrayList<Gem>((Arrays.asList(new Gem("diamond", Colour.COLOURLESS, 50),
new Gem("diamond", Colour.YELLOW, 45), new Gem("diamond", Colour.BROWN, 40), new Gem("diamond", Colour.GREY, 35),
new Gem("sapphire", Colour.BLUE, 30), new Gem("ruby", Colour.RED, 10), new Gem("ruby", Colour.PINK, 20),
new Gem("emerald", Colour.GREEN, 40), new Gem("amethyst", Colour.PURPLE, 30))));
assertTrue(".testInitGemPool() for AdventureGame is not ok", aG.getPool().containsAll(expected));
}
private static void testInitChalets(){
assertTrue("Number of chalets is not ok", aG.getChalets().size() == AdventureGame.NUM_OF_CHALETS);
ArrayList<Gem> pool = new ArrayList<Gem>((Arrays.asList(new Gem("diamond", Colour.COLOURLESS, 50),
new Gem("diamond", Colour.YELLOW, 45), new Gem("diamond", Colour.BROWN, 40), new Gem("diamond", Colour.GREY, 35),
new Gem("sapphire", Colour.BLUE, 30), new Gem("ruby", Colour.RED, 10), new Gem("ruby", Colour.PINK, 20),
new Gem("emerald", Colour.GREEN, 40), new Gem("amethyst", Colour.PURPLE, 30))));
for (int k=0; k < aG.getChalets().size(); k++){
assertTrue(".initChalets() for AdventureGame is not ok",pool.containsAll(aG.getChalets().get(k).getGemList()));
}
}
private static void testInitTrolls() {
assertTrue("Number of trolls is not ok", aG.getTrolls().size() == AdventureGame.NUM_OF_TROLL_CAVES);
ArrayList<Position> trMap = new ArrayList<Position>();
ArrayList<Position> trPos = new ArrayList<Position>();
for(Map.Entry<Position, Kingdom> boardEntry : aG.getKingdom().entrySet()){
if (boardEntry.getValue().getClass().equals(TrollCave.class)) {
trMap.add(boardEntry.getKey());
}
}
for (int k=0; k < aG.getTrolls().size(); k++){
trPos.add(aG.getTrolls().get(k).getPosition());
aG.getTrolls().get(k).getName().equals("Troll "+k+1);
}
assertTrue(".initTrolls() for AdventureGame is not ok", trPos.containsAll(trMap));
}
private static void testSimulation(){
boolean b = (AdventureGame.princess.getPosition().equals(Position.WINNING_POSITION) || AdventureGame.numOfSteps >= AdventureGame.MAX_NUM_OF_STEPS);
assertTrue(".simulation() for AdventureGame is ok", b);
scores += 3;
}
private static void testInappropriateBoardSizeException() {
assertEquals("Text for NegativeBoardSizeException is not ok",
"Inappropriate board size dimensions.",
new InappropriateBoardSizeException().getMessage());
scores += 1;
}
/*
* Ezek a segedfuggvenyek a teszteléshez hasznalatosak. Ezeket nem szabad
* kikommentezni. Mindegyik valamilyen tulajdonságot ellenoriz es kivételt valt ki, ha
* nem teljesul az adott tulajdonsag.
*/
private static void assertTrue(String msg, boolean p) {
if (!p) {
throw new RuntimeException(msg);
}
}
private static void assertEquals(String msg, Object expected, Object actual) {
if (expected == null && actual == null) {
return;
}
if (expected == null || !expected.equals(actual)) {
throw new RuntimeException(msg + ", expected: " + expected
+ ", actual: " + actual);
}
}
}
|
package LinkedList;
public class Practice5 {
}
|
package sensorySystem;
import java.awt.Color;
import environment.Environment;
import environment.Robot;
/**
* sensory system that collect environment information
* @author simon
*
*/
public class Probe {
private Environment m_env;
private Robot robot;
public double[] distRetina;
public Color[] colRetina;
public int[] tMap;
public int[] corner;
private float offsetX=0;
private float offsetY=0;
public Probe(Robot r, float posX, float posY){
robot=r;
offsetX=posX;
offsetY=posY;
distRetina=new double[360];
colRetina=new Color[360];
tMap=new int[360];
corner=new int[360];
}
public void setEnvironment(Environment e){
m_env=e;
}
/**
* rendu function, draw the visual and tactile retina
* @return
*/
public void rendu(){
double[] rv = new double[360]; // visual distance vector (absolute orientation)
double[] rv2 = new double[360]; // visual distance vector (agent orientation)
double[] rt = new double[360]; // tactile distance vector (absolute orientation)
double[] rt2 = new double[360]; // tactile distance vector (agent orientation)
double[] zVMap = new double[360]; // visual Z-Map
double[] zTMap = new double[360]; // tactile Z-Map
Color[] colorMap =new Color[360]; // color vector (absolute orientation)
int[] tactileMap =new int[360]; // tactile property vector (absolute orientation)
int[] cornerV = new int[360]; // allocentric visual corner vector
int[] cornerT = new int[360]; // allocentric tactile corner vector
double d=0;
double d1,d2,d3; // distance of corners of a square
double a1, a2, a3; // angles of corners of a square (in degree)
int ai1,ai2,ai3;
double imin,iplus,jmin,jplus;
double imin2,jmin2;
float m_w=m_env.getWidth();
float m_h=m_env.getHeight();
float ax=robot.position[0];
float ay=robot.position[1];
double theta=robot.position[2];
float offX = (float)(offsetX * Math.cos(theta-Math.PI/2) - offsetY * Math.sin(theta-Math.PI/2));
float offY =-(float)(offsetX * Math.sin(theta-Math.PI/2) - offsetY * Math.cos(theta-Math.PI/2));
int Im_x=Math.round(robot.position[0]+offX);
int Im_y=Math.round(robot.position[1]+offY);
ax+=offX;
ay+=offY;
// reset vectors
for (int i=0;i<360;i++){
zVMap[i]=1000;
zTMap[i]=1000;
rv[i]=200;
rt[i]=200;
colorMap[i]=new Color(0,0,0);
tactileMap[i]=0;
}
int sight=20; // maximum distance
// the area around the agent is divided into five parts
// 4 4 4 4 5 1 1 1 1 block corner number :
// 4 4 4 4 5 1 1 1 1 area 1 : area 2 : area 3 : area 4 : area 5 :
// 4 4 4 4 5 1 1 1 1 2----- 1----3 3----1 -----3 ------
// 3 3 3 3 A 1 1 1 1 | | | | | | | | | |
// 3 3 3 3 2 2 2 2 2 1----3 2----- -----2 2----1 2----1
// 3 3 3 3 2 2 2 2 2
// 3 3 3 3 2 2 2 2 2
// the five parts are computed in parallel. Only area 1 is commented, other areas are computed in the same way
for (int i=0;i<sight;i++){
for (int j=0;j<sight;j++){
float Im_xpi=Im_x+i;
float Im_ypj=Im_y+j;
float Im_xmi=Im_x-i;
float Im_ymj=Im_y-j;
// (1) cells on the top right side
if ( (i>0)&& (Im_xpi>=0) && (Im_xpi<m_w) && (Im_ypj>=0) && (Im_ypj<m_h) ){
if (!m_env.isEmpty(Im_xpi,Im_ypj) ){
// determine color and tactile property of a block
Color bgc = m_env.seeBlock(Im_xpi,Im_ypj);
int tactile=m_env.touchBlock(Im_xpi,Im_ypj);
// determine the position of the three visible points of the block in polar reference
imin =(double)i-0.5 - (ax-Im_x);
imin2=imin*imin;
iplus=(double)i+0.5 - (ax-Im_x);
jmin =(double)j-0.5 - (ay-Im_y);
jmin2=jmin*jmin;
jplus=(double)j+0.5 - (ay-Im_y);
// determine distance of these points
d1= imin2 + jmin2;
d1=Math.sqrt(d1);
d2= imin2 + (jplus*jplus);
d2=Math.sqrt(d2);
d3= (iplus*iplus) + jmin2;
d3=Math.sqrt(d3);
// compute angles in degrees of these points
a1= Math.toDegrees( Math.acos( jmin/d1));
a2= Math.toDegrees( Math.acos( jplus/d2));
a3= Math.toDegrees( Math.acos( jmin/d3));
ai1=(int)a1;
ai2=(int)a2;
ai3=(int)a3;
// fill the output vectors with the first visible segment (1-2)
for (int k=ai2;k<=ai1;k++){
//d=10* imin/Math.cos((double)(90-k)*Math.PI/180);
d= d2*10 + (d1-d2)*10*(k-ai2)/(ai1-ai2);
// visual vector if the block is visible
if (m_env.isVisible(Im_xpi,Im_ypj)){
if (zVMap[k]>d){
rv[k]=d;
zVMap[k]= d; // fill Z-Map
colorMap[k]=bgc;
}
}
// tactile vector
if (zTMap[k]>d){
rt[k]=d;
zTMap[k]= d; // fill Z-Map
tactileMap[k]=tactile;
if (k==ai2) cornerT[k]=1;
else if (k==ai1) cornerT[k]=2;
else cornerT[k]=0;
}
}
// fill the output vectors with the second visible segment (1-3) (if visible)
if (imin>0){
for (int k=ai1;k<=ai3;k++){
//d=10* jmin/Math.cos((k)*Math.PI/180);
d= d1*10 + (d3-d1)*10*(k-ai1)/(ai3-ai1);
// visual vector if the block is visible
if (m_env.isVisible(Im_xpi,Im_ypj)){
if (zVMap[k]>d){
rv[k]=d;
zVMap[k]= d;
colorMap[k]=bgc;
}
}
// tactile vector
if (zTMap[k]>d){
rt[k]=d;
zTMap[k]= d;
tactileMap[k]=tactile;
if (k==ai1) cornerT[k]=1;
else if (k==ai3) cornerT[k]=2;
else cornerT[k]=0;
}
}
}
}
}
// (2) cells on the bottom right side
if ( (j>0) && (Im_xpi>=0) && (Im_xpi<m_w) && (Im_ymj>=0) && (Im_ymj<m_h)){
if (!m_env.isEmpty(Im_xpi,Im_ymj) ){
Color bgc = m_env.seeBlock(Im_xpi,Im_ymj);
int tactile=m_env.touchBlock(Im_xpi,Im_ymj);
imin =(double)i-0.5 - (ax-Im_x);
imin2=imin*imin;
iplus=(double)i+0.5 - (ax-Im_x);
jmin =(double)j-0.5 + (ay-Im_y);
jmin2=jmin*jmin;
jplus=(double)j+0.5 + (ay-Im_y);
d1= imin2 + jmin2;
d1=Math.sqrt(d1);
d2= (iplus*iplus) + jmin2;
d2=Math.sqrt(d2);
d3= imin2 + (jplus*jplus);
d3=Math.sqrt(d3);
a1= Math.toDegrees( Math.acos( jmin/d1));
a2= Math.toDegrees( Math.acos( jmin/d2));
a3= Math.toDegrees( Math.acos( jplus/d3));
if (i-0.5>=0){
ai1=180-(int)a1;
ai3=180-(int)a3;
}
else{
ai1=180+(int)a1;
ai3=180+(int)a3;
}
ai2=180-(int)a2;
for (int k=ai2;k<=ai1;k++){
d= ( d2*10 + (d1-d2)*10*(k-ai2)/(ai1-ai2));
if (m_env.isVisible(Im_xpi,Im_ymj)){
if (zVMap[k]>d){
rv[k]=d;
zVMap[k]= d;
colorMap[k]=bgc;
}
}
if (zTMap[k]>d){
rt[k]=d;
zTMap[k]= d;
tactileMap[k]=tactile;
if (k==ai1) cornerT[k]=1;
else if (k==ai2) cornerT[k]=2;
else cornerT[k]=0;
}
}
for (int k=ai1;k<=ai3;k++){
d= ( d1*10 + (d3-d1)*10*(k-ai1)/(ai3-ai1));
if (m_env.isVisible(Im_xpi,Im_ymj)){
if (zVMap[k]>d){
rv[k]=d;
zVMap[k]= d;
colorMap[k]=bgc;
}
}
if (zTMap[k]>d){
rt[k]=d;
zTMap[k]= d;
tactileMap[k]=tactile;
if (k==ai1) cornerT[k]=1;
else if (k==ai3) cornerT[k]=2;
else cornerT[k]=0;
}
}
}
}
// (3) cells on the bottom left side
if ( (i>0) && (Im_xmi>=0) && (Im_xmi<m_w) && (Im_ymj>=0) && (Im_ymj<m_h) ){
if (!m_env.isEmpty(Im_xmi,Im_ymj) ){
Color bgc = m_env.seeBlock(Im_xmi,Im_ymj);
int tactile=m_env.touchBlock(Im_xmi,Im_ymj);
imin =(double)i-0.5 + (ax-Im_x);
imin2=imin*imin;
iplus=(double)i+0.5 + (ax-Im_x);
jmin =(double)j-0.5 + (ay-Im_y);
jmin2=jmin*jmin;
jplus=(double)j+0.5 + (ay-Im_y);
d1= imin2 + jmin2;
d1=Math.sqrt(d1);
d2= imin2 + (jplus*jplus);
d2=Math.sqrt(d2);
d3= (iplus*iplus) + jmin2;
d3=Math.sqrt(d3);
a1= Math.toDegrees( Math.acos( jmin/d1));
a2= Math.toDegrees( Math.acos( jplus/d2));
a3= Math.toDegrees( Math.acos( jmin/d3));
ai1=180+(int)a1;
ai2=180+(int)a2;
ai3=180+(int)a3;
for (int k=ai2;k<=ai1;k++){
d= d2*10 + (d1-d2)*10*(k-ai2)/(ai1-ai2);
if (m_env.isVisible(Im_xmi,Im_ymj)){
if (zVMap[k]>d){
rv[k]=d;
zVMap[k]=d;
colorMap[k]=bgc;
}
}
if (zTMap[k]>d){
rt[k]=d;
zTMap[k]=d;
tactileMap[k]=tactile;
if (k==ai2) cornerT[k]=1;
else if (k==ai1) cornerT[k]=2;
else cornerT[k]=0;
}
}
for (int k=ai1;k<=ai3;k++){
d= d1*10 + (d3-d1)*10*(k-ai1)/(ai3-ai1);
if (m_env.isVisible(Im_xmi,Im_ymj)){
if (zVMap[k]>d){
rv[k]=d;
zVMap[k]=d;
colorMap[k]=bgc;
}
}
if (zTMap[k]>d){
rt[k]=d;
zTMap[k]=d;
tactileMap[k]=tactile;
if (k==ai1) cornerT[k]=1;
else if (k==ai3) cornerT[k]=2;
else cornerT[k]=0;
}
}
}
}
// (4) cells on the top left side
if ( (j>0) && (i>0) && (Im_xmi>=0) && (Im_xmi<m_w) && (Im_ypj>=0) && (Im_ypj<m_h) ){
if (!m_env.isEmpty(Im_xmi,Im_ypj) ){
Color bgc = m_env.seeBlock(Im_xmi,Im_ypj);
int tactile=m_env.touchBlock(Im_xmi,Im_ypj);
imin =(double)i-0.5 + (ax-Im_x);
imin2=imin*imin;
iplus=(double)i+0.5 + (ax-Im_x);
jmin =(double)j-0.5 - (ay-Im_y);
jmin2=jmin*jmin;
jplus=(double)j+0.5 - (ay-Im_y);
d1= imin2 + jmin2;
d1=Math.sqrt(d1);
d2= (iplus*iplus) + jmin2;
d2=Math.sqrt(d2);
d3= imin2 + (jplus*jplus);
d3=Math.sqrt(d3);
a1= Math.toDegrees( Math.acos( jmin/d1));
a2= Math.toDegrees( Math.acos( jmin/d2));
a3= Math.toDegrees( Math.acos( jplus/d3));
ai1=360-(int)a1;
ai3=360-(int)a3;
if (ai1==360) ai1=359;
if (ai3==360) ai3=359;
ai2=360-(int)a2;
for (int k=ai2;k<=ai1;k++){
d= d2*10 + (d1-d2)*10*(k-ai2)/(ai1-ai2);
if (m_env.isVisible(Im_xmi,Im_ypj)){
if (zVMap[k]>d){
rv[k]=d;
zVMap[k]= d;
colorMap[k]=bgc;
}
}
if (zTMap[k]>d){
rt[k]=d;
zTMap[k]= d;
tactileMap[k]=tactile;
if (k==ai2) cornerT[k]=1;
else if (k==ai1) cornerT[k]=2;
else cornerT[k]=0;
}
}
for (int k=ai1;k<=ai3;k++){
d= d1*10 + (d3-d1)*10*(k-ai1)/(ai3-ai1);
if (m_env.isVisible(Im_xmi,Im_ypj)){
if (zVMap[k]>d-0.01){
rv[k]=d;
zVMap[k]=d;
colorMap[k]=bgc;
}
}
if (zTMap[k]>d-0.01){
rt[k]=d;
zTMap[k]=d;
tactileMap[k]=tactile;
if (k==ai1) cornerT[k]=1;
else if (k==ai3) cornerT[k]=2;
else cornerT[k]=0;
}
}
}
}
// (5) cells exactly on the top
// In this case, there is only two visible points and one visible segment
if ( (j>0) && (i==0) && (Im_ypj>=0) && (Im_ypj<m_h) && (Im_xmi>=0) && (Im_xmi<m_w) ){
if (!m_env.isEmpty(Im_xmi,Im_ypj) ){
Color bgc = m_env.seeBlock(Im_xmi,Im_ypj);
int tactile=m_env.touchBlock(Im_xmi,Im_ypj);
imin =(double)i-0.5 + (ax-Im_x);
imin2=imin*imin;
iplus=(double)i+0.5 + (ax-Im_x);
jmin =(double)j-0.5 - (ay-Im_y);
jmin2=jmin*jmin;
d1= imin2 + jmin2;
d1=Math.sqrt(d1);
d2= (iplus*iplus) + jmin2;
d2=Math.sqrt(d2);
a1= Math.toDegrees( Math.acos( jmin/d1));
a2= Math.toDegrees( Math.acos( jmin/d2));
ai1=(int)a1;
ai2=360-(int)a2;
if (ai2==360) ai2=359;
int count=0;
for (int k=ai2;k<360;k++){
d= d2*10 + (d1-d2)*10*(k-ai2)/((ai1-ai2+360)%360);
if (m_env.isVisible(Im_xmi,Im_ypj)){
if (zVMap[k]>d){
rv[k]=d;
zVMap[k]= d;
colorMap[k]=bgc;
}
}
if (zTMap[k]>d){
rt[k]=d;
zTMap[k]= d;
tactileMap[k]=tactile;
if (k==ai2) cornerT[k]=1;
else cornerT[k]=0;
}
count++;
}
for (int k=0;k<=ai1;k++){
d= d2*10 + (d1-d2)*10*(k+count)/((ai1-ai2+360)%360);
if (m_env.isVisible(Im_xmi,Im_ypj)){
if (zVMap[k]>d){
rv[k]=d;
zVMap[k]= d;
colorMap[k]=bgc;
}
}
if (zTMap[k]>d){
rt[k]=d;
zTMap[k]= d;
tactileMap[k]=tactile;
if (k==ai1) cornerT[k]=2;
else cornerT[k]=0;
}
}
}
}
}
}
// agents detection
for (int a=0;a<m_env.platform.nbAgent();a++){
// for each other agent (agent or fish)
if (m_env.platform.getAgent(a).getIdent()!=robot.getId()){
// compute distance
d= (ax-m_env.platform.getAgent(a).body.position[0])*(ax-m_env.platform.getAgent(a).body.position[0])
+(ay-m_env.platform.getAgent(a).body.position[1])*(ay-m_env.platform.getAgent(a).body.position[1]);
d=Math.sqrt(d);
// compute angle
int ai4=0;
if (ax-m_env.platform.getAgent(a).body.position[0]<=0){
a1=Math.toDegrees( Math.acos( (ay-m_env.platform.getAgent(a).body.position[1])/d));
ai1=180-(int)a1;
}
else{
a1=Math.toDegrees( Math.acos( (ay-m_env.platform.getAgent(a).body.position[1])/d));
ai1=(int)a1+180;
}
// compute border angles
a2=Math.atan(0.4/d);
a2=Math.toDegrees(a2);
ai2= (int)a2;
ai3=ai1-ai2+360;
ai4=ai1+ai2+360;
for (int k=ai3;k<=ai4;k++){
if (zVMap[k%360]>d*10){
rv[k%360]=d*10 ;
zVMap[k%360]= d*10 ;
colorMap[k%360]=Environment.AGENT_COLOR;
}
if (zTMap[k%360]>d*10){
rt[k%360]=d*10 ;
zTMap[k%360]= d*10 ;
}
}
}
}
// correction of the distance vector (d is supposed constant for each points between 2 corners)
int j=0;
double x,y;
for (int i=0;i<360;i++){
j=(int) rv2[(359-i+180)%360]*2;
double angle =theta + (double)i*Math.PI/180;
boolean found=false;
while (j>0 && !found){
x= ax + ((double)j/20)*Math.cos(angle);
y= ay + ((double)j/20)*Math.sin(angle);
if (Math.round(x)>=0 && Math.round(y)>=0 && Math.round(x)<m_w && Math.round(y)<m_h){
if (m_env.seeBlock(Math.round(x),Math.round(y)).equals(Environment.FIELD_COLOR)){
found=true;
rv2[(359-i+180)%360]=(double)j/2;
rt2[(359-i+180)%360]=(double)j/2;
}
}
else found=true;
j--;
}
}
// fill the output vectors (agent orientation)
int orientationDeg= (int)(theta * 180 / Math.PI); // compute offset
for (int i=0;i<360;i++){
int offset=(i-orientationDeg+630)%360; // 630 = 2 X 360 -90
distRetina[i]=rv[offset];
colRetina[i] =colorMap[offset];
tMap[i]=tactileMap[offset];
corner[i]=cornerT[offset];
}
}
}
|
package com.timmy.customeView.imoocRipple;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Xfermode;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import com.timmy.R;
/**
* Created by admin on 2017/6/15.
* 高仿慕课网下拉刷新控件,具有水波纹效果
* 1.宽高问题处理 onMeasure
* 2.onDraw()绘制
* a.绘制默认展示图片
* b.绘制可以浮动的水波纹:贝塞尔曲线使用
*/
public class ImoocRippleView extends View {
private static final long DUTATION = 6 * 1000;
private int mHeight;
private int mWidth;
private Bitmap mResultBitmap;
private Xfermode xfermode;
private Canvas mCanvas;
private Paint mPaint;
private int mColor = Color.BLUE;
private Bitmap mLogoBitmap;
private Path mPath;
private int currHeight;//水波纹当前的高度: 从mHeight-->0
private int crestWidth, crestHeight;//一个波峰的宽度和高度
private int waveWidth = 100;
private int halfWaveWidth = waveWidth / 2;
private int dx;
public ImoocRippleView(Context context) {
this(context, null);
}
public ImoocRippleView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ImoocRippleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initConfi();
}
/**
* 拿到默认展示图片,获取宽高,在onMeasure方法中需要使用
* 初始化画笔
* 新建画布Canvas,需要在该画布上绘制我们想要展示的水波纹
*/
private void initConfi() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mColor);
mPath = new Path();
mLogoBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_imooc_logo);
mHeight = mLogoBitmap.getHeight();
mWidth = mLogoBitmap.getWidth();
currHeight = mHeight / 2;
crestWidth = mWidth / 4;
crestHeight = 20;
mResultBitmap = Bitmap.createBitmap(mLogoBitmap.getWidth(), mLogoBitmap.getHeight(), Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mResultBitmap);
xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(
getSuggestedDimension(widthMeasureSpec, mWidth),
getSuggestedDimension(heightMeasureSpec, mHeight)
);
}
private int getSuggestedDimension(int measureSpec, int defaultSize) {
int resultSize = defaultSize;
int size = MeasureSpec.getSize(measureSpec);
int mode = MeasureSpec.getMode(measureSpec);
switch (mode) {
case MeasureSpec.EXACTLY:
resultSize = size;
break;
case MeasureSpec.AT_MOST:
resultSize = Math.min(resultSize, size);
break;
default:
break;
}
return resultSize;
}
@Override
protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
drawRippleView();
canvas.drawBitmap(mResultBitmap, getPaddingLeft(), getPaddingTop(), null);
//刷新
}
/**
* 在画布上绘制,就是往mResultBitmap上面绘制图形
* 1.绘制贝塞尔曲线的波纹图形
* 2.再把原图通过xFerMode绘制上去就可以了
*/
private void drawRippleView() {
mPath.reset();
mResultBitmap.eraseColor(Color.parseColor("#00ffffff"));
//左下角
mPath.moveTo(0, mHeight);
//左上角
mPath.lineTo(-dx, currHeight);
//贝塞尔曲线
// mPath.cubicTo(mWidth/4,currHeight-50,mWidth/4*3,currHeight+50,mWidth,currHeight);
//运动的水波纹效果
// mPath.rCubicTo(crestWidth, -crestHeight, crestWidth * 3, crestHeight, mWidth, 0);
for (int i = -waveWidth; i < getWidth() + waveWidth; i += waveWidth) {
//rQuadTo使用的是相对上一个坐标的位置
mPath.rQuadTo(halfWaveWidth / 2, -crestHeight, halfWaveWidth, 0);
mPath.rQuadTo(halfWaveWidth / 2, crestHeight, halfWaveWidth, 0);
}
mPath.lineTo(mWidth, currHeight);
//右下角
mPath.lineTo(mWidth, mHeight);
mPath.close();
//画图片
mCanvas.drawBitmap(mLogoBitmap, 0, 0, mPaint);
mPaint.setXfermode(xfermode);
mCanvas.drawPath(mPath, mPaint);
mPaint.setXfermode(null);
}
public void startRippleMove() {
startHeighMove();
startWaveMove();
}
private void startHeighMove() {
ValueAnimator valueAnimator = ValueAnimator.ofInt(mHeight, 0);
valueAnimator.setDuration(1000);
valueAnimator.setRepeatCount(ValueAnimator.INFINITE);
valueAnimator.start();
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
currHeight = (int) animation.getAnimatedValue();
}
});
}
private void startWaveMove() {
ValueAnimator animator = ValueAnimator.ofInt(0,waveWidth)
.setDuration(DUTATION/4);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setInterpolator(new LinearInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
dx = waveWidth - (int) animation.getAnimatedValue();
invalidate();
}
});
animator.start();
}
/**
* 设置当前加载进度,改变水波纹加载的高度
*
* @param progress
*/
public void setProgress(int progress) {
if (progress > 0 && progress <= 100) {
currHeight = (int) (mHeight - (mHeight * progress / 100 * 1.0f));
Log.d("progress", "progress:" + progress + ",currHeight:" + currHeight);
invalidate();
}
}
}
|
package com.tencent.mm.ui.chatting;
import android.os.Looper;
import android.os.Message;
import com.tencent.mm.model.au;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.x;
class ac$1 extends ag {
final /* synthetic */ ac tMu;
ac$1(ac acVar, Looper looper) {
this.tMu = acVar;
super(looper);
}
public final void handleMessage(Message message) {
if (this.tMu.huM != null && au.HX()) {
x.d("MicroMsg.EggMgr", "post start egg");
this.tMu.a(this.tMu.tMt, this.tMu.huM);
}
}
}
|
package com.oxycab.provider.common.fcm;
/**
* Created by santhosh@appoets.com on 21-05-2018.
*/
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.oxycab.provider.BuildConfig;
import com.oxycab.provider.R;
import com.oxycab.provider.common.SharedHelper;
import com.oxycab.provider.common.Utilities;
import com.oxycab.provider.ui.activity.main.MainActivity;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
int notificationId = 0;
private static final String TAG = "MyFirebaseMsgService";
public static final String INTENT_FILTER = "INTENT_FILTER"+ BuildConfig.APPLICATION_ID;
@Override
public void onNewToken(String s) {
@SuppressLint("HardwareIds")
String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
Log.d("DEVICE_ID: " , deviceId);
Log.d("FCM_TOKEN",s);
SharedHelper.putKeyFCM(this, "device_token", s);
SharedHelper.putKeyFCM(this, "device_id", deviceId);
}
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent intent = new Intent(INTENT_FILTER);
sendBroadcast(intent);
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
sendNotification(remoteMessage.getData().get("message"));
}
}
/**
* Schedule a job using FirebaseJobDispatcher.
*/
/**
* Handle time allotted to BroadcastReceivers.
*/
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
if (!Utilities.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Utilities.printV(TAG, "foreground");
}
else
{
Utilities.printV(TAG,"background");
// app is in background, show the notification in notification tray
if(messageBody.equalsIgnoreCase("New Incoming Ride")){
Intent mainIntent = new Intent(this, MainActivity.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainIntent);
}
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "PUSH");
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(messageBody);
long when = System.currentTimeMillis(); // notification time
// Sets an ID for the notification, so it can be updated.
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = "Channel human readable title";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
Notification notification;
notification = mBuilder.setSmallIcon(R.mipmap.ic_launcher).setTicker(getString(R.string.app_name)).setWhen(when)
// .setAutoCancel(true)
.setContentTitle(getString(R.string.app_name))
.setContentIntent(pendingIntent)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
.setWhen(when)
.setSmallIcon(getNotificationIcon(mBuilder))
.setContentText(messageBody)
.setChannelId(CHANNEL_ID)
.setDefaults(Notification.DEFAULT_VIBRATE
| Notification.DEFAULT_LIGHTS
)
.build();
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
android.app.NotificationChannel mChannel = new android.app.NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(0, notification);
}
private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
return R.drawable.push;
} else {
return R.mipmap.ic_launcher;
}
}
}
|
/**
*
*/
package de.zarncke.lib.sys.module;
import java.io.FileInputStream;
import java.io.IOException;
import de.zarncke.lib.err.Warden;
import de.zarncke.lib.i18n.Translations;
import de.zarncke.lib.io.IOTools;
import de.zarncke.lib.jna.LinuxFunctions;
import de.zarncke.lib.sys.Health;
import de.zarncke.lib.util.Misc;
/**
* This Module tracks the system RAM.
* Only available on Linux.
*
* @author Gunnar Zarncke
*/
public class SystemRamModule extends AbstractModule {
private boolean virgin;
@Override
public Health getHealth() {
Health h = checkRamHealth();
if (h != Health.VIRGIN) {
this.virgin = false;
return h;
}
return this.virgin ? h : Health.CLEAN;
}
@Override
public Translations getName() {
return new Translations("RAM");
}
private Health checkRamHealth() {
double load = getLoad();
if (load == Double.NaN) {
return Health.VIRGIN;
}
if (load >= 0.99) {
return Health.ERRORS;
}
if (load > 0.9) {
return Health.WARNINGS;
}
if (load > 0.8) {
return Health.OK;
}
return Health.CLEAN;
}
@Override
public double getLoad() {
Long total = Misc.getTotalSystemRamBytes();
Long free = Misc.getFreeSystemRamBytes();
if (total == null || free == null) {
return Double.NaN;
}
return 1.0 - free.longValue() / (double) total.longValue();
}
@Override
public String toString() {
return "RAM";
}
@Override
public String getMetaInformation() {
try {
return new String(IOTools.getAllBytes(new FileInputStream(LinuxFunctions.PROC_MEMINFO)), Misc.ASCII);
} catch (IOException e) {
Warden.disregard(e);
return null;
}
}
} |
package com.campus.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
/**
* 学生表
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student implements Serializable {
/**
* 学生编号
*/
private Long sid;
/**
* 学生名称
*/
private String sname;
/**
* 学生账户
*/
private String saccount;
/**
* 密码
*/
private String spwd;
/**
* 身份证号
*/
private String idcard;
/**
* 用户年龄
*/
private Integer age;
/**
* 用户生日
*/
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;
/**
* 用户所在地区
*/
private String address;
/**
* 角色id
*/
private Long rid;
/**
* 学生邮箱
*/
private String seamil;
/**
* 学生验证码
*/
private String scode;
/**
* 班级的实体bean 呈现出一对一的关系
*/
private Grade grade = new Grade();
}
|
package JZOF;
/**
* Created by yang on 2017/3/24.
*/
/*
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
*/
public class IsSubTree {
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
boolean isSubTree = false;
if(root1!=null&&root2!=null) {
if (root1.val == root2.val) {
isSubTree = HasSubTree_(root1, root2);
}
if (!isSubTree) {
isSubTree = HasSubtree(root1.left, root2) ;
}
if(!isSubTree){
isSubTree = HasSubtree(root1.right, root2);
}
}
return isSubTree;
}
public boolean HasSubTree_(TreeNode root1, TreeNode root2) {
if (root2 == null || root1 == null) {
return false;
}
if (root1.val != root2.val) {
return false;
}
return HasSubtree(root1.left, root2.left) && HasSubtree(root1.right, root2.right);
}
// public boolean isSubTree(TreeNode root1,TreeNode root2){
//
// if(root2==NULL)
// return true;
//
// if(root1==NULL)
// return false;
//
// if(root1->data==root2->data)
//
// returnCheckIfSubTree2(root1->LC,root2->LC) &&CheckIfSubTree2(root1->RC,root2->RC);
//
// else
//
// returnCheckIfSubTree2(root1->LC,root2) || CheckIfSubTree2(root1->RC,root2);
// }
}
|
package com.tencent.mm.sdk.platformtools;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build.VERSION;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ListView;
import com.tencent.mm.compatible.util.Exif;
import com.tencent.mm.modelsfs.FileOp;
import java.io.InputStream;
public final class BackwardSupportUtil {
public static class ExifHelper {
public static class LatLongData implements Parcelable {
public static final Creator<LatLongData> CREATOR = new Creator<LatLongData>() {
public final /* synthetic */ Object createFromParcel(Parcel parcel) {
LatLongData latLongData = new LatLongData();
latLongData.bSx = parcel.readFloat();
latLongData.dVI = parcel.readFloat();
return latLongData;
}
public final /* bridge */ /* synthetic */ Object[] newArray(int i) {
return new LatLongData[i];
}
};
public float bSx;
public float dVI;
public LatLongData() {
this.bSx = 0.0f;
this.dVI = 0.0f;
}
public LatLongData(float f, float f2) {
this.bSx = f;
this.dVI = f2;
}
public int hashCode() {
return ((int) (this.bSx * 10000.0f)) + ((int) (this.dVI * 10000.0f));
}
public boolean equals(Object obj) {
if (!(obj instanceof LatLongData)) {
return false;
}
LatLongData latLongData = (LatLongData) obj;
if (Math.abs(this.bSx - latLongData.bSx) >= 1.0E-6f || Math.abs(this.dVI - latLongData.dVI) >= 1.0E-6f) {
return false;
}
return true;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeFloat(this.bSx);
parcel.writeFloat(this.dVI);
}
}
public static int VX(String str) {
if (bi.oW(str)) {
x.d("MicroMsg.SDK.BackwardSupportUtil", "filepath is null or nil");
return 0;
} else if (FileOp.cn(str)) {
return Exif.fromFile(str).getOrientationInDegree();
} else {
x.d("MicroMsg.SDK.BackwardSupportUtil", "file not exist:[%s]", str);
return 0;
}
}
public static LatLongData VY(String str) {
if (bi.oW(str)) {
x.d("MicroMsg.SDK.BackwardSupportUtil", "filepath is null or nil");
return null;
} else if (FileOp.cn(str)) {
com.tencent.mm.compatible.util.Exif.a location = Exif.fromFile(str).getLocation();
if (location == null) {
return null;
}
LatLongData latLongData = new LatLongData();
latLongData.bSx = (float) location.latitude;
latLongData.dVI = (float) location.longitude;
return latLongData;
} else {
x.d("MicroMsg.SDK.BackwardSupportUtil", "file not exist:[%s]", str);
return null;
}
}
}
public static class a {
public static void c(View view, Animation animation) {
if (VERSION.SDK_INT >= 8) {
b bVar = new b();
animation.cancel();
return;
}
a aVar = new a();
if (view != null) {
view.setAnimation(null);
}
}
}
public static class b {
public static Bitmap e(String str, float f) {
float f2 = 160.0f * f;
Bitmap f3 = c.f(str, f);
if (f3 != null) {
f3.setDensity((int) f2);
}
return f3;
}
public static int b(Context context, float f) {
return Math.round((((float) context.getResources().getDisplayMetrics().densityDpi) * f) / 160.0f);
}
public static Bitmap a(InputStream inputStream, float f) {
float f2 = 160.0f * f;
Bitmap a = c.a(inputStream, f, 0, 0);
if (a != null) {
a.setDensity((int) f2);
}
return a;
}
public static String fp(Context context) {
String str;
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
Configuration configuration = context.getResources().getConfiguration();
String str2 = "";
if (displayMetrics.density < 1.0f) {
str = str2 + "LDPI";
} else if (displayMetrics.density >= 1.5f) {
str = str2 + "HDPI";
} else {
str = str2 + "MDPI";
}
return str + (configuration.orientation == 2 ? "_L" : "_P");
}
}
public static class c {
public static void a(ListView listView) {
if (listView != null) {
if (VERSION.SDK_INT >= 8) {
bc bcVar = new bc();
if (listView.getFirstVisiblePosition() > 10) {
listView.setSelection(10);
}
if (VERSION.SDK_INT >= 8) {
listView.smoothScrollToPosition(0);
return;
}
return;
}
bb bbVar = new bb();
listView.setSelection(0);
}
}
public static void b(ListView listView, int i) {
if (listView != null) {
if (VERSION.SDK_INT >= 8) {
bc bcVar = new bc();
int firstVisiblePosition = listView.getFirstVisiblePosition();
if (firstVisiblePosition > i && firstVisiblePosition - i > 10) {
listView.setSelection(i + 10);
} else if (firstVisiblePosition < i && i - firstVisiblePosition > 10) {
listView.setSelection(i - 10);
}
if (VERSION.SDK_INT >= 8) {
listView.smoothScrollToPosition(i);
return;
}
return;
}
bb bbVar = new bb();
listView.setSelection(i);
}
}
}
}
|
package com.holmes.sorts;
/**
* 冒泡排序
*
* 复杂度为 O(n^2)
*/
public class BubbleSort extends AbstractSort{
public static void main(String[] args) {
int[] array = new int[]{15, 18, 13, 16, 2, 5, 8, 4, 6, 9, 12, 3, 5, 15, 16, 118, 1, 6};
AbstractSort bubbleSort = new BubbleSort();
bubbleSort.sort(array);
bubbleSort.display(array);
}
@Override
public void sort(int[] array) {
// 遍历总次数为 array.length - 1 次
for (int i = 0; i < array.length - 1; i++) {
// 每次遍历都将一个最大的元素往上冒
for (int j = 1; j < array.length - i; j++) {
// 每次比较相邻两个数字
if (array[j] < array[j - 1]) {
int temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
}
}
|
package com.mysql.cj.util;
public class DataTypeUtil {
public static long bitToLong(byte[] bytes, int offset, int length) {
long valueAsLong = 0L;
for (int i = 0; i < length; i++)
valueAsLong = valueAsLong << 8L | (bytes[offset + i] & 0xFF);
return valueAsLong;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\c\\util\DataTypeUtil.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
/*
* 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 ejb.session.singleton;
import ejb.session.stateless.AircraftConfigurationSessionBeanLocal;
import ejb.session.stateless.AircraftTypeSessionBeanLocal;
import ejb.session.stateless.AirportSessionBeanLocal;
import ejb.session.stateless.CustomerSessionBeanLocal;
import ejb.session.stateless.EmployeeSessionBeanLocal;
import ejb.session.stateless.FlightRouteSessionBeanLocal;
import ejb.session.stateless.FlightSessionBeanLocal;
import entity.AircraftConfiguration;
import entity.AircraftType;
import entity.Airport;
import entity.CabinClass;
import entity.CabinClassConfiguration;
import entity.Employee;
import entity.Flight;
import entity.FlightRoute;
import entity.Partner;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ejb.LocalBean;
import javax.ejb.Startup;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import util.enumeration.CabinClassType;
import util.enumeration.EmployeeType;
import util.exception.AircraftConfigurationExistExcetpion;
import util.exception.AircraftConfigurationNotFoundException;
import util.exception.AircraftTypeExistException;
import util.exception.AircraftTypeNotFoundException;
import util.exception.AirportExistException;
import util.exception.AirportNotFoundException;
import util.exception.EmployeeExistException;
import util.exception.FlightExistException;
import util.exception.FlightRouteDisabledException;
import util.exception.FlightRouteExistException;
import util.exception.FlightRouteNotFoundException;
import util.exception.GeneralException;
import util.exception.PartnerExistException;
/**
*
* @author Administrator
*/
@Singleton
@LocalBean
@Startup
public class DataInitSessionBean {
@EJB(name = "FlightSessionBeanLocal")
private FlightSessionBeanLocal flightSessionBeanLocal;
@EJB(name = "FlightRouteSessionBeanLocal")
private FlightRouteSessionBeanLocal flightRouteSessionBeanLocal;
@EJB(name = "AircraftConfigurationSessionBeanLocal")
private AircraftConfigurationSessionBeanLocal aircraftConfigurationSessionBeanLocal;
@EJB(name = "CustomerSessionBeanLocal")
private CustomerSessionBeanLocal customerSessionBeanLocal;
@EJB(name = "EmployeeSessionBeanLocal")
private EmployeeSessionBeanLocal employeeSessionBeanLocal;
@EJB(name = "AirportSessionBeanLocal")
private AirportSessionBeanLocal airportSessionBeanLocal;
@EJB(name = "AircraftTypeSessionBeanLocal")
private AircraftTypeSessionBeanLocal aircraftTypeSessionBeanLocal;
@PersistenceContext(unitName = "FlightReservationSystem-ejbPU")
private EntityManager em;
public DataInitSessionBean()
{
}
@PostConstruct
public void postConstruct()
{
if(em.find(Employee.class, 1l) == null)
{
initialiseEmployee();
}
if(em.find(Partner.class, 1l) == null)
{
initialisePartner();
}
if(em.find(Airport.class, 1l) == null)
{
initialiseAirport();
}
if(em.find(AircraftType.class, 1l) == null)
{
initialiseAircraftType();
}
if(em.find(AircraftConfiguration.class, 1l) == null)
{
initialiseAircraftConfiguration();
}
if(em.find(FlightRoute.class, 1l) == null)
{
initialiseFlightRoute();
}
if(em.find(Flight.class, 1l) == null)
{
initialiseFlight();
}
}
private void initialiseEmployee()
{
try {
employeeSessionBeanLocal.createNewEmployee(new Employee("Sales Manager", "salesmanager", "password", EmployeeType.SALESMANAGER));
employeeSessionBeanLocal.createNewEmployee(new Employee("Fleet Manager", "fleetmanager", "password", EmployeeType.FLEETMANAGER));
employeeSessionBeanLocal.createNewEmployee(new Employee("Route Planner", "routeplanner", "password", EmployeeType.ROUTEPLANNER));
employeeSessionBeanLocal.createNewEmployee(new Employee("Schedule Manager", "schedulemanager", "password", EmployeeType.SCHEDULEMANAGER));
} catch (EmployeeExistException | GeneralException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
private void initialisePartner()
{
try {
customerSessionBeanLocal.createNewPartner(new Partner("Holiday.com","holidaydotcom","password"));
} catch (PartnerExistException | GeneralException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
private void initialiseAirport()
{
try {
airportSessionBeanLocal.createNewAirport(new Airport("Changi", "SIN", "Singapore", "Singapore", "Singapore", 8));
airportSessionBeanLocal.createNewAirport(new Airport("Hong Kong", "HKG", "Chek Lap Kok", "HongKong", "China", 8));
airportSessionBeanLocal.createNewAirport(new Airport("Taoyuan", "TPE", "Taipei", "Taiwan Province", "China", 8));
airportSessionBeanLocal.createNewAirport(new Airport("Narita", "NRT", "Narita", "Chiba", "Japan", 9));
airportSessionBeanLocal.createNewAirport(new Airport("Sydney", "SYD", "Sydney", "New South Wales", "Australia", 11));
} catch (AirportExistException | GeneralException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
public void initialiseAircraftType()
{
try {
aircraftTypeSessionBeanLocal.createNewAircraftType(new AircraftType("Boeing 737", 200));
aircraftTypeSessionBeanLocal.createNewAircraftType(new AircraftType("Boeing 747", 400));
} catch (AircraftTypeExistException | GeneralException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
public void initialiseAircraftConfiguration()
{
try {
AircraftType boeing737 = aircraftTypeSessionBeanLocal.retrieveAircraftTypeByName("Boeing 737");
AircraftType boeing747 = aircraftTypeSessionBeanLocal.retrieveAircraftTypeByName("Boeing 747");
//Boeing 737 All Economy
AircraftConfiguration boeing737AllEconomy = new AircraftConfiguration("Boeing 737 All Economy", 1);
List<CabinClass> boeing737AllEconomyList = new ArrayList<>();
CabinClassConfiguration allEconomyEconomyConfig = new CabinClassConfiguration(1, 30, 6, "3-3", 180);
boeing737AllEconomyList.add(new CabinClass(CabinClassType.ECONOMYCLASS, allEconomyEconomyConfig));
aircraftConfigurationSessionBeanLocal.createNewAircraftConfiguration(boeing737AllEconomy, boeing737, boeing737AllEconomyList);
//Boeing 737 Three Classes
AircraftConfiguration boeing737ThreeClasses = new AircraftConfiguration("Boeing 737 Three Classes", 3);
List<CabinClass> boeing737ThreeClassesList = new ArrayList<>();
CabinClassConfiguration boeing737ThreeClassesFirst = new CabinClassConfiguration(1, 5, 2, "1-1", 10);
boeing737ThreeClassesList.add(new CabinClass(CabinClassType.FIRSTCLASS, boeing737ThreeClassesFirst));
CabinClassConfiguration boeing737ThreeClassesBusiness = new CabinClassConfiguration(1, 5, 4, "2-2", 20);
boeing737ThreeClassesList.add(new CabinClass(CabinClassType.BUSINESSCLASS, boeing737ThreeClassesBusiness));
CabinClassConfiguration boeing737ThreeClassesEconomy = new CabinClassConfiguration(1, 25, 6, "3-3", 150);
boeing737ThreeClassesList.add(new CabinClass(CabinClassType.ECONOMYCLASS, boeing737ThreeClassesEconomy));
aircraftConfigurationSessionBeanLocal.createNewAircraftConfiguration(boeing737ThreeClasses, boeing737, boeing737ThreeClassesList);
//Boeing 747 All Economy
AircraftConfiguration boeing747AllEconomy = new AircraftConfiguration("Boeing 747 All Economy", 1);
List<CabinClass> boeing747AllEconomyList = new ArrayList<>();
CabinClassConfiguration boeing747AllEconomyEconomy = new CabinClassConfiguration(2, 38, 10, "3-4-3", 380);
boeing747AllEconomyList.add(new CabinClass(CabinClassType.ECONOMYCLASS, boeing747AllEconomyEconomy));
aircraftConfigurationSessionBeanLocal.createNewAircraftConfiguration(boeing747AllEconomy, boeing747, boeing747AllEconomyList);
//Boeing 747 Three Classes
AircraftConfiguration boeing747ThreeClasses = new AircraftConfiguration("Boeing 747 Three Classes", 3);
List<CabinClass> boeing747ThreeClassesList = new ArrayList<>();
CabinClassConfiguration boeing747ThreeClassesFirst = new CabinClassConfiguration(1, 5, 2, "1-1", 10);
boeing747ThreeClassesList.add(new CabinClass(CabinClassType.FIRSTCLASS, boeing747ThreeClassesFirst));
CabinClassConfiguration boeing747ThreeClassesBusiness = new CabinClassConfiguration(2, 5, 6, "2-2-2", 30);
boeing747ThreeClassesList.add(new CabinClass(CabinClassType.BUSINESSCLASS, boeing747ThreeClassesBusiness));
CabinClassConfiguration boeing747ThreeClassesEconomy = new CabinClassConfiguration(2, 32, 10, "3-4-3", 320);
boeing747ThreeClassesList.add(new CabinClass(CabinClassType.ECONOMYCLASS, boeing747ThreeClassesEconomy));
aircraftConfigurationSessionBeanLocal.createNewAircraftConfiguration(boeing747ThreeClasses, boeing747, boeing747ThreeClassesList);
} catch (AircraftTypeNotFoundException | AircraftConfigurationExistExcetpion | GeneralException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
public void initialiseFlightRoute()
{
try {
Long newFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("SIN", "HKG");
Long newComplementaryFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("HKG", "SIN");
flightRouteSessionBeanLocal.associateComplementaryFlightRoute(newFlightRouteId, newComplementaryFlightRouteId);
newFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("SIN", "TPE");
newComplementaryFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("TPE", "SIN");
flightRouteSessionBeanLocal.associateComplementaryFlightRoute(newFlightRouteId, newComplementaryFlightRouteId);
newFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("SIN", "NRT");
newComplementaryFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("NRT", "SIN");
flightRouteSessionBeanLocal.associateComplementaryFlightRoute(newFlightRouteId, newComplementaryFlightRouteId);
newFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("HKG", "NRT");
newComplementaryFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("NRT", "HKG");
flightRouteSessionBeanLocal.associateComplementaryFlightRoute(newFlightRouteId, newComplementaryFlightRouteId);
newFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("TPE", "NRT");
newComplementaryFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("NRT", "TPE");
flightRouteSessionBeanLocal.associateComplementaryFlightRoute(newFlightRouteId, newComplementaryFlightRouteId);
newFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("SIN", "SYD");
newComplementaryFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("SYD", "SIN");
flightRouteSessionBeanLocal.associateComplementaryFlightRoute(newFlightRouteId, newComplementaryFlightRouteId);
newFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("SYD", "NRT");
newComplementaryFlightRouteId = flightRouteSessionBeanLocal.createNewFlightRoute("NRT", "SYD");
flightRouteSessionBeanLocal.associateComplementaryFlightRoute(newFlightRouteId, newComplementaryFlightRouteId);
} catch (FlightRouteExistException | GeneralException | AirportNotFoundException | FlightRouteNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
public void initialiseFlight()
{
try {
Flight ml111 = new Flight("ML111");
Long newFlightId = flightSessionBeanLocal.createNewFlight(ml111, "SIN", "HKG", "Boeing 737 Three Classes");
Flight ml112 = new Flight("ML112");
Long newComplementaryReturnFlightId = flightSessionBeanLocal.createNewFlight(ml112, "HKG", "SIN", "Boeing 737 Three Classes");
flightSessionBeanLocal.associateComplementaryFlight(newFlightId, newComplementaryReturnFlightId);
Flight ml211 = new Flight("ML211");
newFlightId = flightSessionBeanLocal.createNewFlight(ml211, "SIN", "TPE", "Boeing 737 Three Classes");
Flight ml212 = new Flight("ML212");
newComplementaryReturnFlightId = flightSessionBeanLocal.createNewFlight(ml212, "TPE", "SIN", "Boeing 737 Three Classes");
flightSessionBeanLocal.associateComplementaryFlight(newFlightId, newComplementaryReturnFlightId);
Flight ml311 = new Flight("ML311");
newFlightId = flightSessionBeanLocal.createNewFlight(ml311, "SIN", "NRT", "Boeing 747 Three Classes");
Flight ml312 = new Flight("ML312");
newComplementaryReturnFlightId = flightSessionBeanLocal.createNewFlight(ml312, "NRT", "SIN", "Boeing 747 Three Classes");
flightSessionBeanLocal.associateComplementaryFlight(newFlightId, newComplementaryReturnFlightId);
Flight ml411 = new Flight("ML411");
newFlightId = flightSessionBeanLocal.createNewFlight(ml411, "HKG", "NRT", "Boeing 737 Three Classes");
Flight ml412 = new Flight("ML412");
newComplementaryReturnFlightId = flightSessionBeanLocal.createNewFlight(ml412, "NRT", "HKG", "Boeing 737 Three Classes");
flightSessionBeanLocal.associateComplementaryFlight(newFlightId, newComplementaryReturnFlightId);
Flight ml511 = new Flight("ML511");
newFlightId = flightSessionBeanLocal.createNewFlight(ml511, "TPE", "NRT", "Boeing 737 Three Classes");
Flight ml512 = new Flight("ML512");
newComplementaryReturnFlightId = flightSessionBeanLocal.createNewFlight(ml512, "NRT", "TPE", "Boeing 737 Three Classes");
flightSessionBeanLocal.associateComplementaryFlight(newFlightId, newComplementaryReturnFlightId);
Flight ml611 = new Flight("ML611");
newFlightId = flightSessionBeanLocal.createNewFlight(ml611, "SIN", "SYD", "Boeing 737 Three Classes");
Flight ml612 = new Flight("ML612");
newComplementaryReturnFlightId = flightSessionBeanLocal.createNewFlight(ml612, "SYD", "SIN", "Boeing 737 Three Classes");
flightSessionBeanLocal.associateComplementaryFlight(newFlightId, newComplementaryReturnFlightId);
Flight ml621 = new Flight("ML621");
newFlightId = flightSessionBeanLocal.createNewFlight(ml621, "SIN", "SYD", "Boeing 737 All Economy");
Flight ml622 = new Flight("ML622");
newComplementaryReturnFlightId = flightSessionBeanLocal.createNewFlight(ml622, "SYD", "SIN", "Boeing 737 All Economy");
flightSessionBeanLocal.associateComplementaryFlight(newFlightId, newComplementaryReturnFlightId);
Flight ml711 = new Flight("ML711");
newFlightId = flightSessionBeanLocal.createNewFlight(ml711, "SYD", "NRT", "Boeing 747 Three Classes");
Flight ml712 = new Flight("ML712");
newComplementaryReturnFlightId = flightSessionBeanLocal.createNewFlight(ml712, "NRT", "SYD", "Boeing 747 Three Classes");
flightSessionBeanLocal.associateComplementaryFlight(newFlightId, newComplementaryReturnFlightId);
} catch (AircraftConfigurationNotFoundException | FlightExistException | GeneralException
| FlightRouteNotFoundException | FlightRouteDisabledException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
}
|
package httf;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import javax.swing.JPanel;
import httf.ui.Screen;
import httf.util.InputHandler;
public class RetroGame extends Canvas implements Runnable {
public static int WIDTH = 300;
public static int HEIGHT = 210;
public static final int SCALE = 4;
public static final String TITLE = "Hack to the future 2017";
public static final boolean FULLSCREEN = false;
public JFrame frame;
public BufferedImage img;
public int[] pixels;
public InputHandler input;
public Screen screen;
public Thread thread;
public boolean running;
public RetroGame() {
input = new InputHandler(65535);
frame = new JFrame(TITLE + " | 000");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.addKeyListener(input);
frame.addMouseListener(input);
frame.addMouseMotionListener(input);
frame.addMouseWheelListener(input);
if(FULLSCREEN) frame.setUndecorated(true);
addKeyListener(input);
addMouseListener(input);
addMouseMotionListener(input);
addMouseWheelListener(input);
thread = new Thread(this);
img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt) img.getData().getDataBuffer()).getData();
screen = new Screen(WIDTH, HEIGHT);
Canvas c = this;
JPanel panel = new JPanel(new BorderLayout());
panel.add(c);
frame.setContentPane(panel);
panel.addKeyListener(input);
panel.addMouseListener(input);
panel.addMouseMotionListener(input);
panel.addMouseWheelListener(input);
frame.setVisible(true);
start();
}
@Override
public void run() {
long lastTime = System.currentTimeMillis();
int frames = 0;
while(running) {
tick();
render();
frames++;
while(System.currentTimeMillis() - lastTime > 1000) {
// System.out.println(frames + " fps");
frame.setTitle(TITLE + " | " + frames);
lastTime += 1000;
frames = 0;
}
}
}
private void tick() {
if(input.keys[KeyEvent.VK_ESCAPE]) {
System.exit(0);
}
if(input.keys[KeyEvent.VK_W]) {
if(screen.player.y > 0) {
screen.maze.tick(0, -1);
}
}
if(input.keys[KeyEvent.VK_A]) {
if(screen.player.x > 0) {
screen.maze.tick(-1, 0);
}
}
if(input.keys[KeyEvent.VK_S]) {
if(screen.player.y < HEIGHT - 24) {
screen.maze.tick(0, 1);
}
}
if(input.keys[KeyEvent.VK_D]) {
if(screen.player.x < WIDTH - 16) {
screen.maze.tick(1, 0);
}
}
}
private void render() {
BufferStrategy bs = getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
screen.render();
screen.postProcess();
for(int x = 0; x < WIDTH; x++) {
for(int y = 0; y < HEIGHT; y++) {
pixels[x + y * WIDTH] = screen.pixels[x][y];
img.setRGB(x, y, pixels[x + y * WIDTH]);
}
}
Graphics g = bs.getDrawGraphics();
g.fillRect(0, 0, WIDTH, HEIGHT);
g.drawImage(img, 0, 0, WIDTH * SCALE, HEIGHT * SCALE, null);
g.dispose();
bs.show();
}
public synchronized void start() {
if(running) return;
running = true;
thread.start();
}
public synchronized void stop() {
if(!running) return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if(FULLSCREEN) {
WIDTH = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
HEIGHT = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
}
else {
WIDTH = 300;
HEIGHT = 210;
}
new RetroGame();
}
}
|
package MiddleClass;
import java.util.Stack;
/**
* @author admin
* @version 1.0.0
* @ClassName useOneStackToSort.java
* @Description 对一个栈里的整型数据, 按升序进行排序(即排序前, 栈里 的数据是无序的, 排序后最大元素位于栈顶) ,
* 要求最多只能使用一个额外的 栈存放临时数据, 但不得将元素复制到别的数据结构中
*
* 这题的关键是只能使用一个额外的stack,这是个临时栈,用于倒转,还有一个本身的原有栈
* 大致思路是临时栈中由栈底从大到小排列(降序),遇到不符合规则的(从原始栈提取的大于临时栈顶元素),将临时栈中不符合规则的,返回原有栈,最后在倒序
* @createTime 2021年07月22日 10:10:00
*/
public class useOneStackToSort {
public static void sortStackByStack(Stack<Integer> stack) {
Stack<Integer> temp = new Stack<>();
while (!stack.isEmpty()) {
//stack.peek返回的是一个值,相当于获取一个数,
//但是stack.pop会在这个stack里面删除一个元素。
Integer curr = stack.pop();
while (!temp.isEmpty() && curr > temp.peek()) {
stack.push(temp.pop());
}
//否则的话就把原始栈顶的元素插到临时栈
temp.push(curr);
}
//最后,舍弃临时栈,把临时栈的倒转回原始栈,就是"对一个栈里的整型数据,按升序进行排序"
while (!temp.isEmpty()){
stack.push(temp.pop());
}
}
public static void main(String[] args) {
Stack<Integer> test = new Stack<>();
test.push(3);
test.push(1);
test.push(6);
test.push(2);
test.push(5);
test.push(4);
sortStackByStack(test);
System.out.println(test.pop());
System.out.println(test.pop());
System.out.println(test.pop());
System.out.println(test.pop());
System.out.println(test.pop());
System.out.println(test.pop());
}
}
|
package com.zhouyi.business.core.utils;
import org.jsoup.helper.DataUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @author 李秸康
* @ClassNmae: CalendarUtils
* @Description: TODO 时间工具类
* @date 2019/9/4 9:54
* @Version 1.0
**/
public class CalendarUtils {
/**
* 默认日期格式
*/
public static String DEFAULT_FORMAT = "yyyy-MM-dd";
/**
/**
* 格式化日期
* @param date 日期对象
* @return String 日期字符串
*/
public static String formatDate(Date date){
SimpleDateFormat f = new SimpleDateFormat(DEFAULT_FORMAT);
String sDate = f.format(date);
return sDate;
}
/**
* 获取当年的第一天
* @param year
* @return
*/
public static Date getCurrYearFirst(){
Calendar currCal=Calendar.getInstance();
int currentYear = currCal.get(Calendar.YEAR);
return getYearFirst(currentYear);
}
/**
* 获取当年的最后一天
* @param year
* @return
*/
public static Date getCurrYearLast(){
Calendar currCal=Calendar.getInstance();
int currentYear = currCal.get(Calendar.YEAR);
return getYearLast(currentYear);
}
/**
* 获取某年第一天日期
* @param year 年份
* @return Date
*/
public static Date getYearFirst(int year){
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, year);
Date currYearFirst = calendar.getTime();
return currYearFirst;
}
/**
* 获取某年最后一天日期
* @param year 年份
* @return Date
*/
public static Date getYearLast(int year){
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.roll(Calendar.DAY_OF_YEAR, -1);
Date currYearLast = calendar.getTime();
return currYearLast;
}
/**
* 返回两个季度的Calendar
* @return
*/
public static Calendar[] quarterDate(Integer quarter){
Calendar calendars[] =new Calendar[2];
switch (quarter){
case 1:
calendars[0]=getFisrtDayOfMonth(getSysYear(),1);
calendars[1]=getFisrtDayOfMonth(getSysYear(),3);
break;
case 2:
calendars[0]=getFisrtDayOfMonth(getSysYear(),4);
calendars[1]=getFisrtDayOfMonth(getSysYear(),6);
break;
case 3:
calendars[0]=getFisrtDayOfMonth(getSysYear(),7);
calendars[1]=getFisrtDayOfMonth(getSysYear(),9);
break;
case 4:
calendars[0]=getFisrtDayOfMonth(getSysYear(),10);
calendars[1]=getFisrtDayOfMonth(getSysYear(),12);
break;
}
return calendars;
}
public static Calendar getLastDayOfMonth(int year,int month)
{
Calendar cal = Calendar.getInstance();
//设置年份
cal.set(Calendar.YEAR,year);
//设置月份
cal.set(Calendar.MONTH, month-1);
//获取某月最大天数
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
//设置日历中月份的最大天数
cal.set(Calendar.DAY_OF_MONTH, lastDay);
return cal;
}
public static Calendar getFisrtDayOfMonth(int year,int month)
{
Calendar cal = Calendar.getInstance();
//设置年份
cal.set(Calendar.YEAR,year);
//设置月份
cal.set(Calendar.MONTH, month-1);
//获取某月最小天数
int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
//设置日历中月份的最小天数
cal.set(Calendar.DAY_OF_MONTH, firstDay);
return cal;
}
public static Date[] weekDate(Integer year,Integer week){
Date[] dates=new Date[2];
Calendar calendar = Calendar.getInstance();
calendar.set(year, 0, 1);
int dayOfWeek = 7- calendar.get(Calendar.DAY_OF_WEEK) + 1;//算出第一周还剩几天 +1是因为1号是1天
week = week -2;//周数减去第一周再减去要得到的周
calendar.add(Calendar.DAY_OF_YEAR, week*7+dayOfWeek);
dates[0]=calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 6);
dates[1]=calendar.getTime();
return dates;
}
public static Integer getSysYear() {
Calendar date = Calendar.getInstance();
String year = String.valueOf(date.get(Calendar.YEAR));
return Integer.parseInt(year);
}
public static Calendar generateCalendar(Date date){
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
/**
* 将日期转为Calendar
* @param date
* @return
*/
public static Calendar[] transferToCalendar(Date[] date){
Calendar[] calendars=new Calendar[date.length];
for (int i=0;i<date.length;i++){
Calendar calendar=Calendar.getInstance();
calendar.setTime(date[i]);
calendars[i]=calendar;
}
return calendars;
}
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Date s = sdf.parse("2019-05");
Calendar ca = Calendar.getInstance();
ca.setTime(s);
ca.setFirstDayOfWeek(Calendar.MONDAY);
System.out.println(ca.getActualMaximum(Calendar.WEEK_OF_MONTH));
}
}
|
package lintcode;
import lintcode.util.TreeNode;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* 二叉查找树迭代器
*
* @author zhoubo
* @create 2017-11-03 14:29
*/
public class L86 {
}
class BSTIterator {
List<TreeNode> treeNodes = new LinkedList<>();
Iterator<TreeNode> iterator;
public BSTIterator(TreeNode root) {
inorderTraversal(root);
iterator = treeNodes.iterator();
}
public boolean hasNext() {
return iterator.hasNext();
}
public TreeNode next() {
return iterator.next();
}
public void inorderTraversal(TreeNode treeNode) {
if (null == treeNode) {
return;
}
inorderTraversal(treeNode.left);
treeNodes.add(treeNode);
inorderTraversal(treeNode.right);
}
}
|
package generic;
/**
* Author: fangxueshun
* Description:
* Date: 2017/5/31
* Time: 10:23
*/
public class Plate<T> {
private T item;
public Plate(T t){
this.item = t;
}
public void set(T t){this.item = t;}
public T get(){return this.item;}
public static void main(String[] args) {
Plate<Fruit> fruitPlate = new Plate<>(new Apple());
fruitPlate.set(new Lemon());
System.out.println(fruitPlate.get().taste());
}
}
|
/*
* 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 eva_7_arreglos_objetos;
/**
*
* @author danie
*/
public class EVA_7_ARREGLOS_OBJETOS {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//ARREGLO DE ALUMNOS
ALUMNO aaAlumnos[]=new ALUMNO[10];
for (int i = 0; i < 10; i++) {
aaAlumnos[i] = new ALUMNO ("Daniel", "16550723",0);
}
//Imprimir los datos de los alumnos
for (int i = 0; i < 10; i++) {
System.out.println("Nombre "+aaAlumnos[i].getsNom());
System.out.println("NoControl "+aaAlumnos[i].getsNoCtrl());
System.out.println("Carrera "+aaAlumnos[i].getiCarre());
}
//CREAR COPIA DEL ARREGLO
ALUMNO aaCopia [] = new ALUMNO [10];
for (int i = 0; i < 10; i++) {
aaCopia[i]=new ALUMNO{aaAlumnos[i].getsNom,aaAlumnos[i].getsNoCtrl,aaAlumnos[i].getiCarre}/
}
}}
class ALUMNO {
private String sNom;
private String sNoCtrl;
private int iCarre;
public ALUMNO (String sNombre, String NCtrl, int Carrera){
this.sNom=sNombre;
this.iCarre=Carrera;
this.sNoCtrl=NCtrl;
}
public String getsNom() {
return sNom;
}
public void setsNom(String sNom) {
this.sNom = sNom;
}
public String getsNoCtrl() {
return sNoCtrl;
}
public void setsNoCtrl(String sNoCtrl) {
this.sNoCtrl = sNoCtrl;
}
public int getiCarre() {
return iCarre;
}
public void setiCarre(int iCarre) {
this.iCarre = iCarre;
}
}
|
package codechicken.enderstorage.init;
import codechicken.enderstorage.block.BlockEnderStorage;
import codechicken.enderstorage.block.BlockEnderStorage.Type;
import codechicken.enderstorage.client.ParticleDummyModel;
import codechicken.enderstorage.client.render.item.EnderChestItemRender;
import codechicken.enderstorage.client.render.item.EnderTankItemRender;
import codechicken.enderstorage.item.ItemEnderStorage;
import codechicken.enderstorage.tile.TileEnderChest;
import codechicken.enderstorage.tile.TileEnderTank;
import codechicken.lib.model.ModelRegistryHelper;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.StateMap;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Created by covers1624 on 4/11/2016.
*/
public class ModBlocks {
public static BlockEnderStorage blockEnderStorage;
public static ItemEnderStorage itemEnderStorage;
public static void init() {
blockEnderStorage = new BlockEnderStorage();
itemEnderStorage = new ItemEnderStorage(blockEnderStorage);
ForgeRegistries.BLOCKS.register(blockEnderStorage.setRegistryName("ender_storage"));
ForgeRegistries.ITEMS.register(itemEnderStorage.setRegistryName("ender_storage"));
GameRegistry.registerTileEntity(TileEnderChest.class, "Ender Chest");
GameRegistry.registerTileEntity(TileEnderTank.class, "Ender Tank");
}
@SideOnly (Side.CLIENT)
public static void registerModels() {
for (int i = 0; i < Type.VALUES.length; i++) {
Type variant = Type.VALUES[i];
ModelResourceLocation location = new ModelResourceLocation("enderstorage:ender_storage", "type=" + variant.getName());
ModelLoader.setCustomModelResourceLocation(itemEnderStorage, i, location);
}
ModelRegistryHelper.register(new ModelResourceLocation("enderstorage:ender_storage", "type=ender_chest"), new EnderChestItemRender());
ModelRegistryHelper.register(new ModelResourceLocation("enderstorage:ender_storage", "type=ender_tank"), new EnderTankItemRender());
ModelLoader.setCustomStateMapper(blockEnderStorage, new StateMap.Builder().ignore(BlockEnderStorage.VARIANTS).build());
ModelRegistryHelper.register(new ModelResourceLocation("enderstorage:ender_storage", "normal"), ParticleDummyModel.INSTANCE);
}
}
|
package com.cse308.sbuify.playlist;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("playlist")
public class PlaylistProperties {
/**
* Maximum number of songs per playlist.
*/
private Integer maxSongs = 10000;
/**
* Songs per playlist page.
*/
private Integer songsPerPage = 25;
public Integer getMaxSongs() {
return maxSongs;
}
public void setMaxSongs(Integer maxSongs) {
this.maxSongs = maxSongs;
}
public Integer getSongsPerPage() {
return songsPerPage;
}
public void setSongsPerPage(Integer songsPerPage) {
this.songsPerPage = songsPerPage;
}
}
|
package com.tencent.mm.ui.f.a;
public final class a {
c utd;
public a(c cVar) {
this.utd = cVar;
}
}
|
package junkuvo.apps.inputhelper.fragment.item;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import junkuvo.apps.inputhelper.R;
public class ListItemViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public ListItemData mItem;
public ListItemViewHolder(View itemView) {
super(itemView);
mView = itemView;
mIdView = (TextView) itemView.findViewById(R.id.id);
mContentView = (TextView) itemView.findViewById(R.id.content);
}
@Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
|
package abstraction;
interface Bank{
double getInterestRate();
default void welcomeMsg() {
System.out.println("Welcome to bank");
}
static int getPPFInterestRate() {
return 7;
}
}
class ICICI implements Bank{
@Override
public double getInterestRate() {
return 8;
}
public void welcomeMsg() {
System.out.println("Welcome to ICICI");
}
}
class SBI implements Bank{
@Override
public double getInterestRate() {
return 9;
}
}
public class TestInterface1{
public static void main(String []args) {
Bank B;
B = new ICICI();
B.welcomeMsg();
System.out.println(B.getInterestRate());
B = new SBI();
System.out.println(B.getInterestRate());
B.welcomeMsg();
System.out.println(Bank.getPPFInterestRate());
}
}
|
package com.tencent.mm.g.a;
import android.content.Context;
import android.widget.ImageView;
import com.tencent.mm.protocal.c.vx;
import com.tencent.mm.sdk.b.b;
public final class fw extends b {
public a bOx;
public b bOy;
public static final class a {
public long bJA;
public ImageView bOA;
public int bOB;
public boolean bOC = false;
public boolean bOD = false;
public boolean bOE = true;
public vx bOz;
public Context context;
public int height;
public int maxWidth;
public int opType = -1;
public int width;
}
public fw() {
this((byte) 0);
}
private fw(byte b) {
this.bOx = new a();
this.bOy = new b();
this.sFm = false;
this.bJX = null;
}
}
|
package edu.asu.mldelaro.testbed;
public class Main {
public static void main(String[] args) {
//AAAA
//BBBB
//CCCC
//DDDD
//EEEE
//FFFF
//GGGG
}
}
|
package exterminatorJeff.undergroundBiomes.api;
import Zeno410Utils.*;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
*
* @author Zeno410
*/
public final class UndergroundBiomesSettings extends Settings {
public static Streamer<UndergroundBiomesSettings> streamer(final UndergroundBiomesSettings setting) {
return new Streamer<UndergroundBiomesSettings>() {
@Override
public UndergroundBiomesSettings readFrom(DataInput input) throws IOException {
setting.readFrom(input);
return setting;
}
@Override
public void writeTo(UndergroundBiomesSettings written, DataOutput output) throws IOException {
written.writeTo(output);
}
};
}
private final Category blockCategory = category("block");
private final Category itemCategory = category("item");
public final Mutable<Boolean> addOreDictRecipes = this.general().booleanSetting(
"oreDictifyStone", true, "Modify all recipes to include Underground Biomes blocks");
public final Mutable<Boolean> vanillaStoneBiomes = this.general().booleanSetting(
"vanillaStoneBiomes", false, "Will cause sharp biome transitions if changed while playing the same world");
public final Mutable<Boolean> buttonsOn = this.general().booleanSetting(
"UndergroundBiomesButtons", true, "Provide Buttons for non-brick Underground Biomes blocks");
public final Mutable<Boolean> stairsOn = this.general().booleanSetting(
"UndergroundBiomesStairs", true, "Provide Stairs for Underground Biomes blocks");
public final Mutable<Boolean> wallsOn= this.general().booleanSetting(
"UndergroundBiomesWalls", true, "Provide Walls for Underground Biomes blocks");
public final Mutable<Boolean> harmoniousStrata= this.general().booleanSetting(
"HarmoniousStrata", false, "Avoid jarring strata transitions");
public final Mutable<Boolean> replaceCobblestone= this.general().booleanSetting(
"replaceCobblestone", true, "Swap vanilla cobble and slabs with Underground Biomes where appropriate, plus some village changes");
public final Mutable<Boolean> imposeUBStone = this.general().booleanSetting(
"ImposeUBStone", "Impose UB stone on other mods specially programmed for (currently Highlands)", true);
public final Mutable<Boolean> replaceVillageGravel= this.general().booleanSetting(
"ReplaceVillageGravel", false, "Replace village gravel with brick");
public final Mutable<Boolean> crashOnProblems= this.general().booleanSetting(
"CrashOnProblems", false, "Crash rather than try to get by when encountering problems");
public final Mutable<Boolean> clearVarsForRecursiveGeneration = this.general().booleanSetting(
"clearVarsForRecursiveGeneration", false, "Clear the world var in BiomeGenBase for recursive generation");
public final Mutable<Boolean> forceConfigIds= this.general().booleanSetting(
"ForceConfigIds", false, "(for worlds created pre-1.7) Force IDs to config values");
public final Mutable<Boolean> ubOres = this.general().booleanSetting(
"UBifyOres", true, "Convert ores to have Underground Biomes stone backgrounds");
public final Mutable<Integer> biomeSize = this.general().intSetting(
"biomeSize", 3, "Warning: exponential");
public final Mutable<String> excludeDimensions = this.general().stringSetting(
"excludeDimensionIDs", "-1,1", "Comma-separated list of dimension IDs, used only if include list is *");
public final Mutable<String> includeDimensions = this.general().stringSetting(
"includeDimensionIDs", "*", "Comma-separated list of dimension IDs, put * to use exclude list");
public final Mutable<Integer> generateHeight = this.general().intSetting(
"generateHeight", 256, "Highest block to generated UB stone for");
public final Mutable<Integer> vanillaStoneCrafting = this.general().intSetting(
"vanillaStoneCrafting", 4, "0 = none; 1 = one rock; 2 = with redstone; 3 = 2x2 stone, lose 3; 4 = 2x2 stone");
public final Mutable<Double> hardnessModifier = this.general().doubleSetting(
"hardnessModifier", 1.5, "Increase to make stone longer to mine. Normal is 1.5");
public final Mutable<Double> resistanceModifier = this.general().doubleSetting(
"resistanceModifier", 6.0, "Increase to make stone more resistant to explosions. Normal is 6.0");
// Item read from block category to be backwards-compatible
public final Mutable<Boolean> ubActive = this.general().booleanSetting(
"undergroundBiomesActive", "True if Underground Biomes is supposed to replace stones", true);
public final Mutable<Boolean> dimensionSpecificSeeds = this.general().booleanSetting(
"DimensionSpecificSeeds", false,"Use different seeds in different dimensions");
public final Mutable<Boolean> inChunkGeneration = this.general().booleanSetting(
"InChunkGeneration", true,"Change stones during chunk generation");
public final Mutable<String> inChunkGenerationExclude = this.general().stringSetting(
"inChunkDimensionExclusions", "-1,1", "Comma-separated list of dimension to only use old decoration-phase generation, used only if inclusion list is *");
public final Mutable<String> inChunkGenerationInclude = this.general().stringSetting(
"inChunkDimensionInclusions", "0", "Comma-separated list of dimension IDs to allow new chunk-phase decoration, put * to use exclusion list");
public final Mutable<Integer> ligniteCoalID = this.blockCategory.intSetting("Lignite Item ID:", 5500);
public final Mutable<Integer> fossilPieceID = this.itemCategory.intSetting("fossilPiece", 5501);
public final Mutable<Integer> igneousStoneID = this.blockCategory.intSetting("Igneous Stone ID:", 209);
public final Mutable<Integer> metamorphicStoneID = this.blockCategory.intSetting("Metamorphic Stone ID:", 210);
public final Mutable<Integer> sedimentaryStoneID = this.blockCategory.intSetting("Sedimentary Stone ID:", 211);
public final Mutable<Integer> igneousCobblestoneID = this.blockCategory.intSetting("Igneous Cobblestone ID:", 200);
public final Mutable<Integer> metamorphicCobblestoneID = this.blockCategory.intSetting("Metamorphic Cobblestone ID:", 201);
public final Mutable<Integer> igneousStoneBrickID = this.blockCategory.intSetting("Igneous Brick ID:", 202);
public final Mutable<Integer> metamorphicStoneBrickID = this.blockCategory.intSetting("Metamorphic Brick ID:", 203);
public final Mutable<Integer> igneousBrickSlabHalfID = this.blockCategory.intSetting("Igneous Stone Brick Slab ID (half):", 205);
public final Mutable<Integer> igneousBrickSlabFullID = this.blockCategory.intSetting("Igneous Stone Brick Slab ID (full):", 206);
public final Mutable<Integer> metamorphicBrickSlabHalfID = this.blockCategory.intSetting("Metamorphic Stone Brick Slab ID (half):", 207);
public final Mutable<Integer> metamorphicBrickSlabFullID = this.blockCategory.intSetting("Metamorphic Stone Brick Slab ID (full):", 208);
public final Mutable<Integer> igneousStoneSlabHalfID = this.blockCategory.intSetting("Igneous Stone Slab ID (half):", 215);
public final Mutable<Integer> igneousStoneSlabFullID = this.blockCategory.intSetting("Igneous Stone Slab ID (full):", 216);
public final Mutable<Integer> metamorphicStoneSlabHalfID = this.blockCategory.intSetting("Metamorphic Stone Slab ID (half):", 217);
// ID 2012 - 2014 used by constructs
public final Mutable<Integer> metamorphicStoneSlabFullID = this.blockCategory.intSetting("Metamorphic Stone Slab ID (full):", 218);
public final Mutable<Integer> igneousCobblestoneSlabHalfID = this.blockCategory.intSetting("Igneous Stone Cobblestone Slab ID (half):", 219);
public final Mutable<Integer> igneousCobblestoneSlabFullID = this.blockCategory.intSetting("Igneous Stone Cobblestone Slab ID (full):", 220);
public final Mutable<Integer> metamorphicCobblestoneSlabHalfID = this.blockCategory.intSetting("Metamorphic Stone Cobblestone Slab ID (half):", 221);
public final Mutable<Integer> metamorphicCobblestoneSlabFullID = this.blockCategory.intSetting("Metamorphic Stone Cobblestone Slab ID (full):", 222);
public final Mutable<Integer> sedimentaryStoneSlabHalfID = this.blockCategory.intSetting("Sedimentary Stone Slab ID (half):", 223);
public final Mutable<Integer> sedimentaryStoneSlabFullID = this.blockCategory.intSetting("Sedimentary Stone Slab ID (full):", 224);
public final Mutable<Integer> stoneStairID = this.blockCategory.intSetting("Universal Biomes Stairs ID:", 212);
public final Mutable<Integer> stoneWallID = this.blockCategory.intSetting("Universal Biomes Wall ID:", 213);
public final Mutable<Integer> stoneButtonID = this.blockCategory.intSetting("Universal Biomes Button ID:", 214);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.