text stringlengths 10 2.72M |
|---|
package com.prokarma.reference.architecture.data;
public class SharedPreferencesConstants {
public static final String KEY_SEARCH_HISTORY = "user_search_keyword";
}
|
package com.freejavaman;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MyPlayer extends Activity implements
MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener,
MediaPlayer.OnPreparedListener
{
//多媒體播放元件
private MediaPlayer mediaPlayer;
Button loadBtn, startBtn, pauseBtn, stopBtn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//取得按鈕物件實體
loadBtn = (Button)this.findViewById(R.id.loadBtn);
startBtn = (Button)this.findViewById(R.id.startBtn);
pauseBtn = (Button)this.findViewById(R.id.pauseBtn);
stopBtn = (Button)this.findViewById(R.id.stopBtn);
//禁能按鈕
startBtn.setEnabled(false);
pauseBtn.setEnabled(false);
stopBtn.setEnabled(false);
//委任載入按鈕
loadBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
try {
//建立多媒體播放元件實體
mediaPlayer = new MediaPlayer();
Log.v("mediaTest", "media player instanced");
//設定音檔資料來源
mediaPlayer.setDataSource("/sdcard/onepiece.mp3");
Log.v("mediaTest", "load file");
//委任事件
mediaPlayer.setOnCompletionListener(MyPlayer.this);
mediaPlayer.setOnErrorListener(MyPlayer.this);
mediaPlayer.setOnPreparedListener(MyPlayer.this);
Log.v("mediaTest", "delegate to listener");
//進行非同步的載入
mediaPlayer.prepareAsync();
Log.v("mediaTest", "prepare async");
} catch (Exception e) {
Log.e("mediaTest", "load error:" + e);
}
}
});
//委任播放按鈕
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.start();
startBtn.setEnabled(false);
Log.v("mediaTest", "start play");
}
}
});
//委任暫停按鈕
pauseBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
startBtn.setEnabled(true);
Log.v("mediaTest", "pause play");
}
}
});
//委任停止按鈕
stopBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mediaPlayer != null) {
mediaPlayer.stop();
try {
mediaPlayer.prepare();
} catch (Exception e) {
Log.v("mediaTest", "stop play (call prepare)");
}
Log.v("mediaTest", "stop play");
}
}
});
}
//繼承自Activity
protected void onPause() {
super.onPause();
//釋放MediaPlayer
if (mediaPlayer != null)
mediaPlayer.release();
}
//實作MediaPlayer.OnPreparedListener
public void onPrepared(MediaPlayer mp) {
//完成檔案載入之後, 致能所有按鈕
startBtn.setEnabled(true);
pauseBtn.setEnabled(true);
stopBtn.setEnabled(true);
Log.v("mediaTest", "enable all button");
}
//實作MediaPlayer.OnErrorListener
public boolean onError(MediaPlayer mp, int arg1, int arg2) {
Log.v("mediaTest", "onError");
return false;
}
//實作MediaPlayer.OnCompletionListener
public void onCompletion(MediaPlayer mp) {
Log.v("mediaTest", "play completed");
}
} |
package kyle.game.besiege.panels;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable;
import kyle.game.besiege.Assets;
import java.util.HashMap;
// Table at the top of the panel. Contains a title, columns, etc.
public class TopTable extends Table {
private final float PAD = 10;
private final float MINI_PAD = 5;
private final float NEG = -5;
private final float NEG_MINI = -2;
// for health bar only
private final int r = 3;
private final String tablePatch = "grey-d9";
private final String redPatch = "red9";
private final String greenPatch = "green9";
private Table health;
private Table red;
private Table green;
private LabelStyle ls;
private LabelStyle lsTitle;
private LabelStyle lsSubtitle;
private Label title;
private float width;
private HashMap<String, Label> labels = new HashMap<String, Label>();
// Optional green/red bar to add to the table,
private Table greenBar;
// To determine proper padding.
boolean wasLastSmallLabel = false;
// in a 2 column table, this means that the next label added will be on the left. if false, will be on the right.
private boolean nextIsLeft = true;
// Subtitle count can be 0-3
public TopTable() {
lsTitle = new LabelStyle();
lsTitle.font = Assets.pixel24;
lsSubtitle = new LabelStyle();
lsSubtitle.font = Assets.pixel18;
ls = new LabelStyle();
ls.font = Assets.pixel16;
// previously padded with neg
this.defaults().padTop(NEG_MINI).left();
// this.debug();
this.width = SidePanel.WIDTH-PAD*2;
this.add().colspan(2).width(width/2);
this.add().colspan(2).width(width/2);
this.row();
}
// Subtitle is a single, centered label (it is the value).
public void addSubtitle(String key, String label, LabelStyle ls, InputListener listener) {
Label subtitle = new Label(label, lsSubtitle);
subtitle.setAlignment(0,0);
subtitle.setWidth(SidePanel.WIDTH-PAD*2-MINI_PAD*2);
subtitle.setWrap(true);
// This isn't changing line spacing
subtitle.getStyle().font.getData().ascent *= 0.2f;
if (ls != null)
subtitle.setStyle(ls);
if (listener != null)
subtitle.addListener(listener);
labels.put(key, subtitle);
this.add(subtitle).colspan(4).padBottom(0).fillX().expandX();
this.row();
wasLastSmallLabel = false;
}
public void addSubtitle(String key, String label, InputListener listener) {
addSubtitle(key, label, null, listener);
}
public void addSubtitle(String key, String label) {
addSubtitle(key, label, null);
}
public void addSmallLabel(String key, String label, InputListener listener) {
Label constantLabel = new Label(label, ls);
Label value = new Label("", ls);
float padTop = 0;
if (wasLastSmallLabel) padTop = NEG;
if (nextIsLeft) {
this.add(constantLabel).padLeft(MINI_PAD).left().padTop(padTop).fill(true, false);
} else {
this.add(constantLabel).padLeft(PAD).left().padTop(padTop).fill(true, false);
wasLastSmallLabel = true;
}
this.add(value).padTop(padTop).fill(true, false);
labels.put(key+"LABEL", constantLabel);
labels.put(key, value);
if (nextIsLeft) {
nextIsLeft = false;
} else {
nextIsLeft = true;
this.row();
}
if (listener != null) {
// TODO somehow have these listeners "overlap"
// could use a container table for these two guys. only problem is it means the parent table boxes might not be lined up perfectly.
constantLabel.addListener(listener);
value.addListener(listener);
}
}
// Big label has a fixed label and a value (e.g. "Troops: 20". It fits two rows across.
public void addSmallLabel(String key, String label) {
addSmallLabel(key, label, null);
}
// Big label has a fixed label and a value (e.g. "Troops: 20". It fits one row across.
public void addBigLabel(String key, String label) {
Table table = new Table();
Label constantLabel = new Label(label, ls);
Label value = new Label("", ls);
value.setWrap(false);
labels.put(key, value);
table.add(constantLabel).padLeft(MINI_PAD).expandX();
float afterColon = 5;
table.add(value).expandX().left().padLeft(afterColon);
float padTop = 0;
if (wasLastSmallLabel) padTop = NEG;
this.add(table).colspan(4).expandX().padTop(padTop);
this.row();
wasLastSmallLabel = true;
}
public void addTable(Table table) {
this.add(table).colspan(4).fillX().expandX().padTop(MINI_PAD)
.padBottom(MINI_PAD);
this.row();
}
public void addGreenBar() {
health = new Table();
red = new Table();
red.setBackground(new NinePatchDrawable(new NinePatch(Assets.atlas.findRegion(redPatch), r,r,r,r)));
green = new Table();
green.setBackground(new NinePatchDrawable(new NinePatch(Assets.atlas.findRegion(greenPatch), r,r,r,r)));
this.add(health).colspan(4).padTop(MINI_PAD).padBottom(MINI_PAD);
this.row();
wasLastSmallLabel = false;
}
public void updateGreenBar(double percentage) {
health.clear();
float totalWidth = SidePanel.WIDTH - PAD;
health.add(green).width((float) (totalWidth*percentage));
if (totalWidth*(1-percentage) > 0)
health.add(red).width((float) (totalWidth*(1-percentage)));
}
public void update(String key, String newValue) {
update(key, newValue, null);
}
public void update(String key, String newValue, InputListener listener) {
if (!labels.containsKey(key)) {
throw new java.lang.AssertionError("No key found for ui element: " + key);
}
Label value = labels.get(key);
value.setText(newValue);
if (listener != null) {
value.clearListeners();
value.addListener(listener);
}
}
public void update(String key, String newValue, InputListener listener, Color color) {
if (!labels.containsKey(key)) {
throw new java.lang.AssertionError();
}
Label value = labels.get(key);
value.setText(newValue);
if (color != null) value.setColor(color);
if (listener != null) {
value.clearListeners();
value.addListener(listener);
}
}
public void updateLabel(String key, String newLabel) {
key = key + "LABEL";
if (!labels.containsKey(key)) {
throw new java.lang.AssertionError();
}
Label value = labels.get(key);
value.setText(newLabel);
}
public void updateTitle(String titleText, InputListener listener, Color color) {
if (title == null) {
title = new Label("", lsTitle);
title.setAlignment(0,0);
title.setWrap(true);
title.setWidth(SidePanel.WIDTH-PAD*2-MINI_PAD*2);
this.add(title).colspan(4).fillX().expandX().padBottom(NEG);
this.row();
}
title.setText(titleText);
if (color != null)
title.setColor(color);
if (listener != null) {
title.addListener(listener);
}
}
public void updateTitle(String titleText, InputListener listener) {
updateTitle(titleText, listener, null);
}
}
|
package com.tyjradio.jrdvoicerecorder.utils;
import java.util.ArrayList;
public class OpusUtils {
static{
System.loadLibrary("opusJni");
}
public native long createEncoder(int sampleRateInHz, int channelConfig, int complexity);
public native long createDecoder(int sampleRateInHz, int channelConfig);
public native int encode(long handle, short[] lin, int offset, byte[] encoded);
public native int decode(long handle, byte[] encoded, short[] lin);
public native void destroyEncoder(long handle);
public native void destroyDecoder(long handle);
}
|
package com.techelevator.shopping.dao;
import java.util.List;
import com.techelevator.shopping.model.Item;
public interface IItemDao {
public List<Item> list();
public Item create(Item item);
public Item read(int id);
public Item update(Item item);
public void delete(int id);
}
|
package com.smxknife.java.ex31;
/**
* @author smxknife
* 2020/7/27
*/
public class EqualsDemo {
public static void main(String[] args) {
Obj obj1 = new Obj();
Obj obj2 = new Obj();
System.out.println(obj1 == obj2);
}
static class Obj {
int age;
@Override
public boolean equals(Object obj) {
return this.age == ((Obj)obj).age;
}
}
}
|
// Sun Certified Java Programmer
// Chapter 5, P386
// Flow Control, Exceptions, and Assertions
class ValidAssert {
}
|
package com.yinghai.a24divine_user.module.divine.book;
import android.content.Context;
import android.view.View;
import com.example.fansonlib.base.BaseDataAdapter;
import com.example.fansonlib.base.BaseHolder;
import com.yinghai.a24divine_user.R;
import com.yinghai.a24divine_user.bean.BusinessBean;
import com.yinghai.a24divine_user.callback.OnAdapterListener;
/**
* Created by chenjianrun on 2017/10/27.
* 描述:占卜预约列表 adapter
*/
public class BusinessListAdapter extends BaseDataAdapter<BusinessBean.DataBean.TfBusinessListBean> {
private OnAdapterListener mListener;
public void setOnAdapterListener(OnAdapterListener listener){
mListener = listener;
}
public BusinessListAdapter(Context context) {
super(context);
}
@Override
public int getLayoutRes(int i) {
return R.layout.master_divine_detail_bottom;
}
@Override
public void bindCustomViewHolder(BaseHolder holder, final int position) {
holder.setText(R.id.tv_divine_type, getItem(position).getBName());
holder.setText(R.id.tv_divine_descripe, getItem(position).getBIntroduction());
holder.setText(R.id.tv_divine_price, getItem(position).getBPrice()/100 + context.getString(R.string.price_every));
holder.setText(R.id.tv_divine_has_num, context.getString(R.string.have_benn) + getItem(position).getBDeals() + context.getString(R.string.consult));
holder.setOnClickListener(R.id.rootView, new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mListener != null) {
mListener.clickItem(getItem(position));
}
}
});
}
}
|
package eu.ase.ro.dam.subway_route.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import eu.ase.ro.dam.subway_route.R;
import eu.ase.ro.dam.subway_route.util_interface.Const;
public class LoginActivity extends AppCompatActivity {
TextInputEditText email;
TextInputEditText password;
Button btnLogin;
Intent intent;
FirebaseAuth mAuth;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
initView();
if(myEmail() != null){
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
}
}
private void initView(){
email = findViewById(R.id.login_et_email);
password = findViewById(R.id.login_et_password);
btnLogin = findViewById(R.id.login_btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(infoValidation()){
login();
}
}
});
}
private void login(){
final String mail = email.getText().toString().trim();
final String pass = password.getText().toString().trim();
mAuth.signInWithEmailAndPassword(mail, pass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
rememberMe(mail, pass);
intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), R.string.errLogin, Toast.LENGTH_SHORT).show();
}
}
});
}
public void rememberMe(String email, String password){
sharedPreferences = getSharedPreferences(Const.SHARED_PREF_LOG, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Const.SP_MAIL_KEY, email);
editor.putString(Const.SP_PASS_KEY, password);
editor.apply();
}
public String myEmail(){
sharedPreferences = getSharedPreferences(Const.SHARED_PREF_LOG, Context.MODE_PRIVATE);
return sharedPreferences.getString(Const.SP_MAIL_KEY, null);
}
private boolean infoValidation(){
if(email.getText() == null || email.getText().toString().trim().isEmpty()){
Toast.makeText(getApplicationContext(), R.string.err_mail, Toast.LENGTH_LONG).show();
return false;
}
if(!Patterns.EMAIL_ADDRESS.matcher(email.getText().toString().trim()).matches()){
Toast.makeText(getApplicationContext(), R.string.errValidEmail, Toast.LENGTH_LONG).show();
return false;
}
if(password.getText() == null || password.getText().toString().trim().isEmpty() || password.getText().toString().trim().length()<7){
Toast.makeText(getApplicationContext(), R.string.err_pass, Toast.LENGTH_LONG).show();
return false;
}
return true;
}
}
|
package dk.aau.models.database;
//Importing classes for database communication
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseManipulator {
/**
* method for establishing a connection to AAU database
* @return a connection if successful else return null
*/
public static Connection getConnection(){
Connection conn = null;
try {
// Define the DB communication driver
Class.forName("com.mysql.cj.jdbc.Driver");
try{
// Set user, password, and adress to database
conn = DriverManager.getConnection(DataBaseDetails.host, DataBaseDetails.username, DataBaseDetails.password);
} catch (SQLException sqlex){
System.out.println(sqlex.getMessage());
}
} catch (ClassNotFoundException ex){
System.out.println(ex.getMessage());
}
return conn;
}
/**
* Method for fetching information from database
* @param queryable - any class implementing the interface Queryable can be used here
* @param sqlStatement must be a SQL-statenent which return a result set
*/
public static void executeQueryWithResultSet(Queryable queryable, String sqlStatement){
// Establish the connection
Connection conn = getConnection();
Statement stmt = null;
ResultSet rs = null;
if (conn != null){
try{
// Creates a Statement object for sending SQL statements to the database.
stmt = conn.createStatement();
// Executes the given SQL statement, which returns a single ResultSet object.
rs = stmt.executeQuery(sqlStatement);
// Make inserted class process the resultset
queryable.processResultSet(rs);
}
catch (SQLException sqlex){
System.out.println(sqlex.getMessage());
}
finally {
// Releases this ResultSet object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.
try{
rs.close();
}
catch (SQLException sqlex){
System.out.println(sqlex.getMessage());
}
// Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.
try{
stmt.close();
}
catch (SQLException sqlex){
System.out.println(sqlex.getMessage());
}
}
}
}
/**
* method for updating database, no Resultset return
* @param sqlStatement
*/
public static void updateDataBase(String sqlStatement){
Connection conn = getConnection();
Statement stmt = null;
if (conn != null){
try{
stmt = conn.createStatement();
stmt.executeUpdate(sqlStatement);
}
catch (SQLException sqlex){
System.out.println(sqlex.getMessage());
}
finally {
try{
stmt.close();
}
catch (SQLException sqlex){
System.out.println(sqlex.getMessage());
}
}
}
}
} |
package com.sixmac.dao;
import com.sixmac.entity.Activity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* Created by Administrator on 2016/5/19 0019 上午 10:08.
*/
public interface ActivityDao extends JpaRepository<Activity, Long>, JpaSpecificationExecutor<Activity> {
} |
package com.example.gwt;
public class Cliente {
int codigo;
String nome;
String email;
String telefone;
String end;
String cpf;
public Cliente(){}
public Cliente(int _codigo, String _nome, String _email, String _telefone, String _end, String _cpf){
this.codigo = _codigo;
this.nome = _nome;
this.email = _email;
this.telefone = _telefone;
this.end = _end;
this.cpf = _cpf;
}
public Cliente(String _nome, String _email, String _telefone, String _end, String _cpf){
this.nome = _nome;
this.email = _email;
this.telefone = _telefone;
this.end = _end;
this.cpf = _cpf;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
}
|
/**
* WebSocket services, using Spring Websocket.
*/
package com.africa.gateway.web.websocket;
|
package com.lance.common;
//导入必需的 java 库
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
/**
* Servlet implementation class AdminUserController
*/
@WebServlet("/LoginFilter")
public class LoginFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
// 获取初始化参数
String site = config.getInitParameter("Site");
// 输出初始化参数
System.out.println("网站名称: " + site);
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws ServletException, IOException {
// 输出站点名称
System.out.println("站点网址:http://www.runoob.com");
// 把请求传回过滤链
chain.doFilter(request, response);
}
public void destroy() {
System.out.println("站点网址:http://www.runoob.com");
/* 在 Filter 实例被 Web 容器从服务移除之前调用 */
}
}
|
package com.skarim.countryservice.servioces;
import com.skarim.countryservice.entity.CountryEntity;
import java.util.List;
public interface ICountryService {
CountryEntity save(CountryEntity countryEntity);
// List<CountryEntity> findAll();
CountryEntity findById(Integer id);
List<CountryEntity> delete(Integer id);
}
|
package com.stem.service;
import com.stem.core.interfaces.BasicService;
import com.stem.entity.TigerNaming;
import com.stem.entity.TigerNamingExample;
public interface TigerNamingService extends BasicService<TigerNamingExample, TigerNaming> {
}
|
package prac;
public abstract class Abst {
int a;
int b=20;
public int sum(int a, int b) {
int sum = a+b;
return sum;
}
abstract public void sub(int a, int b);
}
|
package com.dbs.spring.capstoneproject.model;
import java.time.LocalDate;
import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int tid;
@ManyToOne
@JoinColumn(name="buy_custodianid")
private Custodian buy_custodian;
@ManyToOne
@JoinColumn(name="sell_custodianid")
private Custodian sell_custodian;
@ManyToOne
@JoinColumn(name="instrumentid")
private Instruments instrument;
@ManyToOne
@JoinColumn(name="buyerid")
private Client buyer;
@ManyToOne
@JoinColumn(name="sellerid")
private Client seller;
private int quantity;
private int price;
private LocalDateTime date;
public int getTid() {
return tid;
}
public void setTid(int tid) {
this.tid = tid;
}
public Custodian getBuy_custodian() {
return buy_custodian;
}
public void setBuy_custodian(Custodian buy_custodian) {
this.buy_custodian = buy_custodian;
}
public Custodian getSell_custodian() {
return sell_custodian;
}
public void setSell_custodian(Custodian sell_custodian) {
this.sell_custodian = sell_custodian;
}
public Instruments getInstrument() {
return instrument;
}
public void setInstrument(Instruments instrument) {
this.instrument = instrument;
}
public Client getBuyer() {
return buyer;
}
public void setBuyer(Client buyer) {
this.buyer = buyer;
}
public Client getSeller() {
return seller;
}
public void setSeller(Client seller) {
this.seller = seller;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public LocalDateTime getDate() {
return date;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
public Transaction() {
//super();
// TODO Auto-generated constructor stub
}
public Transaction(int tid, Custodian buy_custodian, Custodian sell_custodian, Instruments instrument, Client buyer,
Client seller, int quantity, int price, LocalDateTime date) {
super();
this.tid = tid;
this.buy_custodian = buy_custodian;
this.sell_custodian = sell_custodian;
this.instrument = instrument;
this.buyer = buyer;
this.seller = seller;
this.quantity = quantity;
this.price = price;
this.date = date;
}
}
|
package com.example.demorestrepo;
import com.example.demorestrepo.entity.CustomerGroup;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface CustomerGroupRepository extends CrudRepository<CustomerGroup, Long> {
Optional<CustomerGroup> findByGroupName(@Param("name")String groupName);
}
|
package hhc.common.utils.date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CommonDay {
static String initDate = "2016-09-26 00:00:00";
static int initIntTime = 1474992000-3600*24*2;
public static int intDay = 3600*24;
public static int getNowTime()
{
return initIntTime+secondBetween();
}
public static int getStartTime()
{
return (secondBetween()/intDay)*3600*24+initIntTime;
}
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
String date = "2016-10-26 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date smdate = null;
try {
smdate = sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(CommonDay.getTime(smdate));
}
/**
* 计算两个日期之间相差的天数
*
* @param smdate
* 较小的时间
* @param bdate
* 较大的时间
* @return 相差天数
* @throws ParseException
*/
public static int secondBetween() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date smdate = null;
try {
smdate = sdf.parse(initDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date nowDate = new Date();
try {
smdate = sdf.parse(sdf.format(smdate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(nowDate);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000);
return Integer.parseInt(String.valueOf(between_days));
}
/**
* 计算两个日期之间相差的天数
*
* @param smdate
* 较小的时间
* @param bdate
* 较大的时间
* @return 相差天数
* @throws ParseException
*/
public static int getTime(Date nowDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date smdate = null;
try {
smdate = sdf.parse(initDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Date nowDate = new Date();
try {
smdate = sdf.parse(sdf.format(smdate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(nowDate);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000);
return Integer.parseInt(String.valueOf(between_days))+initIntTime;
}
public static String getDay() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date nowDate = new Date();
return sdf.format(nowDate);
//return nowDate.toString();
//return Integer.parseInt(String.valueOf(between_days));
}
}
|
package com.shopify.order.popup;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.databind.JsonNode;
import com.shopify.common.RestData;
import com.shopify.common.RestService;
import com.shopify.common.util.UtilFunc;
import com.shopify.mapper.OrderMapper;
import com.shopify.mapper.SettingMapper;
import com.shopify.setting.ShippingCompanyData;
@Service
@Transactional
public class OrderPopupRestService {
private Logger LOGGER = LoggerFactory.getLogger(OrderPopupRestService.class);
@Value("${Order.Variants}") private String variantsUrl;
@Value("${Order.Inventory}") private String inventoryUrl;
@Value("${Order.ProductLinks}") private String productUrl;
@Autowired private RestService restService;
@Autowired private SettingMapper settingMapper;
@Autowired private OrderMapper orderMapper;
private List<Pair> pairList = new ArrayList<>();
/**
* shopify api rest service
* @return
*/
@PostConstruct
public void postConstruct() {
List<ShippingCompanyData> list = settingMapper.selectVolumeticCourierCompany();
Map<Integer, List<ShippingCompanyData>> divisorMap = list.stream().collect(Collectors.groupingBy(ShippingCompanyData::getDivisor));
for( Entry<Integer, List<ShippingCompanyData>> e : divisorMap.entrySet() ) {
int divisor = e.getKey();
int divisorCount = e.getValue().size();
this.pairList.add(new Pair(divisor, divisorCount) );
}
}
public List<Map<String, Object>> getHscode(List<Map<String, Object>> mapList) {
// shopify api 호출용 httpheaders 와 domain 가져오는 방법
// 1. session 에서 가져올 때
// String domain = UtilFunc.getShopDomain(sess);
// HttpHeaders httpHeaders = UtilFunc.generateHeader(sess);
String domain = null;
HttpHeaders httpHeaders = null;
for( Map<String, Object> map : mapList ) {
String hscode = "";
// shopify api 호출용 httpheaders 와 domain 가져오는 방법
// 2. shop_idx 가 주어졌을 때
// hscode 가져오는 data 는 무조건 동일한 shop_idx 에 대해서만 processing 되므로,
// domain 과 httpHeaders 는 단 한번만 가져오도록 한다.
if ( domain == null || httpHeaders == null ) {
String shopIdx = (String) map.get("shopIdx");
RestData restData = restService.getRestDataFromShopIdx(shopIdx);
domain = restData.getShopData().getDomain();
httpHeaders = restData.getHttpHeaders();
}
String goodsCode = (String) map.get("goodsCode");
// 1. orders
String url = String.format(this.variantsUrl, domain, goodsCode);
JsonNode node = restService.getRestTemplate(httpHeaders, url);
if ( node == null ) {
continue;
}
List<JsonNode> items = node.findValues("variants");
for( JsonNode item : items ) {
String inventoryId = item.findValue("inventory_item_id").asText();
// 2. orders
url = String.format(this.inventoryUrl, domain, inventoryId);
node = restService.getRestTemplate(httpHeaders, url);
if ( node == null ) {
continue;
}
hscode = UtilFunc.findPath(node, "harmonized_system_code");
if ( ! org.apache.commons.lang.StringUtils.isBlank(hscode) ) {
break;
}
}
map.put("hscode", hscode);
}
return mapList;
}
public String getProductHandleFullUrl(String shopIdx, String productId) {
LOGGER.debug(">>getProductHandleFullUrl---------------------------------------------------");
String url = "";
String urlProductLink = "";
String handle = ""; // 상품의 handle -> SEO 명
String domain = null;
HttpHeaders httpHeaders = null;
if ( domain == null ) {
RestData restData = restService.getRestDataFromShopIdx(shopIdx);
domain = restData.getShopData().getDomain();
LOGGER.debug(">>DOMAIN:" + domain);
httpHeaders = restData.getHttpHeaders();
}
LOGGER.debug("===============[START]=================");
url = String.format(this.productUrl, domain, productId);
JsonNode node = restService.getRestTemplate(httpHeaders, url);
if(node != null)
{
List<JsonNode> productitems = node.findValues("product");
for( JsonNode item : productitems ) {
handle = item.findValue("handle").asText();
LOGGER.debug(">>handle:" + handle);
}
}
if(!"".equals(handle))
urlProductLink = "https://" + domain + "/products/" + handle;
LOGGER.debug(">urlProductLink:" + urlProductLink);
LOGGER.debug("==============[END]==================");
return urlProductLink;
}
public List<OrderCourierDataWrapper> selectVolumeticCourierList(String email, String buyerCountryCode, String locale, String weight, String length, String width, String height){
int weightValue = UtilFunc.parseInt(weight);
OrderCourierData courier = new OrderCourierData();
courier.setEmail(email);
courier.setLocale(locale == null ? "ko" : locale);
courier.setNationCode(buyerCountryCode);
courier.setNowDate(UtilFunc.today());
List<VolumeticPair> volumeticPairList = new ArrayList<>();
int volumeticWeight = Integer.parseInt(length) * Integer.parseInt(width) * Integer.parseInt(height);
for( Pair pair : this.pairList ) {
VolumeticPair volumeticPair = new VolumeticPair(pair, volumeticWeight); // 나눗셈은 constructor 안에서 발생하므로 먼저 new 를 함
if ( weightValue < volumeticPair.getWeight() ) { // 부피질량이 포장질량보다 클 경우에만 부피질량을 계산함
volumeticPairList.add(volumeticPair);
}
}
List<OrderCourierDataWrapper> list = null;
Set<OrderCourierDataWrapper> set = new HashSet<>();
if ( volumeticPairList.size() > 0 ) {
// set 는 key 가 이미 존재하면 add 하지 않으므로, volumetic 을 먼저 실행함
for( VolumeticPair volumeticPair : volumeticPairList ) {
// case-1 : 부피질량을 계산하는 배송사만 부피질량으로 계산하여 set 에 추가한 후,
courier.setWeight(volumeticPair.getWeight());
courier.setDivisor(volumeticPair.getDivisor());
List<OrderCourierDataWrapper> added = orderMapper.selectWeightCourierListVolumeticMin(courier);
set.addAll(added);
if ( added.size() != volumeticPair.getDivisorCount() ) {
// 주어진 무게를 기준으로 min query 값이 없으면, 최대무게인 부피중량을 가져온다.
added = orderMapper.selectWeightCourierListVolumeticMax(courier);
set.addAll(added); // 빠진 것은 여기서 다시 추가함
}
}
}
// case-2 : 전체 배송사를 총 무게로 계산하고 ( divisor 가 6, 5, 166 등 여러 case 가 있으므로, 무조건 전체를 계산한다. )
courier.setWeight(weightValue);
set.addAll( orderMapper.selectWeightCourierListWeightMin(courier) );
List<OrderCourierDataWrapper> maxList = orderMapper.selectWeightCourierListWeightMax(courier);
if ( set.size() != maxList.size() ) {
set.addAll( maxList ); // min 에서 값이 나오지 않을 경우, max 값으로 채움, 이미 있으면 무시됨
}
// SQL 에서 사용한 field 로 sort 함
list = new LinkedList<>(set);
list.sort( Comparator.comparing(OrderCourierDataWrapper::getServiceCode).thenComparing(OrderCourierDataWrapper::getNationCode));
// list.forEach(UtilFunc::printValue);
return list;
}
} |
package com.weicent.android.csma.support;
import android.content.Context;
import com.ab.util.AbStrUtil;
/**
* Created by admin on 2016/4/10.
*/
public class MyStringTool {
public static boolean isNullToToast(Context context,String c,String t) {
if (AbStrUtil.isEmpty(c)) {
T.showShort(context,t+"不为空");
return true;
}
return false;
}
}
|
package com.tencent.mm.plugin.profile.ui;
import android.text.TextUtils;
import com.tencent.mm.model.am;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.q;
import com.tencent.mm.model.s;
import com.tencent.mm.plugin.account.b;
import com.tencent.mm.plugin.account.friend.a.ao;
import com.tencent.mm.plugin.profile.ui.NormalUserFooterPreference.a;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import com.tencent.mm.ui.e;
import java.util.LinkedList;
import junit.framework.Assert;
class NormalUserFooterPreference$c extends a {
final /* synthetic */ NormalUserFooterPreference lXw;
static /* synthetic */ void a(NormalUserFooterPreference$c normalUserFooterPreference$c) {
int i = 0;
if (((int) NormalUserFooterPreference.a(normalUserFooterPreference$c.lXw).dhP) == 0) {
au.HU();
c.FR().U(NormalUserFooterPreference.a(normalUserFooterPreference$c.lXw));
au.HU();
c.FR().Yg(NormalUserFooterPreference.a(normalUserFooterPreference$c.lXw).field_username);
}
if (((int) NormalUserFooterPreference.a(normalUserFooterPreference$c.lXw).dhP) <= 0) {
x.e("MicroMsg.NormalUserFooterPreference", "addContact : insert contact failed");
return;
}
if (!com.tencent.mm.l.a.gd(NormalUserFooterPreference.a(normalUserFooterPreference$c.lXw).field_type) && NormalUserFooterPreference.l(normalUserFooterPreference$c.lXw) == 15) {
com.tencent.mm.plugin.account.friend.a.a pp = b.getAddrUploadStg().pp(NormalUserFooterPreference.a(normalUserFooterPreference$c.lXw).field_username);
if (pp != null) {
h hVar = h.mEJ;
Object[] objArr = new Object[4];
objArr[0] = NormalUserFooterPreference.a(normalUserFooterPreference$c.lXw).field_username;
objArr[1] = Integer.valueOf(3);
if (!bi.oW(pp.Xh())) {
i = 1;
}
objArr[2] = Integer.valueOf(i);
objArr[3] = Integer.valueOf(NormalUserFooterPreference.a(normalUserFooterPreference$c.lXw).csZ.toString().split(",").length >= 5 ? 5 : NormalUserFooterPreference.a(normalUserFooterPreference$c.lXw).csZ.toString().split(",").length);
hVar.h(12040, objArr);
}
}
s.p(NormalUserFooterPreference.a(normalUserFooterPreference$c.lXw));
NormalUserFooterPreference normalUserFooterPreference = normalUserFooterPreference$c.lXw;
au.HU();
NormalUserFooterPreference.a(normalUserFooterPreference, c.FR().Yg(NormalUserFooterPreference.a(normalUserFooterPreference$c.lXw).field_username));
normalUserFooterPreference$c.bnA();
}
public NormalUserFooterPreference$c(NormalUserFooterPreference normalUserFooterPreference) {
this.lXw = normalUserFooterPreference;
super(normalUserFooterPreference);
}
protected final void FC() {
super.FC();
}
protected void onDetach() {
super.onDetach();
}
protected void bnA() {
Assert.assertTrue(!s.hO(NormalUserFooterPreference.a(this.lXw).field_username));
NormalUserFooterPreference.r(this.lXw).setVisibility(8);
NormalUserFooterPreference.s(this.lXw).setVisibility(8);
if (NormalUserFooterPreference.d(this.lXw)) {
NormalUserFooterPreference.D(this.lXw).setOnClickListener(new 1(this));
if (com.tencent.mm.l.a.gd(NormalUserFooterPreference.a(this.lXw).field_type)) {
NormalUserFooterPreference.D(this.lXw).setVisibility(0);
} else {
NormalUserFooterPreference.D(this.lXw).setVisibility(8);
}
NormalUserFooterPreference.t(this.lXw).setVisibility(8);
NormalUserFooterPreference.f(this.lXw).setVisibility(8);
NormalUserFooterPreference.g(this.lXw).setVisibility(8);
NormalUserFooterPreference.h(this.lXw).setVisibility(8);
NormalUserFooterPreference.q(this.lXw).setVisibility(8);
return;
}
NormalUserFooterPreference.t(this.lXw).setOnClickListener(new 2(this));
if (com.tencent.mm.l.a.gd(NormalUserFooterPreference.a(this.lXw).field_type)) {
NormalUserFooterPreference.t(this.lXw).setVisibility(8);
NormalUserFooterPreference.f(this.lXw).setVisibility(0);
if (this.lXw.bnx() || NormalUserFooterPreference.a(this.lXw).field_username.equals(q.GF()) || s.hO(NormalUserFooterPreference.a(this.lXw).field_username) || s.hH(NormalUserFooterPreference.a(this.lXw).field_username) || ab.XR(NormalUserFooterPreference.a(this.lXw).field_username) || s.hd(NormalUserFooterPreference.a(this.lXw).field_username)) {
NormalUserFooterPreference.h(this.lXw).setVisibility(8);
} else {
NormalUserFooterPreference.h(this.lXw).setVisibility(0);
}
au.HU();
if (c.FR().Yj(NormalUserFooterPreference.a(this.lXw).field_username)) {
NormalUserFooterPreference.k(this.lXw).setVisibility(0);
NormalUserFooterPreference.a(this.lXw, NormalUserFooterPreference.a(this.lXw).getSource());
}
} else {
NormalUserFooterPreference.t(this.lXw).setVisibility(0);
NormalUserFooterPreference.f(this.lXw).setVisibility(8);
NormalUserFooterPreference.g(this.lXw).setVisibility(8);
NormalUserFooterPreference.h(this.lXw).setVisibility(8);
}
if (NormalUserFooterPreference.a(this.lXw).BA()) {
NormalUserFooterPreference.q(this.lXw).setVisibility(0);
} else {
NormalUserFooterPreference.q(this.lXw).setVisibility(8);
}
}
protected final void bnF() {
if (((int) NormalUserFooterPreference.a(this.lXw).dhP) == 0) {
au.HU();
if (c.FR().U(NormalUserFooterPreference.a(this.lXw)) != -1) {
NormalUserFooterPreference normalUserFooterPreference = this.lXw;
au.HU();
NormalUserFooterPreference.a(normalUserFooterPreference, c.FR().Yg(NormalUserFooterPreference.a(this.lXw).field_username));
}
}
if (NormalUserFooterPreference.F(this.lXw) || NormalUserFooterPreference.l(this.lXw) == 12) {
x.d("MicroMsg.NormalUserFooterPreference", "qqNum " + NormalUserFooterPreference.G(this.lXw) + " qqReamrk " + NormalUserFooterPreference.H(this.lXw));
if (!(NormalUserFooterPreference.G(this.lXw) == 0 || NormalUserFooterPreference.H(this.lXw) == null || NormalUserFooterPreference.H(this.lXw).equals(""))) {
ao bK = b.getQQListStg().bK(NormalUserFooterPreference.G(this.lXw));
if (bK == null) {
bK = new ao();
bK.nickname = "";
bK.eLw = NormalUserFooterPreference.G(this.lXw);
bK.eLE = NormalUserFooterPreference.H(this.lXw);
bK.username = NormalUserFooterPreference.a(this.lXw).field_username;
bK.Yc();
b.getQQListStg().a(bK);
} else {
bK.eLw = NormalUserFooterPreference.G(this.lXw);
bK.eLE = NormalUserFooterPreference.H(this.lXw);
bK.username = NormalUserFooterPreference.a(this.lXw).field_username;
bK.Yc();
b.getQQListStg().a(NormalUserFooterPreference.G(this.lXw), bK);
}
}
} else if (NormalUserFooterPreference.l(this.lXw) == 58 || NormalUserFooterPreference.l(this.lXw) == 59 || NormalUserFooterPreference.l(this.lXw) == 60) {
b.getGoogleFriendStorage().ab(NormalUserFooterPreference.a(this.lXw).field_username, 1);
}
String stringExtra = NormalUserFooterPreference.b(this.lXw).getIntent().getStringExtra("Contact_Mobile_MD5");
String stringExtra2 = NormalUserFooterPreference.b(this.lXw).getIntent().getStringExtra("Contact_full_Mobile_MD5");
String oV = bi.oV(stringExtra);
stringExtra2 = bi.oV(stringExtra2);
if (!(oV.equals("") && stringExtra2.equals(""))) {
com.tencent.mm.plugin.account.friend.a.a pq = b.getAddrUploadStg().pq(oV);
if (pq == null) {
pq = b.getAddrUploadStg().pq(stringExtra2);
} else {
stringExtra2 = oV;
}
if (pq != null) {
b.getAddrUploadStg().a(stringExtra2, pq);
}
}
com.tencent.mm.pluginsdk.ui.applet.a aVar = new com.tencent.mm.pluginsdk.ui.applet.a(this.lXw.mContext, new 3(this));
LinkedList linkedList = new LinkedList();
linkedList.add(Integer.valueOf(NormalUserFooterPreference.l(this.lXw)));
stringExtra = NormalUserFooterPreference.b(this.lXw).getIntent().getStringExtra("source_from_user_name");
String stringExtra3 = NormalUserFooterPreference.b(this.lXw).getIntent().getStringExtra("source_from_nick_name");
aVar.qIb = stringExtra;
aVar.qIc = stringExtra3;
aVar.qHX = new 4(this, stringExtra, stringExtra3);
stringExtra3 = NormalUserFooterPreference.b(this.lXw).getIntent().getStringExtra("room_name");
Object stringExtra4 = NormalUserFooterPreference.b(this.lXw).getIntent().getStringExtra(e.a.ths);
if (!TextUtils.isEmpty(stringExtra4)) {
aVar.TC(stringExtra4);
aVar.b(NormalUserFooterPreference.a(this.lXw).field_username, "", linkedList);
} else if (TextUtils.isEmpty(stringExtra3)) {
aVar.TC(NormalUserFooterPreference.a(this.lXw).cta);
aVar.c(NormalUserFooterPreference.a(this.lXw).field_username, linkedList);
} else if (TextUtils.isEmpty(aVar.juZ)) {
au.HU();
ab Yg = c.FR().Yg(NormalUserFooterPreference.a(this.lXw).field_username);
stringExtra4 = Yg != null ? bi.aG(Yg.cta, "") : "";
x.i("MicroMsg.NormalUserFooterPreference", "dkverify footer add:%s chat:%s ticket:%s", new Object[]{NormalUserFooterPreference.a(this.lXw).field_username, stringExtra3, stringExtra4});
if (TextUtils.isEmpty(stringExtra4)) {
am.a.dBr.a(NormalUserFooterPreference.a(this.lXw).field_username, stringExtra3, new 5(this, aVar, stringExtra3, linkedList));
return;
}
aVar.TC(stringExtra4);
aVar.b(NormalUserFooterPreference.a(this.lXw).field_username, stringExtra3, linkedList);
} else {
aVar.b(NormalUserFooterPreference.a(this.lXw).field_username, stringExtra3, linkedList);
}
}
}
|
package com.app.cosmetics.core.discount;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface DiscountRepository extends JpaRepository<Discount, Long> {
Optional<Discount> findDiscountByCode(String code);
}
|
package pl.rogalik.environ1.game_map;
import pl.rogalik.environ1.game_map.map_providers.MapProviding;
import pl.rogalik.environ1.game_map.map_providers.generators.CaveMapGenerator;
import pl.rogalik.environ1.game_map.map_providers.generators.DungeonMapGenerator;
import java.util.Random;
public class MapFabric {
private static Random random = new Random(String.valueOf(System.currentTimeMillis()).hashCode());
public MapProviding getGenerator(){
MapProviding mapGen;
int w = random.nextInt(180)+20;
int h = random.nextInt(180)+20;
if(random.nextDouble()<0.5)
mapGen = new DungeonMapGenerator(w,h);
else
mapGen = new CaveMapGenerator(w,h);
return mapGen;
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.qq;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* 单一线程执行器,负责包含所有的可模块化任务,减少线程数。目前的设置是不管创建
* 几个QQClient,都只使用一个线程来进行一些固定任务,也许QQClient太多的时候这样
* 会有问题
*
* @author luma
*/
public class SingleExecutor {
private int clientCount;
private ScheduledExecutorService executor;
public SingleExecutor() {
clientCount = 0;
}
public <T> Future<T> submit(Callable<T> callable) {
if(executor == null)
executor = Executors.newSingleThreadScheduledExecutor();
return executor.submit(callable);
}
public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
if(executor == null)
executor = Executors.newSingleThreadScheduledExecutor();
return executor.scheduleWithFixedDelay(command, initialDelay, delay, unit);
}
public <T> ScheduledFuture<T> schedule(Callable<T> callable, long delay, TimeUnit unit) {
if(executor == null)
executor = Executors.newSingleThreadScheduledExecutor();
return executor.schedule(callable, delay, unit);
}
/**
* 停止执行器线程
*/
private void dispose() {
if(executor != null) {
executor.shutdownNow();
executor = null;
}
}
/**
* 增加QQClient数目
*/
public void increaseClient() {
clientCount++;
}
/**
* 减少QQ客户端数目,如果数目为0,则释放资源
*/
public void decreaseClient() {
clientCount--;
if(clientCount <= 0)
dispose();
}
}
|
package com.example.animation;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
/**
* Created by ouyangshen on 2017/11/27.
*/
public class FrameAnimActivity extends AppCompatActivity implements OnClickListener {
private ImageView iv_frame_anim; // 声明一个图像视图对象
private AnimationDrawable ad_frame; // 声明一个帧动画对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frame_anim);
// 从布局文件中获取名叫iv_frame_anim的图像视图
iv_frame_anim = findViewById(R.id.iv_frame_anim);
iv_frame_anim.setOnClickListener(this);
showFrameAnimByCode();
//showFrameAnimByXml();
}
// 在代码中生成帧动画并进行播放
private void showFrameAnimByCode() {
// 创建一个帧动画
ad_frame = new AnimationDrawable();
// 下面把每帧图片加入到帧动画的队列中
ad_frame.addFrame(getResources().getDrawable(R.drawable.flow_p1), 50);
ad_frame.addFrame(getResources().getDrawable(R.drawable.flow_p2), 50);
ad_frame.addFrame(getResources().getDrawable(R.drawable.flow_p3), 50);
ad_frame.addFrame(getResources().getDrawable(R.drawable.flow_p4), 50);
ad_frame.addFrame(getResources().getDrawable(R.drawable.flow_p5), 50);
ad_frame.addFrame(getResources().getDrawable(R.drawable.flow_p6), 50);
ad_frame.addFrame(getResources().getDrawable(R.drawable.flow_p7), 50);
ad_frame.addFrame(getResources().getDrawable(R.drawable.flow_p8), 50);
// 设置帧动画是否只播放一次。为true表示只播放一次,为false表示循环播放
ad_frame.setOneShot(false);
// 设置图像视图的图形为帧动画
iv_frame_anim.setImageDrawable(ad_frame);
ad_frame.start(); // 开始播放帧动画
}
// 从xml文件中获取帧动画并进行播放
private void showFrameAnimByXml() {
// 设置图像视图的图像来源为帧动画的XML定义文件
iv_frame_anim.setImageResource(R.drawable.frame_anim);
// 从图像视图对象中获取帧动画
ad_frame = (AnimationDrawable) iv_frame_anim.getDrawable();
ad_frame.start(); // 开始播放帧动画
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.iv_frame_anim) {
if (ad_frame.isRunning()) { // 判断帧动画是否正在播放
ad_frame.stop(); // 停止播放帧动画
} else {
ad_frame.start(); // 开始播放帧动画
}
}
}
}
|
package chap11.sec05.Exam04_getproperty;
import java.util.Properties;
import java.util.Set;
public class GetPropertyExample {
public static void main(String[] args) {
// 자바 버전
System.out.println(System.getProperty("java.version"));
// JRE 파일경로
System.out.println(System.getProperty("java.home"));
// 사용자 OS이름
System.out.println(System.getProperty("os.name"));
System.out.println(System.getProperty("file.separator"));
// 사용자 이름
System.out.println(System.getProperty("user.name"));
// 홈 디렉토리
System.out.println(System.getProperty("user.home"));
// 현재 작업 중인 디렉토리 경로
System.out.println(System.getProperty("user.dir"));
System.out.println("-----------------------------------------------------------");
// map 자료구조: {key:value} 예) {String : String} <-- Properties
Properties prop = System.getProperties();
// set 자료구조: 순서가 없고, 자료가 중복할 수 없고, null 허용
// set<Object> Properties에서 keyset()메소드로
// Object를 담고있는 Set을 가져옴
Set<Object> keys = prop.keySet();
for(Object key : keys) {
// String key 로 property를 출력
System.out.println(key.toString() + " : " +prop.getProperty(key.toString()));
}
}
}
|
package com.example.samxzy0207.mfa;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new com.example.samxzy0207.mfa.ImageAdapter(this));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(MainActivity.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
/*
GridView
gridView.setAdapter(new com.example.samxzy0207.mfa.ImageAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_SHORT).show();
}
});
*/
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
public void searchNearby(View view) {
Intent intent = new Intent(this, DisplayMapActivity.class);
startActivity(intent);
}
}
|
package com.cognitive.newswizard.api.vo.processed;
import java.util.Comparator;
public class MissingProperNounVO {
private final int count;
private final String properNoun;
private final String suggestion;
public MissingProperNounVO(int count, String properNoun, String suggestion) {
super();
this.count = count;
this.properNoun = properNoun;
this.suggestion = suggestion;
}
public int getCount() {
return count;
}
public String getProperNoun() {
return properNoun;
}
public String getSuggestion() {
return suggestion;
}
public static class MissingProperNounComparator implements Comparator<MissingProperNounVO> {
public int compare(MissingProperNounVO o1, MissingProperNounVO o2) {
if (o1.getCount() < o2.getCount()) {
return 1;
} else {
if (o1.getCount() == o2.getCount()) {
return 0;
}
}
return -1;
}
}
}
|
package BLL;
import DAL.BookInfo;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author tunguyen
*/
public class UpdateBookInformationController {
private ArrayList<BookInfo> bookList;
/**
* Get information of all book that match the key on a specific category or
* all categories
*
* @param key a string that input to look up data
* @param catalogue a string that specifies category on where to look up
* @return the ArrayList bookList of all books that match
* @throws SQLException if there was a problem when connect or getting data
* from database
*/
public ArrayList<BookInfo> getBookInfo(String key, String catalogue) throws SQLException {
BookInfo bookInfo = new BookInfo();
this.bookList = bookInfo.getBookInfo(key, catalogue);
return this.bookList;
}
/**
* Get information of specified book
* @param bookID the unique ID of a book
* @return book information
*/
public BookInfo getSelectedBookInfo(String bookID) {
BookInfo book;
book = BookInfo.getSelectedBookInfo(bookID);
return book;
}
/**
* update information of specified book
* @param book the bookinfo param
* @param title the title of a book
* @param author the author of a book
* @param publisher the publisher of a book
* @param ISBN the ISBN code of a book
* @param sequenceNumber the copyNumber of a book
* @param type the copyType of a book
* @param price the price of a book copy
* @param status the status of a book copy
* @return boolean if update book successfully or not
*/
public boolean updateSelectedBook(BookInfo book, String title, String author, String publisher, String ISBN,
int sequenceNumber, String type, long price, String status) {
book.setTitle(title);
book.setAuthor(author);
book.setPublisher(publisher);
book.setISBN(ISBN);
book.setSequenceNumber(sequenceNumber);
book.setType(type);
book.setPrice(price);
book.setStatus(status);
return book.updateQuery();
}
}
|
package com.vilio.bps.inquiry.shchengshi.service;
import java.util.Map;
/**
* Created by dell on 2017/5/12.
*/
public interface SCInquiryPrice {
public String getAppraisalPrice(Map map) throws Exception;
}
|
package com.tencent.mm.ui.tools;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.al.b.a;
import com.tencent.mm.sdk.platformtools.w;
import java.util.ArrayList;
import java.util.List;
public final class c extends BaseAdapter {
private Context context;
private String eIQ;
private List<a> kuM = new ArrayList();
int[] kuO;
boolean kuP = false;
private List<a> list;
public c(Context context, List<a> list) {
this.context = context;
this.list = list;
aYg();
aYh();
}
private void aYg() {
int size = this.list.size();
for (int i = 0; i < size; i++) {
this.kuM.add(this.list.get(i));
}
}
private void aYh() {
this.kuO = new int[this.list.size()];
int size = this.list.size();
for (int i = 0; i < size; i++) {
this.kuO[i] = ((a) this.list.get(i)).dYA;
}
}
public final int getCount() {
return this.list.size();
}
public final Object getItem(int i) {
return this.list.get(i);
}
public final long getItemId(int i) {
return (long) i;
}
public final void pi(String str) {
if (str != null) {
this.eIQ = str.trim();
this.list.clear();
int size = this.kuM.size();
int i = 0;
while (i < size) {
if (((a) this.kuM.get(i)).dYy.toUpperCase().contains(this.eIQ.toUpperCase()) || ((a) this.kuM.get(i)).dYz.toUpperCase().contains(this.eIQ.toUpperCase()) || ((a) this.kuM.get(i)).dYx.contains(this.eIQ)) {
this.list.add(this.kuM.get(i));
}
i++;
}
aYh();
super.notifyDataSetChanged();
}
}
public final View getView(int i, View view, ViewGroup viewGroup) {
View inflate;
a aVar;
a aVar2 = (a) getItem(i);
if (view == null) {
if (w.chN()) {
inflate = View.inflate(this.context, R.i.country_code_item_big5, null);
} else {
inflate = View.inflate(this.context, R.i.country_code_item, null);
}
aVar = new a();
aVar.kuR = (TextView) inflate.findViewById(R.h.contactitem_catalog);
aVar.eMf = (TextView) inflate.findViewById(R.h.contactitem_nick);
aVar.kuS = (TextView) inflate.findViewById(R.h.contactitem_signature);
inflate.setTag(aVar);
} else {
aVar = (a) view.getTag();
inflate = view;
}
int i2 = i > 0 ? this.kuO[i - 1] : -1;
if (i == 0) {
aVar.kuR.setVisibility(0);
aVar.kuR.setText(rB(this.kuO[i]));
} else if (i <= 0 || this.kuO[i] == i2) {
aVar.kuR.setVisibility(8);
} else {
aVar.kuR.setVisibility(0);
aVar.kuR.setText(rB(this.kuO[i]));
}
aVar.eMf.setText(aVar2.dYy);
aVar.kuS.setText(aVar2.dYx);
if (this.kuP) {
aVar.kuS.setVisibility(0);
} else {
aVar.kuS.setVisibility(4);
}
return inflate;
}
private static String rB(int i) {
if (w.chN()) {
return Integer.toString(i) + "劃";
}
return String.valueOf((char) i);
}
}
|
package com.gcsw.teamone;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.annotations.NotNull;
import com.google.firebase.functions.FirebaseFunctions;
import com.google.firebase.functions.FirebaseFunctionsException;
import com.google.firebase.functions.HttpsCallableResult;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class groupTable extends AppCompatActivity {
TimetableView timetable;
private todaySchedule adapter;
private FirebaseFunctions mFunctions;
FirebaseDatabase Database =FirebaseDatabase.getInstance();
DatabaseReference scheduleRef = Database.getReference("schedule");
DatabaseReference groupRef = Database.getReference("grouplist");
DatabaseReference planRef = Database.getReference("plan");
DatabaseReference usersRef = Database.getReference("users");
ArrayList<String> WantPushMembers;
ArrayList<String> membersToken;
ArrayList<String> members;
String name;
String groupCode;
ArrayList<Schedule> total;
String planName = "not yet !@!@#@$";
boolean[] weekdayTrue = new boolean[7];
int hourInt, minuteInt;
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grouptable);
View selfLayout = (View) findViewById(R.id.gtLayout);
mFunctions = FirebaseFunctions.getInstance();
WantPushMembers = new ArrayList<>();
membersToken = new ArrayList<>();
members = new ArrayList<>();
total = new ArrayList<>();
LocalDate nowDate = LocalDate.now();
LocalDate sunday = nowDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
LocalDate satday = nowDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY));
LocalDate nextDate = LocalDate.now().plusDays(6);
timetable = (TimetableView) findViewById(R.id.timetable_group);
timetable.setOnStickerSelectEventListener(new TimetableView.OnStickerSelectedListener() {
@Override
public void OnStickerSelected(int idx, ArrayList<Schedule> schedules) {
// ...
}
});
timetable.setHeaderHighlightDefault();
timetable.setHeaderHighlight(getHeaderIndex(LocalDate.now().getDayOfWeek().toString()));
Intent intent = getIntent();
name = intent.getStringExtra("name");
groupCode = intent.getStringExtra("code");
TextView names = (TextView)findViewById(R.id.grouptableName);
names.setText(name);
//read group schedule
groupRef.child(groupCode).child("GroupSchedule").child("schedule").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @org.jetbrains.annotations.NotNull Task<DataSnapshot> task) {
if (!task.getResult().getValue().toString().equals("0")) {
String s = task.getResult().getValue().toString();
String[] fortable = s.split("!/");
String[] starttime = fortable[2].split(":");
String[] Endtime = fortable[3].split(":");
String[] date = fortable[4].split("/");
LocalDate scheduleDate = LocalDate.of(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2]));
if (getDateDif(scheduleDate, nowDate) < 0) {
deleteGroupPlan();
} else if (getDateDif(scheduleDate, nowDate) > 0 && getDateDif(scheduleDate, nextDate) < 0) {
addNew(Integer.parseInt(fortable[0]), fortable[1], "", new Time(Integer.parseInt(starttime[0]), Integer.parseInt(starttime[1])), new Time(Integer.parseInt(Endtime[0]), Integer.parseInt(Endtime[1])));
setColor(planName);
}
planName = fortable[1];
}
}
});//read group's meeting schedule
//read member's schedules
groupRef.child(groupCode).child("members").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
for (DataSnapshot member : task.getResult().getChildren()) {
String Want = member.child("WantPush").getValue().toString();
if(Want.equals("1")){ WantPushMembers.add(member.getKey()); } // Want Push User (for Push on/off)
members.add(member.getKey());
scheduleRef.child(member.getKey()).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
for (DataSnapshot schedules : task.getResult().getChildren()) {
String a = schedules.getKey();
scheduleRef.child(member.getKey()).child(a).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @org.jetbrains.annotations.NotNull Task<DataSnapshot> task) {
String title = task.getResult().child("title").getValue().toString();
String weekday = task.getResult().child("weekday").getValue().toString();
String Time = task.getResult().child("time").getValue().toString();
String[] times = Time.split("~");
String[] startTime = times[0].split(":");
String[] endTime = times[1].split(":");
String startDate = task.getResult().child("startDate").getValue().toString();
String endDate = task.getResult().child("endDate").getValue().toString();
String[] startDateSplit = startDate.split("/");
String[] endDateSplit = endDate.split("/");
LocalDate startLocalDate = LocalDate.of(Integer.parseInt(startDateSplit[0]), Integer.parseInt(startDateSplit[1]), Integer.parseInt(startDateSplit[2]));
LocalDate endLocalDate = LocalDate.of(Integer.parseInt(endDateSplit[0]), Integer.parseInt(endDateSplit[1]), Integer.parseInt(endDateSplit[2]));
LocalDate tmpDate = nowDate.with(TemporalAdjusters.nextOrSame(getDatePersonal(Integer.parseInt(weekday))));
if (getDateDif(tmpDate, startLocalDate) >= 0 && getDateDif(tmpDate, endLocalDate) <= 0) {
addNew(Integer.parseInt(weekday), "", "", new Time(Integer.parseInt(startTime[0]), Integer.parseInt(startTime[1])), new Time(Integer.parseInt(endTime[0]), Integer.parseInt(endTime[1])));
setColor(planName);
} else if (getDateDif(tmpDate, endLocalDate) > 0) {
deleteSchedule(title, startDateSplit[0] + startDateSplit[1] + startDateSplit[2], endDateSplit[0] + endDateSplit[1] + endDateSplit[2], Time, weekday,member.getKey());
}
}
});
}
}
});
}
}
});
//read member's plan & show only plan in 7 days
groupRef.child(groupCode).child("members").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
for (DataSnapshot member : task.getResult().getChildren()) {
planRef.child(member.getKey()).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
for (DataSnapshot plan : task.getResult().getChildren()) {
String a = plan.getKey();
planRef.child(member.getKey()).child(a).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @org.jetbrains.annotations.NotNull Task<DataSnapshot> task) {
String title = plan.child("title").getValue().toString();
if (!title.equals(planName)) {
String date = plan.child("date").getValue().toString();
String time = plan.child("time").getValue().toString();
String[] timeSplitPlan = time.split("~");
int startHour = Integer.parseInt(timeSplitPlan[0].substring(0, 2));
int startMinute = Integer.parseInt(timeSplitPlan[0].substring(3, 5));
int endHour = Integer.parseInt(timeSplitPlan[1].substring(0, 2));
int endMinute = Integer.parseInt(timeSplitPlan[1].substring(3, 5));
String[] dateSplitPlan = date.split("/");
LocalDate tmpDatePlan = LocalDate.of(Integer.parseInt(dateSplitPlan[0]), Integer.parseInt(dateSplitPlan[1]), Integer.parseInt(dateSplitPlan[2]));
int weekday = getWeekdayIndex(tmpDatePlan.getDayOfWeek().toString());
if (getDateDif(tmpDatePlan, nowDate) < 0) {
deletePlan(title, dateSplitPlan[0] + dateSplitPlan[1] + dateSplitPlan[2], time,member.getKey());
} else if (getDateDif(tmpDatePlan, nowDate) > 0 && getDateDif(tmpDatePlan, nextDate) < 0) {
addNew(weekday, "", "", new Time(startHour, startMinute), new Time(endHour, endMinute));
setColor(planName);
}
}
}
});
}
}
});
}
}
});
//read User's info
usersRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @org.jetbrains.annotations.NotNull Task<DataSnapshot> task) {
for (String GroupMember : WantPushMembers) {
if (task.getResult().child(GroupMember).hasChild("token")) {
membersToken.add(task.getResult().child(GroupMember).child("token").getValue().toString());
}
}
}
});
//Above reading from DB is done only 1 time. So if someone change their schedule or add new schedule, user need to
//user need to reset to call that data
Button resetB = (Button) findViewById(R.id.reset);
resetB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
reset();
timetable.setHeaderHighlightDefault();
timetable.setHeaderHighlight(getHeaderIndex(LocalDate.now().getDayOfWeek().toString()));
}
});
Button cancel = findViewById(R.id.cancel_groupMeeting);
cancel.setOnClickListener(new View.OnClickListener(){
String s;
String[] fortable;
String[] starttime;
String[] Endtime;
String[] date;
boolean correct;
@Override
public void onClick(View view) {
correct =false;
//read group schedule and if there is group schedule, delete each user's plan(group schedule)
groupRef.child(groupCode).child("GroupSchedule").child("schedule").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @org.jetbrains.annotations.NotNull Task<DataSnapshot> task) {
if (!task.getResult().getValue().toString().equals("0")) {
s = task.getResult().getValue().toString();
fortable = s.split("!/");
starttime = fortable[2].split(":");
Endtime = fortable[3].split(":");
date = fortable[4].split("/");
deleteGroupPlan();
correct=true;
planName = "not yet !@!@#@$";
}
}
});
groupRef.child(groupCode).child("members").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
for (DataSnapshot member : task.getResult().getChildren()) {
planRef.child(member.getKey()).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
if(correct) {
String title = fortable[1];
String startTime = starttime[0] + ":" + starttime[1];
startTime = convertPlanTime(startTime);
String endTime = Endtime[0] + ":" + Endtime[1];
endTime = convertPlanTime(endTime);
String time = startTime + "~" + endTime;
String[] dates = convertPlanDate(date[0] + "/" + date[1] + "/" + date[2]);
deletePlan(title, dates[0] + dates[1] + dates[2], time, member.getKey());
}
}
});
}
}
});
}
});
Button goBack = (Button)selfLayout.findViewById(R.id.btnBack);
goBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("fragment","1");
startActivity(intent);
}
});//fragment "1" is grouplist fragment
Button calculating = (Button) findViewById(R.id.calculate);
calculating.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), calculateTime.class);
startActivityForResult(intent, 0);
}
});//setting rule of meeting and calculating group's meeting
//send group name and groupcode to add new member in this group
Button AddMember = (Button) selfLayout.findViewById(R.id.btnAddMember);
AddMember.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), groupMemberAdder.class);
intent.putExtra("name", name);
intent.putExtra("code", groupCode);
startActivity(intent);
}
});//
AddMember.setSelected(true);
cancel.setSelected(true);
resetB.setSelected(true);
calculating.setSelected(true);
}
@RequiresApi(api = Build.VERSION_CODES.O)
public DayOfWeek getDate(int weekday) {
if (weekday == 6) {
return DayOfWeek.SUNDAY;
} else if (weekday == 0) {
return DayOfWeek.MONDAY;
} else if (weekday == 1) {
return DayOfWeek.TUESDAY;
} else if (weekday == 2) {
return DayOfWeek.WEDNESDAY;
} else if (weekday == 3) {
return DayOfWeek.THURSDAY;
} else if (weekday == 4) {
return DayOfWeek.FRIDAY;
} else if (weekday == 5) {
return DayOfWeek.SATURDAY;
}
return DayOfWeek.SUNDAY;
}
@RequiresApi(api = Build.VERSION_CODES.O)
public DayOfWeek getDatePersonal(int weekday) {
if (weekday == 0) {
return DayOfWeek.SUNDAY;
} else if (weekday == 1) {
return DayOfWeek.MONDAY;
} else if (weekday == 2) {
return DayOfWeek.TUESDAY;
} else if (weekday == 3) {
return DayOfWeek.WEDNESDAY;
} else if (weekday == 4) {
return DayOfWeek.THURSDAY;
} else if (weekday == 5) {
return DayOfWeek.FRIDAY;
} else if (weekday == 6) {
return DayOfWeek.SATURDAY;
}
return DayOfWeek.SUNDAY;
}
/*
calculate the new schedule's time to put in the group timetable
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public void putCalcul() {
LocalDate nowDate = LocalDate.now();
groupRef.child(groupCode).child("GroupSchedule").child("schedule").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onComplete(@NonNull @org.jetbrains.annotations.NotNull Task<DataSnapshot> task) {
if (!task.getResult().getValue().toString().equals("0")) {
Toast.makeText(getApplicationContext(), "이미 그룹 미팅시간이 잡혀있습니다.", Toast.LENGTH_SHORT).show();
} else {
ArrayList<Schedule> forCalculating = new ArrayList<>();
forCalculating = timetable.getAllSchedulesInStickers();
Schedule[] baseSchedule = new Schedule[forCalculating.size()];
int i = 0;
for (Schedule s : forCalculating)
baseSchedule[i++] = s;
Schedule createTime = new Schedule();
if (calculate(baseSchedule, createTime, hourInt * 100 + minuteInt)) {
LocalDate calculDate;
calculDate = nowDate.with(TemporalAdjusters.nextOrSame(getDate(createTime.getDay())));
int startHour = createTime.getStartTime().getHour();
int startMinute = createTime.getStartTime().getMinute();
if (startHour == 0) {
startHour = 9;
}
int year = calculDate.getYear();
int month = calculDate.getMonthValue();
int day = calculDate.getDayOfMonth();
int endHour = startHour + hourInt;
int endMinute = startMinute + minuteInt;
Time endTimeTik = createTime.getStartTime();
int weekdayIndex = getWeekdayIndex(calculDate.getDayOfWeek().toString());
String calculDateStr = Integer.toString(year) + "/" + Integer.toString(month) + "/" + Integer.toString(day);
addNew(weekdayIndex, name + "'s meeting", "", new Time(startHour, startMinute), new Time(endHour, endMinute));
groupRef.child(groupCode).child("GroupSchedule").child("schedule").setValue(weekdayIndex + "!/" + name + "'s meeting" + "!/" + startHour + ":" + startMinute + "!/" + endHour + ":" + endMinute + "!/" + calculDateStr);
planName = name + "'s meeting";
setColor(planName);
//String date, String startTime, String endTime, String title
addPlan(calculDateStr, startHour + ":" + startMinute, endHour + ":" + endMinute, name + "'s meeting");
if(!membersToken.isEmpty()){
for(String token:membersToken){
On_MakeNotification(token, name, "새로운 일정이 추가되었습니다.", "TeamOne");
}
}
} else {
Toast.makeText(getApplicationContext(), "가능한 시간이 없습니다", Toast.LENGTH_SHORT).show();
}
}
}
});
}
/*
result from add new group schedule
*/
@RequiresApi(api = Build.VERSION_CODES.O)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
weekdayTrue = data.getExtras().getBooleanArray("weekday");
hourInt = data.getExtras().getInt("hour");
minuteInt = data.getExtras().getInt("minute");
putCalcul();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "취소되었습니다", Toast.LENGTH_SHORT).show();
}
}
}
// remove data and create new group timetable
@RequiresApi(api = Build.VERSION_CODES.O)
public void reset() {
members.removeAll(members);
timetable.removeAll();
LocalDate nowDate = LocalDate.now();
LocalDate sunday = nowDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
LocalDate satday = nowDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY));
LocalDate nextDate = LocalDate.now().plusDays(6);
groupRef.child(groupCode).child("members").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
for (DataSnapshot member : task.getResult().getChildren()) {
planRef.child(member.getKey()).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
for (DataSnapshot plan : task.getResult().getChildren()) {
String a = plan.getKey();
planRef.child(member.getKey()).child(a).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @org.jetbrains.annotations.NotNull Task<DataSnapshot> task) {
String title = plan.child("title").getValue().toString();
if (!title.equals(planName)) {
String date = plan.child("date").getValue().toString();
String time = plan.child("time").getValue().toString();
String[] timeSplitPlan = time.split("~");
int startHour = Integer.parseInt(timeSplitPlan[0].substring(0, 2));
int startMinute = Integer.parseInt(timeSplitPlan[0].substring(3, 5));
int endHour = Integer.parseInt(timeSplitPlan[1].substring(0, 2));
int endMinute = Integer.parseInt(timeSplitPlan[1].substring(3, 5));
String[] dateSplitPlan = date.split("/");
LocalDate tmpDatePlan = LocalDate.of(Integer.parseInt(dateSplitPlan[0]), Integer.parseInt(dateSplitPlan[1]), Integer.parseInt(dateSplitPlan[2]));
int weekday = getWeekdayIndex(tmpDatePlan.getDayOfWeek().toString());
if (getDateDif(tmpDatePlan, nowDate) < 0) {
deletePlan(title, dateSplitPlan[0] + dateSplitPlan[1] + dateSplitPlan[2], time,member.getKey());
} else if (getDateDif(tmpDatePlan, nowDate) > 0 && getDateDif(tmpDatePlan, nextDate) < 0) {
addNew(weekday, "", "", new Time(startHour, startMinute), new Time(endHour, endMinute));
setColor(planName);
}
}
}
});
}
}
});
}
}
});
groupRef.child(groupCode).child("GroupSchedule").child("schedule").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @org.jetbrains.annotations.NotNull Task<DataSnapshot> task) {
if (!task.getResult().getValue().toString().equals("0")) {
String s = task.getResult().getValue().toString();
String[] fortable = s.split("!/");
String[] starttime = fortable[2].split(":");
String[] Endtime = fortable[3].split(":");
String[] date = fortable[4].split("/");
LocalDate tmpDate = LocalDate.of(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2]));
if (getDateDif(tmpDate, nowDate) < 0) {
deleteGroupPlan();
} else if (getDateDif(tmpDate, nowDate) > 0 && getDateDif(tmpDate, nextDate) < 0) {
addNew(Integer.parseInt(fortable[0]), fortable[1], "", new Time(Integer.parseInt(starttime[0]), Integer.parseInt(starttime[1])), new Time(Integer.parseInt(Endtime[0]), Integer.parseInt(Endtime[1])));
setColor(planName);
}
planName = fortable[1];
}
}
});
groupRef.child(groupCode).child("members").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
for (DataSnapshot member : task.getResult().getChildren()) {
members.add(member.getKey());
scheduleRef.child(member.getKey()).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
for (DataSnapshot schedules : task.getResult().getChildren()) {
String a = schedules.getKey();
scheduleRef.child(member.getKey()).child(a).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @org.jetbrains.annotations.NotNull Task<DataSnapshot> task) {
String title = task.getResult().child("title").getValue().toString();
String weekday = task.getResult().child("weekday").getValue().toString();
String Time = task.getResult().child("time").getValue().toString();
String[] times = Time.split("~");
String[] startTime = times[0].split(":");
String[] endTime = times[1].split(":");
String startDate = task.getResult().child("startDate").getValue().toString();
String endDate = task.getResult().child("endDate").getValue().toString();
String[] startDateSplit = startDate.split("/");
String[] endDateSplit = endDate.split("/");
LocalDate startLocalDate = LocalDate.of(Integer.parseInt(startDateSplit[0]), Integer.parseInt(startDateSplit[1]), Integer.parseInt(startDateSplit[2]));
LocalDate endLocalDate = LocalDate.of(Integer.parseInt(endDateSplit[0]), Integer.parseInt(endDateSplit[1]), Integer.parseInt(endDateSplit[2]));
LocalDate tmpDate = nowDate.with(TemporalAdjusters.nextOrSame(getDatePersonal(Integer.parseInt(weekday))));
if (getDateDif(tmpDate, startLocalDate) >= 0 && getDateDif(tmpDate, endLocalDate) <= 0) {
addNew(Integer.parseInt(weekday), "", "", new Time(Integer.parseInt(startTime[0]), Integer.parseInt(startTime[1])), new Time(Integer.parseInt(endTime[0]), Integer.parseInt(endTime[1])));
setColor(planName);
} else if (getDateDif(tmpDate, endLocalDate) > 0) {
deleteSchedule(title, startDateSplit[0] + startDateSplit[1] + startDateSplit[2], endDateSplit[0] + endDateSplit[1] + endDateSplit[2], Time, weekday,member.getKey());
}
}
});
}
}
});
}
}
});
}
public void addNew(int day, String title, String place, Time startTime, Time endTime) {
ArrayList<Schedule> schedules = new ArrayList<Schedule>();
Schedule schedule = new Schedule();
schedule.setClassTitle(title); // sets subject
schedule.setClassPlace(place); // sets place
schedule.setStartTime(startTime); // sets the beginning of class time (hour,minute)
schedule.setEndTime(endTime); // sets the end of class time (hour,minute)
schedule.setDay(day);
schedules.add(schedule);
timetable.add(schedules);
}
/*
check if there is any time to put in new group schedule into group timetable
make each weekday's index and Schedul[e
get each weekday's schedules or plans and count, and merge it
if the weekday is selected, check if there is any time to put in new schedule
return the result
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public boolean calculate(Schedule[] groupSchedule, Schedule newSchedule, int length) {
int index = groupSchedule.length;
Schedule[][] day = new Schedule[7][groupSchedule.length];
int[] indicies = new int[7];
for (int j = 0; j < 7; j++) {
for (int i = 0; i < index; i++) {
day[j][i] = new Schedule();
}
}
for (int i = 0; i < index; i++) {
if (groupSchedule[i].getDay() == 0) {
day[0][indicies[0]] = groupSchedule[i];
indicies[0]++;
} else if (groupSchedule[i].getDay() == 1) {
day[1][indicies[1]] = groupSchedule[i];
indicies[1]++;
} else if (groupSchedule[i].getDay() == 2) {
day[2][indicies[2]] = groupSchedule[i];
indicies[2]++;
} else if (groupSchedule[i].getDay() == 3) {
day[3][indicies[3]] = groupSchedule[i];
indicies[3]++;
} else if (groupSchedule[i].getDay() == 4) {
day[4][indicies[4]] = groupSchedule[i];
indicies[4]++;
} else if (groupSchedule[i].getDay() == 5) {
day[5][indicies[5]] = groupSchedule[i];
indicies[5]++;
} else if (groupSchedule[i].getDay() == 6) {
day[6][indicies[6]] = groupSchedule[i];
indicies[6]++;
}
}
Schedule[][] merged = new Schedule[7][index];
LocalDate nowDate = LocalDate.now();
int weekday = getWeekdayIndex(nowDate.getDayOfWeek().toString());
int i=weekday+1;
if(i==7){
i=0;
}
boolean correct=true;
while(correct){
for (int j = 0; j < index; j++) {
merged[i][j] = new Schedule();
}
if (weekdayTrue[i] != false) {
if (indicies[i] != 0) {
if (Merging(day[i], merged[i], newSchedule, indicies[i], length, i)) {
return true;
}
} else if (indicies[i] == 0) {
Merging(day[i], merged[i], newSchedule, indicies[i], length, i);
return true;
}
}
i+=1;
if(i==7){
i=0;
}
if(i==weekday){
correct = false;
}
}
return false;
}
public boolean Merging(Schedule[] days, Schedule[] merging, Schedule newschedule, int index, int length, int day) {
Schedule temp = new Schedule();
int done = 0;
int minIndex = 0;
int minStartTime = 2400; //시간이기 때문에 24가 가장 큰 수 & 시간계산은 hour * 100 + minute로 할것.
for (int i = 0; i < index - 1; i++) {
minIndex = i;
for (int j = i; j < index; j++) {
if (days[j].getStartTime().getHour() * 100 + days[i].getStartTime().getMinute() < days[minIndex].getStartTime().getHour() * 100 + days[i].getStartTime().getMinute()) {
minIndex = j;
}
temp = days[minIndex];
days[minIndex] = days[i];
days[i] = temp;
}
} //sorting
// need to merging them -> We don't need to show name and title in this table. So only use time
int count = 0; //merging 의 갯수 새기
// done는 merge에 포함된 array의 갯수
// done = 0부터 시작,
while (done != index) {
merging[count].setStartTime(days[done].getStartTime());
merging[count].setEndTime(days[done].getEndTime());
for (int i = done; i < index; i++) {
if (merging[count].getStartTime().getHour() * 100 + merging[count].getStartTime().getMinute() <= days[i].getStartTime().getHour() * 100 + days[i].getStartTime().getMinute()// merging의 시작시간이 더 빠르고
&& merging[count].getEndTime().getHour() * 100 + merging[count].getEndTime().getMinute() >= days[i].getStartTime().getHour() * 100 + days[i].getStartTime().getMinute() // merging의 시작과 끝 사이에 새로운 스케쥴의 시작시간이 있고
&& i != done
) {
if (merging[count].getEndTime().getHour() * 100 + merging[count].getEndTime().getMinute() < days[i].getEndTime().getHour() * 100 + days[i].getEndTime().getMinute()) {//merging의 끝시간 보다 새로운 스케쥴의 끝이 더 느릴때
merging[count].setEndTime(days[i].getEndTime()); //더 늦게 끝나는걸 merging의 끝나는 시간으로 선택하기
done++;//몇개가 합쳐졌는지 카운트
if (done == index)
break;
} else {
done++;
if (done == index)
break;
}
}
}
if (done == index)
break;
done++;
count++; //한바퀴 다 돌고 아직 모든 array의 value들이 안합쳐졌다면 나머지도 합쳐야함.
}
return available(merging, newschedule, count, length, day - 1);
}//merging function end
//합친 것을 바탕으로 boolean함수로 가능한지 확인하기
//length 받은 것을 바탕으로 merge완료 된 각 날짜의 스케줄의 끝나는 시간과 시작시간을 빼면서 length보다 작은 값 나오는 것들 다 찾기.
//만약 여기서 true가 나온다면 전체 함수 끝
public boolean available(Schedule[] days, Schedule sample, int index, int length, int day) {
sample.setDay(day);
if (index == 1) { // 한개로 전체가 merging된 경우 시작시간 - 9시 or 10시 - 끝난시간 해서 이게 length 안이면 return true
if (days[0].getStartTime().getHour() * 100 + days[0].getStartTime().getMinute() - 900 >= length) {
sample.setStartTime(new Time(9, 0));
int hour = length / 100;
int minute = length % 100;
sample.setEndTime(new Time(sample.getStartTime().getHour() + hour, sample.getStartTime().getMinute() + minute));
return true;
} else if (2400 - days[0].getEndTime().getHour() * 100 + days[0].getEndTime().getMinute() >= length) {
sample.setStartTime(days[0].getEndTime());
int hour = length / 100;
int minute = length % 100;
sample.setEndTime(new Time(sample.getStartTime().getHour() + hour, sample.getStartTime().getMinute() + minute));
return true;
} else return false;
} else if (index > 1) { // index가 2개 이상이면 index 0 의 시작시간 - 9시 해서 length 안쪽이면 return true 아닐 경우 (index i+1 시작 시간) - (index i 끝시간) 일 경우 return true, 아니면 10시(default 마지막 시간) - (index i 끝시간) 이면 return true
if (days[0].getStartTime().getHour() * 100 + days[0].getStartTime().getMinute() - 900 >= length) {
sample.setStartTime(new Time(9, 0));
int hour = length / 100;
int minute = length % 100;
sample.setEndTime(new Time(sample.getStartTime().getHour() + hour, sample.getStartTime().getMinute() + minute));
return true;
}
for (int i = 0; i < index - 1; i++) {
int hour = days[i + 1].getStartTime().getHour() - days[i].getEndTime().getHour();
int minute = days[i + 1].getStartTime().getMinute() - days[i].getEndTime().getMinute();
if (minute < 0) {
hour--;
minute = 60 + minute;
}//60분이기 때문에 그에 맞춰서 다시 계산해주기
if (hour * 100 + minute >= length) {
sample.setStartTime(new Time(days[i].getEndTime().getHour(), days[i].getEndTime().getMinute()));
int endMinute = days[i].getEndTime().getMinute() + length % 100;
int endHour = days[i].getEndTime().getHour() + length / 100;
if (endMinute >= 60) {
endHour++;
endMinute = endMinute - 60;
}
sample.setEndTime(new Time(endHour, endMinute));
return true;
}
}
if (2400 - days[index - 1].getEndTime().getHour() * 100 + days[index - 1].getEndTime().getMinute() >= length) {
sample.setStartTime(days[index - 1].getEndTime());
int hour = length / 100;
int minute = length % 100;
sample.setEndTime(new Time(sample.getStartTime().getHour() + hour, sample.getStartTime().getMinute() + minute));
return true;
}
}
return false;
}
/*
if the planName is not set, change schedule which has same name of planName.
*/
public void setColor(String planName) {
ArrayList<String> a = new ArrayList<String>();
a.add(planName);
timetable.setTableColor();
if (!planName.equals("not yet !@!@#@$")) {
timetable.setGroupPlanColor(a);
}
}
public int nextWeekday(int now) {
if (now < 6) {
return now + 1;
} else {
return 0;
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private int getDateDif(LocalDate dgf, LocalDate target) {
return dgf.compareTo(target);
}
private void deleteGroupPlan() {
groupRef.child(groupCode).child("GroupSchedule").child("schedule").setValue("0");
}
private void deletePlan(String title, String date, String time,String ID) {
planRef.child(ID).child(date + "_" + time + "_" + title).setValue(null).addOnSuccessListener(new OnSuccessListener<Void>() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onSuccess(Void unused) {
reset();
}
});
}
private void deleteSchedule(String title, String startDate, String endDate, String time, String weekdayIndex,String ID) {
scheduleRef.child(ID).child(startDate + "~" + endDate + "_" + time + "_" + title + "_" + weekdayIndex).setValue(null);
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void addPlan(String date, String startTime, String endTime, String title) {
startTime = convertPlanTime(startTime);
endTime = convertPlanTime(endTime);
String finalDate[] = convertPlanDate(date);
String finalStartTime = startTime;
String finalEndTime = endTime;
groupRef.child(groupCode).child("members").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
for (DataSnapshot member : task.getResult().getChildren()) {
planRef.child(member.getKey()).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) {
planRef.child(member.getKey()).child(finalDate[0] + finalDate[1] + finalDate[2] + "_" + finalStartTime + "~" + finalEndTime + "_" + title).child("title").setValue(title);
planRef.child(member.getKey()).child(finalDate[0] + finalDate[1] + finalDate[2] + "_" + finalStartTime + "~" + finalEndTime + "_" + title).child("date").setValue(finalDate[0] + "/" + finalDate[1] + "/" + finalDate[2]);
planRef.child(member.getKey()).child(finalDate[0] + finalDate[1] + finalDate[2] + "_" + finalStartTime + "~" + finalEndTime + "_" + title).child("time").setValue(finalStartTime + "~" + finalEndTime);
}
});
}
}
});
}
public String[] convertPlanDate(String date) {
String[] dateSplit = date.split("/");
if (Integer.parseInt(dateSplit[0]) < 10) {
dateSplit[0] = "0" + dateSplit[0];
}
if (Integer.parseInt(dateSplit[1]) < 10) {
dateSplit[1] = "0" + dateSplit[1];
}
if (Integer.parseInt(dateSplit[2]) < 10) {
dateSplit[2] = "0" + dateSplit[2];
}
return dateSplit;
}
public String convertPlanTime(String time) {
String[] timeSplit = time.split(":");
if (Integer.parseInt(timeSplit[0]) < 10) {
timeSplit[0] = "0" + timeSplit[0];
}
if (Integer.parseInt(timeSplit[1]) < 10) {
timeSplit[1] = "0" + timeSplit[1];
}
return timeSplit[0] + ":" + timeSplit[1];
}
public int getWeekdayIndex(String weekday) {
if (weekday.equals("SUNDAY")) {
return 0;
} else if (weekday.equals("MONDAY")) {
return 1;
} else if (weekday.equals("TUESDAY")) {
return 2;
} else if (weekday.equals("WEDNESDAY")) {
return 3;
} else if (weekday.equals("THURSDAY")) {
return 4;
} else if (weekday.equals("FRIDAY")) {
return 5;
} else if (weekday.equals("SATURDAY")) {
return 6;
} else {
return 0;
}
}
public int getHeaderIndex(String weekday) {
if (weekday.equals("SUNDAY")) {
return 1;
} else if (weekday.equals("MONDAY")) {
return 2;
} else if (weekday.equals("TUESDAY")) {
return 3;
} else if (weekday.equals("WEDNESDAY")) {
return 4;
} else if (weekday.equals("THURSDAY")) {
return 5;
} else if (weekday.equals("FRIDAY")) {
return 6;
} else if (weekday.equals("SATURDAY")) {
return 7;
} else {
return 0;
}
}
public Task<String> sendFCM(String regToken, String title, String message, String SubTitle) {
Map<String, Object> data = new HashMap<>();
data.put("token", regToken);
data.put("text", message);
data.put("title", title); // 그룹명
data.put("subtext", SubTitle);
data.put("android_channel_id", "Group");
return mFunctions
.getHttpsCallable("sendFCM")
.call(data)
.continueWith(new Continuation<HttpsCallableResult, String>() {
@Override
public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
String result = (String) Objects.requireNonNull(task.getResult()).getData().toString();
Log.d("SendPush", "then: " + result);
return result;
}
});
}
private void On_MakeNotification(String token, String Title, String text, String SubTitle) {
sendFCM(token, Title, text, SubTitle)
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (!task.isSuccessful()) {
Exception e = task.getException();
if (e instanceof FirebaseFunctionsException) {
FirebaseFunctionsException ffe = (FirebaseFunctionsException) e;
FirebaseFunctionsException.Code code = ffe.getCode();
Object details = ffe.getDetails();
}
Log.w("SendPush", "makeNotification:onFailure", e);
return;
}
String result = task.getResult();
}
});
}
}
|
package com.my.servlet;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.FileInputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
/**
* Класс работы с БД
*/
public class UserDB {
private static String url = "jdbc:postgresql://localhost:5432/Gorbunov_Servlet";
private static String username = "postgres";
private static String password = "5432";
/**
* Получение списка всех зарегистрированных пользователей
* @return Список пользователей
*/
public static ArrayList<User> select() {
ArrayList<User> users = new ArrayList<User>();
try{
Class.forName("org.postgresql.Driver").getDeclaredConstructor().newInstance();
try (Connection conn = DriverManager.getConnection(url, username, password)) {
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
while(resultSet.next()){
int id = resultSet.getInt(1);
String u_login = resultSet.getString(2);
String u_password = resultSet.getString(3);
User user = new User(id, u_login, u_password);
users.add(user);
}
}
}
catch(Exception ex){
System.out.println(ex);
}
return users;
}
public static void saveDocument(StringBuilder data, String filename, String path) {
try {
String str = "";
Class.forName("org.postgresql.Driver").getDeclaredConstructor().newInstance();
try (Connection connection = DriverManager.getConnection(url, username, password)) {
String n = filename.replaceAll("\\.", "|");
if (n.split("\\|")[1].equals("doc")) {
FileInputStream fileInputStream = new FileInputStream(path + "\\" + filename);
HWPFDocument document = new HWPFDocument(fileInputStream);
WordExtractor extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++) {
if (fileData[i] != null) str += fileData[i] + " ";
}
} else if (n.split("\\|")[1].equals("docx")) {
FileInputStream fileInputStream = new FileInputStream(path + "\\" + filename);
XWPFDocument document = new XWPFDocument(fileInputStream);
XWPFWordExtractor extractor = new XWPFWordExtractor(document);
str = extractor.getText();
} else {
str = data.toString();
}
PreparedStatement statement = connection.prepareStatement("INSERT INTO documents (data) VALUES (?)");
statement.setString(1, str);
statement.executeUpdate();
statement.executeUpdate();
} catch (Exception ex) {
System.out.println(ex);
}
} catch (InstantiationException |
InvocationTargetException |
NoSuchMethodException |
IllegalAccessException |
ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
/*
* Copyright (C) 2019 TopCoder Inc., All Rights Reserved.
*/
package com.tmobile.percy;
import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;
/**
* The yaml file type factory.
*
* @author TCSCODER
* @version 1.0
*/
public class PercyFileTypeFactory extends FileTypeFactory {
/**
* Create file type.
*
* @param fileTypeConsumer The file type consumer
*/
@Override
public void createFileTypes(FileTypeConsumer fileTypeConsumer) {
fileTypeConsumer.consume(PercyFileType.INSTANCE,
String.join(FileTypeConsumer.EXTENSION_DELIMITER, PercyFileType.EXTENSIONS));
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mathsapp;
import java.io.Serializable;
/**
*
*
*/
public class Records implements Serializable{
private String name;
private String surname;
private String history;
public Records(){
name = new String();
surname = new String();
history = new String();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getHistory() {
return history;
}
public void setHistory(String history) {
this.history = history;
}
}
|
package scriptinterface.execution.returnvalues;
public class ExecutionBreak extends ExecutionFunctionReturn {
public ExecutionBreak(ExecutionReturn value) {
super(value);
}
@Override
public String toString() {
return "Break";
}
}
|
package chapter_1_07_Swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
public class SampleFrame {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("sd");
//EventQueue.invokeLater
JFrame ff = new JFrame();
MyFrame f = new MyFrame();
f.setSize();
f.setImage();
//f.setContent();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
JButton b = new JButton("emo");
b.setAction(new AbstractAction("emo2") {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.print(" action source: " + e.getSource());
JButton b = (JButton)e.getSource();
JPanel p = (JPanel)b.getParent();
JTextField text = (JTextField)p.getComponent(1);
text.setColumns(10);
//p.revalidate();
//JFrame f = (JFrame)p.getParent();
System.out.println("");
System.out.println(" panel: " + p);
System.out.println(" panel parent: " + p.getParent());
System.out.println(" panel parent parent: " + p.getParent().getParent());
System.out.println(" panel parent parent: " + p.getParent().getParent().getParent());
System.out.println(" panel parent parent: " + p.getParent().getParent().getParent().getParent());
//JFrame f = (JFrame)p.getParent().getParent().getParent().getParent();
JFrame f = (JFrame)SwingUtilities.getAncestorOfClass(JFrame.class, p);
f.validate(); // = p.revalidate();
}
});
b.getModel();
JPanel panel = new JPanel();
panel.add(b);
final JTextField t = new JTextField("input", 30);
panel.add(t);
final JTextArea ta = new JTextArea(3, 10);
JScrollPane scroll = new JScrollPane(ta);
panel.add(scroll);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.print(" 1111 " + e.getSource());
ta.setColumns(5);
ta.revalidate();
}
});
panel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.BLUE, Color.RED));
JComboBox cb = new JComboBox<String>();
cb.addItem("one");
cb.addItem("two");
cb.setEditable(true);
panel.add(cb);
JSlider slide = new JSlider(SwingConstants.VERTICAL, 0, 100, 15);
slide.setMinorTickSpacing(10);
slide.setMajorTickSpacing(20);
slide.setPaintTicks(true);
slide.setPaintLabels(true);
slide.setSnapToTicks(true);
panel.add(slide);
f.add(panel, BorderLayout.SOUTH);
JMenuBar mb = new JMenuBar();
JMenu menu = new JMenu("top");
menu.add(new JMenuItem("one", 'O'));
menu.add(new JMenuItem("two"));
JMenu inside = new JMenu("inside");
inside.add(new JCheckBoxMenuItem("in one"));
inside.add(new JMenuItem("in two"));
menu.addSeparator();
menu.add(inside);
mb.add(menu);
//f.setJMenuBar(mb); //add to TOP
f.add(mb, BorderLayout.EAST);
JPopupMenu popup = new JPopupMenu();
popup.add("One p");
panel.setComponentPopupMenu(popup);
JToolBar tb = new JToolBar("ToolBar", SwingConstants.VERTICAL);
tb.add("one t", new JButton("in one t"));
f.add(tb, BorderLayout.WEST);
f.setLayout(new GridLayout(2,2));
f.pack();
//System.out.print("\n:" + JOptionPane.showInputDialog("mess"));
final JDialog dialog = new JDialog();
final JTextField dtext = new JTextField();
dialog.add(dtext, BorderLayout.CENTER);
JButton dbutton = new JButton();
dbutton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
dialog.setVisible(false);
ta.setText(dtext.getText());
}
});
dialog.add(dbutton, BorderLayout.EAST);
dialog.pack();
dialog.setVisible(true);
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(f);
if (fileChooser.getSelectedFile() != null)
ta.setText(fileChooser.getSelectedFile().getPath());
Color c = JColorChooser.showDialog(f, "color", Color.RED);
if (c != null)
t.setText(c.toString());
}
static class MyFrame extends JFrame {
public void setSize() {
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screen = kit.getScreenSize();
super.setSize(screen.height/5, screen.width/5);
}
public void setImage() {
Image i = new ImageIcon("D:\\_Temp\\_er\\11.jpg").getImage();
File f = new File("D:\\_Temp\\_er\\11.jpg");
System.out.print(" 11.jpg exists: " + f.exists());
setIconImage(i);
}
public void setContent() {
Container cPanel = getContentPane();
cPanel.add(new JComponent() {
@Override
public void paintComponent (Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.drawString("Some Sring", 100, 50);
}
});
add(new JComponent() {
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.drawString("Other sring", 100, 150);
g.drawString("Other 4 sring", 100, 250);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(Color.GREEN);
g2d.setPaint(new Color(24,126,215).brighter().brighter());
Rectangle2D r = new Rectangle2D.Double(50.3, 50.22, 100.442, 150.21);
g2d.draw(r);
g2d.fill(r);
}
});
}
}
}
|
package com.jk.jkproject.ui.inter;
public interface LiveRelease {
void release();
}
|
package com.CollectionsMap;
/**
* Created by Mallika Aruva on 2/16/2018.
*/
public class MainMapTest {
public static void main(String[] args) {
DemoLookUp demoLookUp = new DemoLookUp();
//see if this added
demoLookUp.addProduct(new Product("Java", 20, 1));
Product product = demoLookUp.lookUpByID(1);
System.out.println(product.getName());
//Checking for duplicates, should throw exception
demoLookUp.addProduct(new Product("angular", 50, 1));
Product product2 = demoLookUp.lookUpByID(1);
System.out.println(product.getName());
}
}
|
package com.github.mikewtao.webf.mvc;
import java.lang.reflect.Method;
import com.github.mikewtao.webf.annotation.RequestMethod;
public class WebHandler {
private Method method;// 处理方法
private RequestMethod[] reqMethod;// 请求方式
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public RequestMethod[] getReqMethod() {
return reqMethod;
}
public void setReqMethod(RequestMethod[] reqMethod) {
this.reqMethod = reqMethod;
}
}
|
package com.sporsimdi.action.util.spi;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.sporsimdi.action.util.UtilDate;
public abstract class SSSchedulerBase implements Serializable {
private static final long serialVersionUID = 6241171977842416805L;
private List<UtilDate> dateList = new ArrayList<UtilDate>();
protected String baseName;
private boolean dateAtBegin = false;
private boolean dateAtEnd = false;
public SSSchedulerBase() {
getDateList().add(new UtilDate());
setBaseName();
controlDateLimits();
}
public SSSchedulerBase(UtilDate date) {
getDateList().add(date);
}
public List<UtilDate> getDateList() {
return dateList;
}
public void setDateList(List<UtilDate> dateList) {
this.dateList = dateList;
}
public String getBaseName() {
return baseName;
}
public boolean isDateAtBegin() {
return dateAtBegin;
}
public void setDateAtBegin(boolean dateAtBegin) {
this.dateAtBegin = dateAtBegin;
}
public boolean isDateAtEnd() {
return dateAtEnd;
}
public void setDateAtEnd(boolean dateAtEnd) {
this.dateAtEnd = dateAtEnd;
}
protected abstract void setBaseName();
public abstract String getDisplayName(int index);
public abstract UtilDate getDateBegin(int index);
public abstract UtilDate getDateEnd(int index);
public abstract void addFirstDate();
public abstract void addPrevDate();
public abstract void addNextDate();
public abstract void addLastDate();
public abstract void controlDateLimits();
}
|
package assgn.hooi;
import assgn.DMHome;
import assgn.JianKai.aff;
import javax.swing.table.DefaultTableModel;
import listLink.JKLL;
import listLink.JKLLI;
import listLink.ListLink;
import listLink.ListLinkInt;
import listLink.store;
/**
*
* @author Aphro97
*/
public class orderReport extends javax.swing.JFrame {
store save;
DefaultTableModel model;
LinkQueueInt<Order1> order = new LinkQueue<>();
ListLinkInt<Cart> cartHi = new ListLink<>();
ListLinkInt<Cart> cart = new ListLink<>();
JKLLI<aff> aff = new JKLL<>();
aff affi;
Order1 o;
public orderReport() {
initComponents();
save = new store(1);
setup();
}
public orderReport(store save) {
initComponents();
this.save = save;
setup();
}
private void setup(){
this.setTitle("Order Report");
this.setVisible(true);
this.setLocationRelativeTo(null);
model = (DefaultTableModel)reportTable.getModel();
reportTable.setModel(model);
order = save.getOrder();
aff = save.getAff();
cartHi = save.getCartHi();
double avg = 0.0;
int numOfOrder = 0;
for(int n=1;n<aff.getSize()+1;n++){
affi = aff.get(n);
for(int a=0;a<order.size();a++){
o = order.get(a);
if(affi.getAid().equals(o.getAffID())){
for(int b=1;b<cartHi.getSize()+1;b++){
if(cartHi.get(b).getCartID().equals(o.getCartID())){
System.out.println("Checking: "+cartHi.get(b).getCartID()+"@"+cartHi.get(b).getTotal()+"@"+cartHi.get(b).getItemName());
avg += cartHi.get(b).getTotal();
System.out.println(avg);
}
}
numOfOrder++;
}
}
if(avg == 0.0){
model.addRow(new Object[]{affi.getResname(),affi.getAid(),numOfOrder,0.0});
}else{
avg = avg/(numOfOrder);
model.addRow(new Object[]{affi.getResname(),affi.getAid(),numOfOrder,avg});
}
avg = 0.0;
numOfOrder = 0;
}
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
reportTable = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
reportTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Restaurant", "Affiliate ID", "Number of Order", "Average price"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(reportTable);
if (reportTable.getColumnModel().getColumnCount() > 0) {
reportTable.getColumnModel().getColumn(0).setResizable(false);
reportTable.getColumnModel().getColumn(1).setResizable(false);
reportTable.getColumnModel().getColumn(2).setResizable(false);
reportTable.getColumnModel().getColumn(3).setResizable(false);
}
jButton1.setText("Back");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 379, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(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
// TODO add your handling code here:
this.setVisible(false);
DMHome next = new DMHome(save);
next.setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(orderReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(orderReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(orderReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(orderReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new orderReport().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable reportTable;
// End of variables declaration//GEN-END:variables
}
|
package cn.edu.hebtu.software.sharemate.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import cn.edu.hebtu.software.sharemate.Adapter.ChatListAdapter;
import cn.edu.hebtu.software.sharemate.Bean.ChatBean;
import cn.edu.hebtu.software.sharemate.Bean.UserBean;
import cn.edu.hebtu.software.sharemate.R;
public class ChatActivity extends AppCompatActivity {
private List<ChatBean> chats = new ArrayList<>();
private UserBean me ;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
me = new UserBean("bjt的小公主",R.drawable.me);
listView = findViewById(R.id.lv_content);
Intent intent = getIntent();
UserBean user = (UserBean) intent.getSerializableExtra("user");
TextView nameView = findViewById(R.id.tv_name);
nameView.setText(user.getUserName());
switch (user.getUserName()){
case "白敬亭":
chats.add(new ChatBean(me,"亲爱的,在么?",0));
chats.add(new ChatBean(user,"在呢,刚录完明星大侦探。怎么了",1));
chats.add(new ChatBean(me,"明天我们出去吃饭吧,吃你喜欢吃的",0));
chats.add(new ChatBean(user,"那明天我们一起出去吃火锅!",1));
break;
case "王鸥":
chats.add(new ChatBean(user,"小公主,我收工了",1));
chats.add(new ChatBean(me,"鸥姐辛苦了!",0));
chats.add(new ChatBean(user,"刚刚录完明星大侦探",1));
chats.add(new ChatBean(user,"我刚才还和小白说你呢",1));
chats.add(new ChatBean(me,"明天你有空么?",0));
chats.add(new ChatBean(me,"我和小白说明天去吃火锅!",0));
chats.add(new ChatBean(user,"好呀",1));
chats.add(new ChatBean(me,"说定了呀",0));
break;
case "你的小可爱":
chats.add(new ChatBean(me,"您的小公主已上线!",0));
chats.add(new ChatBean(user,"臭不要脸",1));
chats.add(new ChatBean(me,"你上回分享的那个大理石眼影盘也太好看了吧!",0));
chats.add(new ChatBean(user,"那是,也不看是谁的眼光",1));
chats.add(new ChatBean(me,"你是魔鬼么做个人不好么?",0));
break;
case "plly":
chats.add(new ChatBean(me,"暑假在必胜客赚了多少钱?",0));
chats.add(new ChatBean(user,"没多少,每天又累又困,工资还很少.",1));
chats.add(new ChatBean(me,"没关系马上就开学了。想我么?",0));
chats.add(new ChatBean(user,"天哪!时间过的也太快了吧!已经开学了!",1));
break;
}
ChatListAdapter adapter = new ChatListAdapter(this,chats,R.layout.chat_left_item_layout,R.layout.chat_right_item_layout);
listView.setAdapter(adapter);
//为返回按钮绑定事件
Button back = findViewById(R.id.btn_back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
|
package leecode.other;
import java.util.Arrays;
public class 计数质数_204 {
public int countPrimes(int n) {
int count=0;
for (int i = 2; i <n ; i++) {//从2开始
//判断素数
if(isPrime(i)){
count++;
}
}
return count;
}
public boolean isPrime(int n){
for (int i = 2; i <n ; i++) {
if(n%i==0){//这里是 n%i 不是 2
return false;
}
}
return true;
}
//优化1
public int countPrimes2(int n) {
boolean[] isPrime=new boolean[n];
Arrays.fill(isPrime,true);
for (int i = 2; i <n ; i++) {
if(isPrime[i]){
// i的倍数就不可能是素数了
// 2是一个素数,那么 2*2 2*3 2*4 。。。。都不是素数
// 每次 j=j+i 开始 j=2*2 循环一次加2 相当于 2*3
for (int j = 2*i; j <n ; j=j+i) {
isPrime[j]=false;
}
}
}
int count=0;
for (int i = 2; i <n ; i++) {
if(isPrime[i]){
count++;
}
}
return count;
}
//优化2
public int countPrimes3(int n) {
boolean[]isPrime=new boolean[n];
Arrays.fill(isPrime,true);
for (int i = 2; i <n ; i++) {
if(isPrime[i]){
for (int j = i*i; j <n ; j=j+i) {//从i*i开始
isPrime[j]=false;
}
}
}
int count=0;
for (int i = 2; i <n ; i++) {
if(isPrime[i]){
count++;
}
}
return count;
}
}
|
package com.shakeboy.controller;
import com.alibaba.fastjson.JSON;
import com.shakeboy.pojo.Book;
import com.shakeboy.pojo.Star;
import com.shakeboy.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.websocket.server.PathParam;
import java.util.List;
@RestController
@RequestMapping("/book")
public class BookController {
@Autowired
private BookService bookService;
// 获取所有书籍,最后渲染十本
@RequestMapping("/getAllBooks")
public String getAllBooks(){
List<Book> bookList = bookService.getAllBooks();
return JSON.toJSONString(bookList);
}
// 关键字搜索书籍
@RequestMapping("/searchByBookName")
public String searchByBookName(@PathParam("value")String value){
List<Book> books = bookService.searchByBookName(value);
return JSON.toJSONString(books);
}
// 关键字搜索书籍
@RequestMapping("/search")
public String search(@PathParam("value")String value){
List<Book> books = bookService.search(value);
return JSON.toJSONString(books);
}
// 通过种类搜索
@RequestMapping("/searchByType")
public String searchByType(@PathParam("book_type") String book_type){
List<Book> books = bookService.searchByType(book_type);
return JSON.toJSONString(books);
}
// 收藏star
@PostMapping("/star")
public String star(@PathParam("user_id")int user_id,@PathParam("book_id")int book_id){
System.out.println(user_id+"==="+book_id);
return bookService.star(user_id,book_id).toString();
}
// 收藏star
@PostMapping("/cancelStar")
public String cancelStar(@PathParam("user_id")int user_id,@PathParam("book_id")int book_id){
System.out.println(user_id+"==="+book_id);
return bookService.cancelStar(user_id,book_id).toString();
}
// getStarId
@RequestMapping("/getStarId")
public String getStarId(@PathParam("user_id")int user_id){
List<Star> stars = bookService.getStarId(user_id);
return JSON.toJSONString(stars);
}
//getBookById
@RequestMapping("/getBookById")
public String getBookById(@PathParam("book_id")int book_id){
Book book = bookService.getBookById(book_id);
return JSON.toJSONString(book);
}
}
|
package com.alonemusk.medicalapp.ui.utils;
import android.net.Uri;
import androidx.annotation.NonNull;
import com.alonemusk.medicalapp.ui.models.CallRequest;
import com.alonemusk.medicalapp.ui.models.Doctor;
import com.alonemusk.medicalapp.ui.models.OrdersByPres;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.UploadTask;
public class FirebaseUtils {
public static void getDoctor(final listener<Doctor> listener){
FirebaseDatabase.getInstance().getReference("calls").child("admins").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for( DataSnapshot a:dataSnapshot.getChildren()){
Doctor doctor=a.getValue(Doctor.class);
if(doctor.getAvailable()){
listener.onSuccess(doctor);
break;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public static void uploadOrderByPres(final OrdersByPres order, Uri uri, final listener<String> listener){
FirebaseStorage.getInstance().getReference(order.getOrderId()).child(order.getTimestamp()).putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
FirebaseDatabase.getInstance().getReference("ordersByPres").push().setValue(order).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
listener.onSuccess("Yo");
}
});
}
});
}
public static void requestPhone(String phone, String message, final listener<String>listener) {
FirebaseDatabase.getInstance().getReference("calls").child("requests").push().setValue(new CallRequest(phone, message, Utils.Companion.getTime())).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
listener.onSuccess("Request successfully send");
}
});
}
public interface listener<T>{
public void onSuccess(T it);
public void onError(DatabaseError it);
}
}
|
/**
* original(c) zhuoyan company
* projectName: java-design-pattern
* fileName: LogSend.java
* packageName: cn.zy.pattern.command.log
* date: 2018-12-20 21:21
* history:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package cn.zy.pattern.command.log;
import java.util.ArrayList;
import java.util.List;
/**
* @version: V1.0
* @author: ending
* @className: LogSend
* @packageName: cn.zy.pattern.command.log
* @description:
* @data: 2018-12-20 21:21
**/
public class LogSend{
private List<LogCommand> commands = new ArrayList<>();
private LogCommand logCommand;
public LogCommand getLogCommand() {
return logCommand;
}
public void setLogCommand(LogCommand logCommand) {
this.logCommand = logCommand;
}
public void execute(String name){
logCommand.execute(name);
commands.add(logCommand);
}
} |
package org.tomat.translate.brooklyn;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.tomat.ResourcePathResolver;
import org.tomat.agnostic.application.AgnosticApplication;
import org.tomat.agnostic.application.ApplicationAgnosticMetadata;
import org.tomat.exceptions.AgnosticPropertyException;
import org.tomat.exceptions.NodeTemplateTypeNotSupportedException;
import org.tomat.exceptions.TopologyTemplateFormatException;
import org.tomat.tosca.parsers.ToscaProcessor;
import org.tomat.translate.brooklyn.entity.BrooklynApplicationEntity;
import org.tomat.translate.brooklyn.entity.BrooklynEntity;
import org.tomat.translate.brooklyn.entity.BrooklynServiceEntity;
import org.tomat.translate.brooklyn.exceptions.BrooklynVisitorRelationConfigurationNotSupportedType;
import org.tomat.translate.exceptions.NotSupportedTypeByTechnologyException;
import java.io.IOException;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* Created by Kiuby88 on 15/10/14.
*/
public class BrooklynTranslatorSimpleAppTest {
ToscaProcessor toscaProcessor;
String file;
AgnosticApplication agnosticApplication;
BrooklynTranslator brooklynTranslator;
BrooklynApplicationEntity brooklynApplicationEntity;
String yamlFile;
public BrooklynTranslatorSimpleAppTest()
throws AgnosticPropertyException, TopologyTemplateFormatException,
NodeTemplateTypeNotSupportedException {
setUp();
}
//TODO refactor test to init using less code
public static void main(String[] args) {
Result result = JUnitCore.runClasses(BrooklynTranslatorSimpleAppTest.class);
}
public void setUp() throws TopologyTemplateFormatException,
NodeTemplateTypeNotSupportedException, AgnosticPropertyException {
ResourcePathResolver resourcePathResolver= new ResourcePathResolver();
file=resourcePathResolver.getPathFile(ResourcePathResolver.AWS_LOCATION_SAMPLE);
yamlFile=resourcePathResolver.getPathFile(ResourcePathResolver.SIMPLE_DB_APP_YAML);
toscaProcessor = new ToscaProcessor();
toscaProcessor
.parsingApplicationTopology(file).buildAgnostics();
agnosticApplication=new AgnosticApplication(toscaProcessor);
brooklynTranslator=new BrooklynTranslator(agnosticApplication);
}
@Test
public void testBrooklynTranslationCreation_Empty(){
agnosticApplication=new AgnosticApplication(new ToscaProcessor());
brooklynTranslator=new BrooklynTranslator(agnosticApplication);
brooklynApplicationEntity=brooklynTranslator.getBrooklynApplicationEntity();
Assert.assertNotNull(brooklynApplicationEntity);
assertEquals(brooklynApplicationEntity.getId(), ApplicationAgnosticMetadata.APPLICATION_ID_BY_DEFAULT);
assertEquals(brooklynApplicationEntity.getName(), ApplicationAgnosticMetadata.APPLICATION_NAME_BY_DEFAULT);
assertEquals(brooklynApplicationEntity.getLocation(), BrooklynEntity.LOCATION_BY_DEFAULT);
assertEquals(brooklynApplicationEntity.getServices().size(), 0);
}
@Test
public void testBrooklynTranslatorMetadata() {
brooklynApplicationEntity=brooklynTranslator.getBrooklynApplicationEntity();
Assert.assertNotNull(brooklynApplicationEntity);
assertEquals(brooklynApplicationEntity.getId(), "AppOnlineRetailing");
assertEquals(brooklynApplicationEntity.getName(), "OnlineRetailing Template");
assertEquals(brooklynApplicationEntity.getLocation(), BrooklynEntity.LOCATION_BY_DEFAULT);
}
@Test
public void testBrooklynTranslating_Empty()
throws NotSupportedTypeByTechnologyException,
BrooklynVisitorRelationConfigurationNotSupportedType {
agnosticApplication=new AgnosticApplication(new ToscaProcessor());
brooklynTranslator=new BrooklynTranslator(agnosticApplication);
brooklynTranslator.translate();
}
@Test
public void testBrooklynTranslating() throws NotSupportedTypeByTechnologyException,
BrooklynVisitorRelationConfigurationNotSupportedType {
brooklynTranslator.translate();
brooklynApplicationEntity=brooklynTranslator.getBrooklynApplicationEntity();
assertEquals(brooklynApplicationEntity.getServices().size(),1);
List<BrooklynServiceEntity> service = brooklynApplicationEntity.getServices();
BrooklynServiceEntity jBossBrooklynService=service.get(0);
Assert.assertNotNull(jBossBrooklynService.getBrooklynConfigProperties());
assertEquals(jBossBrooklynService.getBrooklynConfigProperties().size(), 1);
assertEquals(jBossBrooklynService.getBrooklynConfigProperties().get("port.http"), "80+");
}
@Test
public void testBrooklynPrinting()
throws NotSupportedTypeByTechnologyException, IOException,
BrooklynVisitorRelationConfigurationNotSupportedType {
brooklynTranslator.translate();
brooklynApplicationEntity=brooklynTranslator.getBrooklynApplicationEntity();
brooklynTranslator.print(yamlFile);
}
}
|
import java.util.*;
class ShuffleArray {
public void shuffle(int[] nums) {
Random random = new Random();
for (int i = nums.length - 1; i >= 0; i--) {
int index = random.nextInt(i + 1);
if (i != index) {
swap(nums, index, i);
}
}
}
private void swap(int[] nums, int i, int j) {
nums[i] = nums[i] ^ nums[j];
nums[j] = nums[i] ^ nums[j];
nums[i] = nums[i] ^ nums[j];
}
public static void main(String[] args) {
int[] nums = new int[]{1, 2, 3, 4, 5, 6, 16, 15, 14, 13, 12, 11};
ShuffleArray test = new ShuffleArray();
test.shuffle(nums);
System.out.println(Arrays.toString(nums));
}
}
|
package models;
public class Token {
private int user_id;
private String token;
public Token() {
}
public Token(String token) {
this.token = token;
}
public Token(int user_id, String token) {
this.user_id = user_id;
this.token = token;
}
public int getUser_id() {
return user_id;
}
public String getToken() {
return token;
}
}
|
package zuoshen.list;
//对比lee 114
public class 搜索二叉树转换成双向链表 {
public TreeNode_two head=null;//指针,已经转化好链表的尾部,这个head是始终指向已经转换链表的尾部节点
public TreeNode_two realHead=null;//双向链表的头部
// 把树的left,right 转为链表的前后指针,所以没有使用链表节点,只使用树节点就可以
public void transfer(TreeNode_two treenode){//要转化二叉搜索树的头部
if(treenode==null){//树节点先考虑null,递归终止,对节点单独处理时考虑head为null
return ;
}
transfer(treenode.left);//搜索二叉树,转化为有序链表,所以中序遍历
if(head==null){
head=treenode;
realHead=treenode;
}else {
head.right=treenode;
treenode.left=head;
head=treenode;
}
transfer(treenode.right);
}
}
|
/*
* 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 areaperimetro;
/**
*
* @author ESTUDIANTE
*/
public class Circulo4 extends Figura4 {
private float radioCirc;
public void establecerRadioCirc(float radioCirc) {
this.radioCirc = radioCirc;
}
@Override
public void calcularArea() {
super.area = (float) Math.PI * (float) Math.pow(this.radioCirc, 2);
}
@Override
public void calcularPerim() {
super.perim = 2 * (float) Math.PI * this.radioCirc;
}
}
|
package ru.vlad805.mapssharedpoints;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import java.util.Date;
import java.util.List;
import mjson.Json;
public class EditPointActivity extends ExtendedActivity {
private Point point = null;
private int pointId;
private EditText evTitle;
private EditText evDescription;
private CheckBox cbIsPublic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
hideActionBar();
setContentView(R.layout.activity_editing);
evTitle = (EditText) findViewById(R.id.edit_title);
evDescription = (EditText) findViewById(R.id.edit_description);
cbIsPublic = (CheckBox) findViewById(R.id.edit_isPublic);
Bundle extras = getIntent().getExtras();
if (extras != null) {
pointId = extras.getInt(Const.POINT_ID);
point = Point.getById(this, pointId);
}
if (point == null)
finish();
evTitle.setText(point.title);
evDescription.setText(point.description);
cbIsPublic.setChecked(point.isPublic);
}
public void onSubmit (View view) {
final String title = evTitle.getText().toString().trim();
final String description = evDescription.getText().toString().trim();
final boolean isPublic = cbIsPublic.isChecked();
if (title.isEmpty()) {
Utils.toast(this, "Введите название!");
return;
}
setProgressDialog(R.string.sync);
point.edit(getActivity(), new APICallback() {
@Override
public void onResult(Json result) {
closeProgressDialog();
List<Json> local = Json.read(Utils.getString(getActivity(), Const.SHARED_DATA)).asJsonList();
long updated = new Date().getTime() / 1000;
for (int i = 0, l = local.size(); i < l; ++i) {
if (local.get(i).at(Const.POINT_ID).asInteger() == pointId) {
local.get(i).set(Const.TITLE, title);
local.get(i).set(Const.DESCRIPTION, description);
local.get(i).set(Const.IS_PUBLIC, isPublic);
local.get(i).set(Const.DATE_UPDATED, updated);
point.title = title;
point.description = description;
point.isPublic = isPublic;
point.updated = updated;
}
}
Utils.setString(getActivity(), Const.SHARED_DATA, local.toString());
Utils.toast(getActivity(), R.string.point_saved);
finish();
}
@Override
public void onError(APIError e) {
showAPIError(e);
}
}, title, description, isPublic);
}
}
|
/**
*
*/
package com.cnk.travelogix.supplier.masters.core.interceptors;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.InterceptorException;
import de.hybris.platform.servicelayer.interceptor.ValidateInterceptor;
import de.hybris.platform.util.localization.Localization;
import org.apache.log4j.Logger;
import com.cnk.travelogix.masterdata.core.model.TravelogixPolicyModel;
import com.cnk.travelogix.supplier.core.daos.services.TravelogixPolicyService;
/**
* Interceptor to validate duplicacy of ProductCategorySubtype, PolicyType,Policy Category and Policy Name
*
*/
public class TravelogixPolicyValidateInterceptor implements ValidateInterceptor<TravelogixPolicyModel>
{
private static final Logger LOG = Logger.getLogger(TravelogixPolicyValidateInterceptor.class);
TravelogixPolicyService travelogixPolicyService;
@Override
public void onValidate(final TravelogixPolicyModel travelogixPolicyModel, final InterceptorContext ctx)
throws InterceptorException
{
if (LOG.isDebugEnabled())
{
LOG.info("Inside the onValidate method of AccoDynamicPolicyValidateInterceptor");
}
if (ctx.isNew(travelogixPolicyModel))
{
if (((travelogixPolicyModel.getProductCategorySubType() != null) && (travelogixPolicyModel.getPolicyCategory() != null)
&& (travelogixPolicyModel.getPolicyType() != null) && (travelogixPolicyModel.getName() != null))
&& (!travelogixPolicyService
.duplicacyOfSlab(travelogixPolicyModel.getProductCategorySubType(), travelogixPolicyModel.getPolicyType(),
travelogixPolicyModel.getName(), travelogixPolicyModel.getPolicyCategory())
.isEmpty()))
{
LOG.debug("Record is already exist.");
throw new InterceptorException(Localization.getLocalizedString("supplier.policy.duplicate"));
}
}
}
public TravelogixPolicyService getTravelogixPolicyService()
{
return travelogixPolicyService;
}
public void setTravelogixPolicyService(final TravelogixPolicyService travelogixPolicyService)
{
this.travelogixPolicyService = travelogixPolicyService;
}
}
|
package zm.gov.moh.common.submodule.form.widget;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.Bundle;
import android.text.InputFilter;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.content.ContextCompat;
import zm.gov.moh.common.R;
public class ReadonlyTextWidget extends TextViewWidget implements Submittable<CharSequence> {
protected String mValue;
protected String mHint;
protected Bundle mBundle;
protected AppCompatEditText mEditText;
private Context context;
public ReadonlyTextWidget(Context context){
super(context);
}
@Override
public String getValue() {
return mValue;
}
@Override
public void setValue(CharSequence value) {
mBundle.putString((String) this.getTag(),value.toString());
}
@Override
public boolean isValid() {
return true;
}
public void setHint(String hint){
mHint = hint;
}
@Override
public void setBundle(Bundle bundle) {
mBundle = bundle;
}
@Override
public void onCreateView() {
super.onCreateView();
mEditText = new AppCompatEditText(mContext);
mEditText.setHint(mHint);
mEditText.addTextChangedListener(WidgetUtils.createTextWatcher(this::setValue));
WidgetUtils.setLayoutParams(mEditText,WidgetUtils.MATCH_PARENT,WidgetUtils.WRAP_CONTENT, mWeight);
addView(mEditText);
//auto populate
String value = mBundle.getString((String) getTag());
if(value != null)
mEditText.setText(value);
//mEditText.setEnabled(false);
mEditText.setKeyListener(null);
}
@Override
public void addViewToViewGroup() {
}
AppCompatEditText getEditTextView(){
return mEditText;
}
public static class Builder extends TextViewWidget.Builder{
protected String mHint;
protected Bundle mBundle;
public Builder(Context context){
super(context);
}
public Builder setHint(String hint){
mHint = hint;
return this;
}
public Builder setBundle(Bundle bundle){
mBundle = bundle;
return this;
}
@Override
public BaseWidget build() {
// super.build();
EditTextWidget widget = new EditTextWidget(mContext);
if(mHint != null)
widget.setHint(mHint);
if(mBundle != null)
widget.setBundle(mBundle);
if(mLabel != null)
widget.setLabel(mLabel);
if(mTag != null)
widget.setTag(mTag);
widget.setTextSize(mTextSize);
widget.onCreateView();
return widget;
}
}
}
|
import java.util.*;
class ln{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
ll.add("A");
ll.add("B");
ll.addLast("C");
ll.addFirst("D");
ll.add(2,"E");
System.out.println(ll);
ll.remove(3);
ll.removeFirst();
ll.set(1,"F");
for(String str:ll)
System.out.print(str+" ");
LinkedList sec_list=new LinkedList();
sec_list=(LinkedList)ll.clone();
System.out.println("Second LinkedList is:"+sec_list);
System.out.println("The Object that replaced is:"+ll.set(2,"G"));
System.out.println("The element is:"+ll.get(2));
System.out.println("Does the List contains'A':"+ll.contains("A"));
ll.push("Z");
System.out.println(ll);
String s=ll.pop();
System.out.println(s);
Collection<String>collect=new ArrayList<String>();
collect.add("A");
collect.add("Computer");
ll.addAll(collect);
System.out.println("the first element is:"+ll.getFirst());
System.out.println("the last element is:"+ll.getLast());
System.out.println("The first element is:"+ll.removeFirst());
System.out.println("The last element is :"+ll.removeLast());
ll.addLast("Last");
ll.add("L");
ll.add("M");
ll.add("N");
System.out.println("The list is as fallows:");
ListIterator list_Iter=ll.listIterator(2);
while(list_Iter.hasNext()){
System.out.println(list_Iter.next());
}
System.out.println("The first occurrence of Fis at index:"+ll.indexOf("F"));
ll.clear();
System.out.println("List after clearing all elements:"+ll);
}
}
|
/**
*
*/
package com.yougou.yop.api.service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.yougou.dto.input.QueryCommodityInputDto;
import com.yougou.dto.output.QueryCommodityOutputDto;
import com.yougou.dto.output.QueryCommodityOutputDto.Product;
import com.yougou.merchant.api.supplier.service.ISupplierCommodityService;
import com.yougou.pc.api.ICommodityClientApiService;
import com.yougou.pc.api.ICommodityMerchantApiService;
import com.yougou.pc.model.commodityinfo.Commodity;
import com.yougou.pc.model.commodityinfo.CommodityDto;
import com.yougou.pc.model.commodityinfo.CommoditySearch;
import com.yougou.yop.api.IMerchantApiCommodityService;
/**
* @author zheng.qq
*
*/
@Service(value="merchantApiCommodityService")
public class MerchantApiCommodityService implements IMerchantApiCommodityService {
private final Logger logger = Logger.getLogger(MerchantApiCommodityService.class);
@Resource
ISupplierCommodityService supplierCommodityService;
@Resource
private ICommodityMerchantApiService commodityMerchantApiService;
@Override
public Object queryCommodity(Map<String, Object> parameterMap)
throws Exception {
// TODO Auto-generated method stub
QueryCommodityInputDto dto = new QueryCommodityInputDto();
BeanUtils.populate(dto, parameterMap);
if(StringUtils.isEmpty(dto.getMerchant_code())){
logger.error("商家编码不能为空!");
throw new Exception("商家编码不能为空!");
}
if(dto.getPage_size()==null || dto.getPage_size()>100 || dto.getPage_size()<=0){
logger.error("分页大小在(0-100]之间!");
throw new Exception("分页大小在(0-100]之间!");
}
if(dto.getPage_index()==null || dto.getPage_index()<0){
logger.error("页码必须是>0!");
throw new Exception("页码必须是>0!");
}
//转化page_index,以满足商品接口。
dto.setPage_index(dto.getPage_index()/dto.getPage_size() + 1);
logger.warn("商品下载接口入参:"+ToStringBuilder.reflectionToString(dto));
//商品状态调用货品接口入参
Integer[] status = null;
String commodityStatus = (String) parameterMap.get("status");
if(StringUtils.isNotBlank(commodityStatus)
&& StringUtils.isNumeric(commodityStatus)
&& dto.getStatus() >0){
status = new Integer[]{dto.getStatus()};
}else{
status = new Integer[]{1,2,3,4,5,6};
}
logger.warn("商品下载接口商品状态入参:"+ToStringBuilder.reflectionToString(status));
//System.out.println("商品状态:"+dto.getStatus());
CommodityDto commodityList = commodityMerchantApiService.getCommodityByMerchantWithStatusTime(dto.getMerchant_code(),dto.getCommodity_no(),
status,dto.getStart_modified(), dto.getEnd_modified(),
false, true, dto.getPage_size(), dto.getPage_index());
logger.warn("商品下载接口调用货品接口返回数据:"+ToStringBuilder.reflectionToString(commodityList));
QueryCommodityOutputDto outDto = this.convert(commodityList);
outDto.setPage_index(dto.getPage_index());
outDto.setPage_size(dto.getPage_size());
outDto.setTotal_count(commodityList.getCount());
return outDto;
}
/**
* 转化招商商品API输出对象
*
* @param dto 商品dto
* @return
*/
private QueryCommodityOutputDto convert(CommodityDto dto) {
QueryCommodityOutputDto result = new QueryCommodityOutputDto();
List<QueryCommodityOutputDto.Commodity> items = new ArrayList<QueryCommodityOutputDto.Commodity>();
QueryCommodityOutputDto.Commodity item = null;
Commodity c = null;
if (CollectionUtils.isNotEmpty(dto.getCommodityList())) {
for (Commodity _item : dto.getCommodityList()) {
item = new QueryCommodityOutputDto.Commodity();
item.setAliasName(_item.getAliasName());
item.setBrandEnglishName(_item.getBrandEnglishName());
item.setBrandName(_item.getBrandName());
item.setBrandNo(_item.getBrandNo());
item.setCatName(_item.getCatName());
item.setCatNo(_item.getCatNo());
item.setCatStructName(_item.getCatStructName());
item.setColorName(_item.getColorName());
item.setColorNo(_item.getColorNo());
item.setCommodityDesc(_item.getCommodityDesc());
item.setCommodityName(_item.getCommodityName());
item.setCommodityNo(_item.getCommodityNo());
item.setCostPrice(_item.getCostPrice());
item.setCreateDate(_item.getCreateDate());
item.setDefalutPic(_item.getDefalutPic());
item.setDownDate(_item.getDownDate());
item.setFirstSellDate(_item.getFirstSellDate());
item.setMarkPrice(_item.getMarkPrice());
item.setMerchantCode(_item.getMerchantCode());
item.setPicSmall(_item.getPicSmall());
item.setSellDate(_item.getSellDate());
item.setSellPrice(_item.getSellPrice());
item.setStatus(_item.getStatus());
item.setStyleNo(_item.getStyleNo());
item.setSupplierCode(_item.getSupplierCode());
item.setUpdateDate(_item.getUpdateDate());
item.setYears(_item.getYears());
List<Product> productList = new ArrayList<Product>();
List<com.yougou.pc.model.product.Product> products = _item.getProducts();
if (CollectionUtils.isNotEmpty(products)) {
Product product = null;
for (com.yougou.pc.model.product.Product _product : products) {
product = new Product();
product.setHeight(_product.getHeight());
product.setInsideCode(_product.getInsideCode());
product.setLength(_product.getLength());
product.setProductNo(_product.getProductNo());
product.setQuantity(_product.getQuantity());
product.setSizeName(_product.getSizeName());
product.setSizeNo(_product.getSizeNo());
product.setTaobaoReserved(_product.getTaobaoReserved());
product.setThirdPartyInsideCode(_product.getThirdPartyInsideCode());
product.setWeight(_product.getWeight());
product.setWidth(_product.getWidth());
product.setYougouReserved(_product.getYougouReserved());
productList.add(product);
}
}
//货品明细
item.setProducts(productList);
items.add(item);
}
}
result.setItems(items);
return result;
}
}
|
package com.tfjybj.integral.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Column;
import java.io.Serializable;
/**
* TagsUser实体
* tagsUser
*
* @author 王云召
* @version ${version}
* @since ${version} 2019-09-11 22:13:52
*/
@ApiModel(value = "TagsUserEntity:tagsUser")
@Data
@TableName(value = "tik_tags_user")
public class TagsUserEntity implements Serializable {
/**
* 用户ID
*/
@ApiModelProperty(value = "用户ID")
@Column(name = "user_id")
private String userId;
/**
* 属性ID
*/
@ApiModelProperty(value = "属性ID")
@Column(name = "tags_id")
private String tagsId;
}
|
package br.com.rd.rdevs.conta.model;
public class ContaPoupanca extends Conta {
private ContaPoupanca tipoConta;
public ContaPoupanca (){
}
public ContaPoupanca(int numero, String titular, double saldo, double limite, String agencia, String dataDeAbertura) {
super(numero, titular, saldo, limite, agencia, dataDeAbertura);
}
public ContaPoupanca(int numero, String titular, double saldo, double limite, String agencia, String dataDeAbertura, ContaPoupanca tipoConta) {
super(numero, titular, saldo, limite, agencia, dataDeAbertura, tipoConta);
this.tipoConta = tipoConta;
}
@Override
public Conta getTipoConta() {
return tipoConta;
}
@Override
public boolean sacar(double valorSacado) {
if(valorSacado <= 0){
throw new IllegalArgumentException("Valor sacado nao permitido");
}else if (getSaldo() < valorSacado){
throw new SaldoInsuficienteException("Valor sacado nao permitido");
}else{
this.setSaldo(this.getSaldo() - valorSacado);
return true;
}
}
@Override
public String toString() {
return "Tipo da Conta = Poupanca";
}
}
|
package fadhel.iac.tn.eventtracker.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import fadhel.iac.tn.eventtracker.utils.ConnectionController;
import fadhel.iac.tn.eventtracker.adapters.CustomEventAdapter;
import fadhel.iac.tn.eventtracker.data.DatabaseHandler;
import fadhel.iac.tn.eventtracker.utils.DateComparator;
import fadhel.iac.tn.eventtracker.parsers.HandleRest;
import fadhel.iac.tn.eventtracker.R;
import fadhel.iac.tn.eventtracker.model.Event;
import fadhel.iac.tn.eventtracker.utils.EventsDBLoader;
import fadhel.iac.tn.eventtracker.utils.WSEventsHandler;
public class ResultActivity extends BaseActivity {
FloatingActionButton cultureFab;
FloatingActionButton sportFab;
FloatingActionButton allFab;
FloatingActionButton asc;
FloatingActionButton desc;
private RecyclerView list = null;
private HandleRest handleRest = null;
private List<Event> Allitems = new ArrayList<>();
private List<Event> culturalItems = new ArrayList<>();
private List<Event> sportItems = new ArrayList<>();
private CustomEventAdapter customAdapter = new CustomEventAdapter(culturalItems,ResultActivity.this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
setTitle(getString(R.string.results));
cultureFab = (FloatingActionButton) findViewById(R.id.cultureButton);
sportFab = (FloatingActionButton) findViewById(R.id.sportButton);
allFab = (FloatingActionButton) findViewById(R.id.allButton);
desc = (FloatingActionButton) findViewById(R.id.descButton);
asc = (FloatingActionButton) findViewById(R.id.ascButton);
allFab.setBackgroundTintList(ContextCompat.getColorStateList(ResultActivity.this, R.color.fabpressed));
sportFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sportFab.setBackgroundTintList(ContextCompat.getColorStateList(ResultActivity.this, R.color.fabpressed));
cultureFab.setBackgroundTintList(ContextCompat.getColorStateList(ResultActivity.this, R.color.fabnotpressed));
allFab.setBackgroundTintList(ContextCompat.getColorStateList(ResultActivity.this, R.color.fabnotpressed));
Toast t;
if (!sportItems.isEmpty()) {
t = Toast.makeText(ResultActivity.this, getApplicationContext().getString(R.string.events_sport), Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
t.show();
customAdapter.setItems(sportItems);
customAdapter.notifyDataSetChanged();
} else {
t = Toast.makeText(ResultActivity.this,getApplicationContext().getString(R.string.no_sportive), Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
t.show();
}
}
});
cultureFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cultureFab.setBackgroundTintList(ContextCompat.getColorStateList(ResultActivity.this, R.color.fabpressed));
sportFab.setBackgroundTintList(ContextCompat.getColorStateList(ResultActivity.this, R.color.fabnotpressed));
allFab.setBackgroundTintList(ContextCompat.getColorStateList(ResultActivity.this, R.color.fabnotpressed));
Toast t;
if (!culturalItems.isEmpty()) {
t = Toast.makeText(ResultActivity.this, getApplicationContext().getString(R.string.events_culturel), Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
t.show();
customAdapter.setItems(culturalItems);
customAdapter.notifyDataSetChanged();
} else {
t = Toast.makeText(ResultActivity.this, getApplicationContext().getString(R.string.no_cultural), Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
t.show();
}
}
});
allFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
allFab.setBackgroundTintList(ContextCompat.getColorStateList(ResultActivity.this, R.color.fabpressed));
sportFab.setBackgroundTintList(ContextCompat.getColorStateList(ResultActivity.this, R.color.fabnotpressed));
cultureFab.setBackgroundTintList(ContextCompat.getColorStateList(ResultActivity.this, R.color.fabnotpressed));
Toast t = Toast.makeText(ResultActivity.this, getApplicationContext().getString(R.string.all_events), Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
t.show();
customAdapter.setItems(Allitems);
customAdapter.notifyDataSetChanged();
}
});
asc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collections.sort(customAdapter.getItems(), new DateComparator());
customAdapter.notifyDataSetChanged();
Toast t = Toast.makeText(ResultActivity.this, getApplicationContext().getString(R.string.tri_date_croi), Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
t.show();
}
});
desc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collections.sort(customAdapter.getItems(), Collections.reverseOrder(new DateComparator()));
customAdapter.notifyDataSetChanged();
Toast t = Toast.makeText(ResultActivity.this, getApplicationContext().getString(R.string.tri_date_decroi), Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
t.show();
}
});
list = (RecyclerView) findViewById(R.id.list);
LinearLayoutManager llm = new LinearLayoutManager(ResultActivity.this);
list.setLayoutManager(llm);
list.setAdapter(customAdapter);
Intent i = getIntent();
String urlSport = i.getStringExtra("urlsport");
String urlCulture = i.getStringExtra("urlculture");
String urlws = i.getStringExtra("wsurl");
String country = i.getStringExtra("country");
String city = i.getStringExtra("city");
if(country!=null && city!=null && !country.isEmpty() && !city.isEmpty()) {
Log.d("country", country);
Log.d("city", city);
}
// if we were redirected from preferences activity
if (urlSport == null && urlCulture == null) {
SharedPreferences sp = getSharedPreferences("myPrefs", MODE_PRIVATE);
String culture = sp.getString("urlculture", null);
String sport = sp.getString("urlsport",null);
String d1=null,d2=null;
if(sport!=null && !sport.isEmpty())
d1 = sport.substring(sport.indexOf(";date="),sport.indexOf(";location="));
if(culture!=null && !culture.isEmpty())
d2 = culture.substring(culture.indexOf("date="),culture.indexOf(";location="));
if(d1!=null && !d1.isEmpty())
Log.d("d1",d1);
if(d2!=null && !d2.isEmpty())
Log.d("d2",d2);
urlCulture = sp.getString("urlculture",null);
urlSport = sp.getString("urlsport",null);
}
// Verification de la connexion
boolean connected=false;
try {
Log.d("results","checking connection");
connected = new ConnectionController(ResultActivity.this).execute().get();
}
catch(InterruptedException | ExecutionException e) {e.printStackTrace();}
Log.d("Searching", "Seaching");
// Si la connexion internet est disponible on effectue la recherche
if(connected)
new RetrieveEvents().execute(urlSport,urlCulture,urlws);
//Sinon on charge le résultat de la dernière recherche
else new EventsDBLoader(ResultActivity.this).execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.action_search:
boolean connected=false;
try{
connected = new ConnectionController(ResultActivity.this).execute().get();
}catch(InterruptedException | ExecutionException e) {e.printStackTrace();}
if(connected) {
Intent i = getIntent();
if (i.getStringExtra("activity").equals("splash")) {
i = new Intent(ResultActivity.this, ChoiceActivity.class);
startActivity(i);
} else finish();
} else {
Toast t = Toast.makeText(ResultActivity.this, getApplicationContext().getString(R.string.connectez_internet), Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
t.show();
}
break;
case R.id.favorites_main:
Intent i = new Intent(ResultActivity.this, FavoritesActivity.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
private class RetrieveEvents extends AsyncTask<String, Void, Void> {
private ProgressDialog progress = null;
@Override
protected void onPreExecute() {
Log.d("display","progress");
progress = ProgressDialog.show(
ResultActivity.this, null, getString(R.string.loading));
super.onPreExecute();
}
@Override
protected Void doInBackground(String... params) {
List<Event> listres = new ArrayList<>();
if(!params[0].isEmpty()) {
int i=1;
handleRest = new HandleRest(params[0], "sport");
Log.d("urlSPORT",params[0]);
int total= handleRest.ParseAndStore(listres,i);
int pagenumbers = (total%100==0)?total/100:total/100+1;
Log.d("pages",pagenumbers+"");
for( i=2;i<=pagenumbers;i++)
handleRest.ParseAndStore(listres,i);
Allitems.addAll(listres);
sportItems.addAll(listres);
listres.clear();
}
if (!params[1].isEmpty()) {
int i=1;
handleRest = new HandleRest(params[1], "culture");
Log.d("urlCULTURE",params[1]);
int total = handleRest.ParseAndStore(listres,i);
int pagenumbers = (total%100==0)?total/100:total/100+1;
Log.d("Total",total+"");
Log.d("pages", pagenumbers + "");
for( i=2;i<=pagenumbers;i++)
handleRest.ParseAndStore(listres,i);
Allitems.addAll(listres);
culturalItems.addAll(listres);
listres.clear();
}
if(params[2]!=null)
{
WSEventsHandler wshandler = new WSEventsHandler(ResultActivity.this,params[2]);
listres = wshandler.loadEvents();
Allitems.addAll(listres);
for(Event ev : listres)
if(ev.getCatégorie().equalsIgnoreCase("football") || ev.getCatégorie().equalsIgnoreCase("basketball")|| ev.getCatégorie().equalsIgnoreCase("handball") || ev.getCatégorie().equalsIgnoreCase("tennis"))
sportItems.add(ev);
else culturalItems.add(ev);
}
customAdapter.setItems(Allitems);
DatabaseHandler db = new DatabaseHandler(ResultActivity.this);
if(db.getEventsCount("events")!=0)
db.deleteAll("events");
for(Event ev : Allitems)
db.addEvent(ev);
return null;
}
@Override
protected void onPostExecute(Void a) {
customAdapter.notifyDataSetChanged();
progress.dismiss();
}
}
public List<Event> getSportItems() {
return sportItems;
}
public CustomEventAdapter getCustomAdapter() {
return customAdapter;
}
public List<Event> getCulturalItems() {
return culturalItems;
}
public List<Event> getAllitems() {
return Allitems;
}
} |
package ast.statements;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import ast.ArgNode;
import ast.IdNode;
import ast.LhsNode;
import ast.Node;
import ast.expressions.DerExpNode;
import ast.expressions.ExpNode;
import ast.types.TypeNode;
import ast.types.FunTypeNode;
import exceptions.TypeException;
import semanticAnalysis.Effect;
import semanticAnalysis.Environment;
import semanticAnalysis.STentry;
import semanticAnalysis.SemanticError;
public class CallNode implements Node{
private final IdNode id;
private String callerId;
private final List<ExpNode> params;//ExpNode
private int currentNl;
public CallNode(final IdNode id, final List<ExpNode> params) {
this.id = id;
this.params=params;
}
@Override
public String toPrint(String indent) {
String s = "(";
if(! params.isEmpty()) {
for (ExpNode p : params) {
s += p.toPrint("") + ", ";
}
s = s.substring(0, s.length()); //s.length() -2
}
s += ")";
return indent + "call: " + id.toPrint("") + s;
}
@Override
public TypeNode typeCheck() throws TypeException {
//first of all we check that the ID found is a funTypeNode, otherwise it will be a variable or pointer and this element don't allow call
TypeNode type = id.typeCheck();
//then check that the actual and formal params have the same type
if(type instanceof FunTypeNode){
List<TypeNode> formalParamsTypes = ((FunTypeNode) type).getParamsType();
List<TypeNode> actualParamsTypes = new ArrayList<>();
List<ExpNode> actualParams = new ArrayList<>();
for(ExpNode p: params){
actualParams.add(p);
actualParamsTypes.add(p.typeCheck());
}
for(int i=0; i <formalParamsTypes.size(); i++ ){
if (!Node.sametype(actualParamsTypes.get(i), formalParamsTypes.get(i)))
throw new TypeException("Type Error: actual parameters types don't match with the formal parameters type. Expected: " + formalParamsTypes + " got " + actualParamsTypes + " in "+ id.toPrint("" )+ actualParams);
}
return ((FunTypeNode) type).getReturnedValue();
}
else
throw new TypeException("Type Error: trying to invoke a non-function identifier: " +id.toPrint("") + ". ");
}
@Override
public String codeGeneration() {
//i feel like something's missing
String ret = "; BEGIN CALLING " + id.getTextId() + "\n";
ret += "push $fp\n";
ret += "push $sp\n";
ret += "mv $cl $sp\n";
ret += "addi $t1 $cl 2\n";
ret += "sw $t1 0($cl)\n";
ret += "addi $sp $sp -1\n";
if(this.callerId == null || !(this.callerId.endsWith(id.getTextId())))
ret += "mv $al $fp\n";
else
ret += "lw $al 0($fp)\n";
for(int i = 0; i < currentNl - id.getNl(); i++)
ret += "lw $al 0($al)\n";
ret += "push $al\n";
for(ExpNode p : params){
ret += p.codeGeneration() +
"push $a0 ; pushing " + p +"\n";
}
ret += "mv $fp $sp\n";
ret += "addi $fp $fp " + params.size() + "\n";
ret += "jal " + id.getTextId(); //decfun saves ra firstly
ret += "; END CALLING " + id.getTextId()+ "\n";
return ret;
}
@Override
public ArrayList<SemanticError> checkSemantics(Environment env) {
ArrayList<SemanticError> errors = new ArrayList<>();
//check if the id exists, if not we're using an undeclared identifier
errors.addAll(id.checkSemantics(env));
if(!errors.isEmpty())
return errors;
//check all the parameters, if there's something wrong with them during the invocation such as int + bool
for(ExpNode p : params)
errors.addAll(p.checkSemantics(env));
//check if the number of actual parameters is equal to the number of formal parameters
currentNl = env.getNestingLevel();
int nFormalParams = 0;
int nActualParams = params.size();
if(id.getSTentry().getType() instanceof FunTypeNode)
nFormalParams = ((FunTypeNode) id.getSTentry().getType()).getParamsType().size();
if(nActualParams != nFormalParams)
errors.add(new SemanticError("There's a difference in the number of actual parameters versus the number of formal parameters declared in the function " + id.getTextId()));
//idk if i'm missing something but this seems fine to me
return errors;
}
@Override
public ArrayList<SemanticError> checkEffects(Environment env) {
ArrayList<SemanticError> errors = new ArrayList<>();
ArrayList<SemanticError> expEvalErrors = new ArrayList<>();
//\Gamma |- f : &t1 x .. x &tm x t1' x .. x tn' -> void DONE
//\Sigma(f) = \Sigma_0 -> Sigma_1 ?? DONE
//\Sigma_1(yi) <= d, 1<=i<=n DONE
//\Sigma' = \Sigma [(zi -> \Sigma(zi) seq rw) where zi \in parameters passed as value], \Sigma(zi) = effect status of zi DONE
//\Sigma'' = par [ui -> \Sigma(ui) seq \Sigma1(xi)] 1 <= i <= m, where ui are the parameters passed as reference DONE
// ui should be the status outside the function, xi should be the status inside the function
//-------------------------------------------------------
//\Sigma |- f(u1, .., um, e1, .., en) : update(\Sigma', \Sigma'')
expEvalErrors.addAll(id.checkEffects(env));
List<ExpNode> passedByReferenceParams = new ArrayList<>();
List<ExpNode> passedByValueParams = new ArrayList<>();
// Creating the statuses of the variables given as input to the function call.
// If actual parameters are expressions not instance of DereferenceExpNode, Effect.READ_WRITE is the status given.
for(ExpNode p : params) {
errors.addAll(p.checkEffects(env));
if (p instanceof DerExpNode)
passedByReferenceParams.add(p);
else
passedByValueParams.add(p);
}
//processing passed by value params
STentry fun = env.lookupForEffectAnalysis(id.getTextId());
//getting Sigma1
HashMap<String, Effect> sigma1 = fun.getFunStatus().get(1);
//checking ( ∑ 1 (y i ) ≤ d ) 1 ≤ i ≤ n
for (int i =0 ;i<fun.getFunNode().getArgs().size(); i++){
ArgNode arg = fun.getFunNode().getArgs().get(i);
Effect e = sigma1.get(arg.getId().getTextId());
List<ArgNode> passedByValueArgs = fun.getFunNode().getPassedByValueParams();
if( passedByValueArgs.contains(arg) ) {
if (e.getType() > Effect.DEL)
errors.add(new SemanticError("Cannot use " + id.getTextId() + " with effect " + e.getType() + "inside a function. "));
}
}
// getting effect of z_i in ∑ while invoking function
// ∑'= ∑ [( z i ⟼ ∑(z i )⊳rw ) zi ∈ var(e1,…,en) ]
STentry varInSigma = new STentry(0,0);
Effect varInSigmaEffect = new Effect();
Environment sigmaPrimo = new Environment(env);
for (ExpNode exp: passedByValueParams){
//getting exp variable and setting to rw
for (LhsNode expVar : exp.getExpVar()){
//getting ∑(z i )
varInSigma = sigmaPrimo.lookupForEffectAnalysis(expVar.getLhsId().getTextId());
varInSigmaEffect = varInSigma.getIVarStatus(expVar.getLhsId().getTextId());
varInSigma.setVarStatus(expVar.getLhsId().getTextId(), Effect.seq(varInSigmaEffect, new Effect(Effect.RW)));
}
}
//∑"= ⊗ i ∈ 1..m [ u i ⟼ ∑(u i )⊳ ∑ 1 (x i )]
//processing passed by reference values
Effect formalParamEffect ;
List<Environment> resultingEnvironment = new ArrayList<>();
Environment sigmaSecondo = new Environment(env);
for (int i = 0; i<passedByReferenceParams.size(); i++){
ExpNode ithParam = passedByReferenceParams.get(i);
LhsNode actualParam = ithParam.getExpVar().get(0) ;
//getting formal and actual params effect from the respective environment.
varInSigma = env.lookupForEffectAnalysis(actualParam.getLhsId().getTextId());
varInSigmaEffect = varInSigma.getIVarStatus(actualParam.getLhsId().getTextId());
ArgNode formalParam = fun.getFunNode().getArgs().get(i);
formalParamEffect = sigma1.get(formalParam.getId().getTextId());
//creating the environment with a single entry that will be used for the creation os Sigma''; [ui -> ∑(u i )⊳ ∑ 1 (x i )]
Environment newEnv = new Environment();
newEnv.onScopeEntry();
STentry tmp = new STentry(varInSigma.getNl(),varInSigma.getOffset(),varInSigma.getType());
tmp.initializeStatus(actualParam.getLhsId());
tmp.setVarStatus(actualParam.getLhsId().getTextId() ,Effect.seq(varInSigmaEffect,formalParamEffect));
newEnv.addEntry(actualParam.getLhsId().getTextId(), tmp);
resultingEnvironment.add(newEnv);
}
//applying par to par [ui -> \Sigma(ui) seq \Sigma1(xi)] 1 <= i <= m,
if(resultingEnvironment.size()>0) {
sigmaSecondo = resultingEnvironment.get(0);
for (int i = 1; i < resultingEnvironment.size(); i++) {
sigmaSecondo = Environment.par(sigmaSecondo, resultingEnvironment.get(i));
}
}
List<String> unique = new ArrayList<>();
//avoid double processing in case of aliasing
for(ExpNode param : passedByReferenceParams) {
if(!unique.contains(param.getExpVar().get(0).getLhsId().getTextId()))
unique.add(param.getExpVar().get(0).getLhsId().getTextId());
}
//checking that after function invocation all the params aren't in TOP status
for(String paramName : unique) {
varInSigma = sigmaSecondo.lookupForEffectAnalysis(paramName);
varInSigmaEffect = varInSigma.getIVarStatus(paramName);
if(varInSigmaEffect.getType() == Effect.TOP)
errors.add(new SemanticError(paramName + " is used after deletion. " ));
}
Environment updatedEnv = Environment.update(env,sigmaSecondo);
env.replace(updatedEnv);
if(! expEvalErrors.isEmpty()) {
errors.add(new SemanticError("During invocation you're trying to use bad expression: "));
errors.addAll(expEvalErrors);
}
return errors;
}
public List<LhsNode> getExpVar() {
List<LhsNode> ret = new ArrayList<>();
for(ExpNode p : params) {
ret.addAll(p.getExpVar());
}
return ret;
}
public void setCallerId(final String callerId){
this.callerId = callerId;
}
}
|
package com.lambdatest.Tests;
import org.json.JSONArray;
import org.json.JSONObject;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.UnexpectedException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class TestBase {
public String buildTag = System.getenv("LT_BUILD");
public String username = System.getenv("LT_USERNAME");
public String accesskey = System.getenv("LT_APIKEY");
public String gridURL = System.getenv("LT_GRID_URL");
private ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
@DataProvider(name = "browsersDetails", parallel = true)
public static Iterator<Object[]> ltBrowserDataProvider(Method testMethod) {
String jsonText = System.getenv("LT_BROWSERS");
ArrayList<Object> lt_browser = new ArrayList<Object>();
ArrayList<Object> lt_operating_system = new ArrayList<Object>();
ArrayList<Object> lt_browserVersion = new ArrayList<Object>();
ArrayList<Object> lt_resolution = new ArrayList<Object>();
JSONArray allCities = new JSONArray(jsonText);
for (int j = 0; j < allCities.length(); j ++){
JSONObject cityObject = allCities.getJSONObject(j);
if (! cityObject.getString("browserName").isEmpty()) {
lt_browser.add(cityObject.getString("browserName"));
}
if (! cityObject.getString("operatingSystem").isEmpty()) {
lt_operating_system.add(cityObject.getString("operatingSystem"));
}
if (! cityObject.getString("browserVersion").isEmpty()) {
lt_browserVersion.add(cityObject.getString("browserVersion"));
}
if (! cityObject.getString("resolution").isEmpty()) {
lt_resolution.add(cityObject.getString("resolution"));
}
}
Object[][] arrMulti = new Object[lt_browser.size()][1];
for (int l =0 ; l<lt_browser.size();l++) {
arrMulti[l][0]=lt_browser.get(l)+","+lt_operating_system.get(l)+","+lt_browserVersion.get(l)+","+lt_resolution.get(l);
}
List<Object[]> capabilitiesData = new ArrayList<Object[]>();
// Object[][] data = new Object[arrMulti.length][1];
for (int i = 0; i < arrMulti.length; i++) {
for (int j = 0; j < 1; j++) {
capabilitiesData.add(new Object[] { arrMulti[i][j] });
}
}
return capabilitiesData.iterator();
}
public WebDriver getWebDriver() {
return webDriver.get();
}
protected void setUp(String browser, String version, String os, String res )
throws MalformedURLException, Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
// set desired capabilities to launch appropriate browser on Lambdatest
capabilities.setCapability(CapabilityType.BROWSER_NAME, browser);
capabilities.setCapability(CapabilityType.VERSION, version);
capabilities.setCapability(CapabilityType.PLATFORM, os);
capabilities.setCapability("screen_resolution", res);
Reporter.log("os"+os);
Reporter.log("version"+version);
Reporter.log("browser"+browser);
Reporter.log("resValue"+res);
if (buildTag == null) {
capabilities.setCapability("build", "TestNG-Java-Jenkins-Parallel");
}
gridURL = System.getenv("LT_GRID_URL");
// Launch remote browser and set it as the current thread
webDriver.set(new RemoteWebDriver(new URL(gridURL), capabilities));
}
@AfterMethod(alwaysRun = true)
public void tearDown(ITestResult result) throws Exception {
// ((JavascriptExecutor) webDriver.get()).executeScript("Lambdatest:job-result="
// + (result.isSuccess() ? "passed" : "failed"));
if (!(webDriver.get()==null))
webDriver.get().quit();
}
}
|
package br.edu.ifam.saf.mvp;
public interface LoadingView {
void mostrarLoading();
void esconderLoading();
void mostrarInfoMensagem(String mensagem);
}
|
package com.penzias.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.penzias.core.BasicServiceImpl;
import com.penzias.core.interfaces.BasicMapper;
import com.penzias.dao.SmModularMapper;
import com.penzias.entity.SmModular;
import com.penzias.entity.SmModularExample;
import com.penzias.service.SmModularService;
@Service("smModularService")
public class SmModularServiceImpl extends BasicServiceImpl<SmModularExample, SmModular> implements SmModularService {
@Resource
private SmModularMapper smModularMapper;
@Override
public BasicMapper<SmModularExample, SmModular> getMapper(){
return smModularMapper;
}
}
|
package app0512.graphic;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class ImageTest extends JFrame{
Image img=null;//이미지는 추상클래스이므로 즉 불완전하므로 개발자가 직접 new할 수 없다
//일반적으로 추상 클래스는 개발자가 상속받아 완성한후 자식 객체를 생성할때 사용할수 있지만
//언제나 그런것은 아니다, 즉 sun에서 추상클래스 객체의 인스턴스를 얻는 또 다른 방법을
//제공해주는 경우가 많다 (즉 메서드 호출에 의해서 인스턴스를 얻는 방법)
Toolkit kit;//툴킷을 이용하면, os경로로 접근한 이미지의 인스턴스를 얻을 수 있다..
public ImageTest() {
//이미지를 얻기 위한 객체인 툴킷 객체의 인스턴스를 먼저 얻어와야한다
kit= Toolkit.getDefaultToolkit();//인스턴스를 얻는 메서드 사용
img=kit.getImage("C:\\korea202102_javaworkspace\\app0512\\res\\images\\mt.jpg");
setBounds(1600,100,700,650);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void paint(Graphics g) {
g.drawImage(img, 0, 0, this);
}
public static void main(String[] args) {
new ImageTest();
}
}
|
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.util.ArrayList;
import java.util.HashMap;
class Wallet {
PrivateKey privateKey;
PublicKey publicKey;
private HashMap<String, TransactionOutput> UTXOs = new HashMap<>();
Wallet() {
generateKeyPair();
}
float getBalance() {
float total = 0;
for (TransactionOutput output : PokeChain.UTXOs.values()) {
if (output.belongTo(publicKey)) {
UTXOs.put(output.id, output);
total += output.value;
}
}
return total;
}
Transaction sendCoin(PublicKey recipient, float value) {
if (getBalance() < value)
return null;
ArrayList<TransactionInput> inputs = new ArrayList<>();
float total = 0;
for (TransactionOutput output : UTXOs.values()) {
total += output.value;
inputs.add(new TransactionInput(output.id));
if (total > value)
break;
}
Transaction transaction = new Transaction(publicKey, recipient, value, inputs);
transaction.generateSignature(privateKey);
for (TransactionInput input : inputs)
UTXOs.remove(input.transactionOutputId);
return transaction;
}
private void generateKeyPair() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDSA", "BC");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("prime192v1");
keyPairGenerator.initialize(ecGenParameterSpec, secureRandom);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
privateKey = keyPair.getPrivate();
publicKey = keyPair.getPublic();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
package cracking.structure;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Graph {
private int numVertices;
private int numEdges;
private HashMap<String, Vertex> verticesList;
private List<Edge> edgesList;
public Graph() {
this.verticesList = new HashMap<String, Vertex>();
this.setEdgesList(new ArrayList<Edge>());
}
public void addVertex(Vertex v) {
if (!verticesList.containsKey(v.getLabel())) {
verticesList.put(v.getLabel(), v);
numVertices++;
}
}
public void addEdge() {
numEdges++;
}
public int getNumVertices() {
return numVertices;
}
public void setNumVertices(int numVertices) {
this.numVertices = numVertices;
}
public int getNumEdges() {
return numEdges;
}
public void setNumEdges(int numEdges) {
this.numEdges = numEdges;
}
/**
* @return the edgesList
*/
public List<Edge> getEdgesList() {
return edgesList;
}
/**
* @param edgesList
* the edgesList to set
*/
public void setEdgesList(List<Edge> edgesList) {
this.edgesList = edgesList;
}
}
|
package com.tomek.filters;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AddAnimalFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest httpRequest = (HttpServletRequest) req;
Object access = httpRequest.getSession().getAttribute("priviliges");
if (access != null) {
chain.doFilter(httpRequest, resp);
} else {
HttpServletResponse httpResponse = (HttpServletResponse) resp;
httpResponse.sendRedirect("login.jsp");
}
}
public void init(FilterConfig config) throws ServletException {
}
}
|
package com.accp.pub.pojo;
public class Awardandpunishmentaccessory {
private Integer accessoryid;
private String aid;
private String accessoryname;
private String accessorysize;
private String accessoryurl;
private String bz1;
private String bz2;
public Integer getAccessoryid() {
return accessoryid;
}
public void setAccessoryid(Integer accessoryid) {
this.accessoryid = accessoryid;
}
public String getAid() {
return aid;
}
public void setAid(String aid) {
this.aid = aid;
}
public String getAccessoryname() {
return accessoryname;
}
public void setAccessoryname(String accessoryname) {
this.accessoryname = accessoryname == null ? null : accessoryname.trim();
}
public String getAccessorysize() {
return accessorysize;
}
public void setAccessorysize(String accessorysize) {
this.accessorysize = accessorysize;
}
public String getAccessoryurl() {
return accessoryurl;
}
public void setAccessoryurl(String accessoryurl) {
this.accessoryurl = accessoryurl == null ? null : accessoryurl.trim();
}
public String getBz1() {
return bz1;
}
public void setBz1(String bz1) {
this.bz1 = bz1 == null ? null : bz1.trim();
}
public String getBz2() {
return bz2;
}
public void setBz2(String bz2) {
this.bz2 = bz2 == null ? null : bz2.trim();
}
} |
package nl.tim.aoc.day8;
import nl.tim.aoc.Challenge;
import nl.tim.aoc.Main;
import java.util.ArrayList;
import java.util.List;
public class Day8Challenge1 extends Challenge
{
private String read;
@Override
public void prepare() {
read = Main.readFile("8.txt").get(0);
}
@Override
public Object run(String alternative) {
List<Integer> in = new ArrayList<>();
for (String s : read.split("\\s"))
{
in.add(Integer.valueOf(s));
}
return calc(in);
}
private int calc(List<Integer> input)
{
if (input.isEmpty())
{
return 0;
}
int children = input.remove(0);
int data = input.remove(0);
int sum = 0;
for (int i = 0; i < children; i++)
{
sum += calc(input);
}
for (int i = 0; i < data; i++)
{
sum += input.remove(0);
}
return sum;
}
}
|
package Utils;
public class Util {
public static int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
}
|
package ru.test.cmdline;
public enum ContentsType {
STRING, INTEGER
}
|
package com.weixin.apiobject;
import io.restassured.response.Response;
import java.util.HashMap;
import static io.restassured.RestAssured.given;
/**
* @program: testAppium
* @description:代表运行一个单一的http接口
* @author: mengmeng
* @create: 2020-11-02 12:22
**/
public class ApiObjectMethodModel {
public String method="get";
public String url;
public HashMap<String,Object> query;
public String save;
public HashMap<String,Object> json;
public String post;
public String get;
/*
发起请求获取相应
*/
public Response run() {
if(post!=null){
return given()
.queryParams(query)
.post(post)
.then()
.log()
.all()
.extract()
.response();}
if (get!=null){
return given()
.queryParams(query)
.get(get)
.then()
.log()
.all()
.extract()
.response();
}
Response response=given()
.queryParams(query)
.request(method, url)
.then()
.log()
.all()
.extract()
.response();
return response;
}
}
|
package com.gft.playground.nta.adaption.login;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import com.gft.playground.nta.adaption.login.model.User;
public class LoginTest {
protected static User successUser;
protected static User failureUser;
@BeforeClass
public static void setUp() {
setUpSuccessUser();
setUpFailureUser();
}
@AfterClass
public static void tearDown() {
tearDownSuccessUser();
tearDownFailureUser();
}
private static void setUpSuccessUser() {
successUser = new User();
successUser.setUsername("user1");
successUser.setPassword("user1");
}
private static void setUpFailureUser() {
failureUser = new User();
failureUser.setUsername("asds");
failureUser.setPassword("zxcx");
}
private static void tearDownSuccessUser() {
successUser = null;
}
private static void tearDownFailureUser() {
failureUser = null;
}
}
|
package com.moon.moon_thread.juc.Map;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* @ClassName ConCurrentHashMapTest
* @Description: TODO
* @Author zyl
* @Date 2020/12/29
* @Version V1.0
**/
@Slf4j
public class ConCurrentHashMapTest {
public static void main(String[] args) {
Map map = new ConcurrentHashMap();
for (int i = 0; i < 3000; i++) {
new Thread(()->{
map.put(UUID.randomUUID().toString().substring(0,5),UUID.randomUUID().toString().substring(0,5));
log.info("{}",map);
}).start();
}
}
}
|
package com.anibal.educational.rest_service.domain;
import java.util.Date;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class Subproject implements Cloneable {
private Long subprojectId;
private String subprojectName;
private Long userId;
@JsonSerialize(using = DateSerializer.class)
private Date creacionFecha;
public Subproject() {
super();
}
public Long getSubprojectId() {
return subprojectId;
}
public void setSubprojectId(Long subprojectId) {
this.subprojectId = subprojectId;
}
public String getSubprojectName() {
return subprojectName;
}
public void setSubprojectName(String subprojectName) {
this.subprojectName = subprojectName;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Date getCreacionFecha() {
return creacionFecha;
}
public void setCreacionFecha(Date creacionFecha) {
this.creacionFecha = creacionFecha;
}
@Override
public String toString() {
return "Subproject [subprojectId=" + subprojectId + ", subprojectName=" + subprojectName + ", userId=" + userId
+ ", creacionFecha=" + creacionFecha + "]";
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
|
package com.infy.surveyExpert.model;
public class DiscreteAnswers {
private Integer organizerId;
private Integer surveyId;
private Integer participantId;
private Integer questionId;
private Integer optionId;
private Integer id;
public Integer getOrganizerId() {
return organizerId;
}
public void setOrganizerId(Integer organizerId) {
this.organizerId = organizerId;
}
public Integer getSurveyId() {
return surveyId;
}
public void setSurveyId(Integer surveyId) {
this.surveyId = surveyId;
}
public Integer getParticipantId() {
return participantId;
}
public void setParticipantId(Integer participantId) {
this.participantId = participantId;
}
public Integer getQuestionId() {
return questionId;
}
public void setQuestionId(Integer questionId) {
this.questionId = questionId;
}
public Integer getOptionId() {
return optionId;
}
public void setOptionId(Integer optionId) {
this.optionId = optionId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
|
package kr.re.keti.ui;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.airbnb.lottie.LottieAnimationView;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import kr.re.keti.model.AE;
import kr.re.keti.model.ApplicationEntityObject;
import kr.re.keti.model.CSEBase;
import kr.re.keti.model.ContentInstanceObject;
import kr.re.keti.model.ContentSubscribeObject;
import kr.re.keti.service.mqtt.MqttClientRequest;
import kr.re.keti.util.MqttClientRequestParser;
import kr.re.keti.util.ParseElementXml;
public class MainActivity extends AppCompatActivity implements Button.OnClickListener, CompoundButton.OnCheckedChangeListener {
public Button btnRetrieve;
public LottieAnimationView lottie_air_animation;
public LottieAnimationView lottie_light_animation;
public LottieAnimationView lottie_air_control_animation;
public LottieAnimationView lottie_loading_animation;
public ToggleButton btnControl_Led;
public Switch Switch_MQTT;
public TextView textView_airConditioner_data;
public TextView textView_led_data;
public TextView textView_preview;
public TextView textView_air_control;
public TextView textView_led_loading;
public Button button_frontLight_control;
public Button button_backLight_control;
public Button button_airConditioner_off;
public Button button_airConditioner_on;
public Handler handler;
private static CSEBase csebase = new CSEBase();
private static AE ae = new AE();
private static String TAG = "MainActivity";
private String MQTTPort = "1883";
private String ServiceAEName = "daewon_demo";
private String MQTT_Req_Topic = "";
private String MQTT_Resp_Topic = "";
private MqttAndroidClient mqttClient = null;
// Main
public MainActivity() {
handler = new Handler();
}
/* onCreate */
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// bind(R.layout.activity_main);
setContentView(R.layout.activity_main);
// binding.setLifecycleOwner(this);
lottie_air_animation = (LottieAnimationView) findViewById(R.id.lottie_air_animation);
lottie_light_animation = (LottieAnimationView) findViewById(R.id.lottie_light_animation);
lottie_air_control_animation = (LottieAnimationView) findViewById(R.id.lottie_air_control_animation);
lottie_loading_animation = (LottieAnimationView) findViewById(R.id.lottie_loading_animation);
Switch_MQTT = (Switch) findViewById(R.id.switch_mqtt);
btnControl_Led = (ToggleButton) findViewById(R.id.btnControl_Led);
button_backLight_control = (Button) findViewById(R.id.button_backLight_control);
button_frontLight_control = (Button) findViewById(R.id.button_frontLight_control);
button_airConditioner_off = (Button) findViewById(R.id.button_airConditioner_off);
button_airConditioner_on = (Button) findViewById(R.id.button_airConditioner_on);
textView_airConditioner_data = (TextView) findViewById(R.id.textView_airConditioner_data);
textView_led_data = (TextView) findViewById(R.id.textView_led_data);
textView_preview = (TextView) findViewById(R.id.textView_preview);
textView_air_control = (TextView) findViewById(R.id.textView_air_control);
button_airConditioner_on.setOnClickListener(this);
button_airConditioner_off.setOnClickListener(this);
button_frontLight_control.setOnClickListener(this);
button_backLight_control.setOnClickListener(this);
Switch_MQTT.setOnCheckedChangeListener(this);
btnControl_Led.setOnClickListener(this);
// Create AE and Get AEID
GetAEInfo();
}
/* AE Create for android AE */
public void GetAEInfo() {
csebase.setInfo("192.168.10.238", "7579", "Mobius", "1883");
// AE Create for Android AE
ae.setAppName("wisoftApp");
aeCreateRequest aeCreate = new aeCreateRequest();
aeCreate.setReceiver(new IReceived() {
public void getResponseBody(final String msg) {
handler.post(new Runnable() {
public void run() {
Log.d(TAG, "** AE Create ResponseCode[" + msg + "]");
if (Integer.parseInt(msg) == 201) {
// MQTT_Req_Topic = "/oneM2M/req/Mobius2/" + ae.getAEid() + "_sub" + "/#";
MQTT_Req_Topic = "/oneM2M/req/Mobius2/Sdaewon_demo/json";
MQTT_Resp_Topic = "/oneM2M/resp/Mobius2/" + ae.getAEid() + "_sub" + "/json";
Log.d(TAG, "ReqTopic[" + MQTT_Req_Topic + "]");
Log.d(TAG, "ResTopic[" + MQTT_Resp_Topic + "]");
} else { // If AE is Exist , GET AEID
aeRetrieveRequest aeRetrive = new aeRetrieveRequest();
aeRetrive.setReceiver(new IReceived() {
public void getResponseBody(final String resmsg) {
handler.post(new Runnable() {
public void run() {
Log.d(TAG, "** AE Retrive ResponseCode[" + resmsg + "]");
// MQTT_Req_Topic = "/oneM2M/req/Mobius2/" + ae.getAEid() + "_sub" + "/#";
MQTT_Req_Topic = "/oneM2M/req/Mobius2/Sdaewon_demo/json";
MQTT_Resp_Topic = "/oneM2M/resp/Mobius2/" + ae.getAEid() + "_sub" + "/json";
Log.d(TAG, "ReqTopic[" + MQTT_Req_Topic + "]");
Log.d(TAG, "ResTopic[" + MQTT_Resp_Topic + "]");
}
});
}
});
aeRetrive.start();
}
}
});
}
});
aeCreate.start();
}
/* Switch - Get Co2 Data With MQTT */
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.d(TAG, "MQTT Create");
button_airConditioner_off.setVisibility(View.VISIBLE);
button_airConditioner_on.setVisibility(View.VISIBLE);
textView_preview.setVisibility(View.GONE);
textView_airConditioner_data.setVisibility(View.VISIBLE);
MQTT_Create(true);
} else {
lottie_loading_animation.setVisibility(View.GONE);
button_airConditioner_off.setVisibility(View.GONE);
button_airConditioner_on.setVisibility(View.GONE);
lottie_air_animation.setVisibility(View.GONE);
textView_airConditioner_data.setVisibility(View.GONE);
textView_preview.setVisibility(View.VISIBLE);
textView_air_control.setVisibility(View.GONE);
Log.d(TAG, "MQTT Close");
MQTT_Create(false);
}
}
/* MQTT Subscription */
public void MQTT_Create(boolean mtqqStart) {
if (mtqqStart && mqttClient == null) {
lottie_loading_animation.setVisibility(View.VISIBLE);
/* Subscription Resource Create to Yellow Turtle */
SubscribeResource subcribeResource = new SubscribeResource();
subcribeResource.setReceiver(new IReceived() {
@Override
public void getResponseBody(final String msg) {
handler.post(new Runnable() {
public void run() {
System.out.println("subscription 완료");
}
});
}
});
subcribeResource.start();
/* MQTT Subscribe */
mqttClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://" + csebase.getHost() + ":" + csebase.getMQTTPort(), MqttClient.generateClientId());
//http://192.168.10.75:7579/Mobius/IYAHN_DEMO/co2
mqttClient.setCallback(mainMqttCallback);
try {
IMqttToken token = mqttClient.connect();
token.setActionCallback(mainIMqttActionListener);
} catch (MqttException e) {
e.printStackTrace();
}
} else {
/* MQTT unSubscribe or Client Close */
mqttClient.setCallback(null);
mqttClient.close();
mqttClient = null;
// MQTT_Create(true);
}
}
/* MQTT Listener */
private IMqttActionListener mainIMqttActionListener = new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(TAG, "onSuccess");
String payload = "";
int mqttQos = 1; /* 0: NO QoS, 1: No Check , 2: Each Check */
MqttMessage message = new MqttMessage(payload.getBytes());
System.out.println(MQTT_Req_Topic);
try {
if (mqttClient != null) {
mqttClient.subscribe(MQTT_Req_Topic, mqttQos);
}
} catch (MqttException e) {
System.out.println("섭 에러");
e.printStackTrace();
}
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "onFailure");
}
};
/* MQTT Broker Message Received */
private MqttCallback mainMqttCallback = new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
Log.d(TAG, "connectionLost");
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
lottie_loading_animation.setVisibility(View.GONE);
lottie_air_animation.resumeAnimation();
lottie_air_animation.setProgress(0.1f);
lottie_air_animation.setVisibility(View.VISIBLE);
Log.d(TAG, "messageArrived");
JSONObject jsonObject = new JSONObject(String.valueOf(message));
JSONObject pc = new JSONObject(jsonObject.get("pc").toString());
JSONObject m2m_sgn = new JSONObject(pc.get("m2m:sgn").toString());
JSONObject nev = new JSONObject(m2m_sgn.get("nev").toString());
JSONObject rep = new JSONObject(nev.get("rep").toString());
JSONObject m2m_cin = new JSONObject(rep.get("m2m:cin").toString());
String tem = m2m_sgn.get("sur").toString();
String temParse = tem.split("/")[2];
if (temParse.equals("temperature")) {
textView_airConditioner_data.setText("");
textView_airConditioner_data.setText("연구실 에어컨 온도 \r\n\r\n" + m2m_cin.get("con"));
}
Log.d(TAG, "Notify ResMessage:" + message.toString());
/* Json Type Response Parsing */
String retrqi = MqttClientRequestParser.notificationJsonParse(message.toString());
Log.d(TAG, "RQI[" + retrqi + "]");
String responseMessage = MqttClientRequest.notificationResponse(retrqi);
Log.d(TAG, "Receive OK ResMessage [" + responseMessage + "]");
/* Make json for MQTT Response Message */
MqttMessage res_message = new MqttMessage(responseMessage.getBytes());
try {
mqttClient.publish(MQTT_Resp_Topic, res_message);
} catch (MqttException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.d(TAG, "deliveryComplete");
}
};
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_airConditioner_off: {
lottie_air_animation.setVisibility(View.GONE);
textView_airConditioner_data.setVisibility(View.GONE);
lottie_loading_animation.setVisibility(View.GONE);
lottie_air_control_animation.resumeAnimation();
lottie_air_control_animation.setVisibility(View.VISIBLE);
textView_air_control.setVisibility(View.VISIBLE);
AirOffControlRequest req = new AirOffControlRequest("off");
try {
mqttClient.unsubscribe(MQTT_Req_Topic);
mqttClient.unsubscribe(MQTT_Resp_Topic);
System.out.println("unsub");
} catch (MqttException e) {
e.printStackTrace();
}
req.setReceiver(new IReceived() {
public void getResponseBody(final String msg) {
handler.post(new Runnable() {
public void run() {
//에어컨 제어 완료시 나올 텍스트 뷰...
}
});
}
});
req.start();
break;
}
case R.id.button_airConditioner_on: {
lottie_air_control_animation.setVisibility(View.GONE);
textView_air_control.setVisibility(View.GONE);
textView_airConditioner_data.setVisibility(View.VISIBLE);
lottie_loading_animation.setVisibility(View.VISIBLE);
AirOnControlRequest req = new AirOnControlRequest("on");
mqttClient = null;
mqttClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://" + csebase.getHost() + ":" + csebase.getMQTTPort(), MqttClient.generateClientId());
//http://192.168.10.75:7579/Mobius/IYAHN_DEMO/co2
mqttClient.setCallback(mainMqttCallback);
try {
IMqttToken token = mqttClient.connect();
token.setActionCallback(mainIMqttActionListener);
} catch (MqttException e) {
e.printStackTrace();
}
req.setReceiver(new IReceived() {
public void getResponseBody(final String msg) {
handler.post(new Runnable() {
public void run() {
textView_airConditioner_data.setVisibility(View.VISIBLE);
}
});
}
});
req.start();
break;
}
case R.id.btnControl_Led: {
if (((ToggleButton) v).isChecked()) {
textView_airConditioner_data.setVisibility(View.GONE);
textView_preview.setVisibility(View.VISIBLE);
button_backLight_control.setVisibility(View.VISIBLE);
button_frontLight_control.setVisibility(View.VISIBLE);
} else {
lottie_light_animation.setVisibility(View.GONE);
button_backLight_control.setVisibility(View.GONE);
button_frontLight_control.setVisibility(View.GONE);
}
break;
}
case R.id.button_frontLight_control: {
if (((ToggleButton) v).isChecked()) {
FrontLedControlRequest req = new FrontLedControlRequest("on");
req.setReceiver(new IReceived() {
public void getResponseBody(final String msg) {
handler.post(new Runnable() {
public void run() {
try {
textView_preview.setVisibility(View.GONE);
lottie_light_animation.resumeAnimation();
lottie_light_animation.setVisibility(View.VISIBLE);
JSONObject jsonObject = new JSONObject(msg);
JSONObject m2m_cin = new JSONObject(jsonObject.get("m2m:cin").toString());
textView_led_data.setVisibility(View.VISIBLE);
textView_led_data.setText("전등 센서 \r\n\r\n" + m2m_cin.get("con"));
} catch (JSONException e) {
// textView_led_loading.setVisibility(View.VISIBLE);
e.printStackTrace();
}
}
});
}
});
req.start();
} else {
lottie_light_animation.setVisibility(View.GONE);
BackLedControlRequest req = new BackLedControlRequest("off");
textView_preview.setVisibility(View.VISIBLE);
req.setReceiver(new IReceived() {
public void getResponseBody(final String msg) {
handler.post(new Runnable() {
public void run() {
try {
JSONObject jsonObject = new JSONObject(msg);
JSONObject m2m_cin = new JSONObject(jsonObject.get("m2m:cin").toString());
textView_led_data.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
req.start();
}
break;
}
case R.id.button_backLight_control: {
if (((ToggleButton) v).isChecked()) {
BackLedControlRequest req = new BackLedControlRequest("on");
req.setReceiver(new IReceived() {
public void getResponseBody(final String msg) {
handler.post(new Runnable() {
public void run() {
try {
textView_preview.setVisibility(View.GONE);
lottie_light_animation.resumeAnimation();
lottie_light_animation.setVisibility(View.VISIBLE);
JSONObject jsonObject = new JSONObject(msg);
JSONObject m2m_cin = new JSONObject(jsonObject.get("m2m:cin").toString());
textView_led_data.setVisibility(View.VISIBLE);
textView_led_data.setText("후등 센서 \r\n\r\n" + m2m_cin.get("con"));
} catch (JSONException e) {
// textView_led_loading.setVisibility(View.VISIBLE);
e.printStackTrace();
}
}
});
}
});
req.start();
} else {
lottie_light_animation.setVisibility(View.GONE);
BackLedControlRequest req = new BackLedControlRequest("off");
textView_preview.setVisibility(View.VISIBLE);
req.setReceiver(new IReceived() {
public void getResponseBody(final String msg) {
handler.post(new Runnable() {
public void run() {
try {
JSONObject jsonObject = new JSONObject(msg);
JSONObject m2m_cin = new JSONObject(jsonObject.get("m2m:cin").toString());
textView_led_data.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
req.start();
}
break;
}
}
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
/* Response callback Interface */
public interface IReceived {
void getResponseBody(String msg);
}
/* Retrieve airConditioner Sensor */
class RetrieveRequest extends Thread {
private final Logger LOG = Logger.getLogger(RetrieveRequest.class.getName());
private IReceived receiver;
private String ContainerName = "temperature";
public RetrieveRequest(String containerName) {
this.ContainerName = containerName;
}
public RetrieveRequest() {
}
public void setReceiver(IReceived handler) {
this.receiver = handler;
}
@Override
public void run() {
try {
String sb = csebase.getServiceUrl() + "/" + ServiceAEName + "/" + ContainerName + "/" + "latest";
URL mUrl = new URL(sb);
HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(false);
conn.setRequestProperty("Accept", "application/xml");
conn.setRequestProperty("X-M2M-RI", "12345");
conn.setRequestProperty("X-M2M-Origin", ae.getAEid());
conn.setRequestProperty("nmtype", "long");
conn.connect();
StringBuilder strResp = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String strLine = "";
while ((strLine = in.readLine()) != null) {
strResp.append(strLine);
}
if (strResp.toString() != "") {
receiver.getResponseBody(strResp.toString());
}
conn.disconnect();
} catch (Exception exp) {
LOG.log(Level.WARNING, exp.getMessage());
}
}
}
/* AirOff Control*/
class AirOffControlRequest extends Thread {
private final Logger LOG = Logger.getLogger(BackLedControlRequest.class.getName());
private IReceived receiver;
private String container_name = "aircon";
public ContentInstanceObject contentinstance;
//led con 값
public AirOffControlRequest(String comm) {
contentinstance = new ContentInstanceObject();
contentinstance.setContent(comm);
}
public void setReceiver(IReceived hanlder) {
this.receiver = hanlder;
}
@Override
public void run() {
try {
String sb = csebase.getServiceUrl() + "/" + ServiceAEName + "/" + container_name;
URL mUrl = new URL(sb);
HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/vnd.onem2m-res+xml;ty=4");
conn.setRequestProperty("locale", "ko");
conn.setRequestProperty("X-M2M-RI", "12345");
conn.setRequestProperty("X-M2M-Origin", ae.getAEid());
String reqContent = contentinstance.makeXML();
conn.setRequestProperty("Content-Length", String.valueOf(reqContent.length()));
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(reqContent.getBytes());
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder resp = new StringBuilder();
String strLine = "";
while ((strLine = in.readLine()) != null) {
resp.append(strLine);
}
if (resp.toString() != "") {
receiver.getResponseBody(resp.toString());
}
conn.disconnect();
} catch (Exception exp) {
LOG.log(Level.SEVERE, exp.getMessage());
}
}
}
/* AirOff Control*/
class AirOnControlRequest extends Thread {
private final Logger LOG = Logger.getLogger(BackLedControlRequest.class.getName());
private IReceived receiver;
private String container_name = "aircon";
public ContentInstanceObject contentinstance;
//led con 값
public AirOnControlRequest(String comm) {
contentinstance = new ContentInstanceObject();
contentinstance.setContent(comm);
}
public void setReceiver(IReceived hanlder) {
this.receiver = hanlder;
}
@Override
public void run() {
try {
String sb = csebase.getServiceUrl() + "/" + ServiceAEName + "/" + container_name;
URL mUrl = new URL(sb);
HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/vnd.onem2m-res+xml;ty=4");
conn.setRequestProperty("locale", "ko");
conn.setRequestProperty("X-M2M-RI", "12345");
conn.setRequestProperty("X-M2M-Origin", ae.getAEid());
String reqContent = contentinstance.makeXML();
conn.setRequestProperty("Content-Length", String.valueOf(reqContent.length()));
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(reqContent.getBytes());
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder resp = new StringBuilder();
String strLine = "";
while ((strLine = in.readLine()) != null) {
resp.append(strLine);
}
if (resp.toString() != "") {
receiver.getResponseBody(resp.toString());
}
conn.disconnect();
} catch (Exception exp) {
LOG.log(Level.SEVERE, exp.getMessage());
}
}
}
/* Request Control LED */
class FrontLedControlRequest extends Thread {
private final Logger LOG = Logger.getLogger(BackLedControlRequest.class.getName());
private IReceived receiver;
private String container_name = "front-led";
public ContentInstanceObject contentinstance;
//led con 값
public FrontLedControlRequest(String comm) {
contentinstance = new ContentInstanceObject();
contentinstance.setContent(comm);
}
public void setReceiver(IReceived hanlder) {
this.receiver = hanlder;
}
@Override
public void run() {
try {
String sb = csebase.getServiceUrl() + "/" + ServiceAEName + "/" + container_name;
URL mUrl = new URL(sb);
HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/vnd.onem2m-res+xml;ty=4");
conn.setRequestProperty("locale", "ko");
conn.setRequestProperty("X-M2M-RI", "12345");
conn.setRequestProperty("X-M2M-Origin", ae.getAEid());
String reqContent = contentinstance.makeXML();
conn.setRequestProperty("Content-Length", String.valueOf(reqContent.length()));
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(reqContent.getBytes());
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder resp = new StringBuilder();
String strLine = "";
while ((strLine = in.readLine()) != null) {
resp.append(strLine);
}
if (resp.toString() != "") {
System.out.println("HTTP 과부하");
receiver.getResponseBody(resp.toString());
}
conn.disconnect();
} catch (Exception exp) {
LOG.log(Level.SEVERE, exp.getMessage());
}
}
}
/* Request Control LED */
class BackLedControlRequest extends Thread {
private final Logger LOG = Logger.getLogger(BackLedControlRequest.class.getName());
private IReceived receiver;
private String container_name = "back-led";
public ContentInstanceObject contentinstance;
//led con 값
public BackLedControlRequest(String comm) {
contentinstance = new ContentInstanceObject();
contentinstance.setContent(comm);
}
public void setReceiver(IReceived hanlder) {
this.receiver = hanlder;
}
@Override
public void run() {
try {
String sb = csebase.getServiceUrl() + "/" + ServiceAEName + "/" + container_name;
URL mUrl = new URL(sb);
HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/vnd.onem2m-res+xml;ty=4");
conn.setRequestProperty("locale", "ko");
conn.setRequestProperty("X-M2M-RI", "12345");
conn.setRequestProperty("X-M2M-Origin", ae.getAEid());
String reqContent = contentinstance.makeXML();
conn.setRequestProperty("Content-Length", String.valueOf(reqContent.length()));
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(reqContent.getBytes());
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder resp = new StringBuilder();
String strLine = "";
while ((strLine = in.readLine()) != null) {
resp.append(strLine);
}
if (resp.toString() != "") {
System.out.println("HTTP 과부하");
receiver.getResponseBody(resp.toString());
}
conn.disconnect();
} catch (Exception exp) {
LOG.log(Level.SEVERE, exp.getMessage());
}
}
}
/* Request AE Creation */
static class aeCreateRequest extends Thread {
private final Logger LOG = Logger.getLogger(aeCreateRequest.class.getName());
String TAG = aeCreateRequest.class.getName();
private IReceived receiver;
int responseCode = 0;
public ApplicationEntityObject applicationEntity;
public void setReceiver(IReceived hanlder) {
this.receiver = hanlder;
}
public aeCreateRequest() {
applicationEntity = new ApplicationEntityObject();
applicationEntity.setResourceName(ae.getappName());
}
@Override
public void run() {
try {
String sb = csebase.getServiceUrl();
URL mUrl = new URL(sb);
HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("Content-Type", "application/vnd.onem2m-res+xml;ty=2");
conn.setRequestProperty("Accept", "application/xml");
conn.setRequestProperty("locale", "ko");
conn.setRequestProperty("X-M2M-Origin", "S" + ae.getappName());
conn.setRequestProperty("X-M2M-RI", "12345");
conn.setRequestProperty("X-M2M-NM", ae.getappName());
System.out.println();
String reqXml = applicationEntity.makeXML();
conn.setRequestProperty("Content-Length", String.valueOf(reqXml.length()));
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(reqXml.getBytes());
dos.flush();
dos.close();
responseCode = conn.getResponseCode();
BufferedReader in = null;
String aei = "";
if (responseCode == 201) {
// Get AEID from Response Data
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder resp = new StringBuilder();
String strLine;
while ((strLine = in.readLine()) != null) {
resp.append(strLine);
}
ParseElementXml pxml = new ParseElementXml();
aei = pxml.GetElementXml(resp.toString(), "aei");
ae.setAEid(aei);
Log.d(TAG, "Create Get AEID[" + aei + "]");
in.close();
}
if (responseCode != 0) {
receiver.getResponseBody(Integer.toString(responseCode));
}
conn.disconnect();
} catch (Exception exp) {
LOG.log(Level.SEVERE, exp.getMessage());
}
}
}
/* Retrieve AE-ID */
class aeRetrieveRequest extends Thread {
private final Logger LOG = Logger.getLogger(aeCreateRequest.class.getName());
private IReceived receiver;
int responseCode = 0;
public aeRetrieveRequest() {
}
public void setReceiver(IReceived hanlder) {
this.receiver = hanlder;
}
@Override
public void run() {
try {
String sb = csebase.getServiceUrl() + "/" + ae.getappName();
URL mUrl = new URL(sb);
HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(false);
conn.setRequestProperty("Accept", "application/xml");
conn.setRequestProperty("X-M2M-RI", "12345");
conn.setRequestProperty("X-M2M-Origin", "Sandoroid");
conn.setRequestProperty("nmtype", "short");
conn.connect();
responseCode = conn.getResponseCode();
BufferedReader in = null;
String aei = "";
if (responseCode == 200) {
// Get AEID from Response Data
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder resp = new StringBuilder();
String strLine;
while ((strLine = in.readLine()) != null) {
resp.append(strLine);
}
ParseElementXml pxml = new ParseElementXml();
aei = pxml.GetElementXml(resp.toString(), "aei");
ae.setAEid(aei);
//Log.d(TAG, "Retrieve Get AEID[" + aei + "]");
in.close();
}
if (responseCode != 0) {
receiver.getResponseBody(Integer.toString(responseCode));
}
conn.disconnect();
} catch (Exception exp) {
LOG.log(Level.SEVERE, exp.getMessage());
}
}
}
/* Subscribe air conditional Content Resource */
class SubscribeResource extends Thread {
private final Logger LOG = Logger.getLogger(SubscribeResource.class.getName());
private IReceived receiver;
private String container_name = "temperature"; //change to control container name
public ContentSubscribeObject subscribeInstance;
public SubscribeResource() {
subscribeInstance = new ContentSubscribeObject();
subscribeInstance.setUrl(csebase.getHost());
subscribeInstance.setResourceName(ae.getAEid() + "_rn3");
subscribeInstance.setPath(ae.getAEid() + "_sub");
subscribeInstance.setOrigin_id(ae.getAEid());
}
public void setReceiver(IReceived hanlder) {
this.receiver = hanlder;
}
@Override
public void run() {
try {
String sb = csebase.getServiceUrl() + "/" + ServiceAEName + "/" + container_name;
URL mUrl = new URL(sb);
HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("Accept", "application/xml");
conn.setRequestProperty("Content-Type", "application/vnd.onem2m-res+xml; ty=23");
conn.setRequestProperty("locale", "ko");
conn.setRequestProperty("X-M2M-RI", "12345");
conn.setRequestProperty("X-M2M-Origin", ae.getAEid());
String reqmqttContent = subscribeInstance.makeXML();
conn.setRequestProperty("Content-Length", String.valueOf(reqmqttContent.length()));
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(reqmqttContent.getBytes());
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String resp = "";
String strLine = "";
while ((strLine = in.readLine()) != null) {
resp += strLine;
}
if (resp != "") {
receiver.getResponseBody(resp);
}
conn.disconnect();
} catch (Exception exp) {
//이미 sub을 생성했기에, resource name이 겹쳐서 생기는 오류
LOG.log(Level.SEVERE, exp.getMessage());
}
}
}
} |
package com.timmy.framework.downRefresh;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.timmy.R;
public class CustomRefreshActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_refresh);
}
}
|
package com.mygdx.GameObjects;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ai.fsm.DefaultStateMachine;
import com.badlogic.gdx.ai.fsm.StateMachine;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.mygdx.Global.Assets;
import com.mygdx.Global.Constants;
import com.mygdx.ObjectInfo.CharacterStatsInfo;
import com.mygdx.ObjectInfo.ObjectSkillsInformation;
import com.mygdx.StateMachineHelper.OwnCharacterState;
import com.mygdx.assets.AbstractAssetInfo;
import com.mygdx.assets.AssetImpCharacter;
import com.mygdx.game.SkillHandler;
public class OwnCharacter extends AttackAbleGameObject{
public static final String Tag = OwnCharacter.class.getName();
public TextureRegion texReg = Assets.instance.assetCharacterGreenImp.walk_Vanilla_DOWN.getKeyFrame(0);
public AssetImpCharacter assetImpCharacter;
public StateMachine<OwnCharacter> stateMachine;
public boolean isAnimationFinish;
public float stateTime;
public OwnCharacter(CharacterStatsInfo characterStatsInfo,ObjectSkillsInformation skillInformation,AbstractAssetInfo asset){
super(characterStatsInfo,skillInformation,asset);
stateMachine = new DefaultStateMachine<OwnCharacter>(this, OwnCharacterState.IDLE);
assetImpCharacter = (AssetImpCharacter) asset;
//initSkilltestbegin
skillInformation.init();
//initSkilltestend
Gdx.app.debug(Tag, skillInformation.getSkill("BoltSizzle").skillInfo.skillName);
Gdx.app.debug(Tag, "baöböaböab");
//test end
bounds.width = texReg.getRegionWidth() * Constants.UNITSCALE;
bounds.height = texReg.getRegionHeight() * Constants.UNITSCALE;
position.x = 0;
position.y = 0;
scale.x= 1f;
scale.y =1f;
origin.x = bounds.width/2;
origin.y = bounds.height/2;
rotation = 0;
terminalVelocity.set(6.0f, 6.0f);
friction.set(18.0f, 18.0f);
acceleration.set(0.0f, 0.0f);
}
@Override
public void render(Batch batch) {
batch.begin();
batch.draw(texReg,position.x,position.y,
origin.x,origin.y,
bounds.width,bounds.height,scale.x,scale.y,rotation);
batch.end();
}
public void update(float deltaTime){
super.update(deltaTime);
stateTime += deltaTime;
stateMachine.update();
}
public void handleSkill(String skillName){
SkillHandler.handleSkill(skillInformation.getSkill(skillName),this, new Vector2());
}
}
|
/**
*
*/
package com.cnk.travelogix.common.facades.product.facet.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.fest.util.Collections;
import com.cnk.travelogix.common.facades.product.data.BaseProductData;
import com.cnk.travelogix.common.facades.product.data.CnkFacetData;
import com.cnk.travelogix.common.facades.product.data.CnkFacetValueData;
import com.cnk.travelogix.common.facades.product.facet.CnkFacetCalculationHelper;
/**
* @author i313879
*
*/
public class DefaultFacetCalculationHelper implements CnkFacetCalculationHelper
{
/*
* (non-Javadoc)
*
* @see
* com.cnk.travelogix.common.facades.product.facet.CnkFacetCalculationHelper#process(com.cnk.travelogix.common.facades
* .product.data.BaseProductData, com.cnk.travelogix.common.facades.product.data.CnkFacetData)
*/
@Override
public boolean process(final BaseProductData singleData, final CnkFacetData facet, final FacetToModelEntry facetEntry)
{
boolean result = true;
final Map<Object, CnkFacetValueData> facetMap = getFacetMap(facet);
String code = (String) facetEntry.getFacetValueCode(singleData);
final Object value = facetEntry.getFacetValue(singleData);
code = code == null ? "Empty" : code;
CnkFacetValueData facetValue = facetMap.get(code);
List<CnkFacetValueData> facetValueList = facet.getValues();
if (facetValueList == null)
{
facetValueList = new ArrayList();
}
if (facetValue == null)
{
facetValue = new CnkFacetValueData();
facetValue.setCode(code);
facetValue.setName(code);
facetValue.setValue(value.toString());
facetMap.put(code, facetValue);
facetValueList.add(facetValue);
}
facetValue.setCount(facetValue.getCount() + 1);
if (facetEntry.isNeedMinPrice())
{
final double price = facetEntry.getCaculatedPrice(singleData);
final double existValue = Double.parseDouble(facetValue.getValue());
if (price < existValue)
{
facetValue.setValue(Double.toString(price));
}
}
facet.setValues(facetValueList);
//TODO: need to consider multi select
result = isPassFilter(facetMap, code);
return result;
}
protected boolean isPassFilter(final Map<Object, CnkFacetValueData> facetMap, final String code)
{
boolean result = true;
final List<String> selectedCodes = new ArrayList();
for (final CnkFacetValueData facetValue : facetMap.values())
{
if (facetValue.isSelected())
{
selectedCodes.add(facetValue.getCode());
}
}
if (!Collections.isEmpty(selectedCodes))
{
result = selectedCodes.contains(code);
}
return result;
}
protected Map<Object, CnkFacetValueData> getFacetMap(final CnkFacetData facet)
{
final Map result = new HashMap();
if (facet.getValues() != null)
{
for (final CnkFacetValueData facetValue : facet.getValues())
{
result.put(facetValue.getCode(), facetValue);
}
}
return result;
}
}
|
package com.claycorp.nexstore.api.model;
import java.time.LocalDateTime;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
@JsonClassDescription("Order")
public class OrderVo {
@JsonProperty("orderId")
private String orderId;
@JsonProperty("orderStatusCode")
private RefOrderStatusCodesVo orderStatusCodeVo;
@JsonProperty("dateOfOrderPlaced")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonDeserialize(using=LocalDateTimeDeserializer.class)
@JsonSerialize(using=LocalDateTimeSerializer.class)
private LocalDateTime dateOfOrderPlaced;
@JsonProperty("orderDetails")
private List<OrderItemVo> orderDetailsVo;
public OrderVo() {
}
public String getOrderId() {
return orderId;
}
public OrderVo setOrderId(String orderId) {
this.orderId = orderId;
return this;
}
public RefOrderStatusCodesVo getOrderStatusCodeVo() {
return orderStatusCodeVo;
}
public OrderVo setOrderStatusCodeVo(RefOrderStatusCodesVo orderStatusCodeVo) {
this.orderStatusCodeVo = orderStatusCodeVo;
return this;
}
public LocalDateTime getDateOfOrderPlaced() {
return dateOfOrderPlaced;
}
public OrderVo setDateOfOrderPlaced(LocalDateTime dateOfOrderPlaced) {
this.dateOfOrderPlaced = dateOfOrderPlaced;
return this;
}
public List<OrderItemVo> getOrderDetailsVo() {
return orderDetailsVo;
}
public OrderVo setOrderDetailsVo(List<OrderItemVo> orderDetailsVo) {
this.orderDetailsVo = orderDetailsVo;
return this;
}
@Override
public String toString() {
return "OrderVo [orderId=" + orderId + ", orderStatusCodeVo=" + orderStatusCodeVo + ", dateOfOrderPlaced="
+ dateOfOrderPlaced + ", orderDetailsVo=" + orderDetailsVo + "]";
}
}
|
package com.youthchina.dao.tianjian;
import com.youthchina.domain.tianjian.*;
import com.youthchina.util.permission.HasOwnerMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.util.List;
/**
* Created by zhongyangwu on 11/10/18.
*/
@Mapper
@Component
public interface CommunityMapper extends HasOwnerMapper {
int addEssay(ComEssay essay);
int deleteEssay(@Param("essayId") Integer essay_id, @Param("isDeleteTime") Timestamp delete_time);
int updateEssay(ComEssay essay);
ComEssay getEssay(@Param("essayId") Integer essayId);
List<ComEssay> getEssayList(List<Integer> essayId);
List<ComEssay> getEssayLatest();
Integer countEssay();
int saveFriendsRelation(ComFriendRelation comFriendRelation);
int deleteFriend(@Param("comFriendRelation") ComFriendRelation comFriendRelation);
List<ComFriendRelation> getFriend(@Param("userId") Integer userId);
int saveFriendGroup(ComFriendGroup cfg);
int saveFriendGroupMap(ComFriendGroupMap cfgm);
int updateFriendGroup(@Param("comFriendGroup") ComFriendGroup comFriendGroup, @Param("relaId") Integer rela_id);
List<ComFriendGroup> getFriendGroup(List<ComFriendRelation> comFriendRelation);
void addFriendApply(ComFriendApply comFriendApply);
List<ComFriendApply> getAllFriendApply(@Param("userId") Integer userId);
ComFriendApply getFriendApply(@Param("userId") Integer userId, @Param("friendId") Integer friendId);
List<ComEssay> getAllEssayByUserId(@Param("userId") Integer user_id);
ComFriendApply getFriendApplication(@Param("applicationId") Integer applicationId);
void changeApplicationStatus(ComFriendApply comFriendApply);
}
|
package com.hebe.vo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
@Getter
@Setter
@ToString
public class TodoDTOList {
private ArrayList<TodoDTO> list;
}
|
package com.home.gfg;
public class ArrLargestSubarrayHavingEqual0s1s {
public static void printLargestSubarrayHavingEqual0s1s(int[] arr) {
//element at i having sum of elements from index 0 to i, considering 1 for 1 and -1 for 0
int[] sumLeft = new int[arr.length];
sumLeft[0] = (arr[0] == 0) ? -1 : 1;
int min = sumLeft[0], max = sumLeft[0], startIndex = 0, maxSize = -1;
for (int i = 1; i < sumLeft.length; i++) {
sumLeft[i] = sumLeft[i-1] + ((arr[i] == 0) ? -1 : 1);
if(sumLeft[i] < min) {
min = sumLeft[i];
}
if(sumLeft[i] > max) {
max = sumLeft[i];
}
}
System.out.println(max + " " + min);
int[] hash = new int[max-min+1];
for (int i = 0; i < hash.length; i++) {
hash[i] = -1;
}
for (int i = 0; i < sumLeft.length; i++) {
//for the case if subarray starts with index 0.
if(sumLeft[i] == 0) {
startIndex = 0;
maxSize = i + 1;
continue;
}
if(hash[sumLeft[i] - min] == -1) {
hash[sumLeft[i] - min] = i;
} else {
if(i - hash[sumLeft[i] - min] > maxSize) {
maxSize = i - hash[sumLeft[i] - min];
startIndex = hash[sumLeft[i] - min] + 1;
}
}
}
if(maxSize == -1) {
System.out.println("no such subarray exists");
} else {
System.out.println("max size is " + maxSize + " starting from " + startIndex);
}
}
}
|
public class MainArry extends MeanAvgSdArry
{
public static void main(String[] args) {
MeanAvgSdArry calc;
calc = new MeanAvgSdArry();
System.out.println("Mean " + calc.getMean());
System.out.println("Variance " + calc.getVariance());
System.out.println("Sd " + calc.getStdDev());
}
} |
package com.dicoding.myrecyclerview;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView rvHeroes;
private ArrayList<Hero> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvHeroes = findViewById(R.id.rv_heroes);
rvHeroes.setHasFixedSize(true);
list.addAll(getListHeroes());
showRecyclerList();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_list) {
rvHeroes.setLayoutManager(new LinearLayoutManager(this));
} else if (item.getItemId() == R.id.action_grid) {
rvHeroes.setLayoutManager(new GridLayoutManager(this, 2));
}
return super.onOptionsItemSelected(item);
}
public ArrayList<Hero> getListHeroes() {
String[] dataName = getResources().getStringArray(R.array.data_name);
String[] dataDescription = getResources().getStringArray(R.array.data_description);
String[] dataPhoto = getResources().getStringArray(R.array.data_photo);
ArrayList<Hero> listHero = new ArrayList<>();
for (int i = 0; i < dataName.length; i++) {
Hero hero = new Hero();
hero.setName(dataName[i]);
hero.setDescription(dataDescription[i]);
hero.setPhoto(dataPhoto[i]);
listHero.add(hero);
}
return listHero;
}
private void showRecyclerList(){
rvHeroes.setLayoutManager(new LinearLayoutManager(this));
ListHeroAdapter listHeroAdapter = new ListHeroAdapter(list);
rvHeroes.setAdapter(listHeroAdapter);
listHeroAdapter.setOnItemClickCallback(this::showSelectedHero);
}
private void showSelectedHero(Hero hero) {
Toast.makeText(this, "Kamu memilih " + hero.getName(), Toast.LENGTH_SHORT).show();
}
} |
package net.sourceforge.vrapper.vim.commands.motions;
import net.sourceforge.vrapper.utils.Position;
import net.sourceforge.vrapper.vim.EditorAdaptor;
import net.sourceforge.vrapper.vim.commands.CommandExecutionException;
public abstract class CountAwareMotion implements Motion {
public abstract Position destination(EditorAdaptor editorAdaptor, int count) throws CommandExecutionException;
public Position destination(EditorAdaptor editorAdaptor) throws CommandExecutionException {
return destination(editorAdaptor, getCount());
}
public int getCount() {
return NO_COUNT_GIVEN;
}
public Motion withCount(int count) {
return new CountedMotion(count, this);
}
public boolean isJump() {
return false;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.b2c.facades.homepage.impl;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.servicelayer.search.FlexibleSearchService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import com.cnk.travelogix.b2c.facades.homepage.HomePageFacade;
import com.cnk.travelogix.b2c.services.homepage.HomePageService;
import com.cnk.travelogix.common.core.enums.ProductTypeEnum;
import com.cnk.travelogix.common.core.model.TravellerTypeModel;
import com.cnk.travelogix.common.core.storefront.svcint.dto.air.SvcIntFlightGetAvailabilityAndFareResponse;
import com.cnk.travelogix.common.facades.home.data.TravellerDealData;
import com.cnk.travelogix.common.facades.product.data.flight.PopularFlightData;
import com.cnk.travelogix.common.facades.product.data.flight.PopularHotelCityData;
import com.cnk.travelogix.common.facades.product.data.flight.PopularHotelData;
import com.cnk.travelogix.common.facades.product.util.DateUtil;
/**
*
*/
public class DefaultHomePageFacade implements HomePageFacade
{
@Resource(name = "flexibleSearchService")
private FlexibleSearchService flexibleSearchService;
@Resource(name = "modelService")
private ModelService modelService;
@Resource(name = "homePageService")
private HomePageService homePageService;
@Override
public List<TravellerDealData> getTravellerDealData()
{
final List list = new ArrayList();
list.add(mockTravellerDealData());
final TravellerDealData hotelDeal1 = mockTravellerDealData();
hotelDeal1.setProductCategory("hotel");
list.add(hotelDeal1);
list.add(mockTravellerDealData());
final TravellerDealData hotelDeal2 = mockTravellerDealData();
hotelDeal2.setProductCategory("hotel");
list.add(hotelDeal2);
list.add(mockTravellerDealData());
list.add(mockTravellerDealData());
return list;
}
private TravellerDealData mockTravellerDealData()
{
final TravellerDealData data = new TravellerDealData();
data.setProductCategory("flight");
data.setProductCategprySubType("one way");
data.setOfferId("offerId");
data.setOfferName("offer Name");
data.setOfferImage("/home/deal_image1.jpg");
data.setOfferShortDesc("offer short desc");
data.setOfferType("Deal of the day");
data.setOfferValidity(new Date());
data.setLink("link");
data.setUserIdentity("user idntity");
data.setDestination("destination");
data.setSaving(Double.valueOf(5353.77));
return data;
}
@Override
public List<PopularFlightData> getPopularFlightData()
{
//final Date endDate = new Date();
//final Date startDate = DateUtil.getDateOffest(endDate, -30);
//step1:get top 9 flights in 90days
//final List<List<String>> flightsList = this.getTop9PopularFlights(startDate, endDate, ProductTypeEnum.TICKET);
//step2:get flights info and price by startDate:now,endDate:now +14
// for (int i = 0; i < flightsList.size(); i++)
// {
// final List list = flightsList.get(i);
// final String fromCity = (String) list.get(0);
// final String toCity = (String) list.get(1);
// final String flightType = (String) list.get(2);
// this.getFlightsFromSI(fromCity, toCity, flightType);
// }
final List list = new ArrayList();
list.add(mockPopularFlightData_1());
list.add(mockPopularFlightData_2());
list.add(mockPopularFlightData());
list.add(mockPopularFlightData());
list.add(mockPopularFlightData());
list.add(mockPopularFlightData());
list.add(mockPopularFlightData());
list.add(mockPopularFlightData());
list.add(mockPopularFlightData());
return list;
}
private PopularFlightData getFlightsFromSI(final String fromCity, final String toCity, final String flightType)
{
//final Date startDate = new Date();
//final Date endDate = DateUtil.getDateOffest(startDate, 14);
//TODO:get data from SI
final SvcIntFlightGetAvailabilityAndFareResponse responseFlight = new SvcIntFlightGetAvailabilityAndFareResponse();
final PopularFlightData popularFlightData = new PopularFlightData();
popularFlightData.setFromSector(fromCity);
popularFlightData.setToSector(toCity);
this.convertToPopularFlightData(responseFlight, popularFlightData);
return popularFlightData;
}
private PopularFlightData convertToPopularFlightData(final SvcIntFlightGetAvailabilityAndFareResponse responseFlight,
final PopularFlightData popularFlightData)
{
//final int count = responseFlight.getFlightList().size();
//TODO:common method calculated lowest price from price calendar;
final Double companyPrice = Double.valueOf(23456.66);
final Double publicPirce = Double.valueOf(2435.34);
//final Date LowestPriceDate = new Date();//TODO:
popularFlightData.setTotalBook(Integer.valueOf(0));
popularFlightData.setListPrice(companyPrice);
popularFlightData.setWebPrice(publicPirce);
popularFlightData.setDay("");
popularFlightData.setMonth("");
return popularFlightData;
}
private PopularFlightData mockPopularFlightData()
{
final PopularFlightData data = new PopularFlightData();
data.setFromSector("Delhi");
data.setToSector("Bangalore");
data.setWebPrice(Double.valueOf(3450));
data.setListPrice(Double.valueOf(2450));
data.setSavings(Double.valueOf(1000));
data.setTotalBook(Integer.valueOf(23423));
data.setMonth("Jul");
data.setDay("22");
return data;
}
private PopularHotelData mockPopularHotelData()
{
final PopularHotelData data = new PopularHotelData();
data.setHotelImage("");
data.setHotelListPrice(Double.valueOf(2256.5));
data.setHotelName("Ginger Tree Beach resort");
data.setHotelStarRating(Integer.valueOf(4));
data.setSavings(Double.valueOf(333));
data.setHotelWebPrice(Double.valueOf(1233));
final Date baseDate = new Date();
data.setCheckInDate(DateUtil.formateDateOffset(baseDate, 14));
data.setCheckOutDate(DateUtil.formateDateOffset(baseDate, 15));
return data;
}
private PopularFlightData mockPopularFlightData_1()
{
final PopularFlightData data = new PopularFlightData();
data.setFromSector("Delhi");
data.setToSector("Bangalore");
data.setWebPrice(Double.valueOf(5150));
data.setListPrice(Double.valueOf(2450));
data.setSavings(Double.valueOf(730));
data.setTotalBook(Integer.valueOf(23423));
data.setMonth("Jul");
data.setDay("12");
data.setDepartureTime("2016-08-12");
data.setReturnTime("2016-08-30");
data.setFlightType("RETURN");
return data;
}
private PopularFlightData mockPopularFlightData_2()
{
final PopularFlightData data = new PopularFlightData();
data.setFromSector("Mumbai");
data.setToSector("Delhi");
data.setWebPrice(Double.valueOf(9830));
data.setListPrice(Double.valueOf(2450));
data.setSavings(Double.valueOf(140));
data.setTotalBook(Integer.valueOf(23423));
data.setMonth("Jul");
data.setDay("18");
data.setDepartureTime("2016-08-02");
data.setReturnTime("2016-08-25");
data.setFlightType("ONE_WAY");
return data;
}
@Override
public List<PopularHotelCityData> getPopularHotelCityData()
{
//book 90 day
final Date startDate = new Date();
final Date endDate = DateUtil.getDateOffest(startDate, -90);
return this.requestTripAdvisor(getTop4PopularCities(startDate, endDate, ProductTypeEnum.ROOM));
}
private List<PopularHotelCityData> requestTripAdvisor(final List<String> cities)
{
//TODO: Integration with TripAdvisor to get hotels
final List<PopularHotelCityData> list = new ArrayList<PopularHotelCityData>(4);
list.add(mockPopularHotelCityData());
list.add(mockPopularHotelCityData());
list.add(mockPopularHotelCityData());
list.add(mockPopularHotelCityData());
//TODO:Integration with SI to get price and info
return list;
}
private PopularHotelCityData mockPopularHotelCityData()
{
final PopularHotelCityData data = new PopularHotelCityData();
data.setCity("Goa");
data.setTotalBook(Integer.valueOf(1234));
final Date baseDate = new Date();
data.setStartTime(DateUtil.formateDateOffset(baseDate, 0));
data.setEndTime(DateUtil.formateDateOffset(baseDate, 14));
final List<PopularHotelData> list = new ArrayList<PopularHotelData>(2);
list.add(mockPopularHotelData());
list.add(mockPopularHotelData());
data.setHotelList(list);
return data;
}
@Override
public List<String> getTop4PopularCities(final Date startDate, final Date endDate, final ProductTypeEnum productType)
{
return homePageService.getTop4PopularCitiesOfHotels(startDate, endDate, productType);
}
@Override
public List<TravellerTypeModel> getTravellerType()
{
return homePageService.getTravellerType();
}
@Override
public List getTop9PopularFlights(final Date startDate, final Date endDate, final ProductTypeEnum productType)
{
return homePageService.getTop9PopularFlights(startDate, endDate, productType);
}
}
|
package com.programmers.level1;
/** [평균구하기]
* 함수를 완성해서 매개변수 array의 평균값을 return하도록 만들어 보세요.
* 어떠한 크기의 array가 와도 평균값을 구할 수 있어야 합니다.
*/
public class GetMean {
public int getMean(int[] array) {
/*
return 0;
*/
int sum = 0;
int length = array.length;
for (int i = 0; i < length; i++) {
sum = sum + array[i];
}
return sum / length;
}
public static void main(String[] args) {
int x[] = { 5, 4, 3 };
GetMean getMean = new GetMean();
// 아래는 테스트로 출력해 보기 위한 코드입니다.
System.out.println("평균값 : " + getMean.getMean(x));
}
}
|
package app.integro.sjbhs.models;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class Sjbhs_Photos2List {
private String message;
public ArrayList<Sjbhs_Photos2> getSjbhsPhotos1ArrayList() {
return sjbhsPhotos1ArrayList;
}
public void setSjbhsPhotos1ArrayList(ArrayList<Sjbhs_Photos2> sjbhsPhotos1ArrayList) {
this.sjbhsPhotos1ArrayList = sjbhsPhotos1ArrayList;
}
@SerializedName("newsimages")
ArrayList<Sjbhs_Photos2> sjbhsPhotos1ArrayList;
private String success;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
|
package com.gmail.cwramirezg.task.features.task.add;
import com.gmail.cwramirezg.task.data.models.Task;
import com.gmail.cwramirezg.task.data.source.DataSourceRepository;
import com.gmail.cwramirezg.task.features.shared.BasePresenter;
import javax.inject.Inject;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
class AddTaskFragmentPresenter extends BasePresenter<AddTaskFragmentContract.View> implements AddTaskFragmentContract.Presenter {
private final DataSourceRepository dataSourceRepository;
private final CompositeDisposable disposables = new CompositeDisposable();
@Inject
public AddTaskFragmentPresenter(DataSourceRepository dataSourceRepository) {
this.dataSourceRepository = dataSourceRepository;
}
@Override
public void attachView(AddTaskFragmentContract.View mvpView) {
super.attachView(mvpView);
}
@Override
public void detachView() {
super.detachView();
disposables.clear();
}
@Override
public void addTask(Task task) {
disposables.add(dataSourceRepository.addTask(task)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mensajeResponse -> getView().showMessage("El registro fue agregado"),
throwable -> getView().showError(throwable.getMessage())));
}
}
|
package com.tdd.utils;
/**
*
* @author teyyub Mar 28, 2016 11:39:55 AM
*/
public class ConstantUtil {
public static final String NEWLINE = System.getProperty("line.separator");
public static final String DOT = ".";
public ConstantUtil(){}
}
|
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import misc.Parse;
import model.CouponService;
@WebServlet("/coupon")
public class CouponServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private CouponService service;
@Override
public void init() throws ServletException {
ServletContext application = this.getServletContext();
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);
service = (CouponService) context.getBean("CouponService");
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
String coupon = req.getParameter("coupon");
String discountString = req.getParameter("discount");
String deadlineString = req.getParameter("deadline");
String timesString = req.getParameter("times");
String notes = req.getParameter("notes");
String task = req.getParameter("task");
Map<String, String> errs = new HashMap<String, String>();
req.setAttribute("err", errs);
if(task==null){
errs.put("warning1", "你怎進來的");
}else if(task.equals("select") || task.equals("createOrUpdate") || task.equals("delete") || task.equals("find")) {
}else {
errs.put("warning1", "你怎進來的");
}
JSONObject jObj = new JSONObject();
PrintWriter out = resp.getWriter();
if(task != null){
if(task.equals("select")){
List<Map<String, Object>> beans = service.selectAll();
jObj.put("results", beans);
out.print(jObj);
return;
}
if(task.equals("find")){
int dis = service.select(coupon);
jObj.put("discount", dis);
out.print(jObj);
return;
}
if(task.equals("delete")){
service.delete(coupon);
return;
}
}
if(coupon==null || coupon.length()==0 || discountString==null || discountString.length()==0){
errs.put("warning2", "折扣碼、價值不允許空值");
}
int discount = 0;
if(discountString!=null && discountString.length()!=0){
discount = Parse.convertInt(discountString);
}
java.util.Date deadline = null;
if(deadlineString!=null && deadlineString.length()!=0){
deadline = Parse.convertDate(deadlineString);
}
Integer times = null;
if(timesString!=null && timesString.length()!=0){
times = (Integer)Parse.convertInt(timesString);
}
if(discountString==null || discountString.length()==0){
errs.put("warning1", "你怎進來的");
} else if(discount < 1){
errs.put("warning3", "格式錯誤、價格次數不可小於1");
}
if(deadline!=null){
if(deadline.equals(new java.util.Date(0))){
errs.put("warning4", "日期輸入格式錯誤、不可輸入今天之前");
} else if(deadline.before(new java.util.Date())){
errs.put("warning3", "日期輸入格式錯誤、不可輸入今天之前");
}
}
if(times!=null){
if(times < 1){
errs.put("warning4", "格式錯誤、價格次數不可小於1");
}
}
if(errs!=null && !errs.isEmpty()){
req.getRequestDispatcher(
"/backend_main.html").forward(req, resp);
return;
}
if(task.equals("createOrUpdate")){
service.createOrUpdate(coupon, discount, deadline, times, notes);
return;
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
|
//used by all 4 list classes
public class HNode
{
// HNode contains string, int, and link
private String info;
private FrontSelfAdjList list;
private HNode link;
private int numTimes;
//constructor
public HNode(String info)
{
this.info = info;
link = null;
numTimes = 1;
}
public HNode(FrontSelfAdjList nodeList)
{
this.list = nodeList;
link = null;
}
public void setInfo(String info)
// Sets info string
{
this.info = info;
}
public String getInfo()
// Returns info string
{
return info;
}
public FrontSelfAdjList getList()
{
return list;
}
public void setLink(HNode link)
// Sets link
{
this.link = link;
}
public HNode getLink()
// Returns link
{
return link;
}
public void increaseNumTimes()
{
numTimes++;
}
public void decreaseNumTimes()
{
numTimes--;
}
public int getNumTimes()
{
return numTimes;
}
public String toString()
{
String newString = getInfo()+ " "+ getNumTimes() + " Times";
return newString;
}
}
|
package com.android.lvxin.util;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Point;
import android.provider.MediaStore;
import android.view.Display;
import com.android.lvxin.data.VideoInfo;
import com.android.lvxin.data.AudioInfo;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName: Tools
* @Description: TODO
* @Author: lvxin
* @Date: 6/14/16 14:21
*/
public class Tools {
public static int getWindowWidth(Activity activity) {
Display display = activity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
return width;
}
public static List<AudioInfo> generateAudioItems(Context context) {
List<AudioInfo> items = new ArrayList<>();
String[] videoColumns = {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DURATION,
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, videoColumns, null, null, null);
int totalCount = cursor.getCount();
// no video, then show the no video hint
cursor.moveToFirst();
for (int i = 0; i < totalCount; i++) {
int audioId = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
String audioPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
long audioDuration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
String audioTitle = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
int audioSize = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
AudioInfo item = new AudioInfo(audioId, audioPath, audioTitle, audioSize, audioDuration);
items.add(item);
cursor.moveToNext();
}
cursor.close();
return items;
}
public static List<VideoInfo> generateVideoItems(Context context) {
List<VideoInfo> items = new ArrayList<>();
String[] videoColumns = {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DURATION,
};
Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoColumns, null, null, null);
int totalCount = cursor.getCount();
// no video, then show the no video hint
cursor.moveToFirst();
for (int i = 0; i < totalCount; i++) {
int audioId = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
String audioPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
long audioDuration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
String audioTitle = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
int audioSize = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
VideoInfo item = new VideoInfo(audioId, audioPath, audioTitle, audioSize, audioDuration);
items.add(item);
cursor.moveToNext();
}
cursor.close();
return items;
}
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static String getAbsolutePath(Context context) {
return context.getExternalFilesDir(null).getAbsolutePath();
}
public static String getVideoPath(Context context, String fileName) {
return context.getExternalFilesDir(null).getAbsolutePath() + "/" + fileName + ".mp4";
}
public static String getAudioPath(Context context, String fileName) {
return context.getExternalFilesDir(null).getAbsolutePath() + "/audios/" + fileName + ".mp3";
}
}
|
package com.jack.jkbase.config;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
//@Autowired SecurityInterceptor securityInterceptor;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//registry.addViewController("/").setViewName("forward:/index.html");
//registry.addViewController("/login.html").setViewName("login");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//registry.addInterceptor(securityInterceptor).addPathPatterns("/**/*.do"
// ,"/**/*.page").excludePathPatterns("/","/login.do","/**/*.html");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
}
//替换默认的JSON序列化工具为fastjson
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//1.构建了一个HttpMessageConverter FastJson 消息转换器
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//2.定义一个配置,设置编码方式,和格式化的形式
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//3.设置成了PrettyFormat格式
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullListAsEmpty,SerializerFeature.WriteDateUseDateFormat
,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullListAsEmpty,SerializerFeature.DisableCircularReferenceDetect);
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
//4.处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.TEXT_HTML);
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
//5.将fastJsonConfig加到消息转换器中
fastConverter.setFastJsonConfig(fastJsonConfig);
int idx = -1;
for (int i=0;i<converters.size();i++) {
HttpMessageConverter<?> c = converters.get(i);
if(c.getClass()== MappingJackson2HttpMessageConverter.class) {
idx = i;
break;
}
}
if (idx == -1)
converters.add(fastConverter);
else
converters.add(idx, fastConverter);//只要保证顺序在默认的jackson前面即可
}
@Bean
public DatabaseIdProvider getDatabaseIdProvider() {
DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
Properties properties = new Properties();
properties.setProperty("Oracle","oracle");
properties.setProperty("MySQL","mysql");
properties.setProperty("DB2","db2");
properties.setProperty("Derby","derby");
properties.setProperty("H2","h2");
properties.setProperty("HSQL","hsql");
properties.setProperty("Informix","informix");
properties.setProperty("Microsoft SQL Server","sqlserver");
properties.setProperty("PostgreSQL","postgresql");
properties.setProperty("Sybase","sybase");
properties.setProperty("Hana","hana");
databaseIdProvider.setProperties(properties);
return databaseIdProvider;
}
}
|
package br.usp.ime.restclient;
public class InvalidHTTPMethodException extends Exception{
/**
*
*/
private static final long serialVersionUID = 1L;
public InvalidHTTPMethodException(String message){
super(message);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.