branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>br1zz/HR-php-test<file_sep>/app/Http/Controllers/OrderController.php
<?php
namespace App\Http\Controllers;
use App\Order;
use App\Partner;
use App\Product;
use Illuminate\Http\Request;
class OrderController extends Controller
{
public function index()
{
$orders = Order::paginate(15);
//$price = Order::getPrice('4');
//dd($price);
//$orders = Order::find(2);
//dd($orders->convertStatus('10'));
return view('orders.index', compact('orders'));
}
public function create()
{
return redirect()->route('order.index');
}
public function store(Request $request)
{
return redirect()->route('order.index');
}
public function show($id)
{
return redirect()->route('order.index');
}
public function edit($id)
{
$order = Order::find($id);
$partners = Partner::pluck('name', 'id');
$statuses = Order::$statusArray;
//dd($order);
return view('orders.edit', compact('order','partners', 'product', 'statuses'));
}
public function update(Request $request, $id)
{
//($request);
$order = Order::find($id);
$order->edit($request->all());
$order->setPartner($request->get('partner_id'));
return redirect()->route('order.index');
}
public function destroy($id)
{
return redirect()->route('order.index');
}
}
<file_sep>/app/Order.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
public static $statusArray = ['0' => 'Новый', '10' => 'Подтвержден', '20' => 'Завершен'];
protected $fillable = ['status', 'client_email', 'partner_id'];
public function edit($fields)
{
$this->fill($fields);
$this->save();
}
public function products()
{
return $this->belongsToMany('App\Product','order_products')->withPivot('quantity', 'price');; //Определяем отношение между заказами и товарами
}
public function partner()
{
return $this->belongsTo('App\Partner'); //Определяем отношение между заказами и партнерами
}
public function getPrice($id)
{
$summ = 0;
$order = self::find($id);
foreach ($order->products as $product)
{
$summ += $product->pivot->price;
}
return $summ;
}
public function getStatus($key)
{
return $status = self::$statusArray[$key];
}
public function getPartnerId()
{
return ($this->partner != null) ? $this->partner->id : null;
}
public function setPartner($id)
{
if($id == null) {return;}
$this->partner_id = $id;
$this->save();
}
}
<file_sep>/app/Weather.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Response;
class Weather extends Model
{
public function getWeather($lat, $lon)
{
$url = 'https://api.weather.yandex.ru/v1/forecast?'; //Формируем строку для запроса к API
$params = [
'lat' => $lat,
'lon' => $lon
]; //Параметры, добавляемые к строке запроса. Lat - широта города, Lan - долгота города
$result = file_get_contents($url . http_build_query($params), false, stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => 'X-Yandex-API-Key: <KEY>'
)
))); //Формируем запрос, передавая в заголовке запроса ключ для авторидации в API.
return $result;
}
}
<file_sep>/app/Http/Controllers/WeatherController.php
<?php
namespace App\Http\Controllers;
use App\Weather;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class WeatherController extends Controller
{
public function index()
{
$rowData = new Weather;
$result = json_decode($rowData->getWeather('53.25209','34.37167'));
$time = 'Сейчас ' . date('H:i', time()+ 60*60*3); //Упростил, но конечно могу сделать более универсально, основываясь на времени города, для которго выводим погоду
//dd($result);
return view('weather', compact('result','time'));
}
}
|
9101272824abda63b32a1daeecb1325eda8d3f72
|
[
"PHP"
] | 4
|
PHP
|
br1zz/HR-php-test
|
7fac7f99de14d920c517e9523d5129f368f686c3
|
dde8375093ea36fd1e218cba097547984494eb02
|
refs/heads/master
|
<repo_name>DeltaV93/mdc-user-management-demo<file_sep>/webpack.riot.config.js
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const isProduction = process.env.NODE_ENV === `production`
const isDevelopment = process.env.NODE_ENV === `development`
const cssLoaders = [
{
loader: 'css-loader',
options: {
sourceMap: false,
'import': false,
minimize: isProduction,
},
},
{
loader: 'postcss-loader',
options: {
sourceMap: false,
plugins: () => [require('autoprefixer')({grid: false})],
},
},
{
loader: 'sass-loader',
options: {
sourceMap: false,
includePaths: [path.resolve(__dirname,'./node_modules')],
},
},
];
const rules = [
{
test: /\.tag$/,
loader: 'riot-tag-loader',
options: {
hot: true
}
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [
path.resolve(__dirname, 'riot'),
path.resolve(__dirname, 'node_modules/')
]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
}
}
]
const plugins = [
// create index.html
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'riot/index.html',
// inject: 'body',
minify: false,
chunksSortMode: 'dependency'
})
// add riot dependencies
// new WebpackCdnPlugin({
// modules: [
// {
// name: 'riot',
// var: 'riot',
// path: isProduction ? 'dist/riot.runtime.min.js' : 'dist/riot.runtime.js'
// },
// {
// name: 'riot-router',
// var: 'riotRouter',
// path: isProduction ? 'dist/riot-router.min.js' : 'dist/riot-router.js'
// }
// ],
// }),
]
const config = {
entry: {
'riot': path.resolve(__dirname,'riot/main.js'),
},
output: {
filename: isProduction ? '[name].[chunkhash].js' : '[name].js',
chunkFilename: isProduction ? '[name].[chunkhash].js' : '[name].js',
path: path.resolve(__dirname, isProduction ? 'public/riot-mdc-adapter' : 'dev'),
},
resolve: {
// alias: {
// 'riot-mdc-adapter': path.resolve(__dirname,'components/index.js'),
// 'riot': path.resolve(__dirname,'riot/')
// }
},
externals: {},
devtool: isProduction ? 'source-map' : 'cheap-eval-source-map',
module: { rules },
plugins
}
// Optimize for prod
if (isProduction) {
config.mode = 'production'
config.output.publicPath = '/riot-mdc-adapter/'
// extract css rule
config.module.rules.push({
test: /\.(css|scss)$/,
use: ExtractTextPlugin.extract({
use: cssLoaders,
fallback: 'style-loader'
})
})
config.plugins.push(
// clean output path
new CleanWebpackPlugin(config.output.path),
// split css
new ExtractTextPlugin({
filename: '[name].[chunkhash].css',
allChunks: true
}),
// copy assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, 'static'),
to: config.output.path,
ignore: ['.*']
}
]),
);
}
// Enable dev server
if (isDevelopment) {
config.mode = 'development'
// laod css rule
config.module.rules.push({
test: /\.(css|scss)$/,
use: ['style-loader'].concat(cssLoaders)
})
config.plugins.push(
// HMR
new webpack.HotModuleReplacementPlugin(),
new FriendlyErrorsWebpackPlugin()
)
config.devServer = {
contentBase: path.resolve(__dirname, 'static'),
disableHostCheck: true,
hot: true,
quiet: true
}
// cloud9 support
process.env.IP && (config.devServer.host = process.env.IP)
process.env.PORT && (config.devServer.port = process.env.PORT)
}
module.exports = config
<file_sep>/riot/main.js
import './styles/demo.scss'
import './polyfill.js'
import riot from 'riot'
// import 'riot-hot-reload'
// import router from 'riot-route'
// import VueMDCAdapter from 'vue-mdc-adapter'
// import index from './index.tag'
// import routes from './routes.js'
// Vue.config.productionTip = true
// Vue.use(VueRouter)
// Vue.use(VueMDCAdapter)
// const router = new VueRouter({
// routes,
// scrollBehavior() {
// return { x: 0, y: 0 }
// }
// })
// Vue.use(VueAnalytics, {
// id: 'UA-110490450-1',
// router
// })
//
// // mount app
// const App = Vue.extend({
// render: h => h(index)
// })
// new App({ router }).$mount('#app')
|
6d2bc3aa0569d3fb25bbfd8e6945459407674121
|
[
"JavaScript"
] | 2
|
JavaScript
|
DeltaV93/mdc-user-management-demo
|
85921447866230c3522d5e45a9f6300a8fc631f7
|
1fbaefc6d60a3b5a1afc555cd96b44492ad7d7b9
|
refs/heads/master
|
<file_sep># shell-tools
shell工具
自己常用的shell脚本
- phpslow.sh php慢日志分析工具
- nginx_simple.sh 简单的nginx日志分析工具
<file_sep>#===============================================================
#author cyuxlif
#php慢日志分析
#
#使用方法示例: chmod +x ./phpslow.sh
#./phpslow.sh -a bbs.log.slow // bbs.log.slow 为慢日志文件
#可选择日期./phpslow.sh -a bbs.log.slow --since 2015-07-28 --until 2015-07-28 -n 30
#--since 表示开始时间 后面跟日期, --until表示结束时间
#-n表示最终显示的条数
#
#统计每分钟产生的慢日志条数 使用方法为 ./phpslow.sh -s bbs.log.slow // bbs.log.slow 为慢日志文件 就是把-a换成-s 其它都一样,同样可选择时间
#
#===============================================================
#!/bin/bash
eval set -- `getopt -o "a:s:n:h" -l "since:,until:,help" -- "$@"`
SHOW_LINE=30
SINCE_LINE="1"
UNTIL_LINE="\$"
ACTION="a"
while true; do
case "${1}" in
-a)
LOGFILE="${2}"
shift 2
;;
-s)
ACTION="s"
LOGFILE="${2}"
shift 2
;;
-n)
SHOW_LINE="${2}"
shift 2
;;
--since)
SINCE_DATE=`env LANG=en_US.UTF-8 date -d ${2} +%d-%b-%Y`
shift 2
;;
--until)
UNTIL_DATE=`env LANG=en_US.UTF-8 date -d ${2} +%d-%b-%Y`
shift 2
;;
-h|--help)
echo -e "${0} 用法:\n[-a 日志文件]\n[-n 显示条数]]\n[--since 日期]\n[--until 日期]\n[-s 日志文件]"
exit 0
;;
--)
shift
break
;;
*)
echo "使用${0} [-h|--help]查看帮助"
exit 0
;;
esac
done
if [ ! -f "$LOGFILE" ]; then
echo "error:日志文件不存在"
exit 0
fi
#起始日期 行
if [ $SINCE_DATE ]; then
SINCE_LINE=`grep -n ${SINCE_DATE} ${LOGFILE} | head -n 1 | cut -d : -f 1`
SINCE_LINE=${SINCE_LINE:="1"}
fi
#终止日期 行
if [ $UNTIL_DATE ]; then
UNTIL_LINE=`grep -n ${UNTIL_DATE} ${LOGFILE} | tail -n 1 | cut -d : -f 1`
UNTIL_LINE=${UNTIL_LINE:="\$"}
fi
if [ $ACTION == "a" ]; then
#sed -n "${SINCE_LINE},${UNTIL_LINE}p" $LOGFILE 显示起止行
#sed "s/\[0x.*\] //;/pool www/d" 分别为删除[0x00007fe2e81f8500]类似字样, 删除[30-Jul-2015 14:16:12] [pool www] pid 35163 类似行
#awk -v RS="" '{gsub("\n", "|");print}'以空行为awk单位 并将以上处理过的换行替换成| 这样所有执行堆栈为一个整体 方便统计 和后面替换
#| sort | uniq -c | sort -nr | head -n $SHOW_LINE | 统计排序
#sed "s/|/\n\t/g" 替换|回换行符
sed -n "${SINCE_LINE},${UNTIL_LINE}p" $LOGFILE | sed "s/\[0x.*\] //;/pool www/d" | awk -v RS="" '{gsub("\n", "|");print}' | sort | uniq -c | sort -nr | head -n $SHOW_LINE | sed "s/|/\n\t/g"
fi
if [ $ACTION == "s" ]; then
sed -n "${SINCE_LINE},${UNTIL_LINE}p" $LOGFILE | grep 'pool www' | cut -d " " -f 2 | cut -d : -f 1,2 | sort | uniq -c | sort -nr | head -n $SHOW_LINE
fi
<file_sep>#===============================================================
#author cyuxlif
#nginx简单统计分析
#
#使用方法示例: chmod +x ./nginx_simple.sh
#./nginx_simple.sh -a www.bbs.nginx_access.log // nginx_access.log为nginx日志
#可选类型./nginx_simple.sh -a www.bbs.nginx_access.log -t url // nginx_access.log为nginx日志 -t url根据 url频次排序,-t ip根据ip频次排序
#可选择日期./nginx_simple.sh -a www.bbs.nginx_access.log --since "2015-10-21 05" --until "2015-10-21 07" -n 50
#--since 表示开始时间 后面跟日期, --until表示结束时间
#-n表示最终显示的条数
#
#
#===============================================================
#!/bin/bash
eval set -- `getopt -o "a:t:n:h" -l "since:,until:,help" -- "$@"`
SHOW_LINE=50
SINCE_LINE="1"
UNTIL_LINE="\$"
TYPE="url"
while true; do
case "${1}" in
-a)
LOGFILE="${2}"
shift 2
;;
-t)
TYPE="${2}"
shift 2
;;
-n)
SHOW_LINE="${2}"
shift 2
;;
--since)
SINCE_DATE=`env LANG=en_US.UTF-8 date -d "${2}" +%d/%b/%Y:%H`
shift 2
;;
--until)
UNTIL_DATE=`env LANG=en_US.UTF-8 date -d "${2}" +%d/%b/%Y:%H`
shift 2
;;
-h|--help)
echo -e "${0} 用法:\n[-a 日志文件]\n[-n 显示条数]]\n[--since 日期]\n[--until 日期]\n[-t 类型:url|ip]"
exit 0
;;
--)
shift
break
;;
*)
echo "使用${0} [-h|--help]查看帮助"
exit 0
;;
esac
done
if [ ! -f "$LOGFILE" ]; then
echo "error:日志文件不存在"
exit 0
fi
#起始日期 行
if [ $SINCE_DATE ]; then
SINCE_LINE=`grep -n ${SINCE_DATE} ${LOGFILE} | head -n 1 | cut -d : -f 1`
SINCE_LINE=${SINCE_LINE:="1"}
fi
#终止日期 行
if [ $UNTIL_DATE ]; then
UNTIL_LINE=`grep -n ${UNTIL_DATE} ${LOGFILE} | tail -n 1 | cut -d : -f 1`
UNTIL_LINE=${UNTIL_LINE:="\$"}
fi
if [ $TYPE == "url" ]; then
#$8 根据nginx日志配置格式自行调整
sed -n "${SINCE_LINE},${UNTIL_LINE}p" $LOGFILE |awk '{print $8}' | sort | uniq -c | sort -nr | head -n $SHOW_LINE
fi
if [ $TYPE == "ip" ]; then
sed -n "${SINCE_LINE},${UNTIL_LINE}p" $LOGFILE |awk '{print $1}' | sort | uniq -c | sort -nr | head -n $SHOW_LINE
fi
|
1dead156dee7f7491a78d254f73b808fed433f93
|
[
"Markdown",
"Shell"
] | 3
|
Markdown
|
cyuxlif/shellTools
|
5b971e49d6abc076374f97f15a1feb4c75b0b6d4
|
a4a669782be0395f09b6d7f033e28fe669bec1e2
|
refs/heads/master
|
<file_sep>#!/bin/bash
SUCCESS="\033[;32;1m"
WARNING="\033[;33;1m"
DANGER="\033[;31;1m"
INFO="\033[;35;1m"
END="\033[0m"
PWD=`pwd`
if [ `uname -s` != "Linux" ];then
printf "$DANGER This script only support Linux system.\n$END"
exit 126
fi
read -p "Please Input your supervisor config dir:" SPWD
read -p "Please Input your bind ip :" BIP
read -p "Please Input your bind port:" BP
read -p "Please Input your error log dir:" ELPWD
read -p "Please Input your info log dir:" ILPWD
function Install() {
yum install -y mysql-devel python-setuptools
easy_install pip
pip install -r $PWD/requiremets.txt
echo_supervisord_conf > $PWD/supervisor.conf
sed -i "s/bind = '127.0.0.1:5000'/bind = '$BIP:$BP'" $PWD/gunicorn_config.py
echo >> "[program:web]
command=gunicorn manage:web -c $PWD/gunicorn_config.py
directory=$PWD
autorestart=false
stdout_logfile=$ELPWD/gunicorn.log
stderr_logfile=$ILPWD/gunicorn.err"
}
Install
supervisord -c $SPWD/supervisor.conf
if [ `echo $?` -eq 0 ];then
printf "$SUCCESS Inception-web start success.\n$END"
else
printf "$DANGER Inception-web start failed.\n$END"
fi
<file_sep># inception-web
已经能简单的使用了, 现在还只能作为检查sql使用,并不能执行
<pre><code>sh install.sh</code></pre>
<file_sep>#!/usr/bin/env python
# encoding: utf-8
import MySQLdb
from chardet import detect
from flask import current_app, render_template
from flask.ext.mail import Message
from weberror import ResultError, SqlError
from .. import mail
from threading import Thread
def Con():
try:
conn=MySQLdb.connect(
host=current_app.config['INCEPTION_HOST'],
user=current_app.config['INCEPTION_USER'],
passwd=current_app.config['INCEPTION_PASSWORD'],
port=current_app.config['INCEPTION_PORT'],
)
cur=conn.cursor()
return cur
except MySQLdb.Error, e:
return "Mysql Error %d: %s" % (e.args[0], e.args[1])
def Exec(database, SQL):
sql = '''/*--user=%s;--password=%s;--host=%s;--check=1;--port=%s;*/
inception_magic_start;
use %s;
%s
inception_magic_commit;
''' % (current_app.config['MYSQL_USER_EXCUTE'], current_app.config['MYSQL_PASSWORD_EXCUTE'],
current_app.config['MYSQL_HOST_EXCUTE'], current_app.config['MYSQL_PORT_EXCUTE'],
database, SQL)
try:
cur = Con()
ret = cur.execute(sql)
result = cur.fetchall()
if len(cur.description) != 11:
raise ResultError('Result must 11 keys.')
res = {
'number': int(ret),
'result': result,
}
cur.close()
return res
except MySQLdb.Error, e:
return "%s" % e
def Schema(res):
if type(res) is not dict:
raise TypeError('variable must dict.')
num = res['number']
info = res['result']
if num != len(info):
raise SqlError('input and execute are not equal.')
if type(info) is not tuple:
raise TypeError('inception result must be tuple.')
Query_set = {}
for result in range(num):
row = info[result]
Query_set['sql' + str(result)] = {
'ID': int(row[0]),
'stage': row[1],
'errlevel': int(row[2]),
'stagestatus': row[3],
'errormessage': row[4].decode('utf8'),
'SQL': row[5].decode('utf8'),
'affected_rows': row[6],
'sequence': row[7],
'backup_dbname': row[8],
'execute_time': row[9],
'SQLSHA1': row[10],
}
return Query_set
def Opinception(option):
sql = option
try:
cur = Con()
ret = cur.execute(sql)
result = cur.fetchall()
cur.close()
return result
except MySQLdb.Error, e:
return "%s" % e
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(to, subject, template, **kwargs):
app = current_app._get_current_object()
msg = Message(app.config['FLASK_MAIL_SUBJECT_PREFIX'] + subject,
sender=current_app.config['FLASK_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return thr
<file_sep>#!/usr/bin/env python
# encoding: utf-8
import os
from web import create_app, db
from web.models import User, Task
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
web = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(web)
migrate = Migrate(web, db)
def make_shell_context():
return dict(web=web, db=db, User=User, Task=Task)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
<file_sep>$(document).ready(function(){
$("a#mydropdown").click(function(){
$("a#mydropdown").css("color", "black");
});
$("a#mydropdown").mouseout(function(){
$("a#mydropdown").css("color", "white");
});
$("a#mydropdown").mouseover(function(){
$("a#mydropdown").css("color", "red");
});
});
<file_sep>#!/usr/bin/env python
# coding:utf-8
from flask import render_template, redirect, request, url_for, flash, current_app
from flask.ext.login import login_user, logout_user, login_required, current_user
from . import auth
from ..models import User
from .forms import LoginForm, AddUserForm, ChangepasswordForm, EditProfileAdminForm
from ..decorators import administrator_required
from .. import db
_THOUSAND_DAY = 86400 * 1000
@auth.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user, form.remember_me.data)
return redirect(request.args.get('next') or url_for('main.index'))
flash(u'无效的地址或密码')
return render_template('auth/login.html', form=form)
@auth.route('/logout', methods=['GET', 'POST'])
@login_required
def logout():
logout_user()
flash(u'已退出登录')
return redirect(url_for('auth.login'))
@auth.route('/add_user', methods=['GET', 'POST'])
@login_required
@administrator_required
def AddUser():
form = AddUserForm()
if form.validate_on_submit():
user = User(email=form.email.data,
username=form.username.data,
password=form.password.data)
db.session.add(user)
return redirect(url_for('main.users'))
return render_template('auth/add_user.html', form=form)
@auth.route('/del_user/<int:id>', methods=['GET', 'POST'])
@login_required
@administrator_required
def del_user(id):
'''admin can del a user'''
user = User.query.get_or_404(id)
name = user.username
db.session.delete(user)
flash(u'删除用户%s' % name)
return redirect(url_for('main.users'))
@auth.route('/changepassword', methods=['GET', 'POST'])
@login_required
def changepassword():
'''change password route url'''
form = ChangepasswordForm()
if request.method == "POST":
if current_user.verify_password(form.oldpassword.data):
current_user.password = form.newpassword.data
db.session.add(current_user)
flash(u'更改成功.')
return redirect(url_for('main.index'))
else:
flash(u'更改失败.')
return render_template("auth/changepassword.html", form=form)
@auth.route('/editprofile/<int:id>', methods=['GET', 'POST'])
@login_required
@administrator_required
def edit_profile_admin(id):
'''admin user information edit url'''
user = User.query.get_or_404(id)
form = EditProfileAdminForm(user=user)
if form.validate_on_submit():
user.email = form.email.data
user.username = form.username.data
user.password = form.password.data
db.session.add(user)
flash(u'资料已修改')
return redirect(url_for('main.users'))
form.email.data = user.email
form.username.data = user.username
return render_template('auth/edit_profile.html', form=form)
@auth.route('/sudo/<int:id>', methods=['GET', 'POST'])
@login_required
@administrator_required
def sudo(id):
'''admin can give user administrator privileges'''
user = User.query.get_or_404(id)
if user.permissions != 0:
user.permissions = 0
db.session.add(user)
return redirect(url_for('main.users'))
else:
user.permissions = 1
db.session.add(user)
return redirect(url_for('main.users'))
<file_sep>from . import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask.ext.login import UserMixin
from . import login_manager
from datetime import datetime
class User(UserMixin, db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
permissions = db.Column(db.Integer, nullable=False, default=1)
def __repr__(self):
return self.email
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def admin(self):
if self.permissions == 0:
return True
@staticmethod
def set_admin(passwd, mail='<EMAIL>'):
u = User(email=mail,
username='admin',
password=<PASSWORD>,
permissions=0)
db.session.add(u)
db.session.commit()
@staticmethod
def generate_fake(count=10):
from sqlalchemy.exc import IntegrityError
from random import seed
import forgery_py
seed()
for i in range(count):
u = User(email=forgery_py.internet.email_address(),
username=forgery_py.internet.user_name(True),
password=for<PASSWORD>())
db.session.add(u)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
class Task(db.Model):
__tablename__ = 'task'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(128), unique=True, index=True)
uuid = db.Column(db.String(40))
createtime = db.Column(db.DateTime(), default=datetime.now, index=True)
author = db.Column(db.String(64), nullable=True, index=True)
exectime = db.Column(db.DateTime(), nullable=True, index=True)
auditlog = db.Column(db.Text, nullable=True)
# STATUS 0:success; 1:wating check; 2:error; 3:wating audit; 4:no pass audit
status = db.Column(db.Integer, default=1, index=True)
date_base = db.Column(db.String(32))
sql = db.Column(db.Text)
remark = db.Column(db.Text, nullable=True)
def __repr__(self):
return self.title
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
<file_sep>"""initial migration
Revision ID: 2c8964ea9e55
Revises: None
Create Date: 2016-06-22 13:14:49.799422
"""
# revision identifiers, used by Alembic.
revision = '2<PASSWORD>'
down_revision = None
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('task', sa.Column('date_base', sa.String(length=32), nullable=True))
op.drop_column('task', 'apptime')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('task', sa.Column('apptime', mysql.DATETIME(), nullable=True))
op.drop_column('task', 'date_base')
### end Alembic commands ###
<file_sep>#!/usr/bin/env python
#! coding: utf8
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
DEBUG = True
SECRET_KEY = os.environ.get('SECRET_KEY') or 'oU0GKFWBC67sJDrghm3o5eVpLc'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_POOL_SIZE = 100
SQLALCHEMY_POOL_TIMEOUT = 10
SQLALCHEMY_POOL_RECYCLE = 2000
FLASK_PER_PAGE = 20
MAIL_SERVER = 'smtp.163.com'
MAIL_PORT = 465
MAIL_USE_TLS = True
MAIL_USERNAME = os.getenv('MAIL_USERNAME', '<EMAIL>')
MAIL_PASSWORD = os.getenv('MAIL_PASSWORD', '<PASSWORD>')
FLASK_MAIL_SUBJECT_PREFIX = 'Inception'
FLASK_MAIL_SENDER = 'Inception Admin <test>'
INCEPTION_HOST = os.getenv('INCEPTION_HOST', '127.0.0.1')
INCEPTION_PORT = os.getenv('INCEPTION_PORT', 6669)
INCEPTION_USER = os.getenv('INCEPTION_USER', 'root')
INCEPTION_PASSWORD = os.getenv('INCEPTION_PASSWORD', '')
MYSQL_HOST_EXCUTE = os.getenv('MYSQL_HOST', '127.0.0.1')
MYSQL_PORT_EXCUTE = os.getenv('MYSQL_PORT', 3306)
MYSQL_USER_EXCUTE = os.getenv('MYSQL_USER', 'root')
MYSQL_PASSWORD_EXCUTE = os.getenv('MYSQL_PASSWORD', "<PASSWORD>.")
MYSQL_HOST = os.getenv('MYSQL_HOST', '127.0.0.1')
MYSQL_PORT = os.getenv('MYSQL_PORT', 3306)
MYSQL_USER = os.getenv('MYSQL_USER', 'inception')
MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD', "<PASSWORD>")
MYSQL_DATABASE = os.getenv('MYSQL_DATABASE', 'inception')
SQLALCHEMY_DATABASE_URI = 'mysql://{0}:{1}@{2}:{3}/{4}'.format(
MYSQL_USER, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_PORT, MYSQL_DATABASE,
)
@staticmethod
def init_app(web):
pass
config = {
'default': Config,
}
<file_sep>#!/usr/bin/env python
# encoding: utf-8
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.mail import Mail
from config import config
bootstrap = Bootstrap()
db = SQLAlchemy()
mail = Mail()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
web = Flask(__name__)
web.config.from_object(config[config_name])
config[config_name].init_app(web)
bootstrap.init_app(web)
db.init_app(web)
login_manager.init_app(web)
mail.init_app(web)
from .main import main as main_blueprint
web.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
web.register_blueprint(auth_blueprint, url_prefix='/auth')
return web
<file_sep>#!/usr/bin/env python
# encoding: utf-8
import uuid
from flask import render_template, request, flash, current_app, \
redirect, url_for
from . import main
from ..models import User, Task
from web.main.task import Exec, Schema, send_email, Opinception
from ..decorators import administrator_required
from flask.ext.login import login_required, current_user
from .. import db
@main.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
@main.route('/users', methods=['GET', 'POST'])
@login_required
@administrator_required
def users():
page = request.args.get('page', 1, type=int)
pagination = User.query.order_by(User.id.desc()).paginate(
page, per_page=current_app.config['FLASK_PER_PAGE'],
error_out=False)
users = pagination.items
return render_template('users.html',
pagination=pagination, users=users)
@main.route('/audit', methods=['GET', 'POST'])
@login_required
def audit():
return render_template('sql_audit.html')
@main.route('/result', methods=['GET', 'POST'])
@login_required
def result():
if request.form.get('database', None) and \
request.form.get('sql', None):
database = request.form.getlist('database')[0]
sql = request.form.getlist('sql')[0]
res = Exec(database, sql)
info = Schema(res)
print info
return render_template('result.html', info=info)
flash(u'数据库,sql语句,都不能留空啊.')
return render_template('sql_audit.html')
@main.route('/tasks', methods=['GET', 'POST'])
@login_required
def task():
page = request.args.get('page', 1, type=int)
pagination = Task.query.order_by(Task.createtime.desc()).paginate(
page, per_page=current_app.config['FLASK_PER_PAGE'],
error_out=False)
tasks = pagination.items
return render_template('task.html',
pagination=pagination, tasks=tasks)
@main.route('/addtask', methods=['GET', 'POST'])
@login_required
def addtask():
if request.form.get('tasktitle', None) and \
request.form.get('tasksql', None):
task = Task(
title=request.form.getlist('tasktitle')[0],
uuid=str(uuid.uuid1()),
author=current_user.username,
date_base=request.form.getlist('taskdb')[0],
sql=request.form.getlist('tasksql')[0],
remark=request.form.getlist('taskremark')[0],
)
db.session.add(task)
send_email('<EMAIL>', u'新sql上线任务',
'mail/new_task', user=current_user)
return redirect(url_for('main.task'))
flash(u'标题,sql语句是不是有问题啊!')
return render_template('sql_audit.html')
@main.route('/check/<int:id>', methods=['GET', 'POST'])
@login_required
def check(id):
task = Task.query.get_or_404(id)
date = task.date_base
sql = task.sql
res = Schema(Exec(date, sql))
task.auditlog = str(res)
task.status = 3
db.session.add(task)
return redirect(url_for('main.task'))
@main.route('/sqltask/<int:id>', methods=['GET', 'POST'])
@login_required
def sqltask(id):
task = Task.query.get_or_404(id)
return render_template('sqltask.html', task=task)
@main.route('/settings', methods=['GET', 'POST'])
@login_required
@administrator_required
def GetSetting():
res = Opinception('inception get variables;')
return render_template('setting.html', res=res)
@main.route('/help', methods=['GET', 'POST'])
@login_required
@administrator_required
def help():
return render_template('help.html')
|
e98099729d056f72ba5d8ee60bc8d6bc88dfab92
|
[
"Markdown",
"Python",
"JavaScript",
"Shell"
] | 11
|
Shell
|
Fize/inception-web
|
be516742dc9ef11adcf490d1381142553258921b
|
9a933a53a56dc9e7279c4b288b96e62f49aa04e1
|
refs/heads/master
|
<repo_name>libin1991/audio-test<file_sep>/js/songs.js
var songs = [
{
'pulse': null,
'square': filterNotes(OdetojoySynth1).notes,
'triangle': filterNotes(OdetojoyBass1).notes,
'noise': null,
'length': '32m',
'video': ''
},
{
'pulse': MarioSynth1,
'square': MarioSynth2,
'triangle': MarioBass1,
'noise': MarioBass2,
'length': '85',
'video': 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/355309/8-bit-mario.mp4'
},
{
'pulse': ZeldaSynth1,
'square': ZeldaSynth2,
'triangle': ZeldaBass1,
'noise': ZeldaBass2,
'length': '39',
'video': 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/355309/8-bit-zelda.mp4'
},
{
'pulse': filterNotes(PacmanSynth1).notes,
'square': null,
'triangle': filterNotes(PacmanBass1).notes,
'noise': null,
'length': '2m',
'video': 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/355309/8-bit-pacman.mp4'
}
]
<file_sep>/README.MD
# Demo1
在 https://codepen.io/gregh/project/editor/aAexRX 基础上做了些修改,加了《欢乐颂》的乐曲
参考文章:https://codepen.io/gregh/post/recreating-legendary-8-bit-games-music-with-web-audio-api
|
3468b29e2d335deac18b743b7ec05691e906814b
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
libin1991/audio-test
|
18fef2175cae345ea92d2ea43143ec1605928516
|
78dbe7e53b28e7ab1876f430ba3dbed636c59fb5
|
HEAD
|
<repo_name>jaenwawe/ErrorLogger<file_sep>/MiniInventory/HomeControllerLogic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MiniInventory
{
class HomeControllerLogic
{
}
}
<file_sep>/DBLayer/InventoryLoader.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBLayer
{
public class InventoryLoader
{
}
}
|
1eca453e3be3231261927f62d145b9175c04b457
|
[
"C#"
] | 2
|
C#
|
jaenwawe/ErrorLogger
|
61ce1e3d607c91fa8c8ad3543aa3e1195fc5abde
|
fb86c62929c964d7419289f21abb2970e5d3f5c2
|
refs/heads/master
|
<repo_name>ngust/wethesafe<file_sep>/app/controllers/admin/primes_controller.rb
class Admin::PrimesController < Admin::BaseAdminController
before_action :set_prime, only: [:show, :edit, :update, :destroy]
helper_method :sort_column, :sort_direction
def index
@primes = Prime.all
# @primes = @primes.order(:updated_at).reverse_order.page(params[:page]).per(15)
if sort_column == "company"
emps = []
Employer.all.each do |emp|
emps.push(emp.id)
end
@primes = @primes.where(employer_id: emps).order("id #{sort_direction}").page(params[:page]).per(15)
# @primes = @primes.joins(:employers).where(employer_id: :id).order("employers.name #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "employers"
@primes = @primes.joins(:employers).group(:id).order("COUNT(employers) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "workers"
@primes = @primes.joins(:workers).group(:id).order("COUNT(workers) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "sites"
@primes = @primes.joins(:sites).group(:id).order("COUNT(sites) #{sort_direction}").page(params[:page]).per(15)
else
@primes = @primes.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
end
# GET /primes/1
def show
end
# GET /primes/new
def new
@prime = Prime.new
end
# GET /primes/1/edit
def edit
end
# POST /primes
def create
@prime = Prime.new(prime_params)
if @prime.save
redirect_to admin_primes_path, notice: "Prime Created successfully!"
else
flash[:error] = @prime.errors.full_messages.to_sentence
render :new, notice: "Prime could not be created!"
end
end
# PATCH/PUT /primes/1
# PATCH/PUT /primes/1.json
def update
if @prime.update_attributes(prime_params)
redirect_to admin_primes_path, notice: "Prime Updated successfully!"
else
flash[:error] = @prime.errors.full_messages.to_sentence
render :new, notice: "Prime could not be updated!"
end
end
# DELETE /primes/1
# DELETE /primes/1.json
def destroy
@prime.destroy
redirect_to admin_primes_path, notice: "#{@prime.id} was deleted successfully!"
end
private
# Use callbacks to share common setup or constraints between actions.
def set_prime
@prime = Prime.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def prime_params
params.require(:prime).permit(
:employer_id
)
end
def current_resource
@current_resource ||= Prime.find(params[:id]) if params[:id]
end
def sort_column
params[:column] ? params[:column] : "updated_at"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end
<file_sep>/test/controllers/papwerworks_controller_test.rb
require 'test_helper'
class PapwerworksControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get papwerworks_index_url
assert_response :success
end
test "should get new" do
get papwerworks_new_url
assert_response :success
end
test "should get edit" do
get papwerworks_edit_url
assert_response :success
end
test "should get show" do
get papwerworks_show_url
assert_response :success
end
end
<file_sep>/app/controllers/nyw_forms_controller.rb
class NywFormsController < ApplicationController
def new
@worker = Worker.find(params[:worker_id])
@nyw = Nyw.find(params[:nyw_id])
@nyw_forms = @nyw.nyw_forms.build
@nyw_forms.paperwork_id = params[:paperwork_id]
@nyw_forms.site_id = @worker.site.id if @worker.site
@sites = Site.all
end
def create
@worker = Worker.find(params[:worker_id])
@sites = Site.all
@nyw = Nyw.find(params[:nyw_id])
@nyw_forms = @nyw.nyw_forms.build(nyw_forms_params)
if @nyw_forms.save
redirect_to @worker, notice: "NywForm contacts created successfully"
else
render :new
end
end
def edit
@nyw_forms = NywForm.find(params[:id])
@worker = Worker.find(params[:worker_id])
@nyw = Nyw.find(params[:nyw_id])
@sites = Site.all
end
def destroy
@nyw_forms = NywForm.find(params[:id])
@worker = Worker.find(params[:worker_id])
@nyw_forms.destroy
redirect_to worker_path(@worker), notice: "#{@nyw_forms.id} was deleted successfully!"
end
def update
@nyw_forms = NywForm.find(params[:id])
@worker = Worker.find(params[:worker_id])
if @nyw_forms.update_attributes(nyw_forms_params)
redirect_to worker_path(@worker), notice: "nyw_forms updated successfully"
else
flash[:error] = "#{@nyw_forms.errors.count} errors prevented nyw_forms from being updated."
render :edit
end
end
protected
def nyw_forms_params
params.require(:nyw_form).permit(:id, :site_id, :reviewed, :nyw_id, :paperwork_id)
end
end
<file_sep>/app/models/extra_topic.rb
class ExtraTopic < ApplicationRecord
belongs_to :toolbox
end
<file_sep>/db/migrate/20180929170428_remove_send_from_statement.rb
class RemoveSendFromStatement < ActiveRecord::Migration[5.1]
def change
remove_column :statements, :send, :string
end
end
<file_sep>/db/migrate/20180612231500_add_wethesafe_to_certificates.rb
class AddWethesafeToCertificates < ActiveRecord::Migration[5.1]
def change
add_column :certificates, :wethesafe, :boolean
end
end
<file_sep>/db/migrate/20180613003822_fix_type_in_courses.rb
class FixTypeInCourses < ActiveRecord::Migration[5.1]
def change
rename_column :courses, :type, :enrollment
end
end
<file_sep>/db/migrate/20180515032448_add_fields_to_employer.rb
class AddFieldsToEmployer < ActiveRecord::Migration[5.1]
def change
add_column :employers, :cor_cert, :boolean
add_column :employers, :cor_int, :date
add_column :employers, :cor_ext, :date
end
end
<file_sep>/app/models/course_record.rb
class CourseRecord < ApplicationRecord
belongs_to :course
belongs_to :worker
validates_uniqueness_of :worker_id, scope: :course_id, message: "is already in the course!"
# validate :worker_per_course
# def worker_per_course
# worker = Worker.find(self.worker_id)
# course = Course.find(self.course_id)
# if course.workers.ids.include?(self.worker_id)
# errors.add(:worker, "is already in the course!" )
# end
# end
end
<file_sep>/app/controllers/violations_controller.rb
class ViolationsController < ApplicationController
def new
@worker = Worker.find(params[:worker_id])
@violation = @worker.violations.build
emp = @worker.employer
@sites = emp.sites
end
def create
@worker = Worker.find(params[:worker_id])
emp = @worker.employer
@sites = emp.sites
@violation = @worker.violations.build(violation_params)
if @violation.save
redirect_to @worker, notice: "Violation contacts created successfully"
else
render :new
end
end
def edit
@violation = Violation.find(params[:id])
@worker = Worker.find(params[:worker_id])
emp = @worker.employer
@sites = emp.sites
end
def destroy
@violation = Violation.find(params[:id])
@worker = Worker.find(params[:worker_id])
@violation.destroy
redirect_to worker_path(@worker), notice: "#{@violation.id} was deleted successfully!"
end
def update
@violation = Violation.find(params[:id])
@worker = Worker.find(params[:worker_id])
if @violation.update_attributes(violation_params)
redirect_to worker_path(@worker), notice: "violation updated successfully"
else
flash[:error] = "#{@violation.errors.count} errors prevented violation from being updated."
render :edit
end
end
protected
def violation_params
params.require(:violation).permit(:site_id,:date,:desc)
end
end
<file_sep>/test/controllers/toolboxes_controller_test.rb
require 'test_helper'
class ToolboxesControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get toolboxes_index_url
assert_response :success
end
test "should get new" do
get toolboxes_new_url
assert_response :success
end
test "should get edit" do
get toolboxes_edit_url
assert_response :success
end
end
<file_sep>/db/migrate/20180405000230_add_site_to_workers.rb
class AddSiteToWorkers < ActiveRecord::Migration[5.1]
def change
add_reference :workers, :site, foreign_key: true
end
end
<file_sep>/app/models/sjp.rb
class Sjp < ApplicationRecord
belongs_to :worker
belongs_to :site
belongs_to :paperwork
# validates_presence_of :title
validates_presence_of :site_id
validates_presence_of :reviewed
end
<file_sep>/app/controllers/nyws_controller.rb
class NywsController < ApplicationController
def new
@worker = Worker.find(params[:worker_id])
@nyw = @worker.nyws.build
end
def create
@worker = Worker.find(params[:worker_id])
@nyw = @worker.nyws.build(nyw_params)
if @nyw.save
redirect_to @worker, notice: "NYW record created successfully"
else
render :new
end
end
def edit
@nyw = Nyw.find(params[:id])
@worker = Worker.find(params[:worker_id])
end
def destroy
@nyw = Nyw.find(params[:id])
@worker = Worker.find(params[:worker_id])
@nyw.destroy
redirect_to worker_path(@worker), notice: "#{@nyw.id} was deleted successfully!"
end
def update
@nyw = Nyw.find(params[:id])
@worker = Worker.find(params[:worker_id])
if @nyw.update_attributes(nyw_params)
redirect_to worker_path(@worker), notice: "nyw updated successfully"
else
flash[:error] = "#{@nyw.errors.count} errors prevented nyw from being updated."
render :edit
end
end
protected
def nyw_params
params.require(:nyw).permit(:new_young, :show, :reviewed, :complete, :worker_id, :super)
end
end
<file_sep>/app/models/ppe.rb
class Ppe < ApplicationRecord
belongs_to :worker
end
<file_sep>/app/controllers/pdfs_controller.rb
class PdfsController < ApplicationController
before_action :set_pdf, only: [:edit, :update, :destroy]
helper_method :sort_column, :sort_direction
def index
@pdfs = Pdf.all
# @pdfs = @pdfs.order(:name).page(params[:page]).per(15)
@pdfs = @pdfs.order("#{sort_column} #{sort_direction}")
@pdfs = @pdfs.page(params[:page]).per(15)
end
def new
@pdf = Pdf.new
@employer = params[:employer]
end
def create
@pdf = Pdf.new(pdf_params)
if @pdf.save
if params[:pdf][:employer]
redirect_to employer_pdfs_path(params[:pdf][:employer]), notice: "Pdf Created successfully!"
else
redirect_to pdfs_path, notice: "Pdf Created successfully!"
end
else
flash[:error] = @pdf.errors.full_messages.to_sentence
render :new, notice: "Pdf could not be created!"
end
end
def update
if @pdf.update_attributes(pdf_params)
redirect_to pdfs_path, notice: "Updated successfully!"
else
flash[:error] = @pdf.errors.full_messages.to_sentence
render :edit, notice: "Pdf could not be updated!"
end
end
def destroy
@pdf.destroy
redirect_to pdfs_path, notice: "#{@pdf.id} was deleted successfully!"
end
def employers
@employer = Employer.find(params[:employer_id])
@pdfs = Pdf.all
end
def edit
end
private
def sort_column
params[:column] ? params[:column] : "name"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
def set_pdf
@pdf = Pdf.find(params[:id])
end
def pdf_params
params.require(:pdf).permit(:name, :document, :category, {employer_ids: []})
end
end
<file_sep>/db/migrate/20180509005949_add_show_to_nyws.rb
class AddShowToNyws < ActiveRecord::Migration[5.1]
def change
add_column :nyws, :show, :boolean
end
end
<file_sep>/app/controllers/admin/applications_controller.rb
class Admin::ApplicationsController < Admin::BaseAdminController
def new
@job = Job.friendly.find(params[:job_id])
@seeker = Seeker.where(user_id: current_user.id).first
@resumes = Resume.where(seeker_id: 1)
@resumeTest = @resumes.count
@no_resume = params[:no_resume]
if @job.CompUrl
redirect_to @job.CompUrl, notice: "Good luck!, #{current_user.firstName}!"
elsif @seeker && @resumeTest > 0 || @no_resume
@application = @job.applications.build
@application.seeker_id = @seeker.id
@application.save
elsif @seeker && @resumeTest < 1
flash[:alert] = "No RESUME!"
redirect_to no_resume_seeker_path(@seeker, job_id: @job.id)
else
flash[:alert] = "You need to be a Job Hunter to apply for jobs!"
redirect_back(fallback_location: root_path)
# @application = Application.new(job_id: @job.id)
end
end
def index
@applications = Application.all
@applications = @applications.order(:created_at).reverse_order.page(params[:page]).per(15)
end
def job_apps
@job = Job.friendly.find(params[:job_id])
@applications = Application.where(job_id: @job.id)
render "jobs"
end
def create
@job = Job.friendly.find(params[:job_id])
@application = Application.where(job_id: @job.id).first
if @application.save
@seeker = Seeker.where(user_id: current_user.id).first
redirect_to seeker_path(@seeker), notice: "Application Saved, #{current_user.firstName}!"
else
render :new
flash[:error] = @application.errors.full_messages.to_sentence
end
if @application.errors.any?
@application.errors.full_messages.each do |msg|
flash[:error] = msg
end
end
end
def destroy
@application = Application.find(params[:app_id])
@application.destroy
flash[:alert] = "The application was deleted successfully!"
redirect_back(fallback_location: admin_applications_path)
end
def update
@application = Application.find(params[:id])
@seeker = Seeker.where(user_id: current_user.id).first
# @application.resume = params[:resume]
@application.update_attributes(params.require(:application).permit(:resume))
redirect_to seeker_path(@seeker), notice: "Application Updated, #{current_user.firstName}!"
end
end<file_sep>/app/controllers/courses_controller.rb
class CoursesController < ApplicationController
before_action :set_course, only: [:edit, :update, :destroy]
# before_action :re_authenticate, only: [:onsite]
autocomplete :employer, :name
helper_method :sort_column, :sort_direction
def index
@courses = Course.all
# @courses = @courses.order(:date).reverse_order.page(params[:page]).per(15)
if sort_column == "name"
@courses = @courses.joins(:paperwork).order("title #{sort_direction}")
elsif sort_column == "students"
@courses = @courses.joins(:workers).group(:id).order("COUNT(workers) #{sort_direction}")
elsif sort_column == "instructor"
@courses = @courses.joins(:instructor).order("lastname #{sort_direction}")
else
@courses = @courses.order("#{sort_column} #{sort_direction}")
end
@courses = @courses.page(params[:page]).per(15)
end
def new
# @course = params[:course_id] ? Course.find(params[:course_id]) : Course.new
@course = Course.new
end
def create
@course = Course.new(course_params)
logger.info "#{ap @course}"
existing_select = params[:course][:existing_select]
onsite = params[:course][:onsite]
if existing_select == "selected"
existing = params[:course][:existing]
# @course = Course.new(course_params)
current_user.current_course = existing
user = User.find(current_user.id)
user.update(current_course: existing)
redirect_to onsite_admin_users_path, notice: "Course loaded successfully!"
elsif onsite && onsite == "onsite"
if @course.save
logger.info "XXXXXXXXXXXXXXXXXXXXX course save onsite XXXXXXXXXXXXXXXXx"
logger.info "#{ap @course}"
current_user.current_course = Course.last.id
user = User.find(current_user.id)
user.current_course = Course.last.id
user.save
redirect_to onsite_admin_users_path, notice: "Course Created successfully!"
# redirect_to controller: 'admin/users', action: 'onsite', course_id: @course
else
logger.info "XXXXXXXXXXXXXXXXXXXXX not saved onsite looop XXXXXXXXXXXXXXXXx"
logger.info "#{ap @course}"
logger.info "#{@course.errors.full_messages.to_sentence}"
flash[:error] = @course.errors.full_messages.to_sentence
render :new, notice: "Course could not be created!"
end
else
if @course.save
logger.info "XXXXXXXXXXXXXXXXXXXXX course save normal XXXXXXXXXXXXXXXXx"
redirect_to course_path(@course), notice: "Course Created successfully!"
else
logger.info "XXXXXXXXXXXXXXXXXXXXX not saved XXXXXXXXXXXXXXXXx"
logger.info "#{ap @course}"
logger.info "#{@course.errors.full_messages.to_sentence}"
flash[:error] = @course.errors.full_messages.to_sentence
render :new, notice: "Course could not be created!"
end
end
end
def update
existing_select = params[:course][:existing_select]
onsite = params[:course][:onsite]
if existing_select == "selected"
existing = params[:course][:existing]
# @course = Course.new(course_params)
current_user.current_course = existing
user = User.find(current_user.id)
user.update(current_course: existing)
redirect_to onsite_admin_users_path, notice: "Course loaded successfully!"
elsif @course.update_attributes(course_params)
redirect_to courses_path, notice: "Updated successfully!"
else
flash[:error] = @course.errors.full_messages.to_sentence
render :edit, notice: "Course could not be updated!"
end
end
def destroy
@course.destroy
redirect_to courses_path, notice: "#{@course.id} was deleted successfully!"
end
def workers
@employers = Employer.all
@course = Course.find(params[:course_id])
# @workers_all = Worker.all
# if params[:filter_employer]
# @workers_all = Worker.filter(params[:filter_employer])
# else
# @workers_all = Worker.all
# end
if params[:search]
@workers_all = Worker.search(params[:search]).order(:firstname)
else
@workers_all = Worker.filter(params[:filter_employer], params[:filter_site]).order(:firstname)
end
end
def download_pdf
@record = CourseRecord.find(params[:rec_id])
@course = @record.course
work = Worker.find(@record.worker_id)
set_margin = "0"
# html = render_to_string(:action => '../pages/certs', :layout => false)
html = render_to_string(:action => "pdf_cert", :layout => false, locals: {:course_id => @course.id})
pdf = PDFKit.new(html, :page_size => 'B7', :orientation => 'landscape', :margin_top => set_margin+'in', :margin_right => set_margin+'in', :margin_bottom => set_margin+'in', :margin_left => set_margin+'in')
# pdf.stylesheets << "#{Rails.root}/app/assets/stylesheets/pdf-certs.scss"
css = Rails.application.assets ? Rails.application.assets['pdf-certs.css'].pathname : "#{Rails.public_path}/pdf-certs.css"
# css = "#{Rails.public_path}/pdf-certs.css"
pdf.stylesheets << css
send_data pdf.to_pdf, filename: "#{work.firstname}-#{work.lastname}-#{@course.paperwork.title}-#{@course.id}.pdf"
end
def pdf_cert
@course = Course.find(params[:course_id])
@worker = Worker.find(@course.worker_id)
# @workname = @worker.firstname + " " + @worker.lastname
end
def onsite
@course = Course.new
end
def auth
end
def auth_check
password = params[:password]
@course = current_user.current_course
if current_user.valid_password?(password)
redirect_to course_path(@course), notice: "Access Granted!"
else
# render :auth, notice: "Access Denied!"
redirect_to auth_courses_path, notice: "Access Denied!"
end
end
def existing
@email = params[:email] ? params[:email] : nil
end
def existing_check
email = params[:email]
password = params[:password]
@course = Course.find(current_user.current_course)
# @record = CourseRecord.where(course_id: @course.id).where(worker_id: @worker.id).first
user = User.find_by(email: email)
if user.user_type != "Worker"
redirect_to onsite_admin_users_path, notice: "You need to create a worker profile"
elsif user.valid_password?(password)
# redirect_to course_confirm_path(@course), notice: "You're signed up!"
@worker = Worker.find_by(user_id: user.id)
if @worker
# CourseRecord.create(course_id: @course.id, worker_id: @worker.id)
redirect_to new_course_record_path(worker_id: @worker.id)
else
redirect_to onsite_admin_users_path, notice: "You need to create a worker profile"
end
else
# render :auth, notice: "Access Denied!"
redirect_to existing_courses_path, notice: "Your password is incorrect!"
end
end
def confirm
@course = Course.find(current_user.current_course)
# @worker = @course.workers.first
@worker = @course.course_records.last.worker
end
def show
@course = Course.find(params[:id])
end
def pass
CourseRecord.where(id: params[:record_ids]).update_all(pass: true)
if params[:record_ids]
rec = params[:record_ids][0]
@course = CourseRecord.find(rec).course
redirect_to course_path(@course), notice: "Course Marked!"
else
redirect_to courses_path, notice: "Course Marked!"
end
end
def edit
end
private
def set_course
@course = Course.find(params[:id])
end
def current_resource
@current_resource ||= CourseRecord.find(params[:rec_id]) if params[:rec_id]
end
def course_params
params.require(:course).permit(:existing_select, :existing, :onsite, :instructor_id, :paperwork_id, :location, :enrollment, :date, :expiry, :worker_id, :address)
end
def sort_column
params[:column] ? params[:column] : "date"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "desc"
end
end
<file_sep>/app/controllers/admin/employers_controller.rb
class Admin::EmployersController < Admin::BaseAdminController
before_action :set_employer, only: [:show, :edit, :update, :destroy]
helper_method :sort_column, :sort_direction
def index
@employers = Employer.all
# @employers = @employers.order(:updated_at).reverse_order.page(params[:page]).per(15)
if sort_column == "wcbs"
@employers = @employers.joins(:wcbs).group(:id).order("COUNT(wcbs) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "workers"
@employers = @employers.joins(:workers).group(:id).order("COUNT(workers) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "sites"
@employers = @employers.joins(:sites).group(:id).order("COUNT(sites) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "prime"
primes = []
Prime.all.each do |prime|
primes.push(prime.employer_id)
end
@employers = @employers.where(id: primes).order("name #{sort_direction}").page(params[:page]).per(15)
else
@employers = @employers.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
end
# GET /employers/1
def show
end
# GET /employers/new
def new
@employer = Employer.new
end
# GET /employers/1/edit
def edit
end
def site
@site = Site.find_by(id: params[:site_id])
@employers = @site.employers
@employers = @employers.order(:updated_at).reverse_order.page(params[:page]).per(15)
end
# POST /employers
def create
@employer = Employer.new(employer_params)
if @employer.save
redirect_to admin_employers_path, notice: "Employer Created successfully!"
else
flash[:error] = @employer.errors.full_messages.to_sentence
render :new, notice: "Employer could not be created!"
end
end
# PATCH/PUT /employers/1
# PATCH/PUT /employers/1.json
def update
if @employer.update_attributes(employer_params)
redirect_to admin_employers_path, notice: "Employer Updated successfully!"
else
flash[:error] = @employer.errors.full_messages.to_sentence
render :new, notice: "Employer could not be updated!"
end
end
# DELETE /employers/1
# DELETE /employers/1.json
def destroy
@employer.destroy
redirect_to admin_employers_path, notice: "#{@employer.id} was deleted successfully!"
end
private
# Use callbacks to share common setup or constraints between actions.
def set_employer
@employer = Employer.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def employer_params
params.require(:employer).permit(
:name, :street, :city, :postal, :province, :country, :coordinator, :logo
)
end
def current_resource
@current_resource ||= Employer.find(params[:id]) if params[:id]
end
def sort_column
params[:column] ? params[:column] : "updated_at"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end
<file_sep>/app/controllers/certificates_controller.rb
class CertificatesController < ApplicationController
def new
@worker = Worker.find(params[:worker_id])
@certificate = @worker.certificates.build
end
def create
@worker = Worker.find(params[:worker_id])
@certificate = @worker.certificates.build(certificate_params)
if @certificate.save
redirect_to @worker, notice: "Certificate contacts created successfully"
else
render :new
end
end
def edit
@certificate = Certificate.find(params[:id])
@worker = Worker.find(params[:worker_id])
end
def destroy
@certificate = Certificate.find(params[:id])
@worker = Worker.find(params[:worker_id])
@certificate.destroy
redirect_to worker_path(@worker), notice: "#{@certificate.id} was deleted successfully!"
end
def update
@certificate = Certificate.find(params[:id])
@worker = Worker.find(params[:worker_id])
if @certificate.update_attributes(certificate_params)
redirect_to worker_path(@worker), notice: "certificate updated successfully"
else
flash[:error] = "#{@certificate.errors.count} errors prevented certificate from being updated."
render :edit
end
end
protected
def certificate_params
params.require(:certificate).permit(:coursename,:taken,:expiry,:image,:provider,:paperwork_id, :typed_provider, :instructor_id, :wethesafe)
end
end
<file_sep>/app/models/wcb.rb
class Wcb < ApplicationRecord
has_and_belongs_to_many :wcb_sections
belongs_to :site
belongs_to :employer
end
<file_sep>/test/controllers/swps_controller_test.rb
require 'test_helper'
class SwpsControllerTest < ActionDispatch::IntegrationTest
test "should get new" do
get swps_new_url
assert_response :success
end
test "should get edit" do
get swps_edit_url
assert_response :success
end
test "should get destroy" do
get swps_destroy_url
assert_response :success
end
end
<file_sep>/test/controllers/fallpros_controller_test.rb
require 'test_helper'
class FallprosControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get fallpros_index_url
assert_response :success
end
test "should get new" do
get fallpros_new_url
assert_response :success
end
test "should get edit" do
get fallpros_edit_url
assert_response :success
end
test "should get show" do
get fallpros_show_url
assert_response :success
end
end
<file_sep>/db/migrate/20180502010343_create_nyw_forms.rb
class CreateNywForms < ActiveRecord::Migration[5.1]
def change
create_table :nyw_forms do |t|
t.references :nyw, foreign_key: true
t.references :site, foreign_key: true
t.references :paperwork, foreign_key: true
t.date :reviewed
t.timestamps
end
end
end
<file_sep>/app/controllers/roles_controller.rb
class RolesController < ApplicationController
helper_method :sort_column, :sort_direction
def index
@roles = Role.all
if sort_column == "workers"
@roles = @roles.joins(:workers).group(:id).order("COUNT(workers) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "sjps"
@roles = @roles.joins(:paperworks).where("paperworks.category = ?", "SJP").group(:id).order("COUNT(paperworks) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "swps"
@roles = @roles.joins(:paperworks).where("paperworks.category = ?", "SWP").group(:id).order("COUNT(paperworks) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "certificates"
@roles = @roles.joins(:paperworks).where("paperworks.category = ?", "Certificate").group(:id).order("COUNT(paperworks) #{sort_direction}").page(params[:page]).per(15)
else
@roles = @roles.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
end
def show
@role = Role.find(params[:id])
end
def new
@role = Role.new
end
def create
@role = Role.new(role_params)
if @role.save
redirect_to roles_path, notice: "roles Submitted successfully!"
else
flash[:error] = @role.errors.full_messages.to_sentence
render :new, notice: "role could not be created!"
end
end
def edit
@role = Role.find(params[:id])
end
def update
@role = Role.find(params[:id])
if @role.update_attributes(role_params)
redirect_to roles_path, notice: "role updated successfully"
else
flash[:error] = "#{@role.errors.count} errors prevented certificate from being updated."
render :edit
end
end
def destroy
@role = Role.find(params[:id])
@role.destroy
redirect_to roles_path, notice: "#{@role.id} was deleted successfully!"
end
protected
def role_params
params.require(:role).permit(:id, :title, {paperwork_ids: []})
end
def sort_column
params[:column] ? params[:column] : "updated_at"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end
<file_sep>/app/models/fallpro.rb
class Fallpro < ApplicationRecord
belongs_to :user
end
<file_sep>/app/models/pdf.rb
class Pdf < ApplicationRecord
has_and_belongs_to_many :employers
mount_uploader :document, CertUploader
validates_presence_of :name
validates_presence_of :document
validates_presence_of :category
def self.search(search)
where('name ILIKE :search OR category ILIKE :search', search: "%#{search}%")
end
end
<file_sep>/app/controllers/admin/users_controller.rb
class Admin::UsersController < Admin::BaseAdminController
helper_method :sort_column, :sort_direction
def index
@users = User.all
# @users = @users.order(:updated_at).reverse_order.page(params[:page]).per(15)
@users = @users.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
def new
@user = User.new
@employers = Employer.all
@primes = Prime.all
end
def onsite
@user = User.new
@noEmp = Employer.find_by(name: "No Employer").id
@course = current_user.current_course
end
def edit
@user = User.find(params[:id])
@employers = Employer.all
@primes = Prime.all
end
def create
@user = User.new(user_params)
@employers = Employer.all
@primes = Prime.all
if @user.user_type == "Prime Contractor"
prime = Prime.find_by(employer_id: @user.employer_id)
@user.prime_id = prime.id if prime
end
@user.email = @user.email.downcase.presence
onsite = @user.onsite
no_email = @user.no_email ? @user.no_email : params[:user][:no_email]
course_id = @user.course_id
employer_id = @user.employer_id
if User.exists?(:email => @user.email)
logger.info "XXXXXX User Exists XXXXXXXXXXXXX"
redirect_to existing_courses_path(email: @user.email)
elsif employer_id == nil
logger.info "XXXXXX No Employer XXXXXXXXXXXXX"
# flash[:error] = "Somthing went wrong"
redirect_to onsite_admin_users_path, notice: "You must select an employer from the list or No Employer button."
elsif no_email == "true"
logger.info "XXXXXX No EMAIL Sept 17 XXXXXXXXXXXXX"
logger.info "XXXXXX no_email ---> #{no_email}"
redirect_to onsite_admin_workers_path(course_id: course_id, user_id: current_user.id, employer_id: employer_id), notice: "User creation skipped!"
elsif @user.save && onsite
logger.info "XXXXXX Onsite SAVE XXXXXXXXXXXXX"
# redirect_to admin_root_path, notice: "Onsite! Onsite!"
redirect_to onsite_admin_workers_path(course_id: course_id, user_id: User.last.id, employer_id: employer_id), notice: "User Created successfully!"
elsif @user.save
logger.info "XXXXXX Normal SAVE XXXXXXXXXXXXX"
redirect_to admin_users_path, notice: "User Created successfully!"
elsif onsite
logger.info "XXXXXX Onsite render errors XXXXXXXXXXXXX"
logger.info "XXXXXX No EMAIL ==> #{no_email} XXXXXXXXXXXXX"
flash[:error] = @user.errors.full_messages.to_sentence
render :onsite, notice: "User could not be created!"
# redirect_to :action => "onsite", :course_id=> course_id , notice: "User could not be created!"
else
logger.info "XXXXXX Normal render errors XXXXXXXXXXXXX"
flash[:error] = @user.errors.full_messages.to_sentence
render :new, notice: "User could not be created!"
logger.info "XXXXXX #{@user.errors.full_messages.to_sentence}"
end
end
def update
@user = User.find(params[:id])
@employers = Employer.all
@primes = Prime.all
if @user.user_type == "Prime Contractor"
prime = Prime.find_by(employer_id: @user.employer_id)
@user.prime_id = prime.id if prime
end
@user.email = @user.email.downcase.presence
if params[:user][:password].blank?
params[:user].delete(:password)
params[:user].delete(:password_confirmation)
end
if @user.update_attributes(user_params)
redirect_to admin_users_path, notice: "Updated successfully!"
else
# flash[:error] = @user.errors.full_messages.to_sentence
render :new, notice: "User could not be created! #{@user.errors.full_messages.to_sentence}"
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
redirect_to admin_users_path, notice: "#{@user.id} was deleted successfully!"
end
protected
def user_params
params.require(:user).permit(:employer, :course_id, :onsite, :no_email, :email, :password, :password_confirmation, :user_type, :employer_id, :prime_id)
end
def sort_column
params[:column] ? params[:column] : "updated_at"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end<file_sep>/app/controllers/toolboxes_controller.rb
class ToolboxesController < ApplicationController
before_action :set_toolbox, only: [:edit, :update, :show, :destroy]
def index
@employer = Employer.find(params[:employer_id])
@toolboxes = @employer.toolboxes
@toolboxes = @toolboxes.order(:date).reverse_order.page(params[:page]).per(15)
end
def new
@employer = Employer.find(params[:employer_id])
@workers = @employer.workers
@toolbox = @employer.toolboxes.build
# 1.times {@toolbox.extra_topics.build}
@workers_all = Worker
.where(employer_id: @employer.id)
.order(:lastname, :firstname)
if params[:search]
@workers_all = @workers_all.search(params[:search]).order(:firstname)
end
end
def show
@employer = Employer.find(params[:employer_id])
end
def create
@employer = Employer.find(params[:employer_id])
workers = params[:toolbox][:worker_ids]
workers_split = workers.split(",")
@toolbox = @employer.toolboxes.build(toolbox_params)
if @toolbox.save
redirect_to employer_toolboxes_path(@employer), notice: "Toolbox Created successfully!"
else
logger.info @toolbox.errors.full_messages.to_sentence
@workers = @employer.workers
@workers_all = Worker
.where(employer_id: @employer.id)
.order(:lastname, :firstname)
render :new, notice: "Toolbox could not be created!"
end
end
def update
@employer = Employer.find(params[:employer_id])
if @toolbox.update_attributes(toolbox_params)
redirect_to employer_toolboxes_path(@employer), notice: "Updated successfully!"
else
logger.info @toolbox.errors.full_messages.to_sentence
redirect_to edit_employer_toolbox_path(@employer, @toolbox), notice: "Toolbox could not be updated! #{@toolbox.errors.full_messages.to_sentence}"
end
end
def destroy
@employer = Employer.find(params[:employer_id])
@toolbox.destroy
redirect_to employer_toolboxes_path(@employer), notice: "#{@toolbox.id} was deleted successfully!"
end
def add_workers
@employer = Employer.find(params[:employer_id])
@workers_all = Worker
.where(employer_id: @employer.id)
.order(:lastname, :firstname)
if params[:search]
@workers_all = @workers_all.search(params[:search]).order(:lastname, :firstname)
end
end
def worker_data
respond_to do |format|
format.json {
workers = params[:worker_ids]
render json: {work: workers}
}
end
end
def edit
@employer = Employer.find(params[:employer_id])
@tool_workers = @toolbox.workers
@workers = @employer.workers
@workers_all = Worker
.where(employer_id: @employer.id)
.where(employer_id: @employer.id)
.order(:lastname, :firstname)
@workers_all = @workers_all - @tool_workers
if params[:search]
@workers_all = @workers_all.search(params[:search]).order(:firstname)
end
end
private
def set_toolbox
@toolbox = Toolbox.find(params[:id])
end
def toolbox_params
params.require(:toolbox).permit(:id, :employer_id, :site_id, :date, :comments, :attachment, {worker_ids: []}, {paperwork_ids: []}, extra_topics_attributes: [:id, :title, :_destroy])
end
end
<file_sep>/app/controllers/wcbs_controller.rb
class WcbsController < ApplicationController
helper_method :sort_column, :sort_direction
def new
@employer = Employer.find(params[:employer_id])
@wcb = @employer.wcbs.build
end
def create
@employer = Employer.find(params[:employer_id])
# @sites = Site.all
@wcb = @employer.wcbs.build(wcb_params)
if @wcb.save && current_user && current_user.user_type == "Admin"
redirect_to wcbs_path, notice: "#{@wcb.id} was deleted successfully!"
elsif @wcb.save
redirect_to @employer, notice: "Wcb order created successfully"
else
render :new
end
end
def edit
@wcb = Wcb.find(params[:id])
@sites = Site.all
@employer = Employer.find(params[:employer_id])
end
def index
@wcbs = Wcb.all
# @wcbs = @wcbs.order(:updated_at).reverse_order.page(params[:page]).per(15)
if sort_column == "section"
@wcbs = @wcbs.joins(:wcb_sections).order("number #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "site"
@wcbs = @wcbs.joins(:site).order("name #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "employer"
@wcbs = @wcbs.joins(:employer).order("name #{sort_direction}").page(params[:page]).per(15)
else
@wcbs = @wcbs.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
end
def destroy
@wcb = Wcb.find(params[:id])
@wcb.destroy
if current_user && current_user.user_type == "Admin"
redirect_to wcbs_path, notice: "#{@wcb.id} was deleted successfully!"
else
redirect_back(fallback_location: root_path)
end
end
def update
@wcb = Wcb.find(params[:id])
@employer = Employer.find(params[:employer_id])
if @wcb.update_attributes(wcb_params) && current_user && current_user.user_type == "Admin"
redirect_to wcbs_path, notice: "#{@wcb.id} was deleted successfully!"
elsif @wcb.update_attributes(wcb_params)
flash[:error] = "#{@wcb.errors.count} errors prevented wcb from being updated."
render :edit
end
end
protected
def wcb_params
params.require(:wcb).permit(:site_id, :employer_id, :section, :subsection, :date, :wcb_section_ids)
end
def sort_column
params[:column] ? params[:column] : "updated_at"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end
<file_sep>/db/migrate/20180602161431_remove_addy_from_prime.rb
class RemoveAddyFromPrime < ActiveRecord::Migration[5.1]
def change
remove_column :primes, :city, :string
remove_column :primes, :name, :string
remove_column :primes, :street, :string
remove_column :primes, :postal, :string
remove_column :primes, :country, :string
remove_column :primes, :province, :string
remove_column :primes, :phone, :string
remove_column :primes, :logo, :string
add_column :primes, :employer_id, :integer
end
end
<file_sep>/db/migrate/20180419204330_add_paperwork_to_sjps.rb
class AddPaperworkToSjps < ActiveRecord::Migration[5.1]
def change
add_reference :sjps, :paperwork, foreign_key: true
end
end
<file_sep>/app/controllers/primes_controller.rb
class PrimesController < ApplicationController
before_action :set_prime, only: [:show, :edit, :update, :destroy]
helper_method :sort_column, :sort_direction
# GET /primes
# GET /primes.json
def index
@primes = Prime.all
end
# GET /primes/1
# GET /primes/1.json
def show
@prime = Prime.find(params[:id])
@emp = Employer.find_by(id: @prime.employer_id)
# @workers = Worker.where(prime_id: @prime.id)
@sites = Site.where(prime_id: @prime.id)
# @work_violations = Worker.where(prime_id: @prime.id).joins(:violations).group('workers.id').having('count(violations) > 1')
end
# GET /primes/new
def new
@prime = Prime.new
end
# GET /primes/1/edit
def edit
end
def my_workers
@prime = Prime.find(params[:prime_id])
@workers = @prime.workers
# @workers = @workers.order(:site_id).reverse_order.page(params[:page]).per(25)
if sort_column == "role"
@workers = @workers.joins(:role).order("title #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "employer"
@workers = @workers.joins(:employer).order("employers.name #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "site"
@workers = @workers.joins(:site).order("sites.name #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "certificates"
@workers = @workers.joins(:certificates).group(:id).order("COUNT(certificates) #{sort_direction}").page(params[:page]).per(15)
else
@workers = @workers.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
end
def my_employers
@prime = Prime.find(params[:prime_id])
@employers = @prime.employers.distinct
@employers = @employers.page(params[:page]).per(25)
# @employers = @employers.paginate(:page => params[:page], :per_page => 25)
# Kaminari.paginate_array(@employers).page(params[:page]).per(1)
end
def my_sites
@prime = Prime.find(params[:prime_id])
@sites = @prime.sites
# @sites = @sites.order(:created_at).reverse_order.page(params[:page]).per(10)
if sort_column == "employers"
@sites = @sites.joins(:employers).group(:id).order("COUNT(employers) #{sort_direction}").order("name #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "workers"
@sites = @sites.joins(:workers).group(:id).order("COUNT(workers) #{sort_direction}").page(params[:page]).per(15)
else
@sites = @sites.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
end
def my_sites_workers
@prime = Prime.find(params[:prime_id])
@site = Site.find(params[:site_id])
@workers = Worker.where(site_id: @site.id)
# @workers = @workers.order(:site_id).reverse_order.page(params[:page]).per(25)
if sort_column == "role"
@workers = @workers.joins(:role).order("title #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "employer"
@workers = @workers.joins(:employer).order("employers.name #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "site"
@workers = @workers.joins(:site).order("sites.name #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "certificates"
@workers = @workers.joins(:certificates).group(:id).order("COUNT(certificates) #{sort_direction}").page(params[:page]).per(15)
else
@workers = @workers.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
@workers_all = Worker.where(prime_id: @prime.id)
@workers_all = Worker.where.not(site_id: @site.id)
@workers_all = @workers_all.order(:lastname, :firstname)
end
def create
@prime = Prime.new(prime_params)
respond_to do |format|
if @prime.save
format.html { redirect_to @prime, notice: 'Prime was successfully created.' }
format.json { render :show, status: :created, location: @prime }
else
format.html { render :new }
format.json { render json: @prime.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @prime.update(prime_params)
format.html { redirect_to @prime, notice: 'Prime was successfully updated.' }
format.json { render :show, status: :ok, location: @prime }
else
format.html { render :edit }
format.json { render json: @prime.errors, status: :unprocessable_entity }
end
end
end
# DELETE /primes/1
# DELETE /primes/1.json
def destroy
@prime.destroy
respond_to do |format|
format.html { redirect_to primes_url, notice: 'Prime was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_prime
@prime = Prime.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def prime_params
params.require(:prime).permit(
:employer_id
)
end
def current_resource
if params[:id]
@current_resource ||= Prime.find(params[:id])
elsif params[:prime_id]
@current_resource ||= Prime.find(params[:prime_id])
end
end
def sort_column
params[:column] ? params[:column] : "updated_at"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end
<file_sep>/app/controllers/employers_controller.rb
class EmployersController < ApplicationController
before_action :set_employer, only: [:show, :edit, :update, :destroy]
helper_method :sort_column, :sort_direction
# GET /employers
# GET /employers.json
def index
@employers = Employer.all
end
# GET /employers/1
# GET /employers/1.json
def show
@employer = Employer.find(params[:id])
@workers = Worker.where(employer_id: @employer.id)
# @sites = Site.where(employer_id: @employer.id)
@sites = @employer.sites
@work_violations = Worker.where(employer_id: @employer.id).joins(:violations).group('workers.id').having('count(violations) > 1')
@donut_workers = @workers.joins(:site).group(:name).count.to_a
end
# GET /employers/new
def new
@employer = Employer.new
end
# GET /employers/1/edit
def edit
end
def my_workers
@employer = Employer.find(params[:employer_id])
@workers = Worker.where(employer_id: @employer.id)
# @workers = @workers.order(:created_at).reverse_order.page(params[:page]).per(25)
if sort_column == "site"
@workers = @workers.joins(:site).order("sites.name #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "role"
@workers = @workers.joins(:role).order("title #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "nyws"
@workers = @workers.joins(:nyws).order("nyws #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "certificates"
@workers = @workers.joins(:certificates).group(:id).order("COUNT(certificates) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "orientations"
@workers = @workers.joins(:orientations).group(:id).order("COUNT(orientations) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "sjps"
@workers = @workers.joins(:sjps).group(:id).order("COUNT(sjps) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "swps"
@workers = @workers.joins(:swps).group(:id).order("COUNT(swps) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "violations"
@workers = @workers.joins(:violations).group(:id).order("COUNT(violations) #{sort_direction}").page(params[:page]).per(15)
else
@workers = @workers.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
end
def my_sites
@employer = Employer.find(params[:employer_id])
# @sites = Site.where(employer_id: @employer.id)
@sites = @employer.sites
# @sites = @sites.order(:created_at).reverse_order.page(params[:page]).per(10)
if sort_column == "workers"
@sites = @sites.joins(:workers).group(:id).order("COUNT(workers) #{sort_direction}")
else
@sites = @sites.order("#{sort_column} #{sort_direction}")
end
@sites = @sites.page(params[:page]).per(15)
end
def violations
@employer = Employer.find(params[:employer_id])
@sites = @employer.sites
work_sites = @sites.ids
if params[:filter]
filter = params[:filter]
site = Site.find_by(name: filter)
@violations = Violation.where(site_id: site)
else
@violations = Violation.where(site_id: @sites)
end
@violations = @violations.order(:date).reverse_order.page(params[:page]).per(10)
@viol_data = []
@sites.each do |site|
viols = Violation.where(site_id: site).count
if viols > 0
@viol_data.push([site.name, viols])
else
@viol_data.push([site.name, 0])
end
end
# @violations = Violation.joins(:site).where(sites: {employer_id: @employer.id}).order('violations.date DESC').page(params[:page]).per(10)
# @violations = Violation.joins(:worker).where(workers: {employer_id: @employer.id}).order('violations.date DESC').page(params[:page]).per(10)
end
def add_workers
@employer = Employer.find(params[:employer_id])
@site = Site.find(params[:site_id])
@workers_all = Worker
.where(employer_id: @employer.id)
.where.not(site_id: @site.id)
.order(:lastname, :firstname)
if params[:search]
@workers_all = @workers_all.search(params[:search]).order(:firstname)
end
end
def my_sites_workers
@employer = Employer.find(params[:employer_id])
@site = Site.find(params[:site_id])
@workers = Worker.where(site_id: @site.id).where(employer_id: @employer.id).order(:lastname, :firstname)
# @workers = @workers.order(:created_at).reverse_order.page(params[:page]).per(10)
@workers = @site.workers.where(employer_id: @employer.id).order(:lastname, :firstname)
if params[:search]
@workers = @workers.search(params[:search]).order(:firstname)
else
@workers
end
if sort_column == "site"
@workers = @workers.joins(:site).order("sites.name #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "role"
@workers = @workers.joins(:role).order("title #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "nyws"
@workers = @workers.joins(:nyws).order("nyws #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "certificates"
@workers = @workers.joins(:certificates).group(:id).order("COUNT(certificates) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "orientations"
@workers = @workers.joins(:orientations).group(:id).order("COUNT(orientations) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "sjps"
@workers = @workers.joins(:sjps).group(:id).order("COUNT(sjps) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "swps"
@workers = @workers.joins(:swps).group(:id).order("COUNT(swps) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "violations"
@workers = @workers.joins(:violations).group(:id).order("COUNT(violations) #{sort_direction}").page(params[:page]).per(15)
else
@workers = @workers.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
end
def my_wcbs
@employer = Employer.find(params[:employer_id])
@wcbs = @employer.wcbs
@wcbs = @wcbs.order(:created_at).reverse_order.page(params[:page]).per(10)
end
def my_sjps
@employer = Employer.find(params[:employer_id])
@sites = Site.where(employer_id: @employer.id)
@sites = @sites.order(:created_at).reverse_order.page(params[:page]).per(10)
end
def my_certs
@employer = Employer.find(params[:employer_id])
# @sites = Site.where(employer_id: @employer.id)
@sites = @employer.sites
@sites = @sites.order(:created_at).reverse_order.page(params[:page]).per(10)
end
def cert_report
@employer = Employer.find(params[:employer_id])
@workers = Worker.joins(:site).where(employer_id: @employer.id).order("sites.name ASC, lastname ASC")
@logo = "#{Rails.public_path}/assets/logo-compressor.png"
if params[:role]
@role = params[:role]
role_query = Role.find_by(title: @role)
@workers = @workers.where(role_id: role_query.id)
elsif params[:site]
@site = Site.find(params[:site])
@workers = @workers.where(site_id: @site.id)
end
@certs_exp30 = []
@types = []
@workers_exp = []
@workers.each do |work|
work.certificates.each do |cert|
if cert.expiry && cert.expiry < 30.days.from_now
@certs_exp30.push(cert)
@types.push(cert.paperwork.title) unless @types.include?(cert.paperwork.title)
@workers_exp.push(work) unless @workers_exp.include?(work)
end
end
end
end
def print_cert_report
@employer = Employer.find(params[:employer_id])
@workers = Worker.joins(:site).where(employer_id: @employer.id).order("sites.name ASC, lastname ASC")
@logo = "http://qrsafety.com/public/assets/qrsafetylogo.png"
@certs_exp30 = []
@types = []
@workers_exp = []
@workers.each do |work|
work.certificates.each do |cert|
if cert.expiry && cert.expiry < 30.days.from_now
@certs_exp30.push(cert)
@types.push(cert.paperwork.title) unless @types.include?(cert.paperwork.title)
@workers_exp.push(work) unless @workers_exp.include?(work)
end
end
end
html = render_to_string(:action => "cert_report", :layout => false, :locals => {:@workers_exp => @workers_exp, :@employer => @employer, :@workers => @workers, :@certs_exp30 => @certs_exp30, :@logo => @logo })
# css = "#{Rails.public_path}/assets/application.css"
css = "#{Rails.public_path}/assets/pdf_application.css"
pdf = PDFKit.new(html, :page_size => 'Letter')
pdf.stylesheets << css
# pdf.stylesheets << view_context.asset_path 'application.css'
send_data pdf.to_pdf, filename: "#{Date.today}-#{@employer.name}-crews.pdf"
end
def worksafe
@employer = Employer.find(params[:employer_id])
@wcb_data = []
Site.where(employer_id: @employer.id).each do |site|
wcbs = Wcb.where(site_id: site.id).joins(:site).count
if wcbs > 0
@wcb_data.push([site.name, wcbs])
else
@wcb_data.push([site.name, 0])
end
end
end
def certificates
@employer = Employer.find(params[:employer_id])
@certs_exp = Hash.new(0)
@sjps_crit = Hash.new(0)
@sjps_crit_total = Hash.new(0)
@certs_comp_site = Hash.new(0)
@certs_total_site = Hash.new(0)
@employer.workers.each do |work|
work_exp = 0
role_certs = work.role.paperworks.where(category: "Certificate").ids
role_crit_sjps = work.role.paperworks.where(category: "SJP").where(critical: true).ids
work_sjps = []
work.sjps.each do |s|
work_sjps.push(s.paperwork_id)
end
crit_sjps_incomplete = role_crit_sjps - work_sjps
crit_sjps_complete = role_crit_sjps.count - crit_sjps_incomplete.count
certs_complete = []
work.certificates.each do |cert|
certs_complete.push(cert.paperwork_id)
if role_certs.include? cert.paperwork_id
if cert.expiry && cert.expiry < 30.days.from_now
work_exp += 1
else
logger.info "################## #{cert.provider}, #{cert.expiry} ##############################"
end
end
end
certs_inc = role_certs - certs_complete
certs_comp = role_certs.count - certs_inc.count
if work.site
work_site_name = work.site.name
else
work_site_name = "N/A"
end
@certs_comp_site[work_site_name] += certs_comp
@certs_total_site[work_site_name] += role_certs.count
@certs_exp[work.role.title] += 1 if work_exp >= 1
@sjps_crit[work_site_name] += crit_sjps_complete
@sjps_crit_total[work_site_name] += role_crit_sjps.count
end
@certs_exp_total = @certs_exp.inject(0) { |sum, tuple| sum += tuple[1] }
@sjps_percent = @sjps_crit_total.merge(@sjps_crit) {|k, old_v, new_v| new_v == 0 ? 100 : ((new_v.to_f / old_v.to_f) * 100).round(2) }
@sjps_percent = @sjps_percent.select { |k,v| k.in?(@employer.sites.pluck(:name))}
@certs_sites_complete = @certs_total_site.merge(@certs_comp_site) {|k, old_v, new_v| new_v == 0 ? 100 : ((new_v.to_f / old_v.to_f) * 100).round(2) }
@certs_sites_complete = @certs_sites_complete.select { |k,v| k.in?(@employer.sites.pluck(:name))}
end
def workers
@employer = Employer.find(params[:employer_id])
@workers = Worker.where(employer_id: @employer.id)
@sites = Site.where(employer_id: @employer.id)
@work_violations = Worker.where(employer_id: @employer.id).joins(:violations).group('workers.id').having('count(violations) > 1')
@donut_workers = @workers.joins(:site).group(:name).count.to_a
@new_young = Worker.where(employer_id: @employer.id).joins(:nyws).having('count(nyws) > 0').count
@viol_data = []
Site.where(employer_id: @employer.id).each do |site|
viols = Worker.where(site_id: site.id).joins(:site).joins(:violations).count
if viols > 0
@viol_data.push([site.name, viols])
else
@viol_data.push([site.name, 0])
end
end
end
def create
@employer = Employer.new(employer_params)
respond_to do |format|
if @employer.save
format.html { redirect_to @employer, notice: 'Employer was successfully created.' }
format.json { render :show, status: :created, location: @employer }
else
format.html { render :new }
format.json { render json: @employer.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @employer.update(employer_params)
format.html { redirect_to @employer, notice: 'Employer was successfully updated.' }
format.json { render :show, status: :ok, location: @employer }
else
format.html { render :edit }
format.json { render json: @employer.errors, status: :unprocessable_entity }
end
end
end
# DELETE /employers/1
# DELETE /employers/1.json
def destroy
@employer.destroy
respond_to do |format|
format.html { redirect_to employers_url, notice: 'Employer was successfully destroyed.' }
format.json { head :no_content }
end
end
def pdfs
@employer = Employer.find(params[:employer_id])
if params[:search]
@pdfs =@employer.pdfs.search(params[:search]).order(:name)
else
@pdfs = @employer.pdfs.order("#{pdf_sort_column} #{sort_direction}")
end
first = @pdfs.where(category: 'OHS')
rest = @pdfs.where.not(category: 'OHS')
@pdfs = first + rest
@toggleCat = @pdfs.count < 10 ? "test" : "toggle-cat"
end
def chart_link
respond_to do |format|
# format.html {
# render :show ????this seems unnecessary. Can it be eliminated???
# }
format.json {
@employer = Employer.find(params[:employer_id])
name = params[:name]
site_id = Site.find_by(name: name)
location = employer_my_sites_workers_path(@employer, site_id: site_id)
logger.info location
# render :js => "window.location = '#{location}'"
render json: {link: location}
}
end
end
def certs_chart_link
respond_to do |format|
# format.html {
# render :show ????this seems unnecessary. Can it be eliminated???
# }
format.json {
@employer = Employer.find(params[:employer_id])
# name = params[:name]
# site_id = Site.find_by(name: name)
role = params[:role]
location = employer_cert_report_path(@employer, role: role)
# logger.info location
# # render :js => "window.location = '#{location}'"
render json: {link: location}
}
end
end
def viol_chart_link
respond_to do |format|
# format.html {
# render :show ????this seems unnecessary. Can it be eliminated???
# }
format.json {
@employer = Employer.find(params[:employer_id])
# name = params[:name]
# site_id = Site.find_by(name: name)
filter = params[:filter]
location = employer_violations_path(@employer, filter: filter)
# logger.info location
# # render :js => "window.location = '#{location}'"
render json: {link: location}
}
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_employer
@employer = Employer.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def employer_params
params.require(:employer).permit(
:name, :street, :city, :postal, :province, :country, :coordinator, :logo, :cor_cert, :cor_int, :cor_ext, {pdf_ids: []}
)
end
def current_resource
if params[:id]
@current_resource ||= Employer.find(params[:id])
elsif params[:employer_id]
@current_resource ||= Employer.find(params[:employer_id])
end
end
def sort_column
params[:column] ? params[:column] : "updated_at"
end
def pdf_sort_column
params[:column] ? params[:column] : "name"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end
<file_sep>/db/migrate/20180612221345_add_instructor_to_certifiates.rb
class AddInstructorToCertifiates < ActiveRecord::Migration[5.1]
def change
add_reference :certificates, :instructor, foreign_key: true
end
end
<file_sep>/app/models/site.rb
class Site < ApplicationRecord
# belongs_to :employer
has_and_belongs_to_many :employers
belongs_to :prime
has_many :orientations, dependent: :destroy
has_many :sjps, dependent: :destroy
has_many :swps, dependent: :destroy
has_many :violations, dependent: :destroy
has_many :workers, dependent: :destroy
has_many :forms, dependent: :destroy
has_many :nyw_forms, dependent: :destroy
has_many :wcbs, dependent: :destroy
validates_presence_of :name
end
<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
def print_image(url)
# url = Rails.application.assets.find_asset(url).nil? ? nil : url
# image_tag url || 'closeIcon.png'
if url && url.length > 0
image_tag url
else
image_tag 'closeIcon.png'
end
end
def sort_link(column, title = nil, site = nil)
title ||= column.titleize
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
logger.info "############# #{sort_column} #########################"
icon = sort_direction == "asc" ? "glyphicon glyphicon-chevron-up" : "glyphicon glyphicon-chevron-down"
icon = column == sort_column ? icon : ""
if site
link_to "#{title} <span class='#{icon}'></span>".html_safe, {column: column, direction: direction, site_id: site}
else
link_to "#{title} <span class='#{icon}'></span>".html_safe, {column: column, direction: direction}
end
end
def current_course
if current_user.current_course
return Course.find_by(id: current_user.current_course).id
else
return nil
end
end
# def bootstrap_class_for flash_type
# case flash_type
# when :success
# "alert-success"
# when :error
# "alert-error"
# when :alert
# "alert-block"
# when :notice
# "alert-info"
# else
# flash_type.to_s
# end
# end
end
<file_sep>/app/models/employer.rb
class Employer < ApplicationRecord
has_many :workers
has_many :instructors
has_many :toolboxes
has_and_belongs_to_many :sites
has_many :wcbs, dependent: :destroy
has_and_belongs_to_many :pdfs
mount_uploader :logo, ImageUploader
validates_presence_of :name
# validates_presence_of :street
# validates_presence_of :city
# validates_presence_of :province
# validates_presence_of :postal
# validates_presence_of :country
# validates_presence_of :coordinator
end
<file_sep>/app/controllers/orientations_controller.rb
class OrientationsController < ApplicationController
def new
@worker = Worker.find(params[:worker_id])
@orientation = @worker.orientations.build
emp = @worker.employer
@sites = emp.sites
end
def create
@worker = Worker.find(params[:worker_id])
emp = @worker.employer
@sites = emp.sites
@orientation = @worker.orientations.build(orientation_params)
if @orientation.save
redirect_to @worker, notice: "Orientation contacts created successfully"
else
render :new
end
end
def edit
@orientation = Orientation.find(params[:id])
@worker = Worker.find(params[:worker_id])
emp = @worker.employer
@sites = emp.sites
end
def destroy
@orientation = Orientation.find(params[:id])
@worker = Worker.find(params[:worker_id])
@orientation.destroy
redirect_to worker_path(@worker), notice: "#{@orientation.name} was deleted successfully!"
end
def update
@orientation = Orientation.find(params[:id])
@worker = Worker.find(params[:worker_id])
if @orientation.update_attributes(orientation_params)
redirect_to worker_path(@worker), notice: "orientation updated successfully"
else
flash[:error] = "#{@orientation.errors.count} errors prevented orientation from being updated."
render :edit
end
end
protected
def orientation_params
params.require(:orientation).permit(:site_id,:date)
end
end
<file_sep>/app/models/nyw_form.rb
class NywForm < ApplicationRecord
belongs_to :nyw
belongs_to :site
belongs_to :paperwork
validates_presence_of :reviewed
end
<file_sep>/app/models/role.rb
class Role < ApplicationRecord
has_and_belongs_to_many :paperworks
has_many :workers
end
<file_sep>/db/migrate/20180419052535_fix_type_in_paperworks.rb
class FixTypeInPaperworks < ActiveRecord::Migration[5.1]
def change
rename_column :paperworks, :type, :category
end
end
<file_sep>/app/controllers/emergencies_controller.rb
class EmergenciesController < ApplicationController
def new
@worker = Worker.find(params[:worker_id])
@emergency = @worker.emergencies.build
end
def create
@worker = Worker.find(params[:worker_id])
@emergency = @worker.emergencies.build(emergency_params)
if @emergency.save
redirect_to @worker, notice: "Emergency contacts created successfully"
else
render :new
end
end
def edit
@emergency = Emergency.find(params[:id])
@worker = Worker.find(params[:worker_id])
end
def destroy
@emergency = Emergency.find(params[:id])
@worker = Worker.find(params[:worker_id])
@emergency.destroy
redirect_to worker_path(@worker), notice: "#{@emergency.name} was deleted successfully!"
end
def update
@emergency = Emergency.find(params[:id])
@worker = Worker.find(params[:worker_id])
if @emergency.update_attributes(emergency_params)
redirect_to worker_path(@worker), notice: "emergency updated successfully"
else
flash[:error] = "#{@emergency.errors.count} errors prevented emergency from being updated."
render :edit
end
end
protected
def emergency_params
params.require(:emergency).permit(:name,:phone,:relationship)
end
def current_resource
@current_resource ||= Emergency.find(params[:id]) if params[:id]
end
end<file_sep>/app/models/paperwork.rb
class Paperwork < ApplicationRecord
has_and_belongs_to_many :roles
has_and_belongs_to_many :toolboxes
has_many :sjps
has_many :swps
has_many :certificates
has_many :forms
has_many :nyw_forms
has_many :courses
end
<file_sep>/app/controllers/admin/workers_controller.rb
class Admin::WorkersController < Admin::BaseAdminController
before_action :set_worker, only: [:show, :edit, :update, :destroy]
helper_method :sort_column, :sort_direction
def index
if params[:search]
@workers = Worker.search(params[:search]).order(:firstname)
else
@workers = Worker.all
end
if sort_column == "role"
@workers = @workers.joins(:role).order("title #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "nyws"
@workers = @workers.joins(:nyws).order("nyws #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "employer"
@workers = @workers.joins(:employer).order("name #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "user"
@workers = @workers.joins(:user).order("email #{sort_direction}").page(params[:page]).per(15)
else
@workers = @workers.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
@workers_all = Worker.all.order(:firstname)
end
def site
@workers = Worker.where(site_id: params[:site_id])
@site = Site.find_by(id: params[:site_id])
@workers = @workers.order(:updated_at).reverse_order.page(params[:page]).per(15)
end
def onsite
@worker = params[:worker_id] ? Worker.find(params[:worker_id]) : Worker.new
@user_id = params[:user_id]
@course = current_user.current_course
@employer_id = params[:employer_id]
end
# GET /workers/1
def show
end
# GET /workers/new
def new
@worker = Worker.new
end
# GET /workers/1/edit
def edit
end
# POST /workers
def create
@worker = Worker.new(worker_params)
onsite = @worker.onsite
if @worker.save && onsite
@course = Course.find(current_user.current_course)
# @course.worker_id = Worker.last.id
# @course.save
# @course.update(worker_id: Worker.last.id)
redirect_to new_course_record_path(worker_id: Worker.last.id), notice: "Onsite Worker Created successfully!"
# redirect_to course_confirm_path(course_id: @course.id), notice: "Onsite User Created successfully!"
elsif @worker.save
redirect_to admin_workers_path, notice: "Worker Created successfully!"
elsif onsite
flash[:error] = @worker.errors.full_messages.to_sentence
render :onsite, notice: "Worker could not be created!"
else
flash[:error] = @worker.errors.full_messages.to_sentence
render :new, notice: "Worker could not be created!"
end
end
# PATCH/PUT /workers/1
# PATCH/PUT /workers/1.json
def update
logger.info "XXXXXX Worker ADMIN UPDATE XXXXXXXXXXXXXXX"
course_id = @worker.course_id ? @worker.course_id : params[:worker][:course_id]
onsite = @worker.onsite ? @worker.onsite : params[:worker][:onsite]
if onsite && @worker.update_attributes(worker_params)
logger.info "XXXXXX Worker loop 3"
# redirect_to course_confirm_path(course_id: course_id), notice: "Onsite User Created successfully!"
redirect_to new_course_record_path(worker_id: @worker.id), notice: "Onsite Worker Created successfully!"
elsif @worker.update_attributes(worker_params)
logger.info "XXXXXX Worker loop one"
format.html { redirect_to admin_workers_path, notice: "Worker Updated successfully!" }
format.json { respond_with_bip(@worker) }
else
flash[:error] = @worker.errors.full_messages.to_sentence
logger.info "XXXXXX Worker loop two"
logger.info "XXXXXX #{@worker.errors.full_messages.to_sentence}"
format.html { render :edit, notice: "Worker could not be updated!" }
format.json { respond_with_bip(@worker) }
end
end
# DELETE /workers/1
# DELETE /workers/1.json
def destroy
@worker.destroy
redirect_to admin_workers_path, notice: "#{@worker.id} was deleted successfully!"
end
private
# Use callbacks to share common setup or constraints between actions.
def set_worker
@worker = Worker.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def worker_params
params.require(:worker).permit(:onsite, :course_id, :firstname, :lastname, :startdate, :role_id, :picture, :notes, :med_location, :employer_id, :site_id, :picture, :user_id, allergies: [], med_conditions: [], medications: [])
end
def current_resource
@current_resource ||= Worker.find(params[:id]) if params[:id]
end
def sort_column
params[:column] ? params[:column] : "updated_at"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end
<file_sep>/db/migrate/20180919181911_create_toolboxes.rb
class CreateToolboxes < ActiveRecord::Migration[5.1]
def change
create_table :toolboxes do |t|
t.references :employer, foreign_key: true
t.references :site, foreign_key: true
t.date :date
t.string :comments
t.string :attachment
t.timestamps
end
end
end
<file_sep>/db/migrate/20180518180030_create_join_table_wcb_sections_wcbs.rb
class CreateJoinTableWcbSectionsWcbs < ActiveRecord::Migration[5.1]
def change
create_join_table :wcbs, :wcb_sections do |t|
t.index [:wcb_id, :wcb_section_id]
t.index [:wcb_section_id, :wcb_id]
end
end
end
<file_sep>/app/models/toolbox.rb
class Toolbox < ApplicationRecord
belongs_to :employer
belongs_to :site
has_and_belongs_to_many :workers
has_and_belongs_to_many :paperworks
has_many :extra_topics, dependent: :destroy
accepts_nested_attributes_for :extra_topics, allow_destroy: true, :reject_if => :all_blank
validates_presence_of :site_id
validates_presence_of :date
mount_uploader :attachment, CertUploader
after_save :update_workers
def update_workers
toolbox = self
puts " Toolbox update worker running .... "
toolbox.workers.each do |work|
puts "worker name --> #{work.worker_name}"
toolbox.paperworks.each do |top|
puts "topic --> #{top.title}, ID --> #{top.id}"
if top.category == "SJP"
puts "Category --> SJP"
worker_sjps = work.sjps.pluck(:paperwork_id)
if worker_sjps.include?(top.id)
puts "SJP Match for Toolbox"
sjp = work.sjps.find_by(paperwork_id: top.id)
sjp.update(reviewed: toolbox.date) if toolbox.date > sjp.reviewed
else
Sjp.create(worker_id: work.id, site_id: toolbox.site.id, reviewed: toolbox.date, paperwork_id: top.id)
puts "new SJP created"
end
elsif top.category == "SWP"
puts "Category --> SWP"
worker_forms = work.forms.pluck(:paperwork_id)
if worker_forms.include?(top.id)
puts "SWP Match for Toolbox"
form = work.forms.find_by(paperwork_id: top.id)
form.update(reviewed: toolbox.date) if toolbox.date > form.reviewed
else
Swp.create(worker_id: work.id, site_id: toolbox.site.id, reviewed: toolbox.date, paperwork_id: top.id)
puts "new SWP created"
end
elsif top.category == "Certificate"
puts "Category --> Certificate"
worker_certs = work.certificates.pluck(:paperwork_id)
if worker_certs.include?(top.id)
puts "Cert Match for Toolbox"
puts "Not updated -- Need to add code"
# cert = work.certificates.find_by(paperwork_id: top.id)
# cert.update(reviewed: toolbox.date) if toolbox.date > cert.reviewed
# else
# Certificate.create(worker_id: work.id, site_id: toolbox.site.id, reviewed: toolbox.date, paperwork_id: top.id)
# puts "new SWP created"
end
elsif top.category == "Form"
puts "Category --> Form"
worker_forms = work.forms.pluck(:paperwork_id)
if worker_forms.include?(top.id)
puts "Form Match for Toolbox"
form = work.forms.find_by(paperwork_id: top.id)
form.update(reviewed: toolbox.date) if toolbox.date > form.reviewed
else
Form.create(worker_id: work.id, site_id: toolbox.site.id, reviewed: toolbox.date, paperwork_id: top.id)
puts "new Form created"
end
end
end
end
end
end
<file_sep>/app/models/user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :worker, dependent: :destroy
validate :prime_check
attr_accessor :onsite
attr_accessor :no_email
attr_accessor :course_id
attr_accessor :employer
def prime_check
if user_type == "Prime Contractor" && prime_id.blank?
errors.add(:prime_id, 'Employer must be a prime contractor')
logger.info "############## Prime Check Failed ########################"
end
end
end
<file_sep>/app/models/violation.rb
class Violation < ApplicationRecord
belongs_to :worker
belongs_to :site
validates_presence_of :desc
validates_presence_of :date
validates_presence_of :site_id
end
<file_sep>/app/controllers/workers_controller.rb
class WorkersController < ApplicationController
before_action :set_worker, only: [:show, :edit, :update, :destroy]
# skip_before_action :authenticate_user!, only: :data_export_test
# skip_before_action :authorize, only: :data_export_test
include ActionController::Live # required for streaming
include ZipTricks::RailsStreaming
require 'csv'
# GET /workers
# GET /workers.json
def index
@workers = Worker.all
end
# GET /workers/1
# GET /workers/1.json
def show
## SJPS required from Role
role_sjps = []
@worker.sjps.each do |s|
role_sjps.push(s.paperwork_id)
end
@inc_sjps = @worker.role.paperworks.where(category: "SJP").order(:critical).ids - role_sjps
## SWPS required from Role
role_swps = []
@worker.swps.each do |s|
role_swps.push(s.paperwork_id)
end
@inc_swps = @worker.role.paperworks.where(category: "SWP").ids - role_swps
## Certs required from Role
role_certs = []
@worker.certificates.each do |s|
role_certs.push(s.paperwork_id)
end
@inc_certs = @worker.role.paperworks.where(category: "Certificate").ids - role_certs
## Forms required from Role
role_forms = []
@worker.forms.each do |s|
role_forms.push(s.paperwork_id)
end
@inc_forms = @worker.role.paperworks.where(category: "Form").ids - role_forms
@nyw_role = Role.where(title: "New Young").first
if @nyw_role
nyw_forms = []
@worker.nyw_forms.each do |s|
nyw_forms.push(s.paperwork_id)
end
@nyw_role = Role.where(title: "New Young").first
@inc_nyws = @nyw_role.paperworks.ids - nyw_forms
else
flash[:error] = "New Young Role is missing, contact administrator"
end
end
# GET /workers/new
def new
@worker = Worker.new
@worker.user_id = current_user.id
end
# GET /workers/1/edit
def edit
@worker = Worker.find(params[:id])
end
# POST /workers
# POST /workers.json
def create
@worker = Worker.new(worker_params)
@worker.user_id = current_user.id
if @worker.save
if current_user.user_type == "Admin"
redirect_to admin_workers_path, notice: "Worker Created successfully!"
else
redirect_to worker_path(@worker), notice: "Worker Created successfully!"
end
else
flash[:error] = @worker.errors.full_messages.to_sentence
render :new, notice: "Worker could not be created!"
end
end
# PATCH/PUT /workers/1
def update
logger.info "XXXXXX Worker UPDATE XXXXXXXXXXXXXXX"
emp = params[:worker][:employer_id]
if emp && emp.length > 3
logger.info "XXXXXX EMP ID BAD XXXXXXXXXXXXXXX"
emp_id = Employer.find_by(name: emp).id
params[:worker][:employer_id] = emp_id
end
# if @worker.update_attributes(worker_params)
# logger.info "XXXXXX Trigger UPDATE XXXXXXXXXXXXXXX"
# format.html { redirect_to admin_workers_path, notice: "Worker Updated successfully!" }
# format.json { respond_with_bip(@worker) }
if @worker.update_attributes(worker_params)
if current_user.user_type == "Admin"
redirect_to admin_workers_path, notice: "Updated successfully!"
else
redirect_to worker_path(@worker), notice: "Updated successfully!"
end
else
logger.info "XXXXXX #{@worker.errors.full_messages.to_sentence}"
flash[:error] = @worker.errors.full_messages.to_sentence
render :edit, notice: "Worker could not be updated!"
end
end
# DELETE /workers/1
def destroy
@worker.destroy
respond_to do |format|
format.html { redirect_to workers_url, notice: 'Worker was successfully destroyed.' }
format.json { head :no_content }
end
end
def add_site
# Worker.update_all({site_id: params[:site_id]}, {id: params[:worker_ids]})
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXx ADD SITE WORKERS XXXXXXXXXXXXXXXXXXXXx"
Worker.where(id: params[:worker_ids]).update_all(site_id: params[:site_id])
if params[:employer_id]
employer = Employer.find(params[:employer_id])
else
employer = Employer.find(current_user.employer_id)
end
@site = Site.find(params[:site_id])
redirect_to employer_my_sites_workers_path(employer, site_id: @site.id)
end
def generate_qr
@worker = Worker.find(params[:worker_id])
qrcode = RQRCode::QRCode.new("http://qrsafety.com#{worker_path(@worker)}")
# With default options specified explicitly
png = qrcode.as_png(
resize_gte_to: false,
resize_exactly_to: false,
fill: 'white',
color: 'black',
size: 600,
border_modules: 4,
module_px_size: 6,
file: nil # path to write
)
# png.save("worker-#{@worker.id}-qrcode.png", :interlace => true)
send_data png,
filename: "worker-#{@worker.firstname}-#{@worker.lastname}-#{@worker.id}-qrcode.png",
type: "image/png"
end
def qr_export
# @workers = Worker.all
@workers = Worker.where(id: params[:worker_ids])
compressed_filestream = Zip::OutputStream.write_buffer do |zos|
@workers.each do |work|
zos.put_next_entry "#{work.firstname}-#{work.lastname}-#{work.id}-qrcode.png"
zos.print work.generate_qr
end
end
compressed_filestream.rewind
send_data compressed_filestream.read, filename: "workers.zip"
end
def csv_export
@workers = Worker.all
send_data @workers.to_csv, filename: "#{Date.today}-workers.csv"
end
def csv_export_course
course = Course.find(params[:course_id])
@workers = course.workers
send_data @workers.to_csv(course), filename: "#{Date.today}-workers.csv"
end
def all_export_course
course = Course.find(params[:course_id])
@workers = course.workers
# @workers = Worker.where(id: params[:worker_ids])
compressed_filestream = Zip::OutputStream.write_buffer do |zos|
@workers.each do |work|
zos.put_next_entry "#{work.firstname}-#{work.lastname}-#{work.id}-qrcode.png"
zos.print work.generate_qr
end
course.course_records.each do |rec|
@record = rec
@course = @record.course
work = Worker.find(@record.worker_id)
zos.put_next_entry "#{work.firstname}-#{work.lastname}-#{@course.paperwork.title}-#{@course.id}.pdf"
@record = rec
@course = @record.course
work = Worker.find(@record.worker_id)
set_margin = "0"
# html = render_to_string(:action => '../pages/certs', :layout => false)
html = render_to_string(:action => "pdf_cert", :layout => false, locals: {:course_id => @course.id})
pdf = PDFKit.new(html, :page_size => 'B7', :orientation => 'landscape', :margin_top => set_margin+'in', :margin_right => set_margin+'in', :margin_bottom => set_margin+'in', :margin_left => set_margin+'in')
# pdf.stylesheets << "#{Rails.root}/app/assets/stylesheets/pdf-certs.scss"
css = Rails.application.assets ? Rails.application.assets['pdf-certs.css'].pathname : "#{Rails.public_path}/pdf-certs.css"
# css = "#{Rails.public_path}/pdf-certs.css"
pdf.stylesheets << css
zos.print pdf.to_pdf
end
zos.put_next_entry "#{Date.today}-workers.csv"
zos.print @workers.to_csv_wts(course)
end
compressed_filestream.rewind
send_data compressed_filestream.read, filename: "#{Date.today}-Course-#{course.id}.zip"
end
# def data_export
# # course = Course.find(params[:course_id])
# # @workers = course.workers
# logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX #{params[:all_workers]}"
# all_workers = params[:all_workers]
# if all_workers
# emp_query = params[:emp_query].to_i
# site_query = params[:site_query].to_i
# logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX #{emp_query}"
# if emp_query && emp_query > 0 && site_query && site_query > 0
# @workers = Worker.where(employer_id: emp_query).where(site_id: site_query)
# elsif site_query && site_query > 0
# @workers = Worker.where(site_id: site_query)
# elsif emp_query && emp_query > 0
# @workers = Worker.where(employer_id: emp_query)
# else
# @workers = Worker.all
# end
# else
# @workers = Worker.where(id: params[:worker_ids])
# end
# @qrparams = params[:qr]
# # @workers = Worker.where(id: params[:worker_ids])
# # compressed_filestream = Zip::OutputStream.write_buffer do |zos|
# @workers.find_each(batch_size: 20) do |work|
# if @qrparams
# zos.put_next_entry "#{work.firstname}-#{work.lastname}-#{work.id}-qrcode.png"
# zos.print work.generate_qr
# end
# if params[:certs]
# work.course_records.each do |rec|
# @record = rec
# @course = @record.course
# # work = Worker.find(@record.worker_id)
# zos.put_next_entry "#{work.firstname}-#{work.lastname}-#{@course.paperwork.title}-#{@course.id}.pdf"
# @record = rec
# @course = @record.course
# # work = Worker.find(@record.worker_id)
# set_margin = "0"
# # html = render_to_string(:action => '../pages/certs', :layout => false)
# html = render_to_string(:action => "pdf_cert", :layout => false, locals: {:course_id => @course.id})
# pdf = PDFKit.new(html, :page_size => 'B7', :orientation => 'landscape', :margin_top => set_margin+'in', :margin_right => set_margin+'in', :margin_bottom => set_margin+'in', :margin_left => set_margin+'in')
# # pdf.stylesheets << "#{Rails.root}/app/assets/stylesheets/pdf-certs.scss"
# css = Rails.application.assets ? Rails.application.assets['pdf-certs.css'].pathname : "#{Rails.public_path}/pdf-certs.css"
# # css = "#{Rails.public_path}/pdf-certs.css"
# pdf.stylesheets << css
# zos.print pdf.to_pdf
# end
# work.certificates.each do |cert|
# if cert.image && cert.image.file
# ext = cert.image.file.extension.downcase
# zos.put_next_entry "#{work.firstname}-#{work.lastname}-#{cert.paperwork.title}-#{cert.id}.#{ext}"
# zos.write cert.image.file.read
# else
# logger.info cert.image
# end
# end
# end
# if params[:csv]
# zos.put_next_entry "#{Date.today}-workers.csv"
# zos.print @workers.to_csv
# end
# end
# end
# compressed_filestream.rewind
# send_data compressed_filestream.read, filename: "#{Date.today}-QR-Data.zip"
# end
def data_export
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX All Workers --> #{params[:all_workers]}"
if params[:all_workers] == "true"
emp_query = params[:emp_query].to_i
site_query = params[:site_query].to_i
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Employer --> #{emp_query}"
if emp_query && emp_query > 0 && site_query && site_query > 0
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Employer and Site"
@workers = Worker.where(employer_id: emp_query).where(site_id: site_query)
elsif site_query && site_query > 0
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Site Only"
@workers = Worker.where(site_id: site_query)
elsif emp_query && emp_query > 0
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Employer Only"
@workers = Worker.where(employer_id: emp_query)
else
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Everything"
@workers = Worker.all
end
else
@workers = Worker.where(id: params[:worker_ids])
end
@qrparams = params[:qr]
zip_tricks_stream do |zip|
#### CSV #########
zip.write_deflated_file('report1.csv') do |sink|
CSV(sink) do |csv|
# csv << Person.column_names
lookup = { taken: "Date of Course", id: "Student ID", workname: 'Student Name', name: 'Employer Name', title: "Course Name", provider: "Course Provider", instructor: "Instructor", expiry: "Expiry Date" }
csv << lookup.values
# CSV::Row.new(lookup.values, true)
@workers.find_each(batch_size: 20) do |work|
# csv << person.attributes.values
workname = work.firstname + " " + work.lastname
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Generating CSV --> #{workname}"
work.course_records.each do |rec|
provider = "We The Safe Inc."
instructor = rec.course.instructor.instructor_name
date = rec.course.date
combo = work.attributes.merge(rec.attributes)
combo = combo.merge(rec.course.paperwork.attributes.select { |k,v| k == "title" } )
combo = combo.merge(rec.course.attributes.select { |k,v| k == "expiry" } )
combo = combo.merge(work.employer.attributes.select { |k,v| k == "name" } )
combo = combo.merge({"workname"=>workname})
combo = combo.merge({"provider"=>provider})
combo = combo.merge({"instructor"=>instructor})
combo = combo.merge({"id"=>rec.recid})
combo = combo.merge({"taken"=>date})
csv << lookup.keys.map { |attr| combo["#{attr}"] }
end
work.certificates.each do |cert|
id = cert.id.to_s.rjust(9, '0')
combo = work.attributes.merge(cert.attributes)
combo = combo.merge(cert.paperwork.attributes.select { |k,v| k == "title" } )
combo = combo.merge(work.employer.attributes.select { |k,v| k == "name" } )
combo = combo.merge({"workname"=>workname})
combo = combo.merge({"id"=>id})
csv << lookup.keys.map { |attr| combo["#{attr}"] }
end
end
end
end
#### CSV #########
#### QR Codes #########
if @qrparams
@workers.find_each(batch_size: 20) do |work|
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Generating QR Code --> #{work.worker_name}"
zip.write_deflated_file("#{work.firstname}-#{work.lastname}-#{work.id}-qrcode.png") do |sink|
sink << work.generate_qr.to_s
end
end
end
#### QR Codes #########
#### Certs #########
if params[:certs]
@workers.find_each(batch_size: 20) do |work|
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Generating Certificates --> #{work.worker_name}"
work.course_records.each do |rec|
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Course Record for --> #{work.worker_name} --> #{rec.id}"
@record = rec
@course = @record.course
zip.write_deflated_file("#{work.firstname}-#{work.lastname}-#{@course.paperwork.title}-#{@course.id}.pdf") do |sink|
set_margin = "0"
# html = render_to_string(:action => '../pages/certs', :layout => false)
html = render_to_string(:action => "pdf_cert", :layout => false, locals: {:course_id => @course.id})
pdf = PDFKit.new(html, :page_size => 'B7', :orientation => 'landscape', :margin_top => set_margin+'in', :margin_right => set_margin+'in', :margin_bottom => set_margin+'in', :margin_left => set_margin+'in')
# pdf.stylesheets << "#{Rails.root}/app/assets/stylesheets/pdf-certs.scss"
css = Rails.application.assets ? Rails.application.assets['pdf-certs.css'].pathname : "#{Rails.public_path}/pdf-certs.css"
# css = "#{Rails.public_path}/pdf-certs.css"
pdf.stylesheets << css
# zos.print pdf.to_pdf
sink << pdf.to_pdf.to_s
end ## Sink
end ## Rec Loop
work.certificates.each do |cert|
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Non WTS Certificates for --> #{work.worker_name} --> #{cert.id}"
if cert.image && cert.image.file
ext = cert.image.file.extension.downcase
zip.write_deflated_file("#{work.firstname}-#{work.lastname}-#{cert.paperwork.title}-#{cert.id}.#{ext}") do |sink|
sink << cert.image.file.read
end ## Sink
else
logger.info cert.image
end
end
end ## Work Loop
end
#### Certs #########
end ## Zip Loop
end
def data_export_test
@workers = Worker.where(employer_id: 3)
zip_tricks_stream do |zip|
#### CSV #########
zip.write_deflated_file('report1.csv') do |sink|
CSV(sink) do |csv|
# csv << Person.column_names
lookup = { taken: "Date of Course", id: "Student ID", workname: '<NAME>', name: '<NAME>', title: "Course Name", provider: "Course Provider", instructor: "Instructor", expiry: "Expiry Date" }
csv << lookup.values
# CSV::Row.new(lookup.values, true)
@workers.find_each(batch_size: 20) do |work|
# csv << person.attributes.values
workname = work.firstname + " " + work.lastname
logger.info "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Generating CSV --> #{workname}"
work.course_records.each do |rec|
provider = "We The Safe Inc."
instructor = rec.course.instructor.instructor_name
date = rec.course.date
combo = work.attributes.merge(rec.attributes)
combo = combo.merge(rec.course.paperwork.attributes.select { |k,v| k == "title" } )
combo = combo.merge(rec.course.attributes.select { |k,v| k == "expiry" } )
combo = combo.merge(work.employer.attributes.select { |k,v| k == "name" } )
combo = combo.merge({"workname"=>workname})
combo = combo.merge({"provider"=>provider})
combo = combo.merge({"instructor"=>instructor})
combo = combo.merge({"id"=>rec.recid})
combo = combo.merge({"taken"=>date})
csv << lookup.keys.map { |attr| combo["#{attr}"] }
end
work.certificates.each do |cert|
id = cert.id.to_s.rjust(9, '0')
combo = work.attributes.merge(cert.attributes)
combo = combo.merge(cert.paperwork.attributes.select { |k,v| k == "title" } )
combo = combo.merge(work.employer.attributes.select { |k,v| k == "name" } )
combo = combo.merge({"workname"=>workname})
combo = combo.merge({"id"=>id})
csv << lookup.keys.map { |attr| combo["#{attr}"] }
end
end
end
end
#### CSV #########
end ## Zip Loop
end
def download_pdf
@worker = Worker.find(params[:worker_id])
work = @worker
set_margin = "0"
html = render_to_string(:action => "pdf_cert", :layout => false, locals: {:worker_id => @worker})
pdf = PDFKit.new(html, :page_size => 'B7', :orientation => 'landscape', :margin_top => set_margin+'in', :margin_right => set_margin+'in', :margin_bottom => set_margin+'in', :margin_left => set_margin+'in')
css = Rails.application.assets ? Rails.application.assets['pdf-certs.css'].pathname : "#{Rails.public_path}/pdf-certs.css"
pdf.stylesheets << css
send_data pdf.to_pdf, filename: "#{work.firstname}-#{work.lastname}.pdf"
end
def csv_import
#stuff goes here
Worker.import_csv(params[:file])
redirect_to admin_root_path, notice: "CSV data imported."
end
def pdf_cert
@worker = Worker.find(params[:worker_id])
# @workname = @worker.firstname + " " + @worker.lastname
end
private
# Use callbacks to share common setup or constraints between actions.
def set_worker
@worker = Worker.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def worker_params
# params[:worker][:med_conditions] ||= []
# params[:worker][:medications] ||= []
params.require(:worker).permit(:firstname, :lastname, :startdate, :role, :role_id, :picture, :notes, :med_location, :employer_id, :user_id, :site_id, :picture, allergies: [], med_conditions: [], medications: [])
end
def current_resource
@current_resource ||= Worker.find(params[:id]) if params[:id]
end
end
<file_sep>/db/migrate/20180915230208_create_fallpros.rb
class CreateFallpros < ActiveRecord::Migration[5.1]
def change
create_table :fallpros do |t|
t.references :user, foreign_key: true
t.string :supervisor
t.string :company
t.boolean :add_procedures
t.boolean :picture
t.boolean :sketch
t.timestamps
end
end
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'faker'
Faker::Config.locale = "en-CA"
User.destroy_all
password = "<PASSWORD>"
User.create! [
email: "<EMAIL>",
# password_digest: User.new(:password => <PASSWORD>).password_digest,
password: <PASSWORD>,
password_confirmation: <PASSWORD>,
user_type: "Employer",
employer_id: 1
]
User.create! [
email: "<EMAIL>",
# password_digest: User.new(:password => <PASSWORD>).password_digest,
password: <PASSWORD>,
password_confirmation: <PASSWORD>,
user_type: "Employer",
employer_id: 2
]
User.create! [
email: "<EMAIL>",
# password_digest: User.new(:password => <PASSWORD>).password_digest,
password: <PASSWORD>,
password_confirmation: <PASSWORD>,
user_type: "Employer",
employer_id: 3
]
# User.create! [
# email: "<EMAIL>",
# # password_digest: User.new(:password => <PASSWORD>).password_digest,
# password: <PASSWORD>,
# password_confirmation: <PASSWORD>,
# user_type: "Worker",
# employer_id: 1
# ]
# User.create! [
# email: "<EMAIL>",
# # password_digest: User.new(:password => <PASSWORD>).password_digest,
# password: <PASSWORD>,
# password_confirmation: <PASSWORD>,
# user_type: "Worker",
# employer_id: 2
# ]
p "Created #{User.count} users"
Employer.destroy_all
Employer.create! [
city: Faker::Address.city,
name: Faker::Company.name,
street: Faker::Address.street_address,
postal: "X1X 1X1",
country: "Canada",
province: "British Columbia",
logo: File.open(Dir['public/uploads/BurgerKingLogoDileo.png'].sample),
coordinator: Faker::Hobbit.character,
]
Employer.create! [
city: Faker::Address.city,
name: Faker::Company.name,
street: Faker::Address.street_address,
postal: "X1X 1X1",
country: "Canada",
province: "British Columbia",
logo: File.open(Dir['public/uploads/Apple-logo-png.png'].sample),
coordinator: Faker::Hobbit.character,
]
Employer.create! [
city: Faker::Address.city,
name: "We the Safe Inc.",
street: Faker::Address.street_address,
postal: "X1X 1X1",
country: "Canada",
province: "British Columbia",
logo: File.open('public/uploads/wts.jpg'),
coordinator: Faker::Hobbit.character,
]
p "Created #{Employer.count} employers"
Prime.create! [
employer_id: Employer.last.id
]
p "Created #{Prime.count} primes"
Site.destroy_all
20.times do
Site.create! [
employer_id: [1, 2].sample,
prime_id: 1,
name: Faker::Hobbit.location,
]
end
p "Created #{Site.count} sites"
Worker.destroy_all
Emergency.destroy_all
Certificate.destroy_all
Orientation.destroy_all
Sjp.destroy_all
Swp.destroy_all
Violation.destroy_all
20.times do
Paperwork.create! [
title: Faker::SiliconValley.invention,
category: "SJP",
critical: Faker::Boolean.boolean(0.4)
]
end
20.times do
Paperwork.create! [
title: Faker::SiliconValley.invention,
category: "SWP"
]
end
20.times do
Paperwork.create! [
title: Faker::Beer.style,
category: "Certificate"
]
end
wts_courses = [ "The CORE of Fall Protection", "Fall Protection Recertification", "Fall Protection Review", "The CORE of Confined Space", "The CORE of supervision", "The CORE of JOHS", "Respirable Crystalline Silica Exposure Control", "Scissor Lift", "Boom Lift", "Telehandler", "Forklift", "Respiratory Fit Test"]
wts_courses.each do |wts|
Paperwork.create! [
title: wts,
category: "Wethesafe"
]
end
roles = ["Supervisor", "Superintendent", "CSO", "First Aid", "Laborer", "Carpenter", "Carpenter helper", "Rigger", "Crane Operator", "Layout Technician", "Crane Technician"]
roles.each do |role|
paper_ar = []
10.times do
paper_ar.push(Paperwork.where(category: "Certificate").sample.id)
paper_ar.push(Paperwork.where(category: "SJP").sample.id)
paper_ar.push(Paperwork.where(category: "SWP").sample.id)
end
Role.create! [
title: role,
paperwork_ids: paper_ar
]
end
med_conditions = [
"glaucoma",
"Allergy",
"Alzheimer’s",
"Anemia",
"Anxiety Disorders",
"Arthritis",
"Asthma",
"Blood Pressure",
"Breast Health and Disease",
"Bursitis and Tendonitis",
"Cholesterol",
"Colds and Flu",
"Depression",
"Diabetes",
"Digestive Disorders",
"Fatigue",
"Foot Problems",
"Grief and Loss",
"Headache",
"Hearing Loss",
"Kidney Disease",
"Lung Diseases",
"Memory Loss",
"Menopause",
"Osteoporosis",
"Pain, Back",
"Pain, Generalized",
"Pain, Hand",
"Pain, Hip",
"Pain, Knee",
"Pain, Neck",
"Parkinson’s Disease",
"Pregnancy",
"Prostate Disease",
"Sleep Disorders",
"Stress",
"Stroke",
"Thyroid Disorders",
"Urine and Bladder Problems"
]
allergies = [
"Pollen",
"Animal Dander",
"Dust Mites",
"Insect Stings",
"Mold",
"Mold",
"Food",
"Latex"
]
loopcount = 3
workid = 1
100.times do
emp = [1, 2].sample
contions_no = Faker::Number.between(0, 6)
allergies_no = Faker::Number.between(0, 6)
User.create! [
email: "<EMAIL>",
# password_digest: User.new(:password => <PASSWORD>).<PASSWORD>_<PASSWORD>,
password: <PASSWORD>,
password_confirmation: <PASSWORD>,
user_type: "Worker",
employer_id: emp
]
Worker.create! [
user_id: loopcount,
firstname: Faker::Name.first_name,
lastname: Faker::Name.last_name,
startdate: Faker::Date.between(10.years.ago, 2.months.ago),
role_id: Role.all.sample.id,
picture: File.open(Dir['public/uploads/bean.jpg', 'public/uploads/guy.jpg', 'public/uploads/mib', 'public/uploads/skelletor.jpg'].sample),
allergies: allergies.sample(allergies_no),
med_conditions: med_conditions.sample(contions_no),
med_location: Faker::Simpsons.location,
employer_id: emp,
site_id: Site.where(employer_id: emp).sample.id,
notes: [Faker::Seinfeld.quote, ""].sample
]
Faker::Number.between(1, 5).times do
Emergency.create! [
worker_id: workid,
name: Faker::Seinfeld.character,
phone: Faker::PhoneNumber.cell_phone,
relationship: ["mother", "brother", "son", "daughter", "uncle", "grandma"].sample
]
end
Faker::Number.between(1, 12).times do
taken_date = Faker::Date.between(2.years.ago, 3.months.ago)
Certificate.create! [
worker_id: workid,
# coursename: Faker::Beer.style,
paperwork_id: Paperwork.where(category: "Certificate").sample.id,
taken: taken_date,
expiry: taken_date + 1.year,
image: File.open(Dir['public/uploads/fake_cert.png', 'public/uploads/fake_cert2.jpg'].sample),
provider: Faker::Hobbit.character
]
end
Faker::Number.between(1, 5).times do
Orientation.create! [
site_id: Faker::Number.between(1, 20),
worker_id: workid,
date: Faker::Date.between(2.years.ago, 3.months.ago)
]
end
Faker::Number.between(1, 8).times do
Sjp.create! [
site_id: Faker::Number.between(1, 20),
worker_id: workid,
reviewed: Faker::Date.between(2.years.ago, 3.months.ago),
# title: Faker::SiliconValley.invention,
paperwork_id: Paperwork.where(category: "SJP").sample.id
]
end
Faker::Number.between(1, 8).times do
Swp.create! [
site_id: Faker::Number.between(1, 20),
worker_id: workid,
reviewed: Faker::Date.between(2.years.ago, 3.months.ago),
# title: Faker::SiliconValley.invention,
paperwork_id: Paperwork.where(category: "SWP").sample.id
]
end
Faker::Number.between(0, 8).times do
Violation.create! [
site_id: Faker::Number.between(1, 20),
worker_id: workid,
desc: ["Ladders", "Fall protection", "general requirements", "Hazard communication", "Scaffolding", "Respiratory protection", 'Lockout/tagout'].sample,
date: Faker::Date.between(2.years.ago, 3.months.ago),
]
end
loopcount += 1
workid += 1
end
User.create! [
email: "<EMAIL>",
# password_digest: User.new(:password => <PASSWORD>).password_digest,
password: <PASSWORD>,
password_confirmation: <PASSWORD>,
user_type: "Admin",
employer_id: 2
]
sections = [
[1, "Definitions"],
[2, "Application"],
[3, "Rights and Responsibilities"],
[4, "General Conditions"],
[5, "Chemical Agents and Biological Agents"],
[6, "Substance Specific Requirements"],
[7, "Noise, Vibration, Radiation and Temperature"],
[8, "Personal Protective Clothing and Equipment"],
[9, "Confined Spaces"],
[11, "Fall Protection"],
[12, "Tools, Machinery and Equipment"],
[13, "Ladders, Scaffolds and Temporary Work Platforms"],
[14, "Cranes and Hoists"],
[15, "Rigging"],
[16, "Mobile Equipment"],
[17, "Transportation of Workers"],
[18, "Traffic Control"],
[19, "Electrical Safety"],
[20, "Construction, Excavation and Demolition"],
[21, "Blasting Operations"],
[22, "Underground Workings"],
[23, "Oil and Gas"],
[24, "Diving, Fishing and Other Marine Operations"],
[25, "Camps"],
[26, "Forestry Operations and Similar Activities"],
[27, "Wood Products Manufacturing"],
[28, "Agriculture"],
[29, "Aircraft Operations"],
[30, "Laboratories"],
[31, "Firefighting"],
[32, "Evacuation and Rescue"],
[34, "Rope Access"]
]
sections.each do |sec|
WcbSection.create! [number: sec[0], title: sec[1]]
end
p "Created #{WcbSection.count} WCB Sections"
50.times do
num = Faker::Number.between(1, 20)
let = ["a", "b", "c"].sample
Wcb.create! [
# section: Faker::Number.between(1, 20),
subsection: "#{num}#{let}",
employer_id: Employer.all.ids.sample,
wcb_section_ids: WcbSection.all.ids.sample,
site_id: Site.all.ids.sample,
date: Faker::Date.between(2.years.ago, 3.months.ago)
]
end
p "Created #{Wcb.count} WCB Orders"
p "Created #{Worker.count} workers"
p "Created #{User.count} users"
p "Created #{Emergency.count} emergency contacts"
p "Created #{Certificate.count} Certificates"
p "Created #{Sjp.count} SJPs"
p "Created #{Swp.count} SWPs"
p "Created Admin Account"<file_sep>/app/controllers/admin/mailer_controller.rb
class Admin::MailerController < Admin::ApplicationController
skip_before_action :authenticate_user!
def contact_me
@greeting = "Hi"
@body = "this is a test body"
@email = "<EMAIL>"
@name = "<NAME>"
render :file => 'main_mailer/contact_me.html.erb', :layout => 'mailer'
end
def certs_report(employer)
@employer = Employer.find(employer)
render :file => 'main_mailer/certs_report.html.erb', :layout => 'mailer'
end
end<file_sep>/db/migrate/20180805195436_create_join_table_employer_pdf.rb
class CreateJoinTableEmployerPdf < ActiveRecord::Migration[5.1]
def change
create_join_table :employers, :pdfs do |t|
# t.index [:employer_id, :pdf_id]
# t.index [:pdf_id, :employer_id]
end
end
end
<file_sep>/app/models/prime.rb
class Prime < ApplicationRecord
has_many :sites
has_many :workers, through: :sites
has_many :employers, through: :sites
# mount_uploader :logo, ImageUploader
# validates_presence_of :name
# validates_presence_of :street
# validates_presence_of :city
# validates_presence_of :province
# validates_presence_of :postal
# validates_presence_of :country
validates_presence_of :employer_id
def emp_name
emp = Employer.find_by(id: self.employer_id)
emp.name
end
end
<file_sep>/app/controllers/admin/base_admin_controller.rb
class Admin::BaseAdminController < ActionController::Base
# use an admin-specific layout instead of the main application layout
layout "admin"
before_action :authenticate_user!
# all child controllers will automatically enforce access to admins only
before_action :require_admin
def current_user
@current_user ||= warden.authenticate(:scope => :user)
end
helper_method :current_user
def require_admin
redirect_back( fallback_location: ("/pages/construction"), notice: "You need to be an admin to access that page! #{current_user.user_type}") unless current_user && current_user.user_type == "Admin"
end
end
<file_sep>/app/models/worker.rb
class Worker < ApplicationRecord
require 'csv'
belongs_to :employer
belongs_to :user
belongs_to :site, optional: true
belongs_to :role
has_many :emergencies, dependent: :destroy
has_many :certificates, dependent: :destroy
has_many :orientations, dependent: :destroy
has_many :sjps, dependent: :destroy
has_many :swps, dependent: :destroy
has_many :violations, dependent: :destroy
has_many :forms, dependent: :destroy
has_many :nyws, dependent: :destroy
has_many :nyw_forms, through: :nyws
has_many :ppes, dependent: :destroy
# has_many :courses
has_many :course_records, dependent: :destroy
has_and_belongs_to_many :toolboxes
attr_accessor :onsite
attr_accessor :course_id
after_save :update_employer
# before_save :auto_employer
mount_uploader :picture, ImageUploader
serialize :med_conditions
serialize :allergies
serialize :medications
validates_presence_of :firstname
validates_presence_of :lastname
# validates_presence_of :startdate
# validates_presence_of :role
# validates_presence_of :med_location
validates_presence_of :employer_id
def update_employer
if saved_change_to_attribute?(:employer_id)
user = User.find(self.user_id)
if user && user.user_type != "Admin"
user.update(employer_id: self.employer_id)
else
logger.info "XXXXXXXXXXXXXXX User is Admin XXXXXXXXXXXXXXXXXXX"
end
end
end
# def auto_employer
# if self.employer_id.length > 3
# logger.info "XXXXXXXXXXXXXXX Worker Employer ID is name --> #{self.employer_id} XXXXXXXXXXXXXXXXXXX"
# emp = Employer.find_by(name: self.employer_id)
# self.employer_id = emp
# logger.info "XXXXXXXXXXXXXXX Emp ID changed to --> #{emp} XXXXXXXXXXXXXXXXXXX"
# end
# end
def emp_name
return Employer.find(self.employer_id).name
end
def generate_qr
@worker = self
path = Rails.application.routes.url_helpers.worker_path(@worker)
qrcode = RQRCode::QRCode.new("http://qrsafety.com#{path}")
# With default options specified explicitly
png = qrcode.as_png(
resize_gte_to: false,
resize_exactly_to: false,
fill: 'white',
color: 'black',
size: 600,
border_modules: 4,
module_px_size: 6,
file: nil # path to write
)
# png.save("worker-#{@worker.id}-qrcode.png", :interlace => true)
# send_data png,
# filename: "worker-#{@worker.firstname}-#{@worker.lastname}-#{@worker.id}-qrcode.png",
# type: "image/png"
return png
end
# def self.to_csv
# CSV.generate do |csv|
# work_columns = %w(firstname lastname startdate)
# cert_columns = %w(taken expiry)
# columns = work_columns + cert_columns
# csv << columns.map(&:humanize)
# all.each do |work|
# work.certificates.each do |cert|
# work_certs = cert.attributes.values_at(*cert_columns)
# worker = work.attributes.values_at(*work_columns)
# csv << worker + work_certs
# end
# # csv << work.attributes.values_at(*columns)
# end
# end
# end
def self.import_csv(file)
# for server
courses = {
fallpro: [69, 258],
conSpace: [138, 216],
supervision: [233, 262],
whims: [68, 284],
scissor: [72, 265],
boom: [73, 266],
zoom: [74, 267],
fork: [75, 268],
fitTest: [269, 269],
swingStage: [161, 161],
crane: [251, 251],
ofa: [216, 251]
}
# for development
# courses = {fallpro: [61, 1], conSpace: [60, 2], supervision: [59, 3], whims: [58, 4], scissor: [57, 5], boom: [56, 6], zoom: [55, 7], fork: [54, 8], fitTest: [53, 9], swingStage: [52, 10], crane: [51, 11], ofa: [50, 12]}
CSV.foreach(file.path, headers: true) do |row|
name = row["Name"].split(' ', 2)
provider_arr = row["Provider"] ? row["Provider"].split(',') : ["None"]
fallpro = row["Fall Protection"]
conSpace = row["Confined Space"]
supervision = row["Supervision"]
whims = row["WHMIS 2015"]
scissor = row["Scissor Lift"]
boom = row["Boomlift"]
zoom = row["Telehandler"]
fork = row["Forklift"]
fitTest = row["Fit Test"]
swingStage = row["Swing Stage"]
crane = row["Crane Op."]
ofa = row["OFA"]
dates = {fallpro: fallpro, conSpace: conSpace, supervision: supervision, whims: whims, scissor: scissor, boom: boom, zoom: zoom, fork: fork, fitTest: fitTest, swingStage: swingStage, crane: crane, ofa: ofa}
puts "dates hash --> #{dates}"
dates = dates.compact
puts "dates hash conpact --> #{dates}"
firstname = name[0]
lastname = name[1]
# new_worker = Worker.create!(firstname: firstname, lastname: lastname, user_id: 104, role_id: Role.all.sample.id, employer_id: 4) ## FOR development
new_worker = Worker.create!(firstname: firstname, lastname: lastname, user_id: 105, role_id: 22, employer_id: 4) ## FOR Production Server
loopcount = 0
dates.each do |key, date|
if date
provider = provider_arr.length >= (loopcount + 1) ? provider_arr[loopcount] : provider_arr[0]
puts "date --> #{date}"
puts "Provider --> #{provider}"
puts "paperwork_id --> #{courses[key]}"
if provider == "We The Safe" || "WTS"
paperwork_id = courses[key][1]
else
paperwork_id = courses[key][0]
end
puts "worker_id--> #{new_worker.id}"
puts "expiry--> #{date}"
puts "provider--> #{provider}"
puts "paperwork_id--> #{paperwork_id}"
begin
Date.parse(date)
rescue ArgumentError
day = date.split('/')[0]
month = date.split('/')[1]
year = date.split('/')[-1]
date = "#{month}/#{day}/#{year}"
end
Certificate.create!(worker_id: new_worker.id, taken: '01/01/1901', expiry: date, provider: provider, paperwork_id: paperwork_id)
loopcount += 1
end
end
end
end
def self.to_csv(course = nil)
# lookup = { taken: "Date of Course", id: "Student ID", workname: '<NAME>', name: '<NAME>', title: "Course Name", provider: "Course Provider", instructor: "Instructor", expiry: "Expiry Date" }
# CSV.generate(headers: true) do |csv|
# csv << lookup.values
# all.each do |work|
work = self
workname = work.firstname + " " + work.lastname
work.course_records.each do |rec|
provider = "We The Safe Inc."
instructor = rec.course.instructor.instructor_name
date = rec.course.date
combo = work.attributes.merge(rec.attributes)
combo = combo.merge(rec.course.paperwork.attributes.select { |k,v| k == "title" } )
combo = combo.merge(rec.course.attributes.select { |k,v| k == "expiry" } )
combo = combo.merge(work.employer.attributes.select { |k,v| k == "name" } )
combo = combo.merge({"workname"=>workname})
combo = combo.merge({"provider"=>provider})
combo = combo.merge({"instructor"=>instructor})
combo = combo.merge({"id"=>rec.recid})
combo = combo.merge({"taken"=>date})
csv << lookup.keys.map { |attr| combo["#{attr}"] }
end
unless course
work.certificates.each do |cert|
id = cert.id.to_s.rjust(9, '0')
combo = work.attributes.merge(cert.attributes)
combo = combo.merge(cert.paperwork.attributes.select { |k,v| k == "title" } )
combo = combo.merge(work.employer.attributes.select { |k,v| k == "name" } )
combo = combo.merge({"workname"=>workname})
combo = combo.merge({"id"=>id})
csv << lookup.keys.map { |attr| combo["#{attr}"] }
end
end
# end
#end ## End CSV do
end
def self.to_csv_wts(course = nil)
lookup = { taken: "Date of Course", id: "Student ID", workname: '<NAME>', name: '<NAME>', title: "Course Name", provider: "Course Provider", instructor: "Instructor", expiry: "Expiry Date" }
CSV.generate(headers: true) do |csv|
csv << lookup.values
all.each do |work|
workname = work.firstname + " " + work.lastname
course = Course.find(course.id)
records = work.course_records.where(course_id: course.id)
records.each do |rec|
provider = "We The Safe Inc."
instructor = rec.course.instructor.instructor_name
date = rec.course.date
combo = work.attributes.merge(rec.attributes)
combo = combo.merge(rec.course.paperwork.attributes.select { |k,v| k == "title" } )
combo = combo.merge(rec.course.attributes.select { |k,v| k == "expiry" } )
combo = combo.merge(work.employer.attributes.select { |k,v| k == "name" } )
combo = combo.merge({"workname"=>workname})
combo = combo.merge({"provider"=>provider})
combo = combo.merge({"instructor"=>instructor})
combo = combo.merge({"id"=>rec.recid})
combo = combo.merge({"taken"=>date})
csv << lookup.keys.map { |attr| combo["#{attr}"] }
end
end
end
end
def worker_name
return self.firstname + " " + self.lastname
end
def self.filter(filter_employer, filter_site)
if filter_employer && filter_site
where(employer_id: filter_employer)
where(site_id: filter_site)
# where('"employer_id" = ? AND "site_id" = ?', "#{filter_employer}", "#{filter_site}")
elsif filter_employer
where(employer_id: filter_employer)
elsif filter_site
where(site_id: filter_site)
else
all
end
end
def self.search(search)
where('firstname ILIKE :search OR lastname ILIKE :search', search: "%#{search}%")
end
end
<file_sep>/db/migrate/20180323032209_create_certificates.rb
class CreateCertificates < ActiveRecord::Migration[5.1]
def change
create_table :certificates do |t|
t.references :worker, foreign_key: true
t.string :coursename
t.date :taken
t.date :expiry
t.string :image
t.string :provider
t.timestamps
end
end
end
<file_sep>/app/controllers/messages_controller.rb
class MessagesController < ApplicationController
skip_before_action :authenticate_user!
def new
@message = Message.new
end
def training
@message = Message.new
@employer = Employer.find(params[:employer])
@course = Certificate.find(params[:course])
@worker = Worker.find(params[:worker])
end
def create
@message = Message.new message_params
if @message.course
MainMailer.training(@message).deliver_now
logger.info "XXXXXXXXXXXXXx Message all good!"
# flash[:success] = "Message received, thanks!"
redirect_back( fallback_location: root_path, notice: "Message received, thanks!")
elsif @message.valid?
MainMailer.contact_me(@message).deliver_now
# flash[:success] = "Message received, thanks!"
redirect_back( fallback_location: root_path, notice: "Message received, thanks!")
else
logger.info "There was an error sending your message."
logger.info ap @message
render :new, notice: "Message did not send!"
end
end
private
def message_params
params.require(:message).permit(:name, :email, :body, :course, :worker, :employer, :phone)
end
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :store_user_location!, if: :storable_location?
before_action :authorize
before_action :authenticate_user!
def after_sign_in_path_for(resource)
# user_path(current_user) #your path
if session["user_return_to"]
session["user_return_to"]
elsif current_user.user_type == "Employer" && current_user.employer_id
employer_path(current_user.employer_id)
elsif current_user.user_type == "Worker"
worker = Worker.find_by(user_id: current_user.id)
if worker
worker_path(worker)
else
"/pages/construction"
end
elsif current_user.user_type == "Prime Contractor" && current_user.prime_id
prime_path(current_user.prime_id)
elsif current_user.user_type == "Admin"
admin_root_path
else
"/pages/construction"
end
end
delegate :allow?, to: :current_permission
helper_method :allow?
private
def storable_location?
request.get? && is_navigational_format? && !devise_controller? && !request.xhr?
end
def store_user_location!
# :user is the scope we are authenticating
store_location_for(:user, request.fullpath)
end
def current_permission
@current_permission ||= Permission.new(current_user)
end
def current_resource
nil
end
def authorize
if !current_permission.allow?(params[:controller], params[:action], current_resource)
if params[:controller] == "workers" && current_user && current_user.user_type == "Worker" && current_user.worker == nil
redirect_to new_message_path, notice: "Your account has not been set up!"
elsif params[:controller] == "workers" && params[:action] == "show"
logger.info "################# Worker page #{params[:id]} ##########################"
work_id = params[:id]
redirect_to new_user_session_path(worker_id: work_id), notice: "Please sign in"
else
redirect_back( fallback_location: ("/pages/construction"), notice: "Not authorized.")
end
logger.info "################# NOT AUTHORIZED ##########################"
end
end
end<file_sep>/app/models/certificate.rb
class Certificate < ApplicationRecord
belongs_to :worker
belongs_to :paperwork
attr_accessor :typed_provider
# validates_presence_of :coursename
validates_presence_of :taken
# validates_presence_of :expiry
# validates_presence_of :provider
mount_uploader :image, CertUploader
before_save :check_provider
def check_provider
unless provider && provider.length > 1
self.provider = typed_provider
logger.info "Provider is nil, using #{typed_provider} instead."
else
logger.info "Provider not nil using #{provider}."
end
# provider = typed_provider if provider.blank?
end
end
<file_sep>/app/models/emergency.rb
class Emergency < ApplicationRecord
belongs_to :worker
validates_presence_of :name
validates_presence_of :phone
validates_presence_of :relationship
end
<file_sep>/app/models/statement.rb
class Statement < ApplicationRecord
belongs_to :employer
before_save :check_email
validates_presence_of :email
def check_email
unless email && email.length > 1
self.email = typed_email
logger.info "Email is nil, using #{typed_email} instead."
else
logger.info "Email not nil using #{email}."
end
# email = typed_email if email.blank?
self.email = typed_email if typed_email.length > 0
end
end
<file_sep>/test/controllers/ppes_controller_test.rb
require 'test_helper'
class PpesControllerTest < ActionDispatch::IntegrationTest
test "should get new" do
get ppes_new_url
assert_response :success
end
test "should get edit" do
get ppes_edit_url
assert_response :success
end
end
<file_sep>/app/controllers/fallpro/application_controller.rb
class Fallpro::ApplicationController < ApplicationController
end
<file_sep>/test/controllers/violations_controller_test.rb
require 'test_helper'
class ViolationsControllerTest < ActionDispatch::IntegrationTest
test "should get new" do
get violations_new_url
assert_response :success
end
test "should get edit" do
get violations_edit_url
assert_response :success
end
test "should get destroy" do
get violations_destroy_url
assert_response :success
end
end
<file_sep>/app/controllers/instructors_controller.rb
class InstructorsController < ApplicationController
before_action :set_instructor, only: [:edit, :update, :destroy]
def index
@instructors = Instructor.all
@instructors = @instructors.order(:updated_at).reverse_order.page(params[:page]).per(15)
end
def new
@instructor = Instructor.new
end
def create
@instructor = Instructor.new(instructor_params)
if @instructor.save
redirect_to instructors_path, notice: "Instructor Created successfully!"
else
flash[:error] = @instructor.errors.full_messages.to_sentence
render :new, notice: "Instructor could not be created!"
end
end
def update
if @instructor.update_attributes(instructor_params)
redirect_to instructors_path, notice: "Updated successfully!"
else
flash[:error] = @instructor.errors.full_messages.to_sentence
render :edit, notice: "Instructor could not be updated!"
end
end
def destroy
@instructor.destroy
redirect_to instructors_path, notice: "#{@instructor.id} was deleted successfully!"
end
def edit
end
private
def set_instructor
@instructor = Instructor.find(params[:id])
end
def instructor_params
params.require(:instructor).permit(:firstname, :lastname, :signature, :employer_id)
end
end
<file_sep>/test/controllers/sjps_controller_test.rb
require 'test_helper'
class SjpsControllerTest < ActionDispatch::IntegrationTest
test "should get new" do
get sjps_new_url
assert_response :success
end
test "should get edit" do
get sjps_edit_url
assert_response :success
end
test "should get destroy" do
get sjps_destroy_url
assert_response :success
end
end
<file_sep>/app/controllers/sites_controller.rb
class SitesController < ApplicationController
def new
@employer = Employer.find(params[:employer_id])
@site = @employer.sites.build
end
def create
@employer = Employer.find(params[:employer_id])
@site = @employer.sites.build(site_params)
if @site.save
redirect_to employer_my_sites_path(@employer), notice: "Site created successfully"
else
render :new
end
end
def edit
@site = Site.find(params[:id])
if params[:employer_id]
@employer = Employer.find(params[:employer_id])
else
@employer = @site.employers.first
end
end
def destroy
@site = Site.find(params[:id])
@employer = Employer.find(params[:employer_id])
@site.destroy
redirect_to employer_path(@employer), notice: "#{@site.name} was deleted successfully!"
end
def update
@site = Site.find(params[:id])
@employer = Employer.find(params[:employer_id])
if @site.update_attributes(site_params)
redirect_to employer_path(@employer), notice: "site updated successfully"
else
flash[:error] = "#{@site.errors.count} errors prevented site from being updated."
render :edit
end
end
protected
def site_params
params.require(:site).permit(:name,:location,:prime_id,{employer_ids: []})
end
def current_resource
if params[:id]
@current_resource ||= Site.find(params[:id])
elsif params[:site_id]
@current_resource ||= Site.find(params[:site_id])
end
end
end<file_sep>/db/migrate/20180622203202_add_record_id_to_course_records.rb
class AddRecordIdToCourseRecords < ActiveRecord::Migration[5.1]
def change
add_column :course_records, :recid, :string
end
end
<file_sep>/db/migrate/20180919182132_create_join_table_toolbox_paperwork.rb
class CreateJoinTableToolboxPaperwork < ActiveRecord::Migration[5.1]
def change
create_join_table :toolboxes, :paperworks do |t|
# t.index [:toolbox_id, :paperwork_id]
# t.index [:paperwork_id, :toolbox_id]
end
end
end
<file_sep>/app/models/course.rb
class Course < ApplicationRecord
belongs_to :instructor
belongs_to :paperwork
# belongs_to :worker, optional: true
has_many :course_records, dependent: :destroy
has_many :workers, through: :course_records
attr_accessor :onsite
attr_accessor :existing
attr_accessor :existing_select
validate :check_address
validates_presence_of :date
validates_presence_of :expiry
validates_presence_of :enrollment
validates_presence_of :location
def check_address
if location == "On Site" && address.length < 1
errors.add(:address, "must be included for on site courses")
end
end
def name_plus_date
return self.date.strftime("%b %d, %Y") + " --> " + self.paperwork.title
end
end
<file_sep>/config/initializers/pdfkit.rb
if Rails.env.production?
PDFKit.configure do |config|
config.wkhtmltopdf = '/usr/local/bin/wkhtmltopdf'
config.default_options = {
:print_media_type => true
}
end
end<file_sep>/db/migrate/20180929165058_add_send_to_statement.rb
class AddSendToStatement < ActiveRecord::Migration[5.1]
def change
add_column :statements, :send, :boolean
end
end
<file_sep>/app/controllers/forms_controller.rb
class FormsController < ApplicationController
def new
@worker = Worker.find(params[:worker_id])
@form = @worker.forms.build
@sites = Site.all
end
def create
@worker = Worker.find(params[:worker_id])
@sites = Site.all
@form = @worker.forms.build(form_params)
if @form.save
redirect_to @worker, notice: "Form created successfully"
else
render :new
end
end
def edit
@form = Form.find(params[:id])
@sites = Site.all
@worker = Worker.find(params[:worker_id])
end
def destroy
@form = Form.find(params[:id])
@worker = Worker.find(params[:worker_id])
@form.destroy
redirect_to worker_path(@worker), notice: "#{@form.id} was deleted successfully!"
end
def update
@form = Form.find(params[:id])
@worker = Worker.find(params[:worker_id])
if @form.update_attributes(form_params)
redirect_to worker_path(@worker), notice: "form updated successfully"
else
flash[:error] = "#{@form.errors.count} errors prevented form from being updated."
render :edit
end
end
protected
def form_params
params.require(:form).permit(:site_id, :reviewed, :title, :paperwork_id)
end
end
<file_sep>/app/controllers/paperworks_controller.rb
class PaperworksController < ApplicationController
def index
@paperworks = Paperwork.all
@paperworks = @paperworks.order(:title).page(params[:page]).per(15)
end
def sjps
@SJPs = Paperwork.where(category: "SJP")
@SJPs = @SJPs.order(:critical).order(:title).page(params[:page]).per(15)
end
def swps
@SWPs = Paperwork.where(category: "SWP")
@SWPs = @SWPs.order(:title).page(params[:page]).per(15)
end
def certs
@certs = Paperwork.where(category: "Certificate")
@certs = @certs.order(:title).page(params[:page]).per(15)
end
def forms
@certs = Paperwork.where(category: "Form")
@certs = @certs.order(:title).page(params[:page]).per(15)
end
def wethesafe
@certs = Paperwork.where(category: "Wethesafe")
@certs = @certs.order(:title).page(params[:page]).per(15)
end
def show
@paperwork = Paperwork.find(params[:id])
end
def new
@paperwork = Paperwork.new
@cat = params[:cat]
end
def create
@paperwork = Paperwork.new(paperwork_params)
if @paperwork.category = "Wethesafe" && @paperwork.save
redirect_to wethesafe_paperworks_path, notice: "New Course added successfully!"
elsif @paperwork.save
redirect_to paperworks_path, notice: "paperworks Submitted successfully!"
else
flash[:error] = @paperwork.errors.full_messages.to_sentence
render :new, notice: "paperwork could not be created!"
end
end
def edit
@paperwork = Paperwork.find(params[:id])
end
def update
@paperwork = Paperwork.find(params[:id])
if @paperwork.update_attributes(paperwork_params)
redirect_to paperworks_path, notice: "paperwork updated successfully"
else
flash[:error] = "#{@paperwork.errors.count} errors prevented certificate from being updated."
render :edit
end
end
def critical
@paperwork = Paperwork.find(params[:id])
if @paperwork.critical
@paperwork.critical = false
else
@paperwork.critical = true
end
if @paperwork.save
flash[:error] = "paperwork updated successfully"
redirect_back(fallback_location: paperworks_path)
else
flash[:error] = "#{@paperwork.errors.count} errors prevented certificate from being updated."
redirect_back(fallback_location: paperworks_path)
end
end
def destroy
@paperwork = Paperwork.find(params[:id])
@paperwork.destroy
redirect_to paperworks_path, notice: "#{@paperwork.id} was deleted successfully!"
end
protected
def paperwork_params
params.require(:paperwork).permit(:id, :title, :category, :critical)
end
end
<file_sep>/test/controllers/statements_controller_test.rb
require 'test_helper'
class StatementsControllerTest < ActionDispatch::IntegrationTest
test "should get new" do
get statements_new_url
assert_response :success
end
test "should get index" do
get statements_index_url
assert_response :success
end
test "should get edit" do
get statements_edit_url
assert_response :success
end
end
<file_sep>/app/uploaders/cert_uploader.rb
class CertUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
# storage :file
storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def extension_white_list
%w(jpg jpeg gif png pdf doc docx)
end
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# def fix_exif_rotation
# manipulate! do |img|
# img.tap(&:auto_orient)
# end
# end
# def auto_orient
# manipulate! do |img|
# img = img.auto_orient
# # img = img.resize '200x200'
# end
# end
# def crop(geometry)
# manipulate! do |img|
# img.crop(geometry)
# img
# end
# end
# def resize_and_crop
# manipulate! do |image|
# if image[:width] < image[:height]
# remove = ((image[:height] - image[:width])/2).round
# image.shave("0x#{remove}")
# elsif image[:width] > image[:height]
# remove = ((image[:width] - image[:height])/2).round
# image.shave("#{remove}x0")
# end
# # image.resize("#{size}x#{size}")
# image
# end
# end
# process :auto_orient
# # process scale: [300, 300]
# process :resize_and_crop
end
<file_sep>/app/controllers/swps_controller.rb
class SwpsController < ApplicationController
def new
@worker = Worker.find(params[:worker_id])
@swp = @worker.swps.build
@swp.paperwork_id = params[:paperwork_id]
@swp.site_id = @worker.site.id if @worker.site
emp = @worker.employer
@sites = emp.sites
end
def create
@worker = Worker.find(params[:worker_id])
emp = @worker.employer
@sites = emp.sites
@swp = @worker.swps.build(swp_params)
if @swp.save
redirect_to @worker, notice: "Swp contacts created successfully"
else
render :new
end
end
def edit
@swp = Swp.find(params[:id])
@worker = Worker.find(params[:worker_id])
emp = @worker.employer
@sites = emp.sites
end
def destroy
@swp = Swp.find(params[:id])
@worker = Worker.find(params[:worker_id])
@swp.destroy
redirect_to worker_path(@worker), notice: "#{@swp.id} was deleted successfully!"
end
def update
@swp = Swp.find(params[:id])
@worker = Worker.find(params[:worker_id])
if @swp.update_attributes(swp_params)
redirect_to worker_path(@worker), notice: "swp updated successfully"
else
flash[:error] = "#{@swp.errors.count} errors prevented swp from being updated."
render :edit
end
end
protected
def swp_params
params.require(:swp).permit(:site_id,:reviewed,:title,:paperwork_id)
end
end
<file_sep>/app/controllers/course_records_controller.rb
class CourseRecordsController < ApplicationController
before_action :set_course_record, only: [:edit, :update, :destroy]
def index
@course_records = CourseRecord.all
@course_records = @course_records.order(:updated_at).reverse_order.page(params[:page]).per(15)
end
def new
@course = Course.find(current_user.current_course)
@worker = Worker.find(params[:worker_id])
@course_record = CourseRecord.new
end
def create
@course_record = CourseRecord.new(course_record_params)
@course = Course.find(current_user.current_course)
id = CourseRecord.last.id.to_i + 1
@course_record.recid = Time.now.strftime("%Y%m") + id.to_s.rjust(3, '0')
if @course_record.save
redirect_to course_confirm_path(@course), notice: "CourseRecord Created successfully!"
else
logger.info @course_record.errors.full_messages.to_sentence
# render :new, notice: "CourseRecord could not be created!"
redirect_to onsite_admin_users_path, notice: @course_record.errors.full_messages.to_sentence
end
end
def update
if @course_record.update_attributes(course_record_params)
redirect_to course_records_path, notice: "Updated successfully!"
else
flash[:error] = @course_record.errors.full_messages.to_sentence
render :edit, notice: "CourseRecord could not be updated!"
end
end
def add_workers
logger.info "XXXXXXXXXXXXX add workers"
@course_id = params[:course_id]
rejects = []
# Worker.where(id: params[:worker_ids]).update_all(site_id: params[:site_id])
Worker.where(id: params[:worker_ids]).each do |work|
id = CourseRecord.last.id.to_i + 1
recid = Time.now.strftime("%Y%m") + id.to_s.rjust(3, '0')
rec = CourseRecord.new(worker_id: work.id, course_id: @course_id, recid: recid)
if rec.save
else
rejects.push(work.worker_name)
end
end
# render "courses/show", notice: "#{@course_id} was updated successfully!"
if rejects && rejects.length > 0
rej = rejects.to_sentence
redirect_to course_path(@course_id), alert: "#{rej} are already in the course"
else
redirect_to course_path(@course_id), notice: "#{@course_id} was updated successfully!"
end
return
end
def destroy
@course_record.destroy
redirect_to course_path(@course_record.course_id), notice: "#{@course_record.id} was deleted successfully!"
end
def edit
end
private
def set_course_record
@course_record = CourseRecord.find(params[:id])
end
def course_record_params
params.require(:course_record).permit(:worker_id, :course_id, :pass)
end
end
<file_sep>/app/controllers/fallpro/fallpro_controller.rb
class Fallpro::FallproController < Fallpro::BaseFallproController
def index
@fallpros = Fallpro.all
end
def new
@fallpro = Fallpro.new
end
def edit
@fallpro = Fallpro.find(params[:id])
end
def show
@fallpro = Fallpro.find(params[:id])
end
def create
@fallpro = Fallpro.new(fallpro_params)
if @fallpro.save
redirect_to fallpro_fallpro_index_path, notice: "Fallpro plan created successfully!"
else
logger.info @fallpro.errors.full_messages.to_sentence
render :new, notice: "Fallpro plan could not be created!"
end
end
def update
if @fallpro.update_attributes(instructor_params)
redirect_to fallpro_fallpro_index_path, notice: "Updated successfully!"
else
logger.info @fallpro.errors.full_messages.to_sentence
render :edit, notice: "Fallpro plan could not be updated!"
end
end
private
def fallpro_params
params.require(:fallpro).permit(:user_id, :supervisor, :company, :add_procedures, :picture, :sketch)
end
end
<file_sep>/app/models/nyw.rb
class Nyw < ApplicationRecord
belongs_to :worker
has_many :nyw_forms, dependent: :destroy
# validates_presence_of :reviewed
# validates_presence_of :new_young
validates_presence_of :super
validates_uniqueness_of :worker_id
end
<file_sep>/app/models/permission.rb
class Permission < Struct.new(:user)
def allow?(controller, action, resource = nil)
return true if controller == "users/sessions"
return true if controller == "devise/passwords"
return false if controller == "users/registrations" && action.in?(%w[new])
return true if controller == "users/registrations"
return true if controller == "devise/sessions"
return true if controller == "pages"
return true if controller == "messages"
return true if controller == "employers" && action.in?(%w[print_cert_report])
return true if user && user.user_type == "Admin"
if user && user.user_type == "Employer"
employer = Employer.find_by(id: user.employer_id)
# worker = Worker.find_by(employer_id: employer.id)
return true if controller == "users"# && action.in?(%w[edit update])
return false if controller.in?(%w[sites]) && action.in?(%w[destroy])
return true if controller == "sites" && resource && resource.employer_id == employer.id
return true if controller == "ppes"
return true if controller == "employers" && action.in?(%w[cert_report])
return true if controller == "employers" && resource && resource.id == employer.id
return true if controller == "workers" && action.in?(%w[edit add_site])
return true if controller == "workers" && resource && resource.employer_id == employer.id
return true if controller.in?(%w[emergencies certificates orientations sjps swps violations wcbs toolboxes forms])# && resource && resource.employer_id == employer.id
# return true if user.user_type == "Admin"
elsif user && user.user_type == "Worker"
worker = Worker.find_by(user_id: user.id)
return false if controller.in?(%w[emergencies violations ]) && action.in?(%w[edit update new show])
return false if controller.in?(%w[ppes]) && action.in?(%w[edit update new])
return true if controller.in?(%w[ppes]) && action.in?(%w[show])
return true if controller.in?(%w[sjps swps certificates orientations forms]) && action.in?(%w[show])
return true if controller == "workers" && action.in?(%w[index show]) && resource && resource.user_id == user.id
return true if action.in?(%w[download_pdf]) && resource && resource.worker_id == worker.id
return true if controller == "workers" && action.in?(%w[new])
# return true if resource && resource.user_id == user.id
return true if controller == "users"# && action.in?(%w[edit update])
# return true if user.user_type == "Admin"
elsif user && user.user_type == "Prime Contractor"
prime = Prime.find_by(id: user.prime_id)
# puts "XXXXXXXXX Resource id #{resource.id } XXXXXXXXXXXX" if resource && resource.id
# puts "XXXXXXXXX Resource class #{resource.class.name } XXXXXXXXXXXX" if resource && resource.id
# puts "XXXXXXXXX Resource id #{resource.employer_id == prime.employer_id } XXXXXXXXXXXX" if resource && resource.id
return false if controller.in?(%w[ppes]) && action.in?(%w[edit update new])
return false if controller.in?(%w[sites]) && action.in?(%w[destroy])
return true if controller.in?(%w[ppes]) && action.in?(%w[show])
return true if controller == "workers" && action.in?(%w[add_site])
return true if controller == "workers" && resource && resource.employer_id == prime.employer_id
return true if controller == "users"
return true if controller == "sites"
return true if controller == "primes" && resource && resource.id == prime.id
return true if controller == "workers" && action.in?(%w[index show])
return true if controller.in?(%w[emergencies certificates orientations]) && action.in?(%w[index show])
return true if controller == "employers" && resource && resource.id == prime.employer_id
elsif user
return true if controller == "users"# && action.in?(%w[edit update])
end
false
end
end<file_sep>/db/migrate/20180929224301_add_fields_to_message.rb
class AddFieldsToMessage < ActiveRecord::Migration[5.1]
def change
add_column :messages, :phone, :string
add_column :messages, :course, :string
add_column :messages, :worker, :string
add_column :messages, :employer, :string
end
end
<file_sep>/app/models/form.rb
class Form < ApplicationRecord
belongs_to :worker
belongs_to :paperwork
belongs_to :site
end
<file_sep>/db/migrate/20180613001220_create_courses.rb
class CreateCourses < ActiveRecord::Migration[5.1]
def change
create_table :courses do |t|
t.references :instructor, foreign_key: true
t.references :paperwork, foreign_key: true
t.string :location
t.string :type
t.date :date
t.date :expiry
t.timestamps
end
end
end
<file_sep>/db/migrate/20180620172719_remove_worker_from_courses.rb
class RemoveWorkerFromCourses < ActiveRecord::Migration[5.1]
def change
remove_index :courses, name: :index_courses_on_worker_id
# remove_column :courses, :worker
end
end
<file_sep>/db/migrate/20180428175957_add_primes_to_site.rb
class AddPrimesToSite < ActiveRecord::Migration[5.1]
def change
add_reference :sites, :prime, foreign_key: true
end
end
<file_sep>/app/controllers/statements_controller.rb
class StatementsController < ApplicationController
before_action :set_statement, only: [:edit, :update, :destroy]
def index
@statements = Statement.all.joins(:employer).order('statements.list, employers.name')
end
def new
@statement = Statement.new
end
def create
@statement = Statement.new(statement_params)
if @statement.save
redirect_to statements_path, notice: "Statement Created successfully!"
else
logger.info @statement.errors.full_messages.to_sentence
render :new, notice: "Statement could not be created!"
end
end
def update
if @statement.update_attributes(statement_params)
redirect_to statements_path, notice: "Updated successfully!"
else
logger.info @statement.errors.full_messages.to_sentence
render :edit, notice: "Statement could not be updated!"
end
end
def send_reports
logger.info "XXXXXXXXXXXX Send Reports Working........."
Statement.all.each do |emp|
logger.info "Sending email to #{emp.employer.name}........."
MainMailer.certs_report(emp).deliver if emp.list
end
redirect_to statements_path, notice: "Emails sent"
end
def destroy
@statement.destroy
redirect_to statements_path, notice: "#{@statement.id} was deleted successfully!"
end
def get_email_list
# respond_to do |format|
# format.json {
# @employer = Employer.find(params[:employer_id])
# emp = User.all.where(employer_id:@employer.id).where(user_type: "Employer")
# render json: {emp: emp}
# }
# end
@employer = Employer.find(params[:employer_id])
@emp = User.all.where(employer_id:@employer.id).where(user_type: "Employer")
end
def edit
end
private
def set_statement
@statement = Statement.find(params[:id])
end
def statement_params
params.require(:statement).permit(:employer_id, :email, :list, :typed_email)
end
end
<file_sep>/app/controllers/admin/sites_controller.rb
class Admin::SitesController < Admin::BaseAdminController
helper_method :sort_column, :sort_direction
before_action :set_site, only: [:show, :edit, :update, :destroy]
def index
@sites = Site.all
# @sites = @sites.order(:updated_at).reverse_order.page(params[:page]).per(15)
if sort_column == "employers"
@sites = @sites.joins(:employers).group(:id).order("COUNT(employers) #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "prime"
@sites = @sites.joins(:prime).order("id #{sort_direction}").page(params[:page]).per(15)
elsif sort_column == "workers"
@sites = @sites.joins(:workers).group(:id).order("COUNT(workers) #{sort_direction}").page(params[:page]).per(15)
else
@sites = @sites.order("#{sort_column} #{sort_direction}").page(params[:page]).per(15)
end
end
# GET /sites/1
def show
end
# GET /sites/new
def new
@site = Site.new
end
# GET /sites/1/edit
def edit
end
# POST /sites
def create
@site = Site.new(site_params)
if @site.save
redirect_to admin_sites_path, notice: "Site Created successfully!"
else
flash[:error] = @site.errors.full_messages.to_sentence
render :new, notice: "Site could not be created!"
end
end
# PATCH/PUT /sites/1
# PATCH/PUT /sites/1.json
def update
if @site.update_attributes(site_params)
redirect_to admin_sites_path, notice: "Site Updated successfully!"
else
flash[:error] = @site.errors.full_messages.to_sentence
render :new, notice: "Site could not be updated!"
end
end
# DELETE /sites/1
# DELETE /sites/1.json
def destroy
@site.destroy
redirect_to admin_sites_path, notice: "#{@site.id} was deleted successfully!"
end
private
# Use callbacks to share common setup or constraints between actions.
def set_site
@site = Site.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def site_params
params.require(:site).permit(:name, :site_id, :prime_id, :location,{employer_ids: []})
end
def current_resource
@current_resource ||= Site.find(params[:id]) if params[:id]
end
def sort_column
params[:column] ? params[:column] : "updated_at"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end
<file_sep>/app/models/message.rb
class Message < ApplicationRecord
validates :name, :email, :body, presence: true
# attr_accessor :phone
# attr_accessor :course
# attr_accessor :worker
# attr_accessor :employer
end
<file_sep>/app/models/instructor.rb
class Instructor < ApplicationRecord
belongs_to :employer
has_many :certificates
has_many :courses
mount_uploader :signature, CertUploader
def instructor_name
return self.firstname + " " + self.lastname
end
end
<file_sep>/app/mailers/main_mailer.rb
class MainMailer < ApplicationMailer
def sample_email(user)
@user = user
mail(to: @user.email, subject: 'Sample Email')
end
def contact_me(message)
@greeting = "Hi"
@body = message.body
@email = message.email
@name = message.name
mail to: "<EMAIL>", from: "<EMAIL>"
end
def training(message)
@greeting = "Hi"
@body = message.body
@email = message.email
@name = message.name
@employer = Employer.find(message.employer)
@course = Certificate.find(message.course)
@worker = Worker.find(message.worker)
@phone = message.phone
mail to: "<EMAIL>", from: "<EMAIL>"
end
def certs_report(emp)
@employer = Employer.find(emp.employer_id)
mail to: emp.email, from: "<EMAIL>"
end
end
<file_sep>/app/models/orientation.rb
class Orientation < ApplicationRecord
belongs_to :site
belongs_to :worker
validates_presence_of :date
validates_presence_of :site_id
end
<file_sep>/db/migrate/20180929170528_add_list_to_statement.rb
class AddListToStatement < ActiveRecord::Migration[5.1]
def change
add_column :statements, :list, :boolean
end
end
<file_sep>/app/controllers/wcb_sections_controller.rb
class WcbSectionsController < ApplicationController
def index
@sections = WcbSection.all
@sections = @sections.order(:number).page(params[:page]).per(15)
end
def show
@section = WcbSection.find(params[:id])
end
def new
@section = WcbSection.new
end
def create
@section = WcbSection.new(section_params)
if @section.save
redirect_to admin_root_path, notice: "sections Submitted successfully!"
else
flash[:error] = @section.errors.full_messages.to_sentence
render :new, notice: "section could not be created!"
end
end
def edit
@section = WcbSection.find(params[:id])
end
def update
@section = WcbSection.find(params[:id])
if @section.update_attributes(section_params)
redirect_to admin_root_path, notice: "section updated successfully"
else
flash[:error] = "#{@section.errors.count} errors prevented certificate from being updated."
render :edit
end
end
def destroy
@section = WcbSection.find(params[:id])
@section.destroy
redirect_to wcb_sections_path, notice: "#{@section.id} was deleted successfully!"
end
protected
def section_params
params.require(:wcb_section).permit(:id, :title, :number)
end
end
<file_sep>/app/models/wcb_section.rb
class WcbSection < ApplicationRecord
has_and_belongs_to_many :wcbs
validates_uniqueness_of :number
validates_presence_of :title
def number_title
"#{number}. #{title}"
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
namespace :admin do
resources :dashboard, only: [:landing] do
get 'download', :on => :collection
end
get 'mailer(/:action(/:id(.:format)))' => 'mailer#:action'
# root to: "/admin/dashboard#landing"
root to: "/admin/dashboard#landing"
# devise_for :users
devise_scope :user do
resources :users do
collection do
get :onsite
end
end
end
resources :users, only: [:new, :create, :edit, :update, :index, :destroy]
resources :workers, only: [:new, :create, :edit, :update, :index, :destroy] do
get 'site', :on => :collection
get 'onsite', :on => :collection
end
resources :employers, only: [:new, :create, :edit, :update, :index, :destroy] do
get 'site', :on => :collection
end
resources :primes, only: [:new, :create, :edit, :update, :index, :destroy]
resources :sites, only: [:new, :create, :edit, :update, :index, :destroy]
end
## End of Admin
namespace :fallpro do
resources :fallpro
end
## End of FallPro
resources :primes, only: [:show, :new, :create, :edit, :update, :index, :destroy] do
resources :sites
get :my_workers
get :my_sites
get :my_employers
get :my_sites_workers
end
# devise_for :users
resources :employers do
resources :sites
resources :wcbs
resources :toolboxes
get :my_workers
get :my_sites
get :my_sites_workers
get :my_wcbs
get :my_sjps
get :my_certs
get :cert_report
get :pdfs
get :violations
get :worksafe
get :workers
get :certificates
get :add_workers
post :chart_link, :on => :collection
post :certs_chart_link, :on => :collection
post :viol_chart_link, :on => :collection
get :print_cert_report, :on => :collection
end
resources :roles, only: [:new, :create, :edit, :update, :index, :destroy]
resources :wcb_sections
resources :wcbs
resources :instructors
resources :statements do
get :send_reports, :on => :collection
get :get_email_list, :on => :collection
end
resources :pdfs do
get :employers, :on => :collection
end
resources :toolboxes do
get :add_workers, :on => :collection
put :worker_data, :on => :collection
end
resources :courses do
get :autocomplete_employer_name, :on => :collection
get :download_pdf
get :pdf_cert
get :confirm
get :workers
collection do
get :onsite
get :auth
put :auth_check
get :existing
put :existing_check
put :pass
end
end
resources :course_records do
collection do
put :add_workers
end
end
resources :paperworks, only: [:new, :create, :edit, :update, :index, :destroy] do
get :sjps, :on => :collection
get :swps, :on => :collection
get :certs, :on => :collection
get :forms, :on => :collection
get :wethesafe, :on => :collection
member do
get :critical
end
end
resources :workers do
resources :emergencies
resources :certificates
resources :orientations
resources :sjps
resources :swps
resources :forms
resources :violations
resources :ppes
resources :nyws do
resources :nyw_forms
end
get :generate_qr
get :download_pdf
get :pdf_cert
collection do
put :add_site
put :qr_export
get :csv_export
post :csv_import
get :csv_export_course
get :all_export_course
get :data_export
get :data_export_test
end
end
# root to: 'users/sessions#new_user_session_path'
devise_scope :user do
root to: "devise/sessions#new"
end
resources :messages, only: [:new, :create] do
get :training, :on => :collection
end
devise_for :users, controllers: {
sessions: 'users/sessions',
registrations: 'users/registrations',
}
# root to: "devise/sessions#new"
get "/pages/:page" => "pages#show"
end
<file_sep>/db/migrate/20180319230425_create_workers.rb
class CreateWorkers < ActiveRecord::Migration[5.1]
def change
create_table :workers do |t|
t.string :firstname
t.string :lastname
t.date :startdate
t.string :role
t.string :picture
t.text :notes
t.text :allergies
t.text :med_conditions
t.text :medications
t.string :med_location
t.references :employer, foreign_key: true
t.timestamps
end
end
end
<file_sep>/db/migrate/20180426170027_add_critical_to_paperworks.rb
class AddCriticalToPaperworks < ActiveRecord::Migration[5.1]
def change
add_column :paperworks, :critical, :boolean
end
end
<file_sep>/db/migrate/20180919182013_create_join_table_toolbox_worker.rb
class CreateJoinTableToolboxWorker < ActiveRecord::Migration[5.1]
def change
create_join_table :toolboxes, :workers do |t|
# t.index [:toolbox_id, :worker_id]
# t.index [:worker_id, :toolbox_id]
end
end
end
<file_sep>/app/controllers/sjps_controller.rb
class SjpsController < ApplicationController
def new
@worker = Worker.find(params[:worker_id])
@sjp = @worker.sjps.build
@sjp.paperwork_id = params[:paperwork_id]
@sjp.site_id = @worker.site.id if @worker.site
emp = @worker.employer
@sites = emp.sites
end
def create
@worker = Worker.find(params[:worker_id])
emp = @worker.employer
@sites = emp.sites
@sjp = @worker.sjps.build(sjp_params)
if @sjp.save
redirect_to @worker, notice: "Sjp contacts created successfully"
else
render :new
end
end
def edit
@sjp = Sjp.find(params[:id])
@worker = Worker.find(params[:worker_id])
emp = @worker.employer
@sites = emp.sites
end
def destroy
@sjp = Sjp.find(params[:id])
@worker = Worker.find(params[:worker_id])
@sjp.destroy
redirect_to worker_path(@worker), notice: "#{@sjp.id} was deleted successfully!"
end
def update
@sjp = Sjp.find(params[:id])
@worker = Worker.find(params[:worker_id])
if @sjp.update_attributes(sjp_params)
redirect_to worker_path(@worker), notice: "sjp updated successfully"
else
flash[:error] = "#{@sjp.errors.count} errors prevented sjp from being updated."
render :edit
end
end
protected
def sjp_params
params.require(:sjp).permit(:site_id,:reviewed,:title, :paperwork_id)
end
end
<file_sep>/db/migrate/20180502000912_create_nyws.rb
class CreateNyws < ActiveRecord::Migration[5.1]
def change
create_table :nyws do |t|
t.boolean :new_young
t.date :reviewed
t.date :complete
t.references :worker, foreign_key: true
t.string :super
t.timestamps
end
end
end
<file_sep>/db/migrate/20180515010150_create_ppes.rb
class CreatePpes < ActiveRecord::Migration[5.1]
def change
create_table :ppes do |t|
t.references :worker, foreign_key: true
t.string :item
t.boolean :yes
t.string :id_no
t.string :notes
t.date :last_inspection
t.string :inspection_notes
t.date :next_inspection
t.timestamps
end
end
end
<file_sep>/test/controllers/course_records_controller_test.rb
require 'test_helper'
class CourseRecordsControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get course_records_index_url
assert_response :success
end
test "should get edit" do
get course_records_edit_url
assert_response :success
end
test "should get new" do
get course_records_new_url
assert_response :success
end
end
<file_sep>/app/controllers/ppes_controller.rb
class PpesController < ApplicationController
def new
@worker = Worker.find(params[:worker_id])
@ppe = @worker.ppes.build
end
def create
@worker = Worker.find(params[:worker_id])
@ppe = @worker.ppes.build(ppe_params)
if @ppe.save
redirect_to @worker, notice: "Ppe contacts created successfully"
else
render :new
end
end
def edit
@ppe = Ppe.find(params[:id])
@worker = Worker.find(params[:worker_id])
end
def destroy
@ppe = Ppe.find(params[:id])
@worker = Worker.find(params[:worker_id])
@ppe.destroy
redirect_to worker_path(@worker), notice: "#{@ppe.id} was deleted successfully!"
end
def update
@ppe = Ppe.find(params[:id])
@worker = Worker.find(params[:worker_id])
if @ppe.update_attributes(ppe_params)
redirect_to worker_path(@worker), notice: "ppe updated successfully"
else
flash[:error] = "#{@ppe.errors.count} errors prevented ppe from being updated."
render :edit
end
end
protected
def ppe_params
params.require(:ppe).permit(:worker_id, :item, :yes, :id_no, :notes, :last_inspection, :inspection_notes, :next_inspection)
end
end
<file_sep>/db/migrate/20180531061012_create_join_table_eployer_site.rb
class CreateJoinTableEployerSite < ActiveRecord::Migration[5.1]
def change
create_join_table :employers, :sites do |t|
# t.index [:employer_id, :site_id]
# t.index [:site_id, :employer_id]
end
end
end
<file_sep>/db/migrate/20180419211800_add_paperwork_to_certificates.rb
class AddPaperworkToCertificates < ActiveRecord::Migration[5.1]
def change
add_reference :certificates, :paperwork, foreign_key: true
end
end
<file_sep>/app/controllers/admin/dashboard_controller.rb
class Admin::DashboardController < Admin::BaseAdminController
def landing
@users = User.all
@users = @users.order(:updated_at).reverse_order.page(params[:page]).per(15)
end
def download
@employers = Employer.all
@sites = Site.all
@employer_filter = params[:filter_employer]
@site_filter = params[:filter_site]
if params[:search]
@workers_all = Worker.search(params[:search]).order(:firstname)
else
@workers_all = Worker.filter(params[:filter_employer], params[:filter_site]).order(:firstname)
end
end
def reports
@employers = Employer.all
end
end
|
89cbdb6d5489e90025a2e3ccddd47d7fb8b8c2ec
|
[
"Ruby"
] | 111
|
Ruby
|
ngust/wethesafe
|
d2db24eecd2af686f6f860b64daba52fc0c59767
|
ad6d50579de9853be75c41147e3987a47a7a07ce
|
refs/heads/master
|
<repo_name>UnaiUrti/EDE_UnaiUrtiaga<file_sep>/EjemploGit/src/paquete/Si.java
package paquete;
/**
*
* @author Unai
* @version 1.1
* @since 2021/05/07
*
*/
public class Si {
/**
* aqui va la descripcion de metodo
* @param var1 aqui va la descripcion de la variable var1
* @param var2 aqui va la descripcion de la variable var2
* @returna aqui va la descripcion de lo que devuelve el metodo
*/
public boolean nombreMetodo (int var1, boolean var2) {
return false;}
//Steven hermoso
}
|
849edd24d666c46ce81e7ffb7cc8d138c32778c9
|
[
"Java"
] | 1
|
Java
|
UnaiUrti/EDE_UnaiUrtiaga
|
961b4a1aefd1292b2cca95f512ab341c41df978a
|
cadb8ee8d47aa2ce3f809a974a0d1bc294c279bf
|
refs/heads/master
|
<repo_name>online6731/whoknows-data-manager-web<file_sep>/src/app/_models/Dataset.ts
import { ObjectId } from './ObjectId';
export class Dataset {
_id: ObjectId;
headers: {
name: string;
} = {
name: ''
};
fields: {} = {};
}
<file_sep>/src/app/_models/TemplateNewResponse.ts
import { Template } from './Template';
export class TemplateNewResponse {
ok: Boolean
problem: String
template: Template
}<file_sep>/src/app/_models/Resource.ts
import { ObjectId } from './ObjectId';
export class Resource {
_id: ObjectId;
headers: {
name: string;
type: string;
base: string;
id_resource: string;
id_pattern: string;
} = {
name: '',
type: '',
base: '',
id_resource: '',
id_pattern: '',
};
getters: {} = {};
// getters: {
// name: string;
// xpath: string;
// select: string;
// replace: string[]
// };
}
<file_sep>/src/app/_services/data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { DataFindResponse } from '../_models/DataFindResponse';
import { retry } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(
private http: HttpClient
) { }
dataFind(compact: boolean = true, condition: any = {}): Observable<DataFindResponse> {
return this.http.post<DataFindResponse>(`http://dms.whoknows.ir/data/find`, { compact, condition });
// .pipe(retry(3));
}
}
<file_sep>/src/app/template/template.component.ts
import { COMMA, ENTER } from '@angular/cdk/keycodes';
import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
import { Template } from '../_models/Template';
import { TemplateService } from '../_services/template.service';
import { MatSnackBar, MatAutocompleteSelectedEvent, MatAutocomplete, MatChipInputEvent } from '@angular/material';
import { startWith, map } from 'rxjs/operators';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { Tag } from '../_models/Tag';
import { Dataset } from '../_models/Dataset';
import { DatasetService } from '../_services/dataset.service';
import { TagService } from '../_services/tag.service';
@Component({
selector: 'app-template',
templateUrl: './template.component.html',
styleUrls: ['./template.component.styl']
})
export class TemplateComponent implements OnInit {
constructor(
private templateService: TemplateService,
private snackBar: MatSnackBar,
private datasetService: DatasetService,
private tagService: TagService
) { }
@Input() template: Template;
fields = [];
allTags: Tag[] = [];
allDatasets: Dataset[] = [];
problems: string[] = [];
defaultField = {
type: '&&choose',
section: 'title',
format: 'text',
language: 'persian',
content: ''
};
newField = { ...this.defaultField };
ngOnInit() {
this.fields = [];
this.getAllDatasets();
this.getAllTags();
}
ngOnChanges() {
console.log(this.template);
this.showTemplate();
this.problems = [];
Object.keys(this.template.__test_info).forEach(key => {
this.problems = [...this.problems, ...this.template.__test_info[key].problems];
});
}
sortNull() { }
getAllDatasets() {
this.datasetService.datasetFind().subscribe((body) => {
if (body.ok) {
this.allDatasets = body.datasets;
console.log(body);
} else {
console.log(body);
}
});
}
getAllTags() {
this.tagService.tagFind().subscribe((body) => {
if (body.ok) {
this.allTags = body.tags;
} else {
console.log(body);
}
});
}
showTemplate() {
this.fields = [];
Object.keys(this.template).filter((key) => key.startsWith('&&')).forEach(type => {
Object.keys(this.template[type]).forEach(section => {
Object.keys(this.template[type][section]).forEach(format => {
Object.keys(this.template[type][section][format]).forEach(index => {
this.fields.push({
type, section, format,
content: this.template[type][section][format][index], language: 'persian'
});
});
});
});
});
return this.fields;
}
removeFromList(list: any[], value: any) {
if (list.indexOf(value) !== -1) {
list.splice(list.indexOf(value), 1);
}
console.log(list);
}
addToList(list: any[], value: any) {
list.push(value);
}
removeFromObject(object: any, key: any) {
try {
delete object[key];
} catch (error) {
console.error(error);
}
}
addToObject(object: any, key: any, value: any) {
object[key] = value;
}
addFieldToTemplate(field: any) {
if (!(field.type in this.template)) {
this.template[field.type] = {};
}
if (!(field.section in this.template[field.type])) {
this.template[field.type][field.section] = {};
}
if (!(field.format in this.template[field.type][field.section])) {
this.template[field.type][field.section][field.format] = [];
}
this.template[field.type][field.section][field.format].push(field.content);
this.newField = { ...this.defaultField };
this.ngOnChanges();
}
removeFieldFromTemplate(newField: any) {
try {
delete this.template[newField.type][newField.section][newField.format];
} catch (error) {
console.error(error);
}
}
testTemplate(template: Template) {
this.templateService.templateTest(template).subscribe((body) => {
if (body.ok === true) {
this.template = body.template;
} else {
}
console.log(this.template);
});
}
}
<file_sep>/src/app/_models/DatasetFindResponse.ts
import { Dataset } from './Dataset';
export class DatasetFindResponse {
ok: boolean;
problems: string[];
datasets: Dataset[];
}
<file_sep>/src/app/_services/tag.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { TagFindResponse } from '../_models/TagFindResponse';
@Injectable({
providedIn: 'root'
})
export class TagService {
constructor(
private http: HttpClient
) { }
tagFind(
option: { compact: boolean; condition: any } = {
compact: false,
condition: {}
}
): Observable<TagFindResponse> {
return this.http.post<TagFindResponse>(
`http://server.whoknows.ir/tag/find`,
{ compact: option.compact, condition: option.condition }
);
}
}
<file_sep>/src/app/main/main.component.ts
import { Component, OnInit } from '@angular/core';
import { Dataset } from '../_models/Dataset';
import { Resource } from '../_models/Resource';
import { DatasetService } from '../_services/dataset.service';
import { DataService } from '../_services/data.service';
import { ResourceService } from '../_services/resource.service';
import { Data } from '../_models/Data';
import { TemplateService } from '../_services/template.service';
import { Template } from '../_models/Template';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.styl']
})
export class MainComponent implements OnInit {
resources: Resource[] = [];
datasets: Dataset[] = [];
datas: Data[] = [];
templates: Template[] = [];
testStatus: string;
showingItem: Data | Dataset | Resource | Template;
showingItemType: string;
newGetter = {
name: '',
xpath: '',
select: '',
replace: ['', '']
};
constructor(
private resourceService: ResourceService,
private datasetService: DatasetService,
private dataService: DataService,
private templateService: TemplateService
) { }
ngOnInit() {
this.show('template');
this.updateResources();
this.updateDatasets();
this.updateDatas();
this.updateTemplates();
}
updateResources() {
this.resourceService.resourceFind().subscribe((body) => {
if (body.ok) {
this.resources = body.resources;
} else {
console.log(body);
}
this.updateResources();
});
}
updateDatasets() {
this.datasetService.datasetFind().subscribe((body) => {
if (body.ok) {
this.datasets = body.datasets;
} else {
console.log(body);
}
this.updateDatasets();
});
}
updateDatas() {
this.dataService.dataFind(false).subscribe((body) => {
if (body.ok) {
this.datas = body.datas;
} else {
console.log(body);
}
this.updateDatas();
});
}
updateTemplates() {
this.templateService.templateFind().subscribe((body) => {
if (body.ok) {
this.templates = body.templates;
} else {
console.log(body);
}
this.show('template', this.templates[0]);
// this.updateTemplates();
});
}
show(type: string, item: Data | Dataset | Resource | Template = null) {
if (item == null) {
item = type === 'data' ? new Data() :
type === 'dataset' ? new Dataset() :
type === 'resource' ? new Resource() :
type === 'template' ? new Template() :
null;
}
this.showingItem = item;
this.showingItemType = type;
}
}
<file_sep>/src/app/_models/DataFindResponse.ts
import { Data } from './Data';
export class DataFindResponse {
ok: boolean;
problems: string[];
datas: Data[];
}
<file_sep>/src/app/_models/Tag.ts
import { ObjectId } from './ObjectId';
export class Tag {
_id: ObjectId
title: string
persianTitle: string
}<file_sep>/src/app/_models/TemplateFindResponse.ts
import { Template } from '../_models/Template'
export class TemplateFindResponse {
ok : Boolean
problem : String
templates : Template[]
}<file_sep>/src/app/_services/dataset.service.ts
import { Injectable } from "@angular/core";
import { DatasetFindResponse } from "../_models/DatasetFindResponse";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { Resource } from "../_models/Resource";
import { DatasetTestResponse } from "../_models/DatasetTestResponse";
import { Dataset } from "../_models/Dataset";
@Injectable({
providedIn: "root"
})
export class DatasetService {
constructor(private http: HttpClient) { }
datasetFind(
option: { compact: boolean; condition: any } = {
compact: false,
condition: {}
}
): Observable<DatasetFindResponse> {
return this.http.post<DatasetFindResponse>(
`http://dms.whoknows.ir/dataset/find`,
{ compact: option.compact, condition: option.condition }
);
}
datasetTest(dataset: Dataset): Observable<DatasetTestResponse> {
return this.http.post<DatasetTestResponse>(
`http://dms.whoknows.ir/dataset/test`,
{ dataset }
);
}
}
<file_sep>/src/app/_models/TagFindResponse.ts
import { Tag } from './Tag';
export class TagFindResponse {
ok: boolean;
problems: [];
tags: Tag[];
}
<file_sep>/src/app/_models/DatasetTestResponse.ts
export class DatasetTestResponse {
ok: boolean;
problems: [];
}
<file_sep>/src/app/_services/template.service.ts
import { Injectable } from '@angular/core';
import { TemplateFindResponse } from '../_models/TemplateFindResponse';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { TemplateNewResponse } from '../_models/TemplateNewResponse';
import { TemplateTestResponse } from '../_models/TemplateTestResponse';
import { Template } from '../_models/Template';
@Injectable({
providedIn: 'root'
})
export class TemplateService {
constructor(
private http: HttpClient
) { }
templateFind(compact: boolean = false, condition: any = {}): Observable<TemplateFindResponse> {
return this.http.post<TemplateFindResponse>(`http://tms.whoknows.ir/template/find`, { compact, condition });
}
templateNew(): Observable<TemplateNewResponse> {
return this.http.post<TemplateNewResponse>(`http://tms.whoknows.ir/template/new`, { idea: 'idea of template' });
}
templateTest(template: Template): Observable<TemplateTestResponse> {
return this.http.post<TemplateTestResponse>(`http://tms.whoknows.ir/template/test_save`, { template });
}
}
<file_sep>/src/app/_services/resource.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { ResourceFindResponse } from '../_models/ResourceFindResponse';
import { ResourceTestResponse } from '../_models/ResourceTestResponse';
import { Resource } from '../_models/Resource';
import { ResourceGenerateResponse } from '../_models/ResourceGenerateResponse';
@Injectable({
providedIn: 'root'
})
export class ResourceService {
constructor(
private http: HttpClient,
) { }
resourceFind(compact: boolean = false, condition: any = {}): Observable<ResourceFindResponse> {
return this.http.post<ResourceFindResponse>(`http://dms.whoknows.ir/resource/find`, { compact, condition });
}
resourceTest(resource: Resource): Observable<ResourceTestResponse> {
return this.http.post<ResourceTestResponse>(`http://dms.whoknows.ir/resource/test`, { resource });
}
resourceGenerate(resource: Resource): Observable<ResourceGenerateResponse> {
return this.http.post<ResourceGenerateResponse>(`http://dms.whoknows.ir/resource/generate`, { resource });
}
}
<file_sep>/src/app/_models/Field.ts
export class Field {
type = '';
format = '';
section = '';
language = '';
content = '';
}
<file_sep>/src/app/_models/ResourceTestResponse.ts
import { Resource } from './Resource';
export class ResourceTestResponse {
ok: boolean;
problems: string[];
status: string;
}
<file_sep>/src/app/_models/Template.ts
import { Tag } from './Tag';
import { ObjectId } from './ObjectId';
import { Dataset } from './Dataset';
class X {
text: string[] = [];
audio: string[] = [];
video: string[] = [];
image: string[] = [];
}
export class Template {
_id: ObjectId;
values: any = {};
__idea: string = '';
'&&choose': X;
'&&select': X;
'&&write': X;
'&&bool': X;
tags: Tag[] = [];
usage: string[] = [];
'score_function': string = '';
'time_function': string = '';
'__state': string = 'acceptance';
'__test_info' = {
acceptance: {
ok: false,
problems: []
},
data: {
ok: false,
problems: []
},
duplication: {
ok: false,
problems: []
},
generation: {
ok: false,
problems: []
},
manual: {
ok: false,
problems: []
},
structure: {
ok: false,
problems: []
},
usage_tagging: {
ok: false,
problems: []
}
};
datasets: Dataset[] = [];
}
<file_sep>/src/app/dataset/dataset.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { DatasetService } from '../_services/dataset.service';
import { Dataset } from '../_models/Dataset';
@Component({
selector: 'app-dataset',
templateUrl: './dataset.component.html',
styleUrls: ['./dataset.component.styl']
})
export class DatasetComponent implements OnInit {
@Input()datasetName: string;
@Input()dataset: Dataset;
constructor(
private datasetService: DatasetService
) { }
ngOnInit() {
}
addField(newFieldName: string, newFieldPattern: string) {
this.dataset.fields[newFieldName] = {
pattern: newFieldPattern
};
}
testDataset(dataset: Dataset) {
this.datasetService.datasetTest(dataset).subscribe((body) => {
if (body.ok) {
} else {
console.log(body);
}
});
}
}
<file_sep>/src/app/resource/resource.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Resource } from '../_models/Resource';
import { ResourceService } from '../_services/resource.service';
@Component({
selector: 'app-resource',
templateUrl: './resource.component.html',
styleUrls: ['./resource.component.styl']
})
export class ResourceComponent implements OnInit {
@Input() resourceName: string;
@Input() resource: Resource;
constructor(
private resourceService: ResourceService
) { }
ngOnInit() { }
addGetter(
newGetterName: string,
newGetterXpath: string,
newGetterSelect: string,
newGetterReplace: string
) {
this.resource.getters[newGetterName] = {
xpath: newGetterXpath,
select: newGetterSelect,
replace: newGetterReplace
};
}
deleteGetter(
getterKey: string
) {
delete this.resource.getters[getterKey];
}
testResource(resource: Resource) {
this.resourceService.resourceTest(resource).subscribe((body) => {
if (body.ok) {
// this.testStatus = body.status;
} else {
console.log(body);
}
});
}
}
|
a04cb6df8ec9faf345b70ae0187378de94797a08
|
[
"TypeScript"
] | 21
|
TypeScript
|
online6731/whoknows-data-manager-web
|
2d1c48bf071cb3c542251ded0c612a69720cbe89
|
d9a1eac4b55098a99005cee597b60337bf705c62
|
refs/heads/master
|
<file_sep>"use strict"
import axios from 'axios';
export function getCart(){
return function(dispatch){
axios.get('/api/cart')
.then(function(response){
dispatch({
type: "GET_CART",
payload: response.data
})
})
.catch(function(err){
console.log('ERROR: Error fetching cart from sessions');
dispatch({
type: "GET_CART_REJECTED",
payload: "ERROR: Error fetching cart from sessions"
})
})
}
}
export function addToCart(cart){
return function(dispatch){
axios.post('/api/cart', cart)
.then(function(response){
dispatch({
type: "ADD_TO_CART",
payload: response.data
})
})
.catch(function(err){
console.log('Error while adding book to cart: ' + err);
dispatch({
type: "ADD_TO_CART_REJECTED",
payload: 'Error when adding to cart'
})
})
}
}
export function deleteCartItem(_id, cart){
const currentCart = cart;
function findCartItemToDelete(book){
return book._id === _id;
}
const indexToDelete = currentCart.findIndex(findCartItemToDelete);
var cartUpdate = [...currentCart.slice(0,indexToDelete),...currentCart.slice(indexToDelete+1)];
return function(dispatch){
axios.post('/api/cart', cartUpdate)
.then(function(response){
dispatch({
type: "DELETE_CART_ITEM",
payload: cartUpdate
})
})
.catch(function(err){
dispatch({
type: "DELETE_CART_ITEM_REJECTED",
payload: 'Error when deleting from cart'
})
})
}
/*
return {
type: "DELETE_CART_ITEM",
payload: _id
}*/
}
export function updateCartItem(_id, decinc, cart){
const cartListToUpdate = cart;
function findCartItem(book){
return book._id === _id;
}
const indexToUpdate = cartListToUpdate.findIndex(findCartItem);
var newQuantity;
if(decinc == "+"){
newQuantity = cartListToUpdate[indexToUpdate].quantity+1;
}
else{
if(cartListToUpdate[indexToUpdate].quantity>1){
newQuantity = cartListToUpdate[indexToUpdate].quantity-1;
}else{
newQuantity = 1;
}
}
const newCartItemToUpdate = {
...cartListToUpdate[indexToUpdate],
quantity: newQuantity
};
let cartUpdate = [...cartListToUpdate.slice(0,indexToUpdate), newCartItemToUpdate, ...cartListToUpdate.slice(indexToUpdate+1)];
return function(dispatch){
axios.post('/api/cart', cartUpdate)
.then(function(response){
dispatch({
type: "UPDATE_CART_ITEM",
payload: cartUpdate
})
})
.catch(function(err){
dispatch({
type: "UPDATE_CART_ITEM_REJECTED",
payload: 'Error when updating to cart'
})
})
}
/* return {
type: "UPDATE_CART_ITEM",
payload: stateCart
} */
}
export function grandTotalUpdate(){
return {
type: "TOTAL_CART_ITEM",
payload: []
}
}<file_sep>
"use strict"
export function cartReducers(state={cart:[], cartAmt:[], cartQty:[]}, action){
switch(action.type){
case "GET_CART":
/*
console.log(action.payload == "");
if(action.payload != ""){
state = {cart:[action.payload.cart], cartAmt:[...state.cartAmt], cartQty:[...state.cartQty]};
}else{
state={cart:[], cartAmt:[], cartQty:[]};
}
return state;
*/
if (action.payload != ""){
state = {cart:action.payload, cartAmt:[...state.cartAmt], cartQty:[...state.cartQty]};
}else{
state={cart:[], cartAmt:[], cartQty:[]};
}
var sum = 0;
var qty = 0;
for (var i=0; i<state.cart.length; i++){
sum = sum + state.cart[i].price*state.cart[i].quantity;
qty = qty + state.cart[i].quantity;
}
state = {cart:[...state.cart], cartAmt:[sum], cartQty:[qty]}
return state;
break;
case "ADD_TO_CART":
state = {cart:action.payload, cartAmt:[...state.cartAmt], cartQty:[...state.cartQty]};
var sum = 0;
var qty = 0;
for (var i=0; i<state.cart.length; i++){
sum = sum + state.cart[i].price*state.cart[i].quantity;
qty = qty + state.cart[i].quantity;
}
state = {cart:[...state.cart], cartAmt:[sum], cartQty:[qty]}
return state;
break;
case "DELETE_CART_ITEM":
/*
const currentCart = [...state.cart];
function findCartItemToDelete(cart){
return cart._id === action.payload;
}
const indexToDelete = currentCart.findIndex(findCartItemToDelete);
state = {cart: [...currentCart.slice(0,indexToDelete),...currentCart.slice(indexToDelete+1)], cartAmt:[...state.cartAmt], cartQty:[...state.cartQty]};
return state;
*/
state = {cart:action.payload, cartAmt:[...state.cartAmt], cartQty:[...state.cartQty]};
var sum = 0;
var qty = 0;
for (var i=0; i<state.cart.length; i++){
sum = sum + state.cart[i].price*state.cart[i].quantity;
qty = qty + state.cart[i].quantity;
}
state = {cart:[...state.cart], cartAmt:[sum], cartQty:[qty]}
return state;
break;
case "UPDATE_CART_ITEM":
state = {cart:action.payload, cartAmt:[...state.cartAmt], cartQty:[...state.cartQty]};
var sum = 0;
var qty = 0;
for (var i=0; i<state.cart.length; i++){
sum = sum + state.cart[i].price*state.cart[i].quantity;
qty = qty + state.cart[i].quantity;
}
state = {cart:[...state.cart], cartAmt:[sum], cartQty:[qty]}
return state;
break;
case "TOTAL_CART_ITEM":
var sum = 0;
var qty = 0;
for (var i=0; i<state.cart.length; i++){
sum = sum + state.cart[i].price*state.cart[i].quantity;
qty = qty + state.cart[i].quantity;
}
state = {cart:[...state.cart], cartAmt:[sum], cartQty:[qty]}
return state;
break;
}
return state;
}<file_sep>"use strict";
import React from 'react';
import {InputGroup, MenuItem, DropdownButton, Image, Well, Panel, FormControl, FormGroup, ControlLabel, Button, Row, Col} from 'react-bootstrap';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {findDOMNode} from 'react-dom';
import {postBooks, deleteBooks, updateBooks, getBooks, resetButton} from '../../actions/booksActions';
import {getCart} from '../../actions/cartActions';
import axios from 'axios';
class BooksForm extends React.Component{
constructor(){
super();
this.state = {
images: [{}],
img:''
}
}
componentDidMount(){
this.props.getBooks();
this.props.getCart();
axios.get('/api/images')
.then(function(response){
this.setState({
images: response.data
})
}.bind(this))
.catch(function(err){
this.setState({
images: 'Error loading images from the server',
img: ''
})
})
}
handleSubmit(){
var fname = '';
if(findDOMNode(this.refs.image).value == ''){
fname = 'images/noimage.png';
}else{
fname = findDOMNode(this.refs.image).value;
}
const book = [{
title: findDOMNode(this.refs.title).value,
description: findDOMNode(this.refs.description).value,
image: fname,
price: findDOMNode(this.refs.price).value,
}];
this.props.postBooks(book);
}
deleteBook(){
const _id = findDOMNode(this.refs.delete).value
this.props.deleteBooks(_id);
}
resetForm(){
this.props.resetButton();
findDOMNode(this.refs.title).value = '';
findDOMNode(this.refs.description).value = '';
findDOMNode(this.refs.price).value = '';
this.setState({
img: ''
});
}
findBook(){
this.resetForm();
const currentBookList = this.props.books;
var findID = findDOMNode(this.refs.delete).value;
function findBookIndex(book){
return book._id === findID;
}
const indexToUpdate = currentBookList.findIndex(findBookIndex);
if (indexToUpdate != -1){
findDOMNode(this.refs.title).value = currentBookList[indexToUpdate].title;
findDOMNode(this.refs.description).value = currentBookList[indexToUpdate].description;
if(typeof currentBookList[indexToUpdate].image == 'undefined'){
findDOMNode(this.refs.image).value = "images/noimage.png";
findDOMNode(this.refs.imageBox).src = "images/noimage.png";
}else{
this.setState({
img: currentBookList[indexToUpdate].image
})
// findDOMNode(this.refs.image).value = currentBookList[indexToUpdate].image;
// findDOMNode(this.refs.imageBox).src = currentBookList[indexToUpdate].image;
}
findDOMNode(this.refs.price).value = currentBookList[indexToUpdate].price;
//
}
}
updateBook(){
const currentBookList = this.props.books;
var findID = findDOMNode(this.refs.delete).value;
function findBookIndex(book){
return book._id === findID;
}
const indexToUpdate = currentBookList.findIndex(findBookIndex);
if (indexToUpdate != -1){
let bookDetails = {
_id: findDOMNode(this.refs.delete).value,
title: findDOMNode(this.refs.title).value,
description: findDOMNode(this.refs.description).value,
image: findDOMNode(this.refs.image).value,
price: findDOMNode(this.refs.price).value,
};
this.props.updateBooks(bookDetails);
}
// this.props.updateBooks(book);
}
handleSelect(img){
this.setState({
img: 'images/'+img
})
}
render(){
const booksList = this.props.books.map(function(booksArr){
return (
<option key={booksArr._id} value={booksArr._id}>{booksArr.title}</option>
)
});
const imgList = this.state.images.map(function(imgArr, i){
return (
<MenuItem key={i} eventKey={imgArr.name}
onClick={this.handleSelect.bind(this, imgArr.name)}>{imgArr.name}</MenuItem>
)
}, this);
return(
<Well>
<Row>
<Col xs={12} sm={6} md={6}>
<Panel>
<InputGroup>
<FormControl type="text" ref="image" value={this.state.img}/>
<DropdownButton
componentClass={InputGroup.Button}
id="input-dropdown-addon"
title="Select an Image"
bsStyle="primary"
>
{imgList}
</DropdownButton>
</InputGroup>
<Image className="imgBox" ref="imageBox" src={this.state.img} responsive/>
</Panel>
</Col>
<Col xs={12} sm={6} md={6}>
<Panel>
<FormGroup controlId="title" validationState={this.props.validation}>
<ControlLabel>Title</ControlLabel>
<FormControl
type="text"
placeholder="Enter Title"
ref="title" />
<FormControl.Feedback />
</FormGroup>
</Panel>
<Panel>
<FormGroup controlId="description" validationState={this.props.validation}>
<ControlLabel>Description</ControlLabel>
<FormControl
type="text"
placeholder="Enter Description"
ref="description" />
<FormControl.Feedback />
</FormGroup>
</Panel>
<Panel>
<FormGroup controlId="price" validationState={this.props.validation}>
<ControlLabel>Price ($)</ControlLabel>
<FormControl
type="text"
placeholder="Enter Price in USD"
ref="price" />
<FormControl.Feedback />
</FormGroup>
<Button
onClick={(!this.props.msg)?(this.handleSubmit.bind(this)):(this.resetForm.bind(this))}
bsStyle={(!this.props.msg)?('primary'):(this.props.style)}>
{(!this.props.msg)?('Save Book'):(this.props.msg)}
</Button>
<span> </span>
<Button onClick={this.updateBook.bind(this)} bsStyle="success">Update</Button>
</Panel>
<Panel>
<FormGroup controlId="formControlsSelect">
<ControlLabel>Select a Title to Delete or Update</ControlLabel>
<FormControl
ref="delete"
componentClass="select"
placeholder="select"
onClick={this.findBook.bind(this)}>
<option value="select">select</option>
{booksList}
</FormControl>
</FormGroup>
<Button onClick={this.deleteBook.bind(this)} bsStyle="danger">Delete</Button>
</Panel>
</Col>
</Row>
</Well>
)
}
}
function mapStateToProps(state){
return {
books: state.books.books,
cart: state.cart.cart,
msg: state.books.msg,
style: state.books.style,
validation: state.books.validation
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({
postBooks:postBooks,
deleteBooks: deleteBooks,
updateBooks: updateBooks,
getBooks: getBooks,
resetButton: resetButton,
getCart: getCart
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(BooksForm);<file_sep>
"use strict"
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import {Router, Route, IndexRoute, browserHistory} from 'react-router';
import {applyMiddleware, createStore} from 'redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
// Import combineReducer here
import reducers from './reducers/index'
// Import combined actions here
import {addToCart} from './actions/cartActions';
import {postBooks, deleteBooks, updateBooks} from './actions/booksActions';
/*
// STEP 3 define reducer
const reducer = function(state={books:[]},action){
switch(action.type){
case "POST_BOOK": state = {books:[...state.books, ...action.payload]};
return state;
break;
case "DELETE_BOOK":
const bookListToDelete = [...state.books];
function findBook(book){
return book._id === action.payload._id;
}
const indexToDelete = bookListToDelete.findIndex(findBook);
state = {books: [...bookListToDelete.slice(0,indexToDelete),...bookListToDelete.slice(indexToDelete+1)]};
return state
break;
case "UPDATE_BOOK":
const bookListToUpdate = [...state.books];
function findBook(book){
return book._id === action.payload._id;
}
const indexToUpdate = bookListToUpdate.findIndex(findBook);
const newBookToUpdate = {
...bookListToUpdate[indexToUpdate],
title: action.payload.title
};
state = {books:[...bookListToUpdate.slice(0,indexToUpdate),newBookToUpdate,...bookListToUpdate.slice(indexToUpdate+1)]};
return state;
break;
}
return state;
}
*/
// STEP 1 Create the store
const middleware = applyMiddleware(thunk, logger);
// We will pass initial state from server store
const initialState = window.INITIAL_STATE;
const store = createStore(reducers, initialState, middleware);
/*
import Main from './main';
import BooksList from './components/pages/booksList';
import Cart from './components/pages/cart';
import BooksForm from './components/pages/booksForm';
*/
import routes from './routes.js'
const Routes = (
<Provider store={store}>
{routes}
</Provider>
);
render(
Routes, document.getElementById('app')
);
/*
store.subscribe(function(){
console.log('Current state is ', store.getState());
//console.log('Current price of second book is ', store.getState().books[0].price);
})
*/
// STEP 2 Create and dispatch action
/*
store.dispatch(postBooks(
[
]
))
*/
// Second Action to add book
/* store.dispatch(postBooks(
[
{
_id: 3,
title: 'Third Book Title',
description: 'This is a great third book',
price: 30.00
}
]
)) */
/*
// DELETE a book
store.dispatch(deleteBooks(
{_id:1}
))
// UPDATE a book
store.dispatch(updateBooks(
{
_id:2,
title: 'Learn Revit in 24 hours'
}
))
// Add to cart
store.dispatch(addToCart(
[{_id:1}]
))
*/<file_sep>
"use strict";
import React from 'react';
import {Nav, Navbar, NavItem, NavDropdown, MenuItem, Badge} from 'react-bootstrap';
class Menu extends React.Component{
render(){
return (
<Navbar inverse fixedTop className="navbar">
<Navbar.Header>
<Navbar.Brand className="brand">
<a href="/">ROLL 'N LEARN</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav >
<NavItem eventKey={1} href="/admin">Admin</NavItem>
<NavItem eventKey={2} href="#">Contact Us</NavItem>
<NavItem eventKey={3} href="/cart">Your Cart{(this.props.cartItemNumber > 0)?(<Badge>{this.props.cartItemNumber}</Badge>):('')}</NavItem>
</Nav>
<Nav pullRight>
<NavDropdown eventKey={1} title="Student" id="basic-nav-dropdown">
<MenuItem eventKey={1.1}>Sign Up</MenuItem>
<MenuItem eventKey={1.2}>Sign In</MenuItem>
</NavDropdown>
<NavDropdown eventKey={2} title="Instructor" id="basic-nav-dropdown">
<MenuItem eventKey={2.1}>Sign Up</MenuItem>
<MenuItem eventKey={2.2}>Sign In</MenuItem>
</NavDropdown>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}
export default Menu;<file_sep>"use strict";
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {getBooks} from '../../actions/booksActions';
import {Carousel, Well, Grid, Row, Col, Button} from 'react-bootstrap';
import BookItem from './bookItem';
import BooksForm from './booksForm';
import Cart from './cart';
class BooksList extends React.Component{
componentDidMount(){
this.props.getBooks();
console.log("Trying to get the books")
console.log(this.props.books)
}
render(){
const booksList = this.props.books.map(function(booksArr){
return (
<Col xs={6} sm={6} md={6} key={booksArr._id}>
<BookItem
_id= {booksArr._id}
title= {booksArr.title}
description= {booksArr.description}
image={booksArr.image}
price= {booksArr.price}
val= {5}
/>
</Col>
)
});
return (
<Grid>
<Row>
<Carousel>
<Carousel.Item>
<img width={300} height={300} alt="900x300" src="images/SteveJobs.jpeg"/>
<Carousel.Caption>
<h3><NAME></h3>
<p>Biography of a visionary</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img width={300} height={300} alt="900x300" src="images/IdoWhatIdo.jpg"/>
<Carousel.Caption>
<h3>I Do What I Do</h3>
<p>Pragmatic and liberal regulator</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img width={300} height={300} alt="900x300" src="images/unlimitedpower.jpg"/>
<Carousel.Caption>
<h3>Unlimited Power</h3>
<p>Unleashing your potential within</p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</Row>
<Row style={{marginTop:'15px'}}>
{booksList}
</Row>
<Row>
<Cart />
</Row>
</Grid>
)
}
}
function mapStateToProps(state){
return {
books: state.books.books
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({
getBooks: getBooks,
// OtherActions: xxxx
}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(BooksList);
|
24c31488294580035a17ef8cb7deefa78593e9ca
|
[
"JavaScript"
] | 6
|
JavaScript
|
rollnlearn/shoppingcart
|
e5d71b95b53cf4f8fc33740d8bfddced43427abe
|
44c2aef4c688dd8e0647f16c1168735ece7e65ac
|
refs/heads/master
|
<repo_name>manifoldfinance/ercgas-api<file_sep>/README.md
# [ercgas.org API](#)
> NodeJS API Client
## License
Apache-2.0
<file_sep>/__tests__/lib.spec.ts
import {
asyncFlow,
cacheFor, flow,
mapObj,
pick,
tryNull,
untilSuccessOrNull,
untilSuccessWithErrors,
waitFor,
} from 'lib';
import { timeout } from '@helpers/timeout';
test('pick', async () => {
const obj = { a: 1, b: 2, c: 3 };
const ret = pick(obj, ['a']);
expect(ret).toMatchObject({ a: 1 });
});
test('mapObj', async () => {
const obj = { a: 1, b: 2, c: 3 };
const ret = mapObj(obj, (k, x) => x + 1);
expect(ret).toMatchObject({ a: 2, b: 3, c: 4 });
});
test('tryNull', async () => {
const fn = () => Promise.reject('error');
const ret = await tryNull(fn);
expect(ret).toBeNull();
});
test('untilSuccessOrNull', async () => {
const input = [
jest.fn(() => Promise.reject(0)),
jest.fn(() => Promise.resolve(12)),
jest.fn(() => Promise.resolve(40))];
const ret = await untilSuccessOrNull(input);
expect(ret).toEqual(12);
expect(input[0]).toBeCalledTimes(1);
expect(input[1]).toBeCalledTimes(1);
expect(input[2]).toBeCalledTimes(0);
});
test('untilSuccessOrNull null', async () => {
const input = [
jest.fn(() => Promise.reject(0)),
jest.fn(() => Promise.reject(12)),
jest.fn(() => Promise.reject(40))];
const ret = await untilSuccessOrNull(input);
expect(ret).toBeNull();
expect(input[0]).toBeCalledTimes(1);
expect(input[1]).toBeCalledTimes(1);
expect(input[2]).toBeCalledTimes(1);
});
test('untilSuccessWithErrors', async () => {
const input = [
jest.fn(() => Promise.reject(new Error('foo'))),
jest.fn(() => Promise.resolve(12)),
jest.fn(() => Promise.resolve(40))];
const ret = await untilSuccessWithErrors(input);
expect(ret).toEqual({ value: 12, errors: [new Error('foo')] });
expect(input[0]).toBeCalledTimes(1);
expect(input[1]).toBeCalledTimes(1);
expect(input[2]).toBeCalledTimes(0);
});
test('untilSuccessWithErrors all errors', async () => {
const input = [
jest.fn(() => Promise.reject(new Error('test'))),
jest.fn(() => Promise.reject(new Error('foo'))),
jest.fn(() => Promise.reject(new Error('bar')))];
const ret = await untilSuccessWithErrors(input);
expect(ret).toEqual({ value: undefined, errors: [new Error('test'), new Error('foo'), new Error('bar')] });
expect(input[0]).toBeCalledTimes(1);
expect(input[1]).toBeCalledTimes(1);
expect(input[2]).toBeCalledTimes(1);
});
test('waitFor', async () => {
const ret = await waitFor(500)(() => timeout(100, 42))();
expect(ret).toEqual(42);
});
test('waitFor timeout', async () => {
await expect(() =>
waitFor(500)(async () =>
timeout(1000, 42))()).rejects.toThrowError('Timeout');
});
test('cacheFor', async () => {
const counter = (start: number) => {
let count = start;
return () => Promise.resolve(++count);
};
const mockFn = jest.fn(counter(0));
const fn = async (x: number) => x + await mockFn();
const cachedFn = cacheFor(500)(fn);
expect(await cachedFn(10)).toEqual(11);
expect(mockFn.mock.calls.length).toBe(1);
expect(await cachedFn(10)).toEqual(11);
expect(mockFn.mock.calls.length).toBe(1);
expect(await cachedFn(100)).toEqual(102);
expect(mockFn.mock.calls.length).toBe(2);
expect(await cachedFn(100)).toEqual(102);
expect(mockFn.mock.calls.length).toBe(2);
await timeout<void>(500);
expect(await cachedFn(10)).toEqual(13);
expect(mockFn.mock.calls.length).toBe(3);
expect(await cachedFn(100)).toEqual(104);
expect(mockFn.mock.calls.length).toBe(4);
});
test('flow', () => {
const prog = flow(
(x: number) => x + 1,
(y: number) => `${y}`,
(z: string) => 'foo' + z,
);
expect(prog(10)).toEqual('foo11');
});
test('flow error', () => {
const prog = flow(
(x: number) => x + 1,
(y: number) => { throw new Error('fn2')},
(z: string) => 'foo' + z,
);
expect(() => prog(10)).toThrowError('fn2');
});
test('asyncFlow', async () => {
const prog = asyncFlow(
(x: number) => Promise.resolve(x + 1),
(y: number) => timeout(100, `${y}`),
(z: string) => Promise.resolve('foo' + z),
);
expect(await prog(10)).toEqual('foo11');
});
test('asyncFlow with a sync function', async () => {
const prog = asyncFlow(
(x: number) => Promise.resolve(x + 1),
(y: number) => `${y}`,
(z: string) => Promise.resolve('foo' + z),
);
expect(await prog(10)).toEqual('foo11');
});
test('asyncFlow exception', async () => {
const prog = asyncFlow(
(x: number) => Promise.resolve(x + 1),
(y: number) => Promise.reject('error'),
(z: string) => Promise.resolve('foo' + z),
);
await expect(() => prog(10)).rejects.toEqual('error');
});
<file_sep>/src/fetch-mock-jest/index.d.ts
declare module 'fetch-mock-jest' {
import { FetchMockStatic, MockCall, FetchMockSandbox } from 'fetch-mock';
interface FetchMockJestSandbox {
sandbox(): jest.MockInstance<Response, MockCall> & FetchMockSandbox;
}
export type FetchMockJest = jest.MockInstance<Response, MockCall> & FetchMockJestSandbox & FetchMockStatic;
const fetchMockJest: FetchMockJest;
export default fetchMockJest;
}<file_sep>/src/provider/index.ts
import { BigNumber } from 'bignumber.js';
import { mapObj, roundUp2 } from 'lib';
export * from './ercgas';
export * from './eth-node';
export type GasPrice = BigNumber;
export interface GasPriceInfo {
data: GasPrice,
provider: string,
errors: Error[]
}
export const gasPrice = (val: number | string) => new BigNumber(val);
export type TxSpeed = 'safeLow' | 'average' | 'fast' | 'fastest';
export const TX_SPEEDS: TxSpeed[] = ['safeLow', 'average', 'fast', 'fastest'];
export type GasPrices = { [key in TxSpeed]: GasPrice };
export type Factors = { [key in TxSpeed]: BigNumber };
export interface GasPricesInfo {
data: GasPrices,
provider: string,
}
export type GasPriceProvider = () => Promise<GasPricesInfo>;
export const multiply = (val: BigNumber, factors: Factors): GasPrices =>
mapObj(factors, (k, x) => val.times(x));
export const getMultipliers = (values: GasPrices): Factors => {
const avg = values.average;
return mapObj(values, (k, x) => roundUp2(x.div(avg)));
};<file_sep>/__tests__/provider/index.spec.ts
import { gasPrice, getMultipliers } from 'provider';
test('getMultipliers', () => {
const prices = {
safeLow: gasPrice(100000000000),
average: gasPrice(115000000000),
fast: gasPrice(261000000000),
fastest: gasPrice(280000000000),
};
const factors = getMultipliers(prices);
expect(factors.safeLow.toNumber()).toEqual(0.87);
expect(factors.average.toNumber()).toEqual(1);
expect(factors.fast.toNumber()).toEqual(2.27);
expect(factors.fastest.toNumber()).toEqual(2.44);
});
<file_sep>/__tests__/index.spec.ts
import { gasPriceEstimator, gasPriceSetter } from 'index';
import fetch from '@helpers/fetch';
import { gasPrice } from 'provider';
import { TxData } from 'ethereum-types';
import { GasHelperConfig } from 'index';
import { timeout } from '@helpers/timeout';
const config: GasHelperConfig = {
gasStationApiKey: 'test',
ethNodeUrl: 'http://ethnode',
cacheTimeout: 400,
gasPriceLimit: 100,
providerTimeout: 200,
};
afterEach(() => {
fetch.reset();
});
test('estimate the gas price', async () => {
fetch.mock('https://ethgasstation.info/api/ethgasAPI.json?api-key=test',
_ => Promise.resolve({
status: 200,
body: '{"fast":910,"fastest":1000,"safeLow":820,"average":890,"block_time":14.5,"blockNum":10847268,"speed":0.8971149948865037,"safeLowWait":14.4,"avgWait":3.5,"fastWait":0.5,"fastestWait":0.5,"gasPriceRange":{"4":241.7,"6":241.7,"8":241.7,"10":241.7,"20":241.7,"30":241.7,"40":241.7,"50":241.7,"60":241.7,"70":241.7,"80":241.7,"90":241.7,"100":241.7,"110":241.7,"120":241.7,"130":241.7,"140":241.7,"150":241.7,"160":241.7,"170":241.7,"180":241.7,"190":241.7,"200":241.7,"220":241.7,"240":241.7,"260":241.7,"280":241.7,"300":241.7,"320":241.7,"340":241.7,"360":241.7,"380":241.7,"400":241.7,"420":241.7,"440":241.7,"460":241.7,"480":241.7,"500":241.7,"520":241.7,"540":241.7,"560":241.7,"580":241.7,"600":241.7,"620":241.7,"640":241.7,"660":241.7,"680":241.7,"700":241.7,"720":241.7,"740":241.7,"760":241.7,"780":241.7,"800":241.7,"820":14.4,"840":6,"860":4.8,"880":4.1,"890":3.5,"900":1.1,"910":0.5,"920":0.5,"940":0.5,"960":0.5,"980":0.5,"1000":0.5}}',
}));
const estimate = gasPriceEstimator(config);
const average = await estimate('average');
const fast = await estimate('fast');
const fastest = await estimate('fastest');
const safeLow = await estimate('safeLow');
expect(average.errors).toBeEmpty();
expect(average.provider).toEqual('ethgasstation');
expect(average.data).toEqual(gasPrice(89000000000));
expect(fast.data).toEqual(gasPrice(91000000000));
expect(fastest.data).toEqual(gasPrice(100000000000));
expect(safeLow.data).toEqual(gasPrice(82000000000));
});
test('estimate the gas price when gas station fails', async () => {
fetch.get(/^https:\/\/ethgasstation\.info\/api\/ethgasAPI\.json\?api-key=.*$/,
500);
fetch.post('http://ethnode', { 'jsonrpc': '2.0', 'id': 1, 'result': '0x1f6ea08600' });
const estimate = gasPriceEstimator(config);
const average = await estimate('average');
const fast = await estimate('fast');
const fastest = await estimate('fastest');
const safeLow = await estimate('safeLow');
expect(average.errors).toEqual([new Error('Internal Server Error')]);
expect(average.provider).toEqual('eth-node');
expect(average.data).toEqual(gasPrice(135000000000));
expect(fast.data).toEqual(gasPrice(148500000000));
expect(fastest.data).toEqual(gasPrice(162000000000));
expect(safeLow.data).toEqual(gasPrice(135000000000));
});
test('set the gas price on a tx', async () => {
fetch.mock(/^https:\/\/ethgasstation.info\/api\/ethgasAPI\.json\?api-key=.*$/,
req => Promise.resolve({
status: 200,
body: '{"fast":910,"fastest":1000,"safeLow":820,"average":890,"block_time":14.5,"blockNum":10847268,"speed":0.8971149948865037,"safeLowWait":14.4,"avgWait":3.5,"fastWait":0.5,"fastestWait":0.5,"gasPriceRange":{"4":241.7,"6":241.7,"8":241.7,"10":241.7,"20":241.7,"30":241.7,"40":241.7,"50":241.7,"60":241.7,"70":241.7,"80":241.7,"90":241.7,"100":241.7,"110":241.7,"120":241.7,"130":241.7,"140":241.7,"150":241.7,"160":241.7,"170":241.7,"180":241.7,"190":241.7,"200":241.7,"220":241.7,"240":241.7,"260":241.7,"280":241.7,"300":241.7,"320":241.7,"340":241.7,"360":241.7,"380":241.7,"400":241.7,"420":241.7,"440":241.7,"460":241.7,"480":241.7,"500":241.7,"520":241.7,"540":241.7,"560":241.7,"580":241.7,"600":241.7,"620":241.7,"640":241.7,"660":241.7,"680":241.7,"700":241.7,"720":241.7,"740":241.7,"760":241.7,"780":241.7,"800":241.7,"820":14.4,"840":6,"860":4.8,"880":4.1,"890":3.5,"900":1.1,"910":0.5,"920":0.5,"940":0.5,"960":0.5,"980":0.5,"1000":0.5}}',
}));
const setter = gasPriceSetter(config);
const tx: TxData = {
from: 'xxx',
gasPrice: 0,
gas: 100,
nonce: 42,
value: 10000,
data: 'fffff',
};
const average = await setter('average', tx);
const fast = await setter('fast', tx);
const fastest = await setter('fastest', tx);
const safeLow = await setter('safeLow', tx);
expect(average.gasPrice).toEqual(gasPrice(89000000000));
expect(fast.gasPrice).toEqual(gasPrice(91000000000));
expect(fastest.gasPrice).toEqual(gasPrice(100000000000));
expect(safeLow.gasPrice).toEqual(gasPrice(82000000000));
const eqProps = (x: TxData, y: TxData) => (Object.keys(x) as (keyof TxData)[])
.every((k: keyof TxData) => k === 'gasPrice' || x[k] === y[k]);
const expectEqProps = (x: TxData, y: TxData) => expect(eqProps(x, y)).toBeTrue();
expectEqProps(average, tx);
expectEqProps(fast, tx);
expectEqProps(fastest, tx);
expectEqProps(safeLow, tx);
});
test('estimate the gas price when providers time out', async () => {
fetch.get(/^https:\/\/ethgasstation\.info\/api\/ethgasAPI\.json\?api-key=.*$/,
() => timeout(300, { safeLow: 1000, average: 1000, fast: 2000, fastest: 2100 }));
fetch.post('http://ethnode', () => timeout(300, { 'jsonrpc': '2.0', 'id': 1, 'result': '0x1f6ea08600' }));
const estimate = gasPriceEstimator(config);
await expect(async () => estimate('average')).rejects.toEqual(new Error('Provider timeout, Provider timeout'));
});
test('estimate the gas price when providers timeout', async () => {
fetch.get(/^https:\/\/ethgasstation\.info\/api\/ethgasAPI\.json\?api-key=.*$/,
500);
fetch.post('http://ethnode', () => timeout(300, { 'jsonrpc': '2.0', 'id': 1, 'result': '0x1f6ea08600' }));
const estimate = gasPriceEstimator(config);
await expect(async () => estimate('average')).rejects.toEqual(new Error('Internal Server Error, Provider timeout'));
});
test('cached estimate', async () => {
fetch.get(/^https:\/\/ethgasstation.info\/api\/ethgasAPI\.json\?api-key=.*$/,
req => Promise.resolve({
status: 200,
body: '{"fast":910,"fastest":1000,"safeLow":820,"average":890,"block_time":14.5,"blockNum":10847268,"speed":0.8971149948865037,"safeLowWait":14.4,"avgWait":3.5,"fastWait":0.5,"fastestWait":0.5,"gasPriceRange":{"4":241.7,"6":241.7,"8":241.7,"10":241.7,"20":241.7,"30":241.7,"40":241.7,"50":241.7,"60":241.7,"70":241.7,"80":241.7,"90":241.7,"100":241.7,"110":241.7,"120":241.7,"130":241.7,"140":241.7,"150":241.7,"160":241.7,"170":241.7,"180":241.7,"190":241.7,"200":241.7,"220":241.7,"240":241.7,"260":241.7,"280":241.7,"300":241.7,"320":241.7,"340":241.7,"360":241.7,"380":241.7,"400":241.7,"420":241.7,"440":241.7,"460":241.7,"480":241.7,"500":241.7,"520":241.7,"540":241.7,"560":241.7,"580":241.7,"600":241.7,"620":241.7,"640":241.7,"660":241.7,"680":241.7,"700":241.7,"720":241.7,"740":241.7,"760":241.7,"780":241.7,"800":241.7,"820":14.4,"840":6,"860":4.8,"880":4.1,"890":3.5,"900":1.1,"910":0.5,"920":0.5,"940":0.5,"960":0.5,"980":0.5,"1000":0.5}}',
}), { overwriteRoutes: true, repeat: 1 });
const estimate = gasPriceEstimator(config);
let average = await estimate('average');
expect(fetch.calls().length).toEqual(1);
const fast = await estimate('fast');
expect(fetch.calls().length).toEqual(1);
const fastest = await estimate('fastest');
expect(fetch.calls().length).toEqual(1);
const safeLow = await estimate('safeLow');
expect(fetch.calls().length).toEqual(1);
expect(average.data).toEqual(gasPrice(89000000000));
expect(fast.data).toEqual(gasPrice(91000000000));
expect(fastest.data).toEqual(gasPrice(100000000000));
expect(safeLow.data).toEqual(gasPrice(82000000000));
fetch.get(/^https:\/\/ethgasstation.info\/api\/ethgasAPI\.json\?api-key=.*$/,
req => Promise.resolve({
status: 200,
body: '{"fast":910,"fastest":1000,"safeLow":820,"average":790,"block_time":14.5,"blockNum":10847268,"speed":0.8971149948865037,"safeLowWait":14.4,"avgWait":3.5,"fastWait":0.5,"fastestWait":0.5,"gasPriceRange":{"4":241.7,"6":241.7,"8":241.7,"10":241.7,"20":241.7,"30":241.7,"40":241.7,"50":241.7,"60":241.7,"70":241.7,"80":241.7,"90":241.7,"100":241.7,"110":241.7,"120":241.7,"130":241.7,"140":241.7,"150":241.7,"160":241.7,"170":241.7,"180":241.7,"190":241.7,"200":241.7,"220":241.7,"240":241.7,"260":241.7,"280":241.7,"300":241.7,"320":241.7,"340":241.7,"360":241.7,"380":241.7,"400":241.7,"420":241.7,"440":241.7,"460":241.7,"480":241.7,"500":241.7,"520":241.7,"540":241.7,"560":241.7,"580":241.7,"600":241.7,"620":241.7,"640":241.7,"660":241.7,"680":241.7,"700":241.7,"720":241.7,"740":241.7,"760":241.7,"780":241.7,"800":241.7,"820":14.4,"840":6,"860":4.8,"880":4.1,"890":3.5,"900":1.1,"910":0.5,"920":0.5,"940":0.5,"960":0.5,"980":0.5,"1000":0.5}}',
}), { overwriteRoutes: true });
average = await estimate('average');
expect(average.data).toEqual(gasPrice(89000000000));
expect(fetch.calls().length).toEqual(1);
await timeout(500);
average = await estimate('average');
expect(average.data).toEqual(gasPrice(79000000000));
expect(fetch.calls().length).toEqual(2);
});
<file_sep>/jest.config.js
module.exports = {
globals: {
'ts-jest': {
compiler: 'ttypescript',
},
},
automock: false,
setupFiles: [
'./jest.setup.js',
],
testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
moduleNameMapper: {
'src/(.*)': '<rootDir>/src/$1',
'__tests__/(.*)': '<rootDir>/__tests__/$1',
},
preset: 'ts-jest',
testEnvironment: 'node',
setupFilesAfterEnv: ['jest-extended'],
};<file_sep>/src/index.ts
import {
ethNodeProvider,
GasPrice,
GasPriceInfo,
GasPriceProvider,
gasStationProvider,
getEthNodeDataConverter,
TxSpeed,
} from './provider';
import { TxData } from 'ethereum-types';
import { cacheFor, curry, flow, identity, untilSuccessWithErrors, waitFor } from './lib';
export { GasPrice, TxSpeed };
export interface GasHelperConfig {
gasStationApiKey: string;
ethNodeUrl: string;
providerTimeout: number;
cacheTimeout: number;
gasPriceLimit: number;
}
export type GasPriceEstimator = (speed: TxSpeed) => Promise<GasPriceInfo>;
export type GasPriceSetter = {
(speed: TxSpeed, tx: TxData): Promise<TxData>;
(tx: TxData): Promise<TxData>;
};
export function getGasPriceEstimator(...providers: GasPriceProvider[]): GasPriceEstimator {
return async (speed: TxSpeed): Promise<GasPriceInfo> => {
const ret = await untilSuccessWithErrors(providers.map((p: GasPriceProvider) => () => p()));
if (ret.value) {
return { provider: ret.value.provider, data: ret.value.data[speed], errors: ret.errors };
}
throw new Error(ret.errors.reduce((str, x, idx) => str + (idx ? ', ' : '') + x.message, ''));
};
}
export function getDefaultProviders(config: GasHelperConfig): GasPriceProvider[] {
const providers = [gasStationProvider(config.gasStationApiKey), ethNodeProvider(config.ethNodeUrl, getEthNodeDataConverter())];
return providers.map(flow(
config.cacheTimeout > 0 ? cacheFor(config.cacheTimeout) : identity,
config.providerTimeout > 0 ? waitFor(config.providerTimeout, 'Provider timeout') : identity,
));
}
export const gasPriceEstimator = (config: GasHelperConfig) => getGasPriceEstimator(...getDefaultProviders(config));
export function getGasPriceSetter(estimate: GasPriceEstimator): GasPriceSetter {
return curry(async (speed: TxSpeed, tx: TxData): Promise<TxData> => {
const info = await estimate(speed);
return { ...tx, gasPrice: info.data };
});
}
export function gasPriceSetter(config: GasHelperConfig) {
return getGasPriceSetter(gasPriceEstimator(config));
}
<file_sep>/.eslintrc.js
module.exports = {
env: {
browser: true,
es6: true,
jest: true,
},
extends: [
'airbnb-base',
'eslint:recommended',
'plugin:import/recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
project: './tsconfig.json',
ecmaVersion: 2018,
sourceType: 'module',
},
plugins: [
'prettier',
'@typescript-eslint',
],
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json']
}
},
},
rules: {
'prettier/prettier': [0,
{
'semi': true,
'singleQuote': true,
'trailingComma': 'es5',
'printWidth': 100,
'tabWidth': 2,
'arrowParens': 'avoid',
},
],
'semi': 0,
'eqeqeq': [1, 'always'],
'quotes': [1, 'single'],
'no-undef': 0,
'no-console': 2,
'no-unused-vars': 0,
'no-mixed-operators': [1,
{
'allowSamePrecedence': true,
},
],
'eol-last': [2, 'always'],
'no-confusing-arrow': 0,
'arrow-parens': [2, 'as-needed'],
'arrow-spacing': ['error', { 'before': true, 'after': true }],
'arrow-body-style': [2, 'as-needed'],
'no-extra-parens': [
'warn',
'all',
{
'conditionalAssign': false,
'nestedBinaryExpressions': false,
'ignoreJSX': 'none',
'enforceForArrowConditionals': false,
},
],
'no-param-reassign': 0,
'prefer-template': 0,
'no-script-url': 0,
'prefer-promise-reject-errors': 0,
'no-unused-expressions': 0,
'dot-notation': 1,
'no-plusplus': 0,
'import/prefer-default-export': 0,
'import/no-useless-path-segments': 1,
'import/no-unresolved': 0,
'import/no-extraneous-dependencies': 0,
'import/no-named-as-default': 0,
'import/no-duplicates': 0,
'import/order': 0,
'import/newline-after-import': 1,
'import/no-named-as-default-member': 0,
'import/namespace': 0,
'import/named': 0,
'import/extensions': [
'error',
'ignorePackages',
{
'ts': 'never',
'tsx': 'never',
'js': 'never',
'jsx': 'never'
}
],
'@typescript-eslint/indent': 0,
'@typescript-eslint/camelcase': 0,
'@typescript-eslint/explicit-function-return-type': 0,
'@typescript-eslint/no-non-null-assertion': 0,
'@typescript-eslint/no-use-before-define': 0,
'@typescript-eslint/member-delimiter-style': 0,
'@typescript-eslint/no-unused-vars': 0,
'@typescript-eslint/no-explicit-any': 0,
'@typescript-eslint/explicit-member-accessibility': 0,
'@typescript-eslint/no-angle-bracket-type-assertion': 0,
// TODO: enable the lines below when refactoring
// "react-hooks/rules-of-hooks": 1,
// "react-hooks/exhaustive-deps": 1
},
};
<file_sep>/src/lib.ts
import BigNumber from 'bignumber.js';
export const pick = <T, K extends keyof T>(obj: T, ks: readonly K[]): Pick<T, K> =>
ks.reduce((acc: Pick<T, K>, k: K) => {
acc[k] = obj[k];
return acc;
}, {} as Pick<T, K>);
export const mapObj = <T, K extends keyof T, V extends Record<K, any>>(obj: T, fn: (k: K, x: any) => any) =>
(Object.keys(obj) as Array<K>)
.reduce((acc: V, k: K) => {
acc[k] = fn(k, obj[k]);
return acc;
}, {} as V);
export function idInc() {
let id = 1;
return () => `${id++}`;
}
export const bn = (val: string | number, base?: number) => new BigNumber(val, base);
export function curry(fn: (...args: any[]) => any) {
const argN = fn.length;
return function(...args: any[]) {
if (args.length < argN) {
// @ts-expect-error: Ignore no implicit this
return curry(fn.bind(this, ...args));
}
// @ts-expect-error: Ignore no implicit this
return fn.call(this, ...args);
};
}
export function tryNull<E, T>(fn: () => Promise<T>): Promise<T | null> {
return fn().catch(_ => null);
}
export function untilSuccessOrNull<T>(tasks: (() => Promise<T | null>)[]): Promise<T | null> {
return tasks.reduce<Promise<T | null>>(
(prev: Promise<T | null>, cur: () => Promise<T | null>) =>
prev.then(x => x ?? cur()).catch(_ => null),
Promise.resolve(null),
);
}
type PromiseErrors<T> = Promise<{ value?: T, errors: Error[] }>;
export function wrapErrors<T>(fn: () => Promise<T>, errs: Error[]): () => PromiseErrors<T> {
return () => fn().then(value => ({ value, errors: [...errs] })).catch(err => ({ errors: [...errs, err] }));
}
export function untilSuccessWithErrors<T>(tasks: (() => Promise<T>)[]): PromiseErrors<T> {
return tasks.reduce<PromiseErrors<T>>(
(prev: PromiseErrors<T>, cur: () => Promise<T>) =>
prev.then(({ value, errors }) => value ? { value, errors } : wrapErrors(cur, errors)()),
Promise.resolve({ errors: [] }),
);
}
export function roundUp2(val: BigNumber): BigNumber {
return val.decimalPlaces(2, BigNumber.ROUND_UP);
}
export const waitFor = (millis: number, reason = 'Timeout') => <T, A extends any[] | any[]>(fn: (...a: A) => Promise<T>): (...args: A) => Promise<T> => async (...args: A) => Promise.race([fn(...args), new Promise<T>((res, rej) => {
setTimeout(() => rej(new Error(reason)), millis);
})]);
export const cacheFor = (millis: number) => <T, A extends any[] | any[]>(fn: (...a: A) => Promise<T>): (...args: A) => Promise<T> => {
const cache = new Map();
return async function(...args: A) {
const k = args.join('#');
if (cache.has(k)) {
return Promise.resolve(cache.get(k));
}
const ret = await fn(...args);
cache.set(k, ret);
setTimeout(() => {
cache.delete(k);
}, millis);
return ret;
};
};
export function flow<T1, T2, A extends any>(fn1: (a: A) => T1, fn2: (a1: T1) => T2): (a: A) => T2;
export function flow<T1, T2, T3, A extends any>(fn1: (a: A) => T1, fn2: (a1: T1) => T2, fn3: (a2: T2) => T3): (a: A) => T3;
export function flow<T1, T2, T3, T4, A extends any>(fn1: (a: A) => T1, fn2: (a1: T1) => T2, fn3: (a2: T2) => T3, fn4: (a3: T3) => T4): (a: A) => T4;
export function flow(...fns: ((a: any) => any)[]) {
return (x: any) => fns.reduce((v, f) => f(v), x);
}
export const identity = <T extends any>(x: T): T => x;
export function asyncFlow<T1, T2, A extends any>(fn1: (a: A) => Promise<T1> | T1, fn2: (a1: T1) => Promise<T2> | T2): (a: A) => Promise<T2>;
export function asyncFlow<T1, T2, T3, A extends any>(fn1: (a: A) => Promise<T1> | T1, fn2: (a1: T1) => Promise<T2> | T2, fn3: (a2: T2) => Promise<T3> | T3): (a: A) => Promise<T3>;
export function asyncFlow<T1, T2, T3, T4, A extends any>(fn1: (a: A) => Promise<T1> | T1, fn2: (a1: T1) => Promise<T2> | T2, fn3: (a2: T2) => Promise<T3> | T3, fn4: (a3: T3) => Promise<T4> | T4): (a: A) => Promise<T4>;
export function asyncFlow(...fns: ((a: any) => Promise<any>)[]) {
return (x: any) => fns.reduce((v, f) => Promise.resolve(v).then(f), Promise.resolve(x));
}
<file_sep>/jest.setup.js
jest.mock('cross-fetch', () => require('fetch-mock-jest').sandbox());<file_sep>/src/provider/ercgas.ts
import fetch from 'cross-fetch';
import { pick, mapObj } from 'lib';
import { GasPrices, gasPrice, TX_SPEEDS, GasPriceProvider } from './index';
const PROVIDER_NAME = 'ercgas';
export interface ERCGasData {
average: number;
fast: number;
fastest: number;
safeLow: number;
}
// export async function fetchERCGasData(apiKey: string): Promise<ERCGasData> {
export async function fetchERCGasData(): Promise<ERCGasData> {
const res = await fetch(`https://ercgas.org/api`);
if (res.status !== 200) {
throw new Error(res.statusText);
}
try {
const data = await res.json();
return pick(data, TX_SPEEDS);
} catch (e) {
throw new Error('Invalid server response: ' + e.message);
}
}
export const convertERCGasData = (data: ERCGasData): GasPrices =>
mapObj(data, (k, x) => gasPrice(x).times(100000000));
export function ercGasPricingProvider(): GasPriceProvider {
return async () => ({ data: convertERCGasData(await fetchERCGasData()), provider: PROVIDER_NAME });
}
|
7e1428e6897f51796d39793ce95a931e0ab73898
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 12
|
Markdown
|
manifoldfinance/ercgas-api
|
fcaf259dc6c55904db9f92674c39217864adaa85
|
1705d9a9c7e60f00527c205464d742e7ab98b09f
|
refs/heads/master
|
<repo_name>cessflorendo/Special-Problem<file_sep>/src/javaBackend/ExportPDF.java
package javaBackend;
import java.awt.Image;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import com.itextpdf.io.font.FontConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
public class ExportPDF {
private File file;
private PdfWriter writer;
private PdfDocument pdf;
private Document document;
public ExportPDF(File file) throws IOException{
try {
this.setFile(file);
writer = new PdfWriter(file);
pdf = new PdfDocument(writer);
pdf.setDefaultPageSize(PageSize.A4);
document = new Document(pdf);
} catch (FileNotFoundException e) {
if(writer!=null) writer.close();
MessageDialog md = new MessageDialog("Export PDF File", "Export failed. File may be opened in another application.", "WARNING_MESSAGE");
md.createDialog();
e.printStackTrace();
}
}
public void writeConstraints(ArrayList<String> words) throws IOException{
if(writer!=null){
PdfFont font = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
document.add(new Paragraph("Dataset retrieved from: "+ words.get(0)).setFont(font));
document.add(new Paragraph("Formulation used: "+ words.get(1)).setFont(font));
document.add(new Paragraph("Reference gene sets range: ["+ words.get(2) + ", " + words.get(3) + "]").setFont(font));
document.add(new Paragraph("Weight for missing genes = " + words.get(4)).setFont(font));
document.add(new Paragraph("Weight for additional genes = " + words.get(5)).setFont(font));
document.add(new Paragraph("Size of max gap = " + words.get(6)).setFont(font));
document.add(new Paragraph("Size of k = " + words.get(7)).setFont(font));
document.add(new Paragraph("\n\n"));
}
}
public void writeResults(String word, ArrayList<String> words) throws IOException{
if(writer!=null){
PdfFont font = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
Paragraph row = new Paragraph();
row.setFont(font);
row.add(word + ": ");
for(int i=0; i<words.size(); i++){
row.add(words.get(i) + " ");
}
document.add(row);
}
}
public void writeResults(int num, ArrayList<ArrayList<String>> words) throws IOException{
if(writer!=null){
PdfFont font = PdfFontFactory.createFont(FontConstants.HELVETICA);
PdfFont bold = PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD);
PdfFont italic = PdfFontFactory.createFont(FontConstants.HELVETICA_OBLIQUE);
int row = words.size()/num;
System.out.println(words.size() + " / " + num + " = " + row);
for(int i=1; i<=num; i++){
Table table = new Table(new float[words.get(i*row-row).size()]);
table.setWidth(PageSize.A4.getWidth()-document.getLeftMargin()-document.getRightMargin());
for(int j=(i*row - row); j<(i*row); j++){
for(int k=0; k<words.get(j).size(); k++){
if(k%10==0 && k!=0){
table.startNewRow();
table.addCell(new Cell().setBorder(null));
}
if(j==(i*row - row)){
Cell cell = new Cell().add(new Paragraph(words.get(j).get(k)));
cell.setFont(bold);
cell.setBorder(null);
table.addCell(cell);
} else{
Cell cell = new Cell().add(new Paragraph(words.get(j).get(k)));
if(k==0) cell.setFont(italic);
cell.setFont(font);
cell.setBorder(null);
table.addCell(cell);
}
}
table.startNewRow();
}
document.add(table);
document.add(new Paragraph("\n"));
}
}
}
public boolean close() throws IOException{
if(document!=null){
MessageDialog md = new MessageDialog("Export PDF File", "PDF file created!", "INFORMATION_MESSAGE", new ImageIcon(getResourceImg("export-dialog.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
md.createDialog();
document.close();
return true;
} else return false;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
private Image getResourceImg(String name) throws IOException{
InputStream logoInput = getClass().getClassLoader().getResourceAsStream(name);
Image logoImg = new ImageIcon(ImageIO.read(logoInput)).getImage();
return logoImg;
}
}<file_sep>/src/javaBackend/TabActions.java
package javaBackend;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTabbedPane;
public class TabActions implements ActionListener{
private JTabbedPane pane;
private int active;
public TabActions(JTabbedPane pane, int active){
this.setPane(pane);
this.setActive(active);
}
@Override
public void actionPerformed(ActionEvent e) {
for(int i=0; i<pane.getTabCount(); i++){
if (i==active){
pane.setEnabledAt(i, true);
pane.setSelectedIndex(i);
} else pane.setEnabledAt(i, false);
}
}
public JTabbedPane getPane() {
return pane;
}
public void setPane(JTabbedPane pane) {
this.pane = pane;
}
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
}
<file_sep>/src/javaBackend/Gene.java
package javaBackend;
public class Gene {
private String geneName;
private int geneOrder;
private int geneRep;
private boolean included;
public Gene(String geneName, int geneNumberRep){
this.geneName = geneName;
this.geneRep = geneNumberRep;
this.included = false;
}
public void setGeneName(String geneName){
this.geneName = geneName;
}
public void setGeneOrder(int geneOrder){
this.geneOrder = geneOrder;
}
public void setGeneNumberRep(int geneNumberRep){
this.geneRep = geneNumberRep;
}
public String getGeneName(){
return this.geneName;
}
public void activate(){
this.included = true;
}
public void deactivate(){
this.included = false;
}
public int getGeneOrder(){
return this.geneOrder;
}
public int getGeneNumberRep(){
return this.geneRep;
}
public boolean isActive(){
return this.included;
}
public boolean equals(Gene gene){
if(this.geneRep == gene.getGeneNumberRep()){
return true;
}
return false;
}
}
<file_sep>/src/userInterface/Main.java
package userInterface;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.ColorUIResource;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
import javaBackend.DataConverter;
import javaBackend.ExportCSV;
import javaBackend.ExportPDF;
import javaBackend.GeneSet;
import javaBackend.ILPFormulation;
import javaBackend.MessageDialog;
import javaBackend.TabActions;
import net.miginfocom.swing.MigLayout;
import rBackend.RConnector;
public class Main{
private int additionalGeneWeight, missingGeneWeight, sizeRangeLower, sizeRangeHigher, maxGapSize, rWindowSize;
private boolean isRelaxed;
private boolean basicFormulation, commonIntervals, maxGap, rWindows;
private DataConverter dc;
private ILPFormulation solve;
private ArrayList<GeneSet> results;
private RConnection r;
private int numOfGenomes = 0;
private JFrame frame;
private JPanel homeScreen;
private JPanel HS_title_panel;
private JButton HS_start_button;
private JButton HS_instructions_button;
private JTabbedPane instructions_pane;
private JLabel HS_pic_label;
private JTabbedPane mainDisplay_pane;
private JPanel IP_general;
private JPanel IP_constraints;
private JPanel IP_limitations;
private JEditorPane IP_general_text;
private JEditorPane IP_constraints_text;
private JEditorPane IP_limitations_text;
private JButton IP_mainMenu1;
private JButton IP_mainMenu2;
private JButton IP_mainMenu3;
private ActionListener IP_mainMenu_listener;
private JPanel MD_input_panel;
private JPanel MD_results_panel;
private JButton MD_IP_openFile_button;
private JButton MD_IP_next_btn;
private JButton MD_IP_mainMenu_btn;
private JTextField MD_IP_filename_text;
private File MD_IP_filename;
private JSeparator formulation_constraints_sep;
private JEditorPane MD_RP_results_text;
private JScrollPane MD_RP_results_scr;
private JButton MD_RP_exportCSV_btn;
private JButton MD_RP_exportPDF_btn;
private JButton MD_RP_back_btn;
private Font fontPlain;
private Font fontButton;
private Color buttonColor;
private Color backgroundColor;
private Color buttonTextColor;
private Font fontText;
private JScrollPane IP_general_text_scr;
private JScrollPane IP_constraints_text_scr;
private JScrollPane IP_limitations_text_scr;
private JPanel HS_details_panel;
private JTextPane HS_name_lbl;
private Font fontTitle;
private Color tabPaneColor;
private Font largeText;
private JButton HS_about_button;
private JPanel MD_preview_panel;
private JLabel MD_PP_preview_lbl;
private JEditorPane MD_PP_preview_text;
private JEditorPane MD_PP_previewConverted_text;
private JLabel MD_PP_previewConverted_lbl;
private JScrollPane MD_PP_preview_scr;
private JScrollPane MD_PP_previewConverted_scr;
private JButton MD_PP_back_btn;
private JButton MD_PP_next_btn;
private JTextArea MD_IP_preview;
private JScrollPane MD_IP_preview_scr;
private JLabel MD_VP_formulation_lbl;
private JComboBox<String> MD_VP_group;
private Container MD_variables_panel;
private JLabel MD_VP_constraints_lbl;
private SpinnerNumberModel MD_VP_from_numberModel;
private JSpinner MD_VP_from_spnr;
private SpinnerNumberModel MD_VP_to_numberModel;
private JSpinner MD_VP_to_spnr;
private JLabel MD_VP_additionalWeight_lbl;
private JSpinner MD_VP_additional_spnr;
private JLabel MD_VP_missingWeight_lbl;
private JSpinner MD_VP_missing_spnr;
private JLabel MD_VP_gapSize_lbl;
private JSpinner MD_VP_gapSize_spnr;
private JLabel MD_VP_rWindowSize_Lbl;
private JSpinner MD_VP_rWindowSize_spnr;
private JButton MD_VP_back_btn;
private JButton MD_VP_next_btn;
private JPanel aboutScreen;
private JButton AS_back_btn;
private JEditorPane AS_about_text;
private Color mainColor;
private JList<String> MD_results_list;
private JProgressBar progressBar;
private JProgressBar MD_input_progressBar;
private JProgressBar MD_VP_progressBar;
private JSeparator constraints_prog_sep;
private Font fontPlainBold;
private JEditorPane MD_RP_constraints_text;
private JScrollPane MD_results_list_scr;
private JLabel MD_RP_results_lbl;
private JLabel MD_RP_positions_lbl;
private JLabel MD_RP_constraints_lbl;
private String[] res;
private JTextPane MD_IP_about;
private Font fontPlainSmall;
private JTextPane MD_PP_preview_about;
private JTextPane MD_PP_previewConverted_about;
private JTextPane MD_VP_formulation_about;
private JTextPane MD_VP_constraints_about;
private Color panelColor;
private JLabel MD_VP_sizeRangeHigher_lbl;
private JLabel MD_VP_sizeRangeLower_lbl;
private JPanel AS_title_panel;
private JLabel AS_pic_label;
private JTextPane AS_name_lbl;
private JPanel IP_general_title_panel;
private JLabel IP_general_pic_label;
private JTextPane IP_general_name_lbl;
private JPanel IP_constraints_title_panel;
private JLabel IP_constraints_pic_label;
private JTextPane IP_constraints_name_lbl;
private JPanel IP_limitations_title_panel;
private JLabel IP_limitations_pic_label;
private JTextPane IP_limitations_name_lbl;
private Font fontTitleSmaller;
private SpinnerNumberModel MD_VP_additionalWeight_numberModel;
private SpinnerNumberModel MD_VP_missingWeight_numberModel;
private SpinnerNumberModel MD_VP_gapSize_numberModel;
private SpinnerNumberModel MD_VP_kSize_numberModel;
private JLabel MD_VP_linear_lbl;
private JTextPane MD_VP_linear_about;
private JComboBox<String> MD_VP_linear;
public Main() throws IOException{
this.setAdditionalGeneWeight(0);
this.setMissingGeneWeight(0);
this.setSizeRangeLower(0);
this.setSizeRangeHigher(0);
this.setMaxGapSize(0);
this.setrWindowSize(0);
this.setBasicFormulation(false);
this.setCommonIntervals(false);
this.setMaxGap(false);
this.setrWindows(false);
fontTitle = new Font("Courier New", Font.BOLD, 80);
fontTitleSmaller = new Font("Courier New", Font.BOLD, 60);
fontButton = new Font("Dialog Input", Font.BOLD, 20);
fontText = new Font("Dialog Input", Font.PLAIN, 22);
fontPlain = new Font("Dialog Input", Font.PLAIN, 16);
fontPlainSmall = new Font("Dialog Input", Font.ITALIC, 14);
fontPlainBold = new Font("Dialog Input", Font.BOLD, 18);
largeText = new Font("Dialog Input", Font.PLAIN, 22);
mainColor = Color.decode("#55ACEE");
backgroundColor = Color.decode("#F5F6F9");
buttonColor = Color.decode("#292F33");
buttonTextColor = Color.decode("#E1E8ED");
tabPaneColor = Color.decode("#CCD6DD");
panelColor = Color.decode("#dcebf2");
UIManager.put("TabbedPane.unselectedBackground", new ColorUIResource(tabPaneColor));
UIManager.put("TabbedPane.foreground", new ColorUIResource(buttonTextColor));
UIManager.put("TabbedPane.selectedForeground", new ColorUIResource(mainColor));
UIManager.put("TabbedPane.selected", new ColorUIResource(buttonColor));
UIManager.put("TabbedPane.font", fontButton);
UIManager.put("TabbedPane.tabInsets", new Insets(10,10,10,10));
UIManager.put("ProgressBar.background", Color.decode("#66757F"));
UIManager.put("ProgressBar.foreground", mainColor);
UIManager.put("ProgressBar.selectionBackground", Color.decode("#55ACEE"));
UIManager.put("ProgressBar.selectionForeground", Color.white);
UIManager.put("List.background", Color.decode("#66757F"));
UIManager.put("List.foreground", Color.black);
UIManager.put("List.selectionBackground", mainColor);
UIManager.put("List.selectionForeground", Color.white);
UIManager.put("ComboBox.selectionBackground", Color.decode("#CCD6DD"));
UIManager.put("ScrollPane.background", backgroundColor);
UIManager.put("List.background", backgroundColor);
UIManager.put("List.foreground", Color.black);
UIManager.put("nimbusSelection", backgroundColor);
UIManager.put("nimbusSelectionBackground", backgroundColor);
UIManager.put("nimbusSelectedText", Color.BLACK);
initialize();
}
private void initialize() throws IOException{
frame = new JFrame();
frame.setBackground(mainColor);
frame.setTitle("InteGene");
frame.setMinimumSize(new Dimension(800,600));
frame.setMaximumSize(new Dimension(800,600));
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setIconImage(new ImageIcon(getResourceImg("icon1.png").getScaledInstance(200, 200, java.awt.Image.SCALE_SMOOTH)).getImage());
progressBar = new JProgressBar();
progressBar.setValue(0);
progressBar.setFont(fontPlainBold);
progressBar.setBorderPainted(false);
progressBar.setStringPainted(true);
frame.addWindowListener(new WindowListener(){
public void windowActivated(WindowEvent arg0) {}
public void windowClosed(WindowEvent arg0) {}
public void windowClosing(WindowEvent arg0) {
if(r!=null){
MessageDialog quit = new MessageDialog("Quit", "Quit application?");
boolean exit = false;
try {
exit = quit.createQuestionDialog();
} catch (IOException e) {
e.printStackTrace();
}
if(exit){
try{
r.shutdown();
System.exit(1);
} catch (Exception x) {
System.out.println("R code error: "+x.getMessage());
}
}
else
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
} else{
try {
MessageDialog md = new MessageDialog("Shutdown", "Shutdown succesful.", "INFORMATION_MESSAGE", new ImageIcon(getResourceImg("info.png").getScaledInstance(40, 40, java.awt.Image.SCALE_SMOOTH)));
md.createDialog();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {
progressBar.setIndeterminate(true);
TaskOpenR openR = new TaskOpenR();
try {
openR.doInBackground();
} catch (IOException e) {
e.printStackTrace();
}
}
});
homeScreen = new JPanel();
homeScreen.setBackground(backgroundColor);
homeScreen.setLayout(new MigLayout("insets 50 25 80 50", "[grow][grow][grow]", "[grow][fill]15[fill]"));
frame.add(homeScreen);
frame.setBackground(backgroundColor);
{
HS_title_panel = new JPanel();
{
HS_title_panel.setLayout(new MigLayout("insets 0 100 0 100", "[grow][grow]", "[grow]"));
HS_title_panel.setBackground(backgroundColor);
HS_pic_label = new JLabel(new ImageIcon(getResourceImg("icon1.png").getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH)));
HS_pic_label.getInsets().set(0, 50, 0, 0);
HS_name_lbl = new JTextPane();
HS_name_lbl.setEditable(false);
HS_name_lbl.setMargin(new Insets(130, 0, 0, 0));
HS_name_lbl.setBackground(backgroundColor);
HS_name_lbl.setForeground(mainColor);
HS_name_lbl.setText("InteGene");
HS_name_lbl.setFont(fontTitle);
HS_title_panel.add(HS_pic_label, "grow");
HS_title_panel.add(HS_name_lbl, "grow");
}
HS_details_panel = new JPanel();
{
Color details = Color.decode("#E99FA6");
HS_details_panel.setBackground(details);
}
HS_start_button = new JButton(new ImageIcon(getResourceImg("arrow-point-to-right.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
HS_start_button.setEnabled(false);
HS_start_button.setText("Start");
HS_start_button.setFont(fontButton);
HS_start_button.setForeground(buttonTextColor);
HS_start_button.setBackground(buttonColor);
HS_start_button.setMargin(new Insets(5,15,5,15));
HS_start_button.setIconTextGap(10);
HS_start_button.setFocusPainted(false);
HS_start_button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
frame.remove(homeScreen);
frame.setContentPane(mainDisplay_pane);
frame.setResizable(true);
frame.revalidate();
frame.repaint();
}
});
HS_instructions_button = new JButton(new ImageIcon(getResourceImg("how.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
HS_instructions_button.setEnabled(false);
HS_instructions_button.setText("Getting Started");
HS_instructions_button.setFont(fontButton);
HS_instructions_button.setForeground(buttonTextColor);
HS_instructions_button.setBackground(buttonColor);
HS_instructions_button.setMargin(new Insets(5,15,5,15));
HS_instructions_button.setIconTextGap(10);
HS_instructions_button.setFocusPainted(false);
HS_instructions_button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.remove(frame.getContentPane());
frame.setContentPane(instructions_pane);
frame.revalidate();
frame.repaint();
}
});
HS_about_button = new JButton(new ImageIcon(getResourceImg("info.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
HS_about_button.setEnabled(false);
HS_about_button.setText("About");
HS_about_button.setFont(fontButton);
HS_about_button.setForeground(buttonTextColor);
HS_about_button.setBackground(buttonColor);
HS_about_button.setMargin(new Insets(5,15,5,15));
HS_about_button.setIconTextGap(10);
HS_about_button.setFocusPainted(false);
HS_about_button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.remove(frame.getContentPane());
frame.setContentPane(aboutScreen);
frame.revalidate();
frame.repaint();
}
});
}
instructions_pane = new JTabbedPane(JTabbedPane.TOP);
instructions_pane.setForeground(buttonTextColor);
{
instructions_pane.setFont(fontButton);
IP_mainMenu_listener = new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.remove(mainDisplay_pane);
frame.setContentPane(homeScreen);
frame.revalidate();
frame.repaint();
}
};
IP_general = new JPanel();{
IP_general.setLayout(new MigLayout("insets 20", "[grow]", "[][grow]20[]"));
IP_general.setBackground(backgroundColor);
IP_general_title_panel = new JPanel();
IP_general_title_panel.setLayout(new MigLayout("insets 10 180 0 100", "[grow][grow]", "[grow]20[grow]"));
IP_general_title_panel.setBackground(backgroundColor);
IP_general_pic_label = new JLabel(new ImageIcon(getResourceImg("icon1.png").getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH)));
IP_general_name_lbl = new JTextPane();
IP_general_name_lbl.setEditable(false);
IP_general_name_lbl.setMargin(new Insets(15, 0, 0, 0));
IP_general_name_lbl.setBackground(backgroundColor);
IP_general_name_lbl.setForeground(mainColor);
IP_general_name_lbl.setText("InteGene");
IP_general_name_lbl.setFont(fontTitleSmaller);
IP_general_title_panel.add(IP_general_pic_label, "grow");
IP_general_title_panel.add(IP_general_name_lbl, "grow");
IP_mainMenu1 = new JButton(new ImageIcon(getResourceImg("arrow-point-to-left.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
IP_mainMenu1.setText("Main Menu");
IP_mainMenu1.setFont(fontButton);
IP_mainMenu1.setBackground(buttonColor);
IP_mainMenu1.setForeground(buttonTextColor);
IP_mainMenu1.addActionListener(IP_mainMenu_listener);
IP_mainMenu1.setMargin(new Insets(5,15,5,15));
IP_general_text = new JEditorPane("text/html", "");
IP_general_text.setBackground(panelColor);
IP_general_text.setMargin(new Insets(20,20,20,20));
IP_general_text.setFont(fontPlain);
String fontfamily = IP_general_text.getFont().getFamily();
IP_general_text.setText("<html><body style=\"font-family: " + fontfamily + "\"" + getResourceFileAsString("how-to-use.txt") + "<html>");
IP_general_text.setEditable(false);
IP_general_text_scr = new JScrollPane(IP_general_text);
IP_general_text_scr.setBorder(new CompoundBorder(new EmptyBorder(0, 0, 0, 0), new LineBorder(mainColor, 1)));
IP_general.add(IP_general_title_panel, "span");
IP_general.add(IP_general_text_scr, "grow, span");
IP_general.add(IP_mainMenu1, "tag left");
}
IP_constraints = new JPanel();{
IP_constraints.setBackground(backgroundColor);
IP_constraints.setLayout(new MigLayout("insets 20", "[grow]", "[][grow]20[]"));
IP_constraints_title_panel = new JPanel();
IP_constraints_title_panel.setLayout(new MigLayout("insets 10 180 0 100", "[grow][grow]", "[grow]20[grow]"));
IP_constraints_title_panel.setBackground(backgroundColor);
IP_constraints_pic_label = new JLabel(new ImageIcon(getResourceImg("icon1.png").getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH)));
IP_constraints_name_lbl = new JTextPane();
IP_constraints_name_lbl.setEditable(false);
IP_constraints_name_lbl.setMargin(new Insets(15, 0, 0, 0));
IP_constraints_name_lbl.setBackground(backgroundColor);
IP_constraints_name_lbl.setForeground(mainColor);
IP_constraints_name_lbl.setText("InteGene");
IP_constraints_name_lbl.setFont(fontTitleSmaller);
IP_constraints_title_panel.add(IP_constraints_pic_label, "grow");
IP_constraints_title_panel.add(IP_constraints_name_lbl, "grow");
IP_mainMenu2 = new JButton(new ImageIcon(getResourceImg("arrow-point-to-left.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
IP_mainMenu2.setText("Main Menu");
IP_mainMenu2.setFont(fontButton);
IP_mainMenu2.setBackground(buttonColor);
IP_mainMenu2.setForeground(buttonTextColor);
IP_mainMenu2.setMargin(new Insets(5,15,5,15));
IP_mainMenu2.addActionListener(IP_mainMenu_listener);
IP_constraints_text = new JEditorPane("text/html", "");
IP_constraints_text.setMargin(new Insets(20,20,20,20));
IP_constraints_text.setFont(fontText);
IP_constraints_text.setBackground(panelColor);
String fontfamily = IP_constraints_text.getFont().getFamily();
IP_constraints_text.setText("<html><body style=\"font-family: " + fontfamily + "\"" + getResourceFileAsString("constraints.txt") + "<html>");
IP_constraints_text.setEditable(false);
IP_constraints_text_scr = new JScrollPane(IP_constraints_text);
IP_constraints_text_scr.setBorder(new CompoundBorder(new EmptyBorder(0, 0, 0, 0), new LineBorder(mainColor, 1)));
IP_constraints.add(IP_constraints_title_panel, "span");
IP_constraints.add(IP_constraints_text_scr, "grow, span");
IP_constraints.add(IP_mainMenu2, "tag left");
}
IP_limitations = new JPanel();{
IP_limitations.setBackground(backgroundColor);
IP_limitations.setLayout(new MigLayout("insets 20", "[grow]", "[][grow]20[]"));
IP_limitations.setFont(fontPlain);
IP_limitations_title_panel = new JPanel();
IP_limitations_title_panel.setLayout(new MigLayout("insets 10 180 0 100", "[grow][grow]", "[grow]20[grow]"));
IP_limitations_title_panel.setBackground(backgroundColor);
IP_limitations_pic_label = new JLabel(new ImageIcon(getResourceImg("icon1.png").getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH)));
IP_limitations_name_lbl = new JTextPane();
IP_limitations_name_lbl.setEditable(false);
IP_limitations_name_lbl.setMargin(new Insets(15, 0, 0, 0));
IP_limitations_name_lbl.setBackground(backgroundColor);
IP_limitations_name_lbl.setForeground(mainColor);
IP_limitations_name_lbl.setText("InteGene");
IP_limitations_name_lbl.setFont(fontTitleSmaller);
IP_limitations_title_panel.add(IP_limitations_pic_label, "grow");
IP_limitations_title_panel.add(IP_limitations_name_lbl, "grow");
IP_mainMenu3 = new JButton(new ImageIcon(getResourceImg("arrow-point-to-left.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
IP_mainMenu3.setText("Main Menu");
IP_mainMenu3.setFont(fontButton);
IP_mainMenu3.setBackground(buttonColor);
IP_mainMenu3.setForeground(buttonTextColor);
IP_mainMenu3.setMargin(new Insets(5,15,5,15));
IP_mainMenu3.addActionListener(IP_mainMenu_listener);
IP_limitations_text = new JEditorPane("text/html", "");
IP_limitations_text.setMargin(new Insets(20,20,20,20));
IP_limitations_text.setFont(fontText);
IP_limitations_text.setBackground(panelColor);
String fontfamily = IP_limitations_text.getFont().getFamily();
IP_limitations_text.setText("<html><body style=\"font-family: " + fontfamily + "\"" + getResourceFileAsString("limitations.txt") + "<html>");
IP_limitations_text.setEditable(false);
IP_limitations_text_scr = new JScrollPane(IP_limitations_text);
IP_limitations_text_scr.setBorder(new CompoundBorder(new EmptyBorder(0, 0, 0, 0), new LineBorder(mainColor, 1)));
IP_limitations.add(IP_limitations_title_panel, "span");
IP_limitations.add(IP_limitations_text_scr, "grow, span");
IP_limitations.add(IP_mainMenu3, "tag left");
}
instructions_pane.addTab("How To Use Tool", IP_general);
instructions_pane.addTab("Data Constraints", IP_constraints);
instructions_pane.addTab("Limitations", IP_limitations);
instructions_pane.setIconAt(0, new ImageIcon(getResourceImg("how.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
instructions_pane.setIconAt(1, new ImageIcon(getResourceImg("constraints.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
instructions_pane.setIconAt(2, new ImageIcon(getResourceImg("limitations.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
}
aboutScreen = new JPanel();{
aboutScreen.setBackground(backgroundColor);
aboutScreen.setLayout(new MigLayout("insets 20", "[grow]", "[grow][grow]20[]"));
AS_title_panel = new JPanel();
AS_title_panel.setLayout(new MigLayout("insets 0 100 0 100", "[grow][grow]", "[grow]"));
AS_title_panel.setBackground(backgroundColor);
AS_pic_label = new JLabel(new ImageIcon(getResourceImg("icon1.png").getScaledInstance(150, 150, java.awt.Image.SCALE_SMOOTH)));
AS_pic_label.getInsets().set(0, 50, 0, 0);
AS_name_lbl = new JTextPane();
AS_name_lbl.setEditable(false);
AS_name_lbl.setMargin(new Insets(80, 0, 0, 0));
AS_name_lbl.setBackground(backgroundColor);
AS_name_lbl.setForeground(mainColor);
AS_name_lbl.setText("InteGene");
AS_name_lbl.setFont(fontTitle);
AS_title_panel.add(AS_pic_label, "grow");
AS_title_panel.add(AS_name_lbl, "grow");
AS_about_text = new JEditorPane("text/html", "");
AS_about_text.setFont(fontPlain);
AS_about_text.setBackground(backgroundColor);
String fontfamily = AS_about_text.getFont().getFamily();
AS_about_text.setText("<html><body style=\"font-family: " + fontfamily + "\"" + getResourceFileAsString("about.txt") + "<html>");
AS_back_btn = new JButton(new ImageIcon(getResourceImg("arrow-point-to-left.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
AS_back_btn.setText("Main Menu");
AS_back_btn.setFont(fontButton);
AS_back_btn.setBackground(buttonColor);
AS_back_btn.setForeground(buttonTextColor);
AS_back_btn.setMargin(new Insets(5,15,5,15));
AS_back_btn.setIconTextGap(10);
AS_back_btn.addActionListener(IP_mainMenu_listener);
aboutScreen.add(AS_title_panel, "grow, span");
aboutScreen.add(AS_about_text, "grow, span");
aboutScreen.add(AS_back_btn, "tag left");
}
homeScreen.add(HS_title_panel, "grow, span");
homeScreen.add(HS_start_button, "growx");
homeScreen.add(HS_instructions_button, "growx");
homeScreen.add(HS_about_button, "growx, span");
homeScreen.add(progressBar, "growx, span");
mainDisplay_pane = new JTabbedPane(JTabbedPane.TOP);
mainDisplay_pane.setFont(fontButton);
{
MD_input_panel = new JPanel();{
MD_input_panel.setLayout(new MigLayout("insets 20", "[][grow]", "[][]10[]10[grow]10[]"));
JLabel label = new JLabel();
label.setText("Select input data: ");
label.setFont(largeText);
label.setForeground(Color.black);
MD_input_panel.setBackground(backgroundColor);
MD_IP_filename = null;
MD_IP_about = new JTextPane();
MD_IP_about.setBackground(backgroundColor);
MD_IP_about.setFont(fontPlainSmall);
MD_IP_about.setMargin(new Insets(0,0,0,0));
MD_IP_about.setEditable(false);
MD_IP_about.setText("File must be in CSV format and each row must contain the genome name followed by the genes in the genome. ");
MD_IP_openFile_button = new JButton(new ImageIcon(getResourceImg("folder.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
MD_IP_openFile_button.setText("Open CSV File");
MD_IP_openFile_button.setMargin(new Insets(5,10,5,10));
MD_IP_openFile_button.setFont(fontButton);
MD_IP_openFile_button.setBackground(buttonColor);
MD_IP_openFile_button.setForeground(buttonTextColor);
MD_IP_openFile_button.setIconTextGap(10);
MD_IP_openFile_button.setFocusPainted(false);
MD_IP_filename_text = new JTextField();
MD_IP_filename_text.setMargin(new Insets(7,10,7,10));
MD_IP_filename_text.setFont(fontPlain);
MD_IP_filename_text.setEditable(false);
MD_IP_filename_text.setBackground(backgroundColor);
MD_IP_preview = new JTextArea();
MD_IP_preview.setFont(fontPlain);
MD_IP_preview_scr = new JScrollPane(MD_IP_preview);
MD_IP_preview.setEditable(false);
MD_IP_preview.setMargin(new Insets(10,10,10,10));
MD_IP_next_btn = new JButton(new ImageIcon(getResourceImg("arrow-point-to-right.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
MD_IP_next_btn.setEnabled(false);
MD_IP_next_btn.setMargin(new Insets(5,15,5,15));
MD_IP_next_btn.setText("Preview");
MD_IP_next_btn.setHorizontalTextPosition(SwingConstants.LEFT);
MD_IP_next_btn.setFont(fontButton);
MD_IP_next_btn.setBackground(buttonColor);
MD_IP_next_btn.setForeground(buttonTextColor);
MD_IP_next_btn.setIconTextGap(10);
MD_IP_next_btn.setFocusPainted(false);
MD_IP_next_btn.addActionListener(new TabActions(mainDisplay_pane, 1));
MD_IP_mainMenu_btn = new JButton(new ImageIcon(getResourceImg("arrow-point-to-left.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
MD_IP_mainMenu_btn.setText("Main Menu");
MD_IP_mainMenu_btn.setMargin(new Insets(5,15,5,15));
MD_IP_mainMenu_btn.setFont(fontButton);
MD_IP_mainMenu_btn.setBackground(buttonColor);
MD_IP_mainMenu_btn.setForeground(buttonTextColor);
MD_IP_mainMenu_btn.setIconTextGap(10);
MD_IP_mainMenu_btn.setFocusPainted(false);
MD_IP_mainMenu_btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.remove(mainDisplay_pane);
frame.setContentPane(homeScreen);
frame.setSize(800, 600);
frame.setResizable(false);
frame.revalidate();
frame.repaint();
}
});
MD_input_progressBar = new JProgressBar();
MD_input_progressBar.setBorderPainted(false);
MD_input_progressBar.setFont(fontPlainBold);
MD_input_progressBar.setStringPainted(true);
MD_IP_openFile_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new File(System.getProperty("user.dir")));
jfc.showDialog(null,"Please Select the File");
jfc.setVisible(true);
if(jfc.getSelectedFile()!=null){
MD_IP_filename = jfc.getSelectedFile();
MD_IP_filename_text.setText(MD_IP_filename.getAbsolutePath());
TaskConvert task = new TaskConvert();
try {
MD_input_progressBar.setIndeterminate(true);
task.doInBackground();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
MD_input_panel.add(label, "span");
MD_input_panel.add(MD_IP_about, "span");
MD_input_panel.add(MD_IP_openFile_button);
MD_input_panel.add(MD_IP_filename_text, "growx, span");
MD_input_panel.add(MD_IP_preview_scr, "grow, span");
MD_input_panel.add(MD_input_progressBar, "growx, span");
MD_input_panel.add(MD_IP_mainMenu_btn, "tag bottom");
MD_input_panel.add(MD_IP_next_btn, "tag right, span");
}
MD_preview_panel = new JPanel();
{
MD_preview_panel.setLayout(new MigLayout("insets 20, wrap 4", "[grow]", "[][]10[150px, grow]10[][]10[150px, grow]10[]"));
MD_preview_panel.setBackground(backgroundColor);
MD_PP_preview_lbl = new JLabel();
MD_PP_preview_lbl.setText("Original data: ");
MD_PP_preview_lbl.setFont(largeText);
MD_PP_preview_lbl.getInsets().set(0, 0, 0, 0);
MD_PP_preview_about = new JTextPane();
MD_PP_preview_about.setBackground(backgroundColor);
MD_PP_preview_about.setFont(fontPlainSmall);
MD_PP_preview_about.setText("Provided below is the data as represented in the file. ");
MD_PP_preview_about.setEditable(false);
MD_PP_preview_about.setMargin(new Insets(0,0,0,0));
MD_PP_preview_text = new JEditorPane("text/html", "");
MD_PP_preview_text.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
MD_PP_preview_text.setFont(fontPlain);
MD_PP_preview_text.setEditable(false);
MD_PP_preview_scr = new JScrollPane(MD_PP_preview_text);
MD_PP_previewConverted_lbl = new JLabel();
MD_PP_previewConverted_lbl.setText("Converted data: ");
MD_PP_previewConverted_lbl.setFont(largeText);
MD_PP_previewConverted_lbl.getInsets().set(0, 0, 0, 0);
MD_PP_previewConverted_about = new JTextPane();
MD_PP_previewConverted_about.setBackground(backgroundColor);
MD_PP_previewConverted_about.setFont(fontPlainSmall);
MD_PP_previewConverted_about.setText("Provided below is the converted data wherein the genes are represented as positive integers and non-homologs are represented as 0's.");
MD_PP_previewConverted_about.setEditable(false);
MD_PP_previewConverted_about.setMargin(new Insets(0,0,0,0));
MD_PP_previewConverted_text = new JEditorPane("text/html", "");
MD_PP_previewConverted_text.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
MD_PP_previewConverted_text.setFont(fontPlain);
MD_PP_previewConverted_text.setEditable(false);
MD_PP_previewConverted_scr = new JScrollPane(MD_PP_previewConverted_text);
MD_PP_back_btn = new JButton(new ImageIcon(getResourceImg("arrow-point-to-left.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
MD_PP_back_btn.setText("Back");
MD_PP_back_btn.setMargin(new Insets(5,15,5,15));
MD_PP_back_btn.setHorizontalTextPosition(SwingConstants.RIGHT);
MD_PP_back_btn.setFont(fontButton);
MD_PP_back_btn.setBackground(buttonColor);
MD_PP_back_btn.setForeground(buttonTextColor);
MD_PP_back_btn.setIconTextGap(10);
MD_PP_back_btn.setFocusPainted(false);
MD_PP_back_btn.addActionListener(new TabActions(mainDisplay_pane, 0));
MD_PP_next_btn = new JButton(new ImageIcon(getResourceImg("arrow-point-to-right.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
MD_PP_next_btn.setText("Next");
MD_PP_next_btn.setMargin(new Insets(5,15,5,15));
MD_PP_next_btn.setHorizontalTextPosition(SwingConstants.LEFT);
MD_PP_next_btn.setFont(fontButton);
MD_PP_next_btn.setBackground(buttonColor);
MD_PP_next_btn.setForeground(buttonTextColor);
MD_PP_next_btn.setIconTextGap(10);
MD_PP_next_btn.setFocusPainted(false);
MD_PP_next_btn.addActionListener(new TabActions(mainDisplay_pane, 2));
MD_preview_panel.add(MD_PP_preview_lbl, "growx, span, wrap");
MD_preview_panel.add(MD_PP_preview_about, "growx, span, wrap");
MD_preview_panel.add(MD_PP_preview_scr, "grow, span, wrap");
MD_preview_panel.add(MD_PP_previewConverted_lbl, "growx, span, wrap");
MD_preview_panel.add(MD_PP_previewConverted_about, "growx, span, wrap");
MD_preview_panel.add(MD_PP_previewConverted_scr, "grow, span, wrap");
MD_preview_panel.add(MD_PP_back_btn, "tag left");
MD_preview_panel.add(MD_PP_next_btn, "tag right, span");
}
MD_variables_panel = new JPanel();{
MD_variables_panel.setLayout(new MigLayout("insets 20, aligny 50%", "[150px, grow][150px, grow]", "[grow]10[grow][grow]10[grow][fill]10[]"));
MD_variables_panel.setBackground(backgroundColor);
MD_VP_linear_lbl = new JLabel();
MD_VP_linear_lbl.setFont(largeText);
MD_VP_linear_lbl.setText("Choose linear programming approach: ");
MD_VP_linear_about = new JTextPane();
MD_VP_linear_about.setFont(fontPlainSmall);
MD_VP_linear_about.setBackground(panelColor);
MD_VP_linear_about.setMargin(new Insets(0,0,0,0));
MD_VP_linear_about.setEditable(false);
MD_VP_linear_about.setText("The programming approach defines whether the integrality constraint is relaxed or not. LP Relaxation fastens the process but does not guarantee the best clusters.");
String[] LP = {"Integer Linear Programming", "LP Relaxation"};
MD_VP_linear = new JComboBox<String>(LP);
MD_VP_linear.setBackground(Color.white);
MD_VP_linear.setFont(fontPlain);
MD_VP_linear.setSelectedItem(0);
JPanel programming = new JPanel();
programming.setLayout(new MigLayout("", "[grow]", "[]5[grow]15[]"));
programming.setBackground(panelColor);
programming.add(MD_VP_linear_lbl, "grow, span");
programming.add(MD_VP_linear_about, "grow, span");
programming.add(MD_VP_linear, "grow, span, tag bottom");
MD_VP_linear.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
if(MD_VP_linear.getSelectedIndex() == 0){
isRelaxed = false;
}
else isRelaxed = true;
}
});
MD_VP_formulation_lbl = new JLabel();
MD_VP_formulation_lbl.setFont(largeText);
MD_VP_formulation_lbl.setText("Choose formulation to use: ");
MD_VP_formulation_about = new JTextPane();
MD_VP_formulation_about.setFont(fontPlainSmall);
MD_VP_formulation_about.setBackground(panelColor);
MD_VP_formulation_about.setMargin(new Insets(0,0,0,0));
MD_VP_formulation_about.setEditable(false);
MD_VP_formulation_about.setText("The formulation describes the kind of gene clusters being looked for. For definitions, refer to Getting Started in the home screen. ");
String[] types = {"General", "Common Intervals", "Max Gap", "r-Windows"};
MD_VP_group = new JComboBox<String>(types);
MD_VP_group.setBackground(Color.white);
MD_VP_group.setFont(fontPlain);
MD_VP_group.setSelectedItem(0);
setBasicFormulation(true);
JPanel formulation = new JPanel();
formulation.setBackground(panelColor);
formulation.setLayout(new MigLayout("aligny 50%", "[grow]", "[]5[grow]15[]"));
formulation.add(MD_VP_formulation_lbl, "grow, span");
formulation.add(MD_VP_formulation_about, "grow, span");
formulation.add(MD_VP_group, "grow, span, tag bottom");
MD_VP_group.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
MD_VP_from_spnr.setEnabled(true);
MD_VP_to_spnr.setEnabled(true);
MD_VP_missing_spnr.setEnabled(true);
MD_VP_additional_spnr.setEnabled(true);
MD_VP_gapSize_spnr.setEnabled(false);
MD_VP_rWindowSize_spnr.setEnabled(false);
setCommonIntervals(false);
setMaxGap(false);
setrWindows(false);
if (MD_VP_group.getSelectedIndex() == 0){
setBasicFormulation(true);
}
else if(MD_VP_group.getSelectedIndex() == 1){
MD_VP_missing_spnr.setEnabled(false);
MD_VP_missing_spnr.setValue(1);
MD_VP_additional_spnr.setEnabled(false);
MD_VP_additional_spnr.setValue(1);
setBasicFormulation(false);
setCommonIntervals(true);
}
else if(MD_VP_group.getSelectedIndex() == 2){
MD_VP_missing_spnr.setEnabled(false);
MD_VP_missing_spnr.setValue(0);
MD_VP_additional_spnr.setEnabled(false);
MD_VP_additional_spnr.setValue(0);
MD_VP_gapSize_spnr.setEnabled(true);
setBasicFormulation(false);
setMaxGap(true);
}
else if(MD_VP_group.getSelectedIndex() == 3){
MD_VP_from_spnr.setEnabled(false);
MD_VP_to_spnr.setEnabled(true);
MD_VP_missing_spnr.setEnabled(false);
MD_VP_missing_spnr.setValue(1);
MD_VP_additional_spnr.setEnabled(false);
MD_VP_additional_spnr.setValue(0);
MD_VP_rWindowSize_spnr.setEnabled(true);
setBasicFormulation(false);
setrWindows(true);
}
}
});
MD_VP_constraints_lbl = new JLabel();
MD_VP_constraints_lbl.setText("Input constraints: ");
MD_VP_constraints_lbl.setFont(largeText);
MD_VP_constraints_about = new JTextPane();
MD_VP_constraints_about.setBackground(panelColor);
MD_VP_constraints_about.setFont(fontPlainSmall);
MD_VP_constraints_about.setMargin(new Insets(0,0,0,0));
MD_VP_constraints_about.setEditable(false);
MD_VP_constraints_about.setText("The input constraints define further the kind of gene clusters being looked for. The definitions of each can also be found in Getting Started in the home screen.");
MD_VP_sizeRangeLower_lbl = new JLabel();
MD_VP_sizeRangeLower_lbl.setText("Size (lower bound): D-");
MD_VP_sizeRangeLower_lbl.setFont(fontPlain);
MD_VP_sizeRangeHigher_lbl = new JLabel();
MD_VP_sizeRangeHigher_lbl.setText("(upper bound) D+");
MD_VP_sizeRangeHigher_lbl.setFont(fontPlain);
MD_VP_from_numberModel = new SpinnerNumberModel(2, 2, 2, 1);
MD_VP_from_spnr = new JSpinner(MD_VP_from_numberModel);
MD_VP_from_spnr.setFont(fontPlain);
MD_VP_from_spnr.addChangeListener(new ChangeListener(){
@SuppressWarnings("rawtypes")
public void stateChanged(ChangeEvent arg0) {
MD_VP_to_numberModel.setMinimum((Comparable) MD_VP_from_spnr.getValue());
if((int)MD_VP_to_spnr.getValue() < (int)MD_VP_from_spnr.getValue()){
MD_VP_to_spnr.setValue(MD_VP_from_spnr.getValue());
}
}
});
MD_VP_to_numberModel = new SpinnerNumberModel(2, 2, 2, 1);
MD_VP_to_spnr = new JSpinner(MD_VP_to_numberModel);
MD_VP_to_spnr.setFont(fontPlain);
MD_VP_additionalWeight_lbl = new JLabel();
MD_VP_additionalWeight_lbl.setText("Additional Gene Weight (w+) ");
MD_VP_additionalWeight_lbl.setFont(fontPlain);
MD_VP_additionalWeight_numberModel = new SpinnerNumberModel(0, 0, 100, 1);
MD_VP_additional_spnr = new JSpinner(MD_VP_additionalWeight_numberModel);
MD_VP_additional_spnr.setFont(fontPlain);
MD_VP_missingWeight_lbl = new JLabel();
MD_VP_missingWeight_lbl.setText("Missing Gene Weight (w-)");
MD_VP_missingWeight_lbl.setFont(fontPlain);
MD_VP_missingWeight_numberModel = new SpinnerNumberModel(0, 0, 100, 1);
MD_VP_missing_spnr = new JSpinner(MD_VP_missingWeight_numberModel);
MD_VP_missing_spnr.setFont(fontPlain);
MD_VP_gapSize_numberModel = new SpinnerNumberModel(0, 0, 100, 1);
MD_VP_gapSize_lbl = new JLabel();
MD_VP_gapSize_lbl.setText("Max Gap Size");
MD_VP_gapSize_lbl.setFont(fontPlain);
MD_VP_gapSize_spnr = new JSpinner(MD_VP_gapSize_numberModel);
MD_VP_gapSize_spnr.setFont(fontPlain);
MD_VP_rWindowSize_Lbl = new JLabel();
MD_VP_rWindowSize_Lbl.setText("k Size");
MD_VP_rWindowSize_Lbl.setFont(fontPlain);
MD_VP_kSize_numberModel = new SpinnerNumberModel(0, 0, 100, 1);
MD_VP_rWindowSize_spnr = new JSpinner(MD_VP_kSize_numberModel);
MD_VP_rWindowSize_spnr.setFont(fontPlain);
MD_VP_gapSize_spnr.setEnabled(false);
MD_VP_rWindowSize_spnr.setEnabled(false);
MD_VP_from_spnr.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent arg0) {
setSizeRangeLower((int)MD_VP_from_spnr.getValue());
}
});
MD_VP_to_spnr.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e) {
setSizeRangeHigher((int)MD_VP_to_spnr.getValue());
}
});
MD_VP_additional_spnr.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e) {
setAdditionalGeneWeight((int)MD_VP_additional_spnr.getValue());
}
});
MD_VP_missing_spnr.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e) {
setMissingGeneWeight((int)MD_VP_missing_spnr.getValue());
}
});
MD_VP_gapSize_spnr.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e) {
setMaxGapSize((int)MD_VP_gapSize_spnr.getValue());
}
});
MD_VP_rWindowSize_spnr.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e) {
setrWindowSize((int)MD_VP_rWindowSize_spnr.getValue());
}
});
JPanel constraints = new JPanel();
constraints.setBackground(panelColor);
constraints.setLayout(new MigLayout("aligny 50%", "[grow]5[grow]10[grow]5[grow]", "[]5[]15[]10[]10[]"));
constraints.add(MD_VP_constraints_lbl, "growx, span");
constraints.add(MD_VP_constraints_about, "growx, span");
constraints.add(MD_VP_sizeRangeLower_lbl, "grow, tag right");
constraints.add(MD_VP_from_spnr, "grow");
constraints.add(MD_VP_sizeRangeHigher_lbl, "grow, tag right");
constraints.add(MD_VP_to_spnr, "grow, span");
constraints.add(MD_VP_missingWeight_lbl, "grow, tag right");
constraints.add(MD_VP_missing_spnr, "grow");
constraints.add(MD_VP_additionalWeight_lbl, "grow, tag right");
constraints.add(MD_VP_additional_spnr, "grow, span");
constraints.add(MD_VP_gapSize_lbl, "grow, tag right");
constraints.add(MD_VP_gapSize_spnr, "grow");
constraints.add(MD_VP_rWindowSize_Lbl, "grow, tag right");
constraints.add(MD_VP_rWindowSize_spnr, "grow, span");
MD_VP_back_btn = new JButton(new ImageIcon(getResourceImg("arrow-point-to-left.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
MD_VP_back_btn.setText("Back");
MD_VP_back_btn.setMargin(new Insets(5,15,5,15));
MD_VP_back_btn.setBackground(buttonColor);
MD_VP_back_btn.setForeground(buttonTextColor);
MD_VP_back_btn.setFont(fontButton);
MD_VP_back_btn.setIconTextGap(10);
MD_VP_back_btn.setFocusPainted(false);
MD_VP_back_btn.addActionListener(new TabActions(mainDisplay_pane, 1));
MD_VP_next_btn = new JButton(new ImageIcon(getResourceImg("arrow-point-to-right.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
MD_VP_next_btn.setText("Solve");
MD_VP_next_btn.setHorizontalTextPosition(SwingConstants.LEFT);
MD_VP_next_btn.setMargin(new Insets(5,15,5,15));
MD_VP_next_btn.setBackground(buttonColor);
MD_VP_next_btn.setForeground(buttonTextColor);
MD_VP_next_btn.setFont(fontButton);
MD_VP_next_btn.setFocusPainted(false);
MD_VP_next_btn.setIconTextGap(10);
ListSelectionListener listener = new ListSelectionListener(){
@Override
public void valueChanged(ListSelectionEvent e) {
int selected = MD_results_list.getSelectedIndex();
MD_RP_results_text.setText(res[selected]);
}
};
MD_VP_next_btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(rWindows){
MD_VP_from_spnr.setValue(MD_VP_to_spnr.getValue());
}
MD_results_list.removeListSelectionListener(listener);
MD_RP_results_text.removeAll();
TaskSolve task = new TaskSolve();
MD_results_list.clearSelection();
try {
MD_VP_progressBar.setIndeterminate(true);
task.doInBackground();
MD_results_list.addListSelectionListener(listener);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
MD_variables_panel.add(programming, "grow");
MD_variables_panel.add(formulation, "grow, span");
formulation_constraints_sep = new JSeparator();
MD_variables_panel.add(formulation_constraints_sep, "grow, span");
MD_variables_panel.add(constraints, "grow, span");
constraints_prog_sep = new JSeparator();
MD_variables_panel.add(constraints_prog_sep, "grow, span");
MD_VP_progressBar = new JProgressBar();
MD_VP_progressBar.setBorderPainted(false);
MD_VP_progressBar.setFont(fontPlainBold);
MD_VP_progressBar.setValue(0);
MD_VP_progressBar.setStringPainted(true);
MD_variables_panel.add(MD_VP_progressBar, " grow, span");
MD_variables_panel.add(MD_VP_back_btn, " tag left");
MD_variables_panel.add(MD_VP_next_btn, " tag right, span");
}
MD_results_panel = new JPanel();{
MD_results_panel.setLayout(new MigLayout("insets 20", "[grow]10[grow]", "[][150px, grow]20[]10[150px,grow]10[]"));
MD_results_panel.setBackground(backgroundColor);
MD_RP_results_lbl = new JLabel();
MD_RP_results_lbl.setBackground(backgroundColor);
MD_RP_results_lbl.setText("Resulting Clusters: ");
MD_RP_results_lbl.setFont(largeText);
MD_RP_positions_lbl = new JLabel();
MD_RP_positions_lbl.setBackground(backgroundColor);
MD_RP_positions_lbl.setText("Clusters in genomes: ");
MD_RP_positions_lbl.setFont(largeText);
MD_RP_constraints_lbl = new JLabel();
MD_RP_constraints_lbl.setBackground(backgroundColor);
MD_RP_constraints_lbl.setText("Summary: ");
MD_RP_constraints_lbl.setFont(largeText);
MD_results_list = new JList<String>();
MD_results_list.setFont(fontPlainBold);
DefaultListCellRenderer renderer = (DefaultListCellRenderer)MD_results_list.getCellRenderer();
renderer.setHorizontalAlignment(JLabel.CENTER);
MD_results_list_scr = new JScrollPane(MD_results_list);
MD_results_list.setBackground(panelColor);
MD_results_list.setForeground(mainColor);
MD_results_list_scr.setBorder(new CompoundBorder(new EmptyBorder(0, 0, 0, 0), new LineBorder(mainColor, 1)));
MD_RP_results_text = new JEditorPane("text/html", "");
MD_RP_results_text.setFont(fontPlainSmall);
MD_RP_results_text.setEditable(false);
MD_RP_results_scr = new JScrollPane(MD_RP_results_text);
MD_RP_results_text.setBackground(Color.decode("#E1E8ED"));
MD_RP_results_scr.setBorder(new CompoundBorder(new EmptyBorder(0, 0, 0, 0), new LineBorder(mainColor, 1)));
MD_RP_constraints_text = new JEditorPane("text/html", "");
MD_RP_constraints_text.setBackground(Color.decode("#CCD6DD"));
MD_RP_constraints_text.setForeground(Color.white);
MD_RP_constraints_text.setBorder(new CompoundBorder(new EmptyBorder(0, 0, 0, 0), new LineBorder(mainColor, 1)));
MD_RP_constraints_text.setEditable(false);
JPanel buttons = new JPanel();
buttons.setLayout(new MigLayout("insets 0", "[grow]10[grow]10[grow]", "[grow]"));
buttons.setBackground(backgroundColor);
MD_RP_back_btn = new JButton(new ImageIcon(getResourceImg("arrow-point-to-left.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
MD_RP_back_btn.setText("Back");
MD_RP_back_btn.setMargin(new Insets(5,15,5,15));
MD_RP_back_btn.setFont(fontButton);
MD_RP_back_btn.setBackground(buttonColor);
MD_RP_back_btn.setFocusPainted(false);
MD_RP_back_btn.setForeground(buttonTextColor);
MD_RP_back_btn.setIconTextGap(10);
MD_RP_back_btn.addActionListener(new TabActions(mainDisplay_pane,2));
MD_RP_exportPDF_btn = new JButton(new ImageIcon(getResourceImg("export.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
MD_RP_exportPDF_btn.setText("Export PDF");
MD_RP_exportPDF_btn.setMargin(new Insets(5,15,5,15));
MD_RP_exportPDF_btn.setBackground(buttonColor);
MD_RP_exportPDF_btn.setFont(fontButton);
MD_RP_exportPDF_btn.setForeground(buttonTextColor);
MD_RP_exportPDF_btn.setFocusPainted(false);
MD_RP_exportPDF_btn.setIconTextGap(10);
MD_RP_exportCSV_btn = new JButton(new ImageIcon(getResourceImg("export.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
MD_RP_exportCSV_btn.setText("Export CSV");
MD_RP_exportCSV_btn.setMargin(new Insets(5,15,5,15));
MD_RP_exportCSV_btn.setBackground(buttonColor);
MD_RP_exportCSV_btn.setForeground(buttonTextColor);
MD_RP_exportCSV_btn.setFont(fontButton);
MD_RP_exportCSV_btn.setFocusPainted(false);
MD_RP_exportCSV_btn.setIconTextGap(10);
buttons.add(MD_RP_back_btn, "grow");
buttons.add(MD_RP_exportPDF_btn, "grow");
buttons.add(MD_RP_exportCSV_btn, "grow");
MD_results_panel.add(MD_RP_results_lbl, "growx, span");
MD_results_panel.add(MD_results_list_scr, "grow, span");
MD_results_panel.add(MD_RP_constraints_lbl, "growx");
MD_results_panel.add(MD_RP_positions_lbl, "growx, span");
MD_results_panel.add(MD_RP_constraints_text, "grow");
MD_results_panel.add(MD_RP_results_scr, "grow, span");
MD_results_panel.add(buttons, "growx, span");
MD_RP_exportPDF_btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
chooser.setDialogTitle("Save as");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter pdfFilter = new FileNameExtensionFilter("PDF files", ".pdf");
fileChooser.setFileFilter(pdfFilter);
if (fileChooser.showSaveDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
try {
ExportPDF exportPdf = new ExportPDF(file);
ArrayList<String> words = new ArrayList<String>();
words.add(MD_IP_filename.getAbsolutePath());
if(MD_VP_group.getSelectedIndex()==1) words.add("Common Intervals");
else if(MD_VP_group.getSelectedIndex()==0) words.add("Basic Formulation");
else if(MD_VP_group.getSelectedIndex()==2) words.add("Max-gap");
else if(MD_VP_group.getSelectedIndex()==3) words.add("r-Windows");
words.add(Integer.toString((int) MD_VP_from_spnr.getValue()));
words.add(Integer.toString((int) MD_VP_to_spnr.getValue()));
words.add(Integer.toString((int) MD_VP_additional_spnr.getValue()));
words.add(Integer.toString((int) MD_VP_missing_spnr.getValue()));
words.add(Integer.toString((int) MD_VP_gapSize_spnr.getValue()));
words.add(Integer.toString((int) MD_VP_rWindowSize_spnr.getValue()));
exportPdf.writeConstraints(words);
exportPdf.writeResults(results.size(), solve.getPdfOutput());
exportPdf.close();
} catch (IOException e1) {
e1.printStackTrace();
}
// save to file
}
}
});
MD_RP_exportCSV_btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
chooser.setDialogTitle("Save as");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter csvFilter = new FileNameExtensionFilter("CSV files", ".csv");
fileChooser.setFileFilter(csvFilter);
if (fileChooser.showSaveDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
try {
ExportCSV exportCsv = new ExportCSV(file);
for(int i=0; i<results.size(); i++){
ArrayList<String> write = new ArrayList<String>();
write.add("Reference Gene Set #" + (i+1));
write.addAll(results.get(i).getGeneContentStr());
exportCsv.write(write);
}
exportCsv.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
}
mainDisplay_pane.addTab("Input Data", MD_input_panel);
mainDisplay_pane.addTab("Preview", MD_preview_panel);
mainDisplay_pane.addTab("Constraints", MD_variables_panel);
mainDisplay_pane.addTab("Results",MD_results_panel);
mainDisplay_pane.setIconAt(0, new ImageIcon(getResourceImg("input-data.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
mainDisplay_pane.setIconAt(1, new ImageIcon(getResourceImg("preview.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
mainDisplay_pane.setIconAt(2, new ImageIcon(getResourceImg("constraints.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
mainDisplay_pane.setIconAt(3, new ImageIcon(getResourceImg("results.png").getScaledInstance(25, 25, java.awt.Image.SCALE_SMOOTH)));
mainDisplay_pane.setFont(fontButton);
mainDisplay_pane.setEnabledAt(1, false);
mainDisplay_pane.setEnabledAt(2, false);
mainDisplay_pane.setEnabledAt(3, false);
}
}
private Image getResourceImg(String name) throws IOException{
InputStream logoInput = getClass().getClassLoader().getResourceAsStream(name);
Image logoImg = new ImageIcon(ImageIO.read(logoInput)).getImage();
return logoImg;
}
private String getResourceFileAsString(String fileName) {
InputStream is = getClass().getClassLoader().getResourceAsStream(fileName);
if (is != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
return reader.lines().collect(Collectors.joining(System.lineSeparator()));
}
return null;
}
public int getAdditionalGeneWeight() {
return additionalGeneWeight;
}
public void setAdditionalGeneWeight(int additionalGeneWeight) {
this.additionalGeneWeight = additionalGeneWeight;
}
public boolean isBasicFormulation() {
return basicFormulation;
}
public void setBasicFormulation(boolean basicFormulation) {
this.basicFormulation = basicFormulation;
}
public boolean isCommonIntervals() {
return commonIntervals;
}
public void setCommonIntervals(boolean commonIntervals) {
this.commonIntervals = commonIntervals;
}
public boolean isMaxGap() {
return maxGap;
}
public void setMaxGap(boolean maxGap) {
this.maxGap = maxGap;
}
public boolean isrWindows() {
return rWindows;
}
public void setrWindows(boolean rWindows) {
this.rWindows = rWindows;
}
public int getMissingGeneWeight() {
return missingGeneWeight;
}
public void setMissingGeneWeight(int missingGeneWeight) {
this.missingGeneWeight = missingGeneWeight;
}
public int getSizeRangeLower() {
return sizeRangeLower;
}
public void setSizeRangeLower(int sizeRangeLower) {
this.sizeRangeLower = sizeRangeLower;
}
public int getSizeRangeHigher() {
return sizeRangeHigher;
}
public void setSizeRangeHigher(int sizeRangeHigher) {
this.sizeRangeHigher = sizeRangeHigher;
}
public int getMaxGapSize() {
return maxGapSize;
}
public void setMaxGapSize(int maxGapSize) {
this.maxGapSize = maxGapSize;
}
public int getrWindowSize() {
return rWindowSize;
}
public void setrWindowSize(int rWindowSize) {
this.rWindowSize = rWindowSize;
}
public ILPFormulation getSolve() {
return solve;
}
public void setSolve(ILPFormulation solve) {
this.solve = solve;
}
public static void main(String[] args) throws IOException{
Main window = new Main();
window.frame.setVisible(true);
}
public int getNumOfGenomes() {
return numOfGenomes;
}
public void setNumOfGenomes(int numOfGenomes) {
this.numOfGenomes = numOfGenomes;
}
class TaskConvert extends SwingWorker<Void, Void> {
public Void doInBackground() throws IOException {
Executor executor = java.util.concurrent.Executors.newSingleThreadExecutor();
((ExecutorService) executor).submit(new Runnable() {
public void run() {
try {
MD_input_panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
MD_input_progressBar.setString("Converting data...");
MD_VP_progressBar.setValue(0);
MD_VP_progressBar.setString("0%");
dc = new DataConverter(MD_IP_filename.getAbsolutePath());
BufferedReader br = new BufferedReader(new FileReader(MD_IP_filename));
MD_IP_preview.setText("");
String line = br.readLine();
while(line != null){
MD_IP_preview.append(line + "\n");
line = br.readLine();
}
MD_IP_preview.setCaretPosition(0);
MD_PP_preview_text.setText(dc.getAllGenomes());
MD_PP_preview_text.setCaretPosition(0);
MD_PP_previewConverted_text.setText(dc.getAllConvertedGenomes());
MD_PP_previewConverted_text.setCaretPosition(0);
MD_VP_from_numberModel.setMaximum(dc.getMaxGenomeSize());
MD_VP_to_numberModel.setMaximum(dc.getMaxGenomeSize());
if(dc.getNumberOfGenomes() == 2){
if(MD_VP_group.getItemCount()==3){
MD_VP_group.addItem("r-Windows");
}
} else {
MD_VP_group.removeItemAt(3);
}
done();
} catch (IOException e) {
e.printStackTrace();
}
}
private void done() {
MD_input_panel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
MD_IP_next_btn.setEnabled(true);
MD_input_progressBar.setValue(100);
MD_input_progressBar.setIndeterminate(false);
MD_input_progressBar.setString("Data Converted!");
Toolkit.getDefaultToolkit().beep();
} });
return null;
}
}
class TaskSolve extends SwingWorker<Void, Void> {
long startTime = 0, endTime = 0;
public Void doInBackground() throws IOException {
Executor executor = java.util.concurrent.Executors.newSingleThreadExecutor();
((ExecutorService) executor).submit(new Runnable() {
public void run() {
MD_variables_panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
MD_variables_panel.setEnabled(false);
MD_VP_progressBar.setString("Calculating...");
MD_VP_back_btn.setEnabled(false);
MD_VP_next_btn.setEnabled(false);
startTime = System.nanoTime();
solve = new ILPFormulation(dc.getGenomes(), dc.getGenes(), dc.getMap(), isRelaxed, additionalGeneWeight, missingGeneWeight, sizeRangeLower, sizeRangeHigher, getMaxGapSize(), getrWindowSize(), isBasicFormulation(), isCommonIntervals(), isMaxGap(), isrWindows());
if(!isRelaxed){
try {
solve.generateGeneSets();
results = new ArrayList<GeneSet>();
results = solve.solve(r);
} catch (RserveException | REXPMismatchException e) {
e.printStackTrace();
}
} else{
try {
solve.generateGeneSets();
results = new ArrayList<GeneSet>();
results = solve.solveRelax(r);
} catch (RserveException | REXPMismatchException e) {
e.printStackTrace();
}
}
int cost = solve.getMinimumCost();
endTime = System.nanoTime();
String fontfamily = MD_RP_constraints_text.getFont().getFamily();
if(results.size()>0){
if(!isRelaxed) res = solve.getPositions();
else res = solve.getPositionsRelaxed();
System.out.println("results length" + res.length);
MD_results_list.setListData(solve.getAllResults());
MD_results_list.setSelectedIndex(0);
MD_RP_constraints_text.setFont(fontPlain);
String LPformulation = "";
if(isRelaxed) LPformulation = "LP Relaxation cost: ";
else LPformulation = "ILP cost: ";
MD_RP_constraints_text.setText(""
+ "<html><body><table style='font-family:"+fontfamily+";font-size: 12pt ;width: 100% ; border-spacing:0px ; padding:0px';>"
+ "<tr>"
+ "<td colspan='2'> File location: " + MD_IP_filename.getAbsolutePath() + "</td>"
+ "</tr>"
+ "<tr>"
+ "<td> Number of results: " + results.size() + "</td>"
+ "<td> Time elapsed: " + (double)Math.round((double)(endTime-startTime)/1000000000.0 * 10000d) / 10000d + "s" + "</td>"
+ "</tr>"
+ "<tr>"
+ "<td colspan> Formulation: " + String.valueOf(MD_VP_group.getSelectedItem()) + "</td>"
+ "<td colspan>" + LPformulation + cost + "</td>"
+ "</tr>"
+ "<tr>"
+ "<td> D- = " + sizeRangeLower + "</td>"
+ "<td> D+ = " + sizeRangeHigher + "</td>"
+ "</tr>"
+ "<tr>"
+ "<td> w- = " + missingGeneWeight + "</td>"
+ "<td> w+ = " + additionalGeneWeight + "</td>"
+ "</tr>"
+ "<tr>"
+ "<td> Gap size = " + getMaxGapSize() + "</td>"
+ "<td> k size = " + getrWindowSize() + "</td>"
+ "</tr>"
+ "</table></body></html>");
MD_results_list.setEnabled(true);
MD_RP_exportCSV_btn.setEnabled(true);
MD_RP_exportPDF_btn.setEnabled(true);
} else{
String [] res = new String[1];
res[0] = "Nothing to show";
MD_results_list.setListData(res);
MD_results_list.setEnabled(false);
MD_RP_constraints_text.setText(""
+ "<html><body><table style='font-family:"+fontfamily+";font-size: 12pt ;width: 100% ; border-spacing:0px ; padding:0px';>"
+ "<tr>"
+ "<td colspan='2'> File location: " + MD_IP_filename.getAbsolutePath() + "</td>"
+ "</tr>"
+ "<tr>"
+ "<td colspan='2'> Number of results: 0 </td>"
+ "</tr>"
+ "<tr>"
+ "<td colspan ='2'> Formulation: " + String.valueOf(MD_VP_group.getSelectedItem()) + "</td>"
+ "</tr>"
+ "<tr>"
+ "<td> D- = " + sizeRangeLower + "</td>"
+ "<td> D+ = " + sizeRangeHigher + "</td>"
+ "</tr>"
+ "<tr>"
+ "<td> w- = " + missingGeneWeight + "</td>"
+ "<td> w+ = " + additionalGeneWeight + "</td>"
+ "</tr>"
+ "<tr>"
+ "<td> Gap size = " + getMaxGapSize() + "</td>"
+ "<td> k size = " + getrWindowSize() + "</td>"
+ "</tr>"
+ "</table></body></html>");
MD_RP_results_text.setText("None");
MD_RP_exportCSV_btn.setEnabled(false);
MD_RP_exportPDF_btn.setEnabled(false);
}
mainDisplay_pane.setEnabledAt(0, false);
mainDisplay_pane.setEnabledAt(1, false);
mainDisplay_pane.setEnabledAt(2, false);
mainDisplay_pane.setEnabledAt(3, true);
mainDisplay_pane.setSelectedIndex(3);
done();
}
private void done() {
MD_VP_back_btn.setEnabled(true);
MD_VP_next_btn.setEnabled(true);
MD_variables_panel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
MD_VP_progressBar.setString("Done!");
MD_VP_progressBar.setValue(100);
MD_VP_progressBar.setIndeterminate(false);
Toolkit.getDefaultToolkit().beep();
} });
return null;
}
}
class TaskOpenR extends SwingWorker<Void, Void> {
public Void doInBackground() throws IOException {
Executor executor = java.util.concurrent.Executors.newSingleThreadExecutor();
((ExecutorService) executor).submit(new Runnable() {
public void run() {
homeScreen.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
progressBar.setString("Loading dependencies...");
while(r==null){
System.out.println("result="+RConnector.checkLocalRserve());
try {
r = new RConnection();
if(r.eval("require('lpSolve') == FALSE").asString().equals("TRUE")){
System.out.println("Installing package...");
r.eval("install.packages('lpSolve')\n");
r.eval("install.packages('lpSolveAPI')\n");
} else{
System.out.println("Package already installed. ");
}
} catch (Exception x) {
System.out.println("R code error: "+x.getMessage());
}
}
done();
}
private void done() {
homeScreen.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
HS_start_button.setEnabled(true);
HS_instructions_button.setEnabled(true);
HS_about_button.setEnabled(true);
progressBar.setString("Dependencies loaded.");
progressBar.setValue(100);
progressBar.setIndeterminate(false);
Toolkit.getDefaultToolkit().beep();
} });
return null;
}
}
}
<file_sep>/src/javaBackend/DataConverter.java
package javaBackend;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.SwingWorker;
public class DataConverter extends SwingWorker<Void, Void>{
private ArrayList<Genome> allGenomes;
private ArrayList<Genome> convertedAllGenomes;
private ArrayList<Gene> allGenes;
private MapStringArrayList map;
private int maxGenomeSize;
public DataConverter(String filePath) throws IOException{
System.out.println("Converting data...");
allGenomes = new ArrayList<Genome>();
convertedAllGenomes = new ArrayList<Genome>();
allGenes = new ArrayList<Gene>();
map = new MapStringArrayList();
setMaxGenomeSize(0);
String line = "";
int id = 1;
@SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader(filePath));
allGenes.add(new Gene("0", 0));
for(int i = 0; (line = br.readLine()) != null; i++){
String[] temp = line.split(",");
Genome genome = new Genome(temp[0], i);
ArrayList<Gene> genes = new ArrayList<Gene>();
if(maxGenomeSize < (temp.length-1)){
this.maxGenomeSize = temp.length-1;
}
for(int j=1; j<temp.length; j++){
if(temp[j].equals("0")){
ArrayList<Integer> newArr = new ArrayList<Integer>();
newArr.add(id);
newArr.add(1);
map.add(Integer.toString(id), newArr);
Gene gene = new Gene(Integer.toString(id), id);
id++;
genes.add(gene);
allGenes.add(gene);
}
else if(!map.containsKey(temp[j])){
ArrayList<Integer> newArr = new ArrayList<Integer>();
newArr.add(id);
newArr.add(1);
map.add(temp[j], newArr);
Gene gene = new Gene(temp[j], id);
id++;
genes.add(gene);
allGenes.add(gene);
} else{
int existingId = map.getIntegerMapping(temp[j]);
Gene gene = new Gene(temp[j], existingId);
genes.add(gene);
map.increaseOccurence(temp[j]);
}
}
genome.setGenes(genes);
allGenomes.add(genome);
}
//printStuff();
//printAllGenes();
replaceNonHomologs();
System.out.println("Data converted!");
}
public void replaceNonHomologs(){
for(int i=0; i<allGenomes.size(); i++){
for(int j=0; j<allGenomes.get(i).getGenes().size(); j++){
if(map.getMappingOccurence(allGenomes.get(i).getGenes().get(j).getGeneName()) == 1){
allGenomes.get(i).getGenes().get(j).setGeneNumberRep(0);
}
}
} reduceGenes();
}
private void reduceGenes(){
for(int i=1; i<allGenes.size(); i++){
if(allGenes.get(i).getGeneNumberRep() == 0){
allGenes.remove(i);
i--;
}
}
}
public MapStringArrayList getMap(){
return this.map;
}
public ArrayList<Genome> getGenomes(){
return this.allGenomes;
}
public int getNumberOfGenomes(){
return this.allGenomes.size();
}
public ArrayList<Genome> getConvertedGenomes(){
return this.convertedAllGenomes;
}
public ArrayList<Gene> getGenes(){
return this.allGenes;
}
public void printStuff(){
for(String name: map.keySet()){
String key = name.toString();
ArrayList<Integer> values = map.getValues(key);
System.out.println(key + ": (" + values.get(0) + "," + values.get(1) + ")");
}
}
public void printAllGenomes(){
for(int i=0; i<allGenomes.size(); i++){
System.out.print(allGenomes.get(i).getGenomeName() + ": ");
allGenomes.get(i).printGenes();
}
}
/*
public String getAllGenomes(){
StringBuilder sb = new StringBuilder();
for(int i=0; i<allGenomes.size(); i++){
sb.append(allGenomes.get(i).getGenomeName() + ": ");
for(int j=0; j<allGenomes.get(i).size(); j++){
sb.append(allGenomes.get(i).getGene(j).getGeneName() + " ");
} sb.append("\n");
}
return sb.toString();
}*/
public String getAllGenomes(){
String res = "";
for(int i=0; i<allGenomes.size(); i++){
res += "<b>" + allGenomes.get(i).getGenomeName() + "</b> : ";
for(int j=0; j<allGenomes.get(i).size(); j++){
res += allGenomes.get(i).getGene(j).getGeneName() + " ";
} res += "<br>";
}
return res;
}
/*
public String getAllConvertedGenomes(){
StringBuilder sb = new StringBuilder();
for(int i=0; i<allGenomes.size(); i++){
sb.append(allGenomes.get(i).getGenomeName() + ": ");
for(int j=0; j<allGenomes.get(i).size(); j++){
sb.append(allGenomes.get(i).getGene(j).getGeneNumberRep() + " ");
} sb.append("\n");
}
return sb.toString();
}*/
public String getAllConvertedGenomes(){
String res = "";
for(int i=0; i<allGenomes.size(); i++){
res += "<b>" + allGenomes.get(i).getGenomeName() + "</b> : ";
for(int j=0; j<allGenomes.get(i).size(); j++){
res += allGenomes.get(i).getGene(j).getGeneNumberRep() + " ";
} res += "<br>";
}
return res;
}
public void printAllConvertedGenomes(){
for(int i=0; i<allGenomes.size(); i++){
System.out.print(allGenomes.get(i).getGenomeName() + ": ");
allGenomes.get(i).printConvertedGenes();
}
}
/*
private void printAllGenes(){
System.out.println("All Genes");
for(int i=0; i< allGenes.size(); i++){
System.out.println(allGenes.get(i).getGeneName() + " : " + allGenes.get(i).getGeneNumberRep());
}
}*/
public int getMaxGenomeSize() {
return maxGenomeSize;
}
public void setMaxGenomeSize(int maxGenomeSize) {
this.maxGenomeSize = maxGenomeSize;
}
@Override
protected Void doInBackground() throws Exception {
return null;
}
/*
public void printKeyValuePairs(){
System.out.println("Gene Name - Integer Representation");
for(String name: geneMap.keySet()){
String key =name.toString();
String value = geneMap.get(name).toString();
System.out.println(key + " " + value);
}
}*/
}
|
d485b17b3830c36a60791cd60c6cd3fe75c6f8c0
|
[
"Java"
] | 5
|
Java
|
cessflorendo/Special-Problem
|
9eda400700323f0f2d04076d1d2db85559602e0a
|
70b44e261ad0f3a097b7713ce280ebf4431c3909
|
refs/heads/master
|
<file_sep>--// Initialization
local Module = {}
--// Functions
function Module.RoundNumber(Number, Divider)
--/ Rounds a number using round half up
Divider = Divider or 1
return math.floor(Number / Divider + 0.5) * Divider
end
function Module.PickRandom(Values)
--/ Will return a random pick from a table; NOT DICTIONARY
return Values[math.random(1, #Values)]
end
function Module.GenerateString(Length)
--/ Will return a random string of the required length
assert(Length ~= nil, "A string length must be specified")
local GeneratedString = ""
for Count = 1, Length do
GeneratedString = GeneratedString .. string.char(math.random(65, 90))
end
return GeneratedString
end
function Module.GetIndexByValue(Values, DesiredValue)
--/ Returns the index of a value in a table or dictionary
for Index, Value in next, Values do
if Value == DesiredValue then
return Index
end
end
return nil
end
function Module.MergeTables(...)
--/ Merges tables and dictionaries
local MergedTable = {}
for ArgumentIndex, Argument in ipairs({...}) do
assert(type(Argument) == "table", "Argument " .. ArgumentIndex .. " is not a table")
for Index, Value in ipairs(Argument) do
if type(Index) == "number" then
table.insert(MergedTable, Value)
else
table.insert(MergedTable, Index, Value)
end
end
end
return MergedTable
end
function Module.GetDescendants(ObjectInstance)
--/ Returns descendants of an Instances
local Descendants = ObjectInstance:GetChildren()
local Count = 0
repeat
Count = Count + 1
Descendants = Module.MergeTables(
Descendants,
Descendants[Count]:GetChildren()
)
until Count == #Descendants
return Descendants
end
function Module.CallOnChildren(ParentInstance, FunctionToCall, Recursive)
--/ Runs a function on all children of an Instance
--/ If Recursive is true, will run on all descendants
assert(typeof(ParentInstance) == "Instance", "ParentInstance is not an Instance")
assert(type(FunctionToCall) == "function", "FunctionToCall is not a function")
if #ParentInstance:GetChildren() == 0 then return end
local Children = Recursive and Module.GetDescendants(ParentInstance) or ParentInstance:GetChildren()
for _, Child in next, Children do
FunctionToCall(Child)
end
end
function Module.Modify(ObjectInstance, Values)
--/ Modifies an Instance using a table of properties and values
assert(typeof(ObjectInstance) == "Instance", "ObjectInstance is not an Instance")
assert(type(Values) == "table", "Values is not a table")
for Property, Value in next, Values do
if type(Property) == "number" then
Value.Parent = ObjectInstance
else
ObjectInstance[Property] = Value
end
end
return ObjectInstance
end
function Module.Retrieve(InstanceName, InstanceClass, InstanceParent)
--/ Finds an Instance by name and creates a new one if it doesen't exist
local SearchInstance = nil
local InstanceCreated = false
if InstanceParent:FindFirstChild(InstanceName) then
SearchInstance = InstanceParent[InstanceName]
else
InstanceCreated = true
SearchInstance = Instance.new(InstanceClass)
SearchInstance.Name = InstanceName
SearchInstance.Parent = InstanceParent
end
return SearchInstance, InstanceCreated
end
return Module
|
e1127ef314415cc00d36d223ff3dcb83c203663d
|
[
"Lua"
] | 1
|
Lua
|
Validark/sModules
|
d6e724f654ee4f9a02bac4860ad8d77717f76ffd
|
d0a3eb08b15c1d003078659b6c0b4527b6291ae9
|
refs/heads/master
|
<file_sep>package com.mycompany.agendaturnos;
// Generated 01/12/2017 19:43:32 by Hibernate Tools 4.3.1
import java.util.Date;
/**
* Turno generated by hbm2java
*/
public class Turno implements java.io.Serializable {
private int idTurno;
private Cliente cliente;
private String descripcion;
private Date fecha;
public Turno() {
}
public Turno(int idTurno, Cliente cliente) {
this.idTurno = idTurno;
this.cliente = cliente;
}
public Turno(int idTurno, Cliente cliente, String descripcion, Date fecha) {
this.idTurno = idTurno;
this.cliente = cliente;
this.descripcion = descripcion;
this.fecha = fecha;
}
public int getIdTurno() {
return this.idTurno;
}
public void setIdTurno(int idTurno) {
this.idTurno = idTurno;
}
public Cliente getCliente() {
return this.cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public String getDescripcion() {
return this.descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Date getFecha() {
return this.fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
}
<file_sep>package com.mycompany.agendaturnos;
// Generated 01/12/2017 19:43:32 by Hibernate Tools 4.3.1
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
* Cliente generated by hbm2java
*/
@Entity
@Table (name="cliente")
public class Cliente implements java.io.Serializable {
private Integer idcliente;
private String nombre;
private String telefono;
private String descripcion;
private Set turnos = new HashSet(0);
public Cliente() {
}
public Cliente(String nombre) {
this.nombre = nombre;
}
public Cliente(String nombre, String telefono){
this.nombre = nombre;
this.telefono = telefono;
}
public Cliente(String nombre, String telefono, String descripcion, Set turnos) {
this.nombre = nombre;
this.telefono = telefono;
this.descripcion = descripcion;
this.turnos = turnos;
}
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
public Integer getIdcliente() {
return this.idcliente;
}
public void setIdcliente(Integer idcliente) {
this.idcliente = idcliente;
}
@Column (name="nombre")
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
@Column (name="telefono")
public String getTelefono() {
return this.telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
@Column (name="descripcion")
public String getDescripcion() {
return this.descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Set getTurnos() {
return this.turnos;
}
public void setTurnos(Set turnos) {
this.turnos = turnos;
}
@Override
public String toString() {
return "Cliente{" + "idcliente=" + idcliente + ", nombre=" + nombre + ", telefono=" + telefono + ", descripcion=" + descripcion + ", turnos=" + turnos + '}';
}
}
|
e9d6a44368df7eee4e322534fa7e3db8e75c233f
|
[
"Java"
] | 2
|
Java
|
PaguaMauricio/sistemaTurnos
|
1d735d2f5aac5b0ca71ea78748da63064e4efaac
|
0157e98363514d7a3dec13444ca0281b2c44556c
|
refs/heads/master
|
<file_sep># Fornecedores
É apenas um projeto simples para o aprendizados de Laravel. Está sendo desenvolvida uma API REST utilizando o Passport para autenticação.
<file_sep><?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\API\BaseController as BaseController;
use \App\Models\Fornecedor;
class FornecedoresController extends BaseController
{
/**
* Retorna a listagem de um registros.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$resources = Fornecedor::all();
return $this->sendResponse($resources->toArray(), 'Fornecedores retornados com sucesso.');
}
/**
* Retorna um registro específico.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$resource = Fornecedor::find($id);
if (is_empty($resource)) {
return $this->sendError('Fornecedor não encontrado.');
}
return $this->sendResponse($resource->toArray(), 'Fornecedor obtido com sucesso.');
}
/**
* Armazena um registro recém criado no banco.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = $request->all();
$validator = Validator::make($input, [
'nome_fantasia' => 'required',
'razao_social' => 'required',
'cnpj' => 'required'
]);
if($validator->fails()){
return $this->sendError('Erro de validação.', $validator->errors());
}
$resource = Fornecedor::create($input);
return $this->sendResponse($resource->toArray(), 'Fornecedor criado com sucesso.');
}
/**
* Atualiza um registro específico no banco.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Fornecedor $fornecedor)
{
$input = $request->all();
$validator = Validator::make($input, [
'nome_fantasia' => 'required',
'razao_social' => 'required',
'cnpj' => 'required'
]);
if($validator->fails()){
return $this->sendError('Erro de validação.', $validator->errors());
}
$fornecedor->nome_fantasia = $input['nome_fantasia'];
$fornecedor->razao_social = $input['razao_social'];
$fornecedor->cnpj = $input['cnpj'];
$fornecedor->save();
return $this->sendResponse($fornecedor->toArray(), 'Fornecedor atualizado com sucesso.');
}
/**
* Exclui um registro específico do banco.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Fornecedor $fornecedor)
{
$fornecedor->delete();
return $this->sendResponse($fornecedor->toArray(), 'Fornecedor excluído com sucesso.');
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFornecedoresTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('fornecedores', function (Blueprint $table) {
$table->increments('id');
$table->integer('id_endereco');
$table->string('nome_fantasia')->nullable(false);
$table->string('razao_social')->nullable(false)->unique();
$table->string('cnpj')->nullable(false)->unique();
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('fornecedores');
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome', [
'name' => 'World'
]);
});
/*Route::get('fornecedores', function () {
$fornecedores = DB::table('fornecedores')->get();
return view('fornecedores', compact('fornecedores'));
});*/
//Route::get('fornecedores', 'API\FornecedoresController@index');
//Route::get('fornecedores/{fornecedor}', 'API\FornecedoresController@show');<file_sep><?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
class PessoaController extends Controller
{
//
}
<file_sep><?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
/*
Adicione esses headers às requisições.
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
]
Personal access client created successfully.
Client ID: 1
Client Secret: <KEY>
Password grant client created successfully.
Client ID: 2
Client Secret: <KEY>
*/
/*Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});*/
// App v1 API
Route::group([
'middleware' => ['app', 'api.version:1'],
'namespace' => 'App\Http\Controllers\App',
'prefix' => 'api/v1',
], function ($router) {
require base_path('routes/app_api.v1.php');
});
// App v2 API
/*Route::group([
'middleware' => ['app', 'api.version:2'],
'namespace' => 'App\Http\Controllers\App',
'prefix' => 'api/v2',
], function ($router) {
require base_path('routes/app_api.v2.php');
});*/
Route::post('register', 'API\RegisterController@register');
Route::middleware('auth:api')->group( function () {
Route::resource('fornecedores', 'API\FornecedoresController');
Route::get('fornecedores', 'API\FornecedoresController@index');
//Route::get('fornecedores/{fornecedor}', 'API\FornecedoresController@show');
});
<file_sep><?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class RegisterController extends BaseController
{
/**
* Register API
*
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => '<PASSWORD>',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->sendError('Erro de validação.', $validator->errors());
}
$input = $request->all();
$input['password'] = <PASSWORD>($input['<PASSWORD>']);
$user = User::create($input);
$success['token'] = $user->createToken('CentralFornecedores')->accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'Usuário registrado com sucesso.');
}
catch (\Illuminate\Database\QueryException $e) {
$errorCode = $e->errorInfo[1];
if ($errorCode == '1062') {
return $this->sendError('Esse e-mail já está cadastrado para um usuário.');
}
else {
return $this->sendError('Houve alguma falha inesperada de banco de dados.');
}
}
catch (\Exception $e) {
return $this->sendError('Ocorreu alguma falha inesperada durante o cadastro.');
}
}
}<file_sep><?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\API\BaseController as BaseController;
use Illuminate\Http\Request;
class TelefoneController extends Controller
{
//
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTelefonesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('telefones', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('id_pessoa')->nullable();
$table->unsignedInteger('id_fornecedor')->nullable();
$table->unsignedInteger('id_ponto_apoio')->nullable();
$table->string('ddd', 3)->nullable(false);
$table->string('numero', 10)->nullable(false);
$table->foreign('id_pessoa')->references('id')->on('pessoas')
->onUpdate('CASCADE');
$table->foreign('id_fornecedor')->references('id')->on('pessoas')
->onUpdate('CASCADE');
$table->foreign('id_ponto_apoio')->references('id')->on('pessoas')
->onUpdate('CASCADE');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('telefones');
}
}
<file_sep><?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller as Controller;
/**
* Base controller classe, to be extended for all controller classes.
*
* @category Controller
* @package App\Http\Controllers\Api
* @author <NAME> <<EMAIL>>
* @license BSD-3-Clause <https://opensource.org/licenses/BSD-3-Clause>
* @link https://github.com/evandroabukamel/fornecedores
*/
class BaseController extends Controller
{
/**
* Get the resouce for a class name and API version.
*
* @param string $resourceName Resouce name.
* @param array ...$args Arguments.
*
* @return object
*/
public function resource($resourceName, ...$args)
{
// Get's the request's api version, or the latest if undefined
$v = config('app.api_version', config('app.api_latest'));
$className = $this->getResourceClassname($resourceName, $v);
$class = new \ReflectionClass($className);
return $class->newInstanceArgs($args);
}
/**
* Parse Api\Resource for
* App\Http\Resources\Api\v{$v}\Resource
*
* @param string $className Classname for versioning.
* @param string $v API Verion to be called.
*
* @return string
*/
protected function getResourceClassname($className, $v)
{
$re = '/.*\\\\(.*)/';
return 'App\Http\Resources\\' .
preg_replace($re, 'Api\\v' . $v . '\\\$1', $className);
}
/**
* Success response method.
*
* @param array|object $result Data structure to be returned.
* @param string $message Text message for the response.
*
* @return \Illuminate\Http\Response
*/
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
/**
* Return error response.
*
* @param string $error Unique error message.
* @param array $errorMessages An array of error messages.
* @param integer $code HTTP error code.
*
* @return \Illuminate\Http\Response
*/
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];
if (!empty($errorMessages)) {
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
}<file_sep>CREATE DATABASE `app_prestador` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci */;
CREATE TABLE `endereco` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tabela_referencia` varchar(100) COLLATE utf8_general_ci NOT NULL,
`id_objeto` int(11) NOT NULL,
`cep` varchar(9) COLLATE utf8_general_ci NOT NULL,
`logradouro` varchar(100) COLLATE utf8_general_ci NOT NULL,
`numero` varchar(45) COLLATE utf8_general_ci NOT NULL,
`complemento` varchar(100) COLLATE utf8_general_ci DEFAULT NULL,
`bairro` varchar(100) COLLATE utf8_general_ci NOT NULL,
`cidade` varchar(100) COLLATE utf8_general_ci NOT NULL,
`estado` varchar(2) COLLATE utf8_general_ci NOT NULL,
`latlong` point NOT NULL,
`latitude` varchar(45) COLLATE utf8_general_ci NOT NULL,
`longitude` varchar(45) COLLATE utf8_general_ci NOT NULL,
`data_cadastro` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE `pessoa` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_endereco` int(11) NOT NULL,
`id_ponto_apoio` int(11) DEFAULT NULL,
`nome` varchar(200) COLLATE utf8_general_ci NOT NULL,
`cpf` varchar(14) COLLATE utf8_general_ci NOT NULL,
`data_nascimento` date DEFAULT NULL,
`data_cadastro` date NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_pessoa_endereco` (`id_endereco`),
KEY `fk_pessoa_pontoapoio1_idx` (`id_ponto_apoio`),
CONSTRAINT `fk_pessoa_endereco1` FOREIGN KEY (`id_endereco`) REFERENCES `endereco` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_pessoa_pontoapoio1` FOREIGN KEY (`id_ponto_apoio`) REFERENCES `ponto_apoio` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE `ponto_apoio` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_endereco` int(11) NOT NULL,
`id_prestador` int(11) NOT NULL,
`tipo_ponto_apoio` enum('P','M') COLLATE utf8_general_ci NOT NULL,
`apelido` varchar(45) COLLATE utf8_general_ci NOT NULL,
`nome_fantasia` varchar(200) COLLATE utf8_general_ci NOT NULL,
`contato` varchar(50) COLLATE utf8_general_ci NOT NULL,
`email_contato` varchar(100) COLLATE utf8_general_ci DEFAULT NULL,
`data_cadastro` date DEFAULT NULL,
PRIMARY KEY (`id`,`id_endereco`,`id_prestador`),
KEY `fk_ponto_apoio_endereco` (`id_endereco`),
KEY `fk_ponto_apoio_prestador` (`id_prestador`),
CONSTRAINT `fk_ponto_apoio_endereco` FOREIGN KEY (`id_endereco`) REFERENCES `endereco` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_ponto_apoio_prestador` FOREIGN KEY (`id_prestador`) REFERENCES `prestador` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE `prestador` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nome_fantasia` varchar(200) COLLATE utf8_general_ci NOT NULL,
`razao_social` varchar(200) COLLATE utf8_general_ci NOT NULL,
`cnpj` varchar(18) COLLATE utf8_general_ci NOT NULL,
`inscricao_estadual` varchar(20) COLLATE utf8_general_ci DEFAULT NULL,
`inscricao_municipal` varchar(20) COLLATE utf8_general_ci DEFAULT NULL,
`website` varchar(100) COLLATE utf8_general_ci DEFAULT NULL,
`data_cadastro` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE `telefone` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_pessoa` int(11) DEFAULT NULL,
`id_prestador` int(11) DEFAULT NULL,
`id_ponto_apoio` int(11) DEFAULT NULL,
`ddd` varchar(3) COLLATE utf8_general_ci NOT NULL,
`numero` varchar(10) COLLATE utf8_general_ci NOT NULL,
`situacao` enum('A','I','E') COLLATE utf8_general_ci NOT NULL DEFAULT 'A',
`data_cadastro` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_telefone_pessoa1_idx` (`id_pessoa`),
KEY `fk_telefone_prestador1_idx` (`id_prestador`),
KEY `fk_telefone_pontoapoio1_idx` (`id_ponto_apoio`),
CONSTRAINT `fk_telefone_pessoa1` FOREIGN KEY (`id_pessoa`) REFERENCES `pessoa` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_telefone_prestador1` FOREIGN KEY (`id_prestador`) REFERENCES `prestador` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_telefone_pontoapoio1` FOREIGN KEY (`id_ponto_apoio`) REFERENCES `ponto_apoio` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE `tipo_pessoa` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`descricao` varchar(50) COLLATE utf8_general_ci NOT NULL,
`nivel` enum('S','U') COLLATE utf8_general_ci NOT NULL DEFAULT 'U',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE `tipo_pessoa_pessoa` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tbtipopessoa_id` int(11) NOT NULL,
`tbpessoa_id` int(11) NOT NULL,
PRIMARY KEY (`id`,`tbtipopessoa_id`,`tbpessoa_id`),
KEY `fk_tbtipopessoa_tbpessoa_tbpessoa1` (`tbpessoa_id`),
KEY `fk_tbtipopessoa_tbpessoa_tbtipopessoa` (`tbtipopessoa_id`),
CONSTRAINT `fk_tbtipopessoa_tbpessoa_tbtipopessoa` FOREIGN KEY (`tbtipopessoa_id`) REFERENCES `tipo_pessoa` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `fk_tbtipopessoa_tbpessoa_tbpessoa1` FOREIGN KEY (`tbpessoa_id`) REFERENCES `pessoa` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
CREATE TABLE `usuario` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id_pessoa` int(11) NOT NULL,
`email` varchar(200) COLLATE utf8_general_ci NOT NULL,
`senha` varchar(50) COLLATE utf8_general_ci NOT NULL,
`celular` varchar(10) COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_usuario_pessoa1_idx` (`id_pessoa`),
CONSTRAINT `fk_usuario_pessoa1` FOREIGN KEY (`id_pessoa`) REFERENCES `pessoa` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('usuarios', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('id_pessoa')->nullable();
$table->string('email', 254)->nullable(false)->unique();
$table->string('celular', 11)->default('');
$table->string('senha', 128)->nullable(false);
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
if (Schema::hasTable('pessoas'))
{
Schema::table('usuarios', function (Blueprint $table) {
$table->foreign('id_pessoa')->references('id')->on('pessoas')
->onUpdate('CASCADE');
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('usuarios');
}
}
|
f261a72cf76a183ad5fdca53e7fc69be02bc1623
|
[
"Markdown",
"SQL",
"PHP"
] | 12
|
Markdown
|
evandroabukamel/fornecedores
|
5f01b728fbf89baa7301db16b943ff54c7ad4394
|
74b6656a6c3bb8b3b147167b24957426628f6ef1
|
refs/heads/master
|
<file_sep>// Enemies our player must avoid
var Enemy = function() {
// Variables applied to each of our instances go here,
// we've provided one for you to get started
// The image/sprite for our enemies, this uses
// a helper we've provided to easily load images
this.sprite = "images/enemy-bug.png";
this.yPositions = [150];
this.x = 0;
this.y = this.yPositions[Math.floor(Math.random() * this.yPositions.length)];
this.speed = Math.floor(500 - Math.random()*(500-120));
//reset position
this.reset = function(){
this.x = 0;
this.y = this.yPositions[Math.floor(Math.random() * this.yPositions.length)];
this.speed = Math.floor(500 - Math.random()*(500-120));
};
};
// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
// You should multiply any movement by the dt parameter
// which will ensure the game runs at the same speed for
// all computers.
this.x += dt*this.speed;
if(this.x >= 505){
this.reset();
}
};
// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
/*global ctx*/
/*global Resources*/
/*eslint no-undef: "error"*/
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};
// Now write your own player class
var Player = function(){
this.sprite = "images/char-cat-girl.png";
//location
this.x = 0;
this.y = 0;
this.horizontalStep = 100;
this.verticalStep = 80;
//more
this.isCollided = false;
this.won = false;
this.score = 0;
};
// This class requires an update(), render() and
Player.prototype.setInitial = function(){
this.x = 200;
this.y = 400;
var _this = this;
setTimeout(function(){
_this.setScore(_this.score);
},100);
};
// This class requires an update(), render() and
Player.prototype.update = function(){
if(this.y > 400){
this.y -= this.verticalStep;
}else if(this.y <=50 ){
this.win();
}else if(this.x < 0){
this.x += this.horizontalStep;
}else if(this.x > 400){
this.x -= this.horizontalStep;
}
};
Player.prototype.render = function(){
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};
// a handleInput() method.
Player.prototype.handleInput = function(direction){
switch(direction){
case "left":
this.x -= this.horizontalStep;
break;
case "up":
this.y -= this.verticalStep;
break;
case "right":
this.x += this.horizontalStep;
break;
case "down":
this.y += this.verticalStep;
break;
}
};
Player.prototype.checkCollisions = function(){
allEnemies.forEach(function(item){
if(
player.x < item.x + 100 && player.x + 70 > item.x &&
player.y < item.y + 78 && player.y + 50 > item.y
){
player.lose();
}
});
};
Player.prototype.win = function(){
var _this = this;
if(!this.won)
setTimeout(function(){
_this.setInitial();
_this.won = false;
_this.setScore(++_this.score);
},200);
this.won = true;
};
Player.prototype.lose = function(){
player.setInitial();
};
Player.prototype.setScore = function(score){
this.score = score;
ctx.font = "30px Arial";
ctx.strokeText(score,10,50);
};
// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies
var allEnemies = [];
for(var i=1;i<=3;i++){
allEnemies.push(new Enemy());
}
// Place the player object in a variable called player
var player = new Player();
player.setInitial();
// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener("keyup", function(e) {
var allowedKeys = {
37: "left",
38: "up",
39: "right",
40: "down"
};
player.handleInput(allowedKeys[e.keyCode]);
});
|
352d0eb26eefc5a6f2f39e67a0c3ae239115b472
|
[
"JavaScript"
] | 1
|
JavaScript
|
ashurbeyli/game
|
7d9d554f087dd72b01e6ec9fb6c3d2153fc0caa0
|
d2f2d60c90d6a861c3fb9bb7371f72f5fcc07854
|
refs/heads/master
|
<repo_name>alandickinson/reactnd-myreads<file_sep>/src/App.js
import React, { Component } from 'react'
import { Route, Link } from 'react-router-dom'
import BookList from './BookList'
import SearchPage from './SearchPage'
import * as BooksAPI from './BooksAPI'
import './App.css'
class BooksApp extends Component {
state = {
books: []
}
componentDidMount() {
BooksAPI.getAll().then((books) => {
this.setState({
books: books
})
})
}
updateBook(selectedBook, newShelf) {
BooksAPI.update(selectedBook, newShelf).then(() => {
selectedBook.shelf = newShelf
this.setState((prevState) => ({
books: prevState.books.filter(b => b.id !== selectedBook.id).concat([selectedBook])
}))
})
}
render() {
const onUpdateFunc = (selectedBook, newShelf) => this.updateBook(selectedBook, newShelf)
return (
<div className='app'>
<Route exact path='/' render={() => (
<div>
<div className="list-books">
<div className="list-books-title">
<h1>MyReads</h1>
</div>
<div className="list-books-content">
<BookList
title='Currently Reading'
books={this.state.books.filter((b) => b.shelf === 'currentlyReading')}
onUpdate={onUpdateFunc}
/>
<BookList
title='Want To Read'
books={this.state.books.filter((b) => b.shelf === 'wantToRead')}
onUpdate={onUpdateFunc}
/>
<BookList
title='Read'
books={this.state.books.filter((b) => b.shelf === 'read')}
onUpdate={onUpdateFunc}
/>
</div>
</div>
<div className="open-search">
<Link to='/search'>Add a Book</Link>
</div>
</div>
)}/>
<Route path='/search' render={() => (
<SearchPage onUpdate={onUpdateFunc} booksOnShelf={this.state.books}/>
)}/>
</div>
)
}
}
export default BooksApp;
<file_sep>/src/SearchPage.js
import React from 'react'
import { Link } from 'react-router-dom'
import BookList from './BookList'
import * as BooksAPI from './BooksAPI'
import PropTypes from 'prop-types'
class SearchPage extends React.Component {
static propTypes = {
onUpdate: PropTypes.func.isRequired,
booksOnShelf: PropTypes.array.isRequired
}
state = {
query: '',
searchResults: []
}
updateQuery = (query) => {
this.setState({ query: query.trim() })
this.updateResults()
}
updateResults = debounce(() => {
if (this.state.query) {
BooksAPI.search(this.state.query.trim(), 20).then((books) => {
if (books.error) {
this.setState({searchResults: []})
} else {
for(let i=0; i<books.length;i++) {
for(let j=0; j<this.props.booksOnShelf.length;j++) {
if (books[i].id === this.props.booksOnShelf[j].id) {
books[i].shelf = this.props.booksOnShelf[j].shelf
}
}
}
this.setState({searchResults: books})
}
}).catch((err) => console.log(err));
} else {
this.setState({searchResults: []})
}
}, 300)
componentDidMount() {
document.getElementById("searchInput").focus();
}
render() {
return (
<div className="search-books">
<div className="search-books-bar">
<Link to="/" className="close-search">Close</Link>
<div className="search-books-input-wrapper">
<input
onChange={(event) => this.updateQuery(event.target.value)}
type="text"
placeholder="Search by title or author"
id="searchInput"
/>
</div>
</div>
<div className="search-books-results">
<ol className="books-grid">
<BookList
onUpdate={this.props.onUpdate}
books={this.state.searchResults}
/>
</ol>
</div>
</div>
)
}
}
const debounce = (callback, wait, context = this) => {
let timeout = null
let callbackArgs = null
const later = () => callback.apply(context, callbackArgs)
return function() {
callbackArgs = arguments
clearTimeout(timeout)
timeout = setTimeout(later, wait)
}
}
export default SearchPage
<file_sep>/README.md
MyReads - the final assessment project for Udacity's React Fundamentals course.
## Install
Clone or download this repo and then run `npm install` followed by `npm start` in the main project folder.
|
26b8165fdea211ce7661953ae4269cb4aec10928
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
alandickinson/reactnd-myreads
|
9707e0e311f27ca8ed1e32e332f3330a1c8fecaa
|
04a7e1442bc2692de02ea9d12814bf6c4a9b1274
|
refs/heads/master
|
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:wb="http://open.weibo.com/wb">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="<?= $curArticle['title'] ?>-米兰百分百" />
<meta name="keywords" content="<?= $curArticle['keywords'] ?>" />
<title><?= $curArticle['title'] ?>-米兰百分百</title>
<link href="<?= $this->config->item('base_url') ?>res/css/style1.css" rel="stylesheet" type="text/css" />
<link href="<?= $this->config->item('base_url') ?>res/syntaxhighlighter/styles/shCoreRDark.css" rel="stylesheet" type="text/css" />
<link href="<?= $this->config->item('base_url') ?>res/syntaxhighlighter/styles/shThemeRDark.css" rel="stylesheet" type="text/css" />
<script src="http://tjs.sjs.sinajs.cn/open/api/js/wb.js" type="text/javascript" charset="utf-8"></script>
<script src="/js/jquery.js"></script>
<script src="<?= $this->config->item('base_url') ?>res/syntaxhighlighter/scripts/shCore.js"></script>
<script src="<?= $this->config->item('base_url') ?>res/syntaxhighlighter/scripts/shBrushCss.js"></script>
<script src="<?= $this->config->item('base_url') ?>res/syntaxhighlighter/scripts/shBrushJava.js"></script>
<script src="<?= $this->config->item('base_url') ?>res/syntaxhighlighter/scripts/shBrushJScript.js"></script>
<script src="<?= $this->config->item('base_url') ?>res/syntaxhighlighter/scripts/shBrushPhp.js"></script>
<script src="<?= $this->config->item('base_url') ?>res/syntaxhighlighter/scripts/shBrushPython.js"></script>
<script src="<?= $this->config->item('base_url') ?>res/syntaxhighlighter/scripts/shBrushSql.js"></script>
<style>
#weixinDiv {
position:absolute;
display:none;
padding:5px;
z-index:2;
width:200px;
height:200px;
background-color:whitesmoke;
left:400px;
top:50px;
}
</style>
<script type="text/javascript">
function evalArticle(articleId, evalType) {
$.get("ajax/EvalArticle.php", {
EvalType: evalType,
ArticleId: articleId
}, function (data) {
if (data == "-1") {
alert("您已评价过此文章!");
} else {
switch (evalType) {
case 'good':
$("#spGood").html(eval($("#spGood").html()) + 1);
break;
case 'mid':
$("#spMid").html(eval($("#spMid").html()) + 1);
break;
case 'bad':
$("#spBad").html(eval($("#spBad").html()) + 1);
break;
}
}
});
}
function getComments(articleId)
{
$.getJSON("/article_comment_list.php", {article_id: articleId}, function (comments) {
for (var i in comments)
{
$("#comments").prepend("<li>" + comments[i].content + "</li>");
}
});
}
function commentArticle(articleId)
{
var content = $("#content").val();
$.post("/article_comment.php", {ArticleId: articleId, content: content, VerifyCode: $("#VerifyCode").val()}, function (data) {
if (data == "-1")
{
alert("验证码错误");
}
else
{
alert('评论成功');
$("#comments").prepend("<li>" + content + "</li>");
}
});
}
function refreshImg(imgId)
{
$("#" + imgId).attr("src", $("#" + imgId).attr("src") + "?t=" + Math.random());
}
</script>
</head>
<body onload="getComments(<?= $curArticle['id'] ?>)">
<?php $this->load->view('public/header'); ?>
<div class="glHeight"></div>
<div class="mainDiv">
<div class="nowPosition">
您所在的位置 -> <a href="<?= $this->config->item('base_url') ?>">米兰百分百</a> -> <a href="<?= $this->config->item('base_url') ?>article/list/1/<?=$curArticleClass['id']?>"><?=$curArticleClass['title']?></a> -> <?= $curArticle['title'] ?>
</div>
</div>
<div class="glHeight"></div>
<div class="common_div">
<div style="width:730px;float:left;">
<div>
<script type="text/javascript">
/*728*90,创建于2010-11-3*/
var cpro_id = 'u265470';
</script>
<script type="text/javascript" src="http://cpro.baidu.com/cpro/ui/c.js"></script>
</div>
<div style="clear:both;"></div>
<div class="glHeight"></div>
<div style="text-align: center;height:50px; border-bottom:1px solid silver;">
<h1><?= $curArticle['title'] ?></h1>
</div>
<div>
点击数:<?= $curArticle['HitCount'] ?> 发表时间:<?= $curArticle['PubTime'] ?> 作者:<?= $curArticle['author'] ?> 来源链接:<a href="<?= $curArticle['SourceUrl'] ?>" target="_blank"><?= $curArticle['SourceUrl'] ?></a>
</div>
<div style="position:relative;">
<span style="cursor:pointer;" onclick="window.print();">打印</span>
<!-- Baidu Button BEGIN -->
<div id="bdshare" class="bdshare_t bds_tools get-codes-bdshare">
<span class="bds_more">分享到:</span>
<a class="bds_qzone"></a>
<a class="bds_tsina"></a>
<a class="bds_tqq"></a>
<a class="bds_renren"></a>
<a class="bds_t163"></a>
<a class="shareCount"></a>
</div>
<script type="text/javascript" id="bdshare_js" data="type=tools&uid=6567594" ></script>
<script type="text/javascript" id="bdshell_js"></script>
<script type="text/javascript">
document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil(new Date() / 3600000)
</script>
<!-- Baidu Button END -->
<wb:publish action="pubilish" type="web" language="zh_cn" button_type="red" button_size="middle" refer="y" appkey="2275491453" default_text="<?= $curArticle['title'] ?> http://www.milan100.com/html/article/{$id}.html" default_image="{$imgSrc}" ></wb:publish>
<img id="weixinImg" src="<?= $this->config->item('base_url') ?>res/img/weixin.png" onclick="showWeixinDiv(<?= $curArticle['id'] ?>)" />
<div id="weixinDiv">分享到朋友圈<br/><img id="qrcode" /></div>
</div>
<div class="content">
<?= $curArticle['content'] ?>
</div>
<table width="70%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr align="center">
<td>
<table width="100" border="0" cellspacing="1" cellpadding="3" bgcolor="#0099CC">
<tr>
<td align="center" bgcolor="#FFCC66"><span id="spGood"><?= $curArticle['good'] ?></span></td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF" style="color:#06F;"><span style="cursor:pointer;" onclick="evalArticle('{$id}', 'good');">很 好</span></td>
</tr>
</table></td>
<td>
<table width="100" border="0" cellspacing="1" cellpadding="3" bgcolor="#0099CC">
<tr>
<td align="center" bgcolor="#FFCC66"><span id="spMid"><?= $curArticle['mid'] ?></span></td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF" style="color:#06F;"><span style="cursor:pointer;" onclick="evalArticle('{$id}', 'mid');">一 般</span></td>
</tr>
</table></td>
<td>
<table width="100" border="0" cellspacing="1" cellpadding="3" bgcolor="#0099CC">
<tr>
<td align="center" bgcolor="#FFCC66"><span id="spBad"><?= $curArticle['bad'] ?></span></td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF" style="color:#06F;"><span style="cursor:pointer;" onclick="evalArticle('{$id}', 'bad');">差 劲</span></td>
</tr>
</table></td>
</tr>
</table>
<div class="glHeight"></div>
<div>
<script type="text/javascript">
<!--
google_ad_client = "pub-7070906826715304";
/* 728x90, 创建于 10-10-20 */
google_ad_slot = "7008935553";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div>
</div>
<div style="width:260px;float:right;">
<script type="text/javascript">
/*250*250,创建于2010-11-17*/
var cpro_id = 'u282332';
</script>
<script type="text/javascript" src="http://cpro.baidu.com/cpro/ui/c.js"></script>
<div class="glHeight"></div>
<!--最热文字新闻-->
<div style="background-color: whitesmoke;height:40px;line-height:40px;font-weight:bold;width:250px;padding-left:10px;">热门新闻</div>
<ul style="width:260px;overflow-x: hidden;">
<?php foreach($recommendArticles as $a): ?>
<li style="height:25px;"><a href="<?=$this->config->item('base_url')?>article/show/<?=$a['id']?>"><?=$a['title']?></a></li>
<?php endforeach; ?>
</ul>
<div class="glHeight"></div>
<!--最新图片新闻-->
<iframe width="256" height="170" frameborder="0" scrolling="no" src="/pic_new_articles.php"></iframe>
<div class="glHeight"></div>
<div style="background-color: whitesmoke;height:40px;line-height:40px;font-weight:bold;width:250px;padding-left:10px;">相关文章</div>
<ul style="width:260px;overflow-x: hidden;">
<?php foreach($relatedArticles as $a): ?>
<li style="height:25px;"><a href="<?=$this->config->item('base_url')?>article/show/<?=$a['id']?>"><?=$a['title']?></a></li>
<?php endforeach; ?>
</ul>
</div>
</div>
<div style="clear:both;"></div>
<div class="glHeight"></div>
<div class="common_div">
<div style="float:left;padding:5px;width:200px;">
上一篇:
<?php if($previousArticle): ?>
<a href="<?=$this->config->item('base_url')?>article/show/<?=$previousArticle['id']?>"><?=$previousArticle['title']?></a>
<?php endif; ?>
</div>
<div style="float:left;padding:5px;width:200px;">
下一篇:
<?php if($nextArticle): ?>
<a href="<?=$this->config->item('base_url')?>article/show/<?=$nextArticle['id']?>"><?=$nextArticle['title']?></a>
<?php endif; ?>
</div>
</div>
<div class="glHeight" style="clear:both;"></div>
<div class="common_div">
<div style="padding:5px;">
<strong>评论区</strong>
</div>
<div>
<textarea name="content" id="content" cols="45" rows="5"></textarea>
</div>
<table border="0" cellspacing="0" cellpadding="3">
<tr>
<td>
<input name="checkbox" type="checkbox" id="checkbox" checked="checked" />
匿名</td>
<td>
<input name="VerifyCode" type="text" id="VerifyCode" size="6" />
</td>
<td><img id="vcode" src="/inc/VerifyCode.php" onclick="refreshImg('vcode')" /></td>
<td>
<input type="button" name="button" id="button" value="提交评论" onclick="commentArticle({$id})" />
</td>
<td> </td>
</tr>
</table>
</div>
<div class="glHeight"></div>
<div class="common_div">
<ul id="comments">
</ul>
</div>
<?php $this->load->view('public/footer'); ?>
<script type="text/javascript">
SyntaxHighlighter.all();
function showWeixinDiv(id)
{
$("#weixinDiv").toggle();
$("#qrcode").attr("src", "http://qr.liantu.com/api.php?w=180&h=180&text=http://www.milan100.com/article_show.php?id=" + id);
}
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>宝宝健康日志添加</title>
<link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<form method="post" enctype="multipart/form-data">
<div class="form-group" style="margin-top: 20px;">
<label for="photo">上传图片</label>
<input accept="image/*" type="file" id="photo" name="photo" />
</div>
<div class="form-group">
<label for="date">日 期</label>
<input type="date" id="date" name="date" value="<?=date('Y-m-d')?>" class="form-control" />
</div>
<div class="form-group">
<label for="time"><input type="checkbox" id="is_insert_time" name="is_insert_time" value="1" checked="checked" /> 插入时间</label>
<input id="time" type="time" name="time" value="<?=date('H:i')?>" style="" class="form-control" />
</div>
<div class="form-group">
<label for="content">内 容</label>
<textarea id="content" name="content" class="form-control" rows="5" placeholder="请输入内容"></textarea>
</div>
<button id="btnSave" type="submit" style="" class="btn btn-danger">保 存</button>
<a href="<?=$this->config->item('base_url')?>health_log/"><button type="button" class="btn btn-info">返回列表页</button></a>
</form>
</div>
<script>
$("#is_insert_time").click(function(){
$("#time").toggle();
});
$("#btnSave").click(function(){
$(this).text("正在保存...");
});
</script>
</body>
</html>
<file_sep><?php
/**
* Description of article_model
*
* @author qiaoliang
*/
class Article_model extends CI_Model{
public $table = 'article';
public function __construct() {
parent::__construct();
$this->load->database();
}
public function getById($id)
{
$records = $this->db->get_where($this->table, array('id'=>$id))->result_array();
$targetNews = NULL;
if (!empty($records))
{
$targetNews = $records[0];
}
return $targetNews;
}
/**
* 获取此分类的上一篇
* @param type $id
* @param type $type
* @return type
*/
public function getPrevious($id, $type)
{
$this->db->select(array('id', 'title'));
$this->db->limit(1);
$this->db->where(array('id >'=>$id, 'class_id'=>$type, 'isPublic'=>1));
$records = $this->db->get($this->table)->result_array();
$targetNews = NULL;
if (!empty($records))
{
$targetNews = $records[0];
}
return $targetNews;
}
/**
* 获取此分类的下一篇
* @param type $id
* @param type $type
* @return type
*/
public function getNext($id, $type)
{
$this->db->select(array('id', 'title'));
$this->db->limit(1);
$this->db->where(array('id <'=>$id, 'class_id'=>$type, 'isPublic'=>1));
$records = $this->db->get($this->table)->result_array();
$targetNews = NULL;
if (!empty($records))
{
$targetNews = $records[0];
}
return $targetNews;
}
/**
* 获取相关新闻
* @param type $type
* @return type
*/
public function getRelated($type)
{
$this->db->select(array('id', 'title'));
$this->db->limit(10);
$this->db->where(array('class_id'=>$type, 'isPublic'=>1));
$articles = $this->db->get($this->table)->result_array();
return $articles;
}
/**
* 增加点击数
* @param type $id
*/
public function addHitCount($id)
{
$this->db->where('id', $id);
$this->db->set('HitCount', 'HitCount+1', FALSE);
$this->db->update($this->table);
}
/**
* 后台新增
* @param type $title
* @param type $keywords
* @param type $author
* @param type $isPublic
* @param type $pubTime
* @param type $classId
* @param type $content
* @param tinyint $isRecommend
*/
public function add($title, $keywords, $author, $isPublic, $pubTime, $classId, $content, $isRecommend)
{
$data = array(
'title' => $title,
'keywords' => $keywords,
'author' => $author,
'isPublic' => $isPublic,
'PubTime' => $pubTime,
'class_id' => $classId,
'content' => $content,
'is_recommend' => $isRecommend,
);
$this->db->insert($this->table, $data);
}
/**
* 后台修改
* @param type $id
* @param type $title
* @param type $keywords
* @param type $author
* @param type $isPublic
* @param type $pubTime
* @param type $classId
* @param type $content
*/
public function edit($id, $title, $keywords, $author, $isPublic, $pubTime, $classId, $content, $isRecommend)
{
$data = array(
'title' => $title,
'keywords' => $keywords,
'author' => $author,
'isPublic' => $isPublic,
'PubTime' => $pubTime,
'class_id' => $classId,
'content' => $content,
'is_recommend' => $isRecommend,
);
$this->db->update($this->table, $data, array('id'=>$id));
}
public function del($id)
{
$this->db->delete($this->table, array('id' => $id));
}
/**
* 按条件获取新闻列表,可分页
* @param int $page 当前页码
* @param int $perPage 每页数量
* @param int $newsType 新闻类型
* @param string $title 标题搜索的关键字
* @param bool $isValid 是否已发布
* @param int $createTime 按指定时间段查询,unix时间戳
* @return array
*/
public function listAll($page, $perPage, $newsType, $title, $isValid="")
{
$startIndex = ($page-1) * $perPage;
if ($newsType)
{
$this->db->where('class_id', $newsType);
}
if ($isValid)
{
$this->db->where('isPublic', $isValid);
}
if ($title)
{
$this->db->like('title', $title, 'both');
}
$this->db->from($this->table);
$this->db->limit($perPage, $startIndex);
$this->db->select(array('id', 'title', 'PubTime', 'class_id', 'HitCount', 'isPublic', 'is_recommend'));
$this->db->order_by("id", "desc");
$query = $this->db->get();
$news = $query->result_array();
return $news;
}
public function getCount($newsType, $title)
{
$this->db->from($this->table);
if ($newsType)
{
$this->db->where(array('class_id'=>$newsType));
}
if ($title)
{
$this->db->like('title', $title, 'both');
}
$count = $this->db->count_all_results();
return $count;
}
/**
* 边栏推荐新闻
* @return type
*/
public function getRecommended()
{
$this->db->from($this->table);
$this->db->limit(10);
$this->db->select(array('id', 'title', 'class_id'));
$this->db->where(array('isPublic'=>1, 'is_recommend'=>1));
$this->db->order_by("id", "desc");
$query = $this->db->get();
$news = $query->result_array();
return $news;
}
public function getByType($type)
{
$this->db->from($this->table);
$this->db->limit(10);
$this->db->select(array('id', 'title', 'class_id'));
$this->db->where(array('isPublic'=>1, 'class_id'=>$type));
$this->db->order_by("id", "desc");
$query = $this->db->get();
$news = $query->result_array();
return $news;
}
public function getAllUrl()
{
$allNews = $this->db->select(array('id'))->get($this->table)->result_array();
$urls = array();
foreach($allNews as $n)
{
$urls[] = 'http://www.milan100.com/article/show/' . $n['id'];
}
return $urls;
}
}
<file_sep><?php
$config['corner_positions'] = array(
1 => '前点',
2 => '中点',
3 => '后点',
4 => '禁区外',
);
<file_sep><?php
/**
*
*/
class baidu_map_library
{
private static $searchUrl = "http://api.map.baidu.com/place/v2/search";
private static $detailUrl = "http://api.map.baidu.com/place/v2/detail";
private static $ipCorUrl = "http://api.map.baidu.com/location/ip";
private $ak = '';
private $siteTool = '';
/**
* 根据当前IP获得位置
* @param type $ip
* @return type
*/
public function getAddressInfoByIp($config, $ip='')
{
$params = array('ak'=>$config['ak'], 'ip'=>$ip, 'coor'=>'bd09ll');
$data = file_get_contents(self::$ipCorUrl . '?' . http_build_query($params));
return $data;
}
public function getCourtById($uid)
{
$params = array('uid'=>$uid, 'output'=>'json', 'scope'=>2, 'ak'=>$this->ak);
$result = @file_get_contents(self::$detailUrl . "?" . http_build_query($params));
$data = null;
if (!is_null($result))
{
$result = json_decode($result, true);
if ( ($result['status'] == '0') && ($result['message'] == 'ok') )
{
$data = $this->adaptCourtData($result['result']);
}
}
return $data;
}
public function adaptCourtData($baiduData)
{
$courtData['name'] = $baiduData['name'];
$courtData['location'] = json_encode($baiduData['location']);
$courtData['address'] = $baiduData['address'];
$courtData['telephone'] = $baiduData['telephone'];
$courtData['street_id'] = $baiduData['street_id'];
$courtData['baidu_id'] = $baiduData['uid'];
$courtData['tag'] = $baiduData['detail_info']['tag'];
$courtData['detail_url'] = $baiduData['detail_info']['detail_url'];
return $courtData;
}
public function getCityCourts($city, $keyword, &$courts, &$pageNum = 0)
{
$params = array('region'=>$city, 'output'=>'json', 'ak'=>$this->ak, 'scope'=>2, 'q'=>$keyword, 'page_size'=>20, 'page_num'=>$pageNum);
$data = $this->siteTool->doHttpGet(self::$searchUrl, $params);
if (!is_null($data))
{
$data = json_decode($data, true);
}
if ( ($data['status'] == 0) && ($data['message'] == 'ok') )
{
if (!empty($data['results']))
{
$courts = array_merge($courts, $data['results']);
$pageNum++;
$this->getCityCourts($city, $keyword, $courts, $pageNum);
}
}
return $courts;
}
}
?><file_sep><?php
/**
* Description of article_class_model
*
* @author qiaoliang
*/
class article_class_model extends CI_Model {
private $table = 'articleclass';
public function __construct() {
parent::__construct();
}
public function getAll()
{
$articleClasses = $this->db->get($this->table)->result_array();
return $articleClasses;
}
/**
* 获取分类树
* @return array
*/
public function getTree()
{
$articleClasses = $this->getAll();
$temp = array(); //按parent_id为键的数组
foreach($articleClasses as $ac)
{
if (isset($temp[$ac['parent_id']]))
{
$temp[$ac['parent_id']][] = $ac;
}
else
{
$temp[$ac['parent_id']] = array($ac);
}
}
//先取出顶端的(parent_id=0),然后进行遍历,遍历某一个的时候
$tree = array();
$this->addChildrenOnTree(0, $tree, $temp, 0);
return $tree;
}
/**
* 获取子分类后加入树
* @param type $parentId 父类ID
* @param type $tree 树
* @param type $temp 用父类做键的数据
* @param int $depth 深度
*/
private function addChildrenOnTree($parentId, &$tree, $temp, $depth)
{
$depth++;
if (isset($temp[$parentId]))
{
foreach($temp[$parentId] as $node)
{
$node['depth'] = $depth;
$tree[] = $node;
$this->addChildrenOnTree($node['id'], $tree, $temp, $depth);
}
}
}
public function getById($id)
{
$targetClass = NULL;
$records = $this->db->get_where($this->table, array('id'=>$id))->result_array();
if (!empty($records))
{
$targetClass = $records[0];
}
return $targetClass;
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="<?= $this->config->item('base_url') ?>res/css/back.css" rel="stylesheet" type="text/css" />
<script src="http://d001.download.appget.cn/someapk/jquery-1.11.1.min.js"></script>
</head>
<body>
<div>
<?php $this->load->view('public/back_lefter'); ?>
<div class="right_body">
<div class="mainDiv">
<?php foreach ($leagues as $id => $title): ?>
<?php if ($id == $team['league_id']): ?>
<strong><?= $title ?></strong>
<?php else: ?>
<a href="<?= $this->config->item('base_url') ?>team/list_back/<?= $id ?>"><?= $title ?></a>
<?php endif; ?>
<?php endforeach; ?>
</div>
<div class="glHeight"></div>
<div class="teams clear_both">
<?php foreach ($teams as $k => $t): ?>
<div>
<a href="<?= $this->config->item('base_url') ?>team/edit/<?= $t['id'] ?>">
<img src='<?= $this->config->item('cdn_url') . $t['ImgSrc'] ?>' style="width:60px;height:60px;" /><br/>
<?= $t['name'] ?>
</a>
</div>
<?php endforeach; ?>
</div>
<div class="glHeight"></div>
<div style="float:left;">
<form method="post">
<table border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="silver">
<tr>
<td align="right" bgcolor="whitesmoke">队 标:</td>
<td bgcolor="#FFFFFF"><img width="60" height="60" src="<?= $this->config->item('cdn_url') . $curTeam['ImgSrc'] ?>" /></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">球 队:</td>
<td bgcolor="#FFFFFF"><input type="text" name="name" value="<?= $curTeam['name'] ?>" /></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">主 场:</td>
<td bgcolor="#FFFFFF"><input type="text" name="field_name" value="<?= $curTeam['FieldName'] ?>" /></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">座位数:</td>
<td bgcolor="#FFFFFF"><input type="number" name="seats" value="<?= $curTeam['seats'] ?>" /></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">官方网站:</td>
<td bgcolor="#FFFFFF"><input type="url" name="website" value="<?= $curTeam['website'] ?>" style="width:300px;" /></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke"></td>
<td bgcolor="#FFFFFF"><input type="submit" value="修 改" /></td>
</tr>
</table>
</form>
</div>
<div id="divPlayers" style="float:right;">
<table width="100%" border="0" cellpadding="5" cellspacing="0">
<tr align="center" bgcolor="whitesmoke">
<td>号码</td>
<td>中文名</td>
<td>英文名</td>
<td>国籍</td>
<td>出生日期</td>
<td>身高</td>
<td>体重</td>
<td>删除</td>
</tr>
<?php foreach ($players as $player): ?>
<tr align="center">
<td><?= $player['ShirtNo'] ?></td>
<td><a href="<?= $this->config->item('base_url') ?>player/edit/<?= $player['id'] ?>"><?= $player['name'] ?></a></td>
<td><?= $player['en_name'] ?></td>
<td><?= $player['country'] ?></td>
<td><?= $player['birthday'] ?></td>
<td><?= $player['height'] ?>CM</td>
<td><?= $player['weight'] ?>KG</td>
<td><a href="<?= $this->config->item('base_url') ?>player/del/<?= $player['id'] ?>" onclick="return confirm('确认要删除 <?= $player['name'] ?>?')">删除</a></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div>
</div>
</body>
</html>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>米兰百分百</title>
<script src="http://s11.cnzz.com/stat.php?id=2228734&web_id=2228734&show=pic" language="JavaScript"></script>
</head>
<body>
正在打开...
<script>
setTimeout(function(){
location.href = "http://www.milan100.com/player/show/<?=$_GET['player_id']?>";
}, 500);
</script>
</body>
</html>
<file_sep><?php
class Team extends Back_Controller
{
/**
* 前台列表
* @param type $leagueId
*/
public function list_front($leagueId=1)
{
$this->load->library('user_agent');
$this->load->model(array('team_model'));
$this->config->load('league');
$data['leagues'] = $this->config->item('leagues');
$data['leagueId'] = $leagueId;
$data['teams'] = $this->team_model->getByLeagueId($leagueId);
$data['teamId'] = 0;
if ($this->agent->is_mobile())
{
$this->load->view('team/list_wap', $data);
}
else
{
$this->load->view('team/list_front', $data);
}
}
public function list_back($leagueId=1)
{
$this->checkPurview();
$this->load->model(array('team_model'));
$this->config->load('league');
$data['leagues'] = $this->config->item('leagues');
$data['leagueId'] = $leagueId;
$data['teams'] = $this->team_model->getByLeagueId($leagueId);
$data['teamId'] = 0;
$this->load->view('team/list_back', $data);
}
/**
* 球队主页
* @param type $id
*/
public function show($id)
{
$this->load->library('user_agent');
$this->load->model(array('team_model', 'player_model'));
$this->config->load('league');
$data['leagues'] = $this->config->item('leagues');
$data['curTeam'] = $this->team_model->getById($id);
$data['leagueId'] = $data['curTeam']['id'];
$data['players'] = $this->player_model->getByTeamId($id);
if ($this->agent->is_mobile())
{
$this->load->view('team/show_wap', $data);
}
else
{
$this->load->view('team/show', $data);
}
}
public function edit($id)
{
$this->checkPurview();
$this->load->model(array('team_model', 'player_model'));
$this->config->load('league');
if (empty($_POST))
{
}
else
{
$name = $this->input->post('name');
$fieldName = $this->input->post('field_name');
$seats = $this->input->post('seats');
$website = $this->input->post('website');
$this->team_model->edit($id, $name, $fieldName, $seats, $website);
}
$data['leagues'] = $this->config->item('leagues');
$data['curTeam'] = $this->team_model->getById($id);
$data['leagueId'] = $data['curTeam']['league_id'];
$data['teams'] = $this->team_model->getByLeagueId($data['curTeam']['league_id']);
// print_r($data['teams']);exit;
$data['players'] = $this->player_model->getByTeamId($id);
$this->load->view('team/edit', $data);
}
public function add()
{
$this->checkPurview();
if (empty($_POST))
{
$this->config->load('league');
$this->load->helper('form_helper');
$data['leagues'] = $this->config->item('leagues');
$this->load->view('team/add', $data);
}
else
{
$this->load->model('team_model');
$leagueId = $_POST['league_id'];
$teamId = $this->team_model->add($_POST);
header("location:".$this->config->item('base_url').'team/edit/'.$teamId);
}
}
}
<file_sep><?php
class News_model extends CI_Model
{
private $table = 'article';
public function __construct() {
parent::__construct();
$this->load->database();
}
//米兰新闻(10) 最新发布(20) 热门点击(20)
public function getMilanNews($limit)
{
$this->db->select(array('id', 'title', 'PubTime'));
$this->db->limit($limit);
$query = $this->db->get_where($this->table, array('class_id'=>12));
$news = $query->result_array();
return $news;
}
public function getNewNews($limit)
{
$this->db->select(array('id', 'title', 'PubTime', 'class_id'));
$this->db->limit($limit);
$this->db->order_by('PubTime', 'desc');
$query = $this->db->get($this->table);
$news = $query->result_array();
return $news;
}
public function getHotNews($limit)
{
$this->db->select(array('id', 'title', 'PubTime', 'class_id'));
$this->db->limit($limit);
$this->db->order_by('HitCount', 'desc');
$query = $this->db->get($this->table);
$news = $query->result_array();
return $news;
}
}
<file_sep><?php
class Player extends Back_Controller
{
public function __construct() {
parent::__construct();
}
public function show($id)
{
$this->load->library('user_agent');
$this->load->model(array('player_model', 'team_model', 'player_comment_model', 'article_model'));
$this->config->load('league');
$data['leagues'] = $this->config->item('leagues');
$data['curPlayer'] = $this->player_model->getById($id);
$data['players'] = $this->player_model->getByTeamId($data['curPlayer']['team_id']);
$data['leagueId'] = 0;
$data['myTeam'] = $this->team_model->getById($data['curPlayer']['team_id']);
$data['comments'] = $this->player_comment_model->getAllByPlayerId($id);
$this->config->load('position');
$data['positions'] = $this->config->item('positions');
$data['recommendArticles'] = $this->article_model->getRecommended();
if ($this->agent->is_mobile())
{
$this->load->view('player/show_wap', $data);
}
else
{
$this->load->view('player/show', $data);
}
}
public function add()
{
$this->checkPurview();
$this->load->model(array('player_model', 'team_model'));
if (empty($_POST))
{
$this->load->helper('form');
$this->config->load('league');
$this->config->load('position');
$this->config->load('corner_position');
$data['positions'] = $this->config->item('positions');
$data['corner_positions'] = $this->config->item('corner_positions');
$data['leagues'] = $this->config->item('leagues');
$data['teams'] = $this->team_model->getAll();
$this->load->view('player/add', $data);
}
else
{
$data = $_POST;
$this->player_model->insert($data);
header("location:".$this->config->item('base_url').'team/edit/'.$data['team_id']);
}
}
public function edit($id)
{
$this->checkPurview();
$this->load->model(array('player_model', 'team_model'));
if (empty($_POST))
{
$this->load->helper('form');
$this->config->load('league');
$this->config->load('position');
$this->config->load('corner_position');
$data['positions'] = $this->config->item('positions');
$data['corner_positions'] = $this->config->item('corner_positions');
$data['leagues'] = $this->config->item('leagues');
$data['teams'] = $this->team_model->getAll();
$data['curPlayer'] = $this->player_model->getById($id);
$data['leagueId'] = 0;
$data['myTeam'] = $this->team_model->getById($data['curPlayer']['team_id']);
$this->load->view('player/edit', $data);
}
else
{
$data = $_POST;
$data['is_push_baidu'] = 0;
//对比新旧图片,如果不同则删除旧的
$curPlayer = $this->player_model->getById($id);
if ($curPlayer['ImgSrc'] != $data['ImgSrc'])
{
$this->delRemoteFile($curPlayer['ImgSrc']);
}
$this->player_model->update($id, $data);
header("location:".$this->config->item('base_url').'team/edit/'.$_POST['team_id']);
}
}
public function search()
{
$this->checkPurview();
$data['name'] = '';
$data['birthday'] = '';
if (empty($_POST))
{
$data['players'] = array();
$this->load->view('player/search', $data);
}
else
{
$data['name'] = $this->input->post('name');
$data['birthday'] = $this->input->post('birthday');
$this->load->model('player_model');
$data['players'] = $this->player_model->search($data['name'], $data['birthday']);
$this->load->view('player/search', $data);
}
}
public function add_comment($playerId)
{
$this->load->model('player_comment_model');
$ip = $this->input->ip_address();
$comment = $this->input->post("comment");
$this->player_comment_model->add($playerId, $comment, $ip);
echo json_encode(array('status'=>1, 'comment_data'=>array('ip'=>$ip, 'comment'=>$comment, 'time'=>date('Y-m-d H:i:s', time()))));
}
public function pic_upload()
{
$data['rndName'] = $_SESSION['rnd_name'];
$this->load->view('player/pic_upload', $data);
}
public function upload_success($fileName)
{
$data['prefix'] = 'http://milan100-static.stor.sinaapp.com/ypn_img/';
$data['fileName'] = 'player/' . $fileName;
$this->load->view('player/upload_success', $data);;
}
private function delRemoteFile($imgSrc)
{
$delKey = '<KEY>';
$sign = md5($delKey.$imgSrc);
$result = file_get_contents("http://milan100.sinaapp.com/player_pic_del.php?img_src={$imgSrc}&sign={$sign}");
return $result;
}
public function del($id)
{
$this->checkPurview();
$this->load->model('player_model');
$curPlayer = $this->player_model->getById($id);
$imgSrc = $curPlayer['ImgSrc'];
$this->delRemoteFile($imgSrc);
$this->player_model->del($id);
header("location:".$this->config->item('base_url').'team/edit/'.$curPlayer['team_id']);
}
/**
* 删除数据库里不存在的图片
*/
public function get_all_pic()
{
$this->load->model('player_model');
$databaseFiles = $this->player_model->getAllPic();
echo json_encode($databaseFiles);
}
/**
* @return {"error":400,"message":"over quota"}
*/
public function push_baidu()
{
ini_set('display_errors', 'on');
$this->load->model('player_model');
$ids = $this->player_model->getUnpushedIds();
$idCount = count($ids);
$urls = array();
foreach($ids as $n)
{
$urls[] = 'http://www.milan100.com/player/show/'.$n['id'];
}
if ($idCount > 0)
{
$result = json_decode($this->pushBaidu($urls), TRUE);
if(isset($result['success']))
{
$firstId = $ids[0]['id'];
$lastId = $ids[$idCount-1]['id'];
$this->player_model->setPush($firstId, $lastId);
}
print_r($result);
}
else
{
echo 'no data';
}
}
}<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="<?=$curTeam['name']?>-米兰百分百" />
<meta name="keywords" content="<?=$curTeam['name']?>,<?=$curTeam['alias']?>,官方网站,官网" />
<title><?=$curTeam['name']?> - <?= $this->config->item('site_name') ?></title>
<link href="<?=$this->config->item('base_url')?>css/style1.css" rel="stylesheet" type="text/css" />
<style>
.buttonDiv
{
width:100px;
height:30px;
text-align:center;
line-height:30px;
}
</style>
<script>
function showTeam()
{
$('#divTeam').show();
$('#divPlayers').hide();
$("#tdTeam").attr("bgColor", "silver");
$("#tdPlayers").attr("bgColor", "white");
}
function showPlayers()
{
$('#divTeam').hide();
$('#divPlayers').show();
$("#tdTeam").attr("bgColor", "white");
$("#tdPlayers").attr("bgColor", "silver");
}
</script>
<script src="<?=$this->config->item('base_url')?>js/jquery.js"></script>
</head>
<body>
<?php $this->load->view('public/header'); ?>
<div class="glHeight"></div>
<div class="mainDiv">
<div class="nowPosition">您所在的位置 -> <a href="/index.php">米兰百分百</a> -> 球队资料</div>
</div>
<div class="glHeight"></div>
<div class="mainDiv">
<table cellpadding="3" width="100%">
<tr>
<?php foreach ($leagues as $id => $title): ?>
<td align="center">
<?php if ($leagueId == $id): ?>
<strong><?= $title ?></strong>
<?php else: ?>
<a href="<?=$this->config->item('base_url')?>team/list/<?=$id?>"><?= $title ?></a>
<?php endif; ?>
</td>
<?php if ($id % 7 == 0): ?>
</tr><tr>
<?php endif; ?>
<?php endforeach; ?>
</tr>
</table>
</div>
<div class="glHeight"></div>
<div style="width:1000px; margin:0 auto;">
<table border="0" cellpadding="8" cellspacing="0">
<tr>
<td id="tdTeam" bgcolor="silver" style="cursor:pointer;" onclick="showTeam();">球队信息</td>
<td id="tdPlayers" bgcolor="#FFFFFF" style="cursor:pointer;" onclick="showPlayers();">球员信息</td>
</tr>
</table>
</div>
<table align="center" width="1000" border="0" cellpadding="0" cellspacing="0"><tr valign="top">
<td bgcolor="#FFFFFF">
<div class="glHeight"></div>
<div id="divTeam">
<table width="400" border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="silver">
<tr>
<td align="right" bgcolor="whitesmoke">队 标:</td>
<td bgcolor="#FFFFFF"><img width="60" height="60" src="<?=$this->config->item('cdn_url').$curTeam['ImgSrc']?>" /></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">球 队:</td>
<td bgcolor="#FFFFFF"><?=$curTeam['name']?></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">主 场:</td>
<td bgcolor="#FFFFFF"><?=$curTeam['FieldName']?></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">座位数:</td>
<td bgcolor="#FFFFFF"><?=$curTeam['seats']?></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">官方网站:</td>
<td bgcolor="#FFFFFF"><a href="http://<?=$curTeam['website']?>" target="_blank"><?=$curTeam['website']?></a></td>
</tr>
</table>
</div>
<div id="divPlayers" style="display:none;">
<table width="100%" border="0" cellpadding="5" cellspacing="0">
<tr align="center" bgcolor="whitesmoke">
<td>照片</td>
<td>号码</td>
<td>姓名</td>
<td>国籍</td>
<td>出生日期</td>
<td>身高</td>
<td>体重</td>
</tr>
<?php foreach($players as $player): ?>
<tr align="center">
<td><a href="<?=$this->config->item('base_url')?>player/show/<?=$player['id']?>"><img src="<?=$this->config->item('cdn_url').$player['ImgSrc']?>" width="60" border="0" /></a></td>
<td><?=$player['ShirtNo']?></td>
<td><a href="<?=$this->config->item('base_url')?>player/show/<?=$player['id']?>"><?=$player['name']?></a></td>
<td><?=$player['country']?></td>
<td><?=$player['birthday']?></td>
<td><?=$player['height']?>CM</td>
<td><?=$player['weight']?>KG</td>
</tr>
<?php endforeach; ?>
</table>
</div>
<div class="glHeight"></div>
<div>
<script type="text/javascript"> /*728*90,创建于2010-11-3*/ var cpro_id = 'u265470';</script>
<script type="text/javascript" src="http://cpro.baidu.com/cpro/ui/c.js"></script>
</div>
<div class="glHeight"></div>
<div>
<script type="text/javascript"><!--
google_ad_client = "pub-7070906826715304";
/* 728x90, 创建于 10-10-20 */
google_ad_slot = "7008935553";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
</td>
<td width="10"></td>
<td width="260"><script type="text/javascript"><!--
google_ad_client = "pub-7070906826715304";
/* 250x250, 创建于 10-10-20 */
google_ad_slot = "2412761154";
google_ad_width = 250;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<div class="glHeight"></div>
<script type="text/javascript"> /*250*250,创建于2010-11-17*/ var cpro_id = 'u282332';</script>
<script type="text/javascript" src="http://cpro.baidu.com/cpro/ui/c.js"></script>
<div class="glHeight"></div>
<script type="text/javascript">
u_a_client = "28172";
u_a_width = "157";
u_a_height = "450";
u_a_zones = "20529";
u_a_type = "0"
</script>
<div class="glHeight"></div>
<div style="background-color:#FFF;">
</div>
</td>
</tr>
</table>
<div class="glHeight"></div>
<?php $this->load->view('public/footer'); ?>
</body>
</html>
<file_sep><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="<?php echo $this->config->item("base_url"); ?>res/css/back.css" rel="stylesheet">
<style>
.keyword {
color:#ff0000;
font-weight:bold;
}
</style>
<script src="http://d001.download.appget.cn/someapk/jquery-1.11.1.min.js"></script>
<script src="<?php echo $this->config->item("base_url"); ?>res/js/back.js"></script>
<script>
<?php if ($sessionMsg): ?>
$(document).ready(function () {
showBodyMsg("<?php echo $sessionMsg; ?>");
});
<?php endif; ?>
</script>
</head>
<body>
<?php $this->load->view('public/back_lefter'); ?>
<div class="right_body">
<div style="margin-bottom:20px;">
<form method="post" action="<?=$this->config->item("base_url") ?>article/list_back/">
类 型:<?php // echo form_dropdown('article_type', $articleSearchTypes, $articleSearchType, "id='search_article_type' style='width:200px;';"); ?>
关键字:<input type="text" id="keyword" name="keyword" value="<?php echo $keyword; ?>" />
<button type="submit" >搜 索</button>
</form>
</div>
<table class="table_style_1">
<tr>
<th>ID</th>
<th>类型</th>
<th>标题</th>
<th>发布时间</th>
<th>发布</th>
<th>推荐</th>
<th>点击数</th>
<th>预览</th>
<th>链接</th>
<th>操作</th>
</tr>
<?php foreach ($allNews as $n): ?>
<tr>
<td><?php echo $n['id']; ?></td>
<td></td>
<td><a href="<?php echo $this->config->item("base_url") ?>article/edit/<?php echo $n['id']; ?>"><?php echo str_replace($keyword, "<span class='keyword'>" . $keyword . "</span>", $n['title']); ?></a></td>
<td><?=$n['PubTime']?></td>
<td><?php echo $n['isPublic'] ? "<span style='color:green;'>已发布</span>" : "<span style='color:red;'>未发布</span>"; ?></td>
<td><?php echo $n['is_recommend'] ? "<span style='color:green;'>已推荐</span>" : "<span style='color:red;'>未推荐</span>"; ?></td>
<td><?php echo $n['HitCount']; ?></td>
<td><a href="<?php echo $this->config->item("base_url") ?>article/show/<?php echo $n['id']; ?>" target="_blank">预览</a></td>
<td><?php echo $this->config->item("base_url") ?>article/show/<?php echo $n['id']; ?></td>
<td><a href="<?php echo $this->config->item("base_url") ?>article/edit/<?php echo $n['id']; ?>">修改</a> | <a href="<?php echo $this->config->item("base_url") ?>article/del/<?php echo $n['id']; ?>" onclick="return confirm('确认要删除吗?')";>删除</a></td>
</tr>
<?php endforeach; ?>
</table>
<div>
<?php for ($i = 1; $i <= $pageCount; $i++): ?>
<?php
if ($i == $curPage) {
$className = "current";
$href = "#";
} else {
$className = "";
$href = $this->config->item("base_url") . "article/list_back/" . $i . "/";
}
?>
<a href="<?php echo $href; ?>" class="<?php echo $className; ?>"><?php echo $i; ?></a>
<?php endfor; ?>
</div>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="<?= $this->config->item('base_url') ?>res/css/back.css" rel="stylesheet" type="text/css" />
<script src="http://d001.download.appget.cn/someapk/jquery-1.11.1.min.js"></script>
</head>
<body>
<div>
<?php $this->load->view('public/back_lefter'); ?>
<div class="right_body">
<div class="mainDiv">
<table cellpadding="3" width="100%">
<tr>
<?php foreach ($leagues as $id => $title): ?>
<td align="center">
<?php if ($leagueId == $id): ?>
<strong><?= $title ?></strong>
<?php else: ?>
<a href="<?= $this->config->item('base_url') ?>team/list_back/<?= $id ?>"><?= $title ?></a>
<?php endif; ?>
</td>
<?php if ($id % 7 == 0): ?>
</tr><tr>
<?php endif; ?>
<?php endforeach; ?>
</tr>
</table>
</div>
<div style="text-align: center;"><a href="<?= $this->config->item('base_url') ?>team/edit/<?= $curPlayer['team_id'] ?>">返回球队</a> <a href="<?= $this->config->item('base_url') ?>team/add">添加球员</a></div>
<form method="post" action="<?= $this->config->item('base_url') ?>player/edit/<?= $curPlayer['id'] ?>">
<input type="hidden" id="hdImgSrc" name="ImgSrc" value="<?=$curPlayer['ImgSrc']?>" />
<table align="center" cellpadding="5">
<tr valign="top">
<td>
<table border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="whitesmoke">
<tr>
<td align="right" style="font-weight:bold;">照 片</td>
<td align="center">
<img id="imgSrc" src="<?= $this->config->item('cdn_url') . $curPlayer['ImgSrc'] ?>" />
<iframe id="ifImgSrc" frameborder="0" src="<?=$this->config->item('base_url')?>player/pic_upload" style="width:300px;height:25px;"></iframe>
</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">中文名</td>
<td align="left"><input type="text" name="name" value="<?= $curPlayer['name'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">英文名</td>
<td align="left"><input type="text" name="en_name" value="<?= $curPlayer['en_name'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">别 名</td>
<td align="left"><input type="text" name="alias" value="<?= $curPlayer['alias'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">联 赛</td>
<td align="left"><?= form_dropdown('league_id', $leagues, $curPlayer['league_id'], "id='league_id'") ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">球 队</td>
<td align="left"><select id="team_id" name="team_id"></select></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">号 码</td>
<td><input type="number" name="ShirtNo" value="<?= $curPlayer['ShirtNo'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">国 籍</td>
<td><input type="text" name="country" value="<?= $curPlayer['country'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">生 日</td>
<td><input type="text" name="birthday" value="<?= $curPlayer['birthday'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">位 置</td>
<td><?= form_dropdown('position_id', $positions, $curPlayer['position_id']) ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">角球位</td>
<td><?= form_dropdown('CornerPosition_id', $corner_positions, $curPlayer['CornerPosition_id'], 'id="CornerPosition_id"') ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">身 高</td>
<td><input type="number" name="height" value="<?= $curPlayer['height'] ?>" />CM</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">体 重</td>
<td><input type="number" name="weight" value="<?= $curPlayer['weight'] ?>" />KG</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">周 薪</td>
<td><input type="text" name="salary" value="<?= $curPlayer['salary'] ?>" />W欧元</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">人 品</td>
<td><input type="number" name="moral" value="<?= $curPlayer['moral'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">脾 气</td>
<td><input type="number" name="temper" value="<?= $curPlayer['temper'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">人 气</td>
<td><input type="number" name="popular" value="<?= $curPlayer['popular'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">忠诚度</td>
<td><input type="number" name="loyalty" value="<?= $curPlayer['loyalty'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">合同开始</td>
<td><input type="date" name="ContractBegin" value="<?= $curPlayer['ContractBegin'] ?>" id="ContractBegin" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">合同截止</td>
<td><input type="date" name="ContractEnd" value="<?= $curPlayer['ContractEnd'] ?>" id="ContractEnd" /></td>
</tr>
</table>
</td>
<td>
<table border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="whitesmoke">
<tr>
<td align="right" style="font-weight:bold;">意 识</td>
<td width="150" align="left"><input type="number" name="creativation" value="<?= $curPlayer['creativation'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">传 球</td>
<td align="left"><input type="number" name="pass" value="<?= $curPlayer['pass'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">左属性</td>
<td align="left"><input type="number" name="LeftProperties" value="<?= $curPlayer['LeftProperties'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">中属性</td>
<td align="left"><input type="number" name="MidProperties" value="<?= $curPlayer['MidProperties'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">右属性</td>
<td align="left"><input type="number" name="RightProperties" value="<?= $curPlayer['RightProperties'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门力量</td>
<td align="left"><input type="number" name="ShotPower" value="<?= $curPlayer['ShotPower'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门准确度</td>
<td align="left"><input type="number" name="ShotAccurate" value="<?= $curPlayer['ShotAccurate'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">弧线球</td>
<td align="left"><input type="number" name="arc" value="<?= $curPlayer['arc'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门欲望</td>
<td align="left"><input type="number" name="ShotDesire" value="<?= $curPlayer['ShotDesire'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">头 球</td>
<td align="left"><input type="number" name="header" value="<?= $curPlayer['header'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">抢 点</td>
<td align="left"><input type="number" name="qiangdian" value="<?= $curPlayer['qiangdian'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">守 门</td>
<td align="left"><input type="number" name="save" value="<?= $curPlayer['save'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">盯人防守</td>
<td align="left"><input type="number" name="close-marking" value="<?= $curPlayer['close-marking'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">抢 断</td>
<td align="left"><input type="number" name="tackle" value="<?= $curPlayer['tackle'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">拼 抢</td>
<td align="left"><input type="number" name="pinqiang" value="<?= $curPlayer['pinqiang'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">活动范围</td>
<td align="left"><input type="number" name="scope" value="<?= $curPlayer['scope'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">体 能</td>
<td align="left"><input type="number" name="SinewMax" value="<?= $curPlayer['SinewMax'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">控 球</td>
<td align="left"><input type="number" name="BallControl" value="<?= $curPlayer['BallControl'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">过 人</td>
<td align="left"><input type="number" name="beat" value="<?= $curPlayer['beat'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">速 度</td>
<td align="left"><input type="number" name="speed" value="<?= $curPlayer['speed'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">敏 捷</td>
<td align="left"><input type="number" name="agility" value="<?= $curPlayer['agility'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">理 智</td>
<td align="left"><input type="number" name="mind" value="<?= $curPlayer['mind'] ?>" /></td>
</tr>
</table>
</td>
</tr>
</table>
<div style="text-align: center;">
<input type="submit" value="保 存" style="width:400px;" />
</div>
</form>
</div>
</div>
<script>
var teams = [];
<?php foreach ($teams as $t): ?>
teams.push(<?= json_encode($t) ?>);
<?php endforeach; ?>
var optionStr = '';
function loadTeams(leagueId)
{
$("#team_id").empty();
for (var i in teams)
{
if (teams[i].league_id == leagueId)
{
optionStr = "<option value='" + teams[i].id + "'";
if (teams[i].id == <?= $curPlayer['team_id'] ?>)
{
optionStr += ' selected="selected"';
}
optionStr += ">" + teams[i].name + "</option>";
$("#team_id").append(optionStr);
}
}
$("#team_id").append('<option value="0">自由球员</option>');
}
$("#league_id").change(function () {
loadTeams($(this).val());
});
loadTeams(<?= $curPlayer['league_id'] ?>);
</script>
</body>
</html>
<file_sep><?php
class Team_model extends CI_Model
{
private $table = 'ypn_bak_teams';
public function __construct() {
parent::__construct();
$this->load->database();
}
public function getByLeagueId($leagueId)
{
$query = $this->db->get_where($this->table, array('league_id'=>$leagueId));
$teams = $query->result_array();
return $teams;
}
public function getById($id)
{
$query = $this->db->get_where($this->table, array('id'=>$id));
$teams = $query->result_array();
if (!empty($teams))
{
return $teams[0];
}
}
public function getList()
{
$this->db->select(array('id', 'name'));
$this->db->order_by('league_id', 'asc');
$query = $this->db->get($this->table);
$records = $query->result_array();
$teams = array();
foreach($records as $r)
{
$teams[$r['id']] = $r['name'];
}
return $teams;
}
public function getAll()
{
$this->db->select(array('id', 'name', 'league_id'));
$this->db->order_by('league_id', 'asc');
$teams = $this->db->get($this->table)->result_array();
return $teams;
}
public function add($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function edit($id, $name, $fieldName, $seats, $website)
{
$data = array(
'name' => $name,
'FieldName' => $fieldName,
'seats' => $seats,
'website' => $website,
);
// print_r($data);exit;
$this->db->update($this->table, $data, array('id' => $id));
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="<?= $this->config->item('base_url') ?>res/css/back.css" rel="stylesheet" type="text/css" />
<script src="http://d001.download.appget.cn/someapk/jquery-1.11.1.min.js"></script>
</head>
<body>
<div>
<?php $this->load->view('public/back_lefter'); ?>
<div class="right_body">
<form action="http://www.milan100.com/player/search" method="post">
名字:<input type="text" name="name" value="<?=$name?>" />
生日:<input type="text" name="birthday" value="<?=$birthday?>" />
<input type="submit" value="搜 索">
</form>
<ul>
<?php foreach ($players as $p): ?>
<li><a href="<?= $this->config->item('base_url') ?>player/edit/<?= $p['id'] ?>"><?= $p['name'] ?></a></li>
<?php endforeach; ?>
</ul>
</div>
</div>
</body>
</html>
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta content="米兰,米兰中文网,红黑军团,足球,世界杯,网站开发,网页技术,网站,PHP,JAVASCRIPT" name="Keywords" />
<meta content="米兰百分百:让我们一起爱米兰" name="Description"/>
<meta property="wb:webmaster" content="b01e3dcabcf8d625" />
<meta name="baidu-site-verification" content="F3ruMYqPbW" />
<title><?=$this->config->item('site_name')?></title>
<link href="<?=$this->config->item('base_url')?>css/style1.css" rel="stylesheet" type="text/css" />
<script src="<?=$this->config->item('base_url')?>js/jquery.js"></script>
</head>
<body>
<?php $this->load->view('public/header'); ?>
<div class="glHeight"></div>
<table width="1000" border="0" align="center" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="50%" align="center">
<table width="495" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="25" align="center" bgcolor="#999999" style="font-weight:bold;">最新发布</td>
</tr>
<tr>
<td bgcolor="#FFFFFF">
<table width="95%" border="0" align="center" cellpadding="3" cellspacing="1">
<?php foreach($newNews as $n): ?>
<tr bgcolor="#FFFFFF">
<td align="left" style="border-bottom:1px dashed silver;">·<a href="article_list.php?ClassId=<?=$n['class_id']?>" target="_blank">[]</a><a href="<?=$this->config->item('base_url')?>article/show/<?=$n['id']?>" title="<?=$n['title']?>" target="_blank"><?= mb_substr($n['title'], 0, 25)?></a></td>
<td style="border-bottom:1px dashed silver;"><?=$n['PubTime']?></td>
</tr>
<?php endforeach; ?>
</table></td>
</tr>
</table></td>
<td width="10" align="center"> </td>
<td align="center">
<table width="495" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="25" align="center" bgcolor="#999999" style="font-weight:bold;">热门点击</td>
</tr>
<tr>
<td bgcolor="#FFFFFF">
<table width="95%" border="0" align="center" cellpadding="3" cellspacing="1">
<?php foreach($hotNews as $n): ?>
<tr bgcolor="#FFFFFF">
<td align="left" style="border-bottom:1px dashed silver;">·<a href="article_list.php?ClassId={$article_array[article].class_id}" target="_blank">[]</a><a href="<?=$this->config->item('base_url')?>article/show/<?=$n['id']?>" title="<?=$n['title']?>" target="_blank"><?=$n['title']?></a></td>
<td style="border-bottom:1px dashed silver;"><?=$n['PubTime']?></td>
</tr>
<?php endforeach; ?>
</table></td>
</tr>
</table></td>
</tr>
</table>
<div class="glHeight"></div>
<div class="mainDiv" style="background-color:silver;">
<div style="padding:8px; font-weight:bold;">
友情链接
</div>
</div>
<div class="mainDiv">
<table align="center" border="0" cellspacing="0" cellpadding="8">
<tr>
<td><a href="http://www.weather.com.cn/" target="_blank"><img src="http://www.weather.com.cn/m2/i/logo_header_out.gif" width="173" height="68" border="0" alt="中国天气网" style="border:1px solid silver;" /></a></td>
<td><img src="images/friend.jpg" width="173" height="68" style="border:1px solid silver;" /></td>
<td><img src="images/friend.jpg" style="border:1px solid silver;" /></td>
<td><img src="images/friend.jpg" style="border:1px solid silver;" /></td>
<td><img src="images/friend.jpg" style="border:1px solid silver;" /></td>
</tr>
</table>
</div>
<?php $this->load->view('public/footer'); ?>
</body>
</html><file_sep><?php
$positions[0] = '请选择';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="<?= $this->config->item('base_url') ?>res/css/back.css" rel="stylesheet" type="text/css" />
<script src="http://d001.download.appget.cn/someapk/jquery-1.11.1.min.js"></script>
</head>
<body>
<div>
<?php $this->load->view('public/back_lefter'); ?>
<div class="right_body">
<div class="mainDiv">
<table cellpadding="3" width="100%">
<tr>
<?php foreach ($leagues as $id => $title): ?>
<td align="center">
<a href="<?= $this->config->item('base_url') ?>team/list_back/<?= $id ?>"><?= $title ?></a>
</td>
<?php if ($id % 7 == 0): ?>
</tr><tr>
<?php endif; ?>
<?php endforeach; ?>
</tr>
</table>
</div>
<div style="text-align: center;"></div>
<form method="post" action="<?= $this->config->item('base_url') ?>player/add">
<input type="hidden" id="hdImgSrc" name="ImgSrc" />
<table align="center" cellpadding="5">
<tr valign="top">
<td>
<table border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="whitesmoke">
<tr>
<td align="right" style="font-weight:bold;">照 片</td>
<td align="center">
<img id="imgSrc" />
<iframe id="ifImgSrc" frameborder="0" src="<?=$this->config->item('base_url')?>player/pic_upload" style="width:300px;height:25px;"></iframe>
</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">中文名</td>
<td align="left"><input id="name" type="text" name="name" value="" /><span id="dot_span">用点分割</span></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">英文名</td>
<td align="left"><input type="text" name="en_name" value="" id="en_name" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">别 名</td>
<td align="left"><input type="text" name="alias" value="" id="alias" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">联 赛</td>
<td align="left"><?= form_dropdown('league_id', $leagues, 1, 'id="league_id"') ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">球 队</td>
<td align="left"><select id="team_id" name="team_id"></select></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">号 码</td>
<td><input type="number" name="ShirtNo" value="78" id="ShirtNo" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">国 籍</td>
<td><input type="text" name="country" value="意大利" id="country" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">生 日</td>
<td><input type="text" name="birthday" value="" id="birthday" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">位 置</td>
<td><?= form_dropdown('position_id', $positions, 0 , 'id="position_id"') ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">角球位</td>
<td><?= form_dropdown('CornerPosition_id', $corner_positions, mt_rand(1,4), 'id="CornerPosition_id"') ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">身 高</td>
<td><input type="number" name="height" value="179" id="height" />CM</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">体 重</td>
<td><input type="number" name="weight" value="70" id="weight" />KG</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">周 薪</td>
<td><input type="text" name="salary" value="0.2" id="salary" />W欧元</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">人 品</td>
<td><input type="number" name="moral" value="75" id="moral" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">脾 气</td>
<td><input type="number" name="temper" value="75" id="temper" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">人 气</td>
<td><input type="number" name="popular" value="60" id="popular" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">忠诚度</td>
<td><input type="number" name="loyalty" value="70" id="loyalty" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">合同开始</td>
<td><input type="date" name="ContractBegin" value="2014-8-1" id="ContractBegin" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">合同截止</td>
<td><input type="date" name="ContractEnd" value="2018-6-30" id="ContractEnd" /></td>
</tr>
</table>
</td>
<td>
<table border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="whitesmoke">
<tr>
<td align="right" style="font-weight:bold;">意 识</td>
<td width="150" align="left"><input type="number" name="creativation" value="70" id="creativation" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">传 球</td>
<td align="left"><input type="number" id="pass" name="pass" value="75" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">左属性</td>
<td align="left"><input type="number" id="LeftProperties" name="LeftProperties" value="90" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">中属性</td>
<td align="left"><input type="number" id="MidProperties" name="MidProperties" value="100" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">右属性</td>
<td align="left"><input type="number" id="RightProperties" name="RightProperties" value="90" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门力量</td>
<td align="left"><input type="number" name="ShotPower" value="80" id="ShotPower" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门准确度</td>
<td align="left"><input type="number" id="ShotAccurate" name="ShotAccurate" value="75" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">弧线球</td>
<td align="left"><input type="number" id="arc" name="arc" value="75" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门欲望</td>
<td align="left"><input type="number" id="ShotDesire" name="ShotDesire" value="75" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">头 球</td>
<td align="left"><input type="number" id="header" name="header" value="75" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">抢 点</td>
<td align="left"><input type="number" id="qiangdian" name="qiangdian" value="75" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">守 门</td>
<td align="left"><input type="number" id="save" name="save" value="65" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">盯人防守</td>
<td align="left"><input type="number" id="close-marking" name="close-marking" value="70" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">抢 断</td>
<td align="left"><input type="number" id="tackle" name="tackle" value="75" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">拼 抢</td>
<td align="left"><input type="number" id="pinqiang" name="pinqiang" value="75" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">活动范围</td>
<td align="left"><input type="number" id="scope" name="scope" value="75" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">体 能</td>
<td align="left"><input type="number" id="SinewMax" name="SinewMax" value="84" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">控 球</td>
<td align="left"><input type="number" id="BallControl" name="BallControl" value="75" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">过 人</td>
<td align="left"><input type="number" id="beat" name="beat" value="70" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">速 度</td>
<td align="left"><input type="number" id="speed" name="speed" value="80" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">敏 捷</td>
<td align="left"><input type="number" id="agility" name="agility" value="80" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">理 智</td>
<td align="left"><input type="number" id="mind" name="mind" value="75" /></td>
</tr>
</table>
</td>
</tr>
</table>
<div style="text-align: center;">
<input type="submit" value="新 增" style="width:400px;" />
</div>
</form>
</div>
</div>
<script>
var teams = [];
<?php foreach ($teams as $t): ?>
teams.push(<?= json_encode($t) ?>);
<?php endforeach; ?>
var optionStr = '';
function loadTeams(leagueId)
{
$("#team_id").empty();
for (var i in teams)
{
if (teams[i].league_id == leagueId)
{
optionStr = "<option value='" + teams[i].id + "'";
optionStr += ">" + teams[i].name + "</option>";
$("#team_id").append(optionStr);
}
}
}
$("#league_id").change(function () {
loadTeams($(this).val());
});
loadTeams(1);
$("#dot_span").click(function () {
$("#name").val($("#name").val() + "·");
});
function changeTraining(positionId)
{
//
}
$("#position_id").change(function(){
switch ($("#position_id").val())
{
case "1":
$("#MidProperties").val('100');
$("#ShotPower").val('83');
$("#ShotAccurate").val('78');
$("#ShotDesire").val('83');
$("#header").val('78');
$("#qiangdian").val('78');
$("#speed").val('82');
changeTraining(1);
break;
case "2":
$("#tackle").val('76');
$("#pinqiang").val('78');
$("#SinewMax").val('86');
changeTraining(3);
break;
case "3":
$("#height").val('185');
$("#weight").val('80');
$("#qiangdian").val('77');
$("#tackle").val('77');
$("#close-marking").val('77');
changeTraining(3);
break;
case "4":
$("#ShotDesire").val('30');
$("#save").val('78');
$("#height").val('185');
$("#weight").val('80');
changeTraining(7);
break;
case "5":
$("#LeftProperties").val('100');
$("#MidProperties").val('95');
$("#RightProperties").val('90');
$("#shotPower").val('83');
$("#shotAccurate").val('78');
$("#shotDesire").val('81');
$("#speed").val('83');
$("#beat").val('78');
changeTraining(6);
break;
case "6":
$("#LeftProperties").val('90');
$("#MidProperties").val('95');
$("#RightProperties").val('100');
$("#ShotPower").val('83');
$("#ShotAccurate").val('78');
$("#ShotDesire").val('81');
$("#speed").val('83');
$("#beat").val('78');
changeTraining(6);
break;
case "7":
$("#ShotPower").val('83');
$("#ShotAccurate").val('78');
$("#ShotDesire").val('82');
$("#header").val('78');
$("#qiangdian").val('78');
$("#agility").val('78');
$("#height").val('185');
$("#weight").val('80');
$("#BallControl").val('80');
changeTraining(4);
break;
case "8":
$("#ShotPower").val('83');
$("#ShotAccurate").val('78');
$("#ShotDesire").val('78');
$("#pass").val('80');
$("#BallControl").val('80');
changeTraining(2);
break;
case "9":
$("#LeftProperties").val('100');
$("#MidProperties").val('90');
$("#RightProperties").val('90');
$("#beat").val('78');
$("#speed").val('82');
changeTraining(6);
break;
case "10":
$("#LeftProperties").val('90');
$("#MidProperties").val('90');
$("#RightProperties").val('100');
$("#beat").val('78');
$("#speed").val('82');
changeTraining(6);
break;
case "13":
$("#LeftProperties").val('100');
$("#MidProperties").val('90');
$("#RightProperties").val('90');
$("#tackle").val('77');
$("#close-marking").val('77');
$("#speed").val('82');
changeTraining(3);
break;
case "14":
$("#LeftProperties").val('90');
$("#MidProperties").val('90');
$("#RightProperties").val('100');
$("#tackle").val('77');
$("#close-marking").val('77');
$("#speed").val('82');
changeTraining(3);
break;
}
});
</script>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>宝宝健康名词查看</title>
<link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div>
<h1><?=$curWord['title']?></h1>
<p><?=$curWord['content']?></p>
</div>
<div>
<a href="<?=$this->config->item('base_url')?>word" class="btn btn-info">返回列表</a>
<a href="<?=$this->config->item('base_url')?>word/add" class="btn btn-info">添加新纪录</a>
</div>
</div>
<script type="text/javascript">
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="<?= $this->config->item('base_url') ?>res/tiqiu/css/main.css" rel="stylesheet" type="text/css" />
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title><?= $curField['name'] ?> - 球场上见</title>
<link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div style="container-fluid">
<form class="form-horizontal" style="margin-top:40px;">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">名称</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="inputEmail3" value="<?= $curField['name'] ?>" readonly="readonly">
</div>
</div>
<!-- <div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">城市</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="inputEmail3" value="<?= $curField['city_id'] ?>" readonly="readonly">
</div>
</div>-->
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">地址</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="inputEmail3" value="<?= $curField['address'] ?>" readonly="readonly">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">电话</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="inputEmail3" value="<?= $curField['telephone'] ?>" readonly="readonly">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">标签</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="inputEmail3" value="<?= $curField['tag'] ?>" readonly="readonly">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">可容纳人数</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="inputEmail3" value="<?= $curField['nop'] ?>" readonly="readonly">
</div>
</div>
<div class="form-group">
<label for="content" class="col-sm-2 control-label">内容</label>
<div class="col-sm-2">
<?= $curField['content'] ?>
</div>
</div>
</form>
</div>
<div style="display: none">
<script src="http://s11.cnzz.com/stat.php?id=2228734&web_id=2228734&show=pic" language="JavaScript"></script>
</div>
</body>
</html><file_sep><?php
//print_r($articleClassTree);exit;
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="<?php echo $this->config->item("base_url"); ?>res/css/back.css" rel="stylesheet">
<script src="<?php echo $this->config->item("base_url"); ?>ueditor/ueditor.config.js"></script>
<script src="<?php echo $this->config->item("base_url"); ?>ueditor/ueditor.all.js"></script>
<script src="<?php echo $this->config->item("base_url"); ?>res/js/back.js"></script>
<script src="http://d001.download.appget.cn/someapk/jquery-1.11.1.min.js"></script>
</head>
<body>
<?php $this->load->view('public/back_lefter'); ?>
<div class="right_body">
<form id="form_news" method="post">
<table class="table_style_1">
<tr>
<th>分 类</th>
<td>
<select name="class_id">
<?php foreach ($articleClassTree as $c): ?>
<option value="<?= $c['id'] ?>"><?php if ($c['parent_id']) echo str_repeat(' ', $c['depth']) . '└'; ?><?= $c['title'] ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr><th>标 题</th><td><input type="text" id="title" name="title" autocomplete="off" style="width:400px;" required="required" /></td></tr>
<tr><th>关键字</th><td><input type="text" id="keywords" name="keywords" autocomplete="off" style="width:400px;" required="required" /></td></tr>
<tr><th>作 者</th><td><input type="text" name="author" autocomplete="off" style="" /></td></tr>
<tr><th>发 布</th><td><input type="checkbox" name="isPublic" value="1" checked="checked" /></td></tr>
<tr><th>推 荐</th><td><input type="checkbox" name="is_recommend" value="1" /></td></tr>
<tr>
<th>内 容</th>
<td>
<script id="container" name="content" type="text/plain">
</script>
<script type="text/javascript">
var ue = UE.getEditor('container');
</script>
</td>
</tr>
<tr>
<td></td>
<td><button type="submit" name="submit" style="width:200px;">保 存</button></td>
</tr>
</table>
</form>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://d001.download.appget.cn/someapk/jquery-1.11.1.min.js"></script>
</head>
<body>
图片上传成功
<script>
$('#hdImgSrc', parent.document).val("<?=$fileName?>");
$('#imgSrc', parent.document).attr("src", "<?=$prefix.$fileName?>");
</script>
</body>
</html>
<file_sep><?php
/**
* Description of word
*
* @author qiaoliang
*/
class word extends Back_Controller{
public function index($page=1)
{
$this->load->model('word_model');
$this->load->helper('form');
$perPage = 20;
$recordCount = $this->word_model->getCount();
$pageCount = ceil($recordCount / $perPage);
$data['words'] = $this->word_model->listAll($page, $perPage);
$data['curPage'] = $page;
$data['pageCount'] = $pageCount;
$data['sessionMsg'] = $this->getSessionMsg();
$this->load->view('word/index', $data);
}
public function add()
{
if(!empty($_POST))
{
$this->load->model('word_model');
$title = $this->input->post("title");
$content = nl2br($this->input->post("content"));
$result = $this->word_model->add($title, $content);
header("location:" . $this->config->item('base_url') . 'word');
exit;
}
$this->load->view('word/add');
}
public function edit($id)
{
$this->load->model('word_model');
if(!empty($_POST))
{
$title = $this->input->post("title");
$content = nl2br($this->input->post("content"));
$result = $this->word_model->edit($id, $title, $content);
header("location:" . $this->config->item('base_url') . 'word');
exit;
}
else
{
$curWord = $this->word_model->getById($id);
$this->load->view('word/edit', array('curWord'=>$curWord));
}
}
public function show($id)
{
$this->load->model('word_model');
$curWord = $this->word_model->getById($id);
$this->load->view('word/show', array('curWord'=>$curWord));
}
public function del($id)
{
$this->load->model('word_model');
$this->word_model->del($id);
$this->setSessionMsg("删除成功");
header("location:".$this->config->item('base_url').'word');
}
}
<file_sep><?php
class MY_Controller extends CI_Controller {
function __construct() {
parent::__construct ();
date_default_timezone_set("PRC");
}
}
class Back_Controller extends MY_Controller {
protected $adminSessionKey = 'milan100_admin';
function __construct() {
session_start();
parent::__construct ();
}
/**
* 权限检查
*/
protected function checkPurview()
{
if (!isset($_SESSION[$this->adminSessionKey]))
{
die("<script>top.location.href='" . $this->config->item("base_url") . "admin/login/';</script>");
}
}
/**
* 接收二进制数据生成文件,按日期文件夹保存
* @return string 文件路径及文件名
*/
public function getUploadData($fieldName = "userfile")
{
$imgSrc = "";
$errorMsg = "";
if($_FILES[$fieldName]['name'])
{
$relativeDir = 'uploads/' . date('Ymd') . '/';
if (!is_dir($relativeDir))
{
mkdir($relativeDir);
}
$config['upload_path'] = $relativeDir;
$config['allowed_types'] = 'gif|jpg|png|csv';
$config['max_size'] = '2000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($fieldName))
{
$errorMsg = $this->upload->display_errors();
}
else
{
$uploadData = $this->upload->data();
$fileName = $uploadData['file_name'];
$imgSrc = $relativeDir . $fileName;
}
}
return array('img_src'=>$imgSrc, 'error_msg'=>$errorMsg);
}
public function setSessionMsg($msg)
{
$_SESSION['session_msg'] = $msg;
}
public function getSessionMsg()
{
$msg = "";
if (isset($_SESSION['session_msg']))
{
$msg = $_SESSION['session_msg'];
unset($_SESSION['session_msg']);
}
return $msg;
}
public function pushBaidu($urls)
{
// $urls = array(
// 'http://www.example.com/1.html',
// 'http://www.example.com/2.html',
// );
$api = 'http://data.zz.baidu.com/urls?site=www.milan100.com&token=<PASSWORD>';
$ch = curl_init();
$options = array(
CURLOPT_URL => $api,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => implode("\n", $urls),
CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
return $result;
}
}<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>宝宝健康名词修改</title>
<link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="title" name="title" value="<?=$curWord['title']?>" />
</div>
<div class="form-group">
<textarea name="content" class="form-control" rows="3"><?=$curWord['content']?></textarea>
</div>
<button type="submit" style="" class="btn btn-primary">保存</button>
<a href="<?=$this->config->item('base_url')?>word/"><button type="button" class="btn btn-info">返回列表页</button></a>
</form>
<script>
</script>
</body>
</html>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>球队添加</title>
<link href="<?= $this->config->item('base_url') ?>res/css/back.css" rel="stylesheet" type="text/css" />
<link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div>
<?php $this->load->view('public/back_lefter'); ?>
<div class="right_body">
<div class="mainDiv">
<table cellpadding="3" width="100%">
<tr>
<?php foreach ($leagues as $id => $title): ?>
<td align="center">
<a href="<?= $this->config->item('base_url') ?>team/list_back/<?= $id ?>"><?= $title ?></a>
</td>
<?php if ($id % 7 == 0): ?>
</tr><tr>
<?php endif; ?>
<?php endforeach; ?>
</tr>
</table>
</div>
<div style="text-align: center;"></div>
<form method="post" action="<?= $this->config->item('base_url') ?>team/add">
<div class="form-group">
<label for="name">名 称</label>
<input type="name" class="form-control" id="name" placeholder="名称">
</div>
<table border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="whitesmoke">
<tr>
<td align="right" style="font-weight:bold;">别 名</td>
<td align="left"><input type="text" name="alias" value="" id="alias" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">联 赛</td>
<td align="left"><?= form_dropdown('league_id', $leagues, 1, 'id="league_id"') ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">球场名称</td>
<td align="left"><input type="text" name="FieldName" value="" id="FieldName" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">座位数</td>
<td align="left"><input type="text" name="seats" value="" id="seats" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">官方网站</td>
<td align="left"><input type="text" name="website" value="" id="website" /></td>
</tr>
</table>
<div style="text-align: center;">
<input type="submit" value="新 增" style="width:400px;" />
</div>
</form>
</div>
</div>
<script src="//cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
</script>
</body>
</html>
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="官网 官网 资料" />
<title><?= $this->config->item('site_name') ?></title>
<link href="<?= $this->config->item('base_url') ?>css/style1.css" rel="stylesheet" type="text/css" />
<style>
.buttonDiv
{
width:100px;
height:30px;
text-align:center;
line-height:30px;
}
</style>
<script>
function showTeam()
{
$('#divTeam').show();
$('#divPlayers').hide();
$("#tdTeam").attr("bgColor", "silver");
$("#tdPlayers").attr("bgColor", "white");
}
function showPlayers()
{
$('#divTeam').hide();
$('#divPlayers').show();
$("#tdTeam").attr("bgColor", "white");
$("#tdPlayers").attr("bgColor", "silver");
}
</script>
<script src="<?= $this->config->item('base_url') ?>js/jquery.js"></script>
</head>
<body>
<?php $this->load->view('public/header'); ?>
<div class="glHeight"></div>
<div class="mainDiv">
<div class="nowPosition">您所在的位置 -> <a href="/index.php">米兰百分百</a> -> 球队资料</div>
</div>
<div class="glHeight"></div>
<div class="mainDiv">
<table cellpadding="3" width="100%">
<tr>
<?php foreach ($leagues as $id => $title): ?>
<td align="center">
<?php if ($leagueId == $id): ?>
<strong><?= $title ?></strong>
<?php else: ?>
<a href="<?= $this->config->item('base_url') ?>team/list/<?= $id ?>"><?= $title ?></a>
<?php endif; ?>
</td>
<?php if ($id % 7 == 0): ?>
</tr><tr>
<?php endif; ?>
<?php endforeach; ?>
</tr>
</table>
</div>
<div class="glHeight"></div>
<div class="mainDiv">
<?php foreach ($teams as $k => $team): ?>
<div style="float:left;padding:5px;text-align: center;width:90px;">
<a href="<?= $this->config->item('base_url') ?>team/show/<?= $team['id'] ?>">
<img src='<?=$this->config->item('cdn_url').$team['ImgSrc']?>' style="width:60px;height:60px;" /><br/>
<?= $team['name'] ?>
</a>
</div>
<?php if (($k+1) % 10 == 0): ?>
<div class="clear_both"></div>
<?php endif; ?>
<?php endforeach; ?>
</div>
<div class="glHeight"></div>
<div class="mainDiv clear_both">
<script type="text/javascript"> /*728*90,创建于2010-11-3*/ var cpro_id = 'u265470';</script>
<script type="text/javascript" src="http://cpro.baidu.com/cpro/ui/c.js"></script>
<script type="text/javascript">
google_ad_client = "pub-7070906826715304";
/* 728x90, 创建于 10-10-20 */
google_ad_slot = "7008935553";
google_ad_width = 728;
google_ad_height = 90;
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div>
<div class="glHeight"></div>
<?php $this->load->view('public/footer'); ?>
</body>
</html>
<file_sep><?php
/**
* Description of field_model
*
* @author qiaoliang
*/
class field_model extends CI_Model {
private $table = 'milan100_field';
public function __construct() {
parent::__construct();
$this->load->database();
}
public function getByCityId($cityId, $searchTypeArr)
{
$this->db->select(array('id', 'baidu_id', 'name', 'location', 'address', 'telephone', 'price'));
$this->db->where_in('type', $searchTypeArr);
$this->db->where('city_id', $cityId);
$fields = $this->db->get($this->table)->result_array();
return $fields;
}
/**
* 百度抓取的时候是包含学校公园,返回页面结果可以
* @param type $cityId
* @param type $baiduFields
*/
public function importBaiduData($cityId, $baiduFields, $searchType)
{
$fields = array();
foreach($baiduFields as $f)
{
if (!$this->getByBaiduId($f['uid'])) //当前database里没有此baidu_id的field
{
$newField = array();
$newField['city_id'] = $cityId;
$newField['name'] = $f['name'];
$newField['location'] = json_encode($f['location']);
$newField['address'] = $f['address'];
if (isset($f['telephone']))
{
$newField['telephone'] = $f['telephone'];
}
if (isset($f['street_id']))
{
$newField['street_id'] = $f['street_id'];
}
$newField['baidu_id'] = $f['uid'];
if (strpos($newField['name'], '足球场'))
{
$newField['type'] = 1;
}
else
{
$newField['type'] = 2;
}
$this->db->insert($this->table, $newField);
if ( ($searchType === 1 && $newField['type'] ===1) || ($searchType == 2) )
{
$fields[] = $newField;
}
}
}
return $fields;
}
private function getByBaiduId($baiduId)
{
$this->db->limit(1);
$records = $this->db->get_where($this->table, array('baidu_id'=>$baiduId))->result_array();
$targetField = NULL;
if (!empty($records))
{
$targetField = $records[0];
}
return $targetField;
}
public function getCount($newsType, $title)
{
$this->db->from($this->table);
if ($newsType)
{
$this->db->where(array('class_id'=>$newsType));
}
if ($title)
{
$this->db->like('name', $title, 'both');
}
$count = $this->db->count_all_results();
return $count;
}
public function listAll($page, $perPage, $newsType, $title, $isValid="")
{
$startIndex = ($page-1) * $perPage;
if ($newsType)
{
$this->db->where('class_id', $newsType);
}
if ($isValid)
{
$this->db->where('isPublic', $isValid);
}
if ($title)
{
$this->db->like('name', $title, 'both');
}
$this->db->from($this->table);
$this->db->limit($perPage, $startIndex);
$this->db->select(array('id', 'name', 'city_id', 'telephone', 'address', 'price'));
$this->db->order_by("id", "desc");
$query = $this->db->get();
$news = $query->result_array();
return $news;
}
public function getById($id)
{
$records = $this->db->get_where($this->table, array('id'=>$id))->result_array();
$curField = NULL;
if (!empty($records))
{
$curField = $records[0];
}
return $curField;
}
public function getUnpushedIds()
{
$records = $this->db->get_where($this->table)->result_array();
return $records;
}
}
<file_sep><script type="text/javascript">
function addFavor() {
var title = document.title;
var url = window.location;
if (document.all) {
try {
window.external.addFavorite(window.location.href, document.title);
} catch(e) {
alert("加入收藏失败,请使用Ctrl+D进行添加");
}
} else if (window.sidebar) {
window.sidebar.addPanel(document.title, window.location.href, "");
} else {
alert("加入收藏失败,请使用Ctrl+D进行添加");
}
return false;
}
$(document).ready(function(){
$.getJSON("/ajax/check_login.php", {}, function(data){
if (data.status == 0)
{
$("#no_login_panel").show();
}
else
{
$("#logined_panel").show();
$("#sp_member_name").text(data.member.MemberName);
}
})
});
</script>
<a name="top"></a>
<div class="mainDiv">
<table cellpadding="3">
<tr>
<td width="20"></td>
<td>
<div id="no_login_panel" style="display:none;">
<a href="/login.php">登录</a>
</div>
<div id="logined_panel" style="display:none;">
<span id="sp_member_name" style="color:#00F; font-weight:bold;"></span>,已登录
<a href="/MyArticle_list.php">我添加的信息</a>
<a href="/logout.php">退出登录</a>
</div>
</td>
<td align="center"><span style="cursor:pointer;" onclick="addFavor();">收藏本页</span></td>
</tr>
</table>
<div id="notes" style="text-align:center;width:120px;height:100px;background-color:#FFFFBD;border:1px solid #C2BE88;display:none;position:absolute;left:290px;">
<div>
<textarea id="NotesContent" style=" font-size:12px;overflow:hidden; width:110px; height:80px;background-color:#FFFFBD; border:0px;"></textarea>
</div>
<div style="float:left;">
<a href="#" title="保存" class="notes" onclick="saveNotes();return false;">+</a>
</div>
<div style="float:right;">
<a href="#" title="关闭" class="notes" onclick="closeNotes();return false;">×</a>
</div>
</div>
</div>
<table width="1000" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
<tr>
<td width="150" height="129"><a href="http://www.milan100.com/"><img src="/images/logo.jpg" width="150" height="129" border="0" alt="让我们一起爱米兰" /></a></td>
<td align="left">
<div>
<a href="/index.php">首页</a> |
<a href="<?=$this->config->item('base_url')?>article/list/1/0">新闻</a> |
<a href="<?=$this->config->item('base_url')?>article/list/1/12">米兰</a> |
<a href="<?=$this->config->item('base_url')?>article/list/1/14">军事</a> |
<a href="<?=$this->config->item('base_url')?>article/list/1/19">游戏竞技</a> |
<a href="<?=$this->config->item('base_url')?>article/list/1/31">生活点滴</a> |
<a href="<?=$this->config->item('base_url')?>article/list/1/42">国际动态</a> |
<a href="<?=$this->config->item('base_url')?>article/list/1/43">科技</a> |
<a href="<?=$this->config->item('base_url')?>article/list/1/44">娱乐</a> |
<a href="<?=$this->config->item('base_url')?>article/list/1/45">体育</a> |
<a href="/team/list">球员资料库</a>
</div>
<form id="form2" name="form2" method="get" action="result.php">
<table width="90%" border="0" align="center" cellpadding="3" cellspacing="0">
<tr>
<td>站内搜搜:</td>
<td>
<input name="q" type="text" id="q" size="60" x-webkit-speech />
</td>
<td>
<input type="submit" name="button" id="button" value="搜 索" style="width:80px;" />
</td>
</tr>
</table>
</form></td>
<td align="left" width="190">
<div style="border:1px dashed silver; width:184px; height:100px;">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td><img src="/images/chart.png" width="100" /></td>
<td>移动设备
<br/>
请扫描二维码
<br/>
或访问
<br/>
m.milan100.com </td>
</tr>
</table>
</div></td>
</tr>
</table>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="description" content="<?=$curPlayer['name']?>-<?=$myTeam['name']?>-米兰百分百">
<meta name="keywords" content="<?=$curPlayer['name']?>,<?=$curPlayer['alias']?>,<?=$curPlayer['en_name']?>,<?=$myTeam['name']?>,资料">
<title><?=$curPlayer['name']?> - <?=$myTeam['name']?> - <?= $this->config->item('site_name') ?></title>
</head>
<body>
<div style="text-align: center;"> <a href="<?=$this->config->item('base_url')?>team/show/<?=$curPlayer['team_id']?>">返回球队</a> <a href="<?=$this->config->item('base_url')?>team/list/<?=$curPlayer['league_id']?>">返回联赛</a></div>
<table border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="whitesmoke">
<tr>
<td align="right" style="font-weight:bold;">照 片</td>
<td align="center"><img src="<?= $this->config->item('cdn_url') . $curPlayer['ImgSrc'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">中文名</td>
<td align="left"><?= $curPlayer['name'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">英文名</td>
<td align="left"><?= $curPlayer['en_name'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">别 名</td>
<td align="left"><?= $curPlayer['alias'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">号 码</td>
<td><?= $curPlayer['ShirtNo'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">国 籍</td>
<td><?= $curPlayer['country'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">生 日</td>
<td><?= $curPlayer['birthday'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">位 置</td>
<td></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">身 高</td>
<td><?= $curPlayer['height'] ?>CM</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">体 重</td>
<td><?= $curPlayer['weight'] ?>KG</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">周 薪</td>
<td><?= $curPlayer['salary'] ?>W欧元</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">人 品</td>
<td><?= $curPlayer['moral'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">脾 气</td>
<td><?= $curPlayer['temper'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">人 气</td>
<td><?= $curPlayer['popular'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">忠诚度</td>
<td><?= $curPlayer['loyalty'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">意 识</td>
<td width="150" align="left"><?= $curPlayer['creativation'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">传 球</td>
<td align="left"><?= $curPlayer['pass'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">左属性</td>
<td align="left"><?= $curPlayer['LeftProperties'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">中属性</td>
<td align="left"><?= $curPlayer['MidProperties'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">右属性</td>
<td align="left"><?= $curPlayer['RightProperties'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门力量</td>
<td align="left"><?= $curPlayer['ShotPower'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门准确度</td>
<td align="left"><?= $curPlayer['ShotAccurate'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">弧线球</td>
<td align="left"><?= $curPlayer['arc'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门欲望</td>
<td align="left"><?= $curPlayer['ShotDesire'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">头 球</td>
<td align="left"><?= $curPlayer['header'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">抢 点</td>
<td align="left"><?= $curPlayer['qiangdian'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">守 门</td>
<td align="left"><?= $curPlayer['save'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">盯人防守</td>
<td align="left"><?= $curPlayer['close-marking'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">抢 断</td>
<td align="left"><?= $curPlayer['tackle'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">拼 抢</td>
<td align="left"><?= $curPlayer['pinqiang'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">活动范围</td>
<td align="left"><?= $curPlayer['scope'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">体 能</td>
<td align="left"><?= $curPlayer['SinewMax'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">控 球</td>
<td align="left"><?= $curPlayer['BallControl'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">过 人</td>
<td align="left"><?= $curPlayer['beat'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">速 度</td>
<td align="left"><?= $curPlayer['speed'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">敏 捷</td>
<td align="left"><?= $curPlayer['agility'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">理 智</td>
<td align="left"><?= $curPlayer['mind'] ?></td>
</tr>
</table>
<div style="display:none;">
<script src="http://s11.cnzz.com/stat.php?id=2228734&web_id=2228734&show=pic" language="JavaScript"></script>
</div>
</body>
</html>
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="<?= $curPlayer['name'] ?>-<?= $myTeam['name'] ?>-米兰百分百" />
<meta name="keywords" content="<?= $curPlayer['name'] ?>,<?= $curPlayer['alias'] ?>,<?= $curPlayer['en_name'] ?>,<?= $myTeam['name'] ?>,资料" />
<title><?= $curPlayer['name'] ?> - <?= $myTeam['name'] ?> - <?= $this->config->item('site_name') ?></title>
<link href="<?= $this->config->item('base_url') ?>css/style1.css" rel="stylesheet" type="text/css" />
<script src="<?= $this->config->item('base_url') ?>js/jquery.js"></script>
</head>
<body>
<?php $this->load->view('public/header'); ?>
<div class="glHeight"></div>
<div class="mainDiv">
<div class="nowPosition">
您所在的位置 -> <a href="/index.php">米兰百分百</a> -> <a href="<?= $this->config->item('base_url') ?>team/show/<?= $curPlayer['team_id'] ?>"><?= $myTeam['name'] ?></a> -> <?= $curPlayer['name'] ?>
</div>
</div>
<div class="glHeight"></div>
<div class="mainDiv">
<table cellpadding="3" width="100%">
<tr>
<?php foreach ($leagues as $id => $title): ?>
<td align="center">
<?php if ($leagueId == $id): ?>
<strong><?= $title ?></strong>
<?php else: ?>
<a href="<?= $this->config->item('base_url') ?>team/list/<?= $id ?>"><?= $title ?></a>
<?php endif; ?>
</td>
<?php if ($id % 7 == 0): ?>
</tr><tr>
<?php endif; ?>
<?php endforeach; ?>
</tr>
</table>
</div>
<div class="glHeight"></div>
<table align="center" width="1000" border="0" cellpadding="0" cellspacing="0">
<tr valign="top">
<td style="border:1px solid silver;">
<table align="center" cellpadding="5">
<tr valign="top">
<td>
<table border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="whitesmoke">
<tr>
<td align="right" style="font-weight:bold;">照 片</td>
<td align="center"><img src="<?= $this->config->item('cdn_url') . $curPlayer['ImgSrc'] ?>" /></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">中文名</td>
<td align="left"><?= $curPlayer['name'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">英文名</td>
<td align="left"><?= $curPlayer['en_name'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">别 名</td>
<td align="left"><?= $curPlayer['alias'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">号 码</td>
<td><?= $curPlayer['ShirtNo'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">国 籍</td>
<td><?= $curPlayer['country'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">生 日</td>
<td><?= $curPlayer['birthday'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">位 置</td>
<td><?=$positions[$curPlayer['position_id']]?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">身 高</td>
<td><?= $curPlayer['height'] ?>CM</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">体 重</td>
<td><?= $curPlayer['weight'] ?>KG</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">周 薪</td>
<td><?= $curPlayer['salary'] ?>W欧元</td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">人 品</td>
<td><?= $curPlayer['moral'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">脾 气</td>
<td><?= $curPlayer['temper'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">人 气</td>
<td><?= $curPlayer['popular'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">忠诚度</td>
<td><?= $curPlayer['loyalty'] ?></td>
</tr>
</table>
</td>
<td>
<table border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="whitesmoke">
<tr>
<td align="right" style="font-weight:bold;">意 识</td>
<td width="150" align="left"><?= $curPlayer['creativation'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">传 球</td>
<td align="left"><?= $curPlayer['pass'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">左属性</td>
<td align="left"><?= $curPlayer['LeftProperties'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">中属性</td>
<td align="left"><?= $curPlayer['MidProperties'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">右属性</td>
<td align="left"><?= $curPlayer['RightProperties'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门力量</td>
<td align="left"><?= $curPlayer['ShotPower'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门准确度</td>
<td align="left"><?= $curPlayer['ShotAccurate'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">弧线球</td>
<td align="left"><?= $curPlayer['arc'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">射门欲望</td>
<td align="left"><?= $curPlayer['ShotDesire'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">头 球</td>
<td align="left"><?= $curPlayer['header'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">抢 点</td>
<td align="left"><?= $curPlayer['qiangdian'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">守 门</td>
<td align="left"><?= $curPlayer['save'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">盯人防守</td>
<td align="left"><?= $curPlayer['close-marking'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">抢 断</td>
<td align="left"><?= $curPlayer['tackle'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">拼 抢</td>
<td align="left"><?= $curPlayer['pinqiang'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">活动范围</td>
<td align="left"><?= $curPlayer['scope'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">体 能</td>
<td align="left"><?= $curPlayer['SinewMax'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">控 球</td>
<td align="left"><?= $curPlayer['BallControl'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">过 人</td>
<td align="left"><?= $curPlayer['beat'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">速 度</td>
<td align="left"><?= $curPlayer['speed'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">敏 捷</td>
<td align="left"><?= $curPlayer['agility'] ?></td>
</tr>
<tr>
<td align="right" style="font-weight:bold;">理 智</td>
<td align="left"><?= $curPlayer['mind'] ?></td>
</tr>
</table></td>
</tr>
</table>
<div class="glHeight"></div>
<div>
<script type="text/javascript">
google_ad_client = "pub-7070906826715304";
/* 728x90, 创建于 10-10-20 */
google_ad_slot = "7008935553";
google_ad_width = 728;
google_ad_height = 90;
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div>
<div>
<div style="padding:5px;">
<strong>评论区</strong>
</div>
<!--评论内容-->
<ul id="comment_list">
<?php foreach($comments as $c): ?>
<li><span class="comment"><?=$c['comment']?></span><span class="pub_time"><?=date('Y-m-d H:i:s', $c['pub_time'])?></span></li>
<?php endforeach; ?>
</ul>
<div>
<textarea id="comment" name="comment" cols="45" rows="5"></textarea>
</div>
<table border="0" cellspacing="0" cellpadding="3">
<tr>
<td>
<input name="checkbox" type="checkbox" id="checkbox" checked="checked" />
匿名</td>
<td>
<input name="VerifyCode" type="text" id="VerifyCode" size="6" />
</td>
<td><img id="vcode" src="/inc/VerifyCode.php" onclick="refreshImg('vcode')" /></td>
<td>
<input type="button" name="button" id="btnComment" value="提交评论" />
</td>
<td> </td>
</tr>
</table>
</div>
</td>
<td width="10"></td>
<!--右侧-->
<td width="260">
<div style="background-color: whitesmoke;padding:5px;font-weight:bold;">我的队友</div>
<div style="height:200px;overflow:auto;">
<?php foreach ($players as $p): ?>
<div style="padding:3px;"><a href="<?= $this->config->item('base_url') ?>player/show/<?= $p['id'] ?>"><?= $p['ShirtNo'] ?> <?= $p['name'] ?></a></div>
<?php endforeach; ?>
</div>
<div class="glHeight"></div>
<script type="text/javascript">
/*250*250,创建于2010-11-17*/
var cpro_id = 'u282332';
</script>
<script type="text/javascript" src="http://cpro.baidu.com/cpro/ui/c.js"></script>
<div class="glHeight"></div>
<!--最热文字新闻-->
<div style="background-color: whitesmoke;height:40px;line-height:40px;font-weight:bold;width:250px;padding-left:10px;">热门新闻</div>
<ul style="width:260px;overflow-x: hidden;">
<?php foreach($recommendArticles as $a): ?>
<li style="height:25px;"><a href="<?=$this->config->item('base_url')?>article/show/<?=$a['id']?>"><?=$a['title']?></a></li>
<?php endforeach; ?>
</ul>
</td>
</tr>
</table>
<?php $this->load->view('public/footer'); ?>
<script type="text/javascript">
$("#btnComment").click(function(){
$.post("<?=$this->config->item('base_url')?>player/add_comment/<?=$curPlayer['id']?>", {comment:$("#comment").val()}, function(response){
if (response.status === 1)
{
$("#comment_list").append("<span class='comment'>" + response.comment_data.comment + "</span><span class='pub_time'>" + response.comment_data.time + "</span>");
}
}, 'json');
});
</script>
</body>
</html><file_sep><?php
/**
* Description of article_model
*
* @author qiaoliang
*/
class Health_log_model extends CI_Model{
public $table = 'health_log';
public function __construct() {
parent::__construct();
$this->load->database();
}
public function getById($id)
{
$records = $this->db->get_where($this->table, array('id'=>$id))->result_array();
$targetNews = NULL;
if (!empty($records))
{
$targetNews = $records[0];
}
return $targetNews;
}
public function getByDate($date)
{
$records = $this->db->get_where($this->table, array('date'=>$date))->result_array();
$targetNews = NULL;
if (!empty($records))
{
$targetNews = $records[0];
}
return $targetNews;
}
/**
* 后台新增
* @param type $content
* @param type $date
*/
public function add($content, $date)
{
$data = array(
'content' => $content,
'date' => $date,
);
$this->db->insert($this->table, $data);
}
public function edit($id, $content)
{
$data = array(
'content' => $content,
);
$this->db->update($this->table, $data, array('id'=>$id));
}
public function del($id)
{
$this->db->delete($this->table, array('id' => $id));
}
/**
* 按条件获取新闻列表,可分页
* @param int $page 当前页码
* @param int $perPage 每页数量
* @param int $newsType 新闻类型
* @param string $title 标题搜索的关键字
* @param bool $isValid 是否已发布
* @param int $createTime 按指定时间段查询,unix时间戳
* @return array
*/
public function listAll($page, $perPage)
{
$startIndex = ($page-1) * $perPage;
$this->db->from($this->table);
$this->db->limit($perPage, $startIndex);
$this->db->order_by("date", "desc");
$query = $this->db->get();
$news = $query->result_array();
return $news;
}
public function getCount()
{
$this->db->from($this->table);
$count = $this->db->count_all_results();
return $count;
}
}
<file_sep><?php
$weekarray = array("日","一","二","三","四","五","六");
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>宝宝健康日志查看</title>
<link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<a href="<?=$this->config->item('base_url')?>health_log/add"><button type="button" class="btn btn-danger" style="width:100%;margin-top: 20px;margin-bottom: 20px;">添加记录</button></a>
<a href="http://www.baidu.com/" target="_blank"><button type="button" class="btn btn-info" style="width:100%">打开百度</button></a>
<?php foreach($logs as $l): ?>
<div style="margin-top:20px;border: 1px silver solid;padding:5px;">
<div style="font-weight:bold;">
<div style="float:left;">
<?=$l['date']?> <?="星期".$weekarray[date('w', strtotime($l['date']))]?>
</div>
<div style="float:right;">
<button class="btn btn-warning" for="<?=$l['id']?>">修改</button>
</div>
</div>
<div style="clear:both;" id="div_<?=$l['id']?>">
<?=$l['content']?>
</div>
</div>
<?php endforeach; ?>
</div>
<script>
$(".btn-warning").click(function(){
var logId = $(this).attr("for");
var divId = "div_" + logId;
$("#"+divId).html("<textarea id='textarea_" + logId + "' class='form-control' rows='3'>" + $("#"+divId).html() + "</textarea><button class='btn btn-danger' onclick='saveLog(" + logId + ")'>保存</button>");
});
function saveLog(logId)
{
var postData = {
id:logId,
content:$("#textarea_"+logId).val()
};
$.post("<?=$this->config->item('base_url')?>health_log/ajax_edit_save", postData, function(response){
if (response.status == 1)
{
$("#div_"+logId).html(response.content);
alert('修改成功');
}
else
{
alert('修改失败');
}
}, 'json');
}
</script>
</body>
</html>
<file_sep><?php
class Page extends CI_Controller
{
public function index()
{
$this->load->model(array('news_model'));
$data['milanNews'] = $this->news_model->getMilanNews(10);
$data['newNews'] = $this->news_model->getNewNews(20);
$data['hotNews'] = $this->news_model->getHotNews(20);
$this->load->view('page/index', $data);
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="description" content="<?=$curTeam['name']?>-米兰百分百" />
<meta name="keywords" content="<?=$curTeam['name']?>,<?=$curTeam['alias']?>,官方网站,官网" />
<title><?=$curTeam['name']?> - <?= $this->config->item('site_name') ?></title>
</head>
<body>
<?php foreach ($leagues as $id => $title): ?>
<div style="padding:5px;float:left;">
<?php if ($leagueId == $id): ?>
<strong><?= $title ?></strong>
<?php else: ?>
<a href="<?=$this->config->item('base_url')?>team/list/<?=$id?>"><?= $title ?></a>
<?php endif; ?>
</div>
<?php endforeach; ?>
<div style="clear:both;"></div>
<table border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="silver">
<tr>
<td align="right" bgcolor="whitesmoke">队 标:</td>
<td bgcolor="#FFFFFF"><img width="60" height="60" src="<?= $this->config->item('cdn_url') . $curTeam['ImgSrc'] ?>" /></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">球 队:</td>
<td bgcolor="#FFFFFF"><?= $curTeam['name'] ?></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">主 场:</td>
<td bgcolor="#FFFFFF"><?= $curTeam['FieldName'] ?></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">座位数:</td>
<td bgcolor="#FFFFFF"><?= $curTeam['seats'] ?></td>
</tr>
<tr>
<td align="right" bgcolor="whitesmoke">官方网站:</td>
<td bgcolor="#FFFFFF"><a href="http://<?= $curTeam['website'] ?>" target="_blank"><?= $curTeam['website'] ?></a></td>
</tr>
</table>
<table border="0" cellpadding="5" cellspacing="0">
<tr align="center" bgcolor="whitesmoke">
<td>照片</td>
<td>号码</td>
<td>姓名</td>
<td>国籍</td>
<td>出生日期</td>
<td>身高</td>
<td>体重</td>
</tr>
<?php foreach ($players as $player): ?>
<tr align="center">
<td><a href="<?= $this->config->item('base_url') ?>player/show/<?= $player['id'] ?>"><img src="<?= $this->config->item('cdn_url') . $player['ImgSrc'] ?>" width="60" border="0" /></a></td>
<td><?= $player['ShirtNo'] ?></td>
<td><a href="<?= $this->config->item('base_url') ?>player/show/<?= $player['id'] ?>"><?= $player['name'] ?></a></td>
<td><?= $player['country'] ?></td>
<td><?= $player['birthday'] ?></td>
<td><?= $player['height'] ?>CM</td>
<td><?= $player['weight'] ?>KG</td>
</tr>
<?php endforeach; ?>
</table>
<div style="display:none;">
<script src="http://s11.cnzz.com/stat.php?id=2228734&web_id=2228734&show=pic" language="JavaScript"></script>
</div>
</body>
</html>
<file_sep><?php
/**
* Description of appointment
*
* @author qiaoliang
*/
class appointment extends Back_Controller{
public function show($id)
{
$this->load->model(array('appointment_model', 'joiner_model'));
$data['curAppointment'] = $this->appointment_model->getById($id);
$data['joiners'] = $this->joiner_model->getByAppointmentId($id);
$this->load->view('tiqiu/appointment_show', $data);
}
public function ajax_join()
{
$appointmentId = $this->input->post("appointment_id");
$name = $this->input->post("name");
$mobile = $this->input->post("mobile");
$this->load->model('joiner_model');
$this->joiner_model->add($appointmentId, $name, $mobile);
echo json_encode(array('status'=>1));
}
public function list_back($page=1)
{
$this->checkPurview();
$this->load->model('appointment_model');
$this->load->helper('form');
$keyword = trim($this->input->post("keyword"));
$appointmentType = $this->input->post("appointment_type");
if ($keyword)
{
$perPage = 200;
}
else
{
$perPage = 20;
}
$recordCount = $this->appointment_model->getCount($appointmentType, $keyword);
$pageCount = ceil($recordCount / $perPage);
$allNews = $this->appointment_model->listAll($page, $perPage, $appointmentType, $keyword);
$data['appointments'] = $allNews;
$data['curPage'] = $page;
$data['pageCount'] = $pageCount;
$data['keyword'] = $keyword;
$data['sessionMsg'] = $this->getSessionMsg();
$this->load->view('appointment/list_back', $data);
}
}
<file_sep><?php
class Player_comment_model extends CI_Model
{
private $table = 'milan100_player_comment';
public function __construct() {
parent::__construct();
$this->load->database();
}
/**
*
* @param type $playerId
* @param type $comment
* @param type $ip
*/
public function add($playerId, $comment, $ip)
{
$data = array(
'player_id' => $playerId,
'comment' => $comment,
'ip' => ip2long($ip),
'pub_time' => time()
);
$this->db->insert($this->table, $data);
}
public function getAllByPlayerId($playerId)
{
$this->db->where(array('player_id'=>$playerId));
$this->db->order_by('pub_time', 'asc');
$comments = $this->db->get($this->table)->result_array();
return $comments;
}
}<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>文章列表-米兰百分百</title>
<link href="<?=$this->config->item('base_url')?>res/css/style1.css" rel="stylesheet" type="text/css" />
<script src="<?=$this->config->item('base_url')?>res/js/jquery.js"></script>
</head>
<body>
<?php $this->load->view('public/header'); ?>
<div class="glHeight"></div>
<div class="mainDiv">
<div class="nowPosition">您所在的位置 -> <a href="<?=$this->config->item('base_url')?>">米兰百分百</a> </div>
</div>
<div class="glHeight"></div>
<div class="mainDiv">
<div class="glHeight"></div>
<div style="float:left;">
<table border="0" align="center" cellpadding="3" cellspacing="0">
<?php foreach($allNews as $n): ?>
<tr bgcolor="#FFFFFF">
<td style="border-bottom:1px dashed silver;"><a href="<?=$this->config->item('base_url')?>article/show/<?=$n['id']?>" target="_blank">·<?=$n['title']?></a></td>
<td style="border-bottom:1px dashed silver;"><?=$n['PubTime']?></td>
</tr>
<?php endforeach; ?>
</table>
<div class="glHeight"></div>
<table align="center" border="0" cellspacing="0" cellpadding="0">
<tr>
<td bgcolor="#FFFFFF" align="right">
<table border="0" cellspacing="0" cellpadding="5">
<tr>
<td> </td>
<td>
<?php for($i=1;$i<=$pageCount;$i++): ?>
<a href="<?=$this->config->item("base_url")?>article/list/<?=$i?>/<?=$articleType?>"><?=$i?></a> |
<?php endfor; ?>
</td>
<td><?=$pageCount?>页</td>
<td> </td>
</tr>
</table>
<div class="glHeight"></div>
</td>
</tr>
</table>
</div>
<div style="float:right;">
<script type="text/javascript">
/*250*250,创建于2010-11-17*/
var cpro_id = 'u282332';
</script>
<script type="text/javascript" src="http://cpro.baidu.com/cpro/ui/c.js"></script>
</div>
</div>
<div class="clear_both"></div>
<?php $this->load->view('public/footer'); ?>
</body>
</html><file_sep><?php
/**
* Description of joiner_model
*
* @author qiaoliang
*/
class joiner_model extends CI_Model{
private $table = 'qcsj_joiner';
public function __construct() {
parent::__construct();
$this->load->database();
}
public function add($appointmentId, $name, $mobile)
{
$data = array(
'appointment_id' => $appointmentId,
'name' => $name,
'mobile' => $mobile,
'join_time' => date('Y-m-d H:i:s'),
);
$this->db->insert($this->table, $data);
}
public function getByAppointmentId($appointmentId)
{
$joiners = $this->db->get_where($this->table, array('appointment_id'=>$appointmentId))->result_array();
return $joiners;
}
}
<file_sep><?php
class Player_model extends CI_Model
{
private $table = 'ypn_bak_players';
public function __construct() {
parent::__construct();
$this->load->database();
}
public function getByTeamId($teamId)
{
$this->db->order_by('ShirtNo', 'asc');
$query = $this->db->get_where($this->table, array('team_id'=>$teamId));
$players = $query->result_array();
return $players;
}
public function getById($id)
{
$query = $this->db->get_where($this->table, array('id'=>$id));
$players = $query->result_array();
if (!empty($players))
{
return $players[0];
}
}
public function insert($data)
{
$this->db->insert($this->table, $data);
}
/**
* 更新
* @param type $id
* @param type $data
*/
public function update($id, $data)
{
$this->db->update($this->table, $data, array('id'=>$id));
}
public function search($name, $birthday)
{
if ($name)
{
$this->db->like('name', $name);
}
if ($birthday)
{
$this->db->where('birthday',$birthday);
}
$players = $this->db->get($this->table)->result_array();
return $players;
}
public function del($id)
{
$this->db->delete($this->table, array('id' => $id));
}
public function getAllPic()
{
$this->db->select('ImgSrc');
$records = $this->db->get($this->table)->result_array();
$pics = array();
foreach($records as $r)
{
$pics[] = $r['ImgSrc'];
}
return $pics;
}
public function getUnpushedIds()
{
$ids = $this->db->select(array('id'))->where('is_push_baidu', 0)->limit(2000)->get($this->table)->result_array();
return $ids;
}
public function setPush($firstId, $lastId)
{
$this->db->update($this->table, array('is_push_baidu'=>1), array('id >=' => $firstId, 'id <=' => $lastId));
}
}
<file_sep><?php
/**
* Description of health_log
*
* @author qiaoliang
*/
class health_log extends Back_Controller{
public function index($page=1)
{
$this->load->model('health_log_model');
$this->load->helper('form');
$perPage = 40;
$recordCount = $this->health_log_model->getCount();
$pageCount = ceil($recordCount / $perPage);
$data['logs'] = $this->health_log_model->listAll($page, $perPage);
$data['curPage'] = $page;
$data['pageCount'] = $pageCount;
$data['sessionMsg'] = $this->getSessionMsg();
$this->load->view('health_log/index', $data);
}
public function add()
{
if(!empty($_POST))
{
$this->load->model('health_log_model');
$date = $this->input->post("date");
$content = nl2br($this->input->post("content"));
if (isset($_POST['is_insert_time']))
{
$content = $this->input->post("time") . ' ' . $content;
}
$uploadInfo = $this->getUploadData("photo");
$imgSrc = '';
if (isset($uploadInfo['img_src']) && !$uploadInfo['error_msg']) //有图片
{
$imgSrc = $uploadInfo['img_src'];
$config['image_library'] = 'gd2';
$config['source_image'] = $uploadInfo['img_src'];
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 480;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$content .= "<br/><img src='" . $this->config->item('base_url') . $imgSrc . "' class='img-responsive' /><br/>";
}
$targetLog = $this->health_log_model->getByDate($date);
if($targetLog) //追加
{
$content = $targetLog['content'] . '<br/>' . $content;
$this->health_log_model->edit($targetLog['id'], $content);
}
else
{
$this->health_log_model->add($content, $date);
}
header("location:" . $this->config->item('base_url') . 'health_log');
exit;
}
$this->load->view('health_log/add');
}
public function ajax_edit_save()
{
$id = $this->input->post("id");
$content = nl2br($this->input->post("content"));
$this->load->model('health_log_model');
$this->health_log_model->edit($id, $content);
echo json_encode(array('status'=>1, 'content'=>$content));
}
}
<file_sep><?php
/**
* Description of field
*
* @author qiaoliang
*/
class field extends Back_Controller{
private $ak = '<KEY>';
public function list_back($page=1)
{
$this->checkPurview();
$this->load->model('field_model');
$this->load->helper('form');
$keyword = trim($this->input->post("keyword"));
$fieldType = $this->input->post("field_type");
if ($keyword)
{
$perPage = 200;
}
else
{
$perPage = 20;
}
$recordCount = $this->field_model->getCount($fieldType, $keyword);
$pageCount = ceil($recordCount / $perPage);
$allNews = $this->field_model->listAll($page, $perPage, $fieldType, $keyword);
$data['fields'] = $allNews;
$data['curPage'] = $page;
$data['pageCount'] = $pageCount;
$data['keyword'] = $keyword;
$data['sessionMsg'] = $this->getSessionMsg();
$this->load->view('field/list_back', $data);
}
public function show($id)
{
$this->load->model('field_model');
$data['curField'] = $this->field_model->getById($id);
$this->load->view('field/show', $data);
}
public function push_baidu()
{
ini_set('display_errors', 'on');
$this->load->model('field_model');
$ids = $this->field_model->getUnpushedIds();
$idCount = count($ids);
$urls = array();
foreach($ids as $n)
{
$urls[] = 'http://www.milan100.com/field/show/'.$n['id'];
}
if ($idCount > 0)
{
$result = json_decode($this->pushBaidu($urls), TRUE);
if(isset($result['success']))
{
$firstId = $ids[0]['id'];
$lastId = $ids[$idCount-1]['id'];
// $this->player_model->setPush($firstId, $lastId);
}
print_r($result);
}
else
{
echo 'no data';
}
}
public function fetch_from_baidu_map()
{
$city = '上海';
$keyword = '足球场';
$total = $this->getTotal();
$pageCount = $total / 20;
$fields = array();
for($i=0;$i<$pageCount;$i++)
{
$fields += $this->getByPage($i);
}
print_r($fields);
}
private function getTotal()
{
$total = 0;
$url = "http://api.map.baidu.com/place/v2/search?page_size=20&page_num=" . $curPage . "&query=" . $keyword . "®ion=" . $city . "&output=json&ak=" . $ak;
$responseArr = json_decode(file_get_contents($url), TRUE);
if ( ($responseArr['status'] == 0) && ($responseArr['message'] == 'ok') )
{
$total = $responseArr['total'];
}
return $total;
}
private function getByPage($curPage)
{
$url = "http://api.map.baidu.com/place/v2/search?page_size=20&page_num=" . $curPage . "&query=" . $keyword . "®ion=" . $city . "&output=json&ak=" . $ak;
$responseArr = json_decode(file_get_contents($url), TRUE);
if ( ($responseArr['status'] == 0) && ($responseArr['message'] == 'ok') )
{
return $responseArr['results'];
}
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title><?=$this->config->item('site_name')?></title>
</head>
<body>
<div class="mainDiv">
<?php foreach ($leagues as $id => $title): ?>
<div style="padding:5px;float:left;">
<?php if ($leagueId == $id): ?>
<strong><?= $title ?></strong>
<?php else: ?>
<a href="<?= $this->config->item('base_url') ?>team/list/<?= $id ?>"><?= $title ?></a>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<div class="glHeight" style="clear:both;"></div>
<div class="mainDiv">
<?php foreach ($teams as $k => $team): ?>
<div style="float:left;padding:5px;text-align: center;width:90px;">
<a href="<?= $this->config->item('base_url') ?>team/show/<?= $team['id'] ?>">
<img src='<?=$this->config->item('cdn_url').$team['ImgSrc']?>' style="width:60px;height:60px;" /><br/>
<?= $team['name'] ?>
</a>
</div>
<?php if (($k+1) % 10 == 0): ?>
<div class="clear_both"></div>
<?php endif; ?>
<?php endforeach; ?>
</div>
<div style="display:none;">
<script src="http://s11.cnzz.com/stat.php?id=2228734&web_id=2228734&show=pic" language="JavaScript"></script>
</div>
</body>
</html>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="post">
管理员:<input type="text" name="admin" /><br/>
密 码:<input type="<PASSWORD>" name="password" /><br/>
<input type="submit" value="登录" />
</form>
<?php
// put your code here
?>
</body>
</html>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['default_controller'] = 'page';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['team/list'] = 'team/list_front';
$route['team/list/(:num)'] = "team/list_front/$1";
$route['article/list'] = "article/list_front";
$route['article/list/(:num)'] = "article/list_front/$1";
$route['article/list/(:num)/(:num)'] = "article/list_front/$1/$2";
$route['tiqiu2'] = 'tiqiu/index';<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="<?=$this->config->item('base_url')?>res/css/back.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<?php $this->load->view('public/back_lefter'); ?>
<div class="right_body">
<div class="leagues">
<?php foreach ($leagues as $id => $title): ?>
<div>
<?php if ($leagueId == $id): ?>
<strong><?= $title ?></strong>
<?php else: ?>
<a href="<?= $this->config->item('base_url') ?>team/list_back/<?= $id ?>"><?= $title ?></a>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<div class="teams clear_both">
<?php foreach ($teams as $k => $team): ?>
<div>
<a href="<?= $this->config->item('base_url') ?>team/edit/<?= $team['id'] ?>">
<img src='<?= $this->config->item('cdn_url') . $team['ImgSrc'] ?>' style="width:60px;height:60px;" /><br/>
<?= $team['name'] ?>
</a>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
$weekarray = array("日","一","二","三","四","五","六");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>宝宝健康名词查看</title>
<link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div>
<a href="<?=$this->config->item('base_url')?>word/add"><button type="button" class="btn btn-primary" style="width:100%;margin-bottom: 20px;">添加记录</button></a>
<a href="http://www.baidu.com/" target="_blank"><button type="button" class="btn btn-info" style="width:100%">打开百度</button></a>
</div>
<?php foreach($words as $l): ?>
<div style="margin-top:20px;border: 1px silver solid;padding:5px; clear: both; height:30px;">
<div style="float:left;">
<a href="<?=$this->config->item('base_url')?>word/show/<?=$l['id']?>"><?=$l['title']?></a>
</div>
<div style="float:right">
<a href="<?=$this->config->item('base_url')?>word/edit/<?=$l['id']?>">修改</a>
<a href="<?=$this->config->item('base_url')?>word/del/<?=$l['id']?>" onclick="return confirm('确认要删除吗?')">删除</a>
</div>
</div>
<?php endforeach; ?>
<script>
$(".btn-warning").click(function(){
var logId = $(this).attr("for");
var divId = "div_" + logId;
$("#"+divId).html("<textarea id='textarea_" + logId + "' class='form-control' rows='3'>" + $("#"+divId).html() + "</textarea><button class='btn btn-danger' onclick='saveLog(" + logId + ")'>保存</button>");
});
function saveLog(logId)
{
var postData = {
id:logId,
content:$("#textarea_"+logId).val()
};
$.post("<?=$this->config->item('base_url')?>health_log/ajax_edit_save", postData, function(response){
if (response.status == 1)
{
$("#div_"+logId).html(response.content);
alert('修改成功');
}
else
{
alert('修改失败');
}
}, 'json');
}
</script>
</body>
</html>
<file_sep><?php
/**
* Description of appointment_model
*
* @author qiaoliang
*/
class appointment_model extends CI_Model{
private $table = 'qcsj_appointment';
public function __construct() {
parent::__construct();
$this->load->database();
}
public function add($hostName, $hostMobile, $field, $playTime, $remark, $address)
{
$data = array(
'host_name' => $hostName,
'host_mobile' => $hostMobile,
'field' => $field,
'play_time' => $playTime,
'pub_time' => date('Y-m-d H:i:s'),
'remark' => $remark,
'address' => $address,
);
$this->db->insert($this->table, $data);
}
public function getAll()
{
$this->db->select(array('id', 'field', 'host_name', 'host_mobile', 'play_time'));
$this->db->order_by('id', 'desc');
$appointments = $this->db->get($this->table)->result_array();
return $appointments;
}
public function getById($id)
{
$appointments = $this->db->get_where($this->table, array('id'=>$id))->result_array();
$targetAppointment = NULL;
if (!empty($appointments))
{
$targetAppointment = $appointments[0];
}
return $targetAppointment;
}
public function getCount($newsType, $title)
{
$this->db->from($this->table);
if ($newsType)
{
$this->db->where(array('class_id'=>$newsType));
}
if ($title)
{
$this->db->like('title', $title, 'both');
}
$count = $this->db->count_all_results();
return $count;
}
public function listAll($page, $perPage, $newsType, $title, $isValid="")
{
$startIndex = ($page-1) * $perPage;
if ($newsType)
{
$this->db->where('class_id', $newsType);
}
if ($isValid)
{
$this->db->where('isPublic', $isValid);
}
if ($title)
{
$this->db->like('title', $title, 'both');
}
$this->db->from($this->table);
$this->db->limit($perPage, $startIndex);
$this->db->select(array('id', 'field', 'pub_time', 'play_time', 'address', 'host_name', 'host_mobile', 'remark'));
$this->db->order_by("id", "desc");
$query = $this->db->get();
$news = $query->result_array();
return $news;
}
}<file_sep><?php
/**
* Description of article
*
* @author qiaoliang
*/
class article extends Back_Controller{
/**
* 前台列表
* @param number $curPage
* @param string $articleType 空就是最新
*/
public function list_front($curPage=1, $articleType="")
{
$this->load->model(array('article_model'));
$perPage = 15;
$recordCount = $this->article_model->getCount($articleType, "");
$pageCount = ceil($recordCount / $perPage);
if ($curPage > $pageCount) $curPage = $pageCount;
if ($curPage < 1) $curPage = 1;
$data = array();
$allNews = $this->article_model->listAll($curPage, $perPage, $articleType, "", 1);
$data['allNews'] = $allNews;
$data['curPage'] = $curPage;
$data['pageCount'] = $pageCount;
$data['articleType'] = $articleType;
$this->load->view('article/list_front', $data);
}
public function show($id)
{
$this->load->model(array('article_model', 'article_class_model'));
$this->article_model->addHitCount($id);
$data['curArticle'] = $this->article_model->getById($id);
$data['curArticleClass'] = $this->article_class_model->getById($data['curArticle']['class_id']);
if (!$data['curArticle']['isPublic'])
{
die('access denied');
}
$data['previousArticle'] = $this->article_model->getPrevious($id, $data['curArticle']['class_id']);
$data['nextArticle'] = $this->article_model->getNext($id, $data['curArticle']['class_id']);
$data['relatedArticles'] = $this->article_model->getRelated($data['curArticle']['class_id']);
$data['recommendArticles'] = $this->article_model->getRecommended();
$this->load->view('article/show', $data);
}
/**
* 后台列表
* @param number $page
* @param string $title
* @param string $articleType
*/
public function list_back($page=1)
{
$this->checkPurview();
$this->load->model('article_model');
$this->load->helper('form');
$keyword = trim($this->input->post("keyword"));
$articleType = $this->input->post("article_type");
if ($keyword)
{
$perPage = 200;
}
else
{
$perPage = 20;
}
$recordCount = $this->article_model->getCount($articleType, $keyword);
$pageCount = ceil($recordCount / $perPage);
$allNews = $this->article_model->listAll($page, $perPage, $articleType, $keyword);
$data['allNews'] = $allNews;
$data['curPage'] = $page;
$data['pageCount'] = $pageCount;
$data['keyword'] = $keyword;
$data['articleSearchType'] = $articleType;
$data['sessionMsg'] = $this->getSessionMsg();
$this->load->view('article/list_back', $data);
}
public function add()
{
$this->checkPurview();
$this->load->model(array('article_model', 'article_class_model'));
if (empty($_POST))
{
$data['articleClassTree'] = $this->article_class_model->getTree();
$this->load->view('article/add', $data);
}
else
{
$title = $this->input->post("title");
$keywords = $this->input->post("keywords");
$author = $this->input->post("author");
$isPublic = $this->input->post("isPublic");
$isRecommend = (int)$this->input->post("is_recommend");
$classId = $this->input->post("class_id");
$content = $this->input->post("content");
$this->article_model->add($title, $keywords, $author, $isPublic, date('Y-m-d H:i:s'), $classId, $content, $isRecommend);
$this->setSessionMsg("新闻添加成功");
header("location:".$this->config->item('base_url').'article/list_back');
}
}
public function edit($id)
{
$this->checkPurview();
$this->load->model(array('article_model', 'article_class_model'));
if (empty($_POST))
{
$data['curArticle'] = $this->article_model->getById($id);
$data['articleClassTree'] = $this->article_class_model->getTree();
$this->load->view('article/edit', $data);
}
else
{
$title = $this->input->post("title");
$keywords = $this->input->post("keywords");
$author = $this->input->post("author");
$isPublic = $this->input->post("isPublic");
$isRecommend = $this->input->post("is_recommend");
$classId = $this->input->post("class_id");
$content = $this->input->post("content");
$this->article_model->edit($id, $title, $keywords, $author, $isPublic, date('Y-m-d H:i:s'), $classId, $content, $isRecommend);
$this->setSessionMsg("新闻修改成功");
header("location:".$this->config->item('base_url').'article/list_back');
}
}
public function del($id)
{
$this->checkPurview();
$this->load->model('article_model');
$this->article_model->del($id);
$this->setSessionMsg("新闻删除成功");
header("location:".$this->config->item('base_url').'article/list_back');
}
/**
* 后台一键翻译英文-》中文
*/
public function translate()
{
$q = $_POST['q'];
$url = "http://openapi.baidu.com/public/2.0/bmt/translate";
$key = "<KEY>";
$fromLang = $_POST['from'];
$toLang = $_POST['to'];
$postData = array("from"=>$fromLang, "to"=>$toLang, "client_id"=>$key, "q"=>$q);
$str = SiteTools::doHttpPost_2($url, $postData);
echo $str;
}
public function push_baidu()
{
ini_set('display_errors', 'on');
$this->load->model('article_model');
$urls = $this->article_model->getAllUrl();
$result = $this->pushBaidu($urls);
echo $result;
}
}
<file_sep><ul class="left_menu">
<li><a href="<?=$this->config->item('base_url')?>player/add">球员添加</a></li>
<li><a href="<?=$this->config->item('base_url')?>team/list_back">球员管理</a></li>
<li><a href="<?=$this->config->item('base_url')?>team/add">球队添加</a></li>
<li><a href="<?=$this->config->item('base_url')?>player/search">球员搜索</a></li>
<li><a href="<?=$this->config->item('base_url')?>team/edit/0">自由球员</a></li>
<li><a href="<?=$this->config->item('base_url')?>article/add">新闻添加</a></li>
<li><a href="<?=$this->config->item('base_url')?>article/list_back">新闻管理</a></li>
<li><a href="<?=$this->config->item('base_url')?>appointment/list_back">约球管理</a></li>
<li><a href="<?=$this->config->item('base_url')?>field/list_back">球场管理</a></li>
</ul><file_sep><?php
class Admin extends Back_Controller
{
public function login()
{
if (empty($_POST))
{
$this->load->view('admin/login');
}
else
{
$admin = $this->input->post("admin");
$password = $this->input->post("password");
if ($admin == 'bridge3000' && $password == '<PASSWORD>!')
{
$_SESSION[$this->adminSessionKey] = $admin;
header("location:".$this->config->item('base_url').'team/list_back');
}
else
{
$this->load->view('admin/login');
}
}
}
}
<file_sep><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="<?php echo $this->config->item("base_url"); ?>res/css/back.css" rel="stylesheet">
<style>
.keyword {
color:#ff0000;
font-weight:bold;
}
</style>
<script src="http://d001.download.appget.cn/someapk/jquery-1.11.1.min.js"></script>
<script src="<?php echo $this->config->item("base_url"); ?>res/js/back.js"></script>
<script>
<?php if ($sessionMsg): ?>
$(document).ready(function () {
showBodyMsg("<?php echo $sessionMsg; ?>");
});
<?php endif; ?>
</script>
</head>
<body>
<?php $this->load->view('public/back_lefter'); ?>
<div class="right_body">
<div style="margin-bottom:20px;">
<form method="post" action="<?=$this->config->item("base_url") ?>appointment/list_back/">
关键字:<input type="text" id="keyword" name="keyword" value="<?php echo $keyword; ?>" />
<button type="submit" >搜 索</button>
</form>
</div>
<table class="table_style_1">
<tr>
<th>ID</th>
<th>球场</th>
<th>发布时间</th>
<th>比赛时间</th>
<th>地址</th>
<th>发起人姓名</th>
<th>发起人手机</th>
<th>备注</th>
<th>链接</th>
<th>操作</th>
</tr>
<?php foreach ($appointments as $n): ?>
<?php $url = $this->config->item("base_url") . 'appointment/show/' . $n['id']; ?>
<tr>
<td><?php echo $n['id']; ?></td>
<td><?=$n['field']?></td>
<td><?=$n['pub_time']?></td>
<td><?php echo $n['play_time']; ?></td>
<td><?php echo $n['address']; ?></td>
<td><?php echo $n['host_name']; ?></td>
<td><?php echo $n['host_mobile']; ?></td>
<td><?php echo $n['remark']; ?></td>
<td><a href="<?=$url?>" target="_blank"><?php echo $url; ?></a></td>
<td><a href="<?php echo $this->config->item("base_url") ?>appointment/del/<?php echo $n['id']; ?>" onclick="return confirm('确认要删除吗?')">删除</a></td>
</tr>
<?php endforeach; ?>
</table>
<div>
<?php for ($i = 1; $i <= $pageCount; $i++): ?>
<?php
if ($i == $curPage) {
$className = "current";
$href = "#";
} else {
$className = "";
$href = $this->config->item("base_url") . "appointment/list_back/" . $i . "/";
}
?>
<a href="<?php echo $href; ?>" class="<?php echo $className; ?>"><?php echo $i; ?></a>
<?php endfor; ?>
</div>
</div>
</body>
</html>
|
c823f731e37b4bb0077e355a2672a7545885b041
|
[
"PHP"
] | 52
|
PHP
|
bridge3000/milan100
|
c7c4046d1b3207208bd8a5f26f4d205ae182df26
|
76d7c77036047200723b71e3794a8f3684f5633b
|
refs/heads/master
|
<repo_name>sebastians22/COOP2018-1<file_sep>/Chapter06/U06_Ex09_LetterGrades.py
# U06_Ex09_LetterGrades.py
#
# Author: <NAME>
# Course: Coding for OOP
# Section: A3
# Date: 21 Oct 2017
# IDE: PyCharm Community Edition
#
# Assignment Info
# Exercise: 9
# Source: Python Programming
# Chapter: 6
#
# Program Description
# Solve PE 5.3 using function letterGrade()
# Accepts an exam score as input and prints the corresponding letter grade
#
# Algorithm (pseudocode)
# introduce program
# get exam score from user
# call letterGrade() passing exam score as parameter assign result to grade
# print letter returned from letterGrade()
#
# letterGrade():
# score is argument
# get index by integer dividing score by 10
# set grades to 'FFFFFFDCBAA'
# return letter grade using index to access grades
def main():
# introduce program
print('This program converts a numeric grade (0-100) to a letter grade (A,B,C,D,F)\n')
# get exam score from user
examGrade = int(input('Please enter the exam grade: '))
# call letterGrade() passing exam score as parameter assign result to grade
grade = letterGrade(examGrade)
# print letter returned from letterGrade()
print('An exam grade of {0} corresponds to a letter grade of {1}.'.format(examGrade, grade))
# letterGrade():
# score is argument
def letterGrade(score):
# get index by integer dividing by 10
idx = score // 10
letters = 'F' * 6 + 'DCBAA'
return letters[idx]
main()<file_sep>/Chapter05/U05_Ex14_WordCount.py
# U05_Ex14_WordCount.py
#
# Author: <NAME>
# Course: Coding for OOP
# Section: A3
# Date: 11 Oct 2017
# IDE: PyCharm Community Edition
#
# Assignment Info
# Exercise: 14
# Source: Python Programming
# Chapter: 5
#
# Program Description
# Displays counts of lines, words, and characters in a file
#
# Algorithm (pseudocode)
# Print intro
# Get filename from user
# Open file for reading
# Read lines with lines = readlines()
# Close file
# Loop through lines, counting words and characters
# Print results
def main():
# Print intro
print('This program displays counts of lines, words, and characters in a file input by the user.')
# Get filename from user
fileName = input('Please enter the filename: ')
# Open file for reading
fileHandle = open(fileName, 'r')
# Read lines with lines = readlines()
lines = fileHandle.readlines()
# Close file
fileHandle.close()
# Loop through lines, counting words and characters
wordCount = 0
charCount = 0
for line in lines:
words = line.split(' ')
wordCount += len(words)
for word in words:
charCount += len(word)
# Print results
print('Lines: {0}\nWords: {1}\nChars: {2}'.format(len(lines), wordCount, charCount))
main()
|
d8033d8d631bcc9875dfa6dc9d99971c4dcbe686
|
[
"Python"
] | 2
|
Python
|
sebastians22/COOP2018-1
|
44d8b2f087da9c801efc4d8962857e582c8bcbe8
|
52f670dc1f201a9fe75cf8a4bbf4afbf568a88db
|
refs/heads/master
|
<file_sep>import React, { useRef, useState } from 'react';
import Scene from './Scene';
import _ from 'lodash';
import style from './index.css';
const App = (props) => {
return (
<Scene/>
)
}
export default App;
<file_sep>const randBetween = (start, end) => {
let r = 0;
r = Math.floor(Math.random() * end) + start;
return r;
}
export { randBetween };
|
f1f915398db49e23c8816599a8dc8f5cc516015e
|
[
"JavaScript"
] | 2
|
JavaScript
|
flareg255/threeJs
|
66686c34405f1e16ab5058a55d5f8e09e3abacec
|
30026216a6463f85aeeb0c12d8fabd9b47a3d216
|
refs/heads/master
|
<file_sep>/*
* 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 tikape.runko.database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import tikape.runko.domain.Annos;
import tikape.runko.domain.AnnosRaakaAine;
/**
*
* @author antti
*/
public class AnnosRaakaAineDao {
private Database database;
public AnnosRaakaAineDao(Database database) {
this.database = database;
}
public List<AnnosRaakaAine> findAll() throws SQLException {
Connection connection = database.getConnection();
PreparedStatement stmt = connection.prepareStatement("SELECT * FROM AnnosRaakaAine");
ResultSet rs = stmt.executeQuery();
List<AnnosRaakaAine> annosRaakaAineet = new ArrayList<>();
while (rs.next()) {
Integer id = rs.getInt("id");
Integer annosId = rs.getInt("annos_id");
String annosNimi = rs.getString("annos_nimi");
Integer raakaAineId = rs.getInt("raaka_aine_id");
String raakaAineNimi = rs.getString("raaka_aine_nimi");
Integer jarjestys = rs.getInt("jarjestys");
String maara = rs.getString("maara");
String ohje = rs.getString("ohje");
annosRaakaAineet.add(new AnnosRaakaAine(id, annosId, annosNimi, raakaAineId, raakaAineNimi, jarjestys, maara, ohje));
}
rs.close();
stmt.close();
connection.close();
Collections.sort(annosRaakaAineet);
return annosRaakaAineet;
}
public AnnosRaakaAine saveOrUpdate(AnnosRaakaAine object) throws SQLException {
// simply support saving -- disallow saving if task with
// same name exists
AnnosRaakaAine byCombination = findByCombination(object.getAnnosId(), object.getRaakaAineId());
if (byCombination != null) {
return byCombination;
}
try (Connection conn = database.getConnection()) {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO AnnosRaakaAine (annos_id, annos_nimi, raaka_aine_id, raaka_aine_nimi, jarjestys, maara, ohje) VALUES (?, ?, ?, ?, ?, ?, ?)");
stmt.setInt(1, object.getAnnosId());
stmt.setString(2, object.getAnnosNimi());
stmt.setInt(3, object.getRaakaAineId());
stmt.setString(4, object.getRaakaAineNimi());
stmt.setInt(5, object.getJarjestys());
stmt.setString(6, object.getMaara());
stmt.setString(7, object.getOhje());
stmt.executeUpdate();
}
return findByCombination(object.getAnnosId(), object.getRaakaAineId());
}
private AnnosRaakaAine findByCombination(Integer annosId, Integer raakaAineId) throws SQLException {
try (Connection conn = database.getConnection()) {
PreparedStatement stmt = conn.prepareStatement("SELECT id, annos_id, annos_nimi, raaka_aine_id, raaka_aine_nimi, jarjestys, maara, ohje FROM AnnosRaakaAine WHERE annos_id = ? AND raaka_aine_id = ?");
stmt.setInt(1, annosId);
stmt.setInt(2, raakaAineId);
try (ResultSet result = stmt.executeQuery()) {
if (!result.next()) {
return null;
}
return createFromRow(result);
}
}
}
public List<AnnosRaakaAine> findByAnnosId(Integer annosId) throws SQLException {
List<AnnosRaakaAine> annosRaakaAineet = new ArrayList<>();
try (Connection conn = database.getConnection()) {
PreparedStatement stmt = conn.prepareStatement("SELECT id, annos_id, annos_nimi, raaka_aine_id, raaka_aine_nimi, jarjestys, maara, ohje FROM AnnosRaakaAine WHERE annos_id = ?");
stmt.setInt(1, annosId);
try (ResultSet result = stmt.executeQuery()) {
while (result.next()) {
annosRaakaAineet.add(createFromRow(result));
}
}
}
Collections.sort(annosRaakaAineet);
return annosRaakaAineet;
}
// public AnnosRaakaAine(Integer id, Integer annosId, Integer raakaAineId, Integer jarjestys, String maara, String ohje)
public AnnosRaakaAine createFromRow(ResultSet resultSet) throws SQLException {
return new AnnosRaakaAine(resultSet.getInt("id"), resultSet.getInt("annos_id"), resultSet.getString("annos_nimi"), resultSet.getInt("raaka_aine_id"), resultSet.getString("raaka_aine_nimi"), resultSet.getInt("jarjestys"), resultSet.getString("maara"), resultSet.getString("ohje"));
}
public void deleteByAnnosId(Integer key) throws SQLException {
try (Connection conn = database.getConnection()) {
PreparedStatement stmt = conn.prepareStatement("DELETE FROM AnnosRaakaAine WHERE annos_id = ?");
stmt.setInt(1, key);
stmt.executeUpdate();
}
}
public void deleteByRaakaAineId(Integer key) throws SQLException {
try (Connection conn = database.getConnection()) {
PreparedStatement stmt = conn.prepareStatement("DELETE FROM AnnosRaakaAine WHERE raaka_aine_id = ?");
stmt.setInt(1, key);
stmt.executeUpdate();
}
}
}
<file_sep>package tikape.runko;
import java.util.HashMap;
import java.util.List;
import spark.ModelAndView;
import static spark.Spark.*;
import spark.template.thymeleaf.ThymeleafTemplateEngine;
import tikape.runko.database.AnnosDao;
import tikape.runko.database.AnnosRaakaAineDao;
import tikape.runko.database.Database;
import tikape.runko.database.OpiskelijaDao;
import tikape.runko.database.RaakaAineDao;
import tikape.runko.domain.Annos;
import tikape.runko.domain.AnnosRaakaAine;
import tikape.runko.domain.RaakaAine;
public class Main {
public static void main(String[] args) throws Exception {
Database database = new Database("jdbc:sqlite:reseptit.db");
database.init();
RaakaAineDao raakaAineet = new RaakaAineDao(database);
AnnosDao annokset = new AnnosDao(database);
AnnosRaakaAineDao annosRaakaAineet = new AnnosRaakaAineDao(database);
get("/", (req, res) -> {
HashMap map = new HashMap<>();
map.put("annokset", annokset.findAll());
return new ModelAndView(map, "index");
}, new ThymeleafTemplateEngine());
post("/", (req, res) -> {
Integer annosId = Integer.parseInt(req.queryParams(":id"));
annokset.delete(annosId);
// Delete all annosRaakaAineet where this raakaAine is
annosRaakaAineet.deleteByAnnosId(annosId);
res.redirect("/");
return "";
});
get("/annokset", (req, res) -> {
HashMap map = new HashMap<>();
map.put("annokset", annokset.findAll());
map.put("raakaAineet", raakaAineet.findAll());
return new ModelAndView(map, "annokset");
}, new ThymeleafTemplateEngine());
post("/annokset", (req, res) -> {
Annos annos = new Annos(-1, req.queryParams("name"));
annokset.saveOrUpdate(annos);
res.redirect("/annokset");
return "";
});
get("/annokset/:id", (req, res) -> {
HashMap map = new HashMap<>();
map.put("annos", annokset.findOne(Integer.parseInt(req.params(":id"))));
// etsi kaikki kaikki annokseen kuuluvat raaka-aineet ja palauta ne oikeassa järjestyksessä
List<AnnosRaakaAine> annoksenAnnosRaakaAineet = annosRaakaAineet.findByAnnosId(Integer.parseInt(req.params(":id")));
map.put("annosRaakaAineet", annoksenAnnosRaakaAineet);
List<RaakaAine> annoksenRaakaAineet = raakaAineet.getRaakaAineet(annoksenAnnosRaakaAineet);
map.put("raakaAineet", annoksenRaakaAineet);
return new ModelAndView(map, "annos");
}, new ThymeleafTemplateEngine());
post("/annokset/:id", (req, res) -> {
Integer annosId = Integer.parseInt(req.params(":id"));
annokset.delete(annosId);
// Delete all annosRaakaAineet where this raakaAine is
annosRaakaAineet.deleteByAnnosId(annosId);
res.redirect("/annokset");
return "";
});
post("/annosraaka-aineet", (req, res) -> {
Integer annosId = Integer.parseInt(req.queryParams("annosId"));
String annosNimi = annokset.findOne(annosId).getNimi();
Integer raakaAineId = Integer.parseInt(req.queryParams("raakaAineId"));
String raakaAineNimi = raakaAineet.findOne(raakaAineId).getNimi();
Integer jarjestys = Integer.parseInt(req.queryParams("jarjestys"));
String maara = (req.queryParams("maara"));
String ohje = (req.queryParams("ohje"));
AnnosRaakaAine ar = new AnnosRaakaAine(-1, annosId, annosNimi, raakaAineId, raakaAineNimi, jarjestys, maara, ohje);
annosRaakaAineet.saveOrUpdate(ar);
res.redirect("/annokset");
return "";
});
/*
// polkuun määriteltävä parametri merkitään kaksoispisteellä ja
// parametrin nimellä. Parametrin arvoon pääsee käsiksi kutsulla
// req.params
Spark.post("/tasks/:id", (req, res) -> {
Integer taskId = Integer.parseInt(req.params(":id"));
Integer userId = Integer.parseInt(req.queryParams("userId"));
TaskAssignment ta = new TaskAssignment(-1, taskId, userId, Boolean.FALSE);
taskAssignments.saveOrUpdate(ta);
res.redirect("/tasks");
return "";
});
*/
get("/raaka-aineet", (req, res) -> {
HashMap map = new HashMap<>();
map.put("raakaAineet", raakaAineet.findAll());
return new ModelAndView(map, "raaka-aineet");
}, new ThymeleafTemplateEngine());
post("/raaka-aineet", (req, res) -> {
RaakaAine raakaAine = new RaakaAine(-1, req.queryParams("raakaAine"));
raakaAineet.saveOrUpdate(raakaAine);
res.redirect("/raaka-aineet");
return "";
});
post("/raaka-aineet/:id", (req, res) -> {
Integer raakaAineId = Integer.parseInt(req.params(":id"));
raakaAineet.delete(raakaAineId);
// Delete all annosRaakaAineet where this raakaAine is
annosRaakaAineet.deleteByRaakaAineId(raakaAineId);
res.redirect("/raaka-aineet");
return "";
});
}
}
|
d2445e12b9b89d33ea62269812c418e353878bd6
|
[
"Java"
] | 2
|
Java
|
anttirastas/tikape-runko
|
c0a4cf43a26394d1b33f287cab4abfd04268b166
|
ff8ad57fbc524fc6a210e2fd5a84b9d64769a27b
|
refs/heads/master
|
<repo_name>metalmine/PokemonLegacy<file_sep>/Test1.cs
/*
* Created by SharpDevelop.
* User: Peter
* Date: 15/06/2012
* Time: 2:15 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace Pokemon_Legacy
{
/// <summary>
/// Description of Test1.
/// </summary>
public class Test1
{
public int CritTest()
{
HeldItem CritDmg= new HeldItem();
int damage= CritDmg.CritCalc(true,true,true,50);
Console.WriteLine(damage);
return 0;
}
}
}
<file_sep>/Action.cs
/*
* Created by SharpDevelop.
* User: Peter
* Date: 15/06/2012
* Time: 10:53 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace Pokemon_Legacy
{
/// <summary>
/// Description of Action.
/// </summary>
public class Actions
{
public bool Action()
{
return true;
}
}
}
<file_sep>/map.cs
/*
* Created by SharpDevelop.
* User: Peter
* Date: 13/06/2012
* Time: 2:19 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
namespace Pokemon_Legacy
{
/// <summary>
/// Description of map.
/// </summary>
public class map
{
public string PokeRegion()
{
List<string> Region=new List<string>();
Console.WriteLine("\nTotalRegion:{5}",Region.Capacity);
Region.Add("Kanto");
Region.Add("Orange Islands");
Region.Add("Johto");
Region.Add("Hoen");
Region.Add("Sinoh");
Region.Add("Unova");
return Region[1];
}
}
}
<file_sep>/Program.cs
/*
* Created by Metalmine.
* User: Peter
* Date: 13/06/2012
* Time: 2:19 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace Pokemon_Legacy
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Welcome to the world of Pokemon");
Console.WriteLine("");
Test1 crittest = new Test1();
HeldItem CritDmg= new HeldItem();
for(int i=0;i<100;i++){
int damage= CritDmg.CritCalc(false,false,false,50);
Console.WriteLine(damage);
};
Console.WriteLine("Press any key to continue . . . ");
Console.ReadKey(true);
string myChoice;
Program om= new Program();
do
{
myChoice=om.getChoice();
switch(myChoice)
{
case "K":
case "k":
Console.WriteLine("You have chosen the Kanto region");
break;
case "O":
case "o":
Console.WriteLine("You have chosen the Orange Islands");
break;
case "J":
case "j":
Console.WriteLine("You have chosen the Johto region");
break;
case "H":
case "h":
Console.WriteLine("You have chosen the Hoenn region");
break;
case "S":
case "s":
Console.WriteLine("You have chosen the Sinoh region");
break;
case "U":
case "u":
Console.WriteLine("You have chosen the Unova region");
break;
case "R":
case "r":
Console.WriteLine("Return");
break;
default:
Console.WriteLine("{0} is not a valid choice", myChoice);
break;
}
Console.WriteLine();
Console.Write("press Enter key to continue...");
Console.ReadLine();
Console.WriteLine();
}while (myChoice != "Q" && myChoice != "q"); // Keep going until the user wants to quit
}
string getChoice()
{
string myChoice;
// Print A Menu
Console.WriteLine("Please Select a Region to Start In:\n");
Console.WriteLine("K - Kanto");
Console.WriteLine("O - Orange Islands");
Console.WriteLine("J - Johto");
Console.WriteLine("H - Hoenn");
Console.WriteLine("S - Sinoh");
Console.WriteLine("U - Unova");
Console.WriteLine("R - Main Menu\n");
Console.Write("Choice (K,O,J,H,S,U,R): ");
// Retrieve the user's choice
myChoice = Console.ReadLine();
Console.WriteLine();
return myChoice;
}
}
}<file_sep>/BattleMech.cs
/*
* Created by SharpDevelop.
* User: Peter
* Date: 13/06/2012
* Time: 3:32 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace Pokemon_Legacy
{
//<summary>
/// Description of BattleMech.
///</summary>
public class DmgCalc
{
public int HitDmg(int trueDmg, int def, int acc)
{
Random Rand=new Random();
int i = Rand.Next() % 100;
int NetDmg = trueDmg-def;
if(NetDmg<=0)
NetDmg=1;
if(i>acc)
{
NetDmg=0;
Console.Write("The attack missed...");
}
return NetDmg;
}
}
public class HeldItem
{
public int CritCalc(bool item,bool skill, bool UsedItem,int dmg)
{
Random random = new Random();
double CritPerc = 6.25;
if(item==true)
CritPerc=12.5;
else if(skill==true)
CritPerc=12.5;
else if(UsedItem==true)
CritPerc=12.5;
else if((item==true & skill== true) || (item==true & UsedItem == true) || (skill==true & UsedItem==true))
CritPerc=25;
else if(item==true & skill == true & UsedItem==true)
CritPerc=33.3;
int i= random.Next(0, 100);
if(i<CritPerc)
dmg=2*dmg;
return dmg;
}
}
}
|
3870f16c5a9bafc1730a3374f94ecb78714fe98d
|
[
"C#"
] | 5
|
C#
|
metalmine/PokemonLegacy
|
7d1cf4c5aca1a7a56bc18d21ca0ae0af24111a9a
|
9bb7ed1855017b2475a19dd607e9d75e96dd9b2a
|
refs/heads/master
|
<repo_name>rubictron/pos<file_sep>/src/lk/rubictron/posfinal/service/custom/LoginServise.java
/*
* 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 lk.rubictron.posfinal.service.custom;
import lk.rubictron.posfinal.service.SuperService;
import lk.rubictron.posfinal.dto.LoginDto;
/**
*
* @author rubictron
*/
public interface LoginServise extends SuperService<LoginDto, String>{
public LoginDto CheckUser(LoginDto t) throws Exception;
}
<file_sep>/src/lk/rubictron/posfinal/bussiness/custom/impl/CustomerBussinessImpl.java
/*
* 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 lk.rubictron.posfinal.bussiness.custom.impl;
import java.util.ArrayList;
import lk.rubictron.posfinal.bussiness.custom.CustomerBussiness;
import lk.rubictron.posfinal.dao.DAOFactory;
import lk.rubictron.posfinal.dao.custom.CustomerDAO;
import lk.rubictron.posfinal.dto.CustomerDto;
/**
*
* @author rubictron
*/
public class CustomerBussinessImpl implements CustomerBussiness {
private CustomerDAO customerDAO;
public CustomerBussinessImpl() {
customerDAO = (CustomerDAO) DAOFactory.getDAOFactory(DAOFactory.FactoryType.MYSQL).getDAO(DAOFactory.DAOType.CUSTOMER);
}
@Override
public boolean add(CustomerDto t) throws Exception {
customerDAO.setConnection(DAOFactory.getDAOFactory(DAOFactory.FactoryType.MYSQL).getConnection());
return customerDAO.add(t);
}
@Override
public boolean update(CustomerDto t) throws Exception {
customerDAO.setConnection(DAOFactory.getDAOFactory(DAOFactory.FactoryType.MYSQL).getConnection());
return customerDAO.update(t);
}
@Override
public boolean delete(String id) throws Exception {
customerDAO.setConnection(DAOFactory.getDAOFactory(DAOFactory.FactoryType.MYSQL).getConnection());
return customerDAO.delete(id);
}
@Override
public ArrayList<CustomerDto> serch(String id) throws Exception {
customerDAO.setConnection(DAOFactory.getDAOFactory(DAOFactory.FactoryType.MYSQL).getConnection());
return customerDAO.search(id);
}
@Override
public ArrayList<CustomerDto> getAll() throws Exception {
customerDAO.setConnection(DAOFactory.getDAOFactory(DAOFactory.FactoryType.MYSQL).getConnection());
return customerDAO.getAll();
}
@Override
public CustomerDto getByID(String id) throws Exception {
customerDAO.setConnection(DAOFactory.getDAOFactory(DAOFactory.FactoryType.MYSQL).getConnection());
return customerDAO.getById(id);
}
}
<file_sep>/src/lk/rubictron/posfinal/controller/custom/AdminControler.java
/*
* 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 lk.rubictron.posfinal.controller.custom;
import java.util.ArrayList;
import lk.rubictron.posfinal.dto.OrderDto;
/**
*
* @author rubictron
*/
public interface AdminControler extends CommenControler{
public void deleteCustomer(String id) throws Exception;
public ArrayList<OrderDto> showIncome() throws Exception;
}
<file_sep>/src/lk/rubictron/posfinal/dto/CustomerDto.java
/*
* 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 lk.rubictron.posfinal.dto;
/**
*
* @author rubictron
*/
public class CustomerDto extends SuperDto{
private String customerId;
private String name;
private String contact;
private int salary;
public CustomerDto(String customerId, String name, String contact, int sallery) {
this.customerId = customerId;
this.name = name;
this.contact = contact;
this.salary = sallery;
}
/**
* @return the customerId
*/
public String getCustomerId() {
return customerId;
}
/**
* @param customerId the customerId to set
*/
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the contact
*/
public String getContact() {
return contact;
}
/**
* @param contact the contact to set
*/
public void setContact(String contact) {
this.contact = contact;
}
/**
* @return the salary
*/
public int getSalary() {
return salary;
}
/**
* @param sallery the salary to set
*/
public void setSalary(int sallery) {
this.salary = sallery;
}
}
<file_sep>/src/lk/rubictron/posfinal/dao/DAOFactory.java
/*
* 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 lk.rubictron.posfinal.dao;
import java.sql.Connection;
import lk.rubictron.posfinal.dao.mysql.DAOmySqlFactory;
/**
*
* @author rubictron
*/
public abstract class DAOFactory {
private static DAOFactory factory;
public enum FactoryType {
MYSQL, FILE
}
public enum DAOType {
CUSTOMER, ITEM, ORDER, ORDER_DETAIL, LOGIN
}
/**
*
*/
public abstract SuperDAO getDAO(DAOType type);
public abstract Connection getConnection();
public abstract TransactionScope getTransactionScope();
public static DAOFactory getDAOFactory(FactoryType type) {
switch (type) {
case MYSQL:
return DAOmySqlFactory.getInstance();
case FILE:
return null;
default:
return null;
}
}
}
<file_sep>/src/lk/rubictron/posfinal/dao/mysql/impl/ItemDaoImpl.java
/*
* 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 lk.rubictron.posfinal.dao.mysql.impl;
import lk.rubictron.posfinal.dto.ItemDto;
import lk.rubictron.posfinal.dto.SuperDto;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import lk.rubictron.posfinal.dao.custom.ItemDAO;
/**
*
* @author rubictron
*/
public class ItemDaoImpl implements ItemDAO {
private Connection connection;
@Override
public boolean add(ItemDto t) throws Exception {
String sql = "INSERT INTO item VALUES (?,?,?,?)";
PreparedStatement pstm = connection.prepareStatement(sql);
pstm.setObject(1, t.getItemId());
pstm.setObject(2, t.getName());
pstm.setObject(3, t.getQuantity());
pstm.setObject(4, t.getUnitPrice());
return pstm.executeUpdate() > 0;
}
@Override
public boolean delete(String id) throws Exception {
String sql = "DELETE FROM item WHERE itemId=?";
PreparedStatement pstm = connection.prepareStatement(sql);
pstm.setObject(1, id);
return pstm.executeUpdate() > 0;
}
@Override
public boolean update(ItemDto t) throws Exception {
String sql = "UPDATE item SET name=?, quantity=?, unitPrice=? WHERE itemId=?";
PreparedStatement pstm = connection.prepareStatement(sql);
pstm.setObject(1, t.getName());
pstm.setObject(2, t.getQuantity());
pstm.setObject(3, t.getUnitPrice());
pstm.setObject(4, t.getItemId());
return pstm.executeUpdate() > 0;
}
@Override
public ArrayList<ItemDto> getAll() throws Exception {
String sql = "SELECT * FROM item";
Statement stm = connection.createStatement();
ResultSet rst = stm.executeQuery(sql);
ArrayList<ItemDto> list = new ArrayList<>();
while (rst.next()) {
list.add(new ItemDto(
rst.getString(1),
rst.getString(2),
rst.getInt(3),
rst.getDouble(4)
));
}
return list;
}
@Override
public void setConnection(Connection connection) {
this.connection = connection;
}
@Override
public ArrayList<ItemDto> search(String id) throws Exception {
String sql = "SELECT * FROM item WHERE itemId LIKE '%" + id + "%' OR name LIKE '%" + id + "%'";
Statement stm = connection.createStatement();
ResultSet rst = stm.executeQuery(sql);
ArrayList<ItemDto> list = new ArrayList<>();
while (rst.next()) {
list.add(new ItemDto(
rst.getString(1),
rst.getString(2),
rst.getInt(3),
rst.getDouble(4)
));
}
return list;
}
@Override
public ItemDto getById(String id) throws Exception {
String sql = "SELECT * FROM item WHERE ItemId =\"" + id + "\"";
Statement stm = connection.createStatement();
ResultSet rst = stm.executeQuery(sql);
if (rst.next()) {
return (new ItemDto(rst.getString(1), rst.getString(2), rst.getInt(3), rst.getInt(4)));
} else {
return null;
}
}
}
<file_sep>/posf.sql
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 5.7.21-0ubuntu0.17.10.1 - (Ubuntu)
-- Server OS: Linux
-- HeidiSQL Version: 9.4.0.5125
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping database structure for php-pos
CREATE DATABASE IF NOT EXISTS `php-pos` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `php-pos`;
-- Dumping structure for table php-pos.customer
CREATE TABLE IF NOT EXISTS `customer` (
`customerId` int(11) NOT NULL AUTO_INCREMENT,
`customerName` varchar(50) NOT NULL,
`contactNo` varchar(50) NOT NULL,
PRIMARY KEY (`customerId`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1;
-- Dumping data for table php-pos.customer: ~3 rows (approximately)
/*!40000 ALTER TABLE `customer` DISABLE KEYS */;
REPLACE INTO `customer` (`customerId`, `customerName`, `contactNo`) VALUES
(0, 'admin', '07777123456'),
(1, 'Suranga', '0777123456'),
(17, 'Upul', '0778978758');
/*!40000 ALTER TABLE `customer` ENABLE KEYS */;
-- Dumping structure for table php-pos.item
CREATE TABLE IF NOT EXISTS `item` (
`itemId` int(11) NOT NULL AUTO_INCREMENT,
`itemName` varchar(50) NOT NULL,
`quantity` int(11) NOT NULL,
`unitPrice` double NOT NULL,
PRIMARY KEY (`itemId`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
-- Dumping data for table php-pos.item: ~2 rows (approximately)
/*!40000 ALTER TABLE `item` DISABLE KEYS */;
REPLACE INTO `item` (`itemId`, `itemName`, `quantity`, `unitPrice`) VALUES
(7, 'asasas', 9, 1),
(10, '<NAME>', 15, 250);
/*!40000 ALTER TABLE `item` ENABLE KEYS */;
-- Dumping structure for table php-pos.orderDetails
CREATE TABLE IF NOT EXISTS `orderDetails` (
`orderId` int(11) NOT NULL,
`itemId` int(11) DEFAULT NULL,
`quentity` int(11) DEFAULT NULL,
PRIMARY KEY (`orderId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table php-pos.orderDetails: ~2 rows (approximately)
/*!40000 ALTER TABLE `orderDetails` DISABLE KEYS */;
REPLACE INTO `orderDetails` (`orderId`, `itemId`, `quentity`) VALUES
(1, 4, 1),
(2, 1, 34);
/*!40000 ALTER TABLE `orderDetails` ENABLE KEYS */;
-- Dumping structure for table php-pos.orders
CREATE TABLE IF NOT EXISTS `orders` (
`orderId` int(11) NOT NULL,
`customerId` int(11) NOT NULL,
`date` varchar(20) NOT NULL,
`total` double DEFAULT NULL,
PRIMARY KEY (`orderId`),
KEY `orders_customer_customerId_fk` (`customerId`),
CONSTRAINT `orders_customer_customerId_fk` FOREIGN KEY (`customerId`) REFERENCES `customer` (`customerId`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table php-pos.orders: ~1 rows (approximately)
/*!40000 ALTER TABLE `orders` DISABLE KEYS */;
REPLACE INTO `orders` (`orderId`, `customerId`, `date`, `total`) VALUES
(1, 0, '2018-02-05', 198);
/*!40000 ALTER TABLE `orders` ENABLE KEYS */;
-- Dumping structure for table php-pos.users
CREATE TABLE IF NOT EXISTS `users` (
`username` varchar(50) NOT NULL,
`password` varchar(200) NOT NULL,
`usertype` varchar(50) NOT NULL,
`image` varchar(50) NOT NULL,
`customerId` int(11) NOT NULL DEFAULT '13',
PRIMARY KEY (`username`),
KEY `FK_users_customer` (`customerId`),
CONSTRAINT `FK_users_customer` FOREIGN KEY (`customerId`) REFERENCES `customer` (`customerId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table php-pos.users: ~2 rows (approximately)
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
REPLACE INTO `users` (`username`, `password`, `usertype`, `image`, `customerId`) VALUES
('customer', '$2y$10$0XX5v.gOx1OOmg5meNjawuU1yII86QAc0bNwioX5AharUpRpIQIN.', 'customer', 'user.png', 1),
('rubictron', '$2y$10$0XX5v.gOx1OOmg5meNjawuU1yII86QAc0bNwioX5AharUpRpIQIN.', 'admin', 'logo.jpg', 0);
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
-- Dumping database structure for posf
CREATE DATABASE IF NOT EXISTS `posf` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `posf`;
-- Dumping structure for table posf.customer
CREATE TABLE IF NOT EXISTS `customer` (
`customerId` varchar(5) NOT NULL,
`name` varchar(20) NOT NULL,
`contact` varchar(10) NOT NULL,
`salary` int(11) DEFAULT NULL,
PRIMARY KEY (`customerId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table posf.customer: ~5 rows (approximately)
/*!40000 ALTER TABLE `customer` DISABLE KEYS */;
REPLACE INTO `customer` (`customerId`, `name`, `contact`, `salary`) VALUES
('C0001', 'wersdfghj', '7412', 500),
('C0003', 'asdfg', 'asdfgh', NULL),
('C0004', 'sdfg', 'dfghj', NULL),
('C0005', 'qwerty', 'dfghjml', NULL),
('C0077', 'asd', 'asd', 12);
/*!40000 ALTER TABLE `customer` ENABLE KEYS */;
-- Dumping structure for table posf.item
CREATE TABLE IF NOT EXISTS `item` (
`itemId` varchar(5) NOT NULL,
`name` varchar(15) NOT NULL,
`quantity` int(11) DEFAULT NULL,
`unitPrice` double DEFAULT NULL,
PRIMARY KEY (`itemId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table posf.item: ~5 rows (approximately)
/*!40000 ALTER TABLE `item` DISABLE KEYS */;
REPLACE INTO `item` (`itemId`, `name`, `quantity`, `unitPrice`) VALUES
('I0001', 'Soap', 806, 12),
('I0002', 'Soap', 126, 12),
('I0006', 'aaaaaa', 70, 8),
('I0007', 'sssss', 300, 1),
('I0009', 'Soap', 50, 127);
/*!40000 ALTER TABLE `item` ENABLE KEYS */;
-- Dumping structure for table posf.login
CREATE TABLE IF NOT EXISTS `login` (
`userName` varchar(15) DEFAULT NULL,
`password` varchar(15) DEFAULT NULL,
`accessLevel` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table posf.login: ~2 rows (approximately)
/*!40000 ALTER TABLE `login` DISABLE KEYS */;
REPLACE INTO `login` (`userName`, `password`, `accessLevel`) VALUES
('admin', 'admin', 1),
('user', '<PASSWORD>', 2);
/*!40000 ALTER TABLE `login` ENABLE KEYS */;
-- Dumping structure for table posf.orderDetails
CREATE TABLE IF NOT EXISTS `orderDetails` (
`orderId` varchar(5) NOT NULL,
`itemId` varchar(5) NOT NULL,
`quentity` int(5) NOT NULL,
PRIMARY KEY (`orderId`,`itemId`),
KEY `fk_item_d` (`itemId`),
CONSTRAINT `fk_item_d` FOREIGN KEY (`itemId`) REFERENCES `item` (`itemId`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_order_d` FOREIGN KEY (`orderId`) REFERENCES `orders` (`orderId`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table posf.orderDetails: ~17 rows (approximately)
/*!40000 ALTER TABLE `orderDetails` DISABLE KEYS */;
REPLACE INTO `orderDetails` (`orderId`, `itemId`, `quentity`) VALUES
('ODR44', 'I0002', 1),
('ODR56', 'I0001', 1),
('ODR56', 'I0002', 3),
('ODR88', 'I0001', 1),
('ODR89', 'I0001', 12),
('ODR89', 'I0002', 32),
('ODR90', 'I0001', 12),
('ODR90', 'I0002', 32),
('ODR91', 'I0001', 12),
('ODR91', 'I0002', 1),
('ODR92', 'I0001', 4),
('ODR93', 'I0001', 1),
('ODR94', 'I0001', 1),
('ODR95', 'I0001', 1),
('ODR96', 'I0001', 1),
('ODR96', 'I0006', 2),
('ODR96', 'I0007', 5);
/*!40000 ALTER TABLE `orderDetails` ENABLE KEYS */;
-- Dumping structure for table posf.orders
CREATE TABLE IF NOT EXISTS `orders` (
`orderId` varchar(5) NOT NULL,
`date` date NOT NULL,
`customerId` varchar(5) NOT NULL,
`totalPrice` double DEFAULT NULL,
PRIMARY KEY (`orderId`),
KEY `fk_order_cus` (`customerId`),
CONSTRAINT `fk_order_cus` FOREIGN KEY (`customerId`) REFERENCES `customer` (`customerId`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table posf.orders: ~9 rows (approximately)
/*!40000 ALTER TABLE `orders` DISABLE KEYS */;
REPLACE INTO `orders` (`orderId`, `date`, `customerId`, `totalPrice`) VALUES
('ODR44', '2018-01-02', 'C0001', 12),
('ODR56', '2018-01-31', 'C0001', 48),
('ODR88', '2018-01-18', 'C0001', 12),
('ODR89', '2018-01-01', 'C0001', 528),
('ODR90', '2018-01-01', 'C0001', 528),
('ODR91', '2018-01-01', 'C0001', 156),
('ODR92', '2018-01-02', 'C0001', 48),
('ODR93', '2018-02-05', 'C0001', 12),
('ODR94', '2018-02-06', 'C0001', 12),
('ODR95', '2018-02-01', 'C0001', 12),
('ODR96', '2018-02-07', 'C0001', 33);
/*!40000 ALTER TABLE `orders` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
<file_sep>/src/lk/rubictron/posfinal/dao/mysql/impl/OrderDaoImpl.java
/*
* 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 lk.rubictron.posfinal.dao.mysql.impl;
import lk.rubictron.posfinal.dto.OrderDto;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import lk.rubictron.posfinal.dao.custom.OrderDAO;
/**
*
* @author rubictron
*/
public class OrderDaoImpl implements OrderDAO {
private Connection connection;
@Override
public boolean add(OrderDto t) throws Exception {
String sql = "INSERT INTO orders VALUES (?,?,?,?)";
PreparedStatement pstm = connection.prepareStatement(sql);
pstm.setObject(1, t.getOrderId());
pstm.setObject(2, parseDate(t.getDate()));
pstm.setObject(3, t.getCustomerId());
pstm.setObject(4, t.getTotalPrice());
return pstm.executeUpdate() > 0;
}
@Override
public boolean delete(String id) throws Exception {
String sql = "DELETE FROM order WHERE orderId=?";
PreparedStatement pstm = connection.prepareStatement(sql);
pstm.setObject(1, id);
return pstm.executeUpdate() > 0;
}
@Override
public boolean update(OrderDto t) throws Exception {
String sql = "UPDATE orders SET date=?, customerId=?, totalPrice=? WHERE customerId=?";
PreparedStatement pstm = connection.prepareStatement(sql);
pstm.setObject(1, parseDate(t.getDate()));
pstm.setObject(2, t.getCustomerId());
pstm.setObject(3, t.getTotalPrice());
pstm.setObject(4, t.getOrderId());
return pstm.executeUpdate() > 0;
}
@Override
public ArrayList<OrderDto> getAll() throws Exception {
String sql = "SELECT * FROM orders";
Statement stm = connection.createStatement();
ResultSet rst = stm.executeQuery(sql);
ArrayList<OrderDto> list = new ArrayList<>();
while (rst.next()) {
list.add(new OrderDto(rst.getString(1), rst.getString(2), rst.getString(3), rst.getInt(4)));
}
return list;
}
@Override
public void setConnection(Connection connection) {
this.connection = connection;
}
@Override
public ArrayList<OrderDto> search(String id) throws Exception {
String sql = "SELECT * FROM orders WHERE orderId LIKE '%" + id + "%'";
Statement stm = connection.createStatement();
ResultSet rst = stm.executeQuery(sql);
ArrayList<OrderDto> list = new ArrayList<>();
while (rst.next()) {
list.add(new OrderDto(rst.getString(1), rst.getString(2), rst.getString(3), rst.getInt(4)));
}
return list;
}
private Date parseDate(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
return sdf.parse(date);
} catch (ParseException ex) {
Logger.getLogger(OrderDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
@Override
public OrderDto getById(String id) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getLastId() throws Exception {
String sql = "select max(orderId) from orders";
Statement stm = connection.createStatement();
ResultSet rst = stm.executeQuery(sql);
String res = "0000";
while (rst.next()) {
res = rst.getString("max(orderId)");
}
return res;
}
}
<file_sep>/src/lk/rubictron/posfinal/view/controller/ItemController.java
/*
* 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 lk.rubictron.posfinal.view.controller;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import java.io.File;
import java.io.InputStream;
import java.net.URISyntaxException;
import lk.rubictron.posfinal.dto.ItemDto;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import lk.rubictron.posfinal.view.util.tablemodel.ItemTM;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import lk.rubictron.posfinal.controller.custom.CommenControler;
import lk.rubictron.posfinal.dao.ConnectionFactory;
import net.sf.jasperreports.engine.DefaultJasperReportsContext;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.util.LocalJasperReportsContext;
import net.sf.jasperreports.engine.util.SimpleFileResolver;
import net.sf.jasperreports.view.JasperViewer;
/**
* FXML Controller class
*
* @author rubictron
*/
public class ItemController implements Initializable {
@FXML
private AnchorPane root2;
@FXML
private JFXTextField textfItemId;
@FXML
private JFXTextField textfName;
@FXML
private JFXButton btnSerch;
@FXML
private JFXTextField textfQuentity;
@FXML
private JFXTextField textfUnitPrice;
@FXML
private JFXButton btnDelete;
@FXML
private JFXButton btnViewAll;
private CommenControler controler;
@FXML
private TableView<ItemTM> tableItem;
@FXML
private JFXButton btnItemReport;
public ItemController() {
controler = DashbController.getControler();
}
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
tableItem.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("itemId"));
tableItem.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("name"));
tableItem.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("quantity"));
tableItem.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
tableItem.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ItemTM>() {
@Override
public void changed(ObservableValue<? extends ItemTM> observable, ItemTM oldValue, ItemTM newValue) {
ItemTM currentRow = observable.getValue();
if (currentRow != null) {
textfItemId.setText(currentRow.getItemId());
textfName.setText(currentRow.getName());
textfQuentity.setText(String.valueOf(currentRow.getQuantity()));
textfUnitPrice.setText(String.valueOf(currentRow.getUnitPrice()));
}
}
});
abtnViewAll(new ActionEvent());
}
@FXML
private void abtnSerch(ActionEvent event) {
try {
ArrayList<ItemDto> item = controler.getSerchItems(textfItemId.getText());
ArrayList<ItemTM> alitem = new ArrayList<ItemTM>();
for (ItemDto dto : item) {
alitem.add(new ItemTM(dto.getItemId(),dto.getName(),dto.getQuantity(),dto.getUnitPrice()));
}
ObservableList<ItemTM> allcus = FXCollections.observableArrayList(alitem);
tableItem.setItems(allcus);
} catch (Exception ex) {
Logger.getLogger(ItemController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void abtnSave(ActionEvent event) {
try {
ItemDto dto = new ItemDto(
textfItemId.getText(),
textfName.getText(),
Integer.parseInt(textfQuentity.getText()),
Double.parseDouble(textfUnitPrice.getText()));
controler.saveItem(dto);
abtnSerch(event);
} catch (Exception ex) {
Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void abtnDelete(ActionEvent event) {
try {
String id = tableItem.getSelectionModel().getSelectedItem().getItemId();
controler.deleteItem(id);
abtnViewAll(event);
} catch (Exception ex) {
Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void abtnViewAll(ActionEvent event) {
try {
ArrayList<ItemDto> item = controler.getAllItems();
ArrayList<ItemTM> alitem = new ArrayList<ItemTM>();
for (ItemDto dto : item) {
alitem.add(new ItemTM(dto.getItemId(),dto.getName(),dto.getQuantity(),dto.getUnitPrice()));
}
ObservableList<ItemTM> allcus = FXCollections.observableArrayList(alitem);
tableItem.setItems(allcus);
} catch (Exception ex) {
Logger.getLogger(ItemController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
private void abtnItemReport(ActionEvent event) {
try {
JasperReport compiledReport = (JasperReport) JRLoader.loadObject(ItemController.class.getResourceAsStream("/lk/rubictron/posfinal/view/report/item.jasper"));
HashMap<String, Object> reportParams = new HashMap<>();
JasperPrint filledReport = JasperFillManager.fillReport(compiledReport, reportParams, ConnectionFactory.getInstance().getConnection());
JasperViewer.viewReport(filledReport);
} catch (JRException ex) {
Logger.getLogger(ItemController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<file_sep>/src/lk/rubictron/posfinal/service/ServiceFactory.java
/*
* 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 lk.rubictron.posfinal.service;
import lk.rubictron.posfinal.service.custom.impl.CustomerServiceImpl;
import lk.rubictron.posfinal.service.custom.impl.ItemServiceImpl;
import lk.rubictron.posfinal.service.custom.impl.LoginServiceImpl;
import lk.rubictron.posfinal.service.custom.impl.OrderDetailsServiceImpl;
import lk.rubictron.posfinal.service.custom.impl.OrderServiceImpl;
/**
*
* @author rubictron
*/
public class ServiceFactory {
private static ServiceFactory factory;
private ItemServiceImpl item;
private CustomerServiceImpl customer;
private OrderDetailsServiceImpl orderDetails;
private OrderServiceImpl order;
private LoginServiceImpl log;
public enum ServiceType {
ITEM, CUSTOMER, ORDER, ORDERDETAILS, LOGIN
}
private ServiceFactory() {
item = new ItemServiceImpl();
customer = new CustomerServiceImpl();
order = new OrderServiceImpl();
orderDetails = new OrderDetailsServiceImpl();
log = new LoginServiceImpl();
}
public static ServiceFactory getInstance() {
if (factory == null) {
factory = new ServiceFactory();
}
return factory;
}
public SuperService getService(ServiceType type) {
switch (type) {
case ITEM:
return item;
case CUSTOMER:
return customer;
case ORDER:
return order;
case ORDERDETAILS:
return orderDetails;
case LOGIN:
return log;
default:
return null;
}
}
}
<file_sep>/src/lk/rubictron/posfinal/controller/custom/impl/LoginControlerImpl.java
/*
* 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 lk.rubictron.posfinal.controller.custom.impl;
import lk.rubictron.posfinal.controller.custom.LoginControler;
import lk.rubictron.posfinal.dao.DAOFactory;
import lk.rubictron.posfinal.dao.mysql.impl.LoginDaoImpl;
import lk.rubictron.posfinal.dto.LoginDto;
import lk.rubictron.posfinal.service.ServiceFactory;
import lk.rubictron.posfinal.service.custom.impl.LoginServiceImpl;
/**
*
* @author rubictron
*/
public class LoginControlerImpl implements LoginControler{
private static LoginDto user;
@Override
public LoginDto CheckUser(LoginDto dto) throws Exception {
LoginServiceImpl service= (LoginServiceImpl) ServiceFactory.getInstance().getService(ServiceFactory.ServiceType.LOGIN);
/* LoginDaoImpl dao= (LoginDaoImpl) DAOFactory.getDAOFactory(DAOFactory.FactoryType.MYSQL).getDAO(DAOFactory.DAOType.LOGIN);
user=dao.checklog(dto);*/
user=service.CheckUser(dto);
return user;
}
/**
*
* @return
*/
public static LoginDto getUser(){
return LoginControlerImpl.user;
};
@Override
public boolean addUser() throws Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
<file_sep>/src/lk/rubictron/posfinal/controller/ControlerFactory.java
/*
* 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 lk.rubictron.posfinal.controller;
import lk.rubictron.posfinal.controller.custom.AdminControler;
import lk.rubictron.posfinal.controller.custom.impl.AdminControlerImpl;
import lk.rubictron.posfinal.controller.custom.ReceptionControler;
import lk.rubictron.posfinal.controller.custom.impl.LoginControlerImpl;
import lk.rubictron.posfinal.controller.custom.impl.ReceptionControlerImpl;
/**
*
* @author rubictron
*/
public class ControlerFactory {
private static ControlerFactory factory;
private AdminControler admin;
private ReceptionControler reception;
private LoginControlerImpl login;
public enum ControlerType{
Admin,Reception,LOGIN
}
private ControlerFactory(){
admin=new AdminControlerImpl();
reception=new ReceptionControlerImpl();
login =new LoginControlerImpl();
}
public static ControlerFactory getInstance(){
if(factory==null) factory=new ControlerFactory();
return factory;
}
public SuperControler getController(ControlerType type){
switch(type){
case Admin:return admin;
case Reception: return reception;
case LOGIN: return login;
default:return null;
}
}
}
<file_sep>/src/lk/rubictron/posfinal/controller/custom/LoginControler.java
/*
* 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 lk.rubictron.posfinal.controller.custom;
import lk.rubictron.posfinal.controller.SuperControler;
import lk.rubictron.posfinal.dto.LoginDto;
/**
*
* @author rubictron
*/
public interface LoginControler extends SuperControler{
LoginDto CheckUser(LoginDto dto) throws Exception;
boolean addUser() throws Exception;
}
<file_sep>/src/lk/rubictron/posfinal/controller/custom/CommenControler.java
/*
* 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 lk.rubictron.posfinal.controller.custom;
import lk.rubictron.posfinal.controller.SuperControler;
import lk.rubictron.posfinal.dto.CustomerDto;
import lk.rubictron.posfinal.dto.ItemDto;
import lk.rubictron.posfinal.dto.OrderDetailsDto;
import lk.rubictron.posfinal.dto.OrderDto;
import java.util.ArrayList;
/**
*
* @author rubictron
*/
public interface CommenControler extends SuperControler {
boolean saveCustomer(CustomerDto dto) throws Exception;
boolean saveItem(ItemDto dto) throws Exception;
ArrayList<CustomerDto> getAllCustomers() throws Exception;
ArrayList<ItemDto> getAllItems() throws Exception;
ArrayList<CustomerDto> getSerchCustomers(String id) throws Exception;
ArrayList<ItemDto> getSerchItems(String id) throws Exception;
public void deleteItem(String id) throws Exception;
CustomerDto getCustomerByID(String Id) throws Exception;
ItemDto getItemByID(String Id) throws Exception;
String getnewOrderId() throws Exception;
boolean placeOrder(OrderDto Order, ArrayList<OrderDetailsDto> OrderDetailsArray) throws Exception;
}
<file_sep>/src/lk/rubictron/posfinal/dao/custom/LoginDAO.java
/*
* 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 lk.rubictron.posfinal.dao.custom;
import lk.rubictron.posfinal.dto.LoginDto;
import lk.rubictron.posfinal.dto.SuperDto;
import lk.rubictron.posfinal.dao.SuperDAO;
/**
*
* @author rubictron
*/
public interface LoginDAO extends SuperDAO<SuperDto, Object> {
LoginDto checklog(LoginDto dto) throws Exception;
}
|
f60869824b8af5f39366766fa1a62f9b2fc2fd4d
|
[
"Java",
"SQL"
] | 15
|
Java
|
rubictron/pos
|
d018d498687daa58e1f5c8cbf78204642e4a5bc8
|
8aff4237babf9ced5e24ddd58b8c832f67ff5efc
|
refs/heads/master
|
<repo_name>mtaung/tonic<file_sep>/util/maintenance.py
import imghdr
import aiohttp
import asyncio
import shlex
from discord.ext import commands
from storage.db import User, Guild
from .checks import require_owner_access, no_private_message, require_server_permissions
from .prefix import prefix_changed
class Maintenance:
def __init__(self, bot):
self.bot = bot
self.db = bot.database
@commands.command(pass_context=True)
async def access(self, ctx):
"""Tells you your access level."""
user = self.db.get(User, id=ctx.message.author.id)
level = 'user'
if(user.access > 9000):
level = 'owner'
await ctx.bot.send_message(ctx.message.channel, 'You have {} level access with me.'.format(level))
@commands.command(pass_context=True)
@commands.check(require_owner_access)
async def avatar(self, ctx, url):
"""Changes my avatar from a URL."""
if(not url):
return
msg = await ctx.bot.send_message(ctx.message.channel, 'Downloading new avatar...')
async with aiohttp.ClientSession() as session:
try:
async with session.get(url) as response:
if(response.status == 200):
avi = await response.read()
if(imghdr.what('', h = avi)):
await ctx.bot.edit_profile(avatar = avi)
await ctx.bot.edit_message(msg, 'Avatar changed.')
else:
await ctx.bot.edit_message(msg, 'I\'m sorry, that\'s not a valid image')
else:
await ctx.bot.edit_message(msg, 'I\'m sorry, download failed: {}'.format(response.reason))
except ValueError:
await ctx.bot.edit_message(msg, "I\'m sorry, the URL was invalid.")
@commands.command(pass_context=True)
@commands.check(require_owner_access)
async def dev(self, ctx, command, branch_name=None):
"""Developer commands.
branch - find out which branch I'm on
evolve - get updates from current branch and restart
evolve <branch_name> - change to a different branch, update and restart"""
if command == 'branch':
shell = await asyncio.create_subprocess_shell("git rev-parse --abbrev-ref HEAD", stdout=asyncio.subprocess.PIPE)
stdout, stderr = await shell.communicate()
bname = stdout.decode().strip()
await ctx.bot.send_message(ctx.message.channel, "Current branch: {}".format(bname))
elif command == 'evolve':
msg = "Grabbing the latest updates."
if branch_name:
shell = await asyncio.create_subprocess_shell("git fetch")
await shell.wait()
shell = await asyncio.create_subprocess_shell("git checkout {}".format(shlex.quote(branch_name)))
code = await shell.wait()
if code != 0:
await ctx.bot.send_message(ctx.message.channel, "Couldn't change to branch: {}".format(branch_name))
return
else:
msg = "Changed to branch: {}. {}".format(branch_name, msg)
await ctx.bot.send_message(ctx.message.channel, msg)
await ctx.bot.close()
else:
raise commands.MissingRequiredArgument()
@commands.command(pass_context=True)
@commands.check(no_private_message)
@commands.check(require_server_permissions)
async def prefix(self, ctx, string=None):
"""Changes my command prefix string on this server."""
guild_id = ctx.message.server.id
guild = self.db.get(Guild, id=guild_id)
guild.prefix = string
prefix_changed(guild_id)
self.db.commit()
if(guild.prefix):
await ctx.bot.send_message(ctx.message.channel, f"Command prefix changed to {guild.prefix}")
else:
await ctx.bot.send_message(ctx.message.channel, f"Command prefix disabled. I will still respond to {ctx.bot.user.mention}")
|
faea875698557fc99ad7f7dbe2fe0fff718cdc16
|
[
"Python"
] | 1
|
Python
|
mtaung/tonic
|
6183e2dd5bad11bf2943896b0a63c2603256da4a
|
16552f13f679d9280c618e3fd3759b6695178374
|
refs/heads/master
|
<file_sep>---
title: TC39 globalThis
---
## TC39 `globalThis`
> 草案地址: [Ref](<https://github.com/tc39/proposal-global#html-and-the-windowproxy>)
### 故事的开始
在9102年的ECMAScript(文后戏称JS)世界里,JS已经不是当年那跑在浏览器里的脚本语言了。我们一拍脑子能想到的运行环境就有:
- 浏览器
- Node.js
- 根据草案实现的各个`Standalone`版本(可见此工具的[README](https://github.com/GoogleChromeLabs/jsvu)
为了JS可以在不同的**运行环境**下都访问到自己想要的那个全局的`this`, 于是就有了这个草案,也有了我读了某片博客之后的这篇记录。
### The Polyfill
> 以下polyfill的思路来自Mathiasbynens的一片[博客](https://mathiasbynens.be/notes/globalthis#naive-polyfill)
首先,我们分析一下目前JS的几个运行环境;
浏览器中我们有`window`对象和`frames`对象:
```java
globalThis === window; // true
globalThis === frames; // true
```
虽然在`web wrokers`中window为`undefined`, 但是浏览器扩展中也实现了一个叫做`self`的对象:
```javascript
globalThis === self; // true
```
在 Node.js 中也有很熟悉的`global`对象:
```javascript
globalThis === global; // true
```
就如同我们文章开头提到的, 还有一些独立的JS实现, 就没有以上这些宿主环境的全局对象。这种情况可以直接去访问全局的`this`:
```javascript
globalThis === this; // true
```
而且,在sloppy模式(即没有开启严格模式)下,函数的this总是指向全局的this,所以就算我们不能像上一个例子一样在全局环境下直接访问`this`, 也可以通过一个简单的匿名函数去获得:
```javascript
globalThis === (function () {
return this;
}); // true
```
然鹅,在大部分JS模块标准实现中,最顶层的函数的this一般是`undefined`,而且函数在严格模式下的`this`也是`undefined`, 所以上面这个思路也不行。
到这个地方,Mathias给了一个特别trick的方法,在严格模式下生成非严格模式的函数:
使用`Function`构造器:
```javascript
globalThis === Function('return this')(); // true
```
当然使用`eval`也一样:
```javascript
globalThis === (0, eval)('this');
```
在现代浏览器中,`Funciton`构造器和`eval`通常被[Content Security Policy(CSP)`](http://www.ruanyifeng.com/blog/2016/09/csp.html)限制使用。虽然一般的网站可以选择是否遵循这个准则,但在Chrome插件中则是强制遵循。简而言之,这个polyfill并不能通过这种trick的方法来实现。
### A Naive Polyfill
根据上文的分析,我们能够得到一个不是很健全的Polyfill实现:
```javascript
// Ref: https://mathiasbynens.be/notes/globalthis#naive-polyfill
// A naive globalThis shim. Don’t use this!
const getGlobal = () => {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
if (typeof this !== 'undefined') return this;
throw new Error('Unable to locate global object');
};
// Note: `var` is used instead of `const` to ensure `globalThis`
// becomes a global variable (as opposed to a variable in the
// top-level lexical scope) when running in the global scope.
var globalThis = getGlobal();
```
如前文所说,不支持严格模式,在某些非浏览器环境下的模块化组件函数哪无法使用。
### A Robust Polyfill
那么是否有可能写一个健壮的polyfill实现呢? 在总结如下条件的情况下:
- 我们不能依赖环境实现的`globalThis`, `window`, `self`, `global` 或 `this`;
- 不能使用trick的`Function`构造器和`eval`;
- 但是你可以仔细考虑一下JS本身所具备的功能。
下面有这么一个不算漂亮的实现方案;但是在这之前,让我们考虑一些问题:
我们如何在不考虑`globalThis`从哪里来的前提下,获取`globalThis`本身呢? 如果我们可以添任意一个函数在`globalThis`上,并且我们可以把它当作`globalThis`的方法来执行,同时它放回的就是`this`:
```javascript
globalThis.foo = function () {
return this;
}
var globalThisPolyfilled = globalThis.foo();
```
问题就来了,我们到底如何在不依赖`globalThis`或者任何环境实现的宿主上绑定这样一个函数呢, 这个条件下我们只能得到下文这样的东西:
```javascript
function foo() {
return this;
}
var globalThisPolyfilled = foo();
```
`foo()`并不是作为某个对象的方法被执行的, 在严格模式,一些模块化的模块函数哪,`this`理所当然得是`undefined`。
然而,作为某个对象的`getters`, `setters`就不一样了:
```javascript
Object.defineProperty(globalThis, '__magic__', {
get: function() {
return this;
},
configurable: true // 后续可以删除
});
var globalThisPolyfilled = __magic__;
delete globalThis.__magic__;
```
我们给现在如果直接给`globalThis`添加一个`getter`返回`this`,这个getter会直接返回当前的`this`;但是我们根本的问题没有解决,我们还是需要依赖`GlobalThis`。如何把这个函数安装这样一个全局的`getter`并且不依赖`globalThis`呢?
我们可以把这个`getter`安装到被全局`this`继承的`Object.prototype`上:
```javascript
Object.defineProperty(Object.prototype, '__magic__', {
get: function() {
return this;
},
configurable: true
});
var globalThis = __magic__;
delete Object.prototype.__magic__;
```
**⚠️ ECMAScript Spec 并没有强制要求全局的`this`继承于`Object.prototype`,如果通过`Object.create(null)`的方式生成一个全局使用的`Object`也是可以的,而且 IE7 就是这样做的,幸运的是现代浏览器都是通过`Object.prototype`继承的**
为了避免浏览器已经实现了`globalThis`, 我们简单得调整一下:
```javascript
(function() {
if (typeof globalThis === 'object') return;
Object.defineProperty(Object.prototype, '__magic__', {
get: function() {
return this;
},
configurable: true // This makes it possible to `delete` the getter later.
});
__magic__.globalThis = __magic__; // lolwat
delete Object.prototype.__magic__;
}());
// Your code can use `globalThis` now.
console.log(globalThis);
```
Mathias在文末说到,这可能是你见过最可怕的Polyfill,因为它完全违背了流行的做法:**即不修改不属于你的对象,避免操作内置的原型对象**。
[通过`jsvu`测试这个Polyfill](https://mathiasbynens.be/notes/globalthis#testing)
<file_sep>## Bash Guide Notes 📒
> Bash Guide: http://guide.bash.academy/expansions/
>
> The Chapter: Variables and Expansions
今天也有在看Parcel和Parcel的代码,因为自己的项目用到了这个新的Bundler库,看到一个很有意思的[issue](https://github.com/parcel-bundler/parcel/issues/110#issuecomment-350259878)。里面这个shell蛮有意思的。
### 路径扩展 (Pathname Expansion)
看个例子:
```bash
$ cd ~/Downloads
$ rm -v *
removed '05 *****.ogg'
removed '07 *****.ogg'
$ls
$
```
`rm -v` 后面的`*`会匹配到`Downloads`下所有的文件,这套在bash上使用的扩展匹配符号被叫做`Glob`,下面这个表格来自[原文](http://guide.bash.academy/expansions/?=Pathname_Expansion#p1.1.0_4)。
| Glob | 含义 |
| --------------- | ---------------------------------------- |
| `*` | 匹配N个字符,N包括0 |
| `?` | 匹配0 ~ 1个字符 |
| `[characters]` | 匹配一个字符,范围来自`[...]`中的内容,类似正则表达式的`[]` |
| `[:classname:]` | 类似上一个命令. 支持一系列模式,包括: _alnum_, _alpha_, _ascii_, _blank_, _cntrl_, _digit_, _graph_, _lower_, _print_, _punct_, _space_, _upper_, _word_, _xdigit_ |
可以指令开启更多的glob匹配,具体就不列举了,大概是正则表达式常用的符号[原文](http://guide.bash.academy/expansions/?=Pathname_Expansion#p1.1.0_9)。
```bash
$ shopt -s extglob
```
### ~ 符号
`echo ~` 就知道了, 指向你的`Home`目录
### 命令子句
形式非常简单,看下面的例子,用`$(…)`来说明这是条命令子句。值得注意的是只能用在**双引号**内
```bash
$ echo "The File <hello.txt>: $(cat hello.txt)"
```
### Re-use Code
复用代码,是最基本的抽象。为了让我们从简单的命令中更进一步,必须开始思考如何 re-use 代码了。先从Bash的变量开始。
### Shell 变量
基本形式
```bash
# error
$ name = 1 # bash中的`=`左右两边是不允许出现空格的
bash: name: command not found
# right
$ name=1
$ echo $name # 通过`$`去获取变量
1 # result
```
还能用一下上面的命令子句
```bash
$ qiaqia="$(cat qiaqia.txt)" # good job
```
还能在字符串中插入变量 (即: Parameter Expansion)
```bash
$ name="<NAME>" time=23.23
$ echo "$name's current record is $times."
hali bote's current record is .
$ echo "$name's current record is ${time}s."
hali bote's current record is 23.23s.
```
### 变量扩展 Parameter Expansion
**再次留意**, `${variable}` 这个形式只能使用在**双引号**之间,接下来要比较详细得讲解一些扩展用法。
我们来看一个例子
```bash
$ name=Britta time=23.73
$ echo "$name's current record is ${time%.*} seconds and ${time#*.} hundredths."
Britta's current record is 23 seconds and 73 hundredths.
$ echo "PATH currently contains: ${PATH//:/, }"
PATH currently contains: /Users/lhunath/.bin, /usr/local/bin, /usr/bin, /bin, /usr/libexec
# From Guide Bash
```
你可能留意到了`${}`中的一些特殊用法,`%`是从后向前匹配最小满足该形式的内容并删去,而`#`类似前者,不过是从前向后匹配。而下一句命令里的`//A/B`则是匹配所有满足A形式的内容替换成B。还有一些常见的可以看Bash-Guide的[这个地方](http://guide.bash.academy/expansions/?=Parameter_Expansion#p2.2.2_5),或者是下面的一个简单总结。
```bash
# 例子
url="http://guide.bash.academy/expansions.html"
$ echo "Result: ${url#*/}" # 从开头开始,匹配满足*/的最小内容,并移除
Result: /guide.bash.academy/expansions.html
$ ...${url##*/}... # 两个##和一个#的区别在于,匹配的是满足情况的最大内容
Result: expansions.html
# ${parameter$A} 是从后向前匹配并移除, $$即最大内容
# ${parameter/A/B} 是匹配第一个满足情况A的内容替换成B
# ${parameter//A/B} 则是匹配所有满足情况的替换
# ${parameter/#A/B} 是从__开头__匹配第一个满足情况A的替换成B
# ${parameter/%A/B} 则是从__结尾__匹配
# ${#parameter} 计算参数的长度
# ${parameter:start[:length]} start是截取开始的字符位置,length为截取长度,可省略或者是负数(负数即从后向前数)
# #{parameter[^|^^|,|,,][A]} 根据形式A(不传即匹配任意字符)去把参数转换成^(首个匹配到大写) ^^(所有匹配到大写) ,(首个匹配到小写) ,,(所有匹配到小写)
```
再次提醒,这些命令子句都只能使用在**双引号**之间!
> MMP bash guide 不更新了… 我得另谋出路<file_sep>---
title: More TypeScript
date: 2019-03-27
---
## TypeScript 2.8 News
### Context
之前看了一篇关于Vuex类型的文章,发现其中很多的功能都是TS2.8更新加入的特性;刚好前几天看到一个写的非常好的博客(文末的TypeScript Evolution),决定在这里做一个记录。
### Conditional Type
#### 0x00
条件类型的判断有点像`instance of`,写法如下:
```typescript
T extends U ? X : Y
```
语法上就是JavaScript中常见的条件表达式, `T` `U` `X` `Y` 代表任意类型。如你所见`T extends U`部分描述了`T`是否可以从`U`中扩展出来, 然后满足条件的话得到类型`X`, 否则得到 `Y`。
我们可以看一下lib.es5.d.ts里面预定义的`NonNullable`的写法学习一下:
```typescript
type NonNullable<T> = T extends null | undefined ? never : T;
```
如上所示,如果传入的类型`T`能够从`null | undefined`里扩展出来(即是空值),那么就返回`never`, 反之则正常。
#### 0x01
`NonNullable`的一个使用场景(来自文末的typescript evolution):
```typescript
type EmailAddress = string | string[] null | undefined;
// 然后我们对他NonNullable并展开过程
type NonNullableEmailAddress = NonNullable<EmailAddress>;
type NonNullableEmailAddress = NonNullable<
| string
| string[]
| null
| undefined
>;
// 注意这一步是这样展开的
type NonNullableEmailAddress =
| NonNullable<string> // string
| NonNullable<string[]> // string[]
| NonNullable<null> // never
| NonNullable<undefined> // never
;
// never因为是所有类型的子类型,在unnion type中我们可以忽略掉它
type NonNullableEmailAddress = string | string[];
```
### Mapped Type Modifiers
#### 0x10
这个要说一下2.8带来的相关新预定义类型:`Partical<T>`, `Required<T>`等;
首先有一个这样的`interface`
```typescript
interface TodoItem {
description: string;
priority?: "high" | "medium" | "low";
}
```
如果你需要把这个TodoItem的字段都变成必填的,很简单,你只需要使用keyof关键字取出所有的字段,再使用`-?`操作符去掉可选条件,然后简单得重新声明一下就好了。如下所示:
```typescript
type RequiredTodoItem = {
[K in keyof TodoItem]-?: TodoItem[K]
}
```
至于上面提到的`Required`关键字呢,就是做一模一样的事情的,所以你也可以这样子:
```typescript
type RTodoItem = Required<TodoItem>; // awesome
```
留意`[K in keyof T]`这部分,TS2.8的中所提供的Mapped Type Modifiers都是这类操作。
#### 0x11
我们再看看一个结合了`extends ? : `的预定义类型的例子, 用来帮助我们提取`interface`中不可为空的属性;(来自文末的typescript evolution):
首先有这样一个提取不可为空的`Keys`的类型:
```typescript
type NonNullablePropertyKeys<T> = {
[P in keyof T]: null extends T[P] ? never : P
}[keyof T];
```
我们传入一个`interface`然后一步步展开:
```typescript
type User = {
name: string;
email: string | null;
}
type NonNullablePropertyKeys = NonNullablePropertyKeys<User>;
type NonNullablePropertyKeys = {
[P in keyof User]: null extends User[P] ? never : P
}[keyof User];
// keyof User = "name" | "email"
// 再展开:
// [P in "name" | "email"]: Type[P] =
// { name: Type["name"], email: Type["email"] }
type NonNullableUserPropertyKeys = {
name: null extends User["name"] ? never : "name";
email: null extends User["email"] ? never : "email";
}[keyof User];
type NonNullableUserPropertyKeys = {
name: "name"; // => | { name:""name", email: never }["name"]
email: never; // => | { name:""name", email: never }["email"]
}["name" | "email"];
type NonNullableUserPropertyKeys = "name" | never // 然后可以消除 never
```
我们再往前推进一步, 讲一下新的预定义类型 `Pick<T, K extends keyof T>` :
```typescript
/**
* From T, pick a set of properties
* whose keys are in the union K
*/
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
// 结合上面的 NonNullablePropertyKeys
type NonNullableProperties<T> = Pick<T, NonNullablePropertyKeys<T>>
type NonNullableUserProperties = NonNullableProperties<User>;
// { name: string }
```
great work~
#### 0x12
`infer`也是这次更新里面加入的一个条件类型用的关键字,用来声明类型变量的关键字。
获取First-Type:
```typescript
type First<T> =
T extends [infer U, ...unknown[]]
? U
: never;
type SomeTupleType = [string, number, boolean];
type FirstElementType = First<SomeTupleType>; // string
```
获取返回值类型:
```typescript
type ReturnType<T> =
T extends (...args: any[]) => infer R
? R
: any;
type A = ReturnType<() => string>; // string
type B = ReturnType<() => () => any[]>; // () => any[]
type C = ReturnType<typeof Math.random>; // number
type D = ReturnType<typeof Array.isArray>; // boolean
```
需要注意的地方是,infer声明只能在条件判断类型的`true`分支里面使用。
### 0xff
基于上述的更新内容, TS2.8+添加了不少好用的预定义类型,可以去更新日志里面翻一下看看具体的关键字。
### 相关资源
- [conditional-types-in-typescript](https://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/) 这篇文章下面那个redux的例子是开始有了一些兴趣
- [TypeScript Evolution Blog](https://mariusschulz.com/blog/series/typescript-evolution) 和更新日志的内容差不多
- [TS2.8更新日志](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html)
- [TS Playground](https://typescript-play.js.org/#code/JYOwLgpgTgZghgYwgAgCoHsAm6CSkC2yA3gFDLnKYQDOCUwADmMOiAFzLVj0gDmA3GQoN66emACeAfg4AiABbBe82cgA+yWfgiZgAV3yqNsgDboA7rMEBfEiQSsuyMFnQBGDhmx4IhALzEQuRUtPRMLOyaAIIxsgA0QcgiLOIScorKsiTWgvaOYM6uAEyerj7+gRSUNHSMzKxyAELNWbZ5IE4u2ADMpd4EyAGkVSG14Q2aAMLT8YnJYsCSHHogVDCgOtl2kgwoAApwUMxwJl64BG6DlRQA2gDSyKDIANYQEugwaGUEALoAtDIvv1fPcfjZthJdsgDkdgCczuUrgAlCAARz0wCgOgAPAiCAA+fhAA) Web TS Playground, 方便你随时折腾一下<file_sep>---
title: webpack使用者工具集
date: 2019-03-26
---
# More Webpack
最近这段时间接触Webpack比较多,整理一下比较好用的一些Webpack插件,以及相关的工具。比较常用的一些插件(如`html-webpack-plugin`)以及语言相关的loader就不放在这里了,这个并没有什么值得说的。
### 生态
**更舒服的Webpack**
- 编写更可读的webpack配置文件 [webpack-chain](https://github.com/neutrinojs/webpack-chain)
- 当你需要写loader时,可能需要 [loader-utils](https://github.com/webpack/loader-utils)
- 也许你感兴趣webpack的事件机 [tapable](https://github.com/webpack/tapable)
- 也许你感兴趣你看不见的文件在哪里 [memory-fs](https://github.com/webpack/memory-fs)
### 插件
**大概会用到**
- 对"新"JS支持更好的压缩插件 [terser-plugin](https://github.com/webpack-contrib/terser-webpack-plugin)
- webpack4必备的css提取插件 [mini-css-extract-plugin](https://github.com/webpack-contrib/mini-css-extract-plugin)
- 如果你需要复制一些静态内容 [copy-webpack-plugin](https://github.com/webpack-contrib/copy-webpack-plugin)
- 如果你想让你的应用支持PWA [workbox](https://github.com/GoogleChrome/workbox)
- 如果你需要国际化支持 [i18n-webpack-plugin](https://github.com/webpack/i18n-webpack-plugin)
**开发环境**
- webpack编译过程图形化输出 [webpackbar](https://github.com/nuxt/webpackbar)
**性能调优,TreeShake情况分析,问题调试插件**
- 打包性能分析插件 [Wepack.ProfilingPlugin](https://webpack.js.org/plugins/profiling-plugin/)
- Stats输出插件 [StatsPlugin](https://github.com/unindented/stats-webpack-plugin)
- 打包结果体积可视化 [WebpackBundleAnalyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer)
### Tips
- common部分或者打包成DLL模块这部分尽量不要发生变化,才能在版本迭代的时候保证客户端缓存能被触发(视产品类型,宁可一开始就把整个组件库放进去)
- 大部分脚手架都有合理的生产环境打包配置,出现异常情况时,应该结合获取打包过程信息 `Stat` 的插件分析是不是某个模块或者某个写法导致 tree-shaking 没有合理触发。
### Next Version (Webpack 5)
**开发环境**
- 将会移除node.js的 `crypto` polyfills
- 优化开发环境打包结果,更合理的语意命名
- 优化开发时的打包缓存使用
**生产相关**
- 优化生产环境打包结果,无改动的模块还是一样的 chunkId,优化客户端缓存触发
- JS模块的导出命名调整成可预期的结果
- 优化 `无/少JS模块` 的打包结果(如样式模块)
- 细化 `缓存` 配置,指定缓存的模块,可自定义的缓存结果版本
**杂项**
- **Node Version: >=8.9.0**
- 一些逻辑上的bugs修复
- 一些配置默认值的修改
- `stat` 对象中根据新配置增加了相关信息
- 优化了 `tree-shaking` 对模块的来源分析
- 扩展对象的序列化功能
- Tapable 1 -> 2
- 优化了配置的类型,使用 `Set` 代替数组
- asyncWasm, topLevelAwait, import(Async/Await) 实验性支持
> 参考Tobias最近一次演讲的[slides](https://raw.githubusercontent.com/sokra/slides/master/data/webpack-5-whats-new.pdf)<file_sep>module.exports = {
title: '|> Saki',
base: '/saki/',
dest: '../docs',
ignores: ["ignores/*"],
head: [
['link', { rel: 'icon', href: './favicon.png' }]
],
themeConfig: {
nav: [
{ text: '/Saki', link: '/' },
{ text: '关于我', link: '/About Me.html' }
]
}
}
<file_sep>---
title: 从HellDoc这个项目中学到的东西
date: 2019-02-27
tags: HellDoc,工具,编程
---
> What I cannot create, I do not understand. —— Feynman
`HellDoc`就是我拿来理解[`vuepress`](https://github.com/vuejs/vuepress/blob/master/)工作方式的一个玩具项目。开发的过程中遇到的问题正是我学习的机会,下面是一些我在这之前所不熟悉或事一知半解的内容:
## So...
### 1. Markdown 文件修改的即时更新
vuepress 会把收集到的 md 文件通过 [`markdown-loader`](https://github.com/vuejs/vuepress/blob/master/packages/%40vuepress/markdown-loader/index.js) 编译成一个个的 vue 组件,并且生成一个包括了这些组件的文档应用的 route 文件。
在这个基础上,`*.md`文件的修改理所当然得会被 webpack 自动捕捉到(因为已经在上面生成的 route 的依赖列表里了);而对于目录上的文件增删则是用[`chokidar`](https://github.com/paulmillr/chokidar)做了文件目录的 watch,触发的时候重新渲染`router`文件
值得一提的是,在修改`config.js`这样的配置文件的时候:因为 nodejs 对 js-module 做了缓存的原因,无法触发文件更新,这时候就需要把`require.cache[absoluteFilePath]`的缓存内容删除,然后再进行后续的文档 App 部分的更新。
### 2. 非常友好的 Logger 提示
vuepress 中让我觉得特别友好的 log 提示是怎么做到的
1. @vuepress/logger 统一的 logger 模块
2. [webpackbar](https://github.com/nuxt/webpackbar) 给你更直观的编译信息
3. 在需要的生命周期中添加合理的[log 插件](https://github.com/vuejs/vuepress/blob/master/packages/%40vuepress/core/lib/webpack/DevLogPlugin.js)
### 3. DevServer 的路由设置参考
vuepress 的 dev 指令是在本地编写文档的时候使用的,你可以从这里学到一个 SPA 应用在测试的时候 webpackDevServer 如何设置最为**自由**,**效率**
```javascript
// 摘自@vuepress/core dev.js
const serverConfig = Object.assign(
{
disableHostCheck: true,
compress: true,
clientLogLevel: "error",
hot: true,
quiet: true, // vuepress里面的log都通过插件或自己处理了
headers: {
"access-control-allow-origin": "*"
},
open: cliOptions.open,
publicPath: ctx.base,
watchOptions: {
ignored: [/node_modules/, `!${ctx.tempPath}/**`]
},
historyApiFallback: {
disableDotRule: true,
rewrites: [{ from: /./, to: path.posix.join(ctx.base, "index.html") }]
},
overlay: false,
host,
contentBase,
before(app, server) {
if (fs.existsSync(contentBase)) {
app.use(ctx.base, require("express").static(contentBase));
}
ctx.pluginAPI.options.beforeDevServer.syncApply(app, server);
},
after(app, server) {
ctx.pluginAPI.options.afterDevServer.syncApply(app, server);
}
},
ctx.siteConfig.devServer || {}
);
```
### 4. @ts-check, @ts-ignore
在抽离为Hell服务的皮肤模块的时候,我意识到不需要那么严格的类型检查。通过`@ts-ignore`去忽略一些运行时添加的数据模块的`import`检查,后续再添加一些需要的类型(但实际上是一种无奈之举);`@ts-check`则相反,是给js文件带来一定的类型推导功能。
### 5. webpack如何模拟模块机制
TODO
### OVA
因为自己是 TS 用户,顺手帮社区补全了一下[`webpack-chian`](https://github.com/neutrinojs/webpack-chain/pull/132)的类型声明文件。
: )
<file_sep>---
sidebar: false
---
## 关于我
- 喜欢玩: [Celeste](http://www.celestegame.com/)
- 喜欢的番剧: `物语系列`
- 上一本看的书: 毛姆的《刀锋》
- 使用较多的语言: TypeScript, Elixir
- [Github: fimars](https://github.com/fimars/)
- [Twitter: fimars](https://twitter.com/_fimars)
### 怎么样的一个人呢?
只会一点点前端开发,是鄙视链最底层的程序员;偶尔写一点自己能用得上的代码和能喂饱自己的代码;说是Elixir本当上手,根本就没有写过什么像样的东西!最近在拿着webpack折腾,稍微弄明白了一点点关于webpack的一些基本概念。
其他方面的话;因为特别喜欢一个歌手,买了一把便宜的`takamine`正在练习吉他中;玩了Celeste之后偶尔会想去登山;饮料的话只喝茶茶茶,其他的也不是不可以,但是还是喜欢茶。
看了一眼自己的commit记录,周末从来不写代码成就获得,以上。<file_sep>---
sidebar: false
---
<style>
.markdown-body {
margin-top: 60px;
}
.markdown-body blockquote {
font-size: 22px;
}
.markdown-body ul {
margin-left: 0 !important;
}
.markdown-body li {
font-size: 24px;
}
.markdown-body li:before {
display: none !important;
}
.markdown-body ul + p {
font-size: 15px;
}
</style>

> Welcome to `Saki`, Let's talk we want to talk.
- [JavaScript's Unicode](./JavaScript's%20Unicode.html)
JavaScript中的Unicode
- [TC39 `globalThis`](./TC39%20globalThis.html)
Polyfill实现非常有趣的一个草案
- [More Webpack](./More%20Webpack.html)
记录了使用过的Webpack生态内好用的工具
- [关于HellDoc](./About%20Hell.html)
关于`HellDoc`开发的初衷和从中学到的内容
- [More TypeScript](./TypeScript%202.8%20News.html)
之前看了一篇关于Vuex类型的文章,发现其中很多的功能都是TS2.8更新加入的特性;刚好前几天看到一个写的非常好的博客(文末的TypeScript Evolution),决定在这里做一个记录。<file_sep># 访问
个人学习博客,点这里 [saki](https://fimars.github.io/saki/) <<file_sep>---
title: JS中的Unicode
date: 2019-11-29
---
# JS中的Unicode
缘起于知识星球的某个用户在自己的名字中使用了[U+202E](https://codepoints.net/U+202E)的从右向左显示控制字符,让我对这个事情有了些许的兴趣
### js中使用的unicode版本
关于Unicode团队和USC团队,从网上随处可见的描述可以得知——目前由于历史原因,JS中的unicode字符确实会带来不大不小的坑。
> UTF(Unicode transformation format)Unicode 转换格式,是服务于 Unicode 的,用于将一个 Unicode 码点转换为特定的字节序列。常见的 UTF 有
>
> > UTF-8 可变字节序列,用 1 到 4 个字节表示一个码点
> > UTF-16 可变字节序列,用 2 或 4 个字节表示一个码点
> > UTF-32 固定字节序列,用 4 个字节表示一个码点
>
> [UTF-8](https://en.wikipedia.org/wiki/UTF-8) 对 ASCⅡ编码是兼容的,都是一个字节,超过 U+07FF 的部分则用了复杂的转换方式来映射 Unicode,具体不再详述。
>
> UTF-16 对于 BMP 的码点,采用 2 个字节进行编码,而 BMP 之外的码点,用 4 个字节组成代理对(surrogate pair)来表示。其中前两个字节范围是 U+D800 到 U+DBFF,后两个字节范围是 U+DC00 到 U+DFFF,通过以下公式完成映射(H:高字节 L:低字节 c:码点)
> H = Math.floor((c-0x10000) / 0x400)+0xD800
> L = (c - 0x10000) % 0x400 + 0xDC00
>
> 比如💩用 UTF-16 表示就是"\uD83D\uDCA9"
>
> UCS(Universal Character Set)通用字符集,是一个 ISO 标准,目前与 Unicode 可以说是等价的。
> 相对于 UTF,UCS 也有自己的转换方法(编码)。如
>
> > UCS-2 用 2 个字节表示 BMP 的码点
> > UCS-4 用 4 个字节表示码点
>
> UCS-2 是一个过时的编码方式,因为它只能编码基本平面(BMP) 的码点,在 BMP 的编码上,与 UTF-16 是一致的,所以可以认为是 UTF-16 的一个子集。
> UCS-4 则与 UTF-32 等价,都是用 4 个字节来编码 Unicode。
## 常见问题
### 字符串处理
**string.length**
超过BMP的unicode字符的length会得到 2,可以通过正则表达式解决:
```javascript
var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; // 匹配UTF-16的代理对
function countSymbols(string) {
return string
.replace(regexAstralSymbols, '_')
.length;
}
```
**string.split**
并且,由上面`.length`的情况可以猜测得到,`.split`一样会把这个两位的usc-2码点当作两个字符来处理。如果此时紧随着一个反转操作,不堪入目。(解决办法是通过新的Array.from方法去对字符串进行处理)。
**string.fromCharCode**
这个东西呢,虽然传不了usc-4的值,但是你可以算出高位低位传两个参数进去。不过这也被新方法`.fromCharPoint`完美解决了。
**正则表达式.匹配**
现在支持u-flag了,就酱
```javascript
/foo.bar/.test('foo🔟bar') // false
/foo.bar/u.test('foo🔟bar') // true
```
### 号外
开头说到的那个用户,就是通过一个控制方向字符达到如下的效果
字符串内容`"某某某亲了(\u202e下一(\u202d 回复者"`,由于U+202E前面这部分会变成`某某某亲了(\u202d回复者)一下`,然后又通过U+202d去让后续回复者的内容从左向右显示,达到了某某某亲了回复者一下的效果。
### 参考
1. http://www.alloyteam.com/2016/12/javascript-has-a-unicode-sinkhole/
2. https://mathiasbynens.be/notes/javascript-unicode<file_sep>## Bash Step By Step
> 翻译:Bash我TM社保 —— 某不愿意透露姓名的Ass We Can大佬(纯虚构)
### 缘由
这个月我原本是为了填一个MusicApp的坑,准备入Kotlin的。按照之前的经验,学习语言的初期刷题是一个对提高熟练度非常有帮助的方法,但是当我点开CW的语言分类的时候,我惊喜得发现有Bash这个shell。好“骑”心爆棚的我点进了Bash的题库随便点开了一道,然后就蒙住了。我对不起当年的系统课上的linux老师,对不起作业,我决定把Bash捡起来。(Kotlin呢,MusicApp呢?
### 起手式
*PS: 一些有用的资源, Mac only, Sorry for the proletariat.*
- [Update Bash In Mac By Brew](http://clubmate.fi/upgrade-to-bash-4-in-mac-os-x/)
- [配合iterm2的高亮](https://superuser.com/questions/399594/color-scheme-not-applied-in-iterm2)
- [Bash Guide](http://guide.bash.academy/) 目前在看的就是这个
## Bash Guide Notes 📒
> Bash Guide: http://guide.bash.academy/commands/
### The Chapter: Commands And Arguments
**预备知识:**
0. ~~指令块使用大括号包裹, `{ command1; command2 }`~~
1. Exec指令: 新开一个进程,代替现有的进程。具体可见 [这里](https://askubuntu.com/questions/525767/what-does-an-exec-command-do)
2. **File Descriptor** 见下文
#### File Descriptor
bash中有一个蛮重要的概念——File Descriptor(后简称FD),FD是bash程序和外界交互的一个抽象,常见的有FD0(标准输入)、FD1(标准输入)、FD2(标准Error)。可以参考下图:

~~**可能会有用的情报:**~~
~~Bash会为每条`指令`创建一个`subshell`,这个会放在后面讲解~~
#### 基本语法 Syntax
注:这里以罗列语法为主,自己可以拿几个常用的指令在bash上试试看, 如: `echo`, `ls`, `cat` 等
**Syntax**
1. `[ something ]` 指是可选的
2. `[ FORMAT ...]` 指重复多个这个格式是合法的
**Command**
> 基本形式: `[环境变量 ...] 指令名 [参数 ...] [FD重定向 ...]`
**List 一串Commands**
> 基本形式 : `command control-operator[ commadn2 control-operator ... ]`
控制操作符包含 `|| && ;` `||`在前者执行失败的时候调用,`;`在前者执行结束之后调用, `&&`在前者执行成功之后调用
**Compound Command 混合Command**
> 基本形式: `if list [ ;|<newline> ] then list [ ;|<newline> ] fi` 或 `{ list ; }`
**Coprocesses 异步Command**
> 基本形式: `coproc [ name ] command [ redirection ... ]`
注:会在使用这个`$name`的时候去运行这个指令并拿到即时的结果
**Functions**
> 基本形式: `name () compound-command [ redirection ]`
注:**()内没有参数,一直为空,参数通过$1, $2, $3...获取。**
顺便说一下,一些有用的内置变量:
- `$$ - PID`
- `$! - 后台PID`
- `$? - exit code`
- `$* - 参数列表 空格分割`
- `$@ - 参数列表 回车分割`
- `$# 参数个数`
**Pipeline**
> 基本形式: `[time [-p]] [ ! ] command [ [|或|&] cmmand2 ... ]`
注:以下有个简单例子
```bash
$ echo Hello | rev
# output: olleH
$ rm doesntexistfile |& rev
# output: yrotcerid ro elif hcus oN :eliftsixetnseod :mr
$ time echo Hello
# output: Hello <newline><newline> echo 0m0.004s etc...
# ! 关键字暂时没有讨论到,待补充
```
`Pipeline`具体做的事情就是:把前一条指令的FD1,2,指向了下一跳指令的FD0;
且有`cm1 | cm2` ,`cm1 |& cm2`两种形式。第二种我还是第一次知道呢/doge
#### 简单命令 Simple commands
主要内容就两个,一个是基本的命令使用,另外一个就是用于串联命令之间FD的各种重定向符号
**命令 Command**
**指令名**:Bash会根据 `指令名` 去查找 `已定义的fn` , `builtin-fn` 或 `$PATH` 里有的程序去执行,type可以查找指令的所在位置 —— `type command`。
**参数**:command后面的参数用空格分割,字符串中有空格用`"`, `'`包裹或者用`\`转义空格。字符串`""` 内可包裹变量`$variable` 或 命令`$(command)`
请务必留意引号的使用,有个危险的例子可以看看
```bash
$ read -p 'Which user would you like to remove from your system ?' username
# Something Print ...? lucifa
$ rm -vr /home/$username
# Broken! this command will be:
# -> rm -vr /home/ lucifa
```
**重定向 Redirection**
> DING, 已获得情报如下:
1. `command >File` 可以把指令的FD1指向File
2. `command 2>File` 可以把指令的FD2指向File
3. `/dev ` 下存放的是直接指向系统设备的文件, `/dev/null` 则是其中一个特殊的存在,这个文件不管写,一直为空。可以把不在意的错误信息指向这个文件。
4. 当你很理所当然得使用如下操作时,其实情况非常危险⚠️
```bash
$ ls -l a b >myfiles.ls 2>mayflies.ls
# 理想状态应该是,把正常输入写到myfiles, 然后,把错误信息写到后面
# 实际结果却如下
# -rw-r--r-- 1 lhunath stls: b: No such file or directoryaff 0 30 Apr 14:43 a
# 混乱的结果
```
因为两个FD同时打开了这个文件流,所以导致混合的结果。正确的操作如下
```bash
$ ls -l a b >myfiles.ls 2>&1
# 使用 >& 操作符,让FD2指向FD1的文件流
```
5. `[x]>file, [x]<file` 指令的FD1指向文件,指令的FD0从文件输入
6. `[x]>&y 或 [x]<&y` 复制文件指向流,后者的使用场景还没看到, 但在SO某个问题中看到,前后两者的效果几乎一样 [Link](https://unix.stackexchange.com/questions/120532/what-does-exec-31-do)
7. `x>&-, x<&-` 用`-`去指向,即是关闭这个FD
8. `[x]>&y-, [x]<&y-` 是 `[x]>&y y>&-` 的语法糖
9. `[x]>>file` Appending 文件指向
10. `[x]&>file` 同时重定向FD1,FD2到File
11. `[x]<>file` 把FD0, FD1都指向一个文件
```bash
$ exec 3>&1 >mylog; echo moo; exec 1>&3 3>&-
# 这个地方先把当前进程的FD1 copy 到FD3来,然后把FD1指向一个文件
# 接着来一发echo,等于是把输出值写到文件,最后结束的时候exec
# 重新把FD1指回一开始的Display,把FD3抛弃掉
```
12. Here Documents
```
command <<[-]分隔符(.)
Documents
分隔符
```
直接把分隔符内的内容传输给`指令`的FD0, 带上`-`就是忽略内容每行开头的空格。
13. Here Strings, 类似前一个,更精简一些,`<<<string `即可
|
bb04ef2717d6c3aa14b0ffa1f293fe5db7511770
|
[
"Markdown",
"JavaScript"
] | 11
|
Markdown
|
fimars/saki
|
d5c3ec25fe4d3af9a737d95a94c1c4c0a86c957a
|
784f9b10257e9335f8fa7177aa69daf0bcb06358
|
refs/heads/master
|
<file_sep>import socket
class Network:
def __init__(self, username, ip, port):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = ip
self.MAX_LENGTH = 1024
self.port = port
self.address = (self.host, self.port)
self.id = ''
self.state = ''
self.connect(username)
def connect(self, username):
self.client.connect(self.address)
self.snd(username)
data = self.rcv(self.MAX_LENGTH)
if data == 'wait':
self.state = 'wait'
elif ':' in data:
arr = data.split(':')
print(arr)
self.state = arr[1]
self.id = arr[0]
def snd(self, data):
self.client.send(data.encode())
def rcv(self, size):
return self.client.recv(size).decode()
<file_sep># Pong-Multiplayer
<img src="http://g.recordit.co/cbnnkNjsee.gif" width="416" height="240" />
# Server
To run a server on your computer use the portmapper to port forward `External Port: 59555` to `Internal Port: 59559`
Then you may simply run `python server.py` to host a server.
# Joining Games
To join a game, you have to first get the hosts ip and then use it to join the game when you run `python game.py`
<file_sep>import socket
import select
from requests import get
def main():
ip = get('https://api.ipify.org/?format=text').text
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# host and port
host = '0.0.0.0'
port = 59559
# binding socket and listening
sock.bind((host, port))
sock.listen(2)
print(f'\n[+] Server started on {ip}:{port}')
sockets_list = [sock]
outputs = []
clients = {}
users = []
def get_user(c):
try:
return c.recv(1024).decode()
except Exception as e:
print(e)
while True:
print('\nWaiting for next event')
# selecting readable/writable lists with select module
readable, writable, errs = select.select(sockets_list, outputs, [])
if readable:
for i, s in enumerate(readable):
# check if socket is server socket
if s == sock:
connection, address = sock.accept()
sockets_list.append(connection)
username = get_user(connection)
clients[connection] = username
users.append(username)
# Closing connection with 3 or more players
if len(users) > 2:
connection.close()
# check if two players are connected
elif len(users) == 2:
for client, username in clients.items():
# sending player id and start signal to all sockets
# other than the server socket
if client != s:
for j, user in enumerate(users):
if clients[client] == user:
client.send(f'{j}:start'.encode())
# print(f'Sending start signal to {user} ID:{j}')
else:
connection.send('wait'.encode())
else:
data = s.recv(1024).decode()
if not data:
s.close()
sockets_list.remove(s)
del clients[s]
elif ':' in data:
arr = data.split(':')
player_id = 0
player_one_pos = arr[0]
ball_pos = arr[1]
# print('Client one data:', player_one_pos, ball_pos)
for j, client in enumerate(clients):
if j != player_id:
client.send(data.encode())
print(f'Sending {data} to player: {j}')
elif ':' not in data:
if data != 'enemy' or 'player':
arr = data.split('.')
player_id = 1
player_two_pos = arr[0]
# print("Client two data:", player_two_pos)
for j, client in enumerate(clients):
if j != player_id:
client.send(data.encode())
print(f'Sending {data} to player: {j}')
if __name__ == '__main__':
main()
<file_sep>import pygame
import sys
import math
import random
import os
from pygame.locals import *
from requests import get
from network import Network
ip = get('https://api.ipify.org').text
state = 'menu'
n = None
is_player_two = False
enemy = None
scores = []
player_one = None
display = None
finished = True
username = ''
winner = ''
# open game window centered on the screen
os.environ['SDL_VIDEO_CENTERED'] = "1"
pygame.init()
clock = pygame.time.Clock()
# colors, its B&W
dark_gray = (25, 25, 25)
white = (255, 255, 255)
res = (1250, 720)
darker_gray = (15, 15, 15)
black = (0, 0, 0)
pygame.display.set_caption("Pong by @stoozy")
# this is the ball class. It has a reset and update function.
class Ball:
def __init__(self):
self.direction = 0
if state == 'online_game':
self.speed = 5
else:
self.speed = 1
self.reset()
def reset(self):
self.x = 550
self.y = random.randint(25, 600)
self.direction = random.randrange(30,45)
# Flip a 'coin'
if random.randrange(2) == 0 :
# Reverse ball direction
self.direction += 180
def update(self):
direction_rad = math.radians(self.direction)
self.x += self.speed * math.sin(direction_rad)
self.y -= self.speed * math.cos(direction_rad)
# update collisions
self.collisions()
def online_update(self, x, y):
# print(x, y)
self.x = float(x)
self.y = float(y)
self.collisions()
def collisions(self):
# making the ball a rect object so I can check for collisions
self.rect = pygame.draw.rect(display, white, (self.x, self.y, 20, 20))
# checking for collisions
if state == 'offline':
if pygame.sprite.collide_rect(self, ai):
self.direction = 360-self.direction
if pygame.sprite.collide_rect(self, player):
self.direction = 360-self.direction
if state == 'online_game':
if pygame.sprite.collide_rect(self, enemy):
self.direction = 360-self.direction
if pygame.sprite.collide_rect(self, player):
self.direction = 360-self.direction
# checking for out of bounds
if self.y <= 0:
self.direction = 180-self.direction
elif self.y >= 720:
self.direction = 180-self.direction
class Paddle:
def __init__(self, x, y):
self.score = '00'
self.x = x
self.y = y
if not display:
pass
else:
self.rect = pygame.draw.rect(display, white, (int(x), int(y), 25, 150))
def ai_update(self, ball_y_pos):
self.y = ball_y_pos
if ball_y_pos < 10:
self.y = 10
if ball_y_pos > 560:
self.y = 560
self.rect = pygame.draw.rect(display, white, (self.x, self.y, 25, 150))
def update(self):
if state == 'online_game':
# pressed keys object. Updates on the while loop
keys = pygame.key.get_pressed()
# Player movement
if keys[pygame.K_UP]:
if self.y == 10:
self.y = self.y
else:
self.y -= 5
elif keys[pygame.K_DOWN]:
if self.y == 560:
self.y = self.y
else:
self.y += 5
self.rect = pygame.draw.rect(display, white, (self.x, self.y, 25, 150))
else:
# pressed keys object. Updates on the while loop
keys = pygame.key.get_pressed()
# Player movement
if keys[pygame.K_UP]:
if self.y == 10:
self.y = self.y
else:
self.y -= 1
elif keys[pygame.K_DOWN]:
if self.y == 560:
self.y = self.y
else:
self.y += 1
self.rect = pygame.draw.rect(display, white, (self.x, self.y, 25, 150))
def online_update(self, x, y):
self.x = int(x)
self.y = int(y)
self.rect = pygame.draw.rect(display, white, (self.x, self.y, 25, 150))
# initializing classes
player = None
ai = Paddle(1200, 330)
ball = Ball()
# fonts for pygame
small_font = pygame.font.Font('Roboto-Regular.ttf', 25)
font = pygame.font.Font('Roboto-Regular.ttf', 32)
largeFont = pygame.font.Font('Roboto-Regular.ttf', 60)
def draw_dashed_line():
pygame.draw.rect(display, white, (610, 000, 15, 50))
pygame.draw.rect(display, white, (610, 100, 15, 50))
pygame.draw.rect(display, white, (610, 200, 15, 50))
pygame.draw.rect(display, white, (610, 300, 15, 50))
pygame.draw.rect(display, white, (610, 400, 15, 50))
pygame.draw.rect(display, white, (610, 500, 15, 50))
pygame.draw.rect(display, white, (610, 600, 15, 50))
pygame.draw.rect(display, white, (610, 700, 15, 50))
def check_winner():
if state == 'offline':
if int(ai.score) == 5:
winner_text = largeFont.render('The winner is: computer', True, white, dark_gray)
display.blit(winner_text, (435, 270))
elif int(ai.score) == 6:
pygame.quit()
sys.exit()
if int(player.score) == 5:
winner_text = largeFont.render('The winner is: player one', True, white, dark_gray)
display.blit(winner_text, (425, 270))
elif int(player.score) == 6:
pygame.quit()
sys.exit()
elif state == 'online_game':
# fix for a bug where network receives too much info
if len(enemy.score) > 2:
enemy.score = enemy.score[:2]
if len(player.score) > 2:
enemy.score = enemy.score[:2]
#drawing scores based on client.
if is_player_two:
if int(enemy.score) == 5:
winner_text = largeFont.render('You Won!', True, white, dark_gray)
display.blit(winner_text, (465, 270))
elif int(enemy.score) == 6:
pygame.quit()
sys.exit()
if int(player.score) == 5:
winner_text = largeFont.render('You Lost!', True, white, dark_gray)
display.blit(winner_text, (465, 270))
elif int(player.score) == 6:
pygame.quit()
sys.exit()
else:
if int(enemy.score) == 5:
winner_text = largeFont.render('You Lost!', True, white, dark_gray)
display.blit(winner_text, (465, 270))
elif int(enemy.score) == 6:
pygame.quit()
sys.exit()
if int(player.score) == 5:
winner_text = largeFont.render('You Won!', True, white, dark_gray)
display.blit(winner_text, (465, 270))
elif int(player.score) == 6:
pygame.quit()
sys.exit()
def draw_scores():
global player, enemy, scores
if state == 'online_game':
# defining who gets the score
if not is_player_two:
if ball.x > 1250:
player.score = str(int(player.score) + 1)
ball.reset()
elif ball.x < 0:
enemy.score = str(int(enemy.score) + 1)
ball.reset()
scores = [player.score, enemy.score]
es = str(enemy.score).zfill(2)
ps = str(player.score).zfill(2)
player_score = font.render(str(ps), True, white, dark_gray)
enemy_score = font.render(str(es), True, white, dark_gray)
display.blit(player_score, (560, 10))
display.blit(enemy_score, (650, 10))
elif is_player_two:
# print(player.score, enemy.score)
enemy_score = str(enemy.score).zfill(2)
player_score = str(player.score).zfill(2)
player_score = font.render(str(player_score), True, white, dark_gray)
enemy_score = font.render(str(enemy_score), True, white, dark_gray)
display.blit(player_score, (560, 10))
display.blit(enemy_score, (650, 10))
elif state == 'offline':
if ball.x > 1250:
player.score = str(int(player.score) + 1).zfill(2)
ball.reset()
elif ball.x < 0:
ai.score = str(int(ai.score) + 1).zfill(2)
ball.reset()
player_score = font.render(str(player.score), True, white, dark_gray)
ai_score = font.render(str(ai.score), True, white, dark_gray)
display.blit(player_score, (560, 10))
display.blit(ai_score, (650, 10))
def handle_network():
global is_player_two, enemy, scores, player, winner
data = n.rcv(1024)
if ':' in data:
if 'player' or 'enemy' in data:
if 'player' in data:
winner = 'player'
elif 'enemy' in data:
winner = 'enemy'
arr = data.split(':')
# update enemy player
x, y = arr[0].split('.')[1], arr[0].split('.')[2]
enemy.online_update(x, y)
# update ball position based on client ones ball position
a, b = arr[1].split('|')[0], arr[1].split('|')[1]
ball.online_update(a, b)
# get scores
try:
player.score, enemy.score = arr[2].split(',')
except IndexError as e:
print(e)
# player.score, enemy.score = arr[2].split(',')[0], arr[2].split(',')[1]
# scores = [player.score, enemy.score]
# scores[0], scores[1] = s1, s2
is_player_two = True
elif '.' in data:
arr = data.split('.')
x, y = arr[1], arr[2]
# print(x, y)
# enemy = Paddle(x, y)
enemy.online_update(x, y)
# update ball normally
ball.update()
is_player_two = False
elif 'player' or 'enemy' in data:
if 'player' in data:
winner = 'player'
elif 'enemy' in data:
winner = 'enemy'
def game_loop():
global finished, state, n, display, is_player_two, player, player_one
while not finished:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == pygame.K_ESCAPE:
finished = True
if state == 'offline':
display.fill(dark_gray)
draw_dashed_line()
draw_scores()
check_winner()
player.update()
ai.ai_update(ball.y)
ball.update()
# updating objects and screen
pygame.display.update()
elif state == 'online_wait':
display.fill(dark_gray)
waiting_text = largeFont.render('Waiting...', True, white, dark_gray)
display.blit(waiting_text, (450, 260))
pygame.display.update()
data = n.rcv(1024)
if ':' in data:
arr = data.split(':')
# print(arr)
n.id = arr[0]
state = 'online_game'
print('started game...')
elif state == 'online_game':
# sending client data based on user
if is_player_two:
response = f'{n.id}.{player.x}.{player.y}'
n.snd(response)
elif not is_player_two:
try:
response = f'{n.id}.{player.x}.{player.y}:{ball.x}|{ball.y}:{scores[0]},{scores[1]}'
n.snd(response)
except IndexError:
response = f'{n.id}.{player.x}.{player.y}:{ball.x}|{ball.y}'
n.snd(response)
# updating objects and screen
display.fill(dark_gray)
player.update()
# handle incoming network data
handle_network()
draw_scores()
draw_dashed_line()
check_winner()
pygame.display.update()
def menu():
global ip, finished, display, n, state, is_player_two, player, enemy, username
print("Hello and welcome to pong-multiplayer by @stoozy\nWhat would you like to do?")
print("1. Join a game\n2. Play vs computer (you won't win) ")
choice = int(input("Enter choice:"))
if choice == 2:
state = 'offline'
display = pygame.display.set_mode(res)
player = Paddle(20, 330)
finished = False
game_loop()
else:
state = 'online'
join_ip = str(input("What is the IP of the host?\nIP:"))
finished = False
username = input('Username:')
n = Network(username, ip=join_ip, port=59555)
if n.state == 'wait':
print('waiting for other player...')
state = 'online_wait'
is_player_two = False
player = Paddle(20, 330)
enemy = Paddle(1200, 330)
display = pygame.display.set_mode(res)
game_loop()
elif n.state == 'start':
state = 'online_game'
print('started game...')
if n.id == '0':
is_player_two = False
player = Paddle(20, 330)
enemy = Paddle(1200, 330)
else:
is_player_two = True
player = Paddle(1200, 330)
enemy = Paddle(20, 330)
display = pygame.display.set_mode(res)
game_loop()
if __name__ == '__main__':
menu()
|
48eb0c157dfce384aad3bceb59e76072885dcbb8
|
[
"Markdown",
"Python"
] | 4
|
Python
|
Stoozy/Pong-Multiplayer
|
2ed4aee01f6dc58a6e1e33af0e895c90367c66fa
|
90ab9f559a5633023db0fa5e7c85a00bd31952ec
|
refs/heads/master
|
<repo_name>Roberto-Livi/key-for-min-value-onl01-seng-pt-012120<file_sep>/key_for_min.rb
# prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(name_hash)
key = nil
min_value = 0
name_hash.each do |k, v|
if min_value == 0 || min_value > v
min_value = v
key = k
end
end
key
end
|
89764e4053c07153c244737cea7e1dfbe5e82c9b
|
[
"Ruby"
] | 1
|
Ruby
|
Roberto-Livi/key-for-min-value-onl01-seng-pt-012120
|
40abb44ff282ff305b68a5c9882d12b5a93bccaa
|
efa56615aa6f3b6118c4cde923ec3fb8361f1650
|
refs/heads/master
|
<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.iflytek.cyber.evs.sdk.agent.AudioPlayer
import com.iflytek.cyber.evs.sdk.auth.AuthDelegate
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.FloatingService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.CollectionSingleAdapter
import com.iflytek.cyber.iot.show.core.api.MediaApi
import com.iflytek.cyber.iot.show.core.model.CollectionSong
import com.iflytek.cyber.iot.show.core.model.Error
import com.iflytek.cyber.iot.show.core.model.PlayResult
import com.iflytek.cyber.iot.show.core.model.PlaySingleBody
import com.kk.taurus.playerbase.utils.NetworkUtils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class CollectionSingleFragment : BaseFragment(), AudioPlayer.MediaStateChangedListener {
private lateinit var emptyContent: LinearLayout
private lateinit var recyclerView: RecyclerView
private var adapter: CollectionSingleAdapter? = null
private var items = ArrayList<CollectionSong>()
private var tagId: Int = -1
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragement_collection_media, container, false)
}
fun setItems(items: ArrayList<CollectionSong>, tagId: Int) {
this.tagId = tagId
this.items.clear()
this.items.addAll(items)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view.findViewById(R.id.recycler_view)
emptyContent = view.findViewById(R.id.empty_content)
}
override fun onLazyInitView(savedInstanceState: Bundle?) {
super.onLazyInitView(savedInstanceState)
launcher?.getService()?.getAudioPlayer()?.addListener(this)
adapter = CollectionSingleAdapter {
play(it)
}
adapter?.items = items
recyclerView.adapter = adapter
if (items.isEmpty()) {
emptyContent.isVisible = true
recyclerView.isVisible = false
} else {
emptyContent.isVisible = false
recyclerView.isVisible = true
}
}
override fun onStarted(player: AudioPlayer, type: String, resourceId: String) {
if (type == AudioPlayer.TYPE_PLAYBACK) {
adapter?.notifyDataSetChanged()
}
}
override fun onResumed(player: AudioPlayer, type: String, resourceId: String) {
if (type == AudioPlayer.TYPE_PLAYBACK) {
adapter?.notifyDataSetChanged()
}
}
override fun onPaused(player: AudioPlayer, type: String, resourceId: String) {
if (type == AudioPlayer.TYPE_PLAYBACK) {
adapter?.notifyDataSetChanged()
}
}
override fun onStopped(player: AudioPlayer, type: String, resourceId: String) {
if (type == AudioPlayer.TYPE_PLAYBACK) {
adapter?.notifyDataSetChanged()
}
}
override fun onCompleted(player: AudioPlayer, type: String, resourceId: String) {
}
override fun onPositionUpdated(
player: AudioPlayer,
type: String,
resourceId: String,
position: Long
) {
}
override fun onError(player: AudioPlayer, type: String, resourceId: String, errorCode: String) {
}
override fun onSupportVisible() {
super.onSupportVisible()
adapter?.notifyDataSetChanged()
}
private fun play(song: CollectionSong) {
if (tagId == -1) {
return
}
val body = PlaySingleBody(tagId, song.id)
getMediaApi()?.playSingleCollection(body)?.enqueue(object : Callback<PlayResult> {
override fun onResponse(call: Call<PlayResult>, response: Response<PlayResult>) {
if (!response.isSuccessful) {
showError(response.errorBody()?.string())
}
}
override fun onFailure(call: Call<PlayResult>, t: Throwable) {
if (isAdded && context != null && !NetworkUtils.isNetConnected(context)) {
Toast.makeText(context, "网络连接异常,请重新设置", Toast.LENGTH_SHORT).show()
}
t.printStackTrace()
}
})
}
private fun showError(errorStr: String?) {
try {
val error = Gson().fromJson(errorStr, Error::class.java)
if (error.redirectUrl.isNullOrEmpty()) {
val intent = Intent(context, FloatingService::class.java)
intent.action = FloatingService.ACTION_SHOW_NOTIFICATION
intent.putExtra(FloatingService.EXTRA_MESSAGE, error.message)
intent.putExtra(FloatingService.EXTRA_POSITIVE_BUTTON_TEXT, "我知道了")
context?.startService(intent)
} else {
val context = context ?: return
val uri = Uri.parse(error.redirectUrl)
val codeUrl = uri.buildUpon()
.appendQueryParameter(
"token",
AuthDelegate.getAuthResponseFromPref(context)?.accessToken
)
.build()
.toString()
(parentFragment?.parentFragment as? BaseFragment)?.start(
KugouQRCodeFragment.newInstance(
error.title,
error.message,
error.qrCodeMessage,
error.redirectUrl
)
)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun getMediaApi(): MediaApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(MediaApi::class.java)
} else {
null
}
}
override fun onDestroy() {
super.onDestroy()
launcher?.getService()?.getAudioPlayer()?.removeListener(this)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.impl.alarm
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.util.Log
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.audio.AudioAttributes
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.iflytek.cyber.iot.show.core.impl.audioplayer.MediaSourceFactory
class AlarmPlayerInstance(context: Context) {
private val player = ExoPlayerFactory.newSimpleInstance(
context,
DefaultRenderersFactory(context),
DefaultTrackSelector(),
DefaultLoadControl()
)
private val mMediaSourceFactory: MediaSourceFactory
private val type = "Alarm"
private val audioAttributes = AudioAttributes.Builder()
.setContentType(C.CONTENT_TYPE_SONIFICATION)
.setUsage(C.USAGE_ALARM)
.build()
private var listener: OnAlarmStateChangeListener? = null
private var onStartSent = false
init {
player.addListener(object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
Log.d(type, "onPlayerStateChanged($playWhenReady, $playbackState)")
when (playbackState) {
Player.STATE_IDLE -> {
if (!playWhenReady) {
listener?.onStopped()
}
}
Player.STATE_BUFFERING -> {
}
Player.STATE_READY -> {
if (!onStartSent) {
onStartSent = true
if (playWhenReady)
listener?.onStarted()
}
}
Player.STATE_ENDED -> {
listener?.onStopped()
}
}
}
override fun onPlayerError(error: ExoPlaybackException?) {
playLocalAlarm()
}
})
mMediaSourceFactory = MediaSourceFactory(context)
player.audioAttributes = audioAttributes
player.playWhenReady = false
player.volume = 0.5f
}
fun setOnAlarmStateChangeListener(listener: OnAlarmStateChangeListener) {
this.listener = listener
}
fun removeOnAlarmStateChangeListener() {
listener = null
}
fun play(url: String) {
onStartSent = false
Handler(player.applicationLooper).post {
val uri = Uri.parse(url)
val mediaSource = mMediaSourceFactory.createHttpMediaSource(uri)
player.playWhenReady = true
player.prepare(mediaSource, true, false)
}
}
fun isPlaying(): Boolean {
return player.playbackState == Player.STATE_READY && player.playWhenReady
}
fun playLocalAlarm() {
// todo
}
fun stop() {
Handler(player.applicationLooper).post {
player.playWhenReady = false
player.stop()
}
}
interface OnAlarmStateChangeListener {
fun onStarted()
fun onStopped()
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent.impl
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.iflytek.cyber.evs.sdk.agent.AppAction
import com.iflytek.cyber.evs.sdk.utils.AppUtil
class AppActionImpl(private val context: Context) : AppAction() {
override fun getSupportedExecute(): List<String> {
return listOf(DATA_TYPE_ACTIVITY, DATA_TYPE_BROADCAST, DATA_TYPE_SERVICE)
}
override fun check(payload: JSONObject): JSONObject {
val checkId = payload.getString(KEY_CHECK_ID)
val actionArray: JSONArray = payload.getJSONArray(KEY_ACTIONS) as JSONArray
val resultPayload = JSONObject()
resultPayload[KEY_CHECK_ID] = checkId
val resultArray = JSONArray()
for (i in 0 until actionArray.size) {
val action = actionArray[i] as JSONObject
val actionId = action.getString(KEY_ACTION_ID)
val data = action.getJSONObject(KEY_DATA)
val pkgName = data.getString(KEY_PACKAGE_NAME)
val uri = data.getString(KEY_URI)
val supported = AppUtil.isPackageExist(context, pkgName, uri)
val checkResult = JSONObject()
checkResult[KEY_ACTION_ID] = actionId
checkResult[KEY_RESULT] = supported
resultArray.add(checkResult)
}
resultPayload[KEY_ACTIONS] = resultArray
return resultPayload
}
override fun execute(payload: JSONObject, result: JSONObject): Boolean {
val executeId = payload.getString(KEY_EXECUTION_ID)
val actionArray = payload.getJSONArray(KEY_ACTIONS)
var isSuccess = false
var errorLevel = 0
for (i in 0 until actionArray.size) {
try {
val action = actionArray[i] as JSONObject
val actionId = action.getString(KEY_ACTION_ID)
val data = action.getJSONObject(KEY_DATA)
val type = data.getString(KEY_TYPE)
val pkgName = data.getString(KEY_PACKAGE_NAME)
val actionName = data.getString(KEY_ACTION_NAME)
val className = data.getString(KEY_CLASS_NAME)
val uri = data.getString(KEY_URI)
val categoryName = data.getString(KEY_CATEGORY_NAME)
val extras = data.getJSONObject(KEY_EXTRAS)
val version = data.getJSONObject(KEY_VERSION)
var ver_start = 0
var ver_end = Int.MAX_VALUE
if (version != null) {
ver_start = version.getIntValue(KEY_START)
ver_end = version.getIntValue(KEY_END)
}
if (!pkgName.isNullOrEmpty()) {
val appInfo = AppUtil.getAppInfo(context, pkgName)
if (appInfo == null) {
// 不存在对应的app
if (errorLevel < FAILURE_LEVEL_APP_NOT_FOUND) {
errorLevel = FAILURE_LEVEL_APP_NOT_FOUND
}
continue
} else {
if (appInfo.version in ver_start..ver_end) {
} else {
// 版本不符合,暂时当不存在app处理
if (errorLevel < FAILURE_LEVEL_APP_NOT_FOUND) {
errorLevel = FAILURE_LEVEL_APP_NOT_FOUND
}
continue
}
}
}
val intent: Intent? = if (actionName.isNullOrEmpty()) {
if (uri.isNullOrEmpty()) {
if (className.isNullOrEmpty()) {
context.packageManager.getLaunchIntentForPackage(pkgName)
} else {
Intent()
}
} else {
Intent.parseUri(uri, 0)
}
} else {
Intent(actionName)
}
if (!pkgName.isNullOrEmpty()) {
intent?.setPackage(pkgName)
}
if (!className.isNullOrEmpty()) {
intent?.setClassName(pkgName, className)
}
if (!categoryName.isNullOrEmpty()) {
intent?.addCategory(categoryName)
}
if (!uri.isNullOrEmpty()) {
intent?.run {
if (this.data == null) {
this.data = Uri.parse(uri)
}
}
}
if (!extras.isNullOrEmpty()) {
for (key: String in extras.keys) {
when (val value = extras[key]) {
is Int -> {
intent?.putExtra(key, value)
}
is String -> {
intent?.putExtra(key, value)
}
is Double -> {
intent?.putExtra(key, value)
}
is Boolean -> {
intent?.putExtra(key, value)
}
is Long -> {
// may not happen
intent?.putExtra(key, value)
}
is Float -> {
// may not happen
intent?.putExtra(key, value)
}
is Short -> {
// may not happen
intent?.putExtra(key, value)
}
is List<*> -> {
if (value.isNotEmpty()) {
@Suppress("UNCHECKED_CAST")
when (value[0]) {
is Int -> {
(value as? List<Int>)?.toTypedArray()?.let {
val array = IntArray(it.size) { index ->
it[index]
}
intent?.putExtra(key, array)
}
}
is Byte -> {
// may not happen
(value as? List<Byte>)?.toTypedArray()?.let {
val array = ByteArray(it.size) { index ->
it[index]
}
intent?.putExtra(key, array)
}
}
is Float -> {
// may not happen
(value as? List<Float>)?.toTypedArray()?.let {
val array = FloatArray(it.size) { index ->
it[index]
}
intent?.putExtra(key, array)
}
}
is Double -> {
(value as? List<Double>)?.toTypedArray()?.let {
val array = DoubleArray(it.size) { index ->
it[index]
}
intent?.putExtra(key, array)
}
}
is String -> {
(value as? List<String>)?.toTypedArray()?.let {
intent?.putExtra(key, it)
}
}
is Short -> {
// may not happen
(value as? List<Short>)?.toTypedArray()?.let {
val array = ShortArray(it.size) { index ->
it[index]
}
intent?.putExtra(key, array)
}
}
is Boolean -> {
// may not happen
(value as? List<Boolean>)?.toTypedArray()?.let {
val array = BooleanArray(it.size) { index ->
it[index]
}
intent?.putExtra(key, array)
}
}
}
}
}
else -> {
intent?.putExtra(key, extras.getString(key))
}
}
}
}
if (!type.isNullOrEmpty() && intent != null) {
if (!AppUtil.isActionSupported(context, intent, type)) {
if (type != DATA_TYPE_BROADCAST) {
// 不支持action
if (errorLevel < FAILURE_LEVEL_ACTION_UNSUPPORTED) {
errorLevel = FAILURE_LEVEL_ACTION_UNSUPPORTED
}
continue
}
}
}
when (type) {
DATA_TYPE_SERVICE -> {
context.startService(intent)
isSuccess = true
}
DATA_TYPE_BROADCAST -> {
context.sendBroadcast(intent)
isSuccess = true
}
else -> {
// 打开app
if (intent == null) {
if (errorLevel < FAILURE_LEVEL_INTERNAL_ERROR) {
errorLevel = FAILURE_LEVEL_INTERNAL_ERROR
}
} else {
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
isSuccess = true
}
}
}
if (isSuccess) {
result[KEY_ACTION_ID] = actionId
return true
}
} catch (t: Throwable) {
t.printStackTrace()
errorLevel = FAILURE_LEVEL_ACTION_UNSUPPORTED
}
}
// 执行失败
result[KEY_EXECUTION_ID] = executeId
result[KEY_FAILURE_CODE] = codeMap[errorLevel]
return false
}
override fun getForegroundApp(): AppUtil.AppInfo? {
return AppUtil.getForegroundApp(context)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.AlbumAdapter
import com.iflytek.cyber.iot.show.core.adapter.SpacesItemDecoration
import com.iflytek.cyber.iot.show.core.api.MediaApi
import com.iflytek.cyber.iot.show.core.model.Group
import com.iflytek.cyber.iot.show.core.model.GroupItem
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MediaSectionListFragment : BaseFragment(), PageScrollable {
companion object {
fun instance(id: String, typeName: String?): MediaSectionListFragment {
return MediaSectionListFragment().apply {
arguments = bundleOf(
Pair("id", id),
Pair("type", "SECTION"),
Pair("name", typeName)
)
}
}
fun instance(
group: Group,
abbr: String?,
typeName: String? = null
): MediaSectionListFragment {
return MediaSectionListFragment().apply {
arguments = bundleOf(
Pair("group", group),
Pair("type", if (typeName == null) "MUSIC" else "SECTION"),
Pair("abbr", abbr),
Pair("name", typeName)
)
}
}
}
private lateinit var title: TextView
private lateinit var sectionList: RecyclerView
private var albumAdapter: AlbumAdapter? = null
private var name: String? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return LayoutInflater.from(context)
.inflate(R.layout.fragment_media_section_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back).setOnClickListener { pop() }
sectionList = view.findViewById(R.id.section_list)
title = view.findViewById(R.id.title)
val type = arguments?.getString("type")
val group = arguments?.getParcelable<Group>("group")
val id = arguments?.getString("id")
val abbr = arguments?.getString("abbr")
name = arguments?.getString("name")
if (TextUtils.equals(type, "MUSIC")) {
title.text = abbr
val items = findAnchorList(abbr, group?.items)
setupRecyclerView(items)
} else if (TextUtils.equals(type, "SECTION")) {
if (group != null) {
title.text = group.name
setupRecyclerView(group.items)
} else {
id?.let { getMediaSections(it) }
}
}
}
private fun setupRecyclerView(items: List<GroupItem>?) {
albumAdapter = AlbumAdapter()
val horizontalSpacing = sectionList.context.resources.getDimensionPixelSize(R.dimen.dp_20)
val itemDecoration = SpacesItemDecoration(horizontalSpacing)
itemDecoration.left = 0
itemDecoration.right = 0
sectionList.addItemDecoration(itemDecoration)
if (TextUtils.equals(name, "视频")) {
albumAdapter?.itemViewType = AlbumAdapter.TYPE_RECTANGLE
} else {
albumAdapter?.itemViewType = AlbumAdapter.TYPE_SQUARE
}
albumAdapter?.onGroupItemClickListener = object : AlbumAdapter.OnGroupItemClickListener {
override fun onGroupItemClick(itemView: View, groupItem: GroupItem) {
start(SongListFragment.instance(groupItem.id, groupItem.name, name))
}
}
albumAdapter?.setGroupList(items)
sectionList.adapter = albumAdapter
}
private fun getMediaSections(id: String) {
getMediaApi()?.getMediaSection(id)?.enqueue(object : Callback<Group> {
override fun onFailure(call: Call<Group>, t: Throwable) {
t.printStackTrace()
}
override fun onResponse(call: Call<Group>, response: Response<Group>) {
if (response.isSuccessful) {
val item = response.body()
title.text = item?.name
item?.let { setupRecyclerView(it.items) }
}
}
})
}
private fun findAnchorList(title: String?, items: ArrayList<GroupItem>?): ArrayList<GroupItem> {
val list = ArrayList<GroupItem>()
items?.forEach {
if (TextUtils.equals(it.categoryName, title)) {
list.add(it)
}
}
return list
}
private fun getMediaApi(): MediaApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(MediaApi::class.java)
} else {
null
}
}
override fun scrollToNext(): Boolean {
sectionList.let { recyclerView ->
val lastItem =
(recyclerView.layoutManager as? LinearLayoutManager)?.findLastCompletelyVisibleItemPosition()
val itemCount = albumAdapter?.itemCount ?: 0
if (lastItem == itemCount - 1 || itemCount == 0) {
return false
} else {
recyclerView.smoothScrollBy(0, recyclerView.height)
}
}
return true
}
override fun scrollToPrevious(): Boolean {
sectionList.let { recyclerView ->
val scrollY = recyclerView.computeVerticalScrollOffset()
val itemCount = albumAdapter?.itemCount
if (scrollY == 0 || itemCount == 0) {
return false
} else {
recyclerView.smoothScrollBy(0, -recyclerView.height)
}
}
return true
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat
import com.iflytek.cyber.iot.show.core.R
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
class BoxedHorizontal : View {
/**
* The min value of progress value.
*/
private var mMin = MIN
/**
* The Maximum value that this SeekArc can be set to
*/
private var mMax = MAX
var isEnable = true
/**
* mTouchDisabled touches will not move the slider
* only swipe motion will activate it
*/
private var mTouchDisabled = true
private var mProgressSweep = 0f
private var mProgressPaint: Paint? = null
private var mOnValuesChangeListener: OnValuesChangeListener? = null
private var customBackgroundColor: Int = 0
private var mDefaultValue: Int = 0
private val mPaint = Paint()
private var mPath: Path? = null
var value: Int = 0
set(value) {
field = value
updateProgressByValue(getPointsByValue(value), false)
}
var max: Int = MAX
get() = mMax
set(value) {
if (value <= mMin)
throw IllegalArgumentException("Max should not be less than zero")
this.mMax = value
field = value
}
var min: Int = MIN
get() = mMin
set(value) {
if (value >= max)
throw IllegalArgumentException("Min should not be bigger than max value")
mMin = value
field = value
}
/**
* The corner radius of the view.
*/
var cornerRadius: Int = 10
set(value) {
field = value
if (width > 0 && height > 0) {
mPath = Path()
mPath?.addRoundRect(
RectF(0f, 0f, width.toFloat(), height.toFloat()),
field.toFloat(), field.toFloat(), Path.Direction.CCW
)
invalidate()
}
}
var defaultValue: Int
get() = mDefaultValue
set(mDefaultValue) {
if (mDefaultValue > mMax)
throw IllegalArgumentException("Default value should not be bigger than max value.")
this.mDefaultValue = mDefaultValue
}
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
isClickable = true
isFocusable = true
// Defaults, may need to link this into theme settings
var progressColor = ContextCompat.getColor(context, R.color.slide_progress)
customBackgroundColor = ContextCompat.getColor(context, R.color.slide_background)
customBackgroundColor = ContextCompat.getColor(context, R.color.slide_background)
mDefaultValue = mMax / 2
if (attrs != null) {
val a = context.obtainStyledAttributes(
attrs,
R.styleable.BoxedHorizontal, 0, 0
)
mMax = a.getInteger(R.styleable.BoxedHorizontal_bh_max, mMax)
mMin = a.getInteger(R.styleable.BoxedHorizontal_bh_min, mMin)
mDefaultValue = a.getInteger(R.styleable.BoxedHorizontal_bh_defaultValue, mDefaultValue)
value = a.getInteger(R.styleable.BoxedHorizontal_bh_points, mDefaultValue)
cornerRadius =
a.getDimensionPixelSize(R.styleable.BoxedHorizontal_bh_cornerRadius, cornerRadius)
progressColor = a.getColor(R.styleable.BoxedHorizontal_bh_progressColor, progressColor)
customBackgroundColor =
a.getColor(R.styleable.BoxedHorizontal_bh_backgroundColor, customBackgroundColor)
isEnable = a.getBoolean(R.styleable.BoxedHorizontal_bh_enabled, isEnable)
mTouchDisabled =
a.getBoolean(R.styleable.BoxedHorizontal_bh_touchDisabled, mTouchDisabled)
a.recycle()
}
// range check
value = if (value > mMax) mMax else value
value = if (value < mMin) mMin else value
val progressPaint = Paint()
progressPaint.color = progressColor
progressPaint.isAntiAlias = true
progressPaint.style = Paint.Style.STROKE
mProgressPaint = progressPaint
mPaint.alpha = 255
mPaint.color = customBackgroundColor
mPaint.isAntiAlias = true
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mProgressPaint?.strokeWidth = h.toFloat()
mPath = Path()
mPath?.addRoundRect(
RectF(0f, 0f, width.toFloat(), height.toFloat()),
cornerRadius.toFloat(), cornerRadius.toFloat(), Path.Direction.CCW
)
}
override fun onDraw(canvas: Canvas) {
canvas.translate(0f, 0f)
mPath?.let { path ->
canvas.clipPath(path)
}
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), mPaint)
mProgressPaint?.let { paint ->
if (isInEditMode) {
val progress = getPointsByValue(defaultValue)
//convert min-max range to progress
val sweep = ((progress - mMin) * width / (mMax - mMin)).toFloat()
canvas.drawLine(0f, (height / 2).toFloat(), sweep, (height / 2).toFloat(), paint)
} else {
canvas.drawLine(
0f,
(height / 2).toFloat(),
mProgressSweep,
(height / 2).toFloat(),
paint
)
}
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
if (isEnable) {
this.parent.requestDisallowInterceptTouchEvent(true)
when (event.action) {
MotionEvent.ACTION_DOWN -> {
mOnValuesChangeListener?.onStartTrackingTouch(this)
if (!mTouchDisabled)
updateOnTouch(event)
}
MotionEvent.ACTION_MOVE -> updateOnTouch(event)
MotionEvent.ACTION_UP -> {
updateOnTouch(event)
mOnValuesChangeListener?.onStopTrackingTouch(this)
isPressed = false
this.parent.requestDisallowInterceptTouchEvent(false)
}
MotionEvent.ACTION_CANCEL -> {
mOnValuesChangeListener?.onStopTrackingTouch(this)
isPressed = false
this.parent.requestDisallowInterceptTouchEvent(false)
}
}
return true
}
return false
}
/**
* Update the UI components on touch events.
*
* @param event MotionEvent
*/
private fun updateOnTouch(event: MotionEvent) {
isPressed = true
val mTouch = convertTouchEventPoint(event.x)
val progress = mTouch.roundToInt()
updateProgress(progress)
}
private fun convertTouchEventPoint(xPos: Float): Double {
return when {
xPos > width * 2 -> (width * 2).toDouble()
xPos < 0 -> 0.0
else -> xPos.toDouble()
}
}
private fun updateProgress(progress: Int) {
val realProgress = max(0, min(width, progress))
mProgressSweep = realProgress.toFloat()
//reverse value because progress is descending
mProgressSweep = width - mProgressSweep
//convert progress to min-max range
value = realProgress * (mMax - mMin) / width + mMin
mOnValuesChangeListener?.onPointsChanged(this, value, true)
if (width > 0 && height > 0) {
mPath = Path()
mPath?.addRoundRect(
RectF(0f, 0f, width.toFloat(), height.toFloat()),
cornerRadius.toFloat(), cornerRadius.toFloat(), Path.Direction.CCW
)
invalidate()
}
}
/**
* Gets a value, converts it to progress for the seekBar and updates it.
* @param value The value given
*/
private fun updateProgressByValue(value: Int, fromTouch: Boolean = true) {
//convert min-max range to progress
mProgressSweep = ((value - mMin) * width / (mMax - mMin)).toFloat()
mOnValuesChangeListener?.onPointsChanged(this, value, fromTouch)
if (width > 0 && height > 0) {
mPath = Path()
mPath?.addRoundRect(
RectF(0f, 0f, width.toFloat(), height.toFloat()),
cornerRadius.toFloat(), cornerRadius.toFloat(), Path.Direction.CCW
)
invalidate()
}
}
private fun getPointsByValue(value: Int): Int {
return max(mMin, min(mMax, value))
}
interface OnValuesChangeListener {
/**
* Notification that the point value has changed.
*
* @param boxedPoints The SwagPoints view whose value has changed
* @param points The current point value.
* @param fromTouch Is this callback from touch event
*/
fun onPointsChanged(boxedPoints: BoxedHorizontal, points: Int, fromTouch: Boolean)
fun onStartTrackingTouch(boxedPoints: BoxedHorizontal)
fun onStopTrackingTouch(boxedPoints: BoxedHorizontal)
}
fun setOnBoxedPointsChangeListener(onValuesChangeListener: OnValuesChangeListener) {
mOnValuesChangeListener = onValuesChangeListener
}
companion object {
private val TAG = BoxedHorizontal::class.java.simpleName
private const val MAX = 100
private const val MIN = 0
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.iflytek.cyber.iot.show.core.R
class BannerFragment2 : BaseFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.item_video_banner, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import com.jaredrummler.apkparser.ApkParser
import com.jaredrummler.apkparser.BuildConfig
import java.io.File
import kotlin.Exception
object PackageUtils {
fun checkIfLatest(context: Context, filePath: String?): Boolean {
filePath ?: return false
try {
val apkParser = ApkParser.create(filePath)
val meta = apkParser.apkMeta
if (meta.packageName != context.packageName)
return false
return BuildConfig.VERSION_CODE <= meta.versionCode
} catch (e: Exception) {
return false
}
}
fun notifyInstallApk(context: Context, filePath: String) {
try {
val install = Intent(Intent.ACTION_VIEW)
install.flags = Intent.FLAG_ACTIVITY_NEW_TASK
val apkFile = File(filePath)
val uri = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
Uri.fromFile(apkFile)
} else {
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
FileProvider.getUriForFile(context, "${context.packageName}.fileProvider", apkFile)
}
install.setDataAndType(uri, "application/vnd.android.package-archive")
context.applicationContext.startActivity(install)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import androidx.customview.widget.ViewDragHelper
import com.iflytek.cyber.iot.show.core.R
class ControlPanel @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private var panel: View? = null
private var panelBackground: View? = null
var onReleaseCallback: OnReleaseCallback? = null
var onInterceptTouchListener: OnTouchListener? = null
private val mDragger: ViewDragHelper =
ViewDragHelper.create(this, 1f, object : ViewDragHelper.Callback() {
private var currentY = 0
private var currentX = 0
override fun onViewPositionChanged(
changedView: View,
left: Int,
top: Int,
dx: Int,
dy: Int
) {
super.onViewPositionChanged(changedView, left, top, dx, dy)
currentX = left
currentY = top
}
override fun tryCaptureView(child: View, pointerId: Int): Boolean {
return panel == child
}
override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int): Int {
return 0
}
override fun clampViewPositionVertical(child: View, top: Int, dy: Int): Int {
return Math.min(top, 0)
}
override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
super.onViewReleased(releasedChild, xvel, yvel)
if (releasedChild == panel) {
onReleaseCallback?.onRelease(releasedChild, currentX, currentY)?.let { result ->
if (!result) {
getDragger().settleCapturedViewAt(0, 0)
invalidate()
}
}
}
}
override fun getViewHorizontalDragRange(child: View): Int {
return measuredWidth - child.measuredWidth
}
override fun getViewVerticalDragRange(child: View): Int {
return measuredHeight - child.measuredHeight
}
})
init {
mDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_TOP)
}
private fun getDragger() = mDragger
override fun onFinishInflate() {
super.onFinishInflate()
panel = findViewById(R.id.panel_area)
panelBackground = findViewById(R.id.panel_background)
}
override fun computeScroll() {
if (mDragger.continueSettling(true)) {
invalidate()
}
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
onInterceptTouchListener?.onTouch(this, ev)
return mDragger.shouldInterceptTouchEvent(ev)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
mDragger.processTouchEvent(event)
return true
}
override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
if (event?.action == MotionEvent.ACTION_DOWN) {
if (event.keyCode == KeyEvent.KEYCODE_BACK) {
onReleaseCallback?.onRequestRelease()
}
}
return super.dispatchKeyEvent(event)
}
interface OnReleaseCallback {
fun onRelease(panel: View?, x: Int, y: Int): Boolean
fun onRequestRelease()
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
class SpacesItemDecoration(private val space: Int) : RecyclerView.ItemDecoration() {
var left = -1
var right = -1
var bottom = -1
var top = -1
override fun getItemOffsets(outRect: Rect, view: View,
parent: RecyclerView, state: RecyclerView.State) {
val left = if (left != -1) left else space / 2
val right = if (right != -1) right else space / 2
val bottom = if (bottom != -1) bottom else space / 2
val top = if (top != -1) top else space / 2
// Add top margin only for the first item to avoid double space between result
val layoutManager = parent.layoutManager as GridLayoutManager
val spanCount = layoutManager.spanCount
val position = parent.getChildLayoutPosition(view)
val childCount = parent.adapter?.itemCount ?: 0
outRect.top = top
outRect.left = left
outRect.right = right
outRect.bottom = bottom
if (position < spanCount) {
// 第一横排
outRect.top = 0
}
if (position >= childCount - 3) {
// 最后横排
outRect.bottom = 0
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.core.widget.NestedScrollView
class TouchNestedScrollView : NestedScrollView {
interface OnCustomTouchListener {
fun onTouchEvent(ev: MotionEvent?)
}
constructor(context: Context): super(context)
constructor(context: Context, attrs: AttributeSet): super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int): super(context, attrs, defStyleAttr)
private var customTouchListener: OnCustomTouchListener? = null
fun setOnCustomTouchListener(listener: OnCustomTouchListener?) {
customTouchListener = listener
}
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
customTouchListener?.onTouchEvent(ev)
return super.dispatchTouchEvent(ev)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import com.airbnb.lottie.LottieAnimationView
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.MediaApi
import com.iflytek.cyber.iot.show.core.model.CollectionV3
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class CollectionListFragment : BaseFragment() {
companion object {
fun newInstance(tagId: Int): CollectionListFragment {
return CollectionListFragment().apply {
arguments = bundleOf(Pair("tagId", tagId))
}
}
}
private lateinit var singleTag: TextView
private lateinit var albumTag: TextView
private lateinit var retryFrame: LinearLayout
private lateinit var loadingImage: LottieAnimationView
private var collectionSingleFragment: CollectionSingleFragment? = null
private var collectionAlbumFragment: CollectionAlbumFragment? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_collection_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
singleTag = view.findViewById(R.id.single_tag)
albumTag = view.findViewById(R.id.album_tag)
singleTag.setOnClickListener {
singleTag.isSelected = true
albumTag.isSelected = false
if (collectionSingleFragment != null) {
showHideFragment(collectionSingleFragment!!)
}
}
albumTag.setOnClickListener {
albumTag.isSelected = true
singleTag.isSelected = false
if (collectionAlbumFragment != null) {
showHideFragment(collectionAlbumFragment!!)
}
}
retryFrame = view.findViewById(R.id.retry_frame)
loadingImage = view.findViewById(R.id.loading_image)
val tagId = arguments?.getInt("tagId")
view.findViewById<View>(R.id.retry).setOnClickListener {
retryFrame.isVisible = false
loadingImage.isVisible = true
if (tagId != null) {
getCollection(tagId)
}
}
singleTag.isSelected = true
}
override fun onLazyInitView(savedInstanceState: Bundle?) {
super.onLazyInitView(savedInstanceState)
val tagId = arguments?.getInt("tagId")
if (tagId != null) {
getCollection(tagId)
}
}
private fun setupFragment(collectionV3: CollectionV3, tagId: Int) {
collectionSingleFragment = CollectionSingleFragment()
collectionSingleFragment?.setItems(collectionV3.single.collections, tagId)
collectionAlbumFragment = CollectionAlbumFragment()
collectionAlbumFragment?.setItems(collectionV3.album.collections, tagId)
loadMultipleRootFragment(R.id.fragment, 0, collectionSingleFragment!!, collectionAlbumFragment!!)
}
private fun getCollection(tagId: Int) {
loadingImage.isVisible = true
loadingImage.playAnimation()
getMediaApi()?.getCollection(tagId)?.enqueue(object : Callback<CollectionV3> {
override fun onResponse(call: Call<CollectionV3>, response: Response<CollectionV3>) {
if (!isAdded || context == null) {
return
}
loadingImage.isVisible = false
loadingImage.pauseAnimation()
if (response.isSuccessful) {
retryFrame.isVisible = false
val collectionV3 = response.body()
if (collectionV3 != null) {
setupFragment(collectionV3, tagId)
}
} else {
retryFrame.isVisible = true
}
}
override fun onFailure(call: Call<CollectionV3>, t: Throwable) {
t.printStackTrace()
retryFrame.isVisible = true
loadingImage.isVisible = false
loadingImage.pauseAnimation()
}
})
}
private fun getMediaApi(): MediaApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(MediaApi::class.java)
} else {
null
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.iflytek.cyber.evs.sdk.socket.Result
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.EngineService
import com.iflytek.cyber.iot.show.core.FloatingService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.MediaSectionAdapter
import com.iflytek.cyber.iot.show.core.api.MediaApi
import com.iflytek.cyber.iot.show.core.model.Group
import com.iflytek.cyber.iot.show.core.model.SongList
import kotlinx.android.synthetic.main.item_app.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
class MediaSectionFragment : BaseFragment() {
companion object {
fun newInstance(name: String?, groups: List<Group>): MediaSectionFragment {
return MediaSectionFragment().apply {
arguments = bundleOf(
Pair("name", name),
Pair("groups", groups)
)
}
}
}
private lateinit var sectionList: RecyclerView
private var placeholderView: View? = null
private var mediaSectionAdapter: MediaSectionAdapter? = null
private var requestingGroupId: String? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return LayoutInflater.from(context).inflate(R.layout.fragment_music, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
sectionList = view.findViewById(R.id.section_list)
placeholderView = view.findViewById(R.id.placeholder)
sectionList.postDelayed({
hidePlaceholder()
}, 200)
}
override fun onLazyInitView(savedInstanceState: Bundle?) {
super.onLazyInitView(savedInstanceState)
val name = arguments?.getString("name")
val groups = arguments?.getParcelableArrayList<Group>("groups")
if (name.isNullOrEmpty() || groups == null) {
return
}
mediaSectionAdapter = MediaSectionAdapter(name, groups, {
requestingGroupId = it.id
getMediaApi()?.getSongList(it.id, 1, SongListFragment.LIMIT)?.enqueue(object :
Callback<SongList> {
override fun onFailure(call: Call<SongList>, t: Throwable) {
if (requestingGroupId != it.id)
return
if (t is UnknownHostException) {
val intent = Intent(EngineService.ACTION_SEND_REQUEST_FAILED)
intent.putExtra(
EngineService.EXTRA_RESULT,
Result(Result.CODE_DISCONNECTED, null)
)
context?.sendBroadcast(intent)
}
}
override fun onResponse(call: Call<SongList>, response: Response<SongList>) {
if (requestingGroupId != it.id)
return
if (response.isSuccessful) {
val songList = response.body() ?: return
(parentFragment as BaseFragment).start(
SongListFragment.instance(songList, name)
)
} else {
val disconnectNotification =
Intent(context, FloatingService::class.java)
disconnectNotification.action = FloatingService.ACTION_SHOW_NOTIFICATION
disconnectNotification.putExtra(
FloatingService.EXTRA_MESSAGE,
"请求出错,请稍后再试"
)
disconnectNotification.putExtra(
FloatingService.EXTRA_ICON_RES,
R.drawable.ic_default_error_white_40dp
)
disconnectNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_TEXT,
getString(R.string.i_got_it)
)
context?.startService(disconnectNotification)
}
}
})
}, { position ->
val groupId = groups[position].id
requestingGroupId = groupId
getMediaApi()?.getMediaSection(groupId)?.enqueue(object :
Callback<Group> {
override fun onFailure(call: Call<Group>, t: Throwable) {
if (requestingGroupId != groupId)
return
if (t is UnknownHostException) {
val intent = Intent(EngineService.ACTION_SEND_REQUEST_FAILED)
intent.putExtra(
EngineService.EXTRA_RESULT,
Result(Result.CODE_DISCONNECTED, null)
)
context?.sendBroadcast(intent)
}
}
override fun onResponse(call: Call<Group>, response: Response<Group>) {
if (requestingGroupId != groupId)
return
if (response.isSuccessful) {
val group = response.body() ?: return
(parentFragment as BaseFragment).start(
MediaSectionListFragment.instance(group, null, name)
)
} else {
val disconnectNotification =
Intent(context, FloatingService::class.java)
disconnectNotification.action = FloatingService.ACTION_SHOW_NOTIFICATION
disconnectNotification.putExtra(
FloatingService.EXTRA_MESSAGE,
"请求出错,请稍后再试"
)
disconnectNotification.putExtra(
FloatingService.EXTRA_ICON_RES,
R.drawable.ic_default_error_white_40dp
)
disconnectNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_TEXT,
getString(R.string.i_got_it)
)
context?.startService(disconnectNotification)
}
}
})
})
sectionList.adapter = mediaSectionAdapter
}
private fun hidePlaceholder() {
placeholderView?.let { placeholder ->
placeholder.animate().alpha(0f).setDuration(350)
.withEndAction {
placeholder.isVisible = false
}
.start()
}
}
private fun getMediaApi(): MediaApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(MediaApi::class.java)
} else {
null
}
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent
import com.alibaba.fastjson.JSONObject
import com.iflytek.cyber.evs.sdk.RequestCallback
import com.iflytek.cyber.evs.sdk.RequestManager
/**
* 播放控制模块,详细介绍见https://doc.iflyos.cn/device/evs/reference/playback_controller.html#%E6%92%AD%E6%94%BE%E6%8E%A7%E5%88%B6
*/
abstract class PlaybackController {
val version = "1.0"
companion object {
const val NAME_CONTROL_COMMAND = "playback_controller.control_command"
const val KEY_TYPE = "type"
}
/**
* 发送控制命令。
* @param command 命令
*/
fun sendCommand(command: Command, requestCallback: RequestCallback? = null) {
val payload = JSONObject()
when (command) {
Command.Exit -> payload[KEY_TYPE] = "EXIT"
Command.Next -> payload[KEY_TYPE] = "NEXT"
Command.Pause -> payload[KEY_TYPE] = "PAUSE"
Command.Previous -> payload[KEY_TYPE] = "PREVIOUS"
Command.Resume -> payload[KEY_TYPE] = "RESUME"
}
RequestManager.sendRequest(NAME_CONTROL_COMMAND, payload, requestCallback, true)
}
/**
* 控制命令。
*/
enum class Command {
Exit, // 恢复
Next, // 下一个
Pause, // 暂停
Previous, // 上一个
Resume, // 恢复
}
}<file_sep>package com.iflytek.cyber.product.ota
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
import java.util.*
data class ReportEntity(val pids: List<Long>) {
companion object {
fun from(manifests: List<ManifestEntity>): ReportEntity {
val pids = ArrayList<Long>()
manifests.map {
pids.add(it.id)
}
return ReportEntity(pids)
}
fun from(manifest: ManifestEntity): ReportEntity {
return ReportEntity(listOf(manifest.id))
}
}
}
data class PackageEntity(val id: Long, val revision: Long, val identity: String, val url: String)
@Parcelize
data class PackageEntityNew(
val id: Long?,
val identity: String?,
@SerializedName("version_id") val versionId: String?,
@SerializedName("version_name") val versionName: String?,
val description: String?,
val url: String?
) : Parcelable
data class ManifestEntity(val id: Long, val revision: Long, val identity: String) {
companion object {
fun from(pkg: PackageEntity): ManifestEntity {
return ManifestEntity(pkg.id, pkg.revision, pkg.identity)
}
}
}
data class VersionCodeAndId(val versionCode: Int, val pid: Long)
data class VersionCodeMap(val set: Set<VersionCodeAndId>)<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.Group
import com.iflytek.cyber.iot.show.core.model.GroupItem
class MediaSectionAdapter(private val name: String,
private val items: List<Group>,
private val onItemClickListener: (GroupItem) -> Unit,
private val onMoreClickListener: (Int) -> Unit) : RecyclerView.Adapter<MediaSectionAdapter.MediaSectionHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaSectionHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_category, parent, false)
return MediaSectionHolder(view)
}
override fun getItemCount(): Int {
return items.size
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: MediaSectionHolder, position: Int) {
val item = items[position]
holder.title.text = item.name
holder.more.text = "全部${item.name}"
holder.desc.text = item.descriptions[(Math.random() * item.descriptions.size - 1).toInt()]
val newItems = if (item.items != null && item.items.size > 4) {
item.items.subList(0, 4)
} else {
item.items
}
holder.setAlbumList(name, newItems, object : AlbumAdapter.OnGroupItemClickListener {
override fun onGroupItemClick(itemView: View, groupItem: GroupItem) {
onItemClickListener.invoke(groupItem)
}
})
holder.moreContent.setOnClickListener {
onMoreClickListener.invoke(position)
}
}
class MediaSectionHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val title = itemView.findViewById<TextView>(R.id.category_title)
val desc = itemView.findViewById<TextView>(R.id.category_desc)
val albumList = itemView.findViewById<RecyclerView>(R.id.album_list)
val more = itemView.findViewById<TextView>(R.id.more)
val moreContent = itemView.findViewById<LinearLayout>(R.id.more_content)
val adapter = AlbumAdapter()
fun setAlbumList(name: String, albumList: List<GroupItem>?, onGroupItemClickListener: AlbumAdapter.OnGroupItemClickListener) {
if (TextUtils.equals(name, "视频")) {
adapter.itemViewType = AlbumAdapter.TYPE_RECTANGLE
} else {
adapter.itemViewType = AlbumAdapter.TYPE_SQUARE
}
adapter.setGroupList(albumList)
adapter.onGroupItemClickListener = onGroupItemClickListener
this.albumList.adapter = adapter
}
}
}<file_sep>package com.iflytek.cyber.evs.sdk.focus
import android.os.Handler
import com.iflytek.cyber.evs.sdk.utils.Log
object AudioFocusManager {
const val CHANNEL_OUTPUT = "OUTPUT"
const val CHANNEL_DIAL = "DIAL"
const val CHANNEL_INPUT = "INPUT"
const val CHANNEL_ALARM = "ALARM"
const val CHANNEL_CONTENT = "CONTENT"
private const val TAG = "AudioFocusManager"
internal const val TYPE_SOUND = "Sound" // 提示音
internal const val TYPE_TTS = "Tts"
internal const val TYPE_RECOGNIZE = "Recognize" // 识别
internal const val TYPE_RECOGNIZE_V = "RecognizeV" // 评测模式
internal const val TYPE_RING = "Ring"
internal const val TYPE_ALARM = "Alarm"
internal const val TYPE_PLAYBACK = "Playback"
internal const val TYPE_VIDEO = "Video" // 视频播放器
internal const val TYPE_EXTERNAL_VIDEO = "ExternalVideo" // 外部视频播放器
private val latestForegroundMap = HashMap<String, String>() // <channel, type>
private val statusMap = HashMap<String, FocusStatus>() // <channel, status>
private var audioFocusObserver: AudioFocusObserver? = null
private val handler = Handler()
internal val sortedChannels = arrayOf(
CHANNEL_OUTPUT,
CHANNEL_DIAL,
CHANNEL_INPUT,
CHANNEL_ALARM,
CHANNEL_CONTENT
)
private val priorityMap = HashMap<String, Int>()
init {
priorityMap[CHANNEL_OUTPUT] = 10
priorityMap[CHANNEL_DIAL] = 20
priorityMap[CHANNEL_INPUT] = 30
priorityMap[CHANNEL_ALARM] = 40
priorityMap[CHANNEL_CONTENT] = 50
}
internal fun setFocusObserver(observerAudio: AudioFocusObserver) {
this.audioFocusObserver = observerAudio
}
internal fun removeFocusObserver() {
this.audioFocusObserver = null
}
private fun findForegroundChannel(): String? {
for (channel in sortedChannels) {
if (statusMap[channel] == FocusStatus.Foreground) {
return channel
}
}
return null
}
private fun findBackgroundChannel(): String? {
for (channel in sortedChannels) {
if (statusMap[channel] == FocusStatus.Background) {
return channel
}
}
return null
}
private fun comparePriority(channel1: String, channel2: String): Int {
return (priorityMap[channel1]!! - priorityMap[channel2]!!)
}
// 为channel下某type请求活动焦点
internal fun requestActive(activeChannel: String, type: String) {
val tid = Thread.currentThread().id
Log.d(TAG, "requestActive tid=$tid, activeChannel=$activeChannel, type=$type")
// 若请求的channel处于非前景状态,或者type对不上
if (statusMap[activeChannel] != FocusStatus.Foreground ||
type != latestForegroundMap[activeChannel]
) {
if (statusMap[activeChannel] == FocusStatus.Background &&
type != latestForegroundMap[activeChannel]
) {
statusMap[activeChannel] = FocusStatus.Idle
onInternalFocusChanged(activeChannel)
}
val foreChannel = findForegroundChannel()
if (foreChannel == null) {
statusMap[activeChannel] = FocusStatus.Foreground
} else {
if (activeChannel == foreChannel) {
// activeChannel正处于前景
if (latestForegroundMap[foreChannel] != type) {
statusMap[foreChannel] = FocusStatus.Idle
onInternalFocusChanged(foreChannel)
statusMap[activeChannel] = FocusStatus.Foreground
}
} else {
when (foreChannel) {
CHANNEL_OUTPUT -> {
when (activeChannel) {
CHANNEL_DIAL,
CHANNEL_INPUT,
CHANNEL_ALARM -> {
statusMap[foreChannel] = FocusStatus.Idle
onInternalFocusChanged(foreChannel)
statusMap[activeChannel] = FocusStatus.Foreground
}
CHANNEL_CONTENT -> {
statusMap[activeChannel] = FocusStatus.Background
}
}
}
CHANNEL_DIAL -> {
// 通话通道在活跃,其他通道都不能抢焦点
statusMap[activeChannel] = FocusStatus.Idle
}
CHANNEL_INPUT -> {
when (activeChannel) {
CHANNEL_ALARM -> {
statusMap[foreChannel] = FocusStatus.Idle
onInternalFocusChanged(foreChannel)
statusMap[activeChannel] = FocusStatus.Foreground
}
}
}
CHANNEL_ALARM -> {
if (activeChannel == CHANNEL_OUTPUT || activeChannel == CHANNEL_INPUT) {
statusMap[foreChannel] = FocusStatus.Idle
onInternalFocusChanged(foreChannel)
statusMap[activeChannel] = FocusStatus.Foreground
} else {
statusMap[activeChannel] = FocusStatus.Background
}
}
CHANNEL_CONTENT -> {
if (activeChannel == CHANNEL_CONTENT) {
if (latestForegroundMap[foreChannel] != type) {
statusMap[foreChannel] = FocusStatus.Idle
onInternalFocusChanged(foreChannel)
}
} else {
statusMap[foreChannel] = FocusStatus.Background
onInternalFocusChanged(foreChannel)
}
statusMap[activeChannel] = FocusStatus.Foreground
}
// else -> {
// var backChannel = findBackgroundChannel()
// val result = comparePriority(foreChannel, activeChannel)
//
// if (result > 0) {
// // activeChannel优先级更高
// if (backChannel != null) {
// statusMap[backChannel] = FocusStatus.Idle
// onInternalFocusChanged(backChannel)
// }
//
// statusMap[foreChannel] = FocusStatus.Background
// onInternalFocusChanged(foreChannel)
//
// statusMap[activeChannel] = FocusStatus.Foreground
// } else {
// // foreChannel优先级更高
// if (backChannel != null) {
// if (backChannel == activeChannel) {
// if (latestForegroundMap[backChannel] != type) {
// statusMap[backChannel] = FocusStatus.Idle
// onInternalFocusChanged(backChannel)
// }
// } else {
// statusMap[backChannel] = FocusStatus.Idle
// onInternalFocusChanged(backChannel)
// }
// }
//
// statusMap[activeChannel] = FocusStatus.Background
// }
// }
}
}
}
// var findTarget = false
// for (i in 0 until sortedChannels.size) {
// val channel = sortedChannels[i]
//
// // 若channel处于前景状态,且当前channel不是请求的channel
// if (statusMap[channel] == FocusStatus.Foreground &&
// channel != activeChannel
// ) {
// if (findTarget) {
// if (channel == CHANNEL_ALARM) {
// statusMap[channel] = FocusStatus.Idle
// } else {
// // 直接置为背景
// statusMap[channel] = FocusStatus.Background
// }
// onInternalFocusChanged(channel) // 只需更新被挤掉的
// } else {
// // 当前前景通道(即channel)优先级高,需要区分对待
// when (activeChannel) {
// CHANNEL_OUTPUT -> {
// if (channel == CHANNEL_ALARM) {
// // 若闹钟通道活跃,直接停止
// statusMap[channel] = FocusStatus.Idle
// onInternalFocusChanged(channel)
// } else {
// statusMap[channel] = FocusStatus.Background
// onInternalFocusChanged(channel)
// }
// statusMap[activeChannel] = FocusStatus.Foreground
// }
// CHANNEL_DIAL,
// CHANNEL_INPUT -> {
// if (channel == CHANNEL_OUTPUT) {
// // 设备提示音/TTS 活跃则直接停掉
// statusMap[channel] = FocusStatus.Idle
// onInternalFocusChanged(channel)
// } else {
// statusMap[activeChannel] = FocusStatus.Background
// }
// }
// CHANNEL_ALARM -> {
// if (channel == CHANNEL_OUTPUT) {
// statusMap[channel] = FocusStatus.Idle
// onInternalFocusChanged(channel)
//
// statusMap[activeChannel] = FocusStatus.Foreground
// } else {
// statusMap[activeChannel] = FocusStatus.Background
// }
// }
// CHANNEL_CONTENT -> {
// // 不存在比 Content 更低的优先级
// statusMap[activeChannel] = FocusStatus.Background
// }
// }
// }
// } else if (channel == activeChannel) { // 设置请求的channel
// findTarget = true
// if (statusMap[activeChannel] != FocusStatus.Foreground) {
// statusMap[activeChannel] = FocusStatus.Foreground
// } else {
// // 当前channel的前景类型不是type
// if (latestForegroundMap[channel] != type) {
// statusMap[channel] = FocusStatus.Idle
// onInternalFocusChanged(channel)
//
// statusMap[activeChannel] = FocusStatus.Foreground
// }
// }
// }
// }
// 保证在可置为背景的前景通道通知完后,才通知想要激活的通道
latestForegroundMap[activeChannel] = type
onInternalFocusChanged(activeChannel)
}
}
fun isManageableChannel(channel: String) = sortedChannels.contains(channel)
// 释放channel下某type的焦点
internal fun requestAbandon(abandonChannel: String, @Suppress("UNUSED_PARAMETER") type: String) {
val tid = Thread.currentThread().id
Log.d(TAG, "tid=$tid, abandonChannel=$abandonChannel, type=$type")
when {
latestForegroundMap[abandonChannel] != type ->
Log.w(TAG, "Target type: $type is already abandoned, ignore this operation.")
statusMap[abandonChannel] != FocusStatus.Idle -> {
// 将状态置为丢失焦点
statusMap[abandonChannel] = FocusStatus.Idle
// onInternalFocusChanged(abandonChannel)
latestForegroundMap.remove(abandonChannel)
for (channel in sortedChannels) {
if (statusMap[channel] == FocusStatus.Background) {
// 将某个背景的 channel 置为前景
statusMap[channel] = FocusStatus.Foreground
onInternalFocusChanged(channel)
return
}
}
}
}
}
private fun onInternalFocusChanged(channel: String) {
try {
val type = latestForegroundMap[channel] ?: return
val status = statusMap[channel] ?: return
audioFocusObserver?.onAudioFocusChanged(channel, type, status)
} catch (e: Exception) {
e.printStackTrace()
}
}
interface AudioFocusObserver {
fun onAudioFocusChanged(channel: String, type: String, status: FocusStatus)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import androidx.recyclerview.widget.RecyclerView
import com.iflytek.cyber.iot.show.core.utils.OnLoadMoreListener
inline fun RecyclerView.onLoadMore(crossinline action: () -> Unit) {
this.addOnScrollListener(OnLoadMoreListener(object : OnLoadMoreListener.Callback {
override fun onLoadMore() {
action.invoke()
}
}))
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.annotation.SuppressLint
import com.iflytek.cyber.iot.show.core.model.DateEntity
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
class DateUtils {
companion object {
fun stringToDate(strDate: String): Date {
val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE)
return sdf.parse(strDate)
}
fun stringToDate(pattern: String, strDate: String): Date {
val sdf = SimpleDateFormat(pattern, Locale.CHINESE)
return sdf.parse(strDate)
}
fun dateToStr(pattern: String, date: Date): String {
val sdf = SimpleDateFormat(pattern, Locale.CHINESE)
return sdf.format(date)
}
fun getHourList(): ArrayList<String> {
val hourList = ArrayList<String>()
for (hour in 0..23) {
hourList.add("${hour}时")
}
return hourList
}
fun getMinList(): ArrayList<String> {
val minList = ArrayList<String>()
for (min in 0..59) {
minList.add(String.format("%02d分", min))
}
return minList
}
fun getMonthList(): ArrayList<String> {
val monthList = ArrayList<String>()
for (month in 1..31) {
monthList.add("${month}日")
}
return monthList
}
@SuppressLint("SimpleDateFormat")
fun getDateList(start: String, end: String, type: String): ArrayList<DateEntity> {
val dates = ArrayList<DateEntity>()
val df1 = SimpleDateFormat("yyyy-MM-dd")
var date1: Date? = null
var date2: Date? = null
try {
date1 = df1.parse(start)
date2 = df1.parse(end)
} catch (e: ParseException) {
e.printStackTrace()
}
val cal1 = Calendar.getInstance()
cal1.time = date1
val cal2 = Calendar.getInstance()
cal2.time = date2
while (!cal1.after(cal2)) {
dates.add(DateEntity(cal1.time, type))
cal1.add(Calendar.DATE, 1)
}
return dates
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.annotation.SuppressLint
import android.database.ContentObserver
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import com.airbnb.lottie.LottieAnimationView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.BrightnessUtils
import com.iflytek.cyber.iot.show.core.utils.ScreenOffTimeoutUtils
import com.iflytek.cyber.iot.show.core.widget.BoxedHorizontal
import java.util.concurrent.TimeUnit
import kotlin.math.max
import kotlin.math.min
class ScreenBrightnessFragment : BaseFragment(), View.OnClickListener, PageScrollable {
private var brightnessSlider: BoxedHorizontal? = null
private lateinit var oneMinSleep: TextView
private lateinit var twoMinSleep: TextView
private lateinit var fiveMinSleep: TextView
private lateinit var tenMinSleep: TextView
private lateinit var neverSleep: TextView
private lateinit var tvSleepTips: TextView
private lateinit var tvSleepEnableTips: TextView
private var scrollView: ScrollView? = null
private var contentContainer: LinearLayout? = null
private var selectedViewList = ArrayList<TextView>()
private var backCount = 0
private val brightnessObserver = object : ContentObserver(Handler()) {
override fun onChange(selfChange: Boolean, uri: Uri) {
val context = context ?: return
if (BRIGHTNESS_MODE_URI == uri) {
val mode = BrightnessUtils.getBrightnessMode(context)
if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
brightnessSlider?.let { slider ->
slider.isEnable = true
}
} else {
val currentBrightness = BrightnessUtils.getBrightness(context)
brightnessSlider?.let { slider ->
if (!slider.isPressed) {
slider.isEnable = true
slider.value = currentBrightness
}
}
view?.findViewById<LottieAnimationView>(R.id.brightness_icon)?.let { icon ->
icon.progress = currentBrightness / 100f
}
}
} else if (BRIGHTNESS_URI == uri) {
val currentBrightness = BrightnessUtils.getBrightness(context)
brightnessSlider?.let { slider ->
if (!slider.isPressed) {
slider.isEnable = true
slider.value = currentBrightness
}
}
view?.findViewById<LottieAnimationView>(R.id.brightness_icon)?.let { icon ->
icon.progress = currentBrightness / 100f
}
}
}
}
companion object {
private val BRIGHTNESS_MODE_URI =
Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE)
private val BRIGHTNESS_URI = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS)
val ONE_SLEEP_TIME: Long = TimeUnit.MINUTES.toMillis(1)
val TWO_SLEEP_TIME: Long = TimeUnit.MINUTES.toMillis(2)
val FIVE_SLEEP_TIME: Long = TimeUnit.MINUTES.toMillis(5)
val TEN_SLEEP_TIME: Long = TimeUnit.MINUTES.toMillis(10)
val DEFAULT_SLEEP_TIME: Long = TEN_SLEEP_TIME
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
try {
context?.contentResolver?.let { cr ->
cr.registerContentObserver(BRIGHTNESS_MODE_URI, false, brightnessObserver)
cr.registerContentObserver(BRIGHTNESS_URI, false, brightnessObserver)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_screen_brightness, container, false)
}
@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
scrollView = view.findViewById(R.id.scroll_view)
contentContainer = view.findViewById(R.id.content_container)
oneMinSleep = view.findViewById(R.id.one_min_sleep)
oneMinSleep.setOnClickListener(this)
twoMinSleep = view.findViewById(R.id.two_min_sleep)
twoMinSleep.setOnClickListener(this)
fiveMinSleep = view.findViewById(R.id.five_min_sleep)
fiveMinSleep.setOnClickListener(this)
tenMinSleep = view.findViewById(R.id.ten_min_sleep)
tenMinSleep.setOnClickListener(this)
neverSleep = view.findViewById(R.id.never_sleep)
neverSleep.setOnClickListener(this)
selectedViewList.add(oneMinSleep)
selectedViewList.add(twoMinSleep)
selectedViewList.add(fiveMinSleep)
selectedViewList.add(tenMinSleep)
selectedViewList.add(neverSleep)
tvSleepTips = view.findViewById(R.id.tv_sleep_tips)
tvSleepEnableTips = view.findViewById(R.id.tv_sleep_enable_tips)
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
brightnessSlider = view.findViewById(R.id.brightness_slider)
brightnessSlider?.setOnBoxedPointsChangeListener(object :
BoxedHorizontal.OnValuesChangeListener {
override fun onPointsChanged(
boxedPoints: BoxedHorizontal,
points: Int,
fromTouch: Boolean
) {
if (BrightnessUtils.hasPermission(context) && !fromTouch) {
BrightnessUtils.setBrightness(context, points)
view.findViewById<LottieAnimationView>(R.id.brightness_icon)?.let { icon ->
icon.progress = points / 100f
}
}
}
override fun onStartTrackingTouch(boxedPoints: BoxedHorizontal) {
}
override fun onStopTrackingTouch(boxedPoints: BoxedHorizontal) {
}
})
post {
updateBrightness()
}
}
private fun updatePref() {
val context = context ?: return
val sleepTime = ScreenOffTimeoutUtils.getTimeout(context)
when {
sleepTime == ScreenOffTimeoutUtils.ONE_MIN_TIMEOUT -> {
tvSleepTips.text =
launcher?.getString(R.string.sleep_tips, oneMinSleep.text.toString())
oneMinSleep.isSelected = true
updateSelectState(oneMinSleep)
}
sleepTime == ScreenOffTimeoutUtils.TWO_MIN_TIMEOUT -> {
tvSleepTips.text =
launcher?.getString(R.string.sleep_tips, twoMinSleep.text.toString())
twoMinSleep.isSelected = true
updateSelectState(twoMinSleep)
}
sleepTime == ScreenOffTimeoutUtils.FIVE_MIN_TIMEOUT -> {
tvSleepTips.text =
launcher?.getString(R.string.sleep_tips, fiveMinSleep.text.toString())
fiveMinSleep.isSelected = true
updateSelectState(fiveMinSleep)
}
sleepTime == ScreenOffTimeoutUtils.TEN_MIN_TIMEOUT -> {
tvSleepTips.text =
launcher?.getString(R.string.sleep_tips, tenMinSleep.text.toString())
tenMinSleep.isSelected = true
updateSelectState(tenMinSleep)
}
sleepTime == ScreenOffTimeoutUtils.NEVER_TIMEOUT -> {
tvSleepTips.text = null
// switchScreenTimeoutContent.isVisible = false
neverSleep.isSelected = true
updateSelectState(neverSleep)
}
}
}
private fun updateSelectState(selected: TextView) {
selectedViewList.forEach {
if (selected != it) {
it.isSelected = false
}
}
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.ten_min_sleep -> {
ScreenOffTimeoutUtils.setTimeout(v.context, ScreenOffTimeoutUtils.TEN_MIN_TIMEOUT)
updatePref()
}
R.id.five_min_sleep -> {
ScreenOffTimeoutUtils.setTimeout(v.context, ScreenOffTimeoutUtils.FIVE_MIN_TIMEOUT)
updatePref()
}
R.id.two_min_sleep -> {
ScreenOffTimeoutUtils.setTimeout(v.context, ScreenOffTimeoutUtils.TWO_MIN_TIMEOUT)
updatePref()
}
R.id.one_min_sleep -> {
ScreenOffTimeoutUtils.setTimeout(v.context, ScreenOffTimeoutUtils.ONE_MIN_TIMEOUT)
updatePref()
}
R.id.never_sleep -> {
ScreenOffTimeoutUtils.setTimeout(v.context, ScreenOffTimeoutUtils.NEVER_TIMEOUT)
updatePref()
}
}
}
override fun onDestroy() {
super.onDestroy()
context?.contentResolver?.unregisterContentObserver(brightnessObserver)
}
private fun updateBrightness() {
context?.let { context ->
val currentBrightness = BrightnessUtils.getBrightness(context)
val mode = BrightnessUtils.getBrightnessMode(context)
brightnessSlider?.let { slider ->
slider.isEnable = mode != Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
slider.value = currentBrightness
}
view?.findViewById<LottieAnimationView>(R.id.brightness_icon)?.let { icon ->
icon.progress = currentBrightness / 100f
}
}
}
override fun onSupportVisible() {
super.onSupportVisible()
updatePref()
}
override fun scrollToNext(): Boolean {
scrollView?.let { scrollView ->
val pageHeight = scrollView.height
val scrollY = scrollView.scrollY
val contentHeight = contentContainer?.height ?: 0
if (scrollY == contentHeight - pageHeight) {
return false
}
val target = min(contentHeight - pageHeight, scrollY + pageHeight)
smoothScrollTo(target)
return true
} ?: run {
return false
}
}
override fun scrollToPrevious(): Boolean {
scrollView?.let { scrollView ->
val pageHeight = scrollView.height
val scrollY = scrollView.scrollY
if (scrollY == 0) {
return false
}
val target = max(0, scrollY - pageHeight)
smoothScrollTo(target)
return true
} ?: run {
return false
}
}
private fun smoothScrollTo(scrollY: Int) {
scrollView?.isSmoothScrollingEnabled = true
scrollView?.smoothScrollTo(0, scrollY)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.CollectionAlbumAdapter
import com.iflytek.cyber.iot.show.core.model.CollectionSong
import com.kk.taurus.playerbase.utils.NetworkUtils
class CollectionAlbumFragment : BaseFragment() {
private lateinit var emptyContent: LinearLayout
private lateinit var recyclerView: RecyclerView
private var adapter: CollectionAlbumAdapter? = null
private var items = ArrayList<CollectionSong>()
private var tagId: Int = -1
fun setItems(items: ArrayList<CollectionSong>, tagId: Int) {
this.tagId = tagId
this.items.clear()
this.items.addAll(items)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragement_collection_media, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view.findViewById(R.id.recycler_view)
emptyContent = view.findViewById(R.id.empty_content)
}
override fun onLazyInitView(savedInstanceState: Bundle?) {
super.onLazyInitView(savedInstanceState)
adapter = CollectionAlbumAdapter {
if (isAdded && context != null && !NetworkUtils.isNetConnected(context)) {
Toast.makeText(context, "网络连接异常,请重新设置", Toast.LENGTH_SHORT).show()
return@CollectionAlbumAdapter
}
(parentFragment?.parentFragment as? BaseFragment)?.start(SongListFragment.newInstance(it, 1))
}
adapter?.items = items
recyclerView.adapter = adapter
if (items.isEmpty()) {
emptyContent.isVisible = true
recyclerView.isVisible = false
} else {
emptyContent.isVisible = false
recyclerView.isVisible = true
}
}
override fun onSupportVisible() {
super.onSupportVisible()
adapter?.notifyDataSetChanged()
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent.impl
import android.content.Context
import android.os.Handler
import android.util.Log
import android.view.SurfaceView
import com.google.android.exoplayer2.ExoPlaybackException
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.ui.PlayerView
import com.iflytek.cyber.evs.sdk.agent.VideoPlayer
import java.lang.Thread.sleep
class VideoPlayerImpl : VideoPlayer {
companion object {
private const val TAG = "VideoPlayerImpl"
}
private var player: VideoPlayerInstance? = null
var volGrowFlag = false
constructor(context: Context) {
player?.destroy()
player = VideoPlayerInstance(context)
player?.setListener(listener)
}
constructor(context: Context, playerView: PlayerView) {
initPlayer(context, playerView)
}
private val listener = object : VideoPlayerInstance.Listener {
private var playWhenReady = false
private var lastPlayState = -1
fun initState() {
playWhenReady = false
lastPlayState = -1
}
override fun onPlayerStateChanged(
player: VideoPlayerInstance,
playWhenReady: Boolean,
playbackState: Int
) {
Log.d(TAG, "onPlayerStateChanged($playWhenReady, $playbackState)")
val isPlayingChanged = this.playWhenReady != playWhenReady
this.playWhenReady = playWhenReady
when (playbackState) {
Player.STATE_ENDED -> {
player.isStarted = false
if (playWhenReady)
onCompleted(player.resourceId ?: "")
}
Player.STATE_BUFFERING -> {
// ignore
}
Player.STATE_IDLE -> {
player.isStarted = false
if (!playWhenReady) {
onStopped(player.resourceId ?: "")
}
}
Player.STATE_READY -> {
if (lastPlayState == Player.STATE_BUFFERING) {
if (playWhenReady) {
if (!player.isStarted) {
player.isStarted = true
onStarted(player.resourceId ?: "")
} else {
onResumed(player.resourceId ?: "")
}
}
} else {
if (isPlayingChanged) {
if (playWhenReady) {
onResumed(player.resourceId ?: "")
} else {
onPaused(player.resourceId ?: "")
}
}
}
}
}
lastPlayState = playbackState
}
override fun onPlayerPositionUpdated(player: VideoPlayerInstance, position: Long) {
onPositionUpdated(player.resourceId ?: "", position)
}
override fun onPlayerError(player: VideoPlayerInstance, error: ExoPlaybackException?) {
val errorCode: String = when (error?.type) {
ExoPlaybackException.TYPE_UNEXPECTED -> {
MEDIA_ERROR_UNKNOWN
}
ExoPlaybackException.TYPE_SOURCE -> {
MEDIA_ERROR_INVALID_REQUEST
}
ExoPlaybackException.TYPE_REMOTE -> {
MEDIA_ERROR_SERVICE_UNAVAILABLE
}
ExoPlaybackException.TYPE_RENDERER -> {
MEDIA_ERROR_INTERNAL_SERVER_ERROR
}
ExoPlaybackException.TYPE_OUT_OF_MEMORY -> {
MEDIA_ERROR_INTERNAL_DEVICE_ERROR
}
else -> {
MEDIA_ERROR_UNKNOWN
}
}
onError(player.resourceId ?: "", errorCode)
}
}
private fun initPlayer(context: Context, playerView: PlayerView) {
player?.destroy()
player = VideoPlayerInstance(context, playerView)
player?.setListener(listener)
}
private fun getPlayer(): VideoPlayerInstance? {
return player
}
fun setVideoSurfaceView(surfaceView: SurfaceView) {
getPlayer()?.setVideoSurfaceView(surfaceView)
}
override fun play(resourceId: String, url: String): Boolean {
Log.d(TAG, "try to play $url on video player")
val player = getPlayer()
player?.let {
listener.initState()
it.resourceId = resourceId
it.isStarted = false
it.play(url)
return true
} ?: run {
return false
}
}
override fun resume(): Boolean {
val player = getPlayer()
player?.resume() ?: run {
return false
}
return true
}
override fun pause(): Boolean {
val player = getPlayer()
player?.pause() ?: run {
return false
}
return true
}
override fun stop(): Boolean {
val player = getPlayer()
player?.stop() ?: run {
return false
}
return true
}
override fun exit(): Boolean {
val player = getPlayer()
player?.stop() ?: run {
return false
}
return true
}
override fun seekTo(offset: Long): Boolean {
super.seekTo(offset)
val player = getPlayer()
player?.let {
it.seekTo(offset)
return true
} ?: run {
return false
}
}
override fun getOffset(): Long {
return getPlayer()?.getOffset() ?: 0
}
override fun getDuration(): Long {
return getPlayer()?.getDuration() ?: 0
}
override fun moveToBackground(): Boolean {
getPlayer()?.run {
synchronized(volGrowFlag) {
volGrowFlag = false
val targetVolume = .1f
Handler(getLooper()).post {
setVolume(targetVolume)
}
}
return true
} ?: run {
return false
}
}
override fun moveToForegroundIfAvailable(): Boolean {
getPlayer()?.run {
synchronized(volGrowFlag) {
volGrowFlag = true
}
val volume = getVolume()
val targetVolume = 1f
Thread {
var nextVolume = volume
val step = 0.05f
while (volGrowFlag && nextVolume != targetVolume) {
nextVolume =
if (nextVolume + step > targetVolume) targetVolume else nextVolume + step
try {
sleep(30)
} catch (_: Exception) {
//ignore
}
synchronized(volGrowFlag) {
if (volGrowFlag) {
Handler(getLooper()).post {
setVolume(nextVolume)
}
} else {
return@Thread
}
}
}
}.start()
return true
} ?: run {
return false
}
}
}<file_sep>//
// Created by huang on 2019/1/25.
//
#ifndef IVWENGINEDEMO_LOG_H
#define IVWENGINEDEMO_LOG_H
#include <android/log.h>
#define LOG_TAG "ivw"
#define LOG_D(...) do {\
if (isLogOn()) {\
__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__);\
}\
} while(false)
#define LOG_E(...) do {\
if (true) { \
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__); \
} \
} while (false)
bool isLogOn();
void setLog(bool isOn);
#endif //IVWENGINEDEMO_LOG_H
<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core
import android.Manifest
import android.app.AlarmManager
import android.app.IntentService
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.content.PermissionChecker
import org.apache.commons.net.ntp.NTPUDPClient
import org.apache.commons.net.ntp.TimeInfo
import java.net.InetAddress
import java.util.*
import java.util.concurrent.TimeUnit
/**
* 时间同步服务,需要有 SET_TIME 权限才能设置成功
*/
class TimeService : IntentService("time") {
override fun onHandleIntent(intent: Intent?) {
val client = NTPUDPClient()
client.defaultTimeout = TimeUnit.SECONDS.toMillis(10).toInt()
try {
client.open()
val info = client.getTime(InetAddress.getByName(NTP_SERVER))
handleResponse(info)
Log.d(TAG, "Time sync done")
} catch (e: Exception) {
Log.w(TAG, "Failed syncing time", e)
}
}
private fun handleResponse(info: TimeInfo) {
val message = info.message
val time = message.transmitTimeStamp
Log.d(TAG, "Current time is " + Date().toString())
Log.d(TAG, "Setting time to " + time.date.toString())
if (PermissionChecker.checkSelfPermission(this, Manifest.permission.SET_TIME)
== PermissionChecker.PERMISSION_GRANTED) {
val alarm = getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarm.setTime(time.time)
}
}
companion object {
private const val TAG = "TimeService"
private const val NTP_SERVER = "time1.aliyun.com" // 使用阿里云的时间同步接口
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.alibaba.fastjson.JSON
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.AlbumSectionContentAdapter
import com.iflytek.cyber.iot.show.core.adapter.TemplateAppAlbumAdapter
import com.iflytek.cyber.iot.show.core.adapter.TemplateAppMediaAdapter
import com.iflytek.cyber.iot.show.core.api.AppApi
import com.iflytek.cyber.iot.show.core.impl.prompt.PromptManager
import com.iflytek.cyber.iot.show.core.model.*
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.widget.StyledProgressDialog
import com.kk.taurus.playerbase.utils.NetworkUtils
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
class TemplateCategoryContentFragment : Fragment() {
companion object {
const val TAG = "TemplateCategoryContentFragment"
private const val LIMIT = 20
fun newInstance(
templateApp: TemplateApp,
category: String,
initialMediaList: List<MediaItem>? = null,
initialAlbumList: List<AlbumItem>? = null,
justMedia: Boolean = false
): TemplateCategoryContentFragment {
val fragment = TemplateCategoryContentFragment()
fragment.templateApp = templateApp
fragment.category = category
initialMediaList?.let {
fragment.mediaList.addAll(it)
}
initialAlbumList?.let {
fragment.albumList.addAll(it)
}
fragment.justMedia = justMedia
return fragment
}
fun newInstance(
templateApp: TemplateApp,
sourceItem: SourceItem?
): TemplateCategoryContentFragment {
val fragment = TemplateCategoryContentFragment()
fragment.templateApp = templateApp
fragment.sourceItem = sourceItem
return fragment
}
}
private var templateApp: TemplateApp? = null
private var category: String? = null
private val mediaList = mutableListOf<MediaItem>()
private val albumList = mutableListOf<AlbumItem>()
private var sourceItem: SourceItem? = null
private var justMedia = false
private val albumSectionContentAdapter = AlbumSectionContentAdapter()
private var page = 1
private var totalListSize = 0
private var recyclerView: RecyclerView? = null
private var loading: LottieAnimationView? = null
private var loadingBottom: LottieAnimationView? = null
private var tvError: TextView? = null
private var tvRetry: TextView? = null
private var errorRetry: View? = null
private var errorContainer: View? = null
private var loadingCenter: LottieAnimationView? = null
private var progressDialog: StyledProgressDialog? = null
private var isLoading = false
private var isLoadComplete = false
private val onScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (isLoadComplete || isLoading) return
val itemCount = recyclerView.adapter?.itemCount
(recyclerView.layoutManager as? GridLayoutManager)?.let {
if (it.findLastCompletelyVisibleItemPosition() == it.findLastVisibleItemPosition() &&
itemCount == it.findLastVisibleItemPosition() + 1 &&
itemCount < totalListSize
) {
page++
//getCategoryContent()
getTemplateList()
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_template_category_content, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view.findViewById(R.id.template_category_content)
loading = view.findViewById(R.id.loading)
loadingBottom = view.findViewById(R.id.loading_bottom)
tvRetry = view.findViewById(R.id.tv_retry)
tvError = view.findViewById(R.id.tv_error)
errorContainer = view.findViewById(R.id.error_container)
errorRetry = view.findViewById(R.id.error_retry)
loadingCenter = view.findViewById(R.id.loading_center)
errorRetry?.setOnClickListener {
if (!isLoading) {
page = 1
getTemplateList()
}
}
recyclerView?.adapter = albumSectionContentAdapter
albumSectionContentAdapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: ViewGroup, itemView: View, position: Int) {
val albumItem = albumSectionContentAdapter.getAlbumItem(position)
val templateApp = templateApp ?: return
if (albumItem != null) {
if (albumItem.type == 1) {
(parentFragment as? BaseFragment)?.apply {
start(
TemplateApp1Fragment.newInstance(templateApp, sourceItem)
)
}
} else if (albumItem.type > 1) {
if (!albumItem.metadata?.resourceId.isNullOrEmpty()) {
postPlay(albumItem)
} else {
(parentFragment as? BaseFragment)?.apply {
start(
SongListFragment.newInstance(albumItem, 2, 1002)
)
}
}
}
}
}
}
recyclerView?.addOnScrollListener(onScrollListener)
setLayoutManager(1.0f)
applyTheme(templateApp?.isDark != false)
getTemplateList()
}
private fun setLayoutManager(ratio: Float) {
val layoutManager = if (ratio <= 1) {
GridLayoutManager(context, 5)
} else {
GridLayoutManager(context, 3)
}
recyclerView?.post {
recyclerView?.layoutManager = layoutManager
}
}
override fun onDestroy() {
super.onDestroy()
recyclerView?.removeOnScrollListener(onScrollListener)
}
private fun showError(message: String?, showRetry: Boolean = true) {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = false
errorContainer?.isVisible = true
errorRetry?.isVisible = showRetry
tvError?.text = message
}
private fun hideError() {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = true
errorContainer?.isVisible = false
}
private fun showLoading() {
if (isRemoving || isDetached)
return
context ?: return
if (page == 1) {
loading?.isVisible = true
loading?.repeatMode = LottieDrawable.RESTART
loading?.repeatCount = LottieDrawable.INFINITE
loading?.playAnimation()
} else {
loadingBottom?.isVisible = true
loadingBottom?.repeatMode = LottieDrawable.RESTART
loadingBottom?.repeatCount = LottieDrawable.INFINITE
loadingBottom?.playAnimation()
}
}
private fun hideLoading() {
if (isRemoving || isDetached)
return
context ?: return
if (loading?.isVisible == true) {
loading?.pauseAnimation()
loading?.isVisible = false
}
if (loadingBottom?.isVisible == true) {
loadingBottom?.pauseAnimation()
loadingBottom?.isVisible = false
}
}
private fun showProgress(title: String, message: String? = null) {
if (isRemoving || isDetached)
return
context ?: return
progressDialog = StyledProgressDialog.Builder()
.setTitle(title)
.setMessage(message)
.show(fragmentManager)
}
private fun dismissProgress() {
if (isRemoving || isDetached)
return
context ?: return
progressDialog?.let {
it.dismissAllowingStateLoss()
progressDialog = null
}
}
private fun getFirstItemCover(items: ArrayList<SourceItem>): String? {
var firstCover: String? = null
for (item in items) {
if (firstCover.isNullOrEmpty()) {
firstCover = item.cover
}
}
return firstCover
}
private fun getTemplateList() {
val templateApp = templateApp ?: return
val metaData = sourceItem?.metadata ?: return
isLoading = true
showLoading()
hideError()
getAppApi()?.getTemplateList(
templateApp.name,
metaData.topLevel,
metaData.secondLevel,
metaData.thirdLevel,
page
)?.enqueue(object : Callback<TemplateMediaItem> {
override fun onResponse(
call: Call<TemplateMediaItem>,
response: Response<TemplateMediaItem>
) {
if (isRemoving || isDetached || context == null) {
return
}
isLoading = false
if (response.isSuccessful) {
val templateMediaItem = response.body()
if (templateMediaItem != null) {
totalListSize = templateMediaItem.total
handleResult(templateMediaItem)
}
} else {
hideLoading()
if (albumSectionContentAdapter.itemCount == 0) {
showError("请求出错,请稍后重试")
}
}
}
override fun onFailure(call: Call<TemplateMediaItem>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
isLoading = false
hideLoading()
if (t is UnknownHostException) {
showError("Ooooops,请检查网络后重试")
} else {
showError("请求出错,请稍后重试")
}
}
})
}
private fun setRecyclerViewPadding() {
recyclerView?.let { recyclerView ->
recyclerView.post {
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
}
}
private fun handleResult(templateMediaItem: TemplateMediaItem) {
if (templateMediaItem.items == null) {
return
}
val firstCover = getFirstItemCover(templateMediaItem.items)
if (firstCover.isNullOrEmpty()) {
hideLoading()
setupAlbumList(1.0f, templateMediaItem.items)
return
}
Glide.with(this)
.asBitmap()
.load(firstCover)
.into(object : CustomTarget<Bitmap>() {
override fun onLoadCleared(placeholder: Drawable?) {
hideLoading()
}
override fun onLoadFailed(errorDrawable: Drawable?) {
super.onLoadFailed(errorDrawable)
hideLoading()
showError("请求出错,请稍后重试")
}
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
hideLoading()
val ratio = 1f * resource.width / resource.height
setupAlbumList(ratio, templateMediaItem.items)
}
})
}
private fun setupAlbumList(ratio: Float, items: ArrayList<SourceItem>) {
if (page == 1) {
setLayoutManager(ratio)
albumSectionContentAdapter.ratio = ratio
setRecyclerViewPadding()
albumSectionContentAdapter.setAlbumList(items)
} else {
albumSectionContentAdapter.appendAlbumList(items)
}
albumSectionContentAdapter.notifyDataSetChanged()
}
private fun postPlay(sourceItem: SourceItem) {
val audioId = sourceItem.metadata?.resourceId
val sourceType = sourceItem.metadata?.source
val business = sourceItem.metadata?.business
loadingCenter?.isVisible = true
loadingCenter?.playAnimation()
val json = com.alibaba.fastjson.JSONObject()
json["audio_id"] = audioId
json["source_type"] = sourceType
json["business"] = business
val requestBody = RequestBody.create(
MediaType.parse("application/json"),
json.toString()
)
getAppApi()?.postPlayMedia(requestBody)?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
loadingCenter?.isVisible = false
loadingCenter?.pauseAnimation()
Toast.makeText(context, "请求出错", Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (isRemoving || isDetached)
return
context ?: return
loadingCenter?.isVisible = false
loadingCenter?.pauseAnimation()
if (response.isSuccessful) {
Toast.makeText(context, "开始播放", Toast.LENGTH_SHORT).show()
} else {
response.errorBody()?.let { errorBody ->
val errorString = errorBody.string()
val errorJson = JSONObject(errorString)
if (errorJson.has("message")) {
Toast.makeText(
context,
errorJson.optString("message"),
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(context, "播放失败", Toast.LENGTH_SHORT).show()
}
errorBody.close()
} ?: run {
Toast.makeText(context, "播放失败", Toast.LENGTH_SHORT).show()
}
}
}
})
}
fun applyTheme(isDark: Boolean) {
if (isDark) {
loading?.setAnimation(R.raw.animation_loading_l_white)
loadingBottom?.setAnimation(R.raw.animation_loading_l_white)
} else {
loading?.setAnimation(R.raw.animation_loading_l)
loadingBottom?.setAnimation(R.raw.animation_loading_l)
}
albumSectionContentAdapter.isDark = isDark
if (albumSectionContentAdapter.itemCount != 0) {
albumSectionContentAdapter.notifyDataSetChanged()
}
tvError?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
tvRetry?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
errorRetry?.setBackgroundResource(
if (isDark) R.drawable.bg_round_border_white_36dp
else R.drawable.bg_round_border_black_36dp
)
}
private fun getAppApi(): AppApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(AppApi::class.java)
}
}<file_sep>package com.iflytek.cyber.evs.sdk.model
import android.os.Parcelable
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.annotation.JSONField
import kotlinx.android.parcel.Parcelize
@Parcelize
data class AuthResponse(
@JSONField(name = "access_token") val accessToken: String,
@JSONField(name = "created_at") val createdAt: Long,
@JSONField(name = "expires_in") val expiresIn: Long,
@JSONField(name = "refresh_token") val refreshToken: String,
@JSONField(name = "token_type") val tokenType: String
) : Parcelable {
fun toJSONString(): String {
return JSON.toJSONString(this)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
class HighLightUtils {
companion object {
fun highLightText(
str: String,
inputs: ArrayList<String>,
resStr: StringBuffer
): StringBuffer {
var index = str.length//用来做为标识,判断关键字的下标
var next = "" //保存str中最先找到的关键字
for (i in inputs.size - 1 downTo 0) {
val theNext = inputs[i]
val theIndex = str.indexOf(theNext)
if (theIndex == -1) {
inputs.removeAt(i)
} else {
index = theIndex
next = theNext
}
}
if (index == str.length) {
resStr.append(str)
} else {
resStr.append(str.substring(0, index))
resStr.append(
"<font color='#4C93D4'>" + str.substring(
index,
index + next.length
) + "</font>"
)
val str1 = str.substring(index + next.length, str.length)
highLightText(str1, inputs, resStr)
}
return resStr
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.graphics.Bitmap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.app.ActivityCompat
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.WriterException
import com.google.zxing.qrcode.QRCodeWriter
import com.iflytek.cyber.iot.show.core.R
import java.util.*
class KugouQRCodeFragment : BaseFragment() {
companion object {
const val EXTRA_TITLE = "text"
const val EXTRA_MESSAGE = "message"
const val EXTRA_QRCODE_MESSAGE = "qrcode_message"
const val EXTRA_URL = "url"
fun newInstance(
title: String?,
message: String?,
qrCodeMessage: String?,
url: String
): KugouQRCodeFragment {
val fragment = KugouQRCodeFragment()
val arguments = Bundle()
arguments.putString(EXTRA_TITLE, title)
arguments.putString(EXTRA_MESSAGE, message)
arguments.putString(EXTRA_QRCODE_MESSAGE, qrCodeMessage)
arguments.putString(EXTRA_URL, url)
fragment.arguments = arguments
return fragment
}
}
private var backCount = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_kugou_qrcode, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back)?.setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
view.findViewById<View>(R.id.cannot_use_phone)?.setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
val tvTitle = view.findViewById<TextView>(R.id.title)
val tvQrCodeMessage = view.findViewById<TextView>(R.id.message)
val ivQrCode = view.findViewById<ImageView>(R.id.qrcode)
arguments?.let { arguments ->
val title = arguments.getString(EXTRA_TITLE)
val message = arguments.getString(EXTRA_MESSAGE)
val qrCodeMessage = arguments.getString(EXTRA_QRCODE_MESSAGE)
val url = arguments.getString(EXTRA_URL)
tvTitle?.text = title ?: message
qrCodeMessage?.let {
tvQrCodeMessage?.text = qrCodeMessage
}
url?.let {
view.findViewById<View>(R.id.cannot_use_phone)?.setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
val webViewFragment = WebViewFragment()
val webArguments = Bundle()
webArguments.putString("url", url)
webViewFragment.arguments = webArguments
start(webViewFragment)
}
ivQrCode?.post {
Thread {
val bitmap = createQRBitmap(url, ivQrCode.width, ivQrCode.height)
ivQrCode.post {
ivQrCode.setImageBitmap(bitmap)
}
}.start()
}
}
}
}
private fun createQRBitmap(content: String, width: Int, height: Int): Bitmap? {
val context = context ?: return null
try {
val colorBlack = ActivityCompat.getColor(context, android.R.color.black)
val coloWhite = ActivityCompat.getColor(context, android.R.color.transparent)
// 设置二维码相关配置,生成BitMatrix(位矩阵)对象
val hints = Hashtable<EncodeHintType, String>()
hints[EncodeHintType.CHARACTER_SET] = "UTF-8" // 字符转码格式设置
hints[EncodeHintType.ERROR_CORRECTION] = "H" // 容错级别设置
hints[EncodeHintType.MARGIN] = "2" // 空白边距设置
val bitMatrix =
QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints)
// 创建像素数组,并根据BitMatrix(位矩阵)对象为数组元素赋颜色值
val pixels = IntArray(width * height)
for (y in 0 until height) {
for (x in 0 until width) {
if (bitMatrix.get(x, y)) {
pixels[y * width + x] = colorBlack // 黑色色块像素设置
} else {
pixels[y * width + x] = coloWhite // 白色色块像素设置
}
}
}
// 创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,之后返回Bitmap对象
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
return bitmap
} catch (e: WriterException) {
e.printStackTrace()
}
return null
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.WifiUtils
class WifiConnectFailedFragment : BaseFragment() {
companion object {
fun newInstance(
errorMessage: String? = null,
ssid: String? = null,
cancelText: String? = null,
retryText: String? = null
): WifiConnectFailedFragment {
val fragment = WifiConnectFailedFragment()
val arguments = Bundle()
arguments.putString("error", errorMessage)
arguments.putString("ssid", ssid)
arguments.putString("cancelText", cancelText)
arguments.putString("retryText", retryText)
fragment.arguments = arguments
return fragment
}
}
private var backCount = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_wifi_connect_failed, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val cancelText = arguments?.getString("cancelText")
val retryText = arguments?.getString("retryText")
val ssid = arguments?.getString("ssid")
if (cancelText.isNullOrEmpty() && retryText.isNullOrEmpty()) {
view.findViewById<View>(R.id.retry).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
view.findViewById<View>(R.id.cancel).setOnClickListener {
popTo(WifiSettingsFragment::class.java, false)
}
arguments?.getString("error")?.let { errorMessage ->
val tvMessage = view.findViewById<TextView>(R.id.error_text)
tvMessage?.text = errorMessage
}
} else if (!cancelText.isNullOrEmpty() && !retryText.isNullOrEmpty()) {
val retryTextView = view.findViewById<TextView>(R.id.retry)
retryTextView.text = retryText
retryTextView.setOnClickListener {
if (!ssid.isNullOrEmpty()) {
WifiUtils.forget(context, ssid)
}
popTo(WifiSettingsFragment::class.java, false)
}
val cancelTextView = view.findViewById<TextView>(R.id.cancel)
cancelTextView.text = cancelText
cancelTextView.setOnClickListener {
popTo(WifiSettingsFragment::class.java, false)
}
arguments?.getString("error")?.let { errorMessage ->
val tvMessage = view.findViewById<TextView>(R.id.error)
tvMessage?.text = errorMessage
}
}
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.model
class ContentStorage {
var currentContent: Content? = null
private set
var isMusicPlaying = false
var template: TemplateContent? = null
private set
var playerInfo: PlayerInfoPayload? = null
private set
var video: Video? = null
fun saveContent(content: Content?) {
this.currentContent = content
}
fun saveTemplate(template: TemplateContent?) {
this.template = template
}
fun savePlayInfo(playerInfo: PlayerInfoPayload?) {
this.playerInfo = playerInfo
}
fun saveVideo(video: Video?) {
this.video = video
}
companion object {
private var sStorage: ContentStorage? = null
fun get(): ContentStorage {
val current = sStorage
return if (current == null) {
val newStorage = ContentStorage()
sStorage = newStorage
newStorage
} else
current
}
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.impl.alarm
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_CANCEL_CURRENT
import android.content.*
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.iflytek.cyber.evs.sdk.agent.Alarm
import java.lang.ref.SoftReference
import java.sql.Date
import java.text.SimpleDateFormat
import java.util.*
class EvsAlarm private constructor(context: Context) : Alarm() {
private val dataHelper = AlarmDataHelper(context)
private val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
private val alarmPlayer = AlarmPlayerInstance(context)
private val contextRef = SoftReference(context)
private var activeAlarmId: String? = null
private var packageName = ""
companion object {
private const val TAG = "EvsAlarm"
const val NAME_DB_ALARMS = "alarms"
const val NAME_TABLE_ALARMS = "alarms"
const val ACTION_ALARM_ARRIVED = "com.iflytek.cyber.evs.sdk.agent.action.ARRIVED"
private var instance: EvsAlarm? = null
fun get(context: Context?): EvsAlarm {
instance?.let {
return it
} ?: run {
val alarm = EvsAlarm(context!!)
instance = alarm
return alarm
}
}
}
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
"$packageName&$ACTION_ALARM_ARRIVED" -> {
val alarmId = intent.getStringExtra(KEY_ALARM_ID)
val url = intent.getStringExtra(KEY_URL)
val timestamp = intent.getLongExtra(KEY_TIMESTAMP, -1L)
Log.d(TAG, "alarm arrived, {alarm_id=$alarmId, url=$url}.")
val current = System.currentTimeMillis() / 1000
if (current - timestamp > 5000) {
Log.w(
TAG,
"alarm {alarm_id=$alarmId} expired. Now is $current, alarm time is $timestamp"
)
} else {
activeAlarmId = alarmId
alarmPlayer.play(url)
}
dataHelper.deleteAlarm(alarmId)
onAlarmUpdated()
}
}
}
}
init {
packageName = context.packageName
// 注册广播接收
val intentFilter = IntentFilter()
intentFilter.addAction("$packageName&$ACTION_ALARM_ARRIVED")
context.registerReceiver(receiver, intentFilter)
// 初始化闹钟服务
val currentTimestamp = System.currentTimeMillis() / 1000
dataHelper.queryLocalAlarms().map {
if (it.timestamp <= currentTimestamp) {
// 过时闹钟应被删除
dataHelper.deleteAlarm(it.alarmId)
onAlarmUpdated()
} else {
// 重新设置闹钟到服务中
val intent = Intent("$packageName&$ACTION_ALARM_ARRIVED")
intent.putExtra(KEY_ALARM_ID, it.alarmId)
intent.putExtra(KEY_TIMESTAMP, it.timestamp)
intent.putExtra(KEY_URL, it.url)
val pendingIntent = PendingIntent.getBroadcast(
context,
it.alarmId.hashCode(),
intent,
FLAG_CANCEL_CURRENT // 更新已存在的闹钟
)
alarmManager.set(AlarmManager.RTC_WAKEUP, it.timestamp * 1000, pendingIntent)
}
}
alarmPlayer.setOnAlarmStateChangeListener(object :
AlarmPlayerInstance.OnAlarmStateChangeListener {
override fun onStarted() {
activeAlarmId?.let { alarmId ->
onAlarmStarted(alarmId)
}
}
override fun onStopped() {
activeAlarmId?.let { alarmId ->
onAlarmStopped(alarmId)
activeAlarmId = null
}
}
})
}
override fun stop() {
super.stop()
alarmPlayer.stop()
}
override fun setAlarm(alarm: Item) {
super.setAlarm(alarm)
val fmt = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
val time = fmt.format(Date(alarm.timestamp * 1000))
Log.d(TAG, "set alarm, {alarm_id=${alarm.alarmId}, time=$time}.")
val context = contextRef.get() ?: run {
Log.e(TAG, "Set alarm failed! Context is null.")
return
}
val intent = Intent("$packageName&$ACTION_ALARM_ARRIVED")
intent.putExtra(KEY_ALARM_ID, alarm.alarmId)
intent.putExtra(KEY_TIMESTAMP, alarm.timestamp)
intent.putExtra(KEY_URL, alarm.url)
val pendingIntent = PendingIntent.getBroadcast(
context,
alarm.alarmId.hashCode(),
intent,
FLAG_CANCEL_CURRENT // 更新已存在的闹钟
)
alarmManager.set(AlarmManager.RTC_WAKEUP, alarm.timestamp * 1000, pendingIntent)
dataHelper.addAlarm(alarm)
}
private fun cancelAlarm(alarmId: String) {
val alarm = dataHelper.queryAlarm(alarmId)
alarm?.let {
Log.d(TAG, "cancel unarrived alarm, {alarm_id=$alarmId}.")
val context = contextRef.get() ?: run {
Log.e(TAG, "Set alarm failed! Context is null.")
return
}
val intent = Intent("$packageName&$ACTION_ALARM_ARRIVED")
intent.putExtra(KEY_ALARM_ID, it.alarmId)
intent.putExtra(KEY_TIMESTAMP, it.timestamp)
intent.putExtra(KEY_URL, it.url)
val pendingIntent = PendingIntent.getBroadcast(
context,
alarmId.hashCode(),
intent,
FLAG_CANCEL_CURRENT // 更新已存在的闹钟
)
alarmManager.cancel(pendingIntent)
}
if (activeAlarmId == alarmId) {
Log.d(TAG, "stop active alarm, {alarm_id=$alarmId}.")
Handler(Looper.getMainLooper()).post {
alarmPlayer.stop()
}
}
}
fun isPlaying() = alarmPlayer.isPlaying()
override fun deleteAlarm(alarmId: String) {
super.deleteAlarm(alarmId)
cancelAlarm(alarmId)
Log.d(TAG, "delete alarm, {alarm_id=$alarmId}.")
dataHelper.deleteAlarm(alarmId)
}
override fun getLocalAlarms(): List<Item> {
return dataHelper.queryLocalAlarms()
}
override fun getActiveAlarmId(): String? {
return activeAlarmId
}
override fun destroy() {
val context = contextRef.get()
context?.unregisterReceiver(receiver)
}
private class AlarmDataHelper(
context: Context?
) : SQLiteOpenHelper(context, NAME_DB_ALARMS, null, 1) {
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("CREATE TABLE $NAME_TABLE_ALARMS (id INTEGER PRIMARY KEY AUTOINCREMENT, $KEY_ALARM_ID TEXT, $KEY_URL TEXT, $KEY_TIMESTAMP TEXT)")
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS $NAME_TABLE_ALARMS")
onCreate(db)
}
override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
onUpgrade(db, oldVersion, newVersion)
}
fun queryLocalAlarms(): List<Item> {
val list = mutableListOf<Item>()
val db = readableDatabase
val cursor = db.query(
NAME_TABLE_ALARMS, // The table to query
null, // The array of columns to return (pass null to get all)
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
)
with(cursor) {
while (moveToNext()) {
val alarmId = getString(getColumnIndexOrThrow(KEY_ALARM_ID))
val timestamp = getString(getColumnIndexOrThrow(KEY_TIMESTAMP))
val url = getString(getColumnIndexOrThrow(KEY_URL))
val timestampValue = try {
timestamp.toLong()
} catch (e: NumberFormatException) {
e.printStackTrace()
-1L
}
if (timestampValue > 0) {
list.add(Item(alarmId, timestampValue, url))
}
}
}
cursor.close()
return list.toList()
}
fun queryAlarm(alarmId: String): Item? {
val list = mutableListOf<Item>()
val db = readableDatabase
val cursor = db.query(
NAME_TABLE_ALARMS, // The table to query
null, // The array of columns to return (pass null to get all)
"$KEY_ALARM_ID = ?", // The columns for the WHERE clause
arrayOf(alarmId), // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
)
with(cursor) {
while (moveToNext()) {
val perAlarmId = getString(getColumnIndexOrThrow(KEY_ALARM_ID))
val timestamp = getString(getColumnIndexOrThrow(KEY_TIMESTAMP))
val url = getString(getColumnIndexOrThrow(KEY_URL))
val timestampValue = try {
timestamp.toLong()
} catch (e: NumberFormatException) {
e.printStackTrace()
-1L
}
if (timestampValue > 0) {
list.add(Item(perAlarmId, timestampValue, url))
}
}
}
cursor.close()
if (list.isEmpty()) {
return null
}
return list[0]
}
fun deleteAlarm(alarmId: String) {
val db = writableDatabase
db.delete(NAME_TABLE_ALARMS, "$KEY_ALARM_ID = ?", arrayOf(alarmId))
}
fun addAlarm(item: Item) {
val db = writableDatabase
val values = ContentValues().apply {
put(KEY_ALARM_ID, item.alarmId)
put(KEY_TIMESTAMP, item.timestamp.toString())
put(KEY_URL, item.url)
}
db.insert(NAME_TABLE_ALARMS, null, values)
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.model
import com.zyyoona7.wheel.IWheelEntity
import java.text.SimpleDateFormat
import java.util.*
class DateEntity(var date: Date, var type: String) : IWheelEntity {
override fun getWheelText(): String {
return formatDate(date)
}
private fun formatDate(date: Date): String {
val format = if (type == Alert.TYPE_NONE) {
SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA)
} else {
SimpleDateFormat("MM月dd日", Locale.CHINA)
}
return format.format(date)
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent.impl
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.view.SurfaceView
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.ui.PlayerView
import com.iflytek.cyber.evs.sdk.player.MediaSourceFactory
class VideoPlayerInstance {
private lateinit var player: SimpleExoPlayer
private val mediaSourceFactory: MediaSourceFactory
private val period = Timeline.Period()
private var listener: Listener? = null
private val handler = Handler()
var resourceId: String? = null
var isStarted: Boolean = false
constructor(context: Context) {
createPlayer(context)
player.addListener(object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
listener?.onPlayerStateChanged(
this@VideoPlayerInstance,
playWhenReady,
playbackState
)
}
override fun onPlayerError(error: ExoPlaybackException?) {
listener?.onPlayerError(this@VideoPlayerInstance, error)
}
})
player.playWhenReady = true
mediaSourceFactory = MediaSourceFactory(context, "")
}
constructor(context: Context, playerView: PlayerView) {
createPlayer(context)
player.addListener(object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
listener?.onPlayerStateChanged(
this@VideoPlayerInstance,
playWhenReady,
playbackState
)
}
override fun onPlayerError(error: ExoPlaybackException?) {
listener?.onPlayerError(this@VideoPlayerInstance, error)
}
})
player.playWhenReady = true
playerView.player = player
mediaSourceFactory = MediaSourceFactory(context, "")
}
private fun createPlayer(context: Context) {
player = ExoPlayerFactory.newSimpleInstance(
context,
DefaultRenderersFactory(context),
DefaultTrackSelector(),
DefaultLoadControl()
)
}
private val positionUpdateRunnable = object : Runnable {
override fun run() {
if (player.playbackState == Player.STATE_READY
|| player.playbackState == Player.STATE_BUFFERING
) {
if (player.playWhenReady) {
listener?.onPlayerPositionUpdated(this@VideoPlayerInstance, getOffset())
handler.postDelayed(this, 500)
}
}
}
}
interface Listener {
fun onPlayerStateChanged(
player: VideoPlayerInstance,
playWhenReady: Boolean,
playbackState: Int
)
fun onPlayerError(player: VideoPlayerInstance, error: ExoPlaybackException?)
fun onPlayerPositionUpdated(player: VideoPlayerInstance, position: Long)
}
fun setListener(listener: Listener) {
this.listener = listener
}
fun setVideoSurfaceView(surfaceView: SurfaceView) {
player.setVideoSurfaceView(surfaceView)
}
fun play(url: String) {
handler.post {
val uri = Uri.parse(url)
val mediaSource = mediaSourceFactory.createHttpMediaSource(uri)
player.prepare(mediaSource, true, false)
player.playWhenReady = true
}
handler.post(positionUpdateRunnable)
}
fun setVolume(volume: Float) {
if (Looper.myLooper() == Looper.getMainLooper()) {
player.volume = volume
} else {
handler.post {
player.volume = volume
}
}
}
fun getVolume() = player.volume
fun resume() {
if (Looper.myLooper() == Looper.getMainLooper()) {
// if (player.playbackState == Player.STATE_READY) {
player.playWhenReady = true
// }
} else {
// if (player.playbackState == Player.STATE_READY) {
handler.post {
player.playWhenReady = true
}
// }
}
handler.post(positionUpdateRunnable)
}
fun pause() {
if (Looper.myLooper() == Looper.getMainLooper()) {
player.playWhenReady = false
} else {
handler.post {
player.playWhenReady = false
}
}
}
fun stop() {
if (Looper.myLooper() == Looper.getMainLooper()) {
player.playWhenReady = false
player.stop(true)
} else {
handler.post {
player.playWhenReady = false
player.stop(true)
}
}
}
fun seekTo(offset: Long) {
if (Looper.myLooper() == Looper.getMainLooper()) {
player.seekTo(offset)
} else {
player.seekTo(offset)
}
}
fun getOffset(): Long {
val position = player.currentPosition
return try {
position - player.currentTimeline.getPeriod(
player.currentPeriodIndex, period
).positionInWindowMs
} catch (e: Exception) {
position
}
}
fun getDuration(): Long {
val duration = player.duration
return if (duration != C.TIME_UNSET) duration else 0
}
fun getLooper(): Looper = player.applicationLooper
fun destroy() {
player.stop(true)
player.release()
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.evs.sdk.player
import android.content.Context
import android.net.Uri
import android.os.Handler
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.MediaSourceEventListener
import com.google.android.exoplayer2.source.dash.DashMediaSource
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource
import com.google.android.exoplayer2.source.hls.HlsMediaSource
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource
import com.google.android.exoplayer2.upstream.*
import com.google.android.exoplayer2.util.Util
import java.io.IOException
class MediaSourceFactory internal constructor(
private val mContext: Context, private val mName: String) {
private val mMainHandler: Handler
private val mPlaylistParser = PlaylistParser()
private val mMediaSourceListener = MediaSourceListener()
private val mFileDataSourceFactory = FileDataSourceFactory(null)
private val mHttpDataSourceFactory: DataSource.Factory
init {
mHttpDataSourceFactory = buildHttpDataSourceFactory(mContext)
mMainHandler = Handler()
}// mLogger = logger;
private fun buildHttpDataSourceFactory(context: Context): HttpDataSource.Factory {
val userAgent = Util.getUserAgent(context, sUserAgentName)
// Some streams may see a long response time to begin data transfer from server after
// connection. Use default 8 second connection timeout and increased 20 second read timeout
// to catch this case and avoid reattempts to connect that will continue to time out.
// May perceive long "dead time" in cases where data read takes a long time
return DefaultHttpDataSourceFactory(userAgent, null, 8000,
20000, true)
}
@Throws(Exception::class)
internal fun createFileMediaSource(uri: Uri): MediaSource {
return createMediaSource(uri, mFileDataSourceFactory, mMediaSourceListener, mMainHandler,
mPlaylistParser)
}
@Throws(Exception::class)
internal fun createHttpMediaSource(uri: Uri): MediaSource {
return createMediaSource(uri, mHttpDataSourceFactory, mMediaSourceListener, mMainHandler,
mPlaylistParser)
}
//
// Media types for creating an ExoPlayer MediaSource
//
enum class MediaType private constructor(val type: Int) {
DASH(C.TYPE_DASH),
SMOOTH_STREAMING(C.TYPE_SS),
HLS(C.TYPE_HLS),
OTHER(C.TYPE_OTHER),
M3U(4),
PLS(5);
companion object {
fun inferContentType(fileExtension: String?): MediaType {
if (fileExtension == null) {
return OTHER
} else if (fileExtension.endsWith(".ashx") || fileExtension.endsWith(".m3u")) {
return M3U
} else if (fileExtension.endsWith(".pls")) {
return PLS
} else {
val type = Util.inferContentType(fileExtension)
for (mediaType in MediaType.values()) {
if (mediaType.type == type) return mediaType
}
return OTHER
}
}
}
}
//
// Media Source event listener
//
private inner class MediaSourceListener : MediaSourceEventListener {
private var mRetryCount = 0
override fun onLoadStarted(windowIndex: Int, mediaPeriodId: MediaSource.MediaPeriodId?, loadEventInfo: MediaSourceEventListener.LoadEventInfo?, mediaLoadData: MediaSourceEventListener.MediaLoadData?) {
mRetryCount = 1
}
override fun onLoadCompleted(windowIndex: Int, mediaPeriodId: MediaSource.MediaPeriodId?, loadEventInfo: MediaSourceEventListener.LoadEventInfo?, mediaLoadData: MediaSourceEventListener.MediaLoadData?) {
mRetryCount = 0
}
override fun onLoadCanceled(windowIndex: Int, mediaPeriodId: MediaSource.MediaPeriodId?, loadEventInfo: MediaSourceEventListener.LoadEventInfo?, mediaLoadData: MediaSourceEventListener.MediaLoadData?) {
mRetryCount = 0
}
override fun onLoadError(windowIndex: Int, mediaPeriodId: MediaSource.MediaPeriodId?, loadEventInfo: MediaSourceEventListener.LoadEventInfo?, mediaLoadData: MediaSourceEventListener.MediaLoadData?, error: IOException?, wasCanceled: Boolean) {
mRetryCount++
}
override fun onUpstreamDiscarded(windowIndex: Int, mediaPeriodId: MediaSource.MediaPeriodId?, mediaLoadData: MediaSourceEventListener.MediaLoadData?) {
}
override fun onDownstreamFormatChanged(windowIndex: Int, mediaPeriodId: MediaSource.MediaPeriodId?, mediaLoadData: MediaSourceEventListener.MediaLoadData?) {
}
override fun onMediaPeriodCreated(windowIndex: Int, mediaPeriodId: MediaSource.MediaPeriodId?) {
}
override fun onMediaPeriodReleased(windowIndex: Int, mediaPeriodId: MediaSource.MediaPeriodId?) {
}
override fun onReadingStarted(windowIndex: Int, mediaPeriodId: MediaSource.MediaPeriodId?) {
}
}
companion object {
private val sTag = "MediaSourceFactory"
private const val sUserAgentName = "com.iflytek.sampleapp"
@Throws(Exception::class)
private fun createMediaSource(uri: Uri,
dataSourceFactory: DataSource.Factory,
mediaSourceListener: MediaSourceEventListener,
handler: Handler,
playlistParser: PlaylistParser): MediaSource {
when (MediaType.inferContentType(uri.lastPathSegment)) {
MediaType.DASH -> {
return DashMediaSource.Factory(
DefaultDashChunkSource.Factory(dataSourceFactory),
dataSourceFactory
).createMediaSource(uri, handler, mediaSourceListener)
}
MediaType.SMOOTH_STREAMING -> {
return SsMediaSource.Factory(
DefaultSsChunkSource.Factory(dataSourceFactory),
dataSourceFactory
).createMediaSource(uri, handler, mediaSourceListener)
}
MediaType.HLS -> {
return HlsMediaSource.Factory(dataSourceFactory)
.createMediaSource(uri, handler, mediaSourceListener)
}
MediaType.M3U, MediaType.PLS -> {
val parsedUri = playlistParser.parseUri(uri)
return createMediaSource(parsedUri, dataSourceFactory, mediaSourceListener,
handler, playlistParser)
}
MediaType.OTHER -> {
return ExtractorMediaSource.Factory(dataSourceFactory)
.createMediaSource(uri, handler, mediaSourceListener)
}
else -> {
throw IllegalStateException("Unsupported type")
}
}
}
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.iflytek.cyber.iot.show.core.R
class StyledProgressDialog : DialogFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
return inflater.inflate(R.layout.layout_styled_progress_dialog, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val title = arguments?.getString("text")
val message = arguments?.getString("message")
val isCancelable = arguments?.getBoolean("is_cancelable", true)
this.isCancelable = isCancelable == true
view.findViewById<TextView>(R.id.dialog_title)?.let { tvTitle ->
if (title.isNullOrEmpty()) {
(tvTitle.layoutParams as? ConstraintLayout.LayoutParams)?.let { layoutParams ->
layoutParams.width = resources.getDimensionPixelSize(R.dimen.dp_40)
layoutParams.constrainedWidth = false
tvTitle.layoutParams = layoutParams
}
} else {
tvTitle.text = title
}
}
view.findViewById<TextView>(R.id.dialog_message)?.let { tvMessage ->
if (message.isNullOrEmpty()) {
(tvMessage.layoutParams as? ConstraintLayout.LayoutParams)?.let { layoutParams ->
layoutParams.width = resources.getDimensionPixelSize(R.dimen.dp_40)
layoutParams.constrainedWidth = false
tvMessage.layoutParams = layoutParams
}
} else {
tvMessage.text = message
}
}
}
override fun onStart() {
super.onStart()
dialog?.let { dialog ->
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.window?.setLayout(
resources.getDimensionPixelSize(R.dimen.dp_380),
WindowManager.LayoutParams.WRAP_CONTENT
)
}
}
class Builder {
private var message: String? = null
private var title: String? = null
private var isCancelable = true
fun setTitle(title: String?): Builder {
this.title = title
return this
}
fun setMessage(message: String?): Builder {
this.message = message
return this
}
fun setCancelable(isCancelable: Boolean): Builder {
this.isCancelable = isCancelable
return this
}
fun build(): StyledProgressDialog {
val dialog = StyledProgressDialog()
val arguments = Bundle()
arguments.putString("text", title)
arguments.putString("message", message)
arguments.putBoolean("is_cancelable", isCancelable)
dialog.arguments = arguments
return dialog
}
fun show(fragmentManager: FragmentManager?): StyledProgressDialog {
build().apply {
fragmentManager?.let {
show(fragmentManager, "Progress")
}
return this
}
}
}
}<file_sep>#include <jni.h>
#include <string>
#include "hlw.h"
#include "com_iflytek_ivw_IVWEngine.h"
JavaVM* g_JVM = NULL;
jobject g_thiz = NULL;
jmethodID g_ivwCb_method = NULL;
CAE_HANDLE g_handle = NULL;
void ivw_cb_func(short angle, short channel, float power, short CMScore, short beam,
char *param1, void *param2, void *userData)
{
if (g_JVM == NULL) {
return;
}
JNIEnv* pEnv = NULL;
int ret = g_JVM->AttachCurrentThread(&pEnv, NULL);
if (ret != JNI_OK) {
return;
}
if (g_thiz != NULL) {
jstring param1Str = pEnv->NewStringUTF(param1);
pEnv->CallVoidMethod(g_thiz, g_ivwCb_method,
angle, channel, power, CMScore, beam, param1Str, NULL);
}
g_JVM->DetachCurrentThread();
}
void audio_cb_func(const void *audioData, unsigned int audioLen,
int param1, const void *param2, void *userData)
{
}
void ivw_audio_cb_func(const void *audioData, unsigned int audioLen,
int param1, const void *param2, void *userData)
{
}
/*
* Class: com_iflytek_ivw_IVWEngine
* Method: create_ivw
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_com_iflytek_ivw_IVWEngine_create_1ivw
(JNIEnv *pEnv, jobject thiz, jstring ivwResPath)
{
int ret = pEnv->GetJavaVM(&g_JVM);
if (ret != JNI_OK) {
return -1;
}
g_thiz = pEnv->NewGlobalRef(thiz);
g_ivwCb_method = pEnv->GetMethodID(pEnv->GetObjectClass(thiz), "ivwCb",
"(SSFSSLjava/lang/String;Ljava/lang/String;)V");
const char* pIvwResPathChar = pEnv->GetStringUTFChars(ivwResPath, JNI_FALSE);
ret = CAENew(&g_handle, pIvwResPathChar, ivw_cb_func, ivw_audio_cb_func, audio_cb_func,
NULL, NULL);
pEnv->ReleaseStringUTFChars(ivwResPath, pIvwResPathChar);
return ret;
}
/*
* Class: com_iflytek_ivw_IVWEngine
* Method: ivw_auth
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_com_iflytek_ivw_IVWEngine_ivw_1auth
(JNIEnv *pEnv, jobject thiz, jstring sn)
{
int ret = -1;
if (g_handle != NULL) {
const char *pSnChar = pEnv->GetStringUTFChars(sn, JNI_FALSE);
ret = CAEAuth((char*) pSnChar);
pEnv->ReleaseStringUTFChars(sn, pSnChar);
}
return ret;
}
/*
* Class: com_iflytek_ivw_IVWEngine
* Method: write_audio
* Signature: ([BI)I
*/
JNIEXPORT jint JNICALL Java_com_iflytek_ivw_IVWEngine_write_1audio
(JNIEnv *pEnv, jobject thiz, jbyteArray audio, jint len)
{
int ret = -1;
if (g_handle != NULL) {
char* pAudioChar = (char*) pEnv->GetByteArrayElements(audio, JNI_FALSE);
ret = CAEAudioWrite(g_handle, pAudioChar, len);
pEnv->ReleaseByteArrayElements(audio, (jbyte*) pAudioChar, 0);
}
return ret;
}
/*
* Class: com_iflytek_ivw_IVWEngine
* Method: get_version
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_iflytek_ivw_IVWEngine_get_1version
(JNIEnv *pEnv, jobject thiz)
{
char* pVer = CAEGetVersion();
return pEnv->NewStringUTF(pVer);
}
/*
* Class: com_iflytek_ivw_IVWEngine
* Method: set_log_level
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_iflytek_ivw_IVWEngine_set_1log_1level
(JNIEnv *pEnv, jobject thiz, jint level)
{
CAESetShowLog(level);
}
/*
* Class: com_iflytek_ivw_IVWEngine
* Method: destroy_ivw
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_com_iflytek_ivw_IVWEngine_destroy_1ivw
(JNIEnv *pEnv, jobject thiz)
{
int ret = -1;
if (g_handle != NULL) {
ret = CAEDestroy(g_handle);
g_handle = NULL;
}
if (g_thiz != NULL) {
pEnv->DeleteGlobalRef(g_thiz);
g_thiz = NULL;
}
g_ivwCb_method = NULL;
return ret;
}
<file_sep>@file:Suppress("FunctionName")
package com.iflytek.cyber.iot.show.core.utils
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import android.os.PowerManager
import android.os.Process
import android.os.RecoverySystem
import android.provider.Settings
import com.iflytek.cyber.iot.show.core.BuildConfig
import com.iflytek.cyber.iot.show.core.EngineService
import com.iflytek.cyber.iot.show.core.FloatingService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.impl.speaker.EvsSpeaker
import java.io.File
object DeviceUtils {
@SuppressLint("HardwareIds")
fun getDeviceId(context: Context): String {
return Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
}
fun getClientId(): String {
val savedClientId = ConfigUtils.getString(ConfigUtils.KEY_CLIENT_ID, null)
return if (savedClientId.isNullOrEmpty()) {
BuildConfig.CLIENT_ID
} else {
savedClientId
}
}
fun getIvwVersion(): String? {
return "7.0"
}
fun getSystemVersionName(): String {
val systemVersion = BuildConfig.VERSION_NAME
if (BuildConfig.DEBUG)
return "$systemVersion(${BuildConfig.VERSION_CODE})"
return systemVersion
}
fun getSystemVersion(): Int {
return BuildConfig.VERSION_CODE
}
fun lockScreen(context: Context) {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
val screenOn = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
pm.isInteractive
} else {
pm.isScreenOn
}
if (screenOn && Process.myUid() == Process.SYSTEM_UID) {
// 点亮屏幕
TerminalUtils.execute("input keyevent POWER")
}
}
fun unlockScreen(context: Context) {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
val screenOn = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
pm.isInteractive
} else {
pm.isScreenOn
}
if (!screenOn) {
// 点亮屏幕
@SuppressLint("InvalidWakeLockTag")
val wl = pm.newWakeLock(
PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
"bright"
)
wl.acquire(10000)
wl.release()
}
}
fun getBatteryLevel(context: Context?): Int {
context?.registerReceiver(
null,
IntentFilter(Intent.ACTION_BATTERY_CHANGED)
)?.let { intent ->
// val status: Int = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
//
// // How are we charging?
// val chargePlug: Int = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
// val usbCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_USB
// val acCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_AC
//
// val isCharging: Boolean =
// (status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL)
// && chargePlug == BatteryManager.BATTERY_PLUGGED_USB
val level: Int = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale: Int = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
return level * 100 / scale
}
return 0
}
fun doFactoryReset(context: Context) {
Thread {
try {
RecoverySystem.rebootWipeUserData(context)
} catch (t: Throwable) {
if (t is SecurityException) {
val intent = Intent(context, FloatingService::class.java)
intent.action = FloatingService.ACTION_SHOW_NOTIFICATION
intent.putExtra(FloatingService.EXTRA_MESSAGE, "恢复出厂操作无法获得权限")
intent.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_TEXT,
context.getString(R.string.i_got_it)
)
context.startService(intent)
ConfigUtils.removeAll()
val revokeAuth = Intent(context, EngineService::class.java)
revokeAuth.action = EngineService.ACTION_AUTH_REVOKED
context.startService(revokeAuth)
// init overlay
val overlay = Intent(context, FloatingService::class.java)
overlay.action = FloatingService.ACTION_INIT_CONFIG
context.startService(overlay)
// 重置音量和亮度
EvsSpeaker.get(context).setVolumeLocally(50)
BrightnessUtils.setBrightness(context, 50)
// 删除自定义唤醒词文件
val externalCache = context.externalCacheDir
val customWakeResFile = File("$externalCache/wake_up_res_custom.bin")
if (customWakeResFile.exists()) {
customWakeResFile.delete()
}
} else {
t.printStackTrace()
}
}
}.start()
}
}<file_sep>package com.iflytek.cyber.iot.show.core.template
import android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewTreeObserver
import android.widget.*
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.google.gson.JsonParser
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
import com.iflytek.cyber.iot.show.core.widget.HighlightTextView
class BodyTemplateView1 @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val bodyText: HighlightTextView
private val bodyImage: ImageView
private val skillIconImage: ImageView
private val backgroundImage: ImageView
private val bodyContainer: LinearLayout
private val bodyHorizontalContainer: LinearLayout
private val bodyScrollView: ScrollView
private val mainTitle: TextView
private val subTitle: TextView
private val bodyHorizontalImage: ImageView
private val horizontalBodyText: HighlightTextView
private val horizontalScrollView: ScrollView
private val imageMaxHeight =
resources.getDimensionPixelSize(R.dimen.body_template_image_max_height)
private var currentPayload: String? = null
private val innerOnClickBackListener = OnClickListener { v ->
onClickBackListener?.onClick(v)
}
private var onClickBackListener: OnClickListener? = null
init {
val childView = LayoutInflater.from(context)
.inflate(R.layout.layout_body_template_1, null)
bodyContainer = childView.findViewById(R.id.body_vertical_container)
bodyHorizontalContainer = childView.findViewById(R.id.body_horizontal_container)
bodyScrollView = childView.findViewById(R.id.body_scroll_view)
bodyText = childView.findViewById(R.id.body_text)
bodyImage = childView.findViewById(R.id.body_image)
bodyHorizontalImage = childView.findViewById(R.id.body_horizontal_image)
skillIconImage = childView.findViewById(R.id.skill_icon)
backgroundImage = childView.findViewById(R.id.background_image)
mainTitle = childView.findViewById(R.id.main_title)
subTitle = childView.findViewById(R.id.sub_title)
horizontalBodyText = childView.findViewById(R.id.horizontal_body_text)
horizontalScrollView = childView.findViewById(R.id.horizontal_scroll_view)
bodyText.onHighlightChangeListener = object : HighlightTextView.OnHighlightChangeListener {
override fun onHighlightChange(view: HighlightTextView, line: Int, offset: Int) {
bodyScrollView.smoothScrollTo(0, offset)
}
}
horizontalBodyText.onHighlightChangeListener =
object : HighlightTextView.OnHighlightChangeListener {
override fun onHighlightChange(view: HighlightTextView, line: Int, offset: Int) {
horizontalScrollView.smoothScrollTo(0, offset)
}
}
childView.findViewById<View>(R.id.back)?.setOnClickListener(innerOnClickBackListener)
addView(childView)
}
fun updatePayload(payload: String) {
val json = JsonParser().parse(payload).asJsonObject
mainTitle.text = json.get(Constant.PAYLOAD_MAIN_TITLE)?.asString
json.get(Constant.PAYLOAD_SUB_TITLE)?.asString?.let { subTitle ->
if (subTitle.isNotEmpty()) {
this.subTitle.visibility = View.VISIBLE
this.subTitle.text = subTitle
} else {
this.subTitle.visibility = View.GONE
}
} ?: run {
this.subTitle.visibility = View.GONE
}
json.get(Constant.PAYLOAD_BACK_BUTTON)?.asString?.let { backButton ->
when (backButton) {
Constant.BACK_BUTTON_HIDDEN -> {
findViewById<View>(R.id.back_icon).visibility = View.GONE
}
else -> {
findViewById<View>(R.id.back_icon).visibility = View.VISIBLE
}
}
} ?: run {
findViewById<View>(R.id.back_icon).visibility = View.VISIBLE
}
bodyText.text = json.get(Constant.PAYLOAD_BODY_TEXT)?.asString
horizontalBodyText.text = bodyText.text
val imageUrl = json.get(Constant.PAYLOAD_BODY_IMAGE_URL)?.asString
if (!imageUrl.isNullOrEmpty()) {
Glide.with(context)
.asBitmap()
.load(imageUrl)
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?
) {
val width = resource.width
val height = resource.height
if (width.toFloat() / height.toFloat() < 1) {
bodyScrollView.isVisible = false
bodyHorizontalContainer.isVisible = true
showHorizontalTemplate(imageUrl, resource)
} else {
bodyScrollView.isVisible = true
bodyHorizontalContainer.isVisible = false
showVerticalTemplate(imageUrl, resource)
}
}
})
} else {
bodyContainer.isVisible = false
bodyScrollView.isVisible = true
bodyHorizontalContainer.isVisible = false
}
json.get(Constant.PAYLOAD_SKILL_ICON_URL)?.asString?.let { skillIconUrl ->
if (skillIconUrl.isNotEmpty()) {
skillIconImage.visibility = View.VISIBLE
Glide.with(skillIconImage)
.load(skillIconUrl)
.apply(
RequestOptions()
.transform(
RoundedCornersTransformation(
resources.getDimensionPixelSize(R.dimen.dp_8), 0
)
)
)
.transition(DrawableTransitionOptions.withCrossFade())
.into(skillIconImage)
} else {
skillIconImage.visibility = View.GONE
}
} ?: run {
skillIconImage.visibility = View.GONE
}
json.get(Constant.PAYLOAD_BACKGROUND_IMAGE_URL)?.asString?.let { backgroundImageUrl ->
if (backgroundImageUrl.isNotEmpty()) {
backgroundImage.visibility = View.VISIBLE
Glide.with(backgroundImage)
.load(backgroundImageUrl)
.transition(DrawableTransitionOptions.withCrossFade())
.into(backgroundImage)
} else {
backgroundImage.visibility = View.GONE
}
} ?: run {
backgroundImage.visibility = View.GONE
}
currentPayload = payload
}
private fun showVerticalTemplate(url: String, bitmap: Bitmap) {
val transformer = MultiTransformation(
CenterCrop(),
RoundedCornersTransformation(
context.resources.getDimensionPixelSize(R.dimen.dp_12), 0
)
)
//bodyImage.setOriginalSize(bitmap.width, bitmap.height)
Glide.with(context)
.load(url)
.transform(transformer)
.override(bitmap.width, bitmap.height)
.into(bodyImage)
}
private fun showHorizontalTemplate(url: String, bitmap: Bitmap) {
val transformer = MultiTransformation(
CenterCrop(),
RoundedCornersTransformation(
context.resources.getDimensionPixelSize(R.dimen.dp_12), 0
)
)
Glide.with(context)
.load(url)
.transform(transformer)
.override(bitmap.width, bitmap.height)
.into(bodyHorizontalImage)
}
fun updateBodyPosition(position: Long) {
bodyText.updatePosition(position)
horizontalBodyText.updatePosition(position)
}
fun startBodyAnimation() {
bodyText.startAnimation()
horizontalBodyText.startAnimation()
if (!(bodyText.text.isNullOrEmpty()) && bodyText.lineCount > 0) {
bodyText.startAnimation()
} else {
bodyText.viewTreeObserver.addOnGlobalLayoutListener(object :
ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (!(bodyText.text.isNullOrEmpty()) && bodyText.lineCount > 0) {
bodyText.startAnimation()
bodyText.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
}
})
}
if (!(horizontalBodyText.text.isNullOrEmpty()) && horizontalBodyText.lineCount > 0) {
horizontalBodyText.startAnimation()
} else {
horizontalBodyText.viewTreeObserver.addOnGlobalLayoutListener(object :
ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (!(horizontalBodyText.text.isNullOrEmpty()) && horizontalBodyText.lineCount > 0) {
horizontalBodyText.startAnimation()
horizontalBodyText.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
}
})
}
}
fun isBodyAnimating() = bodyText.isAnimationStarted() || horizontalBodyText.isAnimationStarted()
fun stopBodyAnimation() {
post {
bodyText.stopAnimation()
horizontalBodyText.stopAnimation()
}
}
fun setOnClickBackListener(onClickListener: OnClickListener?) {
this.onClickBackListener = onClickListener
}
class Builder(private val context: Context) {
private var payload: String? = null
private var onClickListener: OnClickListener? = null
fun payload(payload: String): Builder {
this.payload = payload
return this
}
fun onClickBackListener(onClickListener: OnClickListener?): Builder {
this.onClickListener = onClickListener
return this
}
fun build(): BodyTemplateView1 {
val view = BodyTemplateView1(context)
payload?.let { payload ->
view.updatePayload(payload)
}
onClickListener?.let {
view.setOnClickBackListener(it)
}
return view
}
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent
import androidx.annotation.CallSuper
import com.alibaba.fastjson.JSONObject
import com.iflytek.cyber.evs.sdk.RequestManager
import com.iflytek.cyber.evs.sdk.model.Constant
/**
* 启动器模块。详细介绍见https://doc.iflyos.cn/device/evs/reference/launcher.html#%E5%90%AF%E5%8A%A8%E5%99%A8
*/
abstract class Launcher {
val version
get() = "1.0"
companion object {
const val NAME_START_ACTIVITY = "${Constant.NAMESPACE_LAUNCHER}.start_activity"
const val NAME_BACK = "${Constant.NAMESPACE_LAUNCHER}.back"
const val NAME_START_ACTIVITY_RESULT =
"${Constant.NAMESPACE_LAUNCHER}.start_activity_result"
const val NAME_BACK_RESULT =
"${Constant.NAMESPACE_LAUNCHER}.back_result"
const val NAME_START_INTERNAL_APP = "${Constant.NAMESPACE_LAUNCHER}.start_internal_app"
const val NAME_START_INTERNAL_APP_RESULT = "${Constant.NAMESPACE_LAUNCHER}.start_internal_app_result"
const val PAYLOAD_PAGE = "page"
const val PAYLOAD_RESULT = "result"
const val PAYLOAD_FAILURE_CODE = "failure_code"
const val PAYLOAD_FEEDBACK_TEXT = "feedback_text"
const val KEY_SUPPORTED_APP_TYPE = "supported_app_type"
const val KEY_FOREGROUND_APP_TYPE = "foreground_app_type"
const val KEY_FOREGROUND_APP_ID = "foreground_app_id"
const val KET_INTERNAL_APP = "internal_app"
const val TYPE_TEMPLATE = "TEMPLATE"
const val TYPE_SKILL = "SKILL"
const val TYPE_EVALUATE = "EVALUATE"
const val TYPE_H5_APP = "H5_APP"
const val PAGE_HOME = "home"
const val PAGE_SETTINGS = "settings"
const val PAGE_CONTENTS = "contents"
const val PAGE_SKILLS = "skills"
const val PAGE_ALARMS = "alarms"
const val PAGE_MESSAGES = "messages"
const val PAGE_NEXT = "next"
const val PAGE_PREVIOUS = "previous"
const val RESULT_SUCCEED = "SUCCEED"
const val RESULT_FAILED = "FAILED"
const val FAILURE_CODE_NOT_FOUND_PAGE = "NOT_FOUND_PAGE"
const val FAILURE_CODE_INTERNAL_ERROR = "INTERNAL_ERROR"
const val FAILURE_CODE_NOT_FOUND_APP = "APP_NOT_FOUND"
}
/**
* 打开跳转 Launcher 内的某个页面
* @return 是否自定义反馈结果
*/
abstract fun startActivity(page: String, callback: ExecuteCallback): Boolean
abstract fun back(callback: ExecuteCallback)
abstract fun startInternalApp(payload: JSONObject, callback: ExecuteCallback): Boolean
abstract fun getForegroundAppType(): String?
abstract fun getForegroundAppId(): String?
abstract fun getSupportedType(): List<String>
@CallSuper
open fun sendStartActivitySucceed(page: String, feedbackText: String? = null) {
val payload = JSONObject()
payload[PAYLOAD_RESULT] = RESULT_SUCCEED
payload[PAYLOAD_PAGE] = page
feedbackText?.let {
payload[PAYLOAD_FEEDBACK_TEXT] = feedbackText
}
RequestManager.sendRequest(NAME_START_ACTIVITY_RESULT, payload)
}
@CallSuper
open fun sendStartActivityFailed(
page: String,
failureCode: String?, feedbackText: String?
) {
val payload = JSONObject()
payload[PAYLOAD_RESULT] = RESULT_FAILED
payload[PAYLOAD_PAGE] = page
failureCode?.let {
payload[PAYLOAD_FAILURE_CODE] = it
}
feedbackText?.let {
payload[PAYLOAD_FEEDBACK_TEXT] = it
}
RequestManager.sendRequest(NAME_START_ACTIVITY_RESULT, payload)
}
open fun sendBackSucceed(feedbackText: String? = null) {
val payload = JSONObject()
payload[PAYLOAD_RESULT] = RESULT_SUCCEED
feedbackText?.let {
payload[PAYLOAD_FEEDBACK_TEXT] = feedbackText
}
RequestManager.sendRequest(NAME_BACK_RESULT, payload)
}
open fun sendBackFailed(feedbackText: String?) {
val payload = JSONObject()
payload[PAYLOAD_RESULT] = RESULT_FAILED
feedbackText?.let {
payload[PAYLOAD_FEEDBACK_TEXT] = it
}
RequestManager.sendRequest(NAME_BACK_RESULT, payload)
}
open fun sendStartInternalAppSucceed(
internalAppId: String,
type: String,
feedbackText: String? = null
) {
val payload = JSONObject()
payload[PAYLOAD_RESULT] = RESULT_SUCCEED
payload["id"] = internalAppId
payload["type"] = type
feedbackText?.let {
payload[PAYLOAD_FEEDBACK_TEXT] = it
}
RequestManager.sendRequest(NAME_START_INTERNAL_APP_RESULT, payload)
}
open fun sendStartInternalAppFailed(
internalAppId: String,
type: String,
feedbackText: String? = null,
failureCode: String? = null
) {
val payload = JSONObject()
payload[PAYLOAD_RESULT] = RESULT_FAILED
payload["id"] = internalAppId
payload["type"] = type
payload["failure_code"] = failureCode
feedbackText?.let {
payload[PAYLOAD_FEEDBACK_TEXT] = it
}
RequestManager.sendRequest(NAME_START_INTERNAL_APP_RESULT, payload)
}
abstract class ExecuteCallback {
var result = ""
var page = ""
var failureCode: String? = null
var feedbackText: String? = null
abstract fun onSuccess(feedbackText: String? = null)
abstract fun onFailed(failureCode: String?, feedbackText: String?)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.RecyclerView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.widget.CircleCheckBox
import com.iflytek.cyber.iot.show.core.widget.DividerItemDecoration
class SingleChoiceFragment : BaseFragment() {
private val titles = mutableListOf<String>()
private val summaries = mutableListOf<String>()
private var selectedItem = 0
private var title: String? = null
private var message: String? = null
private var popWhenSelected: Boolean = false
private val adapter = ListAdapter()
private var backCount = 0
companion object {
fun newInstance(
title: String,
message: String?,
itemTitles: Array<String>,
itemSummaries: Array<String>?,
selectedItem: Int = 0,
popWhenSelected: Boolean = false
): SingleChoiceFragment {
val fragment = SingleChoiceFragment()
fragment.titles.addAll(itemTitles)
itemSummaries?.let {
fragment.summaries.addAll(itemSummaries)
}
fragment.selectedItem = selectedItem
fragment.title = title
fragment.message = message
fragment.popWhenSelected = popWhenSelected
return fragment
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_single_choice, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
setResult()
pop()
}
val recyclerView = view.findViewById<RecyclerView>(R.id.recycler_view)
recyclerView.adapter = adapter
recyclerView.itemAnimator = DefaultItemAnimator()
val itemDecoration = DividerItemDecoration.Builder(view.context)
.setDividerColor(resources.getColor(R.color.divider_line))
.setPaddingLeft(resources.getDimensionPixelSize(R.dimen.dp_40))
.setPaddingRight(resources.getDimensionPixelSize(R.dimen.dp_40))
.build()
recyclerView.addItemDecoration(itemDecoration)
val messageView = view.findViewById<TextView>(R.id.message)
messageView.text = message
messageView.isVisible = !message.isNullOrEmpty()
val titleView = view.findViewById<TextView>(R.id.title)
titleView.text = title
}
private inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = ItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_single_choice,
parent,
false
)
)
holder.itemView.setOnClickListener {
selectedItem = holder.adapterPosition
adapter.notifyItemRangeChanged(0, itemCount)
if (popWhenSelected) {
setResult()
pop()
}
}
holder.checkBox.isClickable = false
return holder
}
override fun getItemCount(): Int {
return titles.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ItemViewHolder) {
holder.titleView.text = titles[position]
if (summaries.size > position) {
holder.summaryView.isVisible = true
holder.summaryView.text = summaries[position]
} else {
holder.summaryView.isVisible = false
}
holder.checkBox.isVisible = position == selectedItem
}
}
}
override fun onBackPressedSupport(): Boolean {
setResult()
return super.onBackPressedSupport()
}
private fun setResult() {
val bundle = Bundle()
bundle.putInt("selected_item", selectedItem)
setFragmentResult(0, bundle)
}
private class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val titleView: TextView = itemView.findViewById(R.id.title)
val summaryView: TextView = itemView.findViewById(R.id.message)
val checkBox: CircleCheckBox = itemView.findViewById(R.id.check_box)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class OnLoadMoreListener(val callback: Callback) : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return
val visibleItemCount = recyclerView.childCount
val totalItemCount = layoutManager.itemCount
val firstVisibleItem = layoutManager.findFirstVisibleItemPosition()
if (totalItemCount > 1 && totalItemCount - visibleItemCount <= firstVisibleItem + VISIBLE_THRESHOLD) {
callback.onLoadMore()
}
}
companion object {
private const val VISIBLE_THRESHOLD = 5
}
interface Callback {
fun onLoadMore()
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.launcher.AppData
import com.iflytek.cyber.iot.show.core.launcher.TemplateAppData
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
class AppAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val internalApps = mutableListOf<AppData>()
private val partyApps = mutableListOf<AppData>()
private val templateApps = mutableListOf<TemplateAppData>()
private val privateApps = mutableListOf<AppData>()
var onItemClickListener: OnItemClickListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = AppViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_app,
parent,
false
)
)
holder.itemView.findViewById<View>(R.id.clickable_view).setOnClickListener {
val position = holder.adapterPosition
onItemClickListener?.onItemClick(parent, holder.itemView, position)
}
return holder
}
fun setInternalAppData(apps: List<AppData>) {
this.internalApps.clear()
this.internalApps.addAll(apps)
}
fun setPartyAppData(apps: List<AppData>) {
this.partyApps.clear()
this.partyApps.addAll(apps)
}
fun setPrivateAppData(apps: List<AppData>) {
this.privateApps.clear()
this.privateApps.addAll(apps)
}
fun setTemplateAppData(apps: List<TemplateAppData>) {
this.templateApps.clear()
this.templateApps.addAll(apps)
}
/**
* 应用显示顺序 内置页面 -> 内置 App -> 应用模板 -> 第三方应用
*/
fun getAppData(position: Int): AppData? {
return when (position) {
in 0 until internalApps.size -> {
internalApps[position]
}
in internalApps.size until internalApps.size + privateApps.size -> {
privateApps[position - internalApps.size]
}
in internalApps.size + privateApps.size until templateApps.size + internalApps.size + privateApps.size -> {
templateApps[position - internalApps.size - privateApps.size]
}
in templateApps.size + internalApps.size + privateApps.size until itemCount -> {
partyApps[position - internalApps.size - privateApps.size - templateApps.size]
}
else -> {
null
}
}
}
override fun getItemCount(): Int {
return partyApps.size + internalApps.size + templateApps.size + privateApps.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is AppViewHolder) {
val context = holder.itemView.context
try {
val app = getAppData(position) ?: return
when (app.appType) {
AppData.TYPE_PARTY, AppData.TYPE_INTERNAL -> {
if ((holder.itemView.tag == null
|| holder.itemView.tag?.toString() != "${app.name}|${app.packageName}")
&& app.icon != null
) {
Glide.with(context)
.asDrawable()
.load(app.icon)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(holder.iconView)
holder.itemView.tag = "${app.name}|${app.packageName}"
}
}
AppData.TYPE_TEMPLATE -> {
if ((holder.itemView.tag == null
|| holder.itemView.tag?.toString() != "${app.name}|${app.packageName}")
&& !app.iconUrl.isNullOrEmpty()
) {
Glide.with(context)
.asDrawable()
.load(app.iconUrl)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(holder.iconView)
holder.itemView.tag = "${app.name}|${app.packageName}"
}
}
}
holder.nameView.text = app.name
(holder.itemView.parent as? RecyclerView)?.let { recyclerView ->
val layoutManager =
recyclerView.layoutManager as? GridLayoutManager ?: return@let
val paddingBottom =
if (position / layoutManager.spanCount == itemCount / layoutManager.spanCount) {
recyclerView.resources.getDimensionPixelSize(R.dimen.dp_30)
} else {
0
}
if (paddingBottom != holder.itemView.paddingBottom) {
holder.itemView.updatePadding(bottom = paddingBottom)
}
}
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
private class AppViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val iconView = itemView.findViewById<ImageView>(R.id.icon)
val nameView = itemView.findViewById<TextView>(R.id.name)
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent.impl
import com.iflytek.cyber.evs.sdk.agent.PlaybackController
class PlaybackControllerImpl : PlaybackController()<file_sep>package com.iflytek.cyber.iot.show.core.demo
import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.provider.OpenableColumns
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.PermissionChecker
import androidx.core.view.isVisible
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
class MainActivity : AppCompatActivity() {
companion object {
private const val ACTION_PREFIX = "com.iflytek.cyber.iot.show.core.action"
private const val PERMISSION_PREFIX = "com.iflytek.cyber.iot.show.core.permission"
const val ACTION_INTERCEPTOR_RESULT = "$ACTION_PREFIX.INTERCEPTOR_RESULT"
const val ACTION_PLAY_TTS = "$ACTION_PREFIX.PLAY_TTS"
const val PERMISSION_RECEIVE_BROADCAST = "$PERMISSION_PREFIX.RECEIVE_BROADCAST"
const val EXTRA_PAYLOAD = "payload"
const val EXTRA_TYPE = "type"
const val EXTRA_TTS_TEXT = "tts_text"
const val EXTRA_TTS_PATH = "tts_path"
const val FILE_CHOOSE_CODE = 10010
const val REQUEST_PERMISSION_CODE = 10011
private val TTS_DIR = "${Environment.getExternalStorageDirectory()}/ShowCoreDemo"
private val TTS_FILE_PATH =
"$TTS_DIR/tts.mp3"
}
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
ACTION_INTERCEPTOR_RESULT -> {
Log.d("Receiver", intent.action.toString())
broadcast_action_name.text = intent.action
broadcast_type_value.text = intent.getStringExtra(EXTRA_TYPE)
broadcast_extra_value.text = intent.getStringExtra(EXTRA_PAYLOAD)
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val intentFilter = IntentFilter()
intentFilter.addAction(ACTION_INTERCEPTOR_RESULT)
registerReceiver(receiver, intentFilter)
tts_send_text.isChecked = true
tts_send_type_group.setOnCheckedChangeListener { group, checkedId ->
et_tts_text.isVisible = checkedId == R.id.tts_send_text
tts_path_container.isVisible = checkedId == R.id.tts_send_path
}
btn_choose_tts_path.setOnClickListener {
if (PermissionChecker.checkSelfPermission(
this,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PermissionChecker.PERMISSION_GRANTED
) {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "audio/mpeg"
intent.addCategory(Intent.CATEGORY_OPENABLE)
try {
startActivityForResult(
Intent.createChooser(intent, "选择一个可播放的 TTS 文件"),
FILE_CHOOSE_CODE
)
} catch (t: Throwable) {
t.printStackTrace()
}
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_PERMISSION_CODE
)
Toast.makeText(this, "请先授予读取外置存储权限", Toast.LENGTH_SHORT).show()
}
}
tts_send.setOnClickListener {
try {
val intent = Intent(ACTION_PLAY_TTS)
intent.setClassName(
"com.iflytek.cyber.iot.show.core",
"com.iflytek.cyber.iot.show.core.EngineService"
)
when (tts_send_type_group.checkedRadioButtonId) {
R.id.tts_send_path -> {
val file = File(TTS_FILE_PATH)
if (!file.exists()) {
Toast.makeText(this, "请先选择 TTS 文件", Toast.LENGTH_SHORT).show()
return@setOnClickListener
} else {
intent.putExtra(EXTRA_TTS_PATH, TTS_FILE_PATH)
}
}
R.id.tts_send_text -> {
val text = et_tts_text.text.toString()
if (text.isEmpty()) {
Toast.makeText(this, "请先选择 TTS 文件", Toast.LENGTH_SHORT).show()
return@setOnClickListener
} else {
intent.putExtra(EXTRA_TTS_TEXT, et_tts_text.text.toString())
}
}
}
startService(intent)
Toast.makeText(this, "已发送", Toast.LENGTH_SHORT).show()
} catch (t: Throwable) {
t.printStackTrace()
Toast.makeText(this, "请求失败", Toast.LENGTH_SHORT).show()
}
}
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(receiver)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
FILE_CHOOSE_CODE -> {
if (resultCode == RESULT_OK) {
val uri = data?.data ?: return
Log.d("FileChooser", uri.toString())
try {
contentResolver.query(uri, null, null, null, null)?.let { cursor ->
cursor.moveToFirst()
val name =
cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
tv_tts_file_name.text = name
cursor.close()
}
} catch (t: Throwable) {
t.printStackTrace()
}
try {
val fileDescriptor = contentResolver.openFileDescriptor(uri, "r") ?: return
val fd = fileDescriptor.fileDescriptor
val fis = FileInputStream(fd)
val ttsFileDir = File(TTS_DIR)
if (ttsFileDir.exists()) {
if (!ttsFileDir.isDirectory) {
ttsFileDir.mkdirs()
}
} else {
ttsFileDir.mkdirs()
}
val ttsFile = File(TTS_FILE_PATH)
if (ttsFile.exists()) {
ttsFile.delete()
}
ttsFile.createNewFile()
val fos = FileOutputStream(ttsFile)
val byteArray = ByteArray(1024)
var readSize = fis.read(byteArray)
while (readSize != -1) {
fos.write(byteArray, 0, readSize)
readSize = fis.read(byteArray)
}
fos.flush()
fis.close()
fos.close()
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
}
}
}
<file_sep>package com.iflytek.cyber.evs.sdk.agent
import androidx.annotation.CallSuper
import com.iflytek.cyber.evs.sdk.model.Constant
/**
* 视频播放器模块。详细介绍见https://doc.iflyos.cn/device/evs/reference/video_player.html#%E8%A7%86%E9%A2%91%E6%92%AD%E6%94%BE%E5%99%A8
*/
abstract class VideoPlayer {
val version = "1.0"
companion object {
const val NAME_PROGRESS_SYNC = "${Constant.NAMESPACE_VIDEO_PLAYER}.progress_sync"
const val NAME_VIDEO_OUT = "${Constant.NAMESPACE_VIDEO_PLAYER}.video_out"
const val SYNC_TYPE_STARTED = "STARTED"
const val SYNC_TYPE_FINISHED = "FINISHED"
const val SYNC_TYPE_FAILED = "FAILED"
const val SYNC_TYPE_NEARLY_FINISHED = "NEARLY_FINISHED"
const val STATE_IDLE = "IDLE"
@Deprecated("", replaceWith = ReplaceWith(STATE_PLAYING))
const val STATE_RUNNING = "PLAYING"
const val STATE_PLAYING = "PLAYING"
const val STATE_PAUSED = "PAUSED"
const val KEY_URL = "url"
const val KEY_STATE = "state"
const val KEY_RESOURCE_ID = "resource_id"
const val KEY_OFFSET = "offset"
const val KEY_CONTROL = "control"
const val KEY_BEHAVIOR = "behavior"
const val KEY_FAILURE_CODE = "failure_code"
const val KEY_TYPE = "type"
const val CONTROL_PLAY = "PLAY"
const val CONTROL_PAUSE = "PAUSE"
const val CONTROL_RESUME = "RESUME"
const val CONTROL_EXIT = "EXIT"
const val BEHAVIOR_IMMEDIATELY = "IMMEDIATELY"
const val BEHAVIOR_UPCOMING = "UPCOMING"
const val MEDIA_ERROR_UNKNOWN = "1001" // 发生了未知错误
const val MEDIA_ERROR_INVALID_REQUEST =
"1002" // 请求无效。可能的情况有:bad request, unauthorized, forbidden, not found等。
const val MEDIA_ERROR_SERVICE_UNAVAILABLE = "1003" // 设备端无法获取音频文件
const val MEDIA_ERROR_INTERNAL_SERVER_ERROR = "1004" // 服务端接收了请求但未能正确处理
const val MEDIA_ERROR_INTERNAL_DEVICE_ERROR = "1005" // 设备端内部错误
}
var state = STATE_IDLE
private set
get() {
return if (isVisible || field == STATE_PLAYING)
field
else
STATE_IDLE
}
var resourceId: String? = null
private set
var videoOffset = 0L
var isVisible = false
private val listeners = HashSet<VideoStateChangedListener>()
fun addListener(listener: VideoStateChangedListener) {
listeners.add(listener)
}
fun removeListener(listener: VideoStateChangedListener) {
listeners.remove(listener)
}
abstract fun getOffset(): Long
abstract fun getDuration(): Long
abstract fun play(resourceId: String, url: String): Boolean
@CallSuper
open fun seekTo(offset: Long): Boolean {
this.videoOffset = offset
return false
}
abstract fun pause(): Boolean
abstract fun resume(): Boolean
abstract fun stop(): Boolean
abstract fun exit(): Boolean
abstract fun moveToBackground(): Boolean
abstract fun moveToForegroundIfAvailable(): Boolean
fun onStarted(resourceId: String) {
state = STATE_PLAYING
this.resourceId = resourceId
listeners.map {
try {
it.onStarted(this, resourceId)
} catch (_: Exception) {
}
}
}
fun onResumed(resourceId: String) {
state = STATE_PLAYING
listeners.map {
try {
it.onResumed(this, resourceId)
} catch (_: Exception) {
}
}
}
fun onPaused(resourceId: String) {
state = STATE_PAUSED
listeners.map {
try {
it.onPaused(this, resourceId)
} catch (_: Exception) {
}
}
}
fun onStopped(resourceId: String) {
state = STATE_PAUSED
listeners.map {
try {
it.onStopped(this, resourceId)
} catch (_: Exception) {
}
}
}
fun onCompleted(resourceId: String) {
state = STATE_PAUSED
listeners.map {
try {
it.onCompleted(this, resourceId)
} catch (_: Exception) {
}
}
}
fun onPositionUpdated(resourceId: String, position: Long) {
videoOffset = position
listeners.map {
try {
it.onPositionUpdated(this, resourceId, position)
} catch (_: Exception) {
}
}
}
fun onError(resourceId: String, errorCode: String) {
state = STATE_PAUSED
listeners.map {
try {
it.onError(this, resourceId, errorCode)
} catch (_: Exception) {
}
}
}
interface VideoStateChangedListener {
fun onStarted(player: VideoPlayer, resourceId: String)
fun onResumed(player: VideoPlayer, resourceId: String)
fun onPaused(player: VideoPlayer, resourceId: String)
fun onStopped(player: VideoPlayer, resourceId: String)
fun onCompleted(player: VideoPlayer, resourceId: String)
fun onPositionUpdated(player: VideoPlayer, resourceId: String, position: Long)
fun onError(player: VideoPlayer, resourceId: String, errorCode: String)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Shader
import android.util.AttributeSet
import android.widget.TextView
class GradientTextView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : TextView(context, attrs, defStyleAttr) {
var startColor = Color.WHITE
set(value) {
field = value
if (isGradient)
paint.shader = currentShader()
if (width > 0 || height > 0)
text = text
}
var endColor = Color.WHITE
set(value) {
field = value
if (isGradient)
paint.shader = currentShader()
if (width > 0 || height > 0)
text = text
}
var isGradient = false
set(value) {
field = value
if (!value) {
paint.shader = null
} else {
paint.shader = currentShader()
}
if (width > 0 || height > 0)
text = text
}
override fun onDraw(canvas: Canvas?) {
if (isGradient && paint.shader !is LinearGradient)
paint.shader = currentShader()
super.onDraw(canvas)
}
private fun currentShader(): Shader {
return LinearGradient(
0f, 0f, width.toFloat(), 0f,
intArrayOf(
startColor,
startColor,
endColor
),
floatArrayOf(0f, 0.5f, 1f),
Shader.TileMode.CLAMP
)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.core.view.postDelayed
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.IotApi
import com.iflytek.cyber.iot.show.core.model.Action
import com.iflytek.cyber.iot.show.core.model.Device
import com.iflytek.cyber.iot.show.core.utils.clickWithTrigger
import com.iflytek.cyber.iot.show.core.utils.dp2Px
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import com.zhy.view.flowlayout.TagFlowLayout
import okhttp3.MediaType
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class DeviceDetailFragment : BaseFragment() {
companion object {
fun newInstance(deviceId: String?, iotInfoId: Int?): DeviceDetailFragment {
return DeviceDetailFragment().apply {
arguments = bundleOf(Pair("deviceId", deviceId), Pair("iotInfoId", iotInfoId))
}
}
}
private lateinit var ivDeviceIcon: ImageView
private lateinit var tvDeviceName: TextView
private lateinit var ivDeviceStatus: ImageView
private lateinit var tvDeviceStatus: TextView
private lateinit var tvZone: TextView
private lateinit var tvDeviceType: TextView
private lateinit var ivBrandIcon: ImageView
private lateinit var tvBrand: TextView
private lateinit var actionList: RecyclerView
private lateinit var mainContent: NestedScrollView
private lateinit var errorContainer: View
private lateinit var loading: LottieAnimationView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_device_detail, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ivDeviceIcon = view.findViewById(R.id.iv_device_icon)
tvDeviceName = view.findViewById(R.id.tv_device_name)
ivDeviceStatus = view.findViewById(R.id.iv_device_status)
tvDeviceStatus = view.findViewById(R.id.tv_status)
tvZone = view.findViewById(R.id.tv_zone)
tvDeviceType = view.findViewById(R.id.tv_device_type)
ivBrandIcon = view.findViewById(R.id.iv_brand_icon)
tvBrand = view.findViewById(R.id.tv_brand)
actionList = view.findViewById(R.id.action_list)
mainContent = view.findViewById(R.id.main_content)
errorContainer = view.findViewById(R.id.error_container)
loading = view.findViewById(R.id.loading)
view.findViewById<View>(R.id.back).clickWithTrigger {
pop()
}
showLoading()
val deviceId = arguments?.getString("deviceId")
val iotInfoId = arguments?.getInt("iotInfoId")
view.postDelayed(200) {
getDeviceDetail(deviceId, iotInfoId)
}
view.findViewById<Button>(R.id.retry).setOnClickListener {
showLoading()
getDeviceDetail(deviceId, iotInfoId)
}
}
private fun setupUI(device: Device) {
if (!isAdded || context == null) {
return
}
Glide.with(context!!)
.load(device.icon)
.into(ivDeviceIcon)
tvDeviceName.text = device.friendlyName
if (device.reacheable == true) {
ivDeviceStatus.isSelected = true
tvDeviceStatus.isSelected = true
tvDeviceStatus.text = "在线"
} else {
ivDeviceStatus.isSelected = false
tvDeviceStatus.isSelected = false
tvDeviceStatus.text = "离线"
}
if (!device.zone.isNullOrEmpty()) {
tvZone.isVisible = true
tvZone.text = device.zone
} else {
tvZone.isVisible = false
}
tvDeviceType.text = device.deviceType.describe
Glide.with(context!!)
.load(device.iotInfo?.iconUrl)
.into(ivBrandIcon)
tvBrand.text = device.iotInfo?.name
if (device.actions != null) {
actionList.adapter = ActionAdapter(device.actions)
}
}
private fun showLoading() {
mainContent.isVisible = false
errorContainer.isVisible = false
loading.isVisible = true
loading.playAnimation()
}
private fun hideLoading() {
loading.isVisible = false
loading.pauseAnimation()
}
private fun getDeviceDetail(deviceId: String?, iotInfoId: Int?) {
val json = JSONObject()
json["device_id"] = deviceId
json["iot_info_id"] = iotInfoId
val body = RequestBody.create(
MediaType.parse("application/json"),
json.toString()
)
getIotApi()?.getDeviceDetail(body)?.enqueue(object : Callback<Device> {
override fun onResponse(call: Call<Device>, response: Response<Device>) {
hideLoading()
if (response.isSuccessful) {
mainContent.isVisible = true
errorContainer.isVisible = false
val device = response.body()
if (device != null) {
setupUI(device)
}
} else {
errorContainer.isVisible = true
mainContent.isVisible = false
}
}
override fun onFailure(call: Call<Device>, t: Throwable) {
t.printStackTrace()
hideLoading()
errorContainer.isVisible = true
mainContent.isVisible = false
}
})
}
private fun getIotApi(): IotApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(IotApi::class.java)
} else {
null
}
}
private inner class ActionAdapter(val actions: ArrayList<Action>) :
RecyclerView.Adapter<ActionAdapter.ActionHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ActionHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_device_action, parent, false)
return ActionHolder(view)
}
override fun getItemCount(): Int {
return actions.size
}
private fun createActionText(context: Context, action: String?): TextView {
val textView = TextView(context)
textView.setPadding(16.dp2Px(), 12.dp2Px(), 16.dp2Px(), 12.dp2Px())
textView.setTextColor(Color.parseColor("#1784E9"))
textView.textSize = 16f
textView.setBackgroundResource(R.drawable.bg_light_blue_round_12dp)
val layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
layoutParams.marginStart = 8.dp2Px()
layoutParams.marginEnd = 8.dp2Px()
layoutParams.topMargin = 8.dp2Px()
layoutParams.bottomMargin = 8.dp2Px()
textView.layoutParams = layoutParams
textView.text = action
return textView
}
override fun onBindViewHolder(holder: ActionHolder, position: Int) {
val action = actions[position]
holder.tvName.text = action.name
holder.actionTag.adapter = object : TagAdapter<String>(action.values) {
override fun getView(parent: FlowLayout?, position: Int, t: String?): View {
return createActionText(holder.itemView.context, t)
}
}
}
inner class ActionHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvName = itemView.findViewById<TextView>(R.id.tv_name)
val actionTag = itemView.findViewById<TagFlowLayout>(R.id.action_tag)
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.view.isVisible
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.iflytek.cyber.iot.show.core.BuildConfig
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.SelfBroadcastReceiver
import com.iflytek.cyber.iot.show.core.impl.system.EvsSystem
import com.iflytek.cyber.iot.show.core.utils.*
import com.iflytek.cyber.iot.show.core.widget.StyledAlertDialog
import com.iflytek.cyber.product.ota.OtaService
import com.iflytek.cyber.product.ota.PackageEntityNew
class CheckUpdateFragment : BaseFragment() {
private var currentVersionContainer: View? = null
private var currentVersion: TextView? = null
private var loadingContainer: View? = null
private var loadingView: LottieAnimationView? = null
private var newVersionContainer: View? = null
private var newVersionTitleView: TextView? = null
private var newVersionDescriptionView: TextView? = null
private var updateButton: TextView? = null
private var progressContainer: View? = null
private var tvProgress: TextView? = null
private var progressBar: ProgressBar? = null
private var failedContainer: View? = null
private var tvProgressDescription: TextView? = null
private var tvFailed: TextView? = null
private var tvDownloadCompleted: TextView? = null
private var progressBarCompleted: ProgressBar? = null
private var packageEntity: PackageEntityNew? = null
private var downloadedPath: String? = null
private var otaService: OtaService? = null
private var backCount = 0
private val otaReceiver = object : SelfBroadcastReceiver(
OtaService.ACTION_CHECK_UPDATE_RESULT,
OtaService.ACTION_CHECK_UPDATE_FAILED,
OtaService.ACTION_NEW_UPDATE_DOWNLOADED,
OtaService.ACTION_NEW_UPDATE_DOWNLOAD_STARTED
) {
override fun onReceiveAction(action: String, intent: Intent) {
when (action) {
OtaService.ACTION_CHECK_UPDATE_RESULT -> {
if (intent.hasExtra(OtaService.EXTRA_PACKAGE_ENTITY)) {
val packageEntity =
intent.getParcelableExtra<PackageEntityNew>(
OtaService.EXTRA_PACKAGE_ENTITY
)
showNewVersion(packageEntity.versionName, packageEntity.description)
this@CheckUpdateFragment.packageEntity = packageEntity
if (otaService?.isUrlDownloaded(packageEntity.url) == true) {
showProgress()
downloadProgressCallback.onDownloadProgress(packageEntity.id!!, 100)
downloadedPath = otaService?.getUrlDownloadedPath(packageEntity.url)
updateButton?.post {
updateButton?.isVisible = true
updateButton?.setText(R.string.install_now)
}
}
} else {
showCurrent()
packageEntity = null
}
}
OtaService.ACTION_NEW_UPDATE_DOWNLOAD_STARTED -> {
showProgress()
updateButton?.isVisible = false
tvProgressDescription?.setText(R.string.downloading_software)
}
OtaService.ACTION_NEW_UPDATE_DOWNLOADED -> {
updateButton?.isVisible = true
updateButton?.setText(R.string.install_now)
tvDownloadCompleted?.isVisible = true
tvProgress?.isVisible = false
progressBar?.isVisible = false
progressBarCompleted?.isVisible = true
downloadProgressCallback.onDownloadProgress(packageEntity?.id!!, 100)
downloadedPath = intent.getStringExtra(OtaService.EXTRA_PATH)
tvProgressDescription?.setText(R.string.download_completed)
}
OtaService.ACTION_CHECK_UPDATE_FAILED -> {
showFailed()
intent.getStringExtra(OtaService.EXTRA_MESSAGE)?.let { message ->
tvFailed?.text = message
} ?: run {
tvFailed?.setText(R.string.update_failed_common)
}
packageEntity = null
}
}
}
}
private val serviceConnection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName?) {
otaService?.unregisterDownloadProgressCallback(downloadProgressCallback)
otaService = null
}
override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
if (binder is OtaService.OtaBinder) {
otaService = binder.service()
otaService?.registerDownloadProgressCallback(downloadProgressCallback)
}
}
}
private val downloadProgressCallback = object : OtaService.DownloadProgressCallback {
override fun onDownloadProgress(id: Long, progress: Int) {
val context = context ?: return
if (id != packageEntity?.id)
return
if (!isSupportVisible || isDetached)
return
tvProgress?.post {
tvProgress?.text = context.getString(R.string.count_of_percent, progress)
progressBar?.progress = progress
if (progress == 100) {
tvProgressDescription?.setText(R.string.download_completed)
} else {
showProgress()
tvProgressDescription?.setText(R.string.downloading_software)
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
otaReceiver.register(context)
val intent = Intent(context, OtaService::class.java)
context?.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_check_update, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
loadingContainer = view.findViewById(R.id.loading_container)
currentVersion = view.findViewById(R.id.current_version)
currentVersionContainer = view.findViewById(R.id.current_version_container)
loadingView = view.findViewById(R.id.loading)
newVersionContainer = view.findViewById(R.id.new_version_container)
newVersionTitleView = view.findViewById(R.id.new_version_title)
newVersionDescriptionView = view.findViewById(R.id.new_version_description)
updateButton = view.findViewById(R.id.update_button)
progressContainer = view.findViewById(R.id.progress_container)
tvProgress = view.findViewById(R.id.tv_progress)
progressBar = view.findViewById(R.id.progress_bar)
failedContainer = view.findViewById(R.id.failed_container)
tvProgressDescription = view.findViewById(R.id.progress_description)
tvFailed = view.findViewById(R.id.failed_message)
tvDownloadCompleted = view.findViewById(R.id.download_completed)
progressBarCompleted = view.findViewById(R.id.progress_bar_completed)
view.findViewById<View>(R.id.back)?.setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
view.findViewById<View>(R.id.retry)?.setOnClickListener {
val checkUpdate = Intent(context, OtaService::class.java)
checkUpdate.action = OtaService.ACTION_REQUEST_CHECKING
context?.startService(checkUpdate)
}
updateButton?.setOnClickListener {
val checkSize = if (downloadedPath != null) {
1.0 * 1024 * 1024 * 1024
} else {
1.5 * 1024 * 1024 * 1024
}
if (CleanerUtils.getSdcardFreeSpace() <= checkSize) {
// 下载或升级要求剩余控件 1.5G 以上
fragmentManager?.let {
StyledAlertDialog.Builder()
.setTitle("设备可用空间不足")
.setMessage("设备可用空间不足,是否清理缓存")
.setPositiveButton("清理", View.OnClickListener { view ->
TerminalUtils.execute("rm /sdcard/ota_update.zip")
CleanerUtils.clearRecordDebugFiles()
CleanerUtils.clearWakeWordCache(view.context)
CleanerUtils.clearCache(view.context)
})
.setNegativeButton(getString(R.string.cancel), null)
.show(it)
}
return@setOnClickListener
}
downloadedPath?.let { path ->
if (DeviceUtils.getBatteryLevel(context) < 40) {
// 下载或升级要求剩余控件 1.5G 以上
fragmentManager?.let {
StyledAlertDialog.Builder()
.setTitle("设备电量不足")
.setMessage("请将设备电量保持在 40% 上再进行固件更新")
.setPositiveButton(getString(R.string.ensure), null)
.show(it)
}
return@setOnClickListener
}
PackageUtils.notifyInstallApk(it.context, path)
ConfigUtils.putBoolean(ConfigUtils.KEY_OTA_REQUEST, true)
packageEntity?.let { packageEntityNew ->
EvsSystem.get().sendUpdateSoftwareStarted(
packageEntityNew.versionName.toString(),
packageEntityNew.description
)
ConfigUtils.putInt(
ConfigUtils.KEY_OTA_VERSION_ID, packageEntityNew.versionId?.toInt()
?: 0
)
ConfigUtils.putString(
ConfigUtils.KEY_OTA_VERSION_NAME,
packageEntityNew.versionName
)
ConfigUtils.putString(
ConfigUtils.KEY_OTA_VERSION_DESCRIPTION,
packageEntityNew.description
)
}
} ?: run {
val packageEntity = packageEntity ?: return@run
downloadProgressCallback.onDownloadProgress(packageEntity.id!!, 0)
val intent = Intent(it.context, OtaService::class.java)
intent.action = OtaService.ACTION_REQUEST_DOWNLOAD
intent.putExtra(OtaService.EXTRA_ID, packageEntity.id ?: -1L)
intent.putExtra(OtaService.EXTRA_URL, packageEntity.url)
context?.startService(intent)
}
}
loadingView?.repeatCount = LottieDrawable.INFINITE
loadingView?.playAnimation()
progressBar?.max = 100
currentVersion?.text = getString(R.string.version_value, BuildConfig.VERSION_NAME)
val checkUpdate = Intent(context, OtaService::class.java)
checkUpdate.action = OtaService.ACTION_REQUEST_CHECKING
context?.startService(checkUpdate)
}
override fun onDestroy() {
super.onDestroy()
otaReceiver.unregister(context)
context?.unbindService(serviceConnection)
}
private fun showNewVersion(title: String?, message: String?) {
newVersionTitleView?.text =
getString(R.string.new_version_title, title)
updateButton?.setText(R.string.update_now)
newVersionDescriptionView?.text = message
newVersionContainer?.isVisible = true
loadingContainer?.isVisible = false
failedContainer?.isVisible = false
currentVersionContainer?.isVisible = false
hideProgress()
}
private fun showProgress() {
progressContainer?.isVisible = true
updateButton?.isVisible = false
}
private fun hideProgress() {
updateButton?.isVisible = true
progressContainer?.isVisible = false
}
private fun showFailed() {
failedContainer?.isVisible = true
loadingContainer?.isVisible = false
currentVersionContainer?.isVisible = false
progressContainer?.isVisible = false
newVersionContainer?.isVisible = false
}
private fun showCurrent() {
currentVersionContainer?.isVisible = true
newVersionContainer?.isVisible = false
loadingContainer?.isVisible = false
failedContainer?.isVisible = false
progressContainer?.isVisible = false
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.AppApi
import com.iflytek.cyber.iot.show.core.model.*
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
import com.iflytek.cyber.iot.show.core.widget.StyledProgressDialog
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
import kotlin.math.min
class TemplateXmlySectionContentFragment : Fragment() {
companion object {
const val TAG = "TemplateCategoryContentFragment"
private const val LIMIT = 10
fun fromCategoryList(
templateApp: TemplateApp?,
section: String,
categoryList: List<XmlyCategoryItem>
): TemplateXmlySectionContentFragment {
val fragment = TemplateXmlySectionContentFragment()
fragment.templateApp = templateApp
fragment.isCategoryList = true
fragment.section = section
fragment.categoryList.addAll(categoryList)
//fragment.sectionContentAdapter.isCategoryList = true
return fragment
}
fun fromAlbumList(
templateApp: TemplateApp?,
section: String,
albumList: List<XmlyAlbumItem>
): TemplateXmlySectionContentFragment {
val fragment = TemplateXmlySectionContentFragment()
fragment.templateApp = templateApp
fragment.isCategoryList = false
fragment.section = section
fragment.albumList.addAll(albumList)
//fragment.sectionContentAdapter.isCategoryList = false
return fragment
}
fun newInstance(
templateApp: TemplateApp?,
section: String
): TemplateXmlySectionContentFragment {
val fragment = TemplateXmlySectionContentFragment()
fragment.templateApp = templateApp
fragment.section = section
return fragment
}
}
private var isCategoryList = false
private var section: String? = null
private var templateApp: TemplateApp? = null
private val categoryList = mutableListOf<XmlyCategoryItem>()
private val albumList = mutableListOf<XmlyAlbumItem>()
//private val sectionContentAdapter = XmlySectionContentAdapter()
private val sectionContentAdapter = SectionContentAdapter()
private var page = 1
private var isLoading = false
private var isLoadComplete = false
private var recyclerView: RecyclerView? = null
private var loading: LottieAnimationView? = null
private var loadingBottom: LottieAnimationView? = null
private var errorContainer: View? = null
private var tvError: TextView? = null
private var errorRetry: View? = null
private var tvRetry: TextView? = null
private var progressDialog: StyledProgressDialog? = null
private var onScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (isLoading || isLoadComplete)
return
(recyclerView.layoutManager as? LinearLayoutManager)?.let {
if (it.findLastCompletelyVisibleItemPosition() == it.findLastVisibleItemPosition() &&
recyclerView.adapter?.itemCount == it.findLastVisibleItemPosition() + 1
) {
page++
getSectionContent()
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_template_category_content, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view.findViewById(R.id.template_category_content)
loading = view.findViewById(R.id.loading)
loadingBottom = view.findViewById(R.id.loading_bottom)
tvError = view.findViewById(R.id.tv_error)
errorContainer = view.findViewById(R.id.error_container)
errorRetry = view.findViewById(R.id.error_retry)
tvRetry = view.findViewById(R.id.tv_retry)
recyclerView?.adapter = sectionContentAdapter
recyclerView?.addOnScrollListener(onScrollListener)
//sectionContentAdapter.isCategoryList = isCategoryList
errorRetry?.setOnClickListener {
getSectionContent()
}
applyTheme(templateApp?.isDark != false)
/*sectionContentAdapter.onSubItemClickListener = object : OnSubItemClickListener {
override fun onSubItemClick(
parent: ViewGroup,
view: View,
position: Int,
subPosition: Int
) {
if (sectionContentAdapter.isCategoryList) {
sectionContentAdapter.getCategoryItem(position)?.let { categoryItem ->
categoryItem.result?.get(subPosition)?.let { album ->
(parentFragment as? BaseFragment)?.start(
TemplateXmlyAlbumFragment.newInstance(
templateApp,
album.id,
album.name
)
)
}
}
} else {
sectionContentAdapter.getAlbumItem(position)?.let { albumItem ->
if (isAdded && context != null && !NetworkUtils.isNetConnected(context)) {
PromptManager.play(PromptManager.NETWORK_LOST)
return
}
albumItem.result?.get(subPosition)?.let { mediaItem ->
postPlay(mediaItem, albumItem.albumId)
}
}
}
}
}
sectionContentAdapter.onMoreClickListener = object : OnMoreClickListener {
override fun onMoreClick(parent: ViewGroup, view: View, position: Int) {
if (sectionContentAdapter.isCategoryList) {
sectionContentAdapter.getCategoryItem(position)?.let { categoryItem ->
(parentFragment as? BaseFragment)?.start(
TemplateXmlyContentListFragment.fromCategory(
templateApp,
section,
categoryItem.categoryId,
categoryItem.categoryName
)
)
}
} else {
sectionContentAdapter.getAlbumItem(position)?.let { albumItem ->
(parentFragment as? BaseFragment)?.start(
TemplateXmlyContentListFragment.fromAlbum(
templateApp,
section,
albumItem.albumId,
albumItem.name
)
)
}
}
}
}*/
sectionContentAdapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: ViewGroup, itemView: View, position: Int) {
val albumItem = sectionContentAdapter.getAlbumItem(position)
if (albumItem != null) {
val newItem = AlbumItem(
album = null,
business = templateApp?.business,
source = templateApp?.source,
type = null,
albumId = albumItem.albumId,
cover = albumItem.cover,
title = albumItem.name,
from = templateApp?.name,
result = null)
(parentFragment as? BaseFragment)?.apply {
start(
SongListFragment.newInstance(newItem, 2, 1001)
)
}
}
}
}
if (isCategoryList) {
if (categoryList.isNotEmpty()) {
val categoryItem = categoryList[0]
page = 1
var firstCover: String? = null
categoryItem.result?.map { albumItem ->
if (!albumItem.cover.isNullOrEmpty() && firstCover.isNullOrEmpty()) {
try {
Uri.parse(albumItem.cover)?.let {
firstCover = albumItem.cover
}
} catch (t: Throwable) {
}
}
}
if (firstCover.isNullOrEmpty()) {
recyclerView?.let { recyclerView ->
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
//sectionContentAdapter.setCategoryList(categoryList)
}
} else {
getSectionContent()
}
} else {
if (albumList.isNotEmpty()) {
val albumItem = albumList[0]
page = 1
var firstCover: String? = albumItem.cover
/*albumItem.result?.map { mediaItem ->
if (!mediaItem.cover.isNullOrEmpty() && firstCover.isNullOrEmpty()) {
try {
Uri.parse(mediaItem.cover)?.let {
firstCover = mediaItem.cover
}
} catch (t: Throwable) {
}
}
}*/
if (firstCover.isNullOrEmpty()) {
recyclerView?.let { recyclerView ->
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
sectionContentAdapter.setAlbumList(albumList)
} else {
loading?.isVisible = true
loading?.repeatMode = LottieDrawable.RESTART
loading?.repeatCount = LottieDrawable.INFINITE
loading?.playAnimation()
Glide.with(this)
.asBitmap()
.load(firstCover)
.into(object : CustomTarget<Bitmap>() {
override fun onLoadFailed(errorDrawable: Drawable?) {
super.onLoadFailed(errorDrawable)
hideLoading()
recyclerView?.let { recyclerView ->
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
sectionContentAdapter.setAlbumList(albumList)
sectionContentAdapter.notifyDataSetChanged()
}
override fun onLoadCleared(placeholder: Drawable?) {
}
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?
) {
val ratio =
1f * resource.width / resource.height
sectionContentAdapter.ratio = ratio
setLayoutManager(ratio)
recyclerView?.let { recyclerView ->
when {
ratio <= 1f -> {
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
ratio > 1f -> {
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingBottom
)
}
}
hideLoading()
sectionContentAdapter.setAlbumList(albumList)
sectionContentAdapter.notifyDataSetChanged()
}
}
})
}
} else {
getSectionContent()
}
}
}
private fun setLayoutManager(ratio: Float) {
val layoutManager = if (ratio <= 1) {
GridLayoutManager(context, 5)
} else {
GridLayoutManager(context, 3)
}
recyclerView?.post {
recyclerView?.layoutManager = layoutManager
}
}
override fun onDestroy() {
super.onDestroy()
recyclerView?.removeOnScrollListener(onScrollListener)
}
private fun showProgress(title: String, message: String? = null) {
if (isRemoving || isDetached)
return
context ?: return
progressDialog = StyledProgressDialog.Builder()
.setTitle(title)
.setMessage(message)
.show(fragmentManager)
}
private fun dismissProgress() {
if (isRemoving || isDetached)
return
context ?: return
progressDialog?.let {
it.dismiss()
progressDialog = null
}
}
private fun showLoading() {
if (page == 1) {
loading?.isVisible = true
loading?.repeatCount = LottieDrawable.INFINITE
loading?.repeatMode = LottieDrawable.RESTART
loading?.playAnimation()
} else {
loadingBottom?.isVisible = true
loadingBottom?.repeatCount = LottieDrawable.INFINITE
loadingBottom?.repeatMode = LottieDrawable.RESTART
loadingBottom?.playAnimation()
}
}
private fun hideLoading() {
if (isRemoving || isDetached)
return
context ?: return
if (loading?.isVisible == true) {
loading?.pauseAnimation()
loading?.isVisible = false
}
if (loadingBottom?.isVisible == true) {
loadingBottom?.pauseAnimation()
loadingBottom?.isVisible = false
}
}
private fun showError(message: String?, showRetry: Boolean? = true) {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = false
errorContainer?.isVisible = true
tvError?.text = message
errorRetry?.isVisible = showRetry == true
}
private fun hideError() {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = true
errorContainer?.isVisible = false
}
private fun getSectionContent() {
val section = section ?: return
isLoading = true
showLoading()
hideError()
getAppApi()?.getXmlyIndex(section, page)?.enqueue(object :
Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
isLoading = false
hideLoading()
if (t is UnknownHostException) {
showError("Ooooops,请检查网络后重试")
} else {
showError("请求出错")
}
}
override fun onResponse(
call: Call<ResponseBody>, response: Response<ResponseBody>
) {
if (isRemoving || isDetached)
return
context ?: return
isLoading = false
if (response.isSuccessful) {
response.body()?.let { body ->
val bodyString = body.string()
Thread {
try {
val json = JSON.parseObject(bodyString)
val resultArray = json.getJSONArray("result")
var isCategoryList = false
if (page == 1 && resultArray.size > 0) {
val sample = resultArray.getJSONObject(0)
if (sample.containsKey("category_id")) {
isCategoryList = true
}
} else {
isCategoryList =
this@TemplateXmlySectionContentFragment.isCategoryList
}
//sectionContentAdapter.isCategoryList = isCategoryList
if (isCategoryList) {
val categoryList = mutableListOf<XmlyCategoryItem>()
var firstCover: String? = null
for (index in 0 until resultArray.size) {
val jsonItem = resultArray.getJSONObject(index)
val categoryItem = JSON.parseObject(
jsonItem.toString(),
XmlyCategoryItem::class.java
)
categoryItem.result?.map { albumItem ->
if (firstCover.isNullOrEmpty()) {
firstCover = albumItem.cover
}
}
categoryList.add(categoryItem)
}
if (categoryList.size < LIMIT)
isLoadComplete = true
if (page == 1) {
if (firstCover.isNullOrEmpty()) {
/*sectionContentAdapter.setCategoryList(
categoryList
)*/
sectionContentAdapter.notifyDataSetChanged()
} else
Glide.with(this@TemplateXmlySectionContentFragment)
.asBitmap()
.load(firstCover)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?
) {
val ratio =
1f * resource.width / resource.height
sectionContentAdapter.ratio = ratio
setLayoutManager(ratio)
recyclerView?.let { recyclerView ->
recyclerView.post {
when {
ratio <= 1f -> {
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
ratio > 1f -> {
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingBottom
)
}
}
hideLoading()
/* sectionContentAdapter.setCategoryList(
categoryList
)*/
sectionContentAdapter.notifyDataSetChanged()
}
}
}
override fun onLoadCleared(placeholder: Drawable?) {
}
})
} else {
//sectionContentAdapter.appendCategoryList(categoryList)
recyclerView?.post {
hideLoading()
sectionContentAdapter.notifyDataSetChanged()
}
}
} else {
val albumList = mutableListOf<XmlyAlbumItem>()
var firstCover: String? = null
for (index in 0 until resultArray.size) {
val jsonItem = resultArray.getJSONObject(index)
val albumItem = JSON.parseObject(
jsonItem.toString(),
XmlyAlbumItem::class.java
)
/*albumItem.result?.map { mediaItem ->
if (firstCover.isNullOrEmpty()) {
firstCover = mediaItem.cover
}
}*/
if (firstCover.isNullOrEmpty()) {
firstCover = albumItem.cover
}
albumList.add(albumItem)
}
if (page == 1) {
if (albumList.isEmpty()) {
showError("Ooooops,找不到结果", false)
}
if (firstCover.isNullOrEmpty()) {
recyclerView?.let { recyclerView ->
recyclerView.post {
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
sectionContentAdapter.setAlbumList(albumList)
sectionContentAdapter.notifyDataSetChanged()
hideLoading()
}
}
} else
Glide.with(this@TemplateXmlySectionContentFragment)
.asBitmap()
.load(firstCover)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?
) {
val ratio =
1f * resource.width / resource.height
sectionContentAdapter.ratio = ratio
setLayoutManager(ratio)
recyclerView?.let { recyclerView ->
recyclerView.post {
when {
ratio <= 1f -> {
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
ratio > 1f -> {
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingBottom
)
}
}
hideLoading()
sectionContentAdapter.setAlbumList(
albumList
)
sectionContentAdapter.notifyDataSetChanged()
}
}
}
override fun onLoadCleared(placeholder: Drawable?) {
}
})
} else {
sectionContentAdapter.appendAlbumList(albumList)
recyclerView?.post {
hideLoading()
sectionContentAdapter.notifyDataSetChanged()
}
}
}
} catch (t: Throwable) {
t.printStackTrace()
}
}.start()
}
} else {
showError("请求出错")
}
}
})
}
private fun postPlay(mediaItem: MediaItem, id: String?) {
val audioId = mediaItem.id ?: return
val sourceType = mediaItem.source ?: templateApp?.source ?: return
val albumId = mediaItem.albumId ?: id ?: return
showProgress(getString(R.string.loading), getString(R.string.please_wait))
val json = JSONObject()
json["audio_id"] = audioId
json["source_type"] = sourceType
json["album_id"] = albumId
val requestBody = RequestBody.create(
MediaType.parse("application/json"),
json.toString()
)
getAppApi()?.postPlayMedia(requestBody)?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
dismissProgress()
Toast.makeText(context, "请求出错", Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (isRemoving || isDetached)
return
context ?: return
dismissProgress()
if (response.isSuccessful) {
Toast.makeText(context, "开始播放", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, "播放失败", Toast.LENGTH_SHORT).show()
}
}
})
}
fun applyTheme(isDark: Boolean) {
sectionContentAdapter.isDark = isDark
if (sectionContentAdapter.itemCount != 0) {
sectionContentAdapter.notifyDataSetChanged()
}
tvError?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
tvRetry?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
errorRetry?.setBackgroundResource(
if (isDark)
R.drawable.bg_round_border_white_36dp
else
R.drawable.bg_round_border_black_36dp
)
}
private fun getAppApi(): AppApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(AppApi::class.java)
}
private class SectionContentAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
const val TYPE_1P0 = 0
const val TYPE_1P6 = 1
const val TYPE_0P75 = 2
}
private val albumList = mutableListOf<XmlyAlbumItem>()
var onItemClickListener: OnItemClickListener? = null
var isDark = false
var ratio = 1f
fun getAlbumItem(position: Int) = if (position < albumList.size) albumList[position] else null
fun setAlbumList(albumList: List<XmlyAlbumItem>) {
this.albumList.clear()
this.albumList.addAll(albumList)
}
fun appendAlbumList(albumList: List<XmlyAlbumItem>) {
this.albumList.addAll(albumList)
}
override fun getItemViewType(position: Int): Int {
return when {
ratio < 1 -> TYPE_0P75
ratio == 1f -> TYPE_1P0
else -> TYPE_1P6
}
}
override fun getItemCount(): Int {
return albumList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = when (viewType) {
TYPE_1P6 -> SectionContentHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_single_album_1p6,
parent,
false
)
)
TYPE_1P0 -> SectionContentHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_single_album_1p0,
parent,
false
)
)
else -> SectionContentHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_single_album_0p75,
parent,
false
)
)
}
holder.itemView.setOnClickListener {
onItemClickListener?.onItemClick(parent, it, holder.adapterPosition)
}
return holder
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is SectionContentHolder) {
val albumItem = albumList[position]
if (isDark) {
holder.titleTextView.setTextColor(Color.WHITE)
holder.subTitleTextView.setTextColor(Color.WHITE)
} else {
holder.titleTextView.setTextColor(Color.BLACK)
holder.subTitleTextView.setTextColor(Color.BLACK)
}
holder.indexTextView.text = (position + 1).toString()
holder.titleTextView.text = albumItem.name
holder.subTitleTextView.isVisible = !albumItem.subtitle.isNullOrEmpty()
holder.subTitleTextView.text = albumItem.subtitle
if (!albumItem.cover.isNullOrEmpty()) {
try {
Uri.parse(albumItem.cover)?.let { uri ->
Glide.with(holder.albumImageView)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transform(
MultiTransformation(
CenterCrop(), RoundedCornersTransformation(
holder.albumImageView.resources.getDimensionPixelSize(
R.dimen.dp_6
), 0
)
)
)
.into(holder.albumImageView)
}
} catch (t: Throwable) {
t.printStackTrace()
holder.albumImageView.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
holder.albumImageView.setImageResource(R.drawable.bg_default_template_app_2)
}
}
}
}
private class SectionContentHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val albumImageView = itemView.findViewById<ImageView>(R.id.album_media_0)
val indexTextView = itemView.findViewById<TextView>(R.id.index_media_0)
val titleTextView = itemView.findViewById<TextView>(R.id.title_media_0)
val subTitleTextView = itemView.findViewById<TextView>(R.id.subtitle_media_0)
}
private class XmlySectionContentAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
const val TYPE_1P0 = 0
const val TYPE_1P6 = 1
const val TYPE_0P75 = 2
}
var isCategoryList = false
private val categoryList = mutableListOf<XmlyCategoryItem>()
private val albumList = mutableListOf<XmlyAlbumItem>()
var isDark = false
var onMoreClickListener: OnMoreClickListener? = null
var onSubItemClickListener: OnSubItemClickListener? = null
private val innerOnSubItemClickListener = object : OnSubItemClickListener {
override fun onSubItemClick(
parent: ViewGroup,
view: View,
position: Int,
subPosition: Int
) {
onSubItemClickListener?.onSubItemClick(
parent, view, position, subPosition
)
}
}
var ratio = 1f
fun setCategoryList(categoryList: List<XmlyCategoryItem>) {
clear()
this.categoryList.addAll(categoryList)
}
fun appendCategoryList(categoryList: List<XmlyCategoryItem>) {
this.categoryList.addAll(categoryList)
}
fun getCategoryItem(position: Int): XmlyCategoryItem? {
return if (categoryList.size > position) {
categoryList[position]
} else {
null
}
}
fun getAlbumItem(position: Int): XmlyAlbumItem? {
return if (albumList.size > position) {
albumList[position]
} else {
null
}
}
fun setAlbumList(albumList: List<XmlyAlbumItem>) {
clear()
this.albumList.addAll(albumList)
}
fun appendAlbumList(albumList: List<XmlyAlbumItem>) {
this.albumList.addAll(albumList)
}
fun clear() {
categoryList.clear()
albumList.clear()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = when (viewType) {
TYPE_1P6 -> AlbumItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_album_1p6,
parent,
false
)
)
TYPE_1P0 -> AlbumItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_album_1p0,
parent,
false
)
)
else -> AlbumItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_album_0p75,
parent,
false
)
)
}
holder.childList.mapIndexed { index, item ->
item.ivAlbumMedia?.setOnClickListener {
innerOnSubItemClickListener.onSubItemClick(
parent,
holder.itemView,
holder.adapterPosition,
index
)
}
}
holder.seeMore?.setOnClickListener {
onMoreClickListener?.onMoreClick(parent, it, holder.adapterPosition)
}
return holder
}
override fun getItemViewType(position: Int): Int {
return when {
ratio < 1 -> TYPE_0P75
ratio == 1f -> TYPE_1P0
else -> TYPE_1P6
}
}
override fun getItemCount(): Int {
return if (isCategoryList) {
categoryList.size
} else {
albumList.size
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder !is AlbumItemViewHolder) return
val childSize = holder.fullChildSize()
var indexSize = 0
for (i in 0 until position) {
indexSize += if (isCategoryList)
min(childSize, categoryList[i].result?.size ?: 0)
else
min(childSize, albumList[i].result?.size ?: 0)
}
if (isCategoryList) {
val categoryItem = categoryList[position]
holder.setupCategory(categoryItem, isDark, indexSize)
} else {
val albumItem = albumList[position]
holder.setupAlbum(albumItem, isDark, indexSize)
}
}
}
private class AlbumItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvAlbumTitle: TextView? = itemView.findViewById(R.id.album_title)
val seeMore: View? = itemView.findViewById(R.id.album_more)
val tvMore: TextView? = itemView.findViewById(R.id.tv_more)
val ivMore: ImageView? = itemView.findViewById(R.id.iv_more)
val childList = listOf(
MediaGroup(
itemView,
R.id.album_media_0,
R.id.title_media_0,
R.id.subtitle_media_0,
R.id.index_media_0
),
MediaGroup(
itemView,
R.id.album_media_1,
R.id.title_media_1,
R.id.subtitle_media_1,
R.id.index_media_1
),
MediaGroup(
itemView,
R.id.album_media_2,
R.id.title_media_2,
R.id.subtitle_media_2,
R.id.index_media_2
),
MediaGroup(
itemView,
R.id.album_media_3,
R.id.title_media_3,
R.id.subtitle_media_3,
R.id.index_media_3
),
MediaGroup(
itemView,
R.id.album_media_4,
R.id.title_media_4,
R.id.subtitle_media_4,
R.id.index_media_4
)
)
fun setupCategory(categoryItem: XmlyCategoryItem, isDark: Boolean, indexFirst: Int) {
val childSize = fullChildSize()
tvAlbumTitle?.text = categoryItem.categoryName
seeMore?.isVisible =
!categoryItem.result.isNullOrEmpty() && categoryItem.result.size > childSize
if (isDark) {
tvAlbumTitle?.setTextColor(Color.WHITE)
tvMore?.setTextColor(Color.WHITE)
ivMore?.imageTintList = ColorStateList.valueOf(Color.WHITE)
} else {
tvAlbumTitle?.setTextColor(Color.BLACK)
tvMore?.setTextColor(Color.BLACK)
ivMore?.imageTintList = ColorStateList.valueOf(Color.BLACK)
}
for (i in 0 until childSize) {
if (i < categoryItem.result?.size ?: 0) {
categoryItem.result?.get(i)?.let { albumItem ->
childList[i].setupAlbumItem(
albumItem,
isDark,
(indexFirst + i + 1).toString()
)
childList[i].setVisible(true)
} ?: run {
childList[i].setVisible(false)
}
} else {
childList[i].setVisible(false)
}
}
}
fun setupAlbum(albumItem: XmlyAlbumItem, isDark: Boolean, indexFirst: Int) {
val childSize = fullChildSize()
tvAlbumTitle?.text = albumItem.name
seeMore?.isVisible =
!albumItem.result.isNullOrEmpty() && albumItem.result.size > childSize
if (isDark) {
tvAlbumTitle?.setTextColor(Color.WHITE)
tvMore?.setTextColor(Color.WHITE)
ivMore?.imageTintList = ColorStateList.valueOf(Color.WHITE)
} else {
tvAlbumTitle?.setTextColor(Color.BLACK)
tvMore?.setTextColor(Color.BLACK)
ivMore?.imageTintList = ColorStateList.valueOf(Color.BLACK)
}
for (i in 0 until childSize) {
if (i < albumItem.result?.size ?: 0) {
albumItem.result?.get(i)?.let { mediaItem ->
childList[i].setupMediaItem(
mediaItem,
isDark,
(indexFirst + i + 1).toString()
)
childList[i].setVisible(true)
} ?: run {
childList[i].setVisible(false)
}
} else {
childList[i].setVisible(false)
}
}
}
fun fullChildSize() = if (childList[3].exists()) 5 else 3
}
private class MediaGroup(
itemView: View,
albumId: Int,
titleId: Int,
subtitleId: Int,
indexId: Int
) {
val ivAlbumMedia: ImageView? = itemView.findViewById(albumId)
val tvAlbumTitle: TextView? = itemView.findViewById(titleId)
val tvAlbumSubtitle: TextView? = itemView.findViewById(subtitleId)
val tvAlbumIndex: TextView? = itemView.findViewById(indexId)
fun exists() = ivAlbumMedia != null
fun setVisible(isVisible: Boolean) {
ivAlbumMedia?.isVisible = isVisible
tvAlbumTitle?.isVisible = isVisible
tvAlbumSubtitle?.isVisible = isVisible
tvAlbumIndex?.isVisible = isVisible
}
fun setupAlbumItem(albumItem: XmlyAlbumItem, isDark: Boolean, indexValue: String) {
tvAlbumTitle?.text = albumItem.name
tvAlbumSubtitle?.text = albumItem.subtitle
tvAlbumSubtitle?.isVisible = !albumItem.subtitle.isNullOrEmpty()
tvAlbumIndex?.text = indexValue
if (isDark) {
tvAlbumTitle?.setTextColor(Color.WHITE)
tvAlbumSubtitle?.setTextColor(Color.WHITE)
} else {
tvAlbumTitle?.setTextColor(Color.BLACK)
tvAlbumSubtitle?.setTextColor(Color.BLACK)
}
ivAlbumMedia?.let { imageView ->
if (!albumItem.cover.isNullOrEmpty()) {
try {
Uri.parse(albumItem.cover)?.let { uri ->
Glide.with(imageView)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transform(
MultiTransformation(
CenterCrop(), RoundedCornersTransformation(
imageView.resources.getDimensionPixelSize(
R.dimen.dp_6
), 0
)
)
)
.into(imageView)
}
} catch (t: Throwable) {
t.printStackTrace()
imageView.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
imageView.setImageResource(R.drawable.bg_default_template_app_2)
}
}
}
fun setupMediaItem(mediaItem: MediaItem, isDark: Boolean, indexValue: String) {
tvAlbumTitle?.text = mediaItem.title
tvAlbumSubtitle?.text = mediaItem.subtitle
tvAlbumSubtitle?.isVisible = !mediaItem.subtitle.isNullOrEmpty()
tvAlbumIndex?.text = indexValue
if (isDark) {
tvAlbumTitle?.setTextColor(Color.WHITE)
tvAlbumSubtitle?.setTextColor(Color.WHITE)
} else {
tvAlbumTitle?.setTextColor(Color.BLACK)
tvAlbumSubtitle?.setTextColor(Color.BLACK)
}
ivAlbumMedia?.let { imageView ->
if (!mediaItem.cover.isNullOrEmpty()) {
try {
Uri.parse(mediaItem.cover)?.let { uri ->
Glide.with(imageView)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transform(
MultiTransformation(
CenterCrop(), RoundedCornersTransformation(
imageView.resources.getDimensionPixelSize(
R.dimen.dp_6
), 0
)
)
)
.into(imageView)
}
} catch (t: Throwable) {
t.printStackTrace()
imageView.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
imageView.setImageResource(R.drawable.bg_default_template_app_2)
}
}
}
}
private interface OnMoreClickListener {
fun onMoreClick(parent: ViewGroup, view: View, position: Int)
}
private interface OnSubItemClickListener {
fun onSubItemClick(parent: ViewGroup, view: View, position: Int, subPosition: Int)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.core.os.postDelayed
import androidx.core.view.GravityCompat
import androidx.core.view.isVisible
import androidx.core.view.postDelayed
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.AlarmApi
import com.iflytek.cyber.iot.show.core.model.*
import com.iflytek.cyber.iot.show.core.utils.DateUtils.Companion.dateToStr
import com.iflytek.cyber.iot.show.core.utils.DateUtils.Companion.getDateList
import com.iflytek.cyber.iot.show.core.utils.DateUtils.Companion.getHourList
import com.iflytek.cyber.iot.show.core.utils.DateUtils.Companion.getMinList
import com.iflytek.cyber.iot.show.core.utils.DateUtils.Companion.getMonthList
import com.iflytek.cyber.iot.show.core.utils.DateUtils.Companion.stringToDate
import com.iflytek.cyber.iot.show.core.widget.CircleCheckBox
import com.zyyoona7.wheel.WheelView
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
import kotlin.collections.ArrayList
class EditAlarmFragment : BaseFragment(), View.OnClickListener {
companion object {
private const val REQUEST_EDIT_CODE = 13023
fun instance(alert: Alert?): EditAlarmFragment {
return EditAlarmFragment().apply {
arguments = bundleOf(Pair("alert", alert))
}
}
}
private lateinit var drawer: DrawerLayout
private lateinit var noneWheel: WheelView<DateEntity>
private lateinit var dailyWheel: WheelView<String>
private lateinit var hourWheel: WheelView<String>
private lateinit var minuteWheel: WheelView<String>
private lateinit var tvRepeatType: TextView
private lateinit var tvAlarmDesc: TextView
private lateinit var tvRepeatSettings: TextView
private lateinit var tvTitle: TextView
private lateinit var customList: RecyclerView
private var customAdapter: CustomAdapter? = null
private lateinit var repeatList: RecyclerView
private var repeatTypeAdapter: RepeatTypeAdapter? = null
private var repeatTypeList = ArrayList<RepeatType>()
private var currentDesc: String? = null
private var dateList = ArrayList<DateEntity>()
private var alert: Alert? = null
private var year = 0
private var currentRepeatType: String? = null
private var handler = Handler(Looper.getMainLooper())
private var backCount = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return LayoutInflater.from(context).inflate(R.layout.fragment_edit_alarm, container, false)
}
@SuppressLint("ClickableViewAccessibility")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.iv_back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
view.findViewById<View>(R.id.done).setOnClickListener(this)
drawer = view.findViewById(R.id.drawer)
repeatList = view.findViewById(R.id.repeat_list)
customList = view.findViewById(R.id.custom_list)
noneWheel = view.findViewById(R.id.none_wheel)
dailyWheel = view.findViewById(R.id.daily_wheel)
hourWheel = view.findViewById(R.id.hour_wheel)
minuteWheel = view.findViewById(R.id.minute_wheel)
tvRepeatType = view.findViewById(R.id.tv_repeat_type)
tvAlarmDesc = view.findViewById(R.id.tv_alarm_desc)
tvRepeatSettings = view.findViewById(R.id.tv_repeat_settings)
tvTitle = view.findViewById(R.id.tv_title)
view.findViewById<View>(R.id.repeat_type).setOnClickListener(this)
view.findViewById<View>(R.id.alarm_desc_content).setOnClickListener(this)
alert = arguments?.getParcelable("alert")
setFragmentResult(0, bundleOf())
currentDesc = alert?.content
hourWheel.data = getHourList()
minuteWheel.data = getMinList()
if (alert == null) { //add new alarm
tvTitle.setText(R.string.add_new_alarm)
tvAlarmDesc.text = "无"
currentRepeatType = Alert.TYPE_NONE
tvRepeatType.text = RepeatType.getName(Alert.TYPE_NONE)
setDateWheel(Alert.TYPE_NONE)
} else { //edit current alarm
tvTitle.setText(R.string.edit_alarm)
currentRepeatType = alert?.repeatType
if (TextUtils.equals(alert?.repeatType, Alert.TYPE_WEEKLY)) {
tvRepeatType.text = alert?.description
} else {
tvRepeatType.text = RepeatType.getName(alert!!.repeatType)
}
if (alert?.content.isNullOrEmpty()) {
tvAlarmDesc.text = "无"
} else {
tvAlarmDesc.text = if (alert?.content?.length ?: 0 > 10) {
alert?.content?.substring(0, 10) + "···"
} else {
alert?.content
}
}
setDateWheel(alert!!.repeatType)
}
noneWheel.onWheelChangedListener = object : WheelView.OnWheelChangedListener {
override fun onWheelScroll(scrollOffsetY: Int) {
}
override fun onWheelSelected(position: Int) {
if (position == noneWheel.data.size - 1) {
year += 1
val calendar = Calendar.getInstance()
val start = "${calendar.get(Calendar.YEAR) + year}-01-01}"
val end = "${calendar.get(Calendar.YEAR) + year}-12-31"
val data = getDateList(start, end, Alert.TYPE_NONE)
dateList.addAll(data)
noneWheel.data = dateList
}
}
override fun onWheelScrollStateChanged(state: Int) {
}
override fun onWheelItemChanged(oldPosition: Int, newPosition: Int) {
}
}
drawer.addDrawerListener(object : DrawerLayout.DrawerListener {
override fun onDrawerStateChanged(newState: Int) {
}
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
}
override fun onDrawerClosed(drawerView: View) {
}
override fun onDrawerOpened(drawerView: View) {
autoCloseDrawer()
}
})
repeatList.setOnTouchListener { v, event ->
autoCloseDrawer()
false
}
customList.setOnTouchListener { v, event ->
autoCloseDrawer()
false
}
setupRepeatType()
setupWeeks()
}
private fun autoCloseDrawer() {
handler.removeCallbacksAndMessages(null)
handler.postDelayed(20000) {
drawer.closeDrawer(GravityCompat.END)
}
}
private fun findCurrentDateIndex(timestamp: Long): Int {
val calendar = Calendar.getInstance()
calendar.time = Date(timestamp * 1000)
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH) + 1
val day = calendar.get(Calendar.DAY_OF_MONTH)
val realMonth = String.format(Locale.getDefault(), "%02d", month)
val realDay = String.format(Locale.getDefault(), "%02d", day)
val newDate = stringToDate("yyyy-MM-dd", "$year-$realMonth-$realDay")
for (i in 0 until noneWheel.data.size) {
val entity = noneWheel.data[i]
if (entity.date.time == newDate.time) {
return i
}
}
return 0
}
private fun setDateWheel(repeatType: String) {
val calendar = Calendar.getInstance()
val times = alert?.time?.split(Regex(":"))
if (!times.isNullOrEmpty()) {
hourWheel.setSelectedItemPosition(times[0].toInt(), false)
minuteWheel.setSelectedItemPosition(times[1].toInt(), false)
} else {
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
hourWheel.setSelectedItemPosition(hour, false)
minuteWheel.setSelectedItemPosition(minute, false)
}
when (repeatType) {
Alert.TYPE_NONE -> {
dailyWheel.isVisible = false
noneWheel.isVisible = true
val start =
"${calendar.get(Calendar.YEAR)}-${calendar.get(Calendar.MONTH) + 1}-${calendar.get(
Calendar.DAY_OF_MONTH
)}"
val end = "${calendar.get(Calendar.YEAR)}-12-31"
val data = getDateList(start, end, Alert.TYPE_NONE)
noneWheel.data = data
if (alert != null && alert!!.timestamp > 0) {
val index = findCurrentDateIndex(alert!!.timestamp)
noneWheel.setSelectedItemPosition(index, false)
} else {
noneWheel.setSelectedItemPosition(0, false)
}
dateList.clear()
dateList.addAll(data)
}
Alert.TYPE_YEARLY -> {
dailyWheel.isVisible = false
noneWheel.isVisible = true
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH) + 1
val day = calendar.get(Calendar.DAY_OF_MONTH)
val data = getDateList("$year-01-01", "$year-12-31", Alert.TYPE_YEARLY)
noneWheel.data = data
if (alert?.repeatDate.isNullOrEmpty()) {
val realMonth = String.format(Locale.getDefault(), "%02d", month)
val realDay = String.format(Locale.getDefault(), "%02d", day)
val date = stringToDate("$year-$realMonth-$realDay")
val index = String.format("%tj", date).toInt() - 1
noneWheel.setSelectedItemPosition(index, false)
} else if (alert != null) {
val date = stringToDate("$year-${alert!!.repeatDate}")
val index = String.format("%tj", date).toInt() - 1
noneWheel.selectedItemPosition = index
}
}
Alert.TYPE_DAILY, Alert.TYPE_WORKDAY, Alert.TYPE_RESTDAY, Alert.TYPE_WEEKEND, Alert.TYPE_WEEKLY, Alert.TYPE_WEEKDAY -> {
dailyWheel.isVisible = false
noneWheel.isVisible = false
}
Alert.TYPE_MONTHLY -> {
val day = calendar.get(Calendar.DAY_OF_MONTH)
dailyWheel.isVisible = true
noneWheel.isVisible = false
dailyWheel.data = getMonthList()
val position = if (alert != null) {
alert!!.repeatDateNumber - 1
} else {
day - 1
}
dailyWheel.setSelectedItemPosition(position, false)
}
}
}
override fun onSupportVisible() {
super.onSupportVisible()
launcher?.setImmersiveFlags()
}
@SuppressLint("SetTextI18n")
override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle) {
if (requestCode == REQUEST_EDIT_CODE) {
val isEdited = data.getBoolean("isEdited")
if (isEdited) {
val desc = data.getString("desc")
if (desc?.length ?: 0 > 10) {
tvAlarmDesc.text = desc.substring(0, 10) + "···"
} else {
tvAlarmDesc.text = desc
}
alert?.content = desc
currentDesc = desc
}
}
}
private fun updateAlert() {
if (alert == null) {
return
}
val body = AlertBody()
body.id = alert!!.id
body.content = currentDesc
var hour = hourWheel.selectedItemData.substring(0, hourWheel.selectedItemData.length - 1)
var minute =
minuteWheel.selectedItemData.substring(0, minuteWheel.selectedItemData.length - 1)
if (hour.toInt() < 10) {
hour = "0$hour"
}
if (minute.toInt() < 10) {
minute = "$minute"
}
if (TextUtils.equals(currentRepeatType, Alert.TYPE_NONE)) {
body.alertType = "single"
val calendar = Calendar.getInstance()
calendar.time = noneWheel.selectedItemData.date
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH) + 1
val day = calendar.get(Calendar.DAY_OF_MONTH)
val date = stringToDate("yyyy-MM-dd HH:mm", "$year-$month-$day $hour:$minute")
body.timestamp = date.time / 1000
} else {
body.alertType = "repeat"
body.time = "$hour:$minute"
body.repeatType = currentRepeatType
if (TextUtils.equals(currentRepeatType, Alert.TYPE_WEEKLY)) {
body.repeatWeekdays = customAdapter?.selects?.toList()?.sorted()
}
if (TextUtils.equals(currentRepeatType, Alert.TYPE_MONTHLY)) {
body.repeatDateNumber =
dailyWheel.selectedItemData.substring(0, dailyWheel.selectedItemData.length - 1)
.toInt()
}
if (TextUtils.equals(currentRepeatType, Alert.TYPE_YEARLY)) {
body.repeatDate = dateToStr("MM-dd", noneWheel.selectedItemData.date)
}
}
getAlarmApi()?.updateAlert(alert!!.id, body)?.enqueue(object : Callback<Message> {
override fun onFailure(call: Call<Message>, t: Throwable) {
t.printStackTrace()
}
override fun onResponse(call: Call<Message>, response: Response<Message>) {
if (response.isSuccessful) {
Toast.makeText(tvAlarmDesc.context, "更新成功", Toast.LENGTH_SHORT).show()
setFragmentResult(0, bundleOf())
pop()
} else {
showError(response.errorBody()?.string())
}
}
})
}
private fun showError(errorStr: String?) {
try {
val error = Gson().fromJson(errorStr, Error::class.java)
Toast.makeText(tvAlarmDesc.context, error.message, Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun addNewAlarm() {
val body = AlertBody()
body.content = currentDesc
var hour = hourWheel.selectedItemData.substring(0, hourWheel.selectedItemData.length - 1)
var minute =
minuteWheel.selectedItemData.substring(0, minuteWheel.selectedItemData.length - 1)
if (hour.toInt() < 10) {
hour = "0$hour"
}
if (minute.toInt() < 10) {
minute = "$minute"
}
if (TextUtils.equals(currentRepeatType, Alert.TYPE_NONE)) {
body.alertType = "single"
val calendar = Calendar.getInstance()
calendar.time = noneWheel.selectedItemData.date
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH) + 1
val day = calendar.get(Calendar.DAY_OF_MONTH)
val date = stringToDate("yyyy-MM-dd HH:mm", "$year-$month-$day $hour:$minute")
body.timestamp = date.time / 1000
} else {
body.alertType = "repeat"
body.time = "$hour:$minute"
body.repeatType = currentRepeatType
if (TextUtils.equals(currentRepeatType, Alert.TYPE_WEEKLY)) {
body.repeatWeekdays = customAdapter?.selects?.toList()?.sorted()
}
if (TextUtils.equals(currentRepeatType, Alert.TYPE_MONTHLY)) {
body.repeatDateNumber =
dailyWheel.selectedItemData.substring(0, dailyWheel.selectedItemData.length - 1)
.toInt()
}
if (TextUtils.equals(currentRepeatType, Alert.TYPE_YEARLY)) {
body.repeatDate = dateToStr("MM-dd", noneWheel.selectedItemData.date)
}
}
getAlarmApi()?.addNewAlarm(body)?.enqueue(object : Callback<Message> {
override fun onFailure(call: Call<Message>, t: Throwable) {
t.printStackTrace()
}
override fun onResponse(call: Call<Message>, response: Response<Message>) {
if (response.isSuccessful) {
Toast.makeText(tvAlarmDesc.context, "添加成功", Toast.LENGTH_SHORT).show()
setFragmentResult(0, bundleOf())
pop()
} else {
showError(response.errorBody()?.string())
}
}
})
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.repeat_type -> {
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END)
} else {
tvRepeatSettings.text = "设置重复"
repeatList.isVisible = true
customList.isVisible = false
drawer.openDrawer(GravityCompat.END)
}
}
R.id.alarm_desc_content -> {
var desc = ""
/*if (alert?.content.isNullOrEmpty()) {
""
} else if (alert != null) {
alert.content
}*/
if (alert != null && alert!!.content != null) {
desc = alert!!.content!!
}
startForResult(
EditAlarmDescFragment.instance(desc),
REQUEST_EDIT_CODE
)
}
R.id.done -> {
drawer.postDelayed(300) {
if (alert != null) {
updateAlert()
} else { //add new alarm
addNewAlarm()
}
}
}
}
}
private fun setupRepeatType() {
val type1 = RepeatType(Alert.TYPE_NONE, "不重复")
repeatTypeList.add(type1)
val type2 = RepeatType(Alert.TYPE_DAILY, "每天")
repeatTypeList.add(type2)
val type3 = RepeatType(Alert.TYPE_MONTHLY, "每月")
repeatTypeList.add(type3)
val type4 = RepeatType(Alert.TYPE_YEARLY, "每年")
repeatTypeList.add(type4)
val type5 = RepeatType(Alert.TYPE_WORKDAY, "法定工作日")
repeatTypeList.add(type5)
val type6 = RepeatType(Alert.TYPE_RESTDAY, "法定节假日")
repeatTypeList.add(type6)
val type7 = RepeatType(Alert.TYPE_WEEKEND, "周末")
repeatTypeList.add(type7)
val type8 = RepeatType(Alert.TYPE_WEEKDAY, "周一至周五")
repeatTypeList.add(type8)
val type9 = RepeatType(Alert.TYPE_WEEKLY, "自定义")
repeatTypeList.add(type9)
repeatTypeAdapter = RepeatTypeAdapter(repeatTypeList) {
currentRepeatType = it.type
if (it.type == Alert.TYPE_WEEKLY) {
//custom
tvRepeatSettings.text = "自定义"
customAdapter?.setRepeatType()
noneWheel.isVisible = false
repeatList.isVisible = false
customList.isVisible = true
} else {
drawer.closeDrawer(GravityCompat.END)
tvRepeatType.text = RepeatType.getName(it.type)
setDateWheel(it.type)
}
}
repeatList.adapter = repeatTypeAdapter
}
private fun setupWeeks() {
val items = arrayListOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")
customAdapter = CustomAdapter(items)
if (alert != null && alert!!.repeatWeekdays != null) {
customAdapter?.selects?.clear()
customAdapter?.selects?.addAll(alert!!.repeatWeekdays!!.toList())
}
customList.adapter = customAdapter
}
inner class RepeatTypeAdapter(
private val repeatList: ArrayList<RepeatType>,
private val onItemClickListener: (RepeatType) -> Unit
) : RecyclerView.Adapter<RepeatTypeAdapter.RepeatTypeHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RepeatTypeHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_repeat_type, parent, false)
return RepeatTypeHolder(view)
}
override fun getItemCount(): Int {
return repeatList.size
}
override fun onBindViewHolder(holder: RepeatTypeHolder, position: Int) {
val repeatType = repeatList[position]
holder.type.text = repeatType.name
holder.itemView.setOnClickListener {
onItemClickListener.invoke(repeatType)
}
}
inner class RepeatTypeHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val type = itemView.findViewById<TextView>(R.id.type)
}
}
inner class CustomAdapter(private val items: ArrayList<String>) :
RecyclerView.Adapter<CustomAdapter.CustomHolder>() {
val selects = hashSetOf(1, 2, 3, 4, 5, 6, 7)
var customText: String = ""
private fun transferText(position: Int): String {
when (position) {
1 -> return "周一"
2 -> return "周二"
3 -> return "周三"
4 -> return "周四"
5 -> return "周五"
6 -> return "周六"
7 -> return "周日"
}
return ""
}
fun setRepeatType() {
customText = ""
selects.sorted().toList().forEach {
customText = customText + transferText(it) + ", "
}
if (customText.length > 1) {
tvRepeatType.text = customText.substring(0, customText.length - 1)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_custom_weekday, parent, false)
return CustomHolder(view)
}
override fun getItemCount(): Int {
return items.size
}
private fun onItemClick(holder: CustomHolder, position: Int) {
if (holder.checkbox.isChecked) {
holder.checkbox.isChecked = false
selects.remove(position + 1)
} else {
holder.checkbox.isChecked = true
selects.add(position + 1)
}
setRepeatType()
}
override fun onBindViewHolder(holder: CustomHolder, position: Int) {
holder.tvWeek.text = items[position]
holder.checkbox.isChecked = selects.contains(position + 1)
holder.itemView.setOnClickListener {
onItemClick(holder, position)
}
holder.checkbox.setOnClickListener {
onItemClick(holder, position)
}
}
inner class CustomHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvWeek = itemView.findViewById<TextView>(R.id.tv_week)
val checkbox = itemView.findViewById<CircleCheckBox>(R.id.check_box)
}
}
private fun getAlarmApi(): AlarmApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(AlarmApi::class.java)
} else {
null
}
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.utils
import android.content.Context
import android.net.ConnectivityManager
import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.Request
object ConnectivityUtils {
private const val IVS_PING_URL = "https://ivs.iflyos.cn/ping"
private const val MIUI_PING_URL = "https://connect.rom.miui.com/generate_204"
private val client = OkHttpClient.Builder()
.build()
/**
* 检查网络是否可用
*/
fun isNetworkAvailable(context: Context?): Boolean {
context ?: return false
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
val networkInfo = manager?.activeNetworkInfo
return networkInfo?.isConnected == true
}
/**
* 检查 iFLYOS 是否可用
*/
fun checkIvsAvailable(
onSuccess: () -> Unit,
onFailed: ((throwable: Throwable?, responseCode: Int) -> Unit)? = null
) {
Thread(Runnable {
var code = -1
try {
val request = Request.Builder()
.url(IVS_PING_URL)
.get()
.build()
val response = client.newCall(request).execute()
code = response.code()
} catch (e: Exception) {
onFailed?.invoke(e, code)
return@Runnable
}
if (code in 200 until 300) {
// available
onSuccess.invoke()
} else {
onFailed?.invoke(IllegalStateException("Response not succeed"), code)
}
}).start()
}
/**
* 检查网络是否可用
*/
fun checkNetworkAvailable(
onSuccess: () -> Unit,
onFailed: ((throwable: Throwable?, responseCode: Int) -> Unit)? = null
) {
Thread(Runnable {
var code = -1
try {
val request = Request.Builder()
.url(MIUI_PING_URL)
.get()
.build()
val response = client.newCall(request).execute()
code = response.code()
} catch (e: Exception) {
onFailed?.invoke(e, code)
return@Runnable
}
if (code in 200 until 300) {
// available
onSuccess.invoke()
} else {
onFailed?.invoke(IllegalStateException("Response not succeed"), code)
}
}).start()
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CenterInside
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.GroupItem
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
import com.iflytek.cyber.iot.show.core.widget.RatioImageView
class AlbumAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
const val TYPE_SQUARE = 0
const val TYPE_RECTANGLE = 1
}
private var groupList: List<GroupItem>? = null
var itemViewType = TYPE_SQUARE
internal var onGroupItemClickListener: OnGroupItemClickListener? = null
fun setGroupList(groupList: List<GroupItem>?) {
this.groupList = groupList
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (itemViewType == TYPE_SQUARE) {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.item_album, parent, false)
AlbumHolder(view)
} else {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_album_video, parent, false)
AlbumVideoHolder(view)
}
}
override fun getItemCount(): Int {
return if (groupList != null) {
groupList!!.size
} else {
0
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is AlbumHolder) {
val context = holder.itemView.context
val groupItem = groupList!![position]
val resource = holder.itemView.resources
val transformer = MultiTransformation(
CenterCrop(),
RoundedCornersTransformation(
resource.getDimensionPixelSize(R.dimen.dp_6), 0
)
)
Glide.with(context)
.load(groupItem.image)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.placeholder(R.drawable.placeholder_music_album)
.transform(transformer)
.into(holder.ivAlbum)
holder.albumTitle.text = groupItem.name
holder.albumContent.setOnClickListener {
onGroupItemClickListener?.onGroupItemClick(it, groupItem)
}
} else if (holder is AlbumVideoHolder) {
val context = holder.itemView.context
val groupItem = groupList!![position]
val resource = holder.itemView.resources
val transformer = MultiTransformation(
CenterCrop(),
RoundedCornersTransformation(
resource.getDimensionPixelSize(R.dimen.dp_6), 0
)
)
holder.ivAlbum.setOriginalSize(1000, 574)
holder.albumContent.setOriginalSize(1000, 574)
Glide.with(context)
.load(groupItem.image)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.placeholder(R.drawable.placeholder_music_album)
.transform(transformer)
.into(holder.ivAlbum)
holder.albumTitle.text = groupItem.name
holder.albumContent.setOnClickListener {
onGroupItemClickListener?.onGroupItemClick(it, groupItem)
}
}
}
class AlbumHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val ivAlbum = itemView.findViewById<ImageView>(R.id.iv_album)
val albumTitle = itemView.findViewById<TextView>(R.id.album_title)
val albumContent = itemView.findViewById<FrameLayout>(R.id.album_content)
}
class AlbumVideoHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val ivAlbum = itemView.findViewById<RatioImageView>(R.id.iv_album)
val albumTitle = itemView.findViewById<TextView>(R.id.album_title)
val albumContent = itemView.findViewById<RatioImageView>(R.id.album_content)
}
interface OnGroupItemClickListener {
fun onGroupItemClick(itemView: View, groupItem: GroupItem)
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.impl.prompt
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.util.SparseArray
import android.util.SparseIntArray
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.ExoPlayerFactory
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.audio.AudioAttributes
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DataSpec
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter
import com.google.android.exoplayer2.upstream.RawResourceDataSource
import com.iflytek.cyber.evs.sdk.focus.AudioFocusChannel
import com.iflytek.cyber.evs.sdk.focus.AudioFocusManager
import com.iflytek.cyber.evs.sdk.focus.FocusStatus
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.impl.audioplayer.MediaSourceFactory
import com.iflytek.cyber.iot.show.core.impl.speaker.EvsSpeaker
import com.iflytek.cyber.iot.show.core.utils.ToneManager
import java.lang.Math.random
import java.lang.ref.SoftReference
import kotlin.math.roundToInt
/**
* 用于播放各种情景下的提示文案
*/
object PromptManager {
const val NETWORK_LOST = 7
const val VOLUME = 23
const val WAKE_1 = 24
const val WAKE_2 = 25
const val WAKE_3 = 26
const val WAKE_4 = 27
const val WAKE_5 = 28
const val WAKE_6 = 29
const val WAKE_7 = 30
const val WAKE_8 = 31
const val WAKE_9 = 32
const val POWER_ON = 33
const val TOKEN_EXPIRED = 34
const val NETWORK_WAIT_RETRY = 35
const val CONNECTING_PLEASE_WAIT = 37
const val EVALUATION_WARN = 38
private const val TAG = "PromptManager"
private val mUriMap = SparseArray<Uri>()
private val mSoundIdMap = SparseIntArray()
private var mPlayer: SimpleExoPlayer? = null
private var contextRef: SoftReference<Context>? = null
private var currentSound = -1
private var mMediaSourceFactory: MediaSourceFactory? = null
private val withoutFocusArray = arrayOf(
VOLUME, WAKE_1, WAKE_2, WAKE_3,
WAKE_4, WAKE_5, WAKE_6, WAKE_7, WAKE_8, WAKE_9, POWER_ON
)
val promptAudioChannel = object : AudioFocusChannel() {
override fun onFocusChanged(focusStatus: FocusStatus) {
if (focusStatus != FocusStatus.Foreground) {
if (!isTone(currentSound))
stop()
}
}
override fun getChannelName(): String {
return AudioFocusManager.CHANNEL_OUTPUT
}
override fun getType(): String {
return "TTS"
}
}
private val onVolumeChangeListener = object : EvsSpeaker.OnVolumeChangedListener {
override fun onVolumeChanged(volume: Int, fromRemote: Boolean) {
mPlayer?.volume = volume / 100f
}
}
init {
mSoundIdMap.put(VOLUME, R.raw.tone_volume)
mSoundIdMap.put(WAKE_1, R.raw.tone_wake_1)
mSoundIdMap.put(WAKE_2, R.raw.tone_wake_2)
mSoundIdMap.put(WAKE_3, R.raw.tone_wake_3)
mSoundIdMap.put(WAKE_4, R.raw.tone_wake_4)
mSoundIdMap.put(WAKE_5, R.raw.tone_wake_5)
mSoundIdMap.put(WAKE_6, R.raw.tone_wake_6)
mSoundIdMap.put(WAKE_7, R.raw.tone_wake_7)
mSoundIdMap.put(WAKE_8, R.raw.tone_wake_8)
mSoundIdMap.put(WAKE_9, R.raw.tone_wake_9)
mSoundIdMap.put(POWER_ON, R.raw.tone_power_on)
mSoundIdMap.put(TOKEN_EXPIRED, R.raw.tts_token_expired)
mSoundIdMap.put(NETWORK_LOST, R.raw.tts_network_lost)
mSoundIdMap.put(NETWORK_WAIT_RETRY, R.raw.tts_network_wait_retry)
mSoundIdMap.put(CONNECTING_PLEASE_WAIT, R.raw.tts_connecting_please_wait)
mSoundIdMap.put(EVALUATION_WARN, R.raw.evaluation_warn)
}
fun init(context: Context) {
val bandwidthMeter = DefaultBandwidthMeter.Builder(context).build()
val selectionFactory = AdaptiveTrackSelection.Factory(bandwidthMeter)
val trackSelector = DefaultTrackSelector(selectionFactory)
mMediaSourceFactory = MediaSourceFactory(context)
mPlayer = ExoPlayerFactory.newSimpleInstance(context, trackSelector)
mPlayer?.audioAttributes = AudioAttributes.Builder()
.setContentType(C.CONTENT_TYPE_SONIFICATION)
.setUsage(C.USAGE_ASSISTANCE_SONIFICATION)
.build()
mPlayer?.addListener(object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
if (playbackState == Player.STATE_ENDED || !playWhenReady) {
if (currentSound !in withoutFocusArray) {
promptAudioChannel.requestAbandon()
}
currentSound = -1
onEnd?.invoke()
}
}
})
contextRef = SoftReference(context)
EvsSpeaker.get(context).let { evsSpeaker ->
evsSpeaker.addOnVolumeChangedListener(onVolumeChangeListener)
mPlayer?.volume = evsSpeaker.getCurrentVolume() / 100f
}
}
fun setupAudioFocusManager(manager: AudioFocusManager) {
promptAudioChannel.setupManager(manager)
}
private var onEnd: (() -> Unit)? = null
fun play(id: Int, onEnd: (() -> Unit)? = null) {
//this.onEnd?.invoke()
this.onEnd = onEnd
play(id)
}
fun playUrl(url: String) {
mPlayer?.let { player ->
Handler(player.applicationLooper).post {
player.stop()
val uri = Uri.parse(url)
val mediaSource = mMediaSourceFactory?.createHttpMediaSource(uri)
player.prepare(mediaSource, true, false)
player.playWhenReady = true
promptAudioChannel.requestActive()
}
}
}
private fun play(id: Int) {
mPlayer?.let { player ->
Handler(player.applicationLooper).post {
player.stop()
mSoundIdMap[id].let {
val rawResourceDataSource = RawResourceDataSource(contextRef?.get())
val factory = DataSource.Factory { rawResourceDataSource }
var uri = mUriMap[it]
if (uri == null) {
val dataSpec = DataSpec(RawResourceDataSource.buildRawResourceUri(it))
rawResourceDataSource.open(dataSpec)
rawResourceDataSource.uri?.let { newUri ->
mUriMap.put(id, newUri)
uri = newUri
}
}
val mediaSource = ExtractorMediaSource.Factory(factory)
.createMediaSource(uri)
player.prepare(mediaSource)
player.playWhenReady = true
currentSound = id
if (id !in withoutFocusArray) {
promptAudioChannel.requestActive()
}
}
}
}
}
private fun isTone(soundId: Int): Boolean {
return arrayOf(
WAKE_1, WAKE_2, WAKE_3,
WAKE_4, WAKE_5, WAKE_6,
WAKE_7, WAKE_8, WAKE_9,
VOLUME
).contains(soundId)
}
fun playWakeSound(onEnd: (() -> Unit)? = null) {
// full
// val array = arrayOf(
// WAKE_1, WAKE_2, WAKE_3,
// WAKE_4, WAKE_5, WAKE_6,
// WAKE_7, WAKE_8, WAKE_9
// )
// simple
val array = arrayOf(WAKE_1, WAKE_2)
play(array[(random() * (array.size - 1)).roundToInt()], onEnd)
// val context = contextRef?.get() ?: return
// ToneManager[context].play(ToneManager.TONE_WAKE, 0.3f)
}
fun isPlaying(): Boolean {
val playWhenReady = mPlayer?.playWhenReady == true
val playbackState = mPlayer?.playbackState
return playWhenReady && (playbackState == Player.STATE_BUFFERING ||
playbackState == Player.STATE_READY)
}
fun setVolume(volume: Byte) {
mPlayer?.let { player ->
Handler(player.applicationLooper).post {
mPlayer?.volume = 1f * volume / 100
}
}
}
fun destroy() {
mPlayer?.release()
EvsSpeaker.get(contextRef?.get()).addOnVolumeChangedListener(onVolumeChangeListener)
currentSound = -1
}
fun stop() {
mPlayer?.let { player ->
Handler(player.applicationLooper).post {
mPlayer?.playWhenReady = false
}
}
if (!isTone(currentSound))
promptAudioChannel.requestAbandon()
currentSound = -1
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.bumptech.glide.request.transition.Transition
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.TemplateAppMediaAdapter
import com.iflytek.cyber.iot.show.core.api.AppApi
import com.iflytek.cyber.iot.show.core.impl.prompt.PromptManager
import com.iflytek.cyber.iot.show.core.model.AppShowResult
import com.iflytek.cyber.iot.show.core.model.MediaItem
import com.iflytek.cyber.iot.show.core.model.TemplateApp
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.widget.StyledProgressDialog
import com.kk.taurus.playerbase.utils.NetworkUtils
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
class TemplateAppMediaListFragment : BaseFragment() {
companion object {
private const val LIMIT = 20
fun newInstance(
templateApp: TemplateApp?,
category: String?,
album: String?
): TemplateAppMediaListFragment {
val fragment = TemplateAppMediaListFragment()
fragment.templateApp = templateApp
fragment.category = category
fragment.album = album
return fragment
}
}
private var templateApp: TemplateApp? = null
private var category: String? = null
private var album: String? = null
private var page = 1
private var clickCount = 0
private var ivBack: ImageView? = null
private var ivIcon: ImageView? = null
private var ivBackground: ImageView? = null
private var recyclerView: RecyclerView? = null
private var tvTitle: TextView? = null
private var loading: LottieAnimationView? = null
private var loadingBottom: LottieAnimationView? = null
private var tvError: TextView? = null
private var tvRetry: TextView? = null
private var errorRetry: View? = null
private var errorContainer: View? = null
private val mediaAdapter = TemplateAppMediaAdapter()
private var progressDialog: StyledProgressDialog? = null
private var isLoading = false
private var isLoadComplete = false
private val onScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (isLoadComplete || isLoading) return
(recyclerView.layoutManager as? LinearLayoutManager)?.let {
if (it.findLastCompletelyVisibleItemPosition() == it.findLastVisibleItemPosition() &&
recyclerView.adapter?.itemCount == it.findLastVisibleItemPosition() + 1
) {
page++
getMediaList()
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.fragment_template_app_media_list_fragment,
container,
false
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back)?.setOnClickListener {
pop()
}
ivBack = view.findViewById(R.id.iv_back)
ivIcon = view.findViewById(R.id.iv_icon)
ivBackground = view.findViewById(R.id.background)
recyclerView = view.findViewById(R.id.recycler_view)
loading = view.findViewById(R.id.loading)
loadingBottom = view.findViewById(R.id.loading_bottom)
tvTitle = view.findViewById(R.id.title)
tvRetry = view.findViewById(R.id.tv_retry)
tvError = view.findViewById(R.id.tv_error)
errorContainer = view.findViewById(R.id.error_container)
errorRetry = view.findViewById(R.id.error_retry)
errorRetry?.setOnClickListener {
if (!isLoading) {
page = 1
getMediaList()
}
}
tvTitle?.text = album
recyclerView?.adapter = mediaAdapter
recyclerView?.addOnScrollListener(onScrollListener)
mediaAdapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: ViewGroup, itemView: View, position: Int) {
mediaAdapter.getMediaItem(position)?.let { mediaItem ->
if (isAdded && context != null && !NetworkUtils.isNetConnected(context)) {
clickCount = 0
PromptManager.play(PromptManager.NETWORK_LOST)
return
}
postPlay(mediaItem)
}
}
}
applyTheme(templateApp?.isDark != false)
loadBackground()
loadAppIcon()
getMediaList()
}
private fun applyTheme(isDark: Boolean) {
ivBack?.imageTintList = ColorStateList.valueOf(if (isDark) Color.WHITE else Color.BLACK)
mediaAdapter.isDark = isDark
if (mediaAdapter.itemCount != 0) {
mediaAdapter.notifyDataSetChanged()
}
tvTitle?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
tvError?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
tvRetry?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
errorRetry?.setBackgroundResource(
if (isDark) R.drawable.bg_round_border_white_36dp
else R.drawable.bg_round_border_black_36dp
)
}
override fun onSupportInvisible() {
super.onSupportInvisible()
clickCount = 0
}
override fun onDestroy() {
super.onDestroy()
recyclerView?.removeOnScrollListener(onScrollListener)
}
private fun loadBackground() {
val templateApp = templateApp ?: return
ivBackground?.let { imageView ->
val url = templateApp.img
if (url.isNullOrEmpty())
return
try {
Uri.parse(url)?.let { uri ->
Glide.with(imageView)
.load(uri)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
private fun loadAppIcon() {
val templateApp = templateApp ?: return
if (!templateApp.icon.isNullOrEmpty()) {
try {
Uri.parse(templateApp.icon)?.let { uri ->
ivIcon?.let { imageView ->
Glide.with(imageView)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
} ?: run {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} catch (t: Throwable) {
t.printStackTrace()
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
}
private fun showError(message: String?, showRetry: Boolean = true) {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = false
errorContainer?.isVisible = true
errorRetry?.isVisible = showRetry
tvError?.text = message
}
private fun hideError() {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = true
errorContainer?.isVisible = false
}
private fun showLoading() {
if (isRemoving || isDetached)
return
context ?: return
if (page == 1) {
loading?.isVisible = true
loading?.repeatCount = LottieDrawable.INFINITE
loading?.repeatMode = LottieDrawable.RESTART
loading?.playAnimation()
} else {
loadingBottom?.isVisible = true
loadingBottom?.repeatCount = LottieDrawable.INFINITE
loadingBottom?.repeatMode = LottieDrawable.RESTART
loadingBottom?.playAnimation()
}
}
private fun hideLoading() {
if (isRemoving || isDetached)
return
context ?: return
if (loading?.isVisible == true) {
loading?.pauseAnimation()
loading?.isVisible = false
}
if (loadingBottom?.isVisible == true) {
loadingBottom?.pauseAnimation()
loadingBottom?.isVisible = false
}
}
private fun showProgress(title: String, message: String? = null) {
if (isRemoving || isDetached)
return
context ?: return
progressDialog = StyledProgressDialog.Builder()
.setTitle(title)
.setMessage(message)
.show(fragmentManager)
}
private fun dismissProgress() {
if (isRemoving || isDetached)
return
context ?: return
progressDialog?.let {
it.dismiss()
progressDialog = null
}
}
private fun getMediaList() {
val templateApp = templateApp ?: return
val source = templateApp.source ?: return
val category = category
val business = templateApp.business ?: return
val album = album ?: return
isLoading = true
showLoading()
hideError()
val json = JSONObject()
json.put("source", source)
category?.let {
json.put("category", category)
}
json.put("business", business)
json.put("album", album)
json.put("page", page)
json.put("limit", LIMIT)
val requestBody = RequestBody.create(
MediaType.parse("application/json"),
json.toString()
)
getAppApi()?.getAlbumShow(requestBody)?.enqueue(object : Callback<AppShowResult> {
override fun onFailure(call: Call<AppShowResult>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
isLoading = false
hideLoading()
if (t is UnknownHostException) {
showError("Ooooops,请检查网络后重试")
} else {
showError("请求出错,请稍后重试")
}
}
override fun onResponse(call: Call<AppShowResult>, response: Response<AppShowResult>) {
if (isRemoving || isDetached)
return
context ?: return
isLoading = false
if (response.isSuccessful) {
val body = response.body()
val mediaList = mutableListOf<MediaItem>()
var firstCover: String? = null
for (index in 0 until (body?.result?.size ?: 0)) {
body?.result?.get(index)?.let { mediaItem ->
if (firstCover.isNullOrEmpty()) {
firstCover = mediaItem.cover
}
mediaList.add(mediaItem)
}
}
if (mediaList.size < LIMIT) {
isLoadComplete = true
}
if (page == 1) {
when {
mediaList.isEmpty() -> {
hideLoading()
showError("Ooooops,找不到结果", false)
}
firstCover.isNullOrEmpty() -> {
mediaAdapter.setMediaList(mediaList)
mediaAdapter.notifyDataSetChanged()
hideLoading()
}
else -> Glide.with(this@TemplateAppMediaListFragment)
.asBitmap()
.load(firstCover)
.into(object : CustomTarget<Bitmap>() {
override fun onLoadFailed(errorDrawable: Drawable?) {
super.onLoadFailed(errorDrawable)
loading?.pauseAnimation()
loading?.isVisible = false
}
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?
) {
val ratio =
1f * resource.width / resource.height
mediaAdapter.ratio = ratio
recyclerView?.let { recyclerView ->
recyclerView.post {
when {
ratio <= 1f -> {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 5
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
5
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
ratio > 1f -> {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 3
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
3
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingBottom
)
}
}
hideLoading()
mediaAdapter.setMediaList(mediaList)
mediaAdapter.notifyDataSetChanged()
}
}
}
override fun onLoadCleared(placeholder: Drawable?) {
}
})
}
} else {
hideLoading()
mediaAdapter.appendMediaList(mediaList)
mediaAdapter.notifyDataSetChanged()
}
} else {
hideLoading()
showError("请求出错,请稍后再试")
}
}
})
}
private fun postPlay(mediaItem: MediaItem) {
val audioId = mediaItem.id ?: return
val sourceType = mediaItem.source ?: templateApp?.source ?: return
val business = templateApp?.business ?: return
//showProgress(getString(R.string.loading), getString(R.string.please_wait))
loading?.isVisible = true
loading?.repeatCount = LottieDrawable.INFINITE
loading?.repeatMode = LottieDrawable.RESTART
loading?.playAnimation()
val json = com.alibaba.fastjson.JSONObject()
json["audio_id"] = audioId
json["source_type"] = sourceType
json["business"] = business
val requestBody = RequestBody.create(
MediaType.parse("application/json"),
json.toString()
)
getAppApi()?.postPlayMedia(requestBody)?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
//dismissProgress()
loading?.isVisible = false
loading?.pauseAnimation()
Toast.makeText(context, "请求出错", Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (isRemoving || isDetached)
return
context ?: return
//dismissProgress()
loading?.isVisible = false
loading?.pauseAnimation()
if (response.isSuccessful) {
Toast.makeText(context, "开始播放", Toast.LENGTH_SHORT).show()
} else {
response.errorBody()?.let { errorBody ->
val errorString = errorBody.string()
val errorJson = JSONObject(errorString)
if (errorJson.has("message")) {
Toast.makeText(
context,
errorJson.optString("message"),
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(context, "播放失败", Toast.LENGTH_SHORT).show()
}
errorBody.close()
} ?: run {
Toast.makeText(context, "播放失败", Toast.LENGTH_SHORT).show()
}
}
}
})
}
private fun getAppApi(): AppApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(AppApi::class.java)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.net.wifi.ScanResult
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.WifiUtils
class WifiInfoFragment(private val scanResult: ScanResult? = null) : BaseFragment() {
private var backCount = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_wifi_info, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val tvSsid: TextView = view.findViewById(R.id.ssid)
val tvIp: TextView = view.findViewById(R.id.ip_address)
val tvMac: TextView = view.findViewById(R.id.wifi_mac)
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
view.findViewById<View>(R.id.forget).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
WifiUtils.forget(it.context, scanResult?.SSID)
pop()
}
tvSsid.text = scanResult?.SSID
if (scanResult?.SSID == WifiUtils.getConnectedSsid(context)) {
tvIp.text = WifiUtils.getIPAddress(view.context)
tvMac.text = WifiUtils.getMacAddress(view.context)
view.findViewById<View>(R.id.ip_container).visibility = View.VISIBLE
view.findViewById<View>(R.id.mac_container).visibility = View.VISIBLE
} else {
view.findViewById<View>(R.id.ip_container).visibility = View.GONE
view.findViewById<View>(R.id.mac_container).visibility = View.GONE
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.impl.template
import com.iflytek.cyber.evs.sdk.agent.Template
class EvsTemplate private constructor() : Template() {
companion object {
private var instance: EvsTemplate? = null
fun get(): EvsTemplate {
instance?.let {
return it
} ?: run {
val template = EvsTemplate()
instance = template
return template
}
}
}
var renderCallback: RenderCallback? = null
var isPlayerInfoFocused = false
var isOtherTemplateFocused = false
var templateType: String? = null
private val isTemplateFocused: Boolean
get() = isPlayerInfoFocused || isOtherTemplateFocused
override fun isFocused(): Boolean {
return isTemplateFocused
}
override fun getFocusTemplateType(): String? {
return if (isPlayerInfoFocused && !isOtherTemplateFocused) TYPE_PLAYER_INFO else templateType
}
override fun isSupportedCustomTemplate(): Boolean {
return true
}
override fun exitStaticTemplate(type: String?) {
super.exitStaticTemplate(type)
renderCallback?.exitStaticTemplate(type)
}
override fun exitPlayerInfo() {
super.exitPlayerInfo()
renderCallback?.exitPlayerInfo()
}
override fun exitCustomTemplate() {
super.exitCustomTemplate()
renderCallback?.exitCustomTemplate()
}
override fun renderStaticTemplate(payload: String) {
super.renderStaticTemplate(payload)
renderCallback?.renderTemplate(payload)
}
override fun renderCustomTemplate(type: String, templateId: String, showingDuration: String?, htmlSourceCode: String) {
super.renderCustomTemplate(type, templateId, showingDuration, htmlSourceCode)
renderCallback?.renderCustomTemplate(type, templateId, showingDuration, htmlSourceCode)
}
override fun notifyPlayerInfoUpdated(resourceId: String, payload: String) {
super.notifyPlayerInfoUpdated(resourceId, payload)
renderCallback?.notifyPlayerInfoUpdated(resourceId, payload)
}
override fun renderPlayerInfo(payload: String) {
super.renderPlayerInfo(payload)
renderCallback?.renderPlayerInfo(payload)
}
override fun renderVideoPlayerInfo(payload: String) {
super.renderVideoPlayerInfo(payload)
renderCallback?.renderVideoPlayerInfo(payload)
}
override fun isTemplatePermanent(): Boolean {
return true
}
interface RenderCallback {
fun renderTemplate(payload: String)
fun notifyPlayerInfoUpdated(resourceId: String, payload: String)
fun renderPlayerInfo(payload: String)
fun exitStaticTemplate(type: String?)
fun exitPlayerInfo()
fun exitCustomTemplate()
fun renderVideoPlayerInfo(payload: String)
fun renderCustomTemplate(type: String, templateId: String, showingDuration: String?, htmlSourceCode: String)
}
abstract class SimpleRenderCallback : RenderCallback {
override fun renderPlayerInfo(payload: String) {
}
override fun notifyPlayerInfoUpdated(resourceId: String, payload: String) {
}
override fun renderTemplate(payload: String) {
}
override fun exitCustomTemplate() {
}
override fun exitPlayerInfo() {
}
override fun exitStaticTemplate(type: String?) {
}
override fun renderVideoPlayerInfo(payload: String) {
}
override fun renderCustomTemplate(
type: String,
templateId: String,
showingDuration: String?,
htmlSourceCode: String
) {
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.core.app.ActivityCompat
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.WriterException
import com.google.zxing.qrcode.QRCodeWriter
import com.iflytek.cyber.iot.show.core.R
import java.util.*
class StyledQRCodeDialog : DialogFragment() {
private var buttonPair: Pair<String, View.OnClickListener?>? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
return inflater.inflate(R.layout.layout_styled_qrcode_dialog, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val title = arguments?.getString("text")
val message = arguments?.getString("message")
val code = arguments?.getString("code")
view.findViewById<ImageView>(R.id.qrcode)?.let { imageView ->
code?.let {
imageView.post {
Thread {
val bitmap = createQRBitmap(code, imageView.width, imageView.height)
imageView.post {
imageView.setImageBitmap(bitmap)
view.findViewById<View>(R.id.progress_bar)?.isVisible = false
}
}.start()
}
}
}
view.findViewById<TextView>(R.id.dialog_title)?.let { tvTitle ->
tvTitle.text = title
tvTitle.isVisible = !title.isNullOrEmpty()
}
view.findViewById<TextView>(R.id.dialog_message)?.let { tvMessage ->
tvMessage.text = message
tvMessage.isVisible = !message.isNullOrEmpty()
}
buttonPair?.let {
view.findViewById<TextView>(R.id.dialog_button)?.let { button ->
button.isVisible = true
button.text = it.first
button.setOnClickListener { view ->
it.second?.onClick(view)
dismiss()
}
}
} ?: run {
view.findViewById<View>(R.id.dialog_button)?.isVisible = false
}
}
private fun createQRBitmap(content: String, width: Int, height: Int): Bitmap? {
val context = context ?: return null
try {
val colorBlack = ActivityCompat.getColor(context, android.R.color.black)
val coloWhite = ActivityCompat.getColor(context, android.R.color.transparent)
// 设置二维码相关配置,生成BitMatrix(位矩阵)对象
val hints = Hashtable<EncodeHintType, String>()
hints[EncodeHintType.CHARACTER_SET] = "UTF-8" // 字符转码格式设置
hints[EncodeHintType.ERROR_CORRECTION] = "H" // 容错级别设置
hints[EncodeHintType.MARGIN] = "2" // 空白边距设置
val bitMatrix =
QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints)
// 创建像素数组,并根据BitMatrix(位矩阵)对象为数组元素赋颜色值
val pixels = IntArray(width * height)
for (y in 0 until height) {
for (x in 0 until width) {
if (bitMatrix.get(x, y)) {
pixels[y * width + x] = colorBlack // 黑色色块像素设置
} else {
pixels[y * width + x] = coloWhite // 白色色块像素设置
}
}
}
// 创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,之后返回Bitmap对象
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
return bitmap
} catch (e: WriterException) {
e.printStackTrace()
}
return null
}
override fun onStart() {
super.onStart()
dialog?.let { dialog ->
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.window?.setLayout(
resources.getDimensionPixelSize(R.dimen.dp_260),
WindowManager.LayoutParams.WRAP_CONTENT
)
}
}
class Builder {
private var code: String? = null
private var title: String? = null
private var message: String? = null
private var buttonPair: Pair<String, View.OnClickListener?>? = null
fun setTitle(title: String?): Builder {
this.title = title
return this
}
fun setMessage(message: String?): Builder {
this.message = message
return this
}
fun setCode(code: String?): Builder {
this.code = code
return this
}
fun setButton(text: String, onClickListener: View.OnClickListener?): Builder {
buttonPair = Pair(text, onClickListener)
return this
}
fun build(): StyledQRCodeDialog {
val dialog = StyledQRCodeDialog()
val arguments = Bundle()
arguments.putString("text", title)
arguments.putString("message", message)
arguments.putString("code", code)
dialog.arguments = arguments
dialog.buttonPair = buttonPair
return dialog
}
fun show(fragmentManager: FragmentManager?): StyledQRCodeDialog {
build().apply {
fragmentManager?.let {
show(it, "QRCode")
}
return this
}
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.Manifest
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.net.*
import android.net.wifi.ScanResult
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.os.*
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.PermissionChecker
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.iflytek.cyber.evs.sdk.auth.AuthDelegate
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.SelfBroadcastReceiver
import com.iflytek.cyber.iot.show.core.utils.ConfigUtils
import com.iflytek.cyber.iot.show.core.utils.WifiUtils
import com.iflytek.cyber.iot.show.core.widget.DividerItemDecoration
import com.iflytek.cyber.iot.show.core.widget.StyledSwitch
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.Comparator
class WifiSettingsFragment : BaseFragment(), PageScrollable {
private val scanReceiver = ScanReceiver()
private val uiHandler = Handler(Looper.getMainLooper())
private var wm: WifiManager? = null
private var scans: List<ScanResult>? = null
private val configs = HashMap<String, WifiConfiguration>()
private var connected: String? = null
private var isAvailable = true
private var recyclerView: RecyclerView? = null
private var adapter: WifiAdapter? = null
private var wifiSwitch: StyledSwitch? = null
private var ivRefresh: ImageView? = null
private var nextStep: TextView? = null
private var loadingView: LottieAnimationView? = null
private var refreshContainer: View? = null
private var wifiWakeLock: PowerManager.WakeLock? = null
private var warningAlert: AlertDialog? = null
private var progressDialog: ProgressDialog? = null
private var isScanning = false
private var fromSetup = false
private var backCount = 0
private var wakeLock: PowerManager.WakeLock? = null
@Suppress("DEPRECATION")
private val connectionReceiver = object : SelfBroadcastReceiver(
ConnectivityManager.CONNECTIVITY_ACTION
) {
override fun onReceiveAction(action: String, intent: Intent) {
when (action) {
ConnectivityManager.CONNECTIVITY_ACTION -> {
val network = intent.getParcelableExtra<NetworkInfo>(
ConnectivityManager.EXTRA_NETWORK_INFO
)
val detailed = network.detailedState
if (detailed == NetworkInfo.DetailedState.CONNECTED) {
WifiUtils.getConnectedSsid(context)?.let { ssid ->
if (ssid.isNotEmpty()) {
connected = ssid
} else {
connected = null
}
} ?: run {
connected = null
}
} else {
connected = null
}
adapter?.notifyDataSetChanged()
}
}
}
}
private var networkCallback: Any? = null // 不声明 NetworkCallback 的类,否则 L 以下会找不到类
companion object {
private const val TAG = "WifiSettingsFragment"
private const val REQUEST_LOCATION_CODE = 10423
fun newInstance(fromSetup: Boolean = false): WifiSettingsFragment {
val fragment = WifiSettingsFragment()
val arguments = Bundle()
arguments.putBoolean("from_setup", fromSetup)
fragment.arguments = arguments
return fragment
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_wifi_settings, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val fromSetup = arguments?.getBoolean("from_setup")
adapter = WifiAdapter(view.context)
val list = view.findViewById<RecyclerView>(R.id.wifi_list)
list.addItemDecoration(
DividerItemDecoration.Builder(list.context)
.setPadding(resources.getDimensionPixelSize(R.dimen.dp_40))
.setDividerColor(ContextCompat.getColor(list.context, R.color.dividerLight))
.setDividerWidth(resources.getDimensionPixelSize(R.dimen.dp_1))
.build()
)
list.adapter = adapter
recyclerView = list
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
wifiSwitch = view.findViewById(R.id.wifi_enabled)
loadingView = view.findViewById(R.id.loading)
refreshContainer = view.findViewById(R.id.refresh_container)
ivRefresh = view.findViewById(R.id.refresh)
nextStep = view.findViewById(R.id.next_step)
ivRefresh?.setOnClickListener {
if (!isScanning) {
startScan()
}
}
view.findViewById<View>(R.id.next_step_container)?.isVisible = fromSetup == true
nextStep?.setOnClickListener {
start(PairFragment2())
}
if (wm?.isWifiEnabled == false) {
if (!ConfigUtils.getBoolean(ConfigUtils.KEY_SETUP_COMPLETED, false)) {
post {
wm?.isWifiEnabled = true
}
}
}
if (context?.let { AuthDelegate.getAuthResponseFromPref(it) == null } == true)
acquireWakeLock()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.ACCESS_FINE_LOCATION)
!= PermissionChecker.PERMISSION_GRANTED
) {
requestPermissions(
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_LOCATION_CODE
)
}
wm = context?.applicationContext?.getSystemService(Context.WIFI_SERVICE) as WifiManager
scanReceiver.register(context)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
connectionReceiver.register(context)
} else {
val connectivityManager =
context?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network?) {
super.onAvailable(network)
WifiUtils.getConnectedSsid(context)?.let { ssid ->
if (ssid.isNotEmpty()) {
connected = ssid
} else {
connected = null
}
} ?: run {
connected = null
}
post {
adapter?.notifyDataSetChanged()
}
}
override fun onLost(network: Network?) {
super.onLost(network)
connected = null
post {
adapter?.notifyDataSetChanged()
}
}
}
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build()
connectivityManager?.registerNetworkCallback(request, networkCallback)
this.networkCallback = networkCallback
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_LOCATION_CODE && grantResults.isNotEmpty()
&& grantResults[0] == PermissionChecker.PERMISSION_GRANTED &&
permissions.isNotEmpty() && permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION
) {
startScan()
} else {
pop()
}
}
override fun onSupportVisible() {
super.onSupportVisible()
fromSetup = arguments?.getBoolean("from_setup") == true
if (fromSetup) {
view?.findViewById<TextView>(R.id.title)?.let { titleView ->
titleView.setText(R.string.connect_wifi)
(titleView.layoutParams as? LinearLayout.LayoutParams)?.let { layoutParams ->
val margin = resources.getDimensionPixelSize(R.dimen.dp_40)
if (layoutParams.marginStart != margin) {
layoutParams.marginStart = margin
titleView.layoutParams = layoutParams
}
}
}
view?.findViewById<View>(R.id.back)?.visibility = View.GONE
} else {
view?.findViewById<TextView>(R.id.title)?.let { titleView ->
titleView.setText(R.string.wlan)
(titleView.layoutParams as? LinearLayout.LayoutParams)?.let { layoutParams ->
if (layoutParams.marginStart != 0) {
layoutParams.marginStart = 0
titleView.layoutParams = layoutParams
}
}
}
view?.findViewById<View>(R.id.back)?.visibility = View.VISIBLE
}
scans = null
connected = WifiUtils.getConnectedSsid(context)
adapter?.notifyDataSetChanged()
if (wm?.isWifiEnabled == true) {
startScan()
}
}
@Suppress("DEPRECATION")
private fun startScan() {
if (wm?.isWifiEnabled != true)
return
wm?.startScan()
isScanning = true
ivRefresh?.animate()?.alpha(0f)?.setDuration(150)?.withEndAction {
loadingView?.let { animationView ->
animationView.repeatCount = Animation.INFINITE
animationView.playAnimation()
animationView.animate()
.alpha(1f)
.setDuration(200)
.start()
}
}?.start()
}
override fun onSupportInvisible() {
super.onSupportInvisible()
uiHandler.removeCallbacksAndMessages(null)
warningAlert?.dismiss()
}
@SuppressLint("WakelockTimeout")
private fun acquireWakeLock() {
wifiWakeLock?.acquire() ?: run {
val powerManager = context?.getSystemService(Context.POWER_SERVICE) as PowerManager
val flag = PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_BRIGHT_WAKE_LOCK
val wakeLock = powerManager.newWakeLock(flag, "iflytek:wifi")
wakeLock.acquire()
wifiWakeLock = wakeLock
}
}
private fun releaseWakeLock() {
wifiWakeLock?.let {
it.release()
val powerManager = context?.getSystemService(Context.POWER_SERVICE) as PowerManager
val flag = PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_BRIGHT_WAKE_LOCK
val wakeLock = powerManager.newWakeLock(flag, "iflytek:wifi.release")
wakeLock.acquire(TimeUnit.SECONDS.toMillis(10))
wifiWakeLock = null
}
}
override fun onBackPressedSupport(): Boolean {
if (getPreFragment() == null)
return true
return super.onBackPressedSupport()
}
override fun onDestroy() {
super.onDestroy()
scanReceiver.unregister(context)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
connectionReceiver.unregister(context)
} else {
(context?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager)
?.let { connectivityManager ->
val networkCallback =
(this.networkCallback as? ConnectivityManager.NetworkCallback)
?: return
connectivityManager.unregisterNetworkCallback(networkCallback)
}
}
releaseWakeLock()
}
private fun handleScanResult() {
Log.d(TAG, "handleScanResult")
if (!isDetached) {
ivRefresh?.postDelayed({
if (!isDetached) {
startScan()
}
}, 30 * 1000)
}
configs.clear()
wm?.let {
val configuredNetworks = it.configuredNetworks
if (configuredNetworks?.isNotEmpty() == true)
for (config in it.configuredNetworks) {
val ssid = config.SSID?.substring(1, config.SSID.length - 1)
if (!ssid.isNullOrEmpty() && ssid.trim().isNotEmpty())
configs[ssid] = config
}
connected = WifiUtils.getConnectedSsid(context)
val scanResults = it.scanResults
val map = HashMap<String, ScanResult>()
for (o1 in scanResults) {
if (!o1.SSID.isNullOrEmpty() && o1.SSID.trim().isNotEmpty()) {
val o2 = map[o1.SSID]
if ((o2 == null || o2.level < o1.level) && o1.level != 0) {
map[o1.SSID] = o1
}
}
}
val list = ArrayList(map.values)
Collections.sort(list, Comparator { o1, o2 ->
val c1 = configs[o1.SSID]
val c2 = configs[o2.SSID]
if (c1 != null && c1.status == WifiConfiguration.Status.CURRENT) {
return@Comparator -1
} else if (c2 != null && c2.status == WifiConfiguration.Status.CURRENT) {
return@Comparator 1
}
if (c1 != null && c2 == null) {
return@Comparator -1
} else if (c1 == null && c2 != null) {
return@Comparator 1
}
o2.level - o1.level
})
scans = list
adapter?.notifyDataSetChanged()
if (!isDetached && scans.isNullOrEmpty()) {
Log.d(TAG, "result is empty. retry in 3 seconds. source: ${scanResults.size}")
ivRefresh?.postDelayed({
if (!isDetached) {
startScan()
}
}, 3 * 1000)
}
}
}
private fun handleOnItemClick(scan: ScanResult) {
val context = context ?: return
if (connected != scan.SSID) {
configs[scan.SSID]?.let { config ->
WifiUtils.connect(context, config.networkId)
start(WifiConnectingFragment(scan.SSID))
} ?: run {
if (!WifiUtils.isEncrypted(scan)) {
WifiUtils.connect(context, scan.SSID)
start(WifiConnectingFragment(scan.SSID))
} else {
start(InputNetworkFragment(scan))
}
}
} else {
start(WifiInfoFragment(scan))
}
}
private fun handleOpenWifiInfo(scan: ScanResult) {
start(WifiInfoFragment(scan))
}
private fun handleAddManual() {
start(InputNetworkFragment())
}
override fun scrollToNext(): Boolean {
recyclerView?.let { recyclerView ->
val lastItem =
(recyclerView.layoutManager as? LinearLayoutManager)?.findLastCompletelyVisibleItemPosition()
val itemCount = adapter?.itemCount ?: 0
if (lastItem == itemCount - 1 || adapter?.itemCount == 0
) {
return false
} else {
recyclerView.smoothScrollBy(0, recyclerView.height)
}
}
return true
}
override fun scrollToPrevious(): Boolean {
recyclerView?.let { recyclerView ->
val scrollY = recyclerView.computeVerticalScrollOffset()
val itemCount = adapter?.itemCount ?: 0
if (scrollY == 0 || itemCount == 0) {
return false
} else {
recyclerView.smoothScrollBy(0, -recyclerView.height)
}
}
return true
}
private inner class WifiAdapter internal constructor(context: Context) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val inflater: LayoutInflater = LayoutInflater.from(context)
override fun getItemViewType(position: Int): Int {
return when (position) {
0 -> 2
itemCount - 1 -> 1
else -> 0
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
0 ->
ItemViewHolder(inflater.inflate(R.layout.item_access_point_2, parent, false))
1 ->
ManualViewHolder(
inflater.inflate(
R.layout.item_access_point_manual,
parent,
false
)
)
2 -> {
val holder = WifiSwitchViewHolder(
inflater.inflate(
R.layout.item_wifi_switch,
parent,
false
)
)
wifiSwitch = holder.itemView.findViewById<StyledSwitch>(R.id.wifi_enabled)
wifiSwitch?.let { wifiSwitch ->
wifiSwitch.isChecked = wm?.isWifiEnabled == true
refreshContainer?.visibility =
if (wifiSwitch.isChecked) View.VISIBLE else View.GONE
wifiSwitch.setOnCheckedChangeListener(object :
StyledSwitch.OnCheckedChangeListener {
override fun onCheckedChange(switch: StyledSwitch, isChecked: Boolean) {
progressDialog?.dismiss()
val target = wifiSwitch.isChecked
if (target == wm?.isWifiEnabled)
return
progressDialog = ProgressDialog.show(
context, null,
if (isChecked) "正在开启" else "正在关闭", false, true
)
post {
val result = wm?.setWifiEnabled(target)
progressDialog?.dismiss()
if (result != true) {
wifiSwitch.isChecked = wm?.isWifiEnabled == true
}
if (!wifiSwitch.isChecked)
refreshContainer?.isVisible = false
}
}
})
}
holder
}
else ->
ItemViewHolder(inflater.inflate(R.layout.item_access_point_2, parent, false))
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ItemViewHolder) {
scans?.get(position - 1)?.let { scan ->
holder.bind(scan)
}
}
}
override fun getItemCount(): Int {
val isWifiEnabled = wm?.isWifiEnabled == true
return if (isWifiEnabled) (scans?.size ?: 0) + 2 else 1
}
internal inner class ManualViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
handleAddManual()
}
}
}
internal inner class WifiSwitchViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView)
internal inner class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val icon: ImageView = itemView.findViewById(R.id.icon)
private val ssid: TextView = itemView.findViewById(R.id.ssid)
private val status: TextView = itemView.findViewById(R.id.status)
private val info: ImageView = itemView.findViewById(R.id.info)
init {
itemView.setOnClickListener { handleOnItemClick(scans!![this@ItemViewHolder.layoutPosition - 1]) }
info.setOnClickListener { handleOpenWifiInfo(scans!![this@ItemViewHolder.layoutPosition - 1]) }
}
fun bind(scan: ScanResult) {
if (WifiUtils.isEncrypted(scan)) {
icon.setImageResource(R.drawable.ic_wifi_locked_black_24dp)
} else {
icon.setImageResource(R.drawable.ic_wifi_black_24dp)
}
ssid.text = scan.SSID
when {
connected == scan.SSID -> {
status.visibility = View.VISIBLE
status.text = "已连接"
info.visibility = View.VISIBLE
}
configs[scan.SSID] != null -> {
status.visibility = View.VISIBLE
status.text = "已保存"
info.visibility = View.VISIBLE
}
else -> {
status.visibility = View.GONE
info.visibility = View.GONE
}
}
}
}
}
private inner class ScanReceiver
internal constructor() :
SelfBroadcastReceiver(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION,
WifiManager.WIFI_STATE_CHANGED_ACTION
) {
override fun onReceiveAction(action: String, intent: Intent) {
when (action) {
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION -> {
handleScanResult()
isScanning = false
loadingView?.animate()?.alpha(0f)?.setDuration(150)?.withEndAction {
ivRefresh?.animate()?.alpha(1f)?.setDuration(200)?.start()
}?.start()
}
WifiManager.WIFI_STATE_CHANGED_ACTION -> {
val state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1)
if (state == WifiManager.WIFI_STATE_ENABLED) {
if (wifiSwitch?.isChecked != true)
wifiSwitch?.isChecked = true
refreshContainer?.visibility = View.VISIBLE
startScan()
} else if (state == WifiManager.WIFI_STATE_DISABLED) {
if (wifiSwitch?.isChecked != false)
wifiSwitch?.isChecked = false
refreshContainer?.visibility = View.GONE
}
scans = null
adapter?.notifyDataSetChanged()
if (refreshContainer?.visibility == View.GONE && wifiSwitch?.isChecked == true) {
ivRefresh?.alpha = 0f
loadingView?.alpha = 1f
loadingView?.playAnimation()
}
}
}
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.widget.CircleCheckBox
class SingleChoicePageFragment : Fragment() {
companion object {
fun newInstance(
titles: Array<String>,
icons: Array<String>?,
selectedItem: Int,
tag: Any? = null
): SingleChoicePageFragment {
val fragment = SingleChoicePageFragment()
fragment.titles.addAll(titles)
icons?.let {
fragment.icons.addAll(it)
}
fragment.selectedItem = selectedItem
fragment.tag = tag
return fragment
}
}
private var recyclerView: RecyclerView? = null
val titles = mutableListOf<String>()
val icons = mutableListOf<String>()
var selectedItem = 0
private set
private val adapter = ListAdapter()
var onItemSelectedListener: OnItemSelectedListener? = null
var tag: Any? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_single_choice_page, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view.findViewById(R.id.recycler_view)
recyclerView?.adapter = adapter
recyclerView?.itemAnimator = DefaultItemAnimator()
}
fun updateData(titles: Array<String>, icons: Array<String>?, selectedItem: Int) {
this.titles.clear()
this.titles.addAll(titles)
this.icons.clear()
icons?.let {
this.icons.addAll(icons)
}
this.selectedItem = selectedItem
adapter.notifyDataSetChanged()
}
private inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = ItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_single_choice_with_icon,
parent,
false
)
)
holder.itemView.setOnClickListener {
selectedItem = holder.adapterPosition
adapter.notifyItemRangeChanged(0, itemCount)
onItemSelectedListener?.onItemSelect(this@SingleChoicePageFragment, selectedItem)
}
holder.checkBox.isClickable = false
return holder
}
override fun getItemCount(): Int {
return titles.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ItemViewHolder) {
holder.titleView.text = titles[position]
holder.summaryView.isVisible = false
holder.checkBox.isVisible = position == selectedItem
if (icons.size > position) {
icons[position].let {
if (it.isEmpty()) {
holder.iconView.isVisible = false
} else {
holder.iconView.isVisible = true
Glide.with(holder.iconView)
.asDrawable()
.transition(DrawableTransitionOptions.withCrossFade())
.load(it)
.into(holder.iconView)
}
}
} else {
holder.iconView.isVisible = false
}
}
}
}
private class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val iconView: ImageView = itemView.findViewById(R.id.icon)
val titleView: TextView = itemView.findViewById(R.id.title)
val summaryView: TextView = itemView.findViewById(R.id.message)
val checkBox: CircleCheckBox = itemView.findViewById(R.id.check_box)
}
interface OnItemSelectedListener {
fun onItemSelect(fragment: SingleChoicePageFragment, position: Int)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.iflytek.cyber.iot.show.core.R
class StyledAlertDialog : DialogFragment() {
private var dialogIconView: ImageView? = null
private var dialogTitleView: TextView? = null
private var dialogMessageView: TextView? = null
private var dialogPositiveButton: TextView? = null
private var dialogNegativeButton: TextView? = null
private var dialogNegativeButton2: TextView? = null
private var isWarningAction = false
private var positiveButton: Pair<String, View.OnClickListener?>? = null
private var negativeButton: Pair<String, View.OnClickListener?>? = null
private var negativeButton2: Pair<String, View.OnClickListener?>? = null
var title: String? = null
var message: String? = null
var iconDrawable: Drawable? = null
set(value) {
value?.let {
dialogIconView?.visibility = View.VISIBLE
} ?: run {
dialogIconView?.visibility = View.GONE
}
dialogIconView?.setImageDrawable(value)
field = value
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
return inflater.inflate(R.layout.layout_styled_dialog, container, false)
}
override fun onStart() {
super.onStart()
dialog?.let { dialog ->
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.window?.setLayout(
resources.getDimensionPixelSize(R.dimen.dp_380),
WindowManager.LayoutParams.WRAP_CONTENT
)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dialogIconView = view.findViewById(R.id.dialog_icon)
dialogTitleView = view.findViewById(R.id.dialog_title)
dialogMessageView = view.findViewById(R.id.dialog_message)
dialogPositiveButton = view.findViewById(R.id.dialog_positive)
dialogNegativeButton = view.findViewById(R.id.dialog_negative)
dialogNegativeButton2 = view.findViewById(R.id.dialog_negative_2)
title?.let { title ->
dialogTitleView?.text = title
dialogTitleView?.visibility = View.VISIBLE
} ?: run {
dialogTitleView?.visibility = View.GONE
}
message?.let { message ->
dialogMessageView?.text = message
dialogMessageView?.visibility = View.VISIBLE
} ?: run {
dialogMessageView?.visibility = View.GONE
}
dialogIconView?.isVisible = iconDrawable != null
dialogIconView?.setImageDrawable(iconDrawable)
dialogPositiveButton?.let { dialogPositiveButton ->
if (isWarningAction) {
dialogPositiveButton.setBackgroundResource(R.drawable.bg_round_warning_32dp)
}
matchPairToButton(positiveButton, dialogPositiveButton)
}
dialogNegativeButton?.let { dialogNegativeButton ->
matchPairToButton(negativeButton, dialogNegativeButton)
}
dialogNegativeButton2?.let { dialogNegativeButton ->
matchPairToButton(negativeButton2, dialogNegativeButton)
}
}
private fun matchPairToButton(pair: Pair<String, View.OnClickListener?>?, button: TextView) {
pair?.let {
button.text = it.first
button.setOnClickListener { view ->
dismiss()
it.second?.onClick(view)
}
button.visibility = View.VISIBLE
} ?: run {
button.visibility = View.GONE
}
}
class Builder {
private var title: String? = null
private var message: String? = null
private var iconDrawable: Drawable? = null
private var positiveButton: Pair<String, View.OnClickListener?>? = null
private var negativeButton: Pair<String, View.OnClickListener?>? = null
private var negativeButton2: Pair<String, View.OnClickListener?>? = null
private var isWarningAction = false
fun setTitle(title: String): Builder {
this.title = title
return this
}
fun setMessage(message: String): Builder {
this.message = message
return this
}
fun setIcon(iconDrawable: Drawable): Builder {
this.iconDrawable = iconDrawable
return this
}
fun setPositiveButton(text: String, onClickListener: View.OnClickListener?): Builder {
positiveButton = Pair(text, onClickListener)
return this
}
fun setNegativeButton(text: String, onClickListener: View.OnClickListener?): Builder {
negativeButton = Pair(text, onClickListener)
return this
}
fun setNegativeButton2(text: String, onClickListener: View.OnClickListener?): Builder {
negativeButton2 = Pair(text, onClickListener)
return this
}
fun setWarningAction(isWarningAction: Boolean): Builder {
this.isWarningAction = isWarningAction
return this
}
fun build(): StyledAlertDialog {
val dialog = StyledAlertDialog()
dialog.title = title
dialog.message = message
dialog.iconDrawable = iconDrawable
dialog.positiveButton = positiveButton
dialog.negativeButton = negativeButton
dialog.negativeButton2 = negativeButton2
dialog.isWarningAction = isWarningAction
return dialog
}
fun show(manager: FragmentManager, tag: String? = null): StyledAlertDialog {
val dialog = build()
dialog.show(manager, tag)
return dialog
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.animation.ValueAnimator
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.google.gson.Gson
import com.google.gson.JsonParser
import com.iflytek.cyber.evs.sdk.auth.AuthDelegate
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.EngineService
import com.iflytek.cyber.iot.show.core.FloatingService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.MediaApi
import com.iflytek.cyber.iot.show.core.impl.prompt.PromptManager
import com.iflytek.cyber.iot.show.core.model.Banner
import com.iflytek.cyber.iot.show.core.model.Error
import com.iflytek.cyber.iot.show.core.model.MusicBody
import com.iflytek.cyber.iot.show.core.widget.StyledAlertDialog
import com.iflytek.cyber.iot.show.core.widget.StyledQRCodeDialog
import me.yokeyword.fragmentation.ISupportFragment
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.Math.random
import java.net.UnknownHostException
import kotlin.math.roundToInt
class BannerFragment : Fragment() {
private var banner: Banner? = null
private var position = 0
private var currentSummary = 0
private var tvSummary: TextView? = null
private val handler = Handler()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_banner, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val banner: Banner? = arguments?.getParcelable("banner")
?: (savedInstanceState?.getParcelable("banner"))
position = arguments?.getInt("position") ?: 0
val background: ImageView = view.findViewById(R.id.background)
val backgroundContainer: FrameLayout = view.findViewById(R.id.background_container)
val tvTitle: TextView = view.findViewById(R.id.title)
val tvSummary: TextView = view.findViewById(R.id.summary)
val container = view.findViewById<View>(R.id.banner_container)
container.tag = position
// setup shadow
val shadowColor = Color.parseColor("#19000000")
val dy = resources.getDimensionPixelSize(R.dimen.dp_2).toFloat()
val radius = resources.getDimensionPixelSize(R.dimen.dp_4).toFloat()
tvTitle.setShadowLayer(radius, 0f, dy, shadowColor)
tvSummary.setShadowLayer(radius, 0f, dy, shadowColor)
tvTitle.text = banner?.title
if (banner?.descriptions?.isNotEmpty() == true) {
val index = (random() * (banner.descriptions.size - 1)).roundToInt()
currentSummary = index
tvSummary.text = banner.descriptions[index]
} else {
tvSummary.text = ""
}
this.tvSummary = tvSummary
if (!banner?.cover.isNullOrEmpty()) {
Glide.with(background)
.load(banner?.cover)
.transition(DrawableTransitionOptions.withCrossFade())
.into(background)
backgroundContainer.foreground = ColorDrawable(Color.parseColor("#33262626"))
} else {
val wallpaper = arrayOf(
"file:///android_asset/wallpaper/wallpaper_a.jpg",
"file:///android_asset/wallpaper/wallpaper_b.jpg",
"file:///android_asset/wallpaper/wallpaper_c.jpg"
)
Glide.with(background)
.load(wallpaper[(random() * (wallpaper.size - 1)).roundToInt()])
.transition(DrawableTransitionOptions.withCrossFade())
.into(background)
backgroundContainer.foreground = null
}
tvTitle.setOnClickListener {
when (banner?.target) {
"webview" -> {
val fragment = WebViewFragment()
val arguments = Bundle()
arguments.putString("url", banner.content)
fragment.arguments = arguments
(parentFragment as? BaseFragment)?.start(fragment)
}
"skill" -> {
val intent = Intent(context, EngineService::class.java)
intent.action = EngineService.ACTION_SEND_TEXT_IN
intent.putExtra(EngineService.EXTRA_QUERY, banner.content)
context?.startService(intent)
}
"video",
"audio" -> {
val api = CoreApplication.from(it.context).createApi(MediaApi::class.java)
val mediaId = try {
Integer.parseInt(banner.content!!)
} catch (t: Throwable) {
t.printStackTrace()
-1
}
if (mediaId != -1)
api?.playMusic(MusicBody(mediaId, null, null))?.enqueue(object :
Callback<String> {
override fun onFailure(call: Call<String>, t: Throwable) {
t.printStackTrace()
if (t is UnknownHostException) {
// 网络不可用
PromptManager.play(PromptManager.NETWORK_LOST)
val intent = Intent(context, FloatingService::class.java)
intent.action = FloatingService.ACTION_SHOW_NOTIFICATION
intent.putExtra(FloatingService.EXTRA_MESSAGE, "网络连接异常,请重新设置")
intent.putExtra(FloatingService.EXTRA_TAG, "network_error")
intent.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_TEXT,
"设置网络"
)
intent.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_ACTION,
MainFragment2.ACTION_OPEN_WIFI
)
intent.putExtra(
FloatingService.EXTRA_ICON_RES,
R.drawable.ic_wifi_error_white_40dp
)
context?.startService(intent)
} else {
val showNotification =
Intent(context, FloatingService::class.java)
showNotification.action =
FloatingService.ACTION_SHOW_NOTIFICATION
showNotification.putExtra(
FloatingService.EXTRA_MESSAGE,
"请求出现错误,请稍后再试"
)
showNotification.putExtra(
FloatingService.EXTRA_ICON_RES,
R.drawable.ic_default_error_white_40dp
)
showNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_TEXT,
getString(R.string.i_got_it)
)
context?.startService(showNotification)
}
}
override fun onResponse(
call: Call<String>,
response: Response<String>
) {
if (response.isSuccessful) {
(parentFragment as? BaseFragment)?.start(
PlayerInfoFragment2(),
ISupportFragment.SINGLETOP
)
} else {
if (response.code() == 401) {
if (context != null &&
AuthDelegate.getAuthResponseFromPref(context!!) == null
) {
val disconnectNotification =
Intent(context, FloatingService::class.java)
disconnectNotification.action =
FloatingService.ACTION_SHOW_NOTIFICATION
disconnectNotification.putExtra(
FloatingService.EXTRA_MESSAGE,
getString(R.string.message_evs_auth_expired)
)
disconnectNotification.putExtra(
FloatingService.EXTRA_TAG,
"auth_error"
)
disconnectNotification.putExtra(
FloatingService.EXTRA_ICON_RES,
R.drawable.ic_default_error_white_40dp
)
disconnectNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_TEXT,
getString(R.string.re_auth)
)
disconnectNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_ACTION,
MainFragment2.ACTION_OPEN_AUTH
)
disconnectNotification.putExtra(
FloatingService.EXTRA_KEEPING, true
)
context?.startService(disconnectNotification)
}
} else {
try {
val body = response.errorBody()?.string()
val error = Gson().fromJson(body, Error::class.java)
if (error.redirectUrl.isNullOrEmpty()) {
val intent = Intent(context, FloatingService::class.java)
intent.action = FloatingService.ACTION_SHOW_NOTIFICATION
intent.putExtra(FloatingService.EXTRA_MESSAGE, error.message)
intent.putExtra(FloatingService.EXTRA_POSITIVE_BUTTON_TEXT, "我知道了")
context?.startService(intent)
} else {
val context = context ?: return
val uri = Uri.parse(error.redirectUrl)
val codeUrl = uri.buildUpon()
.appendQueryParameter(
"token",
AuthDelegate.getAuthResponseFromPref(context)?.accessToken
)
.build()
.toString()
StyledQRCodeDialog.Builder()
.setTitle(error.message)
.setMessage(getString(R.string.scan_qrcode_to_continue))
.setCode(codeUrl)
.setButton(getString(R.string.close), null)
.show(fragmentManager)
}
} catch (t: Throwable) {
t.printStackTrace()
val showNotification =
Intent(context, FloatingService::class.java)
showNotification.action =
FloatingService.ACTION_SHOW_NOTIFICATION
showNotification.putExtra(
FloatingService.EXTRA_MESSAGE,
"请求出现错误,请稍后再试"
)
showNotification.putExtra(
FloatingService.EXTRA_ICON_RES,
R.drawable.ic_default_error_black_40dp
)
showNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_TEXT,
getString(R.string.i_got_it)
)
context?.startService(showNotification)
}
}
}
}
})
}
}
}
this.banner = banner
}
override fun onResume() {
super.onResume()
postNextUpdateSummary()
}
private val updateSummaryRunnable: Runnable = Runnable {
banner?.let { banner ->
if (isResumed) {
if (banner.descriptions?.isNotEmpty() == true && banner.descriptions.size > 1) {
val next = (currentSummary + 1) % banner.descriptions.size
currentSummary = next
startUpdateSummaryAnimator(banner.descriptions[next])
postNextUpdateSummary()
}
}
}
}
private fun postNextUpdateSummary() {
handler.removeCallbacksAndMessages(null)
handler.postDelayed(updateSummaryRunnable, 6 * 1000)
}
private fun startUpdateSummaryAnimator(newText: String) {
val animator = ValueAnimator.ofFloat(0f, 2f)
animator.addUpdateListener {
val value = it.animatedValue as Float
if (value > 1) {
if (tvSummary?.text.toString() != newText) {
tvSummary?.text = newText
}
tvSummary?.alpha = value - 1
} else {
tvSummary?.alpha = 1 - value
}
}
animator.duration = 600
animator.start()
}
override fun onPause() {
super.onPause()
handler.removeCallbacksAndMessages(null)
}
override fun onSaveInstanceState(outState: Bundle) {
banner?.let { banner ->
outState.putParcelable("banner", banner)
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.template
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
class WeatherTemplateView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
companion object {
private const val TYPE_NORMAL = 0
private const val TYPE_FUTURE = 1
private const val TYPE_NOWADAYS = 2
}
private val skillIconImage: ImageView
private val backgroundImage: ImageView
private val mainTitle: TextView
private val subTitle: TextView
// containers
private val normalContainer: View
private val nowadaysContainer: View
private val normalHeader: View
private val normalHeaderIcon: ImageView
private val normalHeaderBody: TextView
private val normalHeaderSubBody: TextView
private val nowadaysIcon: ImageView
private val nowadaysCondition: TextView
private val nowadaysDescription: TextView
private val weatherForecastRecyclerView: RecyclerView
private val adapter = ListAdapter()
private val innerOnClickBackListener = OnClickListener { v ->
onClickBackListener?.onClick(v)
}
private var onClickBackListener: OnClickListener? = null
private var currentPayload: String? = null
private var currentWeather: WeatherPayload? = null
private var forecastItemWidth = 0
init {
val childView = LayoutInflater.from(context).inflate(R.layout.layout_weather_template_normal, null)
skillIconImage = childView.findViewById(R.id.skill_icon)
backgroundImage = childView.findViewById(R.id.background_image)
mainTitle = childView.findViewById(R.id.main_title)
subTitle = childView.findViewById(R.id.sub_title)
normalContainer = childView.findViewById(R.id.normal_container)
normalHeader = childView.findViewById(R.id.normal_header)
nowadaysContainer = childView.findViewById(R.id.nowadays_container)
weatherForecastRecyclerView = childView.findViewById(R.id.forecast_recycler_view)
normalHeaderIcon = childView.findViewById(R.id.normal_icon)
normalHeaderBody = childView.findViewById(R.id.normal_body)
normalHeaderSubBody = childView.findViewById(R.id.normal_sub_body)
nowadaysCondition = childView.findViewById(R.id.nowadays_condition)
nowadaysDescription = childView.findViewById(R.id.nowadays_description)
nowadaysIcon = childView.findViewById(R.id.nowadays_icon)
weatherForecastRecyclerView.adapter = adapter
val layoutManager =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
weatherForecastRecyclerView.layoutManager = layoutManager
weatherForecastRecyclerView.post {
forecastItemWidth = weatherForecastRecyclerView.width / 6
adapter.notifyDataSetChanged()
}
childView.findViewById<View>(R.id.back)?.setOnClickListener(innerOnClickBackListener)
addView(childView)
}
fun updatePayload(payload: String) {
val gson = Gson()
val weather = gson.fromJson(payload, WeatherPayload::class.java)
val type = getWeatherType(weather)
currentPayload?.let {
val prevWeather = gson.fromJson(it, WeatherPayload::class.java)
val prevType = getWeatherType(prevWeather)
if (prevType != type) {
setupView(type)
}
} ?: run {
setupView(type)
}
if (!weather.currentWeather?.iconUrl.isNullOrEmpty()) {
normalHeaderIcon.visibility = View.VISIBLE
if (type == TYPE_NORMAL) {
Glide.with(normalHeaderIcon)
.load(weather.currentWeather?.iconUrl)
.transition(DrawableTransitionOptions.withCrossFade())
.into(normalHeaderIcon)
} else {
Glide.with(nowadaysIcon)
.load(weather.currentWeather?.iconUrl)
.transition(DrawableTransitionOptions.withCrossFade())
.into(nowadaysIcon)
}
} else {
normalHeaderIcon.visibility = View.GONE
}
val size = weather.weatherForecasts?.size ?: 0
if (size in 1..6) {
weatherForecastRecyclerView.layoutManager =
GridLayoutManager(context, size)
} else {
weatherForecastRecyclerView.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
}
if (type == TYPE_NORMAL) {
if (weather.currentWeather?.condition.isNullOrEmpty()) {
if (weather.currentWeather?.description.isNullOrEmpty()) {
normalHeaderBody.text = weather.currentWeather?.highTemperature
normalHeaderSubBody.text = weather.currentWeather?.lowTemperature
} else {
normalHeaderBody.text = weather.currentWeather?.description
normalHeaderSubBody.text = String.format("%s ~ %s",
weather.currentWeather?.lowTemperature,
weather.currentWeather?.highTemperature)
}
} else {
normalHeaderBody.text = weather.currentWeather?.condition
normalHeaderSubBody.text = String.format("%s ~ %s",
weather.currentWeather?.lowTemperature,
weather.currentWeather?.highTemperature)
}
} else if (type == TYPE_NOWADAYS) {
nowadaysCondition.text = weather.currentWeather?.condition
nowadaysDescription.text = weather.currentWeather?.description
}
mainTitle.text = weather.mainTitle
weather.subTitle?.let { subTitle ->
if (subTitle.isNotEmpty()) {
this.subTitle.visibility = View.VISIBLE
this.subTitle.text = subTitle
} else {
this.subTitle.visibility = View.GONE
}
} ?: run {
this.subTitle.visibility = View.GONE
}
weather.skillIconUrl?.let { skillIconUrl ->
if (skillIconUrl.isNotEmpty()) {
skillIconImage.visibility = View.VISIBLE
Glide.with(skillIconImage)
.load(skillIconUrl)
.apply(RequestOptions()
.transform(RoundedCornersTransformation(
resources.getDimensionPixelSize(R.dimen.dp_8), 0)))
.transition(DrawableTransitionOptions.withCrossFade())
.into(skillIconImage)
} else {
skillIconImage.visibility = View.GONE
}
} ?: run {
skillIconImage.visibility = View.GONE
}
weather?.backButton?.let { backgroundImageUrl ->
if (backgroundImageUrl.isNotEmpty()) {
backgroundImage.visibility = View.VISIBLE
Glide.with(backgroundImage)
.load(backgroundImageUrl)
.transition(DrawableTransitionOptions.withCrossFade())
.into(backgroundImage)
} else {
backgroundImage.visibility = View.GONE
}
} ?: run {
backgroundImage.visibility = View.GONE
}
adapter.notifyDataSetChanged()
this.currentPayload = payload
this.currentWeather = weather
}
private fun setupView(type: Int) {
when (type) {
TYPE_FUTURE -> {
normalContainer.visibility = View.VISIBLE
normalHeader.visibility = View.GONE
nowadaysContainer.visibility = View.GONE
}
TYPE_NORMAL -> {
normalContainer.visibility = View.VISIBLE
normalHeader.visibility = View.VISIBLE
nowadaysContainer.visibility = View.GONE
}
TYPE_NOWADAYS -> {
normalContainer.visibility = View.GONE
nowadaysContainer.visibility = View.VISIBLE
}
}
}
fun setOnClickBackListener(onClickListener: OnClickListener?) {
this.onClickBackListener = onClickListener
}
private fun getWeatherType(weather: WeatherPayload): Int {
val isFutureWeatherType = weather.currentWeather == null ||
(weather.currentWeather.highTemperature.isNullOrEmpty() &&
weather.currentWeather.lowTemperature.isNullOrEmpty())
return if (weather.weatherForecasts?.isNotEmpty() == true) {
if (isFutureWeatherType) {
TYPE_FUTURE
} else {
TYPE_NORMAL
}
} else {
TYPE_NOWADAYS
}
}
private inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val typeNormal = 0
private val typeLarge = 1
override fun getItemViewType(position: Int): Int {
return currentWeather?.let { weather ->
when (getWeatherType(weather)) {
TYPE_FUTURE ->
typeLarge
else ->
typeNormal
}
} ?: typeNormal
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == typeLarge) {
ForecastViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.item_weather_forecast_large, parent, false))
} else {
ForecastViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.item_weather_forecast_normal, parent, false))
}
}
override fun getItemCount(): Int {
return currentWeather?.weatherForecasts?.size ?: 0
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ForecastViewHolder) {
val layoutManager = weatherForecastRecyclerView.layoutManager
val targetWidth =
if (layoutManager is GridLayoutManager && layoutManager.spanCount == itemCount)
ViewGroup.LayoutParams.MATCH_PARENT
else
forecastItemWidth
if (targetWidth > 0 &&
holder.itemView.layoutParams.width != targetWidth) {
val layoutParams = holder.itemView.layoutParams
layoutParams.width = targetWidth
holder.itemView.layoutParams = layoutParams
Log.d("Weather", "Set to $targetWidth")
}
currentWeather?.weatherForecasts?.get(position)?.let { forecast ->
holder.tvWeekday?.text = forecast.weekday
if (!forecast.imageUrl.isNullOrEmpty()) {
holder.ivImage?.let { imageView ->
Glide.with(imageView)
.load(forecast.imageUrl)
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageView)
}
}
if (holder.tvTemperature != null) {
holder.tvTemperature.text = String.format("%s ~ %s",
forecast.lowTemperature, forecast.highTemperature)
} else {
holder.tvHighTemperature?.text = forecast.highTemperature
holder.tvLowTemperature?.text = forecast.lowTemperature
holder.tvDate?.text = forecast.date
}
}
}
}
}
class ForecastViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val ivImage: ImageView? = itemView.findViewById(R.id.forecast_image)
val tvWeekday: TextView? = itemView.findViewById(R.id.forecast_weekday)
// normal
val tvTemperature: TextView? = itemView.findViewById(R.id.forecast_temperature)
// large
val tvHighTemperature: TextView? = itemView.findViewById(R.id.forecast_high_temperature)
val tvLowTemperature: TextView? = itemView.findViewById(R.id.forecast_low_temperature)
val tvDate: TextView? = itemView.findViewById(R.id.forecast_date)
}
data class WeatherPayload(
@SerializedName(Constant.PAYLOAD_CURRENT_WEATHER) val currentWeather: CurrentWeather?,
@SerializedName(Constant.PAYLOAD_WEATHER_FORECAST) val weatherForecasts: List<WeatherForecast>?,
@SerializedName(Constant.PAYLOAD_MAIN_TITLE) val mainTitle: String?,
@SerializedName(Constant.PAYLOAD_SUB_TITLE) val subTitle: String?,
@SerializedName(Constant.PAYLOAD_SKILL_ICON_URL) val skillIconUrl: String?,
@SerializedName(Constant.PAYLOAD_TEMPLATE_ID) val templateId: String,
@SerializedName(Constant.PAYLOAD_TYPE) val type: String?,
@SerializedName(Constant.PAYLOAD_BACK_BUTTON) val backButton: String?,
@SerializedName(Constant.PAYLOAD_BACKGROUND_IMAGE_URL) val backgroundImageUrl: String?
)
data class CurrentWeather(
@SerializedName(Constant.PAYLOAD_CONDITION) val condition: String?,
@SerializedName(Constant.PAYLOAD_DESCRIPTION) val description: String?,
@SerializedName(Constant.PAYLOAD_HIGH_TEMPERATURE) val highTemperature: String?,
@SerializedName(Constant.PAYLOAD_LOW_TEMPERATURE) val lowTemperature: String?,
@SerializedName(Constant.PAYLOAD_ICON_URL) val iconUrl: String?
)
data class WeatherForecast(
@SerializedName(Constant.PAYLOAD_WEEKDAY) val weekday: String?,
@SerializedName(Constant.PAYLOAD_DATE) val date: String?,
@SerializedName(Constant.PAYLOAD_HIGH_TEMPERATURE) val highTemperature: String?,
@SerializedName(Constant.PAYLOAD_LOW_TEMPERATURE) val lowTemperature: String?,
@SerializedName(Constant.PAYLOAD_IMAGE_URL) val imageUrl: String?
)
class Builder(private val context: Context) {
private var payload: String? = null
private var onClickListener: OnClickListener? = null
fun payload(payload: String): Builder {
this.payload = payload
return this
}
fun onClickBackListener(onClickListener: OnClickListener?): Builder {
this.onClickListener = onClickListener
return this
}
fun build(): WeatherTemplateView {
val view = WeatherTemplateView(context)
payload?.let { payload ->
view.updatePayload(payload)
}
view.setOnClickBackListener(onClickListener)
return view
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import com.airbnb.lottie.LottieAnimationView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.ScreenUtils
import com.iflytek.cyber.iot.show.core.utils.dp2Px
import com.iflytek.home.sdk.IFlyHome
import com.iflytek.home.sdk.callback.IFlyHomeCallback
class StyledWebDialog : DialogFragment() {
private var webView: WebView? = null
private var loading: LottieAnimationView? = null
private var errorContainer: LinearLayout? = null
private var retry: Button? = null
private var onWebPageCallback: OnWebPageCallback? = null
private var errorCodes = intArrayOf(
WebViewClient.ERROR_AUTHENTICATION,
WebViewClient.ERROR_AUTHENTICATION, WebViewClient.ERROR_BAD_URL,
WebViewClient.ERROR_CONNECT, WebViewClient.ERROR_FAILED_SSL_HANDSHAKE,
WebViewClient.ERROR_FILE, WebViewClient.ERROR_FILE_NOT_FOUND,
WebViewClient.ERROR_HOST_LOOKUP, WebViewClient.ERROR_IO,
WebViewClient.ERROR_PROXY_AUTHENTICATION, WebViewClient.ERROR_UNSAFE_RESOURCE,
WebViewClient.ERROR_REDIRECT_LOOP, WebViewClient.ERROR_TIMEOUT,
WebViewClient.ERROR_TOO_MANY_REQUESTS, WebViewClient.ERROR_UNKNOWN,
WebViewClient.ERROR_UNSAFE_RESOURCE, WebViewClient.ERROR_UNSUPPORTED_AUTH_SCHEME,
WebViewClient.ERROR_UNSUPPORTED_SCHEME
)
private var receivedError = false
fun setOnWebPageCallback(onWebPageCallback: OnWebPageCallback) {
this.onWebPageCallback = onWebPageCallback
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
return inflater.inflate(R.layout.layout_styled_web_dialog, container, false)
}
override fun onStart() {
super.onStart()
val height = ScreenUtils.getHeight(context) - 64.dp2Px()
val width = context?.resources?.getDimensionPixelSize(R.dimen.dp_250) ?: return
dialog?.let { dialog ->
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.window?.setLayout(width, height)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val close = view.findViewById<ImageView>(R.id.close)
close.setOnClickListener {
dismissAllowingStateLoss()
}
webView = view.findViewById(R.id.web_view)
loading = view.findViewById(R.id.loading)
errorContainer = view.findViewById(R.id.error_container)
retry = view.findViewById(R.id.retry)
retry?.setOnClickListener {
receivedError = false
errorContainer?.isVisible = false
loading?.isVisible = true
loading?.playAnimation()
webView?.reload()
}
loading?.isVisible = true
loading?.playAnimation()
webView?.let {
IFlyHome.register(it, object : IFlyHomeCallback() {
override fun openNewPage(tag: String, params: String?) {
onWebPageCallback?.openNewPage(tag, params)
}
override fun closePage() {
onWebPageCallback?.onClosePage()
}
override fun updateTitle(title: String) {
}
override fun getWebViewClient(): WebViewClient? {
return object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
loading?.isVisible = true
loading?.playAnimation()
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
loading?.isVisible = false
loading?.pauseAnimation()
if (!receivedError) {
webView?.isVisible = true
} else {
errorContainer?.isVisible = true
webView?.isVisible = false
}
}
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
super.onReceivedError(view, request, error)
receivedError = true
loading?.isVisible = false
loading?.pauseAnimation()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
handleWebError(error?.errorCode)
}
}
override fun onReceivedError(
view: WebView?,
errorCode: Int,
description: String?,
failingUrl: String?
) {
super.onReceivedError(view, errorCode, description, failingUrl)
receivedError = true
loading?.isVisible = false
loading?.pauseAnimation()
handleWebError(errorCode)
}
}
}
}, null)
}
arguments?.getString("url")?.let { url ->
webView?.loadUrl(url)
}
}
private fun handleWebError(errorCode: Int?) {
for (code in errorCodes) {
if (errorCode == code) {
Log.e("WebDialog", "code: " + code)
webView?.isVisible = false
errorContainer?.isVisible = true
return
}
}
}
override fun onDestroy() {
super.onDestroy()
webView?.run {
IFlyHome.unregister(this)
}
webView?.destroy()
}
interface OnWebPageCallback {
fun onClosePage()
fun openNewPage(tag: String, params: String?)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.iflytek.cyber.iot.show.core.R
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
class StyledSwitch @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val trackPaint = Paint()
private val thumbShadowPaint = Paint()
private val thumbPaint = Paint()
private val pressPaint = Paint()
private var trackRectF = RectF()
private var thumbSize = 0f
private var trackSize = 0f
private var pressSize = 0f
private var trackShadowRadius = 0f
private var trackShadowDy = 0f
private var trackMargin = 0f
private var thumbMargin = 0f
private var thumbLeft = 0f
private var progress = 0f
private var pressProgress = 0f
private var touchX = 0f
private var touchY = 0f
private var touchDownTime = 0L
private var animator: Animator? = null
private var pressAnimator: Animator? = null
private var thumbColor = resources.getColor(R.color.tablet_grey_300)
private val thumbEnableColor = resources.getColor(R.color.setup_primary)
private var trackColor = resources.getColor(R.color.tablet_grey_500)
private val trackEnableColor = Color.argb(
50, Color.red(thumbEnableColor),
Color.green(thumbEnableColor), Color.blue(thumbEnableColor)
)
private val shadowColor = Color.parseColor("#1C000000")
private val shadowEnableColor = Color.parseColor("#500E65FF")
private var onCheckedChangeListener: OnCheckedChangeListener? = null
fun setTrackColor(trackColor: Int) {
this.trackColor = trackColor
trackPaint.color = trackColor
}
fun setThumbColor(thumbColor: Int) {
this.thumbColor = thumbColor
thumbPaint.color = thumbColor
}
var isChecked = false
set(value) {
if (value) {
animatingTo(1f)
} else {
animatingTo(0f)
}
val changed = field != value
field = value
if (changed)
onCheckedChangeListener?.onCheckedChange(this, value)
}
init {
isClickable = true
isFocusable = true
thumbPaint.isAntiAlias = true
pressPaint.isAntiAlias = true
trackPaint.isAntiAlias = true
thumbShadowPaint.isAntiAlias = true
thumbPaint.color = thumbColor
trackPaint.color = trackColor
pressPaint.color = Color.BLACK
pressPaint.alpha = 10
setLayerType(LAYER_TYPE_SOFTWARE, Paint())
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val minimumWidth = resources.getDimensionPixelSize(R.dimen.dp_60)
val minimumHeight = resources.getDimensionPixelSize(R.dimen.dp_42)
setMeasuredDimension(
measureSize(widthMeasureSpec, minimumWidth),
measureSize(heightMeasureSpec, minimumHeight)
)
}
private fun measureSize(measureSpec: Int, minWidth: Int): Int {
val mode = MeasureSpec.getMode(measureSpec)
val size = MeasureSpec.getSize(measureSpec)
return when (mode) {
MeasureSpec.AT_MOST -> minWidth
MeasureSpec.EXACTLY -> size
else -> minWidth
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
pressSize = h.toFloat()
thumbSize = pressSize * 30 / 56
trackShadowRadius = 5f / 24 * thumbSize
trackShadowDy = 3f / 24 * thumbSize
thumbMargin = (h - thumbSize) / 2
trackMargin = thumbSize / 15
trackSize = thumbSize - 2 * trackMargin
trackRectF = RectF(
trackMargin + thumbMargin, height / 2 - trackSize / 2,
width - trackMargin - thumbMargin, height / 2 + trackSize / 2
)
updateProgress(progress, false)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas ?: return
canvas.drawRoundRect(trackRectF, trackSize / 2, trackSize / 2, trackPaint)
canvas.drawCircle(thumbLeft, height / 2f, pressProgress * pressSize / 2, pressPaint)
canvas.drawCircle(thumbLeft, height / 2f, thumbSize / 2, thumbShadowPaint)
canvas.drawCircle(thumbLeft, height / 2f, thumbSize / 2, thumbPaint)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
if (isEnabled) {
parent.requestDisallowInterceptTouchEvent(true)
when (event?.action) {
MotionEvent.ACTION_DOWN -> {
touchX = event.x
touchY = event.y
touchDownTime = System.currentTimeMillis()
showPress()
}
MotionEvent.ACTION_MOVE -> {
if (isChecked) {
val offset = min(0f, event.x - touchX)
val percent = min(-offset / width, 1f)
updateProgress(1 - percent)
} else {
val offset = max(0f, event.x - touchX)
val percent = min(offset / width, 1f)
updateProgress(percent)
}
}
MotionEvent.ACTION_UP -> {
dismissPress()
if (System.currentTimeMillis() - touchDownTime < 200
&& (event.x - touchX).toDouble().pow(2.0)
+ (event.y - touchY).toDouble().pow(2.0) < 20 * 20
) {
isChecked = !isChecked
performClick()
} else {
isChecked = progress >= 0.5
}
}
}
return true
} else {
return false
}
}
private fun updateProgress(progress: Float, invalidate: Boolean = true) {
this.progress = progress
trackPaint.color = Color.rgb(
((1 - progress) * Color.red(trackColor)
+ progress * Color.red(trackEnableColor)).toInt(),
((1 - progress) * Color.green(trackColor)
+ progress * Color.green(trackEnableColor)).toInt(),
((1 - progress) * Color.blue(trackColor)
+ progress * Color.blue(trackEnableColor)).toInt()
)
trackPaint.alpha = (255 - 128 * progress).toInt()
thumbPaint.color = Color.rgb(
((1 - progress) * Color.red(thumbColor)
+ progress * Color.red(thumbEnableColor)).toInt(),
((1 - progress) * Color.green(thumbColor)
+ progress * Color.green(thumbEnableColor)).toInt(),
((1 - progress) * Color.blue(thumbColor)
+ progress * Color.blue(thumbEnableColor)).toInt()
)
thumbShadowPaint.alpha = ((0.1f * (1 - progress) + 0.5f * progress) * 255).toInt()
thumbShadowPaint.setShadowLayer(
trackShadowRadius, 0f, trackShadowDy,
Color.rgb(
((1 - progress) * Color.red(shadowColor)
+ progress * Color.red(shadowEnableColor)).toInt(),
((1 - progress) * Color.green(shadowColor)
+ progress * Color.green(shadowEnableColor)).toInt(),
((1 - progress) * Color.blue(shadowColor)
+ progress * Color.blue(shadowEnableColor)).toInt()
)
)
thumbLeft = thumbMargin + thumbSize / 2 +
(width - thumbSize - 2 * thumbMargin) * progress
if (invalidate)
invalidate()
}
private fun showPress() {
pressAnimator?.cancel()
val animator = ValueAnimator.ofFloat(pressProgress, 1f)
animator.addUpdateListener {
pressProgress = it.animatedValue as Float
invalidate()
}
animator.duration = (200 * Math.abs(1f - pressProgress)).toLong()
animator.start()
pressAnimator = animator
}
private fun dismissPress() {
pressAnimator?.cancel()
val animator = ValueAnimator.ofFloat(pressProgress, 0f)
animator.addUpdateListener {
pressProgress = it.animatedValue as Float
invalidate()
}
animator.duration = (200 * Math.abs(0f - pressProgress)).toLong()
animator.start()
pressAnimator = animator
}
private fun animatingTo(target: Float) {
post {
this.animator?.cancel()
val animator = ValueAnimator.ofFloat(progress, target)
animator.addUpdateListener {
val value = it.animatedValue as Float
updateProgress(value)
}
animator.duration = (200 * abs(target - progress)).toLong()
animator.start()
this.animator = animator
}
}
fun setChecked(isChecked: Boolean, animated: Boolean) {
if (animated) {
this.isChecked = isChecked
} else {
updateProgress(if (isChecked) 1f else 0f)
this.isChecked = isChecked
}
}
fun setOnCheckedChangeListener(listener: OnCheckedChangeListener?) {
this.onCheckedChangeListener = listener
}
interface OnCheckedChangeListener {
fun onCheckedChange(switch: StyledSwitch, isChecked: Boolean)
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent.impl
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.AudioRecord.getMinBufferSize
import android.os.Build
import com.iflytek.cyber.evs.sdk.agent.Recognizer
class RecognizerImpl : Recognizer() {
private var recorder: AudioRecord? = null
init {
}
private fun createAudioRecord() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
AudioRecord.Builder()
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(getAudioFormatEncoding())
.setSampleRate(getSampleRateInHz())
.setChannelMask(getAudioChannel())
.build()
)
.setAudioSource(getAudioSource())
.setBufferSizeInBytes(
getMinBufferSize(
getSampleRateInHz(),
getAudioChannel(),
getAudioFormatEncoding()
)
)
.build()
} else {
AudioRecord(
getAudioSource(),
getSampleRateInHz(),
getAudioChannel(),
getAudioFormatEncoding(),
getMinBufferSize(
getSampleRateInHz(),
getAudioChannel(),
getAudioFormatEncoding()
)
)
}
override fun readBytes(byteArray: ByteArray, length: Int): Int {
if (recorder?.recordingState == AudioRecord.RECORDSTATE_RECORDING) {
return recorder?.read(byteArray, 0, length) ?: -1
}
return -1
}
override fun startRecording() {
if (recorder == null) {
recorder = createAudioRecord()
}
recorder?.startRecording()
}
override fun stopRecording() {
recorder?.stop()
recorder = null
}
override fun isRecording(): Boolean {
return recorder?.recordingState == AudioRecord.RECORDSTATE_RECORDING
}
override fun onDestroy() {
super.onDestroy()
try {
recorder?.release()
} catch (e: Exception) {
}
}
}<file_sep>package com.iflytek.cyber.evs.sdk.codec.audio.speex
import com.iflytek.cyber.evs.sdk.codec.audio.AudioCodec
import com.iflytek.cyber.evs.sdk.utils.Log
/**
* Speex编解码类。
*
* 构造函数。
* @param codec 指定编码还是解码,取值:CODEC_ENCODE,CODEC_DECODE
* @param sampleRate 采样率
* @param quality 质量,取值:1-10
*/
class SpeexCodec(codec: Int, sampleRate: Int, mode: Int, quality: Int): AudioCodec(codec) {
companion object {
const val TAG = "SpeexCodec"
const val MODE_NB = 1 // 8bit编码
const val MODE_WB = 2 // 16bit编码
}
init {
System.loadLibrary("speex")
this.sampleRate = sampleRate
this.mode = mode
this.quality = quality
val ret = init_native(codeMode, sampleRate, mode, quality)
if (ret != 0) {
Log.d(TAG, "init failed")
}
}
private var handle_state: ByteArray? = null
private var handle_speex_bits: ByteArray? = null
private fun setHandles(state: ByteArray?, bits: ByteArray?) {
handle_state = state
handle_speex_bits = bits
}
/**
* 初始化本地对象。
* @param codec 编码还是解码器
* @param sampleRate 采样率
* @param mode 模式,取值:MODE_NB,MODE_WB
* @param quality 质量,取值:1-10
* @return 成功返回0,失败返回-1
*/
private external fun init_native(codec: Int, sampleRate: Int, mode: Int, quality: Int): Int
/**
* 编码。
* @param state native指针
* @param speex_bits native指针
* @param data 原始数据
* @param dataLen 原始数据长度
* @param buffer 编码缓存
* @param bufferLen 缓存长度
* @return 编码数据长度,-1表示失败
*/
private external fun encode_native(state: ByteArray?, speex_bits: ByteArray?, data: ByteArray, dataLen: Int,
buffer: ByteArray, bufferLen: Int): Int
/**
* 解码。
* @param state native指针
* @param speex_bits native指针
* @param data 已编码数据
* @param dataLen 数据长度
* @param buffer 解码缓存
* @param bufferLen 缓存长度
* @param mode 模式,取值:MODE_NB,MODE_WB
* @param quality 压缩质量
* @return 解码数据长度,-1表示失败
*/
private external fun decode_native(state: ByteArray?, speex_bits: ByteArray?, data: ByteArray, dataLen: Int,
buffer: ByteArray, bufferLen: Int, mode: Int, quality: Int): Int
/**
* 销毁本地对象。
* @param codec 编码还是解码器
* @param handle_state state指针
* @param handle_speex_bits speex_bits指针
*/
private external fun destroy_native(codec: Int, handle_state: ByteArray?, handle_speex_bits: ByteArray?)
/**
* 编码。
* @param data 原始音频
* @param dataLen 音频长度,必须为20ms音频长度的整数倍
* @param buffer 编码缓存区
* @param bufferLen 缓存区长度
* @return 编码后的长度,负值表示出错
*/
override fun encode(data: ByteArray, dataLen: Int, buffer: ByteArray, bufferLen: Int): Int {
if (isDecoder()) {
Log.e(TAG, "decoder cannot be used to encode")
return -1
}
if (handle_state == null) {
Log.e(TAG, "not inited or destroyed")
return -1
}
val ret = encode_native(handle_state, handle_speex_bits, data, dataLen, buffer, bufferLen)
if (ret < 0) {
Log.e(TAG, "encode error, ret=$ret")
}
return ret
}
/**
* 解码。
* @param data speex音频
* @param dataLen 音频长度
* @param buffer 解码缓存区
* @param bufferLen 缓存区长度
* @return 解后的长度,负值表示出错
*/
override fun decode(data: ByteArray, dataLen: Int, buffer: ByteArray, bufferLen: Int): Int {
if (isEncoder()) {
Log.e(TAG, "encoder cannot be used to decode")
return -1
}
if (handle_state == null) {
Log.e(TAG, "not inited or destroyed")
return -1
}
val ret = decode_native(handle_state, handle_speex_bits, data, dataLen, buffer, bufferLen, mode, quality)
if (ret < 0) {
Log.e(TAG, "decode error, ret=$ret")
}
return ret
}
override fun destroy() {
if (handle_state != null) {
destroy_native(codeMode, handle_state, handle_speex_bits)
handle_state = null
handle_speex_bits = null
}
}
protected fun finalize() {
destroy()
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent.impl
import com.alibaba.fastjson.JSONObject
import com.iflytek.cyber.evs.sdk.agent.System
class SystemImpl : System() {
override fun checkSoftWareUpdate() {
}
override fun onPing(timestamp: Long) {
}
override fun onError(payload: JSONObject) {
super.onError(payload)
}
override fun updateSoftware() {
}
override fun onDeviceModeChanged(kid: Boolean) {
}
override fun onPowerOff(payload: JSONObject) {
}
override fun onUpdateDeviceModes(payload: JSONObject) {
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.os.bundleOf
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.clickWithTrigger
class SpeakTypeEvaluationFragment : BaseFragment() {
companion object {
fun newInstance(type: Int): SpeakTypeEvaluationFragment {
return SpeakTypeEvaluationFragment().apply {
arguments = bundleOf(Pair("type", type))
}
}
}
private lateinit var wordType: FrameLayout
private lateinit var wordsType: FrameLayout
private lateinit var sentenceType: FrameLayout
private lateinit var tvWord: TextView
private lateinit var tvWords: TextView
private lateinit var tvSentence: TextView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_speak_type, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
wordType = view.findViewById(R.id.word_type)
wordsType = view.findViewById(R.id.words_type)
sentenceType = view.findViewById(R.id.sentence_type)
tvWord = view.findViewById(R.id.tv_word)
tvWords = view.findViewById(R.id.tv_words)
tvSentence = view.findViewById(R.id.tv_sentence)
view.findViewById<View>(R.id.back).clickWithTrigger {
pop()
}
val wordsImageView = view.findViewById<ImageView>(R.id.words_img)
val sentenceImageView = view.findViewById<ImageView>(R.id.sentence_img)
val type = arguments?.getInt("type", -1)
if (type == 0) {
wordType.setBackgroundResource(R.drawable.bg_orange_round_42dp)
wordsType.setBackgroundResource(R.drawable.bg_green_round_42dp)
sentenceType.setBackgroundResource(R.drawable.bg_blue_round_42dp)
wordsImageView.setBackgroundResource(R.drawable.ic_ciyu_48)
sentenceImageView.setBackgroundResource(R.drawable.ic_juzi_48)
tvWord.setText(R.string.word_evaluation)
tvWords.setText(R.string.words_evaluation)
tvSentence.setText(R.string.short_sentence_evaluation)
} else if (type == 1) {
wordType.setBackgroundResource(R.drawable.bg_blue_round_42dp)
wordsType.setBackgroundResource(R.drawable.bg_green_round_42dp)
sentenceType.setBackgroundResource(R.drawable.bg_orange_round_42dp)
wordsImageView.setBackgroundResource(R.drawable.ic_juzi_48)
sentenceImageView.setBackgroundResource(R.drawable.ic_wenzhang_48)
tvWord.setText(R.string.english_word_evaluation)
tvWords.setText(R.string.short_sentence_evaluation)
tvSentence.setText(R.string.article_evaluation)
}
view.findViewById<View>(R.id.word_type).clickWithTrigger {
if (type == 0) {
start(SpeakEvaluatingFragment.newInstance(SpeakEvaluatingFragment.CHINESE_SINGLE_WORD_TYPE))
} else {
start(SpeakEvaluatingFragment.newInstance(SpeakEvaluatingFragment.ENGLISH_WORD_TYPE))
}
}
view.findViewById<View>(R.id.words_type).clickWithTrigger {
if (type == 0) {
start(SpeakEvaluatingFragment.newInstance(SpeakEvaluatingFragment.CHINESE_WORDS_TYPE))
} else {
start(SpeakEvaluatingFragment.newInstance(SpeakEvaluatingFragment.ENGLISH_SENTENCE_TYPE))
}
}
view.findViewById<View>(R.id.sentence_type).clickWithTrigger {
if (type == 0) {
start(SpeakEvaluatingFragment.newInstance(SpeakEvaluatingFragment.CHINESE_SENTENCE_TYPE))
} else {
start(SpeakEvaluatingFragment.newInstance(SpeakEvaluatingFragment.ENGLISH_ARTICLE_TYPE))
}
}
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.model
import com.google.gson.annotations.SerializedName
class Content {
var title: String? = null
var titleSubtext1: String? = null
var titleSubtext2: String? = null
var header: String? = null
var headerSubtext1: String? = null
var mediaLengthInMilliseconds: String? = null
var art: Image? = null
var provider: Provider? = null
@SerializedName("secondary_text")
var musicArtist: String? = null
@SerializedName("primary_text")
var musicTitle: String? = null
@SerializedName("image_url")
var imageUrl: String? = null
override fun toString(): String {
return "Content(text=$title, titleSubtext1=$titleSubtext1, titleSubtext2=$titleSubtext2, header=$header, headerSubtext1=$headerSubtext1, mediaLengthInMilliseconds=$mediaLengthInMilliseconds, art=$art, provider=$provider, musicArtist=$musicArtist, musicTitle=$musicTitle, imageUrl=$imageUrl)"
}
}
class Provider {
var name: String? = null
var logo: String? = null
@SerializedName("logo_url") var logoUrl: String? = null
override fun toString(): String {
return "Provider{" +
"name='" + name + '\''.toString() +
", logo=" + logo +
'}'.toString()
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.accessibility
import android.accessibilityservice.AccessibilityService
import android.view.accessibility.AccessibilityEvent
import com.iflytek.cyber.iot.show.core.utils.VoiceButtonUtils
class TouchAccessibility : AccessibilityService() {
companion object {
var isMainFragment = false
var isBodyTemplate = false
val isIgnoreTouchEvent: Boolean
get() = isMainFragment || isBodyTemplate
}
override fun onInterrupt() {
}
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
if (isIgnoreTouchEvent) {
return
}
VoiceButtonUtils.lastTouchTime = System.currentTimeMillis()
// SleepWorker.get(this).doTouchWork(this)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.iflytek.cyber.evs.sdk.auth.AuthDelegate
import com.iflytek.cyber.iot.show.core.BuildConfig
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.DeviceUtils
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.logging.HttpLoggingInterceptor
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
class MessageBoardFragment : BaseFragment() {
companion object {
private const val TAG = "MessageBoard"
}
private val client: OkHttpClient
private val adapter = ListAdapter()
private var recyclerView: RecyclerView? = null
private var messagesData: MessagesData? = null
private var backCount = 0
init {
val logger = HttpLoggingInterceptor()
logger.level = HttpLoggingInterceptor.Level.BODY
client = OkHttpClient.Builder()
.addInterceptor(logger)
.build()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_message_board, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back)?.setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
recyclerView = view.findViewById(R.id.message_list)
recyclerView?.adapter = adapter
post {
getBoardDetail()
requestMessageBoard()
}
}
private fun requestMessageBoard() {
val context = context ?: return
Thread {
val deviceId = DeviceUtils.getDeviceId(context)
val clientId = BuildConfig.CLIENT_ID
val authResponse = AuthDelegate.getAuthResponseFromPref(context)
val request = Request.Builder()
.url("https://staging-home.iflyos.cn/web/message_boards/42/messages?deviceId=$deviceId&clientId=$clientId")
.addHeader("Authorization", "Bearer ${authResponse?.accessToken}")
.get()
.build()
val response = client.newCall(request).execute()
if (response.isSuccessful) {
val body = response.body()?.string()
val messagesData = Gson().fromJson<MessagesData>(body, MessagesData::class.java)
this.messagesData = messagesData
} else {
}
post {
adapter.notifyDataSetChanged()
markAsRead()
}
}.start()
}
private fun getBoardDetail() {
val context = context ?: return
Thread {
val deviceId = DeviceUtils.getDeviceId(context)
val clientId = BuildConfig.CLIENT_ID
val authResponse = AuthDelegate.getAuthResponseFromPref(context)
val request = Request.Builder()
.url("https://staging-home.iflyos.cn/web/message_boards/42?deviceId=$deviceId&clientId=$clientId")
.addHeader("Authorization", "Bearer ${authResponse?.accessToken}")
.put(RequestBody.create(MediaType.get("application/json"), "{}"))
.build()
val response = client.newCall(request).execute()
if (response.isSuccessful) {
}
}.start()
}
private fun markAsRead() {
val context = context ?: return
Thread {
val deviceId = DeviceUtils.getDeviceId(context)
val clientId = BuildConfig.CLIENT_ID
val authResponse = AuthDelegate.getAuthResponseFromPref(context)
val request = Request.Builder()
.url("https://staging-home.iflyos.cn/web/message_boards/42/messages/mark_read?deviceId=$deviceId&clientId=$clientId")
.addHeader("Authorization", "Bearer ${authResponse?.accessToken}")
.put(RequestBody.create(MediaType.get("application/json"), "{}"))
.build()
val response = client.newCall(request).execute()
if (response.isSuccessful) {
}
}.start()
}
private inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val viewTypeSystem = 0
private val viewTypeMessage = 1
private val viewTypeRecord = 2
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
when (viewType) {
viewTypeSystem -> {
return SystemViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_message, parent, false))
}
viewTypeMessage -> {
return MessageViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_message, parent, false))
}
viewTypeRecord -> {
return RecordViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_message, parent, false))
}
}
return SystemViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_message, parent, false))
}
override fun getItemViewType(position: Int): Int {
messagesData?.data?.get(position)?.let {
when (it.msgType) {
0 -> {
return viewTypeSystem
}
1 -> {
return viewTypeMessage
}
2 -> {
return viewTypeRecord
}
else -> {
// ignore
}
}
}
return super.getItemViewType(position)
}
override fun getItemCount(): Int {
return messagesData?.data?.size ?: 0
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
messagesData?.data?.get(position)?.let { message ->
when (holder) {
is MessageViewHolder -> {
val time = message.createTime ?: 0
val shouldShowTime =
if (position > 0) {
messagesData?.data?.get(Math.max(0, position - 1))?.let { preMessage ->
val preTime = preMessage.createTime ?: 0
time - preTime > TimeUnit.MINUTES.toMillis(5)
} ?: true
} else {
true
}
if (shouldShowTime) {
holder.tvTime?.visibility = View.VISIBLE
val nowDate = Calendar.getInstance()
val now = nowDate.timeInMillis
val timeDate = Calendar.getInstance()
timeDate.timeInMillis = time
if (nowDate.get(Calendar.DATE) - 1 == timeDate.get(Calendar.DATE)) {
holder.tvTime?.text = SimpleDateFormat("昨天 HH:mm", Locale.getDefault()).format(timeDate.time)
} else if (now - time < TimeUnit.DAYS.toMicros(7) &&
nowDate.get(Calendar.DATE) - 1 > timeDate.get(Calendar.DATE)) {
val weekday = when (timeDate.get(Calendar.DAY_OF_WEEK)) {
Calendar.SUNDAY -> "星期天"
Calendar.MONDAY -> "星期一"
Calendar.TUESDAY -> "星期二"
Calendar.WEDNESDAY -> "星期三"
Calendar.THURSDAY -> "星期四"
Calendar.FRIDAY -> "星期五"
Calendar.SATURDAY -> "星期六"
else -> ""
}
holder.tvTime?.text = SimpleDateFormat("$weekday HH:mm", Locale.getDefault()).format(timeDate.time)
} else {
holder.tvTime?.text = SimpleDateFormat("HH:mm", Locale.getDefault()).format(timeDate.time)
}
} else {
holder.tvTime?.visibility = View.GONE
}
holder.tvMessage?.text = message.msg
if (message.isOwner == true) {
holder.ivAvatar?.visibility = View.GONE
(holder.messageArea?.layoutParams as? FrameLayout.LayoutParams)?.let {
if (it.gravity != Gravity.CENTER_VERTICAL or Gravity.END) {
it.gravity = Gravity.CENTER_VERTICAL or Gravity.END
holder.messageArea.layoutParams = it
}
}
} else {
holder.ivAvatar?.let { avatar ->
avatar.visibility = View.VISIBLE
Glide.with(avatar)
.asDrawable()
.apply(RequestOptions
.placeholderOf(R.drawable.cover_default)
.transform(RoundedCornersTransformation(avatar.width / 4, 0)))
.load(message.profilePicture)
.into(avatar)
}
(holder.messageArea?.layoutParams as? FrameLayout.LayoutParams)?.let {
if (it.gravity != Gravity.CENTER_VERTICAL) {
it.gravity = Gravity.CENTER_VERTICAL
holder.messageArea.layoutParams = it
}
}
}
}
is SystemViewHolder -> {
val time = message.createTime ?: 0
val shouldShowTime =
if (position > 0) {
messagesData?.data?.get(Math.max(0, position - 1))?.let { preMessage ->
val preTime = preMessage.createTime ?: 0
time - preTime > TimeUnit.MINUTES.toMillis(5)
} ?: true
} else {
true
}
if (shouldShowTime) {
holder.tvTime?.visibility = View.VISIBLE
val nowDate = Calendar.getInstance()
val now = nowDate.timeInMillis
val timeDate = Calendar.getInstance()
timeDate.timeInMillis = time
if (nowDate.get(Calendar.DATE) - 1 == timeDate.get(Calendar.DATE)) {
holder.tvTime?.text = SimpleDateFormat("昨天 HH:mm", Locale.getDefault()).format(timeDate.time)
} else if (now - time < TimeUnit.DAYS.toMicros(7) &&
nowDate.get(Calendar.DATE) - 1 > timeDate.get(Calendar.DATE)) {
val weekday = when (timeDate.get(Calendar.DAY_OF_WEEK)) {
Calendar.SUNDAY -> "星期天"
Calendar.MONDAY -> "星期一"
Calendar.TUESDAY -> "星期二"
Calendar.WEDNESDAY -> "星期三"
Calendar.THURSDAY -> "星期四"
Calendar.FRIDAY -> "星期五"
Calendar.SATURDAY -> "星期六"
else -> ""
}
holder.tvTime?.text = SimpleDateFormat("$weekday HH:mm", Locale.getDefault()).format(timeDate.time)
} else {
holder.tvTime?.text = SimpleDateFormat("HH:mm", Locale.getDefault()).format(timeDate.time)
}
} else {
holder.tvTime?.visibility = View.GONE
}
holder.tvMessage?.text = message.msg
}
is RecordViewHolder -> {
val time = message.createTime ?: 0
val shouldShowTime =
if (position > 0) {
messagesData?.data?.get(Math.max(0, position - 1))?.let { preMessage ->
val preTime = preMessage.createTime ?: 0
time - preTime > TimeUnit.MINUTES.toMillis(5)
} ?: true
} else {
true
}
if (shouldShowTime) {
holder.tvTime?.visibility = View.VISIBLE
val nowDate = Calendar.getInstance()
val now = nowDate.timeInMillis
val timeDate = Calendar.getInstance()
timeDate.timeInMillis = time
if (nowDate.get(Calendar.DATE) - 1 == timeDate.get(Calendar.DATE)) {
holder.tvTime?.text = SimpleDateFormat("昨天 HH:mm", Locale.getDefault()).format(timeDate.time)
} else if (now - time < TimeUnit.DAYS.toMicros(7) &&
nowDate.get(Calendar.DATE) - 1 > timeDate.get(Calendar.DATE)) {
val weekday = when (timeDate.get(Calendar.DAY_OF_WEEK)) {
Calendar.SUNDAY -> "星期天"
Calendar.MONDAY -> "星期一"
Calendar.TUESDAY -> "星期二"
Calendar.WEDNESDAY -> "星期三"
Calendar.THURSDAY -> "星期四"
Calendar.FRIDAY -> "星期五"
Calendar.SATURDAY -> "星期六"
else -> ""
}
holder.tvTime?.text = SimpleDateFormat("$weekday HH:mm", Locale.getDefault()).format(timeDate.time)
} else {
holder.tvTime?.text = SimpleDateFormat("HH:mm", Locale.getDefault()).format(timeDate.time)
}
} else {
holder.tvTime?.visibility = View.GONE
}
if (message.isOwner == true) {
holder.ivAvatar?.visibility = View.GONE
(holder.messageArea?.layoutParams as? FrameLayout.LayoutParams)?.let {
if (it.gravity != Gravity.CENTER_VERTICAL or Gravity.END) {
it.gravity = Gravity.CENTER_VERTICAL or Gravity.END
holder.messageArea.layoutParams = it
}
}
} else {
holder.ivAvatar?.let { avatar ->
avatar.visibility = View.VISIBLE
Glide.with(avatar)
.asDrawable()
.apply(RequestOptions
.placeholderOf(R.drawable.cover_default)
.transform(RoundedCornersTransformation(avatar.width / 4, 0)))
.load(message.profilePicture)
.into(avatar)
}
(holder.messageArea?.layoutParams as? FrameLayout.LayoutParams)?.let {
if (it.gravity != Gravity.CENTER_VERTICAL) {
it.gravity = Gravity.CENTER_VERTICAL
holder.messageArea.layoutParams = it
}
}
}
}
else -> {
}
}
}
}
}
private class MessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvMessage: TextView? = itemView.findViewById(R.id.message)
val messageArea: View? = itemView.findViewById(R.id.message_area)
val ivAvatar: ImageView? = itemView.findViewById(R.id.avatar)
val tvTime: TextView? = itemView.findViewById(R.id.time)
}
private class SystemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvMessage: TextView? = itemView.findViewById(R.id.message)
val tvTime: TextView? = itemView.findViewById(R.id.time)
}
private class RecordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val messageArea: View? = itemView.findViewById(R.id.message_area)
val ivAvatar: ImageView? = itemView.findViewById(R.id.avatar)
val tvTime: TextView? = itemView.findViewById(R.id.time)
}
data class MessageBoard(
@SerializedName("text") val title: String?,
@SerializedName("ownerUserId") val ownerUserId: String?,
@SerializedName("icon") val icon: String?,
@SerializedName("createtime") val createtime: String?
)
data class MessagesData(
val code: Int?,
val data: List<MessageItem>?,
val desc: String?,
val flag: Boolean?
)
data class MessageItem(
@SerializedName("client_id") val clientId: String?,
@SerializedName("createtime") val createTime: Long?,
@SerializedName("device_id") val deviceId: String?,
@SerializedName("id") val id: String?,
@SerializedName("isOwner") val isOwner: Boolean?,
@SerializedName("length") val length: Int?,
@SerializedName("memberType") val memberType: Int?,
@SerializedName("msg") val msg: String?,
@SerializedName("msgType") val msgType: Int?,
@SerializedName("profilePicture") val profilePicture: String?,
@SerializedName("user_id") val userId: String?,
@SerializedName("voiceUrl") val voiceUrl: String?
)
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.ItemViewBinder
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.MainTemplate
class MainLoadingBinder : ItemViewBinder<MainTemplate, MainLoadingBinder.MainLoadingHolder>() {
override fun onBindViewHolder(holder: MainLoadingHolder, item: MainTemplate) {
}
override fun onCreateViewHolder(
inflater: LayoutInflater,
parent: ViewGroup
): MainLoadingHolder {
val view = inflater.inflate(R.layout.item_main_loading, parent, false)
return MainLoadingHolder(view)
}
inner class MainLoadingHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.ItemViewBinder
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.Result
import com.iflytek.cyber.iot.show.core.model.SearchResult
class VideoTypeViewBinder(
val onItemClick: (Result) -> Unit,
val onMoreClick: (ArrayList<Result>) -> Unit
) : ItemViewBinder<SearchResult, VideoTypeViewBinder.VideoTypeHolder>() {
private var keyword = ""
fun setKeyword(keyword: String) {
this.keyword = keyword
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): VideoTypeHolder {
val view = inflater.inflate(R.layout.item_category, parent, false)
return VideoTypeHolder(view)
}
override fun onBindViewHolder(holder: VideoTypeHolder, item: SearchResult) {
holder.title.text = "视频"
holder.more.text = "查看更多"
val newItems = if (item.results != null && item.results.size > 4) {
item.results.subList(0, 4)
} else {
item.results
}
holder.moreContent.isVisible = newItems?.size ?: 0 >= 4
holder.setList(newItems)
holder.moreContent.setOnClickListener {
if (item.results != null) {
onMoreClick.invoke(item.results)
}
}
}
inner class VideoTypeHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val title = itemView.findViewById<TextView>(R.id.category_title)
val albumList = itemView.findViewById<RecyclerView>(R.id.album_list)
val more = itemView.findViewById<TextView>(R.id.more)
val moreContent = itemView.findViewById<LinearLayout>(R.id.more_content)
val adapter = VideoSearchResultAdapter {
onItemClick.invoke(it)
}
fun setList(results: List<Result>?) {
if (results != null) {
adapter.showLoading(false)
adapter.setResults(keyword, results)
albumList.adapter = adapter
}
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.impl.recognizer
import android.content.Context
import com.iflytek.cyber.evs.sdk.agent.Recognizer
import com.iflytek.cyber.iot.show.core.record.GlobalRecorder
import com.iflytek.cyber.iot.show.core.utils.ConfigUtils
import okio.BufferedSink
import okio.BufferedSource
import okio.Pipe
import okio.buffer
import java.io.InterruptedIOException
import java.lang.ref.SoftReference
class EvsRecognizer(context: Context) : Recognizer(), GlobalRecorder.Observer {
private var sink: BufferedSink? = null
private var source: BufferedSource? = null
private var isCapturing = false
private val contextRef = SoftReference(context)
private var onEvaluateResultCallback: OnEvaluateResultCallback? = null
fun registerEvaluateResultCallback(onEvaluateResultCallback: OnEvaluateResultCallback) {
this.onEvaluateResultCallback = onEvaluateResultCallback
}
init {
GlobalRecorder.registerObserver(this)
profile =
when (ConfigUtils.getString(ConfigUtils.KEY_RECOGNIZER_PROFILE, null)) {
Profile.CloseTalk.toString() -> {
Profile.CloseTalk
}
else -> {
Profile.FarField
}
}
val pipe = Pipe(2 * 1024 * 1024)
sink = pipe.sink.buffer()
source = pipe.source.buffer()
}
override fun onAudioData(array: ByteArray, offset: Int, length: Int) {
if (length > 0 && isCapturing)
sink?.write(array, offset, length)
}
override fun onWakeUp(angle: Int, beam: Int, params: String?) {
// ignore
}
override fun readBytes(byteArray: ByteArray, length: Int): Int {
try {
val data = source?.readByteArray(length.toLong())
if (data?.isNotEmpty() == true) {
for (i in data.indices) {
byteArray[i] = data[i]
}
return data.size
}
} catch (e: InterruptedIOException) {
// ignore
}
return -1
}
override fun startRecording() {
isCapturing = true
}
override fun stopRecording() {
isCapturing = false
}
override fun isRecording(): Boolean {
return isCapturing
}
override fun isSupportBackgroundRecognize(): Boolean {
return ConfigUtils.getBoolean(ConfigUtils.KEY_BACKGROUND_RECOGNIZE, false)
}
override fun onDestroy() {
super.onDestroy()
try {
sink?.close()
} catch (e: Exception) {
e.printStackTrace()
} finally {
sink = null
source = null
}
}
override fun onEvaluateResult(payload: String) {
super.onEvaluateResult(payload)
try {
onEvaluateResultCallback?.onEvaluateResult(payload)
} catch (e: Exception) {
e.printStackTrace()
}
}
interface OnEvaluateResultCallback {
fun onEvaluateResult(payload: String)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.animation.ValueAnimator
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.util.Log
import androidx.appcompat.widget.AppCompatTextView
import com.google.gson.Gson
import com.iflytek.cyber.iot.show.core.model.WakeWord
import com.iflytek.cyber.iot.show.core.utils.ConfigUtils
class BannerDescTextView(context: Context?, attrs: AttributeSet?) : AppCompatTextView(context, attrs) {
private var descriptions = ArrayList<String>()
private val timeHandler = Handler()
private var currentSummary = 0
fun setDescs(desc: ArrayList<String>?) {
if (desc == null) {
return
}
val newDesc = ArrayList<String>()
desc.forEach {
val newText = parseDescription(it)
newDesc.add(newText)
}
this.descriptions.clear()
this.descriptions.addAll(newDesc)
}
fun setDescText(text: String?) {
val desc = if (!text.isNullOrEmpty()) {
parseDescription(text)
} else {
text
}
setText(desc)
postNextUpdateSummary()
}
fun stopScroll() {
timeHandler.removeCallbacksAndMessages(null)
}
private val updateSummaryRunnable: Runnable = Runnable {
if(descriptions.isNotEmpty() && descriptions.size > 1) {
val next = (currentSummary + 1) % descriptions.size
currentSummary = next
startUpdateSummaryAnimator(descriptions[next])
postNextUpdateSummary()
}
}
private fun postNextUpdateSummary() {
timeHandler.removeCallbacksAndMessages(null)
timeHandler.postDelayed(updateSummaryRunnable, 6 * 1000)
}
private fun startUpdateSummaryAnimator(newText: String) {
val animator = ValueAnimator.ofFloat(0f, 2f)
animator.addUpdateListener {
val value = it.animatedValue as Float
if (value > 1) {
if (this.text.toString() != newText) {
val name = parseDescription(newText)
this.text = name
}
this.alpha = value - 1
} else {
this.alpha = 1 - value
}
}
animator.duration = 600
animator.start()
}
private fun parseDescription(description: String): String {
try {
val cacheWakeWord = ConfigUtils.getString(ConfigUtils.KEY_CACHE_WAKE_WORD, null)
if (!cacheWakeWord.isNullOrEmpty()) {
val wakeWord = Gson().fromJson(cacheWakeWord, WakeWord::class.java)
if (wakeWord?.name?.isEmpty() == false) {
return description.replace(
"蓝小飞",
wakeWord.name,
false
)
}
}
} catch (t: Throwable) {
}
return description
}
}<file_sep>//
// Created by huang on 2019/1/24.
//
#ifndef __IVWENGINE_H__
#define __IVWENGINE_H__
#include "libivw_defines.h"
#if defined(_MSC_VER)
#if !defined(IVWAPI)
#define IVWAPI _cdecl
#endif
#pragma pack(push, 8)
#else
#if !defined(IVWAPI)
//#define IVWAPI __attribute__((visibility("default")))
#define IVWAPI
#endif
#endif
typedef void* IVW_INSTHANDLE;
typedef struct tagIVW_RES_SET
{
int nResId;
char strType[16];
} IVW_RES_SET;
enum IVW_RES_LOCATION
{
IVW_RES_LOCATION_FILE = 0,
IVW_RES_LOCATION_MEM = 1,
IVW_RES_LOCATION_NONE
};
typedef int (*PWIVWAPIWRAPCallBack)(void* pUserParam, const char* pIvwParam);
struct IVWEngineFace
{
virtual int IvwInit(const char* pEngine, void* pReserved) = 0;
virtual int IvwFini() = 0;
virtual int IvwLoadResource(char* pRes, int nResSize, int bResFlag) = 0;
virtual int IvwCreateInst(IVW_INSTHANDLE* ppIvwInst) = 0;
virtual int IvwDestroyInst(IVW_INSTHANDLE pIvwInst) = 0;
virtual int IvwGetInstParam(IVW_INSTHANDLE pIvwInst, int nParamType, void* nParamValue, int* nParamSize) = 0;
virtual int IvwSetInstParam(IVW_INSTHANDLE pIvwInst, int nParamType, void* nParamValue, int nParamSize) = 0;
virtual int IvwStartInst(IVW_INSTHANDLE pIvwInst) = 0;
virtual int IvwWriteInst(IVW_INSTHANDLE pIvwInst, char* pBuf, int nBufSize) = 0;
virtual int IvwStopInst(IVW_INSTHANDLE pIvwInst) = 0;
virtual int IvwGetVersion(char* pIvwVersion, int* nVerLen) = 0;
};
typedef IVWEngineFace* PIVWEngineFace;
#ifdef __cplusplus
extern "C" {
#endif
int IVWAPI CreateIVWEngine(void* pParam, PIVWEngineFace* ppEngineFace);
typedef int (IVWAPI* Proc_CreateIVWEngine)(void* pParam, PIVWEngineFace* ppEngineFace);
int IVWAPI DestroyIVWEngine(PIVWEngineFace pEngineFace);
typedef int (IVWAPI* Proc_DestroyIVWEngine)(PIVWEngineFace pEngineFace);
#ifdef __cplusplus
};
#endif
#endif //__IVWENGINE_H__
<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.airbnb.lottie.LottieAnimationView
import com.alibaba.fastjson.JSON
import com.bumptech.glide.Glide
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.AppApi
import com.iflytek.cyber.iot.show.core.model.TemplateApp
import com.iflytek.cyber.iot.show.core.model.XmlyAlbumItem
import com.iflytek.cyber.iot.show.core.model.XmlyCategoryItem
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.widget.GradientTextView
import com.iflytek.cyber.iot.show.core.widget.StyledProgressDialog
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
import kotlin.math.abs
class TemplateAppXmlyFragment : BaseFragment(), PageScrollable {
companion object {
private const val TAG = "TemplateAppXmlyFragment"
fun newInstance(templateApp: TemplateApp): TemplateAppXmlyFragment {
val fragment = TemplateAppXmlyFragment()
fragment.templateApp = templateApp
return fragment
}
}
private var templateApp: TemplateApp? = null
private var ivBack: ImageView? = null
private var ivIcon: ImageView? = null
private var ivBackground: ImageView? = null
private var tabLayout: RecyclerView? = null
private var recyclerView: RecyclerView? = null
private var viewPager: ViewPager2? = null
private var errorContainer: View? = null
private var tvError: TextView? = null
private var errorRetry: View? = null
private var tvRetry: TextView? = null
private var loadingContainer: FrameLayout? = null
private var loadingImageView: LottieAnimationView? = null
private val tabAdapter = TabAdapter()
private var pagerAdapter: SectionContentAdapter? = null
//private var progressDialog: StyledProgressDialog? = null
private var clickCount = 0
private val tabScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
(recyclerView.layoutManager as? LinearLayoutManager)?.let { linearLayoutManager ->
val lastComplete = linearLayoutManager.findLastCompletelyVisibleItemPosition()
val lastVisible = linearLayoutManager.findLastVisibleItemPosition()
if (lastComplete == lastComplete
&& linearLayoutManager.findFirstCompletelyVisibleItemPosition()
== linearLayoutManager.findFirstVisibleItemPosition()
&& tabAdapter.itemCount == lastComplete + 1
)
return@let
val targetViewSet = mutableSetOf<View>()
var lastViewWidth = 0
recyclerView.findViewHolderForAdapterPosition(lastVisible)?.let { holder ->
if (holder is TabViewHolder) {
val itemView = holder.itemView
val offset = itemView.width - itemView.right + recyclerView.width
holder.tvTitle?.let { gradientTextView ->
if (!gradientTextView.isGradient)
gradientTextView.isGradient = true
gradientTextView.startColor =
Color.argb(
255 * offset / itemView.width,
255,
255,
255
)
if (recyclerView.adapter?.itemCount == lastVisible + 1) {
gradientTextView.endColor =
Color.argb(
255 * offset / itemView.width,
255,
255,
255
)
} else {
if (gradientTextView.endColor != Color.TRANSPARENT)
gradientTextView.endColor =
Color.TRANSPARENT
}
}
lastViewWidth = itemView.width
targetViewSet.add(itemView)
}
}
if (lastComplete != lastVisible) {
recyclerView.findViewHolderForAdapterPosition(lastComplete)?.let { holder ->
if (holder is TabViewHolder) {
val itemView = holder.itemView
val offset =
lastViewWidth - (itemView.right + lastViewWidth - recyclerView.width)
holder.tvTitle?.let { gradientTextView ->
if (!gradientTextView.isGradient)
gradientTextView.isGradient = true
if (gradientTextView.startColor != Color.WHITE)
gradientTextView.startColor = Color.WHITE
gradientTextView.endColor =
Color.argb(
255 * offset / lastViewWidth,
255,
255,
255
)
}
targetViewSet.add(itemView)
}
}
}
// 从后往前遍历
for (i in 0 until recyclerView.childCount) {
val child = recyclerView.getChildAt(recyclerView.childCount - 1 - i)
if (child !in targetViewSet) {
(recyclerView.getChildViewHolder(child) as? TabViewHolder)?.let {
it.tvTitle?.isGradient = false
}
}
}
}
}
}
private val onPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
val oldPosition = tabAdapter.selectedItem
tabAdapter.selectedItem = position
tabAdapter.notifyItemChanged(oldPosition)
tabAdapter.notifyItemChanged(position)
if (position < tabAdapter.itemCount)
tabLayout?.smoothScrollToPosition(position)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_template_app_xmly, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back)?.setOnClickListener {
if (clickCount != 0)
return@setOnClickListener
clickCount++
pop()
}
ivBack = view.findViewById(R.id.iv_back)
ivIcon = view.findViewById(R.id.iv_icon)
ivBackground = view.findViewById(R.id.background)
tabLayout = view.findViewById(R.id.tab_layout)
viewPager = view.findViewById(R.id.view_pager)
recyclerView = view.findViewById(R.id.recycler_view)
tvRetry = view.findViewById(R.id.tv_retry)
errorRetry = view.findViewById(R.id.error_retry)
tvError = view.findViewById(R.id.tv_error)
errorContainer = view.findViewById(R.id.error_container)
loadingContainer = view.findViewById(R.id.loading_container)
loadingImageView = view.findViewById(R.id.loading_image)
errorRetry?.setOnClickListener {
getFirstSection()
}
viewPager?.registerOnPageChangeCallback(onPageChangeCallback)
tabLayout?.adapter = tabAdapter
tabLayout?.itemAnimator = null
tabLayout?.addOnScrollListener(tabScrollListener)
tabAdapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: ViewGroup, itemView: View, position: Int) {
setCurrentPageItem(position)
}
}
applyTheme(templateApp?.isDark != false)
loadBackground()
loadAppIcon()
getFirstSection()
}
override fun onSupportVisible() {
super.onSupportVisible()
clickCount = 0
}
override fun onDestroy() {
super.onDestroy()
recyclerView?.removeOnScrollListener(tabScrollListener)
viewPager?.unregisterOnPageChangeCallback(onPageChangeCallback)
}
private fun setCurrentPageItem(position: Int) {
val viewPager = viewPager ?: return
if (pagerAdapter?.itemCount ?: 0 <= position) return
val smooth = abs(position - viewPager.currentItem) == 1
viewPager.setCurrentItem(position, smooth)
}
override fun scrollToNext(): Boolean {
if (viewPager?.isVisible == false) {
return false
}
val currentItem = viewPager?.currentItem ?: return false
if (currentItem < (viewPager?.adapter?.itemCount ?: 0) - 1 || currentItem < 0) {
viewPager?.post {
viewPager?.setCurrentItem(currentItem + 1, true)
}
return true
}
return false
}
override fun scrollToPrevious(): Boolean {
if (viewPager?.isVisible == false) {
return false
}
val currentItem = viewPager?.currentItem ?: return false
if (currentItem > 0) {
viewPager?.post {
viewPager?.setCurrentItem(currentItem - 1, true)
}
return true
}
return false
}
private fun applyTheme(isDark: Boolean) {
if (isDark) {
loadingImageView?.setAnimation(R.raw.animation_loading_l_white)
} else {
loadingImageView?.setAnimation(R.raw.animation_loading_l)
}
ivBack?.imageTintList = ColorStateList.valueOf(if (isDark) Color.WHITE else Color.BLACK)
tabAdapter.isDark = isDark
if (tabAdapter.itemCount != 0) {
tabAdapter.notifyDataSetChanged()
}
pagerAdapter?.isDark = isDark
}
private fun loadBackground() {
val templateApp = templateApp ?: return
ivBackground?.let { imageView ->
val url = templateApp.img
if (url.isNullOrEmpty())
return
try {
Uri.parse(url)?.let { uri ->
Glide.with(imageView)
.load(uri)
.into(imageView)
}
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
private fun loadAppIcon() {
val templateApp = templateApp ?: return
if (!templateApp.icon.isNullOrEmpty()) {
try {
Uri.parse(templateApp.icon)?.let { uri ->
ivIcon?.let { imageView ->
Glide.with(imageView)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.into(imageView)
}
} ?: run {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} catch (t: Throwable) {
t.printStackTrace()
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
}
private fun showLoading() {
loadingContainer?.isVisible = true
loadingImageView?.playAnimation()
}
private fun dismissLoading() {
loadingContainer?.post {
loadingImageView?.pauseAnimation()
loadingContainer?.isVisible = false
}
}
private fun getFirstSection() {
/*progressDialog = StyledProgressDialog.Builder()
.setTitle(getString(R.string.loading))
.setMessage(getString(R.string.please_wait))
.show(fragmentManager)*/
showLoading()
hideError()
getAppApi()?.getXmlyIndex()?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
//progressDialog?.dismiss()
dismissLoading()
if (t is UnknownHostException) {
showError("Ooooops,请检查网络后重试")
} else {
showError("请求出错,请稍后重试")
}
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (isRemoving || isDetached)
return
context ?: return
if (response.isSuccessful) {
response.body()?.let { body ->
val bodyString = body.string()
Thread {
try {
val json = JSON.parseObject(bodyString)
val sections = json.getJSONArray("section")
val sectionArray = if (sections.isNullOrEmpty()) {
listOf("热门推荐")
} else {
sections.map { it.toString() }
}
tabAdapter.setSections(sectionArray)
val result = json.getJSONArray("result")
val sample = result.getJSONObject(0)
var isCategoryList = false
if (sample.containsKey("category")) {
isCategoryList = true
}
pagerAdapter =
SectionContentAdapter(templateApp, this@TemplateAppXmlyFragment)
pagerAdapter?.isDark = templateApp?.isDark != false
pagerAdapter?.setSections(sectionArray)
if (isCategoryList) {
val categoryList = mutableListOf<XmlyCategoryItem>()
for (i in 0 until result.size) {
val jsonItem = result.getJSONObject(i)
val category = JSON.parseObject(
jsonItem.toString(),
XmlyCategoryItem::class.java
)
categoryList.add(category)
}
pagerAdapter?.initialCategoryList = categoryList
pagerAdapter?.initialAlbumList = null
} else {
val albumList = mutableListOf<XmlyAlbumItem>()
for (i in 0 until result.size) {
val jsonItem = result.getJSONObject(i)
val album = JSON.parseObject(
jsonItem.toString(),
XmlyAlbumItem::class.java
)
albumList.add(album)
}
pagerAdapter?.initialCategoryList = null
pagerAdapter?.initialAlbumList = albumList
}
post {
viewPager?.adapter = pagerAdapter
tabAdapter.notifyDataSetChanged()
//progressDialog?.dismiss()
dismissLoading()
}
} catch (t: Throwable) {
t.printStackTrace()
}
}.start()
}
} else {
//progressDialog?.dismiss()
dismissLoading()
}
}
})
}
private fun showError(message: String?, showRetry: Boolean = true) {
if (isRemoving || isDetached)
return
context ?: return
viewPager?.isVisible = false
recyclerView?.isVisible = false
errorContainer?.isVisible = true
errorRetry?.isVisible = showRetry
tvError?.text = message
}
private fun hideError() {
if (isRemoving || isDetached)
return
context ?: return
viewPager?.isVisible = true
recyclerView?.isVisible = true
errorContainer?.isVisible = false
}
private fun getAppApi(): AppApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(AppApi::class.java)
}
// Setup ViewPager
private class SectionContentAdapter(val templateApp: TemplateApp?, fragment: Fragment) :
FragmentStateAdapter(fragment) {
private val sections = mutableListOf<String>()
var initialCategoryList: List<XmlyCategoryItem>? = null
var initialAlbumList: List<XmlyAlbumItem>? = null
var isDark = false
set(value) {
field = value
fragments.map {
(it.value as? TemplateXmlySectionContentFragment)?.applyTheme(value)
}
}
private val fragments = mutableMapOf<Int, Fragment>() // position -> fragment
fun setSections(sections: List<String>) {
this.sections.clear()
this.sections.addAll(sections)
}
override fun getItemCount(): Int {
return sections.size
}
override fun createFragment(position: Int): Fragment {
val initialCategoryList = initialCategoryList
val initialAlbumList = initialAlbumList
val fragment = if (position == 0) {
if (initialAlbumList.isNullOrEmpty()) {
TemplateXmlySectionContentFragment.newInstance(
templateApp,
sections[position]
)
} else {
if (initialCategoryList.isNullOrEmpty()) {
TemplateXmlySectionContentFragment.fromAlbumList(
templateApp,
sections[position],
initialAlbumList
)
} else {
TemplateXmlySectionContentFragment.fromCategoryList(
templateApp,
sections[position],
initialCategoryList
)
}
}
} else {
TemplateXmlySectionContentFragment.newInstance(
templateApp,
sections[position]
)
}
fragments[position] = fragment
return fragment
}
fun getFragment(position: Int) = fragments[position]
}
// Setup Tab
private class TabAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val sections = mutableListOf<String>()
var selectedItem = 0
var onItemClickListener: OnItemClickListener? = null
var isDark = false
fun setSections(categories: List<String>) {
this.sections.clear()
this.sections.addAll(categories)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = TabViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_app_tab, parent, false)
)
holder.itemView.setOnClickListener {
onItemClickListener?.onItemClick(parent, it, holder.adapterPosition)
}
return holder
}
override fun getItemCount(): Int {
return sections.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is TabViewHolder) {
holder.tvTitle?.text = sections[position]
if (selectedItem == position) {
if (holder.indicator?.isVisible != true) {
holder.indicator?.isVisible = true
}
if (holder.tvTitle?.alpha != 1f) {
holder.tvTitle?.alpha = 1f
}
} else {
if (holder.indicator?.isVisible != false) {
holder.indicator?.isVisible = false
}
if (holder.tvTitle?.alpha != 0.7f) {
holder.tvTitle?.alpha = 0.7f
}
}
if (isDark) {
holder.indicator?.background?.setColorFilter(
Color.WHITE,
PorterDuff.Mode.SRC_IN
)
holder.tvTitle?.setTextColor(Color.WHITE)
} else {
holder.indicator?.background?.setColorFilter(
Color.WHITE,
PorterDuff.Mode.SRC_IN
)
holder.tvTitle?.setTextColor(Color.WHITE)
}
}
}
}
private class TabViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvTitle: GradientTextView? = itemView.findViewById(R.id.title)
val indicator: View? = itemView.findViewById(R.id.indicator)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatDrawableManager
import androidx.core.content.ContextCompat
import com.iflytek.cyber.iot.show.core.R
import kotlin.math.max
import kotlin.math.min
class BatteryView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val backgroundPaint = Paint()
var isCharging = false
set(value) {
field = value
if (width != 0 && height != 0)
invalidate()
}
var level: Int = 0
set(value) {
field = max(0, min(value, 100))
if (width != 0 && height != 0) {
makeBackgroundRectF(width, height)
invalidate()
}
}
var contentPadding = 0
set(value) {
field = value
if (width != 0 && height != 0)
invalidate()
}
var lowPowerColor = Color.RED
set(value) {
field = value
if (width != 0 && height != 0)
invalidate()
}
var lowPowerLimit = 20
set(value) {
field = max(0, min(100, value))
if (width != 0 && height != 0)
invalidate()
}
var contentColor = Color.WHITE
set(value) {
field = value
if (width != 0 && height != 0)
invalidate()
}
var borderColor = Color.WHITE
set(value) {
field = value
if (width != 0 && height != 0)
invalidate()
}
private var backgroundRectF = RectF()
init {
val typedArray = context.obtainStyledAttributes(
attrs, R.styleable.BatteryView, 0, 0
)
contentPadding = typedArray.getDimensionPixelSize(
R.styleable.BatteryView_contentPadding, resources.getDimensionPixelSize(R.dimen.dp_1)
)
contentColor = typedArray.getColor(R.styleable.BatteryView_contentColor, Color.WHITE)
borderColor = typedArray.getColor(R.styleable.BatteryView_borderColor, contentColor)
lowPowerColor = typedArray.getColor(
R.styleable.BatteryView_lowPowerColor,
ContextCompat.getColor(context, R.color.tablet_red)
)
lowPowerLimit = typedArray.getInt(R.styleable.BatteryView_lowPowerLimit, lowPowerLimit)
level = typedArray.getInt(R.styleable.BatteryView_level, 0)
isCharging = typedArray.getBoolean(R.styleable.BatteryView_isCharging, false)
backgroundPaint.color = contentColor
backgroundPaint.isAntiAlias = true
typedArray.recycle()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
makeBackgroundRectF(w, h)
}
private fun makeBackgroundRectF(width: Int, height: Int) {
val backgroundHeight = height * 9 / 24f
val backgroundMaxWidth = width * 14.5f / 24f - 2 * contentPadding
val percent = level / 100f
val left = width / 24f * 3.5f
backgroundRectF.set(
left + contentPadding,
height / 2 - backgroundHeight / 2f + contentPadding,
left + contentPadding + percent * backgroundMaxWidth,
height / 2 + backgroundHeight / 2f - contentPadding
)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas ?: return
if (!isCharging) {
val targetColor = if (level <= lowPowerLimit)
lowPowerColor
else
contentColor
if (backgroundPaint.color != targetColor) {
backgroundPaint.color = targetColor
}
canvas.drawRoundRect(
backgroundRectF,
(backgroundRectF.bottom - backgroundRectF.top) / 8,
(backgroundRectF.bottom - backgroundRectF.top) / 8,
backgroundPaint
)
}
val borderResId = R.drawable.ic_battery_border_white_24dp
AppCompatDrawableManager.get().getDrawable(context, borderResId)?.apply {
setColorFilter(borderColor, PorterDuff.Mode.SRC_IN)
setBounds(0, 0, width, height)
draw(canvas)
}
if (isCharging) {
val thunderResId = R.drawable.ic_battery_thunder_black_24dp
AppCompatDrawableManager.get().getDrawable(context, thunderResId)?.apply {
setColorFilter(contentColor, PorterDuff.Mode.SRC_IN)
setBounds(0, 0, width, height)
draw(canvas)
}
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.api
import com.iflytek.cyber.iot.show.core.model.Weather
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface WeatherApi {
@GET("/showcore/api/v1/weather")
fun getWeather(@Query("location") location: String): Call<Weather>
}<file_sep>package com.iflytek.cyber.evs.sdk.socket
import android.util.Log
import com.iflytek.cyber.evs.sdk.EvsError
import com.iflytek.cyber.evs.sdk.model.Constant
import okhttp3.*
import okio.ByteString
import java.io.EOFException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.nio.ByteBuffer
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.SocketFactory
import javax.net.ssl.*
/**
* WebSocket realized by okhttp3.
*/
internal class OkHttpWebSocket : SocketManager.EvsWebSocket() {
private val TAG = "OkHttpWebSocket"
private var socket: WebSocket? = null
companion object {
private const val NORMAL_CLOSE_CODE = 1000
private const val CLOSE_NO_STATUS_CODE = 1005
private const val MESSAGE_NORMAL_CLOSE = "Normal close"
private const val MESSAGE_REMOTE_CLOSE = "Remote close"
}
override fun connect(serverUrl: String?, deviceId: String, token: String) {
val url = Constant.getWebSocketUrl(serverUrl, deviceId, token)
Log.d(TAG, "connect evs with url {$url}")
socket?.cancel()
socket = null
val request = Request.Builder().url(url).build()
val listener = InnerListener()
if (url.startsWith("wss")) {
OkHttpClient.Builder()
.sslSocketFactory(createSSLSocketFactory(),
object : X509TrustManager {
override fun checkClientTrusted(
chain: Array<out X509Certificate>?,
authType: String?
) {
}
override fun checkServerTrusted(
chain: Array<out X509Certificate>?,
authType: String?
) {
}
override fun getAcceptedIssuers(): Array<X509Certificate> {
return emptyArray()
}
})
.connectTimeout(3, TimeUnit.SECONDS).build()
.newWebSocket(request, listener)
} else {
OkHttpClient.Builder()
.socketFactory(SocketFactory.getDefault())
.connectTimeout(3, TimeUnit.SECONDS).build()
.newWebSocket(request, listener)
}
this.listener = listener
}
private fun createSSLSocketFactory(): SSLSocketFactory {
val context = SSLContext.getInstance("TLSv1.2")
context.init(null, null, SecureRandom())
return context.socketFactory
}
override fun send(message: String): Result {
return if (socket != null) {
Log.d(TAG, "socket send: $message")
socket?.send(message)
onSend(message)
Result(Result.CODE_SUCCEED, null)
} else {
Log.e(TAG, "send $message failed, socket is null.")
onSendFailed(EvsError.Code.ERROR_CLIENT_DISCONNECTED, null, message)
Result(Result.CODE_DISCONNECTED, null)
}
}
override fun send(message: ByteArray): Result {
return if (socket != null) {
socket?.send(ByteString.of(message, 0, message.size))
onSend(message)
Result(Result.CODE_SUCCEED, null)
} else {
Log.e(TAG, "send failed, socket is null.")
onSendFailed(EvsError.Code.ERROR_CLIENT_DISCONNECTED, null, message)
Result(Result.CODE_DISCONNECTED, null)
}
}
override fun send(message: ByteBuffer): Result {
return if (socket != null) {
socket?.send(ByteString.of(message))
onSend(message)
Result(Result.CODE_SUCCEED, null)
} else {
Log.e(TAG, "send failed, socket is null.")
onSendFailed(EvsError.Code.ERROR_CLIENT_DISCONNECTED, null, message)
Result(Result.CODE_DISCONNECTED, null)
}
}
override fun disconnect() {
socket?.close(NORMAL_CLOSE_CODE, MESSAGE_NORMAL_CLOSE)
socket = null
}
private var listener: WebSocketListener? = null
inner class InnerListener : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
super.onOpen(webSocket, response)
Log.d(TAG, "onOpen: {code: ${response.code()}, message: ${response.message()}}")
socket = webSocket
onConnected()
}
override fun onMessage(webSocket: WebSocket, text: String) {
super.onMessage(webSocket, text)
Log.d(TAG, "onMessage: $text")
onMessage(text)
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
super.onClosing(webSocket, code, reason)
Log.w(TAG, "onClosing, code=$code, reason=$reason")
onDisconnected(code, reason, true)
if (code == EvsError.Code.ERROR_SERVER_DISCONNECTED) {
disconnect()
}
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
super.onFailure(webSocket, t, response)
Log.w(
TAG,
"onFailure, response: $response, code=${response?.code()}, reason=${t.message}"
)
t.printStackTrace()
if (response == null) {
when (t) {
is UnknownHostException -> {
onConnectFailed(t)
}
is SSLException -> {
onDisconnected(EvsError.Code.ERROR_CLIENT_DISCONNECTED, null, false)
disconnect()
}
is EOFException -> {
onDisconnected(EvsError.Code.ERROR_CLIENT_DISCONNECTED, null, false)
disconnect()
}
is SocketException -> {
onDisconnected(EvsError.Code.ERROR_SERVER_DISCONNECTED, null, false)
disconnect()
}
is SocketTimeoutException -> {
onDisconnected(EvsError.Code.ERROR_SOCKET_TIMEOUT, null, false)
disconnect()
}
}
} else {
val code = response.code()
onDisconnected(code, t.message, true)
disconnect()
}
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.MediaEntity
import com.makeramen.roundedimageview.RoundedImageView
class MediaViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private var image: RoundedImageView? = itemView.findViewById(R.id.img_cover)
private var order: TextView? = itemView.findViewById(R.id.txt_order)
private var name: TextView? = itemView.findViewById(R.id.txt_name)
private var posInt: Int? = null
fun setItem(item: MediaEntity, pos: Int) {
posInt = pos
order?.text = (pos + 1).toString()
name?.text = item.name
if (item.image != null) {
Glide.with(itemView.context)
// .asBitmap()
.load(item.image)
.error(R.drawable.default_media_placeholder)
// .diskCacheStrategy(DiskCacheStrategy.ALL)
.into(image!!)
}
}
fun setOnClickListener(listener: View.OnClickListener) {
this.itemView.setOnClickListener(listener)
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.AppApi
import com.iflytek.cyber.iot.show.core.model.SourceItem
import com.iflytek.cyber.iot.show.core.model.TemplateApp
import com.iflytek.cyber.iot.show.core.model.TemplateApp2
import com.iflytek.cyber.iot.show.core.model.TemplateMediaItem
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
import com.iflytek.cyber.iot.show.core.utils.clickWithTrigger
import com.iflytek.cyber.iot.show.core.utils.dp2Px
import com.iflytek.cyber.iot.show.core.widget.StyledProgressDialog
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
class TemplateApp2Fragment : BaseFragment() {
companion object {
fun newInstance(templateApp: TemplateApp): TemplateApp2Fragment {
val fragment = TemplateApp2Fragment()
fragment.templateApp = templateApp
return fragment
}
}
private val adapter = TemplateAppAdapter()
private var templateApp: TemplateApp? = null
private var ivBack: ImageView? = null
private var ivIcon: ImageView? = null
private var ivBackground: ImageView? = null
private var recyclerView: RecyclerView? = null
private var tvError: TextView? = null
private var tvRetry: TextView? = null
private var errorRetry: View? = null
private var errorContainer: View? = null
private var loadingContainer: FrameLayout? = null
private var loadingImageView: LottieAnimationView? = null
private var progressDialog: StyledProgressDialog? = null
private var clickCount = 0
private var page = 1
private var isLoading = false
private var totalListSize = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_template_app_2, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back)?.setOnClickListener {
pop()
}
loadingContainer = view.findViewById(R.id.loading_container)
loadingImageView = view.findViewById(R.id.loading_image)
ivBack = view.findViewById(R.id.iv_back)
ivIcon = view.findViewById(R.id.iv_icon)
ivBackground = view.findViewById(R.id.background)
recyclerView = view.findViewById(R.id.recycler_view)
tvRetry = view.findViewById(R.id.tv_retry)
tvError = view.findViewById(R.id.tv_error)
errorContainer = view.findViewById(R.id.error_container)
errorRetry = view.findViewById(R.id.error_retry)
errorRetry?.setOnClickListener {
if (!isLoading) {
//getTemplate()
getTemplateList()
}
}
recyclerView?.adapter = adapter
recyclerView?.itemAnimator = DefaultItemAnimator()
recyclerView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (isLoading) {
return
}
val itemCount = recyclerView.adapter?.itemCount
(recyclerView.layoutManager as? LinearLayoutManager)?.let {
if (it.findLastCompletelyVisibleItemPosition() == it.findLastVisibleItemPosition() &&
itemCount == it.findLastVisibleItemPosition() + 1 &&
itemCount < totalListSize
) {
page++
getTemplateList()
}
}
}
})
adapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: ViewGroup, itemView: View, position: Int) {
val templateApp = templateApp ?: return
val app = adapter.getAppItem(position)
start(
TemplateApp1Fragment.newInstance(templateApp, app)
)
}
}
loadAppIcon()
//getTemplate()
getTemplateList()
loadBackground()
applyTheme(templateApp?.isDark != false)
}
private fun loadBackground() {
val templateApp = templateApp ?: return
ivBackground?.let { imageView ->
val url = templateApp.img
if (url.isNullOrEmpty())
return
try {
Uri.parse(url)?.let { uri ->
Glide.with(imageView)
.load(uri)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
private fun loadAppIcon() {
val templateApp = templateApp ?: return
if (!templateApp.icon.isNullOrEmpty()) {
try {
Uri.parse(templateApp.icon)?.let { uri ->
ivIcon?.let { imageView ->
Glide.with(imageView)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
} ?: run {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} catch (t: Throwable) {
t.printStackTrace()
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
}
private fun showLoading() {
loadingContainer?.isVisible = true
loadingImageView?.playAnimation()
}
private fun dismissLoading() {
loadingContainer?.post {
loadingImageView?.pauseAnimation()
loadingContainer?.isVisible = false
}
}
private fun showError(message: String?, showRetry: Boolean = true) {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = false
errorContainer?.isVisible = true
errorRetry?.isVisible = showRetry
tvError?.text = message
}
private fun hideError() {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = true
errorContainer?.isVisible = false
}
private fun getTemplateList() {
val templateApp = templateApp ?: return
isLoading = true
hideError()
showLoading()
getAppApi()?.getTemplateList(
templateApp.name,
null, null,
null, page
)?.enqueue(object : Callback<TemplateMediaItem> {
override fun onFailure(call: Call<TemplateMediaItem>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
isLoading = false
dismissLoading()
if (t is UnknownHostException) {
showError("Ooooops,请检查网络后重试")
} else {
showError("请求出错,请稍后重试")
}
}
override fun onResponse(
call: Call<TemplateMediaItem>,
response: Response<TemplateMediaItem>
) {
if (isRemoving || isDetached || context == null)
return
isLoading = false
dismissLoading()
if (response.isSuccessful) {
val templateMediaItem = response.body()
if (templateMediaItem?.items != null) {
totalListSize = templateMediaItem.total
if (page == 1) {
setRecyclerViewLayout(templateMediaItem.items)
adapter.setAppList(templateMediaItem.items)
} else {
adapter.appendList(templateMediaItem.items)
}
adapter.notifyDataSetChanged()
}
} else {
isLoading = false
dismissLoading()
showError("请求出错,请稍后重试")
}
}
})
}
private fun setRecyclerViewLayout(appList: ArrayList<SourceItem>) {
if (appList.size < 3) {
recyclerView?.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
recyclerView?.layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT
).apply {
gravity = Gravity.CENTER
}
} else {
recyclerView?.layoutManager = GridLayoutManager(context, 5)
recyclerView?.layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
if (appList.size > 5)
FrameLayout.LayoutParams.MATCH_PARENT
else
FrameLayout.LayoutParams.WRAP_CONTENT
).apply {
if (appList.size > 5) {
topMargin = recyclerView?.resources?.getDimensionPixelOffset(
R.dimen.dp_56
) ?: 56.dp2Px()
} else {
gravity = Gravity.CENTER
topMargin = 0
}
}
if (appList.size > 5) {
val paddingBottom =
recyclerView?.resources?.getDimensionPixelSize(R.dimen.dp_32)
recyclerView?.paddingBottom != paddingBottom
recyclerView?.setPadding(
recyclerView?.paddingLeft ?: 0,
recyclerView?.paddingTop ?: 0,
recyclerView?.paddingRight ?: 0,
paddingBottom ?: 0
)
} else {
recyclerView?.paddingBottom != 0
recyclerView?.setPadding(
recyclerView?.paddingLeft ?: 0,
recyclerView?.paddingTop ?: 0,
recyclerView?.paddingRight ?: 0,
0
)
}
}
}
override fun onSupportVisible() {
super.onSupportVisible()
clickCount = 0
}
private fun applyTheme(isDark: Boolean) {
val tintColor = if (isDark) Color.WHITE else Color.BLACK
ivBack?.setColorFilter(tintColor)
adapter.titleTextColor = tintColor
if (adapter.itemCount > 0) {
adapter.notifyDataSetChanged()
}
tvError?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
tvRetry?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
errorRetry?.setBackgroundResource(
if (isDark) R.drawable.bg_round_border_white_36dp
else R.drawable.bg_round_border_black_36dp
)
}
private fun getAppApi(): AppApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(AppApi::class.java)
}
private class TemplateAppAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
const val HORIZONTAL = 0
const val VERTICAL = 1
}
var onItemClickListener: OnItemClickListener? = null
private val appList = mutableListOf<SourceItem>()
var titleTextColor: Int? = null
fun setAppList(appList: List<SourceItem>) {
this.appList.clear()
this.appList.addAll(appList)
}
fun appendList(appList: List<SourceItem>) {
this.appList.addAll(appList)
}
override fun getItemViewType(position: Int): Int {
return if (itemCount < 3) {
HORIZONTAL
} else {
VERTICAL
}
}
fun getAppItem(position: Int) = appList[position]
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder =
when (viewType) {
HORIZONTAL -> TemplateAppViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_template_app_2_horizontal, parent, false)
)
else -> TemplateAppViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_template_app_2_vertical, parent, false)
)
}
holder.itemView.findViewById<View>(R.id.clickable_view).clickWithTrigger {
onItemClickListener?.onItemClick(parent, holder.itemView, holder.adapterPosition)
}
return holder
}
override fun getItemCount(): Int {
return appList.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is TemplateAppViewHolder) {
val app = appList[position]
holder.tvIndex?.text = (position + 1).toString()
if (!app.cover.isNullOrEmpty()) {
try {
Uri.parse(app.cover)?.let { uri ->
holder.ivImage?.let { imageView ->
val transformer = MultiTransformation(
CenterCrop(),
RoundedCornersTransformation(
imageView.context.resources.getDimensionPixelSize(R.dimen.dp_6),
0
)
)
Glide.with(imageView)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transform(transformer)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
}
} catch (t: Throwable) {
t.printStackTrace()
holder.ivImage?.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
holder.ivImage?.setImageResource(R.drawable.bg_default_template_app_2)
}
holder.tvName?.text = app.title
titleTextColor?.let { textColor ->
holder.tvName?.setTextColor(textColor)
}
}
}
}
private class TemplateAppViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var tvName: TextView? = itemView.findViewById(R.id.name)
var tvIndex: TextView? = itemView.findViewById(R.id.tv_index)
var ivImage: ImageView? = itemView.findViewById(R.id.image)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkInfo
import android.net.NetworkRequest
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.widget.TextView
import com.airbnb.lottie.LottieAnimationView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.SelfBroadcastReceiver
import com.iflytek.cyber.iot.show.core.utils.ConnectivityUtils
import com.iflytek.cyber.iot.show.core.utils.WifiUtils
import java.util.*
class WifiConnectingFragment(private val ssid: String? = null) : BaseFragment() {
companion object {
private const val TAG = "WifiConnectingFragment"
const val NETWORK_RETRY_COUNT = 10
}
private val countHandler = CountDownHandler()
private val connectionReceiver = object : SelfBroadcastReceiver(
WifiManager.SUPPLICANT_STATE_CHANGED_ACTION,
ConnectivityManager.CONNECTIVITY_ACTION
) {
override fun onReceiveAction(action: String, intent: Intent) {
when (action) {
WifiManager.SUPPLICANT_STATE_CHANGED_ACTION -> {
val error = intent.getIntExtra(
WifiManager.EXTRA_SUPPLICANT_ERROR, -1
)
if (error == WifiManager.ERROR_AUTHENTICATING) {
Log.e(TAG, "Wi-Fi authenticate failed")
handleWifiConfigFailed()
}
}
ConnectivityManager.CONNECTIVITY_ACTION -> {
val network = intent.getParcelableExtra<NetworkInfo>(
ConnectivityManager.EXTRA_NETWORK_INFO
)
val detailed = network.detailedState
if (detailed == NetworkInfo.DetailedState.CONNECTED) {
Log.d(TAG, "Wi-Fi connected")
val checkId = UUID.randomUUID()
this@WifiConnectingFragment.checkId = checkId
handleWifiConfigSucceed(checkId)
}
}
}
}
}
private var networkCallback: Any? = null
private var retryCount = 0
private var isChecking = false
private var checkId: UUID? = null
fun handleWifiConfigFailed() {
WifiUtils.forget(context, ssid)
startWithPop(WifiConnectFailedFragment.newInstance("您的网络异常,请确定网络可用后重试"))
countHandler.stopCount()
}
fun handleWifiConfigSucceed(checkId: UUID) {
isChecking = true
Log.d(TAG, "start checking network")
ConnectivityUtils.checkIvsAvailable({
isChecking = false
retryCount = 0
if (findFragment(MainFragment2::class.java) == null) {
startWithPopTo(PairFragment2(), WifiSettingsFragment::class.java, false)
} else {
popTo(WifiSettingsFragment::class.java, false)
}
}) { exception, _ ->
exception?.printStackTrace()
if (this@WifiConnectingFragment.checkId == checkId) {
if (retryCount < NETWORK_RETRY_COUNT) {
try {
Thread.sleep(2000)
} catch (e: Exception) {
e.printStackTrace()
}
handleWifiConfigSucceed(checkId)
} else {
isChecking = false
startWithPop(
WifiConnectFailedFragment.newInstance(
"网络可能不可用,是否选择其他网络",
ssid,
"忽略",
"重新选择"
)
)
countHandler.stopCount()
}
retryCount++
}
}
countHandler.stopCount()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network?) {
super.onAvailable(network)
val checkId = UUID.randomUUID()
this@WifiConnectingFragment.checkId = checkId
handleWifiConfigSucceed(checkId)
}
override fun onLost(network: Network?) {
super.onLost(network)
handleWifiConfigFailed()
}
}
val request = NetworkRequest.Builder().build()
(context?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager)
?.registerNetworkCallback(request, networkCallback)
this.networkCallback = networkCallback
} else {
connectionReceiver.register(context)
}
if (!WifiUtils.getConnectedSsid(context).isNullOrEmpty()) {
val checkId = UUID.randomUUID()
this@WifiConnectingFragment.checkId = checkId
handleWifiConfigSucceed(checkId)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_wifi_connecting, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val loadingAnimation: LottieAnimationView = view.findViewById(R.id.loading)
val tvConnecting: TextView = view.findViewById(R.id.connecting)
ssid?.let { ssid ->
tvConnecting.text = String.format("正在连接到 %s", ssid)
}
loadingAnimation.repeatCount = Animation.INFINITE
loadingAnimation.playAnimation()
countHandler.startCount(Runnable {
if (WifiUtils.getConnectedSsid(context) != ssid) {
WifiUtils.forget(context, ssid)
startWithPop(WifiConnectFailedFragment())
}
})
retryCount = 0
}
override fun onBackPressedSupport(): Boolean {
return true
}
override fun onDestroy() {
super.onDestroy()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
(networkCallback as? ConnectivityManager.NetworkCallback)?.let { networkCallback ->
(context?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager)
?.unregisterNetworkCallback(networkCallback)
}
} else {
connectionReceiver.unregister(context)
}
}
private class CountDownHandler : Handler() {
private var startTime = 0
private var runnable: Runnable? = null
fun startCount(runnable: Runnable) {
val message = Message.obtain()
message.what = 0
message.arg1 = System.currentTimeMillis().toInt()
startTime = message.arg1
this.runnable = runnable
sendMessageDelayed(message, 20 * 1000)
}
fun stopCount() {
removeCallbacksAndMessages(null)
startTime = 0
runnable = null
}
override fun handleMessage(msg: Message?) {
super.handleMessage(msg)
if (msg?.what == 0) {
if (msg.arg1 == startTime) {
runnable?.run()
}
}
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.impl.system
import android.content.Context
import android.content.Intent
import android.os.PowerManager
import com.alibaba.fastjson.JSONObject
import com.iflytek.cyber.evs.sdk.EvsError
import com.iflytek.cyber.evs.sdk.agent.System
import com.iflytek.cyber.iot.show.core.EngineService
import com.iflytek.cyber.iot.show.core.FloatingService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.SelfBroadcastReceiver
import com.iflytek.cyber.iot.show.core.utils.DeviceUtils
import com.iflytek.cyber.product.ota.OtaService
import com.iflytek.cyber.product.ota.PackageEntityNew
import java.lang.ref.SoftReference
class EvsSystem private constructor() : System() {
override fun onPing(timestamp: Long) {
}
companion object {
private var instance: EvsSystem? = null
fun get(): EvsSystem {
instance?.let {
return it
} ?: run {
val system = EvsSystem()
instance = system
return system
}
}
}
private val receiver = object : SelfBroadcastReceiver(
OtaService.ACTION_NEW_UPDATE_DOWNLOADED,
OtaService.ACTION_CHECK_UPDATE_FAILED,
OtaService.ACTION_CHECK_UPDATE_RESULT
) {
override fun onReceiveAction(action: String, intent: Intent) {
when (action) {
OtaService.ACTION_CHECK_UPDATE_FAILED -> {
sendCheckSoftwareUpdateFailed()
}
OtaService.ACTION_CHECK_UPDATE_RESULT -> {
if (intent.hasExtra(OtaService.EXTRA_PACKAGE_ENTITY)) {
val packageEntity =
intent.getParcelableExtra<PackageEntityNew>(OtaService.EXTRA_PACKAGE_ENTITY)
sendCheckSoftwareUpdateSucceed(
true,
packageEntity.versionName,
packageEntity.description
)
} else {
sendCheckSoftwareUpdateSucceed(false, null, null)
sendUpdateSoftwareFailed(ERROR_TYPE_CHECK_ERROR)
}
}
}
}
}
private var contextRef: SoftReference<Context>? = null
var onDeviceModeChangeListener: OnDeviceModeChangeListener? = null
var onEvsErrorListener: OnEvsErrorListener? = null
fun init(context: Context) {
contextRef = SoftReference(context)
receiver.register(context)
hasPowerController = true
hasDeviceModes = true
hasSoftwareUpdater = true
}
override fun checkSoftWareUpdate() {
val context = contextRef?.get()
val intent = Intent(context, OtaService::class.java)
intent.action = OtaService.ACTION_REQUEST_CHECKING
context?.startService(intent)
}
override fun updateSoftware() {
val context = contextRef?.get()
val intent = Intent(context, OtaService::class.java)
intent.action = OtaService.ACTION_REQUEST_CHECKING
intent.putExtra(OtaService.EXTRA_DOWNLOAD_DIRECTLY, false)
context?.startService(intent)
}
fun destroy(context: Context) {
receiver.unregister(context)
}
override fun onError(payload: JSONObject) {
super.onError(payload)
onEvsErrorListener?.onError(payload)
try {
val code = payload.getIntValue(PAYLOAD_CODE)
when {
code >= EvsError.Code.ERROR_SERVER_INTERNAL && code < 600 -> {
val context = contextRef?.get() ?: return
val showNotification = Intent(context, FloatingService::class.java)
showNotification.action = FloatingService.ACTION_SHOW_NOTIFICATION
showNotification.putExtra(
FloatingService.EXTRA_ICON_RES,
R.drawable.ic_default_error_black_40dp
)
showNotification.putExtra(FloatingService.EXTRA_MESSAGE, "服务端暂无响应,请稍后再试")
showNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_TEXT,
context.getString(R.string.i_got_it)
)
context.startService(showNotification)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onPowerOff(payload: JSONObject) {
try {
val context = contextRef?.get() ?: return
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
val clz = PowerManager::class.java
val method = clz.getDeclaredMethod(
"shutdown",
Boolean::class.java,
String::class.java,
Boolean::class.java
)
method.isAccessible = true
method.invoke(pm, false, "userrequested", false)
} catch (t: Throwable) {
t.printStackTrace()
}
}
override fun onUpdateDeviceModes(payload: JSONObject) {
// ignore
}
override fun onFactoryReset() {
super.onFactoryReset()
val context = contextRef?.get() ?: return
DeviceUtils.doFactoryReset(context)
}
override fun revokeAuth(context: Context?) {
super.revokeAuth(context)
val intent = Intent(context, EngineService::class.java)
intent.action = EngineService.ACTION_AUTH_REVOKED
context?.startService(intent)
}
override fun onDeviceModeChanged(kid: Boolean) {
onDeviceModeChangeListener?.onDeviceModeChanged(kid)
}
interface OnDeviceModeChangeListener {
fun onDeviceModeChanged(kid: Boolean)
}
interface OnEvsErrorListener {
fun onError(payload: JSONObject)
}
}<file_sep># 带屏设备开源项目 ShowCore Open
本项目是使用 iFLYOS 的 [EVS协议](https://doc.iflyos.cn/device/evs/) 开发的、运行在 Android 平台的通用语音交互 Launcher App。项目的根本目的是为了减少开发者集成到自有硬件中的开发成本,可以快速开发一款使用 iFLYOS 的智能音箱。
## 运行项目
### 依赖项
* 要求 cmake 3.6 或更高的版本。(用于编译唤醒的 JNI 模块)
* [Android SDK tools](https://developer.android.com/studio/#comand-tools)。(Android Studio 中已内置)
### 集成开发环境
项目开发使用的是 Android Studio 3.5 正式版。
### EVS SDK
项目中引入了 [SDK-EVS-Android](https://github.com/iFLYOS-OPEN/SDK-EVS-Android) 作为 `evs_sdk` 模块,其中代码更新将与 [SDK-EVS-Android](https://github.com/iFLYOS-OPEN/SDK-EVS-Android) 同步。
## App 提供能力概述
整个项目的前提是,为智能音箱开发语音交互应用。在此前提下,App 声明作为 Launcher,期望作为设备开机后的第一入口,比较符合智能音箱的交互。
初次打开应用时,App 提供了简易的网络配置引导和授权绑定引导。
授权完成后,App 提供了一个会提供部分交互推荐的桌面、音频播放界面、视频播放界面、闹钟界面、包含部分简单配置项的设置界面。在主界面中,提供会在桌面轮播的推荐项,左上角可以进入提供有声内容和视频内容推荐的「内容发现」和语音交互使用概览的「技能中心」。
## App 依赖权限概述
为了实现智能音箱的大部分交互,App 依赖若干权限,期望效果中 ROM 在集成应用后应当能在开机后授予应用所有的权限。以下为各个权限及其相关用途说明,如果你开发过程中并不需要,亦可以酌情移除部分权限。
> 以下罗列的主要是我们认为较为重要的需要介绍的权限,针对一些特殊设备的适配时可能有额外的工作要做。例如,VIVO 一些机型上调节音量会导致自动开关勿扰模式,因此你会发现项目中也声明了 `android.permission.ACCESS_NOTIFICATION_POLICY` 权限来解决这种特殊情况。
### 录音权限(必须)
用于发送语音请求和语音唤醒模块
```xml
<uses-permission android:name="android.permission.RECORD_AUDIO" />
```
### 网络连接权限(必须)
用于各种网络请求
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
### 网络状态获取与修改权限
用于在引导页面、设置页面中的 WLAN 引导。Manifest 包含以下内容。
```xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<!-- 在更高 Android API 版本中还需要以下权限才可以搜索 WLAN -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
```
### 获取当前前台应用状态
服务端可以根据当前前台应用,将语义分配给不同的技能做处理,提供更人性化的交互体验。
```xml
<!-- Android 5.1 及以下 -->
<uses-permission android:name="android.permission.GET_TASKS" />
<!-- Android 6.0 以上 -->
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
```
### 悬浮窗
App 通过悬浮窗接口实现了全局可显示的 **语音唤醒按钮**、**语音识别界面**、**左边缘右滑返回手势**、**上边缘下拉控制栏**、**静态模板渲染界面**。
```xml
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
```
> 请注意,返回手势默认只在 App 内才可以有效,全局返回手势需要将 App 作为系统应用或通过 adb 手动授予 `android.permission.INJECT_EVENTS` 权限。
### 修改系统设置
通过这些权限,App 可以做到识别你调节音量、亮度等系统设置相关的语音请求,并对 Android 设备做出相应的更改。
```xml
<uses-permission
android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
```
### 请求安装应用
项目中包含了一个通用的 OTA 模块,可以通过 iFLYOS 的 [自动更新API](https://doc.iflyos.cn/device/ota.html) 更新 App。下载上传到设备控制台的 APK 后,应用提示安装。
```xml
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
```
## 语音唤醒
项目中使用了 70 版本的唤醒引擎实现,可使用 [自定义唤醒词工具](https://www.iflyos.cn/custom-awake-words) 生成你所要自定义的唤醒词文件,解压后替换到 `app/src/main/assets/wakeup/` 下,并在 `app/src/main/java/com/iflytek/cyber/iot/show/core/record/EvsIvwHandler.kt` 代码文件中对如下代码片段进行修改
```kotlin
// others codes
init {
val externalCache = context.externalCacheDir
val customWakeResFile = File("$externalCache/wake_up_res_custom.bin") // 自定义唤醒词
if (!customWakeResFile.exists()) {
val wakeUpResFile = File("$externalCache/wake_up_res.bin")
wakeUpResFile.createNewFile()
val inputStream = context.assets.open("wakeup/lan2-xiao3-fei1.bin")
val outputStream = FileOutputStream(wakeUpResFile)
val buffer = ByteArray(1024)
var byteCount = inputStream.read(buffer)
}
}
// others codes
```
对其中引用 `assets` 目录的 `wakeup/lan2-xiao3-fei1.bin` 路径替换为你所命名的文件路径即可。
## 应用保活
项目中增加了 `keepalive` 模块,用于保证语音交互服务可以一直运行。语音服务在运行过程中会定制启动 `keepalive` 中的服务,服务在一段时间内未收到心跳包后,则会主动调用启动 ShowCore 的主界面。
> **注意**
>
> `keepalive` 应用并未声明开机自启动,保活功能生效必须至少被语音服务启动过一次。
## 其他
为了拥有更好的体验,我们推荐使用 adb 对设备执行以下命令进入全屏模式。
```
adb shell settings put secure user_setup_complete 0
adb shell settings put global policy_control "immersive.full=*"
```
如果你可以授予设备 `android.permission.WRITE_SECURE_SETTINGS` 权限的话,也可以通过 Android 的 Settings API 执行上述授权。
```kotlin
Settings.Secure.putInt(contentResolver, "user_setup_complete", 0)
Settings.Global.putString(contentResolver, "policy_control", "immersive.full=*")
```
恢复原有状态则执行以下命令
```
adb shell settings put secure user_setup_complete 1
adb shell settings put global policy_control "immersive.full="
```
## License
[Apache License, Version 2.0](LICENSE)
<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.animation.ValueAnimator
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.core.view.postDelayed
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.iflytek.cyber.evs.sdk.agent.Alarm
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.FloatingService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.AlarmAdapter
import com.iflytek.cyber.iot.show.core.api.AlarmApi
import com.iflytek.cyber.iot.show.core.impl.alarm.EvsAlarm
import com.iflytek.cyber.iot.show.core.model.Alert
import com.iflytek.cyber.iot.show.core.model.Message
import com.iflytek.cyber.iot.show.core.utils.ContextWrapper
import com.iflytek.cyber.iot.show.core.utils.InsetDividerDecoration
import com.iflytek.cyber.iot.show.core.widget.ExFrameLayout
import com.kk.taurus.playerbase.utils.NetworkUtils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class AlarmFragment : BaseFragment(), PageScrollable {
companion object {
private const val REQUEST_ADD_ALARM_CODE = 10332
}
//private lateinit var tvSetAlarmTips: TextView
private lateinit var tvEmptyTips: TextView
private lateinit var alarmList: RecyclerView
private lateinit var tvSummary: AppCompatTextView
private lateinit var errorContainer: LinearLayout
private lateinit var loading: LottieAnimationView
private lateinit var alarmAdapter: AlarmAdapter
private var shouldUpdateAlarm = false
private var backCount = 0
private var currentSummary = 0
private var isLoading = false
private val tips = arrayListOf(
"你可以说:帮我设置工作日早上八点半的闹钟",
"你可以说:明天中午12点提醒我和父母吃饭",
"你可以说:提醒我明天下午两点和女朋友逛街"
)
private val handler = Handler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
EvsAlarm.get(context).addOnAlarmUpdatedListener(onAlarmUpdatedListener)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return LayoutInflater.from(context).inflate(R.layout.fragment_alarm, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//tvSetAlarmTips = view.findViewById(R.id.tv_set_alarm_tips)
errorContainer = view.findViewById(R.id.error_container)
loading = view.findViewById(R.id.loading)
view.findViewById<Button>(R.id.retry).setOnClickListener {
errorContainer.isVisible = false
loading.isVisible = true
loading.playAnimation()
getAlerts()
}
tvSummary = view.findViewById(R.id.tv_summary)
tvEmptyTips = view.findViewById(R.id.tv_empty_tips)
alarmList = view.findViewById(R.id.alarm_list)
val exFrameLayout = view.findViewById<ExFrameLayout>(R.id.ex_frame_layout)
exFrameLayout.setOnCloseListener(object : ExFrameLayout.OnCloseListener {
override fun onClose() {
pop()
}
})
tvSummary.text = tips[currentSummary]
view.findViewById<View>(R.id.iv_back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
setFragmentResult(0, bundleOf(Pair("shouldUpdateAlarm", shouldUpdateAlarm)))
pop()
}
val button = view.findViewById<Button>(R.id.add_alarm)
button.setOnClickListener {
if (isAdded && context != null && !NetworkUtils.isNetConnected(context)) {
showNetworkError()
return@setOnClickListener
}
startForResult(EditAlarmFragment(), REQUEST_ADD_ALARM_CODE)
}
alarmAdapter = AlarmAdapter({
start(EditAlarmFragment.instance(it))
}, { alert, position ->
deleteAlarm(alert, position)
})
val lineHeight = resources.getDimensionPixelSize(R.dimen.dp_1)
val padding = resources.getDimensionPixelSize(R.dimen.dp_40)
val dividerColor = ContextCompat.getColor(requireActivity(), R.color.grey_line)
val decoration = InsetDividerDecoration(lineHeight, dividerColor, 0)
decoration.startPadding = padding
decoration.endPadding = padding
alarmList.addItemDecoration(decoration)
alarmList.adapter = alarmAdapter
loading.isVisible = true
loading.playAnimation()
getAlerts()
setFragmentResult(0, bundleOf(Pair("shouldUpdateAlarm", false)))
if (isAdded && context != null && !NetworkUtils.isNetConnected(context)) {
showNetworkError()
}
}
private fun showNetworkError() {
val networkErrorNotification =
Intent(context, FloatingService::class.java)
networkErrorNotification.action =
FloatingService.ACTION_SHOW_NOTIFICATION
networkErrorNotification.putExtra(
FloatingService.EXTRA_MESSAGE, "网络连接异常,请重新设置"
)
networkErrorNotification.putExtra(
FloatingService.EXTRA_TAG, "network_error"
)
networkErrorNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_TEXT, "设置网络"
)
networkErrorNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_ACTION,
MainFragment2.ACTION_OPEN_WIFI
)
networkErrorNotification.putExtra(
FloatingService.EXTRA_ICON_RES,
R.drawable.ic_wifi_error_white_40dp
)
ContextWrapper.startServiceAsUser(context!!, networkErrorNotification, "CURRENT")
}
override fun onDestroy() {
super.onDestroy()
EvsAlarm.get(context).removeOnAlarmUpdatedListener(onAlarmUpdatedListener)
}
override fun onBackPressedSupport(): Boolean {
setFragmentResult(0, bundleOf(Pair("shouldUpdateAlarm", shouldUpdateAlarm)))
return super.onBackPressedSupport()
}
private fun deleteAlarm(alert: Alert, position: Int) {
getAlarmApi()?.deleteAlarm(alert.id)?.enqueue(object : Callback<Message> {
override fun onFailure(call: Call<Message>, t: Throwable) {
t.printStackTrace()
}
override fun onResponse(call: Call<Message>, response: Response<Message>) {
if (!isAdded) {
return
}
if (response.isSuccessful) {
alarmAdapter.alerts.removeAt(position)
alarmAdapter.notifyDataSetChanged()
/*alarmAdapter.notifyItemRemoved(position)
alarmAdapter.notifyItemRangeRemoved(position, alarmAdapter.alerts.size)*/
Toast.makeText(alarmList.context, "删除成功", Toast.LENGTH_SHORT).show()
}
}
})
}
private fun getAlerts() {
if (isLoading) {
return
}
isLoading = true
getAlarmApi()?.getAlerts()?.enqueue(object : Callback<ArrayList<Alert>> {
override fun onFailure(call: Call<ArrayList<Alert>>, t: Throwable) {
t.printStackTrace()
isLoading = false
loading.isVisible = false
loading.pauseAnimation()
errorContainer.isVisible = true
}
override fun onResponse(
call: Call<ArrayList<Alert>>,
response: Response<ArrayList<Alert>>
) {
isLoading = false
loading.isVisible = false
loading.pauseAnimation()
if (response.isSuccessful) {
errorContainer.isVisible = false
val items = response.body()
items?.let {
if (it.isNullOrEmpty()) {
//tvSetAlarmTips.isVisible = false
tvEmptyTips.isVisible = true
alarmList.isVisible = false
} else {
alarmList.isVisible = true
//tvSetAlarmTips.isVisible = true
tvEmptyTips.isVisible = false
}
alarmAdapter.alerts.clear()
alarmAdapter.alerts.addAll(it)
alarmAdapter.notifyDataSetChanged()
}
} else {
errorContainer.isVisible = true
}
}
})
}
override fun onSupportVisible() {
super.onSupportVisible()
postNextUpdateSummary()
}
override fun onSupportInvisible() {
super.onSupportInvisible()
handler.removeCallbacksAndMessages(null)
}
private val updateSummaryRunnable: Runnable = Runnable {
if (isResumed) {
val next = (currentSummary + 1) % tips.size
currentSummary = next
startUpdateSummaryAnimator(tips[next])
postNextUpdateSummary()
}
}
private fun postNextUpdateSummary() {
handler.removeCallbacksAndMessages(null)
handler.postDelayed(updateSummaryRunnable, 6 * 1000)
}
private fun startUpdateSummaryAnimator(newText: String) {
val animator = ValueAnimator.ofFloat(0f, 2f)
animator.addUpdateListener {
val value = it.animatedValue as Float
if (value > 1) {
if (tvSummary.text.toString() != newText) {
tvSummary.text = tips[currentSummary]
}
tvSummary.alpha = value - 1
} else {
tvSummary.alpha = 1 - value
}
}
animator.duration = 600
animator.start()
}
override fun scrollToNext(): Boolean {
alarmList.let { recyclerView ->
val lastItem =
(recyclerView.layoutManager as? LinearLayoutManager)?.findLastCompletelyVisibleItemPosition()
val itemCount = alarmAdapter.itemCount
if (lastItem == itemCount - 1 || itemCount == 0) {
return false
} else {
recyclerView.smoothScrollBy(0, recyclerView.height)
}
}
return true
}
override fun scrollToPrevious(): Boolean {
alarmList.let { recyclerView ->
val scrollY = recyclerView.computeVerticalScrollOffset()
val itemCount = alarmAdapter.itemCount
if (scrollY == 0 || itemCount == 0) {
return false
} else {
recyclerView.smoothScrollBy(0, -recyclerView.height)
}
}
return true
}
private val onAlarmUpdatedListener = object : Alarm.OnAlarmUpdatedListener {
override fun onAlarmUpdated() {
alarmList.postDelayed(50) {
getAlerts()
}
shouldUpdateAlarm = true
}
}
override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle) {
super.onFragmentResult(requestCode, resultCode, data)
if (requestCode == REQUEST_ADD_ALARM_CODE) {
alarmList.postDelayed(80) {
getAlerts()
}
}
}
private fun getAlarmApi(): AlarmApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(AlarmApi::class.java)
} else {
null
}
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent
/**
* 扬声器控制模块。详细介绍见https://doc.iflyos.cn/device/evs/reference/speaker.html#%E6%89%AC%E5%A3%B0%E5%99%A8%E6%8E%A7%E5%88%B6
*/
abstract class Speaker {
val version = "1.0"
companion object {
const val NAME_SET_VOLUME = "speaker.set_volume"
const val KEY_TYPE = "type"
const val KEY_VOLUME = "volume"
}
/**
* 返回音量类型,当前只支持百分比。
*/
fun getType() = "percent"
/**
* 获取当前音量。
* @return 音量值(0-100)
*/
abstract fun getCurrentVolume(): Int
/**
* 设置音量。
* @param volume 音量值(0-100)
* @return 是否设置成功
*/
abstract fun setVolume(volume: Int): Boolean
}<file_sep>cmake_minimum_required(VERSION 3.4.1)
add_subdirectory(opus)
add_subdirectory(speex)<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.core.os.bundleOf
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.KeyboardUtils
class EditAlarmDescFragment : BaseFragment() {
companion object {
fun instance(desc: String): EditAlarmDescFragment {
return EditAlarmDescFragment().apply {
arguments = bundleOf(Pair("desc", desc))
}
}
}
private lateinit var editText: EditText
private var desc: String? = null
private var backCount = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return LayoutInflater.from(context)
.inflate(R.layout.fragment_edit_alarm_desc, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setFragmentResult(0, bundleOf())
desc = arguments?.getString("desc")
view.findViewById<View>(R.id.iv_back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
KeyboardUtils.closeKeyboard(editText)
val bundle = bundleOf(Pair("desc", desc), Pair("isEdited", false))
setFragmentResult(0, bundle)
pop()
}
editText = view.findViewById(R.id.edit_text)
editText.setText(desc)
editText.setSelection(desc?.length ?: 0)
view.findViewById<Button>(R.id.done).setOnClickListener {
KeyboardUtils.closeKeyboard(editText)
val bundle = bundleOf(Pair("desc", editText.text.toString()), Pair("isEdited", true))
setFragmentResult(0, bundle)
pop()
}
}
override fun onBackPressedSupport(): Boolean {
KeyboardUtils.closeKeyboard(editText)
val bundle = bundleOf(Pair("desc", desc))
setFragmentResult(0, bundle)
return super.onBackPressedSupport()
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent.impl
import android.content.Context
import android.media.AudioManager
import android.os.Build
import com.iflytek.cyber.evs.sdk.agent.Speaker
class SpeakerImpl(private val context: Context) : Speaker() {
override fun getCurrentVolume(): Int {
(context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager)?.let { audioManager ->
val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
val min =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
else 0
val current = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
return (1.0 * (current - min) / (max - min) * 100.0).toInt()
}
return 0
}
override fun setVolume(volume: Int): Boolean {
(context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager)?.let { audioManager ->
val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
val min =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
else 0
val realVolume = (1.0 * volume / 100.0 * (max - min) + min).toInt()
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, realVolume, AudioManager.FLAG_SHOW_UI)
return true
}
return false
}
}<file_sep>package com.iflytek.cyber.evs.sdk.utils
import android.app.ActivityManager
import android.app.usage.UsageEvents
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.net.Uri
import android.os.Build
import java.util.ArrayList
object AppUtil {
private const val TYPE_ACTIVITY = "activity"
private const val TYPE_SERVICE = "service"
private const val TYPE_BROADCAST = "broadcast"
data class AppInfo(val appName: String?, val pkgName: String?, val curActivity: String?,
val version: Int = 0)
private var lastForeApp: AppInfo? = null
private var lastQueryTime: Long = 0
fun getForegroundApp(context: Context): AppInfo? {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val runningTasks: List<ActivityManager.RunningTaskInfo> = activityManager.getRunningTasks(1)
if (runningTasks.isNotEmpty()) {
val pkgName = runningTasks[0].topActivity.packageName
val clsName = runningTasks[0].topActivity.className
return if (pkgName != context.packageName)
AppInfo("", pkgName, clsName)
else
AppInfo("", "DEFAULT", clsName)
}
} else {
val time: Long = System.currentTimeMillis()
val usageManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
val events: UsageEvents = usageManager.queryEvents(lastQueryTime, time)
var lastEvent: UsageEvents.Event? = null
while (events.hasNextEvent()) {
val curEvent: UsageEvents.Event = UsageEvents.Event()
events.getNextEvent(curEvent)
if (curEvent.packageName.isNullOrEmpty() || curEvent.className.isNullOrEmpty()) {
continue
}
if (lastEvent == null || curEvent.timeStamp > lastEvent.timeStamp) {
lastEvent = curEvent
}
}
if (lastEvent != null) {
lastForeApp =
if (lastEvent.packageName != context.packageName)
AppInfo("", lastEvent.packageName, lastEvent.className)
else
AppInfo("", "DEFAULT", lastEvent.className)
lastQueryTime = time - 60 * 60 * 1000
}
return lastForeApp
}
return null
}
fun getAppInfo(context: Context, pkgName: String): AppInfo? {
val pm = context.packageManager
val appInfo: AppInfo?
try {
val info = pm.getPackageInfo(pkgName, 0)
val appName = info.applicationInfo.loadLabel(pm)
val version = info.versionCode
appInfo = AppInfo(appName.toString(), pkgName, "", version)
} catch (e: PackageManager.NameNotFoundException) {
return null
}
return appInfo
}
fun isActionSupported(context: Context, intent: Intent, type: String = ""): Boolean {
val pm = context.packageManager
when (type) {
TYPE_ACTIVITY -> {
val activityList: List<ResolveInfo> = pm.queryIntentActivities(intent,
PackageManager.GET_RESOLVED_FILTER)
if (activityList.isNotEmpty()) {
return true
}
}
TYPE_SERVICE -> {
val activityList: List<ResolveInfo> = pm.queryIntentServices(intent,
PackageManager.GET_RESOLVED_FILTER)
if (activityList.isNotEmpty()) {
return true
}
}
TYPE_BROADCAST -> {
val activityList: List<ResolveInfo> = pm.queryBroadcastReceivers(intent,
PackageManager.GET_RESOLVED_FILTER)
if (activityList.isNotEmpty()) {
return true
}
}
else -> {
val list1: List<ResolveInfo> = pm.queryIntentActivities(intent,
PackageManager.GET_RESOLVED_FILTER)
val list2: List<ResolveInfo> = pm.queryIntentServices(intent,
PackageManager.GET_RESOLVED_FILTER)
val list3: List<ResolveInfo> = pm.queryBroadcastReceivers(intent,
PackageManager.GET_RESOLVED_FILTER)
if (list1.isNotEmpty() || list2.isNotEmpty() || list3.isNotEmpty()) {
return true
}
}
}
return false
}
fun isPackageExist(context: Context, pkgName: String?, acceptUri: String?): Boolean {
val pm = context.packageManager
val intent = Intent()
intent.setPackage(pkgName)
var tmpUri: Uri? = null
if (!acceptUri.isNullOrEmpty()) {
tmpUri = Uri.parse(acceptUri)
intent.data = tmpUri
}
val activityList: List<ResolveInfo> = pm.queryIntentActivities(intent,
PackageManager.GET_RESOLVED_FILTER)
val serviceList: List<ResolveInfo> = pm.queryIntentServices(intent,
PackageManager.GET_RESOLVED_FILTER)
val broadcastList: List<ResolveInfo> = pm.queryBroadcastReceivers(intent,
PackageManager.GET_RESOLVED_FILTER)
val infoList: MutableList<ResolveInfo> = ArrayList()
infoList.addAll(activityList)
infoList.addAll(serviceList)
infoList.addAll(broadcastList)
if (!infoList.isNullOrEmpty()) {
return true
}
return false
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.graphics.Color
import android.graphics.PorterDuff
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.drakeet.multitype.ItemViewBinder
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.DeskRecommend
import com.iflytek.cyber.iot.show.core.model.DeskRecommendItem
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.utils.OnMultiTypeItemClickListener
import com.iflytek.cyber.iot.show.core.utils.clickWithTrigger
class RecommendAdviceViewHolder : ItemViewBinder<DeskRecommend, RecyclerView.ViewHolder>() {
var onItemClickListener: OnMultiTypeItemClickListener? = null
var onCardRefreshListener: OnItemClickListener? = null
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: DeskRecommend) {
if (holder is ItemViewHolder) {
holder.setItem(item)
}
}
override fun onCreateViewHolder(
inflater: LayoutInflater,
parent: ViewGroup
): RecyclerView.ViewHolder {
val holder = ItemViewHolder(inflater.inflate(R.layout.item_recommend_advice, parent, false))
holder.onItemClickListener = object :
OnItemClickListener {
@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
override fun onItemClick(parentInside: ViewGroup, itemViewInside: View, position: Int) {
onItemClickListener?.onItemClick(
parent,
holder.itemView,
holder.adapterPosition,
position
)
}
}
holder.refresh?.clickWithTrigger {
onCardRefreshListener?.onItemClick(parent, holder.itemView, holder.adapterPosition)
}
return holder
}
private class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val ivBackground: ImageView? = itemView.findViewById(R.id.background)
val container: View? = itemView.findViewById(R.id.container)
val tvTitle: TextView? = itemView.findViewById(R.id.title)
val recyclerView: RecyclerView? = itemView.findViewById(R.id.recycler_view)
val refresh: ImageView? = itemView.findViewById(R.id.refresh)
private val adapter = AdviceAdapter()
private val innerOnItemCLickListener = object :
OnItemClickListener {
override fun onItemClick(parent: ViewGroup, itemView: View, position: Int) {
onItemClickListener?.let { listener ->
val item = adapter.items[position]
listener.onItemClick(parent, itemView, position)
}
}
}
var onItemClickListener: OnItemClickListener? = null
init {
recyclerView?.adapter = adapter
adapter.onItemClickListener = innerOnItemCLickListener
}
fun setItem(item: DeskRecommend) {
item.background?.let { background ->
if (background.isEmpty()) {
container?.background?.setColorFilter(
itemView.resources.getColor(R.color.campus_blue),
PorterDuff.Mode.SRC_IN
) ?: run {
val drawable =
itemView.resources.getDrawable(R.drawable.bg_white_round_16dp)
drawable.setColorFilter(
itemView.resources.getColor(R.color.campus_blue),
PorterDuff.Mode.SRC_IN
)
container?.background = drawable
}
} else {
var isColor = false
try {
val color = Color.parseColor(background)
container?.background?.setColorFilter(color, PorterDuff.Mode.SRC_IN)
?: run {
val drawable =
itemView.resources.getDrawable(R.drawable.bg_white_round_16dp)
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN)
container?.background = drawable
}
isColor = true
} catch (t: Throwable) {
t.printStackTrace()
}
if (!isColor) {
ivBackground?.let { imageView ->
Glide.with(ivBackground)
.load(background)
.into(imageView)
}
} else {
}
}
}
tvTitle?.text = item.title
try {
val color = Color.parseColor(item.titleColor)
tvTitle?.setTextColor(color)
refresh?.setColorFilter(color)
} catch (t: Throwable) {
}
adapter.items.apply {
clear()
item.items?.let { items ->
addAll(items)
}
adapter.notifyDataSetChanged()
}
}
}
private class AdviceAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val items = mutableListOf<DeskRecommendItem>()
var onItemClickListener: OnItemClickListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = AdviceViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_text_bubble,
parent,
false
)
)
holder.clickableView?.setOnClickListener {
onItemClickListener?.onItemClick(parent, holder.itemView, holder.adapterPosition)
}
return holder
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is AdviceViewHolder) {
holder.tvTitle?.text = items[position].title
try {
val color = Color.parseColor(items[position].titleColor)
holder.tvTitle?.setTextColor(color)
} catch (t: Throwable) {
}
try {
val color = Color.parseColor(items[position].background)
holder.clickableView?.background?.setColorFilter(color, PorterDuff.Mode.SRC_IN)
} catch (t: Throwable) {
}
}
}
}
private class AdviceViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvTitle: TextView? = itemView.findViewById(R.id.title)
val clickableView: View? = itemView.findViewById(R.id.clickable_view)
}
}<file_sep>package com.iflytek.cyber.evs.sdk.focus
enum class FocusStatus {
Foreground,
Background,
Idle
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.impl.audioplayer
import android.net.Uri
import android.os.Build
import okhttp3.OkHttpClient
import okhttp3.OkUrlFactory
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.security.SecureRandom
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.regex.Pattern
import javax.net.ssl.SSLContext
class PlaylistParser {
private val mExecutor = Executors.newSingleThreadExecutor()
// private val mOkHttpClient = Tls12SocketFactory.enableTls12OnPreLollipop(OkHttpClient.Builder()).build()
private val mOkHttpClient: OkHttpClient
private val mOkHttpFactory: OkUrlFactory
init {
val clientBuilder = OkHttpClient.Builder()
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
val context = SSLContext.getInstance("TLSv1.2")
context.init(null, null, SecureRandom())
clientBuilder.sslSocketFactory(context.socketFactory)
}
mOkHttpClient = clientBuilder.build()
mOkHttpFactory = OkUrlFactory(mOkHttpClient)
}
// Extracts Url from redirect Url. Note: not a complete playlist parser implementation
@Throws(IOException::class)
internal fun parseUri(uri: Uri): Uri {
return parsePlaylist(parseResponse(getResponse(uri)))
}
@Throws(IOException::class)
private fun getResponse(uri: Uri): InputStream {
val response = mExecutor.submit(Callable {
var con: HttpURLConnection? = null
try {
val obj = URL(uri.toString())
con = mOkHttpFactory.open(obj)
val responseCode = con!!.responseCode
return@Callable if (responseCode == sResponseOk) {
con.inputStream
} else {
throw IOException("$sTag: Unsuccessful response. Code: $responseCode")
}
} finally {
con?.disconnect()
}
})
try {
return response.get()
} catch (e: Exception) {
throw IOException(sTag + ": Error getting response: " + e.message)
}
}
@Throws(IOException::class)
private fun parseResponse(inStream: InputStream?): String? {
if (inStream != null) {
val `in` = BufferedReader(InputStreamReader(inStream))
var inputLine: String?
val response = StringBuilder()
try {
inputLine = `in`.readLine()
while (inputLine != null) {
response.append(inputLine)
inputLine = `in`.readLine()
}
return response.toString()
} catch (e: Exception) {
throw IOException("$sTag: Error parsing response")
} finally {
inStream.close()
}
}
return null
}
companion object {
private val sTag = "PlaylistParser"
private val sResponseOk = 200
private val sPattern = Pattern.compile("https?:.*")
@Throws(IOException::class)
private fun parsePlaylist(playlist: String?): Uri {
if (playlist != null && !playlist.isEmpty()) {
val matcher = sPattern.matcher(playlist)
return if (matcher.find()) {
Uri.parse(playlist.substring(matcher.start(), matcher.end()))
} else {
throw IOException("$sTag: Response did not contain a URL")
}
} else {
throw IOException("$sTag: Response was empty")
}
}
}
}
<file_sep>package com.iflytek.cyber.evs.sdk.utils
import com.iflytek.cyber.evs.sdk.BuildConfig
internal object Log {
var isDebug = BuildConfig.DEBUG
private const val MAX_LENGTH = 600
fun w(tag: String, log: String, throwable: Throwable? = null) {
if (throwable != null)
android.util.Log.w(tag, log, throwable)
else {
var index = 0
while (index < log.length) {
val sub = if (index + MAX_LENGTH < log.length)
log.substring(index, index + MAX_LENGTH)
else
log.substring(index)
android.util.Log.w(tag, "${if (index != 0) " " else ""}$sub")
index += MAX_LENGTH
}
}
}
fun d(tag: String, log: String, throwable: Throwable? = null) {
if (!isDebug) return
if (throwable != null)
android.util.Log.d(tag, log, throwable)
else {
var index = 0
while (index < log.length) {
val sub = if (index + MAX_LENGTH < log.length)
log.substring(index, index + MAX_LENGTH)
else
log.substring(index)
android.util.Log.d(tag, "${if (index != 0) " " else ""}$sub")
index += MAX_LENGTH
}
}
}
fun i(tag: String, log: String, throwable: Throwable? = null) {
if (!isDebug) return
if (throwable != null)
android.util.Log.i(tag, log, throwable)
else {
var index = 0
while (index < log.length) {
val sub = if (index + MAX_LENGTH < log.length)
log.substring(index, index + MAX_LENGTH)
else
log.substring(index)
android.util.Log.i(tag, "${if (index != 0) " " else ""}$sub")
index += MAX_LENGTH
}
}
}
fun e(tag: String, log: String, throwable: Throwable? = null) {
if (throwable != null)
android.util.Log.e(tag, log, throwable)
else {
var index = 0
while (index < log.length) {
val sub = if (index + MAX_LENGTH < log.length)
log.substring(index, index + MAX_LENGTH)
else
log.substring(index)
android.util.Log.e(tag, "${if (index != 0) " " else ""}$sub")
index += MAX_LENGTH
}
}
}
fun v(tag: String, log: String, throwable: Throwable? = null) {
if (!isDebug) return
if (throwable != null)
android.util.Log.v(tag, log, throwable)
else {
var index = 0
while (index < log.length) {
val sub = if (index + MAX_LENGTH < log.length)
log.substring(index, index + MAX_LENGTH)
else
log.substring(index)
android.util.Log.v(tag, "${if (index != 0) " " else ""}$sub")
index += MAX_LENGTH
}
}
}
}<file_sep>//
// Created by huang on 2019/1/24.
//
#include "FileUtil.h"
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fstream>
namespace iflytek {
bool FileUtil::isPathExist(const string& path, bool& isFile)
{
if (path.empty()) {
return false;
}
bool exist = false;
if (access(path.c_str(), F_OK) != -1) {
exist = true;
struct stat buf;
if (0 == stat(path.c_str(), &buf)) {
isFile = !S_ISDIR(buf.st_mode);
}
}
return exist;
}
long FileUtil::getFileSizeInBytes(const string& path)
{
struct stat buf;
if (0 == stat(path.c_str(), &buf)) {
return buf.st_size;
}
return -1;
}
long FileUtil::readFileToBuffer(const string& path, char* buffer, long bufferSize)
{
fstream ins;
ins.open(path, ios::in | ios::binary);
if (ins.is_open()) {
ins.read(buffer, bufferSize);
return ins.gcount();
}
return -1;
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.webkit.*
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.core.view.postDelayed
import com.airbnb.lottie.LottieAnimationView
import com.iflytek.cyber.iot.show.core.EngineService
import com.iflytek.cyber.iot.show.core.FloatingService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.impl.launcher.EvsLauncher
import com.iflytek.cyber.iot.show.core.model.Skill
import com.iflytek.cyber.iot.show.core.utils.ConfigUtils
import com.iflytek.cyber.iot.show.core.widget.StyledAlertDialog
import com.iflytek.home.sdk.IFlyHome
import com.iflytek.home.sdk.callback.IFlyHomeCallback
class SkillFragment : BaseFragment() {
companion object {
const val EXTRA_URL = "url"
const val EXTRA_TIMEOUT = "timeout"
private const val SESSION_TIMEOUT = 15 * 60 * 1000
fun newInstance(
url: String?,
timeout: Int
): SkillFragment {
return SkillFragment().apply {
arguments = bundleOf(
Pair(EXTRA_URL, url),
Pair(EXTRA_TIMEOUT, timeout)
)
}
}
}
private var webView: WebView? = null
private var loadingView: LottieAnimationView? = null
private var timer: CountDownTimer? = null
private var shouldShowVoice = false
private var isLoading = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_skill, container, false)
}
@SuppressLint("SetJavaScriptEnabled")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
webView = view.findViewById(R.id.webview)
loadingView = view.findViewById(R.id.loading)
webView?.settings?.javaScriptEnabled = true
webView?.settings?.domStorageEnabled = true
webView?.settings?.allowFileAccess = true
webView?.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
val url =
request?.url?.toString() ?: return super.shouldOverrideUrlLoading(view, request)
return shouldOverrideUrlLoading(view, url)
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
if (url.isNullOrEmpty())
return super.shouldOverrideUrlLoading(view, url)
return if (url == "close://now") {
pop()
true
} else {
super.shouldOverrideUrlLoading(view, url)
}
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
isLoading = false
loadingView?.animate()?.alpha(0f)?.setDuration(150)?.withEndAction {
}?.start()
}
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
isLoading = true
}
}
webView?.addJavascriptInterface(SkillInterface(), "androidApi")
arguments?.getString("url")?.let { url ->
webView?.loadUrl(url)
}
val timeout = arguments?.getInt(EXTRA_TIMEOUT, -1)
if (timeout != null && timeout > 0) {
startCount(timeout * 1000)
}
val isMicrophoneEnabled =
ConfigUtils.getBoolean(ConfigUtils.KEY_VOICE_WAKEUP_ENABLED, true)
shouldShowVoice = isMicrophoneEnabled
launcher?.let {
val intent = Intent(it, FloatingService::class.java).apply {
action = FloatingService.ACTION_HIDE_VOICE_BUTTON
}
it.startService(intent)
}
}
private fun startCount(timeout: Int) {
timer?.cancel()
timer = object : CountDownTimer(timeout.toLong(), 1000) {
override fun onFinish() {
if (!isAdded || context == null) {
return
}
pop()
}
override fun onTick(millisUntilFinished: Long) {
}
}
timer?.start()
}
fun setSemanticData(semanticData: String) {
//webView?.loadUrl("javascript:handleSemanticData('$semanticData')")
startCount(SESSION_TIMEOUT)
webView?.evaluateJavascript(
"javascript:handleSemanticData($semanticData)"
) {
Log.d("WebViewFragment", "receive value: $it")
}
}
override fun onDestroy() {
super.onDestroy()
EvsLauncher.get().clearInternalAppId()
webView?.destroy()
if (shouldShowVoice) {
launcher?.let {
val intent = Intent(it, FloatingService::class.java).apply {
action = FloatingService.ACTION_SHOW_VOICE_BUTTON
}
it.startService(intent)
}
}
}
inner class SkillInterface {
@JavascriptInterface
fun audio_in() {
launcher?.let {
val intent = Intent(it, EngineService::class.java)
intent.action = EngineService.ACTION_SEND_AUDIO_IN
it.startService(intent)
}
}
}
}<file_sep>#include <jni.h>
#include <string>
#include <map>
#include "com_iflytek_cyber_iot_show_core_ivw_IVWEngine.h"
#include "include/ivw/engine/IvwEngine.h"
#include "log/log.h"
#include "file/FileUtil.h"
using namespace iflytek;
using namespace std;
#define INVALID_HANDLE 0
// 唤醒回调方法签名
const char* SIGNATURE_WAKEUP_CB = "(Ljava/lang/String;)V";
// 唤醒资源
struct IvwRes {
char* buffer;
size_t size;
IvwRes(size_t nSize) : buffer(nullptr), size(nSize) {
buffer = new char[nSize];
}
void release() {
if (nullptr != buffer) {
delete[] buffer;
size = 0;
buffer = nullptr;
}
}
};
// 引擎上下文
struct EngineContext {
// 引擎接口
PIVWEngineFace engineFace;
// 唤醒资源
IvwRes* ivwRes;
// 唤醒实例指针
IVW_INSTHANDLE instHandle;
// JVM
JavaVM* jvm;
// java对象引用
jobject objRef;
// java对象方法id
jmethodID wakeupCbMethodId;
EngineContext() : engineFace(nullptr),
ivwRes(nullptr),
instHandle(nullptr),
jvm(nullptr),
objRef(nullptr),
wakeupCbMethodId(nullptr) {
}
EngineContext(PIVWEngineFace face,
IvwRes* res,
IVW_INSTHANDLE handle,
JavaVM* vm,
jobject ref,
jmethodID methodID) : engineFace(face),
ivwRes(res),
instHandle(handle),
jvm(vm),
objRef(ref),
wakeupCbMethodId(methodID) {
}
};
int wakeupCbFunc(void* pUserParam, const char* pIvwParam)
{
LOG_D("wakeup result=%s", pIvwParam);
if (nullptr == pUserParam) {
LOG_E("user param is null");
return -1;
}
EngineContext* context = (EngineContext*) pUserParam;
JNIEnv* pEnv = nullptr;
if ((context->jvm)->GetEnv((void**) &pEnv, JNI_VERSION_1_4) != JNI_OK) {
LOG_E("get current jni env failed");
return -1;
}
string resultStr = pIvwParam;
jstring result = pEnv->NewStringUTF(resultStr.c_str());
pEnv->CallVoidMethod(context->objRef, context->wakeupCbMethodId, result);
return 0;
}
int loadIvwResource(PIVWEngineFace engineFace, JNIEnv *pEnv, jstring &resPath)
{
if (nullptr == engineFace) {
LOG_E("engine is null");
return -1;
}
const char* resPathChar = pEnv->GetStringUTFChars(resPath, 0);
string resPathStr = resPathChar;
pEnv->ReleaseStringUTFChars(resPath, resPathChar);
bool isFile = true;
if (!FileUtil::isPathExist(resPathStr, isFile)) {
LOG_E("path %s not exist", resPathStr.c_str());
return -1;
} else {
if (!isFile) {
LOG_E("path %s is not file", resPathStr.c_str());
return -1;
}
}
long resSize = FileUtil::getFileSizeInBytes(resPathStr);
if (resSize <= 0) {
LOG_E("%s is empty", resPathStr.c_str());
return -1;
}
IvwRes* res = new IvwRes(resSize);
long readCount = FileUtil::readFileToBuffer(resPathStr, res->buffer, resSize);
if (readCount != resSize) {
LOG_E("read %s failed", resPathStr.c_str());
res->release();
delete res;
return -1;
}
char* resBuffer = res->buffer;
if (resBuffer[0] == 'I' && resBuffer[3] == 'Y' && resBuffer[6] == 'K') {
int ret = engineFace->IvwLoadResource(resBuffer, res->size, 1);
if (0 != ret) {
LOG_E("load %s failed, ret=%d", resPathStr.c_str(), ret);
res->release();
delete res;
return -1;
} else {
LOG_D("load %s success", resPathStr.c_str());
}
} else {
}
if (nullptr != res) {
res->release();
delete res;
}
return 0;
}
PIVWEngineFace createAndInitEngine()
{
PIVWEngineFace face = nullptr;
int ret = CreateIVWEngine(nullptr, &face);
if (IVW_ERROR_SUCCESS != ret) {
LOG_E("create engine failed, ret=%d", ret);
} else {
face->IvwInit(nullptr, nullptr);
LOG_D("create engine success");
}
return face;
}
JNIEXPORT jlong JNICALL Java_com_iflytek_cyber_iot_show_core_ivw_IVWEngine_jni_1create
(JNIEnv* pEnv, jobject obj, jstring resPath, jstring wakeupCbName)
{
PIVWEngineFace engineFace = createAndInitEngine();
if (nullptr == engineFace) {
LOG_E("engine is null");
return INVALID_HANDLE;
}
LOG_D("create engine success");
int ret = loadIvwResource(engineFace, pEnv, resPath);
if (-1 == ret) {
LOG_E("load ivw resource failed");
DestroyIVWEngine(engineFace);
return INVALID_HANDLE;
}
IVW_INSTHANDLE instHandle = nullptr;
ret = engineFace->IvwCreateInst(&instHandle);
if (IVW_ERROR_SUCCESS != ret) {
LOG_E("create instance failed, ret=%d", ret);
DestroyIVWEngine(engineFace);
return INVALID_HANDLE;
} else {
LOG_D("create engine instance success");
}
JavaVM* vm;
pEnv->GetJavaVM(&vm);
jobject ref = pEnv->NewGlobalRef(obj);
jclass engineCls = pEnv->GetObjectClass(obj);
const char* wakeupCbNameChar = pEnv->GetStringUTFChars(wakeupCbName, 0);
jmethodID methodId = pEnv->GetMethodID(engineCls, wakeupCbNameChar,
SIGNATURE_WAKEUP_CB);
if (nullptr == methodId) {
LOG_E("can't find method %s with signature %s", wakeupCbNameChar, SIGNATURE_WAKEUP_CB);
pEnv->ReleaseStringUTFChars(wakeupCbName, wakeupCbNameChar);
DestroyIVWEngine(engineFace);
pEnv->DeleteGlobalRef(ref);
return INVALID_HANDLE;
}
EngineContext* engineEnv = new EngineContext(engineFace, nullptr, instHandle, vm, ref, methodId);
pEnv->ReleaseStringUTFChars(wakeupCbName, wakeupCbNameChar);
// 设置用户参数,唤醒回调时会带上
engineFace->IvwSetInstParam(engineEnv->instHandle,
IVW_PARAM_RESULT_CB_USERPARAM,
(void*) engineEnv,
sizeof(void*));
// 设置唤醒回调
engineFace->IvwSetInstParam(engineEnv->instHandle,
IVW_PARAM_WAKEUPCALLBACK,
(void*) wakeupCbFunc,
sizeof(void*));
return (jlong) engineEnv;
}
JNIEXPORT void JNICALL Java_com_iflytek_cyber_iot_show_core_ivw_IVWEngine_jni_1destroy
(JNIEnv* pEnv, jclass thiz, jlong handle)
{
if (INVALID_HANDLE == handle) {
LOG_E("invalid engine env handle, destroy failed");
return;
}
EngineContext* context = (EngineContext*) handle;
(context->engineFace)->IvwDestroyInst(context->instHandle);
(context->engineFace)->IvwFini();
DestroyIVWEngine(context->engineFace);
pEnv->DeleteGlobalRef(context->objRef);
delete context;
LOG_D("engine destroyed");
}
JNIEXPORT jint JNICALL Java_com_iflytek_cyber_iot_show_core_ivw_IVWEngine_jni_1set_1cmlevel
(JNIEnv* pEnv, jclass thiz, jlong handle, jint level)
{
if (INVALID_HANDLE == handle) {
LOG_E("invalid engine context, set CMLevel failed");
return -1;
}
EngineContext* context = (EngineContext*) handle;
return (context->engineFace)->IvwSetInstParam(context->instHandle,
IVW_PARAM_CM_LEVEL, &level, sizeof(int));
}
JNIEXPORT jint JNICALL Java_com_iflytek_cyber_iot_show_core_ivw_IVWEngine_jni_1set_1keywordncm
(JNIEnv* pEnv, jclass thiz, jlong handle, jstring ncm)
{
if (INVALID_HANDLE == handle) {
LOG_E("invalid engine context, set keyword ncm failed");
return -1;
}
const char* ncmChar = pEnv->GetStringUTFChars(ncm, 0);
EngineContext* context = (EngineContext*) handle;
int ret = (context->engineFace)->IvwSetInstParam(context->instHandle,
IVW_PARAM_KEYWORD_NCM, (void*) ncmChar, strlen(ncmChar));
pEnv->ReleaseStringUTFChars(ncm, ncmChar);
return ret;
}
JNIEXPORT jint JNICALL Java_com_iflytek_cyber_iot_show_core_ivw_IVWEngine_jni_1start
(JNIEnv* pEnv, jclass thiz, jlong handle)
{
int ret = -1;
if (INVALID_HANDLE == handle) {
LOG_E("invalid engine context, start failed");
return ret;
}
EngineContext* context = (EngineContext*) handle;
ret = (context->engineFace)->IvwStartInst((IVW_INSTHANDLE) context->instHandle);
LOG_D("engine instance started");
return ret;
}
JNIEXPORT jint JNICALL Java_com_iflytek_cyber_iot_show_core_ivw_IVWEngine_jni_1write
(JNIEnv* pEnv, jclass thiz, jlong handle, jbyteArray buffer, jint size)
{
int ret = -1;
if (INVALID_HANDLE == handle) {
LOG_E("invalid engine context, write failed");
return ret;
}
EngineContext* context = (EngineContext*) handle;
char* bufferChar = (char*) pEnv->GetByteArrayElements(buffer, 0);
ret = (context->engineFace)->IvwWriteInst((IVW_INSTHANDLE) context->instHandle, bufferChar, size);
pEnv->ReleaseByteArrayElements(buffer, (jbyte*) bufferChar, 0);
return ret;
}
JNIEXPORT jint JNICALL Java_com_iflytek_cyber_iot_show_core_ivw_IVWEngine_jni_1stop
(JNIEnv* pEnv, jclass thiz, jlong handle)
{
int ret = -1;
if (INVALID_HANDLE == handle) {
LOG_E("invalid engine context, stop failed");
return ret;
}
EngineContext* context = (EngineContext*) handle;
ret = (context->engineFace)->IvwStopInst((IVW_INSTHANDLE) context->instHandle);
LOG_D("engine instance stopped");
return ret;
}
JNIEXPORT void JNICALL Java_com_iflytek_cyber_iot_show_core_ivw_IVWEngine_jni_1set_1log
(JNIEnv* pEnv, jclass thiz, jboolean isOn)
{
setLog(isOn);
}
JNIEXPORT jstring JNICALL Java_com_iflytek_cyber_iot_show_core_ivw_IVWEngine_jni_1get_1version
(JNIEnv* pEnv, jclass thiz, jlong handle)
{
if (INVALID_HANDLE == handle) {
LOG_E("invalid engine context, get vesion failed");
return nullptr;
}
EngineContext* context = (EngineContext*) handle;
int len = 100;
char version[100] = {0};
context->engineFace->IvwGetVersion(version, &len);
return pEnv->NewStringUTF(version);
}
<file_sep>package com.iflytek.cyber.evs.sdk.codec.audio
/**
* 音频编码抽象类。
*/
abstract class AudioCodec(val codeMode: Int) {
companion object {
const val CODEC_ENCODE = 1
const val CODEC_DECODE = 2
}
protected var sampleRate: Int = 16000
protected var mode: Int = 0
protected var quality: Int = 0
var formatName: String = ""
fun isEncoder(): Boolean {
return codeMode == CODEC_ENCODE
}
fun isDecoder(): Boolean {
return codeMode == CODEC_DECODE
}
/**
* 编码。
* @param data 原始音频
* @param dataLen 音频长度,必须为20ms音频长度(对应16000采样的音频640字节)的整数倍
* @param buffer 编码缓存区
* @param bufferLen 缓存区长度
* @return 编码后的长度,负值表示出错
*/
abstract fun encode(data: ByteArray, dataLen: Int, buffer: ByteArray, bufferLen: Int): Int
abstract fun decode(data: ByteArray, dataLen: Int, buffer: ByteArray, bufferLen: Int): Int
abstract fun destroy()
}<file_sep>package com.iflytek.cyber.iot.show.core.model
data class RecommendModel(val id: Int?, val title: String?,
val summary: String?, val backgroundUrl: String?)<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.dp2Px
import kotlin.math.abs
class InterceptRecyclerView(context: Context, attrs: AttributeSet?) : RecyclerView(context, attrs) {
/*override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
if (childCount == 0) {
return super.onInterceptTouchEvent(e)
}
var targetChild: View? = null
val loc = IntArray(2)
for (i in childCount - 1..0) {
val childParent = getChildAt(i) as ViewGroup
var child: View? = null
if (childParent.childCount > 0) {
child = childParent.getChildAt(0)
}
if (child == null) {
return super.onInterceptTouchEvent(e)
}
child.getLocationInWindow(loc)
if (e.x >= loc[0] && e.x <= loc[0] + child.measuredWidth &&
e.y >= loc[1] && e.y <= loc[1] + child.measuredHeight
) {
targetChild = child
break
}
}
Log.e("InterceptRecycler", "target child: " + targetChild.toString())
if (targetChild != null && targetChild is ViewPager2) {
return false
}
return super.onInterceptTouchEvent(e)
}*/
/*override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
if (childCount == 0) {
return super.onInterceptTouchEvent(e)
}
val childParent = findChildViewUnder(e.x, e.y) as ViewGroup
var targetChild: View? = null
val loc = IntArray(2)
if (childParent.childCount > 0) {
var child: View? = null
if (childParent.childCount > 0) {
child = childParent.getChildAt(0)
}
if (child == null) {
return super.onInterceptTouchEvent(e)
}
child.getLocationInWindow(loc)
if (e.x >= loc[0] && e.x <= loc[0] + child.measuredWidth &&
e.y >= loc[1] && e.y <= loc[1] + child.measuredHeight
) {
targetChild = child
}
}
if (targetChild != null && targetChild is ViewPager2) {
return false
}
return super.onInterceptTouchEvent(e)
}*/
/*override fun onInterceptTouchEvent(e: MotionEvent?): Boolean {
return false
}*/
private var threshold = 0
private var touchX = 0f
override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
val view = findChildViewUnder(e.x, e.y)
if (view?.id != R.id.main_item) {
return super.onInterceptTouchEvent(e)
}
val viewPager2 = (view as ViewGroup).findViewById<ViewPager2>(R.id.view_pager)
if (e.x > 0 && e.x < viewPager2.measuredWidth && e.y > 0 && e.y < viewPager2.measuredHeight) {
threshold = viewPager2.measuredWidth
} else {
threshold = 8.dp2Px()
}
when (e.action) {
MotionEvent.ACTION_DOWN -> {
touchX = e.rawX
}
MotionEvent.ACTION_MOVE -> {
val currentX = e.rawX
val distance = abs(currentX - touchX)
return if (distance > threshold) {
super.onInterceptTouchEvent(e)
} else {
false
}
}
}
return super.onInterceptTouchEvent(e)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.graphics.BitmapFactory
import android.widget.ImageView
class FrameAnimation(
private val iv: ImageView,
private val frameRes: IntArray,
private val duration: Long,
isRepeat: Boolean
) {
private var mIsRepeat: Boolean = isRepeat
/**
* 每帧动画的播放间隔数组
*/
private var mDurations: IntArray? = null
/**
* 下一遍动画播放的延迟时间
*/
private var mDelay: Int = 0
private var mLastFrame: Int = 0
private var mNext: Boolean = false
var isPause: Boolean = false
private set
private var mCurrentSelect: Int = 0
private var mCurrentFrame: Int = 0
private val options: BitmapFactory.Options = BitmapFactory.Options()
init {
this.mLastFrame = frameRes.size - 1
options.inMutable = true
options.inBitmap = BitmapFactory.decodeResource(iv.resources, frameRes[0], options)
}
fun startAnimation() {
play(0)
}
fun stopAnimation() {
isPause = true
}
private fun play(index: Int) {
val runnable = FrameRunnable()
runnable.currentFrame = index
iv.postDelayed(runnable, duration)
}
inner class FrameRunnable : Runnable {
var currentFrame = 0
override fun run() {
if (isPause) {
mCurrentFrame = currentFrame
return
}
// iv.setImageResource(frameRes[currentFrame])
val bitmap = BitmapFactory.decodeResource(iv.resources, frameRes[currentFrame], options)
iv.setImageBitmap(bitmap)
if (currentFrame == mLastFrame) {
if (mIsRepeat) {
currentFrame = 0
play(0)
}
} else {
currentFrame++
play(currentFrame)
}
}
}
companion object {
private val SELECTED_A = 1
private val SELECTED_B = 2
private val SELECTED_C = 3
private val SELECTED_D = 4
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.app.ProgressDialog
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.JsonParser
import com.iflytek.cyber.evs.sdk.auth.AuthDelegate
import com.iflytek.cyber.iot.show.core.BuildConfig
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.EngineService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.DeviceApi
import com.iflytek.cyber.iot.show.core.utils.*
import com.iflytek.cyber.iot.show.core.widget.StyledAlertDialog
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class AboutFragment2 : BaseFragment(), PageScrollable {
private var recyclerView: RecyclerView? = null
private val aboutList = mutableListOf<Item>()
private val adapter = ListAdapter()
private var deviceName: String? = null
private var backCount = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_about_2, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
recyclerView = view.findViewById(R.id.about_list)
recyclerView?.itemAnimator = DefaultItemAnimator()
recyclerView?.adapter = adapter
requestDeviceInfo()
}
override fun onSupportVisible() {
super.onSupportVisible()
// init about item
updateAboutContent()
}
override fun scrollToNext(): Boolean {
recyclerView?.let { recyclerView ->
val lastItem =
(recyclerView.layoutManager as? LinearLayoutManager)?.findLastCompletelyVisibleItemPosition()
val itemCount = adapter.itemCount
if (lastItem == itemCount - 1 || itemCount == 0) {
return false
} else {
recyclerView.smoothScrollBy(0, recyclerView.height)
}
}
return true
}
override fun scrollToPrevious(): Boolean {
recyclerView?.let { recyclerView ->
val scrollY = recyclerView.computeVerticalScrollOffset()
val itemCount = adapter.itemCount
if (scrollY == 0 || itemCount == 0) {
return false
} else {
recyclerView.smoothScrollBy(0, -recyclerView.height)
}
}
return true
}
private fun requestDeviceInfo() {
getDeviceApi()?.get()?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
t.printStackTrace()
}
override fun onResponse(
call: Call<ResponseBody>,
response: Response<ResponseBody>
) {
if (response.isSuccessful) {
val responseBody = response.body()
val body = responseBody?.string()
val json = JsonParser().parse(body).asJsonObject
val alias = json.get("alias")?.asString
val speakerName = json.get("speaker")?.asString
this@AboutFragment2.deviceName = alias
responseBody?.close()
post {
updateAboutContent()
}
} else {
Log.d("About", "request failed: ${response.code()}")
}
}
})
}
private fun updateAboutContent() {
val context = context ?: return
val prefSize = aboutList.size
aboutList.clear()
deviceName?.let {
val deviceNameItem = Item("设备名称", it)
aboutList.add(deviceNameItem)
}
DeviceUtils.getIvwVersion().let {
val ivwVersionItem =
if (it.isNullOrEmpty())
Item("唤醒词引擎版本", "暂不支持显示")
else
Item("唤醒词引擎版本", it)
aboutList.add(ivwVersionItem)
}
try {
@Suppress("DEPRECATION")
(if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O_MR1)
Build.SERIAL
else Build.getSerial())?.let {
val serialItem = Item("设备序列号", it)
aboutList.add(serialItem)
}
} catch (e: SecurityException) {
e.printStackTrace()
}
WifiUtils.getIPAddress(context)?.let {
val ipAddressItem = Item("IP 地址", it)
aboutList.add(ipAddressItem)
}
WifiUtils.getMacAddress(context)?.let {
val macAddressItem = Item("MAC 地址", it)
aboutList.add(macAddressItem)
}
val versionItem =
Item(getString(R.string.system_version), "${DeviceUtils.getSystemVersionName()}(${DeviceUtils.getSystemVersion()})")
aboutList.add(versionItem)
aboutList.add(Item(getString(R.string.factory_reset), ""))
if (prefSize > 0) {
adapter.notifyItemRangeChanged(0, prefSize)
if (aboutList.size > prefSize) {
adapter.notifyItemRangeInserted(prefSize, aboutList.size)
}
} else {
adapter.notifyItemRangeInserted(0, aboutList.size)
}
}
private fun getDeviceApi(): DeviceApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(DeviceApi::class.java)
}
private inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = AboutItemViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_two_lines, parent, false)
)
holder.itemView.setOnClickListener {
val position = holder.adapterPosition
val item = aboutList[position]
when (item.title) {
getString(R.string.factory_reset) -> {
val fragmentManager = fragmentManager ?: return@setOnClickListener
StyledAlertDialog.Builder()
.setTitle(getString(R.string.factory_reset))
.setMessage(getString(R.string.factory_reset_message))
.setPositiveButton(
getString(R.string.ensure),
View.OnClickListener { view ->
val context = view.context
val stopPlayers= Intent(context, EngineService::class.java)
stopPlayers.action = EngineService.ACTION_REQUEST_STOP_AUDIO_PLAYER
context.startService(stopPlayers)
val progressDialog = ProgressDialog(context)
progressDialog.setMessage("正在恢复")
progressDialog.show()
CoreApplication.from(context).createApi(DeviceApi::class.java)
?.postRestoreFactory()
?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(
call: Call<ResponseBody>,
t: Throwable
) {
t.printStackTrace()
try {
progressDialog.dismiss()
} catch (tInside: Throwable) {
}
Toast.makeText(
context,
"恢复出厂设置服务端验证失败,请稍后再试",
Toast.LENGTH_SHORT
).show()
}
override fun onResponse(
call: Call<ResponseBody>,
response: Response<ResponseBody>
) {
try {
progressDialog.dismiss()
} catch (t: Throwable) {
}
if (!response.isSuccessful) {
Toast.makeText(
context,
"恢复出厂设置服务端验证失败,请稍后再试",
Toast.LENGTH_SHORT
).show()
}
}
})
})
.setNegativeButton(getString(R.string.cancel), null)
.setWarningAction(true)
.show(fragmentManager)
}
}
}
return holder
}
override fun getItemCount(): Int {
return aboutList.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is AboutItemViewHolder) {
holder.tvTitle.text = aboutList[position].title
holder.tvSummary.text = aboutList[position].summary
holder.tvSummary.isVisible = aboutList[position].summary.isNotEmpty()
}
}
}
private class AboutItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvTitle: TextView = itemView.findViewById(R.id.title)
val tvSummary: TextView = itemView.findViewById(R.id.summary)
}
private data class Item(val title: String, val summary: String)
}<file_sep>package com.iflytek.cyber.iot.show.core.template
object Constant {
const val PAYLOAD_TYPE = "type"
const val PAYLOAD_MAIN_TITLE = "main_title"
const val PAYLOAD_SUB_TITLE = "sub_title"
const val PAYLOAD_BODY_TEXT = "body_text"
const val PAYLOAD_BODY_SUB_TEXT = "body_sub_text"
const val PAYLOAD_BODY_IMAGE_URL = "body_image_url"
const val PAYLOAD_BACKGROUND_IMAGE_URL = "background_image_url"
const val PAYLOAD_SKILL_ICON_URL = "skill_icon_url"
const val PAYLOAD_TEMPLATE_ID = "template_id"
const val PAYLOAD_LEFT_TEXT = "left_text"
const val PAYLOAD_LIST_ITEMS = "list_items"
const val PAYLOAD_RIGHT_TEXT = "right_text"
const val PAYLOAD_BACK_BUTTON = "back_button"
const val PAYLOAD_OPTION_ELEMENTS = "option_elements"
const val PAYLOAD_ELEMENT_ID = "element_id"
const val PAYLOAD_PRIMARY_TEXT = "primary_text"
const val PAYLOAD_SECONDARY_TEXT = "secondary_text"
const val PAYLOAD_TERTIARY_TEXT = "tertiary_text"
const val PAYLOAD_OPTION_IMAGE_URL = "option_image_url"
const val PAYLOAD_CURRENT_WEATHER = "current_weather"
const val PAYLOAD_CONDITION = "condition"
const val PAYLOAD_DESCRIPTION = "description"
const val PAYLOAD_LOW_TEMPERATURE = "low_temperature"
const val PAYLOAD_HIGH_TEMPERATURE = "high_temperature"
const val PAYLOAD_ICON_URL = "icon_url"
const val PAYLOAD_WEATHER_FORECAST = "weather_forecast"
const val PAYLOAD_WEEKDAY = "weekday"
const val PAYLOAD_DATE = "date"
const val PAYLOAD_IMAGE_URL = "image_url"
const val BACK_BUTTON_VISIBLE = "VISIBLE"
const val BACK_BUTTON_HIDDEN = "HIDDEN"
const val TYPE_BODY_TEMPLATE_1 = "body_template_1"
const val TYPE_BODY_TEMPLATE_2 = "body_template_2"
const val TYPE_BODY_TEMPLATE_3 = "body_template_3"
const val TYPE_LIST_TEMPLATE_1 = "list_template_1"
const val TYPE_WEATHER_TEMPLATE = "weather_template"
const val TYPE_OPTION_TEMPLATE_1 = "option_template_1"
const val TYPE_OPTION_TEMPLATE_2 = "option_template_2"
const val TYPE_OPTION_TEMPLATE_3 = "option_template_3"
}
<file_sep>package com.iflytek.cyber.iot.show.core.impl.playback
import com.iflytek.cyber.evs.sdk.agent.PlaybackController
class EvsPlaybackController private constructor() : PlaybackController() {
companion object {
private var instance: EvsPlaybackController? = null
fun get(): EvsPlaybackController {
instance?.let {
return it
} ?: run {
val controller = EvsPlaybackController()
instance = controller
return controller
}
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.ItemViewBinder
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.Result
import com.iflytek.cyber.iot.show.core.model.SearchResult
class AudioTypeViewBinder(
val onItemClick: (Result) -> Unit,
val onMoreClick: (ArrayList<Result>) -> Unit
) :
ItemViewBinder<SearchResult, AudioTypeViewBinder.AudioTypeHolder>() {
private var keyword: String = ""
fun setKeyword(keyword: String) {
this.keyword = keyword
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): AudioTypeHolder {
val view = inflater.inflate(R.layout.item_search_audio, parent, false)
return AudioTypeHolder(view)
}
override fun onBindViewHolder(holder: AudioTypeHolder, item: SearchResult) {
if (item.results != null) {
holder.setupList(item.results)
}
}
inner class AudioTypeHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val audioList = itemView.findViewById<RecyclerView>(R.id.audio_list)
val adapter = AudioTypeListAdapter({
onItemClick.invoke(it)
}, {
onMoreClick.invoke(it)
})
fun setupList(results: ArrayList<Result>) {
adapter.setItems(results, keyword)
audioList.adapter = adapter
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.SkillApi
import com.iflytek.cyber.iot.show.core.model.Skill
import com.iflytek.cyber.iot.show.core.model.SkillDetail
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
import com.iflytek.cyber.iot.show.core.utils.dp2Px
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.math.max
import kotlin.math.min
class SkillDetailFragment : BaseFragment(), PageScrollable {
private lateinit var tvSkillName: TextView
private lateinit var tvSkillDesc: TextView
private lateinit var tvDev: TextView
private lateinit var tvVersion: TextView
private lateinit var tvDate: TextView
private lateinit var ivSkillIcon: ImageView
private lateinit var recyclerView: RecyclerView
private var scrollView: NestedScrollView? = null
private var contentContainer: View? = null
private var backCount = 0
companion object {
fun newInstance(skill: Skill): SkillDetailFragment {
return SkillDetailFragment().apply {
arguments = bundleOf(Pair("skill", skill))
}
}
fun newInstance(skillDetail: SkillDetail): SkillDetailFragment {
return SkillDetailFragment().apply {
arguments = bundleOf(Pair("skill_detail", skillDetail))
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return LayoutInflater.from(context)
.inflate(R.layout.fragment_skill_detail, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
launcher?.onBackPressed()
}
scrollView = view.findViewById(R.id.scroll_view)
contentContainer = view.findViewById(R.id.content_container)
tvSkillName = view.findViewById(R.id.tv_skill_name)
tvSkillDesc = view.findViewById(R.id.tv_skill_desc)
tvDev = view.findViewById(R.id.tv_dev)
tvVersion = view.findViewById(R.id.tv_version)
tvDate = view.findViewById(R.id.tv_date)
ivSkillIcon = view.findViewById(R.id.iv_skill_icon)
recyclerView = view.findViewById(R.id.example_list)
val skillDetail = arguments?.getParcelable<SkillDetail>("skill_detail")
if (skillDetail != null) {
setupUI(skillDetail)
} else {
val skill = arguments?.getParcelable<Skill>("skill")
skill?.let { loadDetail(it.id) }
}
}
private fun setupUI(detail: SkillDetail) {
Glide.with(ivSkillIcon.context)
.load(detail.icon)
.apply(
RequestOptions()
.transform(RoundedCornersTransformation(16.dp2Px(), 0))
)
.into(ivSkillIcon)
tvSkillName.text = detail.name
tvSkillDesc.text = detail.description
tvDate.text = detail.updatedTime
tvVersion.text = detail.version
tvDev.text = detail.developer
detail.examples?.let { examples ->
val adapter = ExampleAdapter(examples)
recyclerView.adapter = adapter
}
}
private fun loadDetail(id: String) {
getSkillApi()?.getSkillDetail(id)?.enqueue(object : Callback<SkillDetail> {
override fun onResponse(call: Call<SkillDetail>, response: Response<SkillDetail>) {
if (response.isSuccessful) {
val detail = response.body()
detail?.let { setupUI(it) }
}
}
override fun onFailure(call: Call<SkillDetail>, t: Throwable) {
t.printStackTrace()
}
})
}
private fun getSkillApi(): SkillApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(SkillApi::class.java)
} else {
null
}
}
override fun scrollToNext(): Boolean {
scrollView?.let { scrollView ->
val pageHeight = scrollView.height
val scrollY = scrollView.scrollY
val contentHeight = contentContainer?.height ?: 0
if (scrollY == contentHeight - pageHeight) {
return false
}
val target = min(contentHeight - pageHeight, scrollY + pageHeight)
smoothScrollTo(target)
return true
} ?: run {
return false
}
}
override fun scrollToPrevious(): Boolean {
scrollView?.let { scrollView ->
val pageHeight = scrollView.height
val scrollY = scrollView.scrollY
if (scrollY == 0) {
return false
}
val target = max(0, scrollY - pageHeight)
smoothScrollTo(target)
return true
} ?: run {
return false
}
}
private fun smoothScrollTo(scrollY: Int) {
scrollView?.isSmoothScrollingEnabled = true
scrollView?.smoothScrollTo(0, scrollY)
}
inner class ExampleAdapter(val examples: ArrayList<String?>) :
RecyclerView.Adapter<ExampleAdapter.ExampleHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.item_example, parent, false)
return ExampleHolder(view)
}
override fun getItemCount(): Int {
return examples.size
}
override fun onBindViewHolder(holder: ExampleHolder, position: Int) {
holder.desc.text = examples[position]
}
inner class ExampleHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val desc = itemView.findViewById<TextView>(R.id.tv_example)
}
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
abstract class SelfBroadcastReceiver(vararg actions: String) : BroadcastReceiver() {
private val filter = IntentFilter()
private var registered = false
init {
for (action in actions) {
filter.addAction(action)
}
}
protected abstract fun onReceiveAction(action: String, intent: Intent)
fun getFilter() = filter
override fun onReceive(context: Context, intent: Intent?) {
intent ?: return
val action = intent.action
if (!action.isNullOrEmpty()) {
onReceiveAction(action, intent)
}
}
fun register(context: Context?) {
if (!registered) {
context?.registerReceiver(this, filter)
registered = true
}
}
fun unregister(context: Context?) {
if (registered) {
registered = false
context?.unregisterReceiver(this)
}
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.recommend
import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.iflytek.cyber.iot.show.core.CoreApplication
import okhttp3.Request
import java.lang.Exception
import com.google.gson.JsonParser
object RecommendAgent {
private const val TAG = "RecommendAgent"
fun <T> getRecommendList(context: Context, url: String, cls : Class<T>): List<T>? {
val client = CoreApplication.from(context).getClient()
val request = Request.Builder().get()
.url(url)
.build()
if (client != null) {
val call = client.newCall(request)
try {
val response = call.execute()
if (response.isSuccessful) {
response.body()?.let {
val result = it.string()
val list = ArrayList<T>()
try {
val array = JsonParser().parse(result).asJsonArray
for (jsonElement in array) {
list.add(Gson().fromJson<T>(jsonElement, cls))
}
} catch (e: Exception) {
e.printStackTrace()
}
return list
}
} else {
Log.d(TAG, "error=${response.code()}")
}
} catch (e1: Exception) {
e1.printStackTrace()
}
}
return null
}
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.content.Context
import android.os.Environment
import android.os.StatFs
import android.util.Log
import java.io.File
object CleanerUtils {
private const val TAG = "CleanerUtils"
fun clearRecordDebugFiles() {
TerminalUtils.execute("rm /sdcard/iflytek_test_audio.pcm")
TerminalUtils.execute("rm /sdcard/recordtest.log")
}
fun clearCache(context: Context) {
// clear data/data/package/cache
val internalCache = context.cacheDir
internalCache.deleteRecursively()
// clear sdcard/Android/data/package/cache
val externalCache = context.externalCacheDir
externalCache?.listFiles()?.map {
if (it.isFile)
it.delete()
}
}
fun clearWakeWordCache(context: Context) {
// clear sdcard/Android/data/package/cache/wakeword
val externalCache = context.externalCacheDir
val wakeWordDirectory = File("$externalCache/wakeword")
Log.d(
TAG,
"exits ${wakeWordDirectory.exists()}, isDirectory ${wakeWordDirectory.isDirectory}"
)
if (wakeWordDirectory.exists() && wakeWordDirectory.isDirectory) {
wakeWordDirectory.deleteRecursively()
}
}
private fun externalMemoryAvailable(): Boolean {
return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
}
fun getSdcardFreeSpace(): Long {
return if (externalMemoryAvailable()) {
val path = Environment.getExternalStorageDirectory()
val stat = StatFs(path.path)
val blockSize = stat.blockSizeLong
val availableBlocks = stat.availableBlocksLong
availableBlocks * blockSize
} else {
-1
}
}
fun getSdcardFullSpace(): Long {
return if (externalMemoryAvailable()) {
val path = Environment.getExternalStorageDirectory()
val stat = StatFs(path.path)
val blockSize = stat.blockSizeLong
val totalBlocks = stat.blockCountLong
totalBlocks * blockSize
} else {
-1
}
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.FrameLayout
import androidx.core.os.postDelayed
class ExFrameLayout(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs, 0) {
private val timeHandler = Handler()
private var onCloseListener: OnCloseListener? = null
fun setOnCloseListener(onCloseListener: OnCloseListener) {
this.onCloseListener = onCloseListener
}
init {
timeHandler.postDelayed(5 * 60 * 1000) {
timeHandler.removeCallbacksAndMessages(null)
onCloseListener?.onClose()
}
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
timeHandler.removeCallbacksAndMessages(null)
timeHandler.postDelayed(5 * 60 * 1000) {
timeHandler.removeCallbacksAndMessages(null)
onCloseListener?.onClose()
}
return super.onInterceptTouchEvent(ev)
}
interface OnCloseListener {
fun onClose()
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.util.Log
import java.io.BufferedReader
import java.io.InputStreamReader
object TerminalUtils {
fun execute(command: String): String? {
try {
val runtime = Runtime.getRuntime()
val process = runtime.exec(command)
val reader = BufferedReader(InputStreamReader(process.inputStream))
val respBuff = StringBuffer()
val buff = CharArray(1024)
var count = reader.read(buff)
while (count != -1) {
respBuff.append(buff, 0, count)
count = reader.read(buff)
}
reader.close()
val result = respBuff.toString().trim()
Log.v(TerminalUtils::class.java.simpleName, "COMMAND $command result: $result")
return result
} catch (t: Throwable) {
t.printStackTrace()
}
return null
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.FrameLayout
import com.iflytek.cyber.iot.show.core.utils.dp2Px
import kotlin.math.abs
class ProgressFrameLayout(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {
private var touchY = 0f
private var viewHeight = 0
private var firstTouchY = 0f
private var maxProgress = 100
private var progressRatio = 0f
private var currentProgress = 0f
private var limitDistance = 2.dp2Px()
private val configuration = ViewConfiguration.get(context)
private var touchSlop = configuration.scaledTouchSlop * 0.8f
private var onTouchProgressChangeListener: OnTouchProgressChangeListener? = null
fun setOnTouchProgressChangeListener(onTouchProgressChangeListener: OnTouchProgressChangeListener) {
this.onTouchProgressChangeListener = onTouchProgressChangeListener
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
viewHeight = h
progressRatio = maxProgress.toFloat() / viewHeight.toFloat() / 100f
}
fun setProgress(progress: Float) {
currentProgress = progress
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
touchY = event.y
firstTouchY = event.y
onTouchProgressChangeListener?.onDown()
}
MotionEvent.ACTION_MOVE -> {
val moveY = event.y
val distance = touchY - moveY
val progress: Float
progress = if (distance < 0) {
-2f
} else {
2f
}
if (abs(distance) > touchSlop) {
currentProgress += progress
if (currentProgress > maxProgress) {
currentProgress = maxProgress.toFloat()
} else if (currentProgress < 0) {
currentProgress = 0f
}
onTouchProgressChangeListener?.onTouchProgressChanged(currentProgress.toInt())
touchY = moveY
} else {
return true
}
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
if (abs(firstTouchY - event.y) > touchSlop) {
onTouchProgressChangeListener?.onStopTouch()
} else {
onTouchProgressChangeListener?.onClick()
}
}
}
return true
}
interface OnTouchProgressChangeListener {
fun onDown()
fun onTouchProgressChanged(progress: Int)
fun onStopTouch()
fun onClick()
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.core.view.postDelayed
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.SkillPagerAdapter
import com.iflytek.cyber.iot.show.core.api.SkillApi
import com.iflytek.cyber.iot.show.core.model.SkillSection
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
class SkillsFragment : BaseFragment(), PageScrollable {
private lateinit var tabLayout: TabLayout
private lateinit var viewPager: ViewPager2
private var adapter: SkillPagerAdapter? = null
private var backCount = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_skills, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tabLayout = view.findViewById(R.id.tab_layout)
viewPager = view.findViewById(R.id.view_pager)
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
view.postDelayed(200) {
loadSkillSections()
}
view.findViewById<View>(R.id.refresh)?.setOnClickListener {
loadSkillSections()
}
}
private fun setupTabLayout(skillSections: ArrayList<SkillSection>) {
if (!isAdded) {
return
}
adapter = SkillPagerAdapter(this)
adapter?.addItems(skillSections)
viewPager.adapter = adapter
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = skillSections[position].title
}.attach()
}
private fun loadSkillSections() {
getSkillApi()?.getSkillSections()?.enqueue(object : Callback<ArrayList<SkillSection>> {
override fun onResponse(
call: Call<ArrayList<SkillSection>>,
response: Response<ArrayList<SkillSection>>
) {
if (response.isSuccessful) {
val skillSections = response.body()
skillSections?.let {
setupTabLayout(it)
}
view?.findViewById<View>(R.id.error_container)?.isVisible = false
} else {
view?.findViewById<View>(R.id.error_container)?.let { errorContainer ->
errorContainer.isVisible = true
val errorText = errorContainer.findViewById<TextView>(R.id.error_text)
errorText?.text = "加载失败,请重试"
}
}
}
override fun onFailure(call: Call<ArrayList<SkillSection>>, t: Throwable) {
t.printStackTrace()
if (t is UnknownHostException) {
view?.findViewById<View>(R.id.error_container)?.let { errorContainer ->
errorContainer.isVisible = true
val errorText = errorContainer.findViewById<TextView>(R.id.error_text)
errorText?.text = "网络出了点小差,请检查网络后重试"
}
} else {
view?.findViewById<View>(R.id.error_container)?.let { errorContainer ->
errorContainer.isVisible = true
val errorText = errorContainer.findViewById<TextView>(R.id.error_text)
errorText?.text = "加载失败,请重试"
}
}
}
})
}
override fun scrollToNext(): Boolean {
val currentItem = viewPager.currentItem
if (currentItem < (adapter?.itemCount ?: 0) - 1 || currentItem < 0) {
viewPager.post {
viewPager.setCurrentItem(currentItem + 1, true)
}
return true
}
return false
}
override fun scrollToPrevious(): Boolean {
val currentItem = viewPager.currentItem
if (currentItem > 0) {
viewPager.post {
viewPager.setCurrentItem(currentItem - 1, true)
}
return true
}
return false
}
private fun getSkillApi(): SkillApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(SkillApi::class.java)
} else {
null
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.daimajia.swipe.SwipeLayout
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.Alert
class AlarmAdapter(private val onItemClickListener: (Alert) -> Unit,
private val onDeleteAlarmListener: (Alert, Int) -> Unit) : RecyclerView.Adapter<AlarmAdapter.AlarmHolder>() {
val alerts = ArrayList<Alert>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AlarmHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_alarm, parent, false)
return AlarmHolder(view)
}
override fun getItemCount(): Int {
return alerts.size
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: AlarmHolder, position: Int) {
val alert = alerts[position]
holder.alarm.text = alert.time
val description = if (alert.content.isNullOrEmpty()) {
alert.description
} else {
val content = if (alert.content?.length ?: 0 > 10) {
alert.content?.substring(0, 10) + "···"
} else {
alert.content
}
alert.description + ", " + content
}
holder.alarmDesc.text = description
holder.item.setOnClickListener {
onItemClickListener.invoke(alert)
}
holder.delete.setOnClickListener {
onDeleteAlarmListener.invoke(alert, position)
}
holder.swipeLayout.showMode = SwipeLayout.ShowMode.PullOut
}
class AlarmHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val alarm = itemView.findViewById<TextView>(R.id.tv_alarm)
val alarmDesc = itemView.findViewById<TextView>(R.id.tv_alarm_desc)
val item = itemView.findViewById<LinearLayout>(R.id.item)
val delete = itemView.findViewById<ImageView>(R.id.delete)
val swipeLayout = itemView.findViewById<SwipeLayout>(R.id.swipe_layout)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.template
import android.content.Context
import android.content.Intent
import android.view.View
import com.google.gson.JsonParser
import com.iflytek.cyber.iot.show.core.EngineService
import com.iflytek.cyber.iot.show.core.template.OptionTemplateView.OptionElement
object TemplateViewBuilder {
fun build(
context: Context,
payload: String,
onClickBackListener: View.OnClickListener? = null
): View? {
val json = JsonParser().parse(payload).asJsonObject
val templateId = json.get(Constant.PAYLOAD_TEMPLATE_ID).asString
return when (json.get(Constant.PAYLOAD_TYPE).asString) {
Constant.TYPE_BODY_TEMPLATE_1,
Constant.TYPE_BODY_TEMPLATE_2 -> {
BodyTemplateView1.Builder(context).payload(payload)
.onClickBackListener(onClickBackListener).build()
}
Constant.TYPE_BODY_TEMPLATE_3 -> {
BodyTemplateView3.Builder(context).payload(payload)
.onClickBackListener(onClickBackListener).build()
}
Constant.TYPE_LIST_TEMPLATE_1 -> {
ListTemplateView1.Builder(context).payload(payload)
.onClickBackListener(onClickBackListener).build()
}
Constant.TYPE_OPTION_TEMPLATE_1,
Constant.TYPE_OPTION_TEMPLATE_2,
Constant.TYPE_OPTION_TEMPLATE_3
-> {
OptionTemplateView.Builder(context).payload(payload)
.onElementSelectedListener(
object : OptionTemplateView.OnElementSelectedListener {
override fun onElementSelected(
parent: OptionTemplateView,
itemView: View,
position: Int,
element: OptionElement
) {
val intent = Intent(context, EngineService::class.java)
intent.action = EngineService.ACTION_SEND_TEMPLATE_ELEMENT_SELECTED
intent.putExtra(EngineService.EXTRA_ELEMENT_ID, element.elementId)
intent.putExtra(EngineService.EXTRA_TEMPLATE_ID, templateId)
context.startService(intent)
}
})
.onClickBackListener(onClickBackListener).build()
}
Constant.TYPE_WEATHER_TEMPLATE -> {
WeatherTemplateView.Builder(context).payload(payload)
.onClickBackListener(onClickBackListener).build()
}
else -> {
null
}
}
}
fun buildCustom(
context: Context,
html: String,
onClickBackListener: View.OnClickListener? = null,
overrideUrlLoadingCallback: CustomTemplateView.OverrideUrlLoadingCallback? = null
): View? {
return CustomTemplateView.Builder(context)
.setHtml(html)
.onClickBackListener(onClickBackListener)
.overrideUrlLoadingCallback(overrideUrlLoadingCallback)
.build()
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.Html
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.ReadWord
class SpeakEvaluationResultFragment : BaseFragment() {
companion object {
fun newInstance(
type: Int?,
readWordList: ArrayList<ReadWord>
): SpeakEvaluationResultFragment {
return SpeakEvaluationResultFragment().apply {
arguments = bundleOf(
Pair("type", type),
Pair("wordList", readWordList)
)
}
}
fun newInstance(
type: Int?,
readWord: ReadWord?,
punctuationList: ArrayList<String>
): SpeakEvaluationResultFragment {
return SpeakEvaluationResultFragment().apply {
arguments = bundleOf(
Pair("type", type),
Pair("word", readWord),
Pair("punctuationList", punctuationList)
)
}
}
}
private lateinit var resultList: RecyclerView
private lateinit var tvResultSentence: TextView
private lateinit var ivScore: ImageView
private lateinit var tvTotalScore: TextView
private lateinit var phoneScore: LinearLayout
private lateinit var toneScore: LinearLayout
private lateinit var tvPhoneSocre: TextView
private lateinit var tvToneScore: TextView
private lateinit var tvTitle: TextView
private lateinit var fluencyScore: LinearLayout
private lateinit var tvFluencyScore: TextView
private lateinit var englishArticleScore: LinearLayout
private lateinit var tvStandardScore: TextView
private lateinit var tvIntegrityScore: TextView
private lateinit var tvEnglishFluencyScore: TextView
private lateinit var tvAccuracyScore: TextView
private var type: Int? = null
private var punctuationList: ArrayList<String>? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_speak_evaluation_result, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
resultList = view.findViewById(R.id.result_list)
tvResultSentence = view.findViewById(R.id.tv_result_sentence)
ivScore = view.findViewById(R.id.iv_score)
tvTotalScore = view.findViewById(R.id.tv_total_score)
phoneScore = view.findViewById(R.id.phone_score)
toneScore = view.findViewById(R.id.tone_score)
tvPhoneSocre = view.findViewById(R.id.tv_phone_score)
tvToneScore = view.findViewById(R.id.tv_tone_score)
tvTitle = view.findViewById(R.id.tv_title)
fluencyScore = view.findViewById(R.id.fluency_score)
tvFluencyScore = view.findViewById(R.id.tv_fluency_score)
englishArticleScore = view.findViewById(R.id.english_article_score)
tvStandardScore = view.findViewById(R.id.tv_standard_score)
tvIntegrityScore = view.findViewById(R.id.tv_integrity_score)
tvEnglishFluencyScore = view.findViewById(R.id.tv_english_fluency_score)
tvAccuracyScore = view.findViewById(R.id.tv_accuracy_score)
view.findViewById<View>(R.id.back).setOnClickListener {
pop()
}
type = arguments?.getInt("type")
punctuationList = arguments?.getStringArrayList("punctuationList")
val wordList = arguments?.getParcelableArrayList<ReadWord>("wordList")
val readWord = arguments?.getParcelable<ReadWord>("word")
if (type == SpeakEvaluatingFragment.CHINESE_SINGLE_WORD_TYPE) {
if (wordList != null) {
setChineseSingleWordScore(wordList)
setupResultAdapter(wordList)
}
} else if (type == SpeakEvaluatingFragment.CHINESE_WORDS_TYPE) {
if (wordList != null) {
setChineseWordsScore(wordList)
setupResultAdapter(wordList)
}
} else if (type == SpeakEvaluatingFragment.ENGLISH_WORD_TYPE) {
if (wordList != null) {
setEnglishSingleWordScore(wordList)
setupResultAdapter(wordList)
}
} else if (type == SpeakEvaluatingFragment.CHINESE_SENTENCE_TYPE) {
if (readWord != null) {
setChineseSentenceScore(readWord)
setupSentenceResult(readWord)
}
} else if (type == SpeakEvaluatingFragment.ENGLISH_SENTENCE_TYPE) {
if (readWord != null) {
setEnglishSentenceScore(readWord)
setupEnglishSentenceResult(readWord)
}
} else if (type == SpeakEvaluatingFragment.ENGLISH_ARTICLE_TYPE) {
if (readWord != null) {
setEnglishArticleScore(readWord)
setupEnglishSentenceResult(readWord)
}
}
view.findViewById<View>(R.id.btn_again).setOnClickListener {
if (type != null) {
startWithPop(SpeakEvaluatingFragment.newInstance(type!!))
}
}
}
@SuppressLint("SetTextI18n")
private fun setChineseSingleWordScore(wordList: ArrayList<ReadWord>) {
var finalScore = 0f
wordList.forEach { readWord ->
val phoneScore = readWord.phoneScore ?: 0f
val toneScore = readWord.toneScore ?: 0f
finalScore += (phoneScore + toneScore) / 2f
}
finalScore /= 10f
tvTotalScore.text = String.format("%.2f", finalScore) + "分"
if (finalScore >= 60) {
ivScore.setImageResource(R.drawable.ic_img_bg_score_high)
} else {
ivScore.setImageResource(R.drawable.ic_img_bg_score_low)
}
setResultTitle(finalScore)
}
@SuppressLint("SetTextI18n")
private fun setChineseWordsScore(wordList: ArrayList<ReadWord>) {
phoneScore.isVisible = true
toneScore.isVisible = true
var finalScore = 0f
var totalPhoneScore = 0f
var totalToneScore = 0f
wordList.forEach { readWord ->
finalScore += readWord.totalScore ?: 0f
totalPhoneScore += readWord.phoneScore ?: 0f
totalToneScore += readWord.toneScore ?: 0f
}
finalScore /= 10f
tvTotalScore.text = String.format("%.2f", finalScore) + "分"
tvPhoneSocre.text = String.format("%.2f", (totalPhoneScore / 10f))
tvToneScore.text = String.format("%.2f", (totalToneScore / 10f))
if (finalScore >= 60) {
ivScore.setImageResource(R.drawable.ic_img_bg_score_high)
} else {
ivScore.setImageResource(R.drawable.ic_img_bg_score_low)
}
setResultTitle(finalScore)
}
@SuppressLint("SetTextI18n")
private fun setChineseSentenceScore(readWord: ReadWord) {
phoneScore.isVisible = true
toneScore.isVisible = true
fluencyScore.isVisible = true
tvPhoneSocre.text = readWord.phoneScore.toString()
tvToneScore.text = readWord.toneScore.toString()
tvFluencyScore.text = readWord.fluencyScore.toString()
tvTotalScore.text = readWord.totalScore.toString() + "分"
if (readWord.totalScore ?: 0f >= 60f) {
ivScore.setImageResource(R.drawable.ic_img_bg_score_high)
} else {
ivScore.setImageResource(R.drawable.ic_img_bg_score_low)
}
setResultTitle(readWord.totalScore ?: 0f)
}
private fun setResultTitle(finalScore: Float) {
when {
finalScore > 90 -> tvTitle.text = "你这么牛,让我膜拜一下可好?"
finalScore in 60.0..90.0 -> tvTitle.text = "还不错,可对照评测结果改进"
finalScore < 60 -> tvTitle.text = "不太理想,还需要加油呀"
}
}
@SuppressLint("SetTextI18n")
private fun setEnglishSingleWordScore(wordList: ArrayList<ReadWord>) {
var finalScore = 0f
wordList.forEach { readWord ->
finalScore += readWord.totalScore ?: 0f
}
finalScore /= 10f
tvTotalScore.text = String.format("%.2f", finalScore) + "分"
if (finalScore >= 60) {
ivScore.setImageResource(R.drawable.ic_img_bg_score_high)
} else {
ivScore.setImageResource(R.drawable.ic_img_bg_score_low)
}
setResultTitle(finalScore)
}
@SuppressLint("SetTextI18n")
private fun setEnglishSentenceScore(readWord: ReadWord) {
tvTotalScore.text = readWord.totalScore.toString() + "分"
if (readWord.totalScore ?: 0f >= 60f) {
ivScore.setImageResource(R.drawable.ic_img_bg_score_high)
} else {
ivScore.setImageResource(R.drawable.ic_img_bg_score_low)
}
if (readWord.exceptInfo == "0") {
setResultTitle(readWord.totalScore ?: 0f)
} else {
setExceptInfo(readWord.exceptInfo)
}
}
@SuppressLint("SetTextI18n")
private fun setEnglishArticleScore(readWord: ReadWord) {
englishArticleScore.isVisible = true
tvTotalScore.text = readWord.totalScore.toString() + "分"
if (readWord.totalScore ?: 0f >= 60f) {
ivScore.setImageResource(R.drawable.ic_img_bg_score_high)
} else {
ivScore.setImageResource(R.drawable.ic_img_bg_score_low)
}
if (readWord.exceptInfo == "0") {
setResultTitle(readWord.totalScore ?: 0f)
} else {
setExceptInfo(readWord.exceptInfo)
}
tvStandardScore.text = readWord.standardScore.toString()
tvIntegrityScore.text = readWord.integrityScore.toString()
tvEnglishFluencyScore.text = readWord.fluencyScore.toString()
tvAccuracyScore.text = readWord.accurecyScore.toString()
}
private fun setExceptInfo(exceptInfo: String?) {
when (exceptInfo) {
"28673" -> tvTitle.text = "声音太小了,大点声音再试一次呀?"
"28676" -> tvTitle.text = "老实说,你是不是在乱讲额"
"28680", "28709" -> tvTitle.text = "杂音太大了,换个安静的环境再试一次?"
"28690" -> tvTitle.text = "声音太大啦,下次声音小点呢"
}
}
private fun setupSentenceResult(readWord: ReadWord) {
tvResultSentence.isVisible = true
var newWord = ""
readWord.sentences.forEachIndexed { index, sentence ->
sentence.words?.forEach { word ->
word.syllables?.forEach {
when (it.dpMessage) {
"0" -> newWord += it.content
"16" -> newWord += "(${it.content})"
"32", "64", "128" -> newWord += "<S><font color='#b3b3b3'>${it.content}</font></S>"
}
}
}
newWord = if (sentence.totalScore ?: 0f >= 90) {
"<font color='#2AE79F'>${newWord}</font>"
} else if (sentence.totalScore ?: 0f <= 60 && sentence.totalScore ?: 0f > 0) {
"<font color='#FF9595'>${newWord}</font>"
} else {
"<font color='#FFFFFF'>${newWord}</font>"
}
if (punctuationList?.size ?: 0 > index) {
newWord += punctuationList?.get(index)
}
}
tvResultSentence.text = Html.fromHtml(newWord)
}
private fun setupEnglishSentenceResult(readWord: ReadWord) {
tvResultSentence.isVisible = true
var newWord = ""
readWord.sentences.forEachIndexed { index, sentence ->
sentence.words?.forEach { word ->
when (word.dpMessage) {
"0" -> {
//newWord += word.content
newWord += if (word.totalScore ?: 0f >= 90) {
"<font color='#2AE79F'>${word.content}</font>"
} else if (word.totalScore ?: 0f <= 60 && word.totalScore ?: 0f > 0) {
"<font color='#FF9595'>${word.content}</font>"
} else {
"<font color='#FFFFFF'>${word.content}</font>"
}
}
"16" -> newWord += "(${word.content})"
"32", "64", "128" -> newWord += "<S><font color='#b3b3b3'>${word.content}</font></S>"
}
newWord += " "
}
if (punctuationList?.size ?: 0 > index) {
newWord += punctuationList?.get(index)
}
}
tvResultSentence.text = Html.fromHtml(newWord)
}
private fun setupResultAdapter(wordList: ArrayList<ReadWord>) {
resultList.isVisible = true
val adapter = ResultAdapter(wordList)
resultList.adapter = adapter
}
private inner class ResultAdapter(val wordList: ArrayList<ReadWord>) :
RecyclerView.Adapter<ResultAdapter.ResultHolder>() {
private val badColor = Color.parseColor("#FF9595")
private val goodColor = Color.parseColor("#2AE79F")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ResultHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_speaker_word, parent, false)
return ResultHolder(view)
}
override fun getItemCount(): Int {
return wordList.size
}
private fun getWord(readWord: ReadWord): String {
var newWord = ""
readWord.sentences.forEach { sentence ->
sentence.words?.forEach { word ->
word.syllables?.forEach {
when (it.dpMessage) {
"0" -> newWord += it.content
"16" -> newWord += "(${it.content})"
"32", "64", "128" -> newWord += "<S><font color='#b3b3b3'>${it.content}</font></S>"
}
}
}
}
return newWord
}
private fun getEnglishWord(readWord: ReadWord): String {
var newWord = ""
readWord.sentences.forEach { sentence ->
val word = sentence.word
when (word.dpMessage) {
"0" -> newWord += word.content
"16" -> newWord += "(${word.content})"
"32", "64", "128" -> newWord += "<S><font color='#b3b3b3'>${word.content}</font></S>"
}
}
return newWord
}
override fun onBindViewHolder(holder: ResultHolder, position: Int) {
val item = wordList[position]
var text = ""
when (type) {
SpeakEvaluatingFragment.CHINESE_SINGLE_WORD_TYPE -> {
text = getWord(item)
holder.tvTag.textSize = 25f
}
SpeakEvaluatingFragment.CHINESE_WORDS_TYPE -> {
text = getWord(item)
holder.tvTag.textSize = 25f
}
SpeakEvaluatingFragment.ENGLISH_WORD_TYPE -> {
text = getEnglishWord(item)
holder.tvTag.textSize = 18f
}
}
holder.tvTag.text = Html.fromHtml(text)
if (item.totalScore ?: 0f >= 90) {
holder.tvTag.setTextColor(goodColor)
} else if (item.totalScore ?: 0f <= 60 && item.totalScore ?: 0f > 0) {
holder.tvTag.setTextColor(badColor)
} else {
holder.tvTag.setTextColor(Color.WHITE)
}
}
inner class ResultHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvTag = itemView.findViewById<TextView>(R.id.tv_tag)
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.net.wifi.ScanResult
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.KeyboardUtils
import com.iflytek.cyber.iot.show.core.utils.WifiUtils
class InputNetworkFragment(private val scanResult: ScanResult? = null) : BaseFragment() {
private var backCount = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_input_network, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val etSsid: EditText = view.findViewById(R.id.ssid)
val etPassword: EditText = view.findViewById(R.id.password)
etPassword.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
scanResult?.let {
view.findViewById<View>(R.id.connect).isEnabled = (s?.length ?: 0) >= 8
}
}
})
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
view.findViewById<View>(R.id.connect).setOnClickListener {
val password = etPassword.text.toString()
KeyboardUtils.closeKeyboard(etPassword)
scanResult?.let { scanResult ->
if (password.length < 8) {
} else {
WifiUtils.connect(it.context, scanResult.SSID, password)
start(WifiConnectingFragment(scanResult.SSID))
}
} ?: run {
if (password.isEmpty())
WifiUtils.connect(it.context, etSsid.text.toString())
else
WifiUtils.connect(it.context, etSsid.text.toString(), password)
start(WifiConnectingFragment(etSsid.text.toString()))
}
}
val titleView: TextView = view.findViewById(R.id.title)
scanResult?.let {
view.findViewById<View>(R.id.connect).isEnabled = false
view.findViewById<View>(R.id.ssid_container).visibility = View.GONE
titleView.text = "连接到 ${it.SSID}"
} ?: run {
view.findViewById<View>(R.id.ssid_container).visibility = View.VISIBLE
titleView.text = "手动添加"
}
}
override fun onDestroyView() {
KeyboardUtils.closeKeyboard(view)
super.onDestroyView()
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.graphics.Color
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.MediaItem
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
import com.iflytek.cyber.iot.show.core.utils.clickWithTrigger
class TemplateAppMediaAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
const val TYPE_1P0 = 0
const val TYPE_1P6 = 1
const val TYPE_0P75 = 2
}
private val mediaList = mutableListOf<MediaItem>()
var onItemClickListener: OnItemClickListener? = null
var ratio = 1f
var isDark = false
fun setMediaList(mediaList: List<MediaItem>) {
clear()
this.mediaList.addAll(mediaList)
}
fun appendMediaList(mediaList: List<MediaItem>) {
this.mediaList.addAll(mediaList)
}
fun getMediaItem(position: Int) = if (position < mediaList.size) mediaList[position] else null
fun clear() {
mediaList.clear()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = when (viewType) {
TYPE_1P6 -> MediaItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_media_1p6,
parent,
false
)
)
TYPE_1P0 -> MediaItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_media_1p0,
parent,
false
)
)
else -> MediaItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_media_0p75,
parent,
false
)
)
}
holder.clickableView.clickWithTrigger {
onItemClickListener?.onItemClick(parent, it, holder.adapterPosition)
}
return holder
}
override fun getItemViewType(position: Int): Int {
return when {
ratio < 1 -> TYPE_0P75
ratio == 1f -> TYPE_1P0
else -> TYPE_1P6
}
}
override fun getItemCount(): Int {
return mediaList.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is MediaItemViewHolder) {
holder.tvIndex.text = (position + 1).toString()
val mediaItem = mediaList[position]
if (!mediaItem.cover.isNullOrEmpty()) {
try {
Uri.parse(mediaItem.cover)?.let { uri ->
Glide.with(holder.ivImage)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.transform(
MultiTransformation(
CenterCrop(), RoundedCornersTransformation(
holder.itemView.resources.getDimensionPixelSize(
R.dimen.dp_6
), 0
)
)
)
.into(holder.ivImage)
} ?: run {
holder.ivImage.setImageResource(R.drawable.bg_default_template_app_2)
}
} catch (t: Throwable) {
t.printStackTrace()
holder.ivImage.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
holder.ivImage.setImageResource(R.drawable.bg_default_template_app_2)
}
holder.tvFirstLine.text = mediaItem.title
holder.tvSecondLine.text = mediaItem.subtitle
holder.tvSecondLine.isVisible = !mediaItem.subtitle.isNullOrEmpty()
if (isDark) {
holder.tvFirstLine.setTextColor(Color.WHITE)
holder.tvSecondLine.setTextColor(Color.WHITE)
} else {
holder.tvFirstLine.setTextColor(Color.BLACK)
holder.tvSecondLine.setTextColor(Color.BLACK)
}
}
}
private class MediaItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val clickableView: View = itemView.findViewById(R.id.clickable_view)
val tvIndex: TextView = itemView.findViewById(R.id.tv_index)
val ivImage: ImageView = itemView.findViewById(R.id.image)
val tvFirstLine: TextView = itemView.findViewById(R.id.first_line)
val tvSecondLine: TextView = itemView.findViewById(R.id.second_line)
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent
import androidx.annotation.CallSuper
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.annotation.JSONField
import com.iflytek.cyber.evs.sdk.RequestManager
import com.iflytek.cyber.evs.sdk.focus.AudioFocusManager
import com.iflytek.cyber.evs.sdk.model.Constant
/**
* 本地闹铃模块。详细介绍见https://doc.iflyos.cn/device/evs/reference/alarm.html#%E6%9C%AC%E5%9C%B0%E9%97%B9%E9%92%9F
*/
abstract class Alarm {
val version = "1.1"
companion object {
const val NAME_SET_ALARM = "${Constant.NAMESPACE_ALARM}.set_alarm"
const val NAME_DELETE_ALARM = "${Constant.NAMESPACE_ALARM}.delete_alarm"
const val NAME_STATE_SYNC = "${Constant.NAMESPACE_ALARM}.state_sync"
const val KEY_ALARM_ID = "alarm_id"
const val KEY_TIMESTAMP = "timestamp"
const val KEY_URL = "url"
const val KEY_ACTIVE = "active"
const val KEY_LOCAL = "local"
const val KEY_TYPE = "type"
/**
* 如果不需要闹钟能力,override 返回此函数即可。
*/
fun disable(): Alarm {
return object : Alarm() {
override fun getLocalAlarms(): List<Item> {
return emptyList()
}
override fun getActiveAlarmId(): String? {
return null
}
override fun setAlarm(alarm: Item) {
}
override fun deleteAlarm(alarmId: String) {
}
override fun stop() {
}
override fun destroy() {
}
override fun isDisabled(): Boolean {
return true
}
}
}
}
private var listeners = HashSet<AlarmStateChangedListener>()
private var alarmUpdateListeners = HashSet<OnAlarmUpdatedListener>()
internal var onAlarmUpdatedListener = object : OnAlarmUpdatedListener {
override fun onAlarmUpdated() {
alarmUpdateListeners.map {
try {
it.onAlarmUpdated()
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
}
/**
* 获取本地闹钟。
* @return 闹钟列表
*/
abstract fun getLocalAlarms(): List<Item>
/**
* 获取活动(正在响铃)闹钟的id。
* @return 闹钟id,为null则无活动闹钟
*/
abstract fun getActiveAlarmId(): String?
/**
* 设置闹钟。
* @param alarm 闹钟对象
*/
@CallSuper
open fun setAlarm(alarm: Item) {
onAlarmUpdated()
}
/**
* 删除闹钟。
* @param alarmId 闹钟id
*/
@CallSuper
open fun deleteAlarm(alarmId: String) {
onAlarmUpdated()
}
/**
* 停止闹钟。
*/
@CallSuper
open fun stop() {
onAlarmUpdated()
}
open fun isDisabled(): Boolean {
return false
}
/**
* 销毁模块。
*/
abstract fun destroy()
@Suppress("unused")
fun addListener(listener: AlarmStateChangedListener) {
listeners.add(listener)
}
@Suppress("unused")
fun removeListener(listener: AlarmStateChangedListener) {
listeners.remove(listener)
}
fun addOnAlarmUpdatedListener(onAlarmUpdatedListener: OnAlarmUpdatedListener) {
alarmUpdateListeners.add(onAlarmUpdatedListener)
}
fun removeOnAlarmUpdatedListener(onAlarmUpdatedListener: OnAlarmUpdatedListener) {
alarmUpdateListeners.remove(onAlarmUpdatedListener)
}
fun onAlarmStarted(alarmId: String) {
val payload = JSONObject()
payload[KEY_TYPE] = "STARTED"
payload[KEY_ALARM_ID] = alarmId
RequestManager.sendRequest(NAME_STATE_SYNC, payload)
AudioFocusManager.requestActive(
AudioFocusManager.CHANNEL_ALARM,
AudioFocusManager.TYPE_ALARM
)
onAlarmStateChanged(alarmId, AlarmState.Started)
}
fun onAlarmStopped(alarmId: String) {
val payload = JSONObject()
payload[KEY_TYPE] = "STOPPED"
payload[KEY_ALARM_ID] = alarmId
RequestManager.sendRequest(NAME_STATE_SYNC, payload)
AudioFocusManager.requestAbandon(
AudioFocusManager.CHANNEL_ALARM,
AudioFocusManager.TYPE_ALARM
)
onAlarmStateChanged(alarmId, AlarmState.Stopped)
}
fun onAlarmUpdated() {
onAlarmUpdatedListener?.onAlarmUpdated()
}
open fun onAlarmStateChanged(alarmId: String, state: AlarmState) {
listeners.map {
try {
it.onAlarmStateChanged(alarmId, state)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
/**
* 闹钟实体类。
* @param alarmId 闹铃id
* @param timestamp 响铃时间(从1970-01-01 00:00:00到现在的时间),单位:秒
* @param url 待播放的铃声url
*/
data class Item(
@JSONField(name = KEY_ALARM_ID) val alarmId: String,
val timestamp: Long,
val url: String
)
interface AlarmStateChangedListener {
fun onAlarmStateChanged(alarmId: String, state: AlarmState)
}
enum class AlarmState {
Started,
Stopped,
}
interface OnAlarmUpdatedListener {
/**
* set alarm or delete alarm, notify user
*/
fun onAlarmUpdated()
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.MultiTypeAdapter
import com.google.gson.Gson
import com.iflytek.cyber.evs.sdk.auth.AuthDelegate
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.FloatingService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.AudioTypeViewBinder
import com.iflytek.cyber.iot.show.core.adapter.VideoTypeViewBinder
import com.iflytek.cyber.iot.show.core.api.MediaApi
import com.iflytek.cyber.iot.show.core.model.*
import com.iflytek.cyber.iot.show.core.utils.ACache
import com.iflytek.cyber.iot.show.core.utils.KeyboardUtils
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import com.zhy.view.flowlayout.TagFlowLayout
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class SearchFragment : BaseFragment(), View.OnClickListener {
companion object {
private const val KEY_TAGS = "key_tags"
}
data class HistoryTag(
val tags: ArrayList<String>
)
private lateinit var recommendTagLayout: TagFlowLayout
private lateinit var historyTagLayout: TagFlowLayout
private lateinit var scrollView: NestedScrollView
private lateinit var mainContent: FrameLayout
private lateinit var edtQuery: EditText
private lateinit var clear: ImageView
private lateinit var deleteTag: ImageView
private lateinit var tvSearchTag: TextView
private lateinit var tvRecommend: TextView
private lateinit var resultList: RecyclerView
//private lateinit var hintList: RecyclerView
//private lateinit var hintContent: LinearLayout
private lateinit var toolbar: FrameLayout
private lateinit var tvSearchEmpty: TextView
private lateinit var retryContent: LinearLayout
private lateinit var retry: TextView
//private var hintResultAdapter: HintResultAdapter? = null
private var resultAdapter: MultiTypeAdapter? = null
private lateinit var audioTypeViewBinder: AudioTypeViewBinder
private lateinit var videoTypeViewBinder: VideoTypeViewBinder
private var historyTags = ArrayList<String>()
private var isSearch = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_search, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toolbar = view.findViewById(R.id.toolbar)
recommendTagLayout = view.findViewById(R.id.recommend_tag_layout)
historyTagLayout = view.findViewById(R.id.history_tag_layout)
resultList = view.findViewById(R.id.result_list)
//hintList = view.findViewById(R.id.hint_list)
//hintContent = view.findViewById(R.id.hint_content)
scrollView = view.findViewById(R.id.scroll_view)
mainContent = view.findViewById(R.id.main_content)
deleteTag = view.findViewById(R.id.delete)
deleteTag.setOnClickListener(this)
tvSearchTag = view.findViewById(R.id.tv_search_tag)
tvRecommend = view.findViewById(R.id.tv_recommend)
edtQuery = view.findViewById(R.id.edt_query)
clear = view.findViewById(R.id.clear)
tvSearchEmpty = view.findViewById(R.id.tv_search_empty)
retryContent = view.findViewById(R.id.retry_content)
retry = view.findViewById(R.id.tv_retry)
retry.setOnClickListener(this)
clear.setOnClickListener(this)
view.findViewById<View>(R.id.back).setOnClickListener { pop() }
edtQuery.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (s.isNullOrEmpty()) {
clear.isVisible = false
scrollView.isVisible = true
resultList.isVisible = false
toolbar.setBackgroundColor(Color.WHITE)
mainContent.setBackgroundColor(Color.WHITE)
} else {
clear.isVisible = true
}
}
})
/*edtQuery.textChanges()
.map { s ->
isSearch = false
if (s.isNotEmpty()) {
mainContent.setBackgroundColor(
ContextCompat.getColor(
requireContext(),
R.color.grey_100
)
)
scrollView.isVisible = false
clear.isVisible = true
} else {
mainContent.setBackgroundColor(Color.WHITE)
scrollView.isVisible = true
clear.isVisible = false
}
return@map s
}
.debounce(400, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.filter { s -> return@filter s.isNotEmpty() }
.switchMap { value ->
if (!TextUtils.isEmpty(value.toString())) {
search(value.toString())
}
return@switchMap Observable.just(value)
}
.subscribe()*/
edtQuery.setOnKeyListener { v, keyCode, event ->
if (event.action != KeyEvent.ACTION_DOWN) {
return@setOnKeyListener true
}
if (keyCode == KeyEvent.KEYCODE_ENTER) {
isSearch = true
if (!edtQuery.text.isNullOrEmpty()) {
KeyboardUtils.closeKeyboard(edtQuery)
search(edtQuery.text.toString())
}
} else if (keyCode == KeyEvent.KEYCODE_BACK) {
pop()
}
return@setOnKeyListener false
}
loadRecommendTag()
loadHistoryTag()
videoTypeViewBinder = VideoTypeViewBinder({
playSearchMedia(it)
}, {
start(
SearchResultFragment.newInstance(
edtQuery.text.toString(),
SearchResultFragment.TYPE_VIDEO, it
)
)
})
audioTypeViewBinder = AudioTypeViewBinder({
playSearchMedia(it)
}, {
start(
SearchResultFragment.newInstance(
edtQuery.text.toString(),
SearchResultFragment.TYPE_AUDIO, it
)
)
})
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.clear -> {
edtQuery.text = null
mainContent.setBackgroundColor(Color.WHITE)
toolbar.setBackgroundColor(Color.WHITE)
scrollView.isVisible = true
resultList.isVisible = false
tvSearchEmpty.isVisible = false
retryContent.isVisible = false
}
R.id.delete -> {
ACache.get(launcher!!).put(KEY_TAGS, "")
historyTags.clear()
setupHistoryTag(historyTags)
}
R.id.tv_retry -> {
if (!edtQuery.text.isNullOrEmpty()) {
search(edtQuery.text.toString())
}
}
}
}
private fun setupRecommendTag(tags: ArrayList<String>) {
recommendTagLayout.adapter = object : TagAdapter<String>(tags) {
override fun getView(parent: FlowLayout?, position: Int, tag: String?): View {
val button = LayoutInflater.from(launcher!!)
.inflate(R.layout.item_recommend_tag, parent, false) as TextView
button.text = tag
return button
}
}
recommendTagLayout.setOnTagClickListener { view, position, parent ->
KeyboardUtils.closeKeyboard(edtQuery)
val tag = tags[position]
edtQuery.setText(tag)
edtQuery.setSelection(tag.length)
addNewTag(tag)
search(tag)
return@setOnTagClickListener true
}
}
private fun setupHistoryTag(tags: ArrayList<String>) {
if (tags.size == 0) {
tvSearchTag.isVisible = false
deleteTag.isVisible = false
} else {
tvSearchTag.isVisible = true
deleteTag.isVisible = true
}
historyTagLayout.adapter = object : TagAdapter<String>(tags) {
override fun getView(parent: FlowLayout?, position: Int, tag: String?): View {
val button = LayoutInflater.from(launcher!!)
.inflate(R.layout.item_history_tag, parent, false) as Button
button.text = tag
return button
}
}
historyTagLayout.setOnTagClickListener { view, position, parent ->
KeyboardUtils.closeKeyboard(edtQuery)
val tag = tags[position]
edtQuery.setText(tag)
edtQuery.setSelection(tag.length)
search(tag)
return@setOnTagClickListener true
}
}
private fun loadRecommendTag() {
getMediaApi()?.loadRecommendTag("showcore")?.enqueue(object : Callback<RecommendTag> {
override fun onResponse(call: Call<RecommendTag>, response: Response<RecommendTag>) {
if (response.isSuccessful) {
val recommendTag = response.body()
if (recommendTag != null && !recommendTag.tags.isNullOrEmpty()) {
tvRecommend.isVisible = true
setupRecommendTag(recommendTag.tags)
} else {
tvRecommend.isVisible = false
}
}
}
override fun onFailure(call: Call<RecommendTag>, t: Throwable) {
t.printStackTrace()
}
})
}
private fun loadHistoryTag() {
val value = ACache.get(launcher!!).getAsString(KEY_TAGS)
if (!value.isNullOrEmpty()) {
val result = Gson().fromJson(value, HistoryTag::class.java)
historyTags = result.tags
setupHistoryTag(result.tags)
} else {
tvSearchTag.isVisible = false
deleteTag.isVisible = false
}
}
private fun search(keyword: String) {
addNewTag(keyword)
val body = SearchBody(keyword, limit = 10)
getMediaApi()?.search(body)?.enqueue(object : Callback<ArrayList<SearchResult>> {
override fun onResponse(
call: Call<ArrayList<SearchResult>>,
response: Response<ArrayList<SearchResult>>
) {
retryContent.isVisible = false
scrollView.isVisible = true
if (response.isSuccessful) {
resultList.scrollToPosition(0)
val result = response.body()
tvSearchEmpty.isVisible = result.isNullOrEmpty()
scrollView.isVisible = !result.isNullOrEmpty()
resultList.isVisible = !result.isNullOrEmpty()
setupResultAdapter(result, keyword)
}
}
override fun onFailure(call: Call<ArrayList<SearchResult>>, t: Throwable) {
t.printStackTrace()
if (isAdded && context != null) {
retryContent.isVisible = true
scrollView.isVisible = false
tvSearchEmpty.isVisible = false
resultList.isVisible = false
}
}
})
}
private fun addNewTag(keyword: String) {
val index = historyTags.indexOf(keyword)
if (index == -1) {
if (historyTags.size > 10) {
historyTags.removeAt(historyTags.size - 1)
}
historyTags.add(0, keyword)
setupHistoryTag(historyTags)
val historyTag = HistoryTag(historyTags)
val result = Gson().toJson(historyTag)
ACache.get(launcher!!).put(KEY_TAGS, result)
}
}
private fun getMediaApi(): MediaApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(MediaApi::class.java)
} else {
null
}
}
private fun setupResultAdapter(items: ArrayList<SearchResult>?, keyword: String) {
if (items.isNullOrEmpty()) {
return
}
val newItems = ArrayList<SearchResult>(items)
items.forEach { searchResult ->
if (searchResult.results.isNullOrEmpty()) {
newItems.remove(searchResult)
}
}
mainContent.setBackgroundColor(
ContextCompat.getColor(
launcher!!,
R.color.grey_100
)
)
toolbar.setBackgroundColor(ContextCompat.getColor(launcher!!, R.color.grey_100))
scrollView.isVisible = false
//hintContent.isVisible = false
resultList.isVisible = true
audioTypeViewBinder.setKeyword(keyword)
videoTypeViewBinder.setKeyword(keyword)
if (resultAdapter == null) {
resultAdapter = MultiTypeAdapter()
resultAdapter?.register(SearchResult::class.java)?.to(
videoTypeViewBinder,
audioTypeViewBinder
)?.withKotlinClassLinker { _, item ->
when (item.type) {
2 -> VideoTypeViewBinder::class
else -> AudioTypeViewBinder::class
}
}
resultAdapter?.items = newItems
resultList.adapter = resultAdapter
} else {
resultAdapter?.items = newItems
resultAdapter?.notifyDataSetChanged()
}
}
private fun playSearchMedia(result: Result) {
val body = PlayBody(result.id, result.business, result.source)
getMediaApi()?.playSearchMedia(body)?.enqueue(object : Callback<String> {
override fun onResponse(call: Call<String>, response: Response<String>) {
if (response.isSuccessful) {
Toast.makeText(launcher!!, "播放${result.title}", Toast.LENGTH_SHORT).show()
} else {
showError(response.errorBody()?.string())
}
}
override fun onFailure(call: Call<String>, t: Throwable) {
t.printStackTrace()
}
})
}
private fun showError(errorStr: String?) {
try {
val error = Gson().fromJson(errorStr, Error::class.java)
if (error.redirectUrl.isNullOrEmpty()) {
val intent = Intent(context, FloatingService::class.java)
intent.action = FloatingService.ACTION_SHOW_NOTIFICATION
intent.putExtra(FloatingService.EXTRA_MESSAGE, error.message)
intent.putExtra(FloatingService.EXTRA_POSITIVE_BUTTON_TEXT, "我知道了")
context?.startService(intent)
} else {
val context = context ?: return
val uri = Uri.parse(error.redirectUrl)
val codeUrl = uri.buildUpon()
.appendQueryParameter(
"token",
AuthDelegate.getAuthResponseFromPref(context)?.accessToken
)
.build()
.toString()
start(
KugouQRCodeFragment.newInstance(
error.title,
error.message,
error.qrCodeMessage,
error.redirectUrl
)
)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
/*private fun setupHintAdapter(items: ArrayList<SearchResult>?) {
if (items.isNullOrEmpty()) {
return
}
toolbar.setBackgroundColor(Color.WHITE)
val newItems = ArrayList<Result>()
items.forEachIndexed { _, searchResult ->
searchResult.results?.forEachIndexed { i, result ->
if (i < 5) {
newItems.add(result)
}
}
}
if (hintResultAdapter == null) {
hintResultAdapter = HintResultAdapter(newItems)
hintList.adapter = hintResultAdapter
} else {
hintResultAdapter?.items = newItems
hintResultAdapter?.notifyDataSetChanged()
}
}*/
/*inner class HintResultAdapter(var items: ArrayList<Result>) :
RecyclerView.Adapter<HintResultAdapter.HintResultHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HintResultHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_hint_result, parent, false)
return HintResultHolder(view)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: HintResultHolder, position: Int) {
val item = items[position]
holder.text.text = item.text
holder.divider.isVisible = position != items.size - 1
holder.itemView.setOnClickListener {
playSearchMedia(item)
}
}
inner class HintResultHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val text = itemView.findViewById<TextView>(R.id.text)
val divider = itemView.findViewById<View>(R.id.divider)
}
}*/
}
<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.widget.FrameLayout
import androidx.annotation.StringRes
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import com.airbnb.lottie.LottieAnimationView
import com.iflytek.cyber.iot.show.core.R
class CircleCheckBox @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr) {
private val checkBoxView = LottieAnimationView(context)
private val textView = AppCompatTextView(context)
private var currentAnimator: ValueAnimator? = null
var isChecked: Boolean = false
set(value) {
if (isChecked == value)
return
setCheckedVisible(value, isAttachedToWindow)
field = value
listener?.invoke(this, value)
}
var text: String = ""
set(value) {
textView.text = value
field = value
}
get() {
return textView.text.toString()
}
init {
val checkBoxSize = resources.getDimensionPixelSize(R.dimen.dp_24)
val checkBoxTextMargin = resources.getDimensionPixelSize(R.dimen.dp_8)
setOnClickListener {
isChecked = !isChecked
}
// get attribute
val attr = context.obtainStyledAttributes(attrs, R.styleable.CircleCheckBox)
val isChecked = attr.getBoolean(R.styleable.CircleCheckBox_isChecked, false)
val text = attr.getString(R.styleable.CircleCheckBox_text)
val textSize = attr.getDimensionPixelSize(R.styleable.CircleCheckBox_textSize, -1)
val textInsetStart = attr.getDimensionPixelSize(R.styleable.CircleCheckBox_textInsetStart, -1)
attr.recycle()
val checkBoxOnLp = LayoutParams(checkBoxSize, checkBoxSize)
checkBoxOnLp.gravity = Gravity.CENTER_VERTICAL
checkBoxView.setAnimation(R.raw.animation_checkbox_1)
addView(checkBoxView, checkBoxOnLp)
val textLp = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
textLp.leftMargin = checkBoxSize + (if (textInsetStart != -1) textInsetStart else checkBoxTextMargin)
textLp.gravity = Gravity.CENTER_VERTICAL
if (textSize != -1) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize.toFloat())
}
textView.text = text
textView.setTextColor(ContextCompat.getColor(context, R.color.semi_black))
addView(textView, textLp)
this.isChecked = isChecked
}
private var listener: ((CircleCheckBox, Boolean) -> Unit)? = null
private fun setCheckedVisible(isChecked: Boolean, shouldAnimate: Boolean) {
if (shouldAnimate) {
currentAnimator = null
val target = if (isChecked) 1f else 0f
val animator = ValueAnimator.ofFloat(checkBoxView.progress, target)
animator.addUpdateListener {
val value = it.animatedValue as Float
checkBoxView.progress = value
}
animator.addListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(animation: Animator?) {
}
override fun onAnimationEnd(animation: Animator?) {
currentAnimator = null
}
override fun onAnimationCancel(animation: Animator?) {
currentAnimator = null
}
override fun onAnimationStart(animation: Animator?) {
}
})
animator.duration = 250
animator.start()
currentAnimator = animator
} else {
if (isChecked) {
checkBoxView.progress = 1f
} else
checkBoxView.progress = 0f
}
}
fun setOnCheckedChangeListener(listener: ((CircleCheckBox, Boolean) -> Unit)) {
this.listener = listener
}
fun setText(@StringRes resId: Int) {
textView.setText(resId)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.wifi.ScanResult
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.os.Build
import android.util.Log
import java.io.BufferedReader
import java.io.FileReader
import java.lang.Exception
import java.lang.StringBuilder
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.util.*
object WifiUtils {
private const val TAG = "WifiUtils"
fun isEncrypted(scan: ScanResult): Boolean {
// [ESS]
// [WPA2-PSK-CCMP][ESS]
// [WPA2-PSK-CCMP][WPS][ESS]
// [WPA-PSK-CCMP+TKIP][WPA2-PSK-CCMP+TKIP][WPS][ESS]
return scan.capabilities.contains("WPA")
}
fun connect(context: Context, ssid: String, password: String? = null): Boolean {
val wm = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val config =
if (password.isNullOrEmpty())
buildWifiConfig(ssid)
else
buildWifiConfig(ssid, password)
val networkId = wm.addNetwork(config)
return connect(context, networkId)
}
fun connect(context: Context, networkId: Int): Boolean {
val wm = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
if (!wm.disconnect()) {
Log.d(TAG, "Disconnect failed")
return false
}
if (!wm.enableNetwork(networkId, true)) {
Log.d(TAG, "Enable failed")
return false
}
if (!wm.reconnect()) {
Log.d(TAG, "Reconnect failed")
return false
}
return true
}
fun forgetAll(context: Context?): Boolean {
(context?.applicationContext?.getSystemService(Context.WIFI_SERVICE)
as? WifiManager)?.let { wm ->
val iterator = wm.configuredNetworks.iterator()
while (iterator.hasNext()) {
val configuration = iterator.next()
iterator.remove()
wm.removeNetwork(configuration.networkId)
}
return false
}
return false
}
fun forget(context: Context?, ssid: String?): Boolean {
(context?.applicationContext?.getSystemService(Context.WIFI_SERVICE)
as? WifiManager)?.let { wm ->
val iterator = wm.configuredNetworks.iterator()
while (iterator.hasNext()) {
val configuration = iterator.next()
val configuredSsid =
if (configuration.SSID.isNullOrEmpty())
""
else
configuration.SSID.substring(1, configuration.SSID.length - 1)
if (configuredSsid == ssid) {
iterator.remove()
wm.removeNetwork(configuration.networkId)
return true
}
}
return false
}
return false
}
private fun buildWifiConfig(ssid: String): WifiConfiguration {
val config = WifiConfiguration()
config.SSID = "\"" + ssid + "\""
config.status = WifiConfiguration.Status.ENABLED
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
return config
}
private fun buildWifiConfig(ssid: String, password: String): WifiConfiguration {
val config = WifiConfiguration()
config.SSID = "\"" + ssid + "\""
config.status = WifiConfiguration.Status.ENABLED
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK)
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN)
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP)
@Suppress("DEPRECATION")
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP)
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP)
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP)
config.preSharedKey = "\"" + password + "\""
return config
}
@SuppressLint("HardwareIds")
fun getMacAddress(context: Context): String? {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
val wifiManager =
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
return wifiManager.connectionInfo.macAddress
} else {
try {
val en = NetworkInterface.getNetworkInterfaces()
while (en.hasMoreElements()) {
val intf = en.nextElement()
if (intf.name == "wlan0") {
val buf = StringBuilder()
intf.hardwareAddress.map {
buf.append(String.format("%02X:", it))
}
buf.deleteCharAt(buf.length - 1)
return buf.toString()
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
}
fun getIPAddress(context: Context): String? {
val info = (context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
if (info != null && info.isConnected) {
if (info.type == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
try {
//Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces()
val en = NetworkInterface.getNetworkInterfaces()
while (en.hasMoreElements()) {
val intf = en.nextElement()
val enumIpAddr = intf.inetAddresses
while (enumIpAddr.hasMoreElements()) {
val inetAddress = enumIpAddr.nextElement()
if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
return inetAddress.getHostAddress()
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
} else if (info.type == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
val wifiManager =
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val wifiInfo = wifiManager.connectionInfo
return intIP2StringIP(wifiInfo.ipAddress)//得到IPV4地址
}
} else {
//当前无网络连接,请在设置中打开网络
}
return null
}
fun getConnectedSsid(context: Context?): String? {
(context?.applicationContext?.getSystemService(Context.WIFI_SERVICE)
as? WifiManager)?.let {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
val configuredNetworks = it.configuredNetworks
if (configuredNetworks?.isNotEmpty() == true)
for (config in configuredNetworks) {
val ssid = config.SSID.substring(1, config.SSID.length - 1)
if (config.status == WifiConfiguration.Status.CURRENT) {
println("ssid: $ssid")
return ssid
}
}
} else {
val connManager = context.applicationContext
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
if (networkInfo.isConnected) {
val wifiInfo = it.connectionInfo
val ssid = wifiInfo.ssid
println("ssid: $ssid")
return ssid.substring(1, ssid.length - 1)
}
}
}
return null
}
/**
* 将得到的int类型的IP转换为String类型
*
* @param ip
* @return
*/
fun intIP2StringIP(ip: Int): String {
return "${ip and 0xFF}.${(ip shr 8) and 0xFF}.${((ip shr 16) and 0xFF)}.${(ip shr 24 and 0xFF)}"
}
fun isWifiEnabled(context: Context?): Boolean {
return (context?.applicationContext?.getSystemService(Context.WIFI_SERVICE)
as? WifiManager)?.isWifiEnabled == true
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.MediaApi
import com.iflytek.cyber.iot.show.core.model.CollectionTag
import com.iflytek.cyber.iot.show.core.model.Tags
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class CollectionFragment : BaseFragment() {
private lateinit var loadingImageView: LottieAnimationView
private lateinit var loadingFrame: LinearLayout
private lateinit var retryFrame: LinearLayout
private lateinit var retryTextView: TextView
private lateinit var backContainer: FrameLayout
private lateinit var tagList: RecyclerView
private var tagAdapter: TagAdapter? = null
private var fragmentList = ArrayList<CollectionListFragment>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_collection, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back).setOnClickListener {
pop()
}
backContainer = view.findViewById(R.id.back_container)
loadingImageView = view.findViewById(R.id.loading_image)
loadingFrame = view.findViewById(R.id.loading_frame)
retryFrame = view.findViewById(R.id.retry_frame)
retryTextView = view.findViewById(R.id.retry)
retryTextView.setOnClickListener {
retryFrame.isVisible = false
backContainer.setBackgroundColor(Color.parseColor("#E2E7EB"))
getTags()
}
tagList = view.findViewById(R.id.tag_list)
getTags()
}
private fun setupTag(tags: ArrayList<Tags>) {
fragmentList.clear()
for (tag in tags) {
fragmentList.add(CollectionListFragment.newInstance(tag.id))
}
if (tagAdapter == null) {
tagAdapter = TagAdapter(tags) { tag, position ->
showHideFragment(fragmentList[position])
}
}
tagList.adapter = tagAdapter
loadMultipleRootFragment(R.id.fragment, 0, fragmentList[0], fragmentList[1], fragmentList[2])
}
private fun getTags() {
loadingImageView.isVisible = true
loadingImageView.playAnimation()
getMediaApi()?.getTags()?.enqueue(object : Callback<CollectionTag> {
override fun onFailure(call: Call<CollectionTag>, t: Throwable) {
t.printStackTrace()
loadingImageView.pauseAnimation()
loadingImageView.isVisible = false
retryFrame.isVisible = true
backContainer.setBackgroundColor(Color.WHITE)
}
override fun onResponse(call: Call<CollectionTag>, response: Response<CollectionTag>) {
loadingImageView.pauseAnimation()
loadingImageView.isVisible = false
if (response.isSuccessful) {
loadingFrame.isVisible = false
val collectionTag = response.body()
if (collectionTag != null) {
setupTag(collectionTag.tags)
}
} else {
backContainer.setBackgroundColor(Color.WHITE)
retryFrame.isVisible = true
}
}
})
}
private fun getMediaApi(): MediaApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(MediaApi::class.java)
} else {
null
}
}
inner class TagAdapter(val items: ArrayList<Tags>, val onItemClick: (Tags, Int) -> Unit) : RecyclerView.Adapter<TagAdapter.TagHolder>() {
private var selectorColor = Color.parseColor("#262626")
private var defaultColor = Color.parseColor("#9E9FA7")
private var currentPosition = 0
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TagHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_tag, parent, false)
return TagHolder(view)
}
override fun getItemCount(): Int {
return items.size
}
private fun updateIndicator(position: Int) {
currentPosition = position
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: TagHolder, position: Int) {
val item = items[position]
holder.tagTextView.text = item.name
if (currentPosition == position) {
holder.indicatorView.isInvisible = false
holder.tagTextView.setTextColor(selectorColor)
} else {
holder.indicatorView.isInvisible = true
holder.tagTextView.setTextColor(defaultColor)
}
holder.itemView.setOnClickListener {
updateIndicator(position)
onItemClick.invoke(item, position)
}
}
inner class TagHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val indicatorView = itemView.findViewById<View>(R.id.indicator_view)
val tagTextView = itemView.findViewById<TextView>(R.id.name_text)
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.launcher
object LauncherMemory {
var privateApps: List<AppData>? = null
var partyApps: List<AppData>? = null
var templateApps: List<TemplateAppData>? = null
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.iflytek.cyber.iot.show.core.R
class SpeakEvaluationFragment : BaseFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_speak_evaluation, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back).setOnClickListener {
pop()
}
view.findViewById<View>(R.id.mandarin_type).setOnClickListener {
start(SpeakTypeEvaluationFragment.newInstance(0))
}
view.findViewById<View>(R.id.american_english_type).setOnClickListener {
start(SpeakTypeEvaluationFragment.newInstance(1))
}
}
}<file_sep>cmake_minimum_required(VERSION 3.4.1)
link_directories(${PROJECT_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI})
find_library(log-lib log)
add_library(ivw-jni SHARED ${CMAKE_SOURCE_DIR}/src/main/cpp/ivw-jni/ivw-jni.cpp
${CMAKE_SOURCE_DIR}/src/main/cpp/ivw-jni/file/FileUtil.cpp
${CMAKE_SOURCE_DIR}/src/main/cpp/ivw-jni/log/log.cpp)
target_link_libraries(ivw-jni
${log-lib}
-lIvw60
)
<file_sep>//
// Created by huang on 2019/1/24.
//
#ifndef __LIBIVW_DEFINES_H__
#define __LIBIVW_DEFINES_H__
#define IVW_PARAM_LOCAL_BASE 0x0000
enum
{
IVW_PARAM_WAKEUPCALLBACK = (IVW_PARAM_LOCAL_BASE + 1),
IVW_PARAM_CM_LEVEL = (IVW_PARAM_LOCAL_BASE + 2),
IVW_PARAM_RESULT_CB_USERPARAM = (IVW_PARAM_LOCAL_BASE + 3),
IVW_PARAM_KEYWORD_NCM = (IVW_PARAM_LOCAL_BASE + 4)
};
enum
{
IVW_ERROR_SUCCESS = (0),
IVW_ERROR_INVALID_HANDLE = (1),
IVW_ERROR_ALREADY_INIT = (2),
IVW_ERROR_INVALID_PARA_VALUE = (3),
IVW_ERROR_FAIL = (4),
IVW_ERROR_NOT_INIT = (5),
IVW_ERROR_INVALID_PARA_TYPE = (6),
IVW_ERROR_BUF_OVERFLOW = (7),
IVW_ERROR_LOAD_DLL = (8)
};
enum
{
IVW_CMLevel_Lowest = 0,
IVW_CMLevel_Lower = 1,
IVW_CMLevel_Low = 2,
IVW_CMLevel_Normal = 3,
IVW_CMLevel_high = 4,
IVW_CMLevel_higher = 5,
IVW_CMLevel_highest = 6
};
#endif //__LIBIVW_DEFINES_H__
<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.ivw
import java.lang.Exception
/**
* 唤醒引擎封闭类。
*/
@Suppress("FunctionName")
class IVWEngine(resPath: String, listener: IVWListener, isLogOn: Boolean? = null) {
private var mResPath: String? = resPath
private var mListener: IVWListener? = listener
private var mEngineContextHandle: Long = 0
val version: String
get() = jni_get_version(mEngineContextHandle)
interface IVWListener {
fun onWakeup(result: String)
}
init {
if (initialed) {
isLogOn?.let {
jni_set_log(it)
}
mEngineContextHandle = jni_create(resPath, "wakeupCb")
}
}
// /**
// * 设置门限等级。已废弃
// *
// * @param level
// * @return
// */
// public int setCMLevel(int level) {
// return jni_set_cmlevel(mEngineContextHandle, level);
// }
//
// /**
// * 设置唤醒词门限。已废弃
// *
// * @param ncm 门限设置,例:"0:1250,1:1300",多个唤醒词用逗号隔开
// * @return
// */
// public int setKeywordNCM(String ncm) {
// return jni_set_keywordncm(mEngineContextHandle, ncm);
// }
fun start(): Int {
if (initialed)
return jni_start(mEngineContextHandle)
return -1
}
fun writeAudio(buffer: ByteArray, len: Int): Int {
if (initialed)
return jni_write(mEngineContextHandle, buffer, len)
return -1
}
fun stop(): Int {
if (initialed)
return jni_stop(mEngineContextHandle)
return -1
}
fun destroy() {
if (initialed) {
jni_destroy(mEngineContextHandle)
mEngineContextHandle = INVALID_HANDLE.toLong()
}
}
fun setLogOn(isOn: Boolean) {
if (initialed)
jni_set_log(isOn)
}
private fun wakeupCb(result: String) {
mListener?.onWakeup(result)
}
private external fun jni_create(resPath: String, wakeupCbName: String): Long
@Suppress("unused")
companion object {
private var initialed = false
init {
try {
System.loadLibrary("ivw-jni")
initialed = true
} catch (e: UnsatisfiedLinkError) {
e.printStackTrace()
} catch (e: Exception) {
e.printStackTrace()
}
}
@JvmStatic
private val INVALID_HANDLE = 0
@JvmStatic
val CMLEVEL_LOWEST = 0
@JvmStatic
val CMLEVEL_LOWER = 1
@JvmStatic
val CMLEVEL_LOW = 2
@JvmStatic
val CMLEVEL_NORMAL = 3
@JvmStatic
val CMLEVEL_HIGH = 4
@JvmStatic
val CMLEVEL_HIGHER = 5
@JvmStatic
val CMLEVEL_HIGHEST = 6
@JvmStatic
private external fun jni_destroy(handle: Long)
@JvmStatic
private external fun jni_set_cmlevel(handle: Long, level: Int): Int
@JvmStatic
private external fun jni_set_keywordncm(handle: Long, ncm: String): Int
@JvmStatic
private external fun jni_start(handle: Long): Int
@JvmStatic
private external fun jni_write(handle: Long, buffer: ByteArray, size: Int): Int
@JvmStatic
private external fun jni_stop(handle: Long): Int
@JvmStatic
private external fun jni_set_log(isOn: Boolean)
@JvmStatic
private external fun jni_get_version(handle: Long): String
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.bumptech.glide.request.transition.Transition
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.AppApi
import com.iflytek.cyber.iot.show.core.impl.prompt.PromptManager
import com.iflytek.cyber.iot.show.core.model.MediaItem
import com.iflytek.cyber.iot.show.core.model.TemplateApp
import com.iflytek.cyber.iot.show.core.model.XmlyAlbumItem
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
import com.iflytek.cyber.iot.show.core.widget.StyledProgressDialog
import com.kk.taurus.playerbase.utils.NetworkUtils
import retrofit2.Callback
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Response
import java.net.UnknownHostException
class TemplateXmlyContentListFragment : BaseFragment() {
companion object {
private const val LIMIT = 20
fun fromCategory(
templateApp: TemplateApp?,
section: String?,
categoryId: String?,
name: String?
): TemplateXmlyContentListFragment {
val fragment = TemplateXmlyContentListFragment()
fragment.isCategory = true
fragment.templateApp = templateApp
fragment.section = section
fragment.categoryId = categoryId
fragment.name = name
return fragment
}
fun fromAlbum(
templateApp: TemplateApp?,
section: String?,
albumId: String?,
name: String?
): TemplateXmlyContentListFragment {
val fragment = TemplateXmlyContentListFragment()
fragment.isCategory = false
fragment.templateApp = templateApp
fragment.section = section
fragment.albumId = albumId
fragment.name = name
return fragment
}
}
private var isCategory = false
private var templateApp: TemplateApp? = null
private var section: String? = null
private var categoryId: String? = null
private var albumId: String? = null
private var name: String? = null
private var page = 1
private var clickCount = 0
private var ivBack: ImageView? = null
private var ivIcon: ImageView? = null
private var ivBackground: ImageView? = null
private var recyclerView: RecyclerView? = null
private var tvTitle: TextView? = null
private var errorContainer: View? = null
private var tvError: TextView? = null
private var errorRetry: View? = null
private var tvRetry: TextView? = null
private var loading: LottieAnimationView? = null
private var loadingBottom: LottieAnimationView? = null
private val adapter = TemplateXmlyContentAdapter()
private var progressDialog: StyledProgressDialog? = null
private var isLoading = false
private var isLoadComplete = false
private val onScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (isLoadComplete || isLoading) return
(recyclerView.layoutManager as? LinearLayoutManager)?.let {
if (it.findLastCompletelyVisibleItemPosition() == it.findLastVisibleItemPosition() &&
recyclerView.adapter?.itemCount == it.findLastVisibleItemPosition() + 1
) {
page++
getContentList()
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.fragment_template_app_media_list_fragment,
container,
false
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back)?.setOnClickListener {
if (clickCount != 0)
return@setOnClickListener
clickCount++
pop()
}
ivBack = view.findViewById(R.id.iv_back)
ivIcon = view.findViewById(R.id.iv_icon)
ivBackground = view.findViewById(R.id.background)
recyclerView = view.findViewById(R.id.recycler_view)
loading = view.findViewById(R.id.loading)
loadingBottom = view.findViewById(R.id.loading_bottom)
tvTitle = view.findViewById(R.id.title)
tvRetry = view.findViewById(R.id.tv_retry)
tvError = view.findViewById(R.id.tv_error)
errorContainer = view.findViewById(R.id.error_container)
errorRetry = view.findViewById(R.id.error_retry)
errorRetry?.setOnClickListener {
if (!isLoading) {
page = 1
getContentList()
}
}
recyclerView?.adapter = adapter
recyclerView?.addOnScrollListener(onScrollListener)
adapter.isCategory = isCategory
adapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: ViewGroup, itemView: View, position: Int) {
if (isCategory) {
if (clickCount != 0)
return
clickCount++
adapter.getAlbumItem(position)?.let { albumItem ->
start(
TemplateXmlyAlbumFragment.newInstance(
templateApp,
albumItem.id,
albumItem.name
)
)
}
} else {
adapter.getMediaItem(position)?.let { mediaItem ->
if (isAdded && context != null && !NetworkUtils.isNetConnected(context)) {
PromptManager.play(PromptManager.NETWORK_LOST)
return
}
postPlay(mediaItem)
}
}
}
}
tvTitle?.text = name
loadBackground()
loadAppIcon()
getContentList()
applyTheme(templateApp?.isDark != false)
}
override fun onSupportVisible() {
super.onSupportVisible()
clickCount = 0
}
override fun onDestroy() {
super.onDestroy()
recyclerView?.removeOnScrollListener(onScrollListener)
}
private fun applyTheme(isDark: Boolean) {
ivBack?.imageTintList = ColorStateList.valueOf(if (isDark) Color.WHITE else Color.BLACK)
adapter.isDark = isDark
if (adapter.itemCount > 0) {
adapter.notifyDataSetChanged()
}
tvTitle?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
tvError?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
tvRetry?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
errorRetry?.setBackgroundResource(
if (isDark) R.drawable.bg_round_border_white_36dp
else R.drawable.bg_round_border_black_36dp
)
}
private fun loadBackground() {
val templateApp = templateApp ?: return
ivBackground?.let { imageView ->
val url = templateApp.img
if (url.isNullOrEmpty())
return
try {
Uri.parse(url)?.let { uri ->
Glide.with(imageView)
.load(uri)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
private fun loadAppIcon() {
val templateApp = templateApp ?: return
if (!templateApp.icon.isNullOrEmpty()) {
try {
Uri.parse(templateApp.icon)?.let { uri ->
ivIcon?.let { imageView ->
Glide.with(imageView)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
} ?: run {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} catch (t: Throwable) {
t.printStackTrace()
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
}
private fun showProgress(title: String, message: String? = null) {
if (isRemoving || isDetached)
return
context ?: return
progressDialog = StyledProgressDialog.Builder()
.setTitle(title)
.setMessage(message)
.show(fragmentManager)
}
private fun dismissProgress() {
if (isRemoving || isDetached)
return
context ?: return
progressDialog?.let {
it.dismiss()
progressDialog = null
}
}
private fun hideLoading() {
if (isRemoving || isDetached)
return
context ?: return
if (loading?.isVisible == true) {
loading?.pauseAnimation()
loading?.isVisible = false
}
if (loadingBottom?.isVisible == true) {
loadingBottom?.pauseAnimation()
loadingBottom?.isVisible = false
}
}
private fun showLoading() {
if (isRemoving || isDetached)
return
context ?: return
if (page == 1) {
loading?.isVisible = true
loading?.repeatCount = LottieDrawable.INFINITE
loading?.repeatMode = LottieDrawable.RESTART
loading?.playAnimation()
} else {
loadingBottom?.isVisible = true
loadingBottom?.repeatCount = LottieDrawable.INFINITE
loadingBottom?.repeatMode = LottieDrawable.RESTART
loadingBottom?.playAnimation()
}
}
private fun showError(message: String?, showRetry: Boolean = true) {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = false
errorContainer?.isVisible = true
errorRetry?.isVisible = showRetry
tvError?.text = message
}
private fun hideError() {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = true
errorContainer?.isVisible = false
}
private fun getContentList() {
val section = section ?: return
val id = if (isCategory) {
categoryId ?: return
} else {
albumId ?: return
}
showLoading()
hideError()
val json = JSONObject()
json["section"] = section
json["id"] = id
json["page"] = page
json["limit"] = LIMIT
val body = RequestBody.create(
MediaType.parse("application/json"),
json.toString()
)
getAppApi()?.getXmlyShow(body)?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
isLoading = false
hideLoading()
if (t is UnknownHostException) {
showError("Ooooops,请检查网络后重试")
} else {
showError("请求出错,请稍后重试")
}
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (isRemoving || isDetached)
return
context ?: return
if (response.isSuccessful) {
response.body()?.let { body ->
val bodyString = body.string()
Thread {
val bodyJson = JSON.parseObject(bodyString)
val resultArray = bodyJson.getJSONArray("result")
if (isCategory) {
val albumList = mutableListOf<XmlyAlbumItem>()
var firstCover: String? = null
for (i in 0 until resultArray.size) {
val jsonItem = resultArray.getJSONObject(i)
val albumItem = JSON.parseObject(
jsonItem.toString(),
XmlyAlbumItem::class.java
)
if (firstCover.isNullOrEmpty()) {
firstCover = albumItem.cover
}
albumList.add(albumItem)
}
if (page == 1) {
when {
albumList.isEmpty() -> {
recyclerView?.post {
hideLoading()
showError("Ooooops,找不到结果", false)
}
}
firstCover.isNullOrEmpty() -> recyclerView?.let { recyclerView ->
adapter.setAlbumList(albumList)
recyclerView.post {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 5
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
5
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
hideLoading()
adapter.notifyDataSetChanged()
}
}
else -> {
Glide.with(this@TemplateXmlyContentListFragment)
.asBitmap()
.load(firstCover)
.into(object : CustomTarget<Bitmap>() {
override fun onLoadFailed(errorDrawable: Drawable?) {
super.onLoadFailed(errorDrawable)
loading?.pauseAnimation()
loading?.isVisible = false
}
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?
) {
val ratio =
1f * resource.width / resource.height
adapter.ratio = ratio
recyclerView?.let { recyclerView ->
recyclerView.post {
when {
ratio <= 1f -> {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 5
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
5
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
ratio > 1f -> {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 3
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
3
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingBottom
)
}
}
hideLoading()
adapter.setAlbumList(albumList)
adapter.notifyDataSetChanged()
}
}
}
override fun onLoadCleared(placeholder: Drawable?) {
}
})
}
}
} else {
adapter.appendAlbumList(albumList)
recyclerView?.post {
hideLoading()
adapter.notifyDataSetChanged()
}
}
} else {
val mediaList = mutableListOf<MediaItem>()
var firstCover: String? = null
for (i in 0 until resultArray.size) {
val jsonItem = resultArray.getJSONObject(i)
val mediaItem = JSON.parseObject(
jsonItem.toString(),
MediaItem::class.java
)
if (firstCover.isNullOrEmpty()) {
firstCover = mediaItem.cover
}
mediaList.add(mediaItem)
}
if (page == 1) {
when {
mediaList.isEmpty() -> {
hideLoading()
showError("Ooooops,找不到结果", false)
}
firstCover.isNullOrEmpty() -> recyclerView?.let { recyclerView ->
adapter.setMediaList(mediaList)
recyclerView.post {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 5
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
5
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
hideLoading()
adapter.notifyDataSetChanged()
}
}
else -> {
Glide.with(this@TemplateXmlyContentListFragment)
.asBitmap()
.load(firstCover)
.into(object : CustomTarget<Bitmap>() {
override fun onLoadFailed(errorDrawable: Drawable?) {
super.onLoadFailed(errorDrawable)
loading?.pauseAnimation()
loading?.isVisible = false
}
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?
) {
val ratio =
1f * resource.width / resource.height
adapter.ratio = ratio
recyclerView?.let { recyclerView ->
recyclerView.post {
when {
ratio <= 1f -> {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 5
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
5
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
ratio > 1f -> {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 3
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
3
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingBottom
)
}
}
hideLoading()
adapter.setMediaList(mediaList)
adapter.notifyDataSetChanged()
}
}
}
override fun onLoadCleared(placeholder: Drawable?) {
}
})
}
}
} else {
adapter.appendMediaList(mediaList)
recyclerView?.post {
hideLoading()
adapter.notifyDataSetChanged()
}
}
}
}.start()
body.close()
}
} else {
hideLoading()
showError("请求出错,请稍后再试")
}
}
})
}
private fun postPlay(mediaItem: MediaItem) {
val audioId = mediaItem.id ?: return
val sourceType = mediaItem.source ?: templateApp?.source ?: return
val albumId = mediaItem.albumId ?: albumId ?: return
showProgress(getString(R.string.loading), getString(R.string.please_wait))
val json = JSONObject()
json["audio_id"] = audioId
json["source_type"] = sourceType
json["album_id"] = albumId
val requestBody = RequestBody.create(
MediaType.parse("application/json"),
json.toString()
)
getAppApi()?.postPlayMedia(requestBody)?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
dismissProgress()
Toast.makeText(context, "请求出错", Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (isRemoving || isDetached)
return
context ?: return
dismissProgress()
if (response.isSuccessful) {
Toast.makeText(context, "开始播放", Toast.LENGTH_SHORT).show()
} else {
response.errorBody()?.let { errorBody ->
val errorString = errorBody.string()
val errorJson = org.json.JSONObject(errorString)
if (errorJson.has("message")) {
Toast.makeText(
context,
errorJson.optString("message"),
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(context, "播放失败", Toast.LENGTH_SHORT).show()
}
errorBody.close()
} ?: run {
Toast.makeText(context, "播放失败", Toast.LENGTH_SHORT).show()
}
}
}
})
}
private fun getAppApi(): AppApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(AppApi::class.java)
}
class TemplateXmlyContentAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
const val TYPE_1P0 = 0
const val TYPE_1P6 = 1
const val TYPE_0P75 = 2
}
var isCategory = false
private val mediaList = mutableListOf<MediaItem>()
private val albumList = mutableListOf<XmlyAlbumItem>()
var onItemClickListener: OnItemClickListener? = null
var ratio = 1f
var isDark = false
fun setMediaList(mediaList: List<MediaItem>) {
clear()
this.mediaList.addAll(mediaList)
}
fun appendMediaList(mediaList: List<MediaItem>) {
this.mediaList.addAll(mediaList)
}
fun setAlbumList(albumList: List<XmlyAlbumItem>) {
clear()
this.albumList.addAll(albumList)
}
fun appendAlbumList(albumList: List<XmlyAlbumItem>) {
this.albumList.addAll(albumList)
}
fun getMediaItem(position: Int) = if (!isCategory) mediaList[position] else null
fun getAlbumItem(position: Int) = if (isCategory) albumList[position] else null
fun clear() {
mediaList.clear()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = when (viewType) {
TYPE_1P6 -> MediaItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_media_1p6,
parent,
false
)
)
TYPE_1P0 -> MediaItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_media_1p0,
parent,
false
)
)
else -> MediaItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_media_0p75,
parent,
false
)
)
}
holder.clickableView.setOnClickListener {
onItemClickListener?.onItemClick(parent, it, holder.adapterPosition)
}
return holder
}
override fun getItemViewType(position: Int): Int {
return when {
ratio < 1 -> TYPE_0P75
ratio == 1f -> TYPE_1P0
else -> TYPE_1P6
}
}
override fun getItemCount(): Int {
return if (isCategory) albumList.size else mediaList.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is MediaItemViewHolder) {
holder.tvIndex.text = (position + 1).toString()
if (isCategory) {
val albumItem = albumList[position]
if (!albumItem.cover.isNullOrEmpty()) {
try {
Uri.parse(albumItem.cover)?.let { uri ->
Glide.with(holder.ivImage)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.transform(
MultiTransformation(
CenterCrop(), RoundedCornersTransformation(
holder.itemView.resources.getDimensionPixelSize(
R.dimen.dp_6
), 0
)
)
)
.into(holder.ivImage)
} ?: run {
holder.ivImage.setImageResource(R.drawable.bg_default_template_app_2)
}
} catch (t: Throwable) {
t.printStackTrace()
holder.ivImage.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
holder.ivImage.setImageResource(R.drawable.bg_default_template_app_2)
}
holder.tvFirstLine.text = albumItem.name
holder.tvSecondLine.text = albumItem.subtitle
holder.tvSecondLine.isVisible = !albumItem.subtitle.isNullOrEmpty()
} else {
val mediaItem = mediaList[position]
if (!mediaItem.cover.isNullOrEmpty()) {
try {
Uri.parse(mediaItem.cover)?.let { uri ->
Glide.with(holder.ivImage)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.transform(
MultiTransformation(
CenterCrop(), RoundedCornersTransformation(
holder.itemView.resources.getDimensionPixelSize(
R.dimen.dp_6
), 0
)
)
)
.into(holder.ivImage)
} ?: run {
holder.ivImage.setImageResource(R.drawable.bg_default_template_app_2)
}
} catch (t: Throwable) {
t.printStackTrace()
holder.ivImage.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
holder.ivImage.setImageResource(R.drawable.bg_default_template_app_2)
}
holder.tvFirstLine.text = mediaItem.title
holder.tvSecondLine.text = mediaItem.subtitle
holder.tvSecondLine.isVisible = !mediaItem.subtitle.isNullOrEmpty()
}
if (isDark) {
holder.tvFirstLine.setTextColor(Color.WHITE)
holder.tvSecondLine.setTextColor(Color.WHITE)
} else {
holder.tvFirstLine.setTextColor(Color.BLACK)
holder.tvSecondLine.setTextColor(Color.BLACK)
}
}
}
private class MediaItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val clickableView: View = itemView.findViewById(R.id.clickable_view)
val tvIndex: TextView = itemView.findViewById(R.id.tv_index)
val ivImage: ImageView = itemView.findViewById(R.id.image)
val tvFirstLine: TextView = itemView.findViewById(R.id.first_line)
val tvSecondLine: TextView = itemView.findViewById(R.id.second_line)
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.api
import com.iflytek.cyber.iot.show.core.model.WakeWordsBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.PUT
interface WakeWordApi {
@GET("v1/wakewords")
fun getWakeWords(): Call<WakeWordsBody>
@PUT("v1/wakeword")
fun putWakeWord(@Body requestBody: RequestBody): Call<ResponseBody>
@POST("v1/wakewords/check")
fun checkWakeWord(@Body requestBody: RequestBody): Call<ResponseBody>
@POST("v1/wakewords")
fun postWakeWords(@Body requestBody: RequestBody): Call<ResponseBody>
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.view.View
import android.widget.TextView
import androidx.viewpager2.widget.ViewPager2
import com.iflytek.cyber.iot.show.core.R
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
private const val MIN_SCALE = 0.95f
private const val MIN_ALPHA = 0.7f
class DepthPageTransformer : ViewPager2.PageTransformer {
override fun transformPage(view: View, position: Float) {
view.apply {
val pageWidth = width
when {
position < -1 -> { // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0f
}
position <= 0 -> { // [-1,0]
// Use the default slide transition when moving to the left page
alpha = 1f
translationX = 0f
scaleX = 1f
scaleY = 1f
}
position <= 1 -> { // (0,1]
// Fade the page out.
alpha = 1 - position
// Counteract the default slide transition
translationX = pageWidth * -position
// Scale the page down (between MIN_SCALE and 1)
val scaleFactor = (MIN_SCALE + (1 - MIN_SCALE) * (1 - abs(position)))
scaleX = scaleFactor
scaleY = scaleFactor
}
else -> { // (1,+Infinity]
// This page is way off-screen to the right.
alpha = 0f
}
}
}
}
}
class FadeInPageTransformer : ViewPager2.PageTransformer {
override fun transformPage(view: View, position: Float) {
view.apply {
val pageWidth = width
when {
position <= -1 -> { // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0f
translationX = 0f
}
position <= 0 -> { // [-1,0]
// Use the default slide transition when moving to the left page
alpha = max(1f + 2 * position, 0f)
translationX = pageWidth * -position
}
position < 1 -> { // (0,1)
alpha = max(1f - 2 * position, 0f)
translationX = pageWidth * -position
}
else -> { // [1,+Infinity]
alpha = 0f
translationX = 0f
}
}
}
}
}
class ZoomOutPageTransformer : ViewPager2.PageTransformer {
override fun transformPage(view: View, position: Float) {
view.apply {
val pageWidth = width
val pageHeight = height
when {
position < -1 -> { // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0f
}
position <= 1 -> { // [-1,1]
// Modify the default slide transition to shrink the page as well
val scaleFactor = max(MIN_SCALE, 1 - abs(position))
val vertMargin = pageHeight * (1 - scaleFactor) / 2
val horzMargin = pageWidth * (1 - scaleFactor) / 2
translationX = if (position < 0) {
horzMargin - vertMargin / 2
} else {
horzMargin + vertMargin / 2
}
// Scale the page down (between MIN_SCALE and 1)
scaleX = scaleFactor
scaleY = scaleFactor
// Fade the page relative to its size.
alpha = (MIN_ALPHA +
(((scaleFactor - MIN_SCALE) / (1 - MIN_SCALE)) * (1 - MIN_ALPHA)))
}
else -> { // (1,+Infinity]
// This page is way off-screen to the right.
alpha = 0f
}
}
}
}
}
class CustomPageTransformer(private val pager: ViewPager2) : ViewPager2.PageTransformer, ViewPager2.OnPageChangeCallback() {
private var currentItem = 0
init {
pager.registerOnPageChangeCallback(this)
}
override fun transformPage(view: View, position: Float) {
view.apply {
val tvTitle: TextView? = view.findViewById(R.id.title)
val tvSummary: TextView? = view.findViewById(R.id.summary)
val recommendContainer: View? = view.findViewById(R.id.banner_container)
val pageWidth = width
val currentPosition = recommendContainer?.tag as? Int
val isEnter = currentItem != currentPosition
when {
position <= -1 -> { // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0f
translationX = 0f
}
position <= 0 -> { // [-1,0]
// Use the default slide transition when moving to the left page
if (isEnter) {
alpha = max(0f, position * 4 + 1)
// Counteract the default slide transition
translationX = -pageWidth * position
tvTitle?.translationX = pageWidth / 4 * position
tvSummary?.translationX = pageWidth / 4 * position
} else {
alpha = max(0f, position * 4 + 1)
translationX = pageWidth / 4 * -position * 3
}
}
position < 1 -> { // (0,1)
if (isEnter) {
alpha = max(0f, 1 - position * 4)
// Counteract the default slide transition
translationX = -pageWidth * position
tvTitle?.translationX = pageWidth / 4 * position
tvSummary?.translationX = pageWidth / 4 * position
} else {
alpha = max(0f, 1 - position * 4)
translationX = pageWidth / 4 * -position * 3
}
}
else -> { // [1,+Infinity]
alpha = 0f
translationX = 0f
}
}
}
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
if (positionOffset == 0f) {
currentItem = position
}
}
fun destroy() {
pager.unregisterOnPageChangeCallback(this)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.animation.Animator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.*
import android.os.Message
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.os.postDelayed
import androidx.core.view.GravityCompat
import androidx.core.view.isVisible
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.alibaba.fastjson.JSONException
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.gson.Gson
import com.iflytek.cyber.evs.sdk.RequestCallback
import com.iflytek.cyber.evs.sdk.agent.PlaybackController
import com.iflytek.cyber.evs.sdk.agent.VideoPlayer
import com.iflytek.cyber.evs.sdk.socket.Result
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.EngineService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.RecommendMediaAdapter
import com.iflytek.cyber.iot.show.core.adapter.VideoListAdapter
import com.iflytek.cyber.iot.show.core.api.MediaApi
import com.iflytek.cyber.iot.show.core.impl.speaker.EvsSpeaker
import com.iflytek.cyber.iot.show.core.impl.template.EvsTemplate
import com.iflytek.cyber.iot.show.core.impl.videoplayer.EvsVideoPlayer
import com.iflytek.cyber.iot.show.core.model.*
import com.iflytek.cyber.iot.show.core.recommend.RecommendAgent
import com.iflytek.cyber.iot.show.core.utils.BrightnessUtils
import com.iflytek.cyber.iot.show.core.utils.VoiceButtonUtils
import com.iflytek.cyber.iot.show.core.widget.BoxedVertical
import com.iflytek.cyber.iot.show.core.widget.ProgressFrameLayout
import com.kk.taurus.playerbase.AVPlayer
import com.kk.taurus.playerbase.widget.SuperContainer
import com.warkiz.widget.IndicatorSeekBar
import com.warkiz.widget.OnSeekChangeListener
import com.warkiz.widget.SeekParams
import okhttp3.Request
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.ref.SoftReference
import java.net.UnknownHostException
import java.util.*
import kotlin.Error
import kotlin.collections.ArrayList
import kotlin.math.abs
class VideoFragment : BaseFragment(), View.OnClickListener {
companion object {
private const val VOLUME_0 = 0f
private const val VOLUME_1 = 0.34444f
private const val VOLUME_2 = 0.66667f
private const val VOLUME_3 = 1f
private const val KEY_RECOMMEND = "recommend"
private const val KEY_URL = "url"
}
private lateinit var drawerLayout: DrawerLayout
private lateinit var videoList: RecyclerView
//private lateinit var progressBar: ProgressBar
private lateinit var seekBar: IndicatorSeekBar
private lateinit var playPause: ImageView
private lateinit var mainContent: RelativeLayout
private lateinit var alphaCover: View
private lateinit var tvVideoTitle: TextView
private lateinit var rootCover: View
private lateinit var brightnessProgress: ProgressFrameLayout
private lateinit var slideBar: FrameLayout
private lateinit var indicatorSlideBar: BoxedVertical
private lateinit var indicatorIcon: LottieAnimationView
private lateinit var volumeBar: FrameLayout
private lateinit var volumeSlideBar: BoxedVertical
private lateinit var volumeIcon: LottieAnimationView
private lateinit var volumeProgress: ProgressFrameLayout
private lateinit var ivPlayList: ImageView
private lateinit var tvPosition: TextView
private lateinit var tvDuration: TextView
private lateinit var loading: LottieAnimationView
/** 推荐相关*/
private lateinit var recommendLayout: LinearLayout
private lateinit var recommendView: RecyclerView
private var previousView: View? = null
private var nextView: View? = null
private val countFullScreenHandler = CountFullScreenHandler(this)
private var videoWakeLock: PowerManager.WakeLock? = null
private var videoListAdapter: VideoListAdapter? = null
private var seekDragging = false
private var handler = Handler(Looper.getMainLooper())
private var volumeAnimator: Animator? = null
private var animatingVolumeTo = 0f
private var backCount = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
launcher?.getService()?.getVideoPlayer()?.addListener(videoStateChangeListener)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return LayoutInflater.from(context).inflate(R.layout.fragment_video, container, false)
}
@SuppressLint("ClickableViewAccessibility")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
drawerLayout = view.findViewById(R.id.drawer)
brightnessProgress = view.findViewById(R.id.brightness_progress)
slideBar = view.findViewById(R.id.slide_bar)
indicatorSlideBar = view.findViewById(R.id.indicator_slide_bar)
indicatorIcon = view.findViewById(R.id.indicator_icon)
volumeBar = view.findViewById(R.id.volume_bar)
volumeProgress = view.findViewById(R.id.volume_progress)
volumeSlideBar = view.findViewById(R.id.volume_slide_bar)
volumeIcon = view.findViewById(R.id.volume_icon)
rootCover = view.findViewById(R.id.root_cover)
mainContent = view.findViewById(R.id.main_content)
tvVideoTitle = view.findViewById(R.id.tv_video_title)
alphaCover = view.findViewById(R.id.iv_alpha_cover)
videoList = view.findViewById(R.id.video_list)
//progressBar = view.findViewById(R.id.progress_bar)
loading = view.findViewById(R.id.loading)
seekBar = view.findViewById(R.id.seek_bar)
ivPlayList = view.findViewById(R.id.iv_play_list)
ivPlayList.setOnClickListener(this)
playPause = view.findViewById(R.id.iv_play_pause)
playPause.setOnClickListener(this)
tvPosition = view.findViewById(R.id.tv_position)
tvDuration = view.findViewById(R.id.tv_duration)
previousView = view.findViewById<ImageView>(R.id.iv_previous)
previousView?.setOnClickListener(this)
nextView = view.findViewById<ImageView>(R.id.iv_next)
nextView?.setOnClickListener(this)
recommendLayout = view.findViewById(R.id.llyt_recommend)
recommendView = view.findViewById(R.id.rcyc_recommend)
val back = view.findViewById<View>(R.id.back)
val renderContainer = view.findViewById<FrameLayout>(R.id.super_container)
renderContainer.setOnClickListener(this)
val superContainer = SuperContainer(renderContainer.context)
renderContainer.addView(
superContainer, ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
)
)
superContainer.setGestureEnable(false)
superContainer.setGestureScrollEnable(false)
superContainer.setOnClickListener {
updateControlUI()
}
val videoPlayerImpl = EvsVideoPlayer.get(context)
videoPlayerImpl.exitCallback = object : EvsVideoPlayer.ExitCallback {
override fun onRequestExit() {
if (!isDetached) {
pop()
}
}
}
videoPlayerImpl.setSuperContainer(superContainer)
seekBar.setProgress(videoPlayerImpl.getOffset().toFloat())
back.setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
val duration = launcher?.getService()?.getVideoPlayer()?.getDuration()
loading.isVisible = true
loading.playAnimation()
if (duration != null) {
tvDuration.text = format(duration)
}
seekBar.onSeekChangeListener = object : OnSeekChangeListener {
override fun onSeeking(seekParams: SeekParams) {
val position = format(seekParams.progress.toLong())
tvPosition.text = position
}
override fun onStartTrackingTouch(seekBar: IndicatorSeekBar?) {
seekDragging = true
}
override fun onStopTrackingTouch(seekBar: IndicatorSeekBar) {
seekDragging = false
val player = launcher?.getService()?.getVideoPlayer()
player?.seekTo(seekBar.progress.toLong())
}
}
mainContent.isVisible = false
alphaCover.isVisible = false
drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
override fun onDrawerStateChanged(newState: Int) {
}
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
}
override fun onDrawerClosed(drawerView: View) {
}
override fun onDrawerOpened(drawerView: View) {
autoCloseDrawer()
}
})
videoList.setOnTouchListener { v, event ->
autoCloseDrawer()
false
}
val contentResolver = launcher?.contentResolver
val currentBrightness = Settings.System.getInt(
contentResolver,
Settings.System.SCREEN_BRIGHTNESS
)
brightnessProgress.setProgress(currentBrightness * 100 / 255f)
val mode = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE)
brightnessProgress.setOnTouchProgressChangeListener(object :
ProgressFrameLayout.OnTouchProgressChangeListener {
override fun onDown() {
val brightness = BrightnessUtils.getBrightness(context)
brightnessProgress.setProgress(brightness.toFloat())
}
override fun onTouchProgressChanged(progress: Int) {
VoiceButtonUtils.lastTouchTime = System.currentTimeMillis()
if (!slideBar.isVisible) {
slideBar.isVisible = true
}
indicatorSlideBar.isEnable =
mode != Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
indicatorSlideBar.setValue(progress)
indicatorIcon.progress = progress / 100f
BrightnessUtils.setBrightness(context, progress)
}
override fun onStopTouch() {
VoiceButtonUtils.lastTouchTime = System.currentTimeMillis()
slideBar.isVisible = false
}
override fun onClick() {
superContainer.performClick()
}
})
val speaker = EvsSpeaker.get(context)
val currentVolume = speaker.getCurrentVolume()
volumeProgress.setProgress(currentVolume.toFloat())
setVolumeIcon(speaker.getCurrentVolume())
volumeProgress.setOnTouchProgressChangeListener(object :
ProgressFrameLayout.OnTouchProgressChangeListener {
override fun onDown() {
val volume = speaker.getCurrentVolume()
volumeProgress.setProgress(volume.toFloat())
setVolumeIcon(volume)
}
override fun onTouchProgressChanged(progress: Int) {
if (!volumeBar.isVisible) {
volumeBar.isVisible = true
}
volumeSlideBar.setValue(progress)
speaker.setVolumeLocally(progress)
val volume = speaker.getCurrentVolume()
setVolumeIcon(volume)
}
override fun onStopTouch() {
volumeBar.isVisible = false
}
override fun onClick() {
superContainer.performClick()
}
})
loadPlayList()
launcher?.registerCallback(simpleRenderCallback)
}
private fun setVolumeIcon(volume: Int) {
when {
volume == 0 -> {
animateVolumeTo(volumeIcon.progress, VOLUME_0)
}
volume in 1..32 -> {
animateVolumeTo(volumeIcon.progress, VOLUME_1)
}
volume in 33..66 -> {
animateVolumeTo(volumeIcon.progress, VOLUME_2)
}
volume >= 67 -> {
animateVolumeTo(volumeIcon.progress, VOLUME_3)
}
}
}
private fun format(duration: Long): String {
return String.format(
Locale.getDefault(),
"%2d:%02d",
duration / 1000 / 60,
duration / 1000 % 60
)
}
override fun onSupportVisible() {
super.onSupportVisible()
acquireVideoWakeLock()
launcher?.getService()?.requestVideoVisualFocus()
launcher?.getService()?.getVideoPlayer()?.isVisible = true
}
override fun onSupportInvisible() {
super.onSupportInvisible()
releaseVideoWakeLock()
launcher?.getService()?.getVideoPlayer()?.let { player ->
if (player.state == VideoPlayer.STATE_PLAYING) {
player.pause()
}
player.isVisible = false
}
}
private val simpleRenderCallback = object : EvsTemplate.SimpleRenderCallback() {
override fun renderVideoPlayerInfo(payload: String) {
videoListAdapter?.notifyDataSetChanged()
tryToLoadRecommend(payload)
}
}
private fun animateVolumeTo(from: Float, progress: Float) {
if (from == progress)
return
if (volumeAnimator?.isStarted == true) {
if (animatingVolumeTo == progress) {
// ignore
} else {
volumeAnimator?.cancel()
}
} else {
val animator = ValueAnimator.ofFloat(from, progress)
animatingVolumeTo = progress
animator.addUpdateListener {
val value = it.animatedValue as Float
volumeIcon.progress = value
}
animator.duration = (500 * abs(from - progress)).toLong()
animator.start()
volumeAnimator = animator
}
}
private fun autoCloseDrawer() {
handler.removeCallbacksAndMessages(null)
handler.postDelayed(20000) {
drawerLayout.closeDrawer(GravityCompat.END)
}
}
private val videoStateChangeListener = object : VideoPlayer.VideoStateChangedListener {
override fun onStarted(player: VideoPlayer, resourceId: String) {
loading.isVisible = true
loading.playAnimation()
loadPlayList()
}
override fun onResumed(player: VideoPlayer, resourceId: String) {
playPause.setImageResource(R.drawable.ic_music_pause)
}
override fun onPaused(player: VideoPlayer, resourceId: String) {
playPause.setImageResource(R.drawable.ic_music_play)
}
override fun onStopped(player: VideoPlayer, resourceId: String) {
playPause.setImageResource(R.drawable.ic_music_play)
if (ContentStorage.get().video?.resourceId == resourceId)
ContentStorage.get().saveVideo(null)
}
override fun onCompleted(player: VideoPlayer, resourceId: String) {
playPause.setImageResource(R.drawable.ic_music_play)
}
override fun onPositionUpdated(player: VideoPlayer, resourceId: String, position: Long) {
if (position > 0) {
if (loading.isVisible) {
loading.isVisible = false
loading.pauseAnimation()
}
rootCover.isVisible = false
playPause.setImageResource(R.drawable.ic_music_pause)
// SleepWorker.get(seekBar.context)
// .doTouchWork(seekBar.context) //video playing, do not show sleep view
}
if (!seekDragging) {
seekBar.max = player.getDuration().toFloat()
tvDuration.text = format(seekBar.max.toLong())
seekBar.setProgress(position.toFloat())
if (position in 1L..999) {
seekBar.showMusicPressState(true)
} else if (position >= 5000) {
seekBar.showMusicPressState(false)
seekBar.resetDraggerTimeFlag()
}
}
}
override fun onError(player: VideoPlayer, resourceId: String, errorCode: String) {
Log.e("VideoFragment", "play video error:$resourceId errorCode: $errorCode")
if (errorCode == VideoPlayer.MEDIA_ERROR_INVALID_REQUEST) {
}
}
}
@SuppressLint("WakelockTimeout")
private fun acquireVideoWakeLock() {
videoWakeLock?.acquire() ?: run {
val powerManager = context?.getSystemService(Context.POWER_SERVICE) as PowerManager
val flag = PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_BRIGHT_WAKE_LOCK
val wakeLock = powerManager.newWakeLock(flag, "iflytek:evs_video")
wakeLock.acquire()
videoWakeLock = wakeLock
}
}
private fun releaseVideoWakeLock() {
videoWakeLock?.release()
videoWakeLock = null
}
private fun setupRecyclerView(items: ArrayList<Song>) {
videoListAdapter = VideoListAdapter(items) {
drawerLayout.closeDrawer(GravityCompat.END)
playVideo(it)
}
videoList.adapter = videoListAdapter
val playingResource = ContentStorage.get().video?.resourceId
for (item in items) {
if (TextUtils.equals(playingResource, item.stream.token)) {
tvVideoTitle.text = item.metadata.title
}
}
}
private fun loadPlayList() {
getMediaApi()?.getPlayList("video")?.enqueue(object : Callback<PlayList> {
override fun onFailure(call: Call<PlayList>, t: Throwable) {
t.printStackTrace()
isNextPlayRecommend = false
ivPlayList.isVisible = false
if (t is UnknownHostException) {
val intent = Intent(EngineService.ACTION_SEND_REQUEST_FAILED)
intent.putExtra(
EngineService.EXTRA_RESULT,
Result(Result.CODE_DISCONNECTED, null)
)
context?.sendBroadcast(intent)
}
}
override fun onResponse(call: Call<PlayList>, response: Response<PlayList>) {
if (response.isSuccessful) {
val items = response.body()
items?.let {
if (it.playlist != null) {
if (it.playlist.isEmpty()) {
ivPlayList.isVisible = false
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
} else {
val isFirst =
it.playlist[0].stream.token == EvsVideoPlayer.get(context).resourceId
val isEnd =
it.playlist[it.playlist.size - 1].stream.token == EvsVideoPlayer.get(
context
).resourceId
previousView?.isEnabled = !isFirst
previousView?.alpha = if (isFirst) .5f else 1f
nextView?.isEnabled = !isEnd
nextView?.alpha = if (isEnd) .5f else 1f
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
ivPlayList.isVisible = true
// 当打开推荐内容时,要打开播放列表
if (isNextPlayRecommend) {
scrollToCurrentPosition()
if (!drawerLayout.isDrawerOpen(GravityCompat.END)) {
drawerLayout.openDrawer(GravityCompat.END)
}
}
}
setupRecyclerView(it.playlist)
}
ivPlayList.isVisible = !it.playlist.isNullOrEmpty()
} ?: run {
ivPlayList.isVisible = false
}
} else {
ivPlayList.isVisible = false
}
isNextPlayRecommend = false
}
})
}
private fun playVideo(song: Song) {
val body = MusicBody(null, song.stream.token, song.stream)
getMediaApi()?.playMusic(body)?.enqueue(object : Callback<String> {
override fun onResponse(call: Call<String>, response: Response<String>) {
if (response.isSuccessful) {
tvVideoTitle.text = song.metadata.title
} else {
showError(response.errorBody()?.string())
}
}
override fun onFailure(call: Call<String>, t: Throwable) {
t.printStackTrace()
if (t is UnknownHostException) {
val intent = Intent(EngineService.ACTION_SEND_REQUEST_FAILED)
intent.putExtra(
EngineService.EXTRA_RESULT,
Result(Result.CODE_DISCONNECTED, null)
)
context?.sendBroadcast(intent)
}
}
})
}
private fun showError(body: String?) {
try {
val error = Gson().fromJson(body, Error::class.java)
Toast.makeText(context, error?.message, Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun scrollToCurrentPosition() {
var position = -1
videoListAdapter?.videoList?.forEachIndexed { index, video ->
val playingId = ContentStorage.get().video?.resourceId
if (TextUtils.equals(playingId, video.stream.token)) {
position = index
return@forEachIndexed
}
}
if (position != -1) {
videoList.scrollToPosition(position)
}
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.iv_play_list -> {
scrollToCurrentPosition()
if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
drawerLayout.closeDrawer(GravityCompat.END)
} else {
drawerLayout.openDrawer(GravityCompat.END)
}
}
R.id.iv_next -> {
val playback = launcher?.getService()?.getPlaybackController()
playback?.sendCommand(PlaybackController.Command.Next, object :
RequestCallback {
override fun onResult(result: Result) {
if (!result.isSuccessful) {
val intent = Intent(EngineService.ACTION_SEND_REQUEST_FAILED)
intent.putExtra(EngineService.EXTRA_RESULT, result)
context?.sendBroadcast(intent)
}
}
})
}
R.id.iv_play_pause -> {
val player = EvsVideoPlayer.get(context)
if (player.resourceId.isNullOrEmpty()
|| player.getPlaybackState() == AVPlayer.STATE_STOPPED
) {
val playback = launcher?.getService()?.getPlaybackController()
playback?.sendCommand(PlaybackController.Command.Resume, object :
RequestCallback {
override fun onResult(result: Result) {
if (!result.isSuccessful) {
val intent = Intent(EngineService.ACTION_SEND_REQUEST_FAILED)
intent.putExtra(EngineService.EXTRA_RESULT, result)
context?.sendBroadcast(intent)
}
}
})
} else {
if (player.state == VideoPlayer.STATE_PLAYING) {
player.pause()
} else {
player.resume()
}
}
}
R.id.iv_previous -> {
val playback = launcher?.getService()?.getPlaybackController()
playback?.sendCommand(PlaybackController.Command.Previous, object :
RequestCallback {
override fun onResult(result: Result) {
if (!result.isSuccessful) {
val intent = Intent(EngineService.ACTION_SEND_REQUEST_FAILED)
intent.putExtra(EngineService.EXTRA_RESULT, result)
context?.sendBroadcast(intent)
}
}
})
}
R.id.super_container -> {
updateControlUI()
}
}
}
private fun updateControlUI() {
if (mainContent.isVisible) {
countFullScreenHandler.clearCount()
mainContent.isVisible = false
alphaCover.isVisible = false
} else {
countFullScreenHandler.postNextClick()
mainContent.isVisible = true
alphaCover.isVisible = true
}
}
private fun getMediaApi(): MediaApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(MediaApi::class.java)
} else {
null
}
}
override fun onDestroy() {
super.onDestroy()
val videoPlayer = EvsVideoPlayer.get(context)
videoPlayer.exitCallback = null
videoPlayer.realStop()
videoPlayer.removeListener(videoStateChangeListener)
ContentStorage.get().saveVideo(null)
launcher?.unregisterCallback(simpleRenderCallback)
}
private class CountFullScreenHandler(fragment: VideoFragment) : Handler() {
private val fragmentRef = SoftReference(fragment)
private var current = -1L
fun postNextClick() {
val newTime = System.currentTimeMillis()
val msg = Message.obtain()
msg.obj = newTime
msg.what = 1
current = newTime
sendMessageDelayed(msg, 5 * 1000)
}
fun clearCount() {
current = -1L
}
override fun handleMessage(msg: Message?) {
super.handleMessage(msg)
if (msg?.what == 1) {
val fragment = fragmentRef.get() ?: return
if (msg.obj == current) {
fragment.updateControlUI()
}
}
}
}
private fun setNoRecommend() {
recommendLayout.visibility = View.GONE
}
private var isNextPlayRecommend = false
private fun playRecommend(video: MediaEntity) {
val client = CoreApplication.from(context!!).getClient()
if (client != null) {
Log.d("playRecommendVideo", "${video.url}")
val request = Request.Builder().get()
.url(video.url!!)
.build()
val call = client.newCall(request)
try {
val response = call.execute()
if (response.isSuccessful) {
// val result = response.body()?.string();
// isNextPlayRecommend = true
Log.d("playRecommendVideo", "success")
} else {
isNextPlayRecommend = false
try {
val result = JSONObject.parseObject(response.body()?.string())
val message = result.getString("message")
Log.d("playRecommendVideo", "failed, result=$result")
post {
Toast.makeText(context!!, message, Toast.LENGTH_SHORT).show()
}
} catch (e: JSONException) {
post {
Toast.makeText(context!!, R.string.play_recommend_fail, Toast.LENGTH_SHORT).show()
}
}
}
} catch (e1: Exception) {
e1.printStackTrace()
isNextPlayRecommend = false
post {
Toast.makeText(context!!, R.string.play_recommend_fail, Toast.LENGTH_SHORT).show()
}
}
}
}
private fun tryToLoadRecommend(payload: String) {
if (!isAdded || context == null) {
return
}
try {
val json = JSONObject.parseObject(payload)
if (!json.containsKey(KEY_RECOMMEND) ||
json.getJSONObject(KEY_RECOMMEND).getString(KEY_URL).isNullOrEmpty()) {
setNoRecommend()
return
}
Thread {
val url = json.getJSONObject(KEY_RECOMMEND).getString(KEY_URL)
val videoList: List<MediaEntity>? = RecommendAgent.getRecommendList(context!!, url,
MediaEntity::class.java)
if (!videoList.isNullOrEmpty()) {
for (video in videoList) {
Glide.with(this)
.asBitmap()
.load(video.url)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.preload()
}
}
post {
if (videoList.isNullOrEmpty()) {
setNoRecommend()
} else {
// 显示推荐
recommendLayout.visibility = View.VISIBLE
val adapter = RecommendMediaAdapter()
adapter.setMediaType(RecommendMediaAdapter.MediaType.VIDEO)
adapter.setItems(videoList)
val layoutManager = LinearLayoutManager(context!!)
layoutManager.orientation = RecyclerView.HORIZONTAL
recommendView.layoutManager = layoutManager
recommendView.adapter = adapter
recommendView.overScrollMode = RecyclerView.OVER_SCROLL_NEVER
adapter.setOnItemClickListener(object : RecommendMediaAdapter
.OnItemClickListener {
override fun onItemClicked(view: View, position: Int) {
val video = (recommendView.adapter as RecommendMediaAdapter)
.getItem(position)
if (video != null) {
Thread {
playRecommend(video)
}.start()
}
}
})
adapter.notifyDataSetChanged()
// 如果用户持续触碰推荐item,则mainContent不消失
recommendView.addOnItemTouchListener(object: RecyclerView.OnItemTouchListener{
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
when (e.action) {
MotionEvent.ACTION_DOWN -> {
if (mainContent.isVisible) {
countFullScreenHandler.clearCount()
} else {
mainContent.isVisible = true
alphaCover.isVisible = true
}
}
MotionEvent.ACTION_UP -> {
if (mainContent.isVisible) {
countFullScreenHandler.clearCount()
countFullScreenHandler.postNextClick()
}
}
}
return false
}
override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
}
})
}
}
}.start()
} catch (e: JSONException) {
e.printStackTrace()
setNoRecommend()
}
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.record
/**
* 用于计算录音音量
*/
object RecordVolumeUtils {
const val AUDIO_METER_MAX_DB = 20f
@Suppress("MemberVisibilityCanBePrivate")
const val AUDIO_METER_MIN_DB = 0f
private var noiseLevel = 75f
fun calculateVolume(data: ByteArray, length: Int): Float {
val rms = calculateRms(data, length)
if (noiseLevel < rms) {
noiseLevel = 0.999f * noiseLevel + 0.001f * rms
} else {
noiseLevel = 0.95f * noiseLevel + 0.05f * rms
}
var db = -120f
if (noiseLevel.toDouble() > 0.0 && (rms / noiseLevel).toDouble() > 0.000001) {
db = 10f * Math.log10((rms / noiseLevel).toDouble()).toFloat()
}
return Math.min(Math.max(db, AUDIO_METER_MIN_DB), AUDIO_METER_MAX_DB)
}
private fun calculateRms(data: ByteArray, length: Int): Float {
if (data.isEmpty() || length == 0)
return 0f
var l1: Long = 0
var l2: Long = 0
val k = length / 2
var i = length
while (i >= 2) {
val j1 = (data[i - 1].toInt().shl(8)) + (0xff and data[i - 2].toInt())
l1 += j1.toLong()
l2 += (j1 * j1).toLong()
i -= 2
}
return Math.sqrt(((l2 * k.toLong() - l1 * l1) / (k * k).toLong()).toDouble()).toFloat()
}
}
<file_sep>/*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.utils
import android.content.res.ColorStateList
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.GradientDrawable
import android.view.View
import androidx.annotation.ColorInt
import androidx.recyclerview.widget.RecyclerView
/**
* A decoration which draws a horizontal divider between [RecyclerView.ViewHolder]s of a given
* type; with a left inset.
*/
class InsetDividerDecoration(
private val height: Int,
@ColorInt dividerColor: Int,
private val offset: Int) : RecyclerView.ItemDecoration() {
private val mDivider = GradientDrawable()
private val mBounds = Rect()
var startPadding = 0
var endPadding = 0
init {
// mDivider.color = ColorStateList.valueOf(dividerColor)
mDivider.setColor(dividerColor)
mDivider.setSize(0, height)
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (parent.layoutManager != null) {
this.drawVertical(c, parent)
}
}
private fun drawVertical(canvas: Canvas, parent: RecyclerView) {
canvas.save()
val left: Int
val right: Int
if (parent.clipToPadding) {
left = parent.paddingLeft
right = parent.width - parent.paddingRight
canvas.clipRect(left, parent.paddingTop, right, parent.height - parent.paddingBottom)
} else {
left = 0
right = parent.width
}
val childCount = parent.childCount
for (i in 0 until childCount - offset) {
val child = parent.getChildAt(i)
parent.getDecoratedBoundsWithMargins(child, this.mBounds)
val bottom = this.mBounds.bottom + Math.round(child.translationY)
val top = bottom - this.mDivider.intrinsicHeight
this.mDivider.setBounds(left + startPadding, top, right - endPadding, bottom)
this.mDivider.draw(canvas)
}
canvas.restore()
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
outRect.set(0, 0, 0, height)
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.utils
object RequestIdMap {
private const val TAG = "RequestIdMap"
private val requestTemplateIdMap = object : LinkedHashMap<String, String>() {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, String>?): Boolean {
return size > 100
}
} // requestId -> templateId
private val requestTtsIdMap = object : LinkedHashMap<String, String>() {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, String>?): Boolean {
return size > 100
}
} // requestId -> resourceId
fun putRequestTemplate(requestId: String, templateId: String) {
synchronized(requestTemplateIdMap) {
requestTemplateIdMap.iterator().run {
while (hasNext()) {
val next = next()
if (next.value == templateId)
remove()
}
}
requestTemplateIdMap.put(requestId, templateId)
}
}
fun putRequestTts(requestId: String, resourceId: String) {
synchronized(requestTtsIdMap) {
requestTtsIdMap.iterator().run {
while (hasNext()) {
val next = next()
if (next.value == resourceId)
remove()
}
}
requestTtsIdMap.put(requestId, resourceId)
}
}
fun findRequestByTts(resourceId: String): String? {
requestTtsIdMap.map {
if (it.value == resourceId) {
return it.key
}
}
return null
}
fun findRequestByTemplate(templateId: String): String? {
requestTemplateIdMap.map {
if (it.value == templateId) {
return it.key
}
}
return null
}
}<file_sep>package com.iflytek.cyber.evs.sdk.socket
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Result(
val code: Int,
val message: String?
) : Parcelable {
companion object {
const val CODE_SUCCEED = 0
const val CODE_DISCONNECTED = -1
const val CODE_UNINITIALIZED = -2
}
val isSuccessful: Boolean
get() = code == CODE_SUCCEED
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.app.Instrumentation
import android.view.KeyEvent
object NavigationUtils {
fun clickBack(
onSuccess: (() -> Unit)? = null,
onFailed: ((e: Exception) -> Unit)? = null
) {
Thread {
try {
val instrumentation = Instrumentation()
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)
onSuccess?.invoke()
} catch (e: Exception) {
e.printStackTrace()
onFailed?.invoke(e)
}
}.start()
}
}<file_sep>package com.iflytek.cyber.iot.show.core.api
import com.iflytek.cyber.iot.show.core.model.SkillDetail
import com.iflytek.cyber.iot.show.core.model.SkillSection
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
interface SkillApi {
@GET("v1/skill_sections")
fun getSkillSections(): Call<ArrayList<SkillSection>>
@GET("v1/skills/{id}")
fun getSkillDetail(@Path("id") id: String): Call<SkillDetail>
}<file_sep>#ifndef __CAE_INTF_H__
#define __CAE_INTF_H__
typedef void * CAE_HANDLE;
//angle 角度
//channel 虚拟波束编号
//power 波束能量
//CMScore 唤醒分值
//beam 麦克风编号
//userData 用户回调数据
typedef void (*cae_ivw_fn)(short angle, short channel, float power, short CMScore, short beam, char *param1, void *param2, void *userData);
//audioData 识别音频地址
//audioLen 识别音频字节数
//userData 用户回调数据
typedef void (*cae_audio_fn)(const void *audioData, unsigned int audioLen, int param1, const void *param2, void *userData);
//audioData 唤醒音频地址
//audioLen 唤醒音频字节数
//userData 用户回调数据
typedef void (*cae_ivw_audio_fn)(const void *audioData, unsigned int audioLen, int param1, const void *param2, void *userData);
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* 初始化实例(实例地址、资源地址、唤醒信息回调、唤醒音频回调、识别音频回调、预留参数、用户回调数据) */
int CAENew(CAE_HANDLE *cae, const char* resPath, cae_ivw_fn ivwCb, cae_ivw_audio_fn ivwAudioCb, cae_audio_fn audioCb, const char *param, void *userData);
typedef int (* Proc_CAENew)(CAE_HANDLE *cae, const char* resPath, cae_ivw_fn ivwCb, cae_ivw_audio_fn ivwAudioCb, cae_audio_fn audioCb, const char *param, void *userData);
/* 重新加载资源(实例地址、资源路径) */
int CAEReloadResource(CAE_HANDLE cae, const char* resPath);
typedef int (* Proc_CAEReloadResource)(CAE_HANDLE cae, const char* resPath);
/* 写入音频数据(实例地址、录音数据地址、录音数据长度) */
int CAEAudioWrite(CAE_HANDLE cae, const void *audioData, unsigned int audioLen);
typedef int (* Proc_CAEAudioWrite)(CAE_HANDLE cae, const void *audioData, unsigned int audioLen);
/* 设置麦克风编号(唤醒模式内部已经设置编号外部不用再次调用、手动模式需要调用设置麦克风编号) */
int CAESetRealBeam(CAE_HANDLE cae, int beam);
typedef int (* Proc_CAESetRealBeam)(CAE_HANDLE cae, int beam);
/* 获取版本号 */
char* CAEGetVersion();
typedef char (* Proc_CAEGetVersion)();
/* 销毁实例(实例地址) */
int CAEDestroy(CAE_HANDLE cae);
typedef int (* Proc_CAEDestroy)(CAE_HANDLE cae);
/* 设置日志级别(日志级别 0 调试、1 信息、2错误) */
int CAESetShowLog(int show_log);
typedef int (* Proc_CAESetShowLog)(int show_log);
/* 请求鉴权(设备授权编号)*/
int CAEAuth(char *sn);
typedef int (* Proc_CAEAuth)(char *sn);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __CAE_INTF_H__ */<file_sep>//
// Created by huang on 2019/1/25.
//
#include "log.h"
static bool gIsLogOn = true;
bool isLogOn()
{
return gIsLogOn;
}
void setLog(bool isOn)
{
gIsLogOn = isOn;
}<file_sep>package com.iflytek.cyber.evs.sdk.model
import android.os.Parcelable
import com.alibaba.fastjson.annotation.JSONField
import kotlinx.android.parcel.Parcelize
@Parcelize
data class DeviceCodeResponse(
@JSONField(name = "verification_uri") val verificationUri: String,
@JSONField(name = "user_code") val userCode: String,
val interval: Int,
@JSONField(name = "expires_in") val expiresIn: Int,
@JSONField(name = "device_code") val deviceCode: String
) : Parcelable<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Intent
import android.media.AudioManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.airbnb.lottie.LottieAnimationView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.SelfBroadcastReceiver
import com.iflytek.cyber.iot.show.core.impl.prompt.PromptManager
import com.iflytek.cyber.iot.show.core.impl.speaker.EvsSpeaker
import com.iflytek.cyber.iot.show.core.widget.BoxedHorizontal
import kotlin.math.abs
class VolumeFragment : BaseFragment() {
companion object {
private const val TAG = "VolumeFragment"
private const val VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION"
private const val EXTRA_VOLUME_STREAM_TYPE = "android.media.EXTRA_VOLUME_STREAM_TYPE"
private const val VOLUME_0 = 0f
private const val VOLUME_1 = 0.34444f
private const val VOLUME_2 = 0.66667f
private const val VOLUME_3 = 1f
}
private var mediaVolumeAnimationView: LottieAnimationView? = null
private var mediaVolumeSlider: BoxedHorizontal? = null
private var mediaVolumeAnimator: Animator? = null
private var mediaAnimatingVolumeTo = 0f
private var backCount = 0
private val volumeChangeReceiver = object : SelfBroadcastReceiver(VOLUME_CHANGED_ACTION) {
override fun onReceiveAction(action: String, intent: Intent) {
when (action) {
VOLUME_CHANGED_ACTION -> {
mediaVolumeSlider?.let { slider ->
val type = intent.getIntExtra(EXTRA_VOLUME_STREAM_TYPE, -1)
if (type == AudioManager.STREAM_MUSIC) {
if (!slider.isPressed) {
updateMediaVolume()
}
}
}
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
volumeChangeReceiver.register(context)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_volume, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
mediaVolumeAnimationView = view.findViewById(R.id.media_volume_icon)
mediaVolumeSlider = view.findViewById(R.id.media_volume_slider)
mediaVolumeSlider?.setOnBoxedPointsChangeListener(
object : BoxedHorizontal.OnValuesChangeListener {
override fun onPointsChanged(
boxedPoints: BoxedHorizontal,
points: Int,
fromTouch: Boolean
) {
if (!fromTouch)
return
val speaker = EvsSpeaker.get(context)
speaker.setVolumeLocally(points)
val volume = speaker.getCurrentVolume()
mediaVolumeAnimationView?.let { icon ->
val current = icon.progress
when {
volume == 0 -> {
animateMediaVolumeTo(current, VOLUME_0)
}
volume in 1..32 -> {
animateMediaVolumeTo(current, VOLUME_1)
}
volume in 33..66 -> {
animateMediaVolumeTo(current, VOLUME_2)
}
volume >= 67 -> {
animateMediaVolumeTo(current, VOLUME_3)
}
}
}
}
override fun onStartTrackingTouch(boxedPoints: BoxedHorizontal) {
}
override fun onStopTrackingTouch(boxedPoints: BoxedHorizontal) {
PromptManager.play(PromptManager.VOLUME)
}
})
post {
mediaVolumeSlider?.let { slider ->
EvsSpeaker.get(context).updateCurrentVolume()
if (!slider.isPressed) {
updateMediaVolume()
}
}
}
}
override fun onDestroy() {
super.onDestroy()
volumeChangeReceiver.unregister(context)
}
private fun updateMediaVolume() {
val volume = EvsSpeaker.get(context).getCurrentVolume()
mediaVolumeSlider?.let { slider ->
slider.value = volume
}
mediaVolumeAnimationView?.let { icon ->
val current = icon.progress
when {
volume == 0 -> {
animateMediaVolumeTo(current, VOLUME_0)
}
volume in 1..32 -> {
animateMediaVolumeTo(current, VOLUME_1)
}
volume in 33..66 -> {
animateMediaVolumeTo(current, VOLUME_2)
}
volume >= 67 -> {
animateMediaVolumeTo(current, VOLUME_3)
}
}
}
}
private fun animateMediaVolumeTo(from: Float, progress: Float) {
if (from == progress)
return
if (mediaVolumeAnimator?.isStarted == true) {
if (mediaAnimatingVolumeTo == progress) {
// ignore
} else {
mediaVolumeAnimator?.cancel()
}
} else {
val animator = ValueAnimator.ofFloat(from, progress)
mediaAnimatingVolumeTo = progress
animator.addUpdateListener {
val value = it.animatedValue as Float
mediaVolumeAnimationView?.progress = value
}
animator.duration = (500 * abs(from - progress)).toLong()
animator.start()
mediaVolumeAnimator = animator
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
fun Int.dp2Px() = ScreenUtils.dpToPx(this)
fun Float.dp2Px() = ScreenUtils.dpToPx(this).toFloat()<file_sep>package com.iflytek.cyber.iot.show.core.api
import com.iflytek.cyber.iot.show.core.model.Alert
import com.iflytek.cyber.iot.show.core.model.AlertBody
import com.iflytek.cyber.iot.show.core.model.Message
import retrofit2.Call
import retrofit2.http.*
interface AlarmApi {
@GET("v1/alerts")
fun getAlerts(): Call<ArrayList<Alert>>
@PUT("v1/alerts/{id}")
fun updateAlert(@Path("id") id: String, @Body body: AlertBody): Call<Message>
@POST("v1/alerts")
fun addNewAlarm(@Body body: AlertBody): Call<Message>
@DELETE("v1/alerts/{id}")
fun deleteAlarm(@Path("id") id: String): Call<Message>
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.content.res.ColorStateList
import android.graphics.Color
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.AlbumItem
import com.iflytek.cyber.iot.show.core.model.MediaItem
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
import com.iflytek.cyber.iot.show.core.utils.clickWithTrigger
import kotlin.math.min
class TemplateAppAlbumAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
const val TYPE_1P0 = 0
const val TYPE_1P6 = 1
const val TYPE_0P75 = 2
}
private val albumList = mutableListOf<AlbumItem>()
var onAlbumMoreClickListener: OnAlbumMoreClickListener? = null
var onSubItemClickListener: OnSubItemClickListener? = null
var ratio = 1f
var isDark = false
fun setAlbumList(albumList: List<AlbumItem>) {
this.albumList.clear()
this.albumList.addAll(albumList)
}
fun appendAlbumList(albumList: List<AlbumItem>) {
this.albumList.addAll(albumList)
}
fun getAlbumItem(position: Int) = if (position < albumList.size) albumList[position] else null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = when (viewType) {
TYPE_1P6 -> AlbumItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_album_1p6,
parent,
false
)
)
TYPE_1P0 -> AlbumItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_album_1p0,
parent,
false
)
)
else -> AlbumItemViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_album_0p75,
parent,
false
)
)
}
holder.childList.mapIndexed { index, mediaGroup ->
mediaGroup.ivAlbumMedia?.clickWithTrigger {
onSubItemClickListener?.onSubItemClick(
parent,
holder.itemView,
holder.adapterPosition,
index
)
}
}
holder.seeMore?.clickWithTrigger {
onAlbumMoreClickListener?.onAlbumMoreClick(
it,
albumList[holder.adapterPosition],
holder.adapterPosition
)
}
return holder
}
override fun getItemViewType(position: Int): Int {
return when {
ratio < 1 -> TYPE_0P75
ratio == 1f -> TYPE_1P0
else -> TYPE_1P6
}
}
override fun getItemCount(): Int {
return albumList.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is AlbumItemViewHolder) {
val childSize = holder.fullChildSize()
var indexSize = 0
for (i in 0 until position) {
indexSize += min(childSize, albumList[i].result?.size ?: 0)
}
holder.setupAlbum(albumList[position], isDark, indexSize)
}
}
private class AlbumItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvAlbumTitle: TextView? = itemView.findViewById(R.id.album_title)
val seeMore: View? = itemView.findViewById(R.id.album_more)
val tvMore: TextView? = itemView.findViewById(R.id.tv_more)
val ivMore: ImageView? = itemView.findViewById(R.id.iv_more)
val childList = listOf(
MediaGroup(
itemView,
R.id.album_media_0,
R.id.title_media_0,
R.id.subtitle_media_0,
R.id.index_media_0
),
MediaGroup(
itemView,
R.id.album_media_1,
R.id.title_media_1,
R.id.subtitle_media_1,
R.id.index_media_1
),
MediaGroup(
itemView,
R.id.album_media_2,
R.id.title_media_2,
R.id.subtitle_media_2,
R.id.index_media_2
),
MediaGroup(
itemView,
R.id.album_media_3,
R.id.title_media_3,
R.id.subtitle_media_3,
R.id.index_media_3
),
MediaGroup(
itemView,
R.id.album_media_4,
R.id.title_media_4,
R.id.subtitle_media_4,
R.id.index_media_4
)
)
fun setupAlbum(albumItem: AlbumItem, isDark: Boolean, indexFirst: Int) {
val childSize = fullChildSize()
tvAlbumTitle?.text = albumItem.album
seeMore?.isVisible =
!albumItem.result.isNullOrEmpty() && albumItem.result.size > childSize
if (isDark) {
seeMore?.setBackgroundResource(R.drawable.bg_round_border_50white_28dp)
tvAlbumTitle?.setTextColor(Color.WHITE)
tvMore?.setTextColor(Color.WHITE)
ivMore?.imageTintList = ColorStateList.valueOf(Color.WHITE)
} else {
seeMore?.setBackgroundResource(R.drawable.bg_round_border_grey_28dp)
tvAlbumTitle?.setTextColor(Color.BLACK)
tvMore?.setTextColor(Color.BLACK)
ivMore?.imageTintList = ColorStateList.valueOf(Color.BLACK)
}
for (i in 0 until childSize) {
if (i < albumItem.result?.size ?: 0) {
albumItem.result?.get(i)?.let { mediaItem ->
childList[i].setupMediaItem(
mediaItem,
isDark,
(indexFirst + i + 1).toString()
)
childList[i].setVisible(true)
} ?: run {
childList[i].setVisible(false)
}
} else {
childList[i].setVisible(false)
}
}
}
fun fullChildSize() = if (childList[3].exists()) 5 else 3
}
private class MediaGroup(
itemView: View,
albumId: Int,
titleId: Int,
subtitleId: Int,
indexId: Int
) {
val ivAlbumMedia: ImageView? = itemView.findViewById(albumId)
val tvAlbumTitle: TextView? = itemView.findViewById(titleId)
val tvAlbumSubtitle: TextView? = itemView.findViewById(subtitleId)
val tvAlbumIndex: TextView? = itemView.findViewById(indexId)
fun exists() = ivAlbumMedia != null
fun setVisible(isVisible: Boolean) {
ivAlbumMedia?.isVisible = isVisible
tvAlbumTitle?.isVisible = isVisible
tvAlbumSubtitle?.isVisible = isVisible
tvAlbumIndex?.isVisible = isVisible
}
fun setupMediaItem(mediaItem: MediaItem, isDark: Boolean, indexValue: String) {
tvAlbumTitle?.text = mediaItem.title
tvAlbumSubtitle?.text = mediaItem.subtitle
if (mediaItem.subtitle.isNullOrEmpty()) {
tvAlbumSubtitle?.height = 0
} else {
if (tvAlbumSubtitle?.height == 0) {
tvAlbumSubtitle.layoutParams = ConstraintLayout.LayoutParams(
0,
ConstraintLayout.LayoutParams.WRAP_CONTENT
).apply {
startToStart = tvAlbumTitle?.id ?: 0
topToBottom = tvAlbumTitle?.id ?: 0
endToEnd = tvAlbumTitle?.id ?: 0
}
}
}
tvAlbumIndex?.text = indexValue
if (isDark) {
tvAlbumTitle?.setTextColor(Color.WHITE)
tvAlbumSubtitle?.setTextColor(Color.WHITE)
} else {
tvAlbumTitle?.setTextColor(Color.BLACK)
tvAlbumSubtitle?.setTextColor(Color.BLACK)
}
ivAlbumMedia?.let { imageView ->
if (!mediaItem.cover.isNullOrEmpty()) {
try {
Uri.parse(mediaItem.cover)?.let { uri ->
Glide.with(imageView)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.transform(
MultiTransformation(
CenterCrop(), RoundedCornersTransformation(
imageView.resources.getDimensionPixelSize(
R.dimen.dp_6
), 0
)
)
)
.into(imageView)
}
} catch (t: Throwable) {
t.printStackTrace()
imageView.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
imageView.setImageResource(R.drawable.bg_default_template_app_2)
}
}
}
}
interface OnAlbumMoreClickListener {
fun onAlbumMoreClick(view: View, albumItem: AlbumItem, position: Int)
}
interface OnSubItemClickListener {
fun onSubItemClick(parent: ViewGroup, view: View, position: Int, subPosition: Int)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.impl.speaker
import android.content.Context
import android.media.AudioManager
import android.os.Build
import android.util.Log
import com.iflytek.cyber.evs.sdk.agent.Speaker
import java.lang.ref.SoftReference
import kotlin.math.ceil
import kotlin.math.roundToInt
class EvsSpeaker private constructor(context: Context) : Speaker() {
companion object {
private const val TAG = "EvsSpeaker"
private var speaker: EvsSpeaker? = null
fun get(context: Context?): EvsSpeaker {
speaker?.let {
return it
} ?: run {
val newSpeaker = EvsSpeaker(context!!)
this.speaker = newSpeaker
return newSpeaker
}
}
}
private var currentVolume = 0
private val contextRef = SoftReference(context)
private var muteCount = 0
var isAudioFocusGain = false
var isVisualFocusGain = false
val isFocusGain: Boolean
get() = isAudioFocusGain || isVisualFocusGain
private var cacheVolume = -1
private val listeners = HashSet<OnVolumeChangedListener>()
init {
(context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager)?.let { audioManager ->
val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
val min =
if (Build.VERSION.SDK_INT > 29)
audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
else
0
val volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
currentVolume = ceil((volume - min) * 100f / (max - min)).roundToInt()
}
}
fun refreshNativeAudioFocus(context: Context) {
if (isFocusGain) {
requestNativeAudioFocus(context)
} else {
abandonNativeAudioFocus(context)
}
}
private fun setMusicVolume(context: Context?, volume: Int) {
if (isFocusGain) {
cacheVolume = volume
} else {
val am = context?.getSystemService(Context.AUDIO_SERVICE) as? AudioManager ?: return
am.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0)
}
}
private fun requestNativeAudioFocus(context: Context) {
Log.v(TAG, "requestNativeAudioFocus")
val am = context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager ?: return
Log.v(TAG, "setMute")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!am.isStreamMute(AudioManager.STREAM_MUSIC))
am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, 0)
} else {
am.setStreamMute(AudioManager.STREAM_MUSIC, true)
muteCount++
}
}
private fun abandonNativeAudioFocus(context: Context) {
Log.v(TAG, "abandonNativeAudioFocus")
val am = context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager ?: return
if (cacheVolume == -1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Log.v(TAG, "setUnmute")
if (am.isStreamMute(AudioManager.STREAM_MUSIC))
am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, 0)
} else {
while (muteCount > 0) {
Log.v(TAG, "setUnmute")
muteCount--
am.setStreamMute(AudioManager.STREAM_MUSIC, false)
}
}
} else {
Log.v(TAG, "set volume to $cacheVolume")
am.setStreamVolume(AudioManager.STREAM_MUSIC, cacheVolume, 0)
cacheVolume = -1
}
}
fun updateCurrentVolume() {
if (isFocusGain)
return
(contextRef.get()?.getSystemService(Context.AUDIO_SERVICE) as? AudioManager)?.let { audioManager ->
val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
val min =
if (Build.VERSION.SDK_INT > 29)
audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
else
0
val volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
currentVolume = ((volume - min) * 100f / (max - min)).roundToInt()
listeners.map {
try {
it.onVolumeChanged(currentVolume, false)
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
}
fun addOnVolumeChangedListener(listener: OnVolumeChangedListener) {
listeners.add(listener)
}
fun removeOnVolumeChangedListener(listener: OnVolumeChangedListener) {
listeners.remove(listener)
}
override fun getCurrentVolume(): Int {
return currentVolume
}
fun raiseVolumeLocally(fakeRemote: Boolean = false): Boolean {
(contextRef.get()?.getSystemService(Context.AUDIO_SERVICE) as? AudioManager)
?.let { audioManager ->
audioManager.adjustStreamVolume(
AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE,
0
)
val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
val min =
if (Build.VERSION.SDK_INT > 29)
audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
else
0
val volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
currentVolume = ((volume - min) * 100f / (max - min)).roundToInt()
listeners.map {
try {
it.onVolumeChanged(currentVolume, fakeRemote)
} catch (t: Throwable) {
t.printStackTrace()
}
}
return true
}
return false
}
fun lowerVolumeLocally(fakeRemote: Boolean = false): Boolean {
(contextRef.get()?.getSystemService(Context.AUDIO_SERVICE) as? AudioManager)
?.let { audioManager ->
audioManager.adjustStreamVolume(
AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER,
0
)
val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
val min =
if (Build.VERSION.SDK_INT > 29)
audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
else
0
val volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
currentVolume = ((volume - min) * 100f / (max - min)).roundToInt()
listeners.map {
try {
it.onVolumeChanged(currentVolume, fakeRemote)
} catch (t: Throwable) {
t.printStackTrace()
}
}
return true
}
return false
}
fun setVolumeLocally(volume: Int): Boolean {
(contextRef.get()?.getSystemService(Context.AUDIO_SERVICE) as? AudioManager)
?.let { audioManager ->
val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
val min =
if (Build.VERSION.SDK_INT > 29)
audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
else
0
val realVolume = (ceil(volume * (max - min) / 100f + min)).roundToInt()
setMusicVolume(contextRef.get(), realVolume)
currentVolume = volume
listeners.map {
try {
it.onVolumeChanged(currentVolume, false)
} catch (t: Throwable) {
t.printStackTrace()
}
}
return true
}
return false
}
override fun setVolume(volume: Int): Boolean {
(contextRef.get()?.getSystemService(Context.AUDIO_SERVICE) as? AudioManager)
?.let { audioManager ->
val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
val min =
if (Build.VERSION.SDK_INT > 29)
audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
else
0
val realVolume = (ceil(volume * (max - min) / 100f + min)).roundToInt()
setMusicVolume(contextRef.get(), realVolume)
currentVolume = volume
listeners.map {
try {
it.onVolumeChanged(currentVolume, true)
} catch (t: Throwable) {
t.printStackTrace()
}
}
return true
}
return false
}
interface OnVolumeChangedListener {
fun onVolumeChanged(volume: Int, fromRemote: Boolean)
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent
import com.iflytek.cyber.evs.sdk.model.Constant
/**
* 屏幕控制模块。详细介绍见https://doc.iflyos.cn/device/evs/reference/screen.html#%E5%B1%8F%E5%B9%95%E6%8E%A7%E5%88%B6
*/
abstract class Screen {
val version = "1.2"
companion object {
const val NAME_SET_STATE = "${Constant.NAMESPACE_SCREEN}.set_state"
const val NAME_SET_BRIGHTNESS = "${Constant.NAMESPACE_SCREEN}.set_brightness"
const val KEY_TYPE = "type"
const val KEY_STATE = "state"
const val KEY_BRIGHTNESS = "brightness"
const val STATE_ON = "ON"
const val STATE_OFF = "OFF"
const val TYPE_PERCENT = "percent"
}
/**
* 获取亮度值类型,暂时只支持百分比。
*/
open fun getBrightnessType() = TYPE_PERCENT
/**
* 设置屏幕状态。
* @param state 状态:ON(打开)、OFF(熄屏)
* @return 是否设置成功
*/
abstract fun setState(state: String): Boolean
/**
* 获取屏幕状态。
* @return 状态:ON(打开)、OFF(熄屏)
*/
abstract fun getState(): String
/**
* 设置屏幕亮度。
* @param brightness 亮度值(0-100)
* @return 是否设置成功
*/
abstract fun setBrightness(brightness: Long): Boolean
/**
* 获取屏幕亮度。
* @return 亮度值(0-100)
*/
abstract fun getBrightness(): Long
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.text.TextUtils
class EvaluationUtils {
private val chineseWordList = arrayListOf(
"掐", "女", "丈", "埋", "损", "丁", "暖",
"对", "促", "铜", "任", "卡", "古",
"揭", "丸", "吞", "抓", "修", "荡", "旺", "摔", "脸", "热", "把", "耗",
"平", "筛", "亏", "否", "瓦", "棍", "松", "匀",
"女", "用", "喜", "说", "揣", "咱", "佛", "此", "勋", "院",
"子", "钻", "牙", "民", "饭", "北", "何", "凋", "坡",
"观", "骗", "荒", "烤", "赔", "级", "贪", "抢", "风", "理", "缤",
"能", "锅", "邻", "口", "而", "翁", "掠", "羊", "思", "捏", "灾",
"穷", "体", "描", "月", "容", "参", "歪",
"续", "贴", "搜", "场", "拨", "是", "支", "窗", "目",
"耻", "掘", "熬", "嘎", "舟", "纲", "押", "帘", "柠", "拽", "慌", "泉", "洒", "开", "揉",
"昂", "别", "件", "揣", "脓", "群", "吓", "债", "产", "檬", "跌", "宾", "铺",
"锐", "综", "迅", "扯", "柴", "删", "风", "夜", "心", "属", "最", "从",
"源", "舍", "赔", "嫩", "坑", "条",
"饮", "塑", "断", "女", "窘", "恶", "费", "狠", "笔", "脚", "亮", "垮", "暖", "绿",
"琼", "池", "给", "坯", "要", "象", "画", "窜", "虐",
"凶", "狮", "贸", "方", "邸", "牛", "洋", "博", "顿", "思", "烤", "浪", "下",
"六", "艇", "某", "托",
"润", "匡", "缺", "捐", "俩", "您", "惨", "肯", "筒", "肿", "疼", "平", "仍", "覃"
)
private val chineseWordsList = arrayListOf(
"迥然", "虐政", "可观", "旅伴", "谱写", "女婿", "老头儿", "高原", "摘要", "迷信", "摧残",
"婆家", "犬马", "穷酸", "贴切", "否则", "衬衫", "能够", "作废", "吹牛", "调查", "仇恨", "刚才", "软件",
"怀念", "军饷", "丁零", "主编", "差点儿", "朋友", "哈哈", "亲爱", "爽快", "花纹", "粗粮", "狂妄", "东风",
"角色", "揣测", "刷子", "聊天儿", "篮球", "寒冷", "航空", "下来", "阔气", "捆绑", "浑身", "没事儿", "巡逻",
"凉粉", "旅途", "挂号", "存在", "捐款", "僧侣", "老头儿", "日常", "罪责", "晒台", "衰弱", "快乐", "学会", "补贴",
"散漫", "参加", "面条儿", "温柔", "喧闹", "牛皮", "窘况", "雄伟", "军队", "群众", "穷人", "省长", "女性", "刀把儿",
"别的", "压迫", "民兵", "马虎", "权贵", "觉悟", "确定", "困难", "理睬", "揣测", "童话", "酿造"
)
private val chineseSentenceList = arrayListOf(
"登月太空飞船飞行时拍摄的照片显示出,地球是一个表面由蓝色和白色构成的美丽的球体。",
"夜从浓浓的蓝黑逐渐浅淡,终于变成带点银灰的乳色。",
"时常,夏日清晨的鸟唱是最轻悄的,像是不忍吵醒那将睡的夜,像是牵挂着那将要隐入林后的夜风。",
"清晨的林术有醉人的清香。那么醇,那么厚,使你不由自主地深深呼吸、闻嗅吸饮那如洒的甘冽。",
"他的脸上呈现出一个悲剧,一张涵蓄了许多愁苦和力量的脸。",
"瞧,它多美丽,娇巧的小嘴,啄理着绿色的羽毛,鸭子样的扁脚,呈现出春草的鹅黄。",
"控制紧张情绪的最佳做法是选择你有所了解并感兴趣的话题。",
"爷爷说,只有那不畏艰险的勇士,才能走进大海的世界,得到幸福和安宁。",
"我盼着长大的一天,骑着骏马,去寻找那迷人的大海。",
"在我的后园,可以看见墙外有两株树,一株是枣树,还有一株也是枣树。",
"人若能知足,虽贫不苦;若能安分,虽失意不苦;",
"母亲本不愿出来的,她老了,身体不好,走远一点儿就觉得很累。",
"那里有金色的菜花,两行整齐的桑树,尽头一口水波粼粼的鱼塘。",
"落叶在欢迎早起者的脚步, 要他们快来欣赏树梢头那更多的新叶 , 与它们身边初放的晨花 。",
"北京的导游跑断腿,西安的导游磨破嘴,海南的导游晒脱水。",
"童年的记忆是河边的那片空地,撒欢儿似的疯跑,欢笑着的追赶,摔跤后的哭喊。",
"秋冬之季,小草熟睡,绿树脱衣,只有松柏依然挺拔。",
"人类赖以生存和发展的环境受到了严峻挑战,生态环境遭到了严重破坏,各种污染事故频频发生。",
"如果二十岁的心像小溪,三十岁的心像小河,四十岁的心像条江。那么,五十岁的心就是大海。",
"成功也并非只有坚持这一条路,适时的认输,适时的放弃,懂得变通,同样也是一种成功智慧。",
"人生本来就是这样,我们如今所遭遇的,放不下的,不过是漫长生命里的沧海一粟。",
"雨还在下着,将操场清刷得一片清新,绿色的草坪,红色的跑道,赏心悦目。",
"回忆,不会仅仅是酸涩的泪水和离情别绪,一如时间之琼酿,总是越陈越香。",
"一池碧蓝的湖水,水鸟贴着水面飞翔,水边金黄色的芦苇草随风轻轻摇摆。",
"流淌的夜色,一如既往的深沉,被月光覆盖的街道,忧伤与思念共舞,洒满了我孤寂的心灵。",
"我敞开胸襟,呼吸着海香很浓的风,开始领略书本里汹涌的内容,澎湃的情思,伟大而深邃的哲理。",
"也就在这个时候,喜悦突然象涌上海面的潜流,滚过我的胸间,使我暗暗地激动。",
"一阵风吹来,树枝轻轻地摇晃,美丽的银条儿和雪球儿簇簇地落下来,玉屑似的雪末儿随风飘扬;",
"客人带着好像敬畏又好像怜惜的神情,默不作声地望着他。"
)
private val englishWordList = arrayListOf(
"volume", "excess", "bake", "dense", "vague", "inference", "chimney", "flexibility ",
"intensify", "weld", "chop", "thrill", "defy", "heave", "forum", "architecture",
"thermos", "filmmaker", "consent", "cereal",
"pit", "grace", "mystery", "undergo", "medium", "existence", "elect",
"accuse", "exclusive", "constitute", "depend", "general",
"venture", "recover", "clap", "contain", "continent", "vain", "indifferent"
, "universe", "ashamed", "vivid", "bakery", "cost",
"soar", "extraordinary", "conservative", "bold", "classify", "magnetic",
"craft", "exaggerate", "rid", "spur", "frequency",
"delivery", "resume", "alternative", "violence", "intensity", "portable",
"eliminate", "plunge", "impulse", "funeral",
"majority", "bend", "triangle", "slender", "scout", "furnace", "brow",
"fluent", "distress", "excess", "agent", "appropriate",
"transfer", "rarely", "headline", "emphasize", "interval", "interfere",
"community", "contemporary", "demonstrate",
"beneficial", "appearance", "undertake", "mental", "worthwhile", "prior",
"invitation", "proud", "undergraduate",
"prospect", "source", "infect", "scheme", "breeze", "lane", "corruption",
"dominant", "fuss", "tanker", "plausible",
"illustration", "horsepower", "radar", "deck", "struggle", "bolt", "weave",
"atomic", "stale", "astronomer", "prime",
"halt", "plague", "torture", "diagram", "anticipate", "modify", "protective", "relate"
)
private val englishSentenceList = arrayListOf(
"Would you please open the door for me?",
"May I ask you a question?",
"Get me my coat, please.",
"Make me a cup of coffee, will you?",
"Call me tomorrow if you have time.",
"I don’t feel very well.",
"He’s got a bad headache.",
"It’s bleeding. You’d better see a doctor about that cut.",
"Take two pills and have a good rest.",
"He was absent yesterday. Do you know why?",
"What you have said about this is very interesting.",
"There are always two sides to everything.",
"I don't know for sure.",
"I've done my best.",
"What’s wrong with you?",
"Today we are going to learn some new words.",
"It’s time to go to bed. ",
"You’re making progress everyday.",
"Excuse me, what’s the time, please? ",
"I like to draw pictures there.",
"I would like to talk to you for a minute.",
"I didn’t mean to offend you.",
"When he was young, he liked to try out new ideas.",
"We can not live without air. ",
"Tom has never done such a thing.",
"Why did Jim go to the hospital yesterday?",
"Ability may get you to the top, but it takes character to keep you there.",
"The important thing in life is to have a great aim, and the determination to attain it. ",
"I enjoy warm in time. I forget blooms in the internal.",
"The fingers will not move, tears will not flow, the time will not go.",
"I want to be strong that nothing can disturb your peace of mind.",
"The time is so precious, just a second toilet by other people robbed.",
"They never seem to say goodbye. And every time is never.",
"Most people want to transform the world, but few people want to change their own.",
"Not caring, is precisely the existence of respect for others.",
"When you use knowledge, you will find you haven't enough.",
"If you keep bothering me, I shall have to dismiss you."
)
private val englishArticleList = arrayListOf(
"Youth is not a time of life; it is a state of mind. It is not a matter of rosy cheeks, red lips and supple knees. It is a matter of the will, a quality of the imagination, vigor of the emotions; it is the freshness of the deep spring of life.",
"The first drops of rain are huge; they split into the dust on the ground, and plunk on the roof. The rain now becomes a torrent, flung by a rising wind. Together they batter the trees and level the grasses. Water streams off roofs.",
"The most beautiful part of spring is sawn. The east side of the sky turns into a grayish color. From the green trees, the chirping of the birds can be heard. The grass is soft and green on the side of the road, they quietly welcome mother earth to wake up.",
"A good book may be among the best of friends. It is the same today that it always was, and it will never change. It is the most patient and cheerful of companions. It does not turn its back upon us in times of adversity or distress.",
"Since I was a child I dream to be a scientist. I think a good scientist can make the world change a lot. If I become a scientist, I will make the desert cover with green trees, make the war never take places and make disaster get far away from people.",
"You can try to write your objective on paper and make some plans to achieve it.In this way,you will know how to arrange your time and to spend your time properly.",
"""We Must Face Failure.As we all know, "Failure is the mother of success." But few people can really understand what the saying means.In the world, In fact, failure is not fearful, but important thing is how to face it correctly.""",
"A man may usually be known by the books he reads as well as by the company he keeps; for there is a companionship of books as well as of men; and one should always live in the best company, whether it be of books or of men.",
"We are not born with courage, but neither are we born with fear. Maybe some of our fears are brought on by your own experiences, by what someone has told you, by what you’ve read in the papers.",
"Lost time is never found again. This is something which I learned very clearly last semester. I spent so much time fooling around that my grades began to suffer. I finally realized that something had to be done."
)
fun getChineseSingleList(): ArrayList<String> {
val wordLength = chineseWordList.size
val hashSet = HashSet<String>()
while(hashSet.size < 10){
val index = (0 until wordLength).random()
val word = chineseWordList[index]
hashSet.add(word)
}
return ArrayList(hashSet)
}
fun getChineseWordsList(): ArrayList<String> {
val wordLength = chineseWordsList.size
val hashSet = HashSet<String>()
while(hashSet.size < 10){
val index = (0 until wordLength).random()
val word = chineseWordsList[index]
hashSet.add(word)
}
return ArrayList(hashSet)
}
fun getChineseSentence(): String? {
val wordLength = chineseSentenceList.size
val index = (0 until wordLength).random()
if (index in 0 until wordLength) {
return chineseSentenceList[index]
}
return null
}
fun getEnglishSingleWordList(): ArrayList<String> {
val wordLength = englishWordList.size
val hashSet = HashSet<String>()
while(hashSet.size < 10){
val index = (0 until wordLength).random()
val word = englishWordList[index]
hashSet.add(word)
}
return ArrayList(hashSet)
}
fun getEnglishSentence(): String? {
val wordLength = englishSentenceList.size
val index = (0 until wordLength).random()
if (index in 0 until wordLength) {
return englishSentenceList[index]
}
return null
}
fun getEnglishArticle(): String? {
val wordLength = englishArticleList.size
val index = (0 until wordLength).random()
if (index in 0 until wordLength) {
return englishArticleList[index]
}
return null
}
fun getPunctuationList(text: String): ArrayList<String> {
val list = ArrayList<String>()
for (str in text) {
val value = str.toString()
if (TextUtils.equals(",", value) ||
TextUtils.equals(".", value) ||
TextUtils.equals(",", value) ||
TextUtils.equals("。", value) ||
TextUtils.equals("?", value) ||
TextUtils.equals(";", value)
) {
list.add(value)
}
}
return list
}
/**
* 移除英文字母
*/
fun filterSentence(sentence: String?): String? {
return sentence?.replace(Regex("[a-zA-Z0-9<>]"), "")
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.retrofit
import android.os.Build
import java.io.IOException
import java.net.InetAddress
import java.net.Socket
import java.net.UnknownHostException
import java.security.GeneralSecurityException
import java.util.Arrays
import java.util.HashSet
import java.util.LinkedList
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509TrustManager
// 兼容 Android 4.4 及以下不支持 SSLv3 的请求
class SSLSocketFactoryCompat(tm: X509TrustManager?) : SSLSocketFactory() {
private var defaultFactory: SSLSocketFactory? = null
init {
try {
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(null, if (tm != null) arrayOf(tm) else null, null)
defaultFactory = sslContext.socketFactory
} catch (e: GeneralSecurityException) {
throw AssertionError() // The system has no TLS. Just give up.
}
}
private fun upgradeTLS(ssl: SSLSocket) {
// Android 5.0+ (API level21) provides reasonable default settings
// but it still allows SSLv3
// https://developer.android.com/about/versions/android-5.0-changes.html#ssl
if (protocols != null) {
ssl.enabledProtocols = protocols
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && cipherSuites != null) {
ssl.enabledCipherSuites = cipherSuites
}
}
override fun getDefaultCipherSuites(): Array<String>? {
return cipherSuites
}
override fun getSupportedCipherSuites(): Array<String>? {
return cipherSuites
}
@Throws(IOException::class)
override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean): Socket {
val ssl = defaultFactory!!.createSocket(s, host, port, autoClose)
if (ssl is SSLSocket)
upgradeTLS(ssl)
return ssl
}
@Throws(IOException::class, UnknownHostException::class)
override fun createSocket(host: String, port: Int): Socket {
val ssl = defaultFactory!!.createSocket(host, port)
if (ssl is SSLSocket)
upgradeTLS(ssl)
return ssl
}
@Throws(IOException::class, UnknownHostException::class)
override fun createSocket(host: String, port: Int, localHost: InetAddress, localPort: Int): Socket {
val ssl = defaultFactory!!.createSocket(host, port, localHost, localPort)
if (ssl is SSLSocket)
upgradeTLS(ssl)
return ssl
}
@Throws(IOException::class)
override fun createSocket(host: InetAddress, port: Int): Socket {
val ssl = defaultFactory!!.createSocket(host, port)
if (ssl is SSLSocket)
upgradeTLS(ssl)
return ssl
}
@Throws(IOException::class)
override fun createSocket(address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int): Socket {
val ssl = defaultFactory!!.createSocket(address, port, localAddress, localPort)
if (ssl is SSLSocket)
upgradeTLS(ssl)
return ssl
}
companion object {
// Android 5.0+ (API level21) provides reasonable default settings
// but it still allows SSLv3
// https://developer.android.com/about/versions/android-5.0-changes.html#ssl
internal var protocols: Array<String>? = null
internal var cipherSuites: Array<String>? = null
init {
try {
val socket = SSLSocketFactory.getDefault().createSocket()
if (socket is SSLSocket) {
/* set reasonable protocol versions */
// - enable all supported protocols (enables TLSv1.1 and TLSv1.2 on Android <5.0)
// - remove all SSL versions (especially SSLv3) because they're insecure now
val protocols = LinkedList<String>()
for (protocol in socket.supportedProtocols)
if (!protocol.toUpperCase().contains("SSL"))
protocols.add(protocol)
SSLSocketFactoryCompat.protocols = protocols.toTypedArray()
/* set up reasonable cipher suites */
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
// choose known secure cipher suites
val allowedCiphers = Arrays.asList(
// TLS 1.2
"TLS_RSA_WITH_AES_256_GCM_SHA384",
"TLS_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
"TLS_ECHDE_RSA_WITH_AES_128_GCM_SHA256",
// maximum interoperability
"TLS_RSA_WITH_3DES_EDE_CBC_SHA",
"TLS_RSA_WITH_AES_128_CBC_SHA",
// additionally
"TLS_RSA_WITH_AES_256_CBC_SHA",
"TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA")
val availableCiphers = Arrays.asList(*socket.supportedCipherSuites)
// take all allowed ciphers that are available and put them into preferredCiphers
val preferredCiphers = HashSet(allowedCiphers)
preferredCiphers.retainAll(availableCiphers)
/* For maximum security, preferredCiphers should *replace* enabled ciphers (thus disabling
* ciphers which are enabled by default, but have become unsecure), but I guess for
* the security level of DAVdroid and maximum compatibility, disabling of insecure
* ciphers should be a server-side task */
// add preferred ciphers to enabled ciphers
preferredCiphers.addAll(HashSet(Arrays.asList(*socket.enabledCipherSuites)))
SSLSocketFactoryCompat.cipherSuites = preferredCiphers.toTypedArray()
}
}
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.content.Context
import android.content.SharedPreferences
import androidx.annotation.Nullable
object ConfigUtils {
private const val PREF_NAME = "com.iflytek.cyber.iot.show.core.CONFIG"
const val KEY_RECOGNIZER_PROFILE = "recognizer_profile"
const val KEY_SCREEN_AUTO_LOCK = "screen_auto_lock"
const val KEY_CACHE_USER_INFO = "cache_user_info"
const val KEY_VOICE_WAKEUP_ENABLED = "voice_wakeup_enabled"
const val KEY_VOICE_BUTTON_ENABLED = "voice_button_enabled"
const val KEY_SETUP_COMPLETED = "setup_completed"
const val KEY_VERSION_CODE = "version_code"
const val KEY_OTA_REQUEST = "ota_request"
const val KEY_OTA_VERSION_ID = "ota_version_id"
const val KEY_OTA_VERSION_NAME = "ota_version_name"
const val KEY_OTA_VERSION_DESCRIPTION = "ota_version_description"
const val KEY_BANNERS = "banners"
const val KEY_BACKGROUND_RECOGNIZE = "background_recognize"
const val KEY_DEVELOPER_OPTIONS = "developer_options"
const val KEY_CLIENT_ID = "client_id"
const val KEY_OTA_DISABLED = "ota_enabled"
const val KEY_CACHE_WAKE_WORD = "cache_wake_word"
const val KEY_WAKE_WORD_SUCCEED = "wake_word_succeed"
const val KEY_SLEEP_TIME = "sleep_time"
const val KEY_RESPONSE_SOUND = "response_sound"
const val KEY_WAKE_UP_SOUND = "wake_up_sound"
private var pref: SharedPreferences? = null
private val listeners = HashSet<OnConfigChangedListener>()
private val onSharedPreferenceChangeListener =
SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
listeners.map {
try {
it.onConfigChanged(key, sharedPreferences.all[key])
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun init(context: Context) {
if (pref != null)
return
pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
pref?.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener)
}
fun registerOnConfigChangedListener(listener: OnConfigChangedListener) {
listeners.add(listener)
}
fun unregisterOnConfigChangedListener(listener: OnConfigChangedListener) {
listeners.remove(listener)
}
fun destroy() {
pref?.unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener)
}
/**
* Set a String value in the preferences editor, to be written back once
* [.commit] or [.apply] are called.
*
* @param key The name of the preference to modify.
* @param value The new value for the preference. Passing `null`
* for this argument is equivalent to calling [.remove] with
* this key.
*
*/
fun putString(key: String, value: String?) {
pref?.edit()?.putString(key, value)?.apply()
}
/**
* Set a set of String values in the preferences editor, to be written
* back once [.commit] or [.apply] is called.
*
* @param key The name of the preference to modify.
* @param values The set of new values for the preference. Passing `null`
* for this argument is equivalent to calling [.remove] with
* this key.
*/
fun putStringSet(key: String, values: Set<String>?) {
pref?.edit()?.putStringSet(key, values)?.apply()
}
/**
* Set an int value in the preferences editor, to be written back once
* [.commit] or [.apply] are called.
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
*
*/
fun putInt(key: String, value: Int) {
pref?.edit()?.putInt(key, value)?.apply()
}
/**
* Set a long value in the preferences editor, to be written back once
* [.commit] or [.apply] are called.
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
*
*/
fun putLong(key: String, value: Long) {
pref?.edit()?.putLong(key, value)?.apply()
}
/**
* Set a float value in the preferences editor, to be written back once
* [.commit] or [.apply] are called.
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
*
*/
fun putFloat(key: String, value: Float) {
pref?.edit()?.putFloat(key, value)?.apply()
}
/**
* Set a boolean value in the preferences editor, to be written back
* once [.commit] or [.apply] are called.
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
*
*/
fun putBoolean(key: String, value: Boolean) {
pref?.edit()?.putBoolean(key, value)?.apply()
}
/**
* Mark in the editor that a preference value should be removed, which
* will be done in the actual preferences once [.commit] is
* called.
*
*
* Note that when committing back to the preferences, all removals
* are done first, regardless of whether you called remove before
* or after put methods on this editor.
*
* @param key The name of the preference to remove.
*
*/
fun remove(key: String) {
pref?.edit()?.remove(key)?.apply()
}
fun removeAll() {
pref?.let { pref ->
val editor = pref.edit()
pref.all.map {
editor.remove(it.key)
}
editor.apply()
}
}
/**
* Retrieve all values from the preferences.
*
*
* Note that you *must not* modify the collection returned
* by this method, or alter any of its contents. The consistency of your
* stored data is not guaranteed if you do.
*
* @return Returns a map containing a list of pairs key/value representing
* the preferences.
*
* @throws NullPointerException
*/
fun getAll(): Map<String, *>? = pref?.all
/**
* Retrieve a String value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defValue Value to return if this preference does not exist.
*
* @return Returns the preference value if it exists, or defValue. Throws
* ClassCastException if there is a preference with this name that is not
* a String.
*
* @throws ClassCastException
*/
@Nullable
fun getString(key: String, defValue: String?): String? {
return pref?.getString(key, defValue) ?: defValue
}
/**
* Retrieve a set of String values from the preferences.
*
*
* Note that you *must not* modify the set instance returned
* by this call. The consistency of the stored data is not guaranteed
* if you do, nor is your ability to modify the instance at all.
*
* @param key The name of the preference to retrieve.
* @param defValues Values to return if this preference does not exist.
*
* @return Returns the preference values if they exist, or defValues.
* Throws ClassCastException if there is a preference with this name
* that is not a Set.
*
* @throws ClassCastException
*/
@Nullable
fun getStringSet(key: String, defValues: Set<String>?): Set<String>? {
return pref?.getStringSet(key, defValues) ?: defValues
}
/**
* Retrieve an int value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defValue Value to return if this preference does not exist.
*
* @return Returns the preference value if it exists, or defValue. Throws
* ClassCastException if there is a preference with this name that is not
* an int.
*
* @throws ClassCastException
*/
fun getInt(key: String, defValue: Int): Int {
return pref?.getInt(key, defValue) ?: defValue
}
/**
* Retrieve a long value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defValue Value to return if this preference does not exist.
*
* @return Returns the preference value if it exists, or defValue. Throws
* ClassCastException if there is a preference with this name that is not
* a long.
*
* @throws ClassCastException
*/
fun getLong(key: String, defValue: Long): Long {
return pref?.getLong(key, defValue) ?: defValue
}
/**
* Retrieve a float value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defValue Value to return if this preference does not exist.
*
* @return Returns the preference value if it exists, or defValue. Throws
* ClassCastException if there is a preference with this name that is not
* a float.
*
* @throws ClassCastException
*/
fun getFloat(key: String, defValue: Float): Float {
return pref?.getFloat(key, defValue) ?: defValue
}
/**
* Retrieve a boolean value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defValue Value to return if this preference does not exist.
*
* @return Returns the preference value if it exists, or defValue. Throws
* ClassCastException if there is a preference with this name that is not
* a boolean.
*
* @throws ClassCastException
*/
fun getBoolean(key: String, defValue: Boolean): Boolean {
return pref?.getBoolean(key, defValue) ?: defValue
}
/**
* Checks whether the preferences contains a preference.
*
* @param key The name of the preference to check.
* @return Returns true if the preference exists in the preferences,
* otherwise false.
*/
operator fun contains(key: String): Boolean {
return pref?.contains(key) == true
}
interface OnConfigChangedListener {
fun onConfigChanged(key: String, value: Any?)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
object VoiceButtonUtils : ConfigUtils.OnConfigChangedListener {
var isPairing = false
set(value) {
field = value
requestRefresh()
}
var isWelcoming = false
set(value) {
field = value
requestRefresh()
}
var isMicrophoneEnabled = false
set(value) {
field = value
requestRefresh()
}
var lastTouchTime = 0L
set(value) {
field = value
onVoiceButtonVisibleCallback?.onScreenTouched()
}
var isBackgroundRecognizing = false
set(value) {
field = value
requestRefresh()
}
var onVoiceButtonVisibleCallback: OnVoiceButtonVisibleCallback? = null
fun requestRefresh() {
val isVoiceButtonEnabled =
ConfigUtils.getBoolean(ConfigUtils.KEY_VOICE_BUTTON_ENABLED, true)
val isSetupCompleted = ConfigUtils.getBoolean(ConfigUtils.KEY_SETUP_COMPLETED, false)
if (!isPairing && isVoiceButtonEnabled && isSetupCompleted
&& !isWelcoming && !isBackgroundRecognizing && isMicrophoneEnabled
) {
onVoiceButtonVisibleCallback?.onShow()
} else {
onVoiceButtonVisibleCallback?.onDisappear()
}
}
override fun onConfigChanged(key: String, value: Any?) {
if (key == ConfigUtils.KEY_VOICE_BUTTON_ENABLED) {
requestRefresh()
}
}
interface OnVoiceButtonVisibleCallback {
fun onShow()
fun onDisappear()
fun onScreenTouched()
}
}<file_sep>package com.iflytek.cyber.iot.show.core.launcher
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.graphics.drawable.Drawable
import com.iflytek.cyber.iot.show.core.impl.alarm.EvsAlarm
class LauncherDataHelper(private val context: Context) :
SQLiteOpenHelper(context, DB_NAME, null, 3) {
companion object {
private const val TAG = "LauncherDataHelper"
private const val TABLE_APPS = "apps"
private const val TABLE_TEMPLATE_APPS = "template_apps"
private const val DB_NAME = "launcher"
private const val KEY_NAME = "name"
private const val KEY_PACKAGE_NAME = "package_name"
private const val KEY_ICON_URL = "icon_url"
private const val KEY_APP_TYPE = "app_type"
private const val KEY_SOURCE = "source"
private const val KEY_IMG = "img"
private const val KEY_TEMPLATE = "template"
private const val KEY_BUSINESS = "business"
private const val KEY_IS_DARK = "is_dark"
private const val KEY_TYPE = "type"
private const val KEY_URL = "url"
private const val KEY_TEXT_IN = "textIn"
}
private fun createTable(db: SQLiteDatabase) {
db.execSQL("CREATE TABLE $TABLE_APPS (id INTEGER PRIMARY KEY AUTOINCREMENT, $KEY_NAME TEXT, $KEY_PACKAGE_NAME TEXT, $KEY_APP_TYPE INTEGER, $KEY_ICON_URL TEXT)")
db.execSQL("CREATE TABLE $TABLE_TEMPLATE_APPS (id INTEGER PRIMARY KEY AUTOINCREMENT, $KEY_SOURCE TEXT, $KEY_NAME TEXT, $KEY_ICON_URL TEXT, $KEY_IMG TEXT, $KEY_TEMPLATE INTEGER, $KEY_BUSINESS TEXT, $KEY_IS_DARK INTEGER, $KEY_TYPE TEXT, $KEY_URL TEXT, $KEY_TEXT_IN TEXT)")
}
private fun deleteTable(db: SQLiteDatabase) {
db.execSQL("DROP TABLE IF EXISTS $TABLE_APPS")
db.execSQL("DROP TABLE IF EXISTS $TABLE_TEMPLATE_APPS")
}
override fun onCreate(db: SQLiteDatabase?) {
db ?: return
createTable(db)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db ?: return
deleteTable(db)
createTable(db)
}
fun queryPartyApps(): List<AppData> {
readableDatabase?.let { db ->
val apps = mutableListOf<AppData>()
val cursor = db.query(
TABLE_APPS, // The table to query
null, // The array of columns to return (pass null to get all)
"$KEY_APP_TYPE = ?", // The columns for the WHERE clause
arrayOf(AppData.TYPE_PARTY.toString()), // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
)
with(cursor) {
while (cursor.moveToNext()) {
val name = getString(getColumnIndexOrThrow(KEY_NAME))
val packageName = getString(getColumnIndexOrThrow(KEY_PACKAGE_NAME))
val icon: Drawable? = try {
context.packageManager.getApplicationIcon(packageName)
} catch (t: Throwable) {
t.printStackTrace()
null
}
val iconUrl = getString(getColumnIndexOrThrow(KEY_ICON_URL))
val appType = getInt(getColumnIndexOrThrow(KEY_APP_TYPE))
if (!(icon == null && iconUrl.isNullOrEmpty())) {
val appData = AppData(
name,
packageName,
icon,
iconUrl,
appType
)
apps.add(appData)
}
}
}
cursor.close()
db.close()
return apps.toList()
}
return emptyList()
}
fun updatePartyApps(apps: List<AppData>) {
writableDatabase?.let { db ->
db.delete(TABLE_APPS, "$KEY_APP_TYPE = ?", arrayOf(AppData.TYPE_PARTY.toString()))
apps.map {
if (db.isOpen) {
val contentValues = ContentValues()
contentValues.put(KEY_NAME, it.name)
contentValues.put(KEY_PACKAGE_NAME, it.packageName)
contentValues.put(KEY_ICON_URL, it.iconUrl)
contentValues.put(KEY_APP_TYPE, it.appType)
db.insert(TABLE_APPS, null, contentValues)
}
}
db.close()
}
}
fun queryTemplateApps(): List<TemplateAppData> {
readableDatabase?.let { db ->
val apps = mutableListOf<TemplateAppData>()
val cursor = db.query(
TABLE_TEMPLATE_APPS, // The table to query
null, // The array of columns to return (pass null to get all)
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
)
while (cursor.moveToNext()) {
val source = cursor.getString(cursor.getColumnIndex(KEY_SOURCE))
val name = cursor.getString(cursor.getColumnIndex(KEY_NAME))
val icon = cursor.getString(cursor.getColumnIndex(KEY_ICON_URL))
val img = cursor.getString(cursor.getColumnIndex(KEY_IMG))
val template = cursor.getInt(cursor.getColumnIndex(KEY_TEMPLATE))
val business = cursor.getString(cursor.getColumnIndex(KEY_BUSINESS))
val isDark = cursor.getInt(cursor.getColumnIndex(KEY_IS_DARK)) > 0
val type = cursor.getString(cursor.getColumnIndex(KEY_TYPE))
val url = cursor.getString(cursor.getColumnIndex(KEY_URL))
val textIn = cursor.getString(cursor.getColumnIndex(KEY_TEXT_IN))
val templateAppData = TemplateAppData(
source,
name,
icon,
img,
template,
business,
isDark,
type,
url,
textIn
)
apps.add(templateAppData)
}
cursor.close()
db.close()
return apps
}
return emptyList()
}
fun updateTemplateAppData(apps: List<TemplateAppData>) {
writableDatabase?.let { db ->
db.delete(TABLE_TEMPLATE_APPS, "$KEY_NAME != null", null)
apps.map {
if (db.isOpen) {
val contentValues = ContentValues()
contentValues.put(KEY_NAME, it.name)
contentValues.put(KEY_SOURCE, it.source)
contentValues.put(KEY_ICON_URL, it.iconUrl)
contentValues.put(KEY_IMG, it.img)
contentValues.put(KEY_TEMPLATE, it.template)
contentValues.put(KEY_BUSINESS, it.business)
contentValues.put(KEY_IS_DARK, if (it.isDark != false) 1 else 0)
contentValues.put(KEY_TYPE, it.type)
contentValues.put(KEY_URL, it.url)
contentValues.put(KEY_TEXT_IN, it.textIn)
db.insert(TABLE_TEMPLATE_APPS, null, contentValues)
}
}
db.close()
}
}
}<file_sep>package com.iflytek.cyber.evs.sdk.utils
import android.Manifest
import android.app.admin.DevicePolicyManager
import android.content.ComponentName
import android.content.Context
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import android.view.Display
import android.view.WindowManager
import androidx.annotation.RequiresPermission
import java.lang.Exception
object ScreenUtil {
/**
* 判断屏幕是否处于点亮状态。
* @param context 上下文对象
* @return 是否点亮
*/
fun isScreenOn(context: Context): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
wm.defaultDisplay.state == Display.STATE_ON
} else {
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
powerManager.isScreenOn
}
}
/**
* 锁屏。
* @param context 上下文对象
* @param componentName 被授予DEVICE_ADMIN的component
* @return 是否成功
*/
fun lockScreen(context: Context, componentName: ComponentName): Boolean {
val policyManager = context.getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager
if (policyManager.isAdminActive(componentName)) {
policyManager.lockNow()
return true
}
return false
}
/**
* 解锁屏幕。
* @param context 上下文对象
* @return 是否成功
*/
fun unlockScreen(context: Context): Boolean {
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
val wl = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
":bright")
wl.acquire(1000)
wl.release()
return true
}
/**
* 获取屏幕亮度(在某些机型如小米6上可能有问题,因为SCREEN_BRIGHTNESS的最大值不是255)。
* @param context 上下文对象
* @return 亮度值(0-100)
*/
fun getBrightness(context: Context): Long {
try {
val brightness: Long = Settings.System.getInt(context.contentResolver,
Settings.System.SCREEN_BRIGHTNESS).toLong()
return (brightness / 255.0 * 100).toLong()
} catch (e: Exception) {
e.printStackTrace()
}
return 0
}
/**
* 设置屏幕亮度(在某些机型如小米6上可能有问题,因为SCREEN_BRIGHTNESS的最大值不是255)。
* @param context 上下文对象
* @param brightness 亮度值(0-100)
* @return 是否成功
*/
@RequiresPermission(Manifest.permission.WRITE_SETTINGS)
fun setBrightness(context: Context, brightness: Long): Boolean {
val resolver = context.contentResolver
val uri = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS)
val result = Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS,
(brightness * 255.0 / 100.0).toInt())
if (result)
resolver.notifyChange(uri, null)
return result
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.record
import android.content.Context
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import com.iflytek.cyber.iot.show.core.BuildConfig
import com.iflytek.ivw.IVWEngine
import org.json.JSONException
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
class EvsIvwHandler(context: Context, private val listener: IvwHandlerListener?) {
private var mHandlerThread: HandlerThread? = null
private var mWakeUpHandler: WakeUpHandler? = null
private val mWakeUpEnable: Boolean = true
private val mWakeResPath: String
private val mObj = Any()
private var mIvwEngine: IVWEngine? = null
private var mIvwListener =
IVWEngine.IVWListener { angle, channel, power, CMScore, beam, param1, param2 ->
Log.v(TAG, param1)
listener?.onWakeUp(angle.toInt(), beam.toInt(), param1)
}
init {
val externalCache = context.externalCacheDir
val customWakeResFile = File("$externalCache/wake_up_res_custom.bin") // 自定义唤醒词
if (!customWakeResFile.exists()) {
val wakeUpResFile = File("$externalCache/wake_up_res.bin")
wakeUpResFile.createNewFile()
val inputStream = context.assets.open("wakeup/lan2-xiao3-fei1.bin")
val outputStream = FileOutputStream(wakeUpResFile)
val buffer = ByteArray(1024)
var byteCount = inputStream.read(buffer)
while (byteCount != -1) {
outputStream.write(buffer, 0, byteCount)
byteCount = inputStream.read(buffer)
}
outputStream.flush()
inputStream.close()
outputStream.close()
mWakeResPath = wakeUpResFile.path
} else {
mWakeResPath = customWakeResFile.path
}
// if wakeup enable, then new some object
if (isWakeUpEnable()) {
Thread {
mIvwEngine = IVWEngine.createInstance(mWakeResPath, mIvwListener)
}.start()
mHandlerThread = HandlerThread("IVW_THREAD", Thread.MAX_PRIORITY)
mHandlerThread?.let {
it.start()
mWakeUpHandler = WakeUpHandler(it.looper)
}
}
}
/**
* Check wakeup enable
*/
fun isWakeUpEnable(): Boolean {
return mWakeUpEnable
&& !TextUtils.isEmpty(mWakeResPath)
&& File(mWakeResPath).exists()
}
/**
* Write audio to ivw engine
*/
fun write(audio: ByteArray?, len: Int) {
synchronized(mObj) {
mWakeUpHandler?.post {
audio?.let {
mIvwEngine?.writeAudio(it, len)
}
}
}
}
private fun stopIvw() {
mIvwEngine?.destroy()
}
fun release() {
stopIvw()
mIvwEngine?.destroy()
}
inner class WakeUpHandler(lopper: Looper) : Handler(lopper)
interface IvwHandlerListener {
fun onWakeUp(angle: Int, beam: Int, params: String?)
}
companion object {
const val TAG = "EvsIvwHandler"
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.util.keyIterator
import androidx.core.view.setPadding
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.DeviceApi
import com.iflytek.cyber.iot.show.core.impl.prompt.PromptManager
import com.iflytek.cyber.iot.show.core.model.ChatConfigData
import com.iflytek.cyber.iot.show.core.model.InteractionMode
import com.iflytek.cyber.iot.show.core.widget.StyledProgressDialog
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
import kotlin.Comparator
class LanguageAndSpeakerFragment : BaseFragment() {
companion object {
fun newInstance(chatConfigData: ChatConfigData?): LanguageAndSpeakerFragment {
val fragment = LanguageAndSpeakerFragment()
fragment.chatConfigData = chatConfigData
return fragment
}
}
private var viewPager: ViewPager2? = null
private var tabLayout: TabLayout? = null
private var tvNextStep: TextView? = null
private var progressDialog: StyledProgressDialog? = null
private var adapter: StepPageAdapter? = null
private var chatConfigData: ChatConfigData? = null
private var backCount = 0
private val onPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
if (position == getPageCount() - 1) {
tvNextStep?.setText(R.string.save)
} else {
tvNextStep?.setText(R.string.next_step)
}
}
}
private val onItemSelectedListener = object : SingleChoicePageFragment.OnItemSelectedListener {
override fun onItemSelect(fragment: SingleChoicePageFragment, position: Int) {
if (viewPager?.currentItem != getPageCount() - 1) {
tvNextStep?.performClick()
}
when (fragment.tag.toString()) {
"language" -> {
chatConfigData?.interactionModes?.get(position)?.let { mode ->
val list = mutableListOf<String>()
var selectedItem = 0
val icons = mutableListOf<String>()
if (mode.speakers?.isNotEmpty() == true) {
for (j in mode.speakers.indices) {
val speaker = mode.speakers[j]
list.add(speaker.voiceName ?: "")
icons.add(speaker.image ?: "")
if (speaker.vcn == chatConfigData?.config?.vcn) {
selectedItem = j
}
}
}
val speakerFragment =
if (chatConfigData?.property.isNullOrEmpty()) {
adapter?.fragments?.get(1)
} else {
adapter?.fragments?.get(2)
}
speakerFragment?.updateData(
list.toTypedArray(),
icons.toTypedArray(),
selectedItem
)
}
}
"speaker" -> {
getCurrentInteractionMode()?.let {
val speakerSize = it.speakers?.size ?: 0
if (speakerSize <= position)
return
val speakerName = fragment.titles[position]
it.speakers ?: return
for (speaker in it.speakers) {
if (speaker.voiceName == speakerName)
speaker.listenUrl?.let { url -> PromptManager.playUrl(url) }
}
}
}
"property" -> {
chatConfigData?.interactionModes?.get(
adapter?.fragments?.get(0)?.selectedItem ?: 0
)?.let { mode ->
val speakers = mode.speakers?.toMutableList() ?: return
val list = mutableListOf<String>()
var selectedItem = 0
val icons = mutableListOf<String>()
val selectedProperty = chatConfigData?.property?.get(position)
val selectedPropertyId = selectedProperty?.propertyId
speakers.sortWith(Comparator { o1, o2 ->
when {
o1.propertyIds?.contains(selectedPropertyId) == true -> -1
o2.propertyIds?.contains(selectedPropertyId) == true -> 1
else -> 0
}
})
for (j in speakers.indices) {
val speaker = speakers[j]
list.add(speaker.voiceName ?: "")
icons.add(speaker.image ?: "")
if (speaker.vcn == chatConfigData?.config?.vcn) {
selectedItem = j
}
}
val speakerFragment =
if (chatConfigData?.property.isNullOrEmpty()) {
adapter?.fragments?.get(1)
} else {
adapter?.fragments?.get(2)
}
speakerFragment?.updateData(
list.toTypedArray(),
icons.toTypedArray(),
selectedItem
)
}
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_language_and_speaker, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tvNextStep = view.findViewById(R.id.next_step)
val viewPager: ViewPager2 = view.findViewById(R.id.view_pager)
val tabLayout: TabLayout = view.findViewById(R.id.tab_layout)
adapter = StepPageAdapter(this)
viewPager.adapter = adapter
tabLayout.tabRippleColor = null
tabLayout.tabMode = TabLayout.MODE_FIXED
tabLayout.setSelectedTabIndicatorColor(Color.TRANSPARENT)
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.setCustomView(R.layout.item_step_tab)
tab.view.setPadding(0)
val num = tab.customView?.findViewById<TextView>(R.id.num)
num?.text = (position + 1).toString()
val title = tab.customView?.findViewById<TextView>(R.id.title)
title?.text = when (position) {
0 -> {
getString(R.string.language)
}
1 -> {
if (chatConfigData?.property?.isNotEmpty() == true) {
getString(R.string.human_property)
} else {
getString(R.string.voice_property)
}
}
2 -> {
getString(R.string.voice_property)
}
else -> {
null
}
}
tab.customView?.findViewById<View>(R.id.divider_start)?.alpha =
if (position != 0) 1f else 0f
tab.customView?.findViewById<View>(R.id.divider_end)?.alpha =
if (position != getPageCount() - 1)
1f
else 0f
}.attach()
viewPager.offscreenPageLimit = 3
viewPager.registerOnPageChangeCallback(onPageChangeCallback)
this.viewPager = viewPager
this.tabLayout = tabLayout
tvNextStep?.setOnClickListener { nextStep ->
if (viewPager.currentItem < getPageCount() - 1) {
viewPager.currentItem = viewPager.currentItem + 1
} else {
tvNextStep?.isEnabled = false
progressDialog = StyledProgressDialog.Builder()
.setTitle(getString(R.string.saving))
.setMessage(getString(R.string.saving_language_and_speaker))
.setCancelable(false)
.show(fragmentManager)
var interactionModeId: Int? = null
var propertyId: String? = null
var vcn: String? = null
adapter?.fragments?.let { fragments ->
for (key in fragments.keyIterator()) {
val fragment = fragments[key]
val tag = fragment.tag
val selectedItem = fragment.selectedItem
if (tag == "language") {
chatConfigData?.interactionModes?.get(selectedItem)?.let {
interactionModeId = it.interactionModeId
}
} else if (tag == "property") {
chatConfigData?.property?.get(selectedItem)?.let {
propertyId = it.propertyId
}
} else if (tag == "speaker") {
val speakerName = fragment.titles[selectedItem]
val selectedModeId =
chatConfigData?.interactionModes?.get(fragments[0].selectedItem)
?.interactionModeId
val modes = chatConfigData?.interactionModes
if (modes?.isNotEmpty() == true) {
for (mode in modes) {
if (mode.interactionModeId == selectedModeId) {
mode.speakers?.let { speakers ->
for (speaker in speakers) {
if (speaker.voiceName == speakerName) {
vcn = speaker.vcn
}
}
}
}
}
}
}
}
}
val json = JsonObject()
interactionModeId?.let {
json.addProperty("interaction_mode_id", it)
}
propertyId?.let {
json.addProperty("property_id", it)
}
vcn?.let {
json.addProperty("vcn", it)
}
getDeviceApi()?.putChatConfig(
RequestBody.create(
MediaType.parse("application/json"),
json.toString()
)
)?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
if (t is UnknownHostException) {
Toast.makeText(activity, "网络异常,请检查网络后重试", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(activity, "请求出现错误,请检查网络后重试", Toast.LENGTH_SHORT).show()
}
progressDialog?.dismiss()
progressDialog = null
tvNextStep?.isEnabled = true
}
override fun onResponse(
call: Call<ResponseBody>,
response: Response<ResponseBody>
) {
if (response.isSuccessful) {
Toast.makeText(activity, "保存成功", Toast.LENGTH_SHORT).show()
if (!isDetached) {
pop()
}
} else {
val errorBody = response.errorBody()
val body = errorBody?.string() ?: "{}"
val errorJson = JsonParser().parse(body).asJsonObject
if (errorJson.has("message")) {
Toast.makeText(
activity,
errorJson.get("message").asString,
Toast.LENGTH_SHORT
).show()
}
errorBody?.close()
}
progressDialog?.dismiss()
progressDialog = null
tvNextStep?.isEnabled = true
}
})
}
}
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
}
override fun onDestroyView() {
super.onDestroyView()
viewPager?.unregisterOnPageChangeCallback(onPageChangeCallback)
}
private fun getPageCount(): Int {
chatConfigData?.let {
if (it.property?.isNotEmpty() == true) {
return 3
}
return 2
}
return 0
}
private fun getCurrentInteractionMode(): InteractionMode? {
chatConfigData?.let {
if (it.interactionModes?.isNotEmpty() == true) {
val fragment = adapter?.fragments?.get(0) ?: return null
return it.interactionModes[fragment.selectedItem]
}
}
return null
}
private fun getDeviceApi(): DeviceApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(DeviceApi::class.java)
}
private inner class StepPageAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
val fragments = SparseArray<SingleChoicePageFragment>()
override fun getItemCount(): Int {
return getPageCount()
}
override fun createFragment(position: Int): Fragment {
val fragment = when (position) {
0 -> {
val list = mutableListOf<String>()
var selectedItem = 0
chatConfigData?.let {
if (it.interactionModes?.isNotEmpty() == true)
for (i in it.interactionModes.indices) {
val mode = it.interactionModes[i]
list.add(mode.name ?: "")
if (mode.interactionModeId == it.config?.interactionModeId) {
selectedItem = i
}
}
}
SingleChoicePageFragment.newInstance(
list.toTypedArray(),
null,
selectedItem,
"language"
)
}
1 -> {
val list = mutableListOf<String>()
var selectedItem = 0
val icons = mutableListOf<String>()
var tag: Any? = null
chatConfigData?.let {
if (it.property?.isNotEmpty() == true) {
for (i in it.property.indices) {
val property = it.property[i]
list.add(property.name)
if (it.config?.propertyId == property.propertyId) {
selectedItem = i
}
}
tag = "property"
} else {
if (it.interactionModes?.isNotEmpty() == true)
for (i in it.interactionModes.indices) {
val mode = it.interactionModes[i]
if (mode.interactionModeId == it.config?.interactionModeId) {
if (mode.speakers?.isNotEmpty() == true) {
for (j in mode.speakers.indices) {
val speaker = mode.speakers[j]
list.add(speaker.voiceName ?: "")
icons.add(speaker.image ?: "")
if (speaker.vcn == it.config?.vcn) {
selectedItem = j
}
}
}
}
}
tag = "speaker"
}
}
SingleChoicePageFragment.newInstance(
list.toTypedArray(),
icons.toTypedArray(),
selectedItem,
tag
)
}
2 -> {
val tag = "speaker"
var selectedModeItem = 0
chatConfigData?.let {
if (it.interactionModes?.isNotEmpty() == true)
for (i in it.interactionModes.indices) {
val mode = it.interactionModes[i]
if (mode.interactionModeId == it.config?.interactionModeId) {
selectedModeItem = i
}
}
}
chatConfigData?.interactionModes?.get(selectedModeItem)?.let { mode ->
val speakers = mode.speakers?.toMutableList()
val list = mutableListOf<String>()
var selectedItem = 0
val icons = mutableListOf<String>()
val selectedPropertyId = chatConfigData?.config?.propertyId
?: chatConfigData?.property?.get(0)?.propertyId ?: ""
speakers?.sortWith(Comparator { o1, o2 ->
when {
o1.propertyIds?.contains(selectedPropertyId) == true -> -1
o2.propertyIds?.contains(selectedPropertyId) == true -> 1
else -> 0
}
})
if (speakers?.isNotEmpty() == true)
for (j in speakers.indices) {
val speaker = speakers[j]
list.add(speaker.voiceName ?: "")
icons.add(speaker.image ?: "")
if (speaker.vcn == chatConfigData?.config?.vcn) {
selectedItem = j
}
}
SingleChoicePageFragment.newInstance(
list.toTypedArray(),
icons.toTypedArray(),
selectedItem,
tag
)
} ?: run {
SingleChoicePageFragment()
}
}
else -> {
SingleChoicePageFragment()
}
}
fragment.onItemSelectedListener = onItemSelectedListener
fragments.put(position, fragment)
return fragment
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
interface PageScrollable {
fun scrollToPrevious(): Boolean
fun scrollToNext(): Boolean
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.Result
class AudioSearchResultAdapter(
val results: ArrayList<Result>,
val onItemClick: (Result) -> Unit
) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var isFinished = false
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
R.layout.item_audio_search_result -> AudioSearchResultHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_audio_search_result, parent, false)
)
R.layout.item_loading -> LoadHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_loading, parent, false)
)
else -> AudioSearchResultHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_audio_search_result, parent, false)
)
}
}
fun loadingFinish(isFinished: Boolean) {
this.isFinished = isFinished
if (results.size > 0) {
notifyItemChanged(results.size)
}
}
override fun getItemViewType(position: Int): Int {
return if (position + 1 == itemCount) {
R.layout.item_loading
} else {
R.layout.item_audio_search_result
}
}
override fun getItemCount(): Int {
var itemCount = 1
if (results.size > 0) {
itemCount += results.size
} else return 0
return itemCount
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (getItemViewType(position) == R.layout.item_audio_search_result) {
holder as AudioSearchResultHolder
val result = results[position]
holder.title.text = result.title
holder.desc.text = result.author
holder.itemView.setOnClickListener {
onItemClick.invoke(result)
}
if (result.author.isNullOrEmpty()) {
holder.title.isVisible = false
holder.desc.isVisible = false
holder.onlyTitle.isVisible = true
holder.onlyTitle.text = result.title
} else {
holder.title.isVisible = true
holder.desc.isVisible = true
holder.onlyTitle.isVisible = false
}
} else if (getItemViewType(position) == R.layout.item_loading) {
holder as LoadHolder
if (isFinished) {
holder.tvLoadingText.text = "已经到底了"
} else {
holder.tvLoadingText.text = "正在加载..."
}
}
}
inner class AudioSearchResultHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val title = itemView.findViewById<TextView>(R.id.title)
val desc = itemView.findViewById<TextView>(R.id.desc)
val onlyTitle = itemView.findViewById<TextView>(R.id.tv_only_title)
}
inner class LoadHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvLoadingText = itemView.findViewById<TextView>(R.id.tv_loading_text)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import com.iflytek.cyber.iot.show.core.R
/**
* fork from https://github.com/lijiankun24/ShadowLayout
*
*/
class ShadowLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr) {
private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val mRectF = RectF()
/**
* 阴影的颜色
*/
private var mShadowColor = Color.TRANSPARENT
/**
* 是否使用 shadowColor 作为 paint 的 颜色(color)
*/
private var mUseShadowColor = false
private var mShadowPaddingTop = 0f
private var mShadowPaddingLeft = 0f
private var mShadowPaddingRight = 0f
private var mShadowPaddingBottom = 0f
/**
* 阴影的大小范围
*/
private var mShadowRadius = 0f
/**
* 阴影的圆角大小
*/
private var mShadowCornerRadius = 0f
/**
* 阴影 x 轴的偏移量
*/
private var mShadowDx = 0f
/**
* 阴影 y 轴的偏移量
*/
private var mShadowDy = 0f
/**
* 阴影显示的边界
*/
private var mShadowSide = ALL
/**
* 阴影的形状,圆形/矩形
*/
private var mShadowShape = SHAPE_RECTANGLE
init {
init(attrs)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
var rectLeft = 0f
var rectTop = 0f
var rectRight = this.measuredWidth.toFloat()
var rectBottom = this.measuredHeight.toFloat()
this.width
if (mShadowSide and LEFT == LEFT) {
rectLeft = mShadowPaddingLeft
}
if (mShadowSide and TOP == TOP) {
rectTop = mShadowPaddingTop
}
if (mShadowSide and RIGHT == RIGHT) {
rectRight = this.measuredWidth - mShadowPaddingRight
}
if (mShadowSide and BOTTOM == BOTTOM) {
rectBottom = this.measuredHeight - mShadowPaddingBottom
}
if (mShadowDy != 0.0f) {
rectBottom -= mShadowDy
}
if (mShadowDx != 0.0f) {
rectRight -= mShadowDx
}
mRectF.left = rectLeft
mRectF.top = rectTop
mRectF.right = rectRight
mRectF.bottom = rectBottom
}
/**
* 真正绘制阴影的方法
*/
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (!isInEditMode) {
setUpShadowPaint()
if (mShadowShape == SHAPE_RECTANGLE) {
if (mShadowCornerRadius <= 0)
canvas.drawRect(mRectF, mPaint)
else
canvas.drawRoundRect(mRectF, mShadowCornerRadius, mShadowCornerRadius, mPaint)
} else if (mShadowShape == SHAPE_OVAL) {
canvas.drawCircle(mRectF.centerX(), mRectF.centerY(), Math.min(mRectF.width(), mRectF.height()) / 2, mPaint)
}
}
}
@Suppress("unused")
fun setShadowColor(shadowColor: Int) {
mShadowColor = shadowColor
requestLayout()
postInvalidate()
}
@Suppress("unused")
fun setShadowRadius(shadowRadius: Float) {
mShadowRadius = shadowRadius
requestLayout()
postInvalidate()
}
/**
* 读取设置的阴影的属性
*
* @param attrs 从其中获取设置的值
*/
private fun init(attrs: AttributeSet?) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null) // 关闭硬件加速
this.setWillNotDraw(false) // 调用此方法后,才会执行 onDraw(Canvas) 方法
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ShadowLayout)
if (typedArray != null) {
mShadowColor = typedArray.getColor(R.styleable.ShadowLayout_shadowColor, Color.BLACK)
mShadowRadius = typedArray.getDimension(R.styleable.ShadowLayout_shadowRadius, dip2px(0f))
mShadowCornerRadius = typedArray.getDimension(R.styleable.ShadowLayout_shadowCornerRadius, dip2px(0f))
mShadowPaddingLeft = typedArray.getDimension(R.styleable.ShadowLayout_shadowPaddingLeft, dip2px(5f) + mShadowRadius)
mShadowPaddingRight = typedArray.getDimension(R.styleable.ShadowLayout_shadowPaddingRight, dip2px(5f) + mShadowRadius)
mShadowPaddingTop = typedArray.getDimension(R.styleable.ShadowLayout_shadowPaddingTop, dip2px(5f) + mShadowRadius)
mShadowPaddingBottom = typedArray.getDimension(R.styleable.ShadowLayout_shadowPaddingBottom, dip2px(5f) + mShadowRadius)
mShadowDx = typedArray.getDimension(R.styleable.ShadowLayout_shadowDx, dip2px(0f))
mShadowDy = typedArray.getDimension(R.styleable.ShadowLayout_shadowDy, dip2px(0f))
mShadowSide = typedArray.getInt(R.styleable.ShadowLayout_shadowSide, ALL)
mShadowShape = typedArray.getInt(R.styleable.ShadowLayout_shadowShape, SHAPE_RECTANGLE)
mUseShadowColor = typedArray.getBoolean(R.styleable.ShadowLayout_useShadowColor, false)
typedArray.recycle()
}
setUpShadowPaint()
}
private fun setUpShadowPaint() {
mPaint.reset()
mPaint.isAntiAlias = true
if (mUseShadowColor) {
mPaint.color = mShadowColor
} else {
mPaint.color = Color.TRANSPARENT
}
if (!isInEditMode) {
mPaint.setShadowLayer(if (mShadowRadius >= 0) mShadowRadius else 0f, mShadowDx, mShadowDy, mShadowColor)
}
}
/**
* dip2px dp 值转 px 值
*
* @param dpValue dp 值
* @return px 值
*/
private fun dip2px(dpValue: Float): Float {
val dm = context.resources.displayMetrics
val scale = dm.density
return dpValue * scale + 0.5f
}
companion object {
const val ALL = 0x1111
const val LEFT = 0x0001
const val TOP = 0x0010
const val RIGHT = 0x0100
const val BOTTOM = 0x1000
const val SHAPE_RECTANGLE = 0x0001
const val SHAPE_OVAL = 0x0010
}
}
<file_sep>package com.iflytek.cyber.evs.sdk.model
import android.os.Build
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.annotation.JSONField
class OsRequestBody(
@JSONField(name = "iflyos_header") val header: OsHeader,
@JSONField(name = "iflyos_context") val context: JSONObject,
@JSONField(name = "iflyos_request") val request: OsRequest
) {
override fun toString(): String {
val json = JSONObject();
json["iflyos_header"] = header.toJSONObject()
json["iflyos_context"] = context
json["iflyos_request"] = request.toJSONObject()
return JSON.toJSONString(json)
}
}
class OsHeader(val authorization: String, val device: HeaderDevice) {
fun toJSONObject(): JSONObject {
val json = JSONObject()
json["authorization"] = authorization
json["device"] = device.toJSONObject()
return json
}
}
class HeaderDevice(
@JSONField(name = "device_id") val deviceId: String,
val location: DeviceLocation?,
val platform: DevicePlatform,
val flags: DeviceFlags?
) {
fun toJSONObject(): JSONObject {
val json = JSONObject()
json["device_id"] = deviceId
location?.let {
json["location"] = it.toJSONObject()
}
json["platform"] = platform.toJSONObject()
/* 最新协议中去掉flags
flags?.let {
json["flags"] = it.toJSONObject()
}*/
return json
}
}
class DeviceLocation(val latitude: Double, val longitude: Double) {
fun toJSONObject(): JSONObject {
val json = JSONObject()
json["latitude"] = latitude
json["longitude"] = longitude
return json
}
}
class DevicePlatform(val name: String = "android", val version: String = Build.VERSION.RELEASE) {
fun toJSONObject(): JSONObject {
val json = JSONObject()
json["name"] = name
json["version"] = version
return json
}
}
class DeviceFlags(val kid: Boolean, @JSONField(name = "full_duplex") val fullDuplex: Boolean) {
fun toJSONObject(): JSONObject {
val json = JSONObject()
json["kid"] = kid
json["full_duplex"] = fullDuplex
return json
}
}
class OsRequest(val header: RequestHeader, val payload: JSONObject) {
fun toJSONObject(): JSONObject {
val json = JSONObject()
json["header"] = header.toJSONObject()
json["payload"] = payload
return json
}
}
class RequestHeader(val name: String, @JSONField(name = "request_id") val requestId: String) {
fun toJSONObject(): JSONObject {
val json = JSONObject()
json["name"] = name
json["request_id"] = requestId
return json
}
}<file_sep>package com.iflytek.cyber.iot.show.core.impl.playback
import com.iflytek.cyber.evs.sdk.agent.PlaybackController
class PlaybackControllerImpl : PlaybackController()<file_sep>package com.iflytek.cyber.iot.show.core.impl.videoplayer
import android.util.Log
import com.iflytek.cyber.evs.sdk.agent.VideoPlayer
import com.iflytek.cyber.iot.show.core.impl.speaker.EvsSpeaker
import com.kk.taurus.playerbase.AVPlayer
import com.kk.taurus.playerbase.entity.DataSource
import com.kk.taurus.playerbase.event.EventKey
import com.kk.taurus.playerbase.event.OnErrorEventListener
import com.kk.taurus.playerbase.event.OnPlayerEventListener
import com.kk.taurus.playerbase.receiver.OnReceiverEventListener
import com.kk.taurus.playerbase.render.IRender
import com.kk.taurus.playerbase.render.RenderTextureView
import com.kk.taurus.playerbase.widget.SuperContainer
class EvsVideoPlayerInstance {
companion object {
private const val TAG = "EvsVideoPlayerInstance"
const val VOLUME_BACKGROUND = .1f
}
private val basePlayer = AVPlayer()
private var listener: Listener? = null
var resourceId: String? = null
private var cacheVolume = 1f
private var superContainer: SuperContainer? = null
private var render: IRender? = null
private var renderHolder: IRender.IRenderHolder? = null
private val playerEventListener = OnPlayerEventListener { eventCode, bundle ->
if (eventCode != OnPlayerEventListener.PLAYER_EVENT_ON_TIMER_UPDATE)
Log.d(TAG, "OnPlayerEventListener event: $eventCode, bundle: $bundle")
when (eventCode) {
OnPlayerEventListener.PLAYER_EVENT_ON_PREPARED -> {
bundle?.let { args ->
val width = args.getInt(EventKey.INT_ARG1)
val height = args.getInt(EventKey.INT_ARG2)
render?.updateVideoSize(width, height)
}
bindRenderHolder(renderHolder)
}
OnPlayerEventListener.PLAYER_EVENT_ON_VIDEO_SIZE_CHANGE -> {
bundle?.let { args ->
val width = args.getInt(EventKey.INT_ARG1)
val height = args.getInt(EventKey.INT_ARG2)
val videoSarNum = bundle.getInt(EventKey.INT_ARG3)
val videoSarDen = bundle.getInt(EventKey.INT_ARG4)
render?.updateVideoSize(width, height)
render?.setVideoSampleAspectRatio(videoSarNum, videoSarDen)
}
}
OnPlayerEventListener.PLAYER_EVENT_ON_STATUS_CHANGE -> {
bundle?.let { args ->
val status = args.getInt(EventKey.INT_DATA)
listener?.onPlayerStateChanged(this, status)
}
}
OnPlayerEventListener.PLAYER_EVENT_ON_TIMER_UPDATE -> {
bundle?.let { args ->
val position = args.getInt(EventKey.INT_ARG1)
if (basePlayer.isPlaying)
listener?.onPlayerPositionUpdated(this, position.toLong())
}
}
}
}
private val errorEventListener = OnErrorEventListener { eventCode, bundle ->
when (eventCode) {
OnErrorEventListener.ERROR_EVENT_COMMON,
OnErrorEventListener.ERROR_EVENT_MALFORMED,
OnErrorEventListener.ERROR_EVENT_IO,
OnErrorEventListener.ERROR_EVENT_TIMED_OUT,
OnErrorEventListener.ERROR_EVENT_DATA_PROVIDER_ERROR,
OnErrorEventListener.ERROR_EVENT_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK,
OnErrorEventListener.ERROR_EVENT_UNSUPPORTED -> {
stop()
listener?.onPlayerError(this, VideoPlayer.MEDIA_ERROR_INVALID_REQUEST, null)
}
OnErrorEventListener.ERROR_EVENT_SERVER_DIED -> {
listener?.onPlayerError(this, VideoPlayer.MEDIA_ERROR_SERVICE_UNAVAILABLE, null)
}
OnErrorEventListener.ERROR_EVENT_UNKNOWN -> {
listener?.onPlayerError(this, VideoPlayer.MEDIA_ERROR_UNKNOWN, null)
}
}
}
private val receiverEventListener = OnReceiverEventListener { eventCode, bundle ->
Log.d(TAG, "OnReceiverEventListener event: $eventCode, bundle: $bundle")
}
private val renderCallback = object : IRender.IRenderCallback {
override fun onSurfaceChanged(
renderHolder: IRender.IRenderHolder?,
format: Int,
width: Int,
height: Int
) {
}
override fun onSurfaceCreated(
renderHolder: IRender.IRenderHolder?,
width: Int,
height: Int
) {
Log.d(TAG, "onSurfaceCreated: width = $width, height = $height")
this@EvsVideoPlayerInstance.renderHolder = renderHolder
bindRenderHolder(renderHolder)
}
override fun onSurfaceDestroy(renderHolder: IRender.IRenderHolder?) {
Log.d(TAG, "onSurfaceDestroy...")
this@EvsVideoPlayerInstance.renderHolder = null
}
}
private val onVolumeChangedListener = object : EvsSpeaker.OnVolumeChangedListener {
override fun onVolumeChanged(volume: Int, fromRemote: Boolean) {
if (isAudioBackground) {
basePlayer.setVolume(
VOLUME_BACKGROUND * volume / 100,
VOLUME_BACKGROUND * volume / 100
)
} else {
basePlayer.setVolume(
volume / 100f,
volume / 100f
)
}
}
}
var isAudioBackground = false
internal set
init {
basePlayer.setOnPlayerEventListener(playerEventListener)
basePlayer.setOnErrorEventListener(errorEventListener)
EvsSpeaker.get(null).addOnVolumeChangedListener(onVolumeChangedListener)
}
interface Listener {
fun onPlayerStateChanged(
player: EvsVideoPlayerInstance,
playbackState: Int
)
fun onPlayerError(player: EvsVideoPlayerInstance, errorCode: String, errorMessage: String?)
fun onPlayerPositionUpdated(player: EvsVideoPlayerInstance, position: Long)
}
fun setListener(listener: Listener) {
this.listener = listener
}
fun setSuperContainer(superContainer: SuperContainer?) {
basePlayer.setSurface(null)
superContainer?.let {
val render = RenderTextureView(superContainer.context)
render.isTakeOverSurfaceTexture = true
render.setRenderCallback(renderCallback)
it.setRenderView(render.renderView)
it.setOnReceiverEventListener(receiverEventListener)
}
this.superContainer = superContainer
}
private fun bindRenderHolder(renderHolder: IRender.IRenderHolder?) {
renderHolder?.bindPlayer(basePlayer)
}
fun play(url: String) {
val dataSource = DataSource(url)
basePlayer.setDataSource(dataSource)
basePlayer.start()
}
fun setVolume(volume: Float) {
cacheVolume = volume
basePlayer.setVolume(volume, volume)
}
fun getVolume(): Float {
return cacheVolume
}
fun resume() {
basePlayer.resume()
}
fun pause() {
basePlayer.pause()
}
fun stop() {
basePlayer.stop()
}
fun seekTo(offset: Long) {
basePlayer.seekTo(offset.toInt())
}
fun getOffset(): Long {
return basePlayer.currentPosition.toLong()
}
fun getDuration(): Long {
return basePlayer.duration.toLong()
}
fun destroy() {
basePlayer.stop()
basePlayer.destroy()
EvsSpeaker.get(null).removeOnVolumeChangedListener(onVolumeChangedListener)
}
fun getPlaybackState(): Int {
return basePlayer.state
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.*
import androidx.core.os.bundleOf
import androidx.core.os.postDelayed
import androidx.core.view.isVisible
import androidx.core.view.postDelayed
import com.airbnb.lottie.LottieAnimationView
import com.google.gson.Gson
import com.iflytek.cyber.evs.sdk.agent.Alarm
import com.iflytek.cyber.evs.sdk.agent.AudioPlayer
import com.iflytek.cyber.evs.sdk.agent.Recognizer
import com.iflytek.cyber.evs.sdk.agent.System.Companion.PAYLOAD_CODE
import com.iflytek.cyber.iot.show.core.FloatingService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.impl.alarm.EvsAlarm
import com.iflytek.cyber.iot.show.core.impl.prompt.PromptManager
import com.iflytek.cyber.iot.show.core.impl.recognizer.EvsRecognizer
import com.iflytek.cyber.iot.show.core.impl.system.EvsSystem
import com.iflytek.cyber.iot.show.core.model.ReadWord
import com.iflytek.cyber.iot.show.core.record.GlobalRecorder
import com.iflytek.cyber.iot.show.core.utils.*
import com.iflytek.cyber.iot.show.core.widget.ShadowFrameLayout
import com.iflytek.cyber.iot.show.core.widget.StyledAlertDialog
import com.kk.taurus.playerbase.utils.NetworkUtils
import kotlinx.android.synthetic.main.fragment_speak_evaluating.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
class SpeakEvaluatingFragment : BaseFragment(), View.OnClickListener,
EvsRecognizer.OnEvaluateResultCallback,
GlobalRecorder.Observer, Alarm.AlarmStateChangedListener {
companion object {
const val CHINESE_SINGLE_WORD_TYPE = 0 //中文单字
const val CHINESE_WORDS_TYPE = 1 //中文词语
const val CHINESE_SENTENCE_TYPE = 2 //中文短句
const val ENGLISH_WORD_TYPE = 3 //英文单词
const val ENGLISH_SENTENCE_TYPE = 4 //英文短句
const val ENGLISH_ARTICLE_TYPE = 5 //英文篇章
fun newInstance(type: Int): SpeakEvaluatingFragment {
return SpeakEvaluatingFragment().apply {
arguments = bundleOf(Pair("type", type))
}
}
}
private lateinit var evaluatingProgress: ProgressBar
private lateinit var progressContainer: LinearLayout
private lateinit var tvWord: TextView
private lateinit var tvSentence: TextView
private lateinit var progressTextView: TextView
private lateinit var tvTitle: TextView
private lateinit var recording: LottieAnimationView
private lateinit var chineseSentence: FrameLayout
private lateinit var englishSentence: FrameLayout
private lateinit var recordButton: ImageView
private lateinit var tvEnglishArticle: TextView
private lateinit var tvRecordingText: TextView
private lateinit var recordingContainer: LinearLayout
private lateinit var tvRecordTips: TextView
private lateinit var tvEnglishTips: TextView
private lateinit var startRecordTips: LinearLayout
private lateinit var recordToolContent: View
private lateinit var restartRecord: TextView
private lateinit var finishRecord: TextView
private lateinit var recordButtonContent: FrameLayout
private lateinit var centerRecord: LottieAnimationView
private val evaluation = EvaluationUtils()
private var currentProgress = 0
private var textList = ArrayList<String>()
private var sentenceText: String? = null
private var animateCount = 0
private var isEndTipsShow = false
private var shouldEnableWakeUp = false //是否应该恢复之前的唤醒按钮
private var retryCount = 0 //max 3
private var isRecording = false
private var shouldShowMidErrorView = false
private var shouldPromptTts = true
private var startRecordTime = 0L
private var isNetworkError = false
private var readSentence: ReadWord? = null
private var readSyllableList = ArrayList<ReadWord>()
private var punctuationList = ArrayList<String>()
private var handler = Handler(Looper.getMainLooper())
private var testType: Int? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_speak_evaluating, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(launcher?.getService()?.getRecognizer() as? EvsRecognizer)?.registerEvaluateResultCallback(
this
)
(launcher?.getService()?.getAlarm() as? EvsAlarm)?.addListener(this)
EvsSystem.get().onEvsErrorListener = onEvsErrorListener
GlobalRecorder.registerObserver(this)
launcher?.window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
view.findViewById<View>(R.id.back).clickWithTrigger {
pop()
}
progressContainer = view.findViewById(R.id.progress_container)
evaluatingProgress = view.findViewById(R.id.progress)
tvWord = view.findViewById(R.id.tv_word)
tvTitle = view.findViewById(R.id.tv_title)
tvSentence = view.findViewById(R.id.tv_sentence)
progressTextView = view.findViewById(R.id.tv_progress)
recording = view.findViewById(R.id.recording)
recording.setOnClickListener(this)
recordingContainer = view.findViewById(R.id.recording_container)
chineseSentence = view.findViewById(R.id.chinese_sentence)
englishSentence = view.findViewById(R.id.english_sentence)
tvEnglishArticle = view.findViewById(R.id.tv_english_article)
recordButton = view.findViewById(R.id.record_button)
recordButton.setOnClickListener(this)
tvRecordingText = view.findViewById(R.id.tv_recording_text)
tvRecordTips = view.findViewById(R.id.tv_record_tips)
tvEnglishTips = view.findViewById(R.id.tv_english_tips)
startRecordTips = view.findViewById(R.id.start_record_tips)
startRecordTips.translationX = 40f.dp2Px()
recordButtonContent = view.findViewById(R.id.record_button_content)
recordToolContent = view.findViewById(R.id.record_tool_content)
centerRecord = view.findViewById(R.id.center_recording)
restartRecord = view.findViewById(R.id.restart_record)
finishRecord = view.findViewById(R.id.finish_record)
restartRecord.clickWithTrigger {
if (restartRecord.isSelected) {
onRestartRecord()
}
}
finishRecord.clickWithTrigger {
if (finishRecord.isSelected) {
onFinishRecord()
}
}
testType = arguments?.getInt("type")
when (testType) {
CHINESE_SINGLE_WORD_TYPE -> {
tvRecordTips.text = "请在开始录音后读出以下汉字"
progressContainer.isVisible = true
chineseSentence.isVisible = true
startRecordTips.isVisible = true
recordToolContent.isVisible = false
progressTextView.text = "1/10"
textList = evaluation.getChineseSingleList()
tvWord.text = evaluation.filterSentence(textList[0])
}
CHINESE_WORDS_TYPE -> {
tvRecordTips.text = "请在开始录音后读出以下词语"
progressContainer.isVisible = true
chineseSentence.isVisible = true
startRecordTips.isVisible = true
recordToolContent.isVisible = false
progressTextView.text = "1/10"
textList = evaluation.getChineseWordsList()
tvWord.text = textList[0]
}
CHINESE_SENTENCE_TYPE -> {
tvRecordTips.text = "请在开始录音后读出以下句子"
tvTitle.isVisible = true
tvSentence.isVisible = true
chineseSentence.isVisible = true
sentenceText = evaluation.getChineseSentence()
punctuationList = evaluation.getPunctuationList(sentenceText!!)
tvSentence.text = evaluation.filterSentence(sentenceText)
}
ENGLISH_WORD_TYPE -> {
tvRecordTips.text = "请在开始录音后读出以下单词"
progressTextView.text = "1/10"
progressContainer.isVisible = true
chineseSentence.isVisible = true
startRecordTips.isVisible = true
recordToolContent.isVisible = false
textList = evaluation.getEnglishSingleWordList()
tvWord.text = textList[0]
}
ENGLISH_SENTENCE_TYPE -> {
tvRecordTips.text = "请在开始录音后读出以下句子"
tvTitle.isVisible = true
tvSentence.isVisible = true
chineseSentence.isVisible = true
sentenceText = evaluation.getEnglishSentence()
punctuationList = evaluation.getPunctuationList(sentenceText!!)
tvSentence.text = sentenceText
}
ENGLISH_ARTICLE_TYPE -> {
tvEnglishTips.text = "请在开始录音后60s读完文章"
tvTitle.isVisible = true
tvTitle.setText(R.string.article_evaluation)
englishSentence.isVisible = true
sentenceText = evaluation.getEnglishArticle()
punctuationList = evaluation.getPunctuationList(sentenceText!!)
tvEnglishArticle.text = sentenceText
}
}
EventBus.getDefault().register(this)
val intent = Intent(context, FloatingService::class.java).apply {
action = FloatingService.ACTION_EVALUATING
putExtra("isEvaluating", true)
}
context?.startService(intent)
val dismissMicErrorIntent = Intent(context, FloatingService::class.java).apply {
action = FloatingService.ACTION_DISMISS_MIC_ERROR
}
context?.startService(dismissMicErrorIntent)
val isMicrophoneEnabled =
ConfigUtils.getBoolean(ConfigUtils.KEY_VOICE_WAKEUP_ENABLED, true)
if (isMicrophoneEnabled) {
shouldPromptTts = true
} else {
shouldPromptTts = false
shouldShowMidErrorView = true
}
handler.postDelayed(100) {
if (isMicrophoneEnabled) {
ConfigUtils.putBoolean(ConfigUtils.KEY_VOICE_WAKEUP_ENABLED, false)
shouldEnableWakeUp = true
}
}
}
override fun onSupportVisible() {
super.onSupportVisible()
if (animateCount < 3) {
view?.postDelayed(500) {
setupStartRecordTipsAnimation()
}
}
ConnectivityUtils.checkIvsAvailable({
post {
isNetworkError = false
}
}, { _, _ ->
post {
isNetworkError = true
if (testType == CHINESE_SENTENCE_TYPE ||
testType == ENGLISH_SENTENCE_TYPE ||
testType == ENGLISH_ARTICLE_TYPE) {
onRestartRecord()
} else {
recordButtonContent.isVisible = true
recordingContainer.isVisible = false
recording.pauseAnimation()
networkUnavailable()
}
}
})
}
override fun onAlarmStateChanged(alarmId: String, state: Alarm.AlarmState) {
if (state == Alarm.AlarmState.Stopped) {
if (testType == CHINESE_SENTENCE_TYPE ||
testType == ENGLISH_SENTENCE_TYPE ||
testType == ENGLISH_ARTICLE_TYPE
) {
val alertDialog = StyledAlertDialog.Builder()
.setMessage("评测被打断,是否重新录音?")
.setPositiveButton("重录该题", View.OnClickListener {
onRecordButtonClick()
})
.setNegativeButton("退出", View.OnClickListener {
startWithPopTo(
SpeakEvaluationFragment(),
SpeakEvaluationFragment::class.java,
true
)
})
.show(childFragmentManager)
alertDialog.isCancelable = false
} else {
onRecordingClick()
}
}
}
private val onEvsErrorListener = object : EvsSystem.OnEvsErrorListener {
override fun onError(payload: com.alibaba.fastjson.JSONObject) {
val code = payload.getIntValue(PAYLOAD_CODE)
if (code == 500) {
if (retryCount < 3) {
showErrorDialog()
} else if (isAdded && context != null) {
Toast.makeText(context, "系统异常,请稍后再开始评测", Toast.LENGTH_SHORT).show()
startWithPopTo(
SpeakEvaluationFragment(),
SpeakEvaluationFragment::class.java,
true
)
}
}
}
}
private fun showErrorDialog() {
if (!isAdded || context == null) {
return
}
val alertDialog = StyledAlertDialog.Builder()
.setMessage("系统出了点问题,你可以选择重录该题")
.setPositiveButton("重录该题", View.OnClickListener {
retryCount += 1
onRecordButtonClick()
})
.setNegativeButton("退出", View.OnClickListener {
startWithPopTo(SpeakEvaluationFragment(), SpeakEvaluationFragment::class.java, true)
})
.show(childFragmentManager)
alertDialog.isCancelable = false
}
private fun setupStartRecordTipsAnimation() {
startRecordTips.translationX = 40f.dp2Px()
startRecordTips.animate()
.translationX(0f)
.setDuration(1000)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
super.onAnimationEnd(animation)
if (animateCount < 3) {
setupStartRecordTipsAnimation()
}
animateCount += 1
}
})
.start()
}
override fun onAudioData(array: ByteArray, offset: Int, length: Int) {
val volume = RecordVolumeUtils.calculateVolume(array, length)
val progress = volume / 100
//recording.progress = progress
}
override fun onWakeUp(angle: Int, beam: Int, params: String?) {
if (shouldPromptTts) {
warnUserWorkingWithEvaluation()
}
}
private fun warnUserWorkingWithEvaluation() {
handler.removeCallbacksAndMessages(null)
launcher?.getService()?.getRecognizer()?.requestCancel()
PromptManager.play(PromptManager.EVALUATION_WARN)
if (isRecording) {
handler.postDelayed(5500) {
onRecordButtonClick()
}
}
}
private fun sendEvaluate(
language: String,
category: String,
text: String,
enableVad: Boolean = true
) {
isRecording = true
launcher?.getService()?.getRecognizer()?.sendEvaluate(
language,
category,
text,
enableVad
)
}
private fun showCodeErrorDialog() {
if (!isAdded || context == null) {
return
}
val alertDialog = StyledAlertDialog.Builder()
.setMessage("系统出了点问题,你可以选择重录该题")
.setPositiveButton("重录该题", View.OnClickListener {
onRecordButtonClick()
})
.setNegativeButton("退出", View.OnClickListener {
startWithPopTo(SpeakEvaluationFragment(), SpeakEvaluationFragment::class.java, true)
})
.show(childFragmentManager)
alertDialog.isCancelable = false
}
override fun onEvaluateResult(payload: String) {
val json = JSONObject(payload)
val code = json.getInt("code")
if (code != 0) {
launcher?.getService()?.getRecognizer()?.requestCancel()
pauseAudioPlayer()
showCodeErrorDialog()
return
}
retryCount = 0
if (testType == CHINESE_SINGLE_WORD_TYPE) {
extraWordPayload(payload, "read_syllable")
if (currentProgress < 9) {
currentProgress += 1
updateEvaluateProgress((currentProgress + 1) * 10)
progressTextView.text = "${currentProgress + 1}/10"
val word = textList[currentProgress]
tvWord.text = evaluation.filterSentence(word)
sendEvaluate(
Recognizer.LANGUAGE_ZH_CN,
Recognizer.EVALUATE_CATEGORY_READ_SYLLABLE,
word
)
} else if (currentProgress == 9) {
progressTextView.text = "10/10"
isRecording = false
startWithPop(SpeakEvaluationResultFragment.newInstance(testType, readSyllableList))
}
}
if (testType == CHINESE_WORDS_TYPE) {
extraWordPayload(payload, "read_word")
if (currentProgress < 9) {
currentProgress += 1
updateEvaluateProgress((currentProgress + 1) * 10)
progressTextView.text = "${currentProgress + 1}/10"
val word = textList[currentProgress]
tvWord.text = word
sendEvaluate(
Recognizer.LANGUAGE_ZH_CN,
Recognizer.EVALUATE_CATEGORY_READ_WORD,
"[word]\n${word}"
)
} else if (currentProgress == 9) {
isRecording = false
progressTextView.text = "10/10"
startWithPop(SpeakEvaluationResultFragment.newInstance(testType, readSyllableList))
}
}
if (testType == CHINESE_SENTENCE_TYPE) {
isRecording = false
extraSentencePayload(payload, "read_sentence")
startWithPop(
SpeakEvaluationResultFragment.newInstance(
testType,
readSentence,
punctuationList
)
)
}
if (testType == ENGLISH_WORD_TYPE) {
extraWordPayload(payload, "read_word")
if (currentProgress < 9) {
currentProgress += 1
updateEvaluateProgress((currentProgress + 1) * 10)
progressTextView.text = "${currentProgress + 1}/10"
val word = textList[currentProgress]
tvWord.text = word
sendEvaluate(
Recognizer.LANGUAGE_EN_US,
Recognizer.EVALUATE_CATEGORY_READ_WORD,
"[word]\n${word}"
)
} else if (currentProgress == 9) {
isRecording = false
progressTextView.text = "10/10"
startWithPop(SpeakEvaluationResultFragment.newInstance(testType, readSyllableList))
}
}
if (testType == ENGLISH_SENTENCE_TYPE) {
isRecording = false
extraSentencePayload(payload, "read_chapter")
startWithPop(
SpeakEvaluationResultFragment.newInstance(
testType,
readSentence,
punctuationList
)
)
}
if (testType == ENGLISH_ARTICLE_TYPE) {
isRecording = false
extraSentencePayload(payload, "read_chapter")
startWithPop(
SpeakEvaluationResultFragment.newInstance(
testType,
readSentence,
punctuationList
)
)
}
}
private fun updateEvaluateProgress(end: Int) {
val start = currentProgress * 10
val animator = ValueAnimator.ofInt(start, end)
animator.addUpdateListener {
val value = it.animatedValue as Int
evaluatingProgress.progress = value
}
animator.duration = 300
animator.start()
}
private fun networkUnavailable() {
if (isAdded && launcher != null) {
PromptManager.play(PromptManager.NETWORK_LOST)
val networkErrorNotification =
Intent(launcher!!, FloatingService::class.java)
networkErrorNotification.action =
FloatingService.ACTION_SHOW_NOTIFICATION
networkErrorNotification.putExtra(
FloatingService.EXTRA_MESSAGE, "网络连接异常,请重新设置"
)
networkErrorNotification.putExtra(
FloatingService.EXTRA_TAG, "network_error"
)
networkErrorNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_TEXT, "设置网络"
)
networkErrorNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_ACTION,
MainFragment2.ACTION_OPEN_WIFI
)
networkErrorNotification.putExtra(
FloatingService.EXTRA_ICON_RES,
R.drawable.ic_wifi_error_white_40dp
)
launcher?.startService(networkErrorNotification)
}
}
/**
* 手动点击唤醒按钮回调
*/
@Subscribe(threadMode = ThreadMode.MAIN)
fun onWakeUpButtonClick(evaluationAction: EvaluationAction) {
if (evaluationAction.action == 0) {
warnUserWorkingWithEvaluation()
}
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.record_button -> {
if (isAdded && context != null && (!NetworkUtils.isNetConnected(context) || isNetworkError)) {
networkUnavailable()
return
}
onRecordButtonClick()
}
R.id.recording -> {
onRecordingClick()
}
}
}
private fun scaleRecordButton() {
recordButton.setBackgroundResource(R.drawable.ic_music_pause)
recordButtonContent.animate()
.setInterpolator(AccelerateDecelerateInterpolator())
.scaleX(0.9f)
.scaleY(0.9f)
.setDuration(300)
.start()
}
private fun onRecordButtonClick() {
//recordButton.isVisible = false
//recordingContainer.isVisible = true
startRecordTime = System.currentTimeMillis()
startRecordTips.isVisible = false
pauseAudioPlayer()
val isMicrophoneEnabled =
ConfigUtils.getBoolean(ConfigUtils.KEY_VOICE_WAKEUP_ENABLED, true)
if (isMicrophoneEnabled) {
ConfigUtils.putBoolean(ConfigUtils.KEY_VOICE_WAKEUP_ENABLED, false)
shouldEnableWakeUp = true
}
if (testType == CHINESE_SINGLE_WORD_TYPE) {
tvRecordTips.text = "请继续…读出以下汉字"
tvRecordingText.isVisible = true
recordButtonContent.isVisible = false
recordingContainer.isVisible = true
recording.playAnimation()
sendEvaluate(
Recognizer.LANGUAGE_ZH_CN,
Recognizer.EVALUATE_CATEGORY_READ_SYLLABLE,
textList[currentProgress]
)
} else if (testType == CHINESE_WORDS_TYPE) {
tvRecordTips.text = "请继续…读出以下词语"
tvRecordingText.isVisible = true
recordButtonContent.isVisible = false
recordingContainer.isVisible = true
recording.playAnimation()
sendEvaluate(
Recognizer.LANGUAGE_ZH_CN,
Recognizer.EVALUATE_CATEGORY_READ_WORD,
"[word]\n${textList[currentProgress]}"
)
} else if (testType == CHINESE_SENTENCE_TYPE && !sentenceText.isNullOrEmpty()) {
tvRecordingText.isVisible = true
restartRecord.isSelected = true
finishRecord.isSelected = true
centerRecord.playAnimation()
recordButtonContent.isVisible = false
sendEvaluate(
Recognizer.LANGUAGE_ZH_CN,
Recognizer.EVALUATE_CATEGORY_READ_SENTENCE,
sentenceText!!,
false
)
handler.removeCallbacksAndMessages(null)
handler.postDelayed(20 * 1000) {
launcher?.getService()?.getRecognizer()?.requestEnd()
}
} else if (testType == ENGLISH_WORD_TYPE) {
tvRecordTips.text = "请继续…读出以下单词"
tvRecordingText.isVisible = true
recordButtonContent.isVisible = false
recordingContainer.isVisible = true
recording.playAnimation()
sendEvaluate(
Recognizer.LANGUAGE_EN_US,
Recognizer.EVALUATE_CATEGORY_READ_WORD,
"[word]\n${textList[currentProgress]}"
)
} else if (testType == ENGLISH_SENTENCE_TYPE && !sentenceText.isNullOrEmpty()) {
tvRecordingText.isVisible = true
restartRecord.isSelected = true
finishRecord.isSelected = true
centerRecord.playAnimation()
recordButtonContent.isVisible = false
sendEvaluate(
Recognizer.LANGUAGE_EN_US,
Recognizer.EVALUATE_CATEGORY_READ_SENTENCE,
sentenceText!!,
false
)
handler.removeCallbacksAndMessages(null)
handler.postDelayed(20 * 1000) {
launcher?.getService()?.getRecognizer()?.requestEnd()
}
} else if (testType == ENGLISH_ARTICLE_TYPE && !sentenceText.isNullOrEmpty()) {
tvEnglishTips.text = "请继续…读完以下文章"
tvRecordingText.isVisible = false
centerRecord.playAnimation()
recordButtonContent.isVisible = false
restartRecord.isSelected = true
finishRecord.isSelected = true
sendEvaluate(
Recognizer.LANGUAGE_EN_US,
Recognizer.EVALUATE_CATEGORY_READ_CHAPTER,
sentenceText!!,
false
)
}
}
private fun onRestartRecord() {
if (testType == ENGLISH_ARTICLE_TYPE ||
testType == CHINESE_SENTENCE_TYPE ||
testType == ENGLISH_SENTENCE_TYPE
) {
centerRecord.pauseAnimation()
recordButtonContent.isVisible = true
recordButton.setBackgroundResource(R.drawable.ic_record_white_40)
restartRecord.isSelected = false
finishRecord.isSelected = false
launcher?.getService()?.getRecognizer()?.requestCancel()
}
}
private fun onFinishRecord() {
if (!isAdded || context == null) {
return
}
val endRecordTime = System.currentTimeMillis()
if (endRecordTime - startRecordTime <= 1000) {
Toast.makeText(context, "录音时间过短", Toast.LENGTH_SHORT).show()
}
launcher?.getService()?.getRecognizer()?.requestEnd()
}
private fun onRecordingClick() {
if (!isAdded || context == null) {
return
}
if (testType == ENGLISH_ARTICLE_TYPE ||
testType == CHINESE_SENTENCE_TYPE ||
testType == ENGLISH_SENTENCE_TYPE
) {
val alertDialog = StyledAlertDialog.Builder()
.setTitle("是否结束并提交录音?")
.setNegativeButton("继续录音", View.OnClickListener {
})
.setNegativeButton2("重录", View.OnClickListener {
launcher?.getService()?.getRecognizer()?.requestCancel()
onRecordButtonClick()
})
.setPositiveButton("提交录音", View.OnClickListener {
launcher?.getService()?.getRecognizer()?.requestEnd()
})
.show(childFragmentManager)
alertDialog.isCancelable = false
} else {
val alertDialog = StyledAlertDialog.Builder()
.setTitle("是否结束并提交录音?")
.setMessage("还没录完,只有录完才可以获得较高分数哦")
.setNegativeButton2("重录", View.OnClickListener {
restartRecord()
})
.setPositiveButton("继续录音", View.OnClickListener {
launcher?.getService()?.getRecognizer()?.requestCancel()
onRecordButtonClick()
})
.show(childFragmentManager)
alertDialog.isCancelable = false
}
}
private fun restartRecord() {
if (testType == CHINESE_SINGLE_WORD_TYPE ||
testType == CHINESE_WORDS_TYPE ||
testType == ENGLISH_WORD_TYPE
) {
currentProgress = 0
progressTextView.text = "1/10"
evaluatingProgress.progress = 10
tvWord.text = textList[0]
readSyllableList.clear()
launcher?.getService()?.getRecognizer()?.requestCancel()
onRecordButtonClick()
} else if (testType == CHINESE_SENTENCE_TYPE ||
testType == ENGLISH_SENTENCE_TYPE
) {
launcher?.getService()?.getRecognizer()?.requestCancel()
onRecordButtonClick()
}
}
private fun extraWordPayload(payload: String, objectName: String) {
val json = JSONObject(payload)
val readSyllableJson = json.getJSONObject("data").getJSONObject(objectName)
val readSyllable =
Gson().fromJson<ReadWord>(readSyllableJson.toString(), ReadWord::class.java)
readSyllableList.add(readSyllable)
}
private fun extraSentencePayload(payload: String, objectName: String) {
val json = JSONObject(payload)
val readSentenceJson = json.getJSONObject("data").getJSONObject(objectName)
val readWord =
Gson().fromJson<ReadWord>(readSentenceJson.toString(), ReadWord::class.java)
this.readSentence = readWord
}
private fun pauseAudioPlayer() {
val audioPlayer = launcher?.getService()?.getAudioPlayer()
if (audioPlayer?.playbackState == AudioPlayer.PLAYBACK_STATE_PLAYING) {
audioPlayer.stop(AudioPlayer.TYPE_TTS)
audioPlayer.stop(AudioPlayer.TYPE_RING)
audioPlayer.stop(AudioPlayer.TYPE_PLAYBACK)
}
}
override fun onDestroy() {
super.onDestroy()
isRecording = false
launcher?.window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
PromptManager.stop()
handler.removeCallbacksAndMessages(null)
EvsSystem.get().onEvsErrorListener = null
val intent = Intent(context, FloatingService::class.java).apply {
action = FloatingService.ACTION_EVALUATING
putExtra("isEvaluating", false)
}
context?.startService(intent)
if (shouldShowMidErrorView) {
val showMicErrorIntent = Intent(context, FloatingService::class.java).apply {
action = FloatingService.ACTION_SHOW_MISC_ERROR
}
context?.startService(showMicErrorIntent)
}
EventBus.getDefault().unregister(this)
handler.postDelayed(100) {
if (shouldEnableWakeUp) {
ConfigUtils.putBoolean(ConfigUtils.KEY_VOICE_WAKEUP_ENABLED, true)
}
}
launcher?.getService()?.getRecognizer()?.requestCancel()
(launcher?.getService()?.getAlarm() as? EvsAlarm)?.removeListener(this)
currentProgress = 0
GlobalRecorder.unregisterObserver(this)
}
data class EvaluationAction(val action: Int)
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.iflytek.cyber.evs.sdk.auth.AuthDelegate
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.FloatingService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.AudioSearchResultAdapter
import com.iflytek.cyber.iot.show.core.adapter.SpacesItemDecoration
import com.iflytek.cyber.iot.show.core.adapter.VideoSearchResultAdapter
import com.iflytek.cyber.iot.show.core.api.MediaApi
import com.iflytek.cyber.iot.show.core.model.Error
import com.iflytek.cyber.iot.show.core.model.PlayBody
import com.iflytek.cyber.iot.show.core.model.Result
import com.iflytek.cyber.iot.show.core.model.SearchBody
import com.iflytek.cyber.iot.show.core.model.SearchResult
import com.iflytek.cyber.iot.show.core.utils.InsetDividerDecoration
import com.iflytek.cyber.iot.show.core.utils.dp2Px
import com.iflytek.cyber.iot.show.core.utils.onLoadMore
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class SearchResultFragment : BaseFragment() {
private lateinit var audioList: RecyclerView
private lateinit var videoList: RecyclerView
private var results: ArrayList<Result>? = null
private var keyword: String? = null
private var listType: Int? = -1
private var page = 1
private var isLoading = false
private var audioSearchResultAdapter: AudioSearchResultAdapter? = null
private var videoSearchResultAdapter: VideoSearchResultAdapter? = null
companion object {
const val TYPE_AUDIO = 10322
const val TYPE_VIDEO = 10323
fun newInstance(
keyword: String,
type: Int,
results: ArrayList<Result>
): SearchResultFragment {
return SearchResultFragment().apply {
arguments = bundleOf(
Pair("keyword", keyword),
Pair("results", results),
Pair("type", type)
)
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_search_result, container, false)
}
@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
audioList = view.findViewById(R.id.audio_list)
videoList = view.findViewById(R.id.video_list)
val title = view.findViewById<TextView>(R.id.title)
view.findViewById<View>(R.id.back).setOnClickListener { pop() }
keyword = arguments?.getString("keyword")
listType = arguments?.getInt("type")
results = arguments?.getParcelableArrayList<Result>("results")
if (listType == TYPE_AUDIO) {
title.text = "“${keyword}” 音频搜索结果"
audioList.isVisible = true
setupAudioList()
} else if (listType == TYPE_VIDEO) {
title.text = "“${keyword}” 视频搜索结果"
videoList.isVisible = true
setupVideoList()
}
}
private fun setupAudioList() {
val itemDecoration = InsetDividerDecoration(
1.dp2Px(),
ContextCompat.getColor(requireContext(), R.color.dividerLight), 1
)
itemDecoration.startPadding = resources.getDimensionPixelOffset(R.dimen.dp_32)
itemDecoration.endPadding = resources.getDimensionPixelOffset(R.dimen.dp_32)
audioList.addItemDecoration(itemDecoration)
if (audioSearchResultAdapter == null && results != null) {
audioSearchResultAdapter = AudioSearchResultAdapter(results!!) {
playSearchMedia(it)
}
/* if (results!!.size < 10) {
audioSearchResultAdapter?.loadingFinish(true)
}*/
audioList.adapter = audioSearchResultAdapter
}
audioList.onLoadMore {
if (!isLoading) {
page += 1
loadMore()
}
}
}
private fun setupVideoList() {
val layoutManager = GridLayoutManager(requireContext(), 4)
videoList.layoutManager = layoutManager
val decoration = SpacesItemDecoration(0)
decoration.top = resources.getDimensionPixelSize(R.dimen.dp_12)
decoration.bottom = resources.getDimensionPixelSize(R.dimen.dp_12)
videoList.addItemDecoration(decoration)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return if (videoSearchResultAdapter != null &&
videoSearchResultAdapter?.getItemViewType(position) == R.layout.item_loading
) {
4
} else {
1
}
}
}
if (videoSearchResultAdapter == null) {
videoSearchResultAdapter = VideoSearchResultAdapter {
playSearchMedia(it)
}
if (results != null) {
videoSearchResultAdapter?.setResults("", results!!)
}
/*if (results!!.size < 10) {
videoSearchResultAdapter?.loadingFinish(true)
}*/
videoList.adapter = videoSearchResultAdapter
}
videoList.onLoadMore {
if (!isLoading) {
page += 1
loadMore()
}
}
}
private fun loadMore() {
if (keyword.isNullOrEmpty()) {
return
}
isLoading = true
val body = SearchBody(keyword!!, 20, page)
getMediaApi()?.search(body)?.enqueue(object : Callback<ArrayList<SearchResult>> {
override fun onResponse(
call: Call<ArrayList<SearchResult>>,
response: Response<ArrayList<SearchResult>>
) {
isLoading = false
if (response.isSuccessful) {
val searchResult = response.body()
if (searchResult.isNullOrEmpty()) {
if (listType == TYPE_AUDIO) {
audioSearchResultAdapter?.loadingFinish(true)
} else {
videoSearchResultAdapter?.loadingFinish(true)
}
} else {
searchResult.forEach {
if (listType == TYPE_AUDIO && it.type == 1) {
if (it.results.isNullOrEmpty()) {
audioSearchResultAdapter?.loadingFinish(true)
} else {
results?.addAll(it.results)
}
} else if (listType == TYPE_VIDEO && it.type == 2) {
if (it.results.isNullOrEmpty()) {
videoSearchResultAdapter?.loadingFinish(true)
} else {
results?.addAll(it.results)
}
}
}
}
if (listType == TYPE_AUDIO) {
audioSearchResultAdapter?.notifyDataSetChanged()
} else if (listType == TYPE_VIDEO && results != null) {
videoSearchResultAdapter?.setResults("", results!!)
videoSearchResultAdapter?.notifyDataSetChanged()
}
} else {
page -= 1
if (listType == TYPE_AUDIO) {
audioSearchResultAdapter?.loadingFinish(true)
} else if (listType == TYPE_VIDEO) {
videoSearchResultAdapter?.loadingFinish(true)
}
}
}
override fun onFailure(call: Call<ArrayList<SearchResult>>, t: Throwable) {
page -= 1
isLoading = false
t.printStackTrace()
}
})
}
private fun playSearchMedia(result: Result) {
val body = PlayBody(result.id, result.business, result.source)
getMediaApi()?.playSearchMedia(body)?.enqueue(object : Callback<String> {
override fun onResponse(call: Call<String>, response: Response<String>) {
if (response.isSuccessful) {
Toast.makeText(requireContext(), "播放${result.title}", Toast.LENGTH_SHORT).show()
} else {
showError(response.errorBody()?.string())
}
}
override fun onFailure(call: Call<String>, t: Throwable) {
t.printStackTrace()
}
})
}
private fun showError(errorStr: String?) {
try {
val error = Gson().fromJson(errorStr, Error::class.java)
if (error.redirectUrl.isNullOrEmpty()) {
val intent = Intent(context, FloatingService::class.java)
intent.action = FloatingService.ACTION_SHOW_NOTIFICATION
intent.putExtra(FloatingService.EXTRA_MESSAGE, error.message)
intent.putExtra(FloatingService.EXTRA_POSITIVE_BUTTON_TEXT, "我知道了")
context?.startService(intent)
} else {
val context = context ?: return
val uri = Uri.parse(error.redirectUrl)
val codeUrl = uri.buildUpon()
.appendQueryParameter(
"token",
AuthDelegate.getAuthResponseFromPref(context)?.accessToken
)
.build()
.toString()
start(
KugouQRCodeFragment.newInstance(
error.title,
error.message,
error.qrCodeMessage,
error.redirectUrl
)
)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun getMediaApi(): MediaApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(MediaApi::class.java)
} else {
null
}
}
}
<file_sep># 版本更新历史
| 日期 | 更新内容 |
| --- | --- |
| 2019-09-20 | 初版更新 |
| 2019-12-13 | <ol><li>EVS SDK 更新,详情参考 [EVS Android SDK](https://github.com/iFLYOS-OPEN/SDK-EVS-Android) 的更新日志</li><li>更新唤醒词引擎至70版本</li><li>增加保活 Demo 模块</li><li>修复若干体验问题</li></ol> |
| 2019-12-30 | <ol><li>EVS SDK 更新,详情参考 [EVS Android SDK](https://github.com/iFLYOS-OPEN/SDK-EVS-Android) 的更新日志</li><li>修复部分情况下设备重连失败的问题</li><li>修复了若干体验问题</li></ol> |
| 2019-04-27 | <ol><li>EVS SDK 更新,详情参考 [EVS Android SDK](https://github.com/iFLYOS-OPEN/SDK-EVS-Android) 的更新日志</li><li>全新的桌面展示</li><li>丰富应用中心内容</li><li>修复了若干遗留问题</li></ol> |
<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.content.ComponentName
import android.content.ContentResolver
import android.content.Context
import android.os.PowerManager
import android.os.SystemClock
import android.os.UserHandle
import android.provider.Settings
import com.iflytek.cyber.iot.show.core.ShowCoreDream
import java.util.concurrent.TimeUnit
object ScreenOffTimeoutUtils {
@Suppress("unused")
private const val TAG = "ScreenOffTimeoutUtils"
private const val SCREENSAVER_ACTIVATE_ON_DOCK = "screensaver_activate_on_dock"
private const val SCREENSAVER_ACTIVATE_ON_SLEEP = "screensaver_activate_on_sleep"
private const val SCREENSAVER_DEFAULT_COMPONENT = "screensaver_default_component"
private const val SCREENSAVER_COMPONENTS = "screensaver_components"
private const val SCREENSAVER_ENABLED = "screensaver_enabled"
val ONE_MIN_TIMEOUT = TimeUnit.MINUTES.toMillis(1).toInt()
val TWO_MIN_TIMEOUT = TimeUnit.MINUTES.toMillis(2).toInt()
val FIVE_MIN_TIMEOUT = TimeUnit.MINUTES.toMillis(5).toInt()
val TEN_MIN_TIMEOUT = TimeUnit.MINUTES.toMillis(10).toInt()
val DEFAULT_TIMEOUT = TWO_MIN_TIMEOUT
@Suppress("MemberVisibilityCanBePrivate")
const val NEVER_TIMEOUT = Int.MAX_VALUE
fun getTimeout(context: Context): Int {
val contentResolver = context.contentResolver
return Settings.System.getInt(
contentResolver,
Settings.System.SCREEN_OFF_TIMEOUT,
DEFAULT_TIMEOUT
)
}
fun setTimeout(context: Context, timeout: Int) {
val contentResolver = context.contentResolver
Settings.System.putInt(
contentResolver,
Settings.System.SCREEN_OFF_TIMEOUT,
timeout
)
}
private fun setActiveDream(context: Context, dream: ComponentName) {
try {
val clz = Settings.Secure::class.java
val putStringForUser = clz.getDeclaredMethod(
"putStringForUser",
ContentResolver::class.java,
String::class.java,
String::class.java,
Int::class.java
)
putStringForUser.invoke(
null,
context.contentResolver,
SCREENSAVER_COMPONENTS,
dream.flattenToString(),
getCurrentUserId()
)
} catch (t: Throwable) {
t.printStackTrace()
}
}
fun dreamNow(context: Context) {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
try {
val time = SystemClock.uptimeMillis()
val clz = PowerManager::class.java
val userActivity =
clz.getDeclaredMethod("userActivity", Long::class.java, Boolean::class.java)
userActivity.isAccessible = true
userActivity.invoke(pm, time, false)
val nap = clz.getDeclaredMethod("nap", Long::class.java)
nap.isAccessible = true
nap.invoke(pm, time)
} catch (t: Throwable) {
t.printStackTrace()
}
}
private fun getCurrentUserId(): Int {
try {
val clz = UserHandle::class.java
val userOwner = clz.getDeclaredField("USER_OWNER")
userOwner.isAccessible = true
return userOwner.get(null) as Int
} catch (t: Throwable) {
t.printStackTrace()
}
return -1
}
fun init(context: Context) {
// only charging
setBoolean(context, SCREENSAVER_ENABLED, true)
setBoolean(context, SCREENSAVER_ACTIVATE_ON_DOCK, false)
setBoolean(context, SCREENSAVER_ACTIVATE_ON_SLEEP, true)
setActiveDream(
context,
ComponentName(context, ShowCoreDream::class.java)
)
}
private fun setBoolean(context: Context, key: String, value: Boolean) {
Settings.Secure.putInt(context.contentResolver, key, if (value) 1 else 0)
}
}<file_sep>//
// Created by huang on 2019/9/23.
//
#include "../../../com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec.h"
#include "src/arch.h"
#include <speex/speex.h>
#include <android/log.h>
#include <stdlib.h>
#undef TAG
#define TAG "SpeexCodec_Jni"
#define METHOD_SET_HANDLES "setHandles"
// nb模式下,各quality下每帧(640bytes,320个short)压缩后字节数
int enc_nb_frame_nbytes_of_quality[11] = {6, 10, 15, 20, 20, 28, 28, 38, 38, 46, 62};
// wb模式下,各quality下每帧(640bytes,320个short)压缩后字节数
int enc_wb_frame_nbytes_of_quality[11] = {10, 15, 20, 25, 32, 42, 52, 60, 70, 86, 106};
void* getHandle(JNIEnv *pEnv, jbyteArray handle)
{
char* handleChar = (char*) pEnv->GetByteArrayElements(handle, JNI_FALSE);
void* st = NULL;
if (sizeof(st) == 8) {
st = (SpeexBits*) (*((unsigned long long*) handleChar));
} else {
st = (SpeexBits*) (*((unsigned long*) handleChar));
}
pEnv->ReleaseByteArrayElements(handle, (jbyte*) handleChar, JNI_FALSE);
return st;
}
/*
* Class: com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec
* Method: init_native
* Signature: (IIII)I
*/
JNIEXPORT jint JNICALL Java_com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec_init_1native
(JNIEnv *pEnv, jobject thiz, jint codec, jint sampleRate, jint mode, jint quality)
{
jmethodID setHandlesMethod = pEnv->GetMethodID(pEnv->GetObjectClass(thiz), METHOD_SET_HANDLES, "([B[B)V");
if (NULL == setHandlesMethod) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "cannot find method %s with signature %s in Java class",
METHOD_SET_HANDLES, "(JJ)V");
return -1;
}
void* state = NULL;
SpeexBits* bits = new SpeexBits;
int tmp = quality;
if (com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec_CODEC_ENCODE == codec) {
if (com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec_MODE_NB == mode) {
state = speex_encoder_init(&speex_nb_mode);
} else {
state = speex_encoder_init(&speex_wb_mode);
}
if (NULL == state) {
if (NULL != bits) {
delete bits;
}
return -1;
}
speex_encoder_ctl(state, SPEEX_SET_QUALITY, &tmp);
} else {
if (com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec_MODE_NB == mode) {
state = speex_decoder_init(&speex_nb_mode);
} else {
state = speex_decoder_init(&speex_wb_mode);
}
if (NULL == state) {
if (NULL != bits) {
delete bits;
}
return -1;
}
tmp = 1;
speex_decoder_ctl(state, SPEEX_SET_ENH, &tmp);
}
speex_bits_init(bits);
int len = sizeof(state);
jbyteArray stateArray = pEnv->NewByteArray(len);
jbyteArray bitsArray = pEnv->NewByteArray(len);
pEnv->SetByteArrayRegion(stateArray, 0, len, (jbyte*) &state);
pEnv->SetByteArrayRegion(bitsArray, 0, len, (jbyte*) &bits);
pEnv->CallVoidMethod(thiz, setHandlesMethod, stateArray, bitsArray);
return 0;
}
/*
* Class: com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec
* Method: encode_native
* Signature: ([BI[BI)I
*/
JNIEXPORT jint JNICALL Java_com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec_encode_1native
(JNIEnv *pEnv, jobject thiz, jbyteArray state, jbyteArray speex_bits, jbyteArray data, jint dataLen,
jbyteArray buffer, jint bufferLen)
{
void* ptr_state = (void*) getHandle(pEnv, state);
SpeexBits* ptr_bits = (SpeexBits*) getHandle(pEnv, speex_bits);
int frameSize = 0;
speex_encoder_ctl(ptr_state, SPEEX_GET_FRAME_SIZE, &frameSize);
int shortDataLen = dataLen / 2;
if (shortDataLen % frameSize != 0) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "dataLen must be multiple of %d", frameSize);
return -1;
}
char* dataChars = (char*) pEnv->GetByteArrayElements(data, JNI_FALSE);
spx_int16_t* dataInt16 = (spx_int16_t*) dataChars;
char* tmpBuffer = new char[bufferLen];
int writeLen = 0;
for (int i = 0; i < shortDataLen; i += frameSize) {
speex_bits_reset(ptr_bits);
speex_encode_int(ptr_state, &dataInt16[i], ptr_bits);
writeLen += speex_bits_write(ptr_bits, &tmpBuffer[writeLen], bufferLen);
}
delete[] tmpBuffer;
pEnv->ReleaseByteArrayElements(data, (jbyte*) dataChars, JNI_FALSE);
pEnv->SetByteArrayRegion(buffer, 0, writeLen, (jbyte*) tmpBuffer);
return writeLen;
}
/*
* Class: com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec
* Method: decode_native
* Signature: (II[BI[BIII)I
*/
JNIEXPORT jint JNICALL Java_com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec_decode_1native
(JNIEnv *pEnv, jobject thiz, jbyteArray state, jbyteArray speex_bits, jbyteArray data, jint dataLen,
jbyteArray buffer, jint bufferLen, jint mode, jint quality)
{
void* ptr_state = (void*) getHandle(pEnv, state);
SpeexBits* ptr_bits = (SpeexBits*) getHandle(pEnv, speex_bits);
int encFrameBytes = 0;
if (com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec_MODE_NB == mode) {
encFrameBytes = enc_nb_frame_nbytes_of_quality[quality];
} else {
encFrameBytes = enc_wb_frame_nbytes_of_quality[quality];
}
if (dataLen % encFrameBytes != 0) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "dataLen must be multiple of %d", encFrameBytes);
return -1;
}
char* dataChars = (char*) pEnv->GetByteArrayElements(data, JNI_FALSE);
int readBytes = 0;
int frameSize = 0;
int writeOffset = 0;
speex_decoder_ctl(ptr_state, SPEEX_GET_FRAME_SIZE, &frameSize);
short* frame = new short[frameSize];
while (readBytes != dataLen) {
speex_bits_read_from(ptr_bits, &dataChars[readBytes], encFrameBytes);
readBytes += encFrameBytes;
int ret = speex_decode_int(ptr_state, ptr_bits, frame);
if (0 == ret) {
if (writeOffset < bufferLen) {
pEnv->SetByteArrayRegion(buffer, writeOffset, frameSize * 2, (jbyte *) frame);
writeOffset += frameSize * 2;
} else {
__android_log_print(ANDROID_LOG_ERROR, TAG, "buffer length is not enough");
break;
}
} else {
__android_log_print(ANDROID_LOG_ERROR, TAG, "decode, ret=%d", ret);
pEnv->ReleaseByteArrayElements(data, (jbyte*) dataChars, JNI_FALSE);
return ret;
}
}
delete[] frame;
pEnv->ReleaseByteArrayElements(data, (jbyte*) dataChars, JNI_FALSE);
return writeOffset;
}
/*
* Class: com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec
* Method: destroy_native
* Signature: (III)V
*/
JNIEXPORT void JNICALL Java_com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec_destroy_1native
(JNIEnv *pEnv, jobject thiz, jint codec, jbyteArray state, jbyteArray bits)
{
void* st = getHandle(pEnv, state);
void* pBits = getHandle(pEnv, bits);
if (com_iflytek_cyber_evs_sdk_codec_audio_speex_SpeexCodec_CODEC_ENCODE == codec) {
speex_encoder_destroy((void*) st);
} else {
speex_decoder_destroy((void*) st);
}
speex_bits_destroy((SpeexBits*) pBits);
delete (SpeexBits*) pBits;
}
<file_sep>package com.iflytek.cyber.iot.show.core.message
import android.content.Context
import android.util.Log
import com.iflytek.cyber.evs.sdk.auth.AuthDelegate
import okhttp3.*
import okio.ByteString
class MessageSocket private constructor() {
companion object {
private const val TAG = "MessageSocket"
private var instance: MessageSocket? = null
fun get(): MessageSocket {
instance?.let {
return it
} ?: run {
val newInstance = MessageSocket()
this.instance = newInstance
return newInstance
}
}
}
private val okHttpClient = OkHttpClient.Builder().build()
private val webSocketListener = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
super.onOpen(webSocket, response)
Log.d(TAG, "Socket connected")
}
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
super.onMessage(webSocket, bytes)
Log.d(TAG, "Socket onMessage: $bytes")
}
override fun onMessage(webSocket: WebSocket, text: String) {
super.onMessage(webSocket, text)
Log.d(TAG, "Socket onMessage: $text")
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
super.onClosed(webSocket, code, reason)
Log.d(TAG, "Socket disconnected")
}
}
fun connect(context: Context) {
val authResponse = AuthDelegate.getAuthResponseFromPref(context)
val request = Request.Builder()
.url("wss://staging-api.iflyos.cn/web/push?command=connect&token=${authResponse?.accessToken}&deviceId=42&fromType=message")
.build()
okHttpClient.newWebSocket(request, webSocketListener)
}
}<file_sep>//
// Created by huang on 2019/9/24.
//
#include "../../../com_iflytek_cyber_evs_sdk_codec_audio_opus_OpusCodec.h"
#include <opus.h>
#include <stdlib.h>
#include <android/log.h>
#undef TAG
#define TAG "OpusCodec_Jni"
#define METHOD_SET_HANDLES "setHandles"
#define CHANNEL_NUM 1
void* getHandle(JNIEnv *pEnv, jbyteArray handle)
{
char* handleChar = (char*) pEnv->GetByteArrayElements(handle, JNI_FALSE);
void* st = NULL;
if (sizeof(st) == 8) {
st = (OpusEncoder*) (*((unsigned long long*) handleChar));
} else {
st = (OpusEncoder*) (*((unsigned long*) handleChar));
}
pEnv->ReleaseByteArrayElements(handle, (jbyte*) handleChar, JNI_FALSE);
return st;
}
/*
* Class: com_iflytek_cyber_evs_sdk_codec_audio_opus_OpusCodec
* Method: init_native
* Signature: (III)I
*/
JNIEXPORT jint JNICALL Java_com_iflytek_cyber_evs_sdk_codec_audio_opus_OpusCodec_init_1native
(JNIEnv *pEnv, jobject thiz, jint codec, jint sampleRate, jint bitRate)
{
jmethodID setHandlesMethod = pEnv->GetMethodID(pEnv->GetObjectClass(thiz), METHOD_SET_HANDLES, "([B)V");
if (NULL == setHandlesMethod) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "cannot find method %s with signature %s in Java class",
METHOD_SET_HANDLES, "(J)V");
return -1;
}
void* st = NULL;
int error = 0;
if (com_iflytek_cyber_evs_sdk_codec_audio_opus_OpusCodec_CODEC_ENCODE == codec) {
st = opus_encoder_create(sampleRate, CHANNEL_NUM, OPUS_APPLICATION_VOIP, &error);
if (OPUS_OK != error) {
return error;
}
opus_encoder_ctl((OpusEncoder*) st, OPUS_SET_VBR(0));
opus_encoder_ctl((OpusEncoder*) st, OPUS_SET_BITRATE(bitRate));
} else {
st = opus_decoder_create(sampleRate, CHANNEL_NUM, &error);
if (OPUS_OK != error) {
return error;
}
}
int len = sizeof(st);
jbyteArray array = pEnv->NewByteArray(len);
pEnv->SetByteArrayRegion(array, 0, len, (jbyte*) &st);
pEnv->CallVoidMethod(thiz, setHandlesMethod, array);
return 0;
}
/*
* Class: com_iflytek_cyber_evs_sdk_codec_audio_opus_OpusCodec
* Method: encode_native
* Signature: (J[BI[BII)I
*/
JNIEXPORT jint JNICALL Java_com_iflytek_cyber_evs_sdk_codec_audio_opus_OpusCodec_encode_1native
(JNIEnv *pEnv, jobject thiz, jbyteArray handle, jbyteArray data, jint dataLen,
jbyteArray buffer, jint bufferLen, jint packetSize)
{
OpusEncoder* st = (OpusEncoder*) getHandle(pEnv, handle);
if (dataLen % packetSize != 0) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "dataLen must be multiple of %d",
packetSize);
return -1;
}
char* dataChars = (char*) pEnv->GetByteArrayElements(data, NULL);
unsigned char* tmpBuffer = new unsigned char[packetSize];
int readLen = 0;
int writeOffset = 0;
while (readLen < dataLen) {
int encLen = opus_encode(st, (opus_int16*) &dataChars[readLen], packetSize / 2, tmpBuffer, 4000);
if (encLen < 0) {
pEnv->ReleaseByteArrayElements(data, (jbyte*) dataChars, JNI_FALSE);
return encLen;
}
if (writeOffset + encLen > bufferLen) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "buffer is not enough");
pEnv->ReleaseByteArrayElements(data, (jbyte*) dataChars, JNI_FALSE);
return -1;
}
pEnv->SetByteArrayRegion(buffer, writeOffset, encLen, (jbyte*) tmpBuffer);
readLen += packetSize;
writeOffset += encLen;
}
delete[] tmpBuffer;
pEnv->ReleaseByteArrayElements(data, (jbyte*) dataChars, JNI_FALSE);
return writeOffset;
}
/*
* Class: com_iflytek_cyber_evs_sdk_codec_audio_opus_OpusCodec
* Method: decode_native
* Signature: (J[BI[BII)I
*/
JNIEXPORT jint JNICALL Java_com_iflytek_cyber_evs_sdk_codec_audio_opus_OpusCodec_decode_1native
(JNIEnv *pEnv, jobject thiz, jbyteArray handle, jbyteArray data, jint dataLen,
jbyteArray buffer, jint bufferLen, jint packetSize, jint packetDecSize)
{
OpusDecoder* st = (OpusDecoder*) getHandle(pEnv, handle);
if (dataLen % packetSize != 0) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "dataLen must be multiple of %d",
packetSize);
return -1;
}
char* dataChars = (char*) pEnv->GetByteArrayElements(data, NULL);
opus_int16* tmpBuffer = new opus_int16[packetDecSize / 2];
int readLen = 0;
int writeOffset = 0;
while (readLen < dataLen) {
int decLen = opus_decode(st, (const unsigned char*) &dataChars[readLen], packetSize,
tmpBuffer, packetDecSize / 2, 0);
if (decLen < 0) {
pEnv->ReleaseByteArrayElements(data, (jbyte*) dataChars, JNI_FALSE);
return decLen;
}
if (writeOffset + decLen > bufferLen) {
__android_log_print(ANDROID_LOG_ERROR, TAG, "buffer is not enough");
pEnv->ReleaseByteArrayElements(data, (jbyte*) dataChars, JNI_FALSE);
return -1;
}
pEnv->SetByteArrayRegion(buffer, writeOffset, decLen * 2, (jbyte*) tmpBuffer);
readLen += packetSize;
writeOffset += decLen * 2;
}
delete[] tmpBuffer;
pEnv->ReleaseByteArrayElements(data, (jbyte*) dataChars, JNI_FALSE);
return writeOffset;
}
/*
* Class: com_iflytek_cyber_evs_sdk_codec_audio_opus_OpusCodec
* Method: destroy_native
* Signature: (IJ)V
*/
JNIEXPORT void JNICALL Java_com_iflytek_cyber_evs_sdk_codec_audio_opus_OpusCodec_destroy_1native
(JNIEnv *pEnv, jobject thiz, jint codec, jbyteArray handle)
{
void* st = getHandle(pEnv, handle);
if (com_iflytek_cyber_evs_sdk_codec_audio_opus_OpusCodec_CODEC_ENCODE == codec) {
opus_encoder_destroy((OpusEncoder*) st);
} else {
opus_decoder_destroy((OpusDecoder*) st);
}
}<file_sep>package com.iflytek.cyber.iot.show.core.impl.audioplayer
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.os.Looper
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.audio.AudioAttributes
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DataSpec
import com.google.android.exoplayer2.upstream.FileDataSource
import com.iflytek.cyber.evs.sdk.agent.AudioPlayer
import com.iflytek.cyber.iot.show.core.impl.speaker.EvsSpeaker
import java.io.File
internal class AudioPlayerInstance(context: Context, private val type: String) {
companion object {
const val TYPE_TTS = AudioPlayer.TYPE_TTS
const val TYPE_PLAYBACK = AudioPlayer.TYPE_PLAYBACK
const val TYPE_RING = AudioPlayer.TYPE_RING
const val BACKGROUND_VOLUME = 0.1f
}
private val player = ExoPlayerFactory.newSimpleInstance(
context,
DefaultRenderersFactory(context),
DefaultTrackSelector(),
if (type == TYPE_TTS)
DefaultLoadControl.Builder()
.setBufferDurationsMs(
DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS,
DefaultLoadControl.DEFAULT_MAX_BUFFER_MS,
100,
DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS
)
.createDefaultLoadControl()
else
DefaultLoadControl()
)
private val mMediaSourceFactory: MediaSourceFactory
private val period = Timeline.Period()
var resourceId: String? = null
var isStarted: Boolean = false
private val audioAttributes = AudioAttributes.Builder()
.setContentType(
when (type) {
TYPE_RING ->
C.CONTENT_TYPE_SONIFICATION
TYPE_TTS ->
C.CONTENT_TYPE_SONIFICATION
TYPE_PLAYBACK ->
C.CONTENT_TYPE_SONIFICATION
else ->
C.CONTENT_TYPE_MUSIC
}
)
.setUsage(
when (type) {
TYPE_RING ->
C.USAGE_ALARM
TYPE_TTS ->
C.USAGE_NOTIFICATION
TYPE_PLAYBACK ->
C.USAGE_NOTIFICATION
else ->
C.USAGE_MEDIA
}
)
.build()
private val onVolumeChangedListener = object : EvsSpeaker.OnVolumeChangedListener {
override fun onVolumeChanged(volume: Int, fromRemote: Boolean) {
if (isBackground) {
player.volume = volume / 100f * BACKGROUND_VOLUME
} else {
player.volume = volume / 100f
}
}
}
private var listener: Listener? = null
var isBackground = false
internal set
private val handler = Handler()
init {
player.addListener(object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
if (playWhenReady && playbackState == Player.STATE_READY) {
handler.post(positionUpdateRunnable)
}
listener?.onPlayerStateChanged(
this@AudioPlayerInstance,
type,
playWhenReady,
playbackState
)
}
override fun onPlayerError(error: ExoPlaybackException?) {
listener?.onPlayerError(this@AudioPlayerInstance, type, error)
}
})
mMediaSourceFactory = MediaSourceFactory(context)
player.audioAttributes = audioAttributes
// player.playWhenReady = false
player.volume = volumePercent()
if (type == TYPE_PLAYBACK || type == TYPE_TTS)
EvsSpeaker.get(null).addOnVolumeChangedListener(onVolumeChangedListener)
}
private val positionUpdateRunnable = object : Runnable {
override fun run() {
if (player.playbackState == Player.STATE_READY
|| player.playbackState == Player.STATE_BUFFERING
) {
if (player.playWhenReady) {
listener?.onPlayerPositionUpdated(this@AudioPlayerInstance, type, getOffset())
handler.postDelayed(this, 500)
}
}
}
}
internal interface Listener {
fun onPlayerStateChanged(
player: AudioPlayerInstance,
type: String,
playWhenReady: Boolean,
playbackState: Int
)
fun onPlayerError(player: AudioPlayerInstance, type: String, error: ExoPlaybackException?)
fun onPlayerPositionUpdated(player: AudioPlayerInstance, type: String, position: Long)
}
fun setListener(listener: Listener) {
this.listener = listener
}
fun getListener(): Listener? {
return this.listener
}
fun play(url: String) {
handler.post {
val uri = Uri.parse(url)
val mediaSource = mMediaSourceFactory.createHttpMediaSource(uri)
player.prepare(mediaSource, true, true)
player.playWhenReady = true
}
}
fun playTtsFile(path: String) {
handler.post {
try {
val uri = Uri.fromFile(File(path))
val dataSpec = DataSpec(uri)
val fileDataSource = FileDataSource()
fileDataSource.open(dataSpec)
val factory = DataSource.Factory {
fileDataSource
}
val audioSource = ExtractorMediaSource(
fileDataSource.uri,
factory,
DefaultExtractorsFactory(),
null,
null
)
player.prepare(audioSource, true, false)
player.playWhenReady = true
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
var volGrowFlag = false
private fun volumePercent() =
if (type == TYPE_RING) 1f
else
EvsSpeaker.get(null).getCurrentVolume() / 100f
fun setVolume(volume: Float) {
if (Looper.myLooper() == Looper.getMainLooper()) {
player.volume = volume * volumePercent()
} else {
handler.post {
player.volume = volume * volumePercent()
}
}
}
fun getVolume() = volumePercent().let { percent ->
if (percent == 0f) {
0f
} else {
player.volume / volumePercent()
}
}
fun resume() {
if (Looper.myLooper() == Looper.getMainLooper()) {
if (player.playbackState == Player.STATE_READY) {
player.playWhenReady = true
} else if (player.playbackState == Player.STATE_ENDED) {
player.seekTo(0)
player.playWhenReady = true
} else if (player.playbackState == Player.STATE_IDLE) {
player.seekTo(player.contentPosition)
player.playWhenReady = true
}
} else {
handler.post {
if (player.playbackState == Player.STATE_READY) {
player.playWhenReady = true
} else if (player.playbackState == Player.STATE_ENDED) {
player.seekTo(0)
player.playWhenReady = true
} else if (player.playbackState == Player.STATE_IDLE) {
player.seekTo(player.contentPosition)
player.playWhenReady = true
}
}
}
}
fun pause() {
if (Looper.myLooper() == Looper.getMainLooper()) {
player.playWhenReady = false
} else {
handler.post {
player.playWhenReady = false
}
}
}
fun stop() {
if (Looper.myLooper() == Looper.getMainLooper()) {
player.playWhenReady = false
//player.stop(true)
} else {
handler.post {
player.playWhenReady = false
//player.stop(true)
}
}
}
fun seekTo(offset: Long) {
if (Looper.myLooper() == getLooper()) {
player.seekTo(offset)
} else {
handler.post {
player.seekTo(offset)
}
}
}
fun getOffset(): Long {
val position = player.currentPosition
return try {
position - player.currentTimeline.getPeriod(
player.currentPeriodIndex, period
).positionInWindowMs
} catch (e: Exception) {
position
}
}
fun getDuration(): Long {
val duration = player.duration
return if (duration != C.TIME_UNSET) duration else 0
}
fun getLooper(): Looper = player.applicationLooper
fun getPlaybackState() = player.playbackState
fun destroy() {
player.stop(true)
player.release()
if (type == TYPE_PLAYBACK || type == TYPE_TTS)
EvsSpeaker.get(null).removeOnVolumeChangedListener(onVolumeChangedListener)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.template
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.google.gson.Gson
import com.google.gson.JsonParser
import com.google.gson.annotations.SerializedName
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
class OptionTemplateView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val optionList = mutableListOf<OptionElement>()
private val adapter = ListAdapter()
private val recyclerView: RecyclerView
private val skillIconImage: ImageView
private val backgroundImage: ImageView
private val mainTitle: TextView
private val subTitle: TextView
private var currentPayload: String? = null
private val innerOnClickBackListener = OnClickListener { v ->
onClickBackListener?.onClick(v)
}
private var onClickBackListener: OnClickListener? = null
private var onElementSelectedListener: OnElementSelectedListener? = null
private var itemViewType = VIEW_TYPE_VERTICAL
companion object {
private const val VIEW_TYPE_VERTICAL = 0
private const val VIEW_TYPE_HORIZONTAL = 1
private const val VIEW_TYPE_NO_IMAGE = 2
}
init {
val childView = LayoutInflater.from(context)
.inflate(R.layout.layout_option_template_2, null)
skillIconImage = childView.findViewById(R.id.skill_icon)
backgroundImage = childView.findViewById(R.id.background_image)
mainTitle = childView.findViewById(R.id.main_title)
subTitle = childView.findViewById(R.id.sub_title)
recyclerView = childView.findViewById(R.id.recycler_view)
recyclerView.adapter = adapter
childView.findViewById<View>(R.id.back)?.setOnClickListener(innerOnClickBackListener)
addView(childView)
}
fun updatePayload(payload: String) {
val json = JsonParser().parse(payload).asJsonObject
mainTitle.text = json.get(Constant.PAYLOAD_MAIN_TITLE)?.asString
json.get(Constant.PAYLOAD_SUB_TITLE)?.asString?.let { subTitle ->
if (subTitle.isNotEmpty()) {
this.subTitle.visibility = View.VISIBLE
this.subTitle.text = subTitle
} else {
this.subTitle.visibility = View.GONE
}
} ?: run {
this.subTitle.visibility = View.GONE
}
when (json.get(Constant.PAYLOAD_TYPE)?.asString) {
Constant.TYPE_OPTION_TEMPLATE_1 -> {
itemViewType = VIEW_TYPE_NO_IMAGE
recyclerView.layoutManager = LinearLayoutManager(context)
}
Constant.TYPE_OPTION_TEMPLATE_2 -> {
itemViewType = VIEW_TYPE_VERTICAL
recyclerView.layoutManager = GridLayoutManager(context, 4)
}
Constant.TYPE_OPTION_TEMPLATE_3 -> {
itemViewType = VIEW_TYPE_HORIZONTAL
recyclerView.layoutManager = GridLayoutManager(context, 4)
}
}
json.get(Constant.PAYLOAD_BACK_BUTTON)?.asString?.let { backButton ->
when (backButton) {
Constant.BACK_BUTTON_HIDDEN -> {
findViewById<View>(R.id.back_icon).visibility = View.GONE
}
else -> {
findViewById<View>(R.id.back_icon).visibility = View.VISIBLE
}
}
} ?: run {
findViewById<View>(R.id.back_icon).visibility = View.VISIBLE
}
json.get(Constant.PAYLOAD_OPTION_ELEMENTS)?.asJsonArray?.let {
optionList.clear()
val arrayIterator = it.iterator()
val gson = Gson()
while (arrayIterator.hasNext()) {
val item = arrayIterator.next().asJsonObject
optionList.add(gson.fromJson(item, OptionElement::class.java))
}
adapter.notifyDataSetChanged()
} ?: run {
optionList.clear()
adapter.notifyDataSetChanged()
}
json.get(Constant.PAYLOAD_SKILL_ICON_URL)?.asString?.let { skillIconUrl ->
if (skillIconUrl.isNotEmpty()) {
skillIconImage.visibility = View.VISIBLE
Glide.with(skillIconImage)
.load(skillIconUrl)
.apply(
RequestOptions()
.transform(
RoundedCornersTransformation(
resources.getDimensionPixelSize(R.dimen.dp_8), 0
)
)
)
.transition(DrawableTransitionOptions.withCrossFade())
.into(skillIconImage)
} else {
skillIconImage.visibility = View.GONE
}
} ?: run {
skillIconImage.visibility = View.GONE
}
json.get(Constant.PAYLOAD_BACKGROUND_IMAGE_URL)?.asString?.let { backgroundImageUrl ->
if (backgroundImageUrl.isNotEmpty()) {
backgroundImage.visibility = View.VISIBLE
Glide.with(backgroundImage)
.load(backgroundImageUrl)
.transition(DrawableTransitionOptions.withCrossFade())
.into(backgroundImage)
} else {
backgroundImage.visibility = View.GONE
}
} ?: run {
backgroundImage.visibility = View.GONE
}
currentPayload = payload
}
fun setOnClickBackListener(onClickListener: OnClickListener?) {
this.onClickBackListener = onClickListener
}
private inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder =
ListItemViewHolder(
LayoutInflater.from(parent.context)
.inflate(
when (itemViewType) {
VIEW_TYPE_NO_IMAGE ->
R.layout.item_option_template_1
VIEW_TYPE_VERTICAL ->
R.layout.item_option_template_2
else ->
R.layout.item_option_template_3
},
parent, false
)
)
holder.itemView.setOnClickListener {
onElementSelectedListener?.onElementSelected(
this@OptionTemplateView, it, holder.adapterPosition,
optionList[holder.adapterPosition]
)
}
return holder
}
override fun getItemViewType(position: Int): Int {
return itemViewType
}
override fun getItemCount(): Int {
return optionList.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ListItemViewHolder) {
val item = optionList[position]
holder.tvPrimary.text = item.primaryText
holder.tvSecondary.text = item.secondaryText
holder.tvTertiary.text = item.tertiaryText
holder.tvTertiary.visibility =
if (item.tertiaryText.isNullOrEmpty()) View.GONE else View.VISIBLE
holder.secondaryContainer?.isVisible =
!(item.secondaryText.isNullOrEmpty() || item.tertiaryText.isNullOrEmpty())
holder.tvIndex?.text = (position + 1).toString()
holder.ivImage?.let { imageView ->
val placeholder = if (itemViewType == VIEW_TYPE_VERTICAL)
R.drawable.placeholder_option_2
else
R.drawable.placeholder_option_3
Glide.with(imageView)
.load(item.optionImageUrl ?: "")
.transition(DrawableTransitionOptions.withCrossFade())
.placeholder(placeholder)
.error(placeholder)
.into(imageView)
}
}
}
}
private class ListItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvPrimary: TextView = itemView.findViewById(R.id.primary_text)
val tvSecondary: TextView = itemView.findViewById(R.id.secondary_text)
val tvTertiary: TextView = itemView.findViewById(R.id.tertiary_text)
val tvIndex: TextView? = itemView.findViewById(R.id.tv_index)
val ivImage: ImageView? = itemView.findViewById(R.id.iv_image)
val secondaryContainer: View? = itemView.findViewById(R.id.secondary_container)
}
interface OnElementSelectedListener {
fun onElementSelected(
parent: OptionTemplateView,
itemView: View,
position: Int,
element: OptionElement
)
}
data class OptionElement(
@SerializedName(Constant.PAYLOAD_ELEMENT_ID) val elementId: String?,
@SerializedName(Constant.PAYLOAD_PRIMARY_TEXT) val primaryText: String?,
@SerializedName(Constant.PAYLOAD_SECONDARY_TEXT) val secondaryText: String?,
@SerializedName(Constant.PAYLOAD_TERTIARY_TEXT) val tertiaryText: String?,
@SerializedName(Constant.PAYLOAD_OPTION_IMAGE_URL) val optionImageUrl: String?
)
class Builder(private val context: Context) {
private var payload: String? = null
private var onClickListener: OnClickListener? = null
private var onElementSelectedListener: OnElementSelectedListener? = null
fun payload(payload: String): Builder {
this.payload = payload
return this
}
fun onClickBackListener(onClickListener: OnClickListener?): Builder {
this.onClickListener = onClickListener
return this
}
fun onElementSelectedListener(onElementSelectedListener: OnElementSelectedListener?): Builder {
this.onElementSelectedListener = onElementSelectedListener
return this
}
fun build(): OptionTemplateView {
val view = OptionTemplateView(context)
payload?.let { payload ->
view.updatePayload(payload)
}
onClickListener?.let {
view.setOnClickBackListener(it)
}
view.onElementSelectedListener = onElementSelectedListener
return view
}
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.utils
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import java.util.*
class WifiInfoManager private constructor() {
private val listeners = ArrayList<NetworkStateListener>()
private val rssiListeners = ArrayList<WifiRssiListener>()
private val uiHandler = Handler(Looper.getMainLooper())
private var receiver: BroadcastReceiver? = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
for (listener in rssiListeners) {
listener.onChange()
}
}
}
private var networkCallback: ConnectivityManager.NetworkCallback? = null
init {
if (Build.VERSION.SDK_INT >= 21)
networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
uiHandler.post {
for (listener in listeners) {
listener.onAvailable(network)
}
}
}
override fun onLost(network: Network) {
super.onLost(network)
uiHandler.post {
for (listener in listeners) {
listener.onLost(network)
}
}
}
}
}
fun getWifiInfo(context: Context): WifiInfo? {
val manager = context.applicationContext
.getSystemService(Context.WIFI_SERVICE) as? WifiManager
return manager?.connectionInfo
}
fun getWifiSignalLevel(context: Context): Int {
val wifiInfo = getWifiInfo(context)
return if (wifiInfo != null) {
WifiManager.calculateSignalLevel(wifiInfo.rssi, 5)
} else {
0
}
}
fun isNetworkAvailable(context: Context): Boolean {
val manager = context.applicationContext
.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
return if (manager != null) {
val networkInfo = manager.activeNetworkInfo
networkInfo != null && networkInfo.isAvailable
} else {
false
}
}
fun registerNetworkCallback(context: Context, networkStateListener: NetworkStateListener) {
listeners.add(networkStateListener)
val manager = context.applicationContext
.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
if (manager != null && Build.VERSION.SDK_INT >= 21) {
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build()
manager.registerNetworkCallback(request, networkCallback)
}
}
fun unregisterNetworkCallback(context: Context) {
val manager = context.applicationContext
.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
if (manager != null && Build.VERSION.SDK_INT >= 21) {
manager.unregisterNetworkCallback(networkCallback)
}
}
fun registerWifiRssiCallback(context: Context, listener: WifiRssiListener) {
rssiListeners.add(listener)
context.registerReceiver(receiver, IntentFilter(WifiManager.RSSI_CHANGED_ACTION))
}
fun unregisterWifiRssiCallback(context: Context) {
if (receiver != null) {
context.unregisterReceiver(receiver)
}
receiver = null
}
interface NetworkStateListener {
fun onAvailable(network: Network)
fun onLost(network: Network)
}
interface WifiRssiListener {
fun onChange()
}
companion object {
val manager = WifiInfoManager()
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.view.View
import android.view.ViewGroup
interface OnItemClickListener {
fun onItemClick(parent: ViewGroup, itemView: View, position: Int)
}
interface OnMultiTypeItemClickListener {
fun onItemClick(parent: ViewGroup, itemView: View, position: Int, subPosition: Int)
}<file_sep>//
// Created by huang on 2019/1/24.
//
#ifndef IVWENGINEDEMO_FILEUTIL_H
#define IVWENGINEDEMO_FILEUTIL_H
#include <string>
using namespace std;
namespace iflytek {
class FileUtil {
public:
static bool isPathExist(const string& path, bool& isFile);
static long getFileSizeInBytes(const string& path);
static long readFileToBuffer(const string& path, char* buffer, long bufferSize);
};
}
#endif //IVWENGINEDEMO_FILEUTIL_H
<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.MediaApi
import com.iflytek.cyber.iot.show.core.model.Group
import com.iflytek.cyber.iot.show.core.utils.dp2Px
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
class MediaFragment : BaseFragment(), PageScrollable {
private lateinit var tabLayout: TabLayout
private lateinit var viewPager: ViewPager
private var placeholderView: View? = null
private var adapter: MediaPagerAdapter? = null
private var backCount = 0
private var isSearchButtonClicked = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return LayoutInflater.from(context).inflate(R.layout.fragment_media, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back_container).setOnClickListener {
}
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
view.findViewById<ImageView>(R.id.iv_search).setOnClickListener {
if (!isSearchButtonClicked) {
isSearchButtonClicked = true
start(SearchFragment())
}
}
tabLayout = view.findViewById(R.id.tab_layout)
viewPager = view.findViewById(R.id.view_pager)
placeholderView = view.findViewById(R.id.placeholder)
getMediaSections()
view.findViewById<View>(R.id.refresh)?.setOnClickListener {
showPlaceholder()
getMediaSections()
}
try {
val field = viewPager.javaClass.getDeclaredField("mTouchSlop")
field.isAccessible = true
field.setInt(viewPager, 18.dp2Px()) // set ViewPager touch slop bigger than default value
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onSupportVisible() {
super.onSupportVisible()
isSearchButtonClicked = false
}
private fun showPlaceholder() {
placeholderView?.let { placeholder ->
placeholder.isVisible = true
placeholder.animate().alpha(1f).setDuration(350)
.start()
}
}
private fun hidePlaceholder() {
placeholderView?.let { placeholder ->
placeholder.animate().alpha(0f).setDuration(350)
.withEndAction {
placeholder.isVisible = false
}
.start()
}
}
private fun setupTab(groups: List<Pair<String?, List<Group>>>) {
adapter = MediaPagerAdapter(childFragmentManager)
groups.forEach { item ->
if (TextUtils.equals(item.first, "音乐")) {
adapter?.addItems(item.first, MusicFragment(), item.second)
} else {
adapter?.addItems(item.first, MediaSectionFragment(), item.second)
}
}
viewPager.offscreenPageLimit = 5
viewPager.adapter = adapter
tabLayout.setupWithViewPager(viewPager)
}
private fun getMediaSections() {
getMediaApi()?.getMediaSections()?.enqueue(object : Callback<ArrayList<Group>> {
override fun onFailure(call: Call<ArrayList<Group>>, t: Throwable) {
t.printStackTrace()
if (isDetached || isRemoving)
return
context ?: return
hidePlaceholder()
if (t is UnknownHostException) {
view?.findViewById<View>(R.id.error_container)?.let { errorContainer ->
errorContainer.isVisible = true
val errorText = errorContainer.findViewById<TextView>(R.id.error_text)
errorText?.text = "网络出了点小差,请检查网络后重试"
}
} else {
view?.findViewById<View>(R.id.error_container)?.let { errorContainer ->
errorContainer.isVisible = true
val errorText = errorContainer.findViewById<TextView>(R.id.error_text)
errorText?.text = "加载失败,请重试"
}
}
}
override fun onResponse(
call: Call<ArrayList<Group>>,
response: Response<ArrayList<Group>>
) {
if (isDetached || isRemoving)
return
context ?: return
hidePlaceholder()
if (response.isSuccessful) {
val groups = response.body()
val groupMap = groups?.groupBy { it.abbr }
groupMap?.let { setupTab(it.toList()) }
view?.findViewById<View>(R.id.error_container)?.isVisible = false
} else {
view?.findViewById<View>(R.id.error_container)?.let { errorContainer ->
errorContainer.isVisible = true
val errorText = errorContainer.findViewById<TextView>(R.id.error_text)
errorText?.text = "加载失败,请重试"
}
}
}
})
}
private fun getMediaApi(): MediaApi? {
return if (launcher != null) {
CoreApplication.from(launcher!!).createApi(MediaApi::class.java)
} else {
null
}
}
override fun scrollToNext(): Boolean {
val currentItem = viewPager.currentItem
if (currentItem < (adapter?.count ?: 0) - 1 || currentItem < 0) {
viewPager.post {
viewPager.setCurrentItem(currentItem + 1, true)
}
return true
}
return false
}
override fun scrollToPrevious(): Boolean {
val currentItem = viewPager.currentItem
if (currentItem > 0) {
viewPager.post {
viewPager.setCurrentItem(currentItem - 1, true)
}
return true
}
return false
}
inner class MediaPagerAdapter(fragmentManager: FragmentManager) :
FragmentPagerAdapter(fragmentManager) {
private var titles = ArrayList<String?>()
private var fragments = ArrayList<Fragment>()
private var groups = ArrayList<List<Group>>()
fun addItems(title: String?, fragment: Fragment, group: List<Group>) {
titles.add(title)
fragments.add(fragment)
groups.add(group)
}
override fun getCount(): Int {
return fragments.size
}
override fun getItem(position: Int): Fragment {
val fragment = fragments[position]
val title = titles[position]
val group = groups[position]
if (TextUtils.equals(title, "音乐")) {
fragment.arguments = bundleOf(Pair("id", group[0].id))
} else {
fragment.arguments = bundleOf(
Pair("name", title),
Pair("groups", group)
)
}
return fragment
}
override fun getPageTitle(position: Int): CharSequence? {
return titles[position]
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.ContentStorage
import com.iflytek.cyber.iot.show.core.model.Song
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
class VideoListAdapter(
val videoList: ArrayList<Song>,
private val onItemClickListener: (song: Song) -> Unit
) : RecyclerView.Adapter<VideoListAdapter.VideoListHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoListHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_video, parent, false)
return VideoListHolder(view)
}
override fun getItemCount(): Int {
return videoList.size
}
override fun onBindViewHolder(holder: VideoListHolder, position: Int) {
val song = videoList[position]
holder.desc.text = song.metadata.title
if (song.metadata.art != null && song.metadata.art?.sources?.isNullOrEmpty() == false) {
holder.cover.isVisible = true
holder.onlyDesc.isVisible = false
val resource = holder.itemView.resources
Glide.with(holder.cover)
.load(song.metadata.art?.sources?.get(0)?.url)
.apply(
RequestOptions()
.centerCrop()
.transform(
RoundedCornersTransformation(
resource.getDimensionPixelSize(R.dimen.dp_4), 0
)
)
)
.into(holder.cover)
} else {
holder.desc.isVisible = false
holder.cover.isVisible = false
holder.onlyDesc.isVisible = true
holder.onlyDesc.text = song.metadata.title
}
val video = ContentStorage.get().video
if (TextUtils.equals(video?.resourceId, song.stream.token)) {
holder.desc.setTextColor(
ContextCompat.getColor(
holder.desc.context,
R.color.setup_primary
)
)
} else {
holder.desc.setTextColor(
ContextCompat.getColor(
holder.desc.context,
R.color.semi_black
)
)
}
holder.itemView.setOnClickListener {
onItemClickListener.invoke(song)
}
}
class VideoListHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val cover = itemView.findViewById<ImageView>(R.id.iv_video_cover)
val desc = itemView.findViewById<TextView>(R.id.tv_video_desc)
val onlyDesc = itemView.findViewById<TextView>(R.id.tv_only_desc)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.isVisible
import com.google.gson.JsonParser
import com.iflytek.cyber.evs.sdk.agent.Recognizer
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.DeviceApi
import com.iflytek.cyber.iot.show.core.model.ChatConfigData
import com.iflytek.cyber.iot.show.core.utils.ConfigUtils
import com.iflytek.cyber.iot.show.core.widget.StyledSwitch
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
import kotlin.math.max
import kotlin.math.min
class MicrophoneFragment : BaseFragment(), PageScrollable {
companion object {
private const val REQUEST_PROFILE_CODE = 10101
}
private var microphoneSwitch: StyledSwitch? = null
private var voiceButtonSwitch: StyledSwitch? = null
private var voiceButtonCover: View? = null
private var dialectView: View? = null
private var speakerView: View? = null
private var languageAndSpeakerView: View? = null
private var languageAndSpeakerValueView: TextView? = null
private var tvSpeakerName: TextView? = null
private var continousView: View? = null
private var continousSwitch: StyledSwitch? = null
private var backgroundRecognizeCover: View? = null
private var backgroundRecognizeSwitch: StyledSwitch? = null
private var responseSoundSwitch: StyledSwitch? = null
private var wakeUpSoundSwitch: StyledSwitch? = null
private var tvRecognizerProfile: TextView? = null
private var scrollView: ScrollView? = null
private var contentContainer: LinearLayout? = null
private var continousMode = false
private var chatConfigData: ChatConfigData? = null
private var backCount = 0
private val configChangedListener = object : ConfigUtils.OnConfigChangedListener {
override fun onConfigChanged(key: String, value: Any?) {
when (key) {
ConfigUtils.KEY_RECOGNIZER_PROFILE -> {
val isCloseTalk = value == Recognizer.Profile.CloseTalk.toString()
if (isCloseTalk)
tvRecognizerProfile?.text = getString(R.string.message_near_field)
else
tvRecognizerProfile?.text = getString(R.string.message_far_field)
}
ConfigUtils.KEY_VOICE_WAKEUP_ENABLED -> {
val microphoneEnabled = value == true
if (microphoneSwitch?.isChecked != microphoneEnabled)
microphoneSwitch?.isChecked = microphoneEnabled
voiceButtonCover?.isVisible = !microphoneEnabled
}
ConfigUtils.KEY_VOICE_BUTTON_ENABLED -> {
val voiceButtonEnabled = value == true
if (voiceButtonSwitch?.isChecked != voiceButtonEnabled)
voiceButtonSwitch?.isChecked = voiceButtonEnabled
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ConfigUtils.registerOnConfigChangedListener(configChangedListener)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_microphone, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
microphoneSwitch = view.findViewById(R.id.microphone_switch)
voiceButtonSwitch = view.findViewById(R.id.voice_button_switch)
voiceButtonCover = view.findViewById(R.id.voice_button_cover)
scrollView = view.findViewById(R.id.scroll_view)
contentContainer = view.findViewById(R.id.content_container)
continousView = view.findViewById(R.id.continous_mode)
continousSwitch = view.findViewById(R.id.continous_switch)
// speakerView = view.findViewById(R.id.speaker)
languageAndSpeakerView = view.findViewById(R.id.language_and_speaker)
languageAndSpeakerValueView = view.findViewById(R.id.language_and_speaker_value)
backgroundRecognizeCover = view.findViewById(R.id.background_recognize_cover)
backgroundRecognizeSwitch = view.findViewById(R.id.background_recognize_switch)
responseSoundSwitch = view.findViewById(R.id.response_sound_switch)
wakeUpSoundSwitch = view.findViewById(R.id.wake_up_sound_switch)
tvRecognizerProfile = view.findViewById(R.id.recognize_profile_value)
view.findViewById<View>(R.id.back).setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
view.findViewById<View>(R.id.recognize_profile).setOnClickListener {
val titles =
arrayOf(
getString(R.string.title_close_talk),
getString(R.string.title_far_field)
)
val messages =
arrayOf(
getString(R.string.summary_close_talk),
getString(R.string.summary_far_field)
)
val profile = ConfigUtils.getString(
ConfigUtils.KEY_RECOGNIZER_PROFILE,
Recognizer.Profile.FarField.toString()
)
val selected = if (profile == Recognizer.Profile.FarField.toString()) {
1
} else {
0
}
val fragment =
SingleChoiceFragment.newInstance(
getString(R.string.recognize_profile),
getString(R.string.message_recognize_profile),
titles,
messages,
selected,
true
)
startForResult(fragment, REQUEST_PROFILE_CODE)
}
view.findViewById<View>(R.id.background_recognize_clickable).setOnClickListener {
backgroundRecognizeSwitch?.isChecked = backgroundRecognizeSwitch?.isChecked != true
}
view.findViewById<View>(R.id.language_and_speaker).setOnClickListener {
start(LanguageAndSpeakerFragment.newInstance(chatConfigData))
}
view.findViewById<View>(R.id.microphone).setOnClickListener {
microphoneSwitch?.isChecked = microphoneSwitch?.isChecked != true
}
view.findViewById<View>(R.id.voice_button).setOnClickListener {
voiceButtonSwitch?.isChecked = voiceButtonSwitch?.isChecked != true
}
view.findViewById<View>(R.id.response_sound_clickable).setOnClickListener {
responseSoundSwitch?.isChecked = responseSoundSwitch?.isChecked != true
}
view.findViewById<View>(R.id.wake_up_sound_clickable).setOnClickListener {
wakeUpSoundSwitch?.isChecked = wakeUpSoundSwitch?.isChecked != true
}
responseSoundSwitch?.setOnCheckedChangeListener(object :
StyledSwitch.OnCheckedChangeListener {
override fun onCheckedChange(switch: StyledSwitch, isChecked: Boolean) {
val responseSoundEnabled =
ConfigUtils.getBoolean(ConfigUtils.KEY_RESPONSE_SOUND, true)
if (isChecked) {
if (!responseSoundEnabled) {
ConfigUtils.putBoolean(ConfigUtils.KEY_RESPONSE_SOUND, true)
}
} else {
if (responseSoundEnabled) {
ConfigUtils.putBoolean(ConfigUtils.KEY_RESPONSE_SOUND, false)
}
}
}
})
wakeUpSoundSwitch?.setOnCheckedChangeListener(object :
StyledSwitch.OnCheckedChangeListener {
override fun onCheckedChange(switch: StyledSwitch, isChecked: Boolean) {
val responseSoundEnabled =
ConfigUtils.getBoolean(ConfigUtils.KEY_WAKE_UP_SOUND, true)
if (isChecked) {
if (!responseSoundEnabled) {
ConfigUtils.putBoolean(ConfigUtils.KEY_WAKE_UP_SOUND, true)
}
} else {
if (responseSoundEnabled) {
ConfigUtils.putBoolean(ConfigUtils.KEY_WAKE_UP_SOUND, false)
}
}
}
})
responseSoundSwitch?.isChecked =
ConfigUtils.getBoolean(ConfigUtils.KEY_RESPONSE_SOUND, true)
wakeUpSoundSwitch?.isChecked =
ConfigUtils.getBoolean(ConfigUtils.KEY_WAKE_UP_SOUND, true)
microphoneSwitch?.setOnCheckedChangeListener(object : StyledSwitch.OnCheckedChangeListener {
override fun onCheckedChange(switch: StyledSwitch, isChecked: Boolean) {
val microphoneEnabled =
ConfigUtils.getBoolean(ConfigUtils.KEY_VOICE_WAKEUP_ENABLED, true)
if (isChecked) {
if (!microphoneEnabled) {
ConfigUtils.putBoolean(ConfigUtils.KEY_VOICE_WAKEUP_ENABLED, true)
}
} else {
if (microphoneEnabled) {
ConfigUtils.putBoolean(ConfigUtils.KEY_VOICE_WAKEUP_ENABLED, false)
}
}
}
})
voiceButtonSwitch?.setOnCheckedChangeListener(object :
StyledSwitch.OnCheckedChangeListener {
override fun onCheckedChange(switch: StyledSwitch, isChecked: Boolean) {
val voiceButtonEnabled =
ConfigUtils.getBoolean(ConfigUtils.KEY_VOICE_BUTTON_ENABLED, true)
if (isChecked) {
if (!voiceButtonEnabled) {
ConfigUtils.putBoolean(ConfigUtils.KEY_VOICE_BUTTON_ENABLED, true)
}
} else {
if (voiceButtonEnabled) {
ConfigUtils.putBoolean(ConfigUtils.KEY_VOICE_BUTTON_ENABLED, false)
}
}
}
})
view.findViewById<View>(R.id.continous_mode_clickable)?.setOnClickListener {
continousSwitch?.isChecked = continousSwitch?.isChecked != true
}
continousSwitch?.setOnCheckedChangeListener(object : StyledSwitch.OnCheckedChangeListener {
override fun onCheckedChange(switch: StyledSwitch, isChecked: Boolean) {
backgroundRecognizeCover?.isVisible = !isChecked
if (isChecked == continousMode)
return
if (isChecked) {
val requestBody =
RequestBody.create(
MediaType.parse("application/json"), """
{"continous_mode": true}
""".trimIndent()
)
getDeviceApi()?.put(requestBody)?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
continousSwitch?.isChecked = false
if (t is UnknownHostException) {
toastError(R.string.network_error)
}
}
override fun onResponse(
call: Call<ResponseBody>,
response: Response<ResponseBody>
) {
if (!response.isSuccessful) {
continousSwitch?.isChecked = false
toastError(R.string.request_params_error)
} else {
continousMode = true
}
}
})
} else {
val requestBody =
RequestBody.create(
MediaType.parse("application/json"), """
{"continous_mode": false}
""".trimIndent()
)
getDeviceApi()?.put(requestBody)?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
continousSwitch?.isChecked = true
if (t is UnknownHostException) {
toastError(R.string.network_error)
}
}
override fun onResponse(
call: Call<ResponseBody>,
response: Response<ResponseBody>
) {
if (!response.isSuccessful) {
continousSwitch?.isChecked = true
toastError(R.string.request_params_error)
} else {
continousMode = false
}
}
})
}
}
})
backgroundRecognizeSwitch?.setOnCheckedChangeListener(object :
StyledSwitch.OnCheckedChangeListener {
override fun onCheckedChange(switch: StyledSwitch, isChecked: Boolean) {
val backgroundRecognizeEnabled =
ConfigUtils.getBoolean(ConfigUtils.KEY_BACKGROUND_RECOGNIZE, false)
if (isChecked == backgroundRecognizeEnabled) {
return
}
ConfigUtils.putBoolean(ConfigUtils.KEY_BACKGROUND_RECOGNIZE, isChecked)
}
})
// init ui value
val profile = ConfigUtils.getString(
ConfigUtils.KEY_RECOGNIZER_PROFILE,
Recognizer.Profile.FarField.toString()
)
val isCloseTalk = profile == Recognizer.Profile.CloseTalk.toString()
if (isCloseTalk)
tvRecognizerProfile?.text = getString(R.string.message_near_field)
else
tvRecognizerProfile?.text = getString(R.string.message_far_field)
val backgroundRecognizeEnabled =
ConfigUtils.getBoolean(ConfigUtils.KEY_BACKGROUND_RECOGNIZE, false)
backgroundRecognizeSwitch?.isChecked = backgroundRecognizeEnabled
val microphoneEnabled = ConfigUtils.getBoolean(ConfigUtils.KEY_VOICE_WAKEUP_ENABLED, true)
microphoneSwitch?.isChecked = microphoneEnabled
val voiceButtonEnabled = ConfigUtils.getBoolean(ConfigUtils.KEY_VOICE_BUTTON_ENABLED, true)
voiceButtonSwitch?.isChecked = voiceButtonEnabled
voiceButtonCover?.isVisible = !microphoneEnabled
}
private fun toastError(stringResId: Int) {
if (isSupportVisible) {
Toast.makeText(context, stringResId, Toast.LENGTH_SHORT).show()
}
}
override fun onSupportVisible() {
super.onSupportVisible()
getDeviceApi()?.let { api ->
api.get().enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
t.printStackTrace()
}
override fun onResponse(
call: Call<ResponseBody>,
response: Response<ResponseBody>
) {
if (response.isSuccessful) {
val responseBody = response.body()
val body = responseBody?.string()
val json = JsonParser().parse(body).asJsonObject
if (json.has("continous_mode")) {
continousMode = json.get("continous_mode").asBoolean
if (continousView?.isVisible != true) {
continousView?.isVisible = true
continousSwitch?.setChecked(continousMode, false)
} else {
continousSwitch?.isChecked = continousMode
}
backgroundRecognizeCover?.isVisible = continousSwitch?.isChecked != true
} else {
continousView?.isVisible = false
}
responseBody?.close()
}
}
})
api.getChatConfig().enqueue(object : Callback<ChatConfigData> {
override fun onFailure(call: Call<ChatConfigData>, t: Throwable) {
t.printStackTrace()
}
override fun onResponse(
call: Call<ChatConfigData>,
response: Response<ChatConfigData>
) {
if (response.isSuccessful) {
val configData = response.body()
languageAndSpeakerView?.isVisible = true
var languageName: String? = null
var propertyName: String? = null
var vcnName: String? = null
val currentConfig = configData?.config
if (configData?.interactionModes?.isNotEmpty() == true) {
for (mode in configData.interactionModes) {
if (mode.interactionModeId == currentConfig?.interactionModeId) {
languageName = mode.name
if (mode.speakers?.isNotEmpty() == true) {
for (speaker in mode.speakers) {
if (speaker.vcn == currentConfig?.vcn) {
vcnName = speaker.voiceName
}
}
}
}
}
}
if (configData?.property?.isNotEmpty() == true) {
for (property in configData.property) {
if (property.propertyId == currentConfig?.propertyId) {
propertyName = property.name
}
}
}
val value = StringBuilder()
if (!languageName.isNullOrEmpty()) {
value.append(languageName)
}
if (!propertyName.isNullOrEmpty()) {
value.append(", ")
value.append(propertyName)
}
if (!vcnName.isNullOrEmpty()) {
value.append(", ")
value.append(vcnName)
}
languageAndSpeakerValueView?.text = value
chatConfigData = configData
} else {
chatConfigData = null
languageAndSpeakerView?.isVisible = false
}
}
})
}
}
override fun onDestroy() {
super.onDestroy()
ConfigUtils.unregisterOnConfigChangedListener(configChangedListener)
}
override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle) {
super.onFragmentResult(requestCode, resultCode, data)
if (requestCode == REQUEST_PROFILE_CODE) {
if (resultCode == 0) {
val selectedItem = data.getInt("selected_item")
if (selectedItem == 0) {
ConfigUtils.putString(
ConfigUtils.KEY_RECOGNIZER_PROFILE,
Recognizer.Profile.CloseTalk.toString()
)
} else {
ConfigUtils.putString(
ConfigUtils.KEY_RECOGNIZER_PROFILE,
Recognizer.Profile.FarField.toString()
)
}
}
}
}
override fun scrollToNext(): Boolean {
scrollView?.let { scrollView ->
val pageHeight = scrollView.height
val scrollY = scrollView.scrollY
val contentHeight = contentContainer?.height ?: 0
if (scrollY == contentHeight - pageHeight) {
return false
}
val target = min(contentHeight - pageHeight, scrollY + pageHeight)
smoothScrollTo(target)
return true
} ?: run {
return false
}
}
override fun scrollToPrevious(): Boolean {
scrollView?.let { scrollView ->
val pageHeight = scrollView.height
val scrollY = scrollView.scrollY
if (scrollY == 0) {
return false
}
val target = max(0, scrollY - pageHeight)
smoothScrollTo(target)
return true
} ?: run {
return false
}
}
private fun smoothScrollTo(scrollY: Int) {
scrollView?.isSmoothScrollingEnabled = true
scrollView?.smoothScrollTo(0, scrollY)
}
private fun getDeviceApi(): DeviceApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(DeviceApi::class.java)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.model
import com.google.gson.annotations.SerializedName
data class PlayerInfoPayload(@SerializedName("resource_id") var resourceId: String?,
@SerializedName("should_popup") var shouldPopup: Boolean,
@SerializedName("main_title") var mainTitle: String?,
@SerializedName("sub_title") var subTitle: String?,
var lyric: Lyric,
var content: Content?,
var provider: Provider?,
var recommend: Recommend?)
data class Lyric(var url: String?,
var format: String?)
data class Recommend(@SerializedName("url") var url: String?)<file_sep>package com.iflytek.cyber.iot.show.core.template
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.google.gson.JsonParser
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
class ListTemplateView1 @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val listItems = mutableListOf<ListItem>()
private val adapter = ListAdapter()
private val recyclerView: RecyclerView
private val skillIconImage: ImageView
private val backgroundImage: ImageView
private val mainTitle: TextView
private val subTitle: TextView
private var currentPayload: String? = null
private val innerOnClickBackListener = OnClickListener { v ->
onClickBackListener?.onClick(v)
}
private var onClickBackListener: OnClickListener? = null
init {
val childView = LayoutInflater.from(context)
.inflate(R.layout.layout_list_template_1, null)
skillIconImage = childView.findViewById(R.id.skill_icon)
backgroundImage = childView.findViewById(R.id.background_image)
mainTitle = childView.findViewById(R.id.main_title)
subTitle = childView.findViewById(R.id.sub_title)
recyclerView = childView.findViewById(R.id.recycler_view)
recyclerView.adapter = adapter
childView.findViewById<View>(R.id.back)?.setOnClickListener(innerOnClickBackListener)
addView(childView)
}
fun updatePayload(payload: String) {
val json = JsonParser().parse(payload).asJsonObject
mainTitle.text = json.get(Constant.PAYLOAD_MAIN_TITLE)?.asString
json.get(Constant.PAYLOAD_SUB_TITLE)?.asString?.let { subTitle ->
if (subTitle.isNotEmpty()) {
this.subTitle.visibility = View.VISIBLE
this.subTitle.text = subTitle
} else {
this.subTitle.visibility = View.GONE
}
} ?: run {
this.subTitle.visibility = View.GONE
}
json.get(Constant.PAYLOAD_BACK_BUTTON)?.asString?.let { backButton ->
when (backButton) {
Constant.BACK_BUTTON_HIDDEN -> {
findViewById<View>(R.id.back_icon).visibility = View.GONE
}
else -> {
findViewById<View>(R.id.back_icon).visibility = View.VISIBLE
}
}
} ?: run {
findViewById<View>(R.id.back_icon).visibility = View.VISIBLE
}
json.get(Constant.PAYLOAD_LIST_ITEMS)?.asJsonArray?.let {
listItems.clear()
val arrayIterator = it.iterator()
while (arrayIterator.hasNext()) {
val item = arrayIterator.next().asJsonObject
listItems.add(ListItem(
item.get(Constant.PAYLOAD_LEFT_TEXT).asString,
item.get(Constant.PAYLOAD_RIGHT_TEXT).asString))
}
adapter.notifyDataSetChanged()
} ?: run {
listItems.clear()
adapter.notifyDataSetChanged()
}
json.get(Constant.PAYLOAD_SKILL_ICON_URL)?.asString?.let { skillIconUrl ->
if (skillIconUrl.isNotEmpty()) {
skillIconImage.visibility = View.VISIBLE
Glide.with(skillIconImage)
.load(skillIconUrl)
.apply(RequestOptions()
.transform(RoundedCornersTransformation(
resources.getDimensionPixelSize(R.dimen.dp_8), 0)))
.transition(DrawableTransitionOptions.withCrossFade())
.into(skillIconImage)
} else {
skillIconImage.visibility = View.GONE
}
} ?: run {
skillIconImage.visibility = View.GONE
}
json.get(Constant.PAYLOAD_BACKGROUND_IMAGE_URL)?.asString?.let { backgroundImageUrl ->
if (backgroundImageUrl.isNotEmpty()) {
backgroundImage.visibility = View.VISIBLE
Glide.with(backgroundImage)
.load(backgroundImageUrl)
.transition(DrawableTransitionOptions.withCrossFade())
.into(backgroundImage)
} else {
backgroundImage.visibility = View.GONE
}
} ?: run {
backgroundImage.visibility = View.GONE
}
currentPayload = payload
}
fun setOnClickBackListener(onClickListener: OnClickListener?) {
this.onClickBackListener = onClickListener
}
private inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return ListItemViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.item_list_template_new, parent, false))
}
override fun getItemCount(): Int {
return listItems.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ListItemViewHolder) {
holder.tvLeft.text = listItems[position].leftText
holder.tvRight.text = listItems[position].rightText
}
}
}
private data class ListItem(val leftText: String?, val rightText: String?)
private class ListItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvLeft: TextView = itemView.findViewById(R.id.left_text)
val tvRight: TextView = itemView.findViewById(R.id.right_text)
}
class Builder(private val context: Context) {
private var payload: String? = null
private var onClickListener: OnClickListener? = null
fun payload(payload: String): Builder {
this.payload = payload
return this
}
fun onClickBackListener(onClickListener: OnClickListener?): Builder {
this.onClickListener = onClickListener
return this
}
fun build(): ListTemplateView1 {
val view = ListTemplateView1(context)
payload?.let { payload ->
view.updatePayload(payload)
}
onClickListener?.let {
view.setOnClickBackListener(it)
}
return view
}
}
}<file_sep>cmake_minimum_required(VERSION 3.4.1)
project(speex)
include_directories(include/)
aux_source_directory(src SPEEX_SRC_FILES)
set(SPEEX_SRC_FILES ${SPEEX_SRC_FILES} SpeexCodec.cpp)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O2")
add_definitions(-DFLOATING_POINT -DUSE_KISS_FFT -DEXPORT= -UHAVE_CONFIG_H)
link_libraries(-llog)
add_library(speex SHARED ${SPEEX_SRC_FILES})
<file_sep>package com.iflytek.cyber.iot.show.core.utils;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.Rect;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
public class ScreenUtils {
private ScreenUtils() {
}
public static int getWidth(Context context) {
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Point size = new Point();
Display display = manager.getDefaultDisplay();
display.getRealSize(size);
return size.x;
}
public static int getRealHeight(Context context) {
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Point size = new Point();
Display display = manager.getDefaultDisplay();
display.getRealSize(size);
return size.y;
}
public static int getHeight(Context context) {
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.y;
}
public static int getStatusBarHeight(Activity activity) {
Rect rectangle = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
return rectangle.top;
}
public static int dpToPx(int dp) {
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
public static int dpToPx(float dp) {
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
public static int pxToDp(float px) {
float scale = Resources.getSystem().getDisplayMetrics().density;
return (int) (px / scale + 0.5);
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.message
import android.content.Context
import com.iflytek.cyber.evs.sdk.agent.Recognizer
import com.iflytek.cyber.iot.show.core.record.GlobalRecorder
import java.io.*
object MessageRecorder : GlobalRecorder.Observer {
override fun onWakeUp(angle: Int, beam: Int, params: String?) {
// ignore
}
private var isRecording = false
private var byteArrayOutputStream: BufferedOutputStream? = null
private var pcmFile: File? = null
private var wavFile: File? = null
override fun onAudioData(array: ByteArray, offset: Int, length: Int) {
if (!isRecording)
return
byteArrayOutputStream?.write(array, offset, length)
}
fun init(context: Context) {
val directory = context.externalCacheDir
pcmFile = File("$directory/${System.currentTimeMillis()}.pcm")
wavFile = File("$directory/${System.currentTimeMillis()}.wav")
if (pcmFile?.exists() == true) {
pcmFile?.delete()
}
if (wavFile?.exists() == true) {
wavFile?.delete()
}
try {
pcmFile?.createNewFile()
wavFile?.createNewFile()
} catch (e: IOException) {
e.printStackTrace()
}
}
private fun createOutputStream() {
byteArrayOutputStream = BufferedOutputStream(FileOutputStream(pcmFile))
}
private fun createRecordFile(context: Context, onCreated: (recordFile: File) -> Unit) {
val file = File("${context.externalCacheDir}/${System.currentTimeMillis()}.wav")
if (file.exists())
file.delete()
file.createNewFile()
val fileOutputStream = FileOutputStream(file)
onCreated.invoke(file)
}
fun startRecording() {
isRecording = true
Thread {
createOutputStream()
}.start()
}
fun stopRecording(context: Context, onCreated: (recordFile: File) -> Unit) {
isRecording = false
Thread {
convertWavFile(onCreated)
}.start()
}
// 这里得到可播放的音频文件
private fun convertWavFile(onCreated: (recordFile: File) -> Unit) {
val inputStream: FileInputStream?
val out: FileOutputStream?
val totalAudioLen: Long
val totalDataLen: Long
val longSampleRate: Long = Recognizer.getSampleRateInHz().toLong()
val channels = 1
val byteRate = 16 * longSampleRate * channels / 8
val data = ByteArray(1024)
try {
val pcmFile = pcmFile ?: return
val wavFile = wavFile ?: return
inputStream = FileInputStream(pcmFile)
out = FileOutputStream(wavFile)
totalAudioLen = inputStream.channel.size()
//由于不包括RIFF和WAV
totalDataLen = totalAudioLen + 36
writeWaveFileHeader(out, totalAudioLen, totalDataLen,
longSampleRate, channels, byteRate)
var size = inputStream.read(data)
while (size != -1) {
out.write(data)
size = inputStream.read(data)
}
inputStream.close()
out.close()
onCreated.invoke(wavFile)
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
/* 任何一种文件在头部添加相应的头文件才能够确定的表示这种文件的格式,wave是RIFF文件结构,每一部分为一个chunk,其中有RIFF WAVE chunk, FMT Chunk,Fact chunk,Data chunk,其中Fact chunk是可以选择的, */
@Throws(IOException::class)
private fun writeWaveFileHeader(out: FileOutputStream, totalAudioLen: Long, totalDataLen: Long, longSampleRate: Long,
channels: Int, byteRate: Long) {
val header = ByteArray(44)
header[0] = 'R'.toByte() // RIFF
header[1] = 'I'.toByte()
header[2] = 'F'.toByte()
header[3] = 'F'.toByte()
header[4] = (totalDataLen and 0xff).toByte()//数据大小
header[5] = (totalDataLen shr 8 and 0xff).toByte()
header[6] = (totalDataLen shr 16 and 0xff).toByte()
header[7] = (totalDataLen shr 24 and 0xff).toByte()
header[8] = 'W'.toByte()//WAVE
header[9] = 'A'.toByte()
header[10] = 'V'.toByte()
header[11] = 'E'.toByte()
//FMT Chunk
header[12] = 'f'.toByte() // 'fmt '
header[13] = 'm'.toByte()
header[14] = 't'.toByte()
header[15] = ' '.toByte()//过渡字节
//数据大小
header[16] = 16 // 4 bytes: size of 'fmt ' chunk
header[17] = 0
header[18] = 0
header[19] = 0
//编码方式 10H为PCM编码格式
header[20] = 1 // format = 1
header[21] = 0
//通道数
header[22] = channels.toByte()
header[23] = 0
//采样率,每个通道的播放速度
header[24] = (longSampleRate and 0xff).toByte()
header[25] = (longSampleRate shr 8 and 0xff).toByte()
header[26] = (longSampleRate shr 16 and 0xff).toByte()
header[27] = (longSampleRate shr 24 and 0xff).toByte()
//音频数据传送速率,采样率*通道数*采样深度/8
header[28] = (byteRate and 0xff).toByte()
header[29] = (byteRate shr 8 and 0xff).toByte()
header[30] = (byteRate shr 16 and 0xff).toByte()
header[31] = (byteRate shr 24 and 0xff).toByte()
// 确定系统一次要处理多少个这样字节的数据,确定缓冲区,通道数*采样位数
header[32] = (1 * 16 / 8).toByte()
header[33] = 0
//每个样本的数据位数
header[34] = 16
header[35] = 0
//Data chunk
header[36] = 'd'.toByte()//data
header[37] = 'a'.toByte()
header[38] = 't'.toByte()
header[39] = 'a'.toByte()
header[40] = (totalAudioLen and 0xff).toByte()
header[41] = (totalAudioLen shr 8 and 0xff).toByte()
header[42] = (totalAudioLen shr 16 and 0xff).toByte()
header[43] = (totalAudioLen shr 24 and 0xff).toByte()
out.write(header, 0, 44)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.content.Context
import android.os.Build
import android.provider.Settings
import android.util.Log
object BrightnessUtils {
private const val MAX_BRIGHTNESS = 255
private const val MIN_BRIGHTNESS = 25
fun hasPermission(context: Context?): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Settings.System.canWrite(context)
} else {
true
}
}
/**
* Android 的亮度范围为 0~255,这里会转为 0~100
*/
fun getBrightness(context: Context?): Int {
val contentResolver = context?.contentResolver ?: return -1
val realBrightness = Settings.System.getInt(
contentResolver,
Settings.System.SCREEN_BRIGHTNESS
)
return (realBrightness - MIN_BRIGHTNESS) * 100 / (MAX_BRIGHTNESS - MIN_BRIGHTNESS)
}
fun getBrightnessMode(context: Context?): Int {
val contentResolver = context?.contentResolver ?: return -1
return Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE)
}
/**
* @param brightness Android 的亮度范围为 0~255,这里会转为 0~100
*/
fun setBrightness(context: Context?, brightness: Int) {
Log.d("setBrightness", brightness.toString())
if (hasPermission(context)) {
val target = brightness * (MAX_BRIGHTNESS - MIN_BRIGHTNESS) / 100 + MIN_BRIGHTNESS
val contentResolver = context?.contentResolver ?: return
try {
if (Settings.System.getInt(
contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE
) ==
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
) {
Settings.System.putInt(
contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
)
}
} catch (e: Settings.SettingNotFoundException) {
e.printStackTrace()
}
try {
Settings.System.putInt(
contentResolver,
Settings.System.SCREEN_BRIGHTNESS, target
)
} catch (e: Settings.SettingNotFoundException) {
e.printStackTrace()
}
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.api
import com.iflytek.cyber.iot.show.core.model.ChatConfigData
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.PUT
interface DeviceApi {
@GET("v1/device")
fun get(): Call<ResponseBody>
@PUT("v1/device")
fun put(@Body requestBody: RequestBody): Call<ResponseBody>
@GET("v1/chat_config")
fun getChatConfig(): Call<ChatConfigData>
@PUT("v1/chat_config")
fun putChatConfig(@Body params: RequestBody): Call<ResponseBody>
@POST("v1/device/restore_factory")
fun postRestoreFactory(): Call<ResponseBody>
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.widget
import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator
import com.iflytek.cyber.iot.show.core.R
class RecognizeWaveView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr) {
private val wave1: ImageView = ImageView(context)
private val wave2: ImageView = ImageView(context)
private val wave3: ImageView = ImageView(context)
private val wave4: ImageView = ImageView(context)
private val fastOutSlowIn = FastOutSlowInInterpolator()
private val linearOutSlowIn = LinearOutSlowInInterpolator()
private var shouldAnimVolume = false
private var volumeUpdateHandler: Handler = Handler()
private var targetVolume = 0.0
private var oldVolume = 0.0
companion object {
private const val sTag = "RecognizeWaveView"
private const val MIN_SCALE_Y = 0.25f
private const val MIN_SCALE_X = 0.6f
private const val ENTER_DURATION = 333L // ms
private const val ENTER_OFFSET = 83L // ms
private const val ENTER_MAX_SCALE_X = 1f
private const val ENTER_MAX_SCALE_Y = 0.3f
private const val VOLUME_CHANGED_MAX_SCALE_Y = 1f
private const val VOLUME_CHANGED_MAX_SCALE_X = 1f
private const val VOLUME_CHANGED_FULL_DURATION = 180L
private const val VOLUME_CHANGED_MIN_DURATION = 135L
private const val VOLUME_CHANGED_OFFSET = 83L
private const val VOLUME_CHANGED_MAGIC_NUMBER = 0.3
}
private val updateVolumeRunnable = object : Runnable {
override fun run() {
if (shouldAnimVolume) {
val offset = targetVolume - oldVolume
val value =
when {
offset > VOLUME_CHANGED_MAGIC_NUMBER ->
Math.min(oldVolume + VOLUME_CHANGED_MAGIC_NUMBER, 1.0)
offset < -VOLUME_CHANGED_MAGIC_NUMBER ->
Math.max(oldVolume - VOLUME_CHANGED_MAGIC_NUMBER, 0.0)
else -> targetVolume
}
oldVolume = targetVolume
shouldAnimVolume = false
updateWaveVolume(wave1, value, offset, Runnable {
shouldAnimVolume = true
})
postDelayed({ updateWaveVolume(wave3, value, offset) }, VOLUME_CHANGED_OFFSET)
postDelayed({ updateWaveVolume(wave2, value, offset) }, VOLUME_CHANGED_OFFSET * 2)
postDelayed({ updateWaveVolume(wave4, value, offset) }, VOLUME_CHANGED_OFFSET * 3)
}
volumeUpdateHandler.postDelayed(this, 1000L / 60) // 60fps
}
}
init {
wave1.setImageResource(R.drawable.vo_light_a)
wave2.setImageResource(R.drawable.vo_light_b)
wave3.setImageResource(R.drawable.vo_light_c)
wave4.setImageResource(R.drawable.vo_light_d)
post {
wave1.scaleX = 0f
wave1.scaleY = 0f
val layoutParams1 = wave1.layoutParams as LayoutParams
layoutParams1.width = width / 2
layoutParams1.height = (layoutParams1.width * 0.547f).toInt()
layoutParams1.gravity = Gravity.BOTTOM
wave1.layoutParams = layoutParams1
wave2.scaleX = 0f
wave2.scaleY = 0f
val layoutParams2 = wave2.layoutParams as LayoutParams
layoutParams2.width = width / 2
layoutParams2.height = (layoutParams1.width * 0.547f).toInt()
layoutParams2.leftMargin = width / 12
layoutParams2.gravity = Gravity.BOTTOM
wave2.layoutParams = layoutParams2
wave3.scaleX = 0f
wave3.scaleY = 0f
val layoutParams3 = wave3.layoutParams as LayoutParams
layoutParams3.width = width / 2
layoutParams3.height = (layoutParams1.width * 0.547f).toInt()
layoutParams3.rightMargin = width / 12
layoutParams3.gravity = Gravity.END or Gravity.BOTTOM
wave3.layoutParams = layoutParams3
wave4.scaleX = 0f
wave4.scaleY = 0f
val layoutParams4 = wave4.layoutParams as LayoutParams
layoutParams4.width = width / 2
layoutParams4.height = (layoutParams1.width * 0.547f).toInt()
layoutParams4.gravity = Gravity.END or Gravity.BOTTOM
wave4.layoutParams = layoutParams4
}
wave1.alpha = 0f
wave2.alpha = 0f
wave3.alpha = 0f
wave4.alpha = 0f
addView(wave1, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
addView(wave2, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
addView(wave3, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
addView(wave4, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
volumeUpdateHandler.post(updateVolumeRunnable)
}
private fun initPivot() {
wave1.pivotX = 0f
wave1.pivotY = wave1.height.toFloat()
wave2.pivotX = (wave2.width / 2).toFloat()
wave2.pivotY = wave2.height.toFloat()
wave3.pivotX = (wave3.width / 2).toFloat()
wave3.pivotY = wave3.height.toFloat()
wave4.pivotX = wave4.width.toFloat()
wave4.pivotY = wave4.height.toFloat()
}
fun startEnterAnimation() {
shouldAnimVolume = false
initPivot()
val animation = ValueAnimator.ofFloat(0f, (ENTER_DURATION + ENTER_OFFSET * 3).toFloat())
animation.duration = ENTER_DURATION + ENTER_OFFSET * 3
animation.addUpdateListener(enterAnimUpdate)
animation.addListener(object : Animator.AnimatorListener {
override fun onAnimationEnd(animation: Animator?) {
shouldAnimVolume = true
}
override fun onAnimationRepeat(animation: Animator?) {
}
override fun onAnimationCancel(animation: Animator?) {
shouldAnimVolume = true
}
override fun onAnimationStart(animation: Animator?) {
}
})
animation.start()
}
fun updateVolume(volume: Double) {
targetVolume = Math.min(1.0, volume / 0.6)
}
private fun updateWaveVolume(waveView: View, value: Double, offset: Double) {
updateWaveVolume(waveView, value, offset, null)
}
private fun updateWaveVolume(waveView: View, value: Double, offset: Double, endRunnable: Runnable?) {
val animator = waveView.animate()
.scaleX((MIN_SCALE_X + value * (VOLUME_CHANGED_MAX_SCALE_X - MIN_SCALE_X)).toFloat())
.scaleY((MIN_SCALE_Y + value * (VOLUME_CHANGED_MAX_SCALE_Y - MIN_SCALE_Y)).toFloat())
.setDuration(Math.max((VOLUME_CHANGED_FULL_DURATION *
Math.abs(offset / VOLUME_CHANGED_MAGIC_NUMBER)).toLong(), VOLUME_CHANGED_MIN_DURATION))
endRunnable?.let {
animator.withEndAction(it)
}
animator.start()
}
// enter with 582ms, per light pay 333ms, and 83ms delay
// order by: 1 -> 3 -> 2 -> 4
private val enterAnimUpdate = ValueAnimator.AnimatorUpdateListener {
val value = it.animatedValue as Float
val wave1Value = Math.min(value, ENTER_DURATION.toFloat())
waveEnterAnimate(wave1, wave1Value)
val wave3Value = Math.max(0f, Math.min(value - ENTER_OFFSET, ENTER_DURATION.toFloat()))
waveEnterAnimate(wave3, wave3Value)
val wave2Value = Math.max(0f, Math.min(value - ENTER_OFFSET * 2, ENTER_DURATION.toFloat()))
waveEnterAnimate(wave2, wave2Value)
val wave4Value = Math.max(0f, Math.min(value - ENTER_OFFSET * 3, ENTER_DURATION.toFloat()))
waveEnterAnimate(wave4, wave4Value)
}
private fun waveEnterAnimate(waveView: View, value: Float) {
if (value < ENTER_DURATION / 2) {
val percent = value / ENTER_DURATION * 2
val realPercent = linearOutSlowIn.getInterpolation(percent)
waveView.scaleX = realPercent * ENTER_MAX_SCALE_X
waveView.scaleY = realPercent * ENTER_MAX_SCALE_Y
waveView.alpha = realPercent
} else {
val percent = (value - ENTER_DURATION / 2) / ENTER_DURATION * 2
val realPercent = 1 - fastOutSlowIn.getInterpolation(percent)
waveView.scaleX = realPercent * (ENTER_MAX_SCALE_X - MIN_SCALE_X) + MIN_SCALE_X
waveView.scaleY = realPercent * (ENTER_MAX_SCALE_Y - MIN_SCALE_Y) + MIN_SCALE_Y
}
}
fun startQuitAnimation() {
oldVolume = 0.0
shouldAnimVolume = false
wave1.animate().cancel()
wave2.animate().cancel()
wave3.animate().cancel()
wave4.animate().cancel()
wave1.animate().alpha(0f).scaleY(0f).scaleX(0f).setDuration(200).start()
wave2.animate().alpha(0f).scaleY(0f).scaleX(0f).setDuration(200).start()
wave3.animate().alpha(0f).scaleY(0f).scaleX(0f).setDuration(200).start()
wave4.animate().alpha(0f).scaleY(0f).scaleX(0f).setDuration(200).start()
}
}
<file_sep>package com.iflytek.cyber.evs.sdk.codec.audio.opus
import com.iflytek.cyber.evs.sdk.codec.audio.AudioCodec
import com.iflytek.cyber.evs.sdk.utils.Log
/**
* Opus编解码类,暂时只支持32bit 16000Hz的PCM。
*
* 构造函数。
* @param codec 指定编码还是解码,取值:CODEC_ENCODE,CODEC_DECODE(暂未支持)
* @param sampleRate 采样率,暂时只支持16000
* @param bitRate 比特率,取值:500-512000,云端暂时只支持32000
*/
class OpusCodec(codec: Int, sampleRate: Int, bitRate: Int) : AudioCodec(codec) {
companion object {
init {
System.loadLibrary("opus")
}
private val TAG = "OpusCodec"
}
private val len_20ms_bytes: Int
private var handle_codec: ByteArray? = null
private fun setHandles(handle: ByteArray) {
handle_codec = handle
}
init {
this.sampleRate = sampleRate
this.quality = bitRate
len_20ms_bytes = sampleRate / 100 * 2 * 2
val ret = init_native(codec, sampleRate, bitRate)
if (ret != 0) {
Log.e(TAG, "init failed", null)
}
}
private external fun init_native(codec: Int, sampleRate: Int, bitRate: Int): Int
/**
* 编码。
* @param handle 编码器指针
* @param data 原始音频数据
* @param dataLen 数据长度
* @param buffer 编码数据缓存
* @param bufferLen 缓存长度
* @param packetSize 编码数据包长度
* @return 编码后的数据总长度,负值表示出错
*/
private external fun encode_native(handle: ByteArray?, data: ByteArray, dataLen: Int,
buffer: ByteArray, bufferLen: Int, packetSize: Int): Int
/**
* 解码。
* @param handle 解码器指针
* @param data 已编码数据
* @param dataLen 数据长度
* @param buffer 解码数据缓存
* @param bufferLen 缓存长度
* @param packetSize 编码数据包长度
* @param packetDecSize 数据包解码后的长度
* @return 解码后的数据总长度,负值表示出错
*/
private external fun decode_native(handle: ByteArray?, data: ByteArray, dataLen: Int,
buffer: ByteArray, bufferLen: Int,
packetSize: Int, packetDecSize: Int): Int
private external fun destroy_native(codec: Int, handle: ByteArray?)
/**
* 编码。
* @param data 原始音频
* @param dataLen 音频长度,必须为20ms音频长度的整数倍
* @param buffer 编码缓存区
* @param bufferLen 缓存区长度
* @return 编码后的长度,负值表示出错
*/
override fun encode(data: ByteArray, dataLen: Int, buffer: ByteArray, bufferLen: Int): Int {
if (isDecoder()) {
Log.e(TAG, "decoder cannot be used to encode")
return -1
}
if (handle_codec == null) {
Log.e(TAG, "not inited or destroyed")
return -1
}
val ret = encode_native(handle_codec, data, dataLen, buffer, bufferLen, len_20ms_bytes)
if (ret < 0) {
Log.e(TAG, "encode error, ret=$ret")
}
return ret
}
/**
* 解码。
* @param data 编码数据
* @param dataLen 数据长度
* @param buffer 解码缓存,必须足够长能容纳解码数据
* @param bufferLen 缓存长度
* @return 解码后的数据长度,负值表示出错
*/
override fun decode(data: ByteArray, dataLen: Int, buffer: ByteArray, bufferLen: Int): Int {
if (isEncoder()) {
Log.e(TAG, "encoder cannot be used to decode")
return -1
}
if (handle_codec == null) {
Log.e(TAG, "not inited or destroyed")
return -1
}
val ret = decode_native(handle_codec, data, dataLen, buffer, bufferLen,
80, len_20ms_bytes)
if (ret < 0) {
Log.e(TAG, "decode error, ret=$ret")
}
return ret
}
override fun destroy() {
if (handle_codec != null) {
destroy_native(codeMode, handle_codec)
handle_codec = null
}
}
protected fun finalize() {
destroy()
}
}<file_sep>package com.iflytek.cyber.evs.sdk.focus
abstract class AudioFocusChannel {
private var manager: AudioFocusManager? = null
abstract fun onFocusChanged(focusStatus: FocusStatus)
abstract fun getChannelName(): String
abstract fun getType(): String
fun setupManager(manager: AudioFocusManager) {
this.manager = manager
}
fun requestActive() {
manager?.requestActive(getChannelName(), getExternalType()) ?: run {
throw IllegalStateException(
"You should override getExternalAudioFocusChannels in EvsService, and add this channel to return value"
)
}
}
fun requestAbandon() {
manager?.requestAbandon(getChannelName(), getExternalType()) ?: run {
throw IllegalStateException(
"You should override getExternalAudioFocusChannels in EvsService, and add this channel to return value"
)
}
}
fun getExternalType() = "External.${getType()}"
fun getCurrentStatus(): FocusStatus {
return FocusStatus.Idle
}
}
abstract class VisualFocusChannel {
private var manager: VisualFocusManager? = null
abstract fun onFocusChanged(focusStatus: FocusStatus)
abstract fun getChannelName(): String
abstract fun getType(): String
fun setupManager(manager: VisualFocusManager) {
this.manager = manager
}
fun requestActive() {
manager?.requestActive(getChannelName(), getExternalType()) ?: run {
throw IllegalStateException(
"You should override getExternalVisualFocusChannels in EvsService, and add this channel to return value"
)
}
}
fun requestAbandon() {
manager?.requestAbandon(getChannelName(), getExternalType()) ?: run {
throw IllegalStateException(
"You should override getExternalVisualFocusChannels in EvsService, and add this channel to return value"
)
}
}
fun getExternalType() = "External.${getType()}"
fun getCurrentStatus(): FocusStatus {
return FocusStatus.Idle
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.content.Context
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.MotionEvent
import android.widget.FrameLayout
class InterceptFrameLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
var onInterceptTouchListener: OnTouchListener? = null
var onInterceptKeyEventListener: OnKeyListener? = null
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
return onInterceptTouchListener?.onTouch(this, ev) ?: super.onInterceptTouchEvent(ev)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
return onInterceptKeyEventListener?.onKey(this, event.keyCode, event)
?: super.dispatchKeyEvent(event)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.record
import android.content.Context
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Build
import android.os.Handler
import android.util.Log
import com.iflytek.cyber.evs.sdk.agent.Recognizer
import org.json.JSONObject
object GlobalRecorder {
private const val TAG = "GlobalRecorder"
private var mAudioRecord: AudioRecord? = null
var isRecording = false
private set
private val observerSet = HashSet<Observer>()
private var mRecordThread: RecordThread? = null
private val minBufferSize = AudioRecord.getMinBufferSize(
Recognizer.getSampleRateInHz(),
Recognizer.getAudioChannel(),
Recognizer.getAudioFormatEncoding()
)
private val ivwListener = object : EvsIvwHandler.IvwHandlerListener {
override fun onWakeUp(angle: Int, beam: Int, params: String?) {
try {
observerSet.map {
it.onWakeUp(0, 0, params)
}
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
private var ivwHandler: EvsIvwHandler? = null
fun init(context: Context) {
mAudioRecord = createAudioRecord()
ivwHandler = EvsIvwHandler(context, ivwListener)
}
private fun getAudioSource() = MediaRecorder.AudioSource.DEFAULT
private fun createAudioRecord() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
AudioRecord.Builder()
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(Recognizer.getAudioFormatEncoding())
.setSampleRate(Recognizer.getSampleRateInHz())
.setChannelMask(Recognizer.getAudioChannel())
.build()
)
.setAudioSource(getAudioSource())
.setBufferSizeInBytes(minBufferSize)
.build()
} else {
AudioRecord(
getAudioSource(),
Recognizer.getSampleRateInHz(),
Recognizer.getAudioChannel(),
Recognizer.getAudioFormatEncoding(),
minBufferSize
)
}
fun startRecording() {
isRecording = true
if (mAudioRecord?.state == AudioRecord.STATE_INITIALIZED)
mAudioRecord?.startRecording()
try {
mRecordThread?.interrupt()
} catch (e: Exception) {
e.printStackTrace()
}
mRecordThread = RecordThread()
mRecordThread?.start()
}
fun stopRecording() {
isRecording = false
Handler().post {
if (mAudioRecord?.recordingState == AudioRecord.RECORDSTATE_RECORDING)
mAudioRecord?.stop()
}
}
fun registerObserver(observer: Observer) {
observerSet.add(observer)
}
fun unregisterObserver(observer: Observer) {
observerSet.remove(observer)
}
private fun publishAudioData(array: ByteArray, offset: Int, length: Int) {
try {
for (observer in observerSet) {
try {
observer.onAudioData(array, offset, length)
} catch (e: Exception) {
e.printStackTrace()
}
}
} catch (e: ConcurrentModificationException) {
// ignore possible ConcurrentModificationException
}
}
private fun isReady(): Boolean {
return mAudioRecord != null && mAudioRecord?.state != AudioRecord.STATE_UNINITIALIZED
}
private class RecordThread : Thread() {
override fun run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO)
try {
val tempBuffer = ByteArray(minBufferSize)
while (isRecording) {
if (isReady()) {
val bytesRecord = mAudioRecord?.read(tempBuffer, 0, minBufferSize) ?: -1
ivwHandler?.write(tempBuffer, bytesRecord)
publishAudioData(tempBuffer, 0, bytesRecord)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
interface Observer {
fun onAudioData(array: ByteArray, offset: Int, length: Int)
fun onWakeUp(angle: Int, beam: Int, params: String?)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.api
import com.iflytek.cyber.iot.show.core.model.Banner
import retrofit2.Call
import retrofit2.http.GET
interface BannerApi {
@GET("v1/banners")
fun getBanners(): Call<List<Banner>>
@GET("v2/desk/banners")
fun loadBanners(): Call<List<Banner>>
}<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.app.AppOpsManager
import android.content.Context
import android.graphics.PixelFormat
import android.os.Binder
import android.os.Build
import android.os.Handler
import android.provider.Settings
import android.util.Log
import android.view.View
import android.view.WindowManager
import androidx.annotation.RequiresApi
object OverlayUtils {
private const val TAG = "OverlayUtils"
fun hasPermission(context: Context): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Settings.canDrawOverlays(context)
} else {
hasPermissionBelowMarshmallow(context)
}
}
fun hasPermissionOnActivityResult(context: Context): Boolean {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {
return hasPermissionForO(context)
}
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Settings.canDrawOverlays(context)
} else {
hasPermissionBelowMarshmallow(context)
}
}
fun hasPermissionAwait(context: Context, callback: (result: Boolean) -> Unit) {
callback.invoke(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Settings.canDrawOverlays(context)
} else {
hasPermissionBelowMarshmallow(context)
}
)
}
fun hasPermissionOnActivityResultAwait(
context: Context, callback: (result: Boolean) -> Unit) {
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
val handler = Handler()
Thread {
try {
Thread.sleep(500)
} catch (e: Exception) {
e.printStackTrace()
}
handler.post {
callback.invoke(Settings.canDrawOverlays(context))
}
}.start()
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ->
callback.invoke(Settings.canDrawOverlays(context))
else ->
callback.invoke(hasPermissionBelowMarshmallow(context))
}
}
/**
* 6.0以下判断是否有权限
* 理论上6.0以上才需处理权限,但有的国内rom在6.0以下就添加了权限
* 其实此方式也可以用于判断6.0以上版本,只不过有更简单的canDrawOverlays代替
*/
private fun hasPermissionBelowMarshmallow(context: Context): Boolean {
return try {
val manager = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
val dispatchMethod = AppOpsManager::class.java.getMethod("checkOp", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, String::class.java)
//AppOpsManager.OP_SYSTEM_ALERT_WINDOW = 24
AppOpsManager.MODE_ALLOWED == dispatchMethod.invoke(
manager, 24, Binder.getCallingUid(), context.applicationContext.packageName) as Int
} catch (e: Exception) {
false
}
}
/**
* 用于判断8.0时是否有权限,仅用于OnActivityResult
* 针对8.0官方bug:在用户授予权限后Settings.canDrawOverlays或checkOp方法判断仍然返回false
*/
@RequiresApi(api = Build.VERSION_CODES.M)
private fun hasPermissionForO(context: Context): Boolean {
try {
val mgr = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val viewToAdd = View(context)
val params = WindowManager.LayoutParams(0, 0,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
else
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSPARENT)
viewToAdd.layoutParams = params
mgr.addView(viewToAdd, params)
mgr.removeView(viewToAdd)
return true
} catch (e: Exception) {
Log.e(TAG, "hasPermissionForO e:$e")
}
return false
}
}<file_sep>package com.iflytek.cyber.evs.sdk
import android.os.Handler
import com.alibaba.fastjson.JSONObject
import com.iflytek.cyber.evs.sdk.socket.RequestBuilder
import com.iflytek.cyber.evs.sdk.socket.Result
import com.iflytek.cyber.evs.sdk.socket.SocketManager
import com.iflytek.cyber.evs.sdk.utils.Log
import java.nio.ByteBuffer
internal object RequestManager {
private var handler: Handler? = null
private var service: EvsService? = null
const val MESSAGE_END = "__END__"
const val MESSAGE_CANCEL = "__CANCEL__"
var currentManualRequestId: String? = null
private set
fun initHandler(handler: Handler?, service: EvsService) {
this.handler = handler
this.service = service
}
fun sendRequest(
name: String,
payload: JSONObject,
requestCallback: RequestCallback? = null,
isManual: Boolean = false
) {
handler?.post {
val requestBody = RequestBuilder.buildRequestBody(name, payload, isManual)
if (isManual) {
currentManualRequestId = requestBody.request.header.requestId
ResponseProcessor.clearPendingManualExecuting()
}
// val requestId = requestBody.request.header.requestId
// if (requestId.startsWith(RequestBuilder.PREFIX_REQUEST))
// ResponseProcessor.updateCurrentRequestId(requestId)
val result = SocketManager.send(requestBody.toString())
requestCallback?.onResult(result)
} ?: run {
requestCallback?.onResult(Result(Result.CODE_UNINITIALIZED, null))
throw IllegalStateException("Must init handler for RequestManager at first.")
}
}
fun sendRawString(
raw: String,
requestCallback: RequestCallback? = null
) {
handler?.post {
if (raw == MESSAGE_CANCEL)
currentManualRequestId = null
val result = SocketManager.send(raw)
requestCallback?.onResult(result)
} ?: run {
requestCallback?.onResult(Result(Result.CODE_UNINITIALIZED, null))
throw IllegalStateException("Must init handler for RequestManager at first.")
}
}
fun sendBinary(byteArray: ByteArray, requestCallback: RequestCallback? = null) {
handler?.post {
val result = SocketManager.send(byteArray)
Log.v("RequestManager", "sendBinary result($result)")
requestCallback?.onResult(result)
} ?: run {
requestCallback?.onResult(Result(Result.CODE_UNINITIALIZED, null))
throw IllegalStateException("Must init handler for RequestManager at first.")
}
}
fun sendBinary(byteBuffer: ByteBuffer, requestCallback: RequestCallback? = null) {
handler?.post {
val result = SocketManager.send(byteBuffer)
requestCallback?.onResult(result)
} ?: run {
requestCallback?.onResult(Result(Result.CODE_UNINITIALIZED, null))
throw IllegalStateException("Must init handler for RequestManager at first.")
}
}
}<file_sep>package com.iflytek.cyber.evs.sdk
import com.iflytek.cyber.evs.sdk.socket.Result
interface RequestCallback {
fun onResult(result: Result)
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.airbnb.lottie.LottieAnimationView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.bumptech.glide.request.transition.Transition
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.AlbumSectionContentAdapter
import com.iflytek.cyber.iot.show.core.api.AppApi
import com.iflytek.cyber.iot.show.core.model.SourceItem
import com.iflytek.cyber.iot.show.core.model.TemplateApp
import com.iflytek.cyber.iot.show.core.model.TemplateMediaItem
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.utils.onLoadMore
import com.iflytek.cyber.iot.show.core.widget.GradientTextView
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
import kotlin.math.abs
class TemplateApp1Fragment : BaseFragment(), PageScrollable {
companion object {
private const val TAG = "TemplateApp1Fragment"
fun newInstance(templateApp: TemplateApp): TemplateApp1Fragment {
val fragment = TemplateApp1Fragment()
fragment.templateApp = templateApp
return fragment
}
fun newInstance(templateApp: TemplateApp, sourceItem: SourceItem?): TemplateApp1Fragment {
val fragment = TemplateApp1Fragment().apply {
arguments = bundleOf(Pair("sourceItem", sourceItem))
}
fragment.templateApp = templateApp
return fragment
}
}
private var templateApp: TemplateApp? = null
private var sourceItem: SourceItem? = null
private var ivBack: ImageView? = null
private var ivIcon: ImageView? = null
private var ivBackground: ImageView? = null
private var tabLayout: RecyclerView? = null
private var recyclerView: RecyclerView? = null
private var viewPager: ViewPager2? = null
private var tvTitle: TextView? = null
private var loadingContainer: FrameLayout? = null
private var loadingImageView: LottieAnimationView? = null
private var loadingBottom: LottieAnimationView? = null
private var loadingCenter: LottieAnimationView? = null
private var errorContainer: View? = null
private var tvError: TextView? = null
private var errorRetry: View? = null
private var tvRetry: TextView? = null
private val tabAdapter = TabAdapter()
private var pagerAdapter: CategoryContentAdapter? = null
private val albumAdapter = AlbumSectionContentAdapter()
private var clickCount = 0
private var page = 1
private var isLoading = false
private var totalListSize = 0
private var templateType = -1
private val tabScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
(recyclerView.layoutManager as? LinearLayoutManager)?.let { linearLayoutManager ->
val lastComplete = linearLayoutManager.findLastCompletelyVisibleItemPosition()
val lastVisible = linearLayoutManager.findLastVisibleItemPosition()
if (lastComplete == lastComplete
&& linearLayoutManager.findFirstCompletelyVisibleItemPosition()
== linearLayoutManager.findFirstVisibleItemPosition()
&& tabAdapter.itemCount == lastComplete + 1
)
return@let
/*val targetViewSet = mutableSetOf<View>()
var lastViewWidth = 0
recyclerView.findViewHolderForAdapterPosition(lastVisible)?.let { holder ->
if (holder is TabViewHolder) {
val itemView = holder.itemView
val offset = itemView.width - itemView.right + recyclerView.width
holder.tvTitle?.let { gradientTextView ->
if (!gradientTextView.isGradient)
gradientTextView.isGradient = true
gradientTextView.startColor =
Color.argb(
255 * offset / itemView.width,
255,
255,
255
)
if (recyclerView.adapter?.itemCount == lastVisible + 1) {
gradientTextView.endColor =
Color.argb(
255 * offset / itemView.width,
255,
255,
255
)
} else {
if (gradientTextView.endColor != Color.TRANSPARENT)
gradientTextView.endColor =
Color.TRANSPARENT
}
}
lastViewWidth = itemView.width
targetViewSet.add(itemView)
}
}*/
/*if (lastComplete != lastVisible) {
recyclerView.findViewHolderForAdapterPosition(lastComplete)?.let { holder ->
if (holder is TabViewHolder) {
val itemView = holder.itemView
val offset =
lastViewWidth - (itemView.right + lastViewWidth - recyclerView.width)
holder.tvTitle?.let { gradientTextView ->
if (!gradientTextView.isGradient)
gradientTextView.isGradient = true
if (gradientTextView.startColor != Color.WHITE)
gradientTextView.startColor = Color.WHITE
gradientTextView.endColor =
Color.argb(
255 * offset / lastViewWidth,
255,
255,
255
)
}
targetViewSet.add(itemView)
}
}
}*/
/*// 从后往前遍历
for (i in 0 until recyclerView.childCount) {
val child = recyclerView.getChildAt(recyclerView.childCount - 1 - i)
if (child !in targetViewSet) {
(recyclerView.getChildViewHolder(child) as? TabViewHolder)?.let {
it.tvTitle?.isGradient = false
}
}
}*/
}
}
}
private val onPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
val oldPosition = tabAdapter.selectedItem
tabAdapter.selectedItem = position
tabAdapter.notifyItemChanged(oldPosition)
tabAdapter.notifyItemChanged(position)
if (position < tabAdapter.itemCount)
tabLayout?.smoothScrollToPosition(position)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_template_app_1, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back)?.setOnClickListener {
pop()
}
ivBack = view.findViewById(R.id.iv_back)
ivIcon = view.findViewById(R.id.iv_icon)
ivBackground = view.findViewById(R.id.background)
tabLayout = view.findViewById(R.id.tab_layout)
viewPager = view.findViewById(R.id.view_pager)
recyclerView = view.findViewById(R.id.recycler_view)
tvRetry = view.findViewById(R.id.tv_retry)
errorRetry = view.findViewById(R.id.error_retry)
tvError = view.findViewById(R.id.tv_error)
errorContainer = view.findViewById(R.id.error_container)
tvTitle = view.findViewById(R.id.title)
loadingContainer = view.findViewById(R.id.loading_container)
loadingImageView = view.findViewById(R.id.loading_image)
loadingBottom = view.findViewById(R.id.loading_bottom)
loadingCenter = view.findViewById(R.id.loading_center)
tvTitle?.text = templateApp?.name
tvTitle?.isVisible = false
errorRetry?.setOnClickListener {
if (!isLoading) {
page = 1
//getFirstTemplate()
getTemplateList()
}
}
viewPager?.registerOnPageChangeCallback(onPageChangeCallback)
tabLayout?.adapter = tabAdapter
tabLayout?.addOnScrollListener(tabScrollListener)
tabLayout?.itemAnimator = null
tabAdapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: ViewGroup, itemView: View, position: Int) {
setCurrentPageItem(position)
}
}
albumAdapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: ViewGroup, itemView: View, position: Int) {
val albumItem = albumAdapter.getAlbumItem(position)
val templateApp = templateApp ?: return
if (albumItem != null) {
if (albumItem.type == 1) {
start(newInstance(templateApp, albumItem))
} else if (albumItem.type == 2) {
if (templateType == 2) {
start(newInstance(templateApp, albumItem))
} else {
start(TemplateApp2Fragment.newInstance(templateApp))
}
} else {
if (!albumItem.metadata?.resourceId.isNullOrEmpty()) {
postPlay(albumItem)
} else {
start(SongListFragment.newInstance(albumItem, 2, 1002))
}
}
}
}
}
setLayoutManager(1.0f)
sourceItem = arguments?.getParcelable("sourceItem")
applyTheme(templateApp?.isDark != false)
loadBackground()
loadAppIcon()
//getFirstTemplate()
getTemplateList()
recyclerView?.onLoadMore {
if (!isLoading && albumAdapter.itemCount < totalListSize) {
page += 1
//getFirstTemplate()
getTemplateList()
}
}
}
override fun onSupportVisible() {
super.onSupportVisible()
clickCount = 0
}
override fun onDestroy() {
super.onDestroy()
recyclerView?.removeOnScrollListener(tabScrollListener)
viewPager?.unregisterOnPageChangeCallback(onPageChangeCallback)
}
private fun applyTheme(isDark: Boolean) {
if (isDark) {
loadingImageView?.setAnimation(R.raw.animation_loading_l_white)
} else {
loadingImageView?.setAnimation(R.raw.animation_loading_l)
}
ivBack?.setColorFilter(if (isDark) Color.WHITE else Color.BLACK)
tabAdapter.isDark = isDark
if (tabAdapter.itemCount != 0) {
tabAdapter.notifyDataSetChanged()
}
albumAdapter.isDark = isDark
if (albumAdapter.itemCount != 0) {
albumAdapter.notifyDataSetChanged()
}
pagerAdapter?.isDark = isDark
tvTitle?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
tvError?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
tvRetry?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
errorRetry?.setBackgroundResource(
if (isDark) R.drawable.bg_round_border_white_36dp
else R.drawable.bg_round_border_black_36dp
)
}
private fun setCurrentPageItem(position: Int) {
val viewPager = viewPager ?: return
if (pagerAdapter?.itemCount ?: 0 <= position) return
val smooth = abs(position - viewPager.currentItem) == 1
viewPager.setCurrentItem(position, smooth)
}
private fun loadBackground() {
val templateApp = templateApp ?: return
ivBackground?.let { imageView ->
val url = templateApp.img
if (url.isNullOrEmpty())
return
try {
Uri.parse(url)?.let { uri ->
Glide.with(imageView)
.load(uri)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
private fun loadAppIcon() {
val templateApp = templateApp ?: return
if (!templateApp.icon.isNullOrEmpty()) {
try {
Uri.parse(templateApp.icon)?.let { uri ->
ivIcon?.let { imageView ->
Glide.with(imageView)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
} ?: run {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} catch (t: Throwable) {
t.printStackTrace()
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
}
private fun showLoading() {
if (page == 1) {
loadingContainer?.isVisible = true
loadingImageView?.playAnimation()
} else {
loadingBottom?.isVisible = true
loadingBottom?.playAnimation()
}
}
private fun dismissLoading() {
loadingContainer?.post {
loadingImageView?.pauseAnimation()
loadingContainer?.isVisible = false
if (loadingBottom?.isVisible == true) {
loadingBottom?.pauseAnimation()
loadingBottom?.isVisible = false
}
}
}
private fun showError(message: String?, showRetry: Boolean = true) {
if (isRemoving || isDetached)
return
context ?: return
viewPager?.isVisible = false
recyclerView?.isVisible = false
errorContainer?.isVisible = true
errorRetry?.isVisible = showRetry
tvError?.text = message
}
private fun hideError() {
if (isRemoving || isDetached)
return
context ?: return
errorContainer?.isVisible = false
}
private fun getTemplateList() {
val templateApp = templateApp ?: return
isLoading = true
hideError()
showLoading()
val metaData = sourceItem?.metadata
getAppApi()?.getTemplateList(
templateApp.name,
metaData?.topLevel,
metaData?.secondLevel,
metaData?.thirdLevel,
page
)?.enqueue(object : Callback<TemplateMediaItem> {
override fun onResponse(
call: Call<TemplateMediaItem>,
response: Response<TemplateMediaItem>
) {
isLoading = false
if (response.isSuccessful) {
val templateMediaItem = response.body()
if (templateMediaItem != null) {
totalListSize = templateMediaItem.total
//templateType = templateMediaItem.type
val type = if (sourceItem != null && sourceItem?.type != null) {
sourceItem!!.type
} else if (templateMediaItem.items?.size ?: 0 > 0) {
templateMediaItem.items?.get(0)?.type
} else {
templateMediaItem.type
}
if (type != null) {
handleResult(templateApp, type, templateMediaItem)
}
}
} else {
dismissLoading()
if (albumAdapter.itemCount == 0) {
showError("请求出错,请稍后重试")
}
}
}
override fun onFailure(call: Call<TemplateMediaItem>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
isLoading = false
dismissLoading()
if (t is UnknownHostException) {
showError("Ooooops,请检查网络后重试")
} else {
showError("请求出错,请稍后重试")
}
}
})
}
private fun getFirstItemCover(items: ArrayList<SourceItem>): String? {
var firstCover: String? = null
for (item in items) {
if (firstCover.isNullOrEmpty()) {
firstCover = item.cover
}
}
return firstCover
}
private fun handleResult(
templateApp: TemplateApp,
type: Int,
templateMediaItem: TemplateMediaItem
) {
if (!isAdded || context == null) {
return
}
if ((templateApp.template == 2 && type == 1) || (templateApp.template == 1 && type == 2)) {
dismissLoading()
viewPager?.isVisible = true
recyclerView?.isVisible = false
pagerAdapter = CategoryContentAdapter(templateApp, templateMediaItem.items, this)
viewPager?.adapter = pagerAdapter
tabAdapter.setCategories(templateMediaItem.items)
tabAdapter.notifyDataSetChanged()
} else if (type > 1 && templateMediaItem.items != null) {
viewPager?.isVisible = false
recyclerView?.isVisible = true
val firstCover = getFirstItemCover(templateMediaItem.items)
if (firstCover.isNullOrEmpty()) {
dismissLoading()
setupAlbumList(1f, templateMediaItem.items)
} else {
setupAlbumAdapter(firstCover, templateMediaItem.items)
}
}
}
private fun setupAlbumAdapter(firstCover: String?, items: ArrayList<SourceItem>) {
Glide.with(this)
.asBitmap()
.load(firstCover)
.into(object : CustomTarget<Bitmap>() {
override fun onLoadCleared(placeholder: Drawable?) {
isLoading = false
dismissLoading()
}
override fun onLoadFailed(errorDrawable: Drawable?) {
super.onLoadFailed(errorDrawable)
dismissLoading()
showError("请求出错,请稍后重试")
}
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
dismissLoading()
val ratio = 1f * resource.width / resource.height
setupAlbumList(ratio, items)
}
})
}
private fun setupAlbumList(ratio: Float, items: ArrayList<SourceItem>) {
if (page == 1) {
setRecyclerViewPadding(ratio)
setLayoutManager(ratio)
albumAdapter.ratio = ratio
albumAdapter.setAlbumList(items)
recyclerView?.adapter = albumAdapter
} else {
albumAdapter.appendAlbumList(items)
albumAdapter.notifyDataSetChanged()
}
}
private fun setRecyclerViewPadding(ratio: Float) {
recyclerView?.let { recyclerView ->
recyclerView.post {
when {
ratio <= 1f -> {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 5
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
5
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
ratio > 1f -> {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 3
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
3
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingBottom
)
}
}
}
}
}
private fun setLayoutManager(ratio: Float) {
val layoutManager = if (ratio <= 1) {
GridLayoutManager(context, 5)
} else {
GridLayoutManager(context, 3)
}
recyclerView?.post {
recyclerView?.layoutManager = layoutManager
}
}
private fun postPlay(mediaItem: SourceItem) {
val audioId = mediaItem.metadata?.resourceId
val sourceType = mediaItem.source
val business = mediaItem.metadata?.business
loadingCenter?.isVisible = true
loadingCenter?.playAnimation()
val json = com.alibaba.fastjson.JSONObject()
json["audio_id"] = audioId
json["source_type"] = sourceType
json["business"] = business
val requestBody = RequestBody.create(
MediaType.parse("application/json"),
json.toString()
)
getAppApi()?.postPlayMedia(requestBody)?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
loadingCenter?.isVisible = false
loadingCenter?.pauseAnimation()
clickCount = 0
Toast.makeText(context, "请求出错", Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (isRemoving || isDetached)
return
context ?: return
loadingCenter?.isVisible = false
loadingCenter?.pauseAnimation()
clickCount = 0
if (response.isSuccessful) {
Toast.makeText(context, "开始播放", Toast.LENGTH_SHORT).show()
} else {
response.errorBody()?.let { errorBody ->
val errorString = errorBody.string()
val errorJson = JSONObject(errorString)
if (errorJson.has("message")) {
Toast.makeText(
context,
errorJson.optString("message"),
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(context, "播放失败", Toast.LENGTH_SHORT).show()
}
errorBody.close()
} ?: run {
Toast.makeText(context, "播放失败", Toast.LENGTH_SHORT).show()
}
}
}
})
}
private fun getAppApi(): AppApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(AppApi::class.java)
}
override fun scrollToNext(): Boolean {
if (viewPager?.isVisible == false) {
return false
}
val currentItem = viewPager?.currentItem ?: return false
if (currentItem < (viewPager?.adapter?.itemCount ?: 0) - 1 || currentItem < 0) {
viewPager?.post {
viewPager?.setCurrentItem(currentItem + 1, true)
}
return true
}
return false
}
override fun scrollToPrevious(): Boolean {
if (viewPager?.isVisible == false) {
return false
}
val currentItem = viewPager?.currentItem ?: return false
if (currentItem > 0) {
viewPager?.post {
viewPager?.setCurrentItem(currentItem - 1, true)
}
return true
}
return false
}
// Setup ViewPager
private class CategoryContentAdapter(
val templateApp: TemplateApp,
val items: ArrayList<SourceItem>?,
fragment: Fragment
) :
FragmentStateAdapter(fragment) {
var isDark = false
set(value) {
field = value
fragments.map {
(it.value as? TemplateCategoryContentFragment)?.applyTheme(value)
}
}
private val fragments = mutableMapOf<Int, Fragment>() // position -> fragment
override fun getItemCount(): Int {
return items?.size ?: 0
}
override fun createFragment(position: Int): Fragment {
val sourceItem = items?.get(position)
val fragment = TemplateCategoryContentFragment.newInstance(templateApp, sourceItem)
fragments[position] = fragment
return fragment
}
}
// Setup Tab
private class TabAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val categories = mutableListOf<SourceItem>()
var selectedItem = 0
var onItemClickListener: OnItemClickListener? = null
var isDark = false
fun setCategories(categories: ArrayList<SourceItem>?) {
if (categories != null) {
this.categories.clear()
this.categories.addAll(categories)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = TabViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_app_tab, parent, false)
)
holder.itemView.setOnClickListener {
onItemClickListener?.onItemClick(parent, it, holder.adapterPosition)
}
return holder
}
override fun getItemCount(): Int {
return categories.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is TabViewHolder) {
if (selectedItem == position) {
if (holder.indicator?.isVisible != true) {
holder.indicator?.isVisible = true
}
if (holder.tvTitle?.alpha != 1f) {
holder.tvTitle?.alpha = 1f
}
} else {
if (holder.indicator?.isVisible != false) {
holder.indicator?.isVisible = false
}
if (holder.tvTitle?.alpha != 0.7f) {
holder.tvTitle?.alpha = 0.7f
}
}
holder.tvTitle?.text = categories[position].title
if (isDark) {
holder.indicator?.background?.setColorFilter(
Color.WHITE,
PorterDuff.Mode.SRC_IN
)
holder.tvTitle?.setTextColor(Color.WHITE)
} else {
holder.indicator?.background?.setColorFilter(
Color.BLACK,
PorterDuff.Mode.SRC_IN
)
holder.tvTitle?.setTextColor(Color.BLACK)
}
}
}
}
private class TabViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvTitle: GradientTextView? = itemView.findViewById(R.id.title)
val indicator: View? = itemView.findViewById(R.id.indicator)
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.utils
import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import android.os.Build
import android.util.SparseIntArray
import androidx.annotation.RawRes
import com.iflytek.cyber.iot.show.core.R
/**
* 用于播放简短的提示音
*/
class ToneManager private constructor(context: Context) {
private val soundPool: SoundPool = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
SoundPool.Builder()
.setMaxStreams(3)
.setAudioAttributes(AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build())
.build()
} else {
@Suppress("DEPRECATION") // Android L 之前未被标为过时
SoundPool(3, AudioManager.STREAM_NOTIFICATION, 0)
}
private val tones = SparseIntArray()
init {
// 加载对应的提示音
load(context, TONE_WAKE, R.raw.wake_up_sound)
load(context, TONE_VOLUME, R.raw.plastic_soda_pop)
// 若要新增自定义的提示音,可新建一个新的、值不同于 WAKE 和 VOLUME 的 TONE_CUSTOM (命名可自定义)
// 然后像下面这样调用加载提示音,加载完后若要播放只需使用 play(TONE_CUSTOM, volume)
// load(context, TONE_CUSTOM, R.raw.custom_tone)
}
private fun load(context: Context, tone: Int, @RawRes resId: Int) {
tones.put(tone, soundPool.load(context, resId, 1))
}
fun play(tone: Int, volume: Float = 1f): Boolean {
val sound = tones.get(tone, -1)
if (sound == -1) {
return false
}
return soundPool.play(sound, volume, volume, 1, 0, 1.0f) != 0
}
fun destroy() {
soundPool.release()
toneManager = null
}
companion object {
const val TONE_WAKE = 1
const val TONE_VOLUME = 2
private var toneManager: ToneManager? = null
operator fun get(context: Context): ToneManager {
val current = toneManager
return if (current == null) {
val newToneManager = ToneManager(context)
toneManager = newToneManager
newToneManager
} else
current
}
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.utils
import android.app.Activity
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Process
import android.os.UserHandle
import java.lang.reflect.InvocationTargetException
object ContextWrapper {
fun startServiceAsUser(context: Context, intent: Intent, userHandle: String) {
try {
if (Process.myUid() == Process.SYSTEM_UID) {
val clz = context::class.java
val method =
clz.getMethod("startServiceAsUser", Intent::class.java, UserHandle::class.java)
method.isAccessible = true
method.invoke(context, intent, newUserHandle(userHandle))
} else {
context.startService(intent)
}
} catch (t: Throwable) {
if (t is InvocationTargetException) {
context.startService(intent)
} else {
t.printStackTrace()
}
}
}
fun startActivityAsUser(activity: Activity, intent: Intent, userHandle: String) {
try {
if (Process.myUid() == Process.SYSTEM_UID) {
val clz = activity::class.java
val method =
clz.getMethod("startActivityAsUser", Intent::class.java, UserHandle::class.java)
method.isAccessible = true
method.invoke(activity, intent, newUserHandle(userHandle))
}
} catch (t: Throwable) {
if (t is InvocationTargetException) {
activity.startActivity(intent)
} else {
t.printStackTrace()
}
}
}
fun getBroadcastAsUser(
context: Context?,
requestCode: Int,
intent: Intent,
flags: Int,
userHandle: String
): PendingIntent? {
try {
if (Process.myUid() == Process.SYSTEM_UID) {
val clz = PendingIntent::class.java
val method =
clz.getMethod(
"getBroadcastAsUser",
Context::class.java,
Int::class.java,
Intent::class.java,
Int::class.java,
UserHandle::class.java
)
method.isAccessible = true
return method.invoke(
null,
context,
requestCode,
intent,
flags,
newUserHandle(userHandle)
) as? PendingIntent
} else {
PendingIntent.getBroadcast(context, requestCode, intent, flags)
}
} catch (t: Throwable) {
if (t is InvocationTargetException) {
return PendingIntent.getBroadcast(context, requestCode, intent, flags)
} else {
t.printStackTrace()
}
}
return null
}
fun startForegroundServiceAsUser(context: Context, intent: Intent, userHandle: String) {
try {
if (Process.myUid() == Process.SYSTEM_UID) {
val clz = context::class.java
val method =
clz.getMethod(
"startForegroundServiceAsUser",
Intent::class.java,
UserHandle::class.java
)
method.isAccessible = true
method.invoke(context, intent, newUserHandle(userHandle))
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
}
}
} catch (t: Throwable) {
if (t is InvocationTargetException) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
}
} else {
t.printStackTrace()
}
}
}
private fun newUserHandle(userHandle: String): UserHandle? {
try {
val clz = UserHandle::class.java
val all = clz.getDeclaredField(userHandle)
all.isAccessible = true
return all.get(null) as UserHandle
} catch (t: Throwable) {
t.printStackTrace()
}
return null
}
}<file_sep>package com.iflytek.cyber.iot.show.core.launcher
import android.graphics.drawable.Drawable
import com.google.gson.annotations.SerializedName
import com.iflytek.cyber.iot.show.core.model.TemplateApp
open class AppData(
val name: String,
val packageName: String,
val icon: Drawable?,
val iconUrl: String? = null,
val appType: Int = TYPE_PARTY
) {
companion object {
const val TYPE_PARTY = 1
const val TYPE_INTERNAL = 2
const val TYPE_TEMPLATE = 3
}
}
class TemplateAppData(
val source: String?,
name: String?,
icon: String?,
val img: String?,
val template: Int?,
val business: String?,
@SerializedName("is_dark") val isDark: Boolean?,
val type: String?,
val url: String?,
val textIn: String?
) : AppData(name ?: "", source ?: "", null, icon, AppData.TYPE_TEMPLATE) {
companion object {
const val TYPE_TEMPLATE = "TEMPLATE"
const val TYPE_SKILL = "SKILL"
const val TYPE_H5_APP = "H5_APP"
fun fromTemplateApp(templateApp: TemplateApp): TemplateAppData {
return TemplateAppData(
templateApp.source,
templateApp.name,
templateApp.icon,
templateApp.img,
templateApp.template,
templateApp.business,
templateApp.isDark,
templateApp.type,
templateApp.url,
templateApp.textIn
)
}
}
fun toTemplateApp(): TemplateApp {
return TemplateApp(
source,
name,
iconUrl,
img,
template,
business,
isDark,
type,
url,
textIn
)
}
}<file_sep>package com.iflytek.cyber.evs.sdk
/**
* 错误码集合
*/
@Suppress("unused")
object EvsError {
object Code {
const val ERROR_UNKNOWN = -1
// from service side
const val ERROR_WRONG_PARAMS = 400
const val ERROR_AUTH_FAILED = 401
const val ERROR_NO_PERMISSION = 403
const val ERROR_SERVER_INTERNAL = 500
const val ERROR_SERVICE_UNAVAILABLE = 503
const val ERROR_NETWORK_UNREACHABLE = 998
const val ERROR_CLIENT_DISCONNECTED = 999
// from WebSocket protocol, part of https://tools.ietf.org/html/rfc6455#section-7.4
const val ERROR_SERVER_DISCONNECTED = 1005
const val ERROR_INVALID_SOCKET = 1011
const val ERROR_SOCKET_EXCEPTION = 1012
const val ERROR_SOCKET_TIMEOUT = 1013
}
/**
* 授权过期异常
*/
class AuthorizationExpiredException : IllegalArgumentException()
}<file_sep>package com.iflytek.cyber.iot.show.core.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Banner(
val id: String?,
val cover: String?,
val title: String?,
val descriptions: Array<String>?,
val target: String?,
val content: String?
) : Parcelable {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Banner
if (id != other.id) return false
if (cover != other.cover) return false
if (title != other.title) return false
if (descriptions != null) {
if (other.descriptions == null) return false
if (!descriptions.contentEquals(other.descriptions)) return false
} else if (other.descriptions != null) return false
if (target != other.target) return false
if (content != other.content) return false
return true
}
override fun hashCode(): Int {
var result = id?.hashCode() ?: 0
result = 31 * result + (cover?.hashCode() ?: 0)
result = 31 * result + (title?.hashCode() ?: 0)
result = 31 * result + (descriptions?.contentHashCode() ?: 0)
result = 31 * result + (target?.hashCode() ?: 0)
result = 31 * result + (content?.hashCode() ?: 0)
return result
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.ItemViewBinder
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.DeskApi
import com.iflytek.cyber.iot.show.core.fragment.MainFragment2
import com.iflytek.cyber.iot.show.core.model.MainTemplate
import com.iflytek.cyber.iot.show.core.utils.ConfigUtils
import com.iflytek.cyber.iot.show.core.widget.StyledSwitch
import com.kk.taurus.playerbase.utils.NetworkUtils
class RecommendSettingsViewBinder(val onCheckedChangeListener: (Boolean) -> Unit) :
ItemViewBinder<MainTemplate, RecommendSettingsViewBinder.RecommendSettingsHolder>() {
var switchCanClickable = true
override fun onCreateViewHolder(
inflater: LayoutInflater,
parent: ViewGroup
): RecommendSettingsHolder {
val view = inflater.inflate(R.layout.item_recommend_settings, parent, false)
return RecommendSettingsHolder(view)
}
fun canSwitchClickable(recyclerView: RecyclerView, position: Int, isLoading: Boolean) {
if (recyclerView.childCount == 0) {
return
}
val switchItem = recyclerView.layoutManager?.findViewByPosition(position) as? ViewGroup
val stateContent = switchItem?.findViewById<FrameLayout>(R.id.state_content)
stateContent?.isVisible = isLoading
}
override fun onBindViewHolder(holder: RecommendSettingsHolder, item: MainTemplate) {
holder.stateContent.isVisible = !NetworkUtils.isNetConnected(holder.itemView.context) || !switchCanClickable
holder.stateContent.setOnClickListener {
if (!NetworkUtils.isNetConnected(holder.itemView.context) || !switchCanClickable) {
Toast.makeText(holder.itemView.context, "网络连接异常,请重新设置", Toast.LENGTH_SHORT).show()
}
}
val mode = ConfigUtils.getInt(MainFragment2.RECOMMEND_CARD_MODE, DeskApi.MODEL_ADULT)
if (mode == DeskApi.MODEL_ADULT) {
holder.switch.setChecked(false, false)
} else {
holder.switch.setChecked(true, false)
}
holder.switch.setOnCheckedChangeListener(object : StyledSwitch.OnCheckedChangeListener {
override fun onCheckedChange(switch: StyledSwitch, isChecked: Boolean) {
onCheckedChangeListener.invoke(isChecked)
}
})
}
inner class RecommendSettingsHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val switch = itemView.findViewById<StyledSwitch>(R.id.styled_switch)
val stateContent = itemView.findViewById<FrameLayout>(R.id.state_content)
init {
switch.setTrackColor(Color.parseColor("#E9EBED"))
switch.setThumbColor(Color.WHITE)
}
}
}<file_sep>package com.iflytek.cyber.evs.sdk.model
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.annotation.JSONField
class OsResponseBody(
@JSONField(name = "iflyos_meta") val meta: OsMeta,
@JSONField(name = "iflyos_responses") val responses: List<OsResponse>
) {
companion object {
fun fromJSONObject(json: JSONObject): OsResponseBody {
val meta = OsMeta.fromJSONObject(json.getJSONObject("iflyos_meta"))
val respJsonArray = json.getJSONArray("iflyos_responses")
val respList: MutableList<OsResponse> = ArrayList()
for (resp in respJsonArray) {
respList.add(OsResponse.fromJSONObject(resp as JSONObject))
}
return OsResponseBody(meta, respList)
}
}
}
class OsMeta(
@JSONField(name = "trace_id") val traceId: String,
@JSONField(name = "request_id") val requestId: String?,
@JSONField(name = "is_last") val isLast: Boolean
) {
companion object {
fun fromJSONObject(json: JSONObject): OsMeta {
val traceId = json.getString("trace_id")
val requestId = json.getString("request_id")
val isLast = json.getBoolean("is_last")
return OsMeta(traceId, requestId, isLast)
}
}
}
class OsResponse(
@JSONField(name = "header") val header: ResponseHeader,
@JSONField(name = "payload") val payload: JSONObject) {
companion object {
fun fromJSONObject(json: JSONObject): OsResponse {
val headJson = json.getJSONObject("header")
val payloadJson = json.getJSONObject("payload")
return OsResponse(ResponseHeader.fromJSONObject(headJson), payloadJson)
}
}
}
class ResponseHeader(
@JSONField(name = "name") val name: String) {
companion object {
fun fromJSONObject(json: JSONObject): ResponseHeader {
val name = json.getString("name")
return ResponseHeader(name)
}
}
}<file_sep>package com.iflytek.cyber.evs.sdk.agent.impl
import android.annotation.SuppressLint
import android.content.Context
import android.provider.Settings
import com.iflytek.cyber.evs.sdk.agent.Screen
import com.iflytek.cyber.evs.sdk.utils.ScreenUtil
class ScreenImpl(private val context: Context) : Screen() {
override fun getState(): String {
return if (ScreenUtil.isScreenOn(context)) STATE_ON else STATE_OFF
}
override fun setState(state: String): Boolean {
return true
}
override fun getBrightness(): Long {
return ScreenUtil.getBrightness(context)
}
@SuppressLint("MissingPermission")
override fun setBrightness(brightness: Long): Boolean {
try {
ScreenUtil.setBrightness(context, brightness * 255 / 100)
return true
} catch (t: Throwable) {
t.printStackTrace()
}
return false
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.iflytek.cyber.iot.show.core.fragment.SkillSectionFragment
import com.iflytek.cyber.iot.show.core.model.SkillSection
class SkillPagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
private val items = ArrayList<SkillSection>()
fun addItems(items: ArrayList<SkillSection>) {
this.items.clear()
this.items.addAll(items)
}
override fun getItemCount(): Int {
return items.size
}
override fun createFragment(position: Int): Fragment {
val skill = items[position]
return SkillSectionFragment.newInstance(skill)
}
}<file_sep>package com.iflytek.cyber.product.ota
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.PUT
interface OtaApi {
@GET("/ota/client/packages")
@Deprecated("Won't be used in future versions", replaceWith = ReplaceWith("getClientCheckPackages"))
fun getPackages(): Call<List<PackageEntity>>
@PUT("/ota/client/packages")
@Deprecated("Won't be used in future versions")
fun putPackages(@Body report: ReportEntity): Call<Void>
@GET("/ota/client/check/packages")
fun getClientCheckPackages(): Call<List<PackageEntityNew>>
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.graphics.Bitmap
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.CollectionSong
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
class CollectionAlbumAdapter(private val onItemClickListener: (song: CollectionSong) -> Unit) :
RecyclerView.Adapter<CollectionAlbumAdapter.CollectionAlbumHolder>() {
var items = ArrayList<CollectionSong>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CollectionAlbumHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_collection_album, parent, false)
return CollectionAlbumHolder(view)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: CollectionAlbumHolder, position: Int) {
val item = items[position]
holder.title.text = item.name
holder.artist.text = item.artist
val transformer: MultiTransformation<Bitmap> = MultiTransformation(
CenterCrop(),
RoundedCornersTransformation(
holder.itemView.context.resources.getDimensionPixelSize(R.dimen.dp_6), 0
)
)
Glide.with(holder.itemView.context)
.load(item.musicImg)
.transform(transformer)
.into(holder.albumImage)
holder.songContent.setOnClickListener {
onItemClickListener.invoke(item)
}
}
inner class CollectionAlbumHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val songContent: FrameLayout = itemView.findViewById(R.id.song_content)
var title: TextView = itemView.findViewById(R.id.album_title)
var artist: TextView = itemView.findViewById(R.id.album_desc)
val divider = itemView.findViewById<View>(R.id.divider)
val albumImage = itemView.findViewById<ImageView>(R.id.album_image)
}
}<file_sep>package com.iflytek.cyber.iot.show.core.impl.videoplayer
import android.content.Context
import android.os.Build
import android.util.Log
import com.google.android.exoplayer2.Player
import com.iflytek.cyber.evs.sdk.agent.VideoPlayer
import com.kk.taurus.playerbase.player.IPlayer
import com.kk.taurus.playerbase.widget.SuperContainer
import java.net.URLEncoder
class EvsVideoPlayer private constructor(context: Context) : VideoPlayer() {
companion object {
private const val TAG = "EvsVideoPlayer"
private var instance: EvsVideoPlayer? = null
fun get(context: Context?): EvsVideoPlayer {
instance?.let {
return it
} ?: run {
val player = EvsVideoPlayer(context!!)
instance = player
return player
}
}
}
private var player: EvsVideoPlayerInstance? = null
private var volGrowFlag = false
var exitCallback: ExitCallback? = null
private val listener = object : EvsVideoPlayerInstance.Listener {
override fun onPlayerStateChanged(
player: EvsVideoPlayerInstance,
playbackState: Int
) {
Log.d(TAG, "onPlayerStateChanged($playbackState)")
when (playbackState) {
IPlayer.STATE_END, IPlayer.STATE_PLAYBACK_COMPLETE -> {
onCompleted(player.resourceId ?: "")
}
Player.STATE_BUFFERING -> {
// ignore
}
IPlayer.STATE_IDLE, IPlayer.STATE_STOPPED -> {
onStopped(player.resourceId ?: "")
}
IPlayer.STATE_STARTED -> {
if (player.getOffset() > 0) {
onResumed(player.resourceId ?: "")
} else {
onStarted(player.resourceId ?: "")
}
}
IPlayer.STATE_PAUSED -> {
onPaused(player.resourceId ?: "")
}
}
}
override fun onPlayerPositionUpdated(player: EvsVideoPlayerInstance, position: Long) {
onPositionUpdated(player.resourceId ?: "", position)
}
override fun onPlayerError(
player: EvsVideoPlayerInstance,
errorCode: String,
errorMessage: String?
) {
onError(player.resourceId ?: "", errorCode)
}
}
init {
player?.destroy()
player = EvsVideoPlayerInstance()
player?.setListener(listener)
}
private fun getPlayer(): EvsVideoPlayerInstance? {
return player
}
fun setSuperContainer(superContainer: SuperContainer?) {
getPlayer()?.setSuperContainer(superContainer)
}
override fun play(resourceId: String, url: String): Boolean {
val player = getPlayer()
player?.let {
it.resourceId = resourceId
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
var mutableUrl = url
val regex = Regex(pattern = "[^\\p{ASCII}]")
val results = regex.findAll(mutableUrl)
for (result in results) {
mutableUrl = mutableUrl.replace(
result.value, URLEncoder.encode(result.value, "utf-8")
)
}
it.play(mutableUrl)
} else {
it.play(url)
}
onStarted(resourceId)
return true
} ?: run {
return false
}
}
override fun resume(): Boolean {
val player = getPlayer()
player?.resume() ?: run {
return false
}
return true
}
override fun pause(): Boolean {
val player = getPlayer()
player?.pause() ?: run {
return false
}
return true
}
override fun stop(): Boolean {
val player = getPlayer()
player?.stop() ?: run {
return false
}
return true
}
override fun exit(): Boolean {
getPlayer()?.let { player ->
player.stop()
exitCallback?.onRequestExit()
} ?: run {
return false
}
return true
}
fun realStop() {
val player = getPlayer()
player?.stop()
}
override fun seekTo(offset: Long): Boolean {
super.seekTo(offset)
val player = getPlayer()
player?.let {
it.seekTo(offset)
return true
} ?: run {
return false
}
}
override fun getOffset(): Long {
return getPlayer()?.getOffset() ?: 0
}
override fun getDuration(): Long {
return getPlayer()?.getDuration() ?: 0
}
override fun moveToBackground(): Boolean {
getPlayer()?.run {
isAudioBackground = true
synchronized(volGrowFlag) {
volGrowFlag = false
setVolume(EvsVideoPlayerInstance.VOLUME_BACKGROUND)
}
return true
} ?: run {
return false
}
}
override fun moveToForegroundIfAvailable(): Boolean {
getPlayer()?.run {
isAudioBackground = false
synchronized(volGrowFlag) {
volGrowFlag = true
}
setVolume(1f)
return true
} ?: run {
return false
}
}
fun getPlaybackState() : Int? {
return player?.getPlaybackState()
}
interface ExitCallback {
fun onRequestExit()
}
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.graphics.Color
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.AlbumItem
import com.iflytek.cyber.iot.show.core.model.SourceItem
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
import com.iflytek.cyber.iot.show.core.utils.clickWithTrigger
class AlbumSectionContentAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
const val TYPE_1P0 = 0
const val TYPE_1P6 = 1
const val TYPE_0P75 = 2
}
private val albumList = mutableListOf<SourceItem>()
var onItemClickListener: OnItemClickListener? = null
var isDark = false
var ratio = 1f
fun setAlbumList(albumList: List<SourceItem>) {
this.albumList.clear()
this.albumList.addAll(albumList)
}
fun appendAlbumList(albumList: List<SourceItem>) {
this.albumList.addAll(albumList)
}
fun getAlbumItem(position: Int) = if (position < albumList.size) albumList[position] else null
override fun getItemViewType(position: Int): Int {
return when {
ratio < 1 -> TYPE_0P75
ratio == 1f -> TYPE_1P0
else -> TYPE_1P6
}
}
override fun getItemCount(): Int {
return albumList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val holder = when (viewType) {
TYPE_1P6 -> SectionContentHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_single_album_1p6,
parent,
false
)
)
TYPE_1P0 -> SectionContentHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_single_album_1p0,
parent,
false
)
)
else -> SectionContentHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_template_app_single_album_0p75,
parent,
false
)
)
}
holder.itemView.clickWithTrigger {
onItemClickListener?.onItemClick(parent, it, holder.adapterPosition)
}
return holder
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is SectionContentHolder) {
val sourceItem = albumList[position]
if (isDark) {
holder.titleTextView.setTextColor(Color.WHITE)
holder.subTitleTextView.setTextColor(Color.WHITE)
} else {
holder.titleTextView.setTextColor(Color.BLACK)
holder.subTitleTextView.setTextColor(Color.BLACK)
}
holder.indexTextView.text = (position + 1).toString()
holder.titleTextView.text = sourceItem.title
//holder.subTitleTextView.text = albumItem.subtitle
holder.subTitleTextView.isVisible = false
if (!sourceItem.cover.isNullOrEmpty()) {
try {
Glide.with(holder.albumImageView)
.load(sourceItem.cover)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.into(holder.albumImageView)
} catch (t: Throwable) {
t.printStackTrace()
holder.albumImageView.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
holder.albumImageView.setImageResource(R.drawable.bg_default_template_app_2)
}
}
}
}
private class SectionContentHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val albumImageView = itemView.findViewById<com.makeramen.roundedimageview.RoundedImageView>(R.id.album_media_0)
val indexTextView = itemView.findViewById<TextView>(R.id.index_media_0)
val titleTextView = itemView.findViewById<TextView>(R.id.title_media_0)
val subTitleTextView = itemView.findViewById<TextView>(R.id.subtitle_media_0)
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.GroupItem
class MusicAdapter(private val items: List<Pair<String?, List<GroupItem>>>,
private val onItemClickListener: (GroupItem) -> Unit,
private val onMoreClickListener: (String?) -> Unit)
: RecyclerView.Adapter<MusicAdapter.MusicHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MusicHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_category, parent, false)
return MusicHolder(view)
}
override fun getItemCount(): Int {
return items.size
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: MusicHolder, position: Int) {
val item = items[position]
holder.title.text = item.first
val newItems = if (item.second.size > 4) {
item.second.subList(0, 4)
} else {
item.second
}
holder.setAlbumList(newItems, object : AlbumAdapter.OnGroupItemClickListener {
override fun onGroupItemClick(itemView: View, groupItem: GroupItem) {
onItemClickListener.invoke(groupItem)
}
})
holder.moreContent.setOnClickListener {
onMoreClickListener.invoke(item.first)
}
holder.more.text = "全部${item.first}"
}
class MusicHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val title = itemView.findViewById<TextView>(R.id.category_title)
val desc = itemView.findViewById<TextView>(R.id.category_desc)
val albumList = itemView.findViewById<RecyclerView>(R.id.album_list)
val more = itemView.findViewById<TextView>(R.id.more)
val moreContent = itemView.findViewById<LinearLayout>(R.id.more_content)
val adapter = AlbumAdapter()
fun setAlbumList(albumList: List<GroupItem>, onGroupItemClickListener: AlbumAdapter.OnGroupItemClickListener) {
adapter.setGroupList(albumList)
adapter.onGroupItemClickListener = onGroupItemClickListener
this.albumList.adapter = adapter
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat
import com.iflytek.cyber.iot.show.core.R
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
class BoxedVertical : View {
/**
* The min value of progress value.
*/
private var mMin = MIN
/**
* The Maximum value that this SeekArc can be set to
*/
private var mMax = MAX
var isEnable = true
/**
* mTouchDisabled touches will not move the slider
* only swipe motion will activate it
*/
private var mTouchDisabled = true
private var mProgressSweep = 0f
private var mProgressPaint: Paint? = null
private var mOnValuesChangeListener: OnValuesChangeListener? = null
private var customBackgroundColor: Int = 0
private var mDefaultValue: Int = 0
private val mPaint = Paint()
private var mPath: Path? = null
var value: Int = 0
private set
var isPreventTouch = false
var max: Int = MAX
get() = mMax
set(value) {
if (value <= mMin)
throw IllegalArgumentException("Max should not be less than zero")
this.mMax = value
field = value
}
var min: Int = MIN
get() = mMin
set(value) {
if (value >= max)
throw IllegalArgumentException("Min should not be bigger than max value")
mMin = value
field = value
}
/**
* The corner radius of the view.
*/
var cornerRadius: Int = 10
set(value) {
field = value
if (width > 0 && height > 0) {
mPath = Path()
mPath?.addRoundRect(RectF(0f, 0f, width.toFloat(), height.toFloat()),
field.toFloat(), field.toFloat(), Path.Direction.CCW)
invalidate()
}
}
var defaultValue: Int
get() = mDefaultValue
set(mDefaultValue) {
if (mDefaultValue > mMax)
throw IllegalArgumentException("Default value should not be bigger than max value.")
this.mDefaultValue = mDefaultValue
}
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
isClickable = true
isFocusable = true
// Defaults, may need to link this into theme settings
var progressColor = ContextCompat.getColor(context, R.color.slide_progress)
customBackgroundColor = ContextCompat.getColor(context, R.color.slide_background)
customBackgroundColor = ContextCompat.getColor(context, R.color.slide_background)
mDefaultValue = mMax / 2
if (attrs != null) {
val a = context.obtainStyledAttributes(attrs,
R.styleable.BoxedVertical, 0, 0)
mMax = a.getInteger(R.styleable.BoxedVertical_bv_max, mMax)
mMin = a.getInteger(R.styleable.BoxedVertical_bv_min, mMin)
mDefaultValue = a.getInteger(R.styleable.BoxedVertical_bv_defaultValue, mDefaultValue)
value = a.getInteger(R.styleable.BoxedVertical_bv_points, mDefaultValue)
cornerRadius = a.getDimensionPixelSize(R.styleable.BoxedVertical_bv_cornerRadius, cornerRadius)
progressColor = a.getColor(R.styleable.BoxedVertical_bv_progressColor, progressColor)
customBackgroundColor = a.getColor(R.styleable.BoxedVertical_bv_backgroundColor, customBackgroundColor)
isEnable = a.getBoolean(R.styleable.BoxedVertical_bv_enabled, isEnable)
mTouchDisabled = a.getBoolean(R.styleable.BoxedVertical_bv_touchDisabled, mTouchDisabled)
a.recycle()
}
// range check
value = if (value > mMax) mMax else value
value = if (value < mMin) mMin else value
val progressPaint = Paint()
progressPaint.color = progressColor
progressPaint.isAntiAlias = true
progressPaint.style = Paint.Style.STROKE
mProgressPaint = progressPaint
mPaint.alpha = 255
mPaint.color = customBackgroundColor
mPaint.isAntiAlias = true
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mProgressPaint?.strokeWidth = h.toFloat()
mPath = Path()
mPath?.addRoundRect(RectF(0f, 0f, width.toFloat(), height.toFloat()),
cornerRadius.toFloat(), cornerRadius.toFloat(), Path.Direction.CCW)
}
override fun onDraw(canvas: Canvas) {
canvas.translate(0f, 0f)
mPath?.let { path ->
canvas.clipPath(path)
}
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), mPaint)
mProgressPaint?.let { paint ->
if (isInEditMode) {
val progress = getPointsByValue(defaultValue)
//convert min-max range to progress
val sweep = ((progress - mMin) * width / (mMax - mMin)).toFloat()
canvas.drawLine((width / 2).toFloat(), height.toFloat(),
(width / 2).toFloat(), sweep, paint)
} else {
canvas.drawLine((width / 2).toFloat(), height.toFloat(),
(width / 2).toFloat(), mProgressSweep, paint)
}
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
if (isEnable) {
this.parent.requestDisallowInterceptTouchEvent(true)
if (!isPreventTouch)
when (event.action) {
MotionEvent.ACTION_DOWN -> {
mOnValuesChangeListener?.onStartTrackingTouch(this)
if (!mTouchDisabled)
updateOnTouch(event)
}
MotionEvent.ACTION_MOVE -> updateOnTouch(event)
MotionEvent.ACTION_UP -> {
updateOnTouch(event)
mOnValuesChangeListener?.onStopTrackingTouch(this)
isPressed = false
this.parent.requestDisallowInterceptTouchEvent(false)
}
MotionEvent.ACTION_CANCEL -> {
mOnValuesChangeListener?.onStopTrackingTouch(this)
isPressed = false
this.parent.requestDisallowInterceptTouchEvent(false)
}
}
return true
}
return false
}
/**
* Update the UI components on touch events.
*
* @param event MotionEvent
*/
private fun updateOnTouch(event: MotionEvent) {
isPressed = true
val mTouch = convertTouchEventPoint(event.y)
val progress = mTouch.roundToInt()
updateProgress(height - progress)
}
private fun convertTouchEventPoint(yPos: Float): Float {
return min(height.toFloat(), max(0f, yPos))
}
private fun updateProgress(progress: Int) {
val realProgress = 1f * max(0, min(height, progress))
mProgressSweep = realProgress
//reverse value because progress is descending
mProgressSweep = height - mProgressSweep
//convert progress to min-max range
value = (realProgress / height * (mMax - mMin) + mMin).toInt()
mOnValuesChangeListener?.onPointsChanged(this, value, true)
if (width > 0 && height > 0) {
mPath = Path()
mPath?.addRoundRect(RectF(0f, 0f, width.toFloat(), height.toFloat()),
cornerRadius.toFloat(), cornerRadius.toFloat(), Path.Direction.CCW)
invalidate()
}
}
/**
* Gets a value, converts it to progress for the seekBar and updates it.
* @param value The value given
*/
private fun updateProgressByValue(value: Int, fromTouch: Boolean = true) {
//convert min-max range to progress
mProgressSweep = ((value - mMin) * height / (mMax - mMin)).toFloat()
//reverse value because progress is descending
mProgressSweep = height - mProgressSweep
mOnValuesChangeListener?.onPointsChanged(this, value, fromTouch)
if (width > 0 && height > 0 && mPath == null) {
mPath = Path()
mPath?.addRoundRect(RectF(0f, 0f, width.toFloat(), height.toFloat()),
cornerRadius.toFloat(), cornerRadius.toFloat(), Path.Direction.CCW)
}
invalidate()
}
fun setValue(value: Int) {
this.value = value
updateProgressByValue(getPointsByValue(value), false)
}
private fun getPointsByValue(value: Int): Int {
return max(mMin, min(mMax, value))
}
interface OnValuesChangeListener {
/**
* Notification that the point value has changed.
*
* @param boxedPoints The SwagPoints view whose value has changed
* @param points The current point value.
* @param fromTouch Is this callback from touch event
*/
fun onPointsChanged(boxedPoints: BoxedVertical, points: Int, fromTouch: Boolean)
fun onStartTrackingTouch(boxedPoints: BoxedVertical)
fun onStopTrackingTouch(boxedPoints: BoxedVertical)
}
fun setOnBoxedPointsChangeListener(onValuesChangeListener: OnValuesChangeListener) {
mOnValuesChangeListener = onValuesChangeListener
}
companion object {
private val TAG = BoxedVertical::class.java.simpleName
private const val MAX = 100
private const val MIN = 0
}
}<file_sep>package com.iflytek.cyber.iot.show.core.template
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import android.widget.Toast
import androidx.core.view.isVisible
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.iflytek.cyber.iot.show.core.EngineService
import com.iflytek.cyber.iot.show.core.R
class CustomTemplateView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
companion object {
private const val TAG = "CustomTemplateView"
}
private val webView: WebView = WebView(context)
private val loadingAnimation = LottieAnimationView(context)
var onClickBackListener: OnClickListener? = null
var overrideUrlLoadingCallback: OverrideUrlLoadingCallback? = null
init {
addView(webView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
val loadingSize = resources.getDimensionPixelSize(R.dimen.dp_40)
val loadingLp = LayoutParams(loadingSize, loadingSize)
loadingLp.gravity = Gravity.CENTER
addView(loadingAnimation, loadingLp)
loadingAnimation.setAnimation(R.raw.animation_loading_l)
loadingAnimation.repeatMode = LottieDrawable.RESTART
loadingAnimation.repeatCount = LottieDrawable.INFINITE
loadingAnimation.post {
loadingAnimation.playAnimation()
}
webView.settings.apply {
javaScriptEnabled = false
}
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
val url =
request?.url?.toString() ?: return super.shouldOverrideUrlLoading(view, request)
return shouldOverrideUrlLoading(view, url)
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
Log.d(TAG, "WebView load $url")
if (url.isNullOrEmpty())
return super.shouldOverrideUrlLoading(view, url)
return when {
url == "close://now" -> {
onClickBackListener?.onClick(this@CustomTemplateView)
true
}
url.startsWith("showcore://") -> {
try {
val uri = Uri.parse(url)
when {
uri.host == "text_in" -> {
if (uri.queryParameterNames.contains("query")) {
val query = uri.getQueryParameter("query")
val intent = Intent(context, EngineService::class.java)
intent.action = EngineService.ACTION_SEND_TEXT_IN
intent.putExtra(EngineService.EXTRA_QUERY, query)
context.startService(intent)
}
}
}
} catch (t: Throwable) {
t.printStackTrace()
Toast.makeText(context, "不支持的 url", Toast.LENGTH_SHORT).show()
}
true
}
else -> overrideUrlLoadingCallback?.shouldOverrideUrlLoading(view, url)
?: super.shouldOverrideUrlLoading(view, url)
}
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
if (loadingAnimation.isVisible && loadingAnimation.alpha == 1f)
loadingAnimation.animate()
.alpha(0f)
.setDuration(500)
.withEndAction {
loadingAnimation.isVisible = false
}
.start()
}
}
webView.webChromeClient = object : WebChromeClient() {
}
}
fun loadHtmlText(html: String) {
webView.loadData(html, "text/html; charset=UTF-8",null)
}
class Builder(private val context: Context) {
private var html: String? = null
private var onClickListener: OnClickListener? = null
private var overrideUrlLoadingCallback: OverrideUrlLoadingCallback? = null
fun onClickBackListener(onClickListener: OnClickListener?): Builder {
this.onClickListener = onClickListener
return this
}
fun overrideUrlLoadingCallback(overrideUrlLoadingCallback: OverrideUrlLoadingCallback?): Builder {
this.overrideUrlLoadingCallback = overrideUrlLoadingCallback
return this
}
fun setHtml(html: String): Builder {
this.html = html
return this
}
fun build(): CustomTemplateView {
val view = CustomTemplateView(context)
html?.let {
view.loadHtmlText(it)
}
view.onClickBackListener = onClickListener
view.overrideUrlLoadingCallback = overrideUrlLoadingCallback
return view
}
}
fun destroy() {
webView.destroy()
}
interface OverrideUrlLoadingCallback {
fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean
}
}<file_sep>package com.iflytek.cyber.iot.show.core
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import android.service.dreams.DreamService
import android.widget.ImageView
import android.widget.TextView
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.iflytek.cyber.evs.sdk.auth.AuthDelegate
import com.iflytek.cyber.iot.show.core.api.WeatherApi
import com.iflytek.cyber.iot.show.core.model.Weather
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.ref.SoftReference
import java.text.SimpleDateFormat
import java.util.*
class ShowCoreDream : DreamService(), AMapLocationListener {
companion object {
private const val CHANGE_WEATHER_TIME = 3L * 60 * 60 * 1000 // 检查天气预报时间间隔
}
private var tvTime: TextView? = null
private var tvDateTime: TextView? = null
private var tvWeather: TextView? = null
private var ivWeather: ImageView? = null
private var tvSlogan: TextView? = null
private val timerHandler = TimerHandler(this)
private var mLocationClient: AMapLocationClient? = null
private val locationRunnable = Runnable {
mLocationClient?.startLocation()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
setContentView(R.layout.layout_dream)
tvTime = findViewById(R.id.time)
tvDateTime = findViewById(R.id.date_time)
tvWeather = findViewById(R.id.weather_text)
ivWeather = findViewById(R.id.weather_icon)
tvSlogan = findViewById(R.id.slogan)
setDateAndTime()
timerHandler.sendEmptyMessageDelayed(0, 1000)
setupLocation()
}
private fun setupLocation() {
val locationClient = AMapLocationClient(baseContext)
val locationOption = AMapLocationClientOption()
locationClient.setLocationListener(this)
locationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
locationOption.isOnceLocation = true
locationClient.setLocationOption(locationOption)
locationClient.startLocation()
mLocationClient = locationClient
}
override fun onLocationChanged(location: AMapLocation?) {
location?.let {
val tvWeather = tvWeather ?: return
if (it.errorCode == 0) {
loadWeather(it)
}
tvWeather.postDelayed(locationRunnable, CHANGE_WEATHER_TIME)
}
}
private fun loadWeather(location: AMapLocation) {
AuthDelegate.getAuthResponseFromPref(baseContext)?.let {
val currentLocation = (String.format(Locale.CHINESE, "%.2f", location.longitude)
+ "," + String.format(Locale.CHINESE, "%.2f", location.latitude))
getWeatherApi()?.getWeather(currentLocation)?.enqueue(object : Callback<Weather> {
override fun onFailure(call: Call<Weather>, t: Throwable) {
t.printStackTrace()
tvWeather?.text = null
ivWeather?.setImageDrawable(null)
}
@SuppressLint("SetTextI18n")
override fun onResponse(call: Call<Weather>, response: Response<Weather>) {
if (response.isSuccessful) {
response.body()?.let { weather ->
tvWeather?.text = "${weather.temperature}℃ ${weather.description}"
ivWeather?.let { imageView ->
Glide.with(imageView)
.asDrawable()
.load(weather.icon)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
}
} else {
tvWeather?.text = null
ivWeather?.setImageDrawable(null)
}
}
})
}?:run {
tvWeather?.text = null
ivWeather?.setImageDrawable(null)
}
}
private fun setDateAndTime() {
val tvTime = tvTime ?: return
val tvDate = tvDateTime ?: return
val date = Date()
val dateFormat = SimpleDateFormat("MM月dd日 EEEE", Locale.getDefault())
tvDate.text = dateFormat.format(date)
val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
tvTime.text = timeFormat.format(date)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
tvTime = null
tvSlogan = null
tvWeather = null
ivWeather = null
tvDateTime = null
timerHandler.removeMessages(0)
}
private fun getWeatherApi(): WeatherApi? {
return CoreApplication.from(baseContext).createApi(WeatherApi::class.java)
}
private class TimerHandler internal constructor(
service: ShowCoreDream,
private val reference: SoftReference<ShowCoreDream> =
SoftReference(service)
) : Handler() {
override fun handleMessage(msg: Message) {
val service = reference.get()
if (service != null) {
service.setDateAndTime()
sendEmptyMessageDelayed(0, 1000)
}
}
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.utils
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.provider.Settings
import android.location.LocationManager.GPS_PROVIDER
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
object GpsUtils {
private fun openGpsSettings(context: Context) {
context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
}
fun checkGpsEnable(context: Context): Boolean {
val manager =
ContextCompat.getSystemService(context, LocationManager::class.java)
?: return true // 跳过检查
// 如果不支持 GPS 那也不强求了
return !manager.allProviders.contains(GPS_PROVIDER) || manager.isProviderEnabled(GPS_PROVIDER)
}
fun requestGps(context: Context) {
AlertDialog.Builder(context)
.setPositiveButton("开启") { _, _ -> openGpsSettings(context) }
.setNegativeButton("取消", null)
.setMessage("开启位置信息,获取更准确的天气信息")
.show()
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.ShapeDrawable
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.iflytek.cyber.iot.show.core.R
/**
* DividerItemDecoration is a [RecyclerView.ItemDecoration] that can be used as a divider
* between result of a [LinearLayoutManager]. It supports both [HORIZONTAL] and
* [VERTICAL] orientations.
*
* <pre>
* mDividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
* mLayoutManager.getOrientation());
* recyclerView.addItemDecoration(mDividerItemDecoration);
</pre> *
*/
class DividerItemDecoration
/**
* Creates a divider [RecyclerView.ItemDecoration] that can be used with a
* [LinearLayoutManager].
*
* @param context Current context, it will be used to access resources.
* @param orientation Divider orientation. Should be [HORIZONTAL] or [VERTICAL].
*/
(context: Context, orientation: Int) : RecyclerView.ItemDecoration() {
private var mDivider: Drawable? = null
/**
* Current orientation. Either [HORIZONTAL] or [VERTICAL].
*/
private var mOrientation: Int = 0
private val mBounds = Rect()
private var padding: Rect? = null
var drawable: Drawable?
/**
* @return the [Drawable] for this divider.
*/
get() = mDivider
/**
* Sets the [Drawable] for this divider.
*
* @param drawable Drawable that should be used as a divider.
*/
set(drawable) {
if (drawable == null) {
throw IllegalArgumentException("Drawable cannot be null.")
}
mDivider = drawable
}
init {
val a = context.obtainStyledAttributes(ATTRS)
mDivider = a.getDrawable(0)
if (mDivider == null) {
Log.w(TAG, "@android:attr/listDivider was not set in the theme used for this " + "DividerItemDecoration. Please set that attribute all call setDrawable()")
}
a.recycle()
setOrientation(orientation)
}
/**
* Sets the orientation for this divider. This should be called if
* [RecyclerView.LayoutManager] changes orientation.
*
* @param orientation [HORIZONTAL] or [VERTICAL]
*/
@Suppress("MemberVisibilityCanBePrivate")
fun setOrientation(orientation: Int) {
if (orientation != HORIZONTAL && orientation != VERTICAL) {
throw IllegalArgumentException(
"Invalid orientation. It should be either HORIZONTAL or VERTICAL")
}
mOrientation = orientation
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (parent.layoutManager == null || mDivider == null) {
return
}
if (mOrientation == VERTICAL) {
drawVertical(c, parent)
} else {
drawHorizontal(c, parent)
}
}
private fun drawVertical(canvas: Canvas, parent: RecyclerView) {
canvas.save()
mDivider?.let { divider ->
val left: Int
val right: Int
val paddingLeft = padding?.left ?: 0
val paddingRight = padding?.right ?: 0
if (parent.clipToPadding) {
left = parent.paddingLeft + paddingLeft
right = parent.width - parent.paddingRight - paddingRight
canvas.clipRect(left, parent.paddingTop, right,
parent.height - parent.paddingBottom)
} else {
left = paddingLeft
right = parent.width - paddingRight
}
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
parent.getDecoratedBoundsWithMargins(child, mBounds)
val bottom = mBounds.bottom + Math.round(child.translationY)
val top = bottom - divider.intrinsicHeight
divider.setBounds(left, top, right, bottom)
// Log.d(TAG, "draw($left, $top, $right, $bottom)")
divider.draw(canvas)
}
}
canvas.restore()
}
private fun drawHorizontal(canvas: Canvas, parent: RecyclerView) {
canvas.save()
mDivider?.let { divider ->
val top: Int
val bottom: Int
val paddingTop = padding?.top ?: 0
val paddingBottom = padding?.bottom ?: 0
if (parent.clipToPadding) {
top = parent.paddingTop + paddingTop
bottom = parent.height - parent.paddingBottom - paddingBottom
canvas.clipRect(parent.paddingLeft, top,
parent.width - parent.paddingRight, bottom)
} else {
top = paddingTop
bottom = parent.height - paddingBottom
}
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
parent.layoutManager?.getDecoratedBoundsWithMargins(child, mBounds)
val right = mBounds.right + Math.round(child.translationX)
val left = right - divider.intrinsicWidth
divider.setBounds(left, top, right, bottom)
// Log.d(TAG, "draw($left, $top, $right, $bottom)")
divider.draw(canvas)
}
}
canvas.restore()
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView,
state: RecyclerView.State) {
mDivider?.let { divider ->
if (mOrientation == VERTICAL) {
outRect.set(0, 0, 0, divider.intrinsicHeight)
} else {
outRect.set(0, 0, divider.intrinsicWidth, 0)
}
} ?: run {
outRect.set(0, 0, 0, 0)
return
}
}
companion object {
const val HORIZONTAL = LinearLayout.HORIZONTAL
const val VERTICAL = LinearLayout.VERTICAL
private const val TAG = "DividerItem"
private val ATTRS = intArrayOf(android.R.attr.listDivider)
}
@Suppress("unused")
class Builder(private val context: Context) {
private var orientation = LinearLayoutManager.VERTICAL
private val padding = Rect()
private var dividerColor: Int? = null
private var dividerWidth = context.resources.getDimensionPixelSize(R.dimen.dp_1)
fun setOrientation(orientation: Int): Builder {
this.orientation = orientation
return this
}
fun setPadding(padding: Int): Builder {
this.padding.top = padding
this.padding.bottom = padding
this.padding.left = padding
this.padding.right = padding
return this
}
fun setPaddingLeft(padding: Int): Builder {
this.padding.left = padding
return this
}
fun setPaddingRight(padding: Int): Builder {
this.padding.right = padding
return this
}
fun setPaddingTop(padding: Int): Builder {
this.padding.top = padding
return this
}
fun setPaddingBottom(padding: Int): Builder {
this.padding.bottom = padding
return this
}
fun setDividerColor(dividerColor: Int): Builder {
this.dividerColor = dividerColor
return this
}
fun setDividerWidth(width: Int): Builder {
this.dividerWidth = width
return this
}
fun build(): DividerItemDecoration {
val decoration = DividerItemDecoration(context, orientation)
dividerColor?.let { color ->
val drawable = GradientDrawable()
drawable.setColor(color)
if (orientation == LinearLayoutManager.VERTICAL) {
drawable.setSize(0, dividerWidth)
} else {
drawable.setSize(dividerWidth, 0)
}
decoration.drawable = drawable
}
decoration.padding = padding
return decoration
}
}
}
<file_sep>package com.iflytek.cyber.iot.show.core.impl.interceptor
import com.alibaba.fastjson.JSONObject
import com.iflytek.cyber.evs.sdk.agent.Interceptor
class EvsInterceptor private constructor() : Interceptor() {
companion object {
private var interceptor: EvsInterceptor? = null
fun get(): EvsInterceptor {
interceptor?.let {
return it
}
val newInterceptor = EvsInterceptor()
interceptor = newInterceptor
return newInterceptor
}
}
private var transferSemanticCallback: ((payload: JSONObject) -> Unit)? = null
private var customCallback: ((payload: JSONObject) -> Unit)? = null
fun transferSemantic(callback: (payload: JSONObject) -> Unit): EvsInterceptor {
transferSemanticCallback = callback
return this
}
fun custom(callback: (payload: JSONObject) -> Unit): EvsInterceptor {
customCallback = callback
return this
}
override fun onResponse(name: String, payload: JSONObject) {
when (name) {
NAME_AIUI -> {
}
NAME_CUSTOM -> {
customCallback?.invoke(payload)
}
NAME_TRANSFER_SEMANTIC -> {
transferSemanticCallback?.invoke(payload)
}
}
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.bumptech.glide.request.transition.Transition
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.adapter.TemplateAppMediaAdapter
import com.iflytek.cyber.iot.show.core.api.AppApi
import com.iflytek.cyber.iot.show.core.impl.prompt.PromptManager
import com.iflytek.cyber.iot.show.core.model.MediaItem
import com.iflytek.cyber.iot.show.core.model.TemplateApp
import com.iflytek.cyber.iot.show.core.model.XmlyQueryResponse
import com.iflytek.cyber.iot.show.core.utils.OnItemClickListener
import com.iflytek.cyber.iot.show.core.widget.StyledProgressDialog
import com.kk.taurus.playerbase.utils.NetworkUtils
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
class TemplateXmlyAlbumFragment : BaseFragment() {
companion object {
private const val LIMIT = 20
fun newInstance(
templateApp: TemplateApp?,
albumId: String?,
name: String?
): TemplateXmlyAlbumFragment {
val fragment = TemplateXmlyAlbumFragment()
fragment.templateApp = templateApp
fragment.albumId = albumId
fragment.name = name
return fragment
}
}
private var templateApp: TemplateApp? = null
private var albumId: String? = null
private var name: String? = null
private var page = 1
private var backCount = 0
private var ivBack: ImageView? = null
private var ivIcon: ImageView? = null
private var ivBackground: ImageView? = null
private var recyclerView: RecyclerView? = null
private var tvTitle: TextView? = null
private var errorContainer: View? = null
private var tvError: TextView? = null
private var errorRetry: View? = null
private var tvRetry: TextView? = null
private var loading: LottieAnimationView? = null
private var loadingBottom: LottieAnimationView? = null
private var progressDialog: StyledProgressDialog? = null
private val mediaAdapter = TemplateAppMediaAdapter()
private var isLoading = false
private var isLoadComplete = false
private val onScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (isLoadComplete || isLoading) return
(recyclerView.layoutManager as? LinearLayoutManager)?.let {
if (it.findLastCompletelyVisibleItemPosition() == it.findLastVisibleItemPosition() &&
recyclerView.adapter?.itemCount == it.findLastVisibleItemPosition() + 1
) {
page++
getAlbum()
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.fragment_template_app_media_list_fragment,
container,
false
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<View>(R.id.back)?.setOnClickListener {
if (backCount != 0)
return@setOnClickListener
backCount++
pop()
}
ivBack = view.findViewById(R.id.iv_back)
ivIcon = view.findViewById(R.id.iv_icon)
ivBackground = view.findViewById(R.id.background)
recyclerView = view.findViewById(R.id.recycler_view)
loading = view.findViewById(R.id.loading)
loadingBottom = view.findViewById(R.id.loading_bottom)
tvTitle = view.findViewById(R.id.title)
tvRetry = view.findViewById(R.id.tv_retry)
tvError = view.findViewById(R.id.tv_error)
errorContainer = view.findViewById(R.id.error_container)
errorRetry = view.findViewById(R.id.error_retry)
errorRetry?.setOnClickListener {
if (!isLoading) {
page = 1
getAlbum()
}
}
recyclerView?.addOnScrollListener(onScrollListener)
recyclerView?.adapter = mediaAdapter
mediaAdapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: ViewGroup, itemView: View, position: Int) {
if (isAdded && context != null && !NetworkUtils.isNetConnected(context)) {
PromptManager.play(PromptManager.NETWORK_LOST)
return
}
mediaAdapter.getMediaItem(position)?.let { mediaItem ->
postPlay(mediaItem)
}
}
}
tvTitle?.text = name
applyTheme(templateApp?.isDark != false)
loadAppIcon()
loadBackground()
getAlbum()
}
override fun onSupportVisible() {
super.onSupportVisible()
backCount = 0
}
override fun onDestroy() {
super.onDestroy()
recyclerView?.removeOnScrollListener(onScrollListener)
}
private fun applyTheme(isDark: Boolean) {
ivBack?.imageTintList = ColorStateList.valueOf(if (isDark) Color.WHITE else Color.BLACK)
tvTitle?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
mediaAdapter.isDark = isDark
if (mediaAdapter.itemCount != 0) {
mediaAdapter.notifyDataSetChanged()
}
tvError?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
tvRetry?.setTextColor(if (isDark) Color.WHITE else Color.BLACK)
errorRetry?.setBackgroundResource(
if (isDark) R.drawable.bg_round_border_white_36dp
else R.drawable.bg_round_border_black_36dp
)
}
private fun loadBackground() {
val templateApp = templateApp ?: return
ivBackground?.let { imageView ->
val url = templateApp.img
if (url.isNullOrEmpty())
return
try {
Uri.parse(url)?.let { uri ->
Glide.with(imageView)
.load(uri)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
private fun loadAppIcon() {
val templateApp = templateApp ?: return
if (!templateApp.icon.isNullOrEmpty()) {
try {
Uri.parse(templateApp.icon)?.let { uri ->
ivIcon?.let { imageView ->
Glide.with(imageView)
.load(uri)
.placeholder(R.drawable.bg_default_template_app_2)
.error(R.drawable.bg_default_template_app_2)
.transition(
DrawableTransitionOptions.with(
DrawableCrossFadeFactory.Builder()
.setCrossFadeEnabled(true).build()
)
)
.into(imageView)
}
} ?: run {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} catch (t: Throwable) {
t.printStackTrace()
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
} else {
ivIcon?.setImageResource(R.drawable.bg_default_template_app_2)
}
}
private fun hideLoading() {
if (isRemoving || isDetached)
return
context ?: return
if (loading?.isVisible == true) {
loading?.pauseAnimation()
loading?.isVisible = false
}
if (loadingBottom?.isVisible == true) {
loadingBottom?.pauseAnimation()
loadingBottom?.isVisible = false
}
}
private fun showLoading() {
if (isRemoving || isDetached)
return
context ?: return
if (page == 1) {
loading?.isVisible = true
loading?.repeatCount = LottieDrawable.INFINITE
loading?.repeatMode = LottieDrawable.RESTART
loading?.playAnimation()
} else {
loadingBottom?.isVisible = true
loadingBottom?.repeatCount = LottieDrawable.INFINITE
loadingBottom?.repeatMode = LottieDrawable.RESTART
loadingBottom?.playAnimation()
}
}
private fun showProgress(title: String, message: String? = null) {
if (isRemoving || isDetached)
return
context ?: return
progressDialog = StyledProgressDialog.Builder()
.setTitle(title)
.setMessage(message)
.show(fragmentManager)
}
private fun dismissProgress() {
if (isRemoving || isDetached)
return
context ?: return
progressDialog?.let {
it.dismiss()
progressDialog = null
}
}
private fun showError(message: String?, showRetry: Boolean = true) {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = false
errorContainer?.isVisible = true
errorRetry?.isVisible = showRetry
tvError?.text = message
}
private fun hideError() {
if (isRemoving || isDetached)
return
context ?: return
recyclerView?.isVisible = true
errorContainer?.isVisible = false
}
private fun getAlbum() {
val albumId = albumId ?: return
isLoading = true
showLoading()
hideError()
val json = JSONObject()
json["id"] = albumId
json["page"] = page
json["limit"] = LIMIT
val body = RequestBody.create(
MediaType.parse("application/json"),
json.toString()
)
getAppApi()?.getXmlyQuery(body)?.enqueue(object : Callback<XmlyQueryResponse> {
override fun onFailure(call: Call<XmlyQueryResponse>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
isLoading = false
hideLoading()
if (t is UnknownHostException) {
showError("Ooooops,请检查网络后重试")
} else {
showError("请求出错,请稍后重试")
}
}
override fun onResponse(
call: Call<XmlyQueryResponse>,
response: Response<XmlyQueryResponse>
) {
if (isRemoving || isDetached)
return
context ?: return
if (response.isSuccessful) {
hideLoading()
response.body()?.let { queryResponse ->
this@TemplateXmlyAlbumFragment.albumId = queryResponse.albumId
val mediaList = mutableListOf<MediaItem>()
var firstCover: String? = null
for (index in 0 until (queryResponse.result?.size ?: 0)) {
queryResponse.result?.get(index)?.let { mediaItem ->
if (firstCover.isNullOrEmpty()) {
firstCover = mediaItem.cover
}
mediaList.add(mediaItem)
}
}
if (mediaList.size < LIMIT) {
isLoadComplete = true
}
if (page == 1) {
when {
mediaList.isEmpty() -> {
hideLoading()
showError("Ooooops,找不到结果", false)
}
firstCover.isNullOrEmpty() -> {
mediaAdapter.setMediaList(mediaList)
mediaAdapter.notifyDataSetChanged()
hideLoading()
}
else -> Glide.with(this@TemplateXmlyAlbumFragment)
.asBitmap()
.load(firstCover)
.into(object : CustomTarget<Bitmap>() {
override fun onLoadFailed(errorDrawable: Drawable?) {
super.onLoadFailed(errorDrawable)
loading?.pauseAnimation()
loading?.isVisible = false
}
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?
) {
val ratio =
1f * resource.width / resource.height
mediaAdapter.ratio = ratio
recyclerView?.let { recyclerView ->
recyclerView.post {
when {
ratio <= 1f -> {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 5
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
5
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_26
),
recyclerView.paddingBottom
)
}
ratio > 1f -> {
(recyclerView.layoutManager as? GridLayoutManager)?.apply {
spanCount = 3
}
?: run {
recyclerView.layoutManager =
GridLayoutManager(
context,
3
)
}
recyclerView.setPadding(
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingTop,
recyclerView.resources.getDimensionPixelSize(
R.dimen.dp_24
),
recyclerView.paddingBottom
)
}
}
hideLoading()
mediaAdapter.setMediaList(mediaList)
mediaAdapter.notifyDataSetChanged()
}
}
}
override fun onLoadCleared(placeholder: Drawable?) {
}
})
}
} else {
mediaAdapter.appendMediaList(mediaList)
mediaAdapter.notifyDataSetChanged()
hideLoading()
}
} ?: run {
hideLoading()
}
} else {
hideLoading()
}
}
})
}
private fun postPlay(mediaItem: MediaItem) {
val audioId = mediaItem.id ?: return
val sourceType = mediaItem.source ?: templateApp?.source ?: return
val albumId = mediaItem.albumId ?: albumId ?: return
showProgress(getString(R.string.loading), getString(R.string.please_wait))
val json = JSONObject()
json["audio_id"] = audioId
json["source_type"] = sourceType
json["album_id"] = albumId
val requestBody = RequestBody.create(
MediaType.parse("application/json"),
json.toString()
)
getAppApi()?.postPlayMedia(requestBody)?.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
if (isRemoving || isDetached)
return
context ?: return
dismissProgress()
Toast.makeText(context, "请求出错", Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (isRemoving || isDetached)
return
context ?: return
dismissProgress()
if (response.isSuccessful) {
Toast.makeText(context, "开始播放", Toast.LENGTH_SHORT).show()
} else {
response.errorBody()?.let { errorBody ->
val errorString = errorBody.string()
val errorJson = org.json.JSONObject(errorString)
if (errorJson.has("message")) {
Toast.makeText(
context,
errorJson.optString("message"),
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(context, "播放失败", Toast.LENGTH_SHORT).show()
}
errorBody.close()
} ?: run {
Toast.makeText(context, "播放失败", Toast.LENGTH_SHORT).show()
}
}
}
})
}
private fun getAppApi(): AppApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(AppApi::class.java)
}
}<file_sep>/*
* Copyright (C) 2019 iFLYTEK CO.,LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iflytek.cyber.iot.show.core.model
object ActionConstant {
private const val ACTION_PREFIX = "com.iflytek.cyber.iot.show.core.action"
const val ACTION_VOLUME_CHANGE = "$ACTION_PREFIX.VOLUME_CHANGE"
const val ACTION_CLIENT_DIALOG_STATE_CHANGE = "$ACTION_PREFIX.CLIENT_DIALOG_STATE_CHANGE"
const val ACTION_CLIENT_MEDIA_STATE_CHANGE = "$ACTION_PREFIX.CLIENT_MEDIA_STATE_CHANGE"
const val ACTION_CLIENT_ALERT_STATE_CHANGE = "$ACTION_PREFIX.CLIENT_ALERT_STATE_CHANGE"
const val ACTION_CLIENT_MEDIA_POSITION_UPDATED = "$ACTION_PREFIX.CLIENT_MEDIA_POSITION_UPDATED"
const val ACTION_CLIENT_INTER_MEDIA_TEXT = "$ACTION_PREFIX.CLIENT_INTER_MEDIA_TEXT"
const val ACTION_CLIENT_RENDER_TEMPLATE = "$ACTION_PREFIX.CLIENT_RENDER_TEMPLATE"
const val ACTION_CLIENT_RENDER_PLAYER_INFO = "$ACTION_PREFIX.CLIENT_RENDER_PLAYER_INFO"
const val ACTION_CLIENT_CLEAR_TEMPLATE = "$ACTION_PREFIX.CLIENT_CLEAR_TEMPLATE"
// Auth
const val ACTION_CLIENT_AUTH_REFRESHED = "$ACTION_PREFIX.CLIENT_AUTH_REFRESHED"
const val ACTION_STOP_SPEAKING = "$ACTION_PREFIX.STOP_SPEAKING"
const val ACTION_REQUEST_CLEAR_CARD = "$ACTION_PREFIX.REQUEST_CLEAR_CARD"
const val ACTION_REQUEST_STOP_CURRENT_ALERT = "$ACTION_PREFIX.REQUEST_STOP_CURRENT_ALERT"
const val ACTION_REQUEST_DIALOG_END = "$ACTION_PREFIX.REQUEST_DIALOG_END"
const val ACTION_PLAY_WAKE_SOUND = "$ACTION_PREFIX.PLAY_WAKE_SOUND"
const val ACTION_TEMPLATE_RUNTIME_SELECT_ELEMENT = "$ACTION_PREFIX.TEMPLATE_RUNTIME_SELECT_ELEMENT"
}<file_sep>package com.iflytek.cyber.iot.show.core.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.model.MediaEntity
class RecommendMediaAdapter : RecyclerView.Adapter<MediaViewHolder>() {
enum class ColsType {
THREE_COLS, FIVE_COLS
}
enum class MediaType {
AUDIO, VIDEO
}
interface OnItemClickListener {
fun onItemClicked(view: View, position: Int)
}
private var colsType = ColsType.THREE_COLS
private var mediaType = MediaType.AUDIO
private var itemList: List<MediaEntity>? = null
private var onItemClickListener: OnItemClickListener? = null
fun setColsType(type: ColsType) {
colsType = type
}
fun setMediaType(type: MediaType) {
mediaType = type
}
fun setItems(items: List<MediaEntity>) {
itemList = items
}
fun setOnItemClickListener(listener: OnItemClickListener) {
onItemClickListener = listener
}
fun getItem(position: Int): MediaEntity? {
return if (itemList == null) null else itemList!![position]
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaViewHolder {
return when (mediaType) {
MediaType.AUDIO -> {
if (colsType == ColsType.THREE_COLS) {
MediaViewHolder(LayoutInflater.from(parent.context).inflate(
R.layout.item_recommend_music_three_cols, null))
} else {
MediaViewHolder(LayoutInflater.from(parent.context).inflate(
R.layout.item_recommend_music_five_cols, null))
}
}
else -> {
MediaViewHolder(LayoutInflater.from(parent.context).inflate(
R.layout.item_recommend_video, null))
}
}
}
override fun getItemCount(): Int {
return if (itemList == null) 0 else itemList!!.size
}
override fun onBindViewHolder(holder: MediaViewHolder, position: Int) {
holder.setItem(getItem(position)!!, position)
holder.setOnClickListener(View.OnClickListener {
onItemClickListener?.onItemClicked(it, position)
})
}
}<file_sep>package com.iflytek.cyber.iot.show.core.fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.iflytek.cyber.evs.sdk.socket.Result
import com.iflytek.cyber.iot.show.core.CoreApplication
import com.iflytek.cyber.iot.show.core.EngineService
import com.iflytek.cyber.iot.show.core.FloatingService
import com.iflytek.cyber.iot.show.core.R
import com.iflytek.cyber.iot.show.core.api.SkillApi
import com.iflytek.cyber.iot.show.core.model.Skill
import com.iflytek.cyber.iot.show.core.model.SkillDetail
import com.iflytek.cyber.iot.show.core.model.SkillSection
import com.iflytek.cyber.iot.show.core.utils.RoundedCornersTransformation
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
class SkillSectionFragment : Fragment() {
private lateinit var recyclerView: RecyclerView
private var requestingSkillId: String? = null
companion object {
fun newInstance(skill: SkillSection): SkillSectionFragment {
return SkillSectionFragment().apply {
arguments = bundleOf(Pair("skill", skill))
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return LayoutInflater.from(context)
.inflate(R.layout.fragment_skill_section, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view.findViewById(R.id.recycler_view)
val skill = arguments?.getParcelable<SkillSection>("skill") ?: return
val adapter = SkillAdapter(skill.skills) {
getSkillApi()?.getSkillDetail(it.id)?.enqueue(object : Callback<SkillDetail> {
override fun onFailure(call: Call<SkillDetail>, t: Throwable) {
if (requestingSkillId != it.id)
return
if (t is UnknownHostException) {
val intent = Intent(EngineService.ACTION_SEND_REQUEST_FAILED)
intent.putExtra(
EngineService.EXTRA_RESULT,
Result(Result.CODE_DISCONNECTED, null)
)
context?.sendBroadcast(intent)
}
}
override fun onResponse(call: Call<SkillDetail>, response: Response<SkillDetail>) {
if (requestingSkillId != it.id)
return
if (response.isSuccessful) {
val detail = response.body() ?: return
(parentFragment as? BaseFragment)?.start(
SkillDetailFragment.newInstance(
detail
)
)
} else {
val disconnectNotification =
Intent(context, FloatingService::class.java)
disconnectNotification.action = FloatingService.ACTION_SHOW_NOTIFICATION
disconnectNotification.putExtra(
FloatingService.EXTRA_MESSAGE,
"请求出错,请稍后再试"
)
disconnectNotification.putExtra(
FloatingService.EXTRA_ICON_RES,
R.drawable.ic_default_error_white_40dp
)
disconnectNotification.putExtra(
FloatingService.EXTRA_POSITIVE_BUTTON_TEXT,
getString(R.string.i_got_it)
)
context?.startService(disconnectNotification)
}
}
})
requestingSkillId = it.id
}
recyclerView.adapter = adapter
}
private fun getSkillApi(): SkillApi? {
val context = context ?: return null
return CoreApplication.from(context).createApi(SkillApi::class.java)
}
inner class SkillAdapter(
private val skills: ArrayList<Skill>,
private val onItemClickListener: (skill: Skill) -> Unit
) : RecyclerView.Adapter<SkillAdapter.SkillHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SkillHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.item_skill, parent, false)
return SkillHolder(view)
}
override fun getItemCount(): Int {
return skills.size
}
override fun onBindViewHolder(holder: SkillHolder, position: Int) {
val skill = skills[position]
holder.tvSkill.text = skill.name
holder.tvDesc.text = skill.description
val transformer = MultiTransformation(
CenterCrop(),
RoundedCornersTransformation(
holder.itemView.resources.getDimensionPixelSize(R.dimen.dp_8), 0
)
)
Glide.with(holder.ivSkillIcon)
.load(skill.icon)
.transform(transformer)
.into(holder.ivSkillIcon)
holder.itemView.setOnClickListener {
onItemClickListener.invoke(skill)
}
}
inner class SkillHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvSkill = itemView.findViewById<TextView>(R.id.tv_skill)
val tvDesc = itemView.findViewById<TextView>(R.id.tv_description)
val ivSkillIcon = itemView.findViewById<ImageView>(R.id.iv_skill_icon)
}
}
}
|
957f793bd3168fb4ea965b35f1de4ecd60180b4a
|
[
"CMake",
"Markdown",
"Java",
"C++",
"C",
"Kotlin"
] | 217
|
Kotlin
|
touchain-project/ShowCore-Open
|
c13383a7233cb64e782e2dbcfddbbccdf8cc5a88
|
f7a081f3ff1892dedbe208a4159d381cd52c911e
|
refs/heads/master
|
<file_sep>/**
* Created by eguoyix on 17/3/13.
* 预存款
*/
package com.yixi.rabbit.mall.predeposite;<file_sep>/**
* Created by eguoyix on 17/3/13.
* 结算模块
*/
package com.yixi.rabbit.mall.settleacount;<file_sep>/**
* Created by eguoyix on 17/3/13.
* 订单管理
*/
package com.yixi.rabbit.mall.order;<file_sep>package com.yixi.rabbit.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* Created by eguoyix on 17/3/13.
*/
@Configuration
@EnableWebMvc
@ComponentScan(value={"com.yixi.rabbit.*"})
public class WebConfig {
}
<file_sep>/**
* Created by eguoyix on 17/3/13.
* 商城首页
*/
package com.yixi.rabbit.mall.home;<file_sep>/**
* Created by eguoyix on 17/3/13.
* 退单模块
*/
package com.yixi.rabbit.mall.salesreturn;<file_sep>/**
* Created by eguoyix on 17/3/13.
* 支付接口
*/
package com.yixi.rabbit.mall.payment;<file_sep>/**
* Created by eguoyix on 17/3/13.
* 商城套件
*/
package com.yixi.rabbit.mall;
|
4a7f7481a3aaa22c4b3ad28b989d38a83d29376f
|
[
"Java"
] | 8
|
Java
|
heiliguai/rabbitshop
|
641698d43691eb5c23acfab847e8d1ff8478afc1
|
7bc8390961421f975a13a3cc731f573ec2435611
|
refs/heads/main
|
<repo_name>cauhuyso0/ReactNative_App<file_sep>/README.md
# ReactNative_App
App ReactNative dùng thư viện expo
<file_sep>/screens/Login.js
import React, { useContext,useState, Component } from "react";
import { View, Text, StyleSheet,TouchableOpacity } from "react-native";
import { AuthContext } from "../navigation/AuthProvider";
import FormInput from '../components/FormInput';
import FormButton from '../components/FormButton';
import { LoginButton } from "react-native-fbsdk";
import { windowHeight, windowWidth } from '../utils/Dimensions';
import { color } from "react-native-reanimated";
export const Login = ({ navigation }) => {
const { login, loginFacebook } = useContext(AuthContext);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
return (
<View style={styles.container}>
<Text style={styles.text}> Đăng Nhập </Text>
<FormInput
value={email}
placeholderText='<NAME>'
onChangeText={userEmail => setEmail(userEmail)}
autoCapitalize='none'
keyboardType='email-address'
autoCorrect={false}
/>
<FormInput
value={password}
placeholderText='<NAME>'
onChangeText={userPassword => setPassword(userPassword)}
secureTextEntry={true}
/>
<FormButton buttonTitle='Đăng Nhập' onPress={() => login(email, password)} />
<TouchableOpacity
style={styles.butonFB}
onPress={()=> loginFacebook()}>
<Text style ={styles.textFB}>LoginFaceBook</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.navButton}
onPress={() => navigation.navigate('Register')}
>
<Text style={styles.navButtonText}>Đăng ký tài khoản ?</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
text: {
fontSize: 24,
marginBottom: 10
},
textFB:{
color: '#ffffff',
fontSize: 20,
},
navButton: {
marginTop: 15
},
navButtonText: {
fontSize: 20,
color: '#8a2be2'
},
butonFB:{
marginTop: 10,
width: windowWidth / 2,
height: windowHeight / 15,
backgroundColor: '#8a2be2',
padding: 10,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 8
}
});<file_sep>/screens/Repass.js
import React, { useContext,useState, Component } from "react";
import { View, Text, StyleSheet,TouchableOpacity } from "react-native";
import { AuthContext } from "../navigation/AuthProvider";
import FormInput from '../components/FormInput';
import FormButton from '../components/FormButton';
import { windowHeight, windowWidth } from '../utils/Dimensions';
export const Repass = ({ navigation }) => {
const [password1, setPassword1] = useState('');
const [password, setPassword] = useState('');
function Repass (){
var user = firebaseConfig.auth().currentUser;
if(password1 === password){
user.updatePassword(password).then(function() {
console.log("Đổi pass thành công")
ToastAndroid.show('Update success!', ToastAndroid.SHORT);
setPassword("");
setPassword1("");
}).catch(function(error) {
console.log(error)
});
}
}
return (
<View style={styles.container}>
<Text style={styles.text}> Đổi Password </Text>
<FormInput
// value={password}
placeholderText='<NAME>'
onChangeText={userPassword => setPassword1(user<PASSWORD>)}
secureTextEntry={true}
/>
<FormInput
//value={password}
placeholderText='Nhập lại Mật khẩu'
onChangeText={userPassword => setPassword(user<PASSWORD>)}
secureTextEntry={true}
/>
<FormButton buttonTitle='Xác nhận' onPress={() => {Repass();}}/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
text: {
fontSize: 24,
marginBottom: 10
},
textFB:{
color: '#ffffff',
fontSize: 20,
},
navButton: {
marginTop: 15
},
navButtonText: {
fontSize: 20,
color: '#8a2be2'
},
butonFB:{
marginTop: 10,
width: windowWidth / 2,
height: windowHeight / 15,
backgroundColor: '#8a2be2',
padding: 10,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 8
}
});<file_sep>/App.js
import React, { useEffect, useState } from 'react';
import {
View,
Text,
StyleSheet,
Dimensions,
FlatList,
Alert,
TouchableOpacity,
TouchableWithoutFeedback,
Image,
Modal,
TextInput,
ToastAndroid,
YellowBox
} from 'react-native';
import firebaseConfig from './firebase/firebase';
import Swipeout from 'react-native-swipeout';
export default function App() {
// const [ item ] = useState(props.item);
const itemsRef = firebaseConfig.database().ref().child('phims');
const [maPhim, setMaPhim] = useState('');
const [tenPhim, setTenPhim] = useState('');
const [theLoai, setTheLoai] = useState('');
const [quocGia, setQuocGia] = useState('');
const [thoiLuong, setThoiLuong] = useState('');
const [daoDien, setDaoDien] = useState('');
const [ lists, setLists ] = useState([]);
useEffect(() => {
itemsRef.on('value', (snap) => {
var items = [];
snap.forEach((child) => {
let item = {
key: child.key,
maPhim: child.val().maPhim,
tenPhim: child.val().tenPhim,
theLoai: child.val().theLoai,
quocGia: child.val().quocGia,
thoiLuong: child.val().thoiLuong,
daoDien: child.val().daoDien
};
items.push(item);
});
setLists(items);
});
}, []);
const insertProduct = async () => {
firebaseConfig
.database()
.ref()
.child('phims')
.push({
maPhim: maPhim,
tenPhim: tenPhim,
theLoai: theLoai,
quocGia: quocGia,
thoiLuong: thoiLuong,
daoDien: daoDien
})
.then(() => {
console.log('Insert success!');
ToastAndroid.show('Insert success!', ToastAndroid.SHORT);
})
.catch((error) => {
console.log(error);
ToastAndroid.show('Insert fail!', ToastAndroid.SHORT);
});
};
const ProductItem = (props) => {
return (
<View>
<View>
<Text style={{ marginLeft: 10, fontSize: 20 }}>Name: {props.item.maPhim}</Text>
<Text style={{ marginLeft: 10 }}>Price: {props.item.tenPhim}</Text>
<Text style={{ marginLeft: 10 }}>Info: {props.item.theLoai}</Text>
</View>
</View>
);
};
return (
<View>
<FlatList
data={lists}
renderItem={({ item }) =>
<ProductItem item={item} />
}
/>
<View styles = {styles.container}>
<TextInput placeholder ={"Nhập mã phim"} onChangeText={(text) => setMaPhim(text)} />
<TextInput placeholder ={"Nhập tên phim"} onChangeText={(text) => setTenPhim(text)} />
<TextInput placeholder ={"Nhập thể loại"} onChangeText={(text) => setTheLoai(text)} />
<TextInput placeholder ={"Nhập quốc gia"} onChangeText={(text) => setQuocGia(text)} />
<TextInput placeholder ={"Nhập thời lượng"} onChangeText={(text) => setThoiLuong(text)} />
<TextInput placeholder ={"Nhập đạo diễn"} onChangeText={(text) => setDaoDien(text)} />
</View>
<TouchableOpacity
style={styles.fab}
onPress={() => {
insertProduct();
}}
>
<Text style={styles.text}>+</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
marginTop: 100,
},
fab: {
height: 50,
width: 50,
borderRadius: 200,
position: 'absolute',
bottom: 20,
right: 20,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#686cc3'
},
})<file_sep>/screens/Information.js
import React, { useEffect, useState } from 'react';
import {
View,
Text,
StyleSheet,
Dimensions,
FlatList,
Alert,
TouchableOpacity,
TouchableWithoutFeedback,
Image,
Modal,
TextInput,
ToastAndroid,
YellowBox
} from 'react-native';
import firebaseConfig from '../firebase/firebase.js';
import { windowHeight, windowWidth } from '../utils/Dimensions';
export const Infor = () => {
const [ modalVisible, setModalVisible ] = useState(false);
const [ name, setName] = useState("");
const [ avatar, setAvatar] = useState("");
_hideDialog = () => {
setModalVisible(false);
};
_showDialog = () => {
setModalVisible(true);
};
var user = firebaseConfig.auth().currentUser;
var email, url, displayName, emailVerified, uid;
if (user !=null){
email = user.email;
url = user.photoURL;
displayName = user.displayName;
emailVerified = user.emailVerified;
uid = user.uid;
}
const updateProfile = () =>{
user.updateProfile({
displayName: name,
photoURL: avatar
}).then(function() {
console.log("Update thành công")
ToastAndroid.show('Update success!', ToastAndroid.SHORT);
}).catch(function(error) {
console.log("Update thất bại")
ToastAndroid.show('Update fail!', ToastAndroid.SHORT);
});
}
return(
<View style = {styles.container}>
<View style={styles.listContainer}>
<Image
source={{ uri: url, width: 120, height: 120 }}
style={{ borderWidth: 1, borderColor: 'black' }}
/>
<View>
<Text style={{ marginLeft: 10, fontSize: 30 }}>Name: {displayName}</Text>
<Text style={{ marginLeft: 10, fontSize: 15 }}>Email: {email}</Text>
</View>
</View>
<TouchableOpacity
style={styles.butonFB}
onPress={()=> {setModalVisible(true)}}>
<Text style ={styles.textFB}>Đổi thông tin</Text>
</TouchableOpacity>
<Modal animationType="slide" transparent={true} visible={modalVisible}>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Thay đổi thông tin</Text>
{/* <TouchableWithoutFeedback onPress={() => _chooseImage()}>
<Image
source={{ uri: image, width: 150, height: 150 }}
style={{ borderWidth: 1, borderColor: 'black' }}
/>
</TouchableWithoutFeedback> */}
<View style={styles.lineDialog}>
<Text style={styles.textDialog}>Name: </Text>
<TextInput style={styles.textInputDialog} value={name} onChangeText={(text) => setName(text)} />
</View>
<View style={styles.lineDialog}>
<Text style={styles.textDialog}>Link ảnh: </Text>
<TextInput style={styles.textInputDialog} value={avatar} onChangeText={(text) => setAvatar(text)} />
</View>
<View
style={{
flex: 1,
flexDirection: 'row',
margin: 2,
alignItems: 'center',
width: width * 80 / 187.5,
padding: width * 8 / 187.5
}}
>
<TouchableOpacity
style={{ ...styles.openButton, backgroundColor: '#2196F3' }}
onPress={() => {
setModalVisible(false);
}}
>
<Text style={styles.textStyle}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity
style={{ ...styles.openButton, backgroundColor: '#2196F3' }}
onPress={() => {
setModalVisible(false);
updateProfile();
}}
>
<Text style={styles.textStyle}>Xác nhận</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
</View>
);
}
const { width, height } = Dimensions.get('window');
const styles = StyleSheet.create ({
listContainer: {
backgroundColor: '#f1f1f1',
flexDirection: 'row',
margin: width * 3.6 / 187.5,
padding: width * 3.6 / 187.5,
borderRadius: width * 3.6 / 187.5
},
textStyle: {
color: 'white',
fontWeight: 'bold',
textAlign: 'center'
},
container: {
flex: 1,
alignItems: "center",
},
butonFB:{
marginTop: 50,
width: windowWidth / 2,
height: windowHeight / 15,
backgroundColor: '#8a2be2',
padding: 10,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 8
},
textFB:{
color: '#ffffff',
fontSize: 20,
},
modalView: {
width: width * 167.5 / 187.5,
padding: width * 8 / 187.5,
borderRadius: width * 3.6 / 187.5,
margin: 20,
backgroundColor: 'white',
alignItems: 'center',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5
},
openButton: {
backgroundColor: '#F194FF',
borderRadius: 20,
padding: 10,
width: 120,
margin: 2,
elevation: 2
},
modalText: {
fontSize: 20,
marginBottom: 15,
textAlign: 'center'
},
lineDialog: {
width: '100%',
height: 40,
margin: 8,
flexDirection: 'row',
alignItems: 'center',
borderWidth: 1,
borderRadius: 5,
backgroundColor: '#f1f1f1'
},
textInputDialog: {
height: 34,
flex: 1,
marginRight: 4,
borderWidth: 0.1,
borderRadius: 5,
color: '#111111',
fontSize: 15,
paddingLeft: 5
},
centeredView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginTop: 22
},
})<file_sep>/screens/List.js
import React, { useEffect, useState } from 'react';
import {
View,
Text,
StyleSheet,
Dimensions,
FlatList,
Alert,
TouchableOpacity,
TouchableWithoutFeedback,
Image,
Modal,
TextInput,
ToastAndroid,
YellowBox
} from 'react-native';
import firebase from '../firebase/firebase.js';
import * as ImagePicker from 'expo-image-picker';
import Swipeout from 'react-native-swipeout';
export const Product = () => {
const itemsRef = firebase.database().ref().child('products');
const [ lists, setLists ] = useState([]);
const [ modalVisible, setModalVisible ] = useState(false);
const [ currentItem, setCurrentItem ] = useState(null);
_hideDialog = () => {
setModalVisible(false);
};
_showDialog = () => {
setModalVisible(true);
};
_setCurrent = async (item) => {
await setCurrentItem(item);
};
// Function add Product vao lists
const listenForItems = (itemsRef) => {
itemsRef.on('value', (snap) => {
var items = [];
snap.forEach((child) => {
let item = {
key: child.key,
name: child.val().name,
price: child.val().price,
info: child.val().info,
image: child.val().image
};
items.push(item);
});
setLists(items);
});
};
useEffect(() => {
listenForItems(itemsRef);
//Tat warning khong can thiet
YellowBox.ignoreWarnings([ 'Setting a timer', 'Warning:' ]);
}, []);
return (
<View style={styles.container}>
<FlatList
data={lists}
renderItem={({ item }) => (
<ProductItem item={item} _showDialog={_showDialog} _setCurrent={_setCurrent} />
)}
/>
<TouchableOpacity
style={styles.fab}
onPress={() => {
_setCurrent(null);
_showDialog();
}}
>
<Text style={styles.text}>+</Text>
</TouchableOpacity>
<Modal animationType="slide" transparent={true} visible={modalVisible}>
<ProductInsUp item={currentItem} _hideDialog={_hideDialog} />
</Modal>
</View>
);
};
//Insert Update Product function
const ProductInsUp = (props) => {
const [ item ] = useState(props.item);
const [ isInsert ] = useState(item == null);
const [ key, setKey ] = useState('');
const [ name, setName ] = useState('');
const [ price, setPrice ] = useState('');
const [ info, setInfo ] = useState('');
const [ image, setImage ] = useState('https://reactjs.org/logo-og.png');
//function chọn ảnh
const _chooseImage = async () => {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [ 4, 3 ]
});
if (!result.cancelled) {
setImage(result.uri);
console.log(image);
}
};
//function up ảnh fireStorage
const _uploadImage = async (uri) => {
const path = 'images/' + name + '.jpg';
return new Promise(async (res, rej) => {
const response = await fetch(uri);
const file = await response.blob();
let upload = firebaseConfig.storage().ref(path).put(file);
upload.on(
'state_changed',
(snapshot) => {},
(err) => {
rej(err);
},
async () => {
const url = await upload.snapshot.ref.getDownloadURL();
res(url);
}
);
});
};
//function Insert Product
const insertProduct = async () => {
const remoteUri = await _uploadImage(image);
firebaseConfig
.database()
.ref()
.child('products')
.push({
name: name,
price: price,
info: info,
image: remoteUri
})
.then(() => {
console.log('Insert success!');
ToastAndroid.show('Insert success!', ToastAndroid.SHORT);
})
.catch((error) => {
console.log(error);
ToastAndroid.show('Insert fail!', ToastAndroid.SHORT);
});
};
//function Update Product
const updateProduct = async () => {
const remoteUri = await _uploadImage(image);
firebaseConfig
.database()
.ref()
.child('products')
.child(key)
.set({
name: name,
price: price,
info: info,
image: remoteUri
})
.then(() => {
console.log('Update success!');
ToastAndroid.show('Update success!', ToastAndroid.SHORT);
})
.catch((error) => {
console.log(error);
ToastAndroid.show('Update fail!', ToastAndroid.SHORT);
});
};
//fuction useEffect
useEffect(() => {
if (!isInsert) {
setKey(props.item.key);
setName(props.item.name);
setPrice(props.item.price);
setInfo(props.item.info);
setImage(props.item.image);
}
}, []);
return (
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>{isInsert ? 'Insert' : 'Update'} Product</Text>
<TouchableWithoutFeedback onPress={() => _chooseImage()}>
<Image
source={{ uri: image, width: 150, height: 150 }}
style={{ borderWidth: 1, borderColor: 'black' }}
/>
</TouchableWithoutFeedback>
<View style={styles.lineDialog}>
<Text style={styles.textDialog}>Name: </Text>
<TextInput style={styles.textInputDialog} value={name} onChangeText={(text) => setName(text)} />
</View>
<View style={styles.lineDialog}>
<Text style={styles.textDialog}>Price: </Text>
<TextInput style={styles.textInputDialog} value={price} onChangeText={(text) => setPrice(text)} />
</View>
<View style={styles.lineDialog}>
<Text style={styles.textDialog}>Info: </Text>
<TextInput style={styles.textInputDialog} value={info} onChangeText={(text) => setInfo(text)} />
</View>
<View
style={{
flex: 1,
flexDirection: 'row',
margin: 2,
alignItems: 'center',
width: width * 80 / 187.5,
padding: width * 8 / 187.5
}}
>
<TouchableOpacity
style={{ ...styles.openButton, backgroundColor: '#2196F3' }}
onPress={() => {
props._hideDialog();
}}
>
<Text style={styles.textStyle}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity
style={{ ...styles.openButton, backgroundColor: '#2196F3' }}
onPress={() => {
props._hideDialog();
isInsert ? insertProduct() : updateProduct();
}}
>
<Text style={styles.textStyle}>{isInsert ? 'Insert' : 'Update'}</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
};
//Item FlatList & Delete function
const ProductItem = (props) => {
const swipeoutSettings = {
autoClose: true,
onClose: () => {},
onOpen: () => {
props._setCurrent(props.item);
},
right: [
{
text: 'Update',
type: 'secondary',
onPress: () => {
props._showDialog();
}
},
{
text: 'Delete',
type: 'delete',
onPress: () => {
Alert.alert(
'Delete',
'Are you want to delete product ' + props.item.name + '?',
[
{ text: 'No', onPress: () => console.log('Cancel Delete '), type: 'cancel' },
{ text: 'Yes', onPress: () => deleteProduct(props.item.key) }
],
{ cancelable: true }
);
}
}
]
};
//Function Xoa Product
const deleteProduct = (key) => {
firebaseConfig.database().ref().child('products').child(key).remove();
};
return (
<Swipeout {...swipeoutSettings}>
<View style={styles.listContainer}>
<Image
source={{ uri: props.item.image, width: 60, height: 60 }}
style={{ borderWidth: 1, borderColor: 'black' }}
/>
<View>
<Text style={{ marginLeft: 10, fontSize: 20 }}>Name: {props.item.name}</Text>
<Text style={{ marginLeft: 10 }}>Price: {props.item.price}</Text>
<Text style={{ marginLeft: 10 }}>Info: {props.item.info}</Text>
</View>
</View>
</Swipeout>
);
};
const { width, height } = Dimensions.get('window');
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff'
},
listContainer: {
backgroundColor: '#f1f1f1',
flexDirection: 'row',
margin: width * 3.6 / 187.5,
padding: width * 3.6 / 187.5,
borderRadius: width * 3.6 / 187.5
},
fab: {
height: 50,
width: 50,
borderRadius: 200,
position: 'absolute',
bottom: 20,
right: 20,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#686cc3'
},
text: {
fontSize: 30,
color: 'white'
},
centeredView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginTop: 22
},
modalView: {
width: width * 167.5 / 187.5,
padding: width * 8 / 187.5,
borderRadius: width * 3.6 / 187.5,
margin: 20,
backgroundColor: 'white',
alignItems: 'center',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5
},
openButton: {
backgroundColor: '#F194FF',
borderRadius: 20,
padding: 10,
width: 120,
margin: 2,
elevation: 2
},
textStyle: {
color: 'white',
fontWeight: 'bold',
textAlign: 'center'
},
modalText: {
fontSize: 20,
marginBottom: 15,
textAlign: 'center'
},
lineDialog: {
width: '100%',
height: 40,
margin: 8,
flexDirection: 'row',
alignItems: 'center',
borderWidth: 1,
borderRadius: 5,
backgroundColor: '#f1f1f1'
},
textInputDialog: {
height: 34,
flex: 1,
marginRight: 4,
borderWidth: 0.1,
borderRadius: 5,
color: '#111111',
fontSize: 15,
paddingLeft: 5
}
});
<file_sep>/firebase/firebase.js
import * as firebase from "firebase";
var Config = {
apiKey: "<KEY>",
authDomain: "ps10826-maixuanhuy-asm.firebaseapp.com",
databaseURL: "https://ps10826-maixuanhuy-asm.firebaseio.com",
projectId: "ps10826-maixuanhuy-asm",
storageBucket: "ps10826-maixuanhuy-asm.appspot.com",
messagingSenderId: "440151028389",
appId: "1:440151028389:web:c671541fff99c098b4d34c",
measurementId: "G-ZKCD89BQ85"
};
// Initialize Firebase
export default (firebaseConfig = firebase.initializeApp(Config));
|
e835dde47a0f9618bd0c23f97242af47f961df54
|
[
"Markdown",
"JavaScript"
] | 7
|
Markdown
|
cauhuyso0/ReactNative_App
|
bbe7444208c6c6fe6bd0a7fb608d2f7276ebcc5f
|
f2a67b751e41fdaf46422580083c354a87032b02
|
refs/heads/master
|
<file_sep>package org.tlab.buzzdroid;
import android.os.AsyncTask;
import android.widget.EditText;
public class TitleFetchTask extends AsyncTask<String, String, String>{
private AddBookmark mActivity;
private EditText mEditTitle;
public TitleFetchTask(AddBookmark activity, EditText editText) {
this.mActivity = activity;
this.mEditTitle = editText;
}
@Override
protected String doInBackground(String... params) {
String url = params[0];
String result = HttpUtil.getTitle(url);
return result;
}
protected void onPostExecute(String result) {
mEditTitle.setText(result);
return;
}
}
<file_sep>package org.tlab.buzzdroid;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
public class Settings extends PreferenceActivity {
private final static String TAG = Settings.class.getSimpleName();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref);
setBackLine();
}
private void setBackLine(){
Preference prefBack = findPreference("back");
prefBack.setOnPreferenceClickListener(new PreferenceClickListener());
}
private class PreferenceClickListener implements OnPreferenceClickListener {
public boolean onPreferenceClick(Preference preference) {
finish();
return true;
}
}
}
|
381ece79c78d226a53ef83d40532151130a0965c
|
[
"Java"
] | 2
|
Java
|
cutmail/Buzzdroid
|
9348cbd81eaa71a8b0eca08fd31427e21710782b
|
b102d8b48057e56ea5ec5c2335cd7902724ad916
|
refs/heads/master
|
<repo_name>enrib82/-Pr-ctica-7.-Ejercicios-de-manejo-de-cadenas-funciones-y-procedimientos.-<file_sep>/ej. 10-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio 10 - Pràctica 7."""
def capicua(texto):
al_reves=""
for i in range(len(texto)-1,-1,-1):
al_reves=al_reves+texto[i]
if al_reves==texto:
print algo,"es capicua o palindromo"
else:
print algo," no es capicua o palindromo"
return al_reves
algo=raw_input("Escribe algo: ")
reves=capicua(algo)
print "El resultado es",reves
<file_sep>/ej.4-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio 4 - Pràctica 7.
Escribe un programa que pida una frase, y le pase como parámetro a una
función dicha frase. La función debe sustituir todos los espacios
en blanco de una frase por un asterisco, y devolver el resultado
para que el programa principal la imprima por pantalla. """
def sustituto(cadena):
nada=""
for i in range(len(cadena)):
if cadena[i]==" ":
nada=nada+"*"
else:
nada=nada+cadena[i]
return nada
frase=raw_input("Escribe una frase: ")
asteriscos=sustituto(frase)
print asteriscos
<file_sep>/ej. 6-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio 6 - Pràctica 7."""
def estar(cadena,caracter):
for i in range(len(cadena)):
if cadena[i]==caracter:
estar=True
else:
estar=False
return estar
nombre=raw_input("Escribe un nombre: ")
caracter=raw_input("Escribe un caracter: ")
v_estar=estar(nombre,caracter)
if v_estar:
print "El caracter si esta en la cadena introducida"
else:
print "El caracter no esta en la cadena introducida"
<file_sep>/ej.1-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio 1 - Pràctica 7.
Escribe un programa que pida un texto por pantalla, este texto lo
pase como parámetro a un procedimiento, y éste lo imprima primero
todo en minúsculas y luego todo en mayúsculas."""
texto=raw_input("Escribe un texto: ")
def definicion(pepe):
print pepe.lower()
print pepe.upper()
definicion(texto)
<file_sep>/ej. 12-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio 12 - Pràctica 7."""
def palabra(frase):
contador=1
for i in range(len(frase)):
if frase[i]==" " or frase[i]=="." or frase[i]=="_" or frase[i]=="-":
if not frase[i-1]==" " or frase[i-1]=="." or frase[i-1]=="_" or frase[i-1]=="-":
contador=contador+1
return contador
frase=raw_input("Escribe una frase: ")
cuenta=palabra(frase)
if cuenta>1:
print "La frase tiene",cuenta,"palabras"
else:
print "La frase tiene sOlo una palabra"
<file_sep>/ej. 8-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio 8 - Pràctica 7."""
def eliminar_espacios(cadena):
sentence=""
for i in range(len(cadena)):
if not cadena[i]==" ":
sentence=sentence+cadena[i]
return sentence
frase=raw_input("Escribe una frase: ")
blanco=eliminar_espacios(frase)
print blanco
<file_sep>/ej. 5-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio 5 - Pràctica 7."""
def modificar(cadena,letra):
text=""
for i in range(len(cadena)):
if cadena[i]=="a" or cadena[i]=="e" or cadena[i]=="i" or cadena[i]=="o" or cadena[i]=="u":
text=text+letra
else:
text=text+cadena[i]
return text
frase=raw_input("Escribe una frase: ")
vocal=raw_input("Escribe una vocal: ")
while len(vocal)!=1:
vocal=raw_input("Solo una vocal, por favor: ")
cadena_modificada=modificar(frase,vocal)
print cadena_modificada
<file_sep>/ej.3-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio 3 - Pràctica 7.
Escribe un programa que lea una frase, y la pase como parámetro a
un procedimiento, y éste debe mostrar la frase con un carácter
en cada línea. """
frase=raw_input("Dime una frase: ")
def funcion(g):
for i in frase:
print i
funcion(frase)
<file_sep>/README.md
# -Pr-ctica-7.-Ejercicios-de-manejo-de-cadenas-funciones-y-procedimientos.-<file_sep>/ej.2-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio 2 - Pràctica 7.
Escribe un programa que lea el nombre y los dos apellidos de una
persona (en tres cadenas de caracteres diferentes), los pase como
parámetros a una función, y ésta debe unirlos y devolver
una única cadena. La cadena final la imprimirá el programa por
pantalla."""
def juntar(a,b,c):
nombre_completo=a+" "+b+" "+c
print nombre_completo
nom=raw_input("Escribe tu nombre: ")
apellido1=raw_input("Escribe tu primer apellido: ")
apellido2=raw_input("Escribe tu segundo apellido: ")
juntar(nom, apellido1, apellido2)
<file_sep>/ej. 9-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio - Pràctica 7."""
def coincidir(word1,word2):
text1="";text2="";probado = False;contador = -1
while not probado:
if word1[contador] == word2[contador] and contador >= -3:
text1=word1[contador]
text2=word2[contador]
contador=contador-1
else:
probado=True
contador = contador+1
if contador == -1:
print "La ultima letra coincide"
elif contador == -2:
print "Las dos ultimas letras coinciden"
elif contador == -3:
print "Las tres ultimas letras coinciden"
else:
print "No coincide ninguna letra de las tres ultimas"
palabra1=raw_input("Escribe una primera palabra: ")
palabra2=raw_input("Escribe una segunda palabra: ")
while len(palabra1)<=3:
print "Escribe la primera palabra con longitud mayor a 3:",
palabra1=raw_input()
while len(palabra2)<=3:
print "Escribe la segunda palabra con longitud mayor a 3:",
palabra2=raw_input()
coincidir(palabra1,palabra2)
<file_sep>/ej. 7-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio 7 - Pràctica 7."""
def contar(sentence):
vocales=["A", "E", "I","O", "U", "a","e", "i", "o","u"];vocal=0
for i in range(len(sentence)):
for j in range(len(vocales)):
if vocales[j]==sentence[i]:
vocal=vocal+1
print "La frase introducida tiene",vocal,"vocales"
frase=raw_input("Escribe una frase: ")
contar(frase)
<file_sep>/ej. 11-7.py
# -*- coding: cp1252 -*-
"""<NAME> - 1º DAW - Practica 7 - Ejercicio 11 - Pràctica 7."""
def palindromo(texto):
al_reves=""
for i in range(len(texto)-1,-1,-1):
al_reves=al_reves+texto[i]
return al_reves
algo=raw_input("Escribe algo: ")
reves=palindromo(algo)
if reves==algo:
print "El resultado es",reves,": Es palindromo"
else:
print "El resultado es",reves,": No es palindromo"
|
4f4be2c57b04ccee887382dcd97831538f217d10
|
[
"Markdown",
"Python"
] | 13
|
Python
|
enrib82/-Pr-ctica-7.-Ejercicios-de-manejo-de-cadenas-funciones-y-procedimientos.-
|
2121ef02db21cb6652d5ba26f8ab0c133e8e1fc8
|
6a334c98e46d3047643af283a7fa7236f84318f6
|
refs/heads/master
|
<file_sep>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <fftw3.h>
#include <math.h>
using namespace std;
#define N 5000
/*void fft(double* in, fftw_complex* out, int sum)
{
fftw_plan plan = fftw_plan_dft_r2c_1d(sum, in, out, FFTW_ESTIMATE);
fftw_execute(plan);
fftw_destroy_plan(plan);
fftw_cleanup();
}*/
void fft(double* in, double* out, int sum)
{
fftw_plan plan = fftw_plan_r2r_1d(sum, in, out, FFTW_REDFT00, FFTW_ESTIMATE);
fftw_execute(plan);
fftw_destroy_plan(plan);
fftw_cleanup();
}
int main() {
double* x;
double* y;
double* z;
x = (double*)malloc(sizeof(double) * N);
y = (double*)malloc(sizeof(double) * N);
z = (double*)malloc(sizeof(double) * N);
double* outx;
double* outy;
double* outz;
outx = (double*)malloc(sizeof(double) * N);
outy = (double*)malloc(sizeof(double) * N);
outz = (double*)malloc(sizeof(double) * N);
/*fftw_complex* outx;
outx = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * N);
fftw_complex* outy;
outy = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * N);
fftw_complex* outz;
outz = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * N);*/
ifstream myfile("1602245833-2715-NAO7856.txt");
int sum = 0;
if (myfile.is_open()) {
std::string line;
while (getline(myfile, line)) {
std::stringstream ss(line);
string sx, sy, sz;
getline(ss, sx, ',');
if (sx == "x") //exclui a primeira linha do arquivo .txt
continue;
getline(ss, sy, ',');
getline(ss, sz, ',');
x[sum] = stod(sx);
y[sum] = stod(sy);
z[sum] = stod(sz);
sum++;
}
myfile.close();
}
fft(x, outx, sum);
fft(y, outy, sum);
fft(z, outz, sum);
ofstream ofs("output.txt", ofstream::out);
double freq = 0.368324125;
/*for (int i = 1; i < 2069; i++) {
ofs << sqrt((outx[i][0] * outx[i][0]) + (outx[i][1] * outx[i][1])) << ","
<< sqrt((outy[i][0] * outy[i][0]) + (outy[i][1] * outy[i][1])) << ","
<< sqrt((outz[i][0] * outz[i][0]) + (outz[i][1] * outz[i][1])) << ","
<< freq << endl;
freq += 0.736826270;
}*/
for (int i = 1; i < sum; i++) {
ofs << sqrt((outx[i] * outx[i]) + (outx[i] * outx[i])) << ","
<< sqrt((outy[i] * outy[i]) + (outy[i] * outy[i])) << ","
<< sqrt((outz[i] * outz[i]) + (outz[i] * outz[i])) << ","
<< freq << endl;
freq += 0.368324125;
}
return 0;
}
|
116a7dae4708c8df89b1e84367e373e3763f0273
|
[
"C++"
] | 1
|
C++
|
luccaki/TestFastFourierTransform
|
ad7d80d36e55f99b9ec0ae405f2a1f24477ffc0a
|
44f01bc8a5587fe37dcd52a19dfac589ed0caeb2
|
refs/heads/master
|
<repo_name>Darkwood9612/PingPong<file_sep>/src/Controller.h
#pragma once
#include "GameModel.h"
#include <SDL2\SDL_events.h>
#include <ctime>
class Controller
{
public:
void UpdateModel(GameModel& model);
private:
const int BALL_UPDATE_PAUSE = 300;
void KeyDown(SDL_Keysym& s, GameModel& model);
SDL_Event event;
clock_t lastApply = 0;
};<file_sep>/src/View.cpp
#include <SDL2\SDL_ttf.h>
#include "SurfaceStorage.h"
#include "View.h"
void View::DrawScore(GameModel& gameModel, Window& window,
SurfaceStorage& surfaceStorage)
{
SDL_Surface* ScoreImage =
gameModel.GetPlayerScoreSurface(window.windowPlayerScore, surfaceStorage);
window.windowPlayerScore = gameModel.GetPlayerScore();
SDL_Rect rect = window.GetPlayerScoreRect();
rect.x -= ScoreImage->w;
SDL_BlitSurface(ScoreImage, NULL, window.screen, &rect);
ScoreImage =
gameModel.GetBotScoreSurface(window.windowBotScore, surfaceStorage);
window.windowBotScore = gameModel.GetBotScore();
rect = window.GetBotScoreRect();
SDL_BlitSurface(ScoreImage, NULL, window.screen, &rect);
}
void View::Draw(GameModel& gameModel, Window& window,
SurfaceStorage& surfaceStorage)
{
window.SetDividingStripXOffset(
gameModel.dividingStrip ? gameModel.dividingStrip->w / 2 : 0);
SDL_FillRect(window.screen, NULL,
SDL_MapRGB(window.screen->format, 0, 0, 0));
SDL_Surface platformBackground = gameModel.GetPlatformBackground();
SDL_Surface ballBackground = gameModel.GetBallBackground();
SDL_Rect playerRect = gameModel.GetPlayerRect();
SDL_Rect botRect = gameModel.GetBotRect();
SDL_Rect dividingStripRect = window.GetDividingStripRect();
SDL_Rect ballRect = gameModel.GetBallRect();
SDL_BlitSurface(gameModel.dividingStrip, NULL, window.screen,
&dividingStripRect);
SDL_BlitSurface(&platformBackground, NULL, window.screen, &playerRect);
SDL_BlitSurface(&platformBackground, NULL, window.screen, &botRect);
SDL_BlitSurface(&ballBackground, NULL, window.screen, &ballRect);
DrawScore(gameModel, window, surfaceStorage);
SDL_UpdateWindowSurface(window.window);
}
<file_sep>/src/GameModel.h
#pragma once
#include "ArtificialIntelligencePlatform.h"
#include "AudioStorage.h"
#include "Ball.h"
#include "SurfaceStorage.h"
#include "Window.h"
class GameModel
{
public:
explicit GameModel(Window& windowModel, SDL_Surface* platformSurface);
void PlayerPlatformMoveDown();
void PlayerPlatformMoveUp();
void BotPlatformMove();
void MoveBall();
SDL_Surface GetPlatformBackground();
SDL_Surface GetBallBackground();
SDL_Rect GetPlayerRect();
SDL_Rect GetBotRect();
SDL_Rect GetBallRect();
int GetBallSpeed() { return ball.speed; };
bool needCloseGame = false;
SDL_Surface* dividingStrip = nullptr;
void SetGameSpeed(int newSpeed);
void AddPointToPlayer() { ++this->playerPoints; };
void AddPointToBot() { ++this->botPoints; };
int GetPlayerScore() { return this->playerPoints; };
int GetBotScore() { return this->botPoints; };
SDL_Surface* GetPlayerScoreSurface(int windowScore,
SurfaceStorage& surfaceStorage);
SDL_Surface* GetBotScoreSurface(int windowScore,
SurfaceStorage& surfaceStorage);
void CreateBall(SDL_Surface* background, SDL_Rect rect = SDL_Rect());
SDL_Rect GetScreenCenter() { return screenCenter; };
AudioStorage audioStorage;
private:
const std::string playerPointsId = "playerScore";
const std::string botPointsId = "botScore";
int playerPoints = 0;
int botPoints = 0;
const int SCREEN_WIDTH;
const int SCREEN_HEIGHT;
SDL_Rect screenCenter;
Ball ball;
const float X_PLAYER_PLATFORM_OFFSET = 0.1f;
const float X_BOT_PLATFORM_OFFSET = 0.9f;
Platform playerPlatform;
ArtificialIntelligencePlatform botPlatform;
};<file_sep>/src/ArtificialIntelligencePlatform.cpp
#include "ArtificialIntelligencePlatform.h"
#include "Ball.h"
void ArtificialIntelligencePlatform::operator=(
const ArtificialIntelligencePlatform& platformAI)
{
this->rect = platformAI.rect;
this->background = platformAI.background;
this->speed = platformAI.speed;
}
void ArtificialIntelligencePlatform::HitBall(const int SCREEN_HEIGHT,
float angleBallFlight,
SDL_Rect ballRect)
{
TryCatchBall(SCREEN_HEIGHT, angleBallFlight, ballRect);
}
void ArtificialIntelligencePlatform::TryCatchBall(const int SCREEN_HEIGHT,
float angleBallFlight,
SDL_Rect ballPointTarget)
{
bool isBallFlightDown = 360 - angleBallFlight > 180;
bool isBallFlightToPlayer =
isBallFlightDown ? angleBallFlight > 90 : angleBallFlight < 270;
if (isBallFlightToPlayer)
return;
int randoOffset = rand() % rect.h;
isBallFlightDown ? ballPointTarget.y += randoOffset
: ballPointTarget.y -= randoOffset;
int halfHeight = rect.h / 2;
auto centrPlatformY = rect.y + halfHeight;
bool abovePoint = ballPointTarget.y <= centrPlatformY - halfHeight;
bool belowPoint = ballPointTarget.y >= centrPlatformY + halfHeight;
if (abovePoint)
(rect.y - STEP > 0) ? rect.y -= STEP : NULL;
if (belowPoint)
(rect.y + STEP + rect.h < SCREEN_HEIGHT) ? rect.y += STEP : NULL;
}
<file_sep>/src/GameModel.cpp
#include "GameModel.h"
#include <stdexcept>
#include <string>
namespace {
SDL_Surface* ScoreToSurface(int number, const std::string& name,
SurfaceStorage& surfaceStorage)
{
std::string score = std::to_string(number);
auto scoreImage = TTF_RenderText_Solid(
surfaceStorage.GetFont(), score.c_str(), surfaceStorage.GetWhite());
if (!scoreImage) {
std::string err = TTF_GetError();
throw std::runtime_error("Error in function 'TTF_RenderText_Solid': " +
err);
}
surfaceStorage.SetBMP(name, scoreImage);
return scoreImage;
}
SDL_Surface* GetScoreSurface(int gameScore, int windowScore,
const std::string name,
SurfaceStorage& surfaceStorage)
{
return gameScore != windowScore
? ScoreToSurface(gameScore, name, surfaceStorage)
: surfaceStorage.GetBMP(name);
};
}
GameModel::GameModel(Window& window, SDL_Surface* platformSurface)
: SCREEN_HEIGHT(window.SCREEN_HEIGHT)
, SCREEN_WIDTH(window.SCREEN_WIDTH)
{
if (!platformSurface)
throw std::runtime_error("platformSurface == nullptr");
SDL_Rect playerRect = { int(window.SCREEN_WIDTH * X_PLAYER_PLATFORM_OFFSET),
int(window.SCREEN_HEIGHT / 2 -
platformSurface->h / 2),
platformSurface->w, platformSurface->h };
SDL_Rect botRect = { int(window.SCREEN_WIDTH * X_BOT_PLATFORM_OFFSET),
int(window.SCREEN_HEIGHT / 2 - platformSurface->h / 2),
platformSurface->w, platformSurface->h };
playerPlatform = Platform(playerRect, platformSurface);
botPlatform = ArtificialIntelligencePlatform(botRect, platformSurface);
screenCenter.x = window.SCREEN_WIDTH / 2;
screenCenter.y = window.SCREEN_HEIGHT / 2;
};
void GameModel::PlayerPlatformMoveDown()
{
if (playerPlatform.rect.y + playerPlatform.rect.h < SCREEN_HEIGHT)
playerPlatform.rect.y = playerPlatform.rect.y + 1 * playerPlatform.speed;
}
void GameModel::PlayerPlatformMoveUp()
{
if (playerPlatform.rect.y > 0)
playerPlatform.rect.y = playerPlatform.rect.y - 1 * playerPlatform.speed;
}
void GameModel::BotPlatformMove()
{
botPlatform.HitBall(SCREEN_HEIGHT, ball.GetAngleOfFlight(), ball.rect);
}
void GameModel::MoveBall()
{
ball.Move(
SCREEN_WIDTH, SCREEN_HEIGHT, GetPlayerRect(), GetBotRect(),
[&]() {
audioStorage.PlaySoundEffect(audioStorage.collisionMusicName, 0);
},
[&](bool isPlayerWin) {
isPlayerWin ? this->AddPointToPlayer() : this->AddPointToBot();
ball.Respawn(screenCenter, isPlayerWin);
audioStorage.PlaySoundEffect(audioStorage.respawnMusicName, 0);
});
}
SDL_Surface GameModel::GetPlatformBackground()
{
return playerPlatform.background ? *playerPlatform.background
: SDL_Surface();
}
SDL_Surface GameModel::GetBallBackground()
{
return ball.background ? *ball.background : SDL_Surface();
;
}
SDL_Rect GameModel::GetPlayerRect()
{
return playerPlatform.rect;
}
SDL_Rect GameModel::GetBotRect()
{
return botPlatform.rect;
}
SDL_Rect GameModel::GetBallRect()
{
return ball.rect;
}
void GameModel::SetGameSpeed(int newSpeed)
{
playerPlatform.speed = newSpeed;
botPlatform.speed = newSpeed;
ball.speed = newSpeed;
}
SDL_Surface* GameModel::GetPlayerScoreSurface(int windowScore,
SurfaceStorage& surfaceStorage)
{
return playerPoints != windowScore
? ScoreToSurface(playerPoints, playerPointsId, surfaceStorage)
: surfaceStorage.GetBMP(playerPointsId);
}
SDL_Surface* GameModel::GetBotScoreSurface(int windowScore,
SurfaceStorage& surfaceStorage)
{
return botPoints != windowScore
? ScoreToSurface(botPoints, botPointsId, surfaceStorage)
: surfaceStorage.GetBMP(botPointsId);
}
void GameModel::CreateBall(SDL_Surface* background, SDL_Rect rect)
{
ball = Ball(rect, background);
}
<file_sep>/src/main.cpp
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_ttf.h>
#include <Windows.h>
#include "Controller.h"
#include "GameModel.h"
#include "SurfaceStorage.h"
#include "View.h"
#include "AudioStorage.h"
#include <filesystem>
#include <stdexcept>
#undef main
namespace {
constexpr char* PLATFORM_BACKGROUND_PATH = "image\\platform.bmp";
constexpr char* SIVIDING_STRIP_BACKGROUND_PATH = "image\\dividingStrip.bmp";
constexpr char* BALL_BACKGROUND_PATH = "image\\ball.bmp";
constexpr char* SOUND_COLLISION_WAV_PATH = "sound\\collision.wav";
constexpr char* BACKGROUND_MUSIC_PATH = "sound\\background_music.wav";
constexpr char* SOUND_RESPAWN_PATH = "sound\\respawn.wav";
constexpr int AUDIO_BUFFERS = 4096;
constexpr char* FONT_PATH = "font\\fast99.ttf";
constexpr int FONT_SIZE = 36;
constexpr char* WINDOW_TITLE = "PingPong";
}
int Quit(SDL_Window* window, SurfaceStorage& surfaceStorage,
AudioStorage& audioStorage)
{
surfaceStorage.FreeAllSurfaces();
audioStorage.FreeAllMusic();
audioStorage.FreeAllSoundEffect();
window ? SDL_DestroyWindow(window)
: throw std::runtime_error("window == nullptr");
Mix_CloseAudio();
Mix_Quit();
TTF_Quit();
SDL_Quit();
return 0;
}
int main(int argc, char** args)
{
// while (!IsDebuggerPresent()) {
// Sleep(1);
//}
std::string tmp;
auto getAbsoluatePath = [&](const char* relativePath) {
tmp =
(std::filesystem::path(args[0]).parent_path() / relativePath).string();
return tmp.c_str();
};
srand(0);
try {
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) {
std::string err = SDL_GetError();
throw std::runtime_error("Fatal initialization SDL error: " + err);
}
if (TTF_Init() != 0) {
std::string err = TTF_GetError();
throw std::runtime_error("Fatal initialization TTF error: " + err);
}
if (MIX_INIT_MID != Mix_Init(MIX_INIT_MID)) {
std::string err = Mix_GetError();
throw std::runtime_error("Could not initialize mixer Mix_Init: " + err);
}
SurfaceStorage surfaceStorage(getAbsoluatePath(FONT_PATH), FONT_SIZE);
Controller controller;
Window window = Window(WINDOW_TITLE, SDL_WINDOW_SHOWN, 1024, 768);
if (!window.window)
throw std::runtime_error("window == nullptr");
GameModel gameModel =
GameModel(window,
surfaceStorage.LoadBMP(
"platform", getAbsoluatePath(PLATFORM_BACKGROUND_PATH)));
gameModel.dividingStrip = surfaceStorage.LoadBMP(
"dividingStrip", getAbsoluatePath(SIVIDING_STRIP_BACKGROUND_PATH));
gameModel.CreateBall(
surfaceStorage.LoadBMP("ball", getAbsoluatePath(BALL_BACKGROUND_PATH)),
gameModel.GetScreenCenter());
gameModel.audioStorage = AudioStorage(44100, MIX_DEFAULT_FORMAT,
MIX_DEFAULT_CHANNELS, AUDIO_BUFFERS);
gameModel.audioStorage.LoadSoundEffect(
gameModel.audioStorage.collisionMusicName,
getAbsoluatePath(SOUND_COLLISION_WAV_PATH));
gameModel.audioStorage.LoadSoundEffect(
gameModel.audioStorage.respawnMusicName,
getAbsoluatePath(SOUND_RESPAWN_PATH));
gameModel.audioStorage.LoadMusic(
gameModel.audioStorage.backgroundMusicName,
getAbsoluatePath(BACKGROUND_MUSIC_PATH));
gameModel.audioStorage.PlayMusic(
gameModel.audioStorage.backgroundMusicName, -1);
while (true) {
controller.UpdateModel(gameModel);
View::Draw(gameModel, window, surfaceStorage);
if (gameModel.needCloseGame)
break;
}
return Quit(window.window, surfaceStorage, gameModel.audioStorage);
} catch (const std::exception& e) {
MessageBox(NULL, e.what(), NULL, MB_OK);
}
};<file_sep>/src/AudioStorage.cpp
#include "AudioStorage.h"
#include <stdexcept>
AudioStorage::AudioStorage(int frequency, Uint16 format, int channels,
int chunksize)
{
if (Mix_OpenAudio(frequency, format, channels, chunksize) != 0) {
std::string err = Mix_GetError();
throw std::runtime_error("Fatal Mix_OpenAudio error: " + err);
}
}
void AudioStorage::LoadSoundEffect(const std::string name, const char* path)
{
if (auto soundEffect = Mix_LoadWAV(path)) {
auto findResult = this->storageSoundEffect.find(name);
findResult == this->storageSoundEffect.end()
? this->storageSoundEffect[name] = soundEffect
: throw std::runtime_error("LoadMID error: SoundEffect already exists");
return;
}
throw std::runtime_error("LoadMID error: SoundEffect == nullptr");
}
void AudioStorage::LoadMusic(const std::string name, const char* path)
{
if (auto music = Mix_LoadMUS(path)) {
auto findResult = this->storageMusic.find(name);
findResult == this->storageMusic.end()
? this->storageMusic[name] = music
: throw std::runtime_error("LoadMID error: music already exists");
return;
}
throw std::runtime_error("LoadMID error: music == nullptr");
}
void AudioStorage::operator=(const AudioStorage& audioStorage)
{
this->storageMusic = audioStorage.storageMusic;
this->storageSoundEffect = audioStorage.storageSoundEffect;
}
void AudioStorage::FreeMusic(const std::string name)
{
auto findResult = this->storageMusic.find(name);
if (findResult != this->storageMusic.end()) {
Mix_FreeMusic(findResult->second);
this->storageMusic.erase(findResult);
}
}
void AudioStorage::FreeAllMusic()
{
for (auto& item : this->storageMusic)
Mix_FreeMusic(item.second);
this->storageMusic.clear();
}
void AudioStorage::FreeSoundEffect(const std::string name)
{
auto findResult = this->storageSoundEffect.find(name);
if (findResult != this->storageSoundEffect.end()) {
Mix_FreeChunk(findResult->second);
this->storageSoundEffect.erase(findResult);
}
}
void AudioStorage::FreeAllSoundEffect()
{
for (auto& item : this->storageSoundEffect)
Mix_FreeChunk(item.second);
this->storageSoundEffect.clear();
}
void AudioStorage::PlayMusic(const std::string name, int loops)
{
auto music = storageMusic.find(name);
if (music == storageMusic.end()) {
throw std::runtime_error("PlayMusic error: music not found. name: " +
name);
}
if (Mix_FadeInMusic(music->second, loops, 0) == -1) {
std::string err = Mix_GetError();
throw std::runtime_error("Mix_PlayMusic: " + err);
}
}
void AudioStorage::PlaySoundEffect(const std::string name, int loops)
{
auto soundEffect = storageSoundEffect.find(name);
if (soundEffect == storageSoundEffect.end()) {
throw std::runtime_error("PlayMusic error: soundEffect not found. name: " +
name);
}
Mix_PlayChannel(-1, soundEffect->second, loops);
}
<file_sep>/src/AudioStorage.h
#pragma once
#include <SDL2\SDL_mixer.h>
#include <map>
#include <string>
class AudioStorage
{
public:
AudioStorage(){};
AudioStorage(int frequency, Uint16 format, int channels, int chunksize);
void LoadSoundEffect(const std::string name, const char* path);
void LoadMusic(const std::string name, const char* path);
void operator=(const AudioStorage& audioStorage);
void FreeMusic(const std::string name);
void FreeAllMusic();
void FreeSoundEffect(const std::string name);
void FreeAllSoundEffect();
void PlayMusic(const std::string name, int loops);
void PlaySoundEffect(const std::string name, int loops);
const std::string collisionMusicName = "collision";
const std::string backgroundMusicName = "background";
const std::string respawnMusicName = "respawn";
private:
using StorageMusic = std::map<std::string, Mix_Music*>;
using StorageSoundEffect = std::map<std::string, Mix_Chunk*>;
StorageMusic storageMusic;
StorageSoundEffect storageSoundEffect;
};<file_sep>/src/Window.cpp
#include "Window.h"
Window::Window(const char* title, uint32_t windowFlags,
const int _SCREEN_WIDTH, const int _SCREEN_HEIGHT)
: SCREEN_WIDTH(_SCREEN_WIDTH)
, SCREEN_HEIGHT(_SCREEN_HEIGHT)
{
this->window =
SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH, SCREEN_HEIGHT, windowFlags);
this->screen = SDL_GetWindowSurface(this->window);
this->playerScoreRect = { int(SCREEN_WIDTH * X_PLAYER_SCORE_OFFSET),
int(SCREEN_HEIGHT * Y_SCORE_OFFSET), 0, 0 };
this->botScoreRect = { int(SCREEN_WIDTH * X_BOT_SCORE_OFFSET),
int(SCREEN_HEIGHT * Y_SCORE_OFFSET), 0, 0 };
this->dividingStripRect = { SCREEN_WIDTH / 2, 0, 0, 0 };
}
void Window::SetDividingStripXOffset(int offset)
{
dividingStripRect = { SCREEN_WIDTH / 2 - offset, 0, 0, 0 };
}
<file_sep>/src/Controller.cpp
#include "Controller.h"
void Controller::UpdateModel(GameModel& model)
{
if (clock() - lastApply > BALL_UPDATE_PAUSE / model.GetBallSpeed()) {
model.MoveBall();
model.BotPlatformMove();
lastApply = clock();
}
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
model.needCloseGame = true;
break;
case SDL_KEYDOWN:
KeyDown(event.key.keysym, model);
break;
default:
return;
}
}
}
void Controller::KeyDown(SDL_Keysym& s, GameModel& model)
{
switch (s.sym) {
case SDLK_UP:
model.PlayerPlatformMoveUp();
break;
case SDLK_DOWN:
model.PlayerPlatformMoveDown();
break;
default:
break;
}
}
<file_sep>/README.md
# PingPong
### [Посмотреть как это выглядит на YouTube](https://youtu.be/COil22iG_zE)
### [Скачать опубликованный релиз 1.0](https://github.com/Darkwood9612/PingPong/releases/tag/1.0)
### Требования:
1. Показать знание языка C++ (не С).
2. Показать знание ООП и умение его использовать.
* Использовалось только наследование и инкапсуляция. В Полиморфизме, по моему мнению, для этого проекта нет необходимости, также как и делать многопоточную архитертуру.
3. Показать умение использовать STL.
* В проекте используются контейнеры `map`, шаблоны класса `function`, а также происходит взаимодействие с итераторами.
4. Аккуратно оформленный структурированный код.
* Код оформлен в виде классов, которые разбиты по файлам `.h` и `.cpp`. Каждый класс имеет свою зону ответственности.
5. Показать умение подключать и использовать внешние библиотеки.
* Для системы сборки используется `CMake`, для управления зависимостями `vcpkg` + `pmm`. Зависимости включают в себя далее перечисленные библиотеки: `SDL2` , `SDL2_ttf`, `SDL2_image`, `SDL2_mixer`.
6. Показать знание архитектуры игровых движков.
7. Показать использование паттернов проектирования (не только Singleton).
* В качестве архитектуры игры был выбран паттерн **Model-View-Controller**
8. Код должен компилироваться либо под Win32 либо под Ubuntu 16.04 x64 или 18.04 x64, чтобы можно было проверить, а также запускаться без дополнительных телодвижений (F5 или же непосредственно запуск из папки с бинарником).
* Проект собирается под Windows, после компиляции поддерживается запуск по нажатию `F5` в `VisualStudio` , а также из папки с `.exe` файлом.
<file_sep>/src/Platform.h
#pragma once
#include <SDL_rect.h>
#include <SDL_surface.h>
class Platform
{
public:
Platform(){};
Platform(SDL_Rect _rect, SDL_Surface* _background)
: rect(_rect)
, background(_background){};
SDL_Surface* background = nullptr;
SDL_Rect rect = { 0, 0, 0, 0 };
int speed = 12;
};<file_sep>/src/View.h
#pragma once
#include "GameModel.h"
#include "Window.h"
class SurfaceStorage;
class View
{
public:
static void Draw(GameModel& gameModel, Window& window,
SurfaceStorage& surfaceStorage);
private:
static void DrawScore(GameModel& gameModel, Window& window,
SurfaceStorage& surfaceStorage);
};<file_sep>/src/Window.h
#pragma once
#include <SDL2\SDL_video.h>
class Window
{
public:
Window(const char* title, uint32_t windowFlags = SDL_WINDOW_SHOWN,
const int _SCREEN_WIDTH = 640, const int _SCREEN_HEIGHT = 480);
SDL_Surface* screen = nullptr;
SDL_Window* window = nullptr;
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
int windowPlayerScore = -1;
int windowBotScore = -1;
SDL_Rect GetPlayerScoreRect() { return playerScoreRect; };
SDL_Rect GetBotScoreRect() { return botScoreRect; };
SDL_Rect GetDividingStripRect() { return dividingStripRect; };
void SetDividingStripXOffset(int offset);
private:
const float X_PLAYER_SCORE_OFFSET = 0.4;
const float X_BOT_SCORE_OFFSET = 0.6;
const float Y_SCORE_OFFSET = 0.06;
SDL_Rect dividingStripRect;
SDL_Rect playerScoreRect;
SDL_Rect botScoreRect;
};<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.17)
project(testTask CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(VCPKG_REVISION f29a191d0afccc3ed6f481283d6d15e0186096ae)
# Download vcpkg dependencies
include(cmake/pmm.cmake)
set(ports sdl2:x64-windows sdl2-ttf:x64-windows sdl2-image:x64-windows sdl2-mixer:x64-windows)
pmm(VCPKG
REVISION ${VCPKG_REVISION}
REQUIRES ${ports}
)
file(GLOB src "${CMAKE_CURRENT_SOURCE_DIR}/src/*" "${CMAKE_CURRENT_SOURCE_DIR}/.clang-format")
add_executable(test_task ${src})
set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT test_task)
find_package(SDL2 REQUIRED)
target_link_libraries(test_task PRIVATE SDL2::SDL2-static)
find_package(SDL2-ttf REQUIRED)
target_link_libraries(test_task PRIVATE SDL2::SDL2_ttf)
find_package(SDL2-image REQUIRED)
target_link_libraries(test_task PRIVATE SDL2::SDL2_image)
find_package(SDL2-mixer REQUIRED)
target_link_libraries(test_task PRIVATE SDL2::SDL2_mixer)
add_custom_target(copy_fonts ALL
COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/image $<TARGET_FILE_DIR:test_task>/image
COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/font $<TARGET_FILE_DIR:test_task>/font
COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/sound $<TARGET_FILE_DIR:test_task>/sound
)<file_sep>/src/ArtificialIntelligencePlatform.h
#pragma once
#include "Platform.h"
class ArtificialIntelligencePlatform : public Platform
{
public:
ArtificialIntelligencePlatform(){};
ArtificialIntelligencePlatform(SDL_Rect _rect, SDL_Surface* _background)
: Platform(_rect, _background){};
void operator=(const ArtificialIntelligencePlatform& platformAI);
void HitBall(const int SCREEN_HEIGHT, float angleBallFlight,
SDL_Rect ballRect);
private:
const int STEP = 3;
void TryCatchBall(const int SCREEN_HEIGHT, float angleBallFlight,
SDL_Rect ballPointTarget);
};<file_sep>/src/Ball.h
#pragma once
#include "Platform.h"
#include <functional>
#include <time.h>
class Ball : public Platform
{
public:
SDL_Rect GetPositionPointOnCircle(float radius, const SDL_Rect& centrPos,
float degrees);
Ball(){};
Ball(SDL_Rect _rect, SDL_Surface* _background)
: Platform(_rect, _background){};
void operator=(const Ball& ball);
float GetAngleOfFlight() { return angleOfFlight; };
void Respawn(SDL_Rect spawnPoint, bool isPlayerLose);
void Move(const int SCREEN_WIDTH, const int SCREEN_HEIGHT,
SDL_Rect playerRect, SDL_Rect botRect,
std::function<void(void)> collisionCallback,
std::function<void(bool)> scoreCallback);
private:
int STEP = 5;
float angleOfFlight = 20.f;
};<file_sep>/src/Ball.cpp
#include "Ball.h"
#include <math.h>
namespace {
constexpr double PI = 3.14159265358979323846;
}
SDL_Rect Ball::GetPositionPointOnCircle(float radius, const SDL_Rect& centrPos,
float degrees)
{
float radian = degrees * (PI / 180);
float x = radius * cos(radian) + centrPos.x;
float y = radius * sin(radian) + centrPos.y;
return { int(x), int(y), 0, 0 };
}
void Ball::operator=(const Ball& ball)
{
this->angleOfFlight = ball.angleOfFlight;
this->background = ball.background;
this->rect = ball.rect;
this->speed = ball.speed;
this->STEP = ball.STEP;
}
void Ball::Respawn(SDL_Rect spawnPoint, bool isPlayerLose)
{
rect = spawnPoint;
float randNum = rand() % 90;
randNum = randNum < 10 ? 10 : randNum;
angleOfFlight = isPlayerLose
? 135.f + randNum
: 405.f - (randNum > 45.f ? randNum : randNum + 360.f);
}
void Ball::Move(const int SCREEN_WIDTH, const int SCREEN_HEIGHT,
SDL_Rect playerRect, SDL_Rect botRect,
std::function<void(void)> collisionCallback,
std::function<void(bool)> scoreCallback)
{
auto nextPoint = GetPositionPointOnCircle(STEP, rect, angleOfFlight);
if (nextPoint.x <= playerRect.x + playerRect.w &&
nextPoint.x >= playerRect.x && nextPoint.y >= playerRect.y &&
nextPoint.y <= playerRect.y + playerRect.h) {
collisionCallback();
angleOfFlight = 180 - angleOfFlight;
angleOfFlight = angleOfFlight < 0 ? angleOfFlight += 360 : angleOfFlight;
rect = GetPositionPointOnCircle(STEP, rect, angleOfFlight);
return;
}
if (nextPoint.x <= botRect.x + botRect.w && nextPoint.x >= botRect.x &&
nextPoint.y >= botRect.y && nextPoint.y <= botRect.y + botRect.h) {
collisionCallback();
angleOfFlight = 180 - angleOfFlight;
angleOfFlight = angleOfFlight < 0 ? angleOfFlight += 360 : angleOfFlight;
rect = GetPositionPointOnCircle(STEP, rect, angleOfFlight);
return;
}
if (nextPoint.x <= 1 || nextPoint.x >= SCREEN_WIDTH - 1) {
angleOfFlight = 180 - angleOfFlight;
angleOfFlight = angleOfFlight < 0 ? angleOfFlight += 360 : angleOfFlight;
rect = GetPositionPointOnCircle(STEP, rect, angleOfFlight);
collisionCallback();
scoreCallback(nextPoint.x <= 0 ? false : true);
return;
}
if (nextPoint.y <= 1 || nextPoint.y >= SCREEN_HEIGHT - 1) {
angleOfFlight = 360 - angleOfFlight;
rect = GetPositionPointOnCircle(STEP, rect, angleOfFlight);
collisionCallback();
return;
}
if (nextPoint.x > 0 && nextPoint.x < SCREEN_WIDTH && nextPoint.y > 0 &&
nextPoint.y < SCREEN_HEIGHT) {
rect = nextPoint;
return;
}
}
<file_sep>/src/SurfaceStorage.h
#pragma once
#include <SDL2\SDL_surface.h>
#include <SDL2\SDL_ttf.h>
#include <map>
#include <string>
class SurfaceStorage
{
public:
SurfaceStorage(const char* fontPath, int fontSize);
SDL_Surface* LoadBMP(const std::string name, const char* path);
void SetBMP(const std::string name, SDL_Surface* surface);
SDL_Surface* GetBMP(const std::string name);
void FreeSurface(const std::string name);
void FreeAllSurfaces();
TTF_Font* GetFont() { return this->myFont; };
SDL_Color GetWhite() { return this->colorWhite; };
SDL_Color GetBlack() { return this->colorBlack; };
private:
using Storage = std::map<std::string, SDL_Surface*>;
SDL_Color colorWhite = { 255, 255, 255 };
SDL_Color colorBlack = { 0, 0, 0 };
TTF_Font* myFont = nullptr;
Storage storage;
};<file_sep>/src/SurfaceStorage.cpp
#include "SurfaceStorage.h"
#include <stdexcept>
SurfaceStorage::SurfaceStorage(const char* fontPath, int fontSize)
{
this->myFont = TTF_OpenFont(fontPath, fontSize);
if (!this->myFont) {
std::string err = TTF_GetError();
throw std::runtime_error("Error in function 'TTF_OpenFont': " + err);
}
}
SDL_Surface* SurfaceStorage::LoadBMP(const std::string name, const char* path)
{
if (auto surface = SDL_LoadBMP(path)) {
auto findResult = this->storage.find(name);
findResult == this->storage.end()
? this->storage[name] = surface
: throw std::runtime_error("LoadBMP error: name already exists");
return surface;
}
throw std::runtime_error("LoadBMP error: surface == nullptr");
}
void SurfaceStorage::SetBMP(const std::string name, SDL_Surface* surface)
{
auto findResult = this->storage.find(name);
if (findResult != this->storage.end()) {
SDL_FreeSurface(findResult->second);
}
this->storage[name] = surface;
}
SDL_Surface* SurfaceStorage::GetBMP(const std::string name)
{
auto findResult = this->storage.find(name);
return findResult != this->storage.end() ? findResult->second : nullptr;
}
void SurfaceStorage::FreeSurface(const std::string name)
{
auto findResult = this->storage.find(name);
if (findResult != this->storage.end()) {
SDL_FreeSurface(findResult->second);
this->storage.erase(findResult);
}
}
void SurfaceStorage::FreeAllSurfaces()
{
for (auto& item : this->storage)
SDL_FreeSurface(item.second);
this->storage.clear();
}
|
a8aed4bdd89c73179d57f1f7e3d8798187cc1570
|
[
"Markdown",
"CMake",
"C++"
] | 20
|
C++
|
Darkwood9612/PingPong
|
cf74e1b2548e35c0514e372d99b3730205ff2145
|
ed01d353367fa75ef5afe8ecaea2009cb143345d
|
refs/heads/master
|
<repo_name>RyanOvO/MyWebApi<file_sep>/MyWebApi/MyWebApi/OrderAppService.cs
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApiHelper;
namespace MyWebApi
{
public class OrderAppService : ApplicationService
{
private static readonly Dictionary<int, string> Apples = new Dictionary<int, string>()
{
[1] = "Big Apple",
[2] = "Small Apple"
};
/// <summary>
/// Get All Apple.
/// </summary>
/// <returns></returns>
public string GetAll(int id)
{
return "111";
}
/// <summary>
/// action
/// 路由 /api/Order/OrderById?Id=6
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public string GetOrderById(int id)
{
return $"自定义Api控制器方法返回的参数{id}";
}
}
}
<file_sep>/MyWebApi/WebApiHelper/IApplicationService.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace WebApiHelper
{
public interface IApplicationService : IRemoteService
{
}
}
<file_sep>/MyWebApi/WebApiHelper/MyWebApiServiceExtension.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebApiHelper
{
public static class MyWebApiServiceExtension
{
/// <summary>
/// Add Dynamic WebApi to Container
/// </summary>
/// <param name="services"></param>
/// <param name="options">configuration</param>
/// <returns></returns>
public static IServiceCollection AddMyWebApi(this IServiceCollection services, MyWebApiOptions options)
{
if (options == null)
{
throw new ArgumentException(nameof(options));
}
options.Valid();
AppConsts.DefaultAreaName = options.DefaultAreaName;
AppConsts.DefaultHttpVerb = options.DefaultHttpVerb;
AppConsts.DefaultApiPreFix = options.DefaultApiPrefix;
AppConsts.ControllerPostfixes = options.RemoveControllerPostfixes;
AppConsts.ActionPostfixes = options.RemoveActionPostfixes;
AppConsts.FormBodyBindingIgnoredTypes = options.FormBodyBindingIgnoredTypes;
var partManager = services.FirstOrDefault(f => f.ServiceType == typeof(ApplicationPartManager))?.ImplementationInstance as ApplicationPartManager;
if (partManager == null)
{
throw new InvalidOperationException("\"AddDynamicWebApi\" must be after \"AddMvc\".");
}
// 自定义控制器入口
partManager.FeatureProviders.Add(new MyWebApiControllerFeatureProvider());
// 以约定的形式覆盖控制器
services.Configure<MvcOptions>(o =>
{
// Register Controller Routing Information Converter
o.Conventions.Add(new MyWebApiConvention(services));
});
return services;
}
public static IServiceCollection AddMyWebApi(this IServiceCollection services)
{
return AddMyWebApi(services, new MyWebApiOptions());
}
}
}
<file_sep>/MyWebApi/WebApiHelper/IRemoteService.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace WebApiHelper
{
/// <summary>
/// 远程接口(用于识别自定义webapi)
/// </summary>
public interface IRemoteService
{
}
}
<file_sep>/MyWebApi/WebApiHelper/ApplicationService.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace WebApiHelper
{
public abstract class ApplicationService : IApplicationService
{
public static string[] CommonPostfixes { get; set; } = { "AppService", "ApplicationService" };
}
}
<file_sep>/MyWebApi/WebApiHelper/MyWebApiConvention.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace WebApiHelper
{
public class MyWebApiConvention : IApplicationModelConvention
{
private readonly IServiceCollection _services;
public MyWebApiConvention(IServiceCollection services) => _services = services;
public void Apply(ApplicationModel application)
{
if(application.Controllers.Count <= 0)
{
return;
}
foreach(var controller in application.Controllers)
{
var controllerType = controller.ControllerType.AsType();
if(typeof(IRemoteService).GetTypeInfo().IsAssignableFrom(controllerType))
{
controller.ControllerName = controller.ControllerName.RemovePostFix(ApplicationService.CommonPostfixes);
ConfigureDynamicWebApi(controller);
}
}
}
private void ConfigureDynamicWebApi(ControllerModel controller)
{
ConfigureApiExplorer(controller);
// Api选择器,主要是路由配置
ConfigureSelector(controller);
ConfigureParameters(controller);
}
private void ConfigureParameters(ControllerModel controller)
{
foreach (var action in controller.Actions)
{
foreach (var para in action.Parameters)
{
if (para.BindingInfo != null)
{
continue;
}
if (!TypeHelper.IsPrimitiveExtendedIncludingNullable(para.ParameterInfo.ParameterType))
{
if (CanUseFormBodyBinding(action, para))
{
para.BindingInfo = BindingInfo.GetBindingInfo(new[] { new FromBodyAttribute() });
}
}
}
}
}
#region ApiExplorer
private void ConfigureApiExplorer(ControllerModel controller)
{
if (controller.ApiExplorer.GroupName.IsNullOrEmpty())
{
controller.ApiExplorer.GroupName = controller.ControllerName;
}
if (controller.ApiExplorer.IsVisible == null)
{
controller.ApiExplorer.IsVisible = true;
}
foreach (var action in controller.Actions)
{
ConfigureApiExplorer(action);
}
}
private void ConfigureApiExplorer(ActionModel action)
{
if (action.ApiExplorer.IsVisible == null)
{
action.ApiExplorer.IsVisible = true;
}
}
#endregion
private void ConfigureSelector(ControllerModel controller)
{
RemoveEmptySelectors(controller.Selectors);
if (controller.Selectors.Any(selector => selector.AttributeRouteModel != null))
{
return;
}
var areaName = string.Empty;
foreach (var action in controller.Actions)
{
ConfigureSelector(areaName, controller.ControllerName, action);
}
}
private void ConfigureSelector(string areaName, string controllerName, ActionModel action)
{
RemoveEmptySelectors(action.Selectors);
if (!action.Selectors.Any())
{
AddAppServiceSelector(areaName, controllerName, action);
}
else
{
NormalizeSelectorRoutes(areaName, controllerName, action);
}
}
private void AddAppServiceSelector(string areaName, string controllerName, ActionModel action)
{
string verb;
var verbKey = action.ActionName.GetPascalOrCamelCaseFirstWord().ToLower();
verb = AppConsts.HttpVerbs.ContainsKey(verbKey) ? AppConsts.HttpVerbs[verbKey] : AppConsts.DefaultHttpVerb;
action.ActionName = GetRestFulActionName(action.ActionName);
var appServiceSelectorModel = new SelectorModel
{
AttributeRouteModel = CreateActionRouteModel(areaName, controllerName, action.ActionName)
};
appServiceSelectorModel.ActionConstraints.Add(new HttpMethodActionConstraint(new[] { verb }));
action.Selectors.Add(appServiceSelectorModel);
}
private bool CanUseFormBodyBinding(ActionModel action, ParameterModel parameter)
{
if (AppConsts.FormBodyBindingIgnoredTypes.Any(t => t.IsAssignableFrom(parameter.ParameterInfo.ParameterType)))
{
return false;
}
foreach (var selector in action.Selectors)
{
if (selector.ActionConstraints == null)
{
continue;
}
foreach (var actionConstraint in selector.ActionConstraints)
{
var httpMethodActionConstraint = actionConstraint as HttpMethodActionConstraint;
if (httpMethodActionConstraint == null)
{
continue;
}
if (httpMethodActionConstraint.HttpMethods.All(hm => hm.IsIn("GET", "DELETE", "TRACE", "HEAD")))
{
return false;
}
}
}
return true;
}
/// <summary>
/// Processing action name
/// </summary>
/// <param name="actionName"></param>
/// <returns></returns>
private static string GetRestFulActionName(string actionName)
{
// Remove Postfix
actionName = actionName.RemovePostFix(AppConsts.ActionPostfixes.ToArray());
// Remove Prefix
var verbKey = actionName.GetPascalOrCamelCaseFirstWord().ToLower();
if (AppConsts.HttpVerbs.ContainsKey(verbKey))
{
if (actionName.Length == verbKey.Length)
{
return "";
}
else
{
return actionName.Substring(verbKey.Length);
}
}
else
{
return actionName;
}
}
private static void NormalizeSelectorRoutes(string areaName, string controllerName, ActionModel action)
{
action.ActionName = GetRestFulActionName(action.ActionName);
foreach (var selector in action.Selectors)
{
selector.AttributeRouteModel = selector.AttributeRouteModel == null ?
CreateActionRouteModel(areaName, controllerName, action.ActionName) :
AttributeRouteModel.CombineAttributeRouteModel(CreateActionRouteModel(areaName, controllerName, ""), selector.AttributeRouteModel);
}
}
private static AttributeRouteModel CreateActionRouteModel(string areaName, string controllerName, string actionName)
{
var routeStr =
$"{AppConsts.DefaultApiPreFix}/{areaName}/{controllerName}/{actionName}".Replace("//", "/");
return new AttributeRouteModel(new RouteAttribute(routeStr));
}
private static void RemoveEmptySelectors(IList<SelectorModel> selectors)
{
selectors
.Where(IsEmptySelector)
.ToList()
.ForEach(s => selectors.Remove(s));
}
private static bool IsEmptySelector(SelectorModel selector)
{
return selector.AttributeRouteModel == null && selector.ActionConstraints.IsNullOrEmpty();
}
}
}
<file_sep>/MyWebApi/WebApiHelper/MyWebApiControllerFeatureProvider.cs
using Microsoft.AspNetCore.Mvc.Controllers;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace WebApiHelper
{
public class MyWebApiControllerFeatureProvider : ControllerFeatureProvider
{
protected override bool IsController(TypeInfo typeInfo)
{
var type = typeInfo.AsType();
if (!typeof(IRemoteService).IsAssignableFrom(type) ||
!typeInfo.IsPublic || typeInfo.IsAbstract || typeInfo.IsGenericType)
{
return false;
}
return true;
}
}
}
|
26426accd4a8976c66c194ff925cbdd9e9f2141e
|
[
"C#"
] | 7
|
C#
|
RyanOvO/MyWebApi
|
f9e1a480e641475aa521e5a55c14e04f94638d34
|
7c225cbc95bb59d7e996d0ec34c12a3916da9838
|
refs/heads/master
|
<repo_name>CraftsmanGuild/EulerPractice-22Feb2011<file_sep>/voigtjr/generate11.rb
# Generates part of the right hand side for the data production
# for Project Euler Problem 11 in Soar
#
# By <NAME> <<EMAIL>>
#
def p11
IO.readlines("data11.txt").each_with_index do |x, i|
x.split.each_with_index do |y, j|
id = sprintf("<c%02d%02d>", i, j)
unless i == 19
right = sprintf("<c%02d%02d>", i + 1, j)
else
right = "nil"
end
unless j == 19
down = sprintf("<c%02d%02d>", i, j + 1)
else
down = "nil"
end
unless right == "nil" || down == "nil"
diag = sprintf("<c%02d%02d>", i + 1, j + 1)
else
diag = "nil"
end
puts " (<t> ^cell " + id + ")"
puts " (" + id + " ^value " + y + " ^right " + right + " ^diag " + diag + " ^down " + down + ")"
end
end
end
p11
<file_sep>/sleepynate/Euler21.py
#!/usr/bin/env python
#
# Project Euler - Problem 21
# Evaluate the sum of all the amicable numbers under 10000.
#
# solution by <NAME>
# nathan (period) dotz (at sign) gmail (period) com
#
amicableSum = 0
def DivisorList(x):
return [y for y in range(1,(x-2)) if not (x%y) ]
def DivisorSum(x):
try:
return reduce(lambda a,b:a+b, DivisorList(x))
except:
return 1
for i in range(1, 10001):
if DivisorSum(DivisorSum(i)) == i and DivisorSum(i) != i:
print i, DivisorList(i), "= ", DivisorSum(i)
amicableSum += i
print amicableSum
<file_sep>/sleepynate/Euler11.py
#!/usr/bin/env python
# Project Euler - Problem 11
# What is the greatest product of four adjacent numbers in any
# direction (up, down, left, right, or diagonally) in the 2020 grid?
#
# solution by <NAME>
# nathan (period) dotz (at sign) gmail (period) com
GRID = []
MAXFOUND = 0
def fillGrid():
infile = open("numbertable","r")
for line in infile.readlines():
grrList=[]
for temp in line.split():
grrList.append(int(temp))
GRID.append(grrList)
def checkHoriz(x):
global MAXFOUND, GRID
for line in GRID:
start = 0
while start < x-3:
#DEBUG print "Iteration: ", start+1
thisRowProduct = 1
for num in line[start:start+3]:
thisRowProduct = thisRowProduct * num
if thisRowProduct > MAXFOUND:
MAXFOUND = thisRowProduct
print "New Maximum found: ", MAXFOUND
start = start + 1
print "Horizontals checked"
def checkVert(x):
global MAXFOUND, GRID
checkColumn = 0
while checkColumn < x:
setStart = 0
thisSetProduct = 1
while setStart < x-3:
#DEBUG print GRID[setStart][checkColumn], GRID[setStart+1][checkColumn], GRID[setStart+2][checkColumn], GRID[setStart+3][checkColumn]
thisSetProduct = GRID[setStart][checkColumn] * GRID[setStart+1][checkColumn] * GRID[setStart+2][checkColumn] * GRID[setStart+3][checkColumn]
if thisSetProduct > MAXFOUND:
MAXFOUND = thisSetProduct
print "New Maximum found: ", MAXFOUND
setStart = setStart + 1
checkColumn = checkColumn + 1
print "Verticals checked"
def checkDiagRight(x):
global GRID, MAXFOUND
startRow = 0
while startRow < x-3:
startColumn = 0
while startColumn < x-3:
thisSetProduct = GRID[startRow][startColumn]*GRID[startRow+1][startColumn+1]*GRID[startRow+2][startColumn+2]*GRID[startRow+3][startColumn+3]
if thisSetProduct > MAXFOUND:
MAXFOUND = thisSetProduct
print "New Maximum found: ", MAXFOUND
startColumn = startColumn + 1
startRow = startRow + 1
print "Diagonal to the right checked"
def checkDiagLeft(x):
global GRID, MAXFOUND
startRow = 0
while startRow < x-3:
startColumn = 3
while startColumn < x:
thisSetProduct = GRID[startRow][startColumn]*GRID[startRow+1][startColumn-1]*GRID[startRow+2][startColumn-2]*GRID[startRow+3][startColumn-3]
if thisSetProduct > MAXFOUND:
MAXFOUND = thisSetProduct
print "New Maximum found: ", MAXFOUND
startColumn = startColumn + 1
startRow = startRow + 1
print "Diagonal to the left checked"
def outputMax():
print "Final maximum product found was: ", MAXFOUND
#debug
fillGrid()
checkHoriz(20)
checkVert(20)
checkDiagRight(20)
checkDiagLeft(20)
outputMax()
|
0413d9611107f59061382439e040eb5f0f0e2533
|
[
"Python",
"Ruby"
] | 3
|
Ruby
|
CraftsmanGuild/EulerPractice-22Feb2011
|
802d58c10d014d556b7dae30f8e971b207a350ef
|
dcf901f27ef8e8e3605821e255248a58fc106735
|
refs/heads/master
|
<repo_name>hjwouden/Green-Chess-AI<file_sep>/StudentAI.cs
//************************************************************************************************//
// Mean Green Chess StudentAI.cs file
//________________________________________________________________________________________________
// Change Log
//================================================================================================
// Date Name Changes
//================================================================================================
// 10-10-2014 Kiaya Optimized the GreedyMove to reduce the number of calls to MoveResultsInCheck and CheckingForCheckAndCheckmate
// Added three features to the ValueOfBoard
// 1. If our high ranking pieces are in danger reduce the value of the board (relative to the value of the piece)
// 2. If one of their pieces are in danger we increase the value of the board (relative to the value of the piece)
// 3. If we have more pieces on the board then they do we increase the value of the board (and of course the reverse)
// Fix for the timer... I think.
// 10-9-2014 Jason Added: Timer (OnTimedEvent <sets bool value isTimeUp>)
// (StartTimer <starts the timer to set interval currently 5 sec>)
// (StopTimer <stops the timer, makes sure we dont carry time over to next turn>)
// Implemented: check for isTimeUp in while loops (Greedymove, GetNextMove)
//
// 10-3-2014 Greg Added:
// bool IsTerminalNode(ChessBoard board, ChessColor myColor)
// int MaxMove(ChessBoard board, ChessColor myColor, int depth, int alpha, int beta)
// int MinMove(ChessBoard board, ChessColor myColor, int depth, int alpha, int beta)
// Changed:
// checkingForCheckOrCheckmate(ChessMove move, ChessBoard board, ChessColor myColor)
// ChessMove GreedyMove(ChessBoard board, ChessColor myColor)
// int ValueOfBoard(ChessBoard board, ChessColor color, MinMaxPlayer p)
// Read the readme.txt for more information
// 9-29-2014 jason Checking opponents move. Works but discovers error in putting opponent in checkmate, we dont signal they are in checkmate, just put them in check. need to fix.
// 9-28-2014 kiaya Handle setting check flag when we move
// 9-28-2014 kiaya Handle setting checkmate flag when we move
// 9-28-2014 kiaya Weighting moves that put the opponent in check or check mate higher than other moves
// 9-28-2014 kiaya Fix to Queen, Rook, and Bishop moves as discribed in readme file
// 9-28-2014 kiaya playerInCheck(...) function to help with all the check/checkmate stuff we needed. Used in MoveResultsInCheck, CheckingForCheckAndCheckmate, and adjustValueOfMoveBasedOnCheckOrCheckMate
// 9-28-2014 kiaya Fix to greedy move to handle if the "random" move is going to put us in check.
// 9-27-2014 greg GreedyMove now choses a "random" move if all move values are the same
// 9-24-2014 greg IMPORTANT UPDATE
// 9-24-2014 kiaya Kiaya_Knight_Canidate
// 9-26-2014 jason reorganized code and clean up
// 9-26-2014 jason Added attack value function
// 9-26-2014 jason Implemented GetattackValue in Rook, ERR:Rook wont move right.
// 9-26-2014 jason Implemented GetAttackValue in Knight
// 9-26-2014 jason Added Joshs Bishop Canidate
// 9-26-2014 jason Implemented GetattackValue in Bishop
// 9-26-2014 jason Added Joshs Queen Canidate
// 9-26-2014 jason Implemented GetattackValue in Queen
//************************************************************************************************//
using System;
using System.Timers;
using System.Collections.Generic;
using System.Text;
using UvsChess;
namespace StudentAI
{
public class StudentAI : IChessAI
{
#region IChessAI Members that are implemented by the Student
public string Name
{
#if DEBUG
get { return "Mean Green Chess Machine (DEBUGE)"; }
#else
get { return "Mean Green Chess Machine"; }
#endif
}
private const int ROWS = 8;
private const int COLS = 8;
private const int VALUE_KING = 10;
private const int VALUE_QUEEN = 8;
private const int VALUE_ROOK = 5;
private const int VALUE_KNIGHT = 4;
private const int VALUE_BISHOP = 3;
private const int VALUE_PAWN = 1;
#region 5 Sec Timer Functions
bool isTimeUp = false;
private static Timer aTimer;
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
isTimeUp = true;
}
private void startTimer()
{
isTimeUp = false;
double interval = 5000.0;
aTimer = new System.Timers.Timer(interval);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.AutoReset = false;
aTimer.Enabled = true;
}
private void resetTimer()
{
aTimer.Stop();
}
// End of Timer Test stuff - HJW
#endregion
#region RepetiveMoves?
// I wasn't exactly sure where to add these values, but we can check for if PossibleLoop, then lower the
// board value of the move that moves the avoidPieceValue, because we have moved it a bunch.
bool PossibleLoop = false;
int avoidPieceValue = 0;
int[] LastMovevalues = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1 }; // array, will enter the value of piece that moves last in here. if we fill it will all the same number then we may be in a loop
int moveArrayCounter = 0;
private void lastTenPiecesMoved(int value)
{
//if the last 20 moves were done by the same value piece we could be in a loop and should move a different piece.
if (moveArrayCounter > 9)
{
moveArrayCounter = 0;
}
//set array to have the value of piece just moved
LastMovevalues[moveArrayCounter] = value;
moveArrayCounter++;
int match = 0;
for (int i = 0; i < 10; i++)
{
if (LastMovevalues[i] == LastMovevalues[0])
{
match++;
}
}
if (match >= 9)
{
//then change the move value of that piece by setting a bool value or something.
PossibleLoop = true;
avoidPieceValue = LastMovevalues[3];
//this.Log("######## 10> moves with same value piece. Set PossibleLoop = true and avoidPiece to piece value");
}
else
{
//if we get in a loop then fix it reset the variables.
PossibleLoop = false;
avoidPieceValue = 0;
}
}
#endregion
//Helper function to check if th move is valid,
//Checks if out of bounds, if the location is empty or if the piece on the board is the same color as the piece trying to move
private bool simpleValidateMove(ChessLocation loc, ChessBoard board, ChessColor color)
{
if (loc.X < 0 || loc.X > 7 || loc.Y < 0 || loc.Y > 7)
{
return false;
}
if (LocationEmpty(board, loc.X, loc.Y))
{
return true;
}
else if (ColorOfPieceAt(loc, board) != color)
{
return true;
}
else
{
return false;
}
}
//checks if the given move will result in check or checkmate and returns the appropriate flag.
private ChessFlag checkingForCheckOrCheckmate(ChessMove move, ChessBoard board, ChessColor myColor)
{
ChessBoard tempBoard = board.Clone();
if (move != null)
tempBoard.MakeMove(move);
// this.Log("######Checking for check with move [" + move.From.X + "," + move.From.Y + "] to [" + move.To.X + "," + move.To.Y + "].");
ChessColor theirColor = myColor == ChessColor.White ? ChessColor.Black : ChessColor.White;
if (playerInCheck(tempBoard, theirColor))
{
bool canGetOutOfCheck = false;
List<ChessMove> kingMoves = GetMovesForKing(GetKingsPosition(tempBoard, theirColor), tempBoard, theirColor);
foreach (var kingMove in kingMoves)
{
ChessBoard temp2 = tempBoard.Clone();
temp2.MakeMove(kingMove);
if (!playerInCheck(temp2, theirColor))
{
canGetOutOfCheck = true;
}
}
if (!canGetOutOfCheck)
{
//this.Log("King can't move to get out of check. Checking the other pieces to see if they can get the king out of check");
List<ChessMove> allEnemiesMoves = new List<ChessMove>();
for (int i = 0; i < ROWS; ++i)
{
for (int j = 0; j < COLS; ++j)
{
ChessLocation pieceLoc = new ChessLocation(i, j);
ChessColor theColor = ColorOfPieceAt(pieceLoc, tempBoard);
if (theColor != myColor && tempBoard[i, j] != ChessPiece.Empty)
{
allEnemiesMoves.AddRange(GetAllValidMovesFor(pieceLoc, tempBoard));
}
}
}
foreach (var enemyMove in allEnemiesMoves)
{
ChessBoard temp2 = tempBoard.Clone();
temp2.MakeMove(enemyMove);
if (!playerInCheck(temp2, theirColor))
{
canGetOutOfCheck = true;
}
}
}
if (!canGetOutOfCheck)
{
return ChessFlag.Checkmate;
}
else
{
return ChessFlag.Check;
}
}
else
{
List<ChessMove> allEnemiesMoves = new List<ChessMove>();
for (int i = 0; i < ROWS; ++i)
{
for (int j = 0; j < COLS; ++j)
{
ChessLocation pieceLoc = new ChessLocation(i, j);
ChessColor theColor = ColorOfPieceAt(pieceLoc, tempBoard);
if (theColor != myColor && tempBoard[i, j] != ChessPiece.Empty)
{
allEnemiesMoves.AddRange(GetAllValidMovesFor(pieceLoc, tempBoard));
}
}
}
if(allEnemiesMoves.Count == 0)
{
return ChessFlag.Stalemate;
}
return ChessFlag.NoFlag;
}
}
//checks if a move will result in check or checkmate (if they do it will add the appropriate flag) and adds a large amount to the value of the move.
private void adjustValueOfMoveBasedOnCheckOrCheckMate(ref ChessMove move, ChessBoard board, ChessColor myColor)
{
move.Flag = checkingForCheckOrCheckmate(move, board, myColor);
if (move.Flag == ChessFlag.Check)
{
#if DEBUG
this.Log("Found a move to put them in check, adjusting value of move");
#endif
move.ValueOfMove += 10;
}
else if (move.Flag == ChessFlag.Checkmate)
{
#if DEBUG
this.Log("Found a move to put them in checkMate, adjusting value of move");
#endif
move.ValueOfMove += 1000;
}
}
// Returns true if this move results in check (used to prune moves from move lists!).
// False otherwise
private bool MoveResultsInCheck(ChessBoard board, ChessMove move, ChessColor myColor)
{
// this works by making a copy of the chessboard, augmenting it with the move in question,
// and then getting all possible moves of the opposing color. If the opposing color can make
// any move which would take the king, then the move has resulted in check by definition.
// Create new temp board and make supposed move
ChessBoard tempBoard = new ChessBoard(board.RawBoard);
tempBoard.MakeMove(move);
//use the player in check to see if we will be in check as a result of the move
return playerInCheck(tempBoard, myColor);
}
private ChessLocation GetKingsPosition(ChessBoard board, ChessColor myColor)
{
for (int i = 0; i < ROWS; ++i)
{
for (int j = 0; j < COLS; ++j)
{
if (myColor == ChessColor.Black && board[i, j] == ChessPiece.BlackKing)
return new ChessLocation(i, j);
else if (myColor == ChessColor.White && board[i, j] == ChessPiece.WhiteKing)
return new ChessLocation(i, j);
}
}
return new ChessLocation(-1, -1);
}
//looks through all moves the opponent of a player (given by the color) and checks to see if any of those moves result in the king being killed.
private bool playerInCheck(ChessBoard board, ChessColor color)
{
ChessBoard tempBoard = board.Clone();
//this.Log("Calling playerInCheck for " + color);
//get all moves of the opposing color
List<ChessMove> allEnemiesMoves = new List<ChessMove>();
for (int i = 0; i < ROWS; ++i)
{
for (int j = 0; j < COLS; ++j)
{
ChessLocation pieceLoc = new ChessLocation(i, j);
ChessColor theColor = ColorOfPieceAt(pieceLoc, tempBoard);
if (theColor != color && tempBoard[i, j] != ChessPiece.Empty)
{
allEnemiesMoves.AddRange(GetAllValidMovesFor(pieceLoc, tempBoard));
}
}
}
//this.Log("playerInCheck found " + allEnemiesMoves.Count + " moves that the other team could make.");
//check if any of those moves will kill a king.
foreach (ChessMove nextPossibleMove in allEnemiesMoves)
{
//this.Log("Checking for check with move [" + nextPossibleMove.From.X + "," + nextPossibleMove.From.Y + "] to [" + nextPossibleMove.To.X + "," + nextPossibleMove.To.Y + "]. The value of that piece is " + GetValueOfPiece(tempBoard[nextPossibleMove.To]));
if (ColorOfPieceAt(nextPossibleMove.To, tempBoard) == color && GetValueOfPiece(tempBoard[nextPossibleMove.To]) == 10)
{
//this.Log("returning true Found a move that puts in check");
return true;
}
}
return false;
}
private bool IsTerminalNode(ChessBoard board, ChessColor myColor)
{
// returns true if the board's state is terminal (ie: checkmate)
if (checkingForCheckOrCheckmate(null, board, myColor) == ChessFlag.Checkmate)
{
return true;
}
return false;
}
private ChessColor GetEnemyColor(ChessColor myColor)
{
if (myColor == ChessColor.White) return ChessColor.Black;
else return ChessColor.White;
}
private int MaxMove(ChessBoard board, ChessColor myColor, int depth, int alpha, int beta, ref Dictionary<int, ChessBoard> plys)
{
if (depth == 0 || IsTerminalNode(board, myColor) || playerInCheck(board, myColor) || isTimeUp == true)
{
int val = ValueOfBoard(board, myColor, MinMaxPlayer.Max);
//this.Log("Value of Max board: " + val);
return val;
}
else
{
List<ChessMove> childMoves = new List<ChessMove>();
Successors(board, myColor, ref childMoves);
ChessBoard tempBoard = null;
if (plys.ContainsKey(depth))
tempBoard = plys[depth];
else
{
tempBoard = board.Clone();
plys[depth] = tempBoard;
}
for (int i = 0; i < childMoves.Count; ++i)
{
tempBoard = plys[depth];
tempBoard.MakeMove(childMoves[i]);
alpha = Math.Max(alpha, MinMove(tempBoard, GetEnemyColor(myColor), depth - 1, alpha, beta, ref plys));
if (alpha >= beta)
return beta;
}
return alpha;
}
}
private int MinMove(ChessBoard board, ChessColor myColor, int depth, int alpha, int beta, ref Dictionary<int, ChessBoard> plys)
{
if (depth == 0 || IsTerminalNode(board, myColor) || playerInCheck(board, myColor) || isTimeUp == true)
{
int val = ValueOfBoard(board, myColor, MinMaxPlayer.Min);
//this.Log("Value of Min board: " + val);
return val;
}
else
{
List<ChessMove> childMoves = new List<ChessMove>();
Successors(board, myColor, ref childMoves);
ChessBoard tempBoard = null;
if (plys.ContainsKey(depth))
tempBoard = plys[depth];
else
{
tempBoard = board.Clone();
plys[depth] = tempBoard;
}
for (int i = 0; i < childMoves.Count; ++i)
{
tempBoard = plys[depth];
tempBoard.MakeMove(childMoves[i]);
beta = Math.Min(beta, MaxMove(tempBoard, GetEnemyColor(myColor), depth - 1, alpha, beta, ref plys));
if (beta <= alpha)
return alpha;
}
return beta;
}
}
private ChessMove GreedyMove(ChessBoard board, ChessColor myColor)
{
// All Greedy move will do is expand the current board, getting
// successor moves, and will simply return the move that has the highest move value!
List<ChessMove> possibleMoves = new List<ChessMove>();
int bestMoveValue = -99;
int bestMoveValueIndex = 0;
ChessMove bestMove = null;
bool moveFound = false;
// Check to see if opponents move was a valid one.
//Get previous board, get current board, see what the move made was.
Successors(board, myColor, ref possibleMoves);
// This doesn't actually work nicely. The move is just registered as an illegal move,
// but I still use it here for logging purposes.
if (possibleMoves.Count == 0)
{
// Checkmate, generally, but just return stalemate?
ChessMove move = new ChessMove(new ChessLocation(0, 0), new ChessLocation(0, 0));
this.Log("PossibleMoves was empty, signaling a checkmate");
move.Flag = ChessFlag.Checkmate;
return move;
}
//else //Run through all possible moves and determine if any of them will result in us putting the enemy in check or checkmate. Weight these moves higher than others.
//{
// for (int i = 0; i < possibleMoves.Count; ++i)
// {
// if (MoveResultsInCheck(board, possibleMoves[i], myColor))
// {
// this.Log("Move resulted in check. Remove from queue!");
// possibleMoves.Remove(possibleMoves[i]);
// }
// }
//}
while (bestMove == null)
{
Dictionary<int, ChessBoard> plyMap = new Dictionary<int, ChessBoard>();
for (int i = 0; i < possibleMoves.Count; ++i)
{
if(isTimeUp == true)
{
break;
}
ChessBoard tempBoard = board.Clone();
tempBoard.MakeMove(possibleMoves[i]);
int depth = 4;
plyMap.Add(depth, tempBoard);
int minimaxVal = -100000;
minimaxVal = MaxMove(tempBoard, myColor, depth, -1000000, 1000000, ref plyMap);
this.Log("Minimax value for generated move: " + possibleMoves[i].From.X +" , " + possibleMoves[i].From.Y + " " + minimaxVal);
plyMap.Clear();
if (minimaxVal > bestMoveValue)
{
bestMoveValueIndex = i;
bestMoveValue = minimaxVal;
}
}
this.Log("Minimax move found " + possibleMoves.Count + " moves. Value of best is: " + bestMoveValue);
bestMove = possibleMoves[bestMoveValueIndex];
bestMove.Flag = checkingForCheckOrCheckmate(bestMove, board, myColor);
moveFound = true;
//if (!MoveResultsInCheck(board, possibleMoves[bestMoveValueIndex], myColor))
//{
// bestMove = possibleMoves[bestMoveValueIndex];
// moveFound = true;
//}
//else // remove this move as it results in check for us!
//{
// possibleMoves.Remove(possibleMoves[bestMoveValueIndex]);
// bestMoveValue = bestMoveValueIndex = 0;
// if (possibleMoves.Count == 0)
// break;
// this.Log("A move was detected that could result in check. Removed from move queue");
// this.Log("The the piece was going to move to: " + possibleMoves[bestMoveValueIndex].To.X + ", " + possibleMoves[bestMoveValueIndex].To.Y);
//}
}
if (moveFound)
return bestMove;
else
return null;
}
private void Successors(ChessBoard board, ChessColor myColor, ref List<ChessMove> movesForEachSucc)
{
for (int i = 0; i < ROWS; ++i)
{
for (int j = 0; j < COLS; ++j)
{
if (ColorOfPieceAt(new ChessLocation(i, j), board) == myColor && board[i, j] != ChessPiece.Empty)
{
List<ChessMove> validMovesForPiece = null;
validMovesForPiece = GetAllValidMovesFor(new ChessLocation(i, j), board);
if (validMovesForPiece != null)
{
// for each piece, we generate all legal moves, and make a new board where that move
// is made to cover all possible choices.
for (int k = 0; k < validMovesForPiece.Count; ++k)
{
if (movesForEachSucc != null)
movesForEachSucc.Add(validMovesForPiece[k]);
}
}
}
}
}
}
private ChessColor ColorOfPieceAt(ChessLocation loc, ChessBoard board)
{
if (board[loc] < ChessPiece.Empty)
return ChessColor.Black;
return ChessColor.White;
}
// Returns a list of all moves that are valid for the ChessPiece located at loc
private List<ChessMove> GetAllValidMovesFor(ChessLocation loc, ChessBoard board)
{
ChessPiece piece = board[loc];
List<ChessMove> moves = null;
// each piece will have its own movement logic based on the piece that it is,
// and also (in some cases) whether it is black or white.
switch (piece)
{
case ChessPiece.BlackPawn:
moves = GetMovesForPawn(loc, board, ChessColor.Black);
break;
case ChessPiece.BlackRook:
moves = GetMovesForRook(loc, board, ChessColor.Black);
break;
case ChessPiece.BlackKnight:
moves = GetMovesForKnight(loc, board, ChessColor.Black);
break;
case ChessPiece.BlackBishop:
moves = GetMovesForBishop(loc, board, ChessColor.Black);
break;
case ChessPiece.BlackQueen:
moves = GetMovesForQueen(loc, board, ChessColor.Black);
break;
case ChessPiece.BlackKing:
moves = GetMovesForKing(loc, board, ChessColor.Black);
break;
case ChessPiece.WhitePawn:
moves = GetMovesForPawn(loc, board, ChessColor.White);
break;
case ChessPiece.WhiteRook:
moves = GetMovesForRook(loc, board, ChessColor.White);
break;
case ChessPiece.WhiteKnight:
moves = GetMovesForKnight(loc, board, ChessColor.White);
break;
case ChessPiece.WhiteBishop:
moves = GetMovesForBishop(loc, board, ChessColor.White);
break;
case ChessPiece.WhiteQueen:
moves = GetMovesForQueen(loc, board, ChessColor.White);
break;
case ChessPiece.WhiteKing:
moves = GetMovesForKing(loc, board, ChessColor.White);
break;
default:
// assume Empty and do nothing
break;
}
return moves;
}
// Evaluation function of the strength of the board state.
enum MinMaxPlayer { Max, Min };
private int ValueOfBoard(ChessBoard board, ChessColor color, MinMaxPlayer p)
{
// every board has a different state
// Index 0 is pawns, then 1 is bishop, etc
List<int> units = NumOfUnits(board, color);
List<int> unitsEnemy = NumOfUnits(board, GetEnemyColor(color));
List<ChessMove> possibleMove = new List<ChessMove>();
List<ChessMove> possibleMoveEnemy = new List<ChessMove>();
for (int i = 0; i < 8; ++i)
{
for (int k = 0; k < 8; ++k)
{
if (board[i, k] != ChessPiece.Empty)
{
if (ColorOfPieceAt(new ChessLocation(i, k), board) == color)
{
possibleMove.AddRange(GetAllValidMovesFor(new ChessLocation(i, k), board));
}
else
{
possibleMoveEnemy.AddRange(GetAllValidMovesFor(new ChessLocation(i, k), board));
}
}
}
}
int totalMovesAvailable = possibleMove.Count;
int totalMovesAvailableEnemy = possibleMoveEnemy.Count;
int currentValueOfBoard = 0;
currentValueOfBoard = units.Count - unitsEnemy.Count;
//If any of the higher value pieces are in danger, lower board value.
//This will handle lowering the board value if we are in check in this particular board variation
foreach (var enemyMove in possibleMoveEnemy)
{
int result = PieceAtPosInDanger(board, enemyMove.To.X, enemyMove.To.Y);
//if (result == 100)
//{
// return -100;
//}
//else
//{
currentValueOfBoard = currentValueOfBoard - result;
//}
}
foreach (var move in possibleMove)
{
//If any of our moves could result in us taking a higher piece increase the board value;
//This will handle increaseing the board value if we put them in check
currentValueOfBoard = currentValueOfBoard + PieceAtPosInDanger(board, move.To.X, move.To.Y);
}
// old feature (probably still good, but I commented it out for testing
//int unitWeight = VALUE_KING + VALUE_QUEEN * units[4] + VALUE_ROOK * units[3] + VALUE_KNIGHT * units[2] +
// VALUE_BISHOP * units[1] + VALUE_PAWN * units[0];
// This example feature maximizes the total moves available to Max, while
// attempting to minimize the total moves available to min. Seems to work fairly well
// as a feature by itself, but obviously we need more!
// Good features to add:
// 1) Check to see if high value peices are in danger. If so, lower board state value
// 2) Check to see if high mobility peices are local to the center of the board where they will
// have most movement ability.
// 3) Try to find other good features to add to score
//this.Log("Value of board will be: " + (totalMovesAvailable - totalMovesAvailableEnemy));
currentValueOfBoard += totalMovesAvailable - totalMovesAvailableEnemy;
return currentValueOfBoard;
}
//looks at the position given. If a piece is there
//then we will return the value that should be taken off of the current value of the board
private int PieceAtPosInDanger(ChessBoard board, int x, int y)
{
int valueOfPieceAtPos = GetValueOfPiece(board[x, y]);
if (valueOfPieceAtPos == VALUE_KING)
{
//this.Log("PieceAtPosInDanger found king in danger. returning 100;");
return 100; //Make value of king very high
}
else
{
return valueOfPieceAtPos;
}
return 0;
}
private List<int> NumOfUnits(ChessBoard board, ChessColor color)
{
List<int> unitCounts = new List<int>();
for (int i = 0; i < 5; ++i)
{
unitCounts.Add(0);
}
for (int i = 0; i < ROWS; ++i)
{
for (int j = 0; j < COLS; ++j)
{
if (ColorOfPieceAt(new ChessLocation(i, j), board) == color)
{
switch (board[i, j])
{
case ChessPiece.BlackQueen:
case ChessPiece.WhiteQueen:
unitCounts[4]++;
break;
case ChessPiece.BlackRook:
case ChessPiece.WhiteRook:
unitCounts[3]++;
break;
case ChessPiece.BlackKnight:
case ChessPiece.WhiteKnight:
unitCounts[2]++;
break;
case ChessPiece.BlackBishop:
case ChessPiece.WhiteBishop:
unitCounts[1]++;
break;
case ChessPiece.BlackPawn:
case ChessPiece.WhitePawn:
unitCounts[0]++;
break;
default:
break;
}
}
}
}
return unitCounts;
}
// Given a chesspiece p returns its value in the game
private int GetValueOfPiece(ChessPiece p)
{
switch (p)
{
case ChessPiece.BlackPawn:
case ChessPiece.WhitePawn:
return VALUE_PAWN;
case ChessPiece.WhiteBishop:
case ChessPiece.BlackBishop:
return VALUE_BISHOP;
case ChessPiece.WhiteKnight:
case ChessPiece.BlackKnight:
return VALUE_KNIGHT;
case ChessPiece.WhiteRook:
case ChessPiece.BlackRook:
return VALUE_ROOK;
case ChessPiece.WhiteQueen:
case ChessPiece.BlackQueen:
return VALUE_QUEEN;
case ChessPiece.WhiteKing:
case ChessPiece.BlackKing:
return VALUE_KING;
default:
return 0;
}
}
// Returns true if the location specified by x and y does not contain any game unit
private bool LocationEmpty(ChessBoard board, int x, int y)
{
return (ChessPiece.Empty == board[x, y]) ? true : false;
}
/// <summary>
/// Evaluates the chess board and decided which move to make. This is the main method of the AI.
/// The framework will call this method when it's your turn.
/// </summary>
/// <param name="board">Current chess board</param>
/// <param name="yourColor">Your color</param>
/// <returns> Returns the best chess move the player has for the given chess board</returns>
public ChessMove GetNextMove(ChessBoard board, ChessColor myColor)
{
//starting the timer for 5 sec
startTimer();
ChessMove myNextMove = null;
while (!IsMyTurnOver() && (isTimeUp != true))
{
if (myNextMove == null)
{
// Greedy move, or whatever generates a move, needs to run on a timer eventually
// myNextMove = GreedyMove(board, myColor);
myNextMove = GreedyMove(board, myColor);
if (!IsValidMove(board, myNextMove, myColor))
this.Log("Minimax generated an illegal move");
this.Log(myColor.ToString() + " (" + this.Name + ") just moved.");
this.Log(string.Empty);
// Since I have a move, break out of loop
break;
}
}
int MyMoveValue = GetValueOfPiece(board[myNextMove.From]); //added HJW, keep track of multiple moves with same piece 10/12
lastTenPiecesMoved(MyMoveValue); //added HJW, keep track of multiple moves with same piece 10/12
resetTimer();
return myNextMove;
}
/// <summary>
/// Validates a move. The framework uses this to validate the opponents move.
/// </summary>
/// <param name="boardBeforeMove">The board as it currently is _before_ the move.</param>
/// <param name="moveToCheck">This is the move that needs to be checked to see if it's valid.</param>
/// <param name="colorOfPlayerMoving">This is the color of the player who's making the move.</param>
/// <returns>Returns true if the move was valid</returns>
public bool IsValidMove(ChessBoard boardBeforeMove, ChessMove moveToCheck, ChessColor colorOfPlayerMoving)
{
this.Log("Validating Move:" + colorOfPlayerMoving.ToString());
this.Log("Move to validate: " + moveToCheck.ToString());
if (playerInCheck(boardBeforeMove, colorOfPlayerMoving))
{
if (MoveResultsInCheck(boardBeforeMove, moveToCheck, colorOfPlayerMoving))
{
this.Log("Opponent was in CHECK at start of their move and still in CHECK after move. Invalid Move");
return false;
}
}
List<ChessMove> possibleMoves = new List<ChessMove>();
Successors(boardBeforeMove, colorOfPlayerMoving, ref possibleMoves);
for (int i = 0; i < possibleMoves.Count; i++)
{
if (moveToCheck.To == possibleMoves[i].To && moveToCheck.From == possibleMoves[i].From)
{
this.Log("Valid Move");
return true;
}
}
this.Log("Move was not found in list our list of successors. Invalid Move");
return false;
}
// Returns int value. Attack Value to assign to a move.
public int GetAttackMoveValue(int MyPieceValue, ChessLocation EnemyLocation, ChessBoard board)
{
//To take the Highest Enemy Piece available, just set value to Enemy Piece Value
int EnemyValue = GetValueOfPiece(board[EnemyLocation]);
return EnemyValue;
} //End GetAttackMoveValue - HJW
#region GetMoveFunction for Pieces
//***********************************************************************************//
//Get Move Functions for Pieces // All moves that can be done by units in the game
//**********************************************************************************//
private List<ChessMove> GetMovesForPawn(ChessLocation loc, ChessBoard board, ChessColor color)
{
List<ChessMove> moves = new List<ChessMove>();
if (ChessColor.Black == color)
{
// we are approaching from low values of Y to higher ones
if (PawnHasNotMoved(loc, ChessColor.Black) && LocationEmpty(board, loc.X, loc.Y + 2) && LocationEmpty(board, loc.X, loc.Y + 1))
{
// we may also move twice towards the enemy
moves.Add(new ChessMove(loc, new ChessLocation(loc.X, loc.Y + 2)));
}
// move up once if space available -- I should add a move value to this that is suitably high if
// this results in queening
if (LocationEmpty(board, loc.X, loc.Y + 1))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X, loc.Y + 1)));
}
// Finally, if an enemy exists exactly one location "up and over left or right"
// then we can take that enemy, and the move itself will produce a move value.
// The move value is just the ABS difference between the two peices, plus 1 so there
// is never competition with a 0 move value ChessMove
ChessMove attackingMoveLeft = null;
ChessMove attackingMoveRight = null;
if (loc.X - 1 >= 0 && loc.Y + 1 < ROWS)
{
// we may be able to attack left assuming an enemy is in that spot!
ChessLocation enemyLocation = new ChessLocation(loc.X - 1, loc.Y + 1);
if (!LocationEmpty(board, enemyLocation.X, enemyLocation.Y) && ChessColor.White == ColorOfPieceAt(enemyLocation, board))
{
attackingMoveLeft = new ChessMove(loc, enemyLocation);
attackingMoveLeft.ValueOfMove = 1 + Math.Abs(VALUE_PAWN - GetValueOfPiece(board[enemyLocation]));
moves.Add(attackingMoveLeft);
}
}
if (loc.X + 1 < COLS && loc.Y + 1 < ROWS)
{
ChessLocation enemyLocation = new ChessLocation(loc.X + 1, loc.Y + 1);
if (!LocationEmpty(board, enemyLocation.X, enemyLocation.Y) && ChessColor.White == ColorOfPieceAt(enemyLocation, board))
{
attackingMoveRight = new ChessMove(loc, enemyLocation);
attackingMoveRight.ValueOfMove = 1 + Math.Abs(VALUE_PAWN - GetValueOfPiece(board[enemyLocation]));
moves.Add(attackingMoveRight);
}
}
}
else // Handle moving White pawns instead. Similar logic with different movement vectors
{
if (PawnHasNotMoved(loc, ChessColor.White) && LocationEmpty(board, loc.X, loc.Y - 2) && LocationEmpty(board, loc.X, loc.Y - 1))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X, loc.Y - 2)));
}
if (LocationEmpty(board, loc.X, loc.Y - 1))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X, loc.Y - 1)));
}
ChessMove attackingMoveLeft = null;
ChessMove attackingMoveRight = null;
if (loc.X - 1 >= 0 && loc.Y - 1 >= 0)
{
ChessLocation enemyLocation = new ChessLocation(loc.X - 1, loc.Y - 1);
if (!LocationEmpty(board, enemyLocation.X, enemyLocation.Y) && ChessColor.Black == ColorOfPieceAt(enemyLocation, board))
{
attackingMoveLeft = new ChessMove(loc, enemyLocation);
attackingMoveLeft.ValueOfMove = 1 + Math.Abs(VALUE_PAWN - GetValueOfPiece(board[enemyLocation]));
moves.Add(attackingMoveLeft);
}
}
if (loc.X + 1 < COLS && loc.Y - 1 >= 0)
{
ChessLocation enemyLocation = new ChessLocation(loc.X + 1, loc.Y - 1);
if (!LocationEmpty(board, enemyLocation.X, enemyLocation.Y) && ChessColor.Black == ColorOfPieceAt(enemyLocation, board))
{
attackingMoveRight = new ChessMove(loc, enemyLocation);
attackingMoveRight.ValueOfMove = 1 + Math.Abs(VALUE_PAWN - GetValueOfPiece(board[enemyLocation]));
moves.Add(attackingMoveRight);
}
}
}
return moves;
}// End GetMovesForPawn
// Used by GetMovesForPawn. Determines if a pawn, has made its first move.
private bool PawnHasNotMoved(ChessLocation loc, ChessColor color)
{
const int FIRST_MOV_LOC_BLACK = 1;
const int FIRST_MOV_LOC_WHITE = 6;
if (ChessColor.Black == color)
{
if (FIRST_MOV_LOC_BLACK == loc.Y)
return true;
return false;
}
else
{
if (FIRST_MOV_LOC_WHITE == loc.Y)
return true;
return false;
}
} // End PawnHasNotMoved
private List<ChessMove> GetMovesForRook(ChessLocation loc, ChessBoard board, ChessColor color)
{
List<ChessMove> moves = new List<ChessMove>();
ChessMove m = null;
//*Check Left
int i = 1;
while ((loc.Y - i >= 0) && LocationEmpty(board, loc.X, loc.Y - i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X, loc.Y - i)));
++i;
}
if (loc.Y - i >= 0)
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X, loc.Y - i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X, loc.Y - i));
m.ValueOfMove = GetAttackMoveValue(VALUE_ROOK, new ChessLocation(loc.X, loc.Y - i), board);
moves.Add(m);
}
}
//*Check Right
i = 1;
while ((loc.Y + i < COLS) && LocationEmpty(board, loc.X, loc.Y + i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X, loc.Y + i)));
++i;
}
if (loc.Y + i < COLS)
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X, loc.Y + i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X, loc.Y + i));
m.ValueOfMove = GetAttackMoveValue(VALUE_ROOK, new ChessLocation(loc.X, loc.Y + i), board);
moves.Add(m);
}
}
//*Check Down
i = 1;
while ((loc.X - i >= 0) && LocationEmpty(board, loc.X - i, loc.Y))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y)));
++i;
}
if (loc.X - i >= 0)
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X - i, loc.Y), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y));
m.ValueOfMove = GetAttackMoveValue(VALUE_ROOK, new ChessLocation(loc.X - i, loc.Y), board);
moves.Add(m);
}
}
//*Check Up
i = 1;
while ((loc.X + i < ROWS) && LocationEmpty(board, loc.X + i, loc.Y))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y)));
++i;
}
if (loc.X + i < ROWS)
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X + i, loc.Y), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y));
m.ValueOfMove = GetAttackMoveValue(VALUE_ROOK, new ChessLocation(loc.X + i, loc.Y), board);
moves.Add(m);
}
}
return moves;
} // End GetMovesForRook - JDB
private List<ChessMove> GetMovesForBishop(ChessLocation loc, ChessBoard board, ChessColor color)
{
List<ChessMove> moves = new List<ChessMove>();
ChessMove m = null;
int i = 1;
//*Check Up Left
while ((loc.X - i >= 0) && (loc.Y - i >= 0) && LocationEmpty(board, loc.X - i, loc.Y - i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y - i)));
++i;
}
if ((loc.X - i >= 0) && (loc.Y - i >= 0))
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X - i, loc.Y - i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y - i));
m.ValueOfMove = GetAttackMoveValue(VALUE_BISHOP, new ChessLocation(loc.X - i, loc.Y - i), board);
moves.Add(m);
}
}
//*Check Up Right
i = 1;
while ((loc.X + i < COLS) && (loc.Y - i >= 0) && LocationEmpty(board, loc.X + i, loc.Y - i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y - i)));
++i;
}
if ((loc.X + i < COLS) && (loc.Y - i >= 0))
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X + i, loc.Y - i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y - i));
m.ValueOfMove = GetAttackMoveValue(VALUE_BISHOP, new ChessLocation(loc.X + i, loc.Y - i), board);
moves.Add(m);
}
}
//*Check Down Left
i = 1;
while ((loc.X - i >= 0) && (loc.Y + i < COLS) && LocationEmpty(board, loc.X - i, loc.Y + i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y + i)));
++i;
}
if ((loc.X - i >= 0) && (loc.Y + i < ROWS))
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X - i, loc.Y + i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y + i));
m.ValueOfMove = GetAttackMoveValue(VALUE_BISHOP, new ChessLocation(loc.X - i, loc.Y + i), board);
moves.Add(m);
}
}
// Check Down Right
i = 1;
while ((loc.X + i < ROWS) && (loc.Y + i < COLS) && LocationEmpty(board, loc.X + i, loc.Y + i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y + i)));
++i;
}
if ((loc.X + i < COLS) && (loc.Y + i < ROWS))
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X + i, loc.Y + i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y + i));
m.ValueOfMove = GetAttackMoveValue(VALUE_BISHOP, new ChessLocation(loc.X + i, loc.Y + i), board);
moves.Add(m);
}
}
return moves;
} // GetMovesForBishop - JDB
private List<ChessMove> GetMovesForQueen(ChessLocation loc, ChessBoard board, ChessColor color)
{
List<ChessMove> moves = new List<ChessMove>();
ChessMove m = null;
// Check up
int i = 1;
while ((loc.Y - i >= 0) && LocationEmpty(board, loc.X, loc.Y - i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X, loc.Y - i)));
++i;
}
if (loc.Y - i >= 0)
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X, loc.Y - i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X, loc.Y - i));
m.ValueOfMove = GetAttackMoveValue(VALUE_QUEEN, new ChessLocation(loc.X, loc.Y - i), board);
moves.Add(m);
}
}
// Check down
i = 1;
while ((loc.Y + i < ROWS) && LocationEmpty(board, loc.X, loc.Y + i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X, loc.Y + i)));
++i;
}
if (loc.Y + i < ROWS)
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X, loc.Y + i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X, loc.Y + i));
m.ValueOfMove = GetAttackMoveValue(VALUE_QUEEN, new ChessLocation(loc.X, loc.Y + i), board);
moves.Add(m);
}
}
// Check left
i = 1;
while ((loc.X - i >= 0) && LocationEmpty(board, loc.X - i, loc.Y))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y)));
++i;
}
if (loc.X - i >= 0)
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X - i, loc.Y), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y));
m.ValueOfMove = GetAttackMoveValue(VALUE_QUEEN, new ChessLocation(loc.X - i, loc.Y), board);
moves.Add(m);
}
}
// Check right
i = 1;
while ((loc.X + i < COLS) && LocationEmpty(board, loc.X + i, loc.Y))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y)));
++i;
}
if (loc.X + i < COLS && loc.X + i >= 0) //just threw in te loc.X + i >= 0 for fun I don't actually expect to need this check because i should always be greater than 0.
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X + i, loc.Y), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y));
m.ValueOfMove = GetAttackMoveValue(VALUE_QUEEN, new ChessLocation(loc.X + i, loc.Y), board);
moves.Add(m);
}
}
// Check up-left
i = 1;
while ((loc.Y - i >= 0) && (loc.X - i >= 0) && LocationEmpty(board, loc.X - i, loc.Y - i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y - i)));
++i;
}
if ((loc.Y - i >= 0) && (loc.X - i >= 0))
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X - i, loc.Y - i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y - i));
m.ValueOfMove = GetAttackMoveValue(VALUE_QUEEN, new ChessLocation(loc.X - i, loc.Y - i), board);
moves.Add(m);
}
}
// Check up-right
i = 1;
while ((loc.Y - i >= 0) && (loc.X + i < COLS) && LocationEmpty(board, loc.X + i, loc.Y - i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y - i)));
++i;
}
if ((loc.Y - i >= 0) && (loc.X + i < COLS))
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X + i, loc.Y - i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y - i));
m.ValueOfMove = GetAttackMoveValue(VALUE_QUEEN, new ChessLocation(loc.X + i, loc.Y - i), board);
moves.Add(m);
}
}
// Check down-left
i = 1;
while ((loc.Y + i < ROWS) && (loc.X - i >= 0) && LocationEmpty(board, loc.X - i, loc.Y + i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y + i)));
++i;
}
if ((loc.Y + i < ROWS) && (loc.X - i >= 0))
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X - i, loc.Y + i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X - i, loc.Y + i));
m.ValueOfMove = GetAttackMoveValue(VALUE_QUEEN, new ChessLocation(loc.X - i, loc.Y + i), board);
moves.Add(m);
}
}
// Check down-right
i = 1;
while ((loc.Y + i < ROWS) && (loc.X + i < COLS) && LocationEmpty(board, loc.X + i, loc.Y + i))
{
moves.Add(new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y + i)));
++i;
}
if ((loc.Y + i < ROWS) && (loc.X + i < COLS))
{
if (color != ColorOfPieceAt(new ChessLocation(loc.X + i, loc.Y + i), board))
{
m = new ChessMove(loc, new ChessLocation(loc.X + i, loc.Y + i));
m.ValueOfMove = GetAttackMoveValue(VALUE_QUEEN, new ChessLocation(loc.X + i, loc.Y + i), board);
moves.Add(m);
}
}
return moves;
} // End GetMovesForQueen - JDB
private List<ChessMove> GetMovesForKnight(ChessLocation loc, ChessBoard board, ChessColor color)
{
List<ChessMove> moves = new List<ChessMove>();
List<ChessLocation> moveLocations = new List<ChessLocation>();
//get all possible locations that a knight can move. And store them in a list.
moveLocations.Add(new ChessLocation(loc.X + 1, loc.Y + 2));
moveLocations.Add(new ChessLocation(loc.X - 1, loc.Y + 2));
moveLocations.Add(new ChessLocation(loc.X + 1, loc.Y - 2));
moveLocations.Add(new ChessLocation(loc.X - 1, loc.Y - 2));
moveLocations.Add(new ChessLocation(loc.X + 2, loc.Y + 1));
moveLocations.Add(new ChessLocation(loc.X + 2, loc.Y - 1));
moveLocations.Add(new ChessLocation(loc.X - 2, loc.Y + 1));
moveLocations.Add(new ChessLocation(loc.X - 2, loc.Y - 1));
foreach (ChessLocation moveLoc in moveLocations)
{
if (simpleValidateMove(moveLoc, board, color))
{
ChessMove move = new ChessMove(loc, moveLoc);
if (ColorOfPieceAt(moveLoc, board) != color)
{
move.ValueOfMove = GetAttackMoveValue(VALUE_KNIGHT, moveLoc, board);
}
moves.Add(move);
}
}
return moves;
} //End GetMovesForKnight
private List<ChessMove> GetMovesForKing(ChessLocation loc, ChessBoard board, ChessColor color)
{
List<ChessMove> moves = new List<ChessMove>();
ChessMove m = null;
//CheckMove LU
ChessLocation nearbypiece = new ChessLocation(loc.X - 1, loc.Y + 1);
m = CheckKingMove(loc, nearbypiece, board, color);
if (!(m.From.X == m.To.X && m.From.Y == m.To.Y)) { moves.Add(m); }
//CheckMove U
nearbypiece = new ChessLocation(loc.X, loc.Y + 1);
m = CheckKingMove(loc, nearbypiece, board, color);
if (!(m.From.X == m.To.X && m.From.Y == m.To.Y)) { moves.Add(m); }
//CheckMove RU
nearbypiece = new ChessLocation(loc.X + 1, loc.Y + 1);
m = CheckKingMove(loc, nearbypiece, board, color);
if (!(m.From.X == m.To.X && m.From.Y == m.To.Y)) { moves.Add(m); }
//CheckMove L
nearbypiece = new ChessLocation(loc.X - 1, loc.Y);
m = CheckKingMove(loc, nearbypiece, board, color);
if (!(m.From.X == m.To.X && m.From.Y == m.To.Y)) { moves.Add(m); }
//CheckMove R
nearbypiece = new ChessLocation(loc.X + 1, loc.Y);
m = CheckKingMove(loc, nearbypiece, board, color);
if (!(m.From.X == m.To.X && m.From.Y == m.To.Y)) { moves.Add(m); }
//CheckMove DL
nearbypiece = new ChessLocation(loc.X - 1, loc.Y - 1);
m = CheckKingMove(loc, nearbypiece, board, color);
if (!(m.From.X == m.To.X && m.From.Y == m.To.Y)) { moves.Add(m); }
//CheckMove D
nearbypiece = new ChessLocation(loc.X, loc.Y - 1);
m = CheckKingMove(loc, nearbypiece, board, color);
if (!(m.From.X == m.To.X && m.From.Y == m.To.Y)) { moves.Add(m); }
//CheckMove DL
nearbypiece = new ChessLocation(loc.X + 1, loc.Y - 1);
m = CheckKingMove(loc, nearbypiece, board, color);
if (!(m.From.X == m.To.X && m.From.Y == m.To.Y)) { moves.Add(m); }
return moves;
}//End GetMovesForKing - HJW
//Used by GetMovesForKing() if move is valid returns move, or returns move with location same as start
private ChessMove CheckKingMove(ChessLocation fromloc, ChessLocation toloc, ChessBoard board, ChessColor color)
{
if ((toloc.X >= ROWS) || (toloc.X < 0) || (toloc.Y >= COLS) || (toloc.Y < 0))
{
ChessMove nomove = new ChessMove(fromloc, fromloc);
return nomove;
}
else
{
if (LocationEmpty(board, toloc.X, toloc.Y))
{
ChessMove validmove = new ChessMove(fromloc, new ChessLocation(toloc.X, toloc.Y));
return validmove;
}
else
{
if (ColorOfPieceAt(new ChessLocation(toloc.X, toloc.Y), board) != color)
{
ChessMove attackingMoveKing = null;
attackingMoveKing = new ChessMove(fromloc, new ChessLocation(toloc.X, toloc.Y));
attackingMoveKing.ValueOfMove = GetAttackMoveValue(VALUE_KING, toloc, board);
return attackingMoveKing;
}
ChessMove noMove = new ChessMove(fromloc, fromloc);
return noMove;
}
}
}//End CheckKingMove - HJW
#endregion
#endregion
#region IChessAI Members that should be implemented as automatic properties and should NEVER be touched by students.
/// <summary>
/// This will return false when the framework starts running your AI. When the AI's time has run out,
/// then this method will return true. Once this method returns true, your AI should return a
/// move immediately.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
public AIIsMyTurnOverCallback IsMyTurnOver { get; set; }
/// <summary>
/// Call this method to print out debug information. The framework subscribes to this event
/// and will provide a log window for your debug messages.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
/// <param name="message"></param>
public AILoggerCallback Log { get; set; }
/// <summary>
/// Call this method to catch profiling information. The framework subscribes to this event
/// and will print out the profiling stats in your log window.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
/// <param name="key"></param>
public AIProfiler Profiler { get; set; }
/// <summary>
/// Call this method to tell the framework what decision print out debug information. The framework subscribes to this event
/// and will provide a debug window for your decision tree.
///
/// You should NEVER EVER set this property!
/// This property should be defined as an Automatic Property.
/// This property SHOULD NOT CONTAIN ANY CODE!!!
/// </summary>
/// <param name="message"></param>
public AISetDecisionTreeCallback SetDecisionTree { get; set; }
#endregion
}
}
|
c6f278eb255a4c5098e75cb221d769490e5dcdff
|
[
"C#"
] | 1
|
C#
|
hjwouden/Green-Chess-AI
|
7c66691ab3537dc6abec9c6826f08d2d6fb8af92
|
8d6fc64f0f04e0988fa46be443cda547afc4d2e5
|
refs/heads/master
|
<repo_name>easilyamused07/java<file_sep>/hua647-Lab2 Test/src/cs3443/Grades.java
package cs3443;
import java.util.*;
public class Grades {
/**<h1> Grades class </h1>
* This class processes each student and their grades to
* calculate various results. i.e. average, median, max etc.
*
* @author <NAME>
*
*/
private String name; //instance variable for student names
private int[] grades; //instance variable for student grades
/**<h1>toString</h1>
* This method returns a string does not take any parameters
*it replaces java.lang toString function for getName() and getGrades()
*
*/
public String toString() {
String str = getName() + " ";
str += getGrades();
return str;
}
/**<h1> inputGrade</h1>
* Takes grades from input file and stores them in an array
*
* @param in takes scanner input
*/
public void inputGrade(Scanner in) {
grades = new int[1];
int cnt = 0;
while (in.hasNextInt()) {
int grade = in.nextInt();
// if need to double the size of the array
if (cnt == grades.length) {
grades = Arrays.copyOf(grades, 2 * grades.length);
}
grades[cnt] = grade;
cnt++;
// place each grade into an array
int[] gradeArray = new int[cnt];
for (int i = 0; i < cnt; i++) {
gradeArray[i] = grades[i];
}
grades = gradeArray; // copy grades into array
}
}
/** <h1> getGrades </h1>
* Converts int array to String using java Arrays methods
*
* @return String of students grades
*/
public String getGrades() {
//convert int array to a string
String stringGrades = Arrays.toString(grades);
return stringGrades;
}
/**<h1> length </h1>
* Counts how many grades each student has
* @return total grades student has
*/
public int length() {
int length = grades.length;
return length;
}
/**<h1>getName</h1>
* Students name
* @return students name
*/
public String getName() {
return name;
}
/**<h1>setName</h1>
* Sets each student name based on input data from file
*
* @param name students name
*/
public void setName(String name) {
this.name = name;
}
/**<h1>average</h1>
* Calculates the average of each students grades
* @return average of students grades
*/
public double average() {
int total = 0;
int i = 0;
while (i < grades.length) {
int grade = grades[i];
//sum of grades
total += grade;
i++;
}
return (double) total / grades.length;
}
/**<h1>median</h1>
* Calculates the median of each student based on grades
* @return the median of grade
*/
public double median() {
double median = 0;
Arrays.sort(grades);
// if length of array is even
if(grades.length % 2 == 0){
int pos1 = (grades.length - 1) / 2;
int pos2 = grades.length / 2;
median = (double) (grades[pos1] + grades[pos2]) / 2;
} else {
// if length of array is odd
int pos = (grades.length - 1) / 2;
median = grades[pos];
}
return median;
}
/**<h1>maximum</h1>
* Gets the max grade for each student
* @return the max grade
*/
public int maximum() {
int max = grades[0];
// loop through each grade in array and check if > previous
for (int grade : grades) {
if (grade > max)
max = grade;
}
return max;
}
/**<h1>minimum</h1>
* Gets the min grade for each student
* @return the minimum grade
*/
public int minimum() {
int min = grades[0];
// for each grade in array check if < previous
for (int i = 0; i < grades.length; i++) {
int grade = grades[i];
if (grade < min)
min = grade;
}
return min;
}
} //end of class
<file_sep>/hua647-Lab 3/src/cs3443/DateRange.java
package cs3443;
/**
* Class to create date range objects to return a date range
* if this date before other date.
* @author <NAME>
*
*/
public class DateRange {
//First date to compare
private Date date1;
//Used for toString
private String str;
//Second date to compare
private Date date2;
/**
* Creates a date range object composed of two valid dates.
* @param start first date object
* @param end second date object
*/
public DateRange(Date start, Date end){
//set incoming date object value to class instance variables
this.date1 = start;
this.date2 = end;
}
/**
* Overrides java toString method and return
* date range object in correct format.
* @return date range object in string format
*/
public String toString(){
if(this.date1 != null && this.date2 != null){
str = "DateRange: " + this.date1
+ " - " + this.date2;
}
return str;
} // end of toString
}//end of class
<file_sep>/hua647-Lab10/src/SortingThread.java
import java.util.Arrays;
import java.util.Random;
/** Provides methods and capabilities to sort arrays of equal size
* between threads and print them out in ascending order.
* @author <NAME>
* */
public class SortingThread implements Runnable {
/** Designates which thread number this SortingThread class belongs to*/
private int threadNumber;
/** The array of numbers to be sorted in this thread.*/
private int[] arrayToSort;
/** SortingBuffer class which provides thread methods to wait and
* notify threads on sort.*/
private SortingBuffer buffer;
/** This class is used to sort arrays between multiple threads. For
* each thread being called, this class identifies the thread number,
* it is given an array of equal size on other threads utilizing this class
* and provides access to the SortingBuffer class which allows access
* to methods that provide notification methods on sort between threads.
* Additionally, it will sort the array before any other operations are
* performed.
* @param threadNumber ID of the thread being executed.
* @param arrayToSort Array to be sorted in between threads.
* @param buffer SortingBuffer class which provides access to thread
* methods to allow sorting between arrays in multiple threads.*/
public SortingThread(int threadNumber, int[] arrayToSort,
SortingBuffer buffer) {
this.threadNumber = threadNumber;
this.arrayToSort = arrayToSort;
Arrays.sort(this.arrayToSort);
this.buffer = buffer;
}
/** Default method executed when class is created in a thread manner.
* It will first print out all array values in the given array in an
* unsynchronized manner. It will then print out the values in the array
* in ascending order when compared to values in an array in a separate
* thread.
* */
@Override
public void run() {
try {
if(this.threadNumber != 0)
Thread.sleep(new Random().nextInt(500));
for(int value : this.arrayToSort){
System.out.println(this.threadNumber + " unsynchronized "
+ value);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
for(int value : this.arrayToSort){
try {
buffer.waitUntilMinimum(this.threadNumber, value);
System.out.println(this.threadNumber + " synchronized "
+ value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer.finished(this.threadNumber);
}
}<file_sep>/hua647-lab4/src/length/Meter.java
package length;
public class Meter extends Length {
public Meter(double length) {
super(length);
}
public void add(Length other) {
double currLength = this.getLength();
currLength += other.toMeters();
this.setLength(currLength);
}
public String getUnit() {
if (this.getLength() == 1.0)
return "meter";
else
return "meters";
}
public double toMeters() {
return this.getLength();
}
}
<file_sep>/hua647-Lab 3/src/cs3443/Date.java
package cs3443;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.StringTokenizer;
/**
* Date class used to parse through input file composed of
* dates in string format. Check is input date is a valid date or not
* and compares dates to see if date is before next date.
* @author <NAME>
*
*/
public class Date implements Comparable<Date> {
//Used to store potential dates in file
private Serializable date;
//Used to pass string value of month from index 0 to 3 to monthToInt
private String strMonth;
//1 to 12 used to compare date to other
private int month;
//Days of month used to compare date to other
private int day;
//Year of date used to compare date to other
private int year;
//Used to return valid output toString
private String str;
//Checks is date is valid true or false is invalid date
private boolean isValid;
// parse string input and change to correct date format
SimpleDateFormat output = new SimpleDateFormat("MMMM d, yyyy");
//Array of different date formats used to parse and validate input
private SimpleDateFormat[] formats = new SimpleDateFormat[] {
new SimpleDateFormat("MMMM dd, yyyy"), new SimpleDateFormat("MMM. d, yyyy"),
new SimpleDateFormat("MMM. dd, yyyy"), new SimpleDateFormat("MMM dd, yyyy"),
new SimpleDateFormat("MMM d, yyyy"), };
/**
* Date constructor used to take in file string input then tokenize the
* input to use for processing the date objects.
* @param line for string input from file
*/
public Date(String line) {
StringTokenizer token = new StringTokenizer(line);
//manually parse through string into to get month date and year
strMonth = token.nextToken().substring(0, 3);
month = monthToInt(strMonth);
day = Integer.parseInt(token.nextToken().replace(",", ""));
year = Integer.parseInt(token.nextToken());
//Loops through array of date formats and throws exception if date is invalid
for (SimpleDateFormat format : formats) {
try {
format.setLenient(false);
date = format.parse(line);
} catch (ParseException e) {
// try more possible date formats
}
}
isValid = true; // input successfully parsed valid date
}
/**
* Compares two date objects to each other using the month
* day and year to determine if this date is before other date.
* If this date is before other date then a DateRange object is created from
* both dates.
* @param other date
* @return -1 is this date before other, 1 is this date after other, and 0 if equal
*/
public int compareTo(Date other) {
if (year < other.getYear()) {
return -1;
} else if (year > other.getYear()) {
return 1;
} else {
if (month < other.getMonth()) {
return -1;
} else if (month > other.getMonth()) {
return 1;
} else {
if (day < other.getDay()) {
return -1;
} else if (day > other.getDay()) {
return 1;
} else {
return 0;
}
}
}
}
/**
* Checks input file month names from index 0 to 3
* and if upper or lower case date returns the numeric version
* of that month.
* @param month name of month
* @return integer version of month
*/
public int monthToInt(String month) {
//Validates entire year January to December
if (month.equals("Jan") || month.equals("jan")) {
return 1;
} else if (month.equals("Feb") || month.equals("feb")) {
return 2;
} else if (month.equals("Mar") || month.equals("mar")) {
return 3;
} else if (month.equals("Apr") || month.equals("apr")) {
return 4;
} else if (month.equals("May") || month.equals("may")) {
return 5;
} else if (month.equals("Jun") || month.equals("jun")) {
return 6;
} else if (month.equals("Jul") || month.equals("jul")) {
return 7;
} else if (month.equals("Aug") || month.equals("aug")) {
return 8;
} else if (month.equals("Sep") || month.equals("sep")) {
return 9;
} else if (month.equals("Oct") || month.equals("oct")) {
return 10;
} else if (month.equals("Nov") || month.equals("nov")) {
return 11;
} else if (month.equals("Dec") || month.equals("dec")) {
return 12;
} else {
return -1; //default invalid value
}
}
/**
* Getter for date objects months integer value
* @return months integer value
*/
public int getMonth() {
return month;
}
/**
* Setter for months
* @param month integer value
*/
public void setMonth(int month) {
this.month = month;
}
/**
* Getter for days value
* @return days integer value
*/
public int getDay() {
return day;
}
/**
* Setter for day value
* @param day integer value
*/
public void setDay(int day) {
this.day = day;
}
/**
* Getter for year integer value
* @return year integer value
*/
public int getYear() {
return year;
}
/**
* Setter for year value
* @param year integer value
*/
public void setYear(int year) {
this.year = year;
}
/**
* Returns true if date is valid or false is invalid date
* @return true or false
*/
public boolean isValid() {
return isValid;
}
/**
* Setter for date verification true or false
* @param valid date
*/
public void setValid(boolean valid) {
this.isValid = valid;
}
/**
* Used to override java toString() and return correct output
* uses simpledateformater to print dates or prints "Invalid Date" is
* not a valid date.
* @return prints dates in correct format
*/
public String toString() {
try {
str = "Date: " + output.format(date);
} catch (IllegalArgumentException e) {
str = "Invalid Date";
isValid = false;
}
return str;
}
}//end of class
<file_sep>/hua647-Lab2 Test/src/cs3443/Lab2.java
package cs3443;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**<h1> Lab2 class</h1>
*Description:
* This class reads in a text file called data.txt which
* contains pairs of lines: the first line of each pair is the name
* of the student, and the second are the list of grades. This class
* uses methods from Grades class and stores data into objects to be processed.
*
* Sample input:
* Carla
* 87 99 96 99
*
* Sample output:
* Carla [87, 99, 96, 99]
* Name: Carla
* Length: 4
* Average: 95.25
* Median: 96.0
* Maximum: 99
* Minimum: 87
* @author <NAME>
*
*/
public class Lab2 {
/**<h1> Main </h1>
* The main method is responsible for opening the data file and
* assigning the name and grades of each student to objects from
* Grades class. It then calls testGrades method to print the values
* of each student and grades. Finally it closes the file.
*
* @param args input arguments for main
*/
public static void main(String[] args) {
Scanner input = null; // initialize input to be null
Grades student = new Grades(); // Grades class object
String name = ""; // initialize variable for name to be blank
try {
input = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open data.txt");
System.exit(1);
}
// continue to read in tokens until EOF
while (input.hasNext()) {
name = input.next();
// Grades method to parse grades and save in array of integers
student.inputGrade(input);
student.setName(name);
// print the results for each student
testGrades(student);
}
input.close(); // close input file
}
/**<h1>testGrades</h1>
* This method uses objects from class Grades to call methods that
* return data for each student. Each student's name grades, averages,
* median, maximum, and minimum grades are displayed in specific format.
*
* @param grades object from Grades class used to access Grades methods
*/
public static void testGrades(Grades grades) {
//prints results of each student
System.out.println(grades.toString());
System.out.printf("\tName: %s\n", grades.getName());
System.out.printf("\tLength: %d\n", grades.length());
System.out.printf("\tAverage: %.2f\n", grades.average());
System.out.printf("\tMedian: %.1f\n", grades.median());
System.out.printf("\tMaximum: %d\n", grades.maximum());
System.out.printf("\tMinimum: %d\n", grades.minimum());
}
}<file_sep>/hua647-Lab 3/src/cs3443/Lab3.java
package cs3443;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
/**
* Class created to house main method.
*
*
* @author <NAME>
*
*/
public class Lab3 {
/**
* Reads input file and parse through input line by line and uses
* Date class to create date objects which are then passed to
* DateRange constructor to create date range objects is both dates are
* valid.
* @param args string input
*/
public static void main(String[] args) {
// first date to compare
Date startDate = null;
// scanner object set to null
Scanner in = null;
try {
in = new Scanner(new File("dates.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open dates.txt");
System.exit(1);
}
//continue looping through file until each EOF
while (in.hasNextLine()) {
String line = in.nextLine();
Date date = new Date(line);
System.out.println(date);
//if first date is null then set it to next date
if (startDate == null) {
startDate = date;
} else {
if (date.isValid()== true && startDate.isValid() == true ) {
if (startDate.compareTo(date) == -1) {
DateRange dateRange = new DateRange(startDate, date);
System.out.println(dateRange);
}
//continue to set first date to next date to loop through file
startDate = date;
}
} //end of else
}//end of while
}//end of main
} //end of class
|
2efddc912ef4a0081543c40c33656eec09bb21f7
|
[
"Java"
] | 7
|
Java
|
easilyamused07/java
|
d31c4f9b1cb206ac2896d736484e9f0072ec37b2
|
ff7eb3f98390236ea45bf2e417475eafcb01ea4e
|
refs/heads/main
|
<repo_name>marinabar/cs50ai<file_sep>/README.md
# cs50ai
My projects for Harvard's CS50 - AI course
<file_sep>/tictactoe/tictactoe.py
"""
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
if board == initial_state():
return X
Xboard_count = board[0].count(X) + board[1].count(X) + board[2].count(X) + board[0].count(O) + board[1].count(O) + board[2].count(O)
if Xboard_count % 2 == 1:
return O
else:
return X
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
action = ()
act1 = list(action)
for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
act1.append((i, j))
action = tuple(act1)
return action
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
if action not in actions(board):
raise Exception("this action is not a valid action")
dcopb = copy.deepcopy(board)
dcopb[action[0]][action[1]] = player(board)
return dcopb
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
for x in range(3):
if board[x][0] == board[x][1] == board[x][2] != EMPTY:
return board[x][0]
for y in range(3):
if board[0][y] == board[1][y] == board[2][y] != EMPTY:
return board[0][y]
if board[0][0] == board[1][1] == board[2][2] != EMPTY:
return board[0][0]
if board[2][0] == board[1][1] == board[0][2] != EMPTY:
return board[2][0]
else:
return None
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if winner(board) == X:
return True
elif winner(board) == O:
return True
for x in range(3):
for y in range(3):
if board[x][y] is None:
return False
return True
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
if winner(board) == X:
return 1
if winner(board) == O:
return -1
else:
return 0
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
if terminal(board):
return None
if player(board) == X:
v = -math.inf
for one in actions(board):
temp = MinValue(result(board, one))
if temp > v:
v = temp
best = one
else:
v = math.inf
for one in actions(board):
temp = MaxValue(result(board, one))
if temp < v:
v = temp
best = one
return best
def MaxValue(board):
if terminal(board):
return utility(board)
v = -math.inf
for one in actions(board):
value = MinValue(result(board, one))
v = max(v, value)
if v == 1:
break
return v
def MinValue(board):
if terminal(board):
return utility(board)
v = math.inf
for one in actions(board):
value = MaxValue(result(board, one))
v = min(v, value)
if v == -1:
break
return v
<file_sep>/traffic/README.md
First added one Conv2D layer, a Maxpool one with 4x4 grid, a flattening layer and 2 other hidden ones.
Then added a SGD optimizer plus a softmax activation at the end.
The model did a pretty bad job, with a 0.056 accuracy after 10 epochs.
I tried adding two dropout layers, with a 0.5 parameter. It also did a horrible job.
Changing one of the parameters of the droput layers to 0.3 and the other to 0.8 didn't do much either. But after changing both of them to 0.3, the model became way more accurate.
After printing out the model summary I decided I wanted to try adding another Conv2D layer, so I did, along with a Maxpool with a 2x2 pool size.
It just made things worse, and the accuracy went from 0.9 to 0.7.
I then proceed to add another Dropout layer before the 2nd Conv2D layer.
Didn't change much things either, therefore I deleted the convolutional layers I had previously added.
+ Put another Dense layer
it really improved the model A LOT (92% accuracy!)
Tried adding another Dense layer + dropout, though deleted the dropout layer right after, and got again the 0.92 accuracy.
Increased the size of the first hidden layer, and decreased the pool size.
Achieved 95% accuracy!
<file_sep>/questions/questions.py
import nltk
import sys
import math
import os
import string
FILE_MATCHES = 1
SENTENCE_MATCHES = 3
def main():
# Check command-line arguments
if len(sys.argv) != 2:
sys.exit("Usage: python questions.py corpus")
# Calculate IDF values across files
files = load_files(sys.argv[1])
file_words = {
filename: tokenize(files[filename])
for filename in files
}
file_idfs = compute_idfs(file_words)
# Prompt user for query
query = set(tokenize(input("Query: ")))
# Determine top file matches according to TF-IDF
filenames = top_files(query, file_words, file_idfs, n=FILE_MATCHES)
# Extract sentences from top files
sentences = dict()
for filename in filenames:
for passage in files[filename].split("\n"):
for sentence in nltk.sent_tokenize(passage):
tokens = tokenize(sentence)
if tokens:
sentences[sentence] = tokens
# Compute IDF values across sentences
idfs = compute_idfs(sentences)
# Determine top sentence matches
matches = top_sentences(query, sentences, idfs, n=SENTENCE_MATCHES)
for match in matches:
print(match)
def load_files(directory):
"""
Given a directory name, return a dictionary mapping the filename of each
`.txt` file inside that directory to the file's contents as a string.
"""
files = {}
for file_name in os.listdir(directory): # In every file in directory
with open(os.path.join(directory, file_name)) as f:
files[file_name] = f.read() # Add text file to dictionary with the text as a key
return files
def tokenize(document):
"""
Given a document (represented as a string), return a list of all of the
words in that document, in order.
Process document by converting all words to lowercase, and removing any
punctuation or English stopwords.
"""
list = []
document = document.lower() # Lowercase the text
words = nltk.word_tokenize(document) # Tokenize using NLTK's library
for one in words:
# Checking if a symbol is neither a punctuation sign neither a stopword, or "unimportant word"
if one not in nltk.corpus.stopwords.words("english") and one not in string.punctuation:
list.append(one)
return list
def compute_idfs(documents):
"""
Given a dictionary of `documents` that maps names of documents to a list
of words, return a dictionary that maps words to their IDF values.
Any word that appears in at least one of the documents should be in the
resulting dictionary.
"""
values = dict()
words = set()
for doc in documents: # Set of all single words across all documents
words.update(set(documents[doc]))
# words_s = set(words)
for one in words:
all = 0
# Loop through the documents to find if the word is in it
for doc in documents:
if one in documents[doc]:
all += 1
idf = math.log(len(documents) / all)
values[one] = idf
return values
def top_files(query, files, idfs, n):
"""
Given a `query` (a set of words), `files` (a dictionary mapping names of
files to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the filenames of the the `n` top
files that match the query, ranked according to tf-idf.
"""
scores = []
for doc in files:
tfidf = 0
# Loop through each word in the query and get the tfidf for each document according to that word
for word in query:
tfidf += idfs[word] * files[doc].count(word)
scores.append((doc, tfidf))
# Rank the dictionary according to each value's tfidf
scores.sort(key=lambda x: x[1], reverse=True)
top = list(scores[0])
# Return first N elements
print(top[0])
return top[:n]
def top_sentences(query, sentences, idfs, n):
"""
Given a `query` (a set of words), `sentences` (a dictionary mapping
sentences to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the `n` top sentences that match
the query, ranked according to idf. If there are ties, preference should
be given to sentences that have a higher query term density.
"""
top = []
for sentence in sentences:
idf = 0
words = 0
for word in query:
if word in sentences[sentence]:
words += 1
idf += idfs[word]
# Calculate query term density
density = float(words) / len(sentences[sentence])
top.append((sentence, idf, density))
top.sort(key=lambda x: (x[1], x[2]), reverse=True) # Sort values by highest idf then density
# best = list(top[0])
return [x[0] for x in top[:n]] # Return first N elements
if __name__ == "__main__":
main()
|
bb1ebd20469047e894e249305498086131ac6ef1
|
[
"Markdown",
"Python"
] | 4
|
Markdown
|
marinabar/cs50ai
|
0ce1d72e9636059f7f9417b1f8035706fa0795eb
|
f13cc26f3d1fa8c380cbb58b4d8babeb3b3e77cd
|
refs/heads/main
|
<repo_name>kudenv/timer-watch-angualr-app<file_sep>/src/app/shared/service/stopwatch.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { LocalStorageService } from './local-storage.service';
@Injectable({
providedIn: 'root'
})
export class StopwatchService {
initialState = {
mm:0,
ss:0,
ms:0
}
nextState = {...this.initialState};
dataList: Array<any> = new Array();
timerData = new BehaviorSubject(this.initialState);
tmpList: Array<any> = [];
savedTimerData = new BehaviorSubject(this.tmpList);
constructor(private localStorageService:LocalStorageService) {}
incrementTimer(){
console.log(this.nextState)
this.nextState.ms++;
if (this.nextState.ms >= 100) {
this.nextState.ss++;
this.nextState.ms = 0;
}
if (this.nextState.ss >= 60) {
this.nextState.mm++;
this.nextState.ss = 0
}
this.timerData.next(this.nextState)
this.localStorageService.setTimerData(this.nextState)
}
addTimerToList(timer: any) {
this.tmpList.push({
mm:timer.mm,
ss:timer.ss,
ms:timer.ms
});
this.savedTimerData.next(this.tmpList);
this.localStorageService.setTimerList(this.tmpList);
}
removeSingleTimerByIndex(index: number){
for(let i=0 ;i<= this.tmpList.length ;i++){
if(index== this.tmpList[i]){
this.tmpList.splice(i,1)
}
}
this.localStorageService.setTimerList(this.tmpList)
}
clearAll() {
this.nextState = this.initialState
this.tmpList = []
this.savedTimerData.next([])
this.timerData.next(this.initialState)
localStorage.clear()
}
getValuesFromLocalStorage(){
this.tmpList = this.localStorageService.getTimerList() || []
this.nextState =this.localStorageService.getTimerData() || this.nextState;
this.savedTimerData.next(this.tmpList)
this.timerData.next(this.nextState)
}
}
<file_sep>/src/app/stop-watch/stop-watch.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { LocalStorageService } from '../shared/service/local-storage.service';
import { StopwatchService } from '../shared/service/stopwatch.service';
@Component({
selector: 'app-stop-watch',
templateUrl: './stop-watch.component.html',
styleUrls: ['./stop-watch.component.css']
})
export class StopWatchComponent implements OnInit, OnDestroy {
mm = 0;
ss = 0;
ms = 0;
public timer = {
mm:0,
ss:0,
ms:0
}
public isRunning = false;
public timerId:any = 0;
public list: Array<any> = [];
hideElement = false;
selectedIndex: any;
private _timerSubscription: any;
private _listDataSubscription: any;
constructor(private _stopWatchService: StopwatchService, private _localStorageService: LocalStorageService) {}
ngOnInit() {
this._stopWatchService.getValuesFromLocalStorage();
this.isRunning = this._localStorageService.getRuningFlag() === "true" ? true : false;
if (this.isRunning) {
this.continueTimer()
}
this._listDataSubscription = this._stopWatchService.savedTimerData.subscribe((data) => {
this.list = data;
})
this._timerSubscription = this._stopWatchService.timerData.subscribe((data) => {
this.timer = data;
})
}
playPause(flag?: any) {
if(!this.isRunning) {
this.timerId = setInterval(() => {
this._stopWatchService.incrementTimer();
}, 10)
} else {
clearInterval(this.timerId)
}
if (flag === false || flag === undefined) {
this.isRunning = !this.isRunning;
this._localStorageService.setRuningFlag(this.isRunning);
}
}
continueTimer() {
this.timerId = setInterval(() => {
this._stopWatchService.incrementTimer();
})
}
add(timer: any) {
this._stopWatchService.addTimerToList(timer);
}
deleteAll() {
this._stopWatchService.clearAll();
}
remove(index: number) {
this._stopWatchService.removeSingleTimerByIndex(index);
}
setButton(flag: any, selectedIndex: number) {
this.selectedIndex = selectedIndex;
if(flag == true) {
this.hideElement = false;
} else {
this.hideElement = true;
}
}
ngOnDestroy() {
this._timerSubscription.unsubscribe();
this._listDataSubscription.unsubscribe();
}
}
<file_sep>/src/app/shared/service/local-storage.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LocalStorageService {
isRuningFlag: string | null = '';
timerList: any;
timerData: string | null = '';
setRuningFlag(flag: any) {
localStorage.setItem('RUNNING_FLAG',flag.toString());
}
getRuningFlag(): string | null {
this.isRuningFlag = localStorage.getItem('RUNING_FLAG');
return this.isRuningFlag;
}
setTimerList(list: any) {
localStorage.setItem('TIMER_LIST', JSON.stringify(list));
}
getTimerList(): any {
this.timerList = JSON.parse(localStorage.getItem("TIMER_LIST") || "[]");
return this.timerList;
}
setTimerData(timer: any) {
localStorage.setItem('TIMER_VALUE', JSON.stringify(timer));
}
getTimerData(): any {
this.timerData = JSON.parse(localStorage.getItem("TIMER_VALUE") as string);
return this.timerData;
}
}
|
b86e6efc07330c7c4c19a8d5ecc368fdb170bd8c
|
[
"TypeScript"
] | 3
|
TypeScript
|
kudenv/timer-watch-angualr-app
|
0b7057328638c124b15f9087d2d5fe5caa2294eb
|
41eedbac7832285da0a98b17c39757d843889aea
|
refs/heads/master
|
<repo_name>amaranabe/java2_OperacionesGeometricas<file_sep>/com/zubiri/geometria/Rectangulo.java
/*
* Clase para obtener resultados del perimetro y area de un rectangulo.
*/
package com.zubiri.geometria;
public class Rectangulo
{
private double base = -1;
private double altura = -1;
public Rectangulo (double valorBase, double valorAltura)
{
base=valorBase;
altura=valorAltura;
}
public double getBase()
{
return base;
}
public double getAltura()
{
return altura;
}
public void setBase (double _base)
{
base=_base;
}
public void setAltura (double _altura)
{
altura=_altura;
}
//Metodo que calcula el perimetro.
public double perimetro ()
{
double result;
result = 2 *(this.getBase() + this.getAltura());
return result;
}
//Metodo que calcula el area (base*altura).
public double area ()
{
double result;
result = this.getBase() * this.getAltura();
return result;
}
}
|
5166dddd3eb0d129a0e1b8301cc1d6403d0cef31
|
[
"Java"
] | 1
|
Java
|
amaranabe/java2_OperacionesGeometricas
|
8c7d50c312289a912b63f7a262d37ea2679f9c1e
|
49fd06f360dd1ca0bef5da7a03e3eee67fb1356a
|
refs/heads/master
|
<file_sep>package practica1;
import java.util.LinkedList;
import java.util.Random;
public class punto12 {
private LinkedList<estudiantePunto12> C1 = new LinkedList<estudiantePunto12>();
private estudiantePunto12 tempStudent;
public void newDataBase(int n){
for( int i=0; i<n; i++){
addStudent(Integer.toString(i));
for( int j=0; j<=3;j++){
setNota(i,j,randNota());
}
getFinal(i);
}
}
public void addStudent(String codigo){
tempStudent = new estudiantePunto12(codigo);
C1.addLast(tempStudent);
}
public String getCodigo(int n){
return C1.get(n).getCodigo();
}
public void setCodigo(int n, String codigo){
C1.get(n).setCodigo(codigo);
}
public void setNota(int Estudiante, int n, double nota){
C1.get(Estudiante).setNota(n, nota);
}
public double getNota(int Estudiante, int n){
return C1.get(Estudiante).getNota(n);
}
public double getPorcentaje(int Estudiante, int n){
return C1.get(Estudiante).getPorcentaje(n);
}
public double randNota(){
Random rand = new Random();
int[] topes = {0,50};
int randomNum = rand.nextInt((topes[1]-topes[0])+1)+topes[0];
return (double)randomNum/10;
}
public double getFinal(int Estudiante){
double nfinal=0;
for( int j=0; j<=3;j++){
nfinal = nfinal + getNota(Estudiante,j)*getPorcentaje(Estudiante,j);
}
setNota(Estudiante,4,nfinal);
return nfinal;
}
public double promDefinitiva(int n){
double suma = 0;
for( int i= 0; i<n; i++){
suma = suma + getFinal(i)/(double)n;
}
return suma;
}
public double porcentajeBrutos(int n){
int cont = 0;
for(int i=0; i<n; i++){
if(getFinal(i)<3) cont++;
}
return (double)cont/(double)n*100;
}
}
<file_sep>package practica1;
public class Libro extends Publicacion {
private long numPag;
private int anoPublica;
public Libro(String titulo, long precio, long numPag, int anoPublica) {
super(titulo, precio);
this.numPag = numPag;
this.anoPublica = anoPublica;
}
public Libro(){
super();
this.numPag = 0;
this.anoPublica = 0;
}
public long getNumPag() {
return numPag;
}
public void setNumPag(long numPag) {
this.numPag = numPag;
}
public int getAnoPublica() {
return anoPublica;
}
public void setAnoPublica(int anoPublica) {
this.anoPublica = anoPublica;
}
public void mostrar(){
System.out.println("Tipo: Libro.");
mostrarTitulo();
mostrarPrecio();
mostrarPag();
mostrarAno();
System.out.println("");
}
private void mostrarPag(){
System.out.println("Número de páginas: "+numPag);
}
private void mostrarAno(){
System.out.println("Año de publicación: "+anoPublica);
}
}
<file_sep>package practica1;
public class nota_DM{
private double[] notas = {0,0,0,0,0,0};
private double[] porcentaje = {0.2,0.3,0.1,0.15,0.25,1};
private String[] trabajos = {"Quices y seguimiento", "Prácticas de laboratorio", "Exposiciones", "Proyecto 1", "Proyecto final", "Nota final"};
private String nombre, ID;
public double notaFinal(){
for( int i = 0; i < notas.length-1; i++){
notas[notas.length-1] += notas[i]*porcentaje[i];
}
return notas[notas.length-1];
}
public nota_DM(String nombre, String ID) {
this.nombre = nombre;
this.ID = ID;
}
public double getNota(int n){
if((n<=notas.length)&&(n>0)){
return notas[n-1];
}else
return 0;
}
public void setNota(int n, double nota){
if((n<=notas.length)&&(n>0)){
notas[n-1] = nota;
}
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public int numNotas(){
return notas.length-1;
}
public String getTrabajo(int n){
if((n<=notas.length)&&(n>0)){
return trabajos[n-1];
}else
return "error";
}
public int mensaje(double nota){
if(nota<=1){
return 1;
}else if(nota <= 2){
return 2;
}else if(nota <= 3){
return 3;
}else if(nota <= 4){
return 4;
}else if(nota <= 4.5){
return 5;
}else if(nota <= 5){
return 6;
}else return 7;
}
}
<file_sep>package practica1;
public class punto10 {
private int[] f = {0,1,0};
public int determinar(int numExt){
while(f[1]<numExt){
f[0]=f[1]+f[2];
f[2]=f[1];
f[1]=f[0];
}
if(numExt==f[1]) return 1;
else return 0;
}
}
<file_sep>package practica1;
public class productos {
private int[] precios = {500,800,300,900};
public int getPrecio1(int n){
if((n>=1)&&(n<=precios.length)){
return precios[n-1];
}else
return -1;
}
public int getPrecio2(int n){
switch (n){
case 1:
return 500; //No es necesario poner break pues con return sale
case 2:
return 800;
case 3:
return 300;
case 4:
return 900;
default:
return -1;
}
}
}
<file_sep>package practica1;
public class Publicacion {
protected String titulo;
protected long precio;
public Publicacion(String titulo, long precio) {
this.titulo = titulo;
this.precio = precio;
}
public Publicacion(){
this.precio = 0;
this.titulo = "";
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public long getPrecio() {
return precio;
}
public void setPrecio(long precio) {
this.precio = precio;
}
public void mostrar(){
mostrarTitulo();
mostrarPrecio();
System.out.println("");
}
protected void mostrarTitulo(){
System.out.println("Título: "+titulo);
}
protected void mostrarPrecio(){
System.out.println("Precio: "+precio);
}
}
<file_sep>package practica1;
public class estudiantePunto12 {
private final double[] porcentajes = {0.25,0.2,0.25,0.3,1};
private double[] notas = {0,0,0,0,0};
private String codigo;
public estudiantePunto12(String codigo) {
this.codigo = codigo;
}
public double getNota(int n){
return notas[n];
}
public double getPorcentaje(int n){
return porcentajes[n];
}
public void setNota(int n, double nota){
notas[n]=nota;
}
public String getCodigo(){
return codigo;
}
public void setCodigo(String codigo){
this.codigo=codigo;
}
}
<file_sep>package practica1;
public class Nombre {
private String nombre, primer_apellido, segundo_apellido;
Nombre(String nombre, String primer_apellido, String segundo_apellido){}
Nombre(){}
void Leer_nombre(String nombre, String primer_apellido, String segundo_apellido){
this.nombre = nombre;
this.primer_apellido = primer_apellido;
this.segundo_apellido = segundo_apellido;
}
void Mostrar_nombre(){
System.out.println(nombre+" "+primer_apellido+" "+segundo_apellido);
}
protected String getNombre() {
return nombre;
}
protected void setNombre(String nombre) {
this.nombre = nombre;
}
protected String getPrimer_apellido() {
return primer_apellido;
}
protected void setPrimer_apellido(String primer_apellido) {
this.primer_apellido = primer_apellido;
}
protected String getSegundo_apellido() {
return segundo_apellido;
}
protected void setSegundo_apellido(String segundo_apellido) {
this.segundo_apellido = segundo_apellido;
}
}
<file_sep>package practica1;
public class pitagoras {
private float lado1, lado2;
public double hipotenusa(){
return Math.sqrt(Math.pow(lado1,2)+Math.pow(lado2,2));
}
public pitagoras(float lado1, float lado2) {
this.lado1 = lado1;
this.lado2 = lado2;
}
}
<file_sep>package practica1;
public class Disco extends Publicacion{
private int durMin;
public Disco(String titulo, long precio, int durMin) {
super(titulo, precio);
this.durMin = durMin;
}
public Disco(){
super();
this.durMin = 0;
}
public int getDurMin() {
return durMin;
}
public void setDurMin(int durMin) {
this.durMin = durMin;
}
public void mostrar(){
System.out.println("Tipo: Disco.");
mostrarTitulo();
mostrarPrecio();
mostrarMin();
System.out.println("");
}
private void mostrarMin(){
System.out.println("Duración en minutos: "+durMin);
}
}
<file_sep>package practica1;
public class punto14 {
private double[] elemento = {0,0,0};
public double getElemento(int n){
return elemento[n];
}
public void setElemento(int n, double valor){
elemento[n] = valor;
}
public double getArea(int elemento){
double area = 0;
switch (elemento){
case 0://círculo
area = Math.PI*Math.pow(this.elemento[0], 2);
break;
case 1://triangulo
double p = 0;
for( int i = 0; i<=2; i++){
p += this.elemento[i]/(double)2;
}
area = Math.sqrt(p*(p-this.elemento[0])*(p-this.elemento[1])*(p-this.elemento[2]));
break;
case 2://cuadrado
area = Math.pow(this.elemento[0], 2);
break;
case 3://rectangulo
area = this.elemento[0] * this.elemento[1];
break;
}
return area;
}
}
|
331239cd37db71f5793605d387ce47e87e46e969
|
[
"Java"
] | 11
|
Java
|
ludagoga117/practica1
|
4f4b1b5dba3a9a40594596696e9f7d47bd3175bb
|
8b26d1f8605486e4d82dedc8ac96fa962f9b7649
|
refs/heads/master
|
<file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="fr">
<head>
<!-- Generated by javadoc (1.8.0_162) on Fri Mar 02 12:51:24 CET 2018 -->
<title>InstructionsParser</title>
<meta name="date" content="2018-03-02">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="InstructionsParser";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/omcis/model/planners/Instructions.html" title="class in com.omcis.model.planners"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../com/omcis/model/planners/InstructionsParserTest.html" title="class in com.omcis.model.planners"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/omcis/model/planners/InstructionsParser.html" target="_top">Frames</a></li>
<li><a href="InstructionsParser.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.omcis.model.planners</div>
<h2 title="Class InstructionsParser" class="title">Class InstructionsParser</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.omcis.model.planners.InstructionsParser</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.util.function.Consumer<java.lang.String></dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">InstructionsParser</span>
extends java.lang.Object
implements java.util.function.Consumer<java.lang.String></pre>
<div class="block">This consumer assists in parsing the instructions.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.util.regex.Pattern</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/omcis/model/planners/InstructionsParser.html#evenRowsMatcher">evenRowsMatcher</a></span></code>
<div class="block">Regex for the mowers initial positioning.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.util.regex.Pattern</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/omcis/model/planners/InstructionsParser.html#firstRowMatcher">firstRowMatcher</a></span></code>
<div class="block">Regex for the first row pattern (upper right corner of the lawn example: "5 5")</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.util.regex.Pattern</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/omcis/model/planners/InstructionsParser.html#oddRowsMatcher">oddRowsMatcher</a></span></code>
<div class="block">Regex for the third row pattern representing the prompts.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../com/omcis/model/planners/InstructionsParser.html#InstructionsParser--">InstructionsParser</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/omcis/model/planners/InstructionsParser.html#accept-java.lang.String-">accept</a></span>(java.lang.String s)</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code><a href="../../../../com/omcis/model/planners/Instructions.html" title="class in com.omcis.model.planners">Instructions</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/omcis/model/planners/InstructionsParser.html#buildFromInstructionsFilePath-java.nio.file.Path-">buildFromInstructionsFilePath</a></span>(java.nio.file.Path path)</code>
<div class="block">Returns a set of instructions to mowe the lawn from an existing file.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><a href="../../../../com/omcis/model/planners/Instructions.html" title="class in com.omcis.model.planners">Instructions</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/omcis/model/planners/InstructionsParser.html#buildFromInstructionsStream-java.util.stream.Stream-">buildFromInstructionsStream</a></span>(java.util.stream.Stream<java.lang.String> instructionsStream)</code>
<div class="block">Returns a set of instructions to mowe the lawn from a stream of string instructions.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>static java.util.regex.Matcher</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/omcis/model/planners/InstructionsParser.html#matchIfRowCompliant-java.util.regex.Pattern-java.lang.String-">matchIfRowCompliant</a></span>(java.util.regex.Pattern pattern,
java.lang.String row)</code>
<div class="block">Checks whether a row is compliant to the expected pattern provided.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.util.function.Consumer">
<!-- -->
</a>
<h3>Methods inherited from interface java.util.function.Consumer</h3>
<code>andThen</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="firstRowMatcher">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>firstRowMatcher</h4>
<pre>public static final java.util.regex.Pattern firstRowMatcher</pre>
<div class="block">Regex for the first row pattern (upper right corner of the lawn example: "5 5")</div>
</li>
</ul>
<a name="evenRowsMatcher">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>evenRowsMatcher</h4>
<pre>public static final java.util.regex.Pattern evenRowsMatcher</pre>
<div class="block">Regex for the mowers initial positioning. These rows are even (example: "1 2 N"</div>
</li>
</ul>
<a name="oddRowsMatcher">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>oddRowsMatcher</h4>
<pre>public static final java.util.regex.Pattern oddRowsMatcher</pre>
<div class="block">Regex for the third row pattern representing the prompts. These rows are odd. Example;"AAADDDGGGA"</div>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="InstructionsParser--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>InstructionsParser</h4>
<pre>public InstructionsParser()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="matchIfRowCompliant-java.util.regex.Pattern-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>matchIfRowCompliant</h4>
<pre>public static java.util.regex.Matcher matchIfRowCompliant(java.util.regex.Pattern pattern,
java.lang.String row)
throws <a href="../../../../com/omcis/model/exceptions/InstructionsParsingException.html" title="class in com.omcis.model.exceptions">InstructionsParsingException</a></pre>
<div class="block">Checks whether a row is compliant to the expected pattern provided.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>pattern</code> - the pattern to match the string row against.</dd>
<dd><code>row</code> - the row to check againt the pattern.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>a Matcher resulting from the compilation of the pattern against the string row.</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../../com/omcis/model/exceptions/InstructionsParsingException.html" title="class in com.omcis.model.exceptions">InstructionsParsingException</a></code> - thrown when the string row does not match the pattern.</dd>
</dl>
</li>
</ul>
<a name="accept-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>accept</h4>
<pre>public void accept(java.lang.String s)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>accept</code> in interface <code>java.util.function.Consumer<java.lang.String></code></dd>
</dl>
</li>
</ul>
<a name="buildFromInstructionsStream-java.util.stream.Stream-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>buildFromInstructionsStream</h4>
<pre>public <a href="../../../../com/omcis/model/planners/Instructions.html" title="class in com.omcis.model.planners">Instructions</a> buildFromInstructionsStream(java.util.stream.Stream<java.lang.String> instructionsStream)
throws <a href="../../../../com/omcis/model/exceptions/InstructionsParsingException.html" title="class in com.omcis.model.exceptions">InstructionsParsingException</a></pre>
<div class="block">Returns a set of instructions to mowe the lawn from a stream of string instructions.
working with the streams instead of a list is a good practice aiming to preserve the memory in case the input files are huge.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>instructionsStream</code> - The stream of string instructions</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>A set of instructions to mowe the lawn.</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../../com/omcis/model/exceptions/InstructionsParsingException.html" title="class in com.omcis.model.exceptions">InstructionsParsingException</a></code> - Thrown when a parsiing exception is encountered. Usually when the input data is not compliant.</dd>
</dl>
</li>
</ul>
<a name="buildFromInstructionsFilePath-java.nio.file.Path-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>buildFromInstructionsFilePath</h4>
<pre>public <a href="../../../../com/omcis/model/planners/Instructions.html" title="class in com.omcis.model.planners">Instructions</a> buildFromInstructionsFilePath(java.nio.file.Path path)
throws <a href="../../../../com/omcis/model/exceptions/InstructionsParsingException.html" title="class in com.omcis.model.exceptions">InstructionsParsingException</a></pre>
<div class="block">Returns a set of instructions to mowe the lawn from an existing file.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>path</code> - the instructions file path.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>A set of instructions to mowe the lawn.</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../../com/omcis/model/exceptions/InstructionsParsingException.html" title="class in com.omcis.model.exceptions">InstructionsParsingException</a></code> - Thrown when a parsiing exception is encountered. Usually when the input data is not compliant.</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/omcis/model/planners/Instructions.html" title="class in com.omcis.model.planners"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../com/omcis/model/planners/InstructionsParserTest.html" title="class in com.omcis.model.planners"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/omcis/model/planners/InstructionsParser.html" target="_top">Frames</a></li>
<li><a href="InstructionsParser.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
<file_sep>package com.omcis.model.planners;
import com.omcis.model.exceptions.IllegalPositioningException;
import com.omcis.model.exceptions.InstructionsRunningException;
import com.omcis.model.trackers.Coordinate;
import com.omcis.model.trackers.Positioning;
import com.omcis.model.trackers.Prompt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import java.util.LinkedList;
import java.util.concurrent.Callable;
import java.util.function.BiConsumer;
/**
* This is a Biconsumer to assist in running the instructions.
* The map""Positioning,Prompt[]"".foreach(instructionsRunner) enables the instructions to be ran.
*/
public class InstructionsRunner implements BiConsumer<Positioning, Prompt[]>, Callable<LinkedList<Positioning>> {
/**
* logger for the InstructionsRunner class
*/
final static Logger logger = LoggerFactory.getLogger(InstructionsRunner.class);
/**
* Tells whether or not the mowers mowe simultaneously.
*/
public static boolean context_lockPosition = false;
/**
*
*/
private LinkedList<Positioning> stackOfPositioning = new LinkedList<>();
/**
*
*/
private Instructions instructions;
/**
* The initial positioning of the mower
*/
private Positioning positioning;
/**
* The set of prompts to run with the current mower
*/
private Prompt[] prompts;
/**
* Constructor based on one parameter: the instructions
*
* @param instructions The instructions
* @throws InstructionsRunningException Thrown when the passed instructions are null.
*/
public InstructionsRunner(Instructions instructions) throws InstructionsRunningException {
//Objects.requireNonNull(instructions); I need to throw a customized exception and also log the issue.
if (instructions != null) {
this.instructions = instructions;
} else {
InstructionsRunningException e = new InstructionsRunningException("instructions should not be null.");
logger.error(Marker.ANY_MARKER, e.getMessage(), e);
throw e;
}
}
/**
* @param instructions the Instructions
* @param positioning the positioning
* @param prompts the prompts
* @throws InstructionsRunningException throw when one of the parameters is null.
*/
public InstructionsRunner(Instructions instructions, Positioning positioning, Prompt[] prompts) throws InstructionsRunningException {
//I did not use Objects.requireNull because I needed to customize the type of exception and the message I am throwing back.
if (instructions != null && positioning != null && prompts != null) {
this.instructions = instructions;
this.positioning = positioning;
this.prompts = prompts;
} else {
String msg = null;
if (instructions == null) {
msg = "instructions should not be null.";
}
if (positioning == null) {
if (msg == null) msg = "positioning should not be null";
else msg = msg + " Positioning should not be null";
}
if (prompts == null)
if (msg == null) msg = "positioning should not be null";
else msg = msg + " Positioning should not be null";
InstructionsRunningException e = new InstructionsRunningException(msg);
logger.error(Marker.ANY_MARKER, e.getMessage(), e);
throw e;
}
}
/**
* Runs the prompts on a mower located by its initial positioning.
*
* @param positioning the first input argument
* @param prompts the second input argument
* @throws InstructionsRunningException this is a runtime exception in case the lawn is not well defined in the instructions.
*/
@Override
public void accept(Positioning positioning, Prompt[] prompts) throws InstructionsRunningException {
Positioning initialPositioning = positioning;
LinkedList<Positioning> stackOfPositioning = new LinkedList<>();
instructions.initMowerTracks(initialPositioning, stackOfPositioning);
stackOfPositioning.addFirst(initialPositioning);
Positioning previousPositioning = positioning;
Positioning newPositioning;
Coordinate upperRightCorner = instructions.getLawn().getUpperRightCorner();
for (Prompt prompt : prompts) {
try {
newPositioning = previousPositioning.move(prompt, upperRightCorner);
stackOfPositioning.addLast(newPositioning);
previousPositioning = newPositioning;
} catch (IllegalPositioningException e) {
logger.info(e.getMessage());
throw new InstructionsRunningException(e.getMessage());
}
}
this.stackOfPositioning = stackOfPositioning;
}
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
@Override
public LinkedList<Positioning> call() {
//logger.info(String.format("Mower at %s starts mowing...", positioning));
accept(positioning, prompts);
// logger.info("Task completed, returning:" + String.format("(x=%d,y=%d)", positioning.getCoordinate().getX(), positioning.getCoordinate().getY()));
return stackOfPositioning;
}
}
<file_sep>package com.omcis.model.trackers;
import com.omcis.model.exceptions.IllegalPositioningException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import java.util.Objects;
/**
* This is a tracked object representation as it is described by the GPS (Global positioning System)
* It is a combination of the Coordinate and the Cardinal point toward which a tracked object is oriented (facing).
*/
public final class Positioning {
/**
* logger for the Positioning class
*/
final static Logger logger = LoggerFactory.getLogger(Positioning.class);
/**
* The coordinate of the tracked object.
*/
private final Coordinate coordinate;
/**
* The cardinal point which the tracked object is facing.
*/
private final CardinalDirection facing;
/**
* Constructs a positioning spot (tracked object) based upon the coordinate of the spot and its orientation.
*
* @param coordinate The {@code coordinate} of the tracked object.
* @param facing The cardinal point which the tracked object is facing.
*/
public Positioning(Coordinate coordinate, CardinalDirection facing) {
this.coordinate = (coordinate != null) ? coordinate : Coordinate.of(0, 0);
this.facing = facing;
}
/**
* Constructs a positioning spot (tracked object) located at the origin and facing North.
*
* @throws IllegalPositioningException Thrown when the lock is kept lockrd for more than 5 seconds.
*/
public Positioning() throws IllegalPositioningException {
this.coordinate = Coordinate.of(0, 0);
this.facing = CardinalDirection.N;
getCoordinate().acquireLock();
}
/**
* Constructs a positioning spot (tracked object) based upon:
* - the distance from the left side {@code x} and the distance from the bottom side {@code y} of a rectangular area identified by its origin (0,0);
* - and the orientation N,E,W,S.
*
* @param x the distance from the left side of a rectangular area identified by its origin (0,0);
* @param y the distance from the bottom side of a rectangular area identified by its origin (0,0);
* @param facing The cardinal point which the tracked object is facing.
*/
public Positioning(int x, int y, CardinalDirection facing) {
Coordinate tmpCoordinate = Coordinate.of(x, y);
this.facing = facing;
try {
tmpCoordinate.acquireLock();
} catch (IllegalPositioningException e) {
logger.info(e.getMessage());
//when the move is not possible, then the mower stays still
tmpCoordinate = Coordinate.of(0, 0);
} finally {
this.coordinate = tmpCoordinate;
}
}
public Coordinate getCoordinate() {
return coordinate;
}
public CardinalDirection getFacing() {
return facing;
}
/**
* String representation of this tracked object.
* Example: 1 5 N
*
* @return The String representation of this tracked object: "X Y (N,E,W,S)"
*/
@Override
public String toString() {
return String.format("%d %d %s", getCoordinate().getX(), getCoordinate().getY(), getFacing());
}
/**
* Returns a hashcode calculated based on the coordinate x , y and the cardinal point.
*
* @return The hashcode calculated based on the coordinate x , y and the cardinal point.
*/
@Override
public int hashCode() {
return Objects.hash(this.getCoordinate().getX(), this.getCoordinate().getY(), this.getFacing());
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object obj) {
return obj instanceof Positioning
&& Objects.equals(getCoordinate(), ((Positioning) obj).getCoordinate())
&& Objects.equals(getFacing(), ((Positioning) obj).getFacing());
}
/**
* Returns the new positioning resulting from a rotation clockwise of the tracked object.
*
* @return The new positioning resulting from a rotation clockwise of the tracked object.
*/
public Positioning swingRight() {
return new Positioning(getCoordinate(), getFacing().swingRight());
}
/**
* Returns the new positioning resulting from a rotation counterclockwise.
*
* @return The new positioning resulting from a rotation counterclockwise
*/
public Positioning swingLeft() {
return new Positioning(getCoordinate(), getFacing().swingLeft());
}
/**
* Returns the new Positioning resulting in a 1 step move relative to the current spot and direction (N,E,W,S).
*
* @param upperRightCorner the upper right corner of the rectangular area to not cross.
* @return the relative new positioning after a 1 step move.
* @throws IllegalPositioningException thrown when upperRightCorner.getX or getY is negative.
*/
public Positioning moveForward(Coordinate upperRightCorner) {
Coordinate newCoordinate;
try {
switch (getFacing()) {
case N:
newCoordinate = getCoordinate().IncreaseYIfPossible(1, upperRightCorner.getY());
break;
case E:
newCoordinate = getCoordinate().IncreaseXIfPossible(1, upperRightCorner.getX());
break;
case W:
newCoordinate = getCoordinate().IncreaseXIfPossible(-1, null);
break;
case S:
newCoordinate = getCoordinate().IncreaseYIfPossible(-1, null);
break;
default:
newCoordinate = Coordinate.of(null, null);
}
//Releasing the lock only when moving out of the current spot.
if (!getCoordinate().equals(newCoordinate)) {
getCoordinate().releaseLock();
newCoordinate.acquireLock();
}
//
return new Positioning(newCoordinate, getFacing());
} catch (IllegalPositioningException e) {
logger.info(e.getMessage());
//when the move is not possible, then the mower stays still
return this;
}
}
/**
* <p>
* Returns the new Positioning resulting in a swingLeft if the prompt is G,
* a swingRight if the prompt is R
* a 1 step move forward relative to the current spot and direction (N,E,W,S)if the prompt is A.
* </p>
*
* @param prompt A,G or D.
* @param upperRightCorner he upper right corner of the rectangular area to not cross.
* @return the relative new positioning after a 1 step move.
* @throws IllegalPositioningException thrown when upperRightCorner.getX or getY is negative.
*/
public Positioning move(Prompt prompt, Coordinate upperRightCorner) throws IllegalPositioningException {
Positioning newPositioning = this;
switch (prompt) {
case G:
newPositioning = this.swingLeft();
break;
case D:
newPositioning = this.swingRight();
break;
case A:
newPositioning = this.moveForward(upperRightCorner);
break;
}
return newPositioning;
}
/**
* Checks whether the current spot (positioning) is inside the area defined by its right upper corner {@code upperRightCorner}.
*
* @param upperRightCorner the upper right corner of the rectangular area against which the positioning is checked.
* @return true when the positioning is inside the area delimited by upperRighCorner.
* @throws IllegalPositioningException in case the positioning is out of the rectangular area defined by its right upper corner.
*/
public boolean checkPositioning(Coordinate upperRightCorner) throws IllegalPositioningException {
if (this.coordinate.isBeyond(upperRightCorner)) {
IllegalPositioningException e = new IllegalPositioningException(toString() + " is beyond the defined area:" + upperRightCorner.toString());
logger.error(Marker.ANY_MARKER, e.getMessage(), e);
throw e;
}
return true;
}
}
<file_sep>package com.omcis.model.planners;
import com.omcis.model.trackers.Prompt;
import org.hamcrest.CoreMatchers;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.hamcrest.MatcherAssert.assertThat;
@RunWith(Theories.class)
public class TestTheory {
/**
* logger for the TestTheory class
*/
final static Logger logger = LoggerFactory.getLogger(TestTheory.class);
@DataPoints
public static String[] stringsToSplit = {"GAGAGAGAA", "AADAADADDA"};
@DataPoints
public static Integer[] integers = {new Integer(-1), new Integer(0), null, 1, 5, -1};
static int classCounter = 0;
public static Consumer<String> myConsumer = new Consumer<String>() {
int counter = 0;
@Override
public void accept(String s) {
counter++;
classCounter++;
assertThat(counter == classCounter).isTrue();
logger.info(String.format("counter=%d Vs classsCounter=%d", counter, classCounter));
}
};
@Theory
public void testSplit(String s) {
System.out.printf("String str: %s, str.length():%d, arrayStr[]: str.split(\"\"):%s, arrayStr.length:%d \n",
s, s.length(), Arrays.toString(s.split("")), s.split("").length);
assertThat("Split with regex=\"\" just splits the string into strings of one character.", s.split("").length, CoreMatchers.equalTo(s.length()));
for (String str : s.split("")
) {
assertThat("After splitting with regex:\"\", checking whether elements are A or D or G", str,
CoreMatchers.anyOf(CoreMatchers.equalTo("A"),
CoreMatchers.equalTo("G"),
CoreMatchers.equalTo("D")));
}
}
@Theory
public void testListToArrayConversion(String s) {
List<Prompt> listOfPromts = Arrays.stream(s.split(""))
.map(Prompt::valueOf)
.collect(Collectors.toList());
assertThat("going from String str -> String[] -> List<Prompt> -> Prompt[] ", listOfPromts.toArray(new Prompt[0]), CoreMatchers.instanceOf(Prompt[].class));
}
@org.junit.Test
public void parseInt() {
assertThatThrownBy(() -> Integer.valueOf("null")).isInstanceOf(NumberFormatException.class);
assertThatThrownBy(() -> Integer.valueOf("")).isInstanceOf(NumberFormatException.class);
assertThat(Integer.valueOf("-1")).isEqualTo(-1);
}
@Theory
public void foreachCounterIncrement(String sequence) {
//checking whether counter gets correctly incremented
Stream<String> stream = Arrays.stream(sequence.split(""));
stream.forEach(myConsumer);
}
@Theory
public void useOfUnsignedInt(Integer intg) {
logger.info(String.format("Integer In:%s , ParseUnsigned:%s", intg, Integer.parseUnsignedInt("" + intg)));
}
}
<file_sep>package com.omcis.model.exceptions;
/**
* Thrown to indicate that a positioning detail is out of range.
* This class will help classifying the application errors by code.
*/
public class IllegalPositioningException extends Exception{
/**
* Constructs a PositioningException with the detail message {@code msg}.
* @param msg the detail message
*/
public IllegalPositioningException(String msg) {
super(msg);
}
}
<file_sep>================ AWESOME LAWN MOWER ======================
To mow the lawn, you will need to call MowerPlanner by passing in one argument or more:
- the relative path to the instructions file.
- -p to enable the mowers to mow in parallel instead of mowing sequentially.
An example of argument is "-p -file=src//main//resources//instructions.txt".

Honda Mean Mower : le retour de la super tondeuse
Lire la suite: http://www.largus.fr/actualite-automobile/honda-mean-mower-le-retour-de-la-super-tondeuse-9057401-11029407-photos.html#ixzz59wgfhVXm
Follow us: @Largus_auto on Twitter | Largus.auto on Facebook
<file_sep>package com.omcis.model.planners;
import com.omcis.model.exceptions.InstructionsParsingException;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InstructionsParserTest {
/**
* logger for the InstructionsParser class
*/
final static Logger logger = LoggerFactory.getLogger(InstructionsParserTest.class);
@Test
public void builderIsRowCompliant() throws InstructionsParsingException {
Pattern firstRowMatcher = InstructionsParser.firstRowMatcher;
Pattern evenRowsMatcher = InstructionsParser.evenRowsMatcher;
Pattern oddRowsMatcher = InstructionsParser.oddRowsMatcher;
String firstRow = "5 5";
String evenRow = "1 2 N";
String evenRow2 = "3 3 E";
String oddRow = "GAGAGAGAA";
String oddRow2 = "AADAADADDA";
assertTrue(InstructionsParser.matchIfRowCompliant(firstRowMatcher, firstRow).matches());
assertTrue(InstructionsParser.matchIfRowCompliant(evenRowsMatcher, evenRow).matches());
assertTrue(InstructionsParser.matchIfRowCompliant(evenRowsMatcher, evenRow2).matches());
assertTrue(InstructionsParser.matchIfRowCompliant(oddRowsMatcher, oddRow).matches());
assertTrue(InstructionsParser.matchIfRowCompliant(oddRowsMatcher, oddRow2).matches());
String firstRowBis = "";
String evenRowBis = "1 2 3";
String evenRow2Bis = "3 3 ";
String oddRowBis = "GAEAGAGAA";
String oddRow2Bis = "";
assertThrows(InstructionsParsingException.class, () -> {
InstructionsParser.matchIfRowCompliant(firstRowMatcher, firstRowBis);
});
assertThrows(InstructionsParsingException.class, () -> {
InstructionsParser.matchIfRowCompliant(evenRowsMatcher, evenRowBis);
});
assertThrows(InstructionsParsingException.class, () -> {
InstructionsParser.matchIfRowCompliant(evenRowsMatcher, evenRow2Bis);
});
assertThrows(InstructionsParsingException.class, () -> {
InstructionsParser.matchIfRowCompliant(oddRowsMatcher, oddRowBis);
});
assertThrows(InstructionsParsingException.class, () -> {
InstructionsParser.matchIfRowCompliant(oddRowsMatcher, oddRow2Bis);
});
}
}
<file_sep>package com.omcis.model.planners;
import com.omcis.model.AwesomeLawn;
import com.omcis.model.exceptions.InstructionsRunningException;
import com.omcis.model.trackers.Coordinate;
import com.omcis.model.trackers.Positioning;
import com.omcis.model.trackers.Prompt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* This class is intended to set up the instructions for the mowers on the lawn, and to run the instructions.
* <p>
* PLease follow these steps to cset Up the instructions:
* <p>
* 0- Retrieve the builder instance to assist in the set up; Instructions.Builder builder= Instructions.builder();
* 1- set the lawn to be mowed
* 2- set the prompts
* 3- parse the all the instructions gathered;
* instructions instruction= builder.setLawn(lawn) //1
* .setPromtsForMower(int x, int y, CardinalDirection facing, Prompt... prompts) as many mowers are planned to mowe the lawn. //2
* .build(); //3
* </p>
* <p>
* There are 2 convenient functions that comprehend the three(3) last steps:
* 1- Instructions instructions=Instructions.builder().buildFromInstructionsFilePath(Path)
* 2- Instructions instructions=Instructions.builder().buildFromInstructionsStream(Stream <String>)
* </p>
*/
public class Instructions {
/**
* logger for the Instructions.Builder class
*/
final static Logger logger = LoggerFactory.getLogger(Instructions.class);
/**
* A key-value map of the mowers and their respective prompts.
* This map keeps the inserting order.
* Static so I do not need to duplicated it in the builder.
*/
private final Map<Positioning, Prompt[]> promptsForMowers = new LinkedHashMap<>();
/**
* The lawn to be mown
*/
private AwesomeLawn lawn;
/**
* A series of key - value pairs representing the initial postisioning of a mower and its postionings tracks at the end of the mowing process.
* Static so it can be kept even after the instructions are cleaned. (Instructions.getInstance()==null).
*/
private Map<Positioning, LinkedList<Positioning>> mowersStartEndPositions = new LinkedHashMap<>();
/**
* Basic Constructor.
*/
public Instructions() {
}
/**
* Constructor based upon a {@code lawn} instance.
*
* @param lawn The {@code lawn}
*/
public Instructions(AwesomeLawn lawn) {
this.lawn = lawn;
}
/**
* get lawn
*
* @return The lawn
*/
public AwesomeLawn getLawn() {
return lawn;
}
public void setLawn(AwesomeLawn lawn) {
this.lawn = lawn;
}
/**
* Sets up a mower initial position and the prompts to plan for this mower.
* Using this methods helps encapsulate the map promptsForMowers
*
* @param mower the mower
* @param prompts a series of prompts G(swingLeft),D(swingRight),A(moveForward)
*/
public void setPromtsForMower(Positioning mower, Prompt... prompts) {
promptsForMowers.put(mower, prompts);
}
/**
* Adds to the map of mowers/tracks the mower and the list designed to contain the successive tracks of the mower.
* Doing so, increases the encapsulation of the member mowersStartEndPositions.
*
* @param mower the mower
* @param stackOfPositioning succesive positionings of the mower.
*/
public void initMowerTracks(Positioning mower,
LinkedList<Positioning> stackOfPositioning) {
mowersStartEndPositions.put(mower, stackOfPositioning);
}
/**
* Logs the result of the run.
*/
public void logRunResults() {
mowersStartEndPositions.forEach((Positioning mower, LinkedList<Positioning> tracks) -> {
logger.info(tracks.getLast().toString());
});
}
/**
* Clear the set of prompts for the mowers after run
*/
private void clearInstructions() {
promptsForMowers.clear();
}
/**
* Runs the instructions. Use only in a the context where the mowers run sequentially (one after the other).
*
* @return true if the instructions run successfully
* @throws InstructionsRunningException thrown when a running exception is encountered.
*/
public boolean run() {
mowersStartEndPositions.clear();
promptsForMowers.forEach(new InstructionsRunner(this));
logRunResults();
clearInstructions();
Coordinate.releaseAllLocks();
Coordinate.clearCoordinateCach();
return true;
}
/**
* Runs the instructions making the mowers move on the lawn and record their tracks.
* All the mowers mow simultaneously.
*
* @throws InstructionsRunningException thrown when a running exception is encountered.
*/
public void runParallel() throws InstructionsRunningException {
ExecutorService service = Executors.newCachedThreadPool();
Collection<InstructionsRunner> instructionRunners = new ArrayList<>();
List<Future<LinkedList<Positioning>>> futureResults;
//Clearing the previous results
mowersStartEndPositions.clear();
//Creating a collection of Callable to pass into the thread ExecutorService
promptsForMowers.forEach((positioning, prompts) -> {
instructionRunners.add(new InstructionsRunner(this, positioning, prompts));
});
//Running the callables with the Thread Executor pool
try {
futureResults = service.invokeAll(instructionRunners);
futureResults.forEach(linkedListFuture -> {
try {
logger.info(linkedListFuture.get().toString());
} catch (InterruptedException | ExecutionException e) {
logger.error(Marker.ANY_MARKER, e.getMessage(), e);
throw new InstructionsRunningException(e.getMessage());
}
});
clearInstructions();
} catch (InterruptedException e) {
InstructionsRunningException ie = new InstructionsRunningException(e.getMessage());
logger.error(Marker.ANY_MARKER, e.getMessage(), e);
throw ie;
} finally {
Coordinate.releaseAllLocks();
Coordinate.clearCoordinateCach();
service.shutdown();
}
}
}<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.omcis</groupId>
<artifactId>lawnmower</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AwesomeLawnMower</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<compiler.plugin.version>3.7.0</compiler.plugin.version>
<surefire.plugin.version>2.19.1</surefire.plugin.version>
<junit.version>4.12</junit.version>
<junit.jupiter.version>5.0.3</junit.jupiter.version>
<junit.platform.version>1.0.3</junit.platform.version>
<mockito.version>2.15.0</mockito.version>
<assertj.core.version>3.9.0</assertj.core.version>
<slf4j.version>1.8.0-beta1</slf4j.version>
<localizer.plugin.version>1.1</localizer.plugin.version>
<commons-cli.version>1.4</commons-cli.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler.plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.junit.platform/junit-platform-surefire-provider -->
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<!--Testing -->
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<!--Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<!--using java.util.logging since it got improved -->
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--localizing-->
<dependency>
<groupId>org.jvnet.localizer</groupId>
<artifactId>maven-localizer-plugin</artifactId>
<version>${localizer.plugin.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-cli/commons-cli -->
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>${commons-cli.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!--Testing -->
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</dependency>
<!--Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<!--using java.util.logging since it got improved -->
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
</dependency>
<!--localizing-->
<dependency>
<groupId>org.jvnet.localizer</groupId>
<artifactId>maven-localizer-plugin</artifactId>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>${commons-cli.version}</version>
</dependency>
</dependencies>
</project>
|
1e9d0594ed18263296e462d5ca60d91b8fa92e6c
|
[
"Markdown",
"Java",
"Maven POM",
"HTML"
] | 9
|
HTML
|
omsix/LawnMower_MowingSimultaneously
|
7c80ba354c454f9573a34933996fadd7d57e3d16
|
79c783d363c290041eb675571b1992ccaca2ba4d
|
refs/heads/master
|
<file_sep>
import cookielib
import urllib2
import urllib
import re
import time
url = "http://lab1.xseclab.com/vcode2_a6e6bac0b47c8187b09deb20babc0e85/index.php"
urlLogin = "http://lab1.xseclab.com/vcode2_a6e6bac0b47c8187b09deb20babc0e85/login.php"
is_out_header_info = True
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
response = opener.open(url)
info = response.read()
vcode = 'aaaa'
print 'start------'
for one in range(1,10):
for two in range(10):
for three in range(10):
for four in range(10):
pwd = one,two,three,four
newPwd = <PASSWORD>' % pwd
values = {'username' : 'admin', 'pwd' : <PASSWORD>, 'vcode' : vcode, 'submit' :'submit'}
print values
data = urllib.urlencode(values)
request = urllib2.Request(urlLogin, data)
urlinfo = opener.open(request)
page = urlinfo.read()
if page != "pwd error":
break;
print page<file_sep>#encoding=utf-8
# file : dichotomy.py 二分法
# 通过二分法,来猜测一个范围在0-999的数
def testDichotomy(num):
import math
low, high = 0, 999
guessNum = math.ceil((high + low) / 2)
guessTotal = 1
while guessNum != num:
print "猜测数字:", guessNum
# guessNum重新赋值
if guessNum > num:
high= guessNum
else:
low = guessNum
guessNum = math.ceil((high + low) / 2)
guessTotal += 1
print '猜测数量:', guessTotal
if __name__ == "__main__":
testDichotomy(498)<file_sep>#encoding=utf-8
# 递推算法---逆推
# 该存多少钱
# 父亲为小龙4年大学生活一次性储蓄一笔钱,使用整存零取的方式,控制小龙每月月底取1000,一年整存零取的年息为1.71%,计算存多少钱
def oppositeRecurrence():
year = 4 #存多久
months = 12 # 一年多少个月
moneys = [0] * (year * months + 1)
moneys[year*months] = 1000
for i in range(year*months-1, 0, -1):
moneys[i] = (moneys[i+1] + 1000) / (1 + 0.0171/12)
return moneys
if __name__ == "__main__":
moneys = oppositeRecurrence()
print moneys
<file_sep>#encoding=utf-8
# 递推算法---顺推
# 举例斐波那契数列
def obeyRecurrent(n):
a, b = 0, 1
i = 0
while i < n:
print b
a, b = b, a+b
i = i +1
return b
if __name__ == "__main__":
print obeyRecurrent(10)<file_sep>#encoding=utf-8
# 下载图片
def uploadImage(url):
import urllib
u = urllib.urlopen(url)
data = u.read()
#动态设置文件名
splitPath = url.split('=')
#保存为jpg
fName = splitPath.pop() + ".jpg"
#写入文件
f = open(fName, 'wb')
f.write(data)
f.close()
#返回文件名
return fName
# 对验证码进行过滤,去噪
def filterImage(imageName):
import Image
im = Image.open(imageName)
#im = im.convert('RGB')
#im = im.filter(ImageFilter.MedianFilter())
#enhancer = ImageEnhance.Contrast(im)
#im = enhancer.enhance(2)
im = im.convert('1')
#im.show()
return im
#取模写入文件
def findMode(l, startx = 0, w=80, h=20):
ytopmin = 0
xleftmin = 0
ybottommax = 0
xrightmax = 0
#获取xmin 和xmax
arrFlag = [0] * w
flag = False;
xminflag = True
for x in range(startx, w):
for y in range(h):
if l[y][x] == str(0):
arrFlag[x] = 0
if xminflag:
xleftmin = x
xminflag = False
break
else:
arrFlag[x] = 1
if arrFlag[x] == 1 and xleftmin:
xrightmax = x-1
flag = True
if flag :
break
#print xleftmin, xrightmax
#获取ymin和ymax
arrFlag = [0] * h
yminflag = True
flag = False
for y in range(h):
for x in xrange(xleftmin, xrightmax+1):
#print l[y][x]
#print x,y
if l[y][x] == str(0):
#print y
arrFlag[y] = 0
if yminflag:
ytopmin = y
yminflag = False
break
else:
arrFlag[y] = 1
if arrFlag[y] == 1 and ytopmin:
ybottommax = y-1
flag = True
if flag :
break
if not ybottommax :
ybottommax = y
return [xleftmin, xrightmax, ytopmin, ybottommax]
def writeMode():
if __name__ == "__main__":
import sys
url = sys.argv[1]
print uploadImage(url)<file_sep>#!/usr/bin/env python
#encoding=utf-8
import Image,ImageEnhance,ImageFilter
import sys
import dealImage
import moResult
image_name = dealImage.uploadImage("http://vc.sinaapp.com/img.php?key=k-14301269702186")
im = dealImage.filterImage(image_name)
# 获取图片的宽和高
w, h = im.size
# 打开摸文件
f = file("data.txt","a")
fp = file('mo.py', 'a')
# 创建一个二维数组
l = [([0] * w) for i in range(h)]
# 写入二维数组
for x in xrange(0, h):
for y in xrange(0, w):
if im.getpixel((y,x)) == 255 :
l[x][y] = str(1)
else:
l[x][y] = str(0)
# 打印二维码过滤后的内容
for x in range(h):
print "".join(l[x])
xleftmin = 0
xrightmax = 0
ytopmin = 0
ybottommax = 0
for i in range(4):
if xrightmax < w:
xleftmin, xrightmax, ytopmin, ybottommax = dealImage.findMode(l, xrightmax+1, w, h)
results = []
getValueFlag = False
for y in xrange(ytopmin, ybottommax+1):
for x in xrange(xleftmin, xrightmax+1):
results.append(l[y][x])
resultStr = "".join(results)
moResults = moResult.result
for key in moResults:
if moResults[key] == resultStr:
print key
getValueFlag = True
break
#读模
if not getValueFlag:
print 'du mo '
continue
i = i + 1
f.close()
fp.close()<file_sep>
import cookielib
import urllib2
import urllib
import re
import time
url = "http://lab1.xseclab.com/xss2_0d557e6d2a4ac08b749b61473a075be1/index.php"
is_out_header_info = True
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
response = opener.open(url)
pageInfo = response.read()
pattern = re.compile('(\d*\*\d*\+\d*\*\(\d*\+\d*\))')
matchInfo = pattern.search(pageInfo)
#print matchInfo.group(1)
num = eval(matchInfo.group(1))
#time.sleep(2)
values = {'v' : num}
data = urllib.urlencode(values)
request = urllib2.Request(url, data)
url = opener.open(request)
page = url.read()
print page<file_sep>#!/usr/bin/env python
#encoding=utf-8
import Image,ImageEnhance,ImageFilter
import sys
import urllib
#image_name = "1.jpg"
image_name = "m.jpg"
conn = urllib.request.urlopen(url)
f = open("m.jpg",'wb')
f.write(conn.read())
im = Image.open(image_name)
#im = im.convert('RGB')
#im = im.filter(ImageFilter.MedianFilter())
#enhancer = ImageEnhance.Contrast(im)
#im = enhancer.enhance(2)
im = im.convert('1')
#im.show()
#all by pixel
s = 12 #start postion of first number
w = 10 #width of each number
h = 15 #end postion from top
t = 2 #start postion of top
w, h = im.size
f = file("data.txt","a")
#print w,h
l = [([0] * w) for i in range(h)]
#for i in range(h):
#print l[i]
for x in xrange(0, h):
for y in xrange(0, w):
if im.getpixel((y,x)) == 255 :
l[x][y] = str(1)
else:
l[x][y] = str(0)
f.close
for x in range(h):
print "".join(l[x])
#获取ymin
#for y in range(h):
#for x in range(w):
#if l[y][x] == str(0):
#flag = True
#print x,y
#ymin = y
#break
#else:
#if
#if flag :
#break
#取模写入文件
def findMode(startx = 0):
print startx
ytopmin = 0
xleftmin = 0
ybottommax = 0
xrightmax = 0
#获取xmin 和xmax
arrFlag = [0] * w
flag = False;
xminflag = True
for x in range(startx, w):
for y in range(h):
if l[y][x] == str(0):
arrFlag[x] = 0
if xminflag:
xleftmin = x
xminflag = False
break
else:
arrFlag[x] = 1
if arrFlag[x] == 1 and xleftmin:
xrightmax = x-1
flag = True
if flag :
break
#print xleftmin, xrightmax
#获取ymin和ymax
arrFlag = [0] * h
yminflag = True
flag = False
for y in range(h):
for x in xrange(xleftmin, xrightmax+1):
#print l[y][x]
#print x,y
if l[y][x] == str(0):
#print y
arrFlag[y] = 0
if yminflag:
ytopmin = y
yminflag = False
break
else:
arrFlag[y] = 1
if arrFlag[y] == 1 and ytopmin:
ybottommax = y-1
flag = True
if flag :
break
if not ybottommax :
ybottommax = y
print xleftmin, xrightmax
print ytopmin, ybottommax
#print l[9][8]
#print l[9][6]
n = 0
f.write("l=[")
for y in xrange(ytopmin, ybottommax+1):
for x in xrange(xleftmin, xrightmax+1):
#print x,y
#if (n%(xrightmax-xleftmin+1)==0):
#f.write("\n")
f.write(str(l[y][x])+",")
#n+=1
f.write("]\n")
return [xleftmin, xrightmax, ytopmin, ybottommax]
xleftmin = 0
xrightmax = 0
ytopmin = 0
ybottommax = 0
for x in range(4):
if xrightmax < w:
xleftmin, xrightmax, ytopmin, ybottommax = findMode(xrightmax+1)
x = x +1
<file_sep>#!/usr/bin/env python
#encoding=utf-8
import Image,ImageEnhance,ImageFilter
import sys
image_name = "1.jpg"
im = Image.open(image_name)
#im = im.convert('RGB')
#im = im.filter(ImageFilter.MedianFilter())
#enhancer = ImageEnhance.Contrast(im)
#im = enhancer.enhance(2)
im = im.convert('1')
im.show()
#exit
#all by pixel
s = 0 #start postion of first number
w = 18 #width of each number
h = 20 #end postion from top
t = 0 #start postion of top
im_new = []
#split four numbers in the picture
for i in range(4):
im1 = im.crop((5+w*i+i*2,t,s+w*(i+1)+i*2,h))
#im1.show()
im_new.append(im1)
f = file("data.txt","a")
for k in range(4):
l = []
#im_new[k].show()
for i in range(18):
for j in range(10):
if (im_new[k].getpixel((j,i)) == 255):
l.append(0)
else:
l.append(1)
f.write("l=[")
n = 0
for i in l:
if (n%10==0):
f.write("\n")
f.write(str(i)+",")
n+=1
f.write("]\n")<file_sep>#encoding=utf-8
# 保存页面
def uploadFile(url):
import urllib
u = urllib.urlopen(url)
data = u.read()
#动态设置文件名
splitPath = url.split('=')
#保存为jpg
fName = splitPath.pop() + ".html"
#写入文件
f = open(fName, 'wb')
f.write(data)
f.close()
#返回文件名
return fName
if __name__ == "__main__":
url = "http://lab1.xseclab.com/sqli7_b95cf5af3a5fbeca02564bffc63e92e5/index.php?username=' union all select database()"
import urllib
u = urllib.urlopen(url)
data = u.read()
print data<file_sep>#encoding=utf-8
# 创建一个list
sampleList = ['a' ,'1', ('a', 'b')]
questions = ['q1', 'q2', 'q3', 'q4']
answers = ['a1', 'a2', 'a3', 'a4']
# list 操作
for x in sampleList:
print x, len(x)
print range(0, 20, 2)
try:
for i,x in enumerate(questions):
print i, x
except Exception, e:
print e
for i, x in enumerate(answers):
print i, x
for i, x in zip(questions, answers):
print i, x
for i in reversed(range(1, 10, 2)):
print i<file_sep>#!/usr/bin/env python
#encoding=utf-8
import Image,ImageEnhance,ImageFilter
import sys
import dealImage
image_name = dealImage.uploadImage("http://vc.sinaapp.com/img.php?key=k-14301269702186")
im = dealImage.filterImage(image_name)
# 获取图片的宽和高
w, h = im.size
# 打开摸文件
f = file("data.txt","a")
fp = file('mo.py', 'a')
# 创建一个二维数组
l = [([0] * w) for i in range(h)]
# 写入二维数组
for x in xrange(0, h):
for y in xrange(0, w):
if im.getpixel((y,x)) == 255 :
l[x][y] = str(1)
else:
l[x][y] = str(0)
# 打印二维码过滤后的内容
for x in range(h):
print "".join(l[x])
xleftmin = 0
xrightmax = 0
ytopmin = 0
ybottommax = 0
for x in range(4):
if xrightmax < w:
xleftmin, xrightmax, ytopmin, ybottommax = dealImage.findMode(l, xrightmax+1, w, h)
f.write("l=[")
n = 0
for y in xrange(ytopmin, ybottommax+1):
for x in xrange(xleftmin, xrightmax+1):
# 写模文件
if (n%(xrightmax-xleftmin+1)==0):
f.write("\n")
f.write(l[y][x]+",")
n+=1
# 写模结果
fp.write(l[y][x]+"")
f.write("]\n")
fp.write("\n")
x = x +1
f.close()
fp.close()<file_sep>import dealFile
dealFile.uploadFile('http://lab1.xseclab.com/sqli7_b95cf5af3a5fbeca02564bffc63e92e5/index.php?username=%27or%201=1%20or%20username=%27')
|
6e9d4a9b3e5397c976a9273341b6e85d937c9b78
|
[
"Python"
] | 13
|
Python
|
xezw211/hsky_python
|
0b3c22dc8fd7aa11f99a23233ea5d5bbb30efb5a
|
b9af57d07cfa2c7a130219e64771c548232d0d9e
|
refs/heads/master
|
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
[RequireComponent (typeof(CharacterController))] //whatever uses this class needs a character controller component
public class FPSC : MonoBehaviour
{
//playerpref flags
public int crouchpowerup = 0;
public int doublejpowerup = 0;
public int triplejpowerup = 0;
public int bunnyhoppowerup = 0;
public int akpowerup = 0;
public int alienpowerup =0;
public int shotgunpowerup =0;
//player stats
public int curglock;
public int totalglock;
public int curak;
public int totalak;
public int curshells;
public int totalshells;
public int curalien;
public int totalalien;
public float health;
public float armor;
public float dmg;
//forward/backward movement
private float directionZ;
//strafing << did i spell that wrong?
private float directionX;
// since rotation switches x and y axes, variables are named accoridingly
private float rotationVertical;
private float rotationHorizontal;
public float verticalViewLimit; //without this, you'll have the ability to completely flip your char. and look upside down
//speed
private float speed; //rate of movement
public float walkSpeed;
public float runSpeed;
//public float speedLimit;
//gravity/jump
public float personalGravity;
private float vertVelocity; //vertical speed and direction
public float jumpSpeed;
public float bHopSpeed;
public bool doubleJump;
private bool doubleJumped;
public bool tripleJump;
private bool tripleJumped;
public bool bunnyHopping;
//crouch ability
public bool crouch;
private bool crouched;
//application of all mvmt
private Vector3 velManager;
//mouse stuff
public float mouseSensitvity;
private CharacterController control;
public bool cursor;
// CHRIS CODE HERE================================
int weap;
float fireRate = .07f, fireCooldown;
//HUD STUFF
public Text ammotext;
public glockScript glockScript;
public shotgunScript shotgunScript;
public akScript akScript;
public alienScript alienScript;
// ===============================================
//new
public GameObject glock, shotgun, ak, alien;
// Use this for initialization
void Start ()
{
control = GetComponent<CharacterController> ();
doubleJumped = false;
tripleJumped = false;
crouched = false;
bunnyHopping = false;
crouchpowerup = PlayerPrefs.GetInt("PlayerCrouch");
doublejpowerup = PlayerPrefs.GetInt("PlayerDoubleJump");
triplejpowerup = PlayerPrefs.GetInt("PlayerTripleJump");
bunnyhoppowerup = PlayerPrefs.GetInt("PlayerBunnyHop");
alienpowerup = PlayerPrefs.GetInt("alienpowerup");
akpowerup = PlayerPrefs.GetInt("akpowerup");
shotgunpowerup = PlayerPrefs.GetInt("shotgunpowerup");
curglock = PlayerPrefs.GetInt("curglock");
curak = PlayerPrefs.GetInt("curak");
curshells = PlayerPrefs.GetInt("curshells");
curalien = PlayerPrefs.GetInt("curalien");
health= PlayerPrefs.GetInt("health");
if(health <=0){
health =100;
}
armor= PlayerPrefs.GetInt("armor");
}
// Update is called once per frame
void Update ()
{
curglock = PlayerPrefs.GetInt("curglock");
totalglock = glockScript.totalBullets;
curak = PlayerPrefs.GetInt("curak");
totalak = akScript.totalBullets;
curshells = PlayerPrefs.GetInt("curshells");
totalshells = shotgunScript.totalBullets;
curalien = PlayerPrefs.GetInt("curalien");
totalalien = alienScript.totalBullets;
// HUD STUFF
weap = GetComponent<weaponMaster>().checkWeapon();
if(weap == 1)
{
ammotext.text = "" + glockScript.clipCurrent + "/" + glockScript.totalBullets;
}
else if(weap == 2)
{
ammotext.text = "" + shotgunScript.clipCurrent + "/" + shotgunScript.totalBullets;
}
else if(weap == 3)
{
ammotext.text = "" + akScript.clipCurrent + "/" + akScript.totalBullets;
}
else if (weap == 4)
{
ammotext.text = "" + alienScript.clipCurrent + "/" + alienScript.totalBullets;
}
//Check player prefs
if(PlayerPrefs.HasKey("PlayerCrouch")){
if(crouchpowerup == 1){
crouch= true;
}else{
crouch = false;
}
}
if(PlayerPrefs.HasKey("PlayerDoubleJump")){
if(doublejpowerup == 1){
doubleJump = true;
}else{
doubleJump = false;
}
}
if(PlayerPrefs.HasKey("PlayerTripleJump")){
if(triplejpowerup == 1){
tripleJump= true;
}else{
tripleJump = false;
}
}
if(PlayerPrefs.HasKey("PlayerBunnyHop")){
if(bunnyhoppowerup == 1){
bunnyHopping = true;
}else{
bunnyHopping = false;
}
}
if(PlayerPrefs.HasKey("alienpowerup")){
if(alienpowerup == 1){
GetComponent<weaponMaster>().setAlienUse();
}
}
if(PlayerPrefs.HasKey("akpowerup")){
if(akpowerup == 1){
GetComponent<weaponMaster>().setAkUse();
}
}
if(PlayerPrefs.HasKey("shotgunpowerup")){
if(shotgunpowerup ==1){
GetComponent<weaponMaster>().setShotgunUse();
}
}
//ROTATION FOR PLAYER AND MAIN CAMERA
// For Horizontal movement, treated as y axis
rotationHorizontal = Input.GetAxis ("Mouse X") * mouseSensitvity;
transform.Rotate (0, rotationHorizontal, 0);
// For vertical movement, treated as x axis
rotationVertical -= Input.GetAxis ("Mouse Y") * mouseSensitvity; //moving the minus sign changes the whole equation
rotationVertical = Mathf.Clamp (rotationVertical, -verticalViewLimit, verticalViewLimit);
Camera.main.transform.localRotation = Quaternion.Euler (rotationVertical, 0, 0);
// GRAVITY/JUMPING
vertVelocity += Physics.gravity.y * personalGravity * Time.deltaTime;
if (Input.GetButtonDown("Jump") && (control.isGrounded) && !bunnyHopping)
{
vertVelocity = jumpSpeed; //<< The action of jumping
}
if (Input.GetButton ("Jump") && (control.isGrounded) && bunnyHopping)
vertVelocity = bHopSpeed;
if (Input.GetButtonDown ("Jump") && (!control.isGrounded) && !doubleJumped && doubleJump && !bunnyHopping)
{
vertVelocity = jumpSpeed; //<< The action of double jumping
doubleJumped = true;
Debug.Log ("Double Jump");
return; //If i don't do this, it will try to do both double jump and triple jump at the same time
}
if (Input.GetButtonDown ("Jump") && (!control.isGrounded) && doubleJumped && !tripleJumped && tripleJump && !bunnyHopping)
{
vertVelocity = jumpSpeed; //<< The action of triple jumping
tripleJumped = true;
Debug.Log ("Triple Jump");
}
if (control.isGrounded)
{
doubleJumped = false;
tripleJumped = false;
}
//PLAYER MOVEMENT/VELOCITY MANAGER
velManager = new Vector3 (directionX, vertVelocity, directionZ); // this vector is applied to the player creating mvmt
velManager = transform.rotation * velManager; //how the hell am i multiplying a vector by a quat?!?!?!?!?
//variables equal whatever number the right side of this operation returns (ex. -1 or backwards if down key/S, 1 is forward if up key/w, 0 if neither)
directionZ = Input.GetAxis ("Vertical") * speed;
directionX = Input.GetAxis ("Horizontal") * speed;
//alternate version: directionZ = Input.GetAxis ("Vertical") * speed * Time.deltaTime;
//control.SimpleMove ( velManager );
//Simple move ignores changes to y, handles gravity
control.Move (velManager * Time.deltaTime); //runs over time, not over frame, DOES NOT deal with gravity however
//OTHER ABILITIES
//CROUCHING
if (Input.GetKeyDown (KeyCode.Return))
{
if (crouch)
{
crouched = !crouched;
}
}
if (crouched)
control.height = 1;
if (!crouched)
control.height = 2;
//RUNNING
if (Input.GetKey(KeyCode.RightShift) || Input.GetKey(KeyCode.LeftShift))
{
speed = runSpeed;
}
else
speed = walkSpeed;
// MOUSE CURSOR
if (cursor == false)
Cursor.visible = false;
else
Cursor.visible = true;
fireCooldown += Time.deltaTime;
weap = GetComponent<weaponMaster>().checkWeapon();
if(Input.GetButtonDown("Fire1") && weap == 1)
{
glock.GetComponent<glockScript>().Shoot();
}
else if(Input.GetButtonDown("Fire1") && weap == 2)
{
shotgun.GetComponent<shotgunScript>().Shoot();
}
else if(Input.GetButton("Fire1") && weap == 3 && fireCooldown >= fireRate)
{
ak.GetComponent<akScript>().Shoot();
fireCooldown = 0f;
}
else if (Input.GetButtonDown("Fire1") && weap == 4)
{
alien.GetComponent<alienScript>().Shoot();
}
//health
if (health <= 0 && armor <= 0)
Application.LoadLevel ("gameover");
//reload button
weap=GetComponent<weaponMaster>().checkWeapon();
if(Input.GetKeyUp(KeyCode.R) && weap ==1)
{
glock.GetComponent<glockScript>().Reload();
}
else if(Input.GetKeyUp(KeyCode.R) && weap ==2)
{
shotgun.GetComponent<shotgunScript>().Reload();
}
else if(Input.GetKeyUp(KeyCode.R) && weap ==3 && fireCooldown >= fireRate)
{
ak.GetComponent<akScript>().Reload();
}
}
void OnTriggerEnter(Collider col)
{
//Debug.Log("is this working?");
if (col.gameObject.tag == "Projectile")
{
if (armor > 0){
armor -= dmg;
}else{
health -= dmg;
}
PlayerPrefs.SetInt("health",(int)health);
PlayerPrefs.SetInt("armor",(int)armor);
}
if (col.gameObject.tag == "spear")
{
if (armor > 0){
armor -= dmg * 1.5f;
}else{
health -= dmg * 1.5f;
}
PlayerPrefs.SetInt("health",(int)health);
PlayerPrefs.SetInt("armor",(int)armor);
}
if (col.gameObject.tag == "Enemy")
{
if (armor > 0){
armor -= dmg;
}else{
health -= dmg;
}
PlayerPrefs.SetInt("health",(int)health);
PlayerPrefs.SetInt("armor",(int)armor);
}
if (col.gameObject.tag == "Crouch")
{
Destroy(col.gameObject);
crouchAllow();
PlayerPrefs.SetInt("PlayerCrouch", 1);
crouchpowerup =PlayerPrefs.GetInt("PlayerCrouch");
}
if (col.gameObject.tag == "DoubleJump")
{
Destroy(col.gameObject);
doubleJumpAllow();
PlayerPrefs.SetInt("PlayerDoubleJump", 1);
doublejpowerup = PlayerPrefs.GetInt("PlayerDoubleJump");
}
if (col.gameObject.tag == "TripleJump")
{
Destroy(col.gameObject);
tripleJumpAllow();
PlayerPrefs.SetInt("PlayerTripleJump", 1);
triplejpowerup = PlayerPrefs.GetInt("PlayerTripleJump");
}
if (col.gameObject.tag == "BunnyHop")
{
Destroy(col.gameObject);
bunnyHop();
PlayerPrefs.SetInt("PlayerBunnyHop", 1);
bunnyhoppowerup = PlayerPrefs.GetInt("PlayerBunnyHop");
}
if ( col.gameObject.tag == "RESET")
{
Destroy(col.gameObject);
ResetPrefs();
}
if (col.gameObject.tag == "health")
{
if(health <100){
Destroy(col.gameObject);
health +=25;
if(health >100){
health =100;
}
}
PlayerPrefs.SetInt("health",(int)health);
}
if (col.gameObject.tag =="armor")
{
if(armor <200){
Destroy(col.gameObject);
armor =200;
}
PlayerPrefs.SetInt("armor",(int)armor);
}
if (col.gameObject.tag == "glock")
{
//ADD AMMO HERE
Destroy(col.gameObject);
GetComponent<weaponMaster>().addGlockAmmo();
totalglock = PlayerPrefs.GetInt("totalglock");
}
if(col.gameObject.tag == "ak")
{
Destroy(col.gameObject);
PlayerPrefs.SetInt("akpowerup", 1);
akpowerup = PlayerPrefs.GetInt("akpowerup");
GetComponent<weaponMaster>().addAkAmmo();
GetComponent<weaponMaster>().setAkUse();
totalak = PlayerPrefs.GetInt("totalak");
//set active here
}
if(col.gameObject.tag == "alien")
{
Destroy(col.gameObject);
PlayerPrefs.SetInt("alienpowerup", 1);
alienpowerup = PlayerPrefs.GetInt("alienpowerup");
GetComponent<weaponMaster>().addAlienAmmo();
GetComponent<weaponMaster>().setAlienUse();
totalalien = PlayerPrefs.GetInt("totalalien");
//set active here
}
if(col.gameObject.tag == "shotgun")
{
Destroy(col.gameObject);
PlayerPrefs.SetInt("shotgunpowerup", 1);
shotgunpowerup = PlayerPrefs.GetInt("shotgunpowerup");
GetComponent<weaponMaster>().addShells();
GetComponent<weaponMaster>().setShotgunUse();
totalshells = PlayerPrefs.GetInt("totalshells");
//set active here
}
}
/*void OnCollisionEnter (Collision col)
{
if (col.gameObject.tag == "Projectile")
{
if (armor > 0){
armor -= dmg;
}else{
health -= dmg;
}
PlayerPrefs.SetInt("health",(int)health);
PlayerPrefs.SetInt("armor",(int)armor);
}
if (col.gameObject.tag == "Enemy")
{
if (armor > 0){
armor -= dmg;
}else{
health -= dmg;
}
PlayerPrefs.SetInt("health",(int)health);
PlayerPrefs.SetInt("armor",(int)armor);
}
}*/
//FUNCTIONS TO BE CALLED BY BUTTONS
public void bunnyHop ()
{
bunnyHopping = !bunnyHopping;
}
public void doubleJumpAllow()
{
doubleJump = !doubleJump;
}
public void tripleJumpAllow()
{
tripleJump = !tripleJump;
}
public void crouchAllow()
{
crouch = !crouch;
}
public void showCursor()
{
cursor = !cursor;
}
public void ResetPrefs()
{
PlayerPrefs.DeleteAll();
}
}
<file_sep>var target : Transform;
var gravity : float = 20;
var moveSpeed : float = 6; // chase speed
var rotSpeed : float = 90; // speed to turn to the player (degrees/second)
var attackDistance : float = 2; // attack distance
var detectRange : float = 20; // detection distance
private var transf : Transform;
private var character: CharacterController;
function Start () {
if (!target) target = GameObject.FindWithTag ("Player").transform;
transf = transform;
character = GetComponent(CharacterController);
}
function Update(){
if (target){
var tgtDir = target.position - transf.position;
var tgtDist = tgtDir.magnitude; // get distance to the target
if (!Physics.Raycast(transf.position, tgtDir, detectRange)){
// stays in idle mode if can't see target
Idle();
}
else {
var moveDir = target.position - transf.position;
moveDir.y = 0; // prevents enemy tilting
rot = Quaternion.FromToRotation(Vector3.forward, moveDir);
transf.rotation = Quaternion.RotateTowards(transf.rotation, rot, rotSpeed * Time.deltaTime);
if (tgtDist <= attackDistance){ // if dist <= attackDistance: stop and attack
// do your attack here
print("Attack!");
}
else { // if attackDistance < dist < detectRange: chase the player
// Move towards target
MoveCharacter(moveDir, moveSpeed);
}
}
}
}
var walkSpeed = 3.0;
var travelTime = 2.0;
var idleTime = 1.5;
var rndAngle = 45; // enemy will turn +/- rndAngle
private var timeToNewDir = 0.0;
private var turningTime = 0.0;
private var turn: float;
function Idle () {
// Walk around and pause in random directions
if (Time.time > timeToNewDir) { // time to change direction?
turn = (Random.value > 0.5)? rndAngle : -rndAngle; // choose new direction
turningTime = Time.time + idleTime; // will stop and turn during idleTime...
timeToNewDir = turningTime + travelTime; // and travel during travelTime
}
if (Time.time < turningTime){ // rotate during idleTime...
transform.Rotate(0, turn*Time.deltaTime/idleTime, 0);
} else { // and travel until timeToNewDir
MoveCharacter(transform.forward, walkSpeed);
}
}
function MoveCharacter(dir: Vector3, speed: float){
var vel = dir.normalized * speed; // vel = velocity to move
// clamp the current vertical velocity for gravity purpose
vel.x = Mathf.Clamp(character.velocity.y, -30, 2);
vel.x -= gravity * Time.deltaTime; // apply gravity
character.Move(vel * Time.deltaTime); // move
}<file_sep>#pragma strict
var effect : Transform;
var damage =50;
var soundrifle : AudioClip;
var maxbullets = 300;
var totalcurbullets =210;
var curclip = 30;
var maxclip =30;
public var reload : boolean = false;
//DONT TOUCH temp OR remainder OR ANYTHING BELOW HERE
var ammoGui : UI.Text;
var temp = 0;
var remainder = 0;
GetComponent.<AudioSource>().clip= soundrifle;
var targetHP : int;
//var target : GameObject;
function Update () {
var hit: RaycastHit;
var ray: Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width * 0.5,Screen.height * 0.5, 0));
if(Input.GetKeyDown(KeyCode.R) && curclip<30){
Reload();
}
if(Input.GetMouseButtonDown(0))
{
if(Physics.Raycast(ray, hit, 100))
{
if(curclip >=1){
var particleclone = Instantiate(effect,hit.point, Quaternion.LookRotation(hit.normal));
Destroy(particleclone.gameObject,2);
if(hit.transform.tag=="Enemy")
{
hit.transform.SendMessage("ApplyDamage", damage,SendMessageOptions.DontRequireReceiver);
}
curclip--;
GetComponent.<AudioSource>().Play();
}else{
Reload();
}
}
}
}
function Reload(){
if(curclip < maxclip && totalcurbullets>0)
{
temp = totalcurbullets%maxclip;
if(temp==0)
{
temp=30;
}
totalcurbullets -= temp;
curclip += temp;
if(curclip > maxclip)
{
remainder = curclip - maxclip;
totalcurbullets += remainder;
curclip = maxclip;
}
if(totalcurbullets < 0)
{
totalcurbullets=0;
}
reload=true;
}
if(reload==true)
{
yield WaitForSeconds(.25);
reload=false;
}
}
function OnGUI(){
ammoGui.text="ACR :" + curclip + "/" + totalcurbullets.ToString();
}
@script RequireComponent(AudioSource);<file_sep>using UnityEngine;
using System.Collections;
public class akScript : MonoBehaviour {
public GameObject bullet_prefab;
AudioSource[] sounds;
AudioSource shoot, reload;
weaponMaster weap;
GameObject player;
public int clipMax = 30, clipCurrent = 30;
public int totalBullets;
public GameObject ak;
float reloadCooldown = 3f, reloadCooldownMax = 3f;
//new
private Vector3 posLock;
void Start ()
{
player = GameObject.FindGameObjectWithTag("Player");
weap = player.GetComponent<weaponMaster>(); // Get Master Script for ammo info
totalBullets = weap.getAkAmmo();
sounds = GetComponents<AudioSource>();
reload = sounds[0];
shoot = sounds[1];
//phil add this for current ammo count
if(PlayerPrefs.HasKey("curak")){
clipCurrent = PlayerPrefs.GetInt("curak");
}
if(PlayerPrefs.HasKey("totalak")){
totalBullets = PlayerPrefs.GetInt("totalak");
}
posLock = new Vector3 (0.05100221f, -0.8060001f, 0.604f);
}
void Update ()
{
totalBullets=weap.getAkAmmo();//phil added this
reloadCooldown += Time.deltaTime;
if(clipCurrent <= 0 && totalBullets > 0)
{
Reload ();
}
PlayerPrefs.SetInt("curak",clipCurrent);
PlayerPrefs.SetInt("totalak",totalBullets);
this.gameObject.transform.localPosition = posLock;
}
public void Shoot()
{
if(clipCurrent > 0 && reloadCooldown > reloadCooldownMax)
{
clipCurrent--;
//Debug.Log("Current clip is" + clipCurrent);
//Debug.Log("Total bullets are" + totalBullets);
//Debug.Log("Struct bullets are" + weap.getAkAmmo());
Instantiate(bullet_prefab, transform.FindChild("muzzle").transform.position, transform.FindChild("muzzle").transform.rotation);
shoot.Play();
ak.GetComponent<Animation>().CrossFade("akfire");
}
}
public void Reload()
{
if(totalBullets > clipMax && clipCurrent == 0) // If I have more than the whole clip can hold set to max
{
clipCurrent = clipMax;
totalBullets -= clipMax;
weap.setAkAmmo(totalBullets); //Update ammo in structure
reload.Play();
reloadCooldown = 0f;
ak.GetComponent<Animation>().CrossFade("akr1");
}
else if(totalBullets <= clipMax && totalBullets > 0 && clipCurrent ==0) // If i have less than maxClip but more than 0 Swap and Update ammo structure
{
clipCurrent = totalBullets;
totalBullets -= clipCurrent;
weap.setAkAmmo(0); // ? This should be correct? Update the structure to have only the remaining loaded bullets?
reload.Play();
reloadCooldown = 0f;
ak.GetComponent<Animation>().CrossFade("akr1");
}
else if(totalBullets > clipMax && clipCurrent < 30){
int ctemp;
ctemp = clipMax - clipCurrent;
totalBullets -= ctemp;
clipCurrent = clipMax;
weap.setAkAmmo(totalBullets);
reload.Play();
reloadCooldown = 0f;
ak.GetComponent<Animation>().CrossFade("akr1");
}
else if(totalBullets <= clipMax && totalBullets > 0 && clipCurrent <30)
{
int ctemp2;
ctemp2= clipMax - clipCurrent;
if(ctemp2 < totalBullets){
clipCurrent += ctemp2;
totalBullets -= ctemp2;
}else{
clipCurrent += totalBullets;
totalBullets =0;
}
weap.setAkAmmo(totalBullets);
reload.Play();
reloadCooldown = 0f;
ak.GetComponent<Animation>().CrossFade("akr1");
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour
{
public float existenceTime;
public Rigidbody bulletPhysics;
public float shootSpeed;
// Use this for initialization
void Start ()
{
//transform.rotation = new Quaternion (transform.rotation.x, -transform.rotation.y, transform.rotation.z, transform.rotation.w);
bulletPhysics = GetComponent<Rigidbody> ();
Destroy (gameObject, existenceTime);
bulletPhysics.velocity = transform.TransformDirection(new Vector3(0,0, shootSpeed));
}
// Update is called once per frame
void Update ()
{
}
}
<file_sep>#pragma strict
public var fieldOfViewAngel : float = 110f;
public var playerInSight : boolean;
public var personalLastSighting : Vector3;
private var nav : NavMeshAgent;
private var col : SphereCollider;
//private var : Animator;
private var lastPlayerSighting : LastPlayerSighting;
private var player : GameObject;
private var playerHealth : int;
private var previousSighting : Vector3;
//private var hash : HashIDs;
//private var
function Awake () {
nav = GetComponent(NavMeshAgent);
col = GetComponent(SphereCollider);
lastPlayerSighting = GameObject.FindGameObjectWithTag("GameController").GetComponent(LastPlayerSighting);
player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent(playerManager).health;
personalLastSighting = lastPlayerSighting.resetPosition;
previousSighting = lastPlayerSighting.resetPosition;
}
function Update () {
if(lastPlayerSighting.position != previousSighting)
{
personalLastSighting = lastPlayerSighting.position;
}
previousSighting = lastPlayerSighting.position;
//if(playerHealth.health > 0f)*/
}
function OnTriggerStay (other : Collider)
{
//checks to see if player hits sphere collider that represents field of view
if(other.gameObject == player)
{
playerInSight = false;
//creates vector from enemy to player and stores angle from that and spiders forward vector
var direction : Vector3 = other.transform.position - this.transform.position;
var angle : float = Vector3.Angle(direction, transform.forward);
//
if(angle < fieldOfViewAngel * 0.5f)
{
var hit : RaycastHit;
//check to see if something is between spider and player
if(Physics.Raycast(transform.position + transform.up, direction.normalized, hit, col.radius))
{
//hits player
Debug.Log("help");
if(hit.collider.gameObject==player)
{
playerInSight =true;
//lastPlayerSighting.position = player.transform.position;
}
}
}
//the player is doing any action can the spider hear the player
var playerWalk : boolean = player.GetComponent(playerManager).playerWalk;
var playerjump : boolean = player.GetComponent(playerManager).playerJump;
var playershoot1 : boolean = player.GetComponent(playerManager).playerShootR;
var playerReload1 : boolean = player.GetComponent(playerManager).playerReloadR;
var playershoot2 : boolean = player.GetComponent(playerManager).playerShootS;
var playerReload2 : boolean = player.GetComponent(playerManager).playerReloadS;
if( playerWalk == true || playerjump == true || playershoot1== true || playerReload1 ==true || playershoot2== true || playerReload2 ==true)
{
//check to see if the player is within hearing range
if(CalculatePathLength(player.transform.position) <= col.radius)
{
//just set personalLastSighting
personalLastSighting = player.transform.position;
}
}
}
}
function OnTriggerExit( other : Collider)
{
//if player leaves the view of sight collider
if(other.gameObject == player)
{
//player is no longer in sight;
playerInSight = false;
}
}
function CalculatePathLength(targetPosition : Vector3)
{
//creates path and set it based on targets position
var path : NavMeshPath = new NavMeshPath();
if(nav.enabled)
{
nav.CalculatePath(targetPosition, path);
}
//creates an array of points which is the length of the number of corners in the path +2
var allWayPoints : Vector3[] = new Vector3[path.corners.Length +2];
//first waypoint is position of spider
allWayPoints[0] = transform.position;
//last way point is the target position
allWayPoints[allWayPoints.Length -1] = targetPosition;
for(var i=0; i<path.corners.Length;i++)
{
allWayPoints[i+1] = path.corners[i];
}
//create a float to store path length
var pathLength : float = 0;
//increment path length by distance between two Waypoints
for(var j=0; j < allWayPoints.Length -1; j++)
{
pathLength += Vector3.Distance(allWayPoints[j], allWayPoints[j+1]);
}
return pathLength;
}<file_sep>#pragma strict
public var health : float = 0f;
var acr : GameObject;
var uts : GameObject;
public var playerWalk : boolean = false;
public var playerJump : boolean = false;
public var playerReloadR : boolean =false;
public var playerReloadS : boolean =false;
public var playerShootR : boolean = false;
public var playerShootS : boolean = false;
var HealthGUI : UI.Text;
function Awake(){
health=100f;
}
function ApplyDamage(damage :int){
health -= damage;
yield WaitForSeconds(3);
}
function Update () {
checkHealth();
checkMoveState();
checkWeaponState();
}
function checkHealth(){
if(health <=0)
{
Application.LoadLevel(Application.loadedLevel);
}
}
function OnTriggerEnter(other: Collider){
if(other.tag=="shells")
{
uts.GetComponent(shootbuckshot).totalcurshells +=30;
Destroy(other.gameObject);
}else if(other.tag=="bullets"){
acr.GetComponent(Raycastshoot).totalcurbullets +=90;
Destroy(other.gameObject);
}else if(other.tag=="Health"){
if(health <=100){
health +=50;
if(health >100){
health =100;
}
Destroy(other.gameObject);
}
}else if(other.tag=="Exit"){
Application.LoadLevel(0);
}else if(other.tag=="Death"){
health =0;
}
}
function checkMoveState(){
if(Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.S))
{
playerWalk=true;
}
if(Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.D) || Input.GetKeyUp(KeyCode.S)){
playerWalk=false;
}
if(Input.GetKeyDown(KeyCode.Space))
{
playerJump=true;
}
if(Input.GetKeyUp(KeyCode.Space))
{
playerJump=false;
}
}
function checkWeaponState(){
if(uts.activeInHierarchy)
{
if(Input.GetMouseButtonDown(0))
{
playerShootS=true;
}
if(Input.GetMouseButtonUp(0))
{
playerShootS=false;
}
playerReloadS=uts.GetComponent(shootbuckshot).reload;
playerShootR=false;
playerReloadR=false;
}
if(acr.activeInHierarchy)
{
if(Input.GetMouseButtonDown(0))
{
playerShootR=true;
}
if(Input.GetMouseButtonUp(0))
{
playerShootR=false;
}
playerReloadR=acr.GetComponent(Raycastshoot).reload;
playerShootS=false;
playerReloadS=false;
}
}
function OnGUI(){
HealthGUI.text="Health :"+health;
}<file_sep>using UnityEngine;
using System.Collections;
public class alienExplodeDie : MonoBehaviour {
float lifetime;
void Update ()
{
lifetime += Time.deltaTime;
if(lifetime > 2)
Destroy(gameObject);
}
}
<file_sep>#pragma strict
function Start () {
}
function Update () {
}
function OnTriggerEnter(collider : Collider){
if(collider.tag == "Player"){
Application.LoadLevel(35);
}
}<file_sep>Dubai: The Game
3D First Person Shooter in Unity/C#
Has multiple weapons, power ups, enemies and different rooms to explore.
Developed for Game Asset Production at NJIT (Spring 2015)
Final version is dubai_final.exe
Game is still subject to changes
Developers: <NAME>, <NAME> (br66), <NAME><file_sep>using UnityEngine;
using System.Collections;
public class START : MonoBehaviour {
// Use this for initialization
public void Start () {
Application.LoadLevel(1);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class weaponMaster : MonoBehaviour {
public struct Weapon
{
public Weapon(int dmg, int coil, int bullets, bool flagCanUse, bool flagInUse)
{
ammo = bullets;
damage = dmg;
recoil = coil;
canUse = flagCanUse;
inUse = flagInUse;
}
public int damage, recoil, ammo;
public bool canUse, inUse;
}
public Weapon Glock = new Weapon(25, 0, 45, true, true);
public Weapon Shotgun = new Weapon(10, 5, 0, false, false);
public Weapon Ak47 = new Weapon(35, 7, 0, false, false);
public Weapon Alien = new Weapon(100, 10, 0, false, false);
public GameObject wGlock, wShotgun, wAk47, wAlien;
void Start ()
{
//wGlock = transform.Find("glock").gameObject;
//wShotgun = transform.Find ("shotgun").gameObject;
//wAk47 = transform.Find("ak47").gameObject;
//wAlien = transform.Find ("alien").gameObject;
wGlock.SetActive(true);
wShotgun.SetActive(false);
wAk47.SetActive(false);
wAlien.SetActive(false);
if(PlayerPrefs.HasKey("totalglock")){
Glock.ammo=PlayerPrefs.GetInt("totalglock");
}
if(PlayerPrefs.HasKey("totalak")){
Ak47.ammo=PlayerPrefs.GetInt("totalak");
}
if(PlayerPrefs.HasKey("totalshells")){
Shotgun.ammo=PlayerPrefs.GetInt("totalshells");
}
if(PlayerPrefs.HasKey("totalalien")){
Alien.ammo=PlayerPrefs.GetInt("totalalien");
}
}
void Update ()
{
if(Input.GetKey("1")) // glock selection
{
if(Glock.inUse == true) // if glock in use
{
Glock.inUse = true; // do nothing
}
else if(Shotgun.inUse == true && /*Glock.ammo > 0 &&*/ Glock.canUse == true) // if shotgun in use
{
Shotgun.inUse = false;
wShotgun.SetActive(false); // disable it
Glock.inUse = true;
wGlock.SetActive(true);
}
else if(Ak47.inUse == true && /*Glock.ammo > 0 &&*/ Glock.canUse == true) // if ak in use
{
Ak47.inUse = false;
wAk47.SetActive(false); // disable it
Glock.inUse = true;
wGlock.SetActive(true);
}
else if(Alien.inUse == true && /*Glock.ammo > 0 &&*/ Glock.canUse == true) // if alien in use
{
Alien.inUse = false;
wAlien.SetActive(false); // disable it
Glock.inUse = true;
wGlock.SetActive(true);
}
}
if(Input.GetKey("2")) //Shotgun selection
{
if(Glock.inUse == true && /*Shotgun.ammo > 0 &&*/ Shotgun.canUse == true) // if glock in use
{
Glock.inUse = false;
wGlock.SetActive(false); // disable it
Shotgun.inUse= true;
wShotgun.SetActive(true);
}
else if(Shotgun.inUse == true) // if shotgun in use
{
Shotgun.inUse = true; // do nothing
}
else if(Ak47.inUse == true && /*Shotgun.ammo > 0 &&*/ Shotgun.canUse == true) // if ak in use
{
Ak47.inUse = false;
wAk47.SetActive(false); // disable it
Shotgun.inUse = true;
wShotgun.SetActive(true);
}
else if(Alien.inUse == true && /*Shotgun.ammo > 0 &&*/ Shotgun.canUse == true) // if alien in use
{
Alien.inUse = false;
wAlien.SetActive(false); // disable it
Shotgun.inUse = true;
wShotgun.SetActive(true);
}
}
if(Input.GetKey("3")) // Ak47 Selection
{
if(Glock.inUse == true && /*Ak47.ammo > 0 &&*/ Ak47.canUse == true) // if glock in use
{
Glock.inUse = false;
wGlock.SetActive(false); // disable it
Ak47.inUse= true;
wAk47.SetActive(true);
}
else if(Shotgun.inUse == true && /*Ak47.ammo > 0 &&*/ Ak47.canUse == true) // if shotgun in use
{
Shotgun.inUse = false; // disable it
wShotgun.SetActive(false);
Ak47.inUse = true;
wAk47.SetActive(true);
}
else if(Ak47.inUse == true) // if ak in use
{
Ak47.inUse = true; // do nothing
}
else if(Alien.inUse == true &&/* Ak47.ammo > 0 &&*/ Ak47.canUse == true) // if alien in use
{
Alien.inUse = false;
wAlien.SetActive(false); // disable it
Ak47.inUse = true;
wAk47.SetActive(true);
}
}
if(Input.GetKey("4")) //Section 9 alien weapon Selection
{
if(Glock.inUse == true && /*Alien.ammo > 0 && */Alien.canUse == true) // if glock in use
{
Glock.inUse = false;
wGlock.SetActive(false); // disable it
Alien.inUse= true;
wAlien.SetActive(true);
}
else if(Shotgun.inUse == true && /*Alien.ammo > 0 && */Alien.canUse == true) // if shotgun in use
{
Shotgun.inUse = false; // do nothing
wShotgun.SetActive(false);
Alien.inUse = true;
wAlien.SetActive(true);
}
else if(Ak47.inUse == true && /*Alien.ammo > 0 && */Alien.canUse == true) // if ak in use
{
Ak47.inUse = false;
wAk47.SetActive(false); // disable it
Alien.inUse = true;
wAlien.SetActive(true);
}
else if(Alien.inUse == true) // if alien in use
{
Alien.inUse = true; // do nothing
}
}
} // End Update
public int checkWeapon()
{
if(Glock.inUse == true)
return 1;
else if (Shotgun.inUse == true)
return 2;
else if (Ak47.inUse == true)
return 3;
else if (Alien.inUse == true)
return 4;
else
return 1;
}
// Get and Sets for weapon sub scripts
public int getGlockAmmo()
{
return Glock.ammo;
}
public void setGlockAmmo(int x)
{
Glock.ammo = x;
}
public int getShotgunAmmo()
{
return Shotgun.ammo;
}
public void setShotgunAmmo(int x)
{
Shotgun.ammo = x;
}
public int getAkAmmo()
{
return Ak47.ammo;
}
public void setAkAmmo(int x)
{
Ak47.ammo = x;
}
public int getAlienAmmo()
{
return Alien.ammo;
}
public void setAlienAmmo(int x)
{
Alien.ammo = x;
}
public void addGlockAmmo()
{
Glock.ammo += 30;
}
public void addShells()
{
Shotgun.ammo += 6;
}
public void addAkAmmo()
{
Ak47.ammo += 60;
//Debug.Log ("you are adding ak ammo somewhere");
}
public void addAlienAmmo()
{
Alien.ammo+= 1;
}
public void setShotgunUse()
{
Shotgun.canUse = true;
}
public int getShotgunUse()
{
if(Shotgun.canUse == true)
return 1;
else
return 0;
}
public void setAkUse()
{
Ak47.canUse = true;
}
public void setAlienUse()
{
Alien.canUse = true;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class shotgunScript : MonoBehaviour {
public GameObject bullet_prefab;
AudioSource[] sounds;
AudioSource shoot, reload;
weaponMaster weap;
GameObject player;
public int clipMax = 3, clipCurrent = 3;
public int totalBullets;
Vector3 dir;
public GameObject shotgun;
float reloadCooldown = 3.331f, reloadCooldownMax = 3.331f;
//new
private Vector3 posLock;
void Start ()
{
player = GameObject.FindGameObjectWithTag("Player");
weap = player.GetComponent<weaponMaster>(); // Get Master Script for ammo info
totalBullets = weap.getShotgunAmmo();
sounds = GetComponents<AudioSource>();
reload = sounds[0];
shoot = sounds[1];
//phil add this for current ammo count
if(PlayerPrefs.HasKey("curshells")){
clipCurrent = PlayerPrefs.GetInt("curshells");
}
if(PlayerPrefs.HasKey("totalshells")){
totalBullets = PlayerPrefs.GetInt("totalshells");
}
//this.gameObject.transform.localPosition = posLock;
posLock = new Vector3 (0.09000088f, -0.22f, 0.3699999f);
}
void Update ()
{
totalBullets = weap.getShotgunAmmo();//Phil Added this, glock was not being updated of ammo update
reloadCooldown += Time.deltaTime;
if(clipCurrent <= 0 && totalBullets > 0)
{
Reload ();
}
PlayerPrefs.SetInt("curshells",clipCurrent);
PlayerPrefs.SetInt("totalshells",totalBullets);
this.gameObject.transform.localPosition = posLock;
}
public void Shoot()
{
if(clipCurrent > 0 && reloadCooldown > reloadCooldownMax)
{
clipCurrent--;
//Debug.Log("Current clip is" + clipCurrent);
//Debug.Log("Total bullets are" + totalBullets);
//Debug.Log("Struct bullets are" + weap.getShotgunAmmo());
for (int i = 0; i < 8; i++)
{
dir.x = Random.Range(-10, 10);
dir.y = Random.Range(-10, 10);
Quaternion adjusted = transform.FindChild("muzzle").transform.rotation;
adjusted = Quaternion.RotateTowards(adjusted, transform.rotation*Quaternion.FromToRotation(transform.forward,transform.up), dir.y);
adjusted = Quaternion.RotateTowards(adjusted, transform.rotation*Quaternion.FromToRotation(transform.forward,transform.right), dir.x);
Instantiate(bullet_prefab, transform.FindChild("muzzle").transform.position, adjusted);
}
shoot.Play();
shotgun.GetComponent<Animation>().CrossFade("shotgunfire");
}
}
public void Reload()
{
if(totalBullets > clipMax && clipCurrent ==0) // If I have more than the whole clip can hold set to max
{
clipCurrent = clipMax;
totalBullets -= clipMax;
weap.setShotgunAmmo(totalBullets); //Update ammo in structure
reload.Play();
reloadCooldown = 0f;
shotgun.GetComponent<Animation>().CrossFade("shotgunreload");
}
else if(totalBullets <= clipMax && totalBullets > 0 && clipCurrent ==0) // If i have less than maxClip but more than 0 Swap and Update ammo structure
{
clipCurrent = totalBullets;
totalBullets -= clipCurrent;
weap.setShotgunAmmo(0); // ? This should be correct? Update the structure to have only the remaining loaded bullets?
reload.Play();
reloadCooldown = 0f;
shotgun.GetComponent<Animation>().CrossFade("shotgunreload");
}
else if(totalBullets > clipMax && clipCurrent < 3) //phil manual reload function
{
int ctemp;
ctemp = clipMax - clipCurrent;
totalBullets -= ctemp;
clipCurrent = clipMax;
weap.setShotgunAmmo(totalBullets);
reload.Play();
reloadCooldown = 0f;
shotgun.GetComponent<Animation>().CrossFade("shotgunreload");
}
else if(totalBullets <= clipMax && totalBullets > 0 && clipCurrent <3)
{
int ctemp2;
ctemp2= clipMax - clipCurrent;
if(ctemp2 < totalBullets){
clipCurrent += ctemp2;
totalBullets -= ctemp2;
}else{
clipCurrent += totalBullets;
totalBullets =0;
}
weap.setShotgunAmmo(totalBullets);
reload.Play();
reloadCooldown = 0f;
shotgun.GetComponent<Animation>().CrossFade("shotgunreload");
//glock.GetComponent<Animation>().CrossFade("glockr1");
//glock.GetComponent<Animation>().CrossFade("glockidle");
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class enemy : MonoBehaviour
{
public float patrol, chase, patrolPause, chasePause;
public Transform[] waypoints;
public Transform player;
public bool patrolState;
public bool chaseState;
public int currentWaypoint;
//private Vector3 playerOffset;
public FPSC playerScript;
public float health;
public float dmg;
private int weap;
public weaponMaster weaponScript;
//public Vector3 normal;
//public Rigidbody bullet;
//public Vector3 offset;
//public Quaternion rotOffset;
//private bool shooting = true;
//public float waitToShoot;
void Start()
{
// transform.position = waypoints [0].position;
// currentWaypoint = 0;
patrolState = true;
//offset = new Vector3 (0, 0, 0);
//StartCoroutine ("Patrol");
}
void Update() //will be patrol state
{
weap = weaponScript.checkWeapon();
//playerOffset = transform.position - player.position;
//normal = transform.TransformDirection(GetComponent<MeshFilter>().mesh.normals[0]);
/*
//if i am at a waypoint, increase currentWaypoint so I move to the next
if (transform.position == waypoints[currentWaypoint].position)
currentWaypoint++;
//if i am at the last waypoint, reset currentWaypoint so I go back to the first
if (currentWaypoint >= waypoints.Length)
currentWaypoint = 0;
if (patrolState && !chaseState)
transform.position = Vector3.MoveTowards (transform.position, waypoints [currentWaypoint].position, patrol * Time.deltaTime);
*/
if(!patrolState && chaseState)
{
//transform.position = Vector3.MoveTowards (transform.position, normal, chase * Time.deltaTime);
//transform.position += transform.forward * chase * Time.deltaTime;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(player.position - transform.position), chase * Time.deltaTime);
transform.position = Vector3.MoveTowards(transform.position, player.position, chase *Time.deltaTime);
// if(shooting)
// {
// Rigidbody instance = Instantiate (bullet, transform.position + offset, transform.rotation) as Rigidbody;
// shooting = false;
// StartCoroutine("shoot");
// }
}
/*
Vector3 direction = transform.position - player.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
//to get player's actual facing direction
Quaternion updatedRot = Quaternion.AngleAxis(angle + 90, Vector3.forward); //this is the new rotation cooridinates based on the player
transform.rotation = Quaternion.Slerp(transform.rotation, updatedRot, Time.deltaTime * 10);
transform.position = Vector3.Lerp(transform.position, new Vector3(player.position.x +2, player.position.y +2, player.position.z), Time.deltaTime * chase)
*/
if(health <= 0)
Destroy(gameObject);
}
void OnCollisionEnter(Collision col)
{
//weapon master
if (col.gameObject.tag == "bullet2")
{
if(weap == 1)
health -= weaponScript.Glock.damage;
else if(weap == 2)
health -= weaponScript.Shotgun.damage;
else if(weap == 3)
health -= weaponScript.Ak47.damage;
}
else if (col.gameObject.tag == "Alienbullet")
{
health -= weaponScript.Alien.damage;
}
}
void OnTriggerStay(Collider col)
{
if (col.gameObject.tag == "Player")
{
patrolState = false;
/// Debug.Log ("Chase State");
chaseState = true;
}
}
void OnTriggerExit(Collider col)
{
if (col.gameObject.tag == "Player")
{
patrolState = true;
chaseState = false;
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class RESET : MonoBehaviour {
// Use this for initialization
public void Start () {
PlayerPrefs.DeleteAll();
}
}
<file_sep>#pragma strict
var fieldOfViewAngle =180;
var Health : int = 100;
var damage : int =20;
var Player : GameObject;
var pp : Transform;
var MoveSpeed : int =4;
var col : SphereCollider;
var hitbox : CapsuleCollider;
var playerHealth : int;
var OnPatrol : boolean =false;
var Chase : boolean =false;
var attack : boolean =false;
var playerInSight : boolean =false;
var playerInHear : boolean =false;
var inAttackRange : boolean = false;
var attackedplayer : boolean =false;
var spiderAttacked : boolean =false;
var pjump : boolean = false;
var pwalk : boolean =false;
var pshoot1 : boolean =false;
var pshoot2 : boolean =false;
var preload1 : boolean =false;
var preload2 : boolean =false;
var MinDist : int = 1;
var MaxDist : int = 10;
function Awake(){
Health =100;
Player = GameObject.FindGameObjectWithTag("Player");
playerHealth=Player.GetComponent(playerManager).health;
pjump=Player.GetComponent(playerManager).playerJump;
pwalk=Player.GetComponent(playerManager).playerWalk;
pshoot1=Player.GetComponent(playerManager).playerShootR;
pshoot2=Player.GetComponent(playerManager).playerShootS;
preload1=Player.GetComponent(playerManager).playerReloadR;
preload2=Player.GetComponent(playerManager).playerReloadS;
}
function Update () {
GetPlayerStatus();
CheckHealth();
if(playerHealth> 0)
{
if(playerInSight ==false){
patrol();
}
if(inAttackRange ==true && attackedplayer==false){
attackPlayer();
delayNextAttack();
}
if(playerInSight== true || playerInHear == true && inAttackRange==false){
chase();
}
}else{
StopPatrol();
}
}
function delayNextAttack(){
if(attackedplayer==true){
yield WaitForSeconds(3);
attackedplayer=false;
}
}
function CheckHealth(){
if(Health <=0)
{
Destroy(gameObject);
}
}
function GetPlayerStatus(){
playerHealth=Player.GetComponent(playerManager).health;
pjump=Player.GetComponent(playerManager).playerJump;
pwalk=Player.GetComponent(playerManager).playerWalk;
pshoot1=Player.GetComponent(playerManager).playerShootR;
pshoot2=Player.GetComponent(playerManager).playerShootS;
preload1=Player.GetComponent(playerManager).playerReloadR;
preload2=Player.GetComponent(playerManager).playerReloadS;
}
function patrol(){
OnPatrol =true;
if(playerInSight == true)
{
OnPatrol=false;
}
}
function chase(){
Chase = true;
MoveSpeed=5;
transform.LookAt(pp);
if(Vector3.Distance(transform.position, pp.position)>= MinDist)
{
transform.Translate(MoveSpeed*Vector3.forward*Time.deltaTime);
if(Vector3.Distance(transform.position, pp.position) <= 1.5)
{
Chase=false;
inAttackRange=true;
}else{
inAttackRange=false;
}
}
}
function StopPatrol(){
OnPatrol =false;
}
function ApplyDamage(damage :int){
Health -=damage;
playerInSight=true;
spiderAttacked =true;
}
function attackPlayer(){
if(attackedplayer==false ){
Player.SendMessage("ApplyDamage", damage,SendMessageOptions.DontRequireReceiver);
}
attackedplayer=true;
//Debug.Log("attackPlayer");
//playerInSight=true;
//Chase=true;
//transform.LookAt(pp);
//transform.Translate(MoveSpeed*Vector3.forward*Time.deltaTime);
}
function OnTriggerStay(other : Collider){
if(other.gameObject==Player)
{
var direction : Vector3 = other.transform.position - this.transform.position;
var angle : float = Vector3.Angle(direction, transform.forward);
if(angle < fieldOfViewAngle * 0.5f)
{
playerInSight=true;
}
if(pjump == true || pwalk == true || pshoot1 == true || pshoot2 == true || preload1 == true || preload2 == true)
{
playerInHear=true;
}
}
}
function OnTriggerExit(other : Collider){
if(spiderAttacked ==false){
playerInSight=false;
}else{
playerInSight=true;
}
playerInHear=false;
OnPatrol=true;
Chase=false;
}<file_sep>using UnityEngine;
using System.Collections;
public class bulletFly : MonoBehaviour {
public Rigidbody bullet;
GameObject player, explode;
public int glockBulletSpeed, shotgunBulletSpeed, akBulletSpeed, alienBulletSpeed;
public int glockBulletDmg, shotgunBulletDmg, akBulletDmg, alienBulletDmg;
weaponMaster weap;
void Start ()
{
player = GameObject.FindGameObjectWithTag("Player");
weap = player.GetComponent<weaponMaster>();
explode = Resources.Load("alienexplode", typeof(GameObject)) as GameObject;
if(weap.checkWeapon() == 1)
{
bullet.velocity = transform.forward * glockBulletSpeed;
}
else if(weap.checkWeapon() == 2)
{
bullet.velocity = transform.forward * shotgunBulletSpeed;
}
else if(weap.checkWeapon() == 3)
{
bullet.velocity = transform.forward * akBulletSpeed;
}
else if(weap.checkWeapon() == 4)
{
bullet.velocity = transform.forward * alienBulletSpeed;
}
}
void Update ()
{
}
void OnCollisionEnter(Collision col)
{
if(weap.checkWeapon() == 4)
Instantiate (explode, col.transform.position, col.transform.rotation);
Destroy(gameObject);
}
}
<file_sep>#pragma strict
var variance = 1.0;
var distance = 10.0;
var spreadFactor : float=1.0;
var effect : Transform;
var damage = 7;
var soundshotty : AudioClip;
var shottydelay : float = 0.25;
var maxshells = 180;
var totalcurshells =45;
var curclip = 15;
var maxclip = 15;
public var reload : boolean = false;
//DONT TOUCH temp OR remainder OR ANYTHING BELOW HERE
var ammoGui : UI.Text;
var temp = 0;
var remainder = 0;
GetComponent.<AudioSource>().clip = soundshotty;
function Update () {
if(Input.GetMouseButtonDown(0))
{
if(curclip >=1)
{
for(var i=0;i<30;i++)
{
shootray();
if(i >= 29)
{
GetComponent.<AudioSource>().Play();
curclip --;
}
}
}else{
Reload();
}
}
if(Input.GetKeyDown(KeyCode.R))
{
Reload();
}
}
function shootray(){
var hit: RaycastHit;
var dir : Vector3 = transform.forward;
dir.x += Random.Range(-spreadFactor, spreadFactor);
dir.y += Random.Range(-spreadFactor, spreadFactor);
dir.z += Random.Range(-spreadFactor, spreadFactor);
if(Physics.Raycast (transform.position, dir, hit, 100))
{
var particleclone = Instantiate(effect,hit.point, Quaternion.LookRotation(hit.normal));
Destroy(particleclone.gameObject,2);
hit.transform.SendMessage("ApplyDamage", damage,SendMessageOptions.DontRequireReceiver);
}
}
function Reload(){
if(curclip < maxclip && totalcurshells>0)
{
temp = totalcurshells%maxclip;
if(temp==0)
{
temp=15;
}
totalcurshells -= temp;
curclip += temp;
if(curclip > maxclip)
{
remainder = curclip - maxclip;
totalcurshells += remainder;
curclip = maxclip;
}
if(totalcurshells<0)
{
totalcurshells=0;
}
reload=true;
}
if(reload==true)
{
yield WaitForSeconds(.25);
reload=false;
}
}
function OnGUI(){
ammoGui.text="UTS :" + curclip + "/" + totalcurshells.ToString();
}
@script RequireComponent(AudioSource);<file_sep>#pragma strict
function Start () {
}
function OnTriggerEnter(){
Application.LoadLevel(0);
}<file_sep>using UnityEngine;
using System.Collections;
public class start : MonoBehaviour {
// Update is called once per frame
public void Start () {
Application.LoadLevel(1);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class enemyGun : MonoBehaviour
{
public Rigidbody bullet;
public Vector3 offset;
public Quaternion rotOffset;
private bool shooting = true;
public float waitToShoot;
public GameObject enemy;
public enemy enemyScript;
// Use this for initialization
void Start ()
{
enemy = transform.parent.parent.gameObject;
enemyScript = enemy.GetComponent<enemy> ();
}
// Update is called once per frame
void Update ()
{
if (!enemyScript.patrolState && enemyScript.chaseState)
{
if(shooting)
{
Rigidbody instance = Instantiate (bullet, transform.position + offset, transform.rotation) as Rigidbody;
shooting = false;
StartCoroutine("shoot");
}
}
}
IEnumerator shoot()
{
yield return new WaitForSeconds(waitToShoot);
shooting = true;
yield break;
}
}
|
055050da62f150115c3332a0f134bc3037864de6
|
[
"JavaScript",
"C#",
"Text"
] | 21
|
C#
|
br66/DubaiTheGame
|
ff83f82082ea5aeab4bf16ce9b8d1ce3dd462fad
|
7cd4a57cdb7c2842729b6ea11a9c9ac46b3bd266
|
refs/heads/master
|
<repo_name>Eros/TindersForTheLazy<file_sep>/__init__.py
import sys
import argparse
import requests
import json
API_URL = "https://api.gotinder.com/"
TINDER_AUTH_TOKE = "#########"
def get_user_information(header, user):
req = requests.get(API_URL + "user/recs", header = header)
if req.status_code == 200:
data = json.loads(req.text)
print(json.dumps(data, indent = 2, sort_keys = False))
def like(header):
req = requests.get(API_URL + "user/recs")
if req.status_code == 200:
data = json.loads(req.text)
print("~~~ Liking now ~~~")
with open("profile.txt", "a") as outfile:
for profile in data["results"]:
liked = requests.get(API_URL + "like/" + profile["id"], header = header)
if liked.status_code == 200:
if profile["name"] == "<NAME>":
print("Your API key has reached its limit, try again at the start of the hour!")
return 1
line = "liked >>" + profile["id"] + profile["name"]
print(line)
outfile.writable()
outfile.write(line + " \n")
else:
print("Error liking the user: " + profile["name"] + "with the ID: " + profile["id"])
print("~~~ Complete You shall not be single for long! ~~~")
return 0
else:
print("Not able to like anyone at this time.")
print("You are either banned from tinder or your API key currently has reached its limit")
return 1
parser = argparse._ArguementParser(description = "Who needs to do tinder manually?")
parser.add_argument("user", metavar = "user", help = "Do you really need fucking help with this?", action = "store", nargs = "?????")
args = parser.parse_args()
if TINDER_AUTH_TOKE == "":
print("You need to add in your tinder authentication token to use this script!")
sys.exit(1)
header = {"Content-Type": "application/json", "X-Auth-Token": <PASSWORD>}
r = 0
if args.user is not None:
r = get_user_information(header, args.user)
else:
r = like(header)
sys.exit(r)
|
3a3a2659c75569810f563cc06f864fc431cfc9cb
|
[
"Python"
] | 1
|
Python
|
Eros/TindersForTheLazy
|
515aadcfc283fca96b9c5522e30f7a4fd3f30fc4
|
c7be399f0c13ec7dcc5c4bcee6e7d155d0402b3f
|
refs/heads/master
|
<repo_name>zendotools/zendoscd<file_sep>/README.md
# zendoscd
osc msg emitter for zendo tools
<file_sep>/index.js
const OSC = require("osc-js");
const read = require('readline');
const Parse = require('parse/node');
const rl = read.createInterface({
input: process.stdin,
output: process.stdout
});
const osc = new OSC({ plugin: new OSC.DatagramPlugin, udpClient: { port: 5278 } })
osc.open()
var players = {}
Parse.initialize("APPLICATION_ID");
Parse.serverURL = 'http://code.zendo.tools:1337/parse'
Parse.masterKey = "MASTER_KEY"
pollUsers();
setInterval(pollUsers, 1000 * 30)
async function pollUsers()
{
var oneMinuteAgo = new Date();
oneMinuteAgo.setMinutes(new Date().getMinutes() - 1)
const users = new Parse.Query(Parse.User);
users.greaterThanOrEqualTo("updatedAt", oneMinuteAgo)
users.exists("game_progress")
const meditators = await users.findAll();
meditators.forEach(element => {
var key = element.id;
var progress = element.get("game_progress")
if(progress != null)
{
let player = players[key]
let previousProgress = null
if(player != null)
{
previousProgress = player.progress
}
players[key] = progress
if(progress != null && previousProgress != progress)
{
const message = new OSC.Message(key, progress)
osc.send( message, { host : "127.0.0.1", port: 5278 } )
}
print()
}
});
}
console.log("zendoscd started.")
console.log("commands: print | update | stats | exit <return>.")
rl.on('line', (line) => {
const command = line.toLowerCase().trim()
switch(command)
{
case 'print':
print();
break;
case 'exit':
process.exit(0);
break;
case 'update':
update();
break;
case 'stats':
stats();
break;
default:
break;
}
});
function update_osc(id, msg)
{
const message = new OSC.Message(id, msg);
osc.send( message, { host : "127.0.0.1", port: 5278 } );
}
function update()
{
for (const key in players)
{
if (players.hasOwnProperty(key))
{
const element = players[key];
console.log("updating " + key + ":" + element);
update_osc(key, element);
}
}
}
function print()
{
for (const key in players)
{
if (players.hasOwnProperty(key))
{
const element = players[key];
console.log(key + ":" + element);
}
}
}
async function stats()
{
const query = new Parse.Query(Parse.User);
query.greaterThan("donatedMinutes", 0);
const donators = await query.count();
console.log("Donators: " + donators)
const pipeline =
[
{
group:
{
objectId: null,
total: { $sum: '$donatedMinutes' }
}
}
];
const totalMinutes = new Parse.Query(Parse.User);
totalMinutes.aggregate(pipeline).then(function(results)
{
console.log("Minutes Donated: " + results[0].total)
})
.catch(function(error)
{
cpnsole.log(error)
});
}
|
cea48fecfb5faf370ebe822baeaf78437f17d03b
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
zendotools/zendoscd
|
d04e412e8278eac3d38addab434e42c01396f4c2
|
cd53d96558bfc13a9cfc28b8f5c4cb1068c9ed62
|
refs/heads/master
|
<repo_name>haideraza/fyp-project<file_sep>/FYP/CreatingProjAssets/Assets/ARFightingGame/Scripts/GameSession.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class GameSession : NetworkBehaviour
{
public List<NetworkPlayer> players = new List<NetworkPlayer>();
bool roundFinished = false;
public bool gameFinished = false;
bool infoUpdated = false;
bool playResetted = false;
int roundNo = 1;
Text roundNoText;
Text playerScoreText;
Text enemyScoreText;
GameObject roundPanel;
GameObject playAgainPanel;
Text roundPanelMsg;
Text playAgainPanelMsg;
Button playAgainYesBtn;
GameObject playMenu;
void Start()
{
playMenu = GameObject.Find("GameplayMenu").transform.GetChild(0).gameObject;
roundNoText = playMenu.transform.GetChild(10).GetChild(0).GetComponent<Text>();
playerScoreText = playMenu.transform.GetChild(10).GetChild(1).GetComponent<Text>();
enemyScoreText = playMenu.transform.GetChild(10).GetChild(2).GetComponent<Text>();
roundPanel = playMenu.transform.GetChild(11).gameObject;
playAgainPanel = playMenu.transform.GetChild(8).gameObject;
roundPanelMsg = roundPanel.transform.GetChild(0).GetChild(0).GetComponent<Text>();
playAgainPanelMsg = playAgainPanel.transform.GetChild(0).GetChild(0).GetComponent<Text>();
playAgainYesBtn = playAgainPanel.transform.GetChild(0).GetChild(2).GetComponent<Button>();
roundPanel.SetActive(false);
playAgainPanel.SetActive(false);
}
void Update()
{
//GameObject.Find("TTT").GetComponent<Text>().text = "No of players connected: " + players.Count;
if (players.Count == 2)
{
if (roundNo <= 3)
{
//if (players.Count == 2)
//{
startGame();
if (roundFinished)
{
StartCoroutine(showRoundEndPanel());
}
else
{
roundPanel.SetActive(false);
}
if (players[0].myPlayerHealth > 0 && players[1].myPlayerHealth > 0)
{
if (infoUpdated)
{
infoUpdated = false;
roundFinished = false;
}
}
/// }
}
else
{
playAgainPanel.SetActive(true);
gameFinished = true;
if (players[0].score > players[1].score)
{
if (players[0].isLocalPlayer)
{
playAgainPanelMsg.text = "You Win";
}
if (players[1].isLocalPlayer)
{
playAgainPanelMsg.text = "You Lose";
}
}
if (players[1].score > players[0].score)
{
if (players[1].isLocalPlayer)
{
playAgainPanelMsg.text = "You Win";
}
if (players[0].isLocalPlayer)
{
playAgainPanelMsg.text = "You Lose";
}
}
}
if (players[0].playAgain && players[1].playAgain)
{
resetGame();
}
updateUI_Info();
if (playResetted) {
StartCoroutine(waitForPlayerToReturn());
}
}
}
void startGame()
{
string str1 = "";
foreach (NetworkPlayer p in players)
{
p.CmdSendHealthInfo(p.playerHealth.updatedHealth);
str1 += " \n My Player " + (players.IndexOf(p) + 1) + " health : " + p.myPlayerHealth;
}
StartCoroutine(startFightRound());
}
IEnumerator startFightRound()
{
yield return new WaitForSeconds(0.1f);
if (players[0].myPlayerHealth <= 0)
{
players[0].winner = false;
players[1].winner = true;
players[1].EndReaction();
if (players[1].endReactionCompleted)
{
roundFinished = true;
}
}
else if (players[1].myPlayerHealth <= 0)
{
players[0].winner = true;
players[1].winner = false;
players[0].EndReaction();
if (players[0].endReactionCompleted)
{
roundFinished = true;
}
}
}
IEnumerator showRoundEndPanel()
{
if (!roundPanel.activeInHierarchy)
{
roundPanel.SetActive(true);
if (players[0].winner)
{
if (players[0].isLocalPlayer)
{
roundPanelMsg.text = "Yeah beat'em up";
}
if (players[1].isLocalPlayer)
{
roundPanelMsg.text = "You lost this round";
}
}
if (players[1].winner)
{
if (players[1].isLocalPlayer)
{
roundPanelMsg.text = "Yeah beat'em up";
}
if (players[0].isLocalPlayer)
{
roundPanelMsg.text = "You lost this round";
}
}
}
yield return new WaitForSeconds(6f);
if (!infoUpdated && roundFinished)
{
if (roundNo <= 3)
{
if (players[0].winner)
{
players[0].score = players[0].score + 1;
}
else if (players[1].winner)
{
players[1].score = players[1].score + 1;
}
roundNo++;
infoUpdated = true;
resetPlay();
}
}
}
void resetPlay()
{
foreach (NetworkPlayer p in players)
{
p.CmdShowHidePlayer(false);
p.CmdResetPlay(players.IndexOf(p));
}
playResetted = true;
}
IEnumerator waitForPlayerToReturn() {
yield return new WaitForSeconds(2);
foreach (NetworkPlayer p in players)
{
p.CmdShowHidePlayer(true);
}
playResetted = false;
roundPanel.SetActive(false);
}
public void resetGame()
{
foreach (NetworkPlayer p in players)
{
p.CmdResetPlay(players.IndexOf(p));
p.winner = false;
p.score = 0;
}
roundNo = 1;
roundPanel.SetActive(false);
playAgainYesBtn.interactable = true;
playAgainPanel.SetActive(false);
infoUpdated = false;
roundFinished = false;
players[0].CmdSendReplayInfo(false);
players[1].CmdSendReplayInfo(false);
}
void updateUI_Info()
{
if (roundNo <= 3)
{
roundNoText.text = "Round No : " + roundNo.ToString();
}
if (players[0].isLocalPlayer)
{
playerScoreText.text = players[0].score.ToString();
enemyScoreText.text = players[1].score.ToString();
}
else if (players[1].isLocalPlayer)
{
playerScoreText.text = players[1].score.ToString();
enemyScoreText.text = players[0].score.ToString();
}
/*
GameObject.Find("TTT").GetComponent<Text>().text = " p1 playagain : " + players[0].playAgain +
"\n p2 playagain : " + players[1].playAgain +
" info updated : " + infoUpdated +
", P1 health:" + players[0].myPlayerHealth;
// "\n game finished : " + gameFinished + ", P2 health:" + players[1].myPlayerHealth;
*/
/*
GameObject.Find("TTT").GetComponent<Text>().text = "p1 pos:" + players[0].transform.position +
"\np2 pos:" + players[1].transform.position +
"\np1 local pos:" + players[0].transform.localPosition +
"\np2 local pos:" + players[1].transform.localPosition +
"\np1 parent:" + players[0].transform.parent +
"\np2 parent:" + players[1].transform.parent;
*/
}
public void addPlayerToList(NetworkPlayer p)
{
players.Add(p);
}
public void playAgainYes()
{
if (players[0].isLocalPlayer)
{
players[0].CmdSendReplayInfo(true);
playAgainYesBtn.interactable = false;
}
else if (players[1].isLocalPlayer)
{
players[1].CmdSendReplayInfo(true);
playAgainYesBtn.interactable = false;
}
}
public void playAgainNo()
{
}
}
<file_sep>/FYP/CreatingProjAssets/Assets/ARFightingGame/Scripts/PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
[SerializeField]
float rotSpeed;
[SerializeField]
float gravity;
[SerializeField]
float actionWaitTime = 1f;
[SerializeField]
Joystick joystick1;
[SerializeField]
Joystick joystick2;
Animator anim;
//CharacterController controller;
float yComponent = 0f;
List<GameObject> colliders;
// Start is called before the first frame update
void Start()
{
Time.timeScale = 1;
anim =gameObject.GetComponent<Animator>();
//controller = gameObject.GetComponent<CharacterController>();
colliders = new List<GameObject>();
colliders.AddRange(GameObject.FindGameObjectsWithTag("HitCollider"));
toggleOnOffColliders(false);
}
// Update is called once per frame
void Update()
{
movement();
}
void movement()
{
if (joystick1.Vertical>0)
{
anim.SetInteger("MovementValue", 1);
}
else if (joystick1.Vertical == 0)
{
anim.SetInteger("MovementValue", 0);
}
if (joystick1.Vertical < 0)
{
anim.SetInteger("MovementValue", 2);
}
else if (joystick1.Vertical == 0)
{
anim.SetInteger("MovementValue", 0);
}
if (joystick2.Horizontal < 0)
{
transform.Rotate(0, -Time.deltaTime * rotSpeed, 0);
}
if (joystick2.Horizontal > 0)
{
transform.Rotate(0, Time.deltaTime * rotSpeed, 0);
}
yComponent = transform.position.y;
//if (!controller.isGrounded)
//{
// yComponent -= gravity * Time.deltaTime;
//transform.Translate(0, yComponent, 0);
//}
}
public void Punch() {
int value = Random.Range(1, 4);
anim.SetInteger("PunchValue", value);
toggleOnOffColliders(true);
StartCoroutine(backToIdleAnim("PunchValue"));
Debug.Log("Punched");
}
public void Kick()
{
int value = Random.Range(1, 3);
anim.SetInteger("KickValue", value);
toggleOnOffColliders(true);
StartCoroutine(backToIdleAnim("KickValue"));
Debug.Log("kicked");
}
IEnumerator backToIdleAnim(string value) {
yield return new WaitForSeconds(actionWaitTime);
anim.SetInteger(value, 0);
toggleOnOffColliders(false);
}
void toggleOnOffColliders(bool value) {
for (int i = 0; i < colliders.Count; i++)
{
colliders[i].GetComponent<Collider>().enabled = value;
}
}
}
<file_sep>/FYP/CreatingProjAssets/Assets/ARFightingGame/Scripts/NetworkGameSession.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using System.Linq;
public enum GameState
{
Offline,
Connecting,
Lobby,
Countdown,
MatchStarted,
GameOver
}
public class NetworkGameSession : NetworkBehaviour
{
GameObject mainMenu;
GameObject playMenu;
Text gameStateField;
public static NetworkGameSession instance;
NetworkListener networkListener;
List<NetworkPlayer> players;
string specialMessage = "";
[SyncVar]
public GameState gameState;
[SyncVar]
public string message = "";
public GameObject playerLeftPanel;
Text msg;
GameSession gameSess;
void Start()
{
players = new List<NetworkPlayer>();
gameStateField =GameObject.Find("NetworkStateField").GetComponent<Text>();
mainMenu = GameObject.Find("MainMenu").transform.GetChild(0).gameObject;
playMenu = GameObject.Find("GameplayMenu").transform.GetChild(0).gameObject;
playerLeftPanel = GameObject.Find("GameplayMenu").transform.GetChild(0).GetChild(9).gameObject;
msg = GameObject.Find("MSG").GetComponent<Text>();
gameSess = GameObject.Find("GameSession").GetComponent<GameSession>();
mainMenu.SetActive(true);
playMenu.SetActive(false);
gameSess.gameFinished = false;
}
void Update()
{
if (isServer)
{
if (gameState == GameState.Countdown)
{
message = "Game Starting in " + Mathf.Ceil(networkListener.mess.CountdownTimer()) + "...";
}
else if (specialMessage != "")
{
message = specialMessage;
}
else
{
message = gameState.ToString();
}
}
gameStateField.text = message;
}
public void OnDestroy()
{
////
}
[Server]
public override void OnStartServer()
{
networkListener = FindObjectOfType<NetworkListener>();
gameState = GameState.Connecting;
}
[Server]
public void OnStartGame(List<CaptainsMessPlayer> aStartingPlayers)
{
players = aStartingPlayers.Select(p => p as NetworkPlayer).ToList();
RpcOnStartedGame();
foreach (NetworkPlayer p in players)
{
p.RpcOnStartedGame();
}
StartCoroutine(RunGame());
}
[Server]
public void OnAbortGame()
{
//msg.text+= "OnAbortGame , ";
if (!gameSess.gameFinished) {
RpcOnAbortedGame();
}
}
[Client]
public void OnClientAbortGame()
{
//msg.text+= "OnClientAbortGame , ";
//CmdOnAbortedGame();
}
[Client]
public override void OnStartClient()
{
if (instance)
{
Debug.LogError("ERROR: Another GameSession!");
}
instance = this;
networkListener = FindObjectOfType<NetworkListener>();
networkListener.gameSession = this;
if (gameState != GameState.Lobby)
{
gameState = GameState.Lobby;
}
}
public void OnJoinedLobby()
{
gameState = GameState.Lobby;
}
public void OnLeftLobby()
{
gameState = GameState.Offline;
}
public void OnCountdownStarted()
{
gameState = GameState.Countdown;
}
public void OnCountdownCancelled()
{
gameState = GameState.Lobby;
}
[Server]
IEnumerator RunGame()
{
gameState = GameState.MatchStarted;
foreach (NetworkPlayer p in players)
{
//p.RpcResetHealth();
}
yield return 0;
}
[Server]
public void PlayAgain()
{
StartCoroutine(RunGame());
}
[ClientRpc]
public void RpcOnStartedGame()
{
mainMenu.SetActive(false);
playMenu.SetActive(true);
playerLeftPanel.SetActive(false);
}
[ClientRpc]
public void RpcOnAbortedGame()
{
//msg.text += "RpcOnAbortGame , ";
playerLeftPanel.SetActive(true);
}
/*
[Command]
public void CmdOnAbortedGame()
{
//msg.text += "CmdOnAbortGame , ";
RpcOnAbortedGame();
}
*/
}
<file_sep>/FYP/CreatingProjAssets/Assets/PracticeAssets(Not Important)/Scripts/DroneController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DroneController : MonoBehaviour
{
public float vertical_force, horizontal_force;
public float fan_speed;
public Rigidbody rb;
public Joystick joystick1;
public Joystick joystick2;
private GameObject[] fans;
private float fan_speed_incrementer;
private bool drone_started=false;
private Vector3 initial_drone_position;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
fan_speed_incrementer = fan_speed;
initial_drone_position = transform.position;
}
// Update is called once per frame
void FixedUpdate()
{
if (drone_started)
{
if (fan_speed_incrementer < 1997f)
{
fan_speed_incrementer += 3;
}
else
{
DroneControls();
}
}
else
{
if (fan_speed_incrementer >= 0)
{
fan_speed_incrementer -= 3;
}
}
RotateFans(fan_speed_incrementer);
transform.rotation=Quaternion.identity;
}
public void ResetDrone() {
transform.position = initial_drone_position;
transform.rotation = Quaternion.identity;
drone_started = false;
}
public void ToggleOn()
{
drone_started = true;
}
public void ToggleOff()
{
drone_started = false;
}
void DroneControls() {
if(joystick1.Vertical>=0.2f)
{
rb.AddForce(transform.forward * horizontal_force);
}
if (joystick1.Vertical <= -0.2f)
{
rb.AddForce(-transform.forward * horizontal_force);
}
if (joystick1.Horizontal >= 0.2f)
{
rb.AddForce(transform.right * horizontal_force);
}
if (joystick1.Horizontal <= -0.2f)
{
rb.AddForce(-transform.right * horizontal_force);
}
if (joystick2.Vertical >= 0.2f)
{
rb.AddForce(transform.up * vertical_force);
}
if (joystick2.Vertical <= -0.2f)
{
rb.AddForce(-transform.up * vertical_force);
}
}
void RotateFans(float speed) {
fans = GameObject.FindGameObjectsWithTag("RotateFan");
foreach (GameObject fan in fans)
{
fan.transform.Rotate(Vector3.up, speed * Time.deltaTime);
}
}
}
<file_sep>/FYP/CreatingProjAssets/Assets/PracticeAssets(Not Important)/EnemyBehaviour.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemyBehaviour : MonoBehaviour
{
/*
[SerializeField]
GameObject healthFillBar;
RectTransform healthRect;
float yComponent = 0f;
float origionalHealth = 100;
float updatedHealth;
int hitRecieved = 0;
float healthX, healthPosX;
*/
Animator anim;
bool isColliding = false;
// Start is called before the first frame update
void Start()
{
anim = gameObject.GetComponent<Animator>();
/*
healthRect = healthFillBar.GetComponent<RectTransform>();
updatedHealth = origionalHealth;
healthX = healthRect.sizeDelta.x;
healthPosX = healthRect.anchoredPosition.x;
*/
}
// Update is called once per frame
void Update()
{
if (anim.GetInteger("HitReactionValue") == 1 && !isColliding) {
/*
Debug.Log("HitCollider");
updatedHealth -= 10f;
healthRect.sizeDelta = new Vector2(healthX * (updatedHealth / origionalHealth), healthRect.sizeDelta.y);
float x = (healthX -(healthX * (updatedHealth / origionalHealth))) / 2;
healthRect.anchoredPosition= new Vector2(healthPosX-x, healthRect.anchoredPosition.y);
*/
isColliding = true;
}
}
void OnTriggerEnter(Collider collider)
{
if (collider.gameObject.tag.Equals("HitCollider"))
{
anim.SetInteger("HitReactionValue", 1);
StartCoroutine(backToIdleAnim());
}
}
//private void OnTriggerExit(Collider collider){}
IEnumerator backToIdleAnim() {
yield return new WaitForSeconds(1);
anim.SetInteger("HitReactionValue", 0);
isColliding = false;
}
}
<file_sep>/FYP/CreatingProjAssets/Assets/PracticeAssets(Not Important)/CustomNetworkManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class CustomNetworkManager : NetworkManager
{
GameObject panel1, panel2;
void Start()
{
panel1 = GameObject.FindGameObjectWithTag("Panel1").transform.GetChild(0).gameObject;
panel2 = GameObject.FindGameObjectWithTag("Panel2").transform.GetChild(0).gameObject;
}
public void startHosting() {
panel1.SetActive(false);
panel2.SetActive(true);
base.StartHost();
}
}
<file_sep>/FYP/CreatingProjAssets/Assets/ARFightingGame/Scripts/NetworkPlayer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class HealthBarStuff
{
RectTransform healthRect;
float origionalHealth = 100;
public float updatedHealth;
int hitRecieved = 0;
float healthX, healthPosX;
public float healthReductionFactor = 10f;
public void initializeObjects(GameObject healthFillBar)
{
healthRect = healthFillBar.GetComponent<RectTransform>();
updatedHealth = origionalHealth;
healthX = healthRect.sizeDelta.x;
healthPosX = healthRect.anchoredPosition.x;
}
public void updateHealthStatus()
{
updatedHealth -= healthReductionFactor;
healthRect.sizeDelta = new Vector2(healthX * (updatedHealth / origionalHealth), healthRect.sizeDelta.y);
float x = (healthX - (healthX * (updatedHealth / origionalHealth))) / 2;
healthRect.anchoredPosition = new Vector2(healthPosX - x, healthRect.anchoredPosition.y);
}
public void resetHealth()
{
updatedHealth = origionalHealth;
healthRect.sizeDelta = new Vector2(healthX, healthRect.sizeDelta.y);
healthRect.anchoredPosition = new Vector2(healthPosX, healthRect.anchoredPosition.y);
}
}
public class NetworkPlayer : CaptainsMessPlayer
{
Animator animator;
[SerializeField]
float turnSpeed = 1.5f;
[SerializeField]
float moveSpeed = 0.2f;
FixedJoystick joystick;
[SerializeField]
float actionWaitTime = 0.5f;
UserHUDControls userHudControls;
UIControls UIControls;
bool isColliding = false;
GameObject playerInfoObject;
Text readyField;
GameObject[] playerSpawnPos=new GameObject[2];
GameObject playerHealthFillBar, enemyHealthFillBar;
public HealthBarStuff playerHealth, enemyHealth;
[SerializeField]
Material indicatorMat1;
[SerializeField]
Material indicatorMat2;
int animMin, animMax;
/// <summary>
/// new stuff
/// </summary>
[SyncVar]
public bool enemyIsAttacking = false;
public bool endReactionCompleted = false;
public bool winner = false;
public int score = 0;
/// <summary>
/// new stuff
/// </summary>
void Awake()
{
UIControls = GameObject.Find("UIControls").GetComponent<UIControls>();
}
// Start is called before the first frame update
void Start()
{
joystick = GameObject.Find("GameplayMenu").transform.GetChild(0).GetChild(3).GetComponent<FixedJoystick>();
animator = GetComponent<Animator>();
userHudControls = GameObject.Find("UserHUDControls").GetComponent<UserHUDControls>();
playerHealth = new HealthBarStuff();
enemyHealth = new HealthBarStuff();
playerHealthFillBar = GameObject.Find("GameplayMenu").transform.GetChild(0).GetChild(4).GetChild(1).gameObject;
playerHealth.initializeObjects(playerHealthFillBar);
enemyHealthFillBar = GameObject.Find("GameplayMenu").transform.GetChild(0).GetChild(5).GetChild(1).gameObject;
enemyHealth.initializeObjects(enemyHealthFillBar);
if (isLocalPlayer)
{
transform.Find("Indicator").gameObject.GetComponent<MeshRenderer>().material = indicatorMat1;
}
else
{
transform.Find("Indicator").gameObject.GetComponent<MeshRenderer>().material = indicatorMat2;
}
playerSpawnPos[0] = GameObject.FindGameObjectWithTag("SpawnPos1").gameObject;
playerSpawnPos[1] = GameObject.FindGameObjectWithTag("SpawnPos2").gameObject;
}
public override void OnStartLocalPlayer()
{
animationSelector();
transform.GetChild(0).gameObject.SetActive(false);
transform.GetChild(2).gameObject.SetActive(false);
gameObject.GetComponent<CapsuleCollider>().enabled = false;
//transform.SetParent(GameObject.FindGameObjectWithTag("FightGround").transform);
//CmdSetPlayerPos();
base.OnStartLocalPlayer();
}
public override void OnStartClient()
{
GameObject.Find("GameSession").GetComponent<GameSession>().addPlayerToList(this);
transform.GetChild(0).gameObject.SetActive(false);
transform.GetChild(2).gameObject.SetActive(false);
gameObject.GetComponent<CapsuleCollider>().enabled = false;
//transform.SetParent(GameObject.FindGameObjectWithTag("FightGround").transform);
//CmdSetPlayerPos();
base.OnStartClient();
}
// Update is called once per frame
void FixedUpdate()
{
if (!isLocalPlayer)
{
return;
}
NetworkGameSession gameSession = NetworkGameSession.instance;
if (gameSession)
{
if (gameSession.gameState == GameState.Lobby ||
gameSession.gameState == GameState.Countdown)
{
UIControls.readybtnVisible(true);
if (UIControls.ReadyBtnClicked)
{
if (IsReady())
{
UIControls.readyBtnTextString = "Ready";
SendNotReadyToBeginMessage();
readyField.text = "Not Ready";
readyField.color = Color.red;
}
else
{
UIControls.readyBtnTextString = "Not Ready";
SendReadyToBeginMessage();
readyField.text = "Ready";
readyField.color = Color.green;
}
UIControls.ReadyBtnClicked = false;
}
}
else if (gameSession.gameState == GameState.GameOver)
{
if (isServer)
{
// CmdPlayAgain();
}
}
else
{
UIControls.readybtnVisible(false);
}
}
move();
punch();
block();
kick();
hitRecieveReaction();
}
void move() {
Vector2 movementInput = new Vector2(joystick.Horizontal, joystick.Vertical);
Vector3 forward = Camera.main.transform.forward;
Vector3 right = Camera.main.transform.right;
forward.y = 0;
right.y = 0;
forward.Normalize();
right.Normalize();
Vector3 desiredMoveDirection = (forward * movementInput.y + right * movementInput.x);
animator.SetFloat("Move", desiredMoveDirection.magnitude);
transform.position = transform.position + desiredMoveDirection * Time.deltaTime * moveSpeed;
if (desiredMoveDirection != Vector3.zero)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(desiredMoveDirection), turnSpeed);
}
}
void punch() {
if (userHudControls.punched) {
int value = Random.Range(animMin, animMax);
animator.SetInteger("PunchValue", value);
StartCoroutine(backToIdleAnim("PunchValue"));
Debug.Log("Punched");
userHudControls.punched = false;
}
}
void kick(){
if (userHudControls.kicked)
{
int value = Random.Range(animMin, animMax);
animator.SetInteger("KickValue", value);
StartCoroutine(backToIdleAnim("KickValue"));
Debug.Log("kicked");
userHudControls.kicked = false;
}
}
void block() {
if (userHudControls.blocked)
{
int value = Random.Range(1, 2);
animator.SetInteger("BlockValue", value);
StartCoroutine(backToIdleAnim("BlockValue"));
Debug.Log("Blocked");
userHudControls.blocked = false;
}
}
void hitRecieveReaction() {
if ((animator.GetInteger("HitReactionValue") == 1 || animator.GetInteger("EndReactionValue") == 1) && !isColliding)
{
playerHealth.updateHealthStatus();
CmdUpdateEnemyHealth();
isColliding = true;
}
}
public void EndReaction() {
Debug.Log("Celebration started");
animator.SetInteger("EndReactionValue", 2);
StartCoroutine(backToIdleAnim("EndReactionValue"));
}
void animationSelector() {
if (UIControls.playerClass == 0)
{
animMin = 1;
animMax = 4;
}
else if (UIControls.playerClass == 1)
{
animMin = 3;
animMax = 6;
}
else if (UIControls.playerClass == 2)
{
animMin = 5;
animMax = 8;
}
else if (UIControls.playerClass == 3)
{
animMin = 7;
animMax = 10;
}
}
void OnTriggerEnter(Collider collider)
{
if (collider.gameObject.tag.Equals("HitCollider") )
{
if (playerHealth.updatedHealth != playerHealth.healthReductionFactor)
{
animator.SetInteger("HitReactionValue", 1);
StartCoroutine(backToIdleAnim("HitReactionValue"));
}
else
{
animator.SetInteger("EndReactionValue", 1);
}
}
}
IEnumerator backToIdleAnim(string value)
{
yield return new WaitForSeconds(actionWaitTime);
animator.SetInteger(value, 0);
isColliding = false;
if (value.Equals("HitReactionValue"))
{
enemyIsAttacking = false;
}
if (value.Equals("EndReactionValue"))
{
yield return new WaitForSeconds(actionWaitTime);
endReactionCompleted = true;
}
}
[Command]
public void CmdPlayAgain()
{
NetworkGameSession.instance.PlayAgain();
}
public override void OnClientEnterLobby()
{
base.OnClientEnterLobby();
Invoke("ShowPlayer", 0.5f);
}
public override void OnClientReady(bool readyState)
{
if (readyField != null) {
if (readyState)
{
readyField.text = "Ready";
readyField.color = Color.green;
}
else
{
readyField.text = "Not Ready";
readyField.color = Color.red;
}
}
}
void ShowPlayer()
{
SpawnObj();
OnClientReady(IsReady());
}
public void SpawnObj() {
playerInfoObject = UIControls.createPlayersInfo();
NetworkServer.Spawn(playerInfoObject);
readyField = playerInfoObject.transform.GetChild(0).GetChild(1).GetChild(0).GetComponent<Text>();
playerInfoObject.transform.GetChild(0).GetChild(0).GetChild(0).GetComponent<Text>().text = deviceName;
}
[Command]
public void CmdUpdateEnemyHealth()
{
RpcUpdateEnemyHealth();
}
[ClientRpc]
public void RpcUpdateEnemyHealth()
{
if (!isLocalPlayer)
{
enemyHealth.updateHealthStatus();
}
}
[ClientRpc]
public void RpcOnStartedGame()
{
transform.GetChild(0).gameObject.SetActive(true);
transform.GetChild(2).gameObject.SetActive(true);
GetComponent<CapsuleCollider>().enabled = true;
}
/*
[Command]
void CmdSetPlayerPos()
{
playerSpawnPos1 = GameObject.Find("PlayerSpawnPos1");
playerSpawnPos2 = GameObject.Find("PlayerSpawnPos2");
if (isServer)
{
transform.position = playerSpawnPos2.transform.position;
transform.rotation = playerSpawnPos2.transform.rotation;
}
else if (isClient)
{
transform.position = playerSpawnPos1.transform.position;
transform.rotation = playerSpawnPos1.transform.rotation;
}
}
*/
public override void OnClientExitLobby()
{
base.OnClientExitLobby();
//NetworkServer.Destroy(playerInfoObject);
}
//// new stuff
public bool playAgain;
[Command]
public void CmdSendReplayInfo(bool x)
{
RpcSendReplayInfo(x);
}
[ClientRpc]
public void RpcSendReplayInfo(bool x)
{
playAgain = x;
}
public float myPlayerHealth;
[Command]
public void CmdSendHealthInfo(float x)
{
RpcSendHealthInfo(x);
}
[ClientRpc]
public void RpcSendHealthInfo(float x)
{
myPlayerHealth = x;
}
[Command]
public void CmdResetPlay(int spawnPosIndex)
{
RpcResetPlay(spawnPosIndex);
}
[ClientRpc]
public void RpcResetPlay(int spawnPosIndex)
{
if (isLocalPlayer)
{
playerHealth.resetHealth();
}
else
{
enemyHealth.resetHealth();
}
gameObject.transform.position = playerSpawnPos[spawnPosIndex].transform.position;
gameObject.transform.rotation = playerSpawnPos[spawnPosIndex].transform.rotation;
animator.SetInteger("EndReactionValue", 0);
}
[Command]
public void CmdShowHidePlayer(bool x) {
RpcShowHidePlayer(x);
}
[ClientRpc]
public void RpcShowHidePlayer(bool x)
{
transform.GetChild(0).gameObject.SetActive(x);
transform.GetChild(2).gameObject.SetActive(x);
gameObject.GetComponent<CapsuleCollider>().enabled = x;
}
///// new stuff
}
<file_sep>/FYP/CreatingProjAssets/Assets/ARFightingGame/Scripts/NetworkControls.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class NetworkControls : MonoBehaviour
{
private CaptainsMess mess;
private CaptainsMessNetworkManager networkManager;
private UIControls UIControls;
public string button3Text;
GameSession gameSess;
public void Awake()
{
mess = FindObjectOfType(typeof(CaptainsMess)) as CaptainsMess;
networkManager = GetComponent<CaptainsMessNetworkManager>();
UIControls = GameObject.Find("UIControls").GetComponent<UIControls>();
}
void Update() {
if (GameObject.Find("GameSession") != null)
{
gameSess = GameObject.Find("GameSession").GetComponent<GameSession>();
}
NetworkDebugString();
peformNetworkOperation_Btn3();
startHost_btn1();
Join_btn2();
}
public string NetworkDebugString()
{
string serverString = "[SERVER] | ";
if (NetworkServer.active && networkManager.numPlayers > 0)
{
//serverString += "Hosting at " + + "\n";
serverString += string.Format("Players Ready = {0}/{1}", networkManager.NumReadyPlayers(), networkManager.NumPlayers()) + " | ";
}
if (networkManager.discoveryServer.running && networkManager.discoveryServer.isServer)
{
serverString += "Broadcasting: " + networkManager.discoveryServer.broadcastData + " | ";
}
string clientString = "[CLIENT] | ";
if (networkManager.IsClientConnected())
{
clientString += "Connected to server: " + networkManager.client.connection.address + " | ";
}
if (networkManager.discoveryClient.running && networkManager.discoveryClient.isClient)
{
// Discovered servers
clientString += "Discovered servers =";
foreach (DiscoveredServer server in networkManager.discoveryClient.discoveredServers.Values)
{
bool isMe = (server.peerId == networkManager.peerId);
clientString += " | - ";
if (isMe)
{
clientString += "(me) ";
}
clientString += server.ipAddress + " : " + server.rawData;
}
clientString += " | ";
// Received broadcasts
clientString += "Received broadcasts =";
foreach (var entry in networkManager.discoveryClient.receivedBroadcastLog)
{
clientString += " | " + entry;
}
clientString += " | ";
}
return serverString + " | " + clientString;
}
void peformNetworkOperation_Btn3()
{
if (UIControls.Btn3Clicked)
{
if (networkManager.IsConnected())
{
button3Text = "Disconnect";
gameSess.players.Clear();
mess.Cancel();
UIControls.ResetMainMenu();
networkManager.StopHost(); }
else if (networkManager.IsBroadcasting() || networkManager.IsJoining())
{
button3Text = "Cancel";
gameSess.players.Clear();
UIControls.ResetMainMenu();
mess.Cancel();
}
else
{
button3Text = "Auto Connect";
mess.AutoConnect();
}
UIControls.Btn3Clicked = false;
}
else {
if (networkManager.IsConnected())
{
button3Text = "Disconnect";
}
else if (networkManager.IsBroadcasting() || networkManager.IsJoining())
{
button3Text = "Cancel";
}
else
{
button3Text = "Auto Connect";
}
}
}
void startHost_btn1() {
if (UIControls.Btn1Clicked)
{
mess.StartHosting();
UIControls.Btn1Clicked = false;
}
}
void Join_btn2()
{
if (UIControls.Btn2Clicked)
{
mess.StartJoining();
UIControls.Btn2Clicked = false;
}
}
}
<file_sep>/FYP/CreatingProjAssets/Assets/ARFightingGame/Scripts/UIControls.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIControls : MonoBehaviour
{
public bool Btn1Clicked = false;
public bool Btn2Clicked = false;
public bool Btn3Clicked = false;
public bool ReadyBtnClicked = false;
NetworkControls netCtrl;
NetworkPlayer netPlayer;
[SerializeField]
GameObject netDebugString;
Text strVal;
[SerializeField]
Button btn1;
[SerializeField]
Button btn2;
[SerializeField]
Button btn3;
[SerializeField]
Button backBtn;
[SerializeField]
Button readyBtn;
[SerializeField]
Button[] charBtn = new Button[4];
Text readyBtnText;
public string readyBtnTextString;
[SerializeField]
public GameObject playerMatchPrefab;
public Transform prefabContainer;
[SerializeField]
GameObject TitleMenu;
[SerializeField]
GameObject ARCoreMenu;
[SerializeField]
GameObject startMenu;
[SerializeField]
GameObject mainMenu;
public int playerClass = 0;
CaptainsMessNetworkManager mgr;
GameSession gameSess;
void Start()
{
TitleMenu.SetActive(true);
ARCoreMenu.SetActive(false);
startMenu.SetActive(false);
mainMenu.SetActive(false);
mgr = GameObject.Find("CaptainsMessNetworkManager").GetComponent<CaptainsMessNetworkManager>();
netCtrl = GameObject.FindGameObjectWithTag("NetMgr").GetComponent<NetworkControls>();
strVal = netDebugString.GetComponent<Text>();
readyBtnText = readyBtn.transform.GetChild(0).GetComponent<Text>();
readyBtn.gameObject.SetActive(false);
readyBtnTextString = "Ready";
prefabContainer = GameObject.Find("MainMenu").transform.GetChild(0).GetChild(2).transform;
toggleOnOffButtons(0);
}
void Update()
{
if (GameObject.Find("GameSession") != null) {
gameSess = GameObject.Find("GameSession").GetComponent<GameSession>();
}
strVal.text = netCtrl.NetworkDebugString();
btn3.transform.GetChild(0).GetComponent<Text>().text = netCtrl.button3Text;
readyBtnText.text = readyBtnTextString;
if (GameObject.FindObjectOfType<NetworkGameSession>()==null)
{
Transform gameplayPanel = GameObject.Find("GameplayMenu").transform.GetChild(0);
if (gameplayPanel.gameObject.activeInHierarchy && !gameSess.gameFinished)
{
gameplayPanel.GetChild(9).gameObject.SetActive(true);
}
}
}
public GameObject createPlayersInfo() {
return Instantiate(playerMatchPrefab, prefabContainer);
}
public void ResetMainMenu() {
mainMenu.SetActive(true);
btn1.interactable = true;
btn2.interactable = true;
btn3.interactable = true;
backBtn.interactable = true;
readyBtn.gameObject.SetActive(false);
readyBtnTextString = "Ready";
for (int i = 0; i < prefabContainer.childCount; i++) {
Destroy(prefabContainer.GetChild(i).gameObject);
}
}
public void btn1Action()
{
Btn1Clicked = true;
btn1.interactable = false;
btn2.interactable = false;
backBtn.interactable = false;
}
public void btn2Action()
{
Btn2Clicked = true;
btn1.interactable = false;
btn2.interactable = false;
backBtn.interactable = false;
}
public void btn3Action()
{
if (netCtrl.button3Text.Equals("Auto Connect"))
{
btn1.interactable = false;
btn2.interactable = false;
backBtn.interactable = false;
}
else {
btn1.interactable = true;
btn2.interactable = true;
backBtn.interactable = true;
mgr.spawnLocationCounter = 0;
}
Btn3Clicked = true;
}
void toggleOnOffButtons(int index) {
for (int i = 0; i < charBtn.Length; i++)
{
if (i == index)
{
charBtn[i].interactable = false;
}
else
{
charBtn[i].interactable = true;
}
}
}
public void selectCharacter1()
{
toggleOnOffButtons(0);
playerClass = 0;
}
public void selectCharacter2()
{
toggleOnOffButtons(1);
playerClass = 1;
}
public void selectCharacter3()
{
toggleOnOffButtons(2);
playerClass = 2;
}
public void selectCharacter4()
{
toggleOnOffButtons(3);
playerClass = 3;
}
public void TitleMenuStartBtnAction()
{
TitleMenu.SetActive(false);
ARCoreMenu.SetActive(true);
startMenu.SetActive(false);
mainMenu.SetActive(false);
}
public void ARCoreMenuProceedBtnAction()
{
TitleMenu.SetActive(false);
ARCoreMenu.SetActive(false);
startMenu.SetActive(true);
mainMenu.SetActive(false);
}
public void proceedBtnAction() {
TitleMenu.SetActive(false);
ARCoreMenu.SetActive(false);
startMenu.SetActive(false);
mainMenu.SetActive(true);
}
public void backBtnAction()
{
TitleMenu.SetActive(false);
ARCoreMenu.SetActive(false);
startMenu.SetActive(true);
mainMenu.SetActive(false);
}
public void backToARCoreMenuBtnAction()
{
TitleMenu.SetActive(false);
ARCoreMenu.SetActive(true);
startMenu.SetActive(false);
mainMenu.SetActive(false);
}
public void backToTitleMenu()
{
TitleMenu.SetActive(true);
ARCoreMenu.SetActive(false);
startMenu.SetActive(false);
mainMenu.SetActive(false);
}
public void readybtnAction()
{
ReadyBtnClicked = true;
}
public void readybtnVisible(bool value)
{
readyBtn.gameObject.SetActive(value);
}
public void Quit()
{
Application.Quit();
}
}<file_sep>/FYP/CreatingProjAssets/Assets/ARFightingGame/Scripts/UserHUDControls.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class UserHUDControls : MonoBehaviour
{
public bool punched = false;
public bool kicked = false;
public bool blocked = false;
[SerializeField]
GameObject gamePlayPanel1;
[SerializeField]
GameObject gamePlayPanel2;
[SerializeField]
GameObject gamePlayPanel3;
[SerializeField]
GameObject gamePlayMenu;
CaptainsMessNetworkManager mgr;
UIControls uicontrols;
GameSession gameSess;
void Start()
{
mgr = GameObject.Find("CaptainsMessNetworkManager").GetComponent<CaptainsMessNetworkManager>();
uicontrols = GameObject.Find("UIControls").GetComponent<UIControls>();
gamePlayPanel1.SetActive(false);
gamePlayPanel2.SetActive(false);
gamePlayPanel3.SetActive(false);
}
void Update()
{
if (GameObject.Find("GameSession") != null)
{
gameSess = GameObject.Find("GameSession").GetComponent<GameSession>();
}
}
public void punchButton() {
punched = true;
}
public void kickButton()
{
kicked = true;
}
public void blockButton()
{
blocked = true;
}
public void GamePlayQuit() {
gamePlayPanel1.SetActive(true);
gamePlayPanel2.SetActive(false);
gamePlayPanel3.SetActive(false);
}
public void QuitYes()
{
gameSess.resetGame();
gameSess.players.Clear();
gamePlayPanel1.SetActive(false);
gamePlayPanel2.SetActive(false);
gamePlayPanel3.SetActive(false);
gamePlayMenu.SetActive(false);
mgr.Cancel();
uicontrols.ResetMainMenu();
mgr.spawnLocationCounter = 0;
}
public void QuitNo()
{
gamePlayPanel1.SetActive(false);
gamePlayPanel2.SetActive(false);
gamePlayPanel3.SetActive(false);
}
public void Leave() {
gameSess.resetGame();
gameSess.players.Clear();
gamePlayPanel1.SetActive(false);
gamePlayPanel2.SetActive(false);
gamePlayPanel3.SetActive(false);
gamePlayMenu.SetActive(false);
mgr.Cancel();
uicontrols.ResetMainMenu();
mgr.spawnLocationCounter = 0;
}
public void PlayAgain() {
gamePlayPanel1.SetActive(false);
gamePlayPanel2.SetActive(false);
gamePlayPanel3.SetActive(false);
}
IEnumerator checkForRemainingPlayerObjects() {
yield return new WaitForSeconds(2);
List<NetworkPlayer> players = new List<NetworkPlayer>();
players.AddRange(GameObject.FindObjectsOfType<NetworkPlayer>());
if (players[0].gameObject != null)
{
NetworkServer.Destroy(players[0].gameObject);
}
if (players[1].gameObject != null)
{
NetworkServer.Destroy(players[1].gameObject);
}
players.Clear();
}
}
|
c57762459cc765af82020ee8756ab703f2867bcf
|
[
"C#"
] | 10
|
C#
|
haideraza/fyp-project
|
f8357d8d44585d55b3b782c14a8ab68568a6a2f0
|
54638a71d7eaf709148286f96bb1f94b26ba1739
|
refs/heads/master
|
<repo_name>masato-ka/GroupingMember<file_sep>/app.py
# -*- coding: utf-8 -*-
import os
import random
import json
from flask import Flask, render_template, request, make_response
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', name=None)
@app.route('/grouping/', methods=['POST', 'GET'])
def proc_post_request():
'''
dispatch RPC request
'''
if request.method == 'POST':
total = request.form['total']
group = request.form['group']
result = grouping(total, group)
res = make_response(result)
res.headers['Cache-Control'] = 'no-cache'
return res
else:
return 'Please PSOT Method'
def grouping(total, group):
'''
全体の人数とグループ数から各グループの数を求める
各グループにランダムに人数を配置する。
'''
try:
number_total = int(total)
number_group = int(group)
except:
return None
number_per_group = number_total / number_group
odd = number_total % number_group
if odd > 0:
number_per_group += 1
persons = range(1, number_total + 1)
groups = range(1, number_group + 1)
# create group
group_dic = {}
for group in groups:
group_dic["%s" % group] = []
random.shuffle(persons)
for key in group_dic.keys():
for enumrate in range(0, number_per_group):
group_dic[key].append('%s番さん' % persons.pop())
if len(persons) == 0:
break
# encode json?
return json.dumps(group_dic)
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
<file_sep>/README.rst
README
======
1. 内容
-------
人数と作りたいチーム数からグループ分けを行う
iPhone向けのWEBアプリケーションです。
雑な作りなのでエラー処理とか適当です。0徐算
とか余裕で発生していろいろとアレです。
2. 動作環境
------------
Heroku アプリケーションになっているので、
Herokuにデプロイしてください。
|
895932f816511b9278046727ce72bcada20c0bcc
|
[
"Python",
"reStructuredText"
] | 2
|
Python
|
masato-ka/GroupingMember
|
7a9ccfeb197feab0b0bc2829ad2fda62b8647124
|
b0deb233f656195a469d0490a39d8ed409e92b6c
|
refs/heads/master
|
<file_sep>-------------------------------------------------------------------------------
--[[LICENSE]]--
-------------------------------------------------------------------------------
-- This is free and unencumbered software released into the public domain.
--
-- Anyone is free to copy, modify, publish, use, compile, sell, or
-- distribute this software, either in source code form or as a compiled
-- binary, for any purpose, commercial or non-commercial, and by any
-- means.
--
-- In jurisdictions that recognize copyright laws, the author or authors
-- of this software dedicate any and all copyright interest in the
-- software to the public domain. We make this dedication for the benefit
-- of the public at large and to the detriment of our heirs and
-- successors. We intend this dedication to be an overt act of
-- relinquishment in perpetuity of all present and future rights to this
-- software under copyright law.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-- IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
-- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-- OTHER DEALINGS IN THE SOFTWARE.
--
-- For more information, please refer to <http://unlicense.org/>
--]]
-------------------------------------------------------------------------------
--[[.luacheckrc]]-- Current Factorio Version .15.3
-------------------------------------------------------------------------------
--Ignore some warnings in .luacheckrc
files['.luacheckrc'] = {
std = "lua52c",
global = false, --Turn of global warnings for this file
max_line_length = false, --turn of line length warnings for this file
--ignore = {"stdlib_ignore_list"},
}
--List of files and directories to exclude
exclude_files = {"**/.mods.*/", "**/.SOURCE/factorio**", "**/.build/", "**/build/", "**/.legacy/", "**/.script-output/*"}
--These globals are not available to the factorio API
not_globals = {"coroutine", "io", "socket"}
-- require("") can be used to require additional luacheck files
-- however LUA_PATH enviroment variable must be
-- declared and required file must reside in path
-------------------------------------------------------------------------------
--[[Set Defaults]]--
-------------------------------------------------------------------------------
-- lua52c -- Lua version 5.2 standard globals
-- factorio -- Factorio globals used in data and control stages
-- factorio_control -- Factorio globals used in the control stage only
-- factorio_data -- Factorio globals used in the data stage only
-- factorio_defines -- Factorio global defines used in both stages.
-- stdlib -- stdlib globals used in data and control stages
-- stdlib_control -- stdlib globals used in control stage only
-- stdlib_data -- stdlib globals used in the data stage only
-- Line length to use
local LINE_LENGTH = 200
-- Uncomment to ignore stdlib errors
--stdlib_ignore_list = {"0..", "1..", "2..", "3..", "4..", "5..", "6..", "7..", "8..", "9..", "fail_if_missing"}
--Set default linting rules to check control stage
std = "lua52c+factorio+factorio_control+stdlib+stdlib_control+factorio_defines"
max_line_length = LINE_LENGTH
-------------------------------------------------------------------------------
--[[Factorio STDLIB Busted]]--
-------------------------------------------------------------------------------
files['**/spec/**'] = {
std = "lua52c+busted+stdlib_busted+factorio_defines+factorio_control+stdlib_control+stdlib",
--ignore = {"0..", "1..", "2..", "3..", "4..", "5..", "6..", "7..", "8..", "9..", "fail_if_missing"}
}
stds.stdlib_busted = {
globals = {
"Event", "Gui", "Config", "Logger", "Area", "Position", "Tile", "Chunk", "Data",
"Recipe", "Color", "Entity", "Inventory", "Trains", "Core", "Game", "Surface",
"Time",
},
--other_globals = {"data", "control", "test_function", "game", "train", "entity"}
}
-------------------------------------------------------------------------------
--[[Prototypes]]--
-------------------------------------------------------------------------------
--Set prototype files
prototypes = "lua52c+factorio+factorio_data+stdlib+stdlib_data+factorio_defines"
files['**/data.lua'].std = prototypes
files['**/data-updates.lua'].std = prototypes
files['**/data-final-fixes.lua'].std = prototypes
files['**/settings.lua'].std = prototypes
files['**/settings-updates.lua'].std = prototypes
files['**/settings-final-fixes.lua'].std = prototypes
files['**/prototypes/'].std = prototypes
files['**/settings/'].std = prototypes
-------------------------------------------------------------------------------
--[[Set STDLIB modules]]--
-------------------------------------------------------------------------------
-- Defaults to use for stdlib
std_stdlib_control = {
std = "lua52c+factorio+factorio_control+stdlib+stdlib_control+factorio_defines",
max_line_length = stdlib_ignore_list and 400 or LINE_LENGTH,
ignore = stdlib_ignore_list or nil,
}
-- Allow mutating table and string,
-- Disallow factorio/stdlib as these are non specific additional helpers
std_stdlib_table_string = {
std = "lua52c+stdlib_overrides",
max_line_length = stdlib_ignore_list and 400 or LINE_LENGTH,
ignore = stdlib_ignore_list and {"14.", "432"} or nil,
}
std_stdlib_data = {
std = "lua52c+factorio+factorio_data+stdlib+stdlib_data+factorio_defines",
max_line_length = stdlib_ignore_list and 400 or LINE_LENGTH,
ignore = stdlib_ignore_list or nil,
}
files["**/stdlib/table.lua"] = std_stdlib_table_string
files["**/stdlib/string.lua"] = std_stdlib_table_string
files["**/stdlib/core.lua"] = std_stdlib_control
files["**/stdlib/game.lua"] = std_stdlib_control
files["**/stdlib/surface.lua"] = std_stdlib_control
files["**/stdlib/time.lua"] = std_stdlib_control
files["**/stdlib/utils/"] = std_stdlib_control
files["**/stdlib/area/"] = std_stdlib_control
files["**/stdlib/config/"] = std_stdlib_control
files["**/stdlib/entity/"] = std_stdlib_control
files["**/stdlib/event/"] = std_stdlib_control
files["**/stdlib/gui/"] = std_stdlib_control
files["**/stdlib/log/"] = std_stdlib_control
files["**/stdlib/trains/"] = std_stdlib_control
files["**/stdlib/data/"] = std_stdlib_data
-------------------------------------------------------------------------------
--[[STDS]]--
-------------------------------------------------------------------------------
-- All globals listed below
-------------------------------------------------------------------------------
--[[STDS.FACTORIO]]--
-------------------------------------------------------------------------------
--Used in both data and control stages
stds.factorio = {
--Set the read only variables
read_globals = {
-- @log@: Gives writing access to Factorio's logger instance.
"log",
-- @serpent@: Lua serializer and pretty printer. (https://github.com/pkulchenko/serpent)
"serpent",
},
}
stds.factorio_control = {
read_globals = {
-- @commands@:
commands = {
fields = {
"add_command",
"commands",
"game_commands",
},
},
-- @settings@:
settings = {
fields = {
"get_player_settings",
"startup",
"global",
"player",
},
},
-- @script@: Provides an interface for registering event handlers.
-- (http://lua-api.factorio.com/latest/LuaBootstrap.html)
script = {
fields = {
"on_event",
"on_configuration_changed",
"on_init",
"on_load",
"generate_event_name",
"raise_event",
"get_event_handler"
},
},
-- @remote@: Allows inter-mod communication by providing a repository of interfaces that is shared by all mods.
-- (http://lua-api.factorio.com/latest/LuaRemote.html)
remote = {
fields = {
"add_interface",
"remove_interface",
"call",
"interfaces"
},
},
-- @game@: Main object through which most of the API is accessed.
-- It is, however, not available inside handlers registered with @script.on_load@.
-- (http://lua-api.factorio.com/latest/LuaGameScript.html)
game ={
--other_fields = true,
--read_only = false,
fields = {
"set_game_state",
"get_entity_by_tag",
"show_message_dialog",
"disable_tips_and_tricks",
"is_demo",
"reload_script",
"save_atlas",
"check_consistency",
"regenerate_entity",
"take_screenshot",
"write_file",
"remove_path",
"remove_offline_players",
"force_crc",
"merge_forces",
"player",
"server_save",
"delete_surface",
"disable_replay",
"direction_to_string",
"print",
"tick",
"finished",
"difficulty",
speed = {
--rw
read_only = false,
},
player = {
--luaPlayer
--The player typing at the console, nil in all other cases
read_only = false,
other_fields = true,
},
players = {
--array of luaPlayer
read_only = false,
other_fields = true,
},
connected_players = {
--array of luaPlayer
read_only = false,
other_fields = true,
},
surfaces = {
--array of luaSurface
read_only = false,
other_fields = true,
},
create_surface = {
--luaSurface
read_only = false,
other_fields = true,
},
forces = {
--array of luaForce
read_only = false,
other_fields = true,
},
create_force = {
--luaForce
read_only = false,
other_fields = true,
},
entity_prototypes = {
--string dictionary - > luaEntityPrototype
read_only = true,
other_fields = true
},
item_prototypes = {
--string dictionary - > luaItemPrototype
read_only = true,
other_fields = true
},
fluid_prototypes = {
--string dictionary - > luaFluidPrototype
read_only = true,
other_fields = true
},
tile_prototypes = {
--string dictionary - > luaTilePrototype
read_only = true,
other_fields = true
},
equipment_prototypes = {
--string dictionary - > luaEquipmentPrototype
read_only = true,
other_fields = true
},
recipe_prototypes = {
--string dictionary - > luaRecipePrototype
read_only = true,
other_fields = true
},
technology_prototypes = {
--string dictionary - > luaTechnologyPrototype
read_only = true,
other_fields = true
},
damage_prototypes = {
--string dictionary - > luaDamagePrototype
read_only = true,
other_fields = true
},
virtual_signal_prototypes = {
--string dictionary - > luaVirtualSignalPrototype
read_only = true,
other_fields = true
},
equipment_grid_prototypes = {
--string dictionary - > luaEquipmentGridPrototype
read_only = true,
other_fields = true
},
map_settings = {
--custom -> mapsettings
read_only = false,
other_fields = true
},
active_mods = {
--string dictionary -> string version
read_only = true,
other_fields = true
}
},
},
util = {
other_fields = true
},
},
globals = {
-- @global@: The global dictionary, useful for storing data persistent across a save-load cycle.
-- Writing access is given to the mod-id field (for mod-wise saved data).
-- (http://lua-api.factorio.com/latest/Global.html)
"global",
-- @MOD@: Keep it organized, use this variable for anything that "NEEDS" to be global for some reason.
"MOD"
},
}
stds.factorio_data = {
read_globals = {
data = {
fields = {
raw = {
other_fields = true,
read_only = false
},
"extend"
},
},
settings = {
fields = {
"startup",
"global",
"player",
},
},
util = {
fields = {
"by_pixel",
"distance",
"findfirstentity",
"positiontostr",
"formattime",
"moveposition",
"oppositedirection",
"ismoduleavailable",
"multiplystripes",
"format_number",
"increment",
table = {
fields = {
"compare",
"deepcopy"
},
},
},
},
--Popular mods
angelsmods = {
other_fields = true
},
bobmods = {
other_fields = true
},
}
}
-------------------------------------------------------------------------------
--[[STDS.STDLIB]]--
-------------------------------------------------------------------------------
stds.stdlib = {
read_globals = {
-- Don't warn on mutated globals.
table = {
fields = {
"map",
"filter",
"find",
"any",
"each",
"flatten",
"first",
"last",
"min",
"max",
"sum",
"avg",
"merge",
"deepcopy",
"value",
"keys",
"remove_keys",
},
},
string = {
fields = {
"trim",
"starts_with",
"ends_with",
"contains",
"is_empty",
"split",
"pretty_number",
},
},
}
}
stds.stdlib_control = {
-- STDLIB globals
-- These need to be reworked in stdlib to not be globals.
globals = {
Event = {
other_fields = true,
fields = {
core_events = {
read_only = true,
other_fields = false,
fields = {
"init", "configuration_changed", "load", "_register"
},
},
},
},
Gui = {
--other_fields = true,
fields = {
on_click = {
read_only = true,
},
on_text_changed = {
read_only = true,
},
on_checked_state_changed = {
read_only = true,
}
},
},
"Config",
"Logger",
},
}
stds.stdlib_data = {
}
stds.stdlib_overrides = {
read_globals = {
table = {
other_fields = true,
read_only = false
},
string = {
other_fields = true,
read_only = false
}
}
}
-------------------------------------------------------------------------------
--[[STDS.DEFINES]]--
-------------------------------------------------------------------------------
-- Due to the size, these are at the bottom so I don't have to scroll through the
-- whole file to change something else
stds.factorio_defines = {
read_globals = {
-- @defines@:
defines = {
fields = {
events = {
fields = {
"on_biter_base_built", --Called when a biter migration builds a base.
"on_built_entity", --Called when player builds something.
"on_canceled_deconstruction", --Called when the deconstruction of an entity is canceled.
"on_chunk_generated", --Called when a chunk is generated.
"on_difficulty_settings_changed", --Called when the map difficulty settings are changed.
"on_entity_died", --Called when an entity dies.
"on_entity_renamed", --Called after an entity has been renamed either by the player or through script.
"on_entity_settings_pasted", --Called after entity copy-paste is done.
"on_force_created", --Called when a new force is created using game.create_force()
"on_forces_merging", --Called when two forces are merged using game.merge_forces().
"on_gui_checked_state_changed", --Called when LuaGuiElement checked state is changed (related to checkboxes and radio buttons)
"on_gui_click", --Called when LuaGuiElement is clicked.
"on_gui_elem_changed", --Called when LuaGuiElement element value is changed (related to choose element buttons)
"on_gui_selection_state_changed", --Called when LuaGuiElement selection state is changed (related to drop-downs)
"on_gui_text_changed", --Called when LuaGuiElement text is changed by the player
"on_marked_for_deconstruction", --Called when an entity is marked for deconstruction with the Deconstruction planner or via script.
"on_market_item_purchased", --Called after a player purchases some offer from a Market entity.
"on_picked_up_item", --Called when a player picks up an item.
"on_player_alt_selected_area", --Called after a player alt-selects an area with a selection-tool item.
"on_player_ammo_inventory_changed", --Called after a players ammo inventory changed in some way.
"on_player_armor_inventory_changed", --Called after a players armor inventory changed in some way.
"on_player_built_tile", --Called after a player builds tiles.
"on_player_changed_force", --Called after a player changes forces.
"on_player_changed_surface", --Called after a player changes surfaces.
"on_player_crafted_item", --Called when the player crafts an item (upon inserting into player's inventory, not clicking the button to craft).
"on_player_created", --Called after the player was created.
"on_player_cursor_stack_changed", --Called after a players cursorstack changed in some way.
"on_player_died", --Called after a player dies.
"on_player_driving_changed_state", --Called when the player's driving state has changed, this means a player has either entered or left a vehicle.
"on_player_dropped_item", --Called when a player drops an item on the ground.
"on_player_gun_inventory_changed", --Called after a players gun inventory changed in some way.
"on_player_joined_game", --Called after a player joins the game.
"on_player_left_game", --Called after a player leaves the game.
"on_player_main_inventory_changed", --Called after a players main inventory changed in some way.
"on_player_mined_entity", --Called after the results of an entity being mined are collected just before the entity is destroyed.
"on_player_mined_item", --Called when the player mines something.
"on_player_mined_tile", --Called after a player mines tiles.
"on_player_placed_equipment", --Called after the player puts equipment in an equipment grid
"on_player_quickbar_inventory_changed", --Called after a players quickbar inventory changed in some way.
"on_player_removed_equipment", --Called after the player removes equipment from an equipment grid
"on_player_respawned", --Called after a player respawns.
"on_player_rotated_entity", --Called when the player rotates an entity (including some non-obvious rotations such as with the stone furnace, but not the solar-panel).
"on_player_selected_area", --Called after a player selects an area with a selection-tool item.
"on_player_tool_inventory_changed", --Called after a players tool inventory changed in some way.
"on_pre_entity_settings_pasted", --Called before entity copy-paste is done.
"on_pre_player_died", --Called before a players dies.
"on_pre_surface_deleted", --Called just before a surface is deleted.
"on_preplayer_mined_item", --Called when the player finishes mining an entity, before the entity is removed from map.
"on_put_item", --Called when players uses item to build something.
"on_research_finished", --Called when a research finishes.
"on_research_started", --Called when a technology research starts.
"on_resource_depleted", --Called when a resource entity reaches 0 or its minimum yield for infinite resources.
"on_robot_built_entity", --Called when a construction robot builds an entity.
"on_robot_built_tile", --Called after a robot builds tiles.
"on_robot_mined", --Called when a robot mines an entity.
"on_robot_mined_entity", --Called after the results of an entity being mined are collected just before the entity is destroyed.
"on_robot_mined_tile", --Called after a robot mines tiles.
"on_robot_pre_mined", --Called before a robot mines an entity.
"on_rocket_launched", --Called when the rocket is launched.
"on_runtime_mod_setting_changed", --Called when a runtime mod setting is changed by a player.
"on_sector_scanned", --Called when the radar finishes scanning a sector.
"on_selected_entity_changed", --Called after the selected entity changes for a given player.
"on_surface_created", --Called when a surface is created.
"on_surface_deleted", --Called after a surface is deleted.
"on_tick", --It is fired once every tick.
"on_train_changed_state", --Called when a train changes state (started to stopped and vice versa)
"on_train_created", --Called when a new train is created either through disconnecting/connecting an existing one or building a new one.
"on_trigger_created_entity",
},
},
alert_type = {
fields = {
"custom",
"entity_destroyed",
"entity_under_attack",
"no_material_for_construction",
"no_storage",
"not_enough_construction_robots",
"not_enough_repair_packs",
"turret_fire",
},
},
chain_signal_state = {
fields = {
"all_open",
"none",
"none_open",
"partially_open",
},
},
chunk_generated_status = {
fields = {
"basic_tiles",
"corrected_tiles",
"custom_tiles",
"entities",
"nothing",
"tiles",
},
},
circuit_condition_index = {
fields = {
"arithmetic_combinator",
"constant_combinator",
"decider_combinator",
"inserter_circuit",
"inserter_logistic",
"lamp",
"offshore_pump",
"pump",
},
},
circuit_connector_id = {
fields = {
"accumulator",
"combinator_input",
"combinator_output",
"constant_combinator",
"container",
"electric_pole",
"inserter",
"lamp",
"offshore_pump",
"programmable_speaker",
"pump",
"rail_signal",
"roboport",
"storage_tank",
"wall",
},
},
command = {
fields = {
"attack",
"attack_area",
"build_base",
"compound",
"go_to_location",
"group",
"wander",
},
},
compound_command = {
fields = {
"logical_and",
"logical_or",
"return_last",
},
},
control_behavior = {
fields = {
inserter = {
fields = {
circuit_mode_of_operation = {
fields = {
"enable_disable",
"none",
"read_hand_contents",
"set_filters",
"set_stack_size",
},
},
hand_read_mode = {
fields = {
"hold",
"pulse",
}
},
},
},
lamp = {
fields = {
circuit_mode_of_operation = {
fields = {
"use_colors",
}
},
},
},
logistic_container = {
fields = {
circuit_mode_of_operation = {
fields = {
"send_contents",
"set_requests",
}
},
},
},
mining_drill = {
fields = {
resource_read_mode = {
fields = {
"entire_patch",
"this_miner",
}
},
},
},
roboport = {
fields = {
circuit_mode_of_operation = {
fields = {
"read_logistics",
"read_robot_stats",
}
},
},
},
train_stop = {
fields = {
circuit_mode_of_operation = {
fields = {
"enable_disable",
"read_from_train",
"send_to_train",
}
},
},
},
type = {
fields = {
"accumulator",
"arithmetic_combinator",
"constant_combinator",
"container",
"decider_combinator",
"generic_on_off",
"inserter",
"lamp",
"logistic_container",
"rail_signal",
"roboport",
"storage_tank",
"train_stop",
"transport_belt",
},
},
},
},
controllers = {
fields = {
"character",
"ghost",
"god",
},
},
deconstruction_item = {
fields = {
entity_filter_mode = {
fields = {
"blacklist",
"whitelist",
},
},
tile_filter_mode = {
fields = {
"always",
"never",
"normal",
"only",
}
},
},
},
difficulty = {
fields = {
"easy",
"hard",
"normal",
},
},
difficulty_settings = {
fields = {
recipe_difficulty = {
fields = {
"expensive",
"normal",
},
},
technology_difficulty = {
fields = {
"expensive",
"normal",
}
},
},
},
direction = {
fields = {
"east",
"north",
"northeast",
"northwest",
"south",
"southeast",
"southwest",
"west",
},
},
distraction = {
fields = {
"by_anything",
"by_damage",
"by_enemy",
"none",
},
},
group_state = {
fields = {
"attacking_distraction",
"attacking_target",
"finished",
"gathering",
"moving",
},
},
gui_type = {
fields = {
"achievement",
"blueprint_library",
"bonus",
"controller",
"entity",
"equipment",
"item",
"kills",
"logistic",
"none",
"other_player",
"permissions",
"production",
"research",
"trains",
"tutorials",
},
},
input_action = {
fields = {
"add_permission_group",
"alt_select_area",
"alt_select_blueprint_entities",
"begin_mining",
"begin_mining_terrain",
"build_item",
"build_rail",
"build_terrain",
"cancel_craft",
"cancel_deconstruct",
"cancel_new_blueprint",
"cancel_research",
"change_active_item_group_for_crafting",
"change_active_item_group_for_filters",
"change_active_quick_bar",
"change_arithmetic_combinator_parameters",
"change_blueprint_book_record_label",
"change_decider_combinator_parameters",
"change_item_label",
"change_picking_state",
"change_programmable_speaker_alert_parameters",
"change_programmable_speaker_circuit_parameters",
"change_programmable_speaker_parameters",
"change_riding_state",
"change_shooting_state",
"change_single_blueprint_record_label",
"change_train_stop_station",
"change_train_wait_condition",
"change_train_wait_condition_data",
"clean_cursor_stack",
"clear_blueprint",
"clear_selected_blueprint",
"clear_selected_deconstruction_item",
"connect_rolling_stock",
"copy_entity_settings",
"craft",
"craft_blueprint_record",
"create_blueprint_like",
"cursor_split",
"cursor_transfer",
"custom_input",
"cycle_blueprint_book_backwards",
"cycle_blueprint_book_forwards",
"deconstruct",
"delete_blueprint_record",
"delete_custom_tag",
"delete_permission_group",
"disconnect_rolling_stock",
"drop_blueprint_record",
"drop_item",
"drop_to_blueprint_book",
"edit_custom_tag",
"edit_permission_group",
"edit_train_schedule",
"export_blueprint",
"fast_entity_split",
"fast_entity_transfer",
"grab_blueprint_record",
"gui_checked_state_changed",
"gui_click",
"gui_elem_selected",
"gui_selection_state_changed",
"gui_text_changed",
"import_blueprint",
"import_blueprint_string",
"inventory_split",
"inventory_transfer",
"launch_rocket",
"market_offer",
"mod_settings_changed",
"open_achievements_gui",
"open_blueprint_library_gui",
"open_blueprint_record",
"open_bonus_gui",
"open_character_gui",
"open_equipment",
"open_gui",
"open_item",
"open_kills_gui",
"open_logistic_gui",
"open_production_gui",
"open_technology_gui",
"open_train_gui",
"open_train_station_gui",
"open_trains_gui",
"open_tutorials_gui",
"paste_entity_settings",
"place_equipment",
"remove_cables",
"reset_assembling_machine",
"reverse_rotate_entity",
"rotate_entity",
"select_area",
"select_blueprint_entities",
"select_entity_slot",
"select_gun",
"select_item",
"select_tile_slot",
"set_auto_launch_rocket",
"set_autosort_inventory",
"set_behavior_mode",
"set_blueprint_icon",
"set_circuit_condition",
"set_circuit_mode_of_operation",
"set_deconstruction_item_tile_selection_mode",
"set_deconstruction_item_trees_only",
"set_entity_color",
"set_entity_energy_property",
"set_filter",
"set_inserter_max_stack_size",
"set_inventory_bar",
"set_logistic_filter_item",
"set_logistic_filter_signal",
"set_logistic_trash_filter_item",
"set_research_finished_stops_game",
"set_signal",
"set_single_blueprint_record_icon",
"set_train_stopped",
"set_use_item_groups",
"setup_assembling_machine",
"setup_blueprint",
"setup_single_blueprint_record",
"shortcut_quick_bar_transfer",
"smart_pipette",
"stack_split",
"stack_transfer",
"start_repair",
"start_research",
"start_walking",
"switch_connect_to_logistic_network",
"switch_constant_combinator_state",
"switch_power_switch_state",
"switch_to_rename_stop_gui",
"take_equipment",
"toggle_connect_center_back_tank",
"toggle_connect_front_center_tank",
"toggle_deconstruction_item_entity_filter_mode",
"toggle_deconstruction_item_tile_filter_mode",
"toggle_driving",
"toggle_enable_vehicle_logistics_while_moving",
"toggle_entity_on_off_state",
"toggle_show_entity_info",
"use_ability",
"use_item",
"wire_dragging",
"write_to_console",
},
},
inventory = {
fields = {
"assembling_machine_input",
"assembling_machine_modules",
"assembling_machine_output",
"beacon_modules",
"burnt_result",
"car_ammo",
"car_trunk",
"cargo_wagon",
"chest",
"fuel",
"furnace_modules",
"furnace_result",
"furnace_source",
"god_main",
"god_quickbar",
"item_main",
"lab_input",
"lab_modules",
"mining_drill_modules",
"player_ammo",
"player_armor",
"player_guns",
"player_main",
"player_quickbar",
"player_tools",
"player_trash",
"player_vehicle",
"roboport_material",
"roboport_robot",
"rocket_silo_result",
"rocket_silo_rocket",
"turret_ammo",
},
},
logistic_member_index = {
fields = {
"character_provider",
"character_requester",
"character_storage",
"generic_on_off_behavior",
"logistic_container",
"vehicle_storage",
},
},
logistic_mode = {
fields = {
"active_provider",
"none",
"passive_provider",
"requester",
"storage",
},
},
mouse_button_type = {
fields = {
"left",
"middle",
"none",
"right",
},
},
rail_connection_direction = {
fields = {
"left",
"none",
"right",
"straight",
},
},
rail_direction = {
fields = {
"back",
"front",
},
},
riding = {
fields = {
acceleration = {
fields = {
"accelerating",
"braking",
"nothing",
"reversing",
},
},
direction = {
fields = {
"left",
"right",
"straight",
}
},
},
},
shooting = {
fields = {
"not_shooting",
"shooting_enemies",
"shooting_selected",
},
},
signal_state = {
fields = {
"closed",
"open",
"reserved",
"reserved_by_circuit_network",
},
},
train_state = {
fields = {
"arrive_signal",
"arrive_station",
"manual_control",
"manual_control_stop",
"no_path",
"no_schedule",
"on_the_path",
"path_lost",
"stop_for_auto_control",
"wait_signal",
"wait_station",
},
},
transport_line = {
fields = {
"left_line",
"left_split_line",
"left_underground_line",
"right_line",
"right_split_line",
"right_underground_line",
"secondary_left_line",
"secondary_left_split_line",
"secondary_right_line",
"secondary_right_split_line",
},
},
wire_type = {
fields = {
"copper",
"green",
"red",
}
},
colors = {
other_fields = true,
},
anticolors = {
other_fields = true,
},
lightcolors = {
other_fields = true,
},
time = {
fields = {
"second",
"minute",
"hour",
"day",
"week",
"month",
"year",
}
},
},
}
}
}
|
03671481525a244821eb9c09d7441ff08443b0e5
|
[
"Lua"
] | 1
|
Lua
|
Adam-Kay/TheFatController_0-16_Fix
|
8d6e51d9a43e8e2941f227bf1ea8cdacf7cb4814
|
e109e9ec5c8a001b446db03e19f5b237947532f1
|
refs/heads/main
|
<file_sep>[Plymouth Theme]
Name=Logo Spinner
Description=Simple logo theme with spinner
ModuleName=script
[script]
ImageDir=/usr/share/plymouth/themes/logo-spinner
ScriptFile=/usr/share/plymouth/themes/logo-spinner/script
# vi: ft=dosini
<file_sep>fun init () {
// Background
Window.SetBackgroundTopColor (0.0, 0.0, 0.0);
Window.SetBackgroundBottomColor (0.0, 0.0, 0.0);
// Logo
logo.image = Image ("logo.png");
logo.sprite = Sprite (logo.image);
logo.x = Window.GetX () + (Window.GetWidth () - logo.image.GetWidth ()) / 2;
logo.y = Window.GetY () + Window.GetHeight () * 0.4;
logo.z = 10000;
logo.sprite.SetPosition (logo.x, logo.y, logo.z);
// Message
message = Sprite ();
// Spinner
spinner.image = Image ("spinner.png");
spinner.sprite = Sprite (spinner.image);
spinner.x = Window.GetX () + (Window.GetWidth () - spinner.image.GetWidth ()) / 2;
spinner.y = Window.GetY () + Window.GetHeight () * 0.7;
spinner.z = 10000;
spinner.sprite.SetPosition (spinner.x, spinner.y, spinner.z);
spinner.index = 0;
spinner.imagecount = 64;
for (index = 0; index < spinner.imagecount; index++) {
spinner.cache[index] = spinner.image.Rotate (2*Math.Pi * index/spinner.imagecount);
}
// Password dialog
entry.image = Image ("entry.png");
entry.sprite = Sprite (entry.image);
entry.x = Window.GetX () + (Window.GetWidth () - entry.image.GetWidth ()) / 2;
entry.y = Window.GetY () + Window.GetHeight () * 0.7;
entry.z = 10000;
entry.sprite.SetPosition (entry.x, entry.y, entry.z);
dialog.entry = entry;
msg = Sprite ();
msg.SetPosition (entry.x + 10, entry.y - 20, entry.z);
dialog.message = msg;
bullet.image = Image ("bullet.png");
bullet.max = 22;
bullet[0].sprite = Sprite (bullet.image);
bullet[0].x = entry.x + 6;
bullet[0].y = entry.y + 7;
bullet[0].z = entry.z + 1;
bullet[0].sprite.SetPosition (bullet[0].x, bullet[0].y, bullet[0].z);
for (index = 1; index < bullet.max; index++) {
bullet[index].sprite = Sprite (bullet.image);
bullet[index].x = bullet[index-1].x + 12;
bullet[index].y = bullet[0].y;
bullet[index].z = bullet[0].z;
bullet[index].sprite.SetPosition (bullet[index].x, bullet[index].y, bullet[index].z);
}
dialog.bullet = bullet;
show_dialog (0);
}
fun show_dialog (visible) {
spinner.visible = 1 - visible;
dialog.entry.sprite.SetOpacity (visible);
dialog.message.SetOpacity (visible);
for (index = 0; index < dialog.bullet.max; index++) {
dialog.bullet[index].sprite.SetOpacity (visible);
}
}
fun refresh_callback () {
spinner.index = (spinner.index + 1) % spinner.imagecount;
spinner.sprite.SetImage (spinner.cache[spinner.index]);
spinner.sprite.SetOpacity (spinner.visible);
}
fun display_normal_callback () {
show_dialog (0);
}
fun display_password_callback (text, nbullets) {
show_dialog (1);
dialog.message.SetImage (Image.Text (text, 1.0, 1.0, 1.0));
for (index = 0; index < nbullets && index < dialog.bullet.max; index++) {
dialog.bullet[index].sprite.SetOpacity (1);
}
for (index = nbullets; index < dialog.bullet.max; index++) {
dialog.bullet[index].sprite.SetOpacity (0);
}
}
fun display_message_callback (text) {
text_img = Image.Text (text, 1.0, 1.0, 1.0);
message.SetImage (text_img);
message.SetPosition (Window.GetX () + (Window.GetWidth () - text_img.GetWidth ()) / 2, Window.GetY () + Window.GetHeight () * 0.93, 2);
}
fun quit_callback () {
spinner.sprite.SetOpacity (0);
}
// Global variables
spinner;
logo;
message;
dialog;
// Initiate all graphical elements
init ();
// Set callback functions
Plymouth.SetRefreshFunction (refresh_callback);
Plymouth.SetDisplayNormalFunction (display_normal_callback);
Plymouth.SetDisplayPasswordFunction (display_password_callback);
Plymouth.SetMessageFunction (display_message_callback);
Plymouth.SetQuitFunction (quit_callback);
// vi: ft=c
|
a56a9202403f0de11cb482719ed5b77c4c347361
|
[
"C",
"INI"
] | 2
|
INI
|
f1rstlady/plymouth-theme-logo-spinner
|
bc5daf8436319db1543dd24669093dd0e1c51bfd
|
60302a25e010454ca1d164c215a8a4064dd78e3b
|
refs/heads/master
|
<file_sep>$(document).ready(() => {
// Show sign out modal
$("#facebookSignOutButton").click(() => {
$("#facebookSignOutModal").modal("toggle");
});
// Fetch request for user to sign out
$("#modalFacebookSignOutButton").click(() => {
fetch("/signout")
.then((response) => {
if (response.status === 200) {
window.location.href = "/";
}
})
.catch((error) => console.error(error));
});
});
(function(d, s, id) {
var js,
fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
})(document, "script", "facebook-jssdk");
window.fbAsyncInit = function() {
FB.init({
appId: "276702183860297",
cookie: true,
xfbml: true,
version: "v10.0",
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
function checkLoginState() {
FB.getLoginStatus(function(response) {
if (response.status === "connected") {
window.location.href = "/";
}
});
}
function postDataToBackend() {
FB.api("/me?fields=id,name,picture", function(response) {
fetch("/signin", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: response.id,
name: response.name,
profilePic: response.picture.data.url,
}),
})
.then((response) => response.json())
.then((result) => {
if (result.code === 1) {
window.location.href = "/";
}
})
.catch((error) => console.log(error));
});
}
function statusChangeCallback(response) {
if (response.status === "connected") {
postDataToBackend();
}
}
function facebookSignOut() {
FB.logout();
}<file_sep>const { OAuth2Client } = require("google-auth-library");
const clientId = "895731525293-i3tcc1kh1ni5eimm82qp6nc9nplqou34.apps.googleusercontent.com"
const client = new OAuth2Client(clientId);
module.exports.signIn = (req, res) => {
res.render("signin");
};
module.exports.postSignIn = (req, res) => {
// Get Google token
let googleIdToken = req.body.googleIdToken;
// Get Facebook sign in id
let facebookId = req.body.id;
// Google authentication processing
if (googleIdToken) {
// User data
let userData;
// Google sign in handler
googleVerifyHandler = async() => {
const ticket = await client.verifyIdToken({
idToken: googleIdToken,
audience: clientId,
});
const payload = ticket.getPayload();
// Add user data
userData = {
username: payload.name,
profilePic: payload.picture,
signInType: "Google",
};
};
googleVerifyHandler()
.then(() => {
// If sign in success then generating user's cookie
res.cookie("googleIdToken", googleIdToken, {
signed: true,
});
res.cookie("userData", userData, {
signed: true,
});
// Send request to Front-end to redirect to weather page
res.send("Sign in successful with Google");
})
.catch((error) => {
res.redirect("/signin");
});
} else if (facebookId) {
let name = req.body.name;
let profilePic = req.body.profilePic;
let userData = {
username: name,
profilePic,
signInType: "Facebook",
};
// If sign in success then generating user's cookie
res.cookie("userData", userData, {
signed: true,
});
// Send request to Front-end to redirect to weather page
res.json({
code: 1,
message: "Sign in successful with Facebook",
});
}
};<file_sep>module.exports.dashboard = async(req, res) => {
let userData = await User.findById(req.signedCookies.userId);
res.render("/weather", {
userData: userData,
});
};<file_sep>$(document).ready(() => {
const API_KEY = "0263f433a04fed1051f0fad6061e06fe";
let hcmQuery = document.getElementById("hcm").innerHTML;
let hnQuery = document.getElementById("hn").innerHTML;
// Fetch to get Ho Chi Minh weather data
fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${hcmQuery}&units=metrics&appid=${API_KEY}`
)
.then((response) => response.json())
.then((result) => {
$("#hcmWeather").append(`
<div>
<span>
${result.sys.country}
</span>
<span>
${Math.round(result.main.temp) / 10}
<sup>°C</sup>
</span>
</div>
<img
src="https://openweathermap.org/img/wn/${
result.weather[0].icon
}@2x.png"
/>
<p>${result.weather[0].description}</p>
`);
})
.catch((error) => console.log(error));
// Fetch to get Ha Noi weather data
fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${hnQuery}&units=metrics&appid=${API_KEY}`
)
.then((response) => response.json())
.then((result) => {
$("#hnWeather").append(`
<div>
<span>
${result.sys.country}
</span>
<span>
${Math.round(result.main.temp) / 10}
<sup>°C</sup>
</span>
</div>
<img
src="https://openweathermap.org/img/wn/${
result.weather[0].icon
}@2x.png"
/>
<p>${result.weather[0].description}</p>
`);
})
.catch((error) => console.log(error));
});<file_sep>// Require variables from .env
require("dotenv").config();
// Initial express
const express = require("express");
// Initial cookie-parser
const cookieParser = require("cookie-parser");
// Initial express flash
const flash = require("express-flash");
// Initial express session
const session = require("express-session");
const authRoute = require("./routes/auth.route");
const dashboardRoute = require("./routes/weather.route");
// Require routes
// App setup
const app = express();
const port = process.env.PORT || 5555;
app.set("view engine", "pug");
app.set("views", "./views");
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser('secret'));
app.use(express.static("public"));
app.use(session({ cookie: { maxAge: 60000 } }));
app.use(flash());
preventWhenLogged = (req, res, next) => {
if (req.signedCookies.userData) {
res.redirect("/weather");
} else {
next();
}
};
requireAuth = async(req, res, next) => {
// Get user info if user has logged in by user id in cookie
// Check if user has not logged in
if (!req.signedCookies.userData) {
res.redirect("/login");
return;
} else { res.redirect("/weather") }
next();
};
// Default app endpoint
app.get("/", (req, res) => {
if (req.signedCookies.userData) {
res.render("weather", {
userData: req.signedCookies.userData,
});
} else {
res.redirect("/signin");
}
});
// User sign out endpoint
app.get("/signout", (req, res) => {
res.clearCookie("userData");
res.clearCookie("googleIdToken");
res.redirect("/signin");
});
app.use("/", preventWhenLogged, authRoute);
app.use("/weather", requireAuth, dashboardRoute);
// Server listen
app.listen(port, () => {
console.log(`Your running server: http://localhost:${port}`);
});<file_sep>$(document).ready(() => {
// Show sign out modal
$("#googleSignOutButton").click(() => {
$("#googleSignOutModal").modal("toggle");
});
// Fetch request for user to sign out
$("#modalGoogleSignOutButton").click(() => {
fetch("/signout")
.then((response) => {
if (response.status === 200) {
window.location.href = "/";
}
})
.catch((error) => console.error(error));
});
});
// Google Auth handler
function onGoogleSignIn(googleUser) {
let googleIdToken = googleUser.getAuthResponse().id_token;
let xhr = new XMLHttpRequest();
// Send AJAX POST Google sign in request to server,
// if receive successful message then redirect back to view weather page
xhr.open("POST", "/signin");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = () => {
if (xhr.responseText === "Sign in successful with Google") {
onGoogleSignOut();
window.location.href = "/";
}
};
xhr.send(JSON.stringify({ googleIdToken: googleIdToken }));
}
function onGoogleSignOut() {
let authentication2 = gapi.auth2.getAuthInstance();
authentication2.signOut();
}
|
508a5ddf9f9d48ce4acabc0b09f9b8db96ad1610
|
[
"JavaScript"
] | 6
|
JavaScript
|
BlueNight5907/Demo-Signin-Facebook-and-Google
|
1359a178c73587ab11d36917b49d3b544b3034fa
|
25339d8ca31b3cdcd086bd07b677ca004333ad29
|
refs/heads/master
|
<repo_name>mikeebert/Homestuff<file_sep>/app/controllers/items_controller.rb
class ItemsController < ApplicationController
before_filter :require_user
def index
@items = @user.items
if params[:item].present?
@items = @items.where(["name LIKE ?", "%#{params[:item]}%"])
end
if params[:condition].present?
@items = @items.where(:condition_id => params[:condition])
end
if params[:category].present?
@items = @items.where(:category_id => params[:category])
end
@items= @items.page(params[:page]).per(5)
@item = Item.new
end
def new
@item = Item.new
end
def show
@item = Item.find(params[:id])
end
def edit
@item = Item.find(params[:id])
end
def create
@item = Item.new(params[:item])
user = User.find(session[:user_id])
@item.user = user
if @item.save
redirect_to items_url, :notice => "Item has been added."
else
render :new, :notice => "Error. Please try again"
end
end
def update
@item = Item.find(params[:id])
if @item.save
redirect_to items_url, :notice => "Item succesfully updated"
else
redirecto_to edit_item_url, :notice => "There was an error updating your item. Please try again."
end
end
def destroy
@item = Item.find(params[:id])
@item.destroy
redirect_to items_url, :notice => "Your item has been deleted"
end
end<file_sep>/db/migrate/20111110171923_add_acquired_on_to_item.rb
class AddAcquiredOnToItem < ActiveRecord::Migration
def change
add_column :items, :acquired_on, :date
end
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
helper_method :admin?
helper_method :logged_in?
def current_user
User.find(session[:user_id])
end
def logged_in?
session[:user_id].present?
end
def admin?
redirect to root_url, :notice=> "You must be an administrator for this feature" unless current_user.admin = true
end
def require_user
redirect_to new_sessions_url, :notice=> "Please log in to continue." unless logged_in?
@user = User.find_by_id(session[:user_id])
end
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
# Mayor.create(:name => 'Emanuel', :city => cities.first)
Category.destroy_all
categories = Category.create([{:title => 'Furniture'}, {:title => 'Clothes'}, {:title => 'Electronics'}, {:title => 'Sporting Goods'}, {:title => 'Appliances'}])
Condition.destroy_all
conditions = Condition.create([{:state => "Excellent"}, {:state => 'Very Good'}, {:state => 'Good'}, {:state => 'Fair'}, {:state => 'Poor'}])<file_sep>/app/models/item.rb
class Item < ActiveRecord::Base
validates_presence_of :name
belongs_to :user
belongs_to :category
belongs_to :condition
end
|
e8190f3f1e5b4d687740779f5a5954fcdeef51d9
|
[
"Ruby"
] | 5
|
Ruby
|
mikeebert/Homestuff
|
3782ca321da564de336e7ba6a5c842bed5ccd90e
|
c03c9062430f39de9efe1679e3e0b4bf07ca4db9
|
HEAD
|
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
const Base = React.createClass({
render: function () {
return (
<div id="CMMCP_actionBlock">
<div id="CMMCP_repository">
<h4>
repository:
</h4>
<code data-cmmcp-repositoryName="https://github.com/solomonbroadbent/C-Minus-Minus-AVC">
https://github.com/solomonbroadbent/C-Minus-Minus-AVC
</code>
<button>
update
</button>
</div>
<div id="CMMCP_branch">
<h4>
branch:
</h4>
<code data-cmmcp-branchName="master">
master
</code>
<button>
update
</button>
</div>
<button>
send code
</button>
</div>
);
}
});
ReactDOM.render(
React.createElement(Base, null, null),
document.getElementById('CMMCP_reactRoot')
);<file_sep>const shell = require('shelljs');
function Result(successful, message) {
var successful = successful;
var message = message;
}
var commander = {
clone: function (directory, repository, branch) {
var result = new Result(false, 'unsuccessful');
if(!shell.which('git')) {
result.successful = false;
result.message = 'command: \'which git\' failed';
return result;
}
const command = 'git clone ' + repository + ' ' + directory;
const cloneResult = shell.exec(command);
if(cloneResult === 0) {
result.successful = false;
result.message = 'command: \'' + command + '\' failed';
return result;
}
return this.switchBranch(branch, directory);
},
switchBranch: function(branch, directory){
var result = new Result(false, 'unsuccessful');
if(!shell.which('git')) {
result.successful = false;
result.message = 'command: \'which git\' failed';
return result;
}
shell.cd(directory);
const command = 'git checkout ' + branch;
const switchBranchResult = shell.exec(command);
if(switchBranchResult === 0) {
result.successful = false;
result.message = 'command: \'' + command + '\' failed';
return result;
}
else {
result.successful = true;
result.message = 'successful';
}
return result;
}
};
module.exports = commander;<file_sep>const path = require('path');
const router = require('express').Router();
router.route('/').get(function (request, response) {
new IndexRoute().get(request, response)
});
function IndexRoute() {
function get(request, response) {
//express knows to serve index.html as the view directory is served statically
response.send('index');
}
}
//pretty sure you need to export the created router like this so it can be used as middle ware
module.exports = router;<file_sep>const path = require('path');
const express = require('express');
const shellCommander = require(
path.join(__dirname, './shellCommands')
);
//this is actually unnecessary
const masterRouter = require(
path.join(__dirname, 'routes/masterRouter')
);
//initialise express
const app = express();
//allow express to serve the view directory statically
app.use(express.static(
path.join(__dirname, '../../public/view')
));
//tell express to user masterRouter as middleware for requests to the base URL. Actually unnecessary!
app.use('/', masterRouter);
app.listen(8000, function () {
const time = new Date();
console.log('Listening on port 8000. Time: ' + time);
});
|
4f542a96de4f93dd878c5c1897211097ddac63e5
|
[
"JavaScript"
] | 4
|
JavaScript
|
solomonbroadbent/C-Minus-Minus-Code-Puller
|
429dfbd1f840d511da16f068153fb65d00a5ec6d
|
e850669042a78ea8ab93470e2432c264196a4d42
|
refs/heads/master
|
<file_sep>package searchAlgorithms;
import searchAlgorithms.CandyLocation.Color;
public class MiniMax extends Search{
public MiniMax() {}
@Override
public Coordinate search(CandyLocation[][] board, int depth, Color color, boolean max, int maxDepth) {
//Makes sure depth is no greater than the remaining moves
if (depth > maxDepth) {
depth = maxDepth;
}
//Creates Best move and sets it to max or min depending on if node is max or min
Coordinate bestMove;
if (max) {
bestMove = new Coordinate(MINIMUM);
} else {
bestMove = new Coordinate(MAXIMUM);
}
//Value of next nodes utility
int nextUtil = 0;
//Checks if min or max and if at leaf
if (depth == 0 && max) {
for (int i=0; i<rows; i++) {
for (int j=0; j<columns; j++) {
if (board[i][j].getColor() == Color.EMPTY) {
//Keeps track of total nodes
nodes++;
//Copy of board to manipulate
CandyLocation[][] copyBoard = copyBoard(board);
//Places move of interest onto board
move(copyBoard, i, j, color);
//Checks utility of said move
nextUtil = checkUtil(copyBoard);
//Sets best move to next move if better
if (bestMove.getUtility() < nextUtil) {
bestMove = new Coordinate(i, j, nextUtil);
}
}
}
}
} else if (depth == 0 && !max) {
for (int i=0; i<rows; i++) {
for (int j=0; j<columns; j++) {
if (board[i][j].getColor() == Color.EMPTY) {
nodes++;
CandyLocation[][] copyBoard = copyBoard(board);
move(copyBoard, i, j, color);
nextUtil = checkUtil(copyBoard);
if (bestMove.getUtility() > nextUtil) {
bestMove = new Coordinate(i, j, nextUtil);
}
}
}
}
} else {
Coordinate nextMove;
for (int i=0; i<rows; i++) {
for (int j=0; j<columns; j++) {
if (board[i][j].getColor() == Color.EMPTY) {
CandyLocation[][] copyBoard = copyBoard(board);
move(copyBoard, i, j, color);
//Recursive search for next move, includes swapping turns
if (color == Color.BLUE) {
nextMove = search(copyBoard, depth-1, Color.GREEN, !max, maxDepth);
if (max) {
if (bestMove.getUtility() < nextMove.getUtility()) {
bestMove = new Coordinate(i, j, nextMove.getUtility());
}
} else {
if (bestMove.getUtility() > nextMove.getUtility()) {
bestMove = new Coordinate(i, j, nextMove.getUtility());
}
}
} else {
nextMove = search(copyBoard, depth-1, Color.BLUE, !max, maxDepth);
if (max) {
if (bestMove.getUtility() < nextMove.getUtility()) {
bestMove = new Coordinate(i, j, nextMove.getUtility());
}
} else {
if (bestMove.getUtility() > nextMove.getUtility()) {
bestMove = new Coordinate(i, j, nextMove.getUtility());
}
}
}
}
}
}
}
// System.out.println("Best Move = (" + bestMove.getX() + ", " + bestMove.getY() + ") util = " + bestMove.getUtility());
return bestMove;
}
@Override
public boolean getSearch() {
//True for MiniMax
return true;
}
}
<file_sep>package searchAlgorithms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import searchAlgorithms.GridLocation.DomainState;
public class LocalSearch {
private static final int MAX_SIDEWAYS = 10;
private static final int OPTIMAL_SOLUTION = 0;
public enum Local_Search_Versions {
SAHC, // Steepest Ascent Hill Climbing V1
SAHCV2, // Steepest Ascent Hill Climbing V2
SAHCV3, // Steepest Ascent Hill Climbing V3
SHC // Stochastic Hill Climbing
}
Grid grid;
private int totalSteps;
public LocalSearch(String forestFilePath) throws IOException, IllegalAccessException {
readFromFileToGrid(forestFilePath);
totalSteps = 0;
}
public int localSearch(Local_Search_Versions version) throws IllegalAccessException {
int result = -1;
switch (version) {
case SAHC:
result = steepestAscentHillClimbingSearch();
break;
case SAHCV2:
result = steepestAscentHillClimbingSearchV2();
break;
case SAHCV3:
result = steepestAscentHillClimbingSearchV3();
break;
case SHC:
result = stochasticHillClimbing();
break;
default:
throw new IllegalAccessException("Not a valid search algorithm");
}
return result;
}
/*
* complete state formulation
* heuristic = sum of all friends each friend can see (sum of all pairs of friends who can see each other * 2)
* 2 methods: iterate through columns systematically, or choose random column
* terminate when: the BEST value of the next state is less than or equal to to the current value of the state. i.e. we cannot go up anymore
* if it's equal, that's a plateau? perhaps we will allow sideways movements in plateaus
* but don't let it reach an infinite loop! set a limit to how many sideways movements it can go before terminating
* this should increase the chance of finding the optimal solution (h = 0), but the algorithm will take longer on average
* variants of hill climbing: 1. steepest ascent - greedy, choose best next state
* 2. stochastic hill climbing - chooses a random state that is better
* 3. first choice - a kind of stochastic, where it generates successors randomly and uses the first successor that is better than the current state
* only practical for states that have many many successors
* 4. random restart hill climbing - keep restarting algorithm with a random initial state until goal is found
*/
public int steepestAscentHillClimbingSearch() {
int currentColumn = 0;
int minimaCounter = 0;
while (true) {
int pivotColumn = currentColumn % grid.getNumFriends();
minimaCounter = findNextBestLocationForFriend(pivotColumn) == 0 ? 0 : (minimaCounter + 1);
if (calculateHeuristic(grid) == OPTIMAL_SOLUTION) {
break;
}
// break when no friends have moved in any column
if (minimaCounter == grid.getNumFriends()) {
break;
}
currentColumn++;
totalSteps++;
}
//System.out.println("The ending heuristic is " + calculateHeuristic(grid));
//printGrid();
return calculateHeuristic(grid);
}
// returns 1 if friend changed to a better location, 0 otherwise
private int findNextBestLocationForFriend(int column) {
GridLocation[][] gridArray = grid.getGrid();
int currentIndex = grid.getColumnToFriendMap().get(column);
int nextBestIndex = currentIndex;
int bestHeuristic = calculateHeuristic(grid);
for (int i = 0; i < grid.getNumFriends(); i++) {
if (i != currentIndex) {
if (gridArray[i][column].getState() == DomainState.EMPTY) {
gridArray[nextBestIndex][column].setState(DomainState.EMPTY);
gridArray[i][column].setState(DomainState.FRIEND);
int heuristic = calculateHeuristic(grid);
if (heuristic < bestHeuristic) {
nextBestIndex = i;
bestHeuristic = heuristic;
} else {
gridArray[i][column].setState(DomainState.EMPTY);
}
}
}
}
gridArray[nextBestIndex][column].setState(DomainState.FRIEND);
grid.updateColumnToFriendMap(column, nextBestIndex);
return nextBestIndex != currentIndex ? 0 : 1;
}
// allows sideways
public int steepestAscentHillClimbingSearchV2() {
int currentColumn = 0;
int minimaCounter = 0;
int sidewaysMoves = 0;
while (true) {
int pivotColumn = currentColumn % grid.getNumFriends();
int result = findNextBestLocationForFriendV2(pivotColumn);
if (calculateHeuristic(grid) == OPTIMAL_SOLUTION) {
break;
}
if (result == 2) {
sidewaysMoves++;
minimaCounter = 0;
} else if (result == 1) {
minimaCounter++;
} else {
minimaCounter = 0;
sidewaysMoves = 0;
}
// break when no friends have moved in any column
if (minimaCounter == grid.getNumFriends()) {
break;
}
if (sidewaysMoves == MAX_SIDEWAYS) {
break;
}
totalSteps++;
currentColumn++;
}
//System.out.println("The ending heuristic is " + calculateHeuristic(grid));
//printGrid();
return calculateHeuristic(grid);
}
private int findNextBestLocationForFriendV2(int column) {
GridLocation[][] gridArray = grid.getGrid();
int currentIndex = grid.getColumnToFriendMap().get(column);
int nextBestIndex = currentIndex;
int bestHeuristic = calculateHeuristic(grid);
int initialHeuristic = bestHeuristic;
for (int i = 0; i < grid.getNumFriends(); i++) {
if (i != currentIndex) {
if (gridArray[i][column].getState() == DomainState.EMPTY) {
gridArray[nextBestIndex][column].setState(DomainState.EMPTY);
gridArray[i][column].setState(DomainState.FRIEND);
int heuristic = calculateHeuristic(grid);
// allow for sideways movement
if (heuristic <= bestHeuristic) {
nextBestIndex = i;
bestHeuristic = heuristic;
} else {
gridArray[i][column].setState(DomainState.EMPTY);
}
}
}
}
gridArray[nextBestIndex][column].setState(DomainState.FRIEND);
grid.updateColumnToFriendMap(column, nextBestIndex);
if (nextBestIndex != currentIndex) {
// if same heuristic but friend moved, return 2, otherwise return 1
return initialHeuristic != bestHeuristic ? 0 : 2;
}
// friend didn't move
return 1;
}
public int steepestAscentHillClimbingSearchV3() {
int minimaCounter = 0;
while (true) {
int randomPivotColumn = (int) (Math.random() * grid.getNumFriends());
minimaCounter = findNextBestLocationForFriend(randomPivotColumn) == 0 ? 0 : (minimaCounter + 1);
if (calculateHeuristic(grid) == OPTIMAL_SOLUTION) {
break;
}
// break when no friends have moved in any column
// increasing this value increases the score
if (minimaCounter == 9) {
break;
}
totalSteps++;
}
//System.out.println("The ending heuristic is " + calculateHeuristic(grid));
//printGrid();
return calculateHeuristic(grid);
}
// stochastic without sliding
public int stochasticHillClimbing() {
int currentColumn = 0;
int minimaCounter = 0;
while (true) {
int pivotColumn = currentColumn % grid.getNumFriends();
minimaCounter = findNextBestLocationForFriendStochatic(pivotColumn) == 0 ? 0 : (minimaCounter + 1);
if (calculateHeuristic(grid) == OPTIMAL_SOLUTION) {
break;
}
// break when no friends have moved in any column
// counter should not affect
if (minimaCounter == grid.getNumFriends()) {
break;
}
totalSteps++;
currentColumn++;
}
// System.out.println("The ending heuristic is " + calculateHeuristic(grid));
//printGrid();
return calculateHeuristic(grid);
}
private int findNextBestLocationForFriendStochatic(int column) {
GridLocation[][] gridArray = grid.getGrid();
int currentIndex = grid.getColumnToFriendMap().get(column);
int currentBestHeuristic = calculateHeuristic(grid);
List<Integer> possibleImprovements = new ArrayList<>();
for (int i = 0; i < grid.getNumFriends(); i++) {
if (i != currentIndex) {
if (gridArray[i][column].getState() == DomainState.EMPTY) {
gridArray[currentIndex][column].setState(DomainState.EMPTY);
gridArray[i][column].setState(DomainState.FRIEND);
int heuristic = calculateHeuristic(grid);
if (heuristic < currentBestHeuristic) {
possibleImprovements.add(i);
}
gridArray[currentIndex][column].setState(DomainState.FRIEND);
gridArray[i][column].setState(DomainState.EMPTY);
}
}
}
if (possibleImprovements.size() > 0) {
int randomIndex = (int) (Math.random() * possibleImprovements.size());
gridArray[possibleImprovements.get(randomIndex)][column].setState(DomainState.FRIEND);
gridArray[currentIndex][column].setState(DomainState.EMPTY);
grid.updateColumnToFriendMap(column, possibleImprovements.get(randomIndex));
return 0;
}
return 1;
}
private int calculateHeuristic(Grid grid) {
int heuristic = 0;
for (int columnIndex = 0; columnIndex < grid.getNumFriends(); columnIndex++) {
int friendIndex = grid.getColumnToFriendMap().get(columnIndex);
heuristic += findConflicts(friendIndex, columnIndex, grid);
}
return heuristic;
}
private int findConflicts(int x, int y, Grid grid) {
int conflicts = 0;
conflicts += findConflictUpRight(x, y, grid);
conflicts += findConflictUpLeft(x, y, grid);
conflicts += findConflictDownLeft(x, y, grid);
conflicts += findConflictDownRight(x, y, grid);
conflicts += findConflictsRight(x, y, grid);
conflicts += findConflictsLeft(x, y, grid);
return conflicts;
}
private int findConflictsRight(int x, int y, Grid grid) {
y++;
boolean conflict = false;
while (y < grid.getNumFriends()) {
DomainState state = grid.getGrid()[x][y].getState();
if (state == DomainState.TREE) {
break;
}
if (state == DomainState.FRIEND) {
conflict = true;
break;
}
y++;
}
return conflict ? 1 : 0;
}
private int findConflictsLeft(int x, int y, Grid grid) {
y--;
boolean conflict = false;
while (y >= 0) {
DomainState state = grid.getGrid()[x][y].getState();
if (state == DomainState.TREE) {
break;
}
if (state == DomainState.FRIEND) {
conflict = true;
break;
}
y--;
}
return conflict ? 1 : 0;
}
private int findConflictUpRight(int x, int y, Grid grid) {
x--; y++;
boolean conflict = false;
while (x >= 0 && y < grid.getNumFriends()) {
DomainState state = grid.getGrid()[x][y].getState();
if (state == DomainState.TREE) {
break;
}
if (state == DomainState.FRIEND) {
conflict = true;
break;
}
x--; y++;
}
return conflict ? 1 : 0;
}
private int findConflictUpLeft(int x, int y, Grid grid) {
x--; y--;
boolean conflict = false;
while (x >= 0 && y >= 0) {
DomainState state = grid.getGrid()[x][y].getState();
if (state == DomainState.TREE) {
break;
}
if (state == DomainState.FRIEND) {
conflict = true;
break;
}
x--; y--;
}
return conflict ? 1 : 0;
}
private int findConflictDownLeft(int x, int y, Grid grid) {
x++; y--;
boolean conflict = false;
while (x < grid.getNumFriends() && y >= 0) {
DomainState state = grid.getGrid()[x][y].getState();
if (state == DomainState.TREE) {
break;
}
if (state == DomainState.FRIEND) {
conflict = true;
break;
}
x++; y--;
}
return conflict ? 1 : 0;
}
private int findConflictDownRight(int x, int y, Grid grid) {
x++; y++;
boolean conflict = false;
while (x < grid.getNumFriends() && y < grid.getNumFriends()) {
DomainState state = grid.getGrid()[x][y].getState();
if (state == DomainState.TREE) {
break;
}
if (state == DomainState.FRIEND) {
conflict = true;
break;
}
x++; y++;
}
return conflict ? 1 : 0;
}
private void readFromFileToGrid(String fileName) throws IOException {
InputStream inputStream = LocalSearch.class.getResourceAsStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String firstLine = reader.readLine();
String[] splitArray = firstLine.split("\\s+");
int numFriends = Integer.parseInt(splitArray[0]);
int numTrees = Integer.parseInt(splitArray[1]);
int[][] treeLocations = new int[numTrees][2];
for (int i = 0; i < numTrees; i++) {
String nextTree = reader.readLine();
splitArray = nextTree.split("\\s+");
// the sample input is 1-indexed
treeLocations[i][0] = Integer.parseInt(splitArray[0]) - 1;
treeLocations[i][1] = Integer.parseInt(splitArray[1]) - 1;
}
this.grid = new Grid(numFriends, numTrees, treeLocations);
}
public void printGrid() {
GridLocation[][] gridArray = grid.getGrid();
int length = gridArray.length;
for (int i = 0; i < length; i++) {
System.out.println();
for (int j = 0; j < length; j++) {
if (gridArray[i][j].getState() == DomainState.FRIEND) {
System.out.print("F");
} else if (gridArray[i][j].getState() == DomainState.TREE) {
System.out.print("T");
} else {
System.out.print(" ");
}
}
}
System.out.println();
}
public static void printGrid(GridLocation[][] grid) {
int length = grid.length;
for (int i = 0; i < length; i++) {
System.out.println();
for (int j = 0; j < length; j++) {
if (grid[i][j].getState() == DomainState.FRIEND) {
System.out.print("F");
} else if (grid[i][j].getState() == DomainState.TREE) {
System.out.print("T");
} else {
System.out.print(" ");
}
}
}
System.out.println();
}
public int getTotalSteps() {
return totalSteps;
}
public Grid getGrid() {
return grid;
}
}<file_sep>package searchAlgorithms;
public class Coordinate {
private int x;
private int y;
private int utility;
public Coordinate(int x, int y, int utility) {
this.x = x;
this.y = y;
this.utility = utility;
}
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public Coordinate(int utility) {
this.utility = utility;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setUtility(int utility) {
this.utility = utility;
}
public int getUtility() {
return this.utility;
}
}
<file_sep>package main;
import java.io.IOException;
import searchAlgorithms.AlphaBeta;
import searchAlgorithms.CandyLocation;
import searchAlgorithms.CandyLocation.Color;
import searchAlgorithms.Game;
import searchAlgorithms.GridLocation;
import searchAlgorithms.LocalSearch;
import searchAlgorithms.LocalSearch.Local_Search_Versions;
import searchAlgorithms.MiniMax;
import searchAlgorithms.Search;
public class Tester {
public static final String defaultForestPath = "../forests/input.txt";
public Tester() {
}
public void runAllLocalSearchTests() throws IllegalAccessException, IOException {
printForest(defaultForestPath);
runLocalSearchTest(Local_Search_Versions.SAHC, defaultForestPath, 100);
runLocalSearchTest(Local_Search_Versions.SAHCV2, defaultForestPath, 100);
runLocalSearchTest(Local_Search_Versions.SAHCV3, defaultForestPath, 100);
runLocalSearchTest(Local_Search_Versions.SHC, defaultForestPath, 100);
}
private void printForest(String forestFilePath) throws IllegalAccessException, IOException {
LocalSearch search = new LocalSearch(forestFilePath);
System.out.println("Default Forest Unsolved");
search.printGrid();
System.out.println("-----------------------------------------------------------");
}
private void runLocalSearchTest(Local_Search_Versions version, String forestFilePath, int iterations) throws IllegalAccessException, IOException {
int foundOptimalCount = 0;
int sumStepsForOptimal = 0;
int sumStepsForNonOptimal = 0;
GridLocation[][] solutionGrid = null;
for (int i = 0; i < iterations; i++) {
LocalSearch localSearch = new LocalSearch(forestFilePath);
int result = localSearch.localSearch(version);
if (result == 0) {
foundOptimalCount++;
sumStepsForOptimal += localSearch.getTotalSteps();
solutionGrid = localSearch.getGrid().getGrid();
} else {
sumStepsForNonOptimal += localSearch.getTotalSteps();
}
}
printLocalSearchResults(version, iterations, foundOptimalCount, sumStepsForOptimal, sumStepsForNonOptimal, solutionGrid);
}
private void printLocalSearchResults(Local_Search_Versions version, int iterations, int foundOptimalCount, int sumStepsForOptimal, int sumStepsForNonOptimal, GridLocation[][] solution) {
if (solution != null) {
System.out.println("An optimal solution from using the " + version + " algorithm");
LocalSearch.printGrid(solution);
System.out.println();
}
System.out.println("Out of " + iterations + " runs, " + version + " found the optimal solution " + foundOptimalCount + " times.");
System.out.println("Average Steps to an optimal solution " + (sumStepsForOptimal / foundOptimalCount) );
System.out.println("Average Steps for non-optimal solution " + (sumStepsForNonOptimal / (iterations - foundOptimalCount)));
System.out.println("-----------------------------------------------------------");
}
private void printGame(CandyLocation[][] board, int rows, int columns){
Color positionColor;
String line = "";
for (int i=0; i<rows; i++) {
for (int j=0; j<columns; j++) {
positionColor = board[i][j].getColor();
if (positionColor == Color.BLUE) {
line += "B ";
} else if (positionColor == Color.GREEN) {
line += "G ";
} else if (positionColor == Color.EMPTY) {
line += "E ";
}
}
System.out.println(line);
line = "";
}
}
private void runGame(String gameBoard, boolean playerA, boolean playerB) throws IOException {
Search player_1;
Search player_2;
String title = "";
if (playerA) {
player_1 = new MiniMax();
title += "Minimax vs. ";
} else {
player_1 = new AlphaBeta();
title += "AlphaBeta vs. ";
}
if (playerB) {
player_2 = new MiniMax();
title += "Minimax";
} else {
player_2 = new AlphaBeta();
title += "AlphaBeta";
}
int depth_1 = 3;
int depth_2 = 3;
String gameFilePath = "../gameBoards/" + gameBoard + ".txt";
System.out.println(gameBoard);
System.out.println(title);
Game game = new Game(gameFilePath, player_1, player_2, depth_1, depth_2);
printGame(game.getBoard(), game.getRows(), game.getColumns());
if (game.checkWinner() == Color.BLUE) {
System.out.println("Blue wins by: " + game.getScore());
System.out.println("Blue score: " + game.getBlue() + " Green score: " + game.getGreen());
System.out.println("Blue Average Move Time: " + game.getBlueTime() + "ms Green Average Move Time: " + game.getGreenTime() + "ms");
System.out.println("Blue Total Nodes: " + game.getBlueNodes() + " Green Total Nodes: " + game.getGreenNodes());
System.out.println("Blue Average Nodes: " + game.getBlueAvg() + " Green Average Nodes: " + game.getGreenAvg());
System.out.println("--------------------------");
} else if (game.checkWinner() == Color.GREEN) {
System.out.println("Green Wins by: " + game.getScore());
System.out.println("Blue score: " + game.getBlue() + " Green score: " + game.getGreen());
System.out.println("Blue Average Move Time: " + game.getBlueTime() + "ms Green Average Move Time: " + game.getGreenTime() + "ms");
System.out.println("Blue Total Nodes: " + game.getBlueNodes() + " Green Total Nodes: " + game.getGreenNodes());
System.out.println("Blue Average Nodes: " + game.getBlueAvg() + " Green Average Nodes: " + game.getGreenAvg());
System.out.println("--------------------------");
} else {
System.out.println("Tie Game");
System.out.println("Blue score: " + game.getBlue() + " Green score: " + game.getGreen());
System.out.println("Blue Average Move Time: " + game.getBlueTime() + "ms Green Average Move Time: " + game.getGreenTime() + "ms");
System.out.println("Blue Total Nodes: " + game.getBlueNodes() + " Green Total Nodes: " + game.getGreenNodes());
System.out.println("Blue Average Nodes: " + game.getBlueAvg() + " Green Average Nodes: " + game.getGreenAvg());
System.out.println("--------------------------");
}
}
private void runAllGames() throws IOException {
runGame("AlmondJoy", true, true);
runGame("AlmondJoy", false, false);
runGame("AlmondJoy", false, true);
runGame("AlmondJoy", true, false);
runGame("Ayds", true, true);
runGame("Ayds", false, false);
runGame("Ayds", false, true);
runGame("Ayds", true, false);
runGame("Bit-O-Honey", true, true);
runGame("Bit-O-Honey", false, false);
runGame("Bit-O-Honey", false, true);
runGame("Bit-O-Honey", true, false);
runGame("Mounds", true, true);
runGame("Mounds", false, false);
runGame("Mounds", false, true);
runGame("Mounds", true, false);
runGame("ReesesPieces", true, true);
runGame("ReesesPieces", false, false);
runGame("ReesesPieces", false, true);
runGame("ReesesPieces", true, false);
}
public static void main(String[] args) throws IOException, IllegalAccessException {
Tester tester = new Tester();
tester.runAllLocalSearchTests();
tester.runAllGames();
}
}
|
bcdda5ec571fa8d4322ba681a9eddcacc22787d3
|
[
"Java"
] | 4
|
Java
|
sjyan/AI-Projects
|
86245ae245b8807c84ff1bb86fadc387d56b9c4c
|
70369869d9ebfb8e9c21e11ba85eda4efc805de7
|
refs/heads/master
|
<file_sep>#include <iostream>
using namespace std;
int main()
{
char str[256];
cout << "Enter your string:" << endl;
cin.getline(str, 256);
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] >= 'a' && str[i] <= 'z')
{
cout << (char)(str[i]-32);
}
else
cout << str[i];
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
cout << "Enter the first number: ";
float first = 0, second = 0;
cin >> first;
cout << "Enter the second number: ";
cin >> second;
cout << "1 - plus" << endl
<< "2 - minus" << endl
<< "3 - multiply" << endl
<< "4 - divide" << endl;
int third = 0;
do
{
cout << "Select the command: ";
cin >> third;
}while (third > 4 || third < 1);
cout << "Result: ";
switch (third)
{
case 1:
cout << first+second;
break;
case 2:
cout << first-second;
break;
case 3:
cout << first*second;
break;
case 4:
cout << first/second;
break;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
int cards[10];
int command = 0;
int card = 0;
int summa = 0;
int money = 0;
for (int i = 0; i < 10; i++)
{
cards[i] = 0;
}
do
{
cout << "YOUR CARDS" << endl;
for (int i = 0; i < 10; i++)
{
cout << cards[i] << " ";
}
cout << endl;
do
{
cout << "Select card: ";
cin >> card;
}while (card > 10 || card < 1);
do
{
cout << "How much money: ";
cin >> money;
}while (money < 0);
cards[card-1] += money;
summa += money;
cout << "BALANCE: " << summa << endl;
cout << "Enter 0 to continue or 1 to exit: ";
cin >> command;
cout << endl;
}while (command != 1);
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
cout << "Enter school numbers" << endl;
int school[10];
for (int i = 0; i < 10; i++)
{
cout << i+1 << ") ";
cin >> school[i];
}
int your_school = 0;
cout << "Enter your school's number: ";
cin >> your_school;
int know = 0;
for (int i = 0; i < 10; i++)
{
if (school[i] == your_school)
know++;
}
if (know > 0)
cout << "I know this school!";
else
cout << "I don't know this school...";
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
cout << "Enter the first number:";
int first = 0, second = 0;
cin >> first;
cout << "Enter the second number:";
cin >> second;
cout << "The sum: " << first + second;
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int EnterHeight()
{
int tree = 0;
do
{
cout << "Tree height: ";
cin >> tree;
}while (tree <= 0);
cout << endl;
return tree;
}
void DrawSpace(int tree, int row)
{
for (int space = 0; space < tree-row+1; space++)
{
cout << " ";
}
}
void DrawStars(int row)
{
for (int star = 0; star < row*2-1; star++)
{
cout << "*";
}
}
void DrawTriangle(int tree)
{
for (int row = 1; row <= tree; row++)
{
DrawSpace(tree, row);
DrawStars(row);
cout << endl;
}
}
void DrawTree(int tree)
{
DrawTriangle(tree);
DrawSpace(tree,1);
DrawStars(1);
}
int main()
{
DrawTree(EnterHeight());
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
int side = 0;
do
{
cout << "Enter the size of triangle side: ";
cin >> side;
}while (side <= 0);
cout << endl;
for (int row = 1; row <= side; row++)
{
for (int column = 0; column < row ; column++)
{
cout << "* ";
}
cout << endl;
}
cout << endl;
for (int row = side; row >= 1; row--)
{
for (int column = 0; column < row; column++)
{
cout << "* ";
}
cout << endl;
}
cout << endl;
for (int row = 0; row < side; row++)
{
for (int space = 0; space < row; space++)
{
cout << " ";
}
for (int star = side; star > row; star--)
{
cout << "* ";
}
cout << endl;
}
cout << endl;
for (int row = 1; row <= side; row++)
{
for (int space = 0; space < side - row; space++)
{
cout << " ";
}
for (int star = 0; star < row; star++)
{
cout << "* ";
}
cout << endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
int numbers[20];
cout << "Enter numbers (only even or only odd)" << endl;
for (int enter = 0; enter < 20; enter++)
{
cin >> numbers[enter];
if (numbers[enter] == 0)
break;
if (enter >= 1) //check for even or odd numbers
{
while (numbers[enter-1]%2 == 0 && numbers[enter]%2 != 0)
{
cout << "Numbers should be even! Try again" << endl;
cin >> numbers[enter];
}
while (numbers[enter-1]%2 != 0 && numbers[enter]%2 == 0)
{
cout << "Numbers should be odd! Try again" << endl;
cin >> numbers[enter];
if (numbers[enter] == 0)
break;
}
}
}
cout << endl;
// search for the largest number in the array
int largest = 0;
for (int big = 0; big < 20; big++)
{
if (numbers[big] == 0)
break;
if (largest < numbers[big])
largest = numbers[big];
}
for (int out = 0; out < 20; out++)
{
if (numbers[out] == 0)
break;
for (int space = 0; space <= (largest/2) - (numbers[out]/2); space++)
{
cout << " ";
}
for (int star = 0; star < numbers[out]; star++)
{
cout << "*";
}
cout << endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
cout << "Squirrel needs this amount of nuts: ";
int N = 0;
cin >> N;
cout << "Nuts in one cone: ";
int K = 0;
cin >> K;
cout << "Squirrel collected this amount of cones: ";
int M = 0;
cin >> M;
cout << "\nDoes squirrel have enough nuts...?" << endl;
if (M*K>=N)
{
cout << "Yes, it's OK";
}
else
{
cout << "NOPE";
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
int numbers[5];
cout << "Enter 5 positive numbers" << endl;
for (int i = 0; i < 5; i++)
{
cout << i+1 << ") ";
cin >> numbers[i];
while (numbers[i] < 0)
{
cout << "The number should be positive! Try again" << endl;
cout << i+1 << ") ";
cin >> numbers[i];
}
}
// search for the largest number in the array
int largest = 0;
for (int big = 0; big < 5; big++)
{
if (largest < numbers[big])
largest = numbers[big];
}
for (int row = 0; row < largest; row++)
{
cout << " ";
for (int column = 0; column < 5; column++)
{
if (numbers[column] != 0 && numbers[column] > row)
{
cout << "*";
}
else
{
cout << " ";
}
}
cout << endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
int number = 0;
do
{
cout << "Enter the positive number: ";
cin >> number;
}while (number < 0);
for (int i = 0; i <= number; i++)
{
if (i != number)
cout << i << ", ";
else
cout << i;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
char str[100];
int start = 0, finish = 5;
int s = 0, f = 0;
cout << "Enter your string:" << endl;
cin.getline(str, 100);
int words[2][10] = {0}; //array with indexes of begins and ends of the words in the string
int length[10] = {0}; //array with lengths of words
for (int i = 0; str[i] != '\0'; i++)
{
if(!(str[i-1] >= 'A' && str[i-1] <= 'Z' || str[i-1] >= 'a' && str[i-1] <= 'z') &&
(str[i] >= 'A' && str[i] <= 'Z' || str[i] >= 'a' && str[i] <= 'z'))
{
words[0][s] = i;
s++;
}
if(!(str[i+1] >= 'A' && str[i+1] <= 'Z' || str[i+1] >= 'a' && str[i+1] <= 'z') &&
(str[i] >= 'A' && str[i] <= 'Z' || str[i] >= 'a' && str[i] <= 'z'))
{
words[1][f] = i;
f++;
}
}
for(int i = 0; i<10; i++)
{
length[i] = words[1][i] - words[0][i];
}
int largest = 0;
for (int big = 0; big < 10; big++)
{
if (largest < length[big])
{
largest = length[big];
start = words[0][big];
finish = words[1][big];
}
}
cout << "The longest word is: ";
for (int i = start; i <= finish; i++)
{
cout << str[i];
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
cout << "How many stars do you want to see?" << endl;
int stars = 0;
cin >> stars;
for (int i = 0; i < stars; i++)
{
cout << "*";
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
system("chcp 1251 & cls");
char command = 0;
do
{
cout << "Солнце давно встало, птички поют за окном, над ухом звенит будильник." << endl
<< "Вы просыпаетесть. Первым делом Вы решаете..." << endl
<< "1 - проверить телефон" << endl
<< "2 - погладить кота" << endl
<< "3 - сделать зарядку" << endl
<< "Введите номер варианта: " << endl;
int var = 0;
cin >> var;
switch (var)
{
case 1:
cout << "Новых сообщений не приходило. Решив полистать ленты в социальных сетях" << endl
<< "Вы застряли в Интернете где-то на час. На завтрак Вы выбрали..." << endl
<< "1 - приготовить омлет" << endl
<< "2 - заказать пиццу" << endl
<< "Введите номер варианта: " << endl;
cin >> var;
switch (var)
{
case 1:
cout << "Благодаря Вашим кулинарным способностям омлет оказался вкусным, хоть и подгорелым." << endl
<< "Пока Вы отмывали сковороду, пришел голодный кот." << endl
<< "После того как все были сыты, Вас ждал хороший день!" << endl;
break;
case 2:
cout << "Пиццу доставили быстро и она была очень вкусной." << endl
<< "Кот тоже оценил и не заставил Вас готовить завтрак для него!" << endl;
break;
default:
cout << "Такого варинта нет!" << endl;
}
break;
case 2:
cout << "Вы не нашли кота в своей комнате, поэтому пошли искать дальше." << endl
<< "Обойдя весь дом, Вы начали волноваться что не видите своего пушистого друга." << endl
<< "Вдруг полсышались странные звуки из кладовой. Кот залез на верхнюю полку" << endl
<< "и не мог самостоятельно спуститься." << endl
<< "1 - дать возможнось коту самому справиться с ситуацией" << endl
<< "2 - снять кота с полки самостоятельно" << endl
<< "Введите номер варианта: " << endl;
cin >> var;
switch (var)
{
case 1:
cout << "Вы попытались соорудить \"ступеньки\" что бы кот смог спуститься самостоятельно." << endl
<< "Он боялся высоты и поэтому смог прийти к вам только после завтрака." << endl
<< "Но он все еще был голодным и Вы отправились кормить своего пушистого друга." << endl;
break;
case 2:
cout << "Кот не понял Ваших намерений ему помочь, в результате чего вы получили" << endl
<< "несколько царапин в ходе спасательной операции." << endl;
break;
default:
cout << "Такого варинта нет!" << endl;
}
break;
case 3:
cout << "Бодро начав свое утро Вы получили заряд энергии и хорошего настроения на весь день." << endl
<< "Отправившись завтракать Вы выбрали..." << endl
<< "1 - приготовить омлет" << endl
<< "2 - заказать пиццу" << endl
<< "Введите номер варианта: " << endl;
cin >> var;
switch (var)
{
case 1:
cout << "Благодаря Вашим кулинарным способностям омлет оказался вкусным, хоть и подгорелым." << endl
<< "Пока Вы отмывали сковороду, пришел голодный кот." << endl
<< "После того как все были сыты, Вас ждал хороший день!" << endl;
break;
case 2:
cout << "Пиццу доставили быстро и она была очень вкусной." << endl
<< "Кот тоже оценил и не заставил Вас готовить завтрак для него!" << endl;
break;
default:
cout << "Такого варинта нет!" << endl;
}
break;
default:
cout << "Такого варинта нет!" << endl;
}
cout << endl << "Нажмите 0 для того что б выйти или другую кнопку что б начать с начала." << endl;
cin >> command;
}while (command != 0);
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
int side = 0;
do
{
cout << "Square side: ";
cin >> side;
}while (side <= 0);
for (int i = 0; i < side; i++)
{
for (int j = 0; j < side; j++)
{
cout << "* ";
}
cout << endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
int tree = 0;
do
{
cout << "Tree height: ";
cin >> tree;
}while (tree <= 0);
cout << endl;
for (int row = 1; row <= tree; row++)
{
cout << " ";
for (int space = 0; space < tree-row; space++)
{
cout << " ";
}
for (int star = 0; star < row*2-1; star++)
{
cout << "*";
}
cout << endl;
}
for (int space = 0; space < tree; space++)
{
cout << " ";
}
cout << "*";
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
cout << "Enter your slary: " << endl;
int pay = 0;
cin >> pay;
if (pay>1000)
{
if (pay<1000000)
{
cout << "Cool";
}
if (pay>999999)
{
cout << "You are millionaire";
}
}
if (pay<1001)
{
cout << "Work harder";
}
cout << ", but you're good!";
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter your string:" << endl;
cin.getline(str, 100);
int words = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if(!(str[i+1] >= 'A' && str[i+1] <= 'Z' || str[i+1] >= 'a' && str[i+1] <= 'z') &&
(str[i] >= 'A' && str[i] <= 'Z' || str[i] >= 'a' && str[i] <= 'z'))
words++;
}
cout << "Words in the string: " << words;
return 0;
}
|
fa3fd38965a6c892088bdade3985de88716abb71
|
[
"C++"
] | 18
|
C++
|
kyoshy/NG_2021_Khovrenko_Yelyzaveta
|
304480da6ea35a634cf3a764d86687eec72f653f
|
8d94c0a4bb81c67ef3b3ff4343d97c6fb9a54765
|
refs/heads/master
|
<repo_name>mlewe/BlossomV.jl<file_sep>/deps/interface/visibility.h
#pragma once
#if defined(_WIN32) || defined(__CYGWIN__)
#ifdef interface_EXPORTS
#ifdef __GNUC__
#define INTERFACE_EXPORT __attribute__ ((dllexport))
#else
#define INTERFACE_EXPORT __declspec(dllexport)
#endif
#else
#ifdef __GNUC__
#define INTERFACE_EXPORT __attribute__ ((dllimport))
#else
#define INTERFACE_EXPORT __declspec(dllimport)
#endif
#endif
#else
#if __GNUC__ >= 4
#define INTERFACE_EXPORT __attribute__ ((visibility ("default")))
#else
#define INTERFACE_EXPORT
#endif
#endif
<file_sep>/Project.toml
name = "BlossomV"
uuid = "6c721016-9dae-5d90-abf6-67daaccb2332"
version = "0.4.3"
[deps]
BinDeps = "9e28174c-4ba2-5203-b857-d8d62c4213ee"
Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[extras]
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[targets]
test = ["Test"]
[compat]
julia = "0.7, 1"
BinDeps = "0.8, 1"
<file_sep>/deps/interface/interface.h
#include <stdint.h>
#include "visibility.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct matching* matching_t;
INTERFACE_EXPORT
matching_t matching_construct(int32_t node_num, int32_t edge_num_max);
INTERFACE_EXPORT
void matching_destruct(matching_t matching);
INTERFACE_EXPORT
int32_t matching_add_edge(matching_t matching, int32_t first_node, int32_t second_node, int32_t cost);
INTERFACE_EXPORT
void matching_solve(matching_t matching);
INTERFACE_EXPORT
int32_t matching_get_match(matching_t matching, int32_t node);
INTERFACE_EXPORT
void matching_verbose(matching_t matching, bool verbose);
INTERFACE_EXPORT
int blossom5_julia_version_major();
INTERFACE_EXPORT
int blossom5_julia_version_minor();
#ifdef __cplusplus
}
#endif
<file_sep>/README.md
# BlossomV.jl
[](https://travis-ci.org/mlewe/BlossomV.jl)
This package provides a julia wrapper to the Blossom V software package which
provides an implementation of a minimum cost perfect matching algorithm.
Blossom V is available under http://pub.ist.ac.at/~vnk/software.html
The algorithm is described in
Blossom V: A new implementation of a minimum cost perfect matching algorithm.
<NAME>.
In Mathematical Programming Computation (MPC), July 2009, 1(1):43-67.
The Wrapper provided in this package is very simplistic, a nicer interface will
be provided in future versions. There are several things you can do that will
cause it to segfault -- often causing julia to segfault.
## Building
You can install the package with the usual `]add BlossomV`.
A common thing that goes wrong is not having current enough version of C++ and
its stdlibs. Currently the minimum requirements are a compiler supporting the
C++11 standard (e.g. gcc-4.6 on ubuntu 12.04, or newer, should be recent
enough).
## LICENSE
This wrapper library is provided under the terms given in the
[license](LICENSE.md).
Be aware that the code of the actual BlossomV library itself underlies a
different license.
It is up to you to check, whether or not that license is acceptable for your
usage.
<file_sep>/deps/interface/interface.cpp
#include "interface.h"
#include "PerfectMatching.h"
#include <memory>
struct matching {
template<typename... Args>
matching(Args&&... args)
: actual(std::forward<Args>(args)...)
{
}
PerfectMatching actual;
};
#ifdef __cplusplus
extern "C" {
#endif
matching_t matching_construct(int32_t node_num, int32_t edge_num_max) {
matching_t result = nullptr;
result = new matching(node_num, edge_num_max);
return result;
}
void matching_destruct(matching_t matching) {
delete matching;
}
int32_t matching_add_edge(matching_t matching, int32_t first_node, int32_t second_node, int32_t cost) {
return matching->actual.AddEdge(first_node, second_node, cost);
}
void matching_solve(matching_t matching) {
matching->actual.Solve();
}
int32_t matching_get_match(matching_t matching, int32_t node) {
return matching->actual.GetMatch(node);
}
void matching_verbose(matching_t matching, bool verbose) {
matching->actual.options.verbose = verbose;
}
int blossom5_julia_version_major() {
return 0;
}
int blossom5_julia_version_minor() {
return 4;
}
#ifdef __cplusplus
}
#endif
|
d8ec8fa37fb9af4dbd9c23ec25296da036c17a18
|
[
"TOML",
"C",
"C++",
"Markdown"
] | 5
|
C
|
mlewe/BlossomV.jl
|
fca1d332d98259c3928f4eecebb574ee9554d340
|
2ee4d8fe1bbf2f7ad949f6969a1426b3f7611d7b
|
refs/heads/master
|
<file_sep>import numpy as np #Para rellenar las matices
import random as rd #Para obtener las posiciones random
import time #Para el delay
'''Conway's Game of Life'''
#Funcion para crear universo(mundo)
def Universo(LiveCell):
universo = (np.zeros((30, 30))).astype(np.int64)#Rellena la matriz de 30x30 con celulas muertas
for cell in range(0,LiveCell): #Ingresa en posiciones random las celulas vivas
posX = rd.randrange(0,30,1)#Random de 0 a 30 con intervalos de 1
posY = rd.randrange(0,30,1)
universo[posX, posY] = 1 #Cambio de la celula muerta por la viva en la posion generada aleatoriamente
#print(universo)
return universo #Regresa el universo
#Funcion para ver los vecinos de alrededor de la celula
def Neighbors(universo):
size = universo.shape #Obtiene el tamaño de la matriz
newUniverse = (np.zeros((30,30))).astype(np.int64) #Se crea una nueva matriz que sera el nuevo universo
neighbor=0 #Variable que cuenta los vecinos
for row in range(0, size[0]): #Recorre la fila
for column in range(0, size[1]): #Recorre la columna
#Condiciones para encontrar los 8 vecinos, y no salir de los indices de la matriz
if column-1>=0:
if (universo[row, column-1])==1: #Verificar el vecino superior
neighbor+=1 #suma el vecino vivo
if row+1<size[0] and column-1>=0:
if (universo[row+1, column-1])==1:#Verificar el vecino superior derecho
neighbor+=1
if row +1< size[0]:
if(universo[row+1, column])==1: #Verificar el vecino derecho
neighbor+=1
if row +1< size[0] and column+1<size[1]:
if (universo[row+1, column+1])==1: #Verificar el vecino inferior derecho
neighbor+=1
if column+1<size[1]:
if (universo[row, column+1])==1: #Verificar el vecino inferior
neighbor+=1
if column-1>=0 and column+1<size[1]:
if (universo[row-1, column+1])==1: #Verificar el vecino inferior izquierdo
neighbor+=1
if row-1>=0:
if (universo[row-1, column])==1: #Verificar el vecino izquierdo
neighbor+=1
if row-1>=0 and column-1>=0:
if (universo[row-1, column-1])==1: #Verificar el vecino superior izquierdo
neighbor+=1
newUniverse[row, column]=LifeDead(neighbor, universo[row, column]) # Cambio de la celula a un nuevo estado segun las condiciones dadas en la funcion LifeDead
neighbor=0 #Regresa los vecinos a 0
return newUniverse # Regresa el nuevo universo
#Funcion para determinar si vive, muere o nace.
def LifeDead(neighbor, cell):
#Para la celulas vivas
if cell==1:
#Si tiene menos de dos vecinos muere
#Si tiene mas de 3 vecinos muere
if neighbor<2 or neighbor>3:
return 0 #Regresa el valor de la celula muerta
#Si la celula tiene dos o 3 vecinos continua viva
elif neighbor==2 or neighbor==3:
return 1 #Regresa el valor de la celula viva
#Para las celulas muertas
else:
#Si tiene tres vecinos la celula nace o vuelve a vivir
if neighbor==3:
return 1
else:
#En caso de que no tenga tres vecinos continua muerta
return 0
live = int(input('Enter the number of live cells: '))
iterations = int(input('Enter the number of iterations: '))
u=Universo(live) #Llamada para crear el universo dando el numero de las celulas vivas
for n in range(0, iterations):
print(u) #Imprime el universo en turno
u=Neighbors(u) #Obtiene los vecinos por lo cual crea el nuevo universo
print(" ") #Espacio entre universos
time.sleep(0.3) #Delay
|
795d122a5ac6796fc57fb9ad00633d5d4ae35c3c
|
[
"Python"
] | 1
|
Python
|
JulioC3094/Game-of-Life
|
df33ab0756a210dd41dd535b08f2d6660f01fbce
|
dc7317ad2c41e2e024fb09b708b2b05e17947031
|
refs/heads/master
|
<repo_name>LechuckThePirate/.flexget<file_sep>/plugins/windows_events.py
from __future__ import unicode_literals, division, absolute_import
from datetime import datetime
import contextlib
import logging
import mmap
import xml.etree.ElementTree as ET
from flexget import plugin
from flexget.event import event
from flexget.entry import Entry
log = logging.getLogger('winevents')
class WindowsEvents(object):
"""
Provide Windows 7 events entries as input.
Produced entries will have the events log id as title and url, plus these fields:
- provider
- short_name
- event_time
- event_id
- event_text
Example (complete task)::
test_monitor:
winevents:
filename: c:\windows\sysnative\winevt\logs\Application.evtx
providers:
- APC UPS Service:
short: UPS
events:
- 61455: test description
- Network something:
events:
- 673
- 345: whatever
accept_all: yes
notify_xmpp:
sender: <EMAIL>
password: <PASSWORD>
recipient: anotherjid@anotherdomain
"""
schema = {
'type': 'object',
'properties': {
'filename': {'type': 'string', 'format': 'filename'},
'providers': {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'short': {'type': 'string'},
'events': {
'type': 'array',
'items': {
'type': 'object',
'additionalProperties': {'type': 'string'}
},
'minItems': 1
},
},
'additionalProperties': {'required': ['events']}
},
'minItems': 1
}
},
'required': ['filename', 'providers'],
'additionalProperties': False
}
def on_task_start(self, task, config):
try:
import Evtx
except ImportError as e:
log.debug('Error importing Evtx: %s' % e)
raise plugin.DependencyError('winevents', 'python-evtx',
'Evtx module required. ImportError: %s' % e)
def on_task_input(self, task, config):
from Evtx.Evtx import FileHeader
from Evtx.Views import evtx_file_xml_view
entries = []
t1 = datetime.now()
ntot = 0
nerr = 0
# WARNING: to open an active Windows eventlog files (i.e. those in the
# %SystemRoot%\System32\Winevt\Logs\ path) Flexget will need to run as
# Administrator, otherwise open() will raise a "permission denied"
# error. Exported logs can be accessed without special permissions.
try:
f = open(config['filename'], 'r')
except Exception as err:
log.error(str(err))
return
try:
with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf:
fh = FileHeader(buf, 0x0)
for xml, record in evtx_file_xml_view(fh):
ntot += 1
# some cleaning: namespaces here only makes accessing
# nodes more difficult, while EventData content sometimes
# fails ElementTree parsing (and it's useless too).
xml = xml.replace(' xmlns="http://schemas.microsoft.com/win/2004/08/events/event"', '')
if '<EventData>' in xml:
i1 = xml.index('<EventData>')-1
i2 = xml.index('</EventData>')+12
xml = xml[:i1] + xml[i2:]
try:
node = ET.fromstring(xml).find('System')
except:
nerr += 1 # malformed XML? lets skip this one...
continue
xprn = node.find('Provider').attrib['Name']
for prov in config['providers']:
cprn = prov.keys()[0]
if cprn == xprn:
erid = node.find('EventRecordID').text
xeid = int(node.find('EventID').text)
text = None
for e in prov[cprn]['events']:
ceid = e if type(e) is int else e.keys()[0]
if ceid == xeid:
try:
text = e[ceid]
except:
text = 'Undefined'
if text:
entry = Entry()
entry['title'] = entry['url'] = erid
entry['provider'] = cprn
entry['short_name'] = prov[cprn]['short'] if 'short' in prov[cprn] else cprn
entry['event_id'] = xeid
entry['event_text'] = text
entry['event_time'] = datetime.strptime(node.find('TimeCreated').attrib['SystemTime'], '%Y-%m-%d %H:%M:%S')
entries.append(entry)
break
finally:
f.close()
t2 = datetime.now()
res = 'Parsed %d events in %d seconds' % (ntot, (t2-t1).seconds)
if nerr:
res += (' (%d skipped for xml issues)' % nerr)
log.verbose(res)
return entries
@event('plugin.register')
def register_plugin():
plugin.register(WindowsEvents, 'winevents', api_ver=2)
<file_sep>/README.md
#My [Flexget](https://github.com/Flexget/Flexget) Setup
Largely inspired to [jawilson](https://github.com/jawilson) setup.
17/08/2014: config_secrets plugin is in Flexget now.
<file_sep>/plugins/fix_subtitles.py
from __future__ import unicode_literals, division, absolute_import
import os
import chardet
import logging
import shutil
from flexget import plugin
from flexget.event import event
log = logging.getLogger('fix_subtitles')
class FixSubs(object):
"""
"""
schema = {
'oneOf': [
{'type': 'boolean'},
{'type': 'array', 'items': {'type': 'string'}, 'minItems': 1}
]
}
def on_task_exit(self, task, config):
exts = ['.it.srt', '.ita.srt']
if isinstance(config, list):
exts = [('.' + s).replace('..', '.') for s in config]
elif isinstance(config, bool) and not config:
return
for entry in task.accepted:
if not ('location' in entry and os.path.exists(entry['location'])):
continue
fn = os.path.splitext(entry['location'])[0]
for ext in exts:
sub = fn + ext
if not os.path.exists(sub):
continue
try:
with open(sub, 'r') as f:
txt = f.read()
enc = chardet.detect(txt)['encoding']
log.debug('encoding is %s for file %s' % (enc, sub))
if enc == 'utf-8' and '\xc3' in txt:
log.verbose('this file contains wrong characters!')
txt = txt.replace('ŕ', 'à').replace('č', 'è').replace('ě', 'ì').replace('ň', 'ò').replace('ů', 'ù').replace('Č', 'È')
bak = sub + '.bak'
if os.path.exists(bak):
raise plugin.PluginWarning('backup already exists')
shutil.copy(sub, bak)
with open(sub, 'w') as f:
f.write(txt)
log.info('Subtitles file fixed: ' + sub)
except Exception as err:
log.error('Error on file %s: %s' % (sub, err))
@event('plugin.register')
def register_plugin():
plugin.register(FixSubs, 'fix_subtitles', api_ver=2)<file_sep>/plugins/forget_series.py
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.event import event
from flexget.components.series.db import remove_series
log = logging.getLogger('forget_series')
class ForgetSeries(object):
"""
Forget the given episode for series. Uses series_name and series_id.
Example::
forget_series: yes
"""
schema = {'type': 'boolean'}
def on_task_output(self, task, config):
if not (config and task.accepted):
return
for entry in task.accepted:
s = entry['title']
try:
log.info('Removing series "%s"' % s)
remove_series(s)
except ValueError as e:
log.error(e)
@event('plugin.register')
def register_plugin():
plugin.register(ForgetSeries, 'forget_series', api_ver=2)
<file_sep>/plugins/require_file.py
from __future__ import unicode_literals, division, absolute_import
import os
import logging
from flexget import plugin
from flexget.event import event
log = logging.getLogger('require_file')
class RequireFile(object):
"""
"""
schema = {'type': 'boolean'}
def on_task_filter(self, task, config):
if not config:
return
for entry in task.accepted:
if not 'location' in entry or not os.path.exists(entry['location']):
entry.reject('file not found "%s"' % entry.get('location', 'Undefined'))
@event('plugin.register')
def register_plugin():
plugin.register(RequireFile, 'require_file', api_ver=2)
<file_sep>/plugins/series_list.py
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.components.series.db import Series
log = logging.getLogger('extratorrent')
class GetSeriesList(object):
schema = {"type": "boolean"}
def on_task_input(self, task, config):
"""asd"""
slist = task.session.query(Series).order_by(Series.name).all()
entries = []
for series in slist:
entry = Entry()
entry['title'] = series.name
entry['url'] = 'http://localhost/mock/%s' % hash(entry['title'])
if entry.isvalid():
entries.append(entry)
else:
log.debug('Invalid entry created? %s' % entry)
return entries
@event('plugin.register')
def register_plugin():
plugin.register(GetSeriesList, 'series_list', api_ver=2)
<file_sep>/plugins/episodes_list.py
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.components.series.db import Series, Episode
from flexget.components.series.utils import normalize_series_name
from sqlalchemy import func
log = logging.getLogger('next_series_episodes')
class GetEpisodesList(object):
schema = {
"oneOf": [
{"type": "boolean"},
{"type": "string"}
]
}
def on_task_input(self, task, config):
"""asd"""
slist = task.session.query(Series)
if isinstance(config, basestring):
name = normalize_series_name(config)
slist = slist.filter(Series._name_normalized.contains(name))
slist = (slist.outerjoin(Series.episodes).outerjoin(Episode.releases).outerjoin(Series.in_tasks).
order_by(Series.name).all())
entries = []
for series in slist:
elist = (task.session.query(Episode).filter(Episode.series_id == series.id).
order_by(Episode.season, Episode.number).all())
for episode in elist:
log.debug('Found episode %s for series "%s"' % (episode.identifier, series.name))
entry = Entry()
entry['title'] = '%s %s' % (series.name, episode.identifier)
entry['url'] = 'http://localhost/mock/%s' % hash(entry['title'])
if entry.isvalid():
entries.append(entry)
else:
log.debug('Invalid entry created? %s' % entry)
return entries
@event('plugin.register')
def register_plugin():
plugin.register(GetEpisodesList, 'episodes_list', api_ver=2)
|
e46ba62c4c5779a4d19eac2b9ed0a9d8f4d01191
|
[
"Markdown",
"Python"
] | 7
|
Python
|
LechuckThePirate/.flexget
|
054ee832bbec595ebffa496789300ccd857aef57
|
7b91fd249f54ab5a7b47563e1fa7e517584881af
|
refs/heads/master
|
<file_sep>STDOUT.sync = true
puts 'What is your name?'
name= gets.chomp
puts "Hello, #{name}!"
puts "Enter the number of the game you'd like to play"
puts "1) Fifa 2004"
puts "2) Pong"
puts "3) <NAME> 64"
puts "4) Super Smash Brothers"
puts "5) Global Thermonuclear War"
selection =gets.chomp
if selection == "5"
puts "BOOM!"
else
puts "I refuse to play"
end
|
16f81da679df2f0703bdfa740497223f3751457d
|
[
"Ruby"
] | 1
|
Ruby
|
tall-dan/Lab9-schepedw
|
a5239c2f57c34c020ca2f387a62a59f205d83ef2
|
207102937b0053529d299367efe8d93b16a6736b
|
refs/heads/master
|
<repo_name>olala13/matricy<file_sep>/matriciiii.c
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
int multi = 0;
void *multiscal(int* c)
{
multi = multi + (*(c)) * (*(c+1));
return 0;
}
// Comment
int main(void)
{
int i;
srand(time(NULL));
int n = rand() % 10 + 2;
int a[n], b[n];
for (i = 0; i < n; i++)
{
a[i] = rand() % 16;
b[i] = rand() % 16;
}
printf("N = %d\n", n);
printf("Vector a = ");
for(i = 0; i < n; i++)
printf("%d, ", a[i]);
printf("\n");
printf("Vector b = ");
for(i = 0; i < n; i++)
printf("%d, ", b[i]);
printf("\n");
int c[2];
pthread_t multithr[n];
for(i = 0; i < n; i++)
{
c[0] = a[i];
c[1] = b[i];
int status = pthread_create( &(multithr[i]), (pthread_attr_t *) NULL, (void*) multiscal, &c);
if (status != 0)
{
printf("Thread was not created! Error # %d\n", status);
exit(-1);
}
int statusj = pthread_join(multithr[i], (void**) NULL);
if (statusj != 0)
{
printf("Can't wait for the thread # %d\n", i);
exit(-1);
}
}
printf("The scalar multiply of vectors a and b is %d\n", multi);
}
|
074ee5840ca54b6400d210bccfa45bf211625724
|
[
"C"
] | 1
|
C
|
olala13/matricy
|
dbdfe1eef922b49b7f566b81b511a3d22a2f9cc5
|
2c513b2e99e3372d7de48fa84c3f945a9fb65d14
|
refs/heads/master
|
<file_sep>import PlaygroundSupport
import AVFoundation
import UIKit
import CoreML
import Vision
class MainView : UIViewController, AVCapturePhotoCaptureDelegate {
private var _session: AVCaptureSession?
private var _input : AVCaptureInput?
private var _imageOut: AVCapturePhotoOutput?
private var _frontCamera: AVCaptureDevice?
private var _previewView : UIView?
private var _previewLayer : AVCaptureVideoPreviewLayer?
private var model : MLModel?
public override func loadView() {
_previewView = UIView()
guard let view = _previewView else{
print("Could not initialize view")
return
}
view.backgroundColor = UIColor.white
self.view = view
}
public override func viewWillAppear(_ animated: Bool) {
do {
let compiledModelUrl = try MLModel.compileModel(at: Bundle.main.url(forResource: "TireClassifier", withExtension: "mlmodel")!)
model = try! MLModel(contentsOf: compiledModelUrl)
} catch {
print(error.localizedDescription)
}
super.viewWillAppear(animated)
_session = AVCaptureSession()
guard let session = _session else{
print( "An error occurred while initiating the AV Capture Session!")
return
}
session.beginConfiguration()
session.sessionPreset = .photo
_frontCamera = AVCaptureDevice.default(for: AVMediaType.video)
guard let frontCamera = _frontCamera
else {
print( "Cannot start front camera!")
return
}
do{
_input = try AVCaptureDeviceInput(device: frontCamera)
} catch let err as NSError {
print( err.localizedDescription)
return
}
guard let input = _input else {
print( "Cannot start input!")
return
}
session.addInput(input)
_imageOut = AVCapturePhotoOutput()
guard let imageOut = _imageOut else{
print("An error ocurred!")
return
}
session.addOutput(imageOut)
session.commitConfiguration()
_previewLayer = AVCaptureVideoPreviewLayer(session: session)
guard let previewLayer = _previewLayer else{
print("Cannot config preview layer")
return
}
self.view.layer.addSublayer(previewLayer)
previewLayer.frame = self.view.frame
session.startRunning()
_imageOut = imageOut
print(imageOut)
}
public override func viewDidLoad() {
super.viewDidLoad()
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard let previewLayer = _previewLayer else {
print("cannot initilaize")
return
}
previewLayer.bounds = self.view.bounds
previewLayer.frame = self.view.frame
/*let image = UIImageView(image: UIImage(named: "tire.png"))
image.frame = CGRect(x: 0, y: self.view.frame.height - 200 , width: self.view.frame.width, height: 200)
view.addSubview(image)*/
let but = UIButton(frame: CGRect(x: 0, y: self.view.frame.height - 200 , width: self.view.frame.width, height: 200))
but.setImage( UIImage(named: "tire.png"), for: .normal)
but.addTarget(self, action: #selector(analyze), for: .touchUpInside)
view.addSubview(but)
}
@objc func analyze(){
let settings = AVCapturePhotoSettings()
let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first!
_imageOut!.capturePhoto(with: settings, delegate: self)
}
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
guard let model = try? VNCoreMLModel(for: model!) else { return }
let request = VNCoreMLRequest(model: model) { (data, error) in do {
guard let results = data.results as? [VNClassificationObservation] else { return }
// Assigns the first result (if it exists) to firstObject
guard let firstObject = results.first else { return }
if firstObject.confidence * 100 >= 50 {
let alertController = UIAlertController(title: "Good Tire", message: "Your tire looks good to me! please make sure to go to a specialist to take a look!", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
}else{
let alertController = UIAlertController(title: "Bad Tire", message: "Your tire does not look that great, please make sure to go to a specialist to take a look!", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
}
}
}
try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])
}
}
PlaygroundPage.current.liveView = MainView()
|
3f2b1ede97003285bb60c153bf30c979f356f75f
|
[
"Swift"
] | 1
|
Swift
|
pedromoter/WWDC19
|
9f30391249ca3abfe667fd5b838c684daba7f2e0
|
19c2e60eeec2e86b8eafed6bd70e67e7cf42e395
|
refs/heads/main
|
<repo_name>13955413303/pytest-demo<file_sep>/testcase/conftest.py
import pytest
@pytest.fixture(scope='function')
def all_fixture():
print('这是前置的方法')
yield
print('这是后置的方法')<file_sep>/testcase/user/test_mashang2.py
def test_huahua(all_fixture,user_fixture):
print('\nmashang2')
print('---------------------',all_fixture)
print('======================',user_fixture)
def test_huahua1(all_fixture,user_fixture):
print('\nmashang2')
print('---------------------',all_fixture)
print('======================',user_fixture)
assert 1==2
<file_sep>/README.md
# pytest-demo
<file_sep>/testcase/yaml_util.py
import yaml
class YamlUtil:
def __init__(self,yaml_file):
"""
通过init方法把yaml文件传入类
:param yaml_file:
"""
self.yaml_file = yaml_file
# 读取yaml文件
def read_yaml(self):
"""
读取yaml,对yanl反序列化,把yaml格式转换成dict格式
:return:
"""
with open(self.yaml_file,encoding='utf-8')as fp:
value = yaml.load(fp,Loader=yaml.FullLoader)
print(value)
fp = open(self.yaml_file,encoding='utf-8')
value = yaml.load(fp,Loader=yaml.FullLoader)
print(value)
return value
if __name__ == '__main__':
YamlUtil('test_api.yaml').read_yaml()<file_sep>/testcase/user/conftest.py
import pytest
@pytest.fixture(scope='function')
def user_fixture():
print('这是用户管理前置的方法')
yield
print('这是用户管理后置的方法')<file_sep>/testcase/product/test_mashang.py
def test_huahua(product_fixture):
print('\nmashang1')
print('======================',product_fixture)
<file_sep>/testcase/product/conftest.py
import pytest
@pytest.fixture(scope='function')
def product_fixture():
print('这是商品管理前置的方法')
yield
print('这是商品管理后置的方法')<file_sep>/pytest.ini
[pytest]
# addopts = -vs --alluredir ./temp --reruns 2
addopts = -vs
testpaths = ./
python_files = test_api.py
python_classes = Test*
python_functions = test
markers =
smoke:冒烟测试
product:商品模块
user:用户模块<file_sep>/testcase/test_zyang.py
import random
import sys
import pytest
def start_class():
print('this is class begin')
def end_class():
print('this is class finish')
def start_func():
print('this is function start ')
def end_func():
print('this is function end ')
@pytest.fixture(scope='class',autouse=True)
def my_class_fixture():
start_class()
yield
end_class()
class TestZyang():
@pytest.fixture(scope='function', autouse=False, params=['aaa', 'bbb', 'ccc'])
def my_function_fixture(self, request):
start_func()
yield request.param
end_func()
def test_001(self, my_function_fixture):
try:
assert random.randint(0, 1)
except AssertionError:
# print(sys._getframe().f_code.co_name)
raise AssertionError
def test_002(self):
try:
assert random.randint(0, 1)
except AssertionError:
print(sys._getframe().f_code.co_name)
raise AssertionError
# class TestZyang:
# def setup_class(self):
# print('\nbegin--test', end='')
#
# def setup(self):
# print('\nstart_test_case ')
#
# def test_001(self):
# try:
# assert random.randint(0, 1)
# except AssertionError:
# print(sys._getframe().f_code.co_name)
# raise AssertionError
#
# def test_002(self):
# try:
# assert random.randint(0, 1)
# except AssertionError:
# print(sys._getframe().f_code.co_name)
# raise AssertionError
#
# def teardown(self):
# print('\nend_test_case')
#
# def teardown_class(self):
# print('finish--test')
<file_sep>/testcase/test_api.py
import pytest
import requests
import json
from testcase.yaml_util import YamlUtil
class TestApi:
@pytest.mark.parametrize('args',YamlUtil('testcase/test_api.yaml').read_yaml())
def test_02(self,args):
url = args['request']['url']
method= args['request']['method']
headers = args['request']['headers']
params = args['request']['params']
resp = requests.request(url=url,method=method,params=params,headers=headers)
resp = json.loads(resp.text)
if 'eq' in args['assert']:
assert args['assert']['eq']['ret'] == resp['ret']
|
bc4d1d7ac8acec66200a8cb232c77d50046beca3
|
[
"Markdown",
"Python",
"INI"
] | 10
|
Python
|
13955413303/pytest-demo
|
2ffdbfeb6f7bfdea740a3cb8da941864363a0b09
|
38115cbd9b839a06d5823cef34c0282f927b4ef0
|
refs/heads/master
|
<repo_name>Charlienofun/SimPanelEncoder<file_sep>/src/main.cpp
// <NAME> 11/15/20
//
#include <Joystick.h>
#include <CD74HC4067.h>
// Vars
const int numberOfDirectlyConnectedButtons = 3;
const int buttonMap[numberOfDirectlyConnectedButtons] = {2,3,4}; // These are the pins on the Pro Mini (not the multiplexer)
const int pinToButtonMap = buttonMap[0]; // Constant that maps the phyical pin to the joystick button.
int lastButtonState[numberOfDirectlyConnectedButtons] = {0,0,0}; // Last state of the buttons attached to the device directly
// s0 s1 s2 s3
CD74HC4067 my_mux(5, 6, 7, 8); // create a new CD74HC4067 object with its four control pins
int lastButtonStateOfMultiplexer[16]; // Last state of the buttons attached to the device via the multiplexer=
const int g_common_pin = 10; // select a pin to share with the 16 channels of the CD74HC4067
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,JOYSTICK_TYPE_GAMEPAD,
19, 0, // Button Count, Hat Switch Count
false, false, false, // X and Y, but no Z Axis
false, false, false, // No Rx, Ry, or Rz
false, false, // No rudder or throttle
false, false, false); // No accelerator, brake, or steering
void setup() {
// Set the directly attached pins to be inputs with pullup enabled.
for (int index = 0; index < (numberOfDirectlyConnectedButtons - 1); index ++) {
pinMode(buttonMap[index], INPUT_PULLUP);
}
// Set the common input pin attached via the multiplexer to have pullup enabled.
pinMode(g_common_pin, INPUT_PULLUP); // set the initial mode of the common pin. (This can be changed in loop() for for each channel)
// init the arrays for the button states
for (int index = 0; index < 15; index ++) {
// Set each of the 16 button states to 0
lastButtonStateOfMultiplexer[index] = 0;
}
// Initialize Joystick Library
Joystick.begin();
// Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// Read pin values
for (int index = 0; index < (numberOfDirectlyConnectedButtons); index++)
{
int currentButtonState = !digitalRead(index + pinToButtonMap);
if (currentButtonState != lastButtonState[index])
{
Joystick.setButton(index + 16, currentButtonState); // 16 because the first 16 are from the multiplexer
lastButtonState[index] = currentButtonState;
}
}
// Read the multiplxer and send the presses
for (int i = 0; i < 16; i++) {
my_mux.channel(i);
// Serial.println(i);
// if (!digitalRead(g_common_pin)) {
// Serial.println("its Happening!!");
// }
// delay(400);
int currentButtonState = !digitalRead(g_common_pin);
if (currentButtonState != lastButtonStateOfMultiplexer[i]) {
Joystick.setButton(i, currentButtonState);
//Serial.println("Hello Computer");
//Serial.print(i);
//Serial.print(currentButtonState);
lastButtonStateOfMultiplexer[i] = currentButtonState;
}
}
}
|
0dcd6879f918abffd766030d536b93e6bbb24aca
|
[
"C++"
] | 1
|
C++
|
Charlienofun/SimPanelEncoder
|
3e1de139dc030b1f006ad5a7c21c8db453b71410
|
b7fb4171db605315aebda1a0e2773bcd2ec1ab57
|
refs/heads/master
|
<repo_name>fernode/site-casa-do-codigo<file_sep>/README.md
# site-casa-do-codigo
Site casa do codigo com node js com objetivo de estudos
Primeiro entre na pasta raiz do projeto e baixe todas as dependências com npm install
Para rodar o projeto localmente é só dar o comando node app.js o projeto estará rodando na porta 3000
<file_sep>/app.js
const app = require('./config/express')();
/*const rotasProdutos = require('./app/rotas/produtos')(app);
Não há mais necessidade de ser carregado, porquê estou usando o express-load
para carregar os arquivos.
*/
const server = app.listen(3000, () => {
console.log('Servidor está rodando na porta 3000');
});
|
08dade3f7cc9f0eef071007f93dcd973a84410cc
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
fernode/site-casa-do-codigo
|
b9367c0a61c7927d2a364c2469f70016a20703a6
|
cdf6d2b7f0cba7f9e0389d39785b45ac3b7012ff
|
refs/heads/master
|
<repo_name>osharim/ethereum-escrow<file_sep>/src/javascript/web3/index.js
import Web3 from "web3";
import { default as contract } from 'truffle-contract'
import trustless_escrow_artifacts from '../../../build/contracts/TrustlessEscrow.json'
var _web3Instance;
// web3 setup
if (typeof web3 !== 'undefined') {
_web3Instance = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
_web3Instance = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
_web3Instance.eth.getAccounts(function(err, accs) {
if (err != null) {
alert("There was an error fetching your accounts. Are you using a web3 compatible browser?");
return;
}
if (accs.length == 0) {
alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
return;
}
});
var TrustlessEscrow = contract(trustless_escrow_artifacts);
TrustlessEscrow.setProvider(_web3Instance.currentProvider);
// TODO: Remove these two lines
window.web3 = _web3Instance;
window.TrustlessEscrow = TrustlessEscrow;
export default TrustlessEscrow;
<file_sep>/test/actions/createAgreement.js
// @flow
declare var artifacts: Artifacts;
let TrustlessEscrow = artifacts.require("TrustlessEscrow");
contract('createAgreement', function(accounts: string[]): void {
describe.skip("createAgreementPending");
describe.skip("createAgreementFulfilled");
describe.skip("createAgreementFailed");
describe.skip("createAgreement");
});
// export function createAgreementPending(): PendingAction {
// return {
// type: 'CREATE_AGREEMENT_PENDING'
// };
// }
// export function createAgreementFulfilled(transactionHash: string): FulfilledAction {
// return {
// type: 'CREATE_AGREEMENT_FULFILLED',
// payload: transactionHash
// };
// }
// export function createAgreementFailed(error: string): FailedAction{
// return {
// type: 'CREATE_AGREEMENT_FAILED',
// payload: error
// };
// }
// // transaction options will be "any" for now
// export function createAgreement(buyer: string, seller: string, price: string, txOptions: any): ThunkAction {
// // Thunk middleware knows how to handle functions.
// // It passes the dispatch method as an argument to the function,
// // thus making it able to dispatch actions itself.
// return function (dispatch) {
// // First dispatch: the app state is updated to inform
// // that the API call is starting.
// dispatch(createAgreementPending());
// // The function called by the thunk middleware can return a value,
// // that is passed on as the return value of the dispatch method.
// // In this case, we return a promise to wait for.
// // This is not required by thunk middleware, but it is convenient for us.
// return TrustlessEscrow.deployed()
// .then(escrowContract => escrowContract.createAgreement(buyer, seller, price, txOptions))
// .then(txHash => dispatch(createAgreementFulfilled(txHash)))
// .catch(e => dispatch(createAgreementFailed(e)));
// }
// }<file_sep>/test/actions/agreementList.js
// @flow
declare var artifacts: Artifacts;
let TrustlessEscrow = artifacts.require("TrustlessEscrow");
contract('agreementList', function(accounts: string[]): void {
describe.skip("sendMoney");
describe.skip("confirmAgreement");
describe.skip("cancelAgreement");
});
// export function sendMoney(transactionHash: string, position: string):ThunkAction {
// return (dispatch) => {
// // as always, return a spinner
// dispatch(requestPending());
// //TODO: need to add the correct reducers
// return dispatch(sellerSendsMoney(transactionHash));
// }
// }
// export function comfirmTransaction(transactionHash: string): ThunkAction {
// return (dispatch) => {
// dispatch(requestPending());
// // check that the transaction was finished
// }
// }
// export function cancelTransaction(transactionHash: string): ThunkAction {
// return (dispatch) => {
// dispatch(requestPending());
// // check and then return
// }
// }
|
42d3ef62dd9a0ba33933a6bea2d29dad1346b3c2
|
[
"JavaScript"
] | 3
|
JavaScript
|
osharim/ethereum-escrow
|
8d165aa8c2da66baf938c1c029693a11949a16e5
|
8f004b42f72b655980294c6b4d8a7888b9fab4ec
|
refs/heads/master
|
<repo_name>naergaga/TextReplace<file_sep>/TextReplace/TextReplace/Services/TextReplaceService.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace TextReplace.Services
{
public class TextReplaceService
{
const int bufferSize = 1024 * 1014;
public void Replace(string path, string oldStr, string newStr)
{
var outPath = path.Replace(".txt", ".out.txt");
Replace(path, outPath, oldStr, newStr);
File.Delete(path);
File.Move(outPath, path);
}
public void Replace(string path, string outPath, string oldStr, string newStr)
{
FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(stream);
if (reader.CurrentEncoding == Encoding.UTF8)
{
var charArray = new char[1024];
reader.Read(charArray, 0, charArray.Length);
var buffer1 = Encoding.UTF8.GetBytes(charArray);
var buffer2 = new byte[buffer1.Length];
stream.Position = 0;
stream.Read(buffer2, 0, buffer2.Length);
var same = true;
for (int i = 0; i < buffer1.Length; i++)
{
if (buffer1[i] != buffer2[i])
{
same = false;
break;
}
}
if (!same)
{
stream.Position = 0;
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
reader = new StreamReader(stream, Encoding.GetEncoding("GBK"));
}else
{
stream.Position = 0;
reader = new StreamReader(stream);
}
}
var writer = new StreamWriter(outPath, false, reader.CurrentEncoding);
char[] bufferText = new char[bufferSize];
int size;
while ((size = reader.Read(bufferText, 0, bufferSize)) > 0)
{
var str = new String(bufferText, 0, size);
str = str.Replace(oldStr, newStr);
writer.Write(str);
}
reader.Close();
writer.Close();
}
}
}
<file_sep>/TextReplace/TextReplace/MainPageModel.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace TextReplace
{
public delegate void SelectFile();
public delegate void CheckPermission();
public class MainPageModel
{
public SelectFile SelectFile { get; set; }
public string Path { get; set; }
}
}
<file_sep>/TextReplace/TextReplace/MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TextReplace.Services;
using Xamarin.Forms;
namespace TextReplace
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPageModel Model { get; set; }
public MainPage()
{
InitializeComponent();
}
public void SelectFileClick(object sender, EventArgs e)
{
Model.SelectFile();
}
public void ReplaceClick(object sender, EventArgs e)
{
var oldStr = EntryOldStr.Text;
var newStr = EntryNewStr.Text;
var service = new TextReplaceService();
service.Replace(Model.Path, oldStr, newStr);
}
}
}
<file_sep>/TextReplace/TextReplaceTests/Services/TextReplaceServiceTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TextReplace.Services;
using System;
using System.Collections.Generic;
using System.Text;
namespace TextReplace.Services.Tests
{
[TestClass()]
public class TextReplaceServiceTests
{
[TestMethod()]
public void ReplaceTest()
{
var service = new TextReplaceService();
service.Replace(@"D:\test.txt", @"D:\test1.txt", "!", "。");
}
}
}<file_sep>/TextReplace/TextReplace.Android/MainActivity.cs
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Content;
using Android;
namespace TextReplace.Droid
{
[Activity(Label = "TextReplace", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
private MainPageModel model = new MainPageModel();
const int REQUEST_TEXT_GET = 1;
const int REQUEST_EXTERNAL_STORAGE = 2;
private void SelectFile()
{
var intent = new Intent(Intent.ActionGetContent);
intent.SetType("text/plain");
intent.AddCategory(Intent.CategoryOpenable);
StartActivityForResult(intent, REQUEST_TEXT_GET);
}
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
var page = App.Current.MainPage as MainPage;
page.Model = model;
model.SelectFile = SelectFile;
}
protected override void OnStart()
{
CheckPermission();
base.OnStart();
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
public void CheckPermission()
{
//检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
if (CheckSelfPermission(Manifest.Permission.WriteExternalStorage) != Permission.Granted || CheckSelfPermission(Manifest.Permission.ReadExternalStorage) != Permission.Granted)
{
//用户已经拒绝过一次,再次弹出权限申请对话框需要给用户一个解释
if (ShouldShowRequestPermissionRationale(Manifest.Permission.WriteExternalStorage) || ShouldShowRequestPermissionRationale(Manifest.Permission.ReadExternalStorage))
{
Toast.MakeText(this, "请开通相关权限,否则无法正常使用本应用!", ToastLength.Short).Show();
}
//申请权限
this.RequestPermissions(new string[] { Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadExternalStorage },
REQUEST_EXTERNAL_STORAGE
);
}
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if (resultCode == Result.Ok)
{
switch (requestCode)
{
case REQUEST_TEXT_GET:
model.Path = PathUtil.GetActualPathFromFile(this, data.Data);
break;
}
}
}
}
}
|
3f17bb27d3eea93188681aae48476891aeca0de0
|
[
"C#"
] | 5
|
C#
|
naergaga/TextReplace
|
fdf70372a52a4c92dbef7a14a566fefd2ca7d222
|
31a32857210c39f05eb863e06c6370530f491a93
|
refs/heads/master
|
<file_sep>#remove old objects
rm *.o
rm *.out
rm *.list
#compile cpp files
g++ -m64 -c -o Grammar.o Grammar.cpp
g++ -m64 -c -o main.o main.cpp
g++ -m64 -c -o Node.o Node.cpp
g++ -m64 -c -o Parser.o Parser.cpp
g++ -m64 -c -o Symbol.o Symbol.cpp
g++ -m64 -c -o SymTable.o SymTable.cpp
g++ -m64 -c -o token.o token.h
g++ -m64 -c -o token_printer.o token_printer.cpp
g++ -m64 -c -o Tokenizer.o Tokenizer.cpp
g++ -m64 -c -o txt_to_strings.o txt_to_strings.cpp
#link all files
g++ -m64 -o project.out Grammar.o main.o Node.o Parser.o Symbol.o SymTable.o token.o token_printer.o Tokenizer.o txt_to_strings.o
sleep 10s
#call program
./project.out<file_sep>#pragma once
#include <string>
#include <vector>
#include "token.h"
#include <regex>
using namespace std;
const int KEY_WORD_SIZE = 13;
string keyWord[KEY_WORD_SIZE] = {
"prog", "main", "fcn", "class",
"float", "int", "string", "if",
"elseif", "else", "while", "input",
"print"
};
static const string NOTKWD("NOTKWD");
struct token {
int ln; // line number
string id; // id based on grammar
int ix; // optional; index number
string str; // optional; actual string
token() {}
token(string rId) {
id = rId;
}
friend bool operator==(const token& lhs, const token& rhs) {
return lhs.id == rhs.id;
}
};
bool isLetter(char, bool);
bool isNumber(char, bool);
string whichKwd(string);
string whichNumType(string);
token tokenate(int, string, int, string);
token tokenate(int, string, string);
token tokenate(int, string);
vector<token> tokenize(vector<string>);
void token_printer(string _Language, vector<token> &tokens);
bool isLetter(char c, bool firstChar) {
string s = string(1, c);
if (firstChar)
return regex_match(s, regex("[a-zA-Z_]"));
else
return regex_match(s, regex("[a-zA-Z_0-9]"));
}
bool isNumber(char c, bool firstChar) {
string s = string(1, c);
if (firstChar)
return regex_match(s, regex("[-0-9]"));
else
return regex_match(s, regex("[\\.0-9]"));
}
string whichKwd(string s) {
// TODO: Check whether string is a keyword
// otherwise return NOTKWD
string key = "kwd";
for (int i = 0; i < KEY_WORD_SIZE; ++i)
{
if (s == keyWord[i])
{
key += keyWord[i];
return key;
}
}
/*if (s == "prog") {
return "kwdprog";
}*/
return NOTKWD;
}
string whichNumType(string s) {
// TODO: Check whether string is a float
// or an int
if (regex_match(s, regex("-?[0-9]*\\.[0-9]+"))) {
return "float";
}
else if (regex_match(s, regex("-?[0-9]+"))) {
return "int";
}
return "wrong";
}
token tokenate(int ln, string id, int ix, string str) {
token tkn = *new token();
tkn.ln = ln;
tkn.id = id;
tkn.ix = ix;
tkn.str = str;
return tkn;
}
token tokenate(int ln, string id, string str) {
token tkn = *new token();
tkn.ln = ln;
tkn.id = id;
tkn.str = str;
return tkn;
}
token tokenate(int ln, string id) {
token tkn = *new token();
tkn.ln = ln;
tkn.id = id;
return tkn;
}
vector<token> tokenize(vector<string> lines) {
vector<token> TokenList = *new vector<token>();
// Vriables for token creation
int currLine = 0;
int currTokenIndex = 0;
string currID;
string currString;
if (!lines.empty()) { // Make sure lines is not empty
for (size_t i = 0; i < lines.size(); i++) { // Going through each line
currLine++; // Increment line number
currTokenIndex = 0; // Reset token index
for (size_t _char = 0; _char < lines[i].length(); _char++) { // Going through each character in a line
if (lines[i][_char] == '/') {
// Check for comments
if (lines[i][_char + 1] == '/') {
break; // A comment has been found, stop processing this line and move on to the next
}
// 48 slash = '/'
else {
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "slash"));
}
}
else if (lines[i][_char] == '"') { // The beginning of a string has been found
string s;
++_char;
while (lines[i][_char] != '"') { // Until the quote is closed keep apending chars to the string
s.append(string(1, lines[i][_char]));
++_char;
}
currTokenIndex++;
// create token for string
TokenList.push_back(tokenate(currLine, "string", s));
}
// If the first character is a letter extract
// the whole word (from current character until
// you reach a non-word character)
else if (isLetter(lines[i][_char], true)) {
string s = string(1, lines[i][_char]);
_char++;
while (isLetter(lines[i][_char], false)) {
s.append(string(1, lines[i][_char]));
_char++;
}
_char--;
if (whichKwd(s) == NOTKWD) { // If not a kwd then it's ident
currTokenIndex++;
// create token for ident
TokenList.push_back(tokenate(currLine, "id", currTokenIndex, s));
}
else {
currTokenIndex++;
// create token for kwd
TokenList.push_back(tokenate(currLine, whichKwd(s)));
}
}
else if (isNumber(lines[i][_char], true)) {
string intStr = string(1, lines[i][_char]);
_char++;
// ERROR Check: can't have -.1 need -0,1
while (isNumber(lines[i][_char], false)) {
intStr.append(string(1, lines[i][_char]));
_char++;
}
_char--;
if (whichNumType(intStr) == "int") { // If not a float it's int
currTokenIndex++;
// create token for int
TokenList.push_back(tokenate(currLine, "int", intStr));
}
else if (whichNumType(intStr) == "float") {
currTokenIndex++;
// create token for float
TokenList.push_back(tokenate(currLine, "float", intStr));
}
}
else {
switch (lines[i][_char]) {
// Paired delimeters
// 6 comma = ','
case ',':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "comma"));
break;
// 7 semi = ';'
case ';':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "semi"));
break;
// 31 angle1 = '<'
case '<':
if (lines[i][_char + 1] == '=') {
// 54 ople = "<="
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "ople"));
}
// 56 opshl = "<<"
else if (lines[i][_char + 1] == '<') {
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "opshl"));
}
else {
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "angle1"));
}
break;
// 32 angle2 = '>'
case '>':
if (lines[i][_char + 1] == '=') {
// 55 opge = ">="
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "opge"));
}
else if (lines[i][_char + 1] == '>') {
// 57 opshr = ">>"
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "opshr"));
}
else {
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "angle2"));
}
break;
// 33 brace1 = '{'
case '{':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "brace1"));
break;
// 34 brace2 = '}'
case '}':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "brace2"));
break;
// 35 bracket1 = '['
case '[':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "bracket1"));
break;
// 36 bracket2 = ']'
case ']':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "bracket2"));
break;
// 37 parens1 = '('
case '(':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "paren1"));
break;
// 38 parens2 = ')'
case ')':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "paren2"));
break;
// Other punctuation
// 41 aster = '*'
case '*':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "aster"));
break;
// 42 caret = '^'
case '^':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "caret"));
break;
// 43 colon = ':'
case ':':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "colon"));
break;
// 44 dot = '.'
case '.':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "angle1"));
break;
// 45 equal = '='
case '=':
if (lines[i][_char + 1] == '=') {
// 52 opeq = "=="
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "opeq"));
}
else {
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "equal"));
}
break;
// 46 minus = '-'
//May need to include with number check
case '-':
if (lines[i][_char + 1] == '>') {
// 51 oparrow = "->"
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "oparrow"));
}
else {
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "minus"));
}
break;
// 47 plus = '+'
case '+':
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "plus"));
break;
// 53 opne = "!="
case '!':
if (lines[i][_char + 1] == '=') {
currTokenIndex++;
TokenList.push_back(tokenate(currLine, "opne"));
}
break;
default:
break;
}
}
}
}
}
return TokenList;
}
void token_printer(string _Language, vector<token> &tokens) { // Prints out all tokens
cout << "(:lang " << _Language << endl; // Print the language
for (size_t i = 0; i < tokens.size(); i++) { // For each token in our tokens vector
for (int i = 0; i < 3; i++) { // Indent the new line
cout << " ";
}
cout << "(:token " << tokens[i].ln << " " << tokens[i].id; // Print line number
if (tokens[i].id == "id") { // If the token has an index, print it
cout << " :ix " << tokens[i].ix;
}
if (tokens[i].id == "id" |
tokens[i].id == "string" |
tokens[i].id == "int" |
tokens[i].id == "float") {
cout << " :str \"" << tokens[i].str << "\""; // If the token has a str, print it
}
cout << ")" << endl; // Finish printing that token
}
cout << ")" << endl; // Finish the print function
}<file_sep>#pragma once
#include <iostream>
#include <list>
#include <string>
#include "token.h"
using namespace std;
class symbol {
string name;
bool isTerminal;
public:
symbol() { }
bool isTerm() {
return isTerminal;
}
symbol(string rName, bool rIsTerminal) {
name = rName;
isTerminal = rIsTerminal;
}
~symbol() {}
string getName() {
return name;
}
string toString() const {
string s;
s += name;
s += " - ";
if(isTerminal)
s += "Terminal symbol";
else
s += "NonTerminal symbol";
return s;
}
/*bool Symbol::operator==(Symbol &rhs) const{
return this->name == rhs.name;
} */
friend ostream& operator<<(ostream& os, const symbol& sym) {
os << sym.toString();
return os;
}
};
class Terminal : public symbol {
token* tkn;
public:
Terminal(string rName, token* rToken) : symbol(rName, true) {
tkn = rToken;
}
Terminal(string rName) : symbol(rName, true) {
}
~Terminal() {
delete tkn;
}
token* getToken() {
return tkn;
}
};
class NonTerminal : public symbol { //------ERROR
vector<symbol> rhs;
// Rule* rule;
int rule;
public:
NonTerminal(string rName, vector<symbol> rRhs) : symbol(rName, false) {
rhs = rRhs;
}
NonTerminal(string rName, int rRule) : symbol(rName, false) {
rule = rRule;
}
NonTerminal(string rName) : symbol(rName, false) {
}
~NonTerminal() {}
};
<file_sep>#pragma once
#include <fstream>
#include <vector>
#include <string>
using namespace std;
vector<string> txt_to_strings(string);
vector<string> txt_to_strings(string txt_file) { // Convert an input txt file to a string with newline characters
vector<string> strings; // This is what our function will return
ifstream reader;
reader.open(txt_file);
while (!reader.eof()) {
string new_string;
getline(reader, new_string);
strings.push_back(new_string);
}
return strings;
}<file_sep>#pragma once
#include <vector>
#include <map>
#include "symbol.h"
#include <string>
using namespace std;
class Rule {
symbol* lhs;
vector<symbol*> rhs;
public:
Rule(symbol* rLhs, vector<symbol*> rRhs) {
lhs = rLhs;
rhs = rRhs;
}
Rule() {}
~Rule() {
// delete lhs;
// while(!rhs.empty()) {
// delete rhs.front();
// rhs.pop_front();
// }
}
string printRule() {
string s;
s += lhs->getName();
s += " = ";
for (size_t i = 0; i < rhs.size(); i++) {
s += rhs[i]->getName();
s += " ";
}
return s;
}
vector<symbol*> rhsReversed() {
vector<symbol*> reversed;
for (int i = rhs.size() - 1; i >= 0; --i) {
reversed.push_back(rhs[i]);
}
return reversed;
}
vector<symbol*> getRhs() {
return rhs;
}
bool isEmpty() {
return rhs.empty();
}
};
class Grammar {
void createTerminals() {
terminals["kwdprog"] = new Terminal("kwdprog", new token("kwdprog"));
terminals["kwdinput"] = new Terminal("kwdinput", new token("kwdinput"));
terminals["kwdprint"] = new Terminal("kwdprint", new token("kwdprint"));
terminals["kwdwhile"] = new Terminal("kwdwhile", new token("kwdwhile"));
terminals["kwdif"] = new Terminal("kwdif", new token("kwdif"));
terminals["kwdelseif"] = new Terminal("kwdelseif", new token("kwdelseif"));
terminals["kwdelse"] = new Terminal("kwdelse", new token("kwdelse"));
terminals["paren1"] = new Terminal("paren1", new token("paren1"));
terminals["paren2"] = new Terminal("paren2", new token("paren2"));
terminals["brace1"] = new Terminal("brace1", new token("brace1"));
terminals["brace2"] = new Terminal("brace2", new token("brace2"));
terminals["comma"] = new Terminal("comma", new token("comma"));
terminals["semi"] = new Terminal("semi", new token("semi"));
terminals["equal"] = new Terminal("equal", new token("equal"));
terminals["plus"] = new Terminal("plus", new token("plus"));
terminals["minus"] = new Terminal("minus", new token("minus"));
terminals["aster"] = new Terminal("aster", new token("aster"));
terminals["slash"] = new Terminal("slash", new token("slash"));
terminals["caret"] = new Terminal("caret", new token("caret"));
terminals["id"] = new Terminal("id", new token("id"));
terminals["int"] = new Terminal("int", new token("int"));
terminals["float"] = new Terminal("float", new token("float"));
terminals["string"] = new Terminal("string", new token("string"));
terminals["$"] = new Terminal ("$", new token("$"));
terminals["eps"] = new Terminal("eps");
}
void createNonTerminals() {
// rules[] = {nonTerminals["Opmul"], terminal["aster"] }
nonTerminals["Opmul"] = new NonTerminal("Opmul", 1);
nonTerminals["Opadd"] = new NonTerminal("Opadd", 2);
nonTerminals["Fatom"] = new NonTerminal("Fatom", 3);
nonTerminals["Pexpr"] = new NonTerminal("Pexpr", 4);
nonTerminals["F"] = new NonTerminal("F", 5);
nonTerminals["T"] = new NonTerminal("T", 5);
nonTerminals["S"] = new NonTerminal("S", 5);
nonTerminals["E"] = new NonTerminal("E", 5);
nonTerminals["R"] = new NonTerminal("R", 5);
nonTerminals["Elist2"] = new NonTerminal("Elist2", 6);
nonTerminals["Elist"] = new NonTerminal("Elist", 6);
nonTerminals["Else2"] = new NonTerminal("Else2", 6);
nonTerminals["Fstmt"] = new NonTerminal("Fstmt", 6);
nonTerminals["Wstmt"] = new NonTerminal("Wstmt", 6);
nonTerminals["Ostmt"] = new NonTerminal("Ostmt", 6);
nonTerminals["Y"] = new NonTerminal("Y", 7);
nonTerminals["Astmt"] = new NonTerminal("Astmt", 8);
nonTerminals["Stmt"] = new NonTerminal("Stmt", 8);
nonTerminals["Stmts"] = new NonTerminal("Stmts", 8);
nonTerminals["Block"] = new NonTerminal("Block", 8);
nonTerminals["Pgm"] = new NonTerminal("Pgm", 9);
}
void createRules() {
vector<symbol*> temp;
rules.push_back(NULL); // no rule at index 0
// Rule 1
temp.push_back(terminals["kwdprog"]);
temp.push_back(nonTerminals["Block"]);
rules.push_back(new Rule(nonTerminals["Pgm"], temp));
temp.clear();
// Rule 2
temp.push_back(terminals["brace1"]);
temp.push_back(nonTerminals["Stmts"]);
temp.push_back(terminals["brace2"]);
rules.push_back(new Rule(nonTerminals["Block"], temp));
temp.clear();
// Rule 3
temp.push_back(nonTerminals["Stmt"]);
temp.push_back(terminals["semi"]);
temp.push_back(nonTerminals["Stmts"]);
rules.push_back(new Rule(nonTerminals["Stmts"], temp));
temp.clear();
// Rule 4
temp.push_back(terminals["eps"]);
rules.push_back(new Rule(nonTerminals["Stmts"], temp));
temp.clear();
// Rule 5
temp.push_back(nonTerminals["Astmt"]);
rules.push_back(new Rule(nonTerminals["Stmt"], temp));
temp.clear();
// Rule 6
temp.push_back(nonTerminals["Ostmt"]);
rules.push_back(new Rule(nonTerminals["Stmt"], temp));
temp.clear();
// Rule 7
temp.push_back(nonTerminals["Wstmt"]);
rules.push_back(new Rule(nonTerminals["Stmt"], temp));
temp.clear();
// Rule 8
temp.push_back(nonTerminals["Fstmt"]);
rules.push_back(new Rule(nonTerminals["Stmt"], temp));
temp.clear();
// Rule 9
temp.push_back(terminals["id"]);
temp.push_back(terminals["equal"]);
temp.push_back(nonTerminals["Y"]);
rules.push_back(new Rule(nonTerminals["Astmt"], temp));
temp.clear();
// Rule 10
temp.push_back(terminals["kwdinput"]);
rules.push_back(new Rule(nonTerminals["Y"], temp));
temp.clear();
// Rule 11
temp.push_back(nonTerminals["E"]);
rules.push_back(new Rule(nonTerminals["Y"], temp));
temp.clear();
// Rule 12
temp.push_back(terminals["kwdprint"]);
temp.push_back(terminals["paren1"]);
temp.push_back(nonTerminals["Elist"]);
temp.push_back(terminals["paren2"]);
rules.push_back(new Rule(nonTerminals["Ostmt"], temp));
temp.clear();
// Rule 13
temp.push_back(terminals["kwdwhile"]);
temp.push_back(nonTerminals["Pexpr"]);
temp.push_back(nonTerminals["Block"]);
rules.push_back(new Rule(nonTerminals["Wstmt"], temp));
temp.clear();
// Rule 14
temp.push_back(terminals["kwdif"]);
temp.push_back(nonTerminals["Pexpr"]);
temp.push_back(nonTerminals["Block"]);
temp.push_back(nonTerminals["Else2"]);
rules.push_back(new Rule(nonTerminals["Fstmt"], temp));
temp.clear();
// Rule 15
temp.push_back(terminals["kwdelseif"]);
temp.push_back(nonTerminals["Pexpr"]);
temp.push_back(nonTerminals["Block"]);
temp.push_back(nonTerminals["Else2"]);
rules.push_back(new Rule(nonTerminals["Else2"], temp));
temp.clear();
// Rule 16
temp.push_back(terminals["kwdelse"]);
temp.push_back(nonTerminals["Block"]);
rules.push_back(new Rule(nonTerminals["Else2"], temp));
temp.clear();
// Rule 17
temp.push_back(terminals["eps"]);
rules.push_back(new Rule(nonTerminals["Else2"], temp));
temp.clear();
// Rule 18
temp.push_back(nonTerminals["E"]);
temp.push_back(nonTerminals["Elist2"]);
rules.push_back(new Rule(nonTerminals["Elist"], temp));
temp.clear();
// Rule 19
temp.push_back(terminals["eps"]);
rules.push_back(new Rule(nonTerminals["Elist"], temp));
temp.clear();
// Rule 20
temp.push_back(terminals["comma"]);
temp.push_back(nonTerminals["Elist"]);
rules.push_back(new Rule(nonTerminals["Elist2"], temp));
temp.clear();
// Rule 21
temp.push_back(nonTerminals["Opadd"]);
temp.push_back(nonTerminals["T"]);
temp.push_back(nonTerminals["R"]);
rules.push_back(new Rule(nonTerminals["R"], temp));
temp.clear();
// Rule 22
temp.push_back(nonTerminals["T"]);
temp.push_back(nonTerminals["R"]);
rules.push_back(new Rule(nonTerminals["E"], temp));
temp.clear();
// Rule 23
temp.push_back(terminals["eps"]);
rules.push_back(new Rule(nonTerminals["R"], temp));
temp.clear();
// Rule 24
temp.push_back(nonTerminals["Opmul"]);
temp.push_back(nonTerminals["F"]);
temp.push_back(nonTerminals["S"]);
rules.push_back(new Rule(nonTerminals["S"], temp));
temp.clear();
// Rule 25
temp.push_back(nonTerminals["F"]);
temp.push_back(nonTerminals["S"]);
rules.push_back(new Rule(nonTerminals["T"], temp));
temp.clear();
// Rule 26
temp.push_back(terminals["eps"]);
rules.push_back(new Rule(nonTerminals["S"], temp));
temp.clear();
// Rule 27
temp.push_back(nonTerminals["Fatom"]);
rules.push_back(new Rule(nonTerminals["F"], temp));
temp.clear();
// Rule 28
temp.push_back(nonTerminals["Pexpr"]);
rules.push_back(new Rule(nonTerminals["F"], temp));
temp.clear();
// Rule 29
temp.push_back(terminals["paren1"]);
temp.push_back(nonTerminals["E"]);
temp.push_back(terminals["paren2"]);
rules.push_back(new Rule(nonTerminals["Pexpr"], temp));
temp.clear();
// Rule 30
temp.push_back(terminals["id"]);
rules.push_back(new Rule(nonTerminals["Fatom"], temp));
temp.clear();
// Rule 31
temp.push_back(terminals["int"]);
rules.push_back(new Rule(nonTerminals["Fatom"], temp));
temp.clear();
// Rule 32
temp.push_back(terminals["float"]);
rules.push_back(new Rule(nonTerminals["Fatom"], temp));
temp.clear();
// Rule 33
temp.push_back(terminals["string"]);
rules.push_back(new Rule(nonTerminals["Fatom"], temp));
temp.clear();
// Rule 34
temp.push_back(terminals["plus"]);
rules.push_back(new Rule(nonTerminals["Opadd"], temp));
temp.clear();
// Rule 35
temp.push_back(terminals["minus"]);
rules.push_back(new Rule(nonTerminals["Opadd"], temp));
temp.clear();
// Rule 36
temp.push_back(terminals["aster"]);
rules.push_back(new Rule(nonTerminals["Opmul"], temp));
temp.clear();
// Rule 37
temp.push_back(terminals["slash"]);
rules.push_back(new Rule(nonTerminals["Opmul"], temp));
temp.clear();
// Rule 38
temp.push_back(terminals["caret"]);
rules.push_back(new Rule(nonTerminals["Opmul"], temp));
temp.clear();
// Rule 39
temp.push_back(terminals["eps"]);
rules.push_back(new Rule(nonTerminals["Elist2"], temp));
temp.clear();
}
void createParseMatrix() {
parseMatrix["Pgm_kwdprog"] = 1;
parseMatrix["Block_brace1"] = 2;
parseMatrix["Stmts_kwdprint"] = 3;
parseMatrix["Stmts_kwdwhile"] = 3;
parseMatrix["Stmts_kwdif"] = 3;
parseMatrix["Stmts_id"] = 3;
parseMatrix["Stmts_brace2"] = 4;
parseMatrix["Stmt_kwdprint"] = 6;
parseMatrix["Stmt_kwdwhile"] = 7;
parseMatrix["Stmt_id"] = 5;
parseMatrix["Astmt_id"] = 9;
parseMatrix["Y_kwdinput"] = 10;
parseMatrix["Y_id"] = 11;
parseMatrix["Y_int"] = 11;
parseMatrix["Y_float"] = 11;
parseMatrix["Y_string"] = 11;
parseMatrix["Y_paren1"] = 11;
parseMatrix["Ostmt_kwdprint"] = 12;
parseMatrix["Wstmt_kwdwhile"] = 13;
parseMatrix["Fstmt_kwdif"] = 14;
parseMatrix["Else2_kwdelseif"] = 15;
parseMatrix["Else2_kwdelse"] = 16;
parseMatrix["Else2_semi"] = 17;
parseMatrix["Elist_id"] = 18;
parseMatrix["Elist_int"] = 18;
parseMatrix["Elist_float"] = 18;
parseMatrix["Elist_string"] = 18;
parseMatrix["Elist_paren1"] = 18;
parseMatrix["Elist_paren2"] = 19;
parseMatrix["Elist2_comma"] = 20;
parseMatrix["R_plus"] = 21;
parseMatrix["R_minus"] = 21;
parseMatrix["R_comma"] = 23;
parseMatrix["R_semi"] = 23;
parseMatrix["R_paren2"] = 23;
parseMatrix["E_id"] = 22;
parseMatrix["E_int"] = 22;
parseMatrix["E_float"] = 22;
parseMatrix["E_string"] = 22;
parseMatrix["E_paren1"] = 22;
parseMatrix["S_plus"] = 26;
parseMatrix["S_minus"] = 26;
parseMatrix["S_aster"] = 24;
parseMatrix["S_slash"] = 24;
parseMatrix["S_caret"] = 24;
parseMatrix["S_comma"] = 26;
parseMatrix["S_semi"] = 26;
parseMatrix["S_paren2"] = 26;
parseMatrix["T_id"] = 25;
parseMatrix["T_int"] = 25;
parseMatrix["T_float"] = 25;
parseMatrix["T_string"] = 25;
parseMatrix["T_paren1"] = 25;
parseMatrix["F_id"] = 27;
parseMatrix["F_int"] = 27;
parseMatrix["F_float"] = 27;
parseMatrix["F_string"] = 27;
parseMatrix["F_paren1"] = 28;
parseMatrix["Pexpr_paren1"] = 29;
parseMatrix["Fatom_id"] = 30;
parseMatrix["Fatom_int"] = 31;
parseMatrix["Fatom_float"] = 32;
parseMatrix["Fatom_string"] = 33;
parseMatrix["Opadd_plus"] = 34;
parseMatrix["Opadd_minus"] = 35;
parseMatrix["Opmul_aster"] = 36;
parseMatrix["Opmul_slash"] = 37;
parseMatrix["Opmul_caret"] = 38;
parseMatrix["Elist2_paren2"] = 39;
}
public:
map<string, symbol*> terminals;
map<string, symbol*> nonTerminals;
map<string, int> parseMatrix;
vector<Rule*> rules;
Grammar() {
createTerminals();
createNonTerminals();
createRules();
createParseMatrix();
}
/*~Grammar() { ---------ERROR CAUSES EXECUTION FAIL------------ Error related to iterator
for(auto it = terminals.begin(); it != terminals.end(); ++it) {
delete it->second;
terminals.erase(it);
}
for(auto it = nonTerminals.begin(); it != nonTerminals.end(); ++it) {
delete it->second;
nonTerminals.erase(it);
}
while(!rules.empty()) {
delete rules.front();
rules.pop_front();
}
}*/
Rule getRuleAt(string row, string col) {
string row_col = row + "_" + col;
if(parseMatrix.count(row_col) > 0) { // Check if key exists
int ruleNum = parseMatrix[row_col];
return *rules[ruleNum];
} else {
return *(new Rule());
}
}
symbol getRule(string rule) {
return *terminals[rule];
}
};<file_sep>#! bash
clear
if [ -f a.out ]; then
rm a.out
fi
g++ -std=c++11 main.cpp && ./a.out
<file_sep> <NAME>
<NAME>
<NAME>
Files needed:
grammar.h
main.cpp
node.h
parser.h
symbol.h
symtable.h
token.h
txt_to_strings.h
Installation/Run Info:
Managing test cases:
Place test files in the ./tests directory in the format "test_x.txt"
where x is an integer value.
Using the program:
Enter the integer value of of the test case you would like to run.
Bugs Remaining/Future Work:
Complete PST/AST construction
Complete PST/AST printer
Features Added:
N/A
<file_sep>#pragma once
#include <string>
#include <vector>
#include "symbol.h"
using namespace std;
class Node {
symbol* content;
Node* parent;
int kidIx;
int id;
public:
vector<Node*> children;
Node() {}
Node(symbol* rContent) {
content = rContent;
}
Node(symbol* rContent, Node* rParent, int rIx) {
content = rContent;
parent = rParent;
kidIx = rIx;
}
~Node() {
delete content;
delete parent;
for (size_t i = 0; i < children.size(); i++) {
delete children[i];
}
}
void setParent(Node * _parent) {
parent = _parent;
}
Node * getParent() {
if(parent) {
return parent;
} else {
return NULL;
}
}
Node* getChild(int ix) {
if(ix >= children.size() || ix < 0){
return NULL;
} else {
return children[ix];
}
}
int getIx() {
return kidIx;
}
void setSymbol(symbol * r_sym) {
content = r_sym;
}
void insert(Node* newChild) {
// Assign the kid his id
// which is the current size
newChild->kidIx = children.size();
// set parent
newChild->parent = this;
// Add kid to kid list
children.push_back(newChild);
}
void insert(Node* newChild, bool b) {
// Add kid to kid list
children.push_back(newChild);
}
// **This only works for mom with no children
void insertChildren(vector<symbol*> children) {
for(int i = 0; i < children.size(); i++) {
insert(new Node(children[i], this, i), true);
}
}
vector<Node*>* getChildren() {
return &children;
}
Node find(string node) {
if (children.empty()) {
//return;
}
for (size_t i = 0; i < children.size(); ++i) {}
return Node();
}
void remove(Node* child) {
// children.erase(/*child position*/);
}
symbol * getSymbol() {
return content;
}
static string toString(Node* ptr) {
// Base step
if(!ptr) {
return "";
}
string s;
s += ptr->content->toString();
s += "\n";
for(size_t i = 0; i < ptr->children.size(); ++i) {
s += toString(ptr->children[i]);
s += "\n";
}
return s;
}
};
<file_sep>#pragma once
#include <string>
#include <vector>
#include <map>
#include "token.h"
#include "grammar.h"
#include "symtable.h"
#include "node.h"
#include <stack>
using namespace std;
const string FILE_PARSER = " - parser.h";
const string PRT_LEVEL_FILL = "___";
class Parser {
Grammar* gmr;
Node* pst;
Node* ast;
SymTable symTable;
vector<token> tokenList;
Node* mom;
public:
Parser(Grammar* rGmr) {
gmr = rGmr;
}
Parser() {
gmr = new Grammar();
}
~Parser() {
// delete gmr;
// delete pst;
// delete ast;
// delete mom;
}
void print_table() {
symTable.print_table();
}
void addTokensToParser(vector<token> _TokenList) {
tokenList = _TokenList;
cout << ">>>>>> Parser received " << tokenList.size() << " token(s)" << endl;
}
Node * makePST() {
cout << "Starting to parse token list" << endl;
// Setup
vector<symbol*> workingStack;
// Add the eof symbol to stack
workingStack.push_back(gmr->terminals["$"]);
// Add the start symbol to stack
workingStack.push_back(gmr->nonTerminals["Pgm"]);
// Add the eof token to input
tokenList.push_back(token("$"));
// Add $ as root
pst = new Node(workingStack[0], NULL, 0);
// Set mom to Pgm
mom = pst;
cout << "Finished setup" << endl;
int tokenIx = 1; // base 1
while(!workingStack.empty()) {
symbol* top = workingStack.back();
token front = tokenList.front();
if(top->isTerm()) {
// if it's an epsilon rule pop it off
if(top->getName() == "eps") {
// check to see if mom has sibling
while( !( ( mom->getParent() )->getChild( mom->getIx() + 1 ) ) ) {
if( mom->getParent() ) {
mom = mom->getParent();
}
}
mom = ( mom->getParent() )->getChild( mom->getIx() + 1 );
cout << "Popping of eps rule." << endl;
workingStack.pop_back();
}
// if top it terminal check if it matches front
else if(*(static_cast<Terminal*>(top)->getToken()) == front) {
cout << "Matched: " << front.id;
cout << ". Popping off the top and the front.\n";
cout << "\tln: " << front.ln << " ix: " << front.ix << endl;
// Add token to symtable if it is identifier
if (front.id=="id") {
Sym * temp = new Sym(front.ln,front.id,front.ix,front.str,0,"null");
symTable.add_symbol(*temp);
}
bool isAtTop = false;
// Set mom to next kid
if(mom->getParent()) {
while( !( ( mom->getParent() )->getChild( mom->getIx() + 1 ) ) ) {
if( mom->getParent() ) {
mom = mom->getParent();
// if we're at the top of the tree
if(mom == pst) {
isAtTop = true;
break;
}
}
}
if(!isAtTop) {
mom = ( mom->getParent() )->getChild( mom->getIx() + 1 );
}
}
// Pop the top
workingStack.pop_back();
// Pop the front
tokenList.erase(tokenList.begin());
tokenIx++;
}
// if top doesn't match with front throw error
else {
cout << "Error occured when parsing token " << tokenIx << endl;
cout << "Predicted: " << (static_cast<Terminal*>(top)->getToken())->id;
cout << " but instead found: " << front.id << endl;
break;
}
}
else {
// M1: Top is a NonTerminal
Rule rule = gmr->getRuleAt(top->getName(), front.id);
cout << "Checking for rule: ";
cout << "(" << top->getName() << ", " << front.id << ")";
cout << endl;
if(!rule.isEmpty()) {
cout << "This rule was found: ";
cout << rule.printRule() << endl;
// Remove the top symbol from stack
workingStack.pop_back();
// Add the rule in reverse
vector<symbol*> rhsRev = rule.rhsReversed();
for (size_t i = 0; i < rhsRev.size(); ++i) {
workingStack.push_back(rhsRev[i]);
// Node * temp = new Node(rule.getRhs()[i]);
// temp->setParent(pst);
// pst->insert(temp);
}
// Add rule rhs to mom
mom->insertChildren(rule.getRhs());
// Set mom to first child
mom = mom->getChild(0);
} else {
cout << "The rule is empty => there is no prediction for this";
cout << endl;
// print stack
cout << "Current stack" << endl;
for(int i = workingStack.size() - 1; i >= 0; i--) {
//cout << *workingStack[i] << endl;
}
// print input stream
cout << endl << "Current token stream" << endl;
for (size_t i = 0; i < tokenList.size(); ++i) {
cout << tokenList[i].id << endl;
}
break;
}
}
}
return pst;
}
//Take the tree and create a printable represenation of it
//@param tree a node pointer to the tree to serialize
// Node * makeAST(Node * pst) {
// Node * AST;
// // NEEDS IMPLEMENTATION
// return AST;
// }
//This is the print function of a PST tree.
//Implemented as a recursive pre-order function.
//NOTE: This is finished
void printPST(Node * current,int level = 0)
{
if (current == nullptr)
{
cout << "null" << endl;
return;
}
/*if (current->getParent() == nullptr) // ---------Checks for root - Found no use for this but kept just in case------------
{
}*/
// Print out the children of current node
for (size_t i = 0; i < current->children.size();++i)
{
// For loop which makes the tree level more obvious
for (int i = 0; i < level; ++i)
{
// Uses filler to show levels(actual variable is found near the top)
cout << PRT_LEVEL_FILL;
}
// Outputs the current node followed by the child node
cout << "|-" << current->getSymbol()->getName() << " >>> " << current->children[i]->getSymbol()->getName() << endl;
}
//Enter each child of the current node using this function
for (size_t i = 0; i < current->children.size(); ++i)
{
// Call function recursively using the child as parameter
// In addition the level will be incremented
printPST(current->children[i],++level);
}
}
string serialize(Node* ptr, int level) {
string s;
// opening paren
s += "(";
// local info
s += "(";
s += "Node";
// children info
// closing paren
s += ")";
}
// The AST printing function implemented in-order
void printAST(Node * current) {
if (current == nullptr)
{
cout << "null" << endl;
return;
}
printAST(current->getChildren()->at(0));
cout << current->getSymbol()->getName() << endl;
printAST(current->getChildren()->at(1));
}
Grammar getGmr() {
return *gmr;
}
};
// Stuff for parser
/*else {
The rule is empty => there is no prediction for this
TODO: throw an error
Error: unexpected token found, line front.line
}*/
// M2
// else {
// if (top->isTerm()) {
// Error();
// }
// // M3
// else if(gmr.getRule(top, front).isEmpty()){
// Error();
// }
// // M4
// else if(!gmr.getRule(top, front).isEmpty()) {
// workingStack.pop();
// workingStack.push(gmr.getRule(top, front).reverse());
// }
// else {
// printStatus();
// }
// }
// }
// Stuff for making a tree
// cout << tokenList.back().id << FILE_PARSER << endl; // Test if token created succesfully
// Start building the PST
// pst = new Node(workingStack.top());
// For test purposes
// pst->insert(new Node(gmr->terminals["$"]));
// pst->insert(new Node(gmr->terminals["id"]));
// pst->insert(new Node(gmr->terminals["int"]));
// pst->insert(new Node(gmr->nonTerminals["Astmt"]));
// pst->insert(new Node(gmr->nonTerminals["Block"]));
// pst->insert(new Node(gmr->nonTerminals["Pexpr"]));
// cout << Node::toString(pst) << FILE_PARSER << endl;
// cout << pst->toString() << FILE_PARSER << endl;
<file_sep>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "txt_to_strings.h"
#include "token.h"
#include "parser.h"
#include "symbol.h"
#include <ctime>
#include <chrono>
#include <thread>
const string FILE_MAIN = " - main.cpp";
using namespace std;
using namespace this_thread;
using namespace chrono;
string Test_File = "test_X.txt";
vector<string> _Strings;
vector<token> _Tokens;
string _Language = "A3";
int pause_time = 500; //Milliseconds
void runParser(vector<token> tokenList);
int main() {
int x = 0;
while (true) {
cout << "Please input a test number (1-6): ";
cin >> x;
if (x < 0) {
break;
}
Test_File = "./tests/test_" + to_string(x) + ".txt";
if (!cin.fail()) {
ifstream f(Test_File.c_str());
if (f.good()) {
cout << "======== Start Test - " << Test_File << " ========" << endl;
_Strings = txt_to_strings(Test_File);
_Tokens = tokenize(_Strings);
token_printer(_Language, _Tokens);
runParser(_Tokens);
_Strings.clear();
_Tokens.clear();
cout << "======== End Test - " << Test_File << " ========" << endl;
}
else {
cout << "No such file found in current directory!" << endl;
}
}
else {
cout << "Bad input detected." << endl;
cin.clear();
cin.ignore(INT_MAX, '\n');
}
}
return 0;
}
void runParser(vector<token> tokenList) {
cout << ">>> Parser Running" << endl;
sleep_until(system_clock::now() + milliseconds(pause_time));
Parser parser;
cout << ">>> Created Parser object 'parser'" << endl;
sleep_until(system_clock::now() + milliseconds(pause_time));
cout << "Parser created" << FILE_MAIN << endl;
// Send the generated tokens to the parse machine
// parser.addTokensToParse(tokenList);
// cout << "Tokens sent to parser" << FILE_MAIN << endl;
Grammar g = parser.getGmr();
cout << ">>> Created grammar object 'g'" << endl;
sleep_until(system_clock::now() + milliseconds(pause_time));
cout << ">>> Sending tokens to 'parser'" << endl;
sleep_until(system_clock::now() + milliseconds(pause_time));
parser.addTokensToParser(tokenList);
sleep_until(system_clock::now() + milliseconds(pause_time));
vector<string> temp;
temp.push_back("kwdprog");
temp.push_back("kwdinput");
temp.push_back("kwdprint");
temp.push_back("kwdwhile");
temp.push_back("kwdif");
temp.push_back("kwdelseif");
temp.push_back("kwdelse");
temp.push_back("paren1");
temp.push_back("paren2");
temp.push_back("brace1");
temp.push_back("brace2");
temp.push_back("comma");
temp.push_back("semi");
temp.push_back("equal");
temp.push_back("plus");
temp.push_back("minus");
temp.push_back("aster");
temp.push_back("slash");
temp.push_back("caret");
temp.push_back("id");
temp.push_back("int");
temp.push_back("float");
temp.push_back("string");
temp.push_back("$");
vector<string> temp2;
temp2.push_back("Opmul");
temp2.push_back("Opadd");
temp2.push_back("Fatom");
temp2.push_back("Pexpr");
temp2.push_back("F");
temp2.push_back("T");
temp2.push_back("S");
temp2.push_back("E");
temp2.push_back("R");
temp2.push_back("Elist2");
temp2.push_back("Elist");
temp2.push_back("Else2");
temp2.push_back("Fstmt");
temp2.push_back("Wstmt");
temp2.push_back("Ostmt");
temp2.push_back("Y");
temp2.push_back("Astmt");
temp2.push_back("Stmt");
temp2.push_back("Stmts");
temp2.push_back("Block");
temp2.push_back("Pgm");
cout << ">>> Created list 'temp'" << endl;
sleep_until(system_clock::now() + milliseconds(pause_time));
/*for(size_t i = 0; i < temp.size(); i++) {
symbol t = *g.terminals[temp[i]];
cout << t.getName() << endl;
}*/
/*for(size_t i = 0; i < temp2.size(); i++) {
symbol t = *g.nonTerminals[temp2[i]];
cout << t.getName() << endl;
}*/
/*cout << ">>> Printing rules" << endl;
sleep_until(system_clock::now() + seconds(1));
list<Rule*> rules = g.rules;
for (auto it = rules.begin(); it != rules.end(); ++it) {
if((*it))
cout << (*it)->printRule() << endl;
}*/
Node * pst = parser.makePST();
cout << ">>> Created PST" << endl;
sleep_until(system_clock::now() + milliseconds(pause_time));
cout << ">>> Printing PST" << endl;
sleep_until(system_clock::now() + milliseconds(pause_time));
parser.printPST(pst);
sleep_until(system_clock::now() + milliseconds(pause_time));
parser.print_table();
// Node * ast = parser.makeAST(pst);
cout << ">>> Created AST" << endl;
sleep_until(system_clock::now() + milliseconds(pause_time));
cout << ">>> Printing AST" << endl;
sleep_until(system_clock::now() + milliseconds(pause_time));
//parser.printAST(NEEDS A NODE);
sleep_until(system_clock::now() + milliseconds(pause_time));
cout << ">>> Parser Done" << endl;
}
<file_sep>#pragma once
//#include "symbol.h"
#include <string>
#include <list>
using namespace std;
struct occurence {
int lineNum;
int tokenNum;
bool isDef;
};
class Sym {
int ln;
string id;
int ix;
string str;
bool isString;
double valueDouble;
string valueString;
public:
Sym() {}
Sym(int _ln, string _id, int _ix, string _str, double _valdb, string _valstr) {
ln = _ln;
id = _id;
ix = _ix;
str = _str;
valueDouble = _valdb;
valueString = _valstr;
}
~Sym() {}
vector<occurence> occs;
void add_occ(int _ln, int _ix) {
occurence a;
a.lineNum = _ln;
a.tokenNum = _ix;
a.isDef = false;
occs.push_back(a);
}
string get_str() {
return str;
}
int get_ln() {
return ln;
}
int get_ix() {
return ix;
}
double get_valdb() {
return valueDouble;
}
string get_valstr() {
return valueString;
}
};
class SymTable {
int current_indent_level;
list<Sym> table;
vector<Sym> symbols;
public:
SymTable() {
current_indent_level = 0;
};
~SymTable() {
};
void add_symbol(Sym new_sym) {
bool sym_exists = false;
bool sym_added = false;
int sym_loc = 0;
cout << "Looking for a symtable match" << endl;
if (symbols.size() == 0) {
symbols.push_back(new_sym);
sym_added = true;
}
else {
for (size_t i = 0; i < symbols.size(); i++) {
if (symbols[i].get_str() == new_sym.get_str()) {
sym_exists = true;
sym_loc = i;
}
}
}
if (sym_exists) {
symbols[sym_loc].add_occ(new_sym.get_ln(), new_sym.get_ix());
}
else {
if (!sym_added) {
symbols.push_back(new_sym);
}
}
}
void print_table() {
indent();
cout << ">>> Symbol Table" << endl;
current_indent_level++;
if (symbols.size() == 0) {
indent();
cout << "0 symbols found." << endl;
}
else {
indent();
cout << symbols.size() << " symbol(s) found:" << endl;
current_indent_level++;
for (size_t i = 0; i < symbols.size(); i++) {
indent();
cout << "Symbol: " << symbols[i].get_str();
indent(1);
cout << "First Found On Line: " << symbols[i].get_ln();
indent(1);
cout << "Index: " << symbols[i].get_ix();
indent(1);
cout << "Double Value: " << symbols[i].get_valdb();
indent(1);
cout << "String Value: " << symbols[i].get_valstr() << endl;
current_indent_level++;
if (symbols[i].occs.size() == 0) {
indent();
cout << "This symbol has only 1 occurrence" << endl;
}
else {
indent();
cout << symbols[i].occs.size() << " additional occurrence(s) found:" << endl;
current_indent_level++;
for (size_t j = 0; j < symbols[i].occs.size(); j++) {
indent();
cout << "Line: " << symbols[i].occs[j].lineNum;
indent(1);
cout << "Index: " << symbols[i].occs[j].tokenNum;
indent(1);
cout << "Is definition: " << symbols[i].occs[j].isDef << endl;
}
current_indent_level--;
}
current_indent_level--;
}
}
}
void indent() {
for (int i = 0; i < current_indent_level; i++) {
cout << "\t";
}
}
void indent(int count) {
for (int i = 0; i < count; i++) {
cout << "\t";
}
}
};
|
000302bd1d08ad661b457d792accde3557089b2f
|
[
"Text",
"C++",
"Shell"
] | 11
|
Shell
|
kernelpop/323.p2
|
dc9c68e9176c52c01ae688c7883d978aef4a45b2
|
0755709d392d61ba84d2b31ae0d4614f9ba04c28
|
refs/heads/master
|
<file_sep># -*- coding: <UTF-8> -*-
from io import open
class Conversa():
def __init__(self, fileConversa):
self.fileConversa = fileConversa
self.pessoa1 = None
self.pessoa2 = None
self.conversa = None
def identificarEnvolvidos(self):
ref_conversa = open(self.fileConversa, "r", encoding="utf-8")
self.conversa = ref_conversa.readlines()
ref_conversa.close()
envolvidos = []
for i in self.conversa:
if " - " in i:
temp = i.split(" - ")
if ":" in temp[1]:
temp = temp[1].split(":")
if temp[0] not in envolvidos:
envolvidos.append(temp[0])
print(envolvidos)
if len(envolvidos) != 2:
return f"Erro, envolvidos diferente de 2 : {envolvidos}"
else:
self.pessoa1 = envolvidos[0]
self.pessoa2 = envolvidos[1]
def deletarLinhas(self):
ref_conversa = open(self.fileConversa, "w", encoding="utf-8")
for l in self.conversa:
if "<Arquivo de mídia oculto>" not in l:
if ":" in l:
if " - " + self.pessoa1 in l:
ref_conversa.write(l)
if " - " + self.pessoa2 in l:
ref_conversa.write(l)
ref_conversa.close()
def juntarDuplicadas(self):
ref_conversa = open(self.fileConversa, "r", encoding="utf-8")
self.conversa = ref_conversa.readlines()
ref_conversa = open(self.fileConversa, "w", encoding="utf-8")
p1 = p2 = 0
l = ""
texto = ""
for l in self.conversa:
print(l)
if self.pessoa1 in l:
p1 += 1
if p2 > 0:
ref_conversa.write(texto + "\n")
texto = ""
p2 = 0
if self.pessoa2 in l:
p2 += 1
if p1 > 0:
ref_conversa.write(texto + "\n")
texto = ""
p1 = 0
l = l.replace("\n", "")
if texto != "":
temp = l.split(":")
texto = texto + ", " + temp[2]
else:
texto = l
ref_conversa.close()
def separarDataMensagem(self):
ref_conversa = open(self.fileConversa, "r", encoding="utf-8")
self.conversa = ref_conversa.readlines()
ref_conversa = open(self.fileConversa, "w", encoding="utf-8")
for l in self.conversa:
l = l.split(":")
ref_conversa.write(l[2])
ref_conversa.close()<file_sep># <p align="center">conversaWhatsApp
<p align="center">Scrip python que organiza uma conversa do WastsApp, para ser aplicada em um treinamentos de chatBot.
<p align="center">Após organização, basta ler linha a linha transformando em uma lista. <file_sep># -*- coding: <UTF-8> -*-
import lerConversa as con
conversa = con.Conversa(fileConversa="Conversa.txt")
conversa.identificarEnvolvidos()
conversa.deletarLinhas()
conversa.juntarDuplicadas()
conversa.separarDataMensagem()
|
7a1bc06ac5d8f94828df3ab43febc4812c665450
|
[
"Markdown",
"Python"
] | 3
|
Python
|
alves-dev/conversaWhatsApp
|
d20e7aa6cb6320367b5b2bda66ebcbfb7b3c9f40
|
7d05ea0640129dbb304fe14494d7ac4223da1bec
|
refs/heads/master
|
<repo_name>Eiskis/scam<file_sep>/README.md
# Scam
Simple schema-based REST API on node and SQLite, with fully functional CRUD flows.
- Source: https://github.com/Eiskis/scam
- Demo project: https://github.com/Eiskis/scam-demo
- Demo project deployed to Heroku: https://scam-demo.herokuapp.com/
**Scam is not suitable for production use** as the name implies! Scam is a prototyping tool intended for designing REST APIs and supporting frontend development.
Scam is still quite early in development.
## Usage
```sh
npm install express scam --save
```
```js
const path = require('path')
const express = require('express')
const scam = require('scam')
const app = express()
app.set('port', (process.env.PORT || 3333))
scam.init(app, {
data: { ... },
schema: { ... },
databasePath: path.resolve(__dirname, './db.sql')
})
app.listen(app.get('port'), function () {
scam.log()
})
```
See the [demo project](https://github.com/Eiskis/scam-demo/blob/master/index.js) for a better example.
## Schema
```js
{
posts: {
singular: 'post',
plural: 'posts',
fields: [
name: {
type: 'string'
},
body: {
type: 'string'
},
flagged: {
type: 'boolean',
default: false
},
user: {
type: 'user' // Note singular
},
comments: {
type: 'comments' // Note plural
}
]
},
comments: {
...
},
users: {
...
}
}
```
## Data (optional)
```js
{
posts: [
{
name: '<NAME>',
body: 'Body text body text body text',
user: 1,
comments: [1, 2, 3]
},
...
]
}
```
### Options
```js
{
// Set Scam to debug mode (prints internal error messages on 500)
debug: debug,
// Default cache time (can be overwritten per resource in schema)
cache: 0,
// Dummy data as an object, or path to `require` it from
data: require('./data'),
// API schema as an object, or path to `require` it from
schema: require('./schema'),
// Path of the db file to create/remove/update (in-memory DB not yet supported)
databasePath: path.resolve(__dirname, 'db/db.sql')
}
```
### API
```js
let app = require('express')()
let scam = require('scam')
// Prepare a new Scam instance
scam.init(app, options)
// Delete DB if it exists
scam.clearDatabase()
// Init new DB based on schema
scam.setupDatabase()
// Load dummy data
scam.loadData()
// Print instructions and endpoints
scam.log()
// Access props
scam.data
scam.dbPath
scam.endpoints
scam.schema
```
### Deployment
You can deploy a Scam API just like any other express app. A quick way to try it out is to host your repo on GitHub and connect it to Heroku.
### Schema: Field types
The following raw types are supported:
- (`integer`)
- `string`
- `float`
- `boolean`
- `array` (will be stored as string (of JSON) in DB)
- `date`
- `time`
- `timestamp`
Default is `'integer'`, and it doesn't need to be specified.
You can also use the key of another resource type as the `type`. In this case the values are integers and are treated as IDs pointing to resources of the given type.
## Contributing
Scam is still early in development, and pretty hacky. See [todo.md](./TODO.md) for the next steps.
Feel free to [file issues or PRs](https://github.com/Eiskis/scam/issues) though!
<file_sep>/lib/helpers/normalizeType.js
const config = require('../config')
// Normalize type of a field
// Returns internal type (not SQL)
module.exports = function (fieldName, resourceType, schema) {
let fields = schema.resourceTypes[resourceType].fields
let type
// Field is a native field
if (config.nativeFields[fieldName]) {
type = config.nativeFields[fieldName].type
// Type defined in schema
} else if (fields[fieldName] && fields[fieldName].type) {
type = fields[fieldName].type
// Default to integer
} else {
type = config.defaultType
}
return type
}
<file_sep>/lib/db/remove.js
const Database = require('better-sqlite3')
const squel = require('squel')
// const config = require('../config')
module.exports = {
one: function (dbPath, schema, resourceType, id) {
let resource = schema.resourceTypes[resourceType]
// Prepare query
let query = squel.delete({}).from(resource.plural).where('id = ' + id)
return new Promise(function (resolve, reject) {
try {
// Init database connection
const db = new Database(dbPath, {
readonly: false
})
// Execute query
db.prepare(query.toString()).run()
// Close local database connection
db.close()
resolve()
// NOTE: should this fail if user with this ID is missing?
} catch (error) {
reject(error)
}
})
},
many: function (dbPath, schema, resourceType, ids) {
const remove = this
let promises = []
// Each object to update in inputs array
for (var i = 0; i < ids.length; i++) {
let id = ids[i]
// Register promise for each removal operation
promises.push(new Promise(function (resolve, reject) {
// `remove.one`
remove.one(dbPath, schema, resourceType, id).then(function () {
resolve()
}).catch(function (error) {
reject(error)
})
}))
}
// Resolve or reject `insert.many`
return new Promise(function (resolve, reject) {
Promise.all(promises).then(function (ids) {
resolve(ids)
}).catch(function (errors) {
reject(errors)
})
})
}
}
<file_sep>/lib/response/fail.js
module.exports = function (scam, resourceType, request, response, status, body, debug) {
// Default error status
// NOTE: Should we read this from error?
if (!status) {
status = 400
}
// Basic format
let content = {
timestamp: new Date()
}
content.body = body
if (scam.debug && debug) {
content.debug = debug
}
// Never cache errors
response.setHeader('Cache-Control', 'no-cache')
return response.status(status).json(content)
}
<file_sep>/lib/helpers/normalizeWhereQuery.js
const _ = require('lodash')
const mathFieldTypes = ['integer', 'float', 'timestamp']
const operators = {
'!': '!=',
'<': '<',
'>': '>'
}
// Set the right operator
// FIXME: needs refactoring, import functionality from select
module.exports = function (rawType, value) {
let operator = '='
// Support comparison operators
if (_.includes(mathFieldTypes, rawType)) {
if (_.isString(value)) {
// HACK: can't believe I'm doing this, there must be a library for this
let potentialOperator = value.substr(0, 1)
for (var key in operators) {
if (potentialOperator === key) {
operator = operators[key]
value = value.substr(1)
break
}
}
}
}
return operator + ' ' + value
}
<file_sep>/lib/cli/logger.js
// Central config
const config = require('../config')
module.exports = {
columnWidth: 22,
color: function (string, key) {
if (key) {
key = key.toLowerCase()
const chalk = require('chalk')
// Hex color set
if (config.consoleLogColors[key]) {
return chalk.hex(config.consoleLogColors[key])(string)
// Color keyword set
} else if (chalk[key]) {
return chalk[key](string)
}
}
return string
},
print: function (line, heading) {
let pad = ' '.repeat(4)
if (heading) {
console.log()
}
if (line) {
console.log(pad + (heading ? '' : pad) + line)
} else {
console.log()
}
if (heading) {
console.log()
}
},
all: function (scam) {
let mono = !scam.debug ? true : false
return this
.endpoints(scam, mono)
.sortParams(mono)
.nestParams(mono)
.filterParams(mono)
},
endpoints: function (scam, mono) {
this.print('A Scam REST API is now running on port ' + scam.app.get('port') + ' with these endpoints:', true)
let lastPath = scam.endpoints[0].path
// List each endpoint
for (let key in scam.endpoints) {
let endpoint = scam.endpoints[key]
let method = endpoint.method.toUpperCase()
let path = endpoint.path + (endpoint.params ? '/:' + endpoint.params.join('/:') : '')
let pad = this.columnWidth - method.length
// Line break between resources
if (lastPath !== endpoint.path) {
lastPath = endpoint.path
this.print()
}
// Print with colors
let line = method
if (!mono) {
line = this.color(line, (method ? method : 'get'))
}
line = line + (' '.repeat(pad)) + path
this.print(line)
}
return this
},
sortParams: function (mono) {
let sort = [
['by ID', '?sort=id'],
['by ID descending', '?sort=-id'],
['by any field', '?sort=name'],
['by multiple fields', '?sort=-created,email']
]
// Heading
this.print('Sort lists:', true)
// Instructions
for (var i = 0; i < sort.length; i++) {
let description = sort[i][0]
let params = sort[i][1]
let pad = ' '.repeat(this.columnWidth - description.length)
if (!mono) {
params = this.color(params, 'get')
}
this.print(description + pad + params)
}
return this
},
nestParams: function (mono) {
let nesting = [
['resource with objects', '?nest=true']
]
// Heading
this.print('Nested resources:', true)
// Instructions
for (var i = 0; i < nesting.length; i++) {
let description = nesting[i][0]
let params = nesting[i][1]
let pad = ' '.repeat(this.columnWidth - description.length)
if (!mono) {
params = this.color(params, 'get')
}
this.print(description + pad + params)
}
return this
},
filterParams: function (mono) {
let filters = [
['by ID', '?id=4'],
['with OR', '?id=4,5,6'],
['with operators', '?id=!4 ?age=>20'],
['by any field', '?email=<EMAIL>'],
['by multiple fields', '?role=admin&age=<20']
]
// Heading
this.print('Filter lists:', true)
// Instructions
for (var i = 0; i < filters.length; i++) {
let description = filters[i][0]
let params = filters[i][1]
let pad = ' '.repeat(this.columnWidth - description.length)
if (!mono) {
params = this.color(params, 'get')
}
this.print(description + pad + params)
}
}
}
<file_sep>/lib/transform/transformOutOne.js
const config = require('../config')
const transformersOut = {
array: require('./transformOutArray'),
timestamp: require('./transformOutTimestamp')
}
const getRawType = require('../helpers/getRawType')
const normalizeType = require('../helpers/normalizeType')
// Transform one object for being exposed to the outside world
module.exports = function (dbPath, schema, resourceType, row, nest) {
return new Promise(function (resolve, reject) {
let promises = 0
// NOTE: runtime require is needed here
const select = require('../db/select')
for (let fieldName in row) {
// Something like string, array, user or posts
let type = normalizeType(fieldName, resourceType, schema, config)
// Something like string or array, never user or posts
let rawType = getRawType(fieldName, resourceType, schema, config)
// ALWAYS transform by raw type first (so arrays and integers get treated even if they refer to resources)
if (transformersOut[rawType]) {
row[fieldName] = transformersOut[rawType](row[fieldName])
}
let value = row[fieldName]
// If user asked to nest, and field is resource
// Type might be defined in schema, meaning it's an ID that refers to another resource
// Singular: one child object
if (nest && schema.singulars[type]) {
promises++
// Select needs the type in plural
let pluralType = schema.singulars[type]
// Select one object
select.one(
dbPath,
schema,
pluralType,
value, // Value is ID
false // No more nesting beyond this point
// After select is complete...
).then(function (childRow) {
// Replace ID with child object
row[fieldName] = childRow
// Keep track of promises, resolve if we're done
promises--
if (!promises) {
resolve(row)
}
})
// Plural: list of child objects
} else if (nest && schema.plurals[type]) {
promises++
// Select one object
select.all(
dbPath,
schema,
type,
{
id: value // Value is array of IDs
},
false // No more nesting beyond this point
// After select is complete...
).then(function (childRows) {
// Replace ID with child object
row[fieldName] = childRows
// Keep track of promises, resolve if we're done
promises--
if (!promises) {
resolve(row)
}
})
}
}
if (!promises) {
resolve(row)
}
})
}
<file_sep>/lib/helpers/normalizeWhereArray.js
const _ = require('lodash')
// Be accepting when people give out values
module.exports = function (rawType, value) {
// Integers user might want to check for multiple integer matches
if (rawType === 'integer' && typeof value === 'string') {
try {
let val = JSON.parse(value)
return val
// We did our best
} catch (error) {
let int = parseInt(value)
if (_.isNumber(int) && !_.isNaN(int)) {
return int
}
}
}
return value
}
<file_sep>/lib/db/select.js
const _ = require('lodash')
const Database = require('better-sqlite3')
const squel = require('squel')
const config = require('../config')
const getRawType = require('../helpers/getRawType')
const normalizeWhereArray = require('../helpers/normalizeWhereArray')
const normalizeWhereValue = require('../helpers/normalizeWhereValue')
const normalizeWhereQuery = require('../helpers/normalizeWhereQuery')
const transformOutOne = require('../transform/transformOutOne')
const transformOutMany = require('../transform/transformOutMany')
module.exports = {
// Select an item by ID
one: function (dbPath, schema, resourceType, id, nest) {
return this.by(dbPath, schema, resourceType, {
'id': id
}, nest)
},
// Select item by value of any one field
by: function (dbPath, schema, resourceType, where, nest) {
let resource = schema.resourceTypes[resourceType]
// Base query
let query = squel.select().from(resource.plural)
// Chain where statements
for (let key in where) {
let value = where[key]
let field = resource.fields[key]
query = query.where(key + '=' + ((field && field.type) === 'string' ? '"' + value + '"' : value))
}
return new Promise(function (resolve, reject) {
try {
// Init database connection
const db = new Database(dbPath, {
readonly: true
})
// Execute query
let row = db.prepare(query.toString()).get()
// Close local database connection
db.close()
// Resolve promise
transformOutOne(dbPath, schema, resourceType, row, nest).then(function (row) {
resolve(row)
}).catch(function (error) {
reject(error)
})
} catch (error) {
reject(error)
}
})
},
all: function (dbPath, schema, resourceType, where, nest, sort) {
let resource = schema.resourceTypes[resourceType]
let query = squel.select().from(resource.plural)
// Chain where statements
// NOTE: normalizing where should be it's own module almost
for (let fieldName in where) {
let rawType = getRawType(fieldName, resourceType, schema)
let value = normalizeWhereArray(rawType, where[fieldName])
let field = resource.fields[fieldName]
// Many possible values provided, using OR to select all matches
if (value instanceof Array) {
// Normalize each value item
let values = _.map(value, function (singleValue) {
if (field) {
return normalizeWhereValue(rawType, singleValue)
}
return singleValue
})
// Compose OR query
query = query.where(fieldName + ' IN (' + values.join(', ') + ')')
// Just one
} else {
let whereValue = normalizeWhereValue(rawType, value)
let whereQuery = normalizeWhereQuery(rawType, whereValue)
query = query.where(fieldName + ' ' + whereQuery)
}
}
// Combine sorting rules
if (sort && (_.isString(sort) || _.isArray(sort)) && sort.length) {
// Normalize sort so we always deal with an array of sort values
if (!(sort instanceof Array)) {
sort = [sort]
}
// Always include with default sort order, unless ID is in sort already
let defaultSort = config.defaultSort
let defaultSortReverse = defaultSort.substr(0, 1) === '-' ? defaultSort.substr(1) : '-' + defaultSort
// Add default sort to the sorting rules if it's not there yet
if (
!_.includes(sort, defaultSort) &&
!_.includes(sort, defaultSortReverse)
) {
sort = [].concat(sort, [defaultSort])
}
} else {
sort = [config.defaultSort]
}
// Apply sorting with "id, -name" syntax support
for (let i = 0; i < sort.length; i++) {
let column = sort[i]
// Desc
if (column.substr(0, 1) === '-') {
column = column.substr(1)
query.order(column, false)
// ASC
} else {
query.order(column)
}
}
return new Promise(function (resolve, reject) {
try {
// Init database connection
const db = new Database(dbPath, {
readonly: true
})
// Execute query
let rows = db.prepare(query.toString()).all()
// Close local database connection
db.close()
// Resolve promise
transformOutMany(dbPath, schema, resourceType, rows, nest).then(function (rows) {
resolve(rows)
}).catch(function (error) {
reject(error)
})
} catch (error) {
reject(error)
}
})
}
}
<file_sep>/lib/routes/putById.js
const normalizeRequestParamatersForInput = require('../helpers/normalizeRequestParamatersForInput')
const fail = require('../response/fail')
const success = require('../response/success')
const exists = require('../db/exists')
const select = require('../db/select')
const update = require('../db/update')
module.exports = function (scam) {
for (let resourceType in scam.schema.resourceTypes) {
let resource = scam.schema.resourceTypes[resourceType]
let handler = function (request, response) {
const requestedId = parseInt(request.params.id)
const message404 = 'A ' + resource.singular + ' with the requested ID ' + requestedId + ' does not exist'
const message500 = 'Something went wrong when updating this resource.'
// Check if resource is there for updating
exists.where(
scam.dbPath,
scam.schema,
resourceType,
{
id: requestedId
}
// Query successful
).then(function (exists) {
// Resource exists, we can update
if (exists) {
// Normalize input sent
let valuesToInsert = normalizeRequestParamatersForInput(request.body, resource.fields)
// Update the database
update.one(
scam.dbPath,
scam.schema,
resourceType,
requestedId,
valuesToInsert
// Updating was successful
).then(function (id) {
// fetch the updated object
select.one(
scam.dbPath,
scam.schema,
resourceType,
id,
false
// Success response
).then(function (row) {
success(
scam,
resourceType,
request,
response,
200,
row
)
// Could not fetch the updated object
}).catch(function (error) {
fail(
scam,
resourceType,
request,
response,
500,
message500,
[
'select.one(...).catch()',
error
]
)
})
// Something went wrong when doing the update
}).catch(function (error) {
fail(
scam,
resourceType,
request,
response,
500,
message500,
[
'update.one(...).catch()',
error
]
)
})
// The resource with the requested ID doesn't exist, so it can't be updated
} else {
fail(
scam,
resourceType,
request,
response,
404,
message404
)
}
// Check failed, this is an internal error
}).catch(function (error) {
fail(
scam,
resourceType,
request,
response,
500,
message500,
[
'exists.where(...).catch()',
error
]
)
})
}
// Register update endpoint
// NOTE: we do this for convenience, but it's not really correct
scam.app.patch('/' + resource.plural + '/:id', handler)
scam.app.put('/' + resource.plural + '/:id', handler)
}
}
<file_sep>/lib/helpers/normalizeWhereValue.js
const _ = require('lodash')
// Be accepting when people give out values
module.exports = function (rawType, value) {
// Strings need quote treatment
if (rawType === 'string') {
return '"' + value + '"'
// Integers, oh integers
} else if (rawType === 'integer') {
let int = parseInt(value)
if (_.isNumber(int) && !_.isNaN(int)) {
return int
}
}
return value
}
<file_sep>/lib/routines/clearDatabase.js
const fs = require('fs')
// Remove DB file
module.exports = function (dbPath) {
if (fs.existsSync(dbPath)) {
fs.unlinkSync(dbPath)
}
}
<file_sep>/lib/helpers/getCacheDuration.js
const _ = require('lodash')
module.exports = function (scam, resourceType) {
// Cache set per type
if (resourceType) {
let typeCacheValue = scam.schema.resourceTypes[resourceType].cache
if (_.isNumber(typeCacheValue)) {
return Math.min(0, typeCacheValue)
}
}
// Default
return scam.cache
}
<file_sep>/lib/config.js
module.exports = {
// Mapping of internally used types to something that SQLite understands
sqlTypes: {
integer: 'INTEGER',
string: 'TEXT',
float: 'FLOAT',
boolean: 'BOOLEAN',
array: 'VARCHAR', // array is stored as a string, transformers will handle this
date: 'TIME',
time: 'DATE',
timestamp: 'TIMESTAMP'
},
// When field type is not explicitly defined in schema, we default to this
defaultType: 'integer',
defaultSort: 'id',
// Some fields are automatically added to the tables, and do not have to be defined in schema
// FIXME: if they are, we have a problem
nativeFields: {
id: {
type: 'integer',
sqlValue: 'primary key'
},
created: {
type: 'timestamp',
sqlValue: 'DEFAULT CURRENT_TIMESTAMP'
},
updated: {
type: 'timestamp',
sqlValue: 'DEFAULT CURRENT_TIMESTAMP'
}
},
// Paramters used in URLs should not be used as field names
reservedParameterNames: [
'sort',
'nest',
// Not used yet
'offset',
'limit'
],
// We use these in the query formatter for insert/update
squelWriteOptions: {
// Overriding default string formatter because we don't want the placeholders escaped
stringFormatter: function (string) {
return string
}
},
consoleLogColors: {
'get': '#4FBEE3', // blue
'post': '#90E92F', // green
'put': '#F5A623', // orange
'delete': '#F0607F' // red
},
errorMessages: {
options: 'Incorrect options passed to Scam',
// Option-related error codes
'options.data.format': 'Data was not passed in the correct format. Pass data as an object, or a string of a path to require data from.',
'options.schema.format': 'Schema was not passed in the correct format. Pass schema as an object, or a string of a path to require schema from.'
}
}
<file_sep>/lib/response/success.js
const _ = require('lodash')
const getCacheDuration = require('../helpers/getCacheDuration')
module.exports = function (scam, resourceType, request, response, status, body) {
// Default status
if (!status) {
status = 200
}
// Figure out the right cache time
let cache = 0
if (request.method.toLowerCase() === 'get' && resourceType) {
cache = getCacheDuration(scam, resourceType)
}
// Response body
// Basic format
let content = {
timestamp: new Date()
}
// Never send out undefined
if (!_.isUndefined(body)) {
content.body = body
}
// Lists get additional meta info
if (content.body instanceof Array) {
// Number of items in list vs. available in total
content.count = content.body.length
content.totalCount = content.body.length
// Offset
content.offset = 0
// No limit = list not paginated
content.limit = null
}
// Add meta info about resource type
if (resourceType) {
content.schema = scam.schema.resourceTypes[resourceType]
}
// Headers
// Set cache headers based on the cache time defined
if (cache > 0) {
response.setHeader('Cache-Control', 'public, max-age=' + (cache * 60))
} else {
response.setHeader('Cache-Control', 'no-cache')
}
// Set and return final response
return response.status(status).json(content)
}
<file_sep>/lib/routes/deleteById.js
const fail = require('../response/fail')
const success = require('../response/success')
const exists = require('../db/exists')
const remove = require('../db/remove')
module.exports = function (scam) {
for (let resourceType in scam.schema.resourceTypes) {
let resource = scam.schema.resourceTypes[resourceType]
// Register delete endpoint
scam.app.delete('/' + resource.plural + '/:id', function (request, response) {
const requestedId = parseInt(request.params.id)
const message404 = 'A ' + resource.singular + ' with the requested ID ' + requestedId + ' does not exist'
const message500 = 'Something went wrong when removing this resource.'
// Check if resource is there for updating
exists.where(
scam.dbPath,
scam.schema,
resourceType,
{
id: requestedId
}
// Query successful
).then(function (exists) {
// Resource exists, we can update
if (exists) {
// Update the database
remove.one(
scam.dbPath,
scam.schema,
resourceType,
requestedId
// Success response
).then(function (id) {
success(
scam,
resourceType,
request,
response,
200,
{}
)
// Error response
}).catch(function (error) {
fail(
scam,
resourceType,
request,
response,
500,
message500,
[
'remove.one(...).catch()',
error
]
)
})
// The resource with the requested ID doesn't exist, so it can't be updated
} else {
fail(
scam,
resourceType,
request,
response,
404,
message404
)
}
// Check failed, this is an internal error
}).catch(function (error) {
fail(
scam,
resourceType,
request,
response,
500,
message500,
[
'exists.where(...).catch()',
error
]
)
})
})
}
}
<file_sep>/lib/helpers/getRawType.js
const normalizeType = require('./normalizeType')
// Normalize type of a field, without returning a resource type
module.exports = function (fieldName, resourceType, schema) {
// If the field is a reference to another resource, we need the field type used when storing it
// List of references to other resources
if (schema.plurals[fieldName]) {
return 'array'
// One reference to another resource
} else if (schema.singulars[fieldName]) {
return 'integer'
}
return normalizeType(fieldName, resourceType, schema)
}
<file_sep>/lib/errors/ScamOptionsError.js
// Error to throw when user has passed incorrect options to a new Scam instance
const config = require('../config')
function ScamOptionsError (code) {
const message = config.errorMessages[code]
this.name = 'ScamOptionsError'
this.code = code
this.message = config.errorMessages['options'] + (message ? ': ' + message : message)
this.stack = (new Error()).stack
}
ScamOptionsError.prototype = Object.create(Error.prototype)
ScamOptionsError.prototype.constructor = ScamOptionsError
module.exports = ScamOptionsError
<file_sep>/lib/transform/transformInOne.js
const config = require('../config')
const transformersIn = {
array: require('./transformInArray'),
timestamp: require('./transformInTimestamp')
}
const getRawType = require('../helpers/getRawType')
// Transform one object for inserting into database
module.exports = function (dbPath, schema, resourceType, values) {
// We transform field by field
for (let fieldName in values) {
let type = getRawType(fieldName, resourceType, schema, config)
let value = values[fieldName]
// Transformer available
if (transformersIn[type]) {
values[fieldName] = transformersIn[type](value)
}
}
return values
}
<file_sep>/lib/routes/deleteToList.js
const _ = require('lodash')
const fail = require('../response/fail')
const success = require('../response/success')
const remove = require('../db/remove')
module.exports = function (scam) {
for (let resourceType in scam.schema.resourceTypes) {
let resource = scam.schema.resourceTypes[resourceType]
// Insert response handler
let handler = function (request, response) {
const message500 = 'Something went wrong when removing these resources.'
let idsToRemove = request.body
// Normalize one ID
if (_.isInteger(idsToRemove)) {
idsToRemove = [idsToRemove]
}
// Insert many
if (_.isArray(idsToRemove)) {
// Remove objects
remove.many(
scam.dbPath,
scam.schema,
resourceType,
idsToRemove
// After remove...
).then(function () {
// Items were removed
// FIXME: will never report 404 or distinguish between IDs found or not found
success(
scam,
resourceType,
request,
response,
200,
{}
)
// Something went wrong when doing the removal
}).catch(function (error) {
fail(
scam,
resourceType,
request,
response,
500,
message500,
error
)
})
// Bad input
} else {
fail(
scam,
resourceType,
request,
response,
400,
'Please remove multiple resources by sending an array of IDs.'
)
}
}
// Register delete endpoints
scam.app.delete('/' + resource.plural, handler)
}
}
<file_sep>/test/tape.js
process.env.NODE_ENV = 'test'
const tape = require('tape')
const axios = require('axios')
const url = 'http://localhost:3333'
tape('HTTP test', function (assert) {
// assert.plan(1)
assert.test('GET /', {}, function (subAssert) {
axios.get(url).then(function (response) {
// subAssert.plan(4)
subAssert.equal(response.status, 200, 'Status should be 200')
subAssert.equal(typeof response.data, 'object', 'Response should be object')
subAssert.ok(response.data.body, 'Response should include endpoints')
subAssert.ok(response.data.body.endpoints, 'Response should include endpoints')
subAssert.ok(response.data.body.resources, 'Response should include schema')
assert.pass()
}).catch(function (error) {
assert.fail(error)
})
})
})
<file_sep>/TODO.md
# Todo
- Support promises in transformMany
- [x] Dummy data
- [x] Field transformers
- [x] `created` timestamp
- [x] Relations via type
- [x] Make config and module code spearate
- [x] Rename from `scam` to something else
- [x] Publish in NPM
- [x] Sorting in lists via `sort` param
- [x] Filtering in lists via any non-reserved field param in query
- [x] Better `normalizeWhereValue`
- [x] PUT/UPDATE
- [x] DELETE
- [x] Move selection after insert/update to route handlers
- [x] Cache in config and schema
- [x] Allow setting type in singular in schema or use another key for setting reference
- [x] Make some kind of response formatter for success and error responses
- [x] Support nested object lists (IDs and/or expanded, singular vs. plural, using `select.all`)
- [x] ~~Control nesting level via `depth` param (have to control circular references somehow)~~
- One is enough
- [x] Add `logEndpoints` to module
- [x] Add option for debug mode and print internal error messages as debug field
- [x] Filter integers and timestamps by operator (`<`, `>`, `<=`, `>=`)
- [x] Separate repos for demo and module
- [x] Validate options upon init
- [x] Support schema and schema path as option
- [x] Support data and data path as option
- [x] Support `POST`ing multiple resources (`insert.many` + handlers)
- [x] Support `PUT`ting multiple resources (`update.many` + handlers)
- [x] Support `DELETE` for multiple resources (`delete.many` + handlers)
- [x] `updated` timestamp
- [ ] Differentiate between `PATCH` and `PUT`
- [ ] Report found and not found IDs in `deleteToList`
- [x] Make `default` work in schema
- [ ] Make `required` work in schema (return errors from POST and UPDATE)
- [ ] Appropriate error codes (returns 500 quite often)
- [ ] Define and document error format
- [ ] Infer type from default if type is omitted in schema
- [ ] Document reserved words (query parameters conflicting with prop names, types conflicting with resource types)
- [ ] Set up test coverage
- [ ] Pagination (limits and offsets)
- [ ] Proper input validation errors
- [ ] Validate schema upon init
- [ ] Validate data upon init (against schema)
- [ ] Default to in-memory db when databasePath is omitted
- [ ] `.log()` some more information about about data, schema, databasePath and other options
- [ ] Validate all params (sort, nest, filter per field rawType)
- [ ] Support custom hooks and transformers per resource (pass in as options or in schema)
- [ ] `update`, `insert` and `remove` multiple items in SQL at once instead of using the `.one` methods
- [ ] Author the module as express middleware
- [ ] Move all of these tasks to GitHub issues
## Rewrite
Refactor app to have a real scalable structure and less just passing the same arguments to helpers.
<file_sep>/lib/routes/putToList.js
const _ = require('lodash')
const normalizeRequestParamatersForInput = require('../helpers/normalizeRequestParamatersForInput')
const fail = require('../response/fail')
const success = require('../response/success')
const update = require('../db/update')
const select = require('../db/select')
module.exports = function (scam) {
for (let resourceType in scam.schema.resourceTypes) {
let resource = scam.schema.resourceTypes[resourceType]
// Insert response handler
let handler = function (request, response) {
const message500 = 'Something went wrong when updating these resources.'
let inputParams = request.body
// Insert many
if (_.isArray(inputParams)) {
let valuesToInsert = []
// Normalize each array item sent
for (var i = 0; i < inputParams.length; i++) {
let values = inputParams[i]
valuesToInsert.push(
// The normalisation helper will only include the fields defined in schema
// ID is an internal field, but we need it for update
_.merge(
{
id: values.id
},
normalizeRequestParamatersForInput(values, resource.fields)
)
)
}
// Update objects with new values
update.many(
scam.dbPath,
scam.schema,
resourceType,
valuesToInsert
// After update...
).then(function (updatedIds) {
// Fetch the updated objects
select.all(
scam.dbPath,
scam.schema,
resourceType,
{
id: updatedIds
},
false
// Send success response with the newly created objects
).then(function (rows) {
success(
scam,
resourceType,
request,
response,
200,
rows
)
// Could not fetch the new objects
}).catch(function (error) {
fail(
scam,
resourceType,
request,
response,
500,
message500,
error
)
})
// Something went wrong when doing the update
}).catch(function (error) {
fail(
scam,
resourceType,
request,
response,
500,
message500,
error
)
})
// Bad input
} else {
fail(
scam,
resourceType,
request,
response,
400,
'Please update multiple resources by sending an array with the new values, with id included in each object.'
)
}
}
// Register update endpoints
// NOTE: we do this for convenience, but it's not really correct
scam.app.patch('/' + resource.plural, handler)
scam.app.put('/' + resource.plural, handler)
}
}
<file_sep>/lib/routes/getById.js
const fail = require('../response/fail')
const success = require('../response/success')
const select = require('../db/select')
module.exports = function (scam) {
for (let resourceType in scam.schema.resourceTypes) {
let resource = scam.schema.resourceTypes[resourceType]
// Register ID getter endpoint
scam.app.get('/' + resource.plural + '/:id', function (request, response) {
const requestedId = parseInt(request.params.id)
const message404 = 'A ' + resource.singular + ' with the requested ID ' + requestedId + ' does not exist'
const message500 = 'Something went wrong when looking for this resource.'
// Find element from database
select.one(
scam.dbPath,
scam.schema,
resourceType,
requestedId,
request.query.nest ? true : false
).then(function (row) {
// Send out success response
if (row) {
success(
scam,
resourceType,
request,
response,
200,
row
)
// Not found
} else {
fail(
scam,
resourceType,
request,
response,
404,
message404
)
}
// Something else went wrong
}).catch(function (error) {
fail(
scam,
resourceType,
request,
response,
500,
message500,
error
)
})
})
}
}
<file_sep>/lib/routes/getList.js
const _ = require('lodash')
const fail = require('../response/fail')
const success = require('../response/success')
const config = require('../config')
const select = require('../db/select')
// Generate list endpoints in a loop
module.exports = function (scam) {
for (let resourceType in scam.schema.resourceTypes) {
let resource = scam.schema.resourceTypes[resourceType]
// Register list getter endpoint
scam.app.get('/' + resource.plural, function (request, response) {
const message500 = 'Something went wrong when looking for these resources.'
// Use query parameters to filter list
// NOTE: would it be better to not loop all query params here?
let where = {}
for (let key in request.query) {
if (!_.includes(config.reservedParameterNames, key)) {
where[key] = request.query[key]
}
}
// Fetch items from database
select.all(
scam.dbPath,
scam.schema,
resourceType,
where,
request.query.nest ? true : false,
request.query.sort ? request.query.sort.split(',') : []
).then(function (rows) {
// Send out success response
success(
scam,
resourceType,
request,
response,
200,
rows
)
// Something else went wrong
}).catch(function (error) {
fail(
scam,
resourceType,
request,
response,
500,
message500,
error
)
})
})
}
}
<file_sep>/lib/index.js
const _ = require('lodash')
const bodyParser = require('body-parser')
// Central config
// const config = require('./config')
// CLI
const logger = require('./cli/logger')
// Scripts
const clearDatabase = require('./routines/clearDatabase')
const createDatabase = require('./routines/createDatabase')
const loadData = require('./routines/loadData')
// Route initialisers
const routes = require('./routes')
// Errors
const ScamOptionsError = require('./errors/ScamOptionsError')
module.exports = {
// Components
logger: logger,
// Props
app: null,
cache: null,
debug: null,
data: {},
dbPath: null,
endpoints: null,
schema: null,
// Setters
setApp: function (app) {
this.app = app
return this
},
setCache: function (cache) {
if (cache) {
cache = parseInt(cache)
if (_.isNumber(cache) && cache > 0) {
this.cache = cache
}
}
return this
},
setDebug: function (debug) {
if (debug) {
this.debug = true
}
return this
},
setData: function (data) {
if (data) {
this.data = data
}
return this
},
setDataFromPath: function (dataPath) {
return this.setData(require(dataPath))
},
setDatabasePath: function (dbPath) {
this.dbPath = dbPath
return this
},
setSchema: function (resourceTypes) {
let schema = {
plurals: {},
singulars: {},
resourceTypes: resourceTypes
}
// Generate mappings between singular and plural, since keys are stored only in the latter format
for (let key in schema.resourceTypes) {
let resource = schema.resourceTypes[key]
schema.plurals[key] = resource.singular
schema.singulars[resource.singular] = key
}
this.schema = schema
return this
},
setSchemaFromPath: function (schemaPath) {
return this.setSchema(require(schemaPath))
},
// Setup work
prepareApp: function () {
// Set up some Express middleware
this.app.use(bodyParser.json())
this.app.use(bodyParser.urlencoded({
extended: true
}))
return this
},
initRoutes: function () {
routes(this)
return this
},
// API
getEndpoints: function () {
// Meta info at root
let endpoints = [
{
method: 'get',
path: '/'
}
]
// Per resource type
for (let key in this.schema.resourceTypes) {
let path = this.schema.resourceTypes[key].plural
// GET list/
endpoints.push({
method: 'get',
path: '/' + path
})
// GET list/:id
endpoints.push({
method: 'get',
path: '/' + path,
params: ['id']
})
// POST list/
endpoints.push({
method: 'post',
path: '/' + path
})
// PUT list/
endpoints.push({
method: 'put',
path: '/' + path
})
// PUT list/:id
endpoints.push({
method: 'put',
path: '/' + path,
params: ['id']
})
// // DELETE list/
endpoints.push({
method: 'delete',
path: '/' + path
})
// DELETE list/:id
endpoints.push({
method: 'delete',
path: '/' + path,
params: ['id']
})
}
return endpoints
},
setEndpoints: function (endpoints) {
this.endpoints = endpoints
return this
},
// CLI logger API
log: function () {
this.logger.all(this, !this.debug)
return this
},
// Lifecycle handling
clearDatabase: function () {
clearDatabase(this.dbPath)
},
createDatabase: function () {
createDatabase(this.dbPath, this.schema)
},
loadData: function () {
loadData(this.dbPath, this.schema, this.data)
},
// Setup
init: function (app, options) {
// Store reference to app and register some middleware
this.setApp(app).prepareApp()
// Consume options
this.setOptions(options)
// Define endpoints based on resource types
this.setEndpoints(this.getEndpoints())
// Register routes and route handlers for all resource types
this.initRoutes()
return this
},
setOptions: function (options) {
// Set default cache time that can be overwritten per resource in schema
this.setCache(options.cache)
// Enable or disable debug mode
this.setDebug(options.debug)
// Options
// Data can be used as it is
if (_.isPlainObject(options.data)) {
this.setData(options.data)
// Data is given as path to require from
} else if (_.isString(options.data)) {
this.setDataFromPath(options.data)
// Data is not ok
} else if (options.data) {
throw new ScamOptionsError('options.data.format')
}
// Database path
// If database path was provided, use it instead of an in-memory DB
if (_.isString(options.databasePath)) {
this.setDatabasePath(options.databasePath)
}
// Schema
// Schema can be used as it is
if (_.isPlainObject(options.schema)) {
this.setSchema(options.schema)
// Schema is given as path to require from
} else if (_.isString(options.schema)) {
this.setSchemaFromPath(options.schema)
// Schema is not ok
} else if (options.schema) {
throw new ScamOptionsError('options.schema.format')
}
}
}
|
79deb2c26ba6834d00f6edead65c96b11ceb6421
|
[
"Markdown",
"JavaScript"
] | 26
|
Markdown
|
Eiskis/scam
|
b0fb9b7f6a52a255e49f1c3edcbb6ae7470d0f16
|
99a05e26c46dcaf697f7f32b6786566e7b1261ab
|
refs/heads/main
|
<repo_name>MIXRONLINE/cutout<file_sep>/src/App.js
import React, { useEffect, useState } from 'react';
import { Rnd } from "react-rnd";
import './App.css'
const style = {
display: "flex",
alignItems: "center",
justifyContent: "center",
border: "solid 1px #ddd",
background: "#f0f0f044",
color: 'white'
};
function App() {
const [img, setImg] = useState('');
const [num, setNum] = useState(1);
const [boxes, setBoxes] = useState(
[{
width: 40,
height: 30,
x: 10,
y: 10
}]
);
const [item, setItem] = useState('');
const [caption, setCaption] = useState('');
useEffect(() => {
// url: "https://i.imgur.com/A3piGqW.png",
// facePos: [
// '17 / 19 / 34 / 35',
// '7 / 30 / 24 / 48',
// '8 / 45 / 28 / 62',
// '8 / 61 / 26 / 77',
// '13 / 73 / 37 / 94',
// '59 / 45 / 85 / 73'
// ],
// caption: "You were the chosen one!"
let text = '{';
let url = "url:'" + img + "', ";
text = text.concat(url);
let cap = "caption:\"" + caption + "\", ";
text = text.concat(cap);
let facePos = "facePos:[";
text = text.concat(facePos);
boxes.forEach((b)=>{
let s = "'"+ b.x + ' / ' + b.y + ' / '+ (parseInt(b.x) + parseInt(b.width.toString().split('px')[0])).toString() +' / ' + (parseInt(b.y) + parseInt(b.height.toString().split('px')[0])).toString() +"',"
text = text.concat(s);
})
text = text.concat(']');
text = text.concat('},')
setItem(text);
}, [boxes, img, caption])
useEffect(() => {
let b = [];
let startX = 10;
for (let i = 0; i < num; i++) {
b.push({
width: 40,
height: 30,
x: startX,
y: 10
})
startX = startX + 50;
}
setBoxes(b);
}, [num])
console.log(boxes)
return (
<div>
<div
className='container'
style={{
backgroundImage: 'url(' + img + ')'
}}
>
{boxes.length > 0 ?
<>
{boxes.map((box, key) => {
console.log(box);
return (
<Rnd
key={key}
lockAspectRatio={1.333333333333333333}
bounds='parent'
style={style}
size={{ width: box.width, height: box.height }}
position={{ x: box.x, y: box.y }}
onDragStop={(e, d) => {
let b = [...boxes];
b[key].x = d.x;
b[key].y = d.y;
console.log(b);
setBoxes(b);
}}
onResizeStop={(e, direction, ref, delta, position) => {
let b = [...boxes]
b[key].width = ref.style.width;
b[key].height = ref.style.height;
setBoxes(b);
}}
>
{key + 1}
</Rnd>
)
})}
</>
: null}
</div>
<div className='controls'>
<p>Img:</p>
<input onChange={(e) => {
setImg(e.target.value)
}} />
<p>Number of faces:</p>
<input type='number' onChange={(e) => {
setNum(e.target.value)
}} />
<p>Caption:</p>
<input onChange={(e) => {
setCaption(e.target.value)
}} />
<br />
<br />
<p>{item}</p>
</div>
</div>
);
}
export default App;
|
3ef01e7437ca4d2664b31d72d9f3894c08e402d7
|
[
"JavaScript"
] | 1
|
JavaScript
|
MIXRONLINE/cutout
|
4224c395335eab7b55a7960df07f49cb73d8f036
|
83b535633ce2b823e045e9c66a8060bccefb613d
|
refs/heads/master
|
<repo_name>dbaxyx/think<file_sep>/src/com/std/reflect/f.java
package com.std.reflect;
/**
* Created by xiaoyx5 on 2016/1/27.
*/
public class f {
protected String str = "123";
}
<file_sep>/src/com/std/io/ioTest5.java
package com.std.io;
import java.io.File;
import java.io.IOException;
/**
* Created by xiaoyx5 on 2016/2/2.
*/
public class ioTest5 {
public static void main(String[] args) throws IOException {
File file = new File("D:/abc/xyz/hello/abc2.txt");
file.createNewFile();
file.delete();
}
}
<file_sep>/src/com/generic/test/test.java
package com.generic.test;
/**
* Created by xiaoyx5 on 2015/12/30.
*/
public interface test {
public String name = null;
}
<file_sep>/src/com/std/io/ioTest.java
package com.std.io;
import java.io.File;
import java.io.IOException;
/**
* Created by xiaoyx5 on 2016/2/2.
*/
public class ioTest {
public static void main(String[] args) {
File file = new File("D:/text.txt");
try {
System.out.println(file.createNewFile());
System.out.println(File.pathSeparator);
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/com/com/classloader/Test8.java
package com.com.classloader;
/**
* Created by xiaoyx5 on 2016/3/9.
*/
public class Test8 {
public static void main(String[] args) throws ClassNotFoundException {
ClassLoader loader = ClassLoader.getSystemClassLoader();
Class<?> clazz = loader.loadClass("com.com.classloader.Ds");
System.out.println("---------------------");
clazz = Class.forName("com.com.classloader.D");
}
}
class D{
static{
System.out.println("Class D");
}
}<file_sep>/src/com/reflect/study/testPrivate3.java
package com.reflect.study;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by xiaoyx5 on 2016/1/30.
*/
public class testPrivate3 {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Private2 p = new Private2();
Class<?> classType = p.getClass();
Field field = classType.getDeclaredField("name");
field.setAccessible(true);
field.set(p,"hello");
System.out.println(field.toString());
System.out.println(p.getName());
Method method = classType.getDeclaredMethod("sayHello");
method.setAccessible(true);
String str = (String)method.invoke(p,new Object[]{});
System.out.println("----Method:"+str);
}
}
<file_sep>/src/com/thread/clone/CloneTest2.java
package com.thread.clone;
/**
* Created by xiaoyx5 on 2016/2/26.
*/
public class CloneTest2 {
public static void main(String[] args) throws CloneNotSupportedException {
Teacher teacher = new Teacher();
teacher.setName("zhangsan");
teacher.setAge(40);
Student2 student2 = new Student2();
student2.setAge(20);
student2.setName("lisi");
student2.setTeacher(teacher);
Student2 student21 = (Student2) student2.clone();
System.out.println(student2.getName());
System.out.println(student2.getAge());
teacher.setName("<NAME>");
System.out.println(student2.getTeacher().getName());
System.out.println(student2.getTeacher().getAge());
System.out.println("-------------------");
System.out.println("student2: "+student2);
System.out.println("student21: "+student21);
System.out.println("student2.teacher: "+student2.getTeacher());
System.out.println("student21.teacher: "+student21.getTeacher());
System.out.println(student2.getTeacher().getName());
System.out.println(student21.getTeacher().getName());
}
}
class Teacher implements Cloneable{
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Object clone() throws CloneNotSupportedException {
Object object = super.clone();
return object;
}
}
class Student2 implements Cloneable{
private int age;
private String name;
private Teacher teacher;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
@Override
public Object clone() throws CloneNotSupportedException {
Student2 student2 = (Student2)super.clone();
student2.setTeacher((Teacher) student2.getTeacher().clone());
return student2;
}
}
<file_sep>/src/com/std/reflect/InvokeTester.java
package com.std.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by xiaoyx5 on 2016/1/1.
*/
public class InvokeTester {
public int add(int param1, int param2){
return param1 + param2;
}
public String echo(String mesage){
return "hello: " + mesage;
}
public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
/* InvokeTester test = new InvokeTester();
System.out.println(test.add(1,2));
System.out.println(test.echo("你好!"));*/
Class<?> classType = InvokeTester.class;
Object invokeTester = classType.newInstance();
// System.out.println(invokeTester instanceof InvokeTester);
Method addMethod = classType.getMethod("add",new Class[]{int.class,int.class});
Object result = addMethod.invoke(invokeTester,new Object[]{1,2});
System.out.println((Integer)result);
System.out.println("----------");
Method echoMethod = classType.getMethod("echo",new Class[]{String.class});
Object result2 = echoMethod.invoke(invokeTester,new Object[]{"hello"});
System.out.println((String)result2);
}
}
<file_sep>/src/com/std/common/stringTest.java
package com.std.common;
/**
* Created by xiaoyx5 on 2016/1/28.
*/
public class stringTest {
public static void main(String[] args) {
String str1 = "DAT_ADB_*_IN.txt";
String str2 = str1.replace("*","20160202");
System.out.println(str2);
}
}
<file_sep>/src/com/decorator/Componet.java
package com.decorator;
/**
* Created by xiaoyx5 on 2016/2/21.
*/
public interface Componet {
public void doSomething();
}
<file_sep>/src/com/classInfo/WildcardClassReferences.java
package com.classInfo;
/**
* Created by xiaoyx5 on 2016/4/3.
*/
public class WildcardClassReferences {
public static void main(String[] args) {
//Anty
Class<?> intClass = int.class;
intClass = double.class;
}
}
<file_sep>/src/com/io/RandomAccessFile1.java
package com.io;
/**
* Created by xiaoyx5 on 2016/2/21.
*/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFile1 {
public static void main(String[] args) throws IOException {
Person p = new Person(1, "hello", 5.42);
RandomAccessFile raf = new RandomAccessFile("test.txt" ,"rw");
p.write(raf);
}
}
class Person{
int id;
String name;
double height;
public Person(){
}
public Person(int id, String name, double height){
this.id = id;
this.name = name;
this.height = height;
}
public void write(RandomAccessFile raf) throws IOException {
raf.writeInt(this.id);
raf.writeUTF(this.name);
raf.writeDouble(this.height);
}
}
<file_sep>/src/com/thread/b.java
package com.thread;
/**
* Created by xiaoyx5 on 2016/3/1.
*/
public class b {
public static void main(String[] args) {
System.out.println(c.a);
System.out.println(c.a++);
System.out.println(c.a++);
System.out.println(c.a++);
c c1 = new c();
c1.b++;
System.out.println(c1.b);
c c2 = new c();
System.out.println(c2.b);
}
}
class c{
public static int a = 3;
public int b= 4;
}<file_sep>/src/com/std/io/ioTest3.java
package com.std.io;
import java.io.File;
/**
* Created by xiaoyx5 on 2016/2/2.
*/
public class ioTest3 {
public static void main(String[] args) {
File file = new File("d:/abc/xyz/hello");
System.out.println(file.mkdirs());
}
}
<file_sep>/src/com/classLoader/getClassLoaderTest.java
package com.classLoader;
/**
* Created by xiaoyx5 on 2016/3/30.
*/
public class getClassLoaderTest {
/* public ClassLoader getClassLoader() {
ClassLoader cl = getClassLoader();
if(cl == null){
return null;
}
SecurityManager sm = System.getSecurityManager();
if(sm != null){
ClassLoader ccl = ClassLoader.getSystemClassLoader();
if(ccl != null && ccl != cl && !cl)
}
return null;
}*/
}
<file_sep>/src/com/std/io/ioTest2.java
package com.std.io;
import java.io.File;
import java.io.IOException;
/**
* Created by xiaoyx5 on 2016/2/2.
*/
public class ioTest2 {
public static void main(String[] args) throws IOException {
File file = new File("D:/tess");
file.mkdir();
File file2 = new File(file, "hello.txt");
file2.createNewFile();
}
}
<file_sep>/src/com/net/TcpServer.kt
package com.net
/**
* Created by xiaoyx5 on 2016/2/28.
*/
<file_sep>/src/com/study/proxy/RealSubject.java
package com.study.proxy;
/**
* Created by xiaoyx5 on 2016/1/31.
*/
public class RealSubject extends Subject {
@Override
public void request() {
System.out.println("From real subject.");
}
}
<file_sep>/src/com/reflect/study/TestPrivate2.java
package com.reflect.study;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by xiaoyx5 on 2016/1/30.
*/
public class TestPrivate2 {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Private2 p = new Private2();
Class<?> classType = p.getClass();
Method method = classType.getDeclaredMethod("sayHello",new Class[] {String.class});
method.setAccessible(true);
String str = (String)method.invoke(p, new Object[]{"zhangsan"});
System.out.print(str);
}
}
<file_sep>/src/com/thread/DcreaseThread.java
package com.thread;
/**
* Created by xiaoyx5 on 2016/2/25.
*/
public class DcreaseThread extends Thread {
private Sample sample;
public DcreaseThread(Sample sample){
this.sample = sample;
}
public void run(){
for(int i =0; i< 20; i++){
try {
Thread.sleep((long)Math.random()*10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
sample.decrease();
}
}
}
<file_sep>/src/com/jvm/mapOfJvm.java
package com.jvm;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Created by xiaoyx5 on 2016/4/1.
*/
public class mapOfJvm {
public static void main(String[] args) {
/*Map<Integer, Object> map = new HashMap<Integer, Object>();
long times1 = new Date().getTime();
for (int i = 0; i < 2000000; i++) {
map.put(i, "1"+i);
}
System.out.println("结束时间》》"+(new Date().getTime()-times1));
*/
Map<Integer, Object> map1 = new HashMap<Integer, Object>(2000000);
long times = new Date().getTime();
for (int i = 0; i < 2000000; i++) {
map1.put(i, "1"+i);
}
System.out.println("结束时间》》"+(new Date().getTime()-times));
}
}
<file_sep>/src/com/com/classloader/Dog.java
package com.com.classloader;
/**
* Created by xiaoyx5 on 2016/3/9.
*/
public class Dog {
public Dog(){
System.out.println("Dog is loaded by : "+this.getClass().getClassLoader());
new Dog();
}
}
<file_sep>/src/com/com/classloader/StringUtils.java
package com.com.classloader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
/**
* Created by xiaoyx5 on 2016/3/4.
*/
public class StringUtils {
protected StringBuffer FormatCustId(String SERVID){
StringBuffer stb = new StringBuffer(SERVID);
while(stb.length() < 16){
stb.insert(0, "0");
}
return stb.insert(0, "29");
}
public static void main(String[] args) throws ParseException {
/* StringUtils stringUtils = new StringUtils();
String str = stringUtils.FormatCustId("30").toString();
System.out.println(str);
System.out.println(str.length());*/
/* String DateStr = "08-6月 -15";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
Date d = sdf.parse(DateStr);
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
String dd = sdf1.format(d);
System.out.println(dd);*/
String strDate = "2015-06-08 15:28:23";
//Date date = new Date(strDate);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.parse(strDate));
}
}
<file_sep>/src/com/net/UrlConnection.kt
package com.net
/**
* Created by xiaoyx5 on 2016/2/26.
*/
<file_sep>/src/com/com/classloader/Test9.java
package com.com.classloader;
import java.io.*;
/**
* Created by xiaoyx5 on 2016/3/9.
*/
public class Test9 extends ClassLoader{
private String name;
private String path = "d:\\"; //加载类的路径
private final String fileTYpe = ".class"; //class文件的扩展名
public Test9(String name){
super(); //让系统类加载器成为该加载器的父加载器
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getFileTYpe() {
return fileTYpe;
}
public Test9(ClassLoader parent, String name){
super(parent); //显式指定该类加载器的父加载器
this.name = name;
}
@Override
public String toString() {
return this.name;
}
private byte[] loadClassData(String name){
InputStream is = null;
byte[] data = null;
ByteArrayOutputStream baos = null;
try{
this.name = this.name.replace(".","\\");
is = new FileInputStream(new File(path + name +fileTYpe));
baos = new ByteArrayOutputStream();
int ch = 0;
while(-1 != (ch =is.read())){
baos.write(ch);
}
data = baos.toByteArray();
}
catch (Exception e){
e.printStackTrace();
}
finally {
try {
is.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] data = this.loadClassData(name);
return this.defineClass(name, data,0,data.length);
}
public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
Test9 loader1 = new Test9("loader1");
loader1.setPath("d:\\myapp\\serverlib");
Test9 loader2 = new Test9(loader1,"loader2");
loader2.setPath("d:\\myapp\\clientlib");
Test9 loader3 = new Test9(null,"loader3");
loader3.setPath("d:\\myapp\\otherlib");
test(loader2);
test(loader3);
}
public static void test(ClassLoader loader) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class clazz = loader.loadClass("com.com.classloader.Sample");
Object object = clazz.newInstance();
}
}
<file_sep>/src/com/generic/test/Coin.java
package com.generic.test;
/**
* Created by xiaoyx5 on 2015/12/30.
*/
public enum Coin {
penny("hello"),mickel("world"),dime("wolcome"),quater("hello world");
private String value;
public String getValue(){
return value;
}
Coin(String value){
this.value = value;
}
public static void main(String[] args){
Coin coin = Coin.quater;
System.out.println(Coin.quater);
}
}
<file_sep>/src/com/com/classloader/Test2.java
package com.com.classloader;
/**
* Created by xiaoyx5 on 2016/3/2.
*/
class FinalTest{
public static final int x = 6/3;
static{
System.out.println("FinalTest static block");
}
}
public class Test2 {
public static void main(String[] args) {
System.out.println(FinalTest.x);
}
}
<file_sep>/src/com/com/study/DynamicProxy/RealSubject.java
package com.com.study.DynamicProxy;
/**
* Created by xiaoyx5 on 2016/1/31.
*/
public class RealSubject implements Subject {
@Override
public void request() {
System.out.println("From real subject!");
}
}
<file_sep>/src/com/std/io/ioTest8.java
package com.std.io;
import java.io.*;
/**
* Created by xiaoyx5 on 2016/2/3.
*/
public class ioTest8 {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("D:/abc/xyz/hello/abc.txt");
InputStream in = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStreamReader);
try {
String line = null;
int i = 0;
while((line = br.readLine()) != null){
if(0 !=i && i%100 == 0){
System.out.println("################################");
br.mark((int)file.length());
File file2 = new File("D:/abc/xyz/hello/abc2.txt");
file2.createNewFile();
FileWriter fileWriter = new FileWriter(file2.getAbsoluteFile(), true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.append("--------------------------------"+"\r\n");
bufferedWriter.flush();
bufferedWriter.close();
System.out.println("################################2");
}
System.out.println(line);
i++;
}
}catch (IOException e){
}
}
}
<file_sep>/src/com/classInfo/BoundedClassReferences.java
package com.classInfo;
/**
* Created by xiaoyx5 on 2016/4/3.
*/
public class BoundedClassReferences {
public static void main(String[] args) {
Class<? extends Number> bounded = int.class;
bounded = double.class;
bounded = Number.class;
Number i = 3;
System.out.println(i); //test
}
}
<file_sep>/src/com/generic/test/EnumMapDemo.java
package com.generic.test;
import java.util.EnumMap;
import java.util.Map;
/**
* Created by xiaoyx5 on 2015/12/30.
*/
public class EnumMapDemo {
public static void main(String[] args){
Map<Action,String> map = new EnumMap<Action,String>(Action.class);
map.put(Action.TURN_LEFT,"向左转");
map.put(Action.TURN_RIGHT,"向右转");
map.put(Action.SHOOT,"射击");
for(Action action : Action.values()){
System.out.println(map.get(action));
}
}
}
enum Action{
TURN_LEFT, TURN_RIGHT,SHOOT;
}
<file_sep>/src/com/jvm/testHandlePromotion.java
package com.jvm;
/**
* Created by xiaoyx5 on 2016/3/20.
*/
public class testHandlePromotion {
private static final int _1MB = 1024 * 1024;
/**
* VM参数: -verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:SurvivorRatio=8 -XX:-HandlePromotionFailure=true
*
* 参数解释:-Xms20M //堆初始化内存20M
* -Xmx20M //堆最大内存20M
* -Xmn10M //新生代内存大小
* -XX:+PrintGCDetails //打印GC详细信息
* -XX:SurvivorRatio=8 //新生代内存区Eden:Suvivor1:Suvivor2内存比例8:1:1 上面新生代内存大小是10M,这个比例分配下来,Eden 8M,Survivor1 1M,Survivor2 1M
* 堆内存总大小20M,新生代分配了10M,剩余10M分配给老年代
* -XX:HandlePromotionFailure //是否允许担保失败
*
* */
public static void testHandlePromotion(){
byte[] allocation1, allocation2, allocation3, allocation4, allocation5, allocation6, allocation7;
allocation1 = new byte[2* _1MB];
allocation2 = new byte[2* _1MB];
allocation3 = new byte[2* _1MB];
allocation1 = null;
allocation4 = new byte[2* _1MB];
allocation5 = new byte[2* _1MB];
allocation6 = new byte[2* _1MB];
allocation4 = null;
allocation5 = null;
allocation6 = null;
allocation7 = new byte[2* _1MB];
}
public static void main(String[] args) {
testHandlePromotion();
}
}
<file_sep>/src/com/std/io/ioTest4.java
package com.std.io;
import java.io.File;
/**
* Created by xiaoyx5 on 2016/2/2.
*/
public class ioTest4 {
public static void main(String[] args) {
File file = new File("D:/OCP11g");
/*String[] names = file.list();
for(String str: names){
System.out.println(str);
}*/
File[] files = file.listFiles();
for(File f : files){
System.out.println(f.getParent());
}
}
}
<file_sep>/src/com/generic/test/StaticImportTest.java
package com.generic.test;
import static com.std.common.Common.output;
import static com.std.common.Common.AGE;
/**
* Created by xiaoyx5 on 2015/12/30.
*/
public class StaticImportTest {
public static void main(String[] args){
int a = AGE;
System.out.println(a);
output();
}
}
<file_sep>/src/com/Collection/PetsList.java
package com.Collection;
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by xiaoyx5 on 2016/4/7.
*/
public class PetsList {
public Collection getPetList(int numOfPet){
ArrayList<Pets> pet = new ArrayList<Pets>();
pet.add(new Pets("pig"));
pet.add(new Pets("monkey"));
pet.add(new Pets("chicken"));
pet.add(new Pets("bird"));
pet.add(new Pets("dog"));
if(pet.size() < numOfPet){
return null;
}else {
return pet.subList(0,numOfPet-1);
}
}
}
<file_sep>/src/com/jvm/PretenureSizeThresholdTest.java
package com.jvm;
/**
* Created by xiaoyx5 on 2016/3/20.
*/
public class PretenureSizeThresholdTest {
private static final int _1MB = 1024 * 1024;
/**
* VM参数: -verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:SurvivorRatio=8 -XX:PretenureSizeThreshold=3145728
* -XX:PretenureSizeThreshold=3145728
* 参数解释:-Xms20M //堆初始化内存20M
* -Xmx20M //堆最大内存20M
* -Xmn10M //新生代内存大小
* -XX:+PrintGCDetails //打印GC详细信息
* -XX:SurvivorRatio=8 //新生代内存区Eden:Suvivor1:Suvivor2内存比例8:1:1 上面新生代内存大小是10M,这个比例分配下来,Eden 8M,Survivor1 1M,Survivor2 1M
* 堆内存总大小20M,新生代分配了10M,剩余10M分配给老年代
* -XX:PretenureSizeThreshold=3145728 大于3M的对象直接放入老年代内存区,这里不能直接写*M
* */
public static void testPretureSizeThreshold(){
byte[] allocation;
allocation = new byte[4 * _1MB]; //直接分配在老年代中
}
public static void main(String[] args) {
PretenureSizeThresholdTest.testPretureSizeThreshold();
}
}
<file_sep>/src/com/reflect/Null.java
package com.reflect;
/**
* Created by xiaoyx5 on 2016/4/4.
*/
public interface Null {
}
|
c1f12dd2d4e850990798b2ebe57914afc439865d
|
[
"Java",
"Kotlin"
] | 37
|
Java
|
dbaxyx/think
|
4ffc589e54c916e0a5d4b9859cf7750cd01970c4
|
df31ebba4a4610ce2d515ecc362391d236f2fc7e
|
refs/heads/main
|
<file_sep>// index.js
var sum,rand;
function createRand(){
rand=[];
for(var i=0;i<7;i++){
var r=0;
while(r==0){
r=parseInt(Math.random()*32);
}
r=(r/Math.pow(10,2)).toFixed(2).substr(2)
rand[i]=r;
for(var j=0;j<i;j++){
if(rand[j]==r){
i=i-1;
}
}
console.log(rand[i]);
}
};
Page({
data:{
imgSrc:'/tupian/039063499214cbc7ce82126e2538212d (3).jpeg'},
onLoad:function(){
createRand();
this.setData({
rand:rand,
sum:rand
})
},
newRand:function(){
createRand();
this.setData({
rand:rand,
sum:rand
})
}
})
|
db247f3e12374774432531e7a0d7467ed5d52fe9
|
[
"JavaScript"
] | 1
|
JavaScript
|
wang1min/1
|
0c5b64e7400560a06983a3a17f2cacafe97e9a2b
|
99abc93d59dda8d838741c113dfb3e7060966e6e
|
refs/heads/main
|
<file_sep># Lists in python
x = [10, 20, 30, 40, 50, 60]
print(x)
print(x[2])
# tuples in python..this is similar to lists in python
y = (1, 2, 3, 4, 5, 5)
print(y)
print(y[0])
# count the number of 5s in the tuple
print("num of 5s : " + str(y.count(5)))
# get the length of the tuple
print("Length of the tuple is " + str(len(y)))
# Concate 2 tuples
a = (4, "max", 4, 8)
b = y + a
print(b)
# print maximum value
print("Max value of y is: " + str(max(y)))
c = ("hello", ) * 5
print(c)<file_sep># x = int(input("Enter num1:"))
# y = int(input("Enter num2:"))
# z = int(input("Enter num3:"))
#
# print("Max value is: ", max(x, y, z))
x = 99
if x == 100:
print("True")
else:
print("False")<file_sep># set in python
# cannot have duplicate values in a set.print only the unique values
x = {1, 4, 5, 6, 7, 8, 4, 7}
print(x)
print(len(x))
|
76fe82f5036941ba784910df1489ea43a910d7d9
|
[
"Python"
] | 3
|
Python
|
gayathribuddhika/python_tutorial
|
32f1c46d6a3a72c74e511f7da76a51e0d2f323b2
|
756775497089a3bfb19249f2110cae5f10295cf8
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
public enum Ingredients {
MagicalMushroom,
Bone,
BatEye,
FenixFeather
}
public enum PowerUps {
None,
Speed,
ManaRegen,
Tenacity,
SpellPower
}
public struct Recipe {
public string name;
Tuple<Ingredients,int>[] ingredients;
int reward;
PowerUps powerUp;
public Recipe(
string name,
Tuple<Ingredients,int>[] ingredients,
int reward,
PowerUps powerUp = PowerUps.None
) {
this.name = name;
this.ingredients = ingredients;
this.reward = reward;
this.powerUp = powerUp;
}
}
public class RecipeManager : MonoBehaviour {
public List<Recipe> recipes;
public GameObject RecipeContainer;
public GameObject RecipePrefab;
private int test = 0;
// Use this for initialization
void Start () {
recipes = new List<Recipe> ();
Tuple<Ingredients,int>[] ingredients = new Tuple<Ingredients,int>[2];
ingredients[0] = Tuple.Create<Ingredients, int>(Ingredients.FenixFeather, 2);
ingredients [1] = Tuple.Create<Ingredients, int> (Ingredients.Bone, 1);
Recipe test = new Recipe (
"Resurrection Potion",
ingredients,
100);
recipes.Add (test);
}
// Update is called once per frame
void Update () {
if (0 == test) {
test = 1;
GameObject card = GameObject.Instantiate (RecipePrefab);
card.transform.SetParent (RecipeContainer.transform);
card.GetComponent<RecipeCard> ().NameLabel.text = recipes [0].name;
}
}
}
|
84b6db8173381b8d75ed530c1bdfed324a2271a0
|
[
"C#"
] | 1
|
C#
|
Cadajo/GGJ-Test
|
e43354c2c9484d0fd7e481cc088779d145455e9a
|
1d77dc83d3e770dc33699fefe5aea9f6255e3405
|
refs/heads/master
|
<file_sep>import React from 'react';
import styled from '@emotion/styled';
import { Global, css } from '@emotion/core';
import Heading from './components/heading';
import Subheading from './components/subheading';
import FavouriteDimsum from './components/favourite-dim-sum';
import DimSumImage from './assets/images/dim-sum.jpg';
import Select from './components/select';
import reset from './reset';
import vars from './theme';
const Wrapper = styled.div`
max-width: 1000px;
margin: 0 auto;
`;
const Grid = styled.div`
display: flex;
flex-direction: column;
padding: 16px;
@media only screen and (min-width: 767px) {
flex-direction: row;
padding: 32px;
}
`;
const Column = styled.div`
width: 100%;
@media only screen and (min-width: 767px) {
width: 50%;
}
`;
const App = () => (
<React.Fragment>
<Global styles={reset()} />
<Wrapper>
<Heading>Dim sum</Heading>
<Grid>
<Column>
<p
css={css`
margin-top: 0;
`}
>
<span
css={css`
color: ${vars.brand};
`}
>
Dim sum
</span>
{` `}literally translates to “touch” and “heart”, or can be
translated simply as “heart’s delight”.
</p>
<p
css={css`
margin-bottom: 0;
`}
>
It is a style of Chinese cuisine (particularly Cantonese but also
other varieties) prepared as small bite-sized portions of food
served in small steamer baskets or on small plate.
</p>
</Column>
<Column>
<div
css={css`
padding-top: 16px;
@media (min-width: 786px) {
padding-top: 0;
padding-left: 32px;
}
`}
>
<img
css={css`
max-width: 100%;
`}
src={DimSumImage}
alt="delicious dim sum"
/>
</div>
</Column>
</Grid>
<Subheading>Select your favorite dim sum dishes</Subheading>
<FavouriteDimsum />
</Wrapper>
</React.Fragment>
);
export default App;
<file_sep>import styled from '@emotion/styled';
import vars from '../theme';
export default styled.h1`
color: ${vars.brand};
text-align: center;
font-size: 3rem;
`;
<file_sep>import React, { useState } from 'react';
import { css } from '@emotion/core';
import Select from './select';
import vars from '../theme';
const FavouriteDimSum = props => {
const [value, setValue] = useState({});
return (
<div
css={css`
padding: 16px 0;
max-width: 600px;
margin: 0 auto;
`}
>
<div
css={css`
display: flex;
padding-bottom: 16px;
align-items: flex-start;
`}
>
<p
css={css`
margin: 0;
`}
>
Favourite dim sum
</p>
<span
css={css`
line-height: 0.7rem;
font-size: 0.7rem;
`}
>
*
</span>
<p
css={css`
margin: 0;
`}
>
: {value.value}
</p>
</div>
<Select
value={value}
onChange={newValue => {
setValue(newValue);
}}
/>
<p
css={css`
margin-top: 1rem;
font-size: 0.3rem;
`}
>
This is the correct spelling of favourite
</p>
</div>
);
};
export default FavouriteDimSum;
<file_sep>## @percy/puppeteer bug
I made this repository to show a bug I have found using the @percy/puppeteer SDK along with [emotion](https://github.com/emotion-js/emotion) and webpack. When I build this app using webpack in mode "production", and then take a percy snapshot of that, the styles are missing in the percy snapshot. However, the styles are _not_ missing in the browser, and can even be seen in a regular screenshot taking by Puppeteer, and they are viewable in the browser.

(Screenshot of webpack production build taken by puppeteer)
### The app
- Very basic React app.
- Built by webpack with basic config
- One component (App.js)
- One test (App.spec.js) that takes one percy snapshot
- Uses jest-puppeteer and puppeteer
### To run the App
```bash
# set your percy token (export PERCY_TOKEN=abc)
# install deps
yarn
# build app in production mode
yarn build
# serve node server
yarn serve
```
### To recreate the bug
Clone this repository
```bash
# set your percy token (export PERCY_TOKEN=abc)
# install deps
yarn
# build app in production mode
yarn build
yarn percy
```
Will result in percy snapshot looking like:

(Screenshot of webpack production build taken by percy)
### Bug fix (by using mode "development" in webpack)
```bash
yarn build:development
yarn percy
```
Results in percy output like this
Will result in percy snapshot looking like:

(Screenshot of webpack development build taken by percy)
<file_sep>const vars = {
headingFont: 'Helvetica, Arial, sans-serif',
baseFont: 'Verdana, Times, Times New Roman, serif',
baseFontSize: '18px',
light: '#cbc5b1',
lightAccent: '#CB9DC0',
dark: '#422317',
brand: '#8A262A',
darkAccent: '#A55F5F',
};
export default vars;
<file_sep>import { css } from '@emotion/core';
import vars from './theme';
const reset = () => css`
body {
background: ${vars.light};
font-size: ${vars.baseFontSize};
color: ${vars.dark};
font-family: ${vars.baseFont};
}
body,
html {
margin: 0;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: ${vars.headingFont};
}
`;
export default reset;
<file_sep>module.exports = {
preset: "jest-puppeteer",
testRegex: "./*\\.spec\\.js$",
transform: {
"^.+\\.js$": "babel-jest"
},
globals: {
HOST: "http://localhost:3001"
}
};
<file_sep>const percy = require('@percy/puppeteer');
describe('App - testing percy with emotion', () => {
beforeAll(async () => {
await page.goto('http://localhost:3001');
});
it('Default', async () => {
await expect(page).toMatch('Dim sum');
await percy.percySnapshot(page, 'Dim sum app');
});
describe('when selecting dim sum', () => {
it('Opening select box', async () => {
await page.click('#select-input');
await expect(page).toMatch('Coconut buns');
await percy.percySnapshot(page, 'Dim sum app - select open');
await page.click('#react-select-2-option-0');
await percy.percySnapshot(page, 'Dim sum app - after select');
});
});
});
|
bd0d02921b97c0f8e51dbce44606a34b0ddafc8a
|
[
"JavaScript",
"Markdown"
] | 8
|
JavaScript
|
montezume/percy-puppeteer-emotion
|
dfa2e483ca58570484b152fc87b8d95944acb8e5
|
926e13fd8233494e888d61fcb613e631826a1896
|
refs/heads/master
|
<file_sep>package CabInvoiceCalculator;
import CabInvoiceCalculator.Ride.TYPE;
public class InvoiceService {
private static final int COST_PER_TIME = 1;
private static final int COST_PER_TIME_PREMIUM = 2;
private static final double MINIMUM_FARE = 5;
private static final double MINIMUM_FARE_PREMIUM = 20;
private static final double MINIMUM_COST_PER_KILOMETER = 10;
private static final double MINIMUM_COST_PER_KILOMETER_PREMIUM = 15;
private RideRepository rideRepository = new RideRepository();
public double calculateFare(double distance, int time) {
double totalFare = distance * MINIMUM_COST_PER_KILOMETER + time * COST_PER_TIME;
return Math.max(MINIMUM_FARE, totalFare);
}
public double calculateFareForPremium(double distance, int time) {
double totalFare = distance * MINIMUM_COST_PER_KILOMETER_PREMIUM + time * COST_PER_TIME_PREMIUM;
return Math.max(MINIMUM_FARE_PREMIUM, totalFare);
}
public double calculateFare(Ride[] rides) {
double totalFare = 0;
for (Ride ride : rides) {
totalFare += (ride.type == TYPE.REGULAR) ? calculateFare(ride.distance, ride.time)
: calculateFareForPremium(ride.distance, ride.time);
}
return totalFare;
}
public InvoiceSummary calculateFareInvoiceSummary(Ride[] rides) {
return new InvoiceSummary(calculateFare(rides), rides.length);
}
public void addRides(String userId, Ride[] rides) {
rideRepository.addRides(userId, rides);
}
public InvoiceSummary getInvoiceFromUserId(String userId) {
return (this.rideRepository.getRidesData(userId) == null) ? null
: this.calculateFareInvoiceSummary(this.rideRepository.getRidesData(userId));
}
}
|
90ef4d9139620376943f4fdf2a95a5fc640647e2
|
[
"Java"
] | 1
|
Java
|
VCHINIMI/CabInvoiceGenerator
|
5ab0f2be01da29263d2ebf19fd1a4db132aa9e85
|
b403b33415c11137cd79dd800c85fb8444370c0a
|
refs/heads/master
|
<file_sep>#pragma once
#include "GameState.h"
#include "Cube.h"
class GameState_Test :
public GameState
{
public:
GameState_Test();
virtual ~GameState_Test();
virtual void Update(double tickTime) override;
virtual void Draw(HDC targetDC) override;
virtual void OnEnterState() override;
virtual void OnLeaveState() override;
private:
Cube* myCube = nullptr;
};
<file_sep>#include "stdafx.h"
#include <stdio.h>
#include "Cube.h"
Cube::Cube()
{
}
Cube::~Cube()
{
}
void Cube::Initialize()
{
vertex[0] = Vector3D(-1, -1, -1);
vertex[1] = Vector3D(-1, 1, -1);
vertex[2] = Vector3D(1, 1, -1);
vertex[3] = Vector3D(1, -1, -1);
vertex[4] = Vector3D(-1, -1, 1);
vertex[5] = Vector3D(-1, 1, 1);
vertex[6] = Vector3D(1, 1, 1);
vertex[7] = Vector3D(1, -1, 1);
triangles[0] = Triangle(0, 1, 2);
triangles[1] = Triangle(0, 2, 3);
triangles[2] = Triangle(4, 6, 5);
triangles[3] = Triangle(4, 7, 6);
triangles[4] = Triangle(4, 5, 1);
triangles[5] = Triangle(4, 1, 0);
triangles[6] = Triangle(3, 2, 6);
triangles[7] = Triangle(3, 6, 7);
triangles[8] = Triangle(1, 5, 6);
triangles[9] = Triangle(1, 6, 2);
triangles[10] = Triangle(4, 0, 3);
triangles[11] = Triangle(4, 3, 7);
}
void Cube::Render(HDC targetDC,
const Matrix& view,
const Matrix& projection,
const Matrix& viewport)
{
Matrix viewProj = view * projection;
for (int i = 0; i < TRIANGLE_COUNT; ++i)
{
Vector3D v1 =
vertex[triangles[i].vertexIndex[0]];//already normalized in view matrix
Vector3D v2 =
vertex[triangles[i].vertexIndex[1]];
Vector3D v3 =
vertex[triangles[i].vertexIndex[2]];
v1 = viewProj * v1;
v2 = viewProj * v2;
v3 = viewProj * v3;
Vector3D normal = (v2 - v1).Cross(v3 - v1);
Vector3D lookAtDirection = g_GameManager.getLookAt() - g_GameManager.getEye();
lookAtDirection.Normalize();
float cos = normal.Dot(lookAtDirection);
if (cos > 0)
{
continue;
}
v1 = viewport * v1;
v2 = viewport * v2;
v3 = viewport * v3;
MoveToEx(targetDC, (int)v1.x, (int)v1.y, nullptr);
LineTo(targetDC, (int)v2.x, (int)v2.y);
LineTo(targetDC, (int)v3.x, (int)v3.y);
LineTo(targetDC, (int)v1.x, (int)v1.y);
}
}<file_sep>#pragma once
#include <Windows.h>
#include "Vector3D.h"
#include "Matrix.h"
struct Triangle
{
Triangle()
{
vertexIndex[0] = -1;
vertexIndex[1] = -1;
vertexIndex[2] = -1;
}
Triangle(int index1, int index2, int index3)
{
vertexIndex[0] = index1;
vertexIndex[1] = index2;
vertexIndex[2] = index3;
}
int vertexIndex[3];
};
class Cube
{
public:
Cube();
~Cube();
void Initialize();
void Render(
HDC targetDC,
const Matrix& view,
const Matrix& projection,
const Matrix& viewport );
protected:
float rotationAxisX = 0.0f;
float rotationAxisY = 0.0f;
static const int VERTEX_COUNT = 8;
static const int TRIANGLE_COUNT = 12;
Vector3D vertex[VERTEX_COUNT];
Triangle triangles[TRIANGLE_COUNT];
};
<file_sep>#include "stdafx.h"
#include "GameState_Test.h"
GameState_Test::GameState_Test()
{
}
GameState_Test::~GameState_Test()
{
}
void GameState_Test::Update(double tickTime)
{
}
void GameState_Test::Draw(HDC targetDC)
{
if (myCube != nullptr)
{
myCube->Render(
targetDC,
g_GameManager.GetViewMatrix(),
g_GameManager.GetProjectionMatrix(),
g_GameManager.GetViewPortMatrix()
);
}
}
void GameState_Test::OnEnterState()
{
if (myCube != nullptr)
{
delete myCube;
myCube = nullptr;
}
myCube = new Cube();
myCube->Initialize();
}
void GameState_Test::OnLeaveState()
{
if (myCube != nullptr)
{
delete myCube;
myCube = nullptr;
}
}
|
cac0f18ee7ecf2fb9c5c1f7448fb659c63fd78b7
|
[
"C++"
] | 4
|
C++
|
SGA160108305C/20160204_1_Back_Face_Culling
|
c9a56735b301876df0ca84b2bcac038e565fac5d
|
5b137b264abc8c4066c53dcb5cbde9f4e941a040
|
refs/heads/master
|
<repo_name>DanyT011/TallerMaterial_motos<file_sep>/app/src/main/java/com/example/tallermaterial_motos/Moto.java
package com.example.tallermaterial_motos;
public class Moto {
private String modelo, marca, placas, id;
public Moto(String modelo, String marca, String placas, String id) {
this.modelo = modelo;
this.marca = marca;
this.placas = placas;
this.id = id;
}
public Moto(){}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getPlacas() {
return placas;
}
public void setPlacas(String placas) {
this.placas = placas;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void guardar(){
Datos.guardar(this);
}
public void eliminar(){
Datos.eliminar(this);
}
}
<file_sep>/app/src/main/java/com/example/tallermaterial_motos/Datos.java
package com.example.tallermaterial_motos;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.util.ArrayList;
public class Datos {
private static String db = "Motos";
private static DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
private static StorageReference storageReference = FirebaseStorage.getInstance().getReference();
private static ArrayList<Moto> motos = new ArrayList();
public static String getId(){
return databaseReference.push().getKey();
}
public static void guardar(Moto m){
databaseReference.child(db).child(m.getId()).setValue(m);
}
public static void setMotos(ArrayList<Moto> motos){motos = motos;}
public static void eliminar(Moto m){
databaseReference.child(db).child(m.getId()).setValue(m);
storageReference.child(m.getId()).delete();
}
}
|
35e2994cce458864159beec9bb5b24f53434e0e1
|
[
"Java"
] | 2
|
Java
|
DanyT011/TallerMaterial_motos
|
cc1d92247192b682b3a482182204086858f86690
|
81e137afd1f89194cfaf98bf3aff05440cfd20d9
|
refs/heads/main
|
<repo_name>klercke/LaTeXBot<file_sep>/latexbot.py
"""
Author: <NAME>
File: latexbot.py
Purpose: Discord bot to typeset math
"""
#####################################
#
import os #
import discord #
from dotenv import load_dotenv #
from discord.ext import commands #
from discord.ext import tasks #
import logging #
import time #
from sympy import preview #
#
#####################################
#################################
#
ACTIVITY = discord.Game("tex!") #
LOG_LEVEL = logging.INFO #
COMMAND_PREFIX = 'tex!' #
VERSION = "v0.0.1-alpha" #
#
#################################
# Initialize bot object to use the COMMAND_PREFIX defined above
bot = commands.Bot(command_prefix=COMMAND_PREFIX)
@bot.event
async def on_connect():
"""
Prints a message with bot name and version when bot connects to Discord servers.
Sets the bot activity to ACTIVITY.
"""
logging.warning(f'{bot.user.name} {VERSION} has successfully connected to Discord.')
await bot.change_presence(activity = ACTIVITY)
@bot.event
async def on_ready():
"""
Prints a list of guilds the bot is connected to when the bot is finished processing
date from Discord servers.
"""
logging.info('Bot loading complete. Current guilds: ')
for guild in bot.guilds:
label = guild.name + " (" + str(guild.id) + ")"
logging.info(label)
@bot.event
async def on_disconnect():
"""
Prints a message when bot disconnects from Discord. Usually this is temporary.
"""
logging.warning('Lost connection to Discord.')
@bot.event
async def on_guild_join(guild):
"""
Logs a message when bot joins a new guild and adds all users from that guild to the database.
"""
logging.warning(f"Joined new guild: {guild.name + ' (' + str(guild.id) + ')'}")
@bot.event
async def on_error(event, *args, **kwargs):
"""
Writes to err.log whenever a message triggers an error
"""
if event == 'on_message':
logging.error(f'Unhandled message: {args[0]}')
else:
logging.exception(event)
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if not message.content:
return
await bot.process_commands(message)
@bot.command(name="c", help="Takes the first code block and interprets it as LaTeX code, responding with a png of the output")
async def compile(ctx):
if not os.path.isdir('tmp'):
logging.info("tmp/ not found, making it now")
os.mkdir('tmp')
if not "```" in ctx.message.content:
return
tmp = ctx.message.content[ctx.message.content.find('`') + 3:]
if not "```" in tmp:
return
user_input = ctx.message.content
user_input = user_input[user_input.find('`') + 3:]
user_input = user_input[:user_input.find('`')]
with ctx.channel.typing():
filename = 'tmp/' + time.strftime('%Y%m%d-%H%M%S') + '.png'
preview(user_input, viewer='file', filename=filename, euler=False)
await ctx.message.channel.send(file = discord.File(filename), reference = ctx.message)
return
def main():
# Load bot token from .env
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
# Generate timestamp of startup
timestamp = time.strftime('%Y%m%d-%H%M%S')
# Configure logging
logging.basicConfig(
level = LOG_LEVEL,
format = '%(asctime)s: [%(levelname)s] - %(message)s',
datefmt = '%Y-%m-%d %H:%M:%S',
handlers = [
logging.FileHandler(f"logs/{timestamp}.log", mode = "w"),
logging.StreamHandler()
]
)
bot.run(TOKEN)
if __name__ == "__main__":
main()
|
5c45c50725f6c160e92e74a0a4a02f464d406175
|
[
"Python"
] | 1
|
Python
|
klercke/LaTeXBot
|
33be869910e763ca02c88a8a37fceb2d45c97889
|
a0689be277f38e1f0403c49637e92aa5295a06e0
|
refs/heads/master
|
<repo_name>Darth98/webinar<file_sep>/AulaColecoe/src/webinar/model/Formacao.java
package webinar.model;
public enum Formacao {
GRADUADO, MESTRADO, DOUTORADO, ESPECIALISTA, JEDI;
}
<file_sep>/AulaColecoe/src/webinar/model/InscricaoSeminario.java
package webinar.model;
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 InscricaoSeminario {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne
@JoinColumn(name = "aluno_id")
private Aluno aluno;
@ManyToOne
@JoinColumn(name = "seminario_id")
private Seminario seminario;
private String datainscricao;
public InscricaoSeminario() {
}
public InscricaoSeminario(Aluno aluno, Seminario seminario) {
this.aluno = aluno;
this.seminario = seminario;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public Seminario getSeminario() {
return seminario;
}
public void setSeminario(Seminario seminario) {
this.seminario = seminario;
}
public String getDatainscricao() {
return datainscricao;
}
public void setDatainscricao(String datainscricao) {
this.datainscricao = datainscricao;
}
}<file_sep>/AulaColecoe/src/webinar/model/Aluno.java
package webinar.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
@Entity
public class Aluno {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String matricula;
private String nome;
@OneToOne(cascade = CascadeType.ALL)
private Endereco endereco;
private String email;
@OneToMany(mappedBy = "seminario")
Set<InscricaoSeminario> inscricoes = new HashSet<InscricaoSeminario>();
public Set<InscricaoSeminario> getInscricoes() {
return inscricoes;
}
public void setInscricoes(Set<InscricaoSeminario> inscricoes) {
this.inscricoes = inscricoes;
}
public Aluno() {
}
public Aluno(String matricula, String nome, Endereco endereco, String email) {
this.matricula = matricula;
this.nome = nome;
this.endereco = endereco;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMatricula() {
return matricula;
}
public void setMatricula(String matricula) {
this.matricula = matricula;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Endereco getEndereco() {
return endereco;
}
public void setEndereco(Endereco endereco) {
this.endereco = endereco;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
<file_sep>/AulaColecoe/src/webinar/model/Instrutor.java
package webinar.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
@Entity
public class Instrutor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String nome;
@OneToOne(cascade = CascadeType.ALL)
private Endereco endereco;
private String email;
private double salario;
@Enumerated(EnumType.STRING)
private Formacao formacao;
public Instrutor() {
}
public Instrutor(String nome, Endereco endereco, String email, double salario, Formacao formacao) {
this.nome = nome;
this.endereco = endereco;
this.email = email;
this.salario = salario;
this.formacao = formacao;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Endereco getEndereco() {
return endereco;
}
public void setEndereco(Endereco endereco) {
this.endereco = endereco;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public double getSalario() {
return salario;
}
public void setSalario(double salario) {
this.salario = salario;
}
public Formacao getFormacao() {
return formacao;
}
public void setFormacao(Formacao formacao) {
this.formacao = formacao;
}
}
|
4971c239090c2a476798dacfebede282aaae8113
|
[
"Java"
] | 4
|
Java
|
Darth98/webinar
|
188e4c46b9fbf12ac638216759791f8fd3ad4224
|
cd6df22c39a8e5115ad4e4bbc5434bf9f68cfe21
|
refs/heads/master
|
<file_sep>package hzb.cdut.com.mycoordinatorlayoutdemo.behavior;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorListenerAdapter;
import android.support.v4.view.WindowInsetsCompat;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by zhongkun on 2016/11/22.
*/
public class ScrollToHideFooterBehavior extends CoordinatorLayout.Behavior {
private int mDySinceDirectionChange;
private boolean mIsHidden = false;
public ScrollToHideFooterBehavior() {
}
public ScrollToHideFooterBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) {
return (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
}
@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed) {
//不再需要滑动隐藏
// if (dy > 0 && mDySinceDirectionChange < 0
// || dy < 0 && mDySinceDirectionChange > 0) {
// mDySinceDirectionChange = 0;
// }
//
// Log.e("Behavior", "onNestedPreScroll: " + mDySinceDirectionChange);
// mDySinceDirectionChange += dy;
//
// if (mDySinceDirectionChange > child.getHeight()
// && !mIsHidden) {
// hide(child);
// } else if (mDySinceDirectionChange < 0
// && mIsHidden) {
// show(child);
// }
// Log.e("Behavior", "onNestedPreScroll: " + dy + ", " + mDySinceDirectionChange + ", " + mIsHidden
// + ", " + child.getHeight());
}
boolean setInitialPaddingTop = false;
int initialPaddingTop;
@NonNull
@Override
public WindowInsetsCompat onApplyWindowInsets(CoordinatorLayout coordinatorLayout, View child, WindowInsetsCompat insets) {
// LogUtil.d(Contant.DEBUG_LOG, "onApplyWindowInsets: " + insets.getSystemWindowInsetBottom()
// + ", " + insets.getSystemWindowInsetLeft()
// + ", " + insets.getSystemWindowInsetRight()
// + ", " + insets.getSystemWindowInsetTop());
// LogUtil.d(Contant.DEBUG_LOG, "onApplyWindowInsets:Stable " + insets.getStableInsetBottom()
// + ", " + insets.getStableInsetLeft()
// + ", " + insets.getStableInsetRight()
// + ", " + insets.getStableInsetTop());
if (!setInitialPaddingTop) {
setInitialPaddingTop = true;
initialPaddingTop = child.getPaddingTop();
}
// LogUtil.d(Contant.DEBUG_LOG, "onApplyWindowInsets: initialPaddingTop" + initialPaddingTop);
WindowInsetsCompat insetsAfterConsume = insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
return insetsAfterConsume;
}
private void show(View child) {
mIsHidden = false;
ViewCompat.animate(child)
.alpha(1)
.translationY(0)
.setDuration(200)
.setListener(new ViewPropertyAnimatorListenerAdapter() {
@Override
public void onAnimationStart(View view) {
view.setVisibility(View.VISIBLE);
}
})
.start();
}
private void hide(View child) {
mIsHidden = true;
ViewCompat.animate(child)
.cancel();
ViewCompat.animate(child)
.alpha(0)
.translationY(child.getHeight())
.setDuration(200)
.setListener(new ViewPropertyAnimatorListenerAdapter() {
@Override
public void onAnimationEnd(View view) {
view.setVisibility(View.GONE);
}
})
.start();
}
}
|
b0461b4b09f363b4b7df5db835acf1ecbf283333
|
[
"Java"
] | 1
|
Java
|
hzbcdut/MyCoordinatorLayoutDemo
|
dfb4cf6f12653f832a2a11f29a40bc9fda8a7c10
|
e17e5c68227a2a1858fc3367edf64994e1249352
|
refs/heads/main
|
<repo_name>jeroen-vankelecom/ansible-desktop<file_sep>/scripts/setup_inventory_and_group_vars.sh
#!/usr/bin/env bash
set -e
GROUP_VARS_FILE="group_vars/$(hostname)"
# If file doesn't exist, prevents appending to existing file
if [ ! -f "$GROUP_VARS_FILE" ]; then
mkdir -p "$GROUP_VARS_FILE"
# -e tells echo to interpret backslash escapes
echo -e "---\n# You can copy and modify variables over from ../all/*.yml" > "group_vars/$(hostname)/all.yml"
fi
PRIVATE_INVENTORY_FILE=".inventory"
# If file doesn't exist, prevents appending to existing file
if [ ! -f "$PRIVATE_INVENTORY_FILE" ]; then
# -e tells echo to interpret backslash escapes
echo -e "[$(hostname)]\n127.0.0.1 ansible_connection=local" > $PRIVATE_INVENTORY_FILE
fi
|
4aef5fb8a7ab38be48d89554b087b512b364ab5b
|
[
"Shell"
] | 1
|
Shell
|
jeroen-vankelecom/ansible-desktop
|
52819310f2a64bf8acca28aa385286ef8f1cd141
|
9633cdfd41629f801457b2186ee3057cfe92f2f8
|
refs/heads/master
|
<repo_name>Ginga1892/heterogeneous-recommendation<file_sep>/model/seq2seq/seq2seq.py
import torch
import torch.nn as nn
import random
class Seq2Seq(nn.Module):
"""Seq2Seq with alignment model
Configs:
encoder: bidirectional
decoder: 1 layer
alignment: feed-forward with no activation
"""
def __init__(self, encoder, decoder):
super(Seq2Seq, self).__init__()
self.encoder = encoder
self.decoder = decoder
def forward(self, src, trg, tf_rate=0):
batch_size, trg_len = trg.shape
decoder_outputs = torch.zeros(trg_len, batch_size, self.decoder.d)
predictions = torch.zeros(trg_len, batch_size)
encoder_output, s = self.encoder(src)
decoder_input = trg[:, 0]
for i in range(1, trg_len):
decoder_output, s = self.decoder(decoder_input, s, encoder_output)
decoder_outputs[i] = decoder_output
# Top 1 prediction
prediction = decoder_output.argmax(1)
predictions[i] = prediction
decoder_input = trg[i] if random.random() < tf_rate else prediction
return decoder_outputs, predictions
class Attention(nn.Module):
"""Alignment model"""
def __init__(self, hid_size):
super(Attention, self).__init__()
self.align = nn.Sequential(nn.Linear(hid_size * 3, hid_size), nn.Linear(hid_size, 1))
def forward(self, s, h):
src_len = h.shape[1]
# s = [batch_size, src_len, hid_size]
s = s.repeat(1, src_len, 1)
# Alignment model
# e = Attention(s, h)
# a = Softmax(e)
e = self.align(torch.cat((s, h), dim=2))
# a = [batch_size, src_len]
a = torch.softmax(e, dim=1).squeeze(2)
return a
class Encoder(nn.Module):
"""Encoder of the Seq2Seq model"""
def __init__(self, vocab_size, emb_size, hid_size, n_layers=1, dropout=0.9):
super(Encoder, self).__init__()
self.embedding = nn.Embedding(vocab_size, emb_size)
self.rnn = nn.GRU(emb_size, hid_size, n_layers, bidirectional=True, batch_first=True)
self.fc = nn.Linear(hid_size * 2, hid_size)
self.dropout = nn.Dropout(dropout)
def forward(self, src):
# src = [batch_size, src_len]
embedded = self.dropout(self.embedding(src))
encoder_output, hidden = self.rnn(embedded)
# Extract both of the directions to initialize the hidden state of the decoder
# encoder_output = [batch_size, src_len, hid_size * 2]
# hidden = [batch_size, 1, hid_size]
hidden = self.fc(torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1)).unsqueeze(1)
return encoder_output, hidden
class Decoder(nn.Module):
"""Decoder of the Seq2Seq model"""
def __init__(self, vocab_size, emb_size, hid_size, attention, dropout=0.9):
super(Decoder, self).__init__()
self.d = vocab_size
self.attention = attention
self.embedding = nn.Embedding(vocab_size, emb_size)
self.rnn = nn.GRU(hid_size * 2 + emb_size, hid_size, batch_first=True)
self.fc = nn.Linear(hid_size, vocab_size)
self.dropout = nn.Dropout(dropout)
def forward(self, decoder_input, s, h):
# decoder_input = [batch_size, 1]
decoder_input = decoder_input.unsqueeze(1)
embedded = self.dropout(self.embedding(decoder_input))
# a = [batch_size, 1, src_len]
a = self.attention(s, h)
a = a.unsqueeze(1)
# c = sigma_j(a_ij, h_j)
# c = [batch_size, 1, hid_size * 2]
c = torch.bmm(a, h)
# decoder_output = [batch_size, 1, hid_size]
# s = [batch_size, 1, hid_size]
decoder_output, s = self.rnn(torch.cat((embedded, c), dim=2), s.permute(1, 0, 2))
# decoder_output = [batch_size, vocab_size]
decoder_output = self.fc(decoder_output.squeeze(1))
return decoder_output, s.permute(1, 0, 2)
<file_sep>/model/transformer/transformer.py
import torch
import torch.nn as nn
import numpy as np
class Transformer(nn.Module):
"""Transformer
Simplified:
layers: 6
heads: 8
feed-forward networks: 2
"""
def __init__(self, encoder, decoder):
super(Transformer, self).__init__()
self.encoder = encoder
self.decoder = decoder
self.enc = None
self.dec = None
@staticmethod
def get_trg_mask(trg):
trg_len = trg.shape[1]
return torch.tril(torch.ones((trg_len, trg_len))).bool()
def forward(self, src, trg):
self.enc = self.encoder(src)
trg_mask = self.get_trg_mask(trg)
self.dec = self.decoder(trg, self.enc, trg_mask)
return self.dec
class MultiHeadAttention(nn.Module):
"""Multi-Head Attention Layer"""
def __init__(self, hid_size, n_heads):
super(MultiHeadAttention, self).__init__()
self.h = n_heads
self.d_k = hid_size // n_heads
self.w_q = nn.Linear(hid_size, hid_size)
self.w_k = nn.Linear(hid_size, hid_size)
self.w_v = nn.Linear(hid_size, hid_size)
self.w_o = nn.Linear(hid_size, hid_size)
# self.d = torch.sqrt(torch.FloatTensor([hid_size // self.h]))
def forward(self, query, key, value, mask=None):
# q, k, v = [batch_size, src_len, hid_size]
batch_size, hid_size = query.shape[0], query.shape[2]
# q, k, v = [batch_size, src_len, hid_size]
q = self.w_q(query)
k = self.w_k(key)
v = self.w_v(value)
# q, v = [batch_size, src_len, n_heads, head_size]
# k = [batch_size, src_len, head_size, n_heads]
q = q.view(batch_size, -1, self.h, self.d_k).permute(0, 2, 1, 3)
k = k.view(batch_size, -1, self.h, self.d_k).permute(0, 2, 3, 1)
v = v.view(batch_size, -1, self.h, self.d_k).permute(0, 2, 1, 3)
# Attention(Q, K, V) = Softmax(Q * K^T / d) * V
attention_scores = torch.matmul(q, k) / np.sqrt(self.d_k)
if mask is not None:
attention_scores = attention_scores.masked_fill(mask == 0, -1e4)
attention = torch.softmax(attention_scores, dim=-1)
y = torch.matmul(attention, v)
# y = [batch_size, src_len, hid_size]
y = y.permute(0, 2, 1, 3).contiguous().view(batch_size, -1, hid_size)
return self.w_o(y)
class Encoder(nn.Module):
"""Encoder of the Transformer model"""
def __init__(self, input_size, hid_size, dropout=0.9, max_len=100):
super(Encoder, self).__init__()
self.n = 6
self.h = 8
self.d_model = hid_size
self.tok_embedding = nn.Embedding(input_size, hid_size)
self.pos_embedding = nn.Embedding(max_len, hid_size)
self.self_attention = MultiHeadAttention(hid_size, self.h)
self.ffn = nn.Sequential(nn.Linear(hid_size, hid_size * 4), nn.GELU(), nn.Linear(hid_size * 4, hid_size))
self.layer_norm = nn.LayerNorm(hid_size)
self.dropout = nn.Dropout(dropout)
def forward(self, src, src_mask=None):
batch_size, src_len = src.shape
# Token embeddings
te = self.tok_embedding(src) * np.sqrt(self.d_model)
# Positional embeddings
pos = torch.arange(0, src_len).unsqueeze(0).repeat(batch_size, 1)
pe = self.pos_embedding(pos)
src = te + pe
src = self.dropout(src)
# Stacked transformer
# multi-head attention layer
# add & layer normalization
# feed-forward networks
# add & layer normalization
for _ in range(self.n):
attention_output = self.self_attention(src, src, src, src_mask)
attention_output = self.layer_norm(src + self.dropout(attention_output))
encoder_output = self.ffn(attention_output)
encoder_output = self.layer_norm(attention_output + self.dropout(encoder_output))
return encoder_output
class Decoder(nn.Module):
"""Decoder of the Transformer model"""
def __init__(self, output_size, hid_size, dropout=0.9, max_len=100):
super(Decoder, self).__init__()
self.n = 6
self.h = 8
self.d_model = hid_size
self.tok_embedding = nn.Embedding(output_size, hid_size)
self.pos_embedding = nn.Embedding(max_len, hid_size)
self.self_attention = MultiHeadAttention(hid_size, self.h)
self.ffn = nn.Sequential(nn.Linear(hid_size, hid_size * 4), nn.GELU(), nn.Linear(hid_size * 4, hid_size))
self.layer_norm = nn.LayerNorm(hid_size)
self.dropout = nn.Dropout(dropout)
self.fc_out = nn.Linear(hid_size, output_size)
def forward(self, trg, encoder_output, trg_mask, src_mask=None):
batch_size, trg_len = trg.shape
# Token embeddings
te = self.tok_embedding(trg) * np.sqrt(self.d_model)
# Positional embeddings
pos = torch.arange(0, trg_len).unsqueeze(0).repeat(batch_size, 1)
pe = self.pos_embedding(pos)
trg = te + pe
trg = self.dropout(trg)
# Stacked transformer
# multi-head attention layer
# add & layer normalization
# feed-forward networks
# add & layer normalization
# encoder-decoder attention layer
# linear & softmax
for _ in range(self.n):
# Self attention
attention_output = self.self_attention(trg, trg, trg, trg_mask)
attention_output = self.layer_norm(trg + self.dropout(attention_output))
# Encoder-decoder attention
attention_output = self.self_attention(attention_output, encoder_output, encoder_output, src_mask)
attention_output = self.layer_norm(attention_output + self.dropout(attention_output))
decoder_output = self.ffn(attention_output)
decoder_output = self.layer_norm(attention_output + self.dropout(decoder_output))
return torch.softmax(self.fc_out(decoder_output), dim=-1)
<file_sep>/model/bert/pretrain.py
import torch
import torch.nn as nn
from .transformer import EncoderLayer
class BERT(nn.Module):
def __init__(self, input_size, hid_size, n_heads=8, n_layers=12, dropout=0.9, max_len=128):
super(BERT, self).__init__()
self.hid_size = hid_size
self.n_heads = n_heads
self.n_layers = n_layers
self.tok_embedding = nn.Embedding(input_size, hid_size)
self.pos_embedding = nn.Embedding(max_len, hid_size)
self.seg_embedding = nn.Embedding(2, hid_size)
self.encoders = nn.ModuleList([EncoderLayer(hid_size, n_heads, dropout) for _ in range(n_layers)])
self.dropout = nn.Dropout(dropout)
def forward(self, x, segment_ids):
batch_size, max_len = x.shape
mask = (x > 0).unsqueeze(1).repeat(1, max_len, 1).unsqueeze(1)
te = self.tok_embedding(x)
pos = torch.arange(0, max_len).unsqueeze(0).repeat(batch_size, 1)
pe = self.pos_embedding(pos)
se = self.seg_embedding(segment_ids)
x = te + pe + se
x = self.dropout(x)
for encoder in self.encoders:
x = encoder(x, mask)
return x
class PreTrainModel(nn.Module):
def __init__(self, bert):
super(PreTrainModel, self).__init__()
self.mlm = MaskedLanguageModel(bert.vocab_size, bert.hid_size)
self.nsp = NextSentencePrediction(bert.hid_size)
def forward(self, x, segment_ids):
x = self.bert(x, segment_ids)
prediction_scores = self.mlm(x)
next_sentence_scores = self.nsp(x)
return prediction_scores, next_sentence_scores
class NextSentencePrediction(nn.Module):
def __init__(self, hid_size):
super(NextSentencePrediction, self).__init__()
self.fc = nn.Linear(hid_size, 2)
def forward(self, x):
return torch.softmax(self.fc(x[:, 0, :]), dim=-1)
class MaskedLanguageModel(nn.Module):
def __init__(self, output_size, hid_size):
super(MaskedLanguageModel, self).__init__()
self.fc = nn.Linear(hid_size, output_size)
def forward(self, x):
return torch.softmax(self.fc(x), dim=-1)
<file_sep>/model/bert/tf-code.md
# BERT TensorFlow源码
## 预处理
**主函数**
```python
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
# 定义分词
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
# 获取输入文件
input_files = []
for input_pattern in FLAGS.input_file.split(","):
input_files.extend(tf.gfile.Glob(input_pattern))
tf.logging.info("*** Reading from input files ***")
for input_file in input_files:
tf.logging.info(" %s", input_file)
# 生成训练样本
rng = random.Random(FLAGS.random_seed)
instances = create_training_instances(
input_files, tokenizer, FLAGS.max_seq_length, FLAGS.dupe_factor,
FLAGS.short_seq_prob, FLAGS.masked_lm_prob,
FLAGS.max_predictions_per_seq, rng)
# 输出
output_files = FLAGS.output_file.split(",")
tf.logging.info("*** Writing to output files ***")
for output_file in output_files:
tf.logging.info(" %s", output_file)
write_instance_to_example_files(instances, tokenizer, FLAGS.max_seq_length,
FLAGS.max_predictions_per_seq, output_files)
```
**生成训练样本**
```python
def create_training_instances(input_files, tokenizer, max_seq_length,
dupe_factor, short_seq_prob, masked_lm_prob,
max_predictions_per_seq, rng):
all_documents = [[]]
for input_file in input_files:
with tf.gfile.GFile(input_file, "r") as reader:
l = 0
while True:
# 转码
line = tokenization.convert_to_unicode(reader.readline())
if not line:
break
line = line.strip()
# 空行划分documents
if not line:
all_documents.append([])
# 分词
tokens = tokenizer.tokenize(line)
if tokens:
all_documents[-1].append(tokens)
all_documents = [x for x in all_documents if x]
rng.shuffle(all_documents)
# 生成词典
vocab_words = list(tokenizer.vocab.keys())
instances = []
for _ in range(dupe_factor):
for document_index in range(len(all_documents)):
# 原子操作
instances.extend(
create_instances_from_document(all_documents, document_index,
max_seq_length, short_seq_prob, masked_lm_prob,
max_predictions_per_seq, vocab_words, rng))
rng.shuffle(instances)
return instances
```
**document原子操作**
```python
def create_instances_from_document(all_documents, document_index,
max_seq_length, short_seq_prob,
masked_lm_prob, max_predictions_per_seq,
vocab_words, rng):
document = all_documents[document_index]
# 减去[CLS]、[SEP]、[SEP]
max_num_tokens = max_seq_length - 3
target_seq_length = max_num_tokens
# 概率变成短句
if rng.random() < short_seq_prob:
target_seq_length = rng.randint(2, max_num_tokens)
instances = []
current_chunk = []
current_length = 0
i = 0
while i < len(document):
# 逐句添加进chunk
segment = document[i]
current_chunk.append(segment)
# 句子长度
current_length += len(segment)
if i == len(document) - 1 or current_length >= target_seq_length:
if current_chunk:
# 随机选定sentence A的末尾位置
a_end = 1
if len(current_chunk) >= 2:
a_end = rng.randint(1, len(current_chunk) - 1)
tokens_a = []
for j in range(a_end):
tokens_a.extend(current_chunk[j])
tokens_b = []
is_random_next = False
# sentence B不是下一句
if len(current_chunk) == 1 or rng.random() < 0.5:
is_random_next = True
# sentence B最大长度
target_b_length = target_seq_length - len(tokens_a)
# 在不同document中采样
for _ in range(10):
random_document_index = rng.randint(0, len(all_documents) - 1)
if random_document_index != document_index:
break
random_document = all_documents[random_document_index]
random_start = rng.randint(0, len(random_document) - 1)
# 添加sentence B直到最长
for j in range(random_start, len(random_document)):
tokens_b.extend(random_document[j])
if len(tokens_b) >= target_b_length:
break
# 如果B不是A下一句,则A的下一句并未被采样到,放回
num_unused_segments = len(current_chunk) - a_end
i -= num_unused_segments
# sentence B是下一句
else:
is_random_next = False
# 从a_end开始顺序添加
for j in range(a_end, len(current_chunk)):
tokens_b.extend(current_chunk[j])
# 截短
truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng)
tokens = []
segment_ids = []
# 添加占位符和句子信息
tokens.append("[CLS]")
segment_ids.append(0)
for token in tokens_a:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
for token in tokens_b:
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
# 打mask
(tokens, masked_lm_positions, masked_lm_labels) =
create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq,
vocab_words, rng)
instance = TrainingInstance(
tokens=tokens,
segment_ids=segment_ids,
is_random_next=is_random_next,
masked_lm_positions=masked_lm_positions,
masked_lm_labels=masked_lm_labels)
instances.append(instance)
current_chunk = []
current_length = 0
i += 1
return instances
```
**打mask**
```python
def create_masked_lm_predictions(tokens, masked_lm_prob,
max_predictions_per_seq, vocab_words, rng):
cand_indexes = []
for (i, token) in enumerate(tokens):
if token == "[CLS]" or token == "[SEP]":
continue
# wwm
if (FLAGS.do_whole_word_mask and len(cand_indexes) >= 1 and token.startswith("##")):
cand_indexes[-1].append(i)
else:
cand_indexes.append([i])
rng.shuffle(cand_indexes)
output_tokens = list(tokens)
num_to_predict = min(max_predictions_per_seq,
max(1, int(round(len(tokens) * masked_lm_prob))))
masked_lms = []
# mask过的位置
covered_indexes = set()
for index_set in cand_indexes:
if len(masked_lms) >= num_to_predict:
break
# wwm
if len(masked_lms) + len(index_set) > num_to_predict:
continue
# 判断是否重复mask,continue
is_any_index_covered = False
for index in index_set:
if index in covered_indexes:
is_any_index_covered = True
break
if is_any_index_covered:
continue
for index in index_set:
covered_indexes.add(index)
masked_token = None
# 80%用[MASK]替换
if rng.random() < 0.8:
masked_token = "[MASK]"
else:
# 10%不替换
if rng.random() < 0.5:
masked_token = tokens[index]
# 10%随机替换
else:
masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)]
output_tokens[index] = masked_token
# 添加样本
masked_lms.append(MaskedLmInstance(index=index, label=tokens[index]))
masked_lms = sorted(masked_lms, key=lambda x: x.index)
# mask的位置、label
masked_lm_positions = []
masked_lm_labels = []
for p in masked_lms:
masked_lm_positions.append(p.index)
masked_lm_labels.append(p.label)
return (output_tokens, masked_lm_positions, masked_lm_labels)
```
## 预训练
**主函数**
```python
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
if not FLAGS.do_train and not FLAGS.do_eval:
raise ValueError("At least one of `do_train` or `do_eval` must be True.")
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
tf.gfile.MakeDirs(FLAGS.output_dir)
# 获取输入文件
input_files = []
for input_pattern in FLAGS.input_file.split(","):
input_files.extend(tf.gfile.Glob(input_pattern))
tf.logging.info("*** Input Files ***")
for input_file in input_files:
tf.logging.info(" %s" % input_file)
# 配置tpu
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver, master=FLAGS.master,
model_dir=FLAGS.output_dir, save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
# 创建bert,config、checkpoint、lr、steps
model_fn = model_fn_builder(
bert_config=bert_config, init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate, num_train_steps=FLAGS.num_train_steps,
num_warmup_steps=FLAGS.num_warmup_steps, use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
# 定义训练器
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu, model_fn=model_fn, config=run_config,
train_batch_size=FLAGS.train_batch_size, eval_batch_size=FLAGS.eval_batch_size)
# 训练
if FLAGS.do_train:
tf.logging.info("***** Running training *****")
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
# 读取tf输入
train_input_fn = input_fn_builder(
input_files=input_files, max_seq_length=FLAGS.max_seq_length,
max_predictions_per_seq=FLAGS.max_predictions_per_seq, is_training=True)
estimator.train(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps)
# 评估
if FLAGS.do_eval:
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
eval_input_fn = input_fn_builder(
input_files=input_files, max_seq_length=FLAGS.max_seq_length,
max_predictions_per_seq=FLAGS.max_predictions_per_seq, is_training=False)
result = estimator.evaluate(input_fn=eval_input_fn, steps=FLAGS.max_eval_steps)
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with tf.gfile.GFile(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
```
**创建bert**
```python
def model_fn_builder(bert_config, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
def model_fn(features, labels, mode, params):
# 特征信息,输入(ids、mask、句对ids)、mask信息(位置、labels、权重)、nsp信息
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
masked_lm_positions = features["masked_lm_positions"]
masked_lm_ids = features["masked_lm_ids"]
masked_lm_weights = features["masked_lm_weights"]
next_sentence_labels = features["next_sentence_labels"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
# bert model
model = modeling.BertModel(
config=bert_config, is_training=is_training,
input_ids=input_ids, input_mask=input_mask,
token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings
# 损失函数
(masked_lm_loss,
masked_lm_example_loss, masked_lm_log_probs) = get_masked_lm_output(
bert_config, model.get_sequence_output(), model.get_embedding_table(),
masked_lm_positions, masked_lm_ids, masked_lm_weights)
(next_sentence_loss, next_sentence_example_loss,
next_sentence_log_probs) = get_next_sentence_output(
bert_config, model.get_pooled_output(), next_sentence_labels)
total_loss = masked_lm_loss + next_sentence_loss
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
# 载入模型
if init_checkpoint:
(assignment_map,
initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(
tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
output_spec = None
# 训练
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate,
num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, loss=total_loss,
train_op=train_op, scaffold_fn=scaffold_fn)
# 评估
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
masked_lm_weights, next_sentence_example_loss,
next_sentence_log_probs, next_sentence_labels):
# mlm logits
masked_lm_log_probs = tf.reshape(
masked_lm_log_probs,[-1, masked_lm_log_probs.shape[-1]])
# 预测值
masked_lm_predictions = tf.argmax(
masked_lm_log_probs, axis=-1, output_type=tf.int32)
masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
# labels
masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
# 计算准确率
masked_lm_accuracy = tf.metrics.accuracy(
labels=masked_lm_ids,
predictions=masked_lm_predictions,
weights=masked_lm_weights)
# 损失加权平均
masked_lm_mean_loss = tf.metrics.mean(
values=masked_lm_example_loss, weights=masked_lm_weights)
# nsp
next_sentence_log_probs = tf.reshape(
next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
next_sentence_predictions = tf.argmax(
next_sentence_log_probs, axis=-1, output_type=tf.int32)
next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
next_sentence_accuracy = tf.metrics.accuracy(
labels=next_sentence_labels, predictions=next_sentence_predictions)
next_sentence_mean_loss = tf.metrics.mean(
values=next_sentence_example_loss)
# 返回准确率+损失
return {
"masked_lm_accuracy": masked_lm_accuracy,
"masked_lm_loss": masked_lm_mean_loss,
"next_sentence_accuracy": next_sentence_accuracy,
"next_sentence_loss": next_sentence_mean_loss,
}
eval_metrics = (metric_fn, [
masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
masked_lm_weights, next_sentence_example_loss,
next_sentence_log_probs, next_sentence_labels
])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, loss=total_loss,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode))
return output_spec
return model_fn
```
**读取tf输入**
```python
def input_fn_builder(input_files,
max_seq_length,
max_predictions_per_seq,
is_training,
num_cpu_threads=4):
def input_fn(params):
batch_size = params["batch_size"]
name_to_features = {
"input_ids": tf.FixedLenFeature([max_seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([max_seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([max_seq_length], tf.int64),
"masked_lm_positions": tf.FixedLenFeature(
[max_predictions_per_seq], tf.int64),
"masked_lm_ids": tf.FixedLenFeature(
[max_predictions_per_seq], tf.int64),
"masked_lm_weights": tf.FixedLenFeature(
[max_predictions_per_seq], tf.float32),
"next_sentence_labels": tf.FixedLenFeature([1], tf.int64),
}
if is_training:
# 读取输入
d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))
d = d.repeat()
d = d.shuffle(buffer_size=len(input_files))
# 并行读取
cycle_length = min(num_cpu_threads, len(input_files))
d = d.apply(
tf.contrib.data.parallel_interleave(
tf.data.TFRecordDataset,
sloppy=is_training,
cycle_length=cycle_length))
d = d.shuffle(buffer_size=100)
else:
d = tf.data.TFRecordDataset(input_files)
d = d.repeat()
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
num_parallel_batches=num_cpu_threads,
drop_remainder=True))
return d
return input_fn
```
<file_sep>/model/deepfm/deepfm.py
import torch
import torch.nn as nn
class DeepFM(nn.Module):
"""DeepFM
Simplified:
DNN layers: 3
feature type: discrete
"""
def __init__(self, field_sizes, emb_size, hid_size, dropout=0.7):
super(DeepFM, self).__init__()
self.m = len(field_sizes)
self.f = field_sizes
self.k = emb_size
self.order_1_embeddings = nn.ModuleList([nn.Embedding(field_size, 1) for field_size in self.f])
self.order_2_embeddings = nn.ModuleList([nn.Embedding(field_size, self.k) for field_size in self.f])
self.dnn = nn.Sequential(nn.Linear(self.k * self.m, hid_size),
nn.Dropout(dropout),
nn.Linear(hid_size, hid_size),
nn.Dropout(dropout),
nn.Linear(hid_size, 1))
self.out = nn.Sigmoid()
def forward(self, x):
"""
Args:
x: a tensor of [batch_size, m], tensor([[2, 0, 1],
[1, 3, 0]])
"""
# Order 1 connections
# order_1_embedded = [batch_size, 1] * m
order_1_embedded = [self.order_1_embeddings[i](x[:, i]) for i in range(self.m)]
# Order 2 connections
# order_1_embedded = [batch_size, emb_size] * m
order_2_embedded = [self.order_2_embeddings[i](x[:, i]) for i in range(self.m)]
# FM part
order_1_product = sum(order_1_embedded)
p1 = torch.pow(sum(order_2_embedded), 2)
p2 = sum([torch.pow(e, 2) for e in order_2_embedded])
order_2_product = torch.sum((p1 - p2) / 2, 1).unsqueeze(1)
# y_fm = [batch_size, 1]
y_fm = order_1_product + order_2_product
# DNN part
# y_dnn = [batch_size, 1]
y_dnn = self.dnn(torch.cat(order_2_embedded, 1))
return self.out(y_fm + y_dnn)
<file_sep>/README.md
# Heterogeneous Recommendation
## Model
* DeepFM
* Transformer
* Seq2Seq
* BERT
## Dataset
* IMDb
| node | num |
| -------- | ----- |
| movie | 8267 |
| director | 3232 |
| actor | 13598 |
| genre | 24 |
| keyword | 13515 |
<file_sep>/model/bert/transformer.py
import torch
import torch.nn as nn
import numpy as np
class EncoderLayer(nn.Module):
def __init__(self, hid_size, n_heads, dropout=0.9):
super(EncoderLayer, self).__init__()
self.self_attention = MultiHeadAttention(hid_size, n_heads)
self.ffn = nn.Sequential(nn.Linear(hid_size, hid_size * 4), nn.GELU(), nn.Linear(hid_size * 4, hid_size))
self.layer_norm = nn.LayerNorm(hid_size)
self.dropout = nn.Dropout(dropout)
def forward(self, x, mask):
attention_output = self.self_attention(x, x, x, mask)
attention_output = self.layer_norm(x + self.dropout(attention_output))
encoder_output = self.ffn(attention_output)
encoder_output = self.layer_norm(attention_output + self.dropout(encoder_output))
return encoder_output
class MultiHeadAttention(nn.Module):
"""Multi-Head Attention Layer"""
def __init__(self, hid_size, n_heads):
super(MultiHeadAttention, self).__init__()
self.h = n_heads
self.d_k = hid_size // n_heads
self.w_q = nn.Linear(hid_size, hid_size)
self.w_k = nn.Linear(hid_size, hid_size)
self.w_v = nn.Linear(hid_size, hid_size)
self.w_o = nn.Linear(hid_size, hid_size)
def forward(self, query, key, value, mask=None):
# q, k, v = [batch_size, src_len, hid_size]
batch_size, hid_size = query.shape[0], query.shape[2]
# q, k, v = [batch_size, src_len, hid_size]
q = self.w_q(query)
k = self.w_k(key)
v = self.w_v(value)
# q, v = [batch_size, src_len, n_heads, head_size]
# k = [batch_size, src_len, head_size, n_heads]
q = q.view(batch_size, -1, self.h, self.d_k).permute(0, 2, 1, 3)
k = k.view(batch_size, -1, self.h, self.d_k).permute(0, 2, 3, 1)
v = v.view(batch_size, -1, self.h, self.d_k).permute(0, 2, 1, 3)
# Attention(Q, K, V) = Softmax(Q * K^T / d) * V
attention_scores = torch.matmul(q, k) / np.sqrt(self.d_k)
if mask is not None:
attention_scores = attention_scores.masked_fill(mask == 0, -1e4)
attention = torch.softmax(attention_scores, dim=-1)
y = torch.matmul(attention, v)
# y = [batch_size, src_len, hid_size]
y = y.permute(0, 2, 1, 3).contiguous().view(batch_size, -1, hid_size)
return self.w_o(y)
|
1356f2155bd0e03d65092262cc727b09ed6da497
|
[
"Markdown",
"Python"
] | 7
|
Python
|
Ginga1892/heterogeneous-recommendation
|
acadb22cbaa97b7e0ad500a42ce79981f581185c
|
19d1727a4cc92f0599684df6051a3a5df9102bf5
|
refs/heads/main
|
<repo_name>pathong/bullet-hell-jam<file_sep>/Assets/Scripts/spawnObj.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class spawnObj : MonoBehaviour
{
private GameObject block_;
public Text textShow;
public GameObject block;
public int count_block;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
textShow.text = count_block.ToString();
if (count_block > 0 && Input.GetKeyDown(KeyCode.LeftShift))
{
Instantiate(block);
count_block--;
}
}
}
<file_sep>/Assets/Scripts/DetectBullet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DetectBullet : MonoBehaviour
{
public GameObject par;
private Collider2D playerColl;
private GameObject player;
private AudioSource audio_;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "enemy_bullet" || collision.gameObject.tag == "bullet" || collision.gameObject.tag == "spike")
{
Instantiate(par, transform.position, Quaternion.identity);
audio_.Play();
StartCoroutine(ded());
}
}
//void OnTriggerEnter2D(Collision2D collision)
//{
// if (collision.gameObject.tag == "enemy_bullet" || collision.gameObject.tag == "bullet")
// {
// Destroy(gameObject);
// }
//}
// Start is called before the first frame update
void Start()
{
audio_ = gameObject.GetComponent<AudioSource>();
if(GameObject.FindGameObjectWithTag("Player") != null)
{
player = GameObject.FindGameObjectWithTag("Player");
playerColl = player.GetComponent<Collider2D>();
}
}
// Update is called once per frame
void Update()
{
Physics2D.IgnoreCollision(playerColl, GetComponent<Collider2D>(), true);
}
IEnumerator ded()
{
gameObject.SetActive(false);
yield return new WaitForSecondsRealtime(1);
Destroy(gameObject);
}
}
<file_sep>/Assets/Scripts/TImeCon.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; // IMPORTANT!!!!!!!!
public class TImeCon : MonoBehaviour
{
public Text textShow;
public float timeRemaining = 10f;
public bool timerIsRunning = false;
public Slider slider;
public void Start()
{
// Starts the timer automatically
timerIsRunning = true;
}
public void Update()
{
float fc = (float)System.Math.Round(timeRemaining * 100f) / 100f;
slider.value = timeRemaining/10;
textShow.text = fc.ToString();
if (timerIsRunning)
{
if (timeRemaining > 0)
{
timeRemaining -= Time.deltaTime;
}
else
{
timeRemaining = 0;
timerIsRunning = false;
}
}
}
}
<file_sep>/Assets/Scripts/SlowTimeCon.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SlowTimeCon : MonoBehaviour
{
public float slowTime = 0.2f;
public bool isSlow = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
StartCoroutine(Slowmotion());
}
}
IEnumerator Slowmotion()
{
Time.timeScale = slowTime;
Time.fixedDeltaTime = slowTime * Time.deltaTime;
yield return new WaitForSeconds(1);
Time.timeScale = 1;
Time.fixedDeltaTime = Time.deltaTime;
}
}
<file_sep>/Assets/Scripts/PlateCon.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlateCon : MonoBehaviour
{
private AudioSource _audio;
public GameObject par;
public GameObject blockWantTodisapper;
// Start is called before the first frame update
void Start()
{
_audio = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "Player" || collision.gameObject.tag == "bullet")
{
if (gameObject.tag == "end")
{
StartCoroutine(end_game());
}
_audio.Play();
Instantiate(par, blockWantTodisapper.transform.position, Quaternion.identity);
blockWantTodisapper.SetActive(false);
}
}
IEnumerator end_game()
{
yield return new WaitForSecondsRealtime(2);
Instantiate(par, blockWantTodisapper.transform.position, Quaternion.identity);
blockWantTodisapper.SetActive(false);
}
}
<file_sep>/Assets/Scripts/Shoot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Shoot : MonoBehaviour
{
public Text textShow;
public int bullet_count;
private float Speed = 5f;
public Transform fireBullet;
public GameObject bullet_prefab; private float timer = 2f;
public float cooldowntimer_bullet = 1;
private AudioSource audio_;
void Update()
{
textShow.text = bullet_count.ToString();
if (timer > 0)
{
timer -= Time.deltaTime * 8;
}
if (timer < 0)
{
timer = 0;
}
if (timer == 0 && Input.GetMouseButtonDown(1))
{
if(bullet_count > 0)
{
Shoot_();
audio_.Play();
timer = cooldowntimer_bullet;
bullet_count--;
}
}
}
public void Shoot_()
{
audio_ = gameObject.GetComponent<AudioSource>();
GameObject bullet = Instantiate(bullet_prefab, fireBullet.position, fireBullet.rotation );
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(fireBullet.right * Speed, ForceMode2D.Impulse);
}
}
<file_sep>/README.md
# bullet-hell-jam
<file_sep>/Assets/Scripts/ButtonCon.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ButtonCon : MonoBehaviour
{
private float startTime = 0f;
private float holdTime = 3.0f; // 3 seconds
public Animator transitionAnim;
// Start is called before the first frame update
private void Update()
{
if (Input.GetKey(KeyCode.R))
{
startTime = Time.time;
if (startTime + holdTime >= Time.time)
ReStart();
}
}
IEnumerator Quit()
{
transitionAnim.SetTrigger("end");
yield return new WaitForSecondsRealtime(1.5f);
Application.Quit();
}
IEnumerator LoadScene_i(int s)
{
transitionAnim.SetTrigger("end");
yield return new WaitForSecondsRealtime(1.5f);
SceneManager.LoadScene(s);
}
IEnumerator LoadScene(string s)
{
transitionAnim.SetTrigger("end");
yield return new WaitForSecondsRealtime(1.5f);
SceneManager.LoadScene(s);
}
public void t1()
{
StartCoroutine(LoadScene("s1"));
}
public void s_play()
{
StartCoroutine(LoadScene("Stage 1"));
}
public void s_opt()
{
StartCoroutine(LoadScene("Option"));
}
public void s_exit()
{
StartCoroutine(Quit());
}
public void s1()
{
StartCoroutine(LoadScene("1"));
}
public void s2()
{
StartCoroutine(LoadScene("2"));
}
public void s3()
{
StartCoroutine(LoadScene("3"));
}
public void s4()
{
StartCoroutine(LoadScene("4"));
}
public void s5()
{
StartCoroutine(LoadScene("5"));
}
public void s6()
{
StartCoroutine(LoadScene("6"));
}
public void s7()
{
StartCoroutine(LoadScene("7"));
}
public void s8()
{
StartCoroutine(LoadScene("11"));
}
public void s9()
{
StartCoroutine(LoadScene("9"));
}
public void s10()
{
StartCoroutine(LoadScene("10"));
}
public void s11()
{
StartCoroutine(LoadScene("8"));
}
public void s12()
{
StartCoroutine(LoadScene("12"));
}
public void s13()
{
StartCoroutine(LoadScene("13"));
}
public void s14()
{
StartCoroutine(LoadScene("14"));
}
public void s15()
{
StartCoroutine(LoadScene("15"));
}
public void ReStart()
{
StartCoroutine(LoadScene_i(SceneManager.GetActiveScene().buildIndex));
}
public void Home()
{
StartCoroutine(LoadScene("Menu"));
}
public void next(){
StartCoroutine(LoadScene_i(SceneManager.GetActiveScene().buildIndex+1));
}
public void t5(){
StartCoroutine(LoadScene("s5"));
}
public void t6()
{
StartCoroutine(LoadScene("s6"));
}
}
<file_sep>/Assets/Scripts/lazer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class lazer : MonoBehaviour
{
[SerializeField] private float defDistanceRay = 100;
public Transform laserFirePoint;
public LineRenderer m_lineREnderer;
Transform m_transform;
// Start is called before the first frame update
private void Awake()
{
m_transform = GetComponent<Transform>();
}
private void Update()
{
ShootLaser();
}
void ShootLaser()
{
if(Physics2D.Raycast(m_transform.position, transform.right))
{
RaycastHit2D _hit = Physics2D.Raycast(laserFirePoint.position, transform.right);
Draw2Dray(laserFirePoint.position, _hit.point);
}
}
void Draw2Dray(Vector2 startPos, Vector2 endPos)
{
m_lineREnderer.SetPosition(0, startPos);
m_lineREnderer.SetPosition(1, endPos);
}
// Update is called once per frame
}
<file_sep>/Assets/Scripts/EnemyShoot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyShoot : MonoBehaviour
{
public AudioSource shoot_audio;
public GameObject par;
private float Speed = 10f;
public Transform fireBullet;
public GameObject bullet_prefab;
public float timer = 9.99f;
public float cooldowntimer_bullet =10;
private void Start()
{
}
void Update()
{
if (timer > 0)
{
timer -= Time.deltaTime;
}
if (timer < 0)
{
timer = 0;
}
if (timer == 0)
{
Shoot_();
timer = cooldowntimer_bullet;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "bullet")
{
Instantiate(par, transform.position, Quaternion.identity);
}
}
public void Shoot_()
{
shoot_audio.Play();
GameObject bullet = Instantiate(bullet_prefab, fireBullet.position, fireBullet.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(fireBullet.right * Speed, ForceMode2D.Impulse);
}
}
<file_sep>/Assets/sound2.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class sound2 : MonoBehaviour
{
public AudioClip clip;
private AudioSource _audio;
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "boss")
{
print("tag");
_audio.PlayOneShot(clip);
}
}
// Start is called before the first frame update
void Start()
{
_audio = gameObject.GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
}
}
<file_sep>/Assets/Scripts/Con1.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Con1 : MonoBehaviour
{
private Scene scene;
public Animator transitionAnim;
// Start is called before the first frame update
void Start()
{
Scene scene = SceneManager.GetActiveScene();
}
IEnumerator LoadScene_i(int s)
{
transitionAnim.SetTrigger("end");
yield return new WaitForSecondsRealtime(1.5f);
SceneManager.LoadScene(s);
}
// Update is called once per frame
void Update()
{
if (Input.anyKeyDown)
{
if(Input.GetKey(KeyCode.Mouse0))
{
return;
}
else
{
StartCoroutine(LoadScene_i(SceneManager.GetActiveScene().buildIndex + 1));
}
}
}
}
<file_sep>/Assets/Scripts/DragObj.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragObj : MonoBehaviour
{
private AudioSource block_audio;
private bool isDragging = true;
private Vector3 player_pos;
private bool canPlace;
private Renderer rend;
[SerializeField]
private Color color = Color.red;
private Collider2D playerColl;
private GameObject player;
private Collider2D myColl;
// Start is called before the first frame update
private void Start()
{
block_audio = gameObject.GetComponent<AudioSource>();
myColl = gameObject.GetComponent<Collider2D>();
myColl.enabled = false;
player = GameObject.FindGameObjectWithTag("Player");
playerColl = player.GetComponent<Collider2D>();
rend = GetComponent<Renderer>();
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0) && canPlace)
{
block_audio.Play();
isDragging = !isDragging;
}
player_pos = player.transform.position;
if (Vector3.Distance(player_pos, transform.position) <= 2)
{
canPlace = true;
rend.material.color = Color.white;
}
else
{
rend.material.color = color;
canPlace = false;
}
if (isDragging)
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
transform.Translate(mousePos);
}
if (!isDragging)
{
myColl.enabled = true ;
this.enabled = false;
}
}
}
<file_sep>/Assets/Scripts/bullet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bullet : MonoBehaviour
{
Vector3 cameraInitialPosition;
public float shakeMagnetude = 0.1f, shakeTime = 0.5f;
public Camera mainCamera;
public GameObject par;
private float timer = 10;
// Start is called before the first frame update
void Start()
{
}
//void OnCollisionEnter2D(Collision2D collision)
//{
// if (collision.gameObject.tag == "enemy")
// {
// Destroy(collision.gameObject);
// Destroy(gameObject);
// }
//}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "ground" || collision.gameObject.tag == "spike")
{
ShakeIt();
Instantiate(par, transform.position, Quaternion.identity);
Destroy(gameObject);
}
if (collision.gameObject.tag == "enemy" || collision.gameObject.tag == "block" )
{
ShakeIt();
Instantiate(par, collision.gameObject.transform.position, Quaternion.identity);
StartCoroutine(ded(collision.gameObject));
Destroy(gameObject);
}
}
// Update is called once per frame
void Update()
{
if (timer > 0)
{
timer -= Time.deltaTime * 6;
}
if (timer < 0)
{
Instantiate(par, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
public void ShakeIt()
{
cameraInitialPosition = Camera.main.transform.position;
InvokeRepeating("StartCameraShaking", 0f, 0.005f);
Invoke("StopCameraShaking", shakeTime);
}
void StartCameraShaking()
{
float cameraShakingOffsetX = Random.value * shakeMagnetude * 2 - shakeMagnetude;
float cameraShakingOffsetY = Random.value * shakeMagnetude * 2 - shakeMagnetude;
Vector3 cameraIntermadiatePosition = Camera.main.transform.position;
cameraIntermadiatePosition.x += cameraShakingOffsetX;
cameraIntermadiatePosition.y += cameraShakingOffsetY;
Camera.main.transform.position = cameraIntermadiatePosition;
}
void StopCameraShaking()
{
CancelInvoke("StartCameraShaking");
Camera.main.transform.position = cameraInitialPosition;
}
IEnumerator ded(GameObject objTodestroy)
{
objTodestroy.SetActive(false);
yield return new WaitForSecondsRealtime(1);
Destroy(objTodestroy);
}
}
<file_sep>/Assets/Scripts/PlayerMove.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public AudioSource jump_audio;
public GameObject par;
private float speed = 5;
private float jump = 2;
public GameObject rayOrigin;
private float rayCheckDistance = 0.1f;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "spike")
{
Instantiate(par, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "end")
{
print("stop");
this.enabled = false;
}
if(collision.gameObject.tag == "enemy_bullet")
{
Instantiate(par, transform.position, Quaternion.identity);
Destroy(collision.gameObject);
Destroy(gameObject);
}
}
void FixedUpdate()
{
float x = Input.GetAxis("Horizontal");
if (Input.GetAxis("Jump") > 0)
{
RaycastHit2D hit = Physics2D.Raycast(rayOrigin.transform.position, Vector2.down, rayCheckDistance);
if (hit.collider != null) //(hit.collider.tag == "ground" || hit.collider.tag == "block")
{
if(hit.collider.gameObject.tag != "boss" && hit.collider.gameObject.tag != "portal" && hit.collider.gameObject.tag != "end"){
jump_audio.Play();
rb.AddForce(Vector2.up * jump, ForceMode2D.Impulse);
}
}
}
rb.velocity = new Vector3(x * speed, rb.velocity.y, 0);
}
}
<file_sep>/Assets/Scripts/WICon.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WICon : MonoBehaviour
{
private bool isPause = false;
public GameObject pauseUI;
public GameObject winUI;
public GameObject looseUI;
// Start is called before the first frame update
private void Awake()
{
Time.timeScale = 1f;
}
// Update is called once per frame
[System.Obsolete]
void Update()
{
GameObject[] enemy_list;
GameObject[] boss;
GameObject[] bullet;
GameObject[] e_bullet;
bullet = GameObject.FindGameObjectsWithTag("bullet");
e_bullet = GameObject.FindGameObjectsWithTag("enemy_bullet");
if (GameObject.FindGameObjectWithTag("boss") == null && Time.timeScale == 1)
{
Time.timeScale = 0f;
print(Time.timeScale);
looseUI.active = true;
}
if (GameObject.Find("TImeCon").GetComponent<TImeCon>().timeRemaining == 0 && bullet.Length + e_bullet.Length == 0 && GameObject.FindGameObjectWithTag("boss") != null && Time.timeScale == 1)
{
winUI.active = true;
print(Time.timeScale);
Time.timeScale = 0f;
}
if (Input.GetKeyDown(KeyCode.Escape))
{
isPause = !isPause;
if (isPause)
{
pauseUI.active = true;
Time.timeScale = 0f;
print(Time.timeScale);
}
if (!isPause)
{
pauseUI.active = false;
Time.timeScale = 1.0f;
print(Time.timeScale);
}
}
}
}
<file_sep>/Assets/Move.cs
using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour {
public float speed;
public float jump;
public GameObject rayOrigin;
public float rayCheckDistance;
Rigidbody2D rb;
void Start () {
rb = GetComponent <Rigidbody2D> ();
}
void FixedUpdate () {
float x = Input.GetAxis ("Horizontal");
if (Input.GetAxis ("Jump") > 0) {
RaycastHit2D hit = Physics2D.Raycast(rayOrigin.transform.position, Vector2.down, rayCheckDistance);
if (hit.collider != null) {
rb.AddForce (Vector2.up * jump, ForceMode2D.Impulse);
}
}
rb.velocity = new Vector3 (x * speed, rb.velocity.y, 0);
}
}<file_sep>/Assets/Scripts/PlateEnd.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlateEnd : MonoBehaviour
{
public Animator end_anim;
private AudioSource _audio;
public GameObject par;
public GameObject blockWantTodisapper;
public GameObject blockWantTodisapper2;
// Start is called before the first frame update
void Start()
{
_audio = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
_audio.Play();
Instantiate(par, blockWantTodisapper.transform.position, Quaternion.identity);
blockWantTodisapper.SetActive(false);
StartCoroutine(end_game());
}
}
IEnumerator end_game()
{
yield return new WaitForSecondsRealtime(2);
Instantiate(par, blockWantTodisapper.transform.position, Quaternion.identity);
blockWantTodisapper2.SetActive(false);
yield return new WaitForSecondsRealtime(2);
end_anim.SetTrigger("end");
yield return new WaitForSecondsRealtime(1);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
<file_sep>/Assets/Scripts/roPlayer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class roPlayer : MonoBehaviour
{
GameObject[] player;
// Start is called before the first frame update
void Start()
{
player = GameObject.FindGameObjectsWithTag("Player");
}
private void FixedUpdate()
{
if (player.Length > 0)
{
Vector3 diff = player[0].transform.position - transform.position;
diff.Normalize();
float rotationZ = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotationZ);
}
}
}
<file_sep>/Assets/Scripts/Portal.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Portal : MonoBehaviour
{
private AudioSource _audio;
private float time = 0f;
public GameObject par;
public GameObject portal;
public GameObject player;
// Start is called before the first frame update
void Start()
{
_audio = gameObject.GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other) {
if(other.gameObject.tag == "Player"){
_audio.Play();
}
}
private void OnTriggerStay2D(Collider2D other) {
if(other.gameObject.tag =="Player"){
time += 1 * Time.deltaTime;
if(time >= 1){
Instantiate(par, transform.position, Quaternion.identity);
player.transform.position = new Vector2(portal.transform.position.x + 0.5f, portal.transform.position.y);
}
}
}
private void OnTriggerExit2D(Collider2D other) {
if(other.gameObject.tag == "Player"){
time = 0f;
}
}
// IEnumerator teleport(){
// }
}
|
3a58adc2cae3532a30d69f71ef817bf776065b00
|
[
"Markdown",
"C#"
] | 20
|
C#
|
pathong/bullet-hell-jam
|
5832d7c76982fd021eada0ae5a22717b99e67d77
|
f0a35dc0a7754c81c1b436782ccb35cfc343ad03
|
refs/heads/master
|
<file_sep>// Input: "The quick brown fox jumped over the lazy dog"
// Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
// Notes:
// S contains only uppercase, lowercase and spaces. Exactly one space between each word.
// 1 <= S.length <= 150.
// */
//1. split the string, put it into array
//2. if arr[i][0] === (a, e, i, o, u, A, E, I, O, U), then arr[i] + ma + (i+1)*a
//3.else, remove the fist letter of the array. then arr[i] + arr[i][0] + ma + (i+1)*a
//4. array.join(" ")
const goatLatin(str) {
arr = str.split() //{I, speak, Goat, Latin}
let vowelSet = new Set(['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']);
for (i, i< arr.size, i++)
if (vowelSet.has(arr[i][0])){
arr[i] + ma + (i+1)*a
}else {
arr[i].substring(1) + arr[i][0] +ma + (i+1)*a
}
}
//const goatLatin = (sting) => {
// let newArr = string.split(' ')
// let vowelSet = new Set(['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']);
// let multiply = 1;
// newArr.forEach((e)=> {
// if(!vowelSet.has(e[0])){
// e = e.substring(1) + e[0] + 'ma' + ;
// }
// e += 'ma' // e = e+'ma'
// e+= 'a'.repeat(multiply);
// multiply++;
// }
// })
// let res = newArr.join(' ');
//return res
// }
|
0a2d1529ec45e3bfaad98acd2fda28acc2cd3676
|
[
"JavaScript"
] | 1
|
JavaScript
|
mia-pan/algorithm_goatLatin
|
6ce6c5519e8fbb2f442c61ab1ac418945442a3a7
|
d8dc4845115c06ff5719c731a84dceb68e5baa26
|
refs/heads/master
|
<repo_name>ejaandersson/EDA031<file_sep>/src/inmemoryserver.h
#ifndef INMEMORYSERVER_H
#define INMEMORYSERVER_H
#include "serverinterface.h"
#include "newsgroup.h"
#include <set>
class InMemoryServer : public ServerInterface {
public:
explicit InMemoryServer(int port) : ServerInterface(port), number(0) {}
virtual ~InMemoryServer(){};
std::vector<std::pair<id,std::string>> list_ng() const override;
id create_ng(std::string&) override;
bool delete_ng(id) override;
std::vector<std::pair<id, std::string> > listArt(id) const override;
id add_art(id, const std::shared_ptr<Article>&) override;
bool delete_art(id, id) override;
std::shared_ptr<const Article> read_art(id, id) const override;
bool exists_ng(id ng) const;
private:
id number;
std::map<id, Newsgroup> newsgroups;
std::set<std::string> ng_names;
};
#endif /* INMEMORYSERVER_H */
<file_sep>/src/diskserver.cc
#include "diskserver.h"
using namespace std;
using namespace tinyxml2;
DiskServer::DiskServer(int port, string fileName) : ServerInterface(port), file(fileName) {
if(xmlDoc.LoadFile(file.c_str()) != XML_SUCCESS)
init_file();
}
/*
* A private function that initialize a new empty xml database file
*/
void DiskServer::init_file(){
file = "savexml.xml";
XMLNode* root = xmlDoc.NewElement("newsserver");
XMLElement* id_tag = xmlDoc.NewElement("newsgroup-id-count");
id_tag->SetText(0);
xmlDoc.InsertFirstChild(root);
root->InsertFirstChild(id_tag);
xmlDoc.SaveFile(file.c_str());
}
/*
* Lists all the news groups on the server.
* Returns a vector containing id numbers and names for all the news groups.
* Returns an empty vector if no newsgroup exists.
*/
vector<std::pair<id,string> > DiskServer::list_ng() const{
vector<pair<id,string> > v;
const char* ng_name;
id ng_nbr;
const XMLElement* name_tag;
const XMLNode* root = xmlDoc.FirstChild();
const XMLElement* newsgroup_tag = root->FirstChildElement("newsgroup");
while(newsgroup_tag != nullptr){
name_tag = newsgroup_tag->FirstChildElement("name");
ng_name = name_tag->GetText();
newsgroup_tag->QueryUnsignedAttribute("id", &ng_nbr);
v.push_back(make_pair(ng_nbr, string(ng_name)));
newsgroup_tag = newsgroup_tag->NextSiblingElement("newsgroup");
}
return v;
}
/*
* Creates a new news group.
* Returns the id number of the newly created news group if successful,
* otherwise 0 if the name was already taken.
*/
id DiskServer::create_ng(string &name){
if (exists_ng(name))
return 0;
id number;
XMLElement* root = xmlDoc.RootElement();
XMLElement* id_tag = const_cast<XMLElement*>(root->FirstChildElement());
id_tag->QueryUnsignedText(&number);
id_tag->SetText(++number);
XMLElement* newsgroup_tag = xmlDoc.NewElement("newsgroup");
newsgroup_tag->SetAttribute("id", number);
XMLElement* name_tag = xmlDoc.NewElement("name");
name_tag->SetText(name.c_str());
XMLElement* art_id_tag = xmlDoc.NewElement("article-id-count");
art_id_tag->SetText(0);
root->InsertEndChild(newsgroup_tag);
newsgroup_tag->InsertFirstChild(name_tag);
newsgroup_tag->InsertEndChild(art_id_tag);
xmlDoc.SaveFile(file.c_str());
return number;
}
/*
* Deletes a news group from the server.
* Returns true if successful.
*/
bool DiskServer::delete_ng(id ng){
XMLElement* newsgroup_tag = find_ng_tag(ng);
if (newsgroup_tag == nullptr)
return false;
xmlDoc.DeleteNode(newsgroup_tag);
xmlDoc.SaveFile(file.c_str());
return true;
}
/*
* Lists all the articles in a news group.
* Returns a vector containing id numbers and names for all the articles.
* Returns an empty vector if the newsgroup is empty or doesn't exist.
*/
std::vector<std::pair<id, std::string> > DiskServer::listArt(id ng) const{
std::vector<std::pair<id, std::string> > v;
XMLElement* ng_tag = find_ng_tag(ng);
if(ng_tag == nullptr)
return v;
id art_nbr;
string art_title;
const XMLElement* title_tag;
XMLElement* article_tag = ng_tag->FirstChildElement("article");
while(article_tag != nullptr){
title_tag = article_tag->FirstChildElement("title");
art_title = title_tag->GetText();
article_tag->QueryUnsignedAttribute("id", &art_nbr);
v.push_back(make_pair(art_nbr, string(art_title)));
article_tag = article_tag->NextSiblingElement("article");
}
return v;
}
/*
* Adds a new article in newsgroup ng.
* Returns true if the article was successfully added to ng.
*/
id DiskServer::add_art(id ng, const std::shared_ptr<Article>& a){
id art_nbr = 0;
XMLElement* ngt = find_ng_tag(ng);
if (ngt == nullptr)
return art_nbr;
const XMLElement* art_id_tag = ngt->FirstChildElement("article-id-count");
art_id_tag->QueryUnsignedText(&art_nbr);
(const_cast<XMLElement*>(art_id_tag))->SetText(++art_nbr);
XMLElement* article_tag = xmlDoc.NewElement("article");
ngt->InsertEndChild(article_tag);
article_tag->SetAttribute("id", art_nbr);
XMLElement* title_tag = xmlDoc.NewElement("title");
article_tag->InsertFirstChild(title_tag);
title_tag->SetText(a->getTitle().c_str());
XMLElement* author_tag = xmlDoc.NewElement("author");
article_tag->InsertEndChild(author_tag);
author_tag->SetText(a->getAuthor().c_str());
XMLElement* text_tag = xmlDoc.NewElement("text");
article_tag->InsertEndChild(text_tag);
text_tag->SetText(a->getText().c_str());
xmlDoc.SaveFile(file.c_str());
return art_nbr;
}
/*
* Deletes an article.
* Returns true if the article was successfully deleted.
*/
bool DiskServer::delete_art(id ng, id art){
XMLNode* article_tag = find_ng_tag(ng, art);
if (article_tag == nullptr)
return false;
xmlDoc.DeleteNode(article_tag);
xmlDoc.SaveFile("savexml.xml");
return true;
}
/*
* Gets an article.
* Returns a pointer to the article.
* Returns nullptr if any of the ids are invalid.
*/
shared_ptr<const Article> DiskServer::read_art(id ng, id art) const{
XMLElement* art_tag = find_ng_tag(ng, art);
if(art_tag == nullptr)
return nullptr;
const XMLElement* title_tag = art_tag->FirstChildElement("title");
shared_ptr<string> title = make_shared<string>(string(title_tag->GetText()));
const XMLElement* author_tag = art_tag->FirstChildElement("author");
shared_ptr<string> author = make_shared<string>(string(author_tag->GetText()));
const XMLElement* text_tag = art_tag->FirstChildElement("text");
shared_ptr<string> text = make_shared<string>(string(text_tag->GetText()));
const Article* a = new const Article(*title, *author, *text);
return shared_ptr<const Article>(a);
}
/*
* Checks if the newsgroup exists by id.
* Returns true if it does.
*/
bool DiskServer::exists_ng(id nbr) const{
return find_ng_tag(nbr) != nullptr;
}
/*
* Checks if the newsgroup exists by name.
* Returns true if it does.
*/
bool DiskServer::exists_ng(string &name) const{
for(auto &p : list_ng()){
if(!p.second.compare(name))
return true;
}
return false;
}
/*
* A private function
* Fetches an an article tag
* Fetches a newsgroup tag if art is set to 0 or left unset.
* Returns the tag requested or nullptr if any id is invalid
*/
XMLElement* DiskServer::find_ng_tag(id ng, id art) const{
const XMLNode* root = xmlDoc.FirstChild();
const XMLElement* newsgroup_tag = root->FirstChildElement("newsgroup");
id nbr;
while(newsgroup_tag != nullptr){
newsgroup_tag->QueryUnsignedAttribute("id", &nbr);
if (nbr == ng){
if (art == 0)
return const_cast<XMLElement*>(newsgroup_tag);
const XMLElement* article_tag = newsgroup_tag->FirstChildElement("article");
while (article_tag != nullptr){
article_tag->QueryUnsignedAttribute("id", &nbr);
if (nbr == art)
return const_cast<XMLElement*>(article_tag);
article_tag = article_tag->NextSiblingElement("article");
}
break;
}
newsgroup_tag = newsgroup_tag->NextSiblingElement("newsgroup");
}
return nullptr;
}
<file_sep>/src/inmemoryserver.cc
#include "inmemoryserver.h"
using namespace std;
/*
* Lists all the news groups on the server.
* Returns a vector containing id numbers and names for all the news groups.
* Returns an empty vector if no newsgroup exists.
*/
vector<pair<id,string>> InMemoryServer::list_ng() const {
vector<pair<id,string>> v;
v.reserve(newsgroups.size());
for (const auto& kv : newsgroups)
v.push_back(make_pair(kv.first, kv.second.getName()));
return v;
}
/*
* Creates a new news group.
* Returns the id number of the newly created news group if successful,
* otherwise 0 if the name was already taken.
*/
id InMemoryServer::create_ng(string& name) {
if (!ng_names.insert(name).second)
return 0;
newsgroups.insert(make_pair(++number, Newsgroup(name)));
return number;
}
/*
* Deletes a news group from the server.
* Returns true if successful.
*/
bool InMemoryServer::delete_ng(id ng) {
auto it = newsgroups.find(ng);
if (it == newsgroups.end())
return false;
newsgroups.erase(it);
return true;
}
/*
* Lists all the articles in a news group.
* Returns a vector containing id numbers and names for all the articles.
* Returns an empty vector if no article exists or if the the id is invalid.
*/
vector<pair<id, string>> InMemoryServer::listArt(id ng) const {
auto it = newsgroups.find(ng);
if (it == newsgroups.end()) {
return vector<pair<id, string>>();
}
return it->second.list_art();
}
/*
* Adds a new article in news group ng.
* Returns the id number of the inserted article if successful,
* otherwise 0 if the newsgroup id coudln't be found.
*/
id InMemoryServer::add_art(id ng, const shared_ptr<Article> &a) {
auto it = newsgroups.find(ng);
if (it == newsgroups.end()) {
return 0;
}
return it->second.add_art(a);
}
/*
* Deletes an article.
* Returns true if the article was successfully deleted.
*/
bool InMemoryServer::delete_art(id ng, id art) {
auto it = newsgroups.find(ng);
if (it == newsgroups.end()) {
return false;
}
return it->second.delete_art(art);
}
/*
* Get an article.
* Returns an pointer to the article
* Returns nullptr if nothing was found
*/
shared_ptr<const Article> InMemoryServer::read_art(id ng, id art) const {
auto it = newsgroups.find(ng);
if (it == newsgroups.end()) {
return nullptr;
}
return it->second.get_art(art);
}
/*
* Checks if a newsgroup exists
* Returns true if it does.
*/
bool InMemoryServer::exists_ng(id ng) const {
if (newsgroups.empty()) {
return false;
}
auto it = newsgroups.find(ng);
if (it == newsgroups.end()) {
return false;
}
return true;
}
<file_sep>/src/illegalcommandexception.h
#include <string>
#ifndef ILLEGAL_COMMAND_EXCEPTION_H
#define ILLEGAL_COMMAND_EXCEPTION_H
struct IllegalCommandException {
std::string message;
std::string error;
int protMessage;
int codeNumber;
IllegalCommandException(std::string m, int prot, int code) : message(m), protMessage(prot), codeNumber(code) {}
IllegalCommandException(std::string m, std::string em) : message(m), error(em) {}
};
#endif<file_sep>/src/article.h
#ifndef ARTICLE_H
#define ARTICLE_H
#include <memory>
#include <string>
class Article {
public:
Article(std::string titl, std::string auth, std::string txt) : title(titl), author(auth), text(txt) {}
virtual ~Article(){}
std::string getTitle() const {return title;}
std::string getAuthor() const {return author;}
const std::string& getText() const {return text;}
private:
std::string title, author, text;
};
#endif /* ARTICLE_H */
<file_sep>/src/servermessagehandler.h
#ifndef SERVERMESSAGEHANDLER_H
#define SERVERMESSAGEHANDLER_H
#include <memory>
#include "illegalcommandexception.h"
#include "messagehandler.h"
#include "serverinterface.h"
class ServerMessageHandler {
public:
ServerMessageHandler(std::shared_ptr<MessageHandler>, std::shared_ptr<ServerInterface>);
int newMessage(void) throw(IllegalCommandException, ConnectionClosedException);
void listGroups(void);
void createGroup(void);
void deleteGroup(void);
void listArticles(void);
void createArticle(void);
void deleteArticle(void);
void getArticle(void);
void checkEnd(void);
private:
std::shared_ptr<MessageHandler> msgH;
std::shared_ptr<ServerInterface> server;
};
#endif
<file_sep>/src/diskserver.h
#ifndef DISKSERVER_H
#define DISKSERVER_H
#include "serverinterface.h"
#include "tinyxml2.h"
class DiskServer : public ServerInterface{
public:
explicit DiskServer(int port, std::string fileName = "database.xml");
virtual ~DiskServer(){};
std::vector<std::pair<id,std::string>> list_ng() const override;
id create_ng(std::string&) override;
bool delete_ng(id) override;
std::vector<std::pair<id, std::string> > listArt(id) const override;
id add_art(id, const std::shared_ptr<Article>&) override;
bool delete_art(id, id) override;
std::shared_ptr<const Article> read_art(id, id) const override;
bool exists_ng(id nbr) const override;
bool exists_ng(std::string&) const;
private:
std::string file;
tinyxml2::XMLDocument xmlDoc;
void init_file();
tinyxml2::XMLElement* find_ng_tag(id ng, id art = 0) const;
};
#endif /* DISKSERVER_H */
<file_sep>/src/servermessagehandler.cc
#include <string>
#include <vector>
#include <utility>
#include "servermessagehandler.h"
#include "protocol.h"
#include "inmemoryserver.h"
#include "diskserver.h"
#include <iostream>
using namespace std;
ServerMessageHandler::ServerMessageHandler(shared_ptr<MessageHandler> msgHandler, shared_ptr<ServerInterface> s) : msgH(msgHandler), server(s) {}
int ServerMessageHandler::newMessage(void) throw(IllegalCommandException, ConnectionClosedException){
uint command = msgH->getCode();
switch (command) {
case Protocol::COM_LIST_NG:
listGroups();
msgH->sendCode(Protocol::ANS_END);
break;
case Protocol::COM_CREATE_NG:
createGroup();
msgH->sendCode(Protocol::ANS_END);
break;
case Protocol::COM_DELETE_NG:
deleteGroup();
msgH->sendCode(Protocol::ANS_END);
break;
case Protocol::COM_LIST_ART:
listArticles();
msgH->sendCode(Protocol::ANS_END);
break;
case Protocol::COM_CREATE_ART:
createArticle();
msgH->sendCode(Protocol::ANS_END);
break;
case Protocol::COM_DELETE_ART:
deleteArticle();
msgH->sendCode(Protocol::ANS_END);
break;
case Protocol::COM_GET_ART:
getArticle();
msgH->sendCode(Protocol::ANS_END);
break;
default:
throw IllegalCommandException("", "");
}
return 0;
}
void ServerMessageHandler::listGroups(void) {
checkEnd();
msgH->sendCode(Protocol::ANS_LIST_NG);
vector<pair<id, string>> newsGroups = server->list_ng();
msgH->sendIntParam(newsGroups.size());
for (auto it = newsGroups.begin(); it != newsGroups.end(); ++it) {
msgH->sendIntParam(it->first);
msgH->sendStrParam(it->second);
}
}
void ServerMessageHandler::createGroup(void) {
string title = msgH->getStrParam();
checkEnd();
msgH->sendCode(Protocol::ANS_CREATE_NG);
id res = server->create_ng(title);
if (res != 0){
msgH->sendCode(Protocol::ANS_ACK);
} else {
msgH->sendCode(Protocol::ANS_NAK);
msgH->sendCode(Protocol::ERR_NG_ALREADY_EXISTS);
}
}
void ServerMessageHandler::deleteGroup(void) {
int ngInt = msgH->getIntParam();
checkEnd();
msgH->sendCode(Protocol::ANS_DELETE_NG);
if (server->delete_ng(ngInt)){
msgH->sendCode(Protocol::ANS_ACK);
} else {
msgH->sendCode(Protocol::ANS_NAK);
msgH->sendCode(Protocol::ERR_NG_DOES_NOT_EXIST);
}
}
void ServerMessageHandler::listArticles(void) {
int ngInt = msgH->getIntParam();
checkEnd();
msgH->sendCode(Protocol::ANS_LIST_ART);
std::vector<std::pair<id, string>> articles = server->listArt(ngInt);
if (!server->exists_ng(ngInt)) {
msgH->sendCode(Protocol::ANS_NAK);
msgH->sendCode(Protocol::ERR_NG_DOES_NOT_EXIST);
} else {
msgH->sendCode(Protocol::ANS_ACK);
msgH->sendIntParam(articles.size());
for(auto it = articles.begin(); it != articles.end(); ++it) {
msgH->sendIntParam(it->first);
msgH->sendStrParam(it->second);
}
}
}
void ServerMessageHandler::createArticle(void) {
int ngInt = msgH->getIntParam();
string title = msgH->getStrParam();
string author = msgH->getStrParam();
string text = msgH->getStrParam();
checkEnd();
msgH->sendCode(Protocol::ANS_CREATE_ART);
if (server->exists_ng(ngInt)) {
server->add_art(ngInt, shared_ptr<Article>(new Article(title, author, text)));
msgH->sendCode(Protocol::ANS_ACK);
} else {
msgH->sendCode(Protocol::ANS_NAK);
msgH->sendCode(Protocol::ERR_NG_DOES_NOT_EXIST);
}
}
void ServerMessageHandler::deleteArticle(void) {
int ngInt = msgH->getIntParam();
int article = msgH->getIntParam();
checkEnd();
msgH->sendCode(Protocol::ANS_DELETE_ART);
if (server->exists_ng(ngInt)) {
if (server->delete_art(ngInt, article)) {
msgH->sendCode(Protocol::ANS_ACK);
} else {
msgH->sendCode(Protocol::ANS_NAK);
msgH->sendCode(Protocol::ERR_ART_DOES_NOT_EXIST);
}
} else {
msgH->sendCode(Protocol::ANS_NAK);
msgH->sendCode(Protocol::ERR_NG_DOES_NOT_EXIST);
}
}
void ServerMessageHandler::getArticle(void) {
int ngInt = msgH->getIntParam();
int articleId = msgH->getIntParam();
checkEnd();
msgH->sendCode(Protocol::ANS_GET_ART);
if (server->exists_ng(ngInt)) {
shared_ptr<const Article> article = server->read_art(ngInt, articleId);
if (article != nullptr) {
msgH->sendCode(Protocol::ANS_ACK);
msgH->sendStrParam(article->getTitle());
msgH->sendStrParam(article->getAuthor());
msgH->sendStrParam(article->getText());
} else {
msgH->sendCode(Protocol::ANS_NAK);
msgH->sendCode(Protocol::ERR_ART_DOES_NOT_EXIST);
}
} else {
msgH->sendCode(Protocol::ANS_NAK);
msgH->sendCode(Protocol::ERR_NG_DOES_NOT_EXIST);
}
}
void ServerMessageHandler::checkEnd(void) {
if (msgH->getCode() != Protocol::COM_END) {
throw IllegalCommandException("", "");
}
}
<file_sep>/src/newsgroup.cc
#include "newsgroup.h"
using namespace std;
id Newsgroup::add_art(shared_ptr<Article> a){
articles.insert(make_pair(++number, a));
return number;
}
bool Newsgroup::delete_art(id nbr){
return articles.erase(nbr);
}
shared_ptr<Article> Newsgroup::get_art(id nbr) const{
auto a = articles.find(nbr);
return a != articles.end() ? a->second : nullptr;
}
vector<pair<id, string>> Newsgroup::list_art() const{
vector<pair<id, string>> v;
v.reserve(articles.size());
for (const auto& kv : articles)
v.push_back(make_pair(kv.first, kv.second->getTitle()));
return v;
}<file_sep>/src/serverinterface.h
#ifndef SERVERINTERFACE_H
#define SERVERINTERFACE_H
#include <string>
#include <vector>
#include <utility>
#include <memory>
#include "article.h"
#include "server.h"
using id = unsigned int;
class ServerInterface : public Server {
public:
ServerInterface(int port) : Server(port) {}
/*
* Lists all the news groups on the server.
* Returns a vector containing id numbers and names for all the news groups.
* Returns an empty vector if no newsgroups exists.
*/
virtual std::vector<std::pair<id,std::string> > list_ng() const = 0;
/*
* Creates a new news group.
* Returns the id number of the newly created news group if successful,
* otherwise 0 if the name was already taken.
*/
virtual id create_ng(std::string& name) = 0;
/*
* Deletes a news group from the server.
* Returns true if successful.
*/
virtual bool delete_ng(id ng) = 0;
/*
* Lists all the articles in a news group.
* Returns a vector containing id numbers and names for all the articles.
* Returns an empty vector if no article exists or if the id is invalid.
*/
virtual std::vector<std::pair<id, std::string> > listArt(id ng) const = 0;
/*
* Adds a new article in news group ng.
* Returns the id number of the inserted article if successful,
* otherwise 0 if the newsgroup id coudln't be found.
*/
virtual id add_art(id ng, const std::shared_ptr<Article>&) = 0;
/*
* Deletes an article.
* Returns true if the article was successfully deleted.
*/
virtual bool delete_art(id ng, id art) = 0;
/*
* Get an article.
* Returns a pointer to the article.
* Returns nullptr if nothing was found.
*/
virtual std::shared_ptr<const Article> read_art(id ng, id art) const = 0;
/*
* Checks if a newsgroup exists.
* Returns true if it does.
*/
virtual bool exists_ng(id ng) const = 0;
private:
};
#endif /* SERVERINTERFACE_H */
<file_sep>/src/messagehandler.cc
#include <iostream>
#include <string>
#include "messagehandler.h"
using namespace std;
/**
Create a message handler through a connection.
@param conn is the connection message handler handles messages through (Bättre kommentar går inte hitta)
*/
MessageHandler::MessageHandler(shared_ptr<Connection> conn) : conn(conn) {}
/**
Change connection.
@param conn is the new Connection object
*/
/**
Sends a code corresponding to a constant from the Protocol class.
@param code is the code to send.
@throws ConnectionClosedException if the server is dead.
*/
void MessageHandler::sendCode(int code) throw(ConnectionClosedException) {
sendByte(code);
}
/**
Sends an int parameter following the Protocol
@param value is the int to be sent
@throws ConnectionClosedException if connection was lost.
*/
void MessageHandler::sendInt(int value) throw(ConnectionClosedException) {
sendByte((value >> 24) & 0xFF);
sendByte((value >> 16) & 0xFF);
sendByte((value >> 8 ) & 0xFF);
sendByte((value & 0xFF));
}
/**
Sends an int parameter following the Protocol
@param i is the integer to be sent
@throws ConnectionClosedException if connection was lost
*/
void MessageHandler::sendIntParam(int i) throw(ConnectionClosedException) {
sendCode(Protocol::PAR_NUM);
sendInt(i);
}
/**
Sends a string parameter following the Protocol
@param str is the string to be sent
@throws ConnectionClosedException if connection was lost.
*/
void MessageHandler::sendStrParam(const string& str) throw(ConnectionClosedException) {
sendCode(Protocol::PAR_STRING);
sendInt(str.length());
for (unsigned int i = 0; i < str.length(); i++) {
sendByte(str[i]);
}
}
/**
Gets an int value
@return the int value
@throws ConnectionClosedException if connection was lost
*/
int MessageHandler::getInt() throw(ConnectionClosedException) {
int byte1 = getByte();
int byte2 = getByte();
int byte3 = getByte();
int byte4 = getByte();
return byte1 << 24 | byte2 << 16 | byte3 << 8 | byte4;
}
/**
Gets an int parameter.
@return the parameter
@throws ConnectionClosedException if connection was lost
@throws IllegalCommandException
*/
int MessageHandler::getIntParam() throw(ConnectionClosedException, IllegalCommandException) {
int code = getCode();
if (code != Protocol::PAR_NUM) {
throw IllegalCommandException("Get integer parameter", Protocol::PAR_NUM, code);
}
return getInt();
}
/**
Gets a string parameter.
@return the parameter
@throws ConnectionClosedException if the connection was lost
@throws IllegalCommandException
*/
string MessageHandler::getStrParam() throw(ConnectionClosedException, IllegalCommandException) {
int code = getCode();
if (code != Protocol::PAR_STRING) {
throw IllegalCommandException("Get string parameter", Protocol::PAR_STRING, code);
}
int n = getInt();
if (n < 1) {
throw IllegalCommandException("Get string parameter", "Number of characters below 0");
}
string result = "";
for (int i = 1; i <= n; i++) {
char ch = conn->read();
result += ch;
}
return result;
}
/**
Gets a code = command
@return the code
@throws ConnectionClosedException if connection was lost
*/
int MessageHandler::getCode() throw(ConnectionClosedException) {
int code = getByte();
return code;
}
/**
*/
int MessageHandler::getByte() {
int code;
try {
code = conn->read();
} catch (...) {
throw ConnectionClosedException();
}
return code;
}
/**
*/
void MessageHandler::sendByte(int code) throw(ConnectionClosedException) {
try {
conn->write(static_cast<char>(code));
} catch(...) {
throw ConnectionClosedException();
}
}
<file_sep>/src/test/myserver.cc
#include "inmemoryserver.h"
#include "diskserver.h"
#include "server.h"
#include "connection.h"
#include "connectionclosedexception.h"
#include "messagehandler.h"
#include "servermessagehandler.h"
#include <memory>
#include <iostream>
#include <string>
#include <stdexcept>
#include <cstdlib>
using namespace std;
int main(int argc, char* argv[]){
if (argc != 2) {
cerr << "Usage: myserver port-number" << endl;
exit(1);
}
int port = -1;
try {
port = stoi(argv[1]);
} catch (exception& e) {
cerr << "Wrong port number. " << e.what() << endl;
exit(1);
}
string servertype;
cout << "Choose server type: " << endl;
cout << "1. InMemoryServer" << endl;
cout << "2. DiskServer" << endl;
cin >> servertype;
ServerInterface* s;
if (servertype.compare("1") == 0) {
s = new InMemoryServer(port);
} else if (servertype.compare("2") == 0) {
s = new DiskServer(port, "savexml.xml");
} else {
cerr << "Invalid server choise." << endl;
}
shared_ptr<ServerInterface> serverptr(s);
if (!serverptr->isReady()) {
cerr << "Server initialization error." << endl;
exit(1);
} else {
cout << "Server is ready." << endl;
}
while (true) {
auto conn = serverptr->waitForActivity();
if (conn != nullptr) {
try {
shared_ptr<MessageHandler> msgptr = make_shared<MessageHandler>(MessageHandler(shared_ptr<Connection>(conn)));
ServerMessageHandler smh(msgptr, serverptr);
smh.newMessage();
} catch (ConnectionClosedException&) {
serverptr->deregisterConnection(conn);
cout << "Client closed connection" << endl;
}
} else {
conn = make_shared<Connection>();
serverptr->registerConnection(conn);
cout << "New client connects" << endl;
}
}
}
<file_sep>/README.md
# EDA031
Project in EDA031 C++
We have followed the projection specifications, while in the root-folder it is possible to use the commands:
* make clean
* make all
* make install
After following this chain of commands it is now possible to go to the bin-folder and run the executables.
<file_sep>/src/newsgroup.h
#ifndef NEWSGROUP_H
#define NEWSGROUP_H
#include "article.h"
#include <map>
#include <vector>
#include <memory>
using id = unsigned int;
class Newsgroup {
public:
Newsgroup(std::string n) : name(n), number(0) {};
virtual ~Newsgroup(){};
id add_art(std::shared_ptr<Article>);
bool delete_art(id nubr);
const std::string& getName() const {return name;}
std::shared_ptr<Article> get_art(id nbr) const;
std::vector<std::pair<id, std::string> > list_art() const;
private:
std::string name;
id number;
std::map<id, std::shared_ptr<Article> > articles;
};
#endif /* NEWSGROUP_H */
<file_sep>/src/messagehandler.h
#ifndef MESSAGEHANDLER_H
#define MESSAGEHANDLER_H
#include <string>
#include <memory>
#include "protocol.h"
#include "connection.h"
#include "connectionclosedexception.h"
#include "illegalcommandexception.h"
class MessageHandler {
public:
explicit MessageHandler(std::shared_ptr<Connection>);
void sendCode(int code) throw(ConnectionClosedException);
void sendByte(int code) throw(ConnectionClosedException);
void sendInt(int value) throw(ConnectionClosedException);
void sendIntParam(int i) throw(ConnectionClosedException);
void sendStrParam(const std::string& str) throw(ConnectionClosedException);
int getCode() throw(ConnectionClosedException);
int getByte();
int getInt() throw(ConnectionClosedException);
int getIntParam() throw(ConnectionClosedException, IllegalCommandException);
std::string getStrParam() throw(ConnectionClosedException, IllegalCommandException);
private:
std::shared_ptr<Connection> conn;
};
#endif
<file_sep>/src/clientmessagehandler.h
#ifndef CLIENTMESSAGEHANDLER_H
#define CLIENTMESSAGEHANDLER_H
#include <string>
#include <vector>
#include <memory>
#include "messagehandler.h"
#include "protocol.h"
#include "connectionclosedexception.h"
#include "illegalcommandexception.h"
class ClientMessageHandler {
public:
ClientMessageHandler(std::shared_ptr<MessageHandler>);
std::vector<std::string> listGroups() throw(ConnectionClosedException, IllegalCommandException);
int createGroup(std::string title) throw(ConnectionClosedException, IllegalCommandException);
int deleteGroup(int groupId) throw (ConnectionClosedException, IllegalCommandException);
std::vector<std::string> listArticles(int groupId) throw (ConnectionClosedException, IllegalCommandException);
int createArticle(int groupId, std::string title, std::string author, std::string text) throw(ConnectionClosedException, IllegalCommandException);
int deleteArticle(int groupId, int articleId) throw(ConnectionClosedException, IllegalCommandException);
std::vector<std::string> getArticle(int groupId, int articleId) throw(ConnectionClosedException, IllegalCommandException);
void checkCode(std::string method, int expectedCode, int code) throw(IllegalCommandException);
void checkCondition(bool condition, std::string method, std::string message) throw(IllegalCommandException);
private:
std::shared_ptr<MessageHandler> messageHandler;
};
#endif
<file_sep>/src/clientmessagehandler.cc
#include "clientmessagehandler.h"
using namespace std;
ClientMessageHandler::ClientMessageHandler(std::shared_ptr<MessageHandler> mh): messageHandler(mh) {}
vector<string> ClientMessageHandler::listGroups() throw (ConnectionClosedException, IllegalCommandException){
messageHandler->sendCode(Protocol::COM_LIST_NG);
messageHandler->sendCode(Protocol::COM_END);
int code = messageHandler->getCode();
checkCode("List groups", Protocol::ANS_LIST_NG, code);
int nbrGroups = messageHandler->getIntParam();
checkCondition(nbrGroups >= 0, "List groups", "Number of groups < 0");
vector<string> groupNames(nbrGroups);
for(int i = 0; i < nbrGroups; ++i){
groupNames[i] = to_string(messageHandler->getIntParam()) + ". ";
groupNames[i] = groupNames[i] + messageHandler->getStrParam();
}
code = messageHandler->getCode();
checkCode("List groups", Protocol::ANS_END, code);
return groupNames;
}
int ClientMessageHandler::createGroup(string title) throw (ConnectionClosedException, IllegalCommandException) {
messageHandler->sendCode(Protocol::COM_CREATE_NG);
messageHandler->sendStrParam(title);
messageHandler->sendCode(Protocol::COM_END);
int errorCode = 0;
int code = messageHandler->getCode();
checkCode("Create group", Protocol::ANS_CREATE_NG, code);
code = messageHandler->getCode();
if (code != Protocol::ANS_ACK) {
checkCondition(code == Protocol::ANS_NAK, "Create group",
"Did not receive ANS_ACK or ANS_NAK");
errorCode = messageHandler->getCode();
}
code = messageHandler->getCode();
checkCode("Create group", Protocol::ANS_END, code);
return errorCode;
}
int ClientMessageHandler::deleteGroup(int groupId) throw (ConnectionClosedException, IllegalCommandException) {
messageHandler->sendCode(Protocol::COM_DELETE_NG);
messageHandler->sendIntParam(groupId);
messageHandler->sendCode(Protocol::COM_END);
int errorCode = 0;
int code = messageHandler->getCode();
checkCode("Delete group", Protocol::ANS_DELETE_NG, code);
code = messageHandler->getCode();
if (code != Protocol::ANS_ACK) {
checkCondition(code == Protocol::ANS_NAK, "Create group",
"Did not receive ANS_ACK or ANS_NAK");
errorCode = messageHandler->getCode();
}
code = messageHandler->getCode();
checkCode("Delete group", Protocol::ANS_END, code);
return errorCode;
}
vector<string> ClientMessageHandler::listArticles(int groupId) throw (ConnectionClosedException, IllegalCommandException){
messageHandler->sendCode(Protocol::COM_LIST_ART);
messageHandler->sendIntParam(groupId);
messageHandler->sendCode(Protocol::COM_END);
int code = messageHandler->getCode();
checkCode("List articles", Protocol::ANS_LIST_ART, code);
code = messageHandler->getCode();
if (code != Protocol::ANS_ACK) {
checkCondition(code == Protocol::ANS_NAK, "Create group",
"Did not receive ANS_ACK or ANS_NAK");
code = messageHandler->getCode(); // error code
messageHandler->getCode();
return vector<string>();
}
int nbrArticles = messageHandler->getIntParam();
checkCondition(nbrArticles >= 0, "List articles",
"Number of groups < 0");
vector<string> articleNames(nbrArticles);
for (int i = 0; i < nbrArticles; i++) {
articleNames[i] = to_string(messageHandler->getIntParam()) + ". ";
articleNames[i] = articleNames[i] + messageHandler->getStrParam();
}
code = messageHandler->getCode();
checkCode("List articles", Protocol::ANS_END, code);
return articleNames;
}
int ClientMessageHandler::createArticle(int groupId, string title, string author, string text) throw (ConnectionClosedException,
IllegalCommandException){
messageHandler->sendCode(Protocol::COM_CREATE_ART);
messageHandler->sendIntParam(groupId);
messageHandler->sendStrParam(title);
messageHandler->sendStrParam(author);
messageHandler->sendStrParam(text);
messageHandler->sendCode(Protocol::COM_END);
int errorCode = 0;
int code = messageHandler->getCode();
checkCode("Create article", Protocol::ANS_CREATE_ART, code);
code = messageHandler->getCode();
if (code != Protocol::ANS_ACK) {
checkCondition(code == Protocol::ANS_NAK, "Create group",
"Did not receive ANS_ACK or ANS_NAK");
errorCode = messageHandler->getCode();
}
code = messageHandler->getCode();
checkCode("Create article", Protocol::ANS_END, code);
return errorCode;
}
int ClientMessageHandler::deleteArticle(int groupId, int articleId) throw (ConnectionClosedException, IllegalCommandException){
messageHandler->sendCode(Protocol::COM_DELETE_ART);
messageHandler->sendIntParam(groupId);
messageHandler->sendIntParam(articleId);
messageHandler->sendCode(Protocol::COM_END);
int errorCode = 0;
int code = messageHandler->getCode();
checkCode("Delete article", Protocol::ANS_DELETE_ART, code);
code = messageHandler->getCode();
if (code != Protocol::ANS_ACK) {
checkCondition(code == Protocol::ANS_NAK, "Create group",
"Did not receive ANS_ACK or ANS_NAK");
errorCode = messageHandler->getCode();
}
code = messageHandler->getCode();
checkCode("Delete article", Protocol::ANS_END, code);
return errorCode;
}
vector<string> ClientMessageHandler::getArticle(int groupId, int articleId) throw (ConnectionClosedException, IllegalCommandException){
messageHandler->sendCode(Protocol::COM_GET_ART);
messageHandler->sendIntParam(groupId);
messageHandler->sendIntParam(articleId);
messageHandler->sendCode(Protocol::COM_END);
vector<string> result;
int code = messageHandler->getCode();
checkCode("Get article", Protocol::ANS_GET_ART, code);
code = messageHandler->getCode();
if (code != Protocol::ANS_ACK) {
checkCondition(code == Protocol::ANS_NAK, "Create group",
"Did not receive ANS_ACK or ANS_NAK");
code = messageHandler->getCode();
checkCode("Delete article", Protocol::ANS_END, messageHandler->getCode());
if (code == Protocol::ERR_NG_DOES_NOT_EXIST || code == Protocol::ERR_ART_DOES_NOT_EXIST) {
return vector<string>();
}
} else {
result = vector<string>();
result.push_back("Title: " + messageHandler->getStrParam());
result.push_back("Author: " + messageHandler->getStrParam());
result.push_back("Text: " + messageHandler->getStrParam());
}
code = messageHandler->getCode();
checkCode("Delete article", Protocol::ANS_END, code);
return result;
}
void ClientMessageHandler::checkCode(string method, int expectedCode, int code) throw(IllegalCommandException){
if (code != expectedCode) {
throw IllegalCommandException(method, expectedCode, code);
}
}
void ClientMessageHandler::checkCondition(bool condition, string method, string message) throw(IllegalCommandException){
if (!condition) {
throw new IllegalCommandException(method, message);
}
}
<file_sep>/src/test/myclient.cc
#include "clientmessagehandler.h"
#include <algorithm>
#include <iostream>
#include <cstdlib>
using namespace std;
int commandToInt(string &cmd) {
if (cmd.compare("help") == 0) {
return 0;
} else if (cmd.compare("listng") == 0){
return Protocol::COM_LIST_NG;
} else if (cmd.compare("createng") == 0) {
return Protocol::COM_CREATE_NG;
} else if (cmd.compare("deleteng") == 0) {
return Protocol::COM_DELETE_NG;
} else if (cmd.compare("listart") == 0) {
return Protocol::COM_LIST_ART;
} else if (cmd.compare("readart") == 0) {
return Protocol::COM_GET_ART;
} else if(cmd.compare("createart") == 0) {
return Protocol::COM_CREATE_ART;
} else if (cmd.compare("deleteart") == 0) {
return Protocol::COM_DELETE_ART;
}
return -1;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
cerr << "Required parameters: hostname portnumber" << endl;
exit(1);
}
int port = -1;
try {
port = stoi(argv[2]);
} catch (exception& e) {
cerr << "Port must be an integer." << endl;
exit(1);
}
if (port < 1025) {
cerr << "Port must be > 1024" << endl;
exit(1);
}
Connection* ptr = new Connection(argv[1], stoi(argv[2]));
shared_ptr<Connection> con = shared_ptr<Connection>(ptr);
if (!con->isConnected()) {
cerr << "Connection failed!" << endl;
exit(1);
}
cout << "Connected to server." << endl;
cout << "For a list of commands, input 'help'." << endl;
shared_ptr<MessageHandler> msgptr = make_shared<MessageHandler>(MessageHandler(con));
ClientMessageHandler cmh(msgptr);
string command;
while (cin >> command) {
int c = commandToInt(command);
try {
switch (c) {
case -1 : {
cout << "Invalid command. Use 'help' to see commands." << endl;
break;
}
case 0 : {
cout << "Valid commands:" << endl;
cout << "listng - Lists all newsgroups with id numbers." << endl;
cout << "createng - Creates a new newsgroup." << endl;
cout << "deleteng - Deletes a newsgroup." << endl;
cout << "listart - Lists all articles in a newsgroup." << endl;
cout << "readart - Reads an article in a newsgroup." << endl;
cout << "createart - Creates a new article in a newsgroup." << endl;
cout << "deleteart - Delets an article in a newsgroup." << endl;
break;
}
case Protocol::COM_LIST_NG : {
vector<string> names = cmh.listGroups();
if (names.empty()) {
cout << "There are no newsgroups." << endl;
} else {
cout << "The current newsgroups are: " << endl;
for (string &s : names) {
cout << s << endl;
}
}
break;
}
case Protocol::COM_CREATE_NG : {
string title;
cout << "Choose newsgroup name: ";
cin >> ws;
getline(cin, title);
cmh.createGroup(title);
cout << "Newsgroup created." << endl;
break;
}
case Protocol::COM_DELETE_NG : {
string group_id;
cout << "Newsgroup id number: ";
cin >> group_id;
int gId = -1;
try {
gId = stoi(group_id);
} catch (exception& e) {
cout << "Group id must be a number." << endl;
break;
}
if (cmh.deleteGroup(gId) == 0) {
cout << "Newsgroup deleted." << endl;
} else {
cout << "Invalid newsgroup id." << endl;
}
break;
}
case Protocol::COM_LIST_ART : {
string group_id;
cout << "Newsgroup id number: ";
cin >> group_id;
int gId = -1;
try {
gId = stoi(group_id);
} catch (exception& e) {
cout << "Group id must be a number." << endl;
break;
}
vector<string> arts = cmh.listArticles(gId);
if (arts.empty()) {
cout << "There are no articles in this newsgroup." << endl;
} else {
for (string &s : arts) {
cout << s << endl;
}
}
break;
}
case Protocol::COM_GET_ART :{
string group_id, art_id;
cout << "Newsgroup id number: ";
cin >> group_id;
int gId = -1;
try {
gId = stoi(group_id);
} catch (exception& e) {
cout << "Group id must be a number." << endl;
break;
}
cout << "Article id number: ";
cin >> art_id;
cout << endl;
int aId = -1;
try {
aId = stoi(art_id);
} catch (exception& e) {
cout << "Article id must be a number." << endl;
break;
}
vector<string> artInfo = cmh.getArticle(gId, aId);
if (artInfo.empty()) {
cout << "Article does not exist." << endl;
break;
}
cout << artInfo[0] << " " << artInfo[1] << endl;
cout << artInfo[2] << endl;
break;
}
case Protocol::COM_CREATE_ART : {
string group_id, title, author, text;
cout << "Choose newsgroup id number: ";
cin >> group_id;
int gId = -1;
try {
gId = stoi(group_id);
} catch (exception& e) {
cout << "Group id must be a number." << endl;
break;
}
cout << "Choose a title: ";
cin >> ws;
getline(cin, title);
cout << "Choose author name: ";
cin >> ws;
getline(cin, author);
cout << "Write article: ";
cin >> ws;
getline(cin, text);
if (cmh.createArticle(gId, title, author, text) == 0) {
cout << "Article created." << endl;
} else {
cout << "That newsgroup does not exist." << endl;
}
break;
}
case (Protocol::COM_DELETE_ART) : {
string group_id, art_id;
cout << "Newsgroup id number: ";
cin >> group_id;
int gId = -1;
try {
gId = stoi(group_id);
} catch (exception& e) {
cout << "Newsgroup id must be a number." << endl;
break;
}
cout << "Article id number: ";
cin >> art_id;
int aId = -1;
try {
aId = stoi(art_id);
} catch (exception& e) {
cout << "Article id must be a number." << endl;
break;
}
cout << endl;
if (cmh.deleteArticle(gId, aId) == 0) {
cout << "Article removed." << endl;
} else {
cout << "That article does not exist." << endl;
}
break;
}
}
}
catch (...) {
cerr << "Something went wrong!" << endl;
exit(1);
}
}
}
<file_sep>/Makefile
all:
cd src; make;
cd src/test; make;
clean:
cd src; make clean;
cd src/test; make clean;
install:
cd src/test; make install;
|
17a57c8851fd06e5187c139942124f511cf36896
|
[
"Markdown",
"Makefile",
"C++"
] | 19
|
C++
|
ejaandersson/EDA031
|
056c45317a1933bcff6509ccf2d8d5bbdccd85ac
|
1badbce48b19bf59ada90166bab6c5f0c38285b3
|
refs/heads/master
|
<repo_name>cyhsu14/invsfm<file_sep>/train_visib.py
# Copyright (c) Microsoft Corporation.
# Copyright (c) University of Florida Research Foundation, Inc.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# train_visib.py
# Training script for VisibNet
# Author: <NAME>
import os
import sys
import tensorflow as tf
import numpy as np
import ctrlc
import utils as ut
import load_data_tflo as ld
from models import VisibNet
#########################################################################
parser = ut.MyParser(description='Configure')
parser.add_argument("-log_file", default=False, action='store_true', help="%(type)s: Print stdout and stderr to log and err files")
parser.add_argument("--input_attr", type=str, default='depth_sift_rgb', choices=['depth','depth_sift','depth_rgb','depth_sift_rgb'],
help="%(type)s: Per-point attributes to inlcude in input tensor (default: %(default)s)")
parser.add_argument("--trn_anns", type=str, default='data/anns/demo_5k/train.txt',
help="%(type)s: Path to annotation file for training samples (default: %(default)s)")
parser.add_argument("--val_anns", type=str, default='data/anns/demo_5k/val.txt',
help="%(type)s: Path to annotation file for validation samples (default: %(default)s)")
parser.add_argument("--batch_size", type=int, default=4, help="%(type)s: Number of images in batch (default: %(default)s)")
parser.add_argument("--crop_size", type=int, default=256, help="%(type)s: Size to crop images to (default: %(default)s)")
parser.add_argument("--scale_size", type=lambda s: [int(i) for i in s.split(',')], default=[296,394,512],
help="int,int,int: Sizes to randomly scale images to before cropping them (default: 296,394,512)")
parser.add_argument("--pct_3D_points", type=lambda s: [float(i) for i in s.split(',')][:2], default=[5.,100.],
help="float,float: Min and max percent of 3D points to keep when performing random subsampling for data augmentation "+\
"(default: 5.,100.)")
parser.add_argument("--vis_thresh", type=float, default=.05, help="%(type)s: Threshold used to compute ground truth visibility mask."+\
"i.e., gt_visibibility_mask = ((inp_depth-gt_depth)/gt_depth) > VISIB_THRESH. (default: %(default)s)")
parser.add_argument("--max_iter", type=int, default=1e6, help="%(type)s: Stop training after MAX_ITER iterations (default: %(default)s)")
parser.add_argument("--log_freq", type=int, default=25, help="%(type)s: Log training stats every LOG_FREQ iterations (default: %(default)s)")
parser.add_argument("--chkpt_freq", type=int, default=1e4, help="%(type)s: Save model state every CHKPT_FREQ iterations. Previous model state "+\
"is deleted after each new save (default: %(default)s)")
parser.add_argument("--save_freq", type=int, default=5e4, help="%(type)s: Permanently save model state every SAVE_FREQ iterations "+\
"(default: %(default)s)")
parser.add_argument("--val_freq", type=int, default=5e3, help="%(type)s: Run validation loop every VAL_FREQ iterations (default: %(default)s)")
parser.add_argument("--val_iter", type=int, default=128, help="%(type)s: Number of validation samples per validation loop (default: %(default)s)")
parser.add_argument("--adam_eps", type=float, default=1e-8, help="%(type)s: Epsilon parameter for adam optimizer (default: %(default)s)")
parser.add_argument("--adam_mom", type=float, default=.9, help="%(type)s: Momentum parameter for adam optimizer (default: %(default)s)")
parser.add_argument("--adam_lr", type=float, default=1e-5, help="%(type)s: Learning rate parameter for adam optmizer (default: %(default)s)")
prm = parser.parse_args()
prm_str = 'Arguments:\n'+'\n'.join(['{} {}'.format(k.upper(),v) for k,v in vars(prm).items()])
print(prm_str+'\n')
#########################################################################
# Create exp dir if does not exist
exp_dir = 'wts/{}/visibnet'.format(prm.input_attr)
os.system('mkdir -p {}'.format(exp_dir))
# redirect stdout and stderr to log files
if prm.log_file:
sys.stdout = open(exp_dir+'/train.log', 'a')
sys.stderr = open(exp_dir+'/info.log', 'a')
# Check for saved weights & find iter
vsave = ut.ckpter(exp_dir+'/iter_*.vmodel.npz')
osave = ut.ckpter(exp_dir+'/iter_*.opt.npz')
vpath = lambda itr: '%s/iter_%07d.vmodel.npz'%(exp_dir,itr)
opath = lambda itr: '%s/iter_%07d.opt.npz'%(exp_dir,itr)
niter = vsave.iter
# Load annotations
ut.mprint("Loading annotations")
tbchr = ut.batcher(prm.trn_anns,prm.batch_size,niter)
vbchr = ut.batcher(prm.val_anns,prm.batch_size,niter)
ut.mprint("Done!")
#########################################################################
# Set up data fetch
camera_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
pts_xyz_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
pts_rgb_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
pts_sift_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
gt_depth_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
getfeed = lambda fps: \
dict([(ph,'data/'+fps[i,3]) for i,ph in enumerate(camera_fps)]+\
[(ph,'data/'+fps[i,0]) for i,ph in enumerate(pts_xyz_fps)]+\
[(ph,'data/'+fps[i,2]) for i,ph in enumerate(pts_sift_fps)]+\
[(ph,'data/'+fps[i,1]) for i,ph in enumerate(pts_rgb_fps)]+\
[(ph,'data/'+fps[i,5]) for i,ph in enumerate(gt_depth_fps)])
gt_depth = ld.load_img_bch(gt_depth_fps,prm.crop_size,prm.scale_size,isval=False,binary=True)
proj_depth,proj_sift,proj_rgb = ld.load_proj_bch(camera_fps,pts_xyz_fps,pts_sift_fps,pts_rgb_fps,
prm.crop_size,prm.scale_size,isval=False)
pd_b=[]; ps_b=[]; pr_b=[]; is_visible=[]; is_valid=[]
keep_prob = tf.random_uniform([prm.batch_size],minval=prm.pct_3D_points[0]/100.,
maxval=prm.pct_3D_points[1]/100.,dtype=tf.float32,seed=niter)
for i in range(prm.batch_size):
# Get visible points
proj_is_val = tf.to_float(tf.greater(proj_depth[i], 0.))
gt_is_val = tf.to_float(tf.greater(gt_depth[i], 0.))
is_val = proj_is_val*gt_is_val
pd = proj_depth[i]*is_val
ps = proj_sift[i]*is_val
pr = proj_rgb[i]*is_val
pct_diff = (pd-gt_depth[i])/(gt_depth[i]+1e-8)
is_vis = tf.to_float(tf.less(pct_diff,prm.vis_thresh))*is_val
# dropout (1-keep_prob)% of projected pts
pd = tf.nn.dropout(pd,keep_prob[i],noise_shape=[prm.crop_size,prm.crop_size,1],seed=niter)*keep_prob[i]
ps = tf.nn.dropout(ps,keep_prob[i],noise_shape=[prm.crop_size,prm.crop_size,1],seed=niter)*keep_prob[i]
pr = tf.nn.dropout(pr,keep_prob[i],noise_shape=[prm.crop_size,prm.crop_size,1],seed=niter)*keep_prob[i]
is_vis = tf.nn.dropout(is_vis,keep_prob[i],noise_shape=[prm.crop_size,prm.crop_size,1],seed=niter)*keep_prob[i]
is_val = tf.nn.dropout(is_val,keep_prob[i],noise_shape=[prm.crop_size,prm.crop_size,1],seed=niter)*keep_prob[i]
pd_b.append(tf.reshape(pd,[1,prm.crop_size,prm.crop_size,1]))
ps_b.append(tf.reshape(ps,[1,prm.crop_size,prm.crop_size,128]))
pr_b.append(tf.reshape(pr,[1,prm.crop_size,prm.crop_size,3]))
is_visible.append(tf.reshape(is_vis,[1,prm.crop_size,prm.crop_size,1]))
is_valid.append(tf.reshape(is_val,[1,prm.crop_size,prm.crop_size,1]))
proj_depth = tf.concat(pd_b,axis=0)
proj_sift = tf.concat(ps_b,axis=0) / 127.5 - 1.
proj_rgb = tf.concat(pr_b,axis=0) / 127.5 - 1.
is_visible = tf.concat(is_visible,axis=0)
is_valid = tf.concat(is_valid,axis=0)
#########################################################################
if prm.input_attr=='depth':
vinp = proj_depth
vinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,1]
elif prm.input_attr=='depth_sift':
vinp = tf.concat((proj_depth,proj_sift),axis=3)
vinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,129]
elif prm.input_attr=='depth_rgb':
vinp = tf.concat((proj_depth,proj_rgb),axis=3)
vinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,4]
elif prm.input_attr=='depth_sift_rgb':
vinp = tf.concat((proj_depth,proj_rgb,proj_sift),axis=3)
vinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,132]
# Set up pre-fetching
vinp_b0 = tf.Variable(tf.zeros(vinp_sz,dtype=tf.float32))
vinp_b1 = tf.Variable(tf.zeros(vinp_sz,dtype=tf.float32))
vgt = tf.concat([is_visible,is_valid],axis=3)
vgt_sz = [prm.batch_size,prm.crop_size,prm.crop_size,2]
vgt_b0 = tf.Variable(tf.zeros(vgt_sz,dtype=tf.float32))
vgt_b1 = tf.Variable(tf.zeros(vgt_sz,dtype=tf.float32))
tldr_fetchOp = [vinp_b0.assign(vinp).op, vgt_b0.assign(vgt).op]
vldr_fetchOp = [vinp_b1.assign(vinp).op, vgt_b1.assign(vgt).op]
tldr_swapOp = [vinp_b1.assign(vinp_b0).op, vgt_b1.assign(vgt_b0).op]
# Init coarse inverter
V = VisibNet(vinp_b1,bn='train',outp_act=False)
vpred = V.pred
#########################################################################
# Set optimizer
vvars = V.trainable_variables()
optV = tf.train.AdamOptimizer(prm.adam_lr,prm.adam_mom,epsilon=prm.adam_eps)
mask = tf.reshape(vgt_b1[:,:,:,1],[-1,1])
logs = tf.boolean_mask(tf.reshape(vpred,[-1,1]),mask)
lbls = tf.boolean_mask(tf.reshape(vgt_b1[:,:,:,0],[-1,1]),mask)
vloss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=lbls,logits=logs))
vacc = tf.reduce_mean(tf.to_float(tf.equal(lbls,tf.to_float(tf.greater(tf.sigmoid(logs),0.5)))))
vStep = optV.minimize(vloss,var_list=list(vvars.keys()))
#########################################################################
# Start TF session (respecting OMP_NUM_THREADS)
try: init_all_vars = tf.global_variables_initializer()
except: init_all_vars = tf.initialize_all_variables()
nthr = os.getenv('OMP_NUM_THREADS')
if nthr is None: sess=tf.Session()
else: sess=tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=int(nthr)))
sess.run(init_all_vars)
#########################################################################
# Load saved models & optimizers
# Load C wts
if vsave.latest != None:
ut.mprint("Restoring V from " + vsave.latest )
V.load(sess,vsave.latest)
ut.mprint("Done!")
# Load optimizers
optlist = [[optV,vvars]]
if osave.latest is not None:
ut.mprint("Restoring optimizers from " + osave.latest )
ut.loadopts(osave.latest,optlist,[],sess)
ut.mprint("Done!")
#########################################################################
# Main Training loop
sess.run(V.set_ifdo)
saviter = niter
tLossAcc=[]
vlog=''
fd=getfeed(tbchr.get_batch())
sess.run(tldr_fetchOp,feed_dict=fd)
ut.mprint("Starting from Iteration %d" % niter)
while not ctrlc.stop and niter < prm.max_iter:
# Val loop
if niter % prm.val_freq == 0:
ut.mprint("Validating networks")
sess.run(V.unset_ifdo)
vLossAcc=[];
for i in range(0,prm.val_iter):
try: # prevent occasional failure when no pts in projection
fps=vbchr.get_batch()
fd=getfeed(fps)
sess.run(vldr_fetchOp,feed_dict=fd)
vLossAcc.append(sess.run([vloss,vacc]))
except:
pass
sess.run(V.set_ifdo)
args = list(np.mean(vLossAcc,axis=0))
vlog=' val.loss {:.6f} val.acc {:.6f}'.format(*args)
# Swap data buffers
sess.run(tldr_swapOp)
# Set up nxt data fetch op
fps=tbchr.get_batch()
fd=getfeed(fps)
# Update vnet
try: # prevent occasional failure when no pts in projection
tLossAcc.append(sess.run([vloss,vacc,vStep]+tldr_fetchOp,feed_dict=fd)[:2])
except:
pass
# Print training loss & accuracy
niter+=1
if niter % prm.log_freq == 0:
args = [niter]+list(np.mean(tLossAcc,axis=0))
tlog = '[{:09d}] . trn.loss {:.6f} trn.acc {:.6f}'.format(*args)
ut.mprint(tlog+vlog)
tLossAcc=[]; vlog='';
# Save models
if niter % prm.chkpt_freq == 0:
#Save VisibNet
V.save(sess,vpath(niter))
vsave.clean(every=prm.save_freq,last=1)
ut.mprint("Saved weights to "+vpath(niter))
# Save Optimizers
ut.saveopts(opath(niter),optlist,{},sess)
osave.clean(last=1)
ut.mprint("Saved optimizers to "+opath(niter))
# Save models & optimizers
if niter > vsave.iter:
# Save VisibNet
V.save(sess,vpath(niter))
vsave.clean(every=prm.save_freq,last=1)
ut.mprint("Saved weights to "+vpath(niter))
# Save Optimizers
ut.saveopts(opath(niter),optlist,{},sess)
osave.clean(last=1)
ut.mprint("Saved optimizers to "+opath(niter))
<file_sep>/models.py
# Copyright (c) Microsoft Corporation.
# Copyright (c) University of Florida Research Foundation, Inc.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# models.py
# Contains all model definitions
# Author: <NAME>
import tensorflow as tf
import numpy as np
# Base Model
class Net(object):
def __init__(self):
self.weights = {}
# Save weights to an npz file
def save(self,sess,fname):
wts = {k:sess.run(v) for k,v in self.weights.items()}
np.savez(fname,**wts)
return wts
# Load weights from an npz file
def load(self,sess,fname=None):
wts = np.load(fname)
ops = [v.assign(wts[k].astype(np.float32)).op
for k,v in self.weights.items() if k in wts]
if len(ops) > 0:
sess.run(ops)
# Get all trainable weights
def trainable_variables(self):
return {v:k for k,v in self.weights.items() if v in tf.trainable_variables()}
# Base Model for VisibNet, CaarseNet and RefineNet
class InvNet(Net):
def __init__(self, inp,
bn='train',
ech = [256,256,256,512,512,512],
dch = [512,512,512,256,256,256,128,64,32,3],
skip_conn = 6,
conv_act = 'relu',
outp_act = 'tanh'):
super().__init__()
self.bn = bn
self.weights = {}
self.ifdo = tf.Variable(False,dtype=tf.bool)
self.set_ifdo = self.ifdo.assign(True).op
self.unset_ifdo = self.ifdo.assign(False).op
#Encoder
out = inp; skip = [out]
for i in range(len(ech)):
out = self.conv(out,4,ech[i],2,True,1.,conv_act,'ec%d'%i)
skip.append(out)
skip = list(reversed(skip))[1:]
# Decoder
for i in range(len(dch)-1):
if i<len(ech): out = tf.image.resize_images(out,tf.shape(out)[1:3]*2,method=1)
out = self.conv(out,3,dch[i],1,True,.5 if i<3 else 1.,conv_act,'dc%d'%i)
if i<skip_conn: out = tf.concat((skip[i],out),axis=3)
self.pred = self.conv(out,3,dch[-1],1,False,1.,outp_act,'dc%d'%(len(dch)-1))
# Covolutional layer with Batchnorm, Bias, Dropout & Activation
def conv(self,inp,ksz,nch,stride,bn,rate,act,nm):
# Conv
ksz = [ksz,ksz,inp.get_shape().as_list()[-1],nch]
sq = np.sqrt(3.0 / np.float32(ksz[0]*ksz[1]*ksz[2]))
self.weights['%s_w'%nm] = tf.Variable(tf.random_uniform(ksz,minval=-sq,maxval=sq,dtype=tf.float32))
out = tf.pad(inp,[[0,0],[1,1],[1,1],[0,0]],'REFLECT')
out = tf.nn.conv2d(out,self.weights['%s_w'%nm],[1,stride,stride,1],'VALID')
# Batchnorm
if bn:
if self.bn=='train' or self.bn=='set':
axis = list(range(len(out.get_shape().as_list())-1))
wmn = tf.reduce_mean(out,axis)
wvr = tf.reduce_mean(tf.squared_difference(out,wmn),axis)
out = tf.nn.batch_normalization(out,wmn,wvr,None,None,1e-3)
if self.bn=='set':
self.weights['%s_mn'%nm] = tf.Variable(tf.zeros([nch],dtype=tf.float32))
self.weights['%s_vr'%nm] = tf.Variable(tf.ones([nch],dtype=tf.float32))
self.bn_outs['%s_mn'%nm] = wmn
self.bn_outs['%s_vr'%nm] = wvr
if self.bn=='test':
self.weights['%s_mn'%nm] = tf.Variable(tf.zeros([nch],dtype=tf.float32))
self.weights['%s_vr'%nm] = tf.Variable(tf.ones([nch],dtype=tf.float32))
out = tf.nn.batch_normalization(out,self.weights['%s_mn'%nm],
self.weights['%s_vr'%nm],None,None,1e-3)
# Bias
self.weights['%s_b'%nm] = tf.Variable(tf.zeros([nch],dtype=tf.float32))
out = out + self.weights['%s_b'%nm]
# Dropout
if rate < 1:
out = tf.cond(self.ifdo, lambda: tf.nn.dropout(out,rate), lambda: out)
# Activation
if act=='relu':
out = tf.nn.relu(out)
elif act=='lrelu':
out = tf.nn.leaky_relu(out)
elif act=='sigm':
out = tf.nn.sigmoid(out)
elif act=='tanh':
out = tf.nn.tanh(out)
return out
# VisibNet
class VisibNet(InvNet):
def __init__(self,inp,bn='train',outp_act=True):
if inp.get_shape().as_list()[-1] < 5:
ech = [64,128,256,512,512,512]
else:
ech = [256,256,256,512,512,512]
super().__init__(inp,bn=bn,
ech = ech,
dch = [512,512,512,256,256,256,128,64,32,1],
skip_conn = 6,
conv_act = 'relu',
outp_act = 'sigm' if outp_act else None)
# CoarseNet
class CoarseNet(InvNet):
def __init__(self,inp,bn='train',outp_act=True):
super().__init__(inp,bn=bn,
ech = [256,256,256,512,512,512],
dch = [512,512,512,256,256,256,128,64,32,3],
skip_conn = 6,
conv_act = 'relu',
outp_act = 'tanh' if outp_act else None)
# RefineNet
class RefineNet(InvNet):
def __init__(self,inp,bn='train',outp_act=True):
super().__init__(inp,bn=bn,
ech = [256,256,256,512,512,512],
dch = [512,512,512,256,256,256,128,64,32,3],
skip_conn = 4,
conv_act = 'lrelu',
outp_act = 'tanh' if outp_act else None)
# Convolutional layers of VGG16
class VGG16(Net):
def __init__(self,inp,stop_layer=''):
super().__init__()
self.pred = {}
# Subtract channel means
mean = tf.constant([123.68,116.779,103.939], dtype=tf.float32, shape=[1,1,1,3])
out = inp-mean
# Set up convolution layers
numl = [2,2,3,3,3]
numc = [64,128,256,512,512]
for i in range(len(numl)):
for j in range(numl[i]):
nm = 'conv{}_{}'.format(i+1,j+1)
if nm+'_W' not in self.weights:
ksz = [3,3,out.get_shape().as_list()[-1],numc[i]]
self.weights[nm+'_W']=tf.Variable(tf.truncated_normal(ksz,dtype=tf.float32,stddev=1e-1), trainable=False)
self.weights[nm+'_b']=tf.Variable(tf.zeros(numc[i], dtype=tf.float32), trainable=False)
out = tf.nn.conv2d(out, self.weights[nm+'_W'], [1,1,1,1], padding='SAME')
out = tf.nn.bias_add(out, self.weights[nm+'_b'])
out = tf.nn.relu(out)
self.pred[nm] = out
if nm == stop_layer:
return
out = tf.nn.max_pool(out,ksize=[1,2,2,1],strides=[1,2,2,1],padding='VALID')
nm = 'pool{}'.format(i+1)
self.pred[nm] = out
if nm == stop_layer:
return
# Discriminator network for training RefineNet
class Discriminator(Net):
def __init__(self):
super().__init__()
self.ifdo = tf.Variable(False,dtype=tf.bool)
self.set_ifdo = self.ifdo.assign(True).op
self.unset_ifdo = self.ifdo.assign(False).op
def pred(self,inp):
ncls = 2
out = inp[0]
# conv layers
cch = [256, 256, 256, 512, 512]
for i,ch in enumerate(cch):
if i > 0 and i < len(inp):
out = tf.concat((inp[i],out),axis=3)
out = self.conv(out,3,ch,1,True,1,'lrelu','SAME','c%d'%i)
out = tf.nn.max_pool(out,ksize=[1,2,2,1],strides=[1,2,2,1],padding='VALID')
# fc layers
fch = [1024,1024,1024]
for i,ch in enumerate(fch):
out = self.conv(out,out.get_shape().as_list()[2],ch,1,False,.5,'lrelu','VALID','fc%d'%i)
out = self.conv(out,out.get_shape().as_list()[2],ncls,1,False,1,False,'VALID','fc%d'%(len(fch)+1))
return tf.reshape(out,[-1,ncls])
# Covolutional layer with Batchnorm, Bias, Dropout & Activation
def conv(self,inp,ksz,nch,stride,bn,rate,act,pad,nm):
# Conv
ksz = [ksz,ksz,inp.get_shape().as_list()[-1],nch]
sq = np.sqrt(3.0 / np.float32(ksz[0]*ksz[1]*ksz[2]))
if '%s_w'%nm not in self.weights:
self.weights['%s_w'%nm] = tf.Variable(tf.random_uniform(ksz,minval=-sq,maxval=sq,dtype=tf.float32))
out = tf.nn.conv2d(inp,self.weights['%s_w'%nm],[1,stride,stride,1],pad)
# Batchnorm
if bn:
axis = list(range(len(out.get_shape().as_list())-1))
wmn = tf.reduce_mean(out,axis)
wvr = tf.reduce_mean(tf.squared_difference(out,wmn),axis)
out = tf.nn.batch_normalization(out,wmn,wvr,None,None,1e-3)
# Bias
if '%s_b'%nm not in self.weights:
self.weights['%s_b'%nm] = tf.Variable(tf.zeros([nch],dtype=tf.float32))
out = out + self.weights['%s_b'%nm]
# Activation
if act=='lrelu':
out = tf.nn.leaky_relu(out)
# Dropout
if rate < 1:
out = tf.cond(self.ifdo, lambda: tf.nn.dropout(out,rate), lambda: out)
return out
<file_sep>/download_wts.sh
# download_wts.sh
# Get pre-trained model wts (1.24G) from gdrive
wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1D2uYQmrZaZPngDi1U8aSPoXdzuAnEwhb' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1D2uYQmrZaZPngDi1U8aSPoXdzuAnEwhb" -O wts.tar.gz && rm -rf /tmp/cookies.txt
# Untar file
echo "Untarring wts.tar.gz"
tar -xf wts.tar.gz
<file_sep>/README.md
# InvSFM: Revealing Scenes by Inverting Structure from Motion Reconstructions

**Synthesizing Imagery from a SFM Point Cloud:** From left to right--Top view of a SfM reconstruction of an indoor scene; 3D points projected into a viewpoint associated with a source image; the image reconstructed using our technique; and the source image. </p>
<br/>
This repository contains a reference implementation of the algorithms described in the CVPR 2019 paper [**Revealing Scenes by Inverting Structutre from Motion Reconstructions**](http://openaccess.thecvf.com/content_CVPR_2019/papers/Pittaluga_Revealing_Scenes_by_Inverting_Structure_From_Motion_Reconstructions_CVPR_2019_paper.pdf). This paper was selected as a **Best Paper Finalist** at CVPR 2019. For more details about the project, please visit the main [project page](https://www.francescopittaluga.com/invsfm/index.html).
If you use this code/model for your research, please cite the following paper:
```
@inproceedings{pittaluga2019revealing,
title={Revealing scenes by inverting structure from motion reconstructions},
author={<NAME> and <NAME>},
booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},
pages={145--154},
year={2019}
}
```
## Installation Guide
The code was tested with Tensorflow 1.10, Ubuntu 16, NVIDIA TitanX / NVIDIA 1080ti.
### Step 1: Install dependencies
See `requirements.txt`. The training code depends only on tensorflow. The demos additionally depend on Pillow and scikit-image.
### Step 2: Download the pre-trained model weights
Run `$ bash download_wts.sh` to programatically download and untar `wts.tar.gz` (1.24G). Alternatively, manually download `wts.tar.gz` from [here](https://drive.google.com/open?id=1D2uYQmrZaZPngDi1U8aSPoXdzuAnEwhb) and untar it in the root directory of the repo.
### Step 3: Download the demo data
Run `$ bash download_data.sh` to programatically download and untar `data.tar.gz` (11G). Alternatively, manually download `data.tar.gz` from [here](https://drive.google.com/open?id=1StpUiEauckZcxHZeBzoq6L2K7pcB9v3E) and untar it in the root directory of the repo.
### Step 4: Run the demos
```
$ python demo_5k.py
$ python demo_colmap.py
```
Note: Run `$ python demo_5k.py --help` and `$ python demo_colmap.py --help` to see the various demo options available.
### Step 5: Run the training scripts
```
$ python train_visib.py
$ python train_coarse.py
$ python train_refine.py
```
Note: Run `$ python train_*.py --help` to see the various training options available.
<file_sep>/train_coarse.py
# Copyright (c) Microsoft Corporation.
# Copyright (c) University of Florida Research Foundation, Inc.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# train_coarse.py
# Training script for CoarseNet
# Author: <NAME>
import os
import sys
import tensorflow as tf
import numpy as np
import ctrlc
import utils as ut
import load_data_tflo as ld
from models import VisibNet
from models import CoarseNet
from models import VGG16
#########################################################################
parser = ut.MyParser(description='Configure')
parser.add_argument("-log_file", default=False, action='store_true', help="%(type)s: Print stdout and stderr to log and err files")
parser.add_argument("--input_attr", type=str, default='depth_sift_rgb', choices=['depth','depth_sift','depth_rgb','depth_sift_rgb'],
help="%(type)s: Per-point attributes to inlcude in input tensor (default: %(default)s)")
parser.add_argument("--trn_anns", type=str, default='data/anns/demo_5k/train.txt',
help="%(type)s: Path to annotation file for training samples (default: %(default)s)")
parser.add_argument("--val_anns", type=str, default='data/anns/demo_5k/val.txt',
help="%(type)s: Path to annotation file for validation samples (default: %(default)s)")
parser.add_argument("--vnet_model", type=str, default=None, help="%(type)s: Path to pre-trained VisibNet model")
parser.add_argument("--vgg16_model", type=str, default='wts/vgg16.model.npz', help="%(type)s: Path to pre-trained vgg16 model (default: %(default)s)")
parser.add_argument("--batch_size", type=int, default=4, help="%(type)s: Number of images in batch (default: %(default)s)")
parser.add_argument("--crop_size", type=int, default=256, help="%(type)s: Size to crop images to (default: %(default)s)")
parser.add_argument("--scale_size", type=lambda s: [int(i) for i in s.split(',')], default=[296,394,512],
help="int,int,int: Sizes to randomly scale images to before cropping them (default: 296,394,512)")
parser.add_argument("--pct_3D_points", type=lambda s: [float(i) for i in s.split(',')][:2], default=[5.,100.],
help="float,float: Min and max percent of 3D points to keep when performing random subsampling for data augmentation "+\
"(default: 5.,100.)")
parser.add_argument("--per_loss_wt", type=float, default=1., help="%(type)s: Perceptual loss weight (default: %(default)s)")
parser.add_argument("--pix_loss_wt", type=float, default=1., help="%(type)s: Pixel loss weight (default: %(default)s)")
parser.add_argument("--max_iter", type=int, default=1e6, help="%(type)s: Stop training after MAX_ITER iterations (default: %(default)s)")
parser.add_argument("--log_freq", type=int, default=25, help="%(type)s: Log training stats every LOG_FREQ iterations (default: %(default)s)")
parser.add_argument("--chkpt_freq", type=int, default=1e4, help="%(type)s: Save model state every CHKPT_FREQ iterations. Previous model state "+\
"is deleted after each new save (default: %(default)s)")
parser.add_argument("--save_freq", type=int, default=5e4, help="%(type)s: Permanently save model state every SAVE_FREQ iterations "+\
"(default: %(default)s)")
parser.add_argument("--val_freq", type=int, default=5e3, help="%(type)s: Run validation loop every VAL_FREQ iterations (default: %(default)s)")
parser.add_argument("--val_iter", type=int, default=128, help="%(type)s: Number of validation samples per validation loop (default: %(default)s)")
parser.add_argument("--adam_eps", type=float, default=1e-8, help="%(type)s: Epsilon parameter for adam optimizer (default: %(default)s)")
parser.add_argument("--adam_mom", type=float, default=.9, help="%(type)s: Momentum parameter for adam optimizer (default: %(default)s)")
parser.add_argument("--adam_lr", type=float, default=1e-4, help="%(type)s: Learning rate parameter for adam optmizer (default: %(default)s)")
prm = parser.parse_args()
prm_str = 'Arguments:\n'+'\n'.join(['{} {}'.format(k.upper(),v) for k,v in vars(prm).items()])
print(prm_str+'\n')
#########################################################################
# Create exp dir if does not exist
exp_dir = 'wts/{}/coarsenet'.format(prm.input_attr)
os.system('mkdir -p {}'.format(exp_dir))
# set path to visibnet wts for demo
if prm.vnet_model == None:
prm.vnet_model = 'wts/pretrained/{}/visibnet.model.npz'.format(prm.input_attr)
# redirect stdout and stderr to log files
if prm.log_file:
sys.stdout = open(exp_dir+'/train.log', 'a')
sys.stderr = open(exp_dir+'/info.log', 'a')
# Check for saved weights & find iter
csave = ut.ckpter(exp_dir+'/iter_*.cmodel.npz')
osave = ut.ckpter(exp_dir+'/iter_*.opt.npz')
cpath = lambda itr: '%s/iter_%07d.cmodel.npz'%(exp_dir,itr)
opath = lambda itr: '%s/iter_%07d.opt.npz'%(exp_dir,itr)
niter = csave.iter
# Load annotations
ut.mprint("Loading annotations")
tbchr = ut.batcher(prm.trn_anns,prm.batch_size,niter)
vbchr = ut.batcher(prm.val_anns,prm.batch_size,niter)
ut.mprint("Done!")
#########################################################################
# Set up data fetch
camera_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
pts_xyz_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
pts_rgb_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
pts_sift_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
gt_rgb_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
getfeed = lambda fps: \
dict([(ph,'data/'+fps[i,3]) for i,ph in enumerate(camera_fps)]+\
[(ph,'data/'+fps[i,0]) for i,ph in enumerate(pts_xyz_fps)]+\
[(ph,'data/'+fps[i,2]) for i,ph in enumerate(pts_sift_fps)]+\
[(ph,'data/'+fps[i,1]) for i,ph in enumerate(pts_rgb_fps)]+\
[(ph,'data/'+fps[i,4]) for i,ph in enumerate(gt_rgb_fps)])
gt_rgb = ld.load_img_bch(gt_rgb_fps,prm.crop_size,prm.scale_size,isval=False,binary=False)
proj_depth,proj_sift,proj_rgb = ld.load_proj_bch(camera_fps,pts_xyz_fps,pts_sift_fps,pts_rgb_fps,
prm.crop_size,prm.scale_size,isval=False)
pd_b=[]; ps_b=[]; pr_b=[]; is_visible=[]; is_valid=[]
keep_prob = tf.random_uniform([prm.batch_size],minval=prm.pct_3D_points[0]/100.,
maxval=prm.pct_3D_points[1]/100.,dtype=tf.float32,seed=niter)
for i in range(prm.batch_size):
# Get valid points
is_val = tf.to_float(tf.greater(proj_depth[i], 0.))
pd = proj_depth[i]*is_val
ps = proj_sift[i]*is_val
pr = proj_rgb[i]*is_val
# dropout (1-keep)% of projected pts
pd = tf.nn.dropout(pd,keep_prob[i],noise_shape=[prm.crop_size,prm.crop_size,1],seed=niter)*keep_prob[i]
ps = tf.nn.dropout(ps,keep_prob[i],noise_shape=[prm.crop_size,prm.crop_size,1],seed=niter)*keep_prob[i]
pr = tf.nn.dropout(pr,keep_prob[i],noise_shape=[prm.crop_size,prm.crop_size,1],seed=niter)*keep_prob[i]
pd_b.append(tf.reshape(pd,[1,prm.crop_size,prm.crop_size,1]))
ps_b.append(tf.reshape(ps,[1,prm.crop_size,prm.crop_size,128]))
pr_b.append(tf.reshape(pr,[1,prm.crop_size,prm.crop_size,3]))
proj_depth = tf.concat(pd_b,axis=0)
proj_sift = tf.concat(ps_b,axis=0)
proj_rgb = tf.concat(pr_b,axis=0)
#########################################################################
# Init visibnet
if prm.input_attr=='depth':
vinp = proj_depth
elif prm.input_attr=='depth_sift':
vinp = tf.concat((proj_depth,proj_sift/127.5-1.),axis=3)
elif prm.input_attr=='depth_rgb':
vinp = tf.concat((proj_depth,proj_rgb/127.5-1.),axis=3)
elif prm.input_attr=='depth_sift_rgb':
vinp = tf.concat((proj_depth,proj_rgb/127.5-1.,proj_sift/127.5-1.),axis=3)
V = VisibNet(vinp,bn='test',outp_act=True)
vpred = tf.cast(tf.greater(V.pred,0.5),tf.float32)
# Set up pre-fetching for coarsnet
if prm.input_attr=='depth':
cinp = proj_depth*vpred
cinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,1]
elif prm.input_attr=='depth_sift':
cinp = tf.concat((proj_depth*vpred, proj_sift*vpred/127.5-1.),axis=3)
cinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,129]
elif prm.input_attr=='depth_rgb':
cinp = tf.concat((proj_depth*vpred, proj_rgb*vpred/127.5-1.),axis=3)
cinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,4]
elif prm.input_attr=='depth_sift_rgb':
cinp = tf.concat((proj_depth*vpred, proj_sift*vpred/127.5-1., proj_rgb*vpred/127.5-1.),axis=3)
cinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,132]
cinp_b0 = tf.Variable(tf.zeros(cinp_sz,dtype=tf.float32))
cinp_b1 = tf.Variable(tf.zeros(cinp_sz,dtype=tf.float32))
cgt = gt_rgb
cgt_sz = [prm.batch_size,prm.crop_size,prm.crop_size,3]
cgt_b0 = tf.Variable(tf.zeros(cgt_sz,dtype=tf.float32))
cgt_b1 = tf.Variable(tf.zeros(cgt_sz,dtype=tf.float32))
tldr_fetchOp = [cinp_b0.assign(cinp).op, cgt_b0.assign(cgt).op]
vldr_fetchOp = [cinp_b1.assign(cinp).op, cgt_b1.assign(cgt).op]
tldr_swapOp = [cinp_b1.assign(cinp_b0).op, cgt_b1.assign(cgt_b0).op]
# Init coarsenet
C = CoarseNet(cinp_b1,bn='train',outp_act=False)
cpred = (C.pred+1.)*127.5
# Init perceptual network
pinp = tf.concat((cgt_b1,cpred),axis=0)
P = VGG16(pinp,stop_layer='conv3_3')
ppred = P.pred
#########################################################################
# Set optimizer
cvars = C.trainable_variables()
optC = tf.train.AdamOptimizer(prm.adam_lr,prm.adam_mom,epsilon=prm.adam_eps)
# Set C loss
cpixloss = tf.reduce_mean(tf.abs(cgt_b1-cpred))
cperloss = (tf.reduce_mean(tf.squared_difference(ppred['conv1_1'][:prm.batch_size],ppred['conv1_1'][prm.batch_size:])) + \
tf.reduce_mean(tf.squared_difference(ppred['conv2_2'][:prm.batch_size],ppred['conv2_2'][prm.batch_size:])) + \
tf.reduce_mean(tf.squared_difference(ppred['conv3_3'][:prm.batch_size],ppred['conv3_3'][prm.batch_size:]))) / 3
closs = prm.pix_loss_wt*cpixloss+prm.per_loss_wt*cperloss
cStep = optC.minimize(closs,var_list=list(cvars.keys()))
#########################################################################
# Start TF session (respecting OMP_NUM_THREADS)
try: init_all_vars = tf.global_variables_initializer()
except: init_all_vars = tf.initialize_all_variables()
nthr = os.getenv('OMP_NUM_THREADS')
if nthr is None: sess=tf.Session()
else: sess=tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=int(nthr)))
sess.run(init_all_vars)
#########################################################################
# Load saved models & optimizers
# Load VGG wts
ut.mprint("Restoring VGG16 from " + prm.vgg16_model )
P.load(sess,prm.vgg16_model)
ut.mprint("Done!")
# Load VisibNet wts
ut.mprint("Restoring VisibNet from " + prm.vnet_model )
V.load(sess,prm.vnet_model)
ut.mprint("Done!")
sess.run(V.unset_ifdo)
# Load CoarseNet wts
if csave.latest != None:
ut.mprint("Restoring CoarseNet from " + csave.latest )
C.load(sess,csave.latest)
ut.mprint("Done!")
# Load optimizers
optlist = [[optC,cvars]]
if osave.latest != None:
ut.mprint("Restoring optimizers from " + osave.latest )
ut.loadopts(osave.latest,optlist,[],sess)
ut.mprint("Done!")
#########################################################################
# Main Training loop
sess.run(C.set_ifdo)
saviter = niter
tLossAcc=[]
vlog=''
fd=getfeed(tbchr.get_batch())
sess.run(tldr_fetchOp,feed_dict=fd)
ut.mprint("Starting from Iteration %d" % niter)
while not ctrlc.stop and niter < prm.max_iter:
# Val loop
if niter % prm.val_freq == 0:
ut.mprint("Validating networks")
sess.run(C.unset_ifdo)
vLossAcc=[];
for i in range(0,prm.val_iter):
try: # prevent occasional failure when no pts in projection
fps=vbchr.get_batch()
fd=getfeed(fps)
sess.run(vldr_fetchOp,feed_dict=fd)
vLossAcc.append(sess.run([closs]))
except:
pass
sess.run(C.set_ifdo)
args = list(np.mean(vLossAcc,axis=0))
vlog=' val.loss {:.6f}'.format(*args)
# Swap data buffers
sess.run(tldr_swapOp)
# Set up nxt data fetch op
fps=tbchr.get_batch()
fd=getfeed(fps)
# Update cnet
try: # prevent occasional failure when no pts in projection
tLossAcc.append(sess.run([closs,cStep]+tldr_fetchOp,feed_dict=fd)[:1])
except:
pass
# Print training loss & accuracy
niter+=1
if niter % prm.log_freq == 0:
args = [niter]+list(np.mean(tLossAcc,axis=0))
tlog = '[{:09d}] . trn.loss {:.6f}'.format(*args)
ut.mprint(tlog+vlog)
tLossAcc=[]; vlog='';
# Save models
if niter % prm.chkpt_freq == 0:
#Save CoarseNet
C.save(sess,cpath(niter))
csave.clean(every=prm.save_freq,last=1)
ut.mprint("Saved weights to "+cpath(niter))
# Save Optimizers
ut.saveopts(opath(niter),optlist,{},sess)
osave.clean(last=1)
ut.mprint("Saved optimizers to "+opath(niter))
# Save models & optimizers
if niter > csave.iter:
# Save CoarseNet
C.save(sess,cpath(niter))
csave.clean(every=prm.save_freq,last=1)
ut.mprint("Saved weights to "+cpath(niter))
# Save Optimizers
ut.saveopts(opath(niter),optlist,{},sess)
osave.clean(last=1)
ut.mprint("Saved optimizers to "+opath(niter))
<file_sep>/ctrlc.py
# Copyright (c) Microsoft Corporation.
# Copyright (c) University of Florida Research Foundation, Inc.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# ctrlc.py
# Script for graceful handling of SIGINT
# Author: <NAME>
import signal
stop = False
_orig = None
def handler(a,b):
global stop
stop = True
signal.signal(signal.SIGINT,_orig)
_orig = signal.signal(signal.SIGINT,handler)
<file_sep>/load_data.py
# Copyright (c) Microsoft Corporation.
# Copyright (c) University of Florida Research Foundation, Inc.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# load_data.py
# Non-Tensorflow functions for loading invsfm data
# Author: <NAME>
import numpy as np
import colmap.database as database
import colmap.read_model as read_model
from skimage.transform import resize
from skimage.io import imread
################################################################################
# Load sfm model directly from colmap output files
################################################################################
# Load point cloud with per-point sift descriptors and rgb features from
# colmap database and points3D.bin file from colmap sparse reconstruction
def load_points_colmap(database_fp,points3D_fp):
db = database.COLMAPDatabase.connect(database_fp)
descriptors = dict(
(image_id, database.blob_to_array(data, np.uint8, (rows, cols)))
for image_id,data,rows,cols in db.execute("SELECT image_id, data, rows, cols FROM descriptors"))
points3D = read_model.read_points3d_binary(points3D_fp)
keys = list(points3D.keys())
pcl_xyz = []
pcl_rgb = []
pcl_sift = []
for pt3D in points3D.values():
pcl_xyz.append(pt3D.xyz)
pcl_rgb.append(pt3D.rgb)
i = np.random.randint(len(pt3D.image_ids),size=1)[0]
pcl_sift.append(descriptors[pt3D.image_ids[i]][pt3D.point2D_idxs[i]])
pcl_xyz = np.vstack(pcl_xyz).astype(np.float32)
pcl_rgb = np.vstack(pcl_rgb).astype(np.uint8)
pcl_sift = np.vstack(pcl_sift).astype(np.uint8)
return pcl_xyz, pcl_rgb, pcl_sift
# Load camera matrices and names of corresponding src images from
# colmap images.bin and cameras.bin files from colmap sparse reconstruction
def load_cameras_colmap(images_fp,cameras_fp):
images = read_model.read_images_binary(images_fp)
cameras = read_model.read_cameras_binary(cameras_fp)
src_img_nms=[]
K = []; T = []; R = []; w = []; h = []
for i in images.keys():
R.append(read_model.qvec2rotmat(images[i].qvec))
T.append((images[i].tvec)[...,None])
k = np.eye(3)
k[0,0] = cameras[images[i].camera_id].params[0]
k[1,1] = cameras[images[i].camera_id].params[0]
k[0,2] = cameras[images[i].camera_id].params[1]
k[1,2] = cameras[images[i].camera_id].params[2]
K.append(k)
w.append(cameras[images[i].camera_id].width)
h.append(cameras[images[i].camera_id].height)
src_img_nms.append(images[i].name)
return K,R,T,h,w,src_img_nms
################################################################################
# Load sfm model (and other data) from custom invsfm files
################################################################################
def load_camera(file_path):
cam = np.fromfile(file_path,dtype=np.float32)
K = np.reshape(cam[:9],(3,3))
R = np.reshape(cam[9:18],(3,3))
T = np.reshape(cam[18:21],(3,1))
h = cam[21]
w = cam[22]
return K,R,T,h,w
def load_points_rgb(file_path):
return np.reshape(np.fromfile(file_path, dtype=np.uint8),(-1,3))
def load_points_xyz(file_path):
return np.reshape(np.fromfile(file_path, dtype=np.float32),(-1,3))
def load_points_sift(file_path):
return np.reshape(np.fromfile(file_path, dtype=np.uint8),(-1,128))
def load_depth_map(file_path,dtype=np.float16):
with open(file_path,'rb') as f:
fbytes = f.read()
w,h,c=[int(x) for x in str(fbytes[:20])[2:].split('&')[:3]]
header='{}&{}&{}&'.format(w,h,c)
body=fbytes[len(header):]
img=np.fromstring(body,dtype=dtype).reshape((h,w,c))
return np.nan_to_num(img)
def load_image(file_path):
return imread(file_path).astype(np.float32)
# Multi-matrix logical AND
def logical_and(mats):
out = mats[0]
for mat in mats[1:]:
out = np.logical_and(out,mat)
return out
# Compute scale & crop corners
def get_scale_and_crop_corners(img_h,img_w,scale_size,crop_size):
sc = float(scale_size)/float(min(img_h,img_w))
h = int(np.ceil(img_h*sc))
w = int(np.ceil(img_w*sc))
y0 = (h-crop_size)//2
x0 = (w-crop_size)//2
y1 = y0+crop_size
x1 = x0+crop_size
cc = [x0,x1,y0,y1]
return sc, cc, h, w
# scale and crop image
def scale_crop(img,scale_size,crop_size,is_depth=False):
sc,cc,h,w = get_scale_and_crop_corners(img.shape[0],img.shape[1],scale_size,crop_size)
x0, x1, y0, y1 = cc
img = resize(img, (h,w), anti_aliasing=True, mode='reflect', preserve_range=True)
img = img[y0:y1,x0:x1]
if is_depth:
img *= sc
return img
# compute sudo ground-truth visibility map
def compute_visib_map(gt_depth,proj_depth,pct_diff_thresh=5.):
is_val = logical_and([proj_depth > 0., gt_depth > 0.,
np.logical_not(np.isnan(proj_depth)), np.logical_not(np.isnan(gt_depth))])
is_val = is_val.astype(np.float32)
pct_diff = (proj_depth - gt_depth) / (gt_depth + 1e-8) * 100.
pct_diff[np.isnan(pct_diff)] = 100.
is_vis = (pct_diff < pct_diff_thresh).astype(np.float32) * is_val
return is_vis, is_val
################################################################################
# Compute 2D projection of point cloud
################################################################################
# Compute 2D projection of point cloud
def project_points(pcl_xyz, pcl_rgb, pcl_sift, proj_mat, src_img_h, src_img_w, scale_size, crop_size):
sc, cc, h, w = get_scale_and_crop_corners(src_img_h,src_img_w,scale_size,crop_size)
x0, x1, y0, y1 = cc
# Project point cloud to camera view & scale
world_xyz = np.hstack((pcl_xyz,np.ones((len(pcl_xyz),1))))
proj_xyz = (proj_mat.dot(world_xyz.T)).T
proj_xyz[:,:2] = proj_xyz[:,:2] / proj_xyz[:,2:3]
# scale point cloud
x = np.rint(proj_xyz[:,0]*sc).astype(int)
y = np.rint(proj_xyz[:,1]*sc).astype(int)
z = proj_xyz[:,2]*sc
# crop point cloud and filter out pts with invalid depths
mask = logical_and([x>=x0, x<x1, y>=y0, y<y1, z>0., np.logical_not(np.isnan(z))])
x=x[mask]; y=y[mask]; z=z[mask]
# z-buffer xy coordinates with multiple descriptors
idx = np.argsort(z)
idx = idx[np.unique(np.ravel_multi_index((y,x), (h,w)),return_index=True)[1]]
x = x[idx]-x0
y = y[idx]-y0
# get projected point cloud scaled & cropped
proj_depth = np.zeros((crop_size,crop_size,1)).astype(np.float32)
proj_rgb = np.zeros((crop_size,crop_size,3)).astype(np.uint8)
proj_sift = np.zeros((crop_size,crop_size,128)).astype(np.uint8)
proj_depth[y,x] = z[idx,None]
proj_rgb[y,x] = pcl_rgb[mask][idx]
proj_sift[y,x] = pcl_sift[mask][idx]
return proj_depth, proj_rgb, proj_sift
<file_sep>/load_data_tflo.py
# Copyright (c) Microsoft Corporation.
# Copyright (c) University of Florida Research Foundation, Inc.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# tf_load_data.py
# Tensorflow functions for loading invsfm data
# Author: <NAME>
import numpy as np
import tensorflow as tf
# Load Images & Depth Maps
def log10(x):
numerator = tf.log(x)
denominator = tf.log(tf.constant(10, dtype=numerator.dtype))
return numerator / denominator
def num_digits(x):
return tf.floor(log10(x)) + 1
def load_img(fp,dtype=None,binary=False):
img = tf.read_file(fp)
if not binary:
code = tf.decode_raw(img,tf.uint8)[0]
img = tf.cond(tf.equal(code,137),
lambda: tf.image.decode_png(img,channels=3),
lambda: tf.image.decode_jpeg(img,channels=3))
else:
hwc = tf.string_split([img],delimiter='&').values[:3]
w = tf.string_to_number(hwc[0],out_type=tf.float32)
h = tf.string_to_number(hwc[1],out_type=tf.float32)
c = tf.string_to_number(hwc[2],out_type=tf.float32)
start = tf.cast(3+num_digits(w)+num_digits(h)+num_digits(c),tf.int64)
img = tf.substr(img,start,-1)
img = tf.cast(tf.decode_raw(img,tf.float16),tf.float32)
img = tf.reshape(img,tf.cast(tf.stack([h,w,c]),tf.int64))
return img
# Load binary files
def load_bin_file(fp,dtype,shape):
data = tf.read_file(fp)
data = tf.decode_raw(data,dtype)
data = tf.reshape(data,shape)
return data
# Load camera from binary file
def load_camera(fp):
cam = load_bin_file(fp,tf.float32,[23])
K = tf.reshape(cam[:9],(3,3))
R = tf.reshape(cam[9:18],(3,3))
T = tf.reshape(cam[18:21],(3,1))
h = cam[21]
w = cam[22]
return K,R,T,h,w
# set scale and crop for data augmentation
def scale_crop(h,w,crxy,crsz,scsz,isval,niter=0):
scsz = tf.constant(np.float32(scsz),dtype=tf.float32)
hw = tf.stack([h,w])
if isval:
sc = scsz[0]/tf.reduce_min(hw)
new_sz = tf.to_int32(tf.ceil(sc*hw))
cry = (new_sz[0]-crsz)//2
crx = (new_sz[1]-crsz)//2
else:
sc = tf.random_shuffle(scsz,seed=niter)[0]/tf.reduce_min(hw)
new_sz = tf.to_int32(tf.ceil(sc*hw))
cry = tf.cast(tf.floor(crxy[0]*tf.to_float(new_sz[0]-crsz)),tf.int32)
crx = tf.cast(tf.floor(crxy[1]*tf.to_float(new_sz[1]-crsz)),tf.int32)
return sc,new_sz,cry,crx
# load and augment (random scale & crop) image batch
def load_img_bch(img_paths,crsz,scsz,niter=0,isval=False,binary=False):
img_batch = []
crxy = tf.random_uniform([len(img_paths),2],minval=0.,maxval=1.,seed=niter)
for i in range(len(img_paths)):
img = load_img(img_paths[i],binary=binary)
h = tf.to_float(tf.shape(img)[0])
w = tf.to_float(tf.shape(img)[1])
nch = tf.shape(img)[2]
_,dep_sz,dep_cry,dep_crx = scale_crop(h,w,crxy[i],crsz,scsz,isval,niter)
img = tf.image.resize_images(img,dep_sz)
img = img[dep_cry:dep_cry+crsz,dep_crx:dep_crx+crsz,:]
if not isval:
img = tf.image.random_flip_left_right(img,seed=niter)
img_batch.append(tf.reshape(img,[1,crsz,crsz,nch]))
return tf.concat(img_batch,axis=0)
# load batch of sfm projections (xyz, color, depth, sift descriptor)
def load_proj_bch(camera_paths,pcl_xyz_paths,pcl_sift_paths,pcl_rgb_paths,
crsz,scsz,isval=False,niter=0):
bsz = len(camera_paths)
proj_depth_batch = []
proj_sift_batch = []
proj_rgb_batch = []
INT32_MAX = 2147483647
INT32_MIN = -2147483648
crxy = tf.random_uniform([bsz,2],minval=0.,maxval=1.,seed=niter)
for i in range(bsz):
# load data from files
K,R,T,w,h = load_camera(camera_paths[i])
pcl_xyz = load_bin_file(pcl_xyz_paths[i],tf.float32,[-1,3])
pcl_sift = tf.cast(load_bin_file(pcl_sift_paths[i],tf.uint8,[-1,128]),tf.float32)
pcl_rgb = tf.cast(load_bin_file(pcl_rgb_paths[i],tf.uint8,[-1,3]),tf.float32)
sc,_,cry,crx = scale_crop(h,w,crxy[i],crsz,scsz,isval,niter)
# project pcl
P = tf.matmul(K,tf.concat((R,T),axis=1))
xyz_world = tf.concat((pcl_xyz,tf.ones([tf.shape(pcl_xyz)[0],1])),axis=1)
xyz_proj = tf.transpose(tf.matmul(P,tf.transpose(xyz_world)))
z = xyz_proj[:,2]
x = xyz_proj[:,0]/z
y = xyz_proj[:,1]/z
mask_x = tf.logical_and(tf.greater(x,-1.),tf.less(x,tf.to_float(w)))
mask_y = tf.logical_and(tf.greater(y,-1.),tf.less(y,tf.to_float(h)))
mask_z = tf.logical_and(tf.greater(z,0.),tf.logical_not(tf.is_nan(z)))
mask = tf.logical_and(mask_z,tf.logical_and(mask_x,mask_y))
proj_x = tf.boolean_mask(x,mask)
proj_y = tf.boolean_mask(y,mask)
proj_z = tf.boolean_mask(z,mask)
proj_depth = tf.expand_dims(proj_z,axis=1)
proj_sift = tf.boolean_mask(pcl_sift,mask,axis=0)
proj_rgb = tf.boolean_mask(pcl_rgb,mask,axis=0)
# scale pcl
proj_x = tf.round(proj_x*sc)
proj_y = tf.round(proj_y*sc)
h *= sc
w *= sc
#################
# sort proj tensor by depth (descending order)
_,inds_global_sort = tf.nn.top_k(-1.*proj_z,k=tf.shape(proj_z)[0])
proj_x = tf.gather(proj_x,inds_global_sort)
proj_y = tf.gather(proj_y,inds_global_sort)
# per pixel depth buffer
seg_ids = tf.cast(proj_x*tf.cast(w,tf.float32) + proj_y, tf.int32)
data = tf.range(tf.shape(seg_ids)[0])
inds_pix_sort = tf.unsorted_segment_min(data,seg_ids,tf.reduce_max(seg_ids))
inds_pix_sort = tf.boolean_mask(inds_pix_sort,tf.less(inds_pix_sort,INT32_MAX))
proj_depth = tf.gather(tf.gather(proj_depth,inds_global_sort),inds_pix_sort)
proj_sift = tf.gather(tf.gather(proj_sift,inds_global_sort),inds_pix_sort)
proj_rgb = tf.gather(tf.gather(proj_rgb,inds_global_sort),inds_pix_sort)
h = tf.cast(h,tf.int32)
w = tf.cast(w,tf.int32)
proj_yx = tf.cast(tf.concat((proj_y[:,None],proj_x[:,None]),axis=1),tf.int32)
proj_yx = tf.gather(proj_yx,inds_pix_sort)
proj_depth = tf.scatter_nd(proj_yx,proj_depth,[h,w,1])
proj_sift = tf.scatter_nd(proj_yx,proj_sift,[h,w,128])
proj_rgb = tf.scatter_nd(proj_yx,proj_rgb,[h,w,3])
################
# crop proj
proj_depth = proj_depth[cry:cry+crsz,crx:crx+crsz,:]
proj_sift = proj_sift[cry:cry+crsz,crx:crx+crsz,:]
proj_rgb = proj_rgb[cry:cry+crsz,crx:crx+crsz,:]
# randomly flip proj
if not isval:
proj_depth = tf.image.random_flip_left_right(proj_depth,seed=niter)
proj_sift = tf.image.random_flip_left_right(proj_sift,seed=niter)
proj_rgb = tf.image.random_flip_left_right(proj_rgb,seed=niter)
proj_depth_batch.append(proj_depth)
proj_rgb_batch.append(proj_rgb)
proj_sift_batch.append(proj_sift)
return proj_depth_batch, proj_sift_batch, proj_rgb_batch
<file_sep>/train_refine.py
# Copyright (c) Microsoft Corporation.
# Copyright (c) University of Florida Research Foundation, Inc.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# train_refine.py
# Training script for RefineNet
# Author: <NAME>
import os
import sys
import tensorflow as tf
import numpy as np
import ctrlc
import utils as ut
import load_data_tflo as ld
from models import VisibNet
from models import CoarseNet
from models import RefineNet
from models import Discriminator
from models import VGG16
#########################################################################
parser = ut.MyParser(description='Configure')
parser.add_argument("-log_file", default=False, action='store_true', help="%(type)s: Print stdout and stderr to log and err files")
parser.add_argument("--input_attr", type=str, default='depth_sift_rgb', choices=['depth','depth_sift','depth_rgb','depth_sift_rgb'],
help="%(type)s: Per-point attributes to inlcude in input tensor (default: %(default)s)")
parser.add_argument("--trn_anns", type=str, default='data/anns/demo_5k/train.txt',
help="%(type)s: Path to annotation file for training samples (default: %(default)s)")
parser.add_argument("--val_anns", type=str, default='data/anns/demo_5k/val.txt',
help="%(type)s: Path to annotation file for validation samples (default: %(default)s)")
parser.add_argument("--vnet_model", type=str, default=None, help="%(type)s: Path to pre-trained VisibNet model")
parser.add_argument("--cnet_model", type=str, default=None, help="%(type)s: Path to pre-trained CoarseNet model")
parser.add_argument("--vgg16_model", type=str, default='wts/vgg16.model.npz', help="%(type)s: Path to pre-trained vgg16 model (default: %(default)s)")
parser.add_argument("--batch_size", type=int, default=4, help="%(type)s: Number of images in batch (default: %(default)s)")
parser.add_argument("--crop_size", type=int, default=256, help="%(type)s: Size to crop images to (default: %(default)s)")
parser.add_argument("--scale_size", type=lambda s: [int(i) for i in s.split(',')], default=[296,394,512],
help="int,int,int: Sizes to randomly scale images to before cropping them (default: 296,394,512)")
parser.add_argument("--pct_3D_points", type=lambda s: [float(i) for i in s.split(',')][:2], default=[5.,100.],
help="float,float: Min and max percent of 3D points to keep when performing random subsampling for data augmentation "+\
"(default: 5.,100.)")
parser.add_argument("--per_loss_wt", type=float, default=1., help="%(type)s: Perceptual loss weight (default: %(default)s)")
parser.add_argument("--pix_loss_wt", type=float, default=1., help="%(type)s: Pixel loss weight (default: %(default)s)")
parser.add_argument("--adv_loss_wt", type=float, default=1e3, help="%(type)s: Adversarial loss weight (default: %(default)s)")
parser.add_argument("--disc_loss_thresh", type=float, default=.1, help="%(type)s: Only Update discriminator when loss above threshold (default: %(default)s)")
parser.add_argument("--max_iter", type=int, default=1e6, help="%(type)s: Stop training after MAX_ITER iterations (default: %(default)s)")
parser.add_argument("--log_freq", type=int, default=25, help="%(type)s: Log training stats every LOG_FREQ iterations (default: %(default)s)")
parser.add_argument("--chkpt_freq", type=int, default=1e4, help="%(type)s: Save model state every CHKPT_FREQ iterations. Previous model state "+\
"is deleted after each new save (default: %(default)s)")
parser.add_argument("--save_freq", type=int, default=5e4, help="%(type)s: Permanently save model state every SAVE_FREQ iterations "+\
"(default: %(default)s)")
parser.add_argument("--val_freq", type=int, default=5e3, help="%(type)s: Run validation loop every VAL_FREQ iterations (default: %(default)s)")
parser.add_argument("--val_iter", type=int, default=128, help="%(type)s: Number of validation samples per validation loop (default: %(default)s)")
parser.add_argument("--adam_eps", type=float, default=1e-8, help="%(type)s: Epsilon parameter for adam optimizer (default: %(default)s)")
parser.add_argument("--adam_mom", type=float, default=.9, help="%(type)s: Momentum parameter for adam optimizer (default: %(default)s)")
parser.add_argument("--adam_lr", type=float, default=1e-4, help="%(type)s: Learning rate parameter for adam optmizer (default: %(default)s)")
prm = parser.parse_args()
prm_str = 'Arguments:\n'+'\n'.join(['{} {}'.format(k.upper(),v) for k,v in vars(prm).items()])
print(prm_str+'\n')
#########################################################################
# Create exp dir if does not exist
exp_dir = 'wts/{}/refinenet'.format(prm.input_attr)
os.system('mkdir -p {}'.format(exp_dir))
# set path to visibnet wts for demo
if prm.vnet_model == None:
prm.vnet_model = 'wts/pretrained/{}/visibnet.model.npz'.format(prm.input_attr)
if prm.cnet_model == None:
prm.cnet_model = 'wts/pretrained/{}/coarsenet.model.npz'.format(prm.input_attr)
# redirect stdout and stderr to log files
if prm.log_file:
sys.stdout = open(exp_dir+'/train.log', 'a')
sys.stderr = open(exp_dir+'/info.log', 'a')
# Check for saved weights & find iter
rsave = ut.ckpter(exp_dir+'/iter_*.rmodel.npz')
dsave = ut.ckpter(exp_dir+'/iter_*.dmodel.npz')
osave = ut.ckpter(exp_dir+'/iter_*.opt.npz')
rpath = lambda itr: '%s/iter_%07d.rmodel.npz'%(exp_dir,itr)
dpath = lambda itr: '%s/iter_%07d.dmodel.npz'%(exp_dir,itr)
opath = lambda itr: '%s/iter_%07d.opt.npz'%(exp_dir,itr)
niter = rsave.iter
# Load annotations
ut.mprint("Loading annotations")
tbchr = ut.batcher(prm.trn_anns,prm.batch_size,niter)
vbchr = ut.batcher(prm.val_anns,prm.batch_size,niter)
ut.mprint("Done!")
#########################################################################
# Set up data fetch
camera_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
pts_xyz_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
pts_rgb_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
pts_sift_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
gt_rgb_fps = [tf.placeholder(tf.string) for i in range(prm.batch_size)]
getfeed = lambda fps: \
dict([(ph,'data/'+fps[i,3]) for i,ph in enumerate(camera_fps)]+\
[(ph,'data/'+fps[i,0]) for i,ph in enumerate(pts_xyz_fps)]+\
[(ph,'data/'+fps[i,2]) for i,ph in enumerate(pts_sift_fps)]+\
[(ph,'data/'+fps[i,1]) for i,ph in enumerate(pts_rgb_fps)]+\
[(ph,'data/'+fps[i,4]) for i,ph in enumerate(gt_rgb_fps)])
gt_rgb = ld.load_img_bch(gt_rgb_fps,prm.crop_size,prm.scale_size,isval=False,binary=False)
proj_depth,proj_sift,proj_rgb = ld.load_proj_bch(camera_fps,pts_xyz_fps,pts_sift_fps,pts_rgb_fps,
prm.crop_size,prm.scale_size,isval=False)
pd_b=[]; ps_b=[]; pr_b=[]; is_visible=[]; is_valid=[]
keep_prob = tf.random_uniform([prm.batch_size],minval=prm.pct_3D_points[0]/100.,
maxval=prm.pct_3D_points[1]/100.,dtype=tf.float32,seed=niter)
for i in range(prm.batch_size):
# Get valid points
is_val = tf.to_float(tf.greater(proj_depth[i], 0.))
pd = proj_depth[i]*is_val
ps = proj_sift[i]*is_val
pr = proj_rgb[i]*is_val
# dropout (1-keep)% of projected pts
pd = tf.nn.dropout(pd,keep_prob[i],noise_shape=[prm.crop_size,prm.crop_size,1],seed=niter)*keep_prob[i]
ps = tf.nn.dropout(ps,keep_prob[i],noise_shape=[prm.crop_size,prm.crop_size,1],seed=niter)*keep_prob[i]
pr = tf.nn.dropout(pr,keep_prob[i],noise_shape=[prm.crop_size,prm.crop_size,1],seed=niter)*keep_prob[i]
pd_b.append(tf.reshape(pd,[1,prm.crop_size,prm.crop_size,1]))
ps_b.append(tf.reshape(ps,[1,prm.crop_size,prm.crop_size,128]))
pr_b.append(tf.reshape(pr,[1,prm.crop_size,prm.crop_size,3]))
proj_depth = tf.concat(pd_b,axis=0)
proj_sift = tf.concat(ps_b,axis=0) / 127.5 - 1.
proj_rgb = tf.concat(pr_b,axis=0) / 127.5 - 1.
#########################################################################
# Init visibnet
if prm.input_attr=='depth':
vinp = proj_depth
elif prm.input_attr=='depth_sift':
vinp = tf.concat((proj_depth,proj_sift/127.5-1.),axis=3)
elif prm.input_attr=='depth_rgb':
vinp = tf.concat((proj_depth,proj_rgb/127.5-1.),axis=3)
elif prm.input_attr=='depth_sift_rgb':
vinp = tf.concat((proj_depth,proj_rgb/127.5-1.,proj_sift/127.5-1.),axis=3)
V = VisibNet(vinp,bn='test',outp_act=True)
vpred = tf.cast(tf.greater(V.pred,0.5),tf.float32)
# Init CoarseNet
if prm.input_attr=='depth':
cinp = proj_depth*vpred
rinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,4]
elif prm.input_attr=='depth_sift':
cinp = tf.concat((proj_depth*vpred, proj_sift*vpred/127.5-1.),axis=3)
rinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,132]
elif prm.input_attr=='depth_rgb':
cinp = tf.concat((proj_depth*vpred, proj_rgb*vpred/127.5-1.),axis=3)
rinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,7]
elif prm.input_attr=='depth_sift_rgb':
cinp = tf.concat((proj_depth*vpred, proj_sift*vpred/127.5-1., proj_rgb*vpred/127.5-1.),axis=3)
rinp_sz = [prm.batch_size,prm.crop_size,prm.crop_size,135]
C = CoarseNet(cinp,bn='test',outp_act=True)
cpred = (C.pred+1.)*127.5
# Set up pre-fetching for RefineNet
rinp = tf.concat((cpred,cinp),axis=3)
rinp_b0 = tf.Variable(tf.zeros(rinp_sz,dtype=tf.float32))
rinp_b1 = tf.Variable(tf.zeros(rinp_sz,dtype=tf.float32))
rgt = gt_rgb
rgt_sz = [prm.batch_size,prm.crop_size,prm.crop_size,3]
rgt_b0 = tf.Variable(tf.zeros(rgt_sz,dtype=tf.float32))
rgt_b1 = tf.Variable(tf.zeros(rgt_sz,dtype=tf.float32))
tldr_fetchOp = [rinp_b0.assign(rinp).op, rgt_b0.assign(rgt).op]
vldr_fetchOp = [rinp_b1.assign(rinp).op, rgt_b1.assign(rgt).op]
tldr_swapOp = [rinp_b1.assign(rinp_b0).op, rgt_b1.assign(rgt_b0).op]
# Init RefineNet
R = RefineNet(rinp_b1,bn='train',outp_act=False)
rpred = (R.pred+1.)*127.5
# Init perceptual network
pinp = tf.concat((rgt_b1,rpred),axis=0)
P = VGG16(pinp,stop_layer='conv3_3')
ppred = P.pred
# Init discriminator network
dgt0 = tf.constant(0,shape=[prm.batch_size],dtype=tf.int64)
dgt1 = tf.constant(1,shape=[prm.batch_size],dtype=tf.int64)
dgt = tf.concat((dgt0,dgt1),axis=0)
layers = ['conv1_1','conv2_2','conv3_3']
dinp_fake = [ppred[layer][prm.batch_size:] for layer in layers]
dinp_real = [ppred[layer][:prm.batch_size] for layer in layers]
dinp_fake[0] = tf.concat((rinp_b1,rpred,dinp_fake[0]),axis=3)
dinp_real[0] = tf.concat((rinp_b1,rgt_b1,dinp_real[0]),axis=3)
D = Discriminator()
dpred_fake = D.pred(dinp_fake)
dpred_real = D.pred(dinp_real)
dpred = tf.concat((dpred_fake,dpred_real),axis=0)
#########################################################################
# Set optimizer
rvars = R.trainable_variables()
dvars = D.trainable_variables()
optR = tf.train.AdamOptimizer(prm.adam_lr,prm.adam_mom,epsilon=prm.adam_eps)
optD = tf.train.AdamOptimizer(prm.adam_lr,prm.adam_mom,epsilon=prm.adam_eps)
# Set discriminator loss
dloss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=dpred,labels=dgt))
dacc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(dpred,1),dgt),tf.float32))
dStep = optD.minimize(dloss,var_list=list(dvars.keys()))
# Set RefineNet loss
radvloss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=dpred_fake,labels=dgt1))
rpixloss = tf.reduce_mean(tf.abs(rgt_b1-rpred))
rperloss = (tf.reduce_mean(tf.squared_difference(ppred['conv1_1'][:prm.batch_size],ppred['conv1_1'][prm.batch_size:])) + \
tf.reduce_mean(tf.squared_difference(ppred['conv2_2'][:prm.batch_size],ppred['conv2_2'][prm.batch_size:])) + \
tf.reduce_mean(tf.squared_difference(ppred['conv3_3'][:prm.batch_size],ppred['conv3_3'][prm.batch_size:]))) / 3
rloss = prm.pix_loss_wt*rpixloss + prm.per_loss_wt*rperloss + prm.adv_loss_wt*radvloss
rStep = optR.minimize(rloss,var_list=list(rvars.keys()))
#########################################################################
# Start TF session (respecting OMP_NUM_THREADS)
try: init_all_vars = tf.global_variables_initializer()
except: init_all_vars = tf.initialize_all_variables()
nthr = os.getenv('OMP_NUM_THREADS')
if nthr is None: sess=tf.Session()
else: sess=tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=int(nthr)))
sess.run(init_all_vars)
#########################################################################
# Load saved models & optimizers
# Load VGG wts
ut.mprint("Restoring VGG16 from " + prm.vgg16_model)
P.load(sess,prm.vgg16_model)
ut.mprint("Done!")
# Load VisibNet wts
ut.mprint("Restoring VisibNet from " + prm.vnet_model)
V.load(sess,prm.vnet_model)
ut.mprint("Done!")
sess.run(V.unset_ifdo)
# Load CoarseNet wts
ut.mprint("Restoring CoarseNet from " + prm.cnet_model)
C.load(sess,prm.cnet_model)
ut.mprint("Done!")
sess.run(C.unset_ifdo)
# Load RefineNet wts
if rsave.latest != None:
ut.mprint("Restoring RefineNet from " + rsave.latest)
R.load(sess,rsave.latest)
ut.mprint("Done!")
# Load optimizers
optlist = [[optR,rvars],[optD,dvars]]
if osave.latest is not None:
ut.mprint("Restoring optimizers from " + osave.latest)
ut.loadopts(osave.latest,optlist,[],sess)
ut.mprint("Done!")
#########################################################################
# Main Training loop
sess.run(R.set_ifdo)
sess.run(D.set_ifdo)
saviter = niter
dloss_prev=1e6
tLossAcc=[]
vlog=''
fd=getfeed(tbchr.get_batch())
sess.run(tldr_fetchOp,feed_dict=fd)
ut.mprint("Starting from Iteration %d" % niter)
while not ctrlc.stop and niter < prm.max_iter:
# Val loop
if niter % prm.val_freq == 0:
ut.mprint("Validating networks")
sess.run([R.unset_ifdo,D.unset_ifdo])
vLossAcc=[];
for i in range(0,prm.val_iter):
try: # prevent occasional failure when no pts in projection
fps=vbchr.get_batch()
fd=getfeed(fps)
sess.run(vldr_fetchOp,feed_dict=fd)
vLossAcc.append(sess.run([rloss,dloss,dacc]))
except:
pass
sess.run([R.set_ifdo,D.set_ifdo])
args = list(np.mean(vLossAcc,axis=0))
vlog=' R.val.loss {:.6f} D.val.loss {:.6f} D.val.acc {:.6f}'.format(*args)
# Swap data buffers
sess.run(tldr_swapOp)
# Set up nxt data fetch op
fps=tbchr.get_batch()
fd=getfeed(fps)
try: # prevent occasional failure when no pts in projection
if niter%2==0 and dloss_prev>prm.disc_loss_thresh:
tLossAcc.append(sess.run([rloss,dloss,dacc,dStep]+tldr_fetchOp,feed_dict=fd)[:3])
else:
tLossAcc.append(sess.run([rloss,dloss,dacc,rStep]+tldr_fetchOp,feed_dict=fd)[:3])
dloss_prev = tLossAcc[-1][1]
except:
pass
# Print training loss & accuracy
niter+=1
if niter % prm.log_freq == 0 and len(tLossAcc) > 2:
args = [niter]+list(np.mean(tLossAcc,axis=0))
tlog = '[{:09d}] . R.trn.loss {:.6f} D.trn.loss {:.6f} D.trn.acc {:.6f}'.format(*args)
ut.mprint(tlog+vlog)
tLossAcc=[]; vlog='';
# Save models
if niter % prm.chkpt_freq == 0:
# Save RefineNet
R.save(sess,rpath(niter))
rsave.clean(every=prm.save_freq,last=1)
ut.mprint("Saved weights to "+rpath(niter))
# Save Discriminator
D.save(sess,dpath(niter))
dsave.clean(every=prm.save_freq,last=1)
ut.mprint("Saved weights to "+dpath(niter))
# Save Optimizers
ut.saveopts(opath(niter),optlist,{},sess)
osave.clean(last=1)
ut.mprint("Saved optimizers to "+opath(niter))
# Save models & optimizers
if niter > rsave.iter:
# Save RefineNet
R.save(sess,rpath(niter))
rsave.clean(every=prm.save_freq,last=1)
ut.mprint("Saved weights to "+rpath(niter))
# Save Discriminator
D.save(sess,dpath(niter))
dsave.clean(every=prm.save_freq,last=1)
ut.mprint("Saved weights to "+dpath(niter))
# Save Optimizers
ut.saveopts(opath(niter),optlist,{},sess)
osave.clean(last=1)
ut.mprint("Saved optimizers to "+opath(niter))
<file_sep>/requirements.txt
tensorflow-gpu
Pillow
scikit-image
<file_sep>/demo_5k.py
# Copyright (c) Microsoft Corporation.
# Copyright (c) University of Florida Research Foundation, Inc.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# demo_5k.py
# Demo script for running pre-trained models on infsfm data
# Author: <NAME>
import os
import sys
import tensorflow as tf
import numpy as np
from PIL import Image, ImageFont, ImageDraw
import utils as ut
import load_data as ld
from models import VisibNet
from models import CoarseNet
from models import RefineNet
################################################################################
parser = ut.MyParser(description='Configure')
parser.add_argument("--input_attr", type=str, default='depth_sift_rgb',
choices=['depth','depth_sift','depth_rgb','depth_sift_rgb'],
help="%(type)s: Per-point attributes to inlcude in input tensor (default: %(default)s)")
parser.add_argument("--pct_3D_points", type=float, default=100., choices=[20,60,100],
help="%(type)s: Percent of available 3D points to include in input tensor (default: %(default)s)")
parser.add_argument("--crop_size", type=int, default=512, choices=[256,512],
help="%(type)s: Size to crop images to (default: %(default)s)")
parser.add_argument("--scale_size", type=int, default=512, choices=[256,394,512],
help="%(type)s: Size to scale images to before crop (default: %(default)s)")
parser.add_argument("--num_samples", type=int, default=32,
help="%(type)s: Number of samples to process/visualize (default: %(default)s)")
parser.add_argument("--seed", type=int, default=1111,
help="%(type)s: Seed for random selection of samples (default: %(default)s)")
prm = parser.parse_args()
if prm.scale_size < prm.crop_size: parser.error("SCALE_SIZE must be >= CROP_SIZE")
if prm.num_samples <= 0: parser.error("NUM_SAMPLES must be > 0")
prm_str = 'Arguments:\n'+'\n'.join(['{} {}'.format(k.upper(),v) for k,v in vars(prm).items()])
print(prm_str+'\n')
# set paths for model wts
vnet_wts_fp = 'wts/pretrained/{}/visibnet.model.npz'.format(prm.input_attr)
cnet_wts_fp = 'wts/pretrained/{}/coarsenet.model.npz'.format(prm.input_attr)
rnet_wts_fp = 'wts/pretrained/{}/refinenet.model.npz'.format(prm.input_attr)
################################################################################
# Load annotations
anns = ut.load_annotations('data/anns/demo_5k/test.txt')
anns = anns[np.random.RandomState(seed=prm.seed).permutation(len(anns))]
# Load data
proj_depth = []
proj_sift = []
proj_rgb = []
src_img = []
gt_vis = []
for i in range(prm.num_samples):
# Load point cloud
pcl_xyz = ld.load_points_xyz('data/'+anns[i,0])
pcl_rgb = ld.load_points_rgb('data/'+anns[i,1])
pcl_sift = ld.load_points_sift('data/'+anns[i,2])
# Load camera
K,R,T,h,w = ld.load_camera('data/'+anns[i,3])
proj_mat = K.dot(np.hstack((R,T)))
# Project point cloud to camera
pdepth, prgb, psift = ld.project_points(pcl_xyz, pcl_rgb, pcl_sift,
proj_mat, h, w, prm.scale_size, prm.crop_size)
simg = ld.scale_crop(ld.load_image('data/'+anns[i,4])/127.5-1.,prm.scale_size,prm.crop_size)
gt_depth = ld.scale_crop(ld.load_depth_map('data/'+anns[i,5],dtype=np.float16).astype(np.float32),
prm.scale_size,prm.crop_size,is_depth=True)
is_vis, is_val = ld.compute_visib_map(gt_depth,pdepth,pct_diff_thresh=5.)
proj_depth.append((pdepth*is_val)[None,...])
proj_sift.append((psift*is_val)[None,...])
proj_rgb.append((prgb*is_val)[None,...])
src_img.append(simg[None,...])
gt_vis.append(is_vis[None,...])
proj_depth = np.vstack(proj_depth)
proj_sift = np.vstack(proj_sift)
proj_rgb = np.vstack(proj_rgb)
src_img = np.vstack(src_img)
gt_vis = np.vstack(gt_vis)
################################################################################
# Build Graph
proj_depth_p = tf.placeholder(tf.float32,shape=[1,prm.crop_size,prm.crop_size,1])
proj_rgb_p = tf.placeholder(tf.uint8,shape=[1,prm.crop_size,prm.crop_size,3])
proj_sift_p = tf.placeholder(tf.uint8,shape=[1,prm.crop_size,prm.crop_size,128])
pdepth = proj_depth_p
prgb = tf.to_float(proj_rgb_p)
psift = tf.to_float(proj_sift_p)
keep = prm.pct_3D_points/100.
pdepth = tf.nn.dropout(pdepth,keep,noise_shape=[1,prm.crop_size,prm.crop_size,1],seed=0)*keep
prgb = tf.nn.dropout(prgb,keep,noise_shape=[1,prm.crop_size,prm.crop_size,1],seed=0)*keep
psift = tf.nn.dropout(psift,keep,noise_shape=[1,prm.crop_size,prm.crop_size,1],seed=0)*keep
valid = tf.greater(pdepth,0.)
# set up visibnet
if prm.input_attr=='depth':
vinp = pdepth
elif prm.input_attr=='depth_rgb':
vinp = tf.concat((pdepth, prgb/127.5-1.),axis=3)
elif prm.input_attr=='depth_sift':
vinp = tf.concat((pdepth, psift/127.5-1.),axis=3)
elif prm.input_attr=='depth_sift_rgb':
vinp = tf.concat((pdepth, psift/127.5-1., prgb/127.5-1.),axis=3)
vnet = VisibNet(vinp,bn='test')
vpred = tf.logical_and(tf.greater(vnet.pred,.5),valid)
vpredf = tf.to_float(vpred)*0.+1.
# set up coarsenet
if prm.input_attr=='depth':
cinp = pdepth*vpredf
elif prm.input_attr=='depth_rgb':
cinp = tf.concat((pdepth*vpredf, prgb*vpredf/127.5-1.),axis=3)
elif prm.input_attr=='depth_sift':
cinp = tf.concat((pdepth*vpredf, psift*vpredf/127.5-1.),axis=3)
elif prm.input_attr=='depth_sift_rgb':
cinp = tf.concat((pdepth*vpredf, psift*vpredf/127.5-1., prgb*vpredf/127.5-1.),axis=3)
cnet = CoarseNet(cinp,bn='test')
cpred = cnet.pred
# set up refinenet
rinp = tf.concat((cpred,cinp),axis=3)
rnet = RefineNet(rinp,bn='train')
rpred = rnet.pred
# scale outputs
cpred = (cpred+1.)*127.5
rpred = (rpred+1.)*127.5
################################################################################
# Run Graph
sess=tf.Session()
try: init_all_vars = tf.global_variables_initializer()
except: init_all_vars = tf.initialize_all_variables()
# Load net wts
vnet.load(sess,vnet_wts_fp)
cnet.load(sess,cnet_wts_fp)
rnet.load(sess,rnet_wts_fp)
sess.run([vnet.unset_ifdo,
cnet.unset_ifdo,
rnet.unset_ifdo])
# Run cnet
vpred_img = []
cpred_img = []
rpred_img = []
valid_img = []
for i in range(prm.num_samples):
fd = {proj_depth_p:proj_depth[i:i+1],
proj_rgb_p:proj_rgb[i:i+1],
proj_sift_p:proj_sift[i:i+1]}
out = sess.run([vpred,cpred,rpred,valid],feed_dict=fd)
vpred_img.append(out[0])
cpred_img.append(out[1])
rpred_img.append(out[2])
valid_img.append(out[3])
vpred_img = np.vstack(vpred_img)
cpred_img = np.vstack(cpred_img)
rpred_img = np.vstack(rpred_img)
valid_img = np.vstack(valid_img)
################################################################################
# Generate visibnet visualization
vpred = np.vstack(vpred_img)
valid = np.vstack(valid_img)
zero = np.zeros(valid.shape,dtype=bool)
vpred_img = np.ones([vpred.shape[0],prm.crop_size,3])*255.
vpred_img[np.dstack((valid,valid,valid))] = 0.
vpred_img[np.dstack((np.logical_and(valid,np.logical_not(vpred)),zero,zero))] = 255.
vpred_img[np.dstack((zero,zero,np.logical_and(valid,vpred)))] = 255.
# Generate gt visibility map visualization
visib = np.vstack(gt_vis)
gt_vis = np.ones([visib.shape[0],prm.crop_size,3])*255.
gt_vis[np.dstack((valid,valid,valid))] = 0.
gt_vis[np.dstack((np.logical_and(valid,np.logical_not(visib)),zero,zero))] = 255.
gt_vis[np.dstack((zero,zero,np.logical_and(valid,visib)))] = 255.
# Build results montage
border_size = 25
header_size = 60
mntg = np.hstack((np.vstack((src_img+1.)*127.5).astype(np.uint8),
gt_vis.astype(np.uint8),
np.zeros((gt_vis.shape[0],border_size,3)).astype(np.uint8),
vpred_img.astype(np.uint8),
np.vstack(cpred_img).astype(np.uint8),
np.vstack(rpred_img).astype(np.uint8)))
header_bot = np.ones((header_size,mntg.shape[1],3))*127.
header_top = np.zeros((header_size,mntg.shape[1],3))
mntg = np.vstack((header_top,header_bot,mntg))
# Add titles to mntg header
mntg = Image.fromarray(mntg.astype(np.uint8))
im_draw = ImageDraw.Draw(mntg)
font = ImageFont.truetype("FreeMonoBold.ttf", 36)
column_titles = ['Target Image','Pseudo-GT Visibility','VisibNet Prediction',
'CoarseNet Prediction','RefineNet Prediction']
figure_title = 'Input Attributes: ' + prm.input_attr.replace('_',', ')
for i in range(len(column_titles)):
xpos = prm.crop_size*i + prm.crop_size/2 - font.getsize(column_titles[i])[0]/2
im_draw.text((xpos,70), column_titles[i], font=font, fill=(255,255,255))
xpos = header_top.shape[1]/2-font.getsize(figure_title)[0]/2
im_draw.text((xpos,10), figure_title, font=font, fill=(255,255,255))
# save montage
fp = 'viz/demo_5k/{}.png'.format(prm.input_attr)
print('Saving visualization to {}...'.format(fp))
mntg.save(fp)
print('Done')
<file_sep>/download_data.sh
# download_data.sh
# Get data files (11G) from gdrive
wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1StpUiEauckZcxHZeBzoq6L2K7pcB9v3E' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1StpUiEauckZcxHZeBzoq6L2K7pcB9v3E" -O data.tar.gz && rm -rf /tmp/cookies.txt
# Untar file
echo "Untarring data.tar.gz"
tar -xf data.tar.gz
<file_sep>/utils.py
# Copyright (c) Microsoft Corporation.
# Copyright (c) University of Florida Research Foundation, Inc.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# utils.py
# Random utilty functions
# Author: <NAME>
import sys
import os
import time
import re
from glob import glob
import numpy as np
import tensorflow as tf
import argparse
# Parser that prints help upon error
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n\n' % message)
self.print_help()
sys.exit(2)
# Print to stdout with date/time
def mprint(s):
sys.stdout.write(time.strftime("%Y-%m-%d %H:%M:%S ") + str(s) + "\n")
sys.stdout.flush()
# Print to stderr with date/time
def eprint(s):
sys.stderr.write(time.strftime("%Y-%m-%d %H:%M:%S ") + str(s) + "\n")
sys.stderr.flush()
# Load annotations file
def load_annotations(fname):
with open(fname,'r') as f:
data = [line.strip().split(' ') for line in f]
return np.array(data)
# Reading in batches (with repeatable random shuffling)
class batcher:
def __init__(self,fname,bsz,niter=0):
# Load from file
self.data = load_annotations(fname)
# Setup batching
nsamp = len(self.data)
self.bsz = bsz
self.rand = np.random.RandomState(0)
idx = self.rand.permutation(nsamp)
for i in range(niter*bsz // len(idx)):
idx = self.rand.permutation(len(idx))
self.idx = np.int32(idx)
self.pos = niter*bsz % len(self.idx)
def get_batch(self):
if self.pos+self.bsz >= len(self.idx):
bidx = self.idx[self.pos:]
idx = self.rand.permutation(len(self.idx))
self.idx = np.int32(idx)
self.pos = 0
if len(bidx) < self.bsz:
self.pos = self.bsz-len(bidx)
bidx2 = self.idx[0:self.pos]
bidx = np.concatenate((bidx,bidx2))
else:
bidx = self.idx[self.pos:self.pos+self.bsz]
self.pos = self.pos+self.bsz
return self.data[bidx]
# Manage checkpoint files, read off iteration number from filename
# Use clean() to keep latest, and modulo n iters, delete rest
class ckpter:
def __init__(self,wcard):
self.wcard = wcard
self.load()
def load(self):
lst = glob(self.wcard)
if len(lst) > 0:
lst=[(l,int(re.match('.*/.*_(\d+)',l).group(1)))
for l in lst]
self.lst=sorted(lst,key=lambda x: x[1])
self.iter = self.lst[-1][1]
self.latest = self.lst[-1][0]
else:
self.lst=[]
self.iter=0
self.latest=None
def clean(self,every=0,last=1):
self.load()
old = self.lst[:-last]
for j in old:
if every == 0 or j[1] % every != 0:
os.remove(j[0])
# Save Optimizer state (Assume Adam)
def saveopts(fn,opts,others,sess):
weights = {}
for i in range(len(opts)):
opt = opts[i][0]
vdict = opts[i][1]
if type(opt) == tf.train.AdamOptimizer:
b1p, b2p = opt._get_beta_accumulators()
weights['%d:b1p'%i] = b1p.eval(sess)
weights['%d:b2p'%i] = b2p.eval(sess)
for v in vdict.keys():
nm = vdict[v]
weights['%d:m_%s' % (i,nm)] = opt.get_slot(v,'m').eval(sess)
weights['%d:v_%s' % (i,nm)] = opt.get_slot(v,'v').eval(sess)
else:
slots = opt.get_slot_names()
for v in vdict.keys():
nm = vdict[v]
for s in slots:
weights['%d:%s%s' % (i,s,nm)] = opt.get_slot(v, s).eval(sess)
weights.update(others)
np.savez(fn,**weights)
# Load Optimizer state (Assume Adam)
def loadopts(fn,opts,others,sess):
if not os.path.isfile(fn):
return None
weights = np.load(fn)
ph = tf.placeholder(tf.float32)
for i in range(len(opts)):
opt = opts[i][0]
vdict = opts[i][1]
if type(opt) == tf.train.AdamOptimizer:
b1p, b2p = opt._get_beta_accumulators()
sess.run(b1p.assign(ph),feed_dict={ph: weights['%d:b1p'%i]})
sess.run(b2p.assign(ph),feed_dict={ph: weights['%d:b2p'%i]})
for v in vdict.keys():
nm = vdict[v]
sess.run(opt.get_slot(v,'m').assign(ph),
feed_dict={ph: weights['%d:m_%s' % (i,nm)]})
sess.run(opt.get_slot(v,'v').assign(ph),
feed_dict={ph: weights['%d:v_%s' % (i,nm)]})
else:
slots = opt.get_slot_names()
for v in vdict.keys():
nm = vdict[v]
for s in slots:
sess.run(opt.get_slot(v, s).assign(ph),
feed_dict={ph: weights['%d:%s%s' % (i,s,nm)]})
oval = [weights[k] for k in others]
return oval
<file_sep>/demo_colmap.py
# Copyright (c) Microsoft Corporation.
# Copyright (c) University of Florida Research Foundation, Inc.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# demo_colmap.py
# Demo script for running pre-trained models on data loaded directly from colmap sparse reconstruction files
# Author: <NAME>
import os
import sys
import tensorflow as tf
import numpy as np
from PIL import Image, ImageFont, ImageDraw
import utils as ut
import load_data as ld
from models import VisibNet
from models import CoarseNet
from models import RefineNet
################################################################################
parser = ut.MyParser(description='Configure')
parser.add_argument("--input_attr", type=str, default='depth_sift_rgb',
choices=['depth','depth_sift','depth_rgb','depth_sift_rgb'],
help="%(type)s: Per-point attributes to inlcude in input tensor (default: %(default)s)")
parser.add_argument("--pct_3D_points", type=float, default=100., choices=[20,60,100],
help="%(type)s: Percent of available 3D points to include in input tensor (default: %(default)s)")
parser.add_argument("--dataset", type=str, default='nyu', choices=['nyu','medadepth'],
help="%(type)s: Dataset to use for demo (default: %(default)s)")
parser.add_argument("--crop_size", type=int, default=512, choices=[256,512],
help="%(type)s: Size to crop images to (default: %(default)s)")
parser.add_argument("--scale_size", type=int, default=512, choices=[256,394,512],
help="%(type)s: Size to scale images to before crop (default: %(default)s)")
parser.add_argument("--num_samples", type=int, default=32,
help="%(type)s: Number of samples to process/visualize (default: %(default)s)")
prm = parser.parse_args()
if prm.scale_size < prm.crop_size: parser.error("SCALE_SIZE must be >= CROP_SIZE")
if prm.num_samples <= 0: parser.error("NUM_SAMPLES must be > 0")
prm_str = 'Parameters:\n'+'\n'.join(['{} {}'.format(k.upper(),v) for k,v in vars(prm).items()])
print(prm_str+'\n')
# set paths for model wts
vnet_wts_fp = 'wts/pretrained/{}/visibnet.model.npz'.format(prm.input_attr)
cnet_wts_fp = 'wts/pretrained/{}/coarsenet.model.npz'.format(prm.input_attr)
rnet_wts_fp = 'wts/pretrained/{}/refinenet.model.npz'.format(prm.input_attr)
# set paths for colmap files
scene = 'nyu_bedroom_0041' if prm.dataset == 'nyu' else 'megadepth_0117_dense0'
cmap_database_fp = 'data/demo_colmap_outputs/{}/database.db'.format(scene)
cmap_points3D_fp = 'data/demo_colmap_outputs/{}/points3D.bin'.format(scene)
cmap_cameras_fp = 'data/demo_colmap_outputs/{}/cameras.bin'.format(scene)
cmap_images_fp = 'data/demo_colmap_outputs/{}/images.bin'.format(scene)
################################################################################
# Load point cloud with per-point sift descriptors and rgb features from
# colmap database and points3D.bin file from colmap sparse reconstruction
print('Loading point cloud...')
pcl_xyz, pcl_rgb, pcl_sift = ld.load_points_colmap(cmap_database_fp,cmap_points3D_fp)
print('Done!')
# Load camera matrices and from images.bin and cameras.bin files from
# colmap sparse reconstruction
print('Loading cameras...')
K,R,T,h,w,_ = ld.load_cameras_colmap(cmap_images_fp,cmap_cameras_fp)
print('Done!')
# Generate projections
proj_depth = []
proj_sift = []
proj_rgb = []
for i in range(len(K))[::(len(K)//prm.num_samples)]:
proj_mat = K[i].dot(np.hstack((R[i],T[i])))
pdepth, prgb, psift = ld.project_points(pcl_xyz, pcl_rgb, pcl_sift,
proj_mat, h[i], w[i], prm.scale_size, prm.crop_size)
proj_depth.append((pdepth)[None,...])
proj_sift.append((psift)[None,...])
proj_rgb.append((prgb)[None,...])
proj_depth = np.vstack(proj_depth)
proj_sift = np.vstack(proj_sift)
proj_rgb = np.vstack(proj_rgb)
################################################################################
# Build Graph
proj_depth_p = tf.placeholder(tf.float32,shape=[1,prm.crop_size,prm.crop_size,1])
proj_rgb_p = tf.placeholder(tf.uint8,shape=[1,prm.crop_size,prm.crop_size,3])
proj_sift_p = tf.placeholder(tf.uint8,shape=[1,prm.crop_size,prm.crop_size,128])
pdepth = proj_depth_p
prgb = tf.to_float(proj_rgb_p)
psift = tf.to_float(proj_sift_p)
keep = prm.pct_3D_points/100.
pdepth = tf.nn.dropout(pdepth,keep,noise_shape=[1,prm.crop_size,prm.crop_size,1],seed=0)*keep
prgb = tf.nn.dropout(prgb,keep,noise_shape=[1,prm.crop_size,prm.crop_size,1],seed=0)*keep
psift = tf.nn.dropout(psift,keep,noise_shape=[1,prm.crop_size,prm.crop_size,1],seed=0)*keep
valid = tf.greater(pdepth,0.)
# set up visibnet
if prm.input_attr=='depth':
vinp = pdepth
elif prm.input_attr=='depth_rgb':
vinp = tf.concat((pdepth, prgb/127.5-1.),axis=3)
elif prm.input_attr=='depth_sift':
vinp = tf.concat((pdepth, psift/127.5-1.),axis=3)
elif prm.input_attr=='depth_sift_rgb':
vinp = tf.concat((pdepth, psift/127.5-1., prgb/127.5-1.),axis=3)
vnet = VisibNet(vinp,bn='test')
vpred = tf.logical_and(tf.greater(vnet.pred,.5),valid)
vpredf = tf.to_float(vpred)*0.+1.
# set up coarsenet
if prm.input_attr=='depth':
cinp = pdepth*vpredf
elif prm.input_attr=='depth_rgb':
cinp = tf.concat((pdepth*vpredf, prgb*vpredf/127.5-1.),axis=3)
elif prm.input_attr=='depth_sift':
cinp = tf.concat((pdepth*vpredf, psift*vpredf/127.5-1.),axis=3)
elif prm.input_attr=='depth_sift_rgb':
cinp = tf.concat((pdepth*vpredf, psift*vpredf/127.5-1., prgb*vpredf/127.5-1.),axis=3)
cnet = CoarseNet(cinp,bn='test')
cpred = cnet.pred
# set up refinenet
rinp = tf.concat((cpred,cinp),axis=3)
rnet = RefineNet(rinp,bn='train')
rpred = rnet.pred
# scale outputs
cpred = (cpred+1.)*127.5
rpred = (rpred+1.)*127.5
################################################################################
# Run Graph
sess=tf.Session()
try: init_all_vars = tf.global_variables_initializer()
except: init_all_vars = tf.initialize_all_variables()
# Load net wts
vnet.load(sess,vnet_wts_fp)
cnet.load(sess,cnet_wts_fp)
rnet.load(sess,rnet_wts_fp)
sess.run([vnet.unset_ifdo,
cnet.unset_ifdo,
rnet.unset_ifdo])
# Run cnet
vpred_img = []
cpred_img = []
rpred_img = []
valid_img = []
for i in range(prm.num_samples):
fd = {proj_depth_p:proj_depth[i:i+1],
proj_rgb_p:proj_rgb[i:i+1],
proj_sift_p:proj_sift[i:i+1]}
out = sess.run([vpred,cpred,rpred,valid],feed_dict=fd)
vpred_img.append(out[0])
cpred_img.append(out[1])
rpred_img.append(out[2])
valid_img.append(out[3])
vpred_img = np.vstack(vpred_img)
cpred_img = np.vstack(cpred_img)
rpred_img = np.vstack(rpred_img)
valid_img = np.vstack(valid_img)
################################################################################
# Generate visibnet visualization
vpred = np.vstack(vpred_img)
valid = np.vstack(valid_img)
zero = np.zeros(valid.shape,dtype=bool)
vpred_img = np.ones([vpred.shape[0],prm.crop_size,3])*255.
vpred_img[np.dstack((valid,valid,valid))] = 0.
vpred_img[np.dstack((np.logical_and(valid,np.logical_not(vpred)),zero,zero))] = 255.
vpred_img[np.dstack((zero,zero,np.logical_and(valid,vpred)))] = 255.
# Build results montage
header_size = 60
mntg = np.hstack((vpred_img.astype(np.uint8),
np.vstack(cpred_img).astype(np.uint8),
np.vstack(rpred_img).astype(np.uint8)))
header_bot = np.ones((header_size,prm.crop_size*3,3))*127.
header_top = np.zeros((header_size,prm.crop_size*3,3))
mntg = np.vstack((header_top,header_bot,mntg))
# Add titles to montage header
mntg = Image.fromarray(mntg.astype(np.uint8))
im_draw = ImageDraw.Draw(mntg)
font = ImageFont.truetype("FreeMonoBold.ttf", 36)
column_titles = ['VisibNet Prediction','CoarseNet Prediction','RefineNet Prediction']
figure_title = 'Input Attributes: ' + prm.input_attr.replace('_',', ')
for i in range(len(column_titles)):
xpos = prm.crop_size*i + prm.crop_size/2 - font.getsize(column_titles[i])[0]/2
im_draw.text((xpos,70), column_titles[i], font=font, fill=(255,255,255))
xpos = header_top.shape[1]/2-font.getsize(figure_title)[0]/2
im_draw.text((xpos,10), figure_title, font=font, fill=(255,255,255))
# Save montage
fp = 'viz/demo_colmap/{}.png'.format(prm.input_attr)
print('Saving visualization to {}...'.format(fp))
mntg.save(fp)
print('Done!')
|
4e8245f7cdec3c1d63a6e259c4ff23d0fe305286
|
[
"Markdown",
"Python",
"Text",
"Shell"
] | 14
|
Python
|
cyhsu14/invsfm
|
ea2ef4e14168c8ee7c187ee1ce08f0b22e7e9000
|
94e7d95f8e422a3f381848f1f63065a45633fa10
|
refs/heads/master
|
<repo_name>Szqii/Vuerld<file_sep>/src/API.js
import axios from 'axios'
const URL = "https://restcountries.eu/rest/v2";
export async function getData() {
const response = await axios.get(URL + '/all');
return response;
}
export async function getDataToContent(country_name) {
const response = await axios.get(URL + '/name/' + country_name);
return response;
}
|
87634311b4e06b94fe9a17c8c5bcccea47c023f4
|
[
"JavaScript"
] | 1
|
JavaScript
|
Szqii/Vuerld
|
bd0b9810be584a9d39e3a23c8d1f5ea62e18540d
|
d99f442680f8ef029f8f119fc68379d0c9f5dc0a
|
refs/heads/master
|
<repo_name>Abdulhmid/article-api<file_sep>/app/Http/Requests/GroupsRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class GroupsRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$lastUrl = \GLobalHelper::lastUrl();
if(!empty(\Request::segment(2))) :
$rules['group_name'] = 'required|unique:groups,group_name,'.$lastUrl.',group_id';
else :
$rules['group_name'] = 'required|unique:groups,group_name';
endif;
return $rules;
}
}
<file_sep>/app/Http/Middleware/ApiMiddleware.php
<?php
namespace App\Http\Middleware;
use App\User;
use App\Models as Md;
use Closure;
use App\Library\Token;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Middleware\BaseMiddleware;
class ApiMiddleware extends BaseMiddleware
{
use Token;
public function handle($request, \Closure $next)
{
if (!$token = \JWTAuth::setRequest($request)->getToken()) {
return $this->respond('tymon.jwt.absent', 'token_not_provided', 400);
}
try {
$user = $this->validateUser();
} catch (TokenExpiredException $e) {
return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]);
} catch (JWTException $e) {
return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]);
}
if (!$user) {
return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404);
}
$this->events->fire('tymon.jwt.valid', $user);
return $next($request);
}
private function validateUser()
{
$user = $this->getAuthenticatedUser();
$find = User::where([
'id' => $user['id']
])->first();
return (empty($find)) ? false : true;
}
}
<file_sep>/app/Http/Controllers/Backend/AccessCheckerTrait.php
<?php
namespace App\Http\Controllers\Backend;
use App\Models\Modules;
trait AccessCheckerTrait
{
private function checkAccess($function)
{
if (\Auth::user()->group_id != 1 ) {
$getAccess = $this->info ?
$this->modules->validAccess($this->info['id'], \Auth::user()->group_id) : "";
if (isset($getAccess[$function])) {
if ($getAccess == "" || $getAccess[$function] == 0)
abort(403);
}else{
abort(403);
}
}
}
}<file_sep>/app/Forms/NewsForm.php
<?php
namespace App\Forms;
use Kris\LaravelFormBuilder\Form;
class NewsForm extends Form
{
public function buildForm()
{
$this
->add('title','text')
->add('tag','text',[
'attr' => ['class' => 'form-control tokenfield-teal']
])
->add('status', 'choice', [
'choices' => ['1' => 'Active', '0' => 'Not Active'],
'label' => "Status",
'expanded' => true,
'multiple' => false
])
/*
** Meta Data
*/
->add('meta_title','text',[
'label' => false
])
->add('meta_keyword','text',[
'label' => false
])
->add('meta_description','textarea',[
'label' => false
])
->add('content','textarea',[
'label' => false
])
->add('photo','file',[
'attr' => [
'id' => 'file',
'onchange' => 'readUrl(this)'
]
]);
}
}
<file_sep>/app/DataTables/GroupsDataTables.php
<?php
namespace App\DataTables;
use App\Models\Groups;
use Yajra\Datatables\Services\DataTable;
class GroupsDataTables extends DataTable
{
/**
* Display ajax response.
*
* @return \Illuminate\Http\JsonResponse
*/
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->editColumn('created_at', function ($row) {
return \GLobalHelper::formatDate($row->created_at);
})
->editColumn('updated_at', function ($row) {
return \GLobalHelper::formatDate($row->updated_at);
})
->addColumn('action', function ($row) {
$column = "<a href=\"" . route('groups.edit', $row->group_id) . "\" class=\"btn btn-flat btn-default btn-sm\" data-toggle=\"tooltip\" data-original-title=\"Edit\">
<i class=\"fa fa-pencil\"></i> Edit
</a>
<a href=\"" . route('groups.destroy', $row->group_id) . "\" class=\"btn btn-flat btn-danger btn-sm btn-delete\" data-toggle=\"tooltip\" data-original-title=\"Delete\" onclick=\"swal_alert(this,null,'delete','" . csrf_token() . "'); return false;\">
<i class=\"fa fa-trash-o\"></i> Hapus
</a>";
return $column;
})
->make(true);
}
/**
* Get the query object to be processed by dataTables.
*
* @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Support\Collection
*/
public function query()
{
$query = Groups::query();
return $this->applyScopes($query);
}
/**
* Optional method if you want to use html builder.
*
* @return \Yajra\Datatables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->ajax('')
->addAction(['width' => '80px'])
->parameters($this->getBuilderParameters());
}
/**
* Get columns.
*
* @return array
*/
protected function getColumns()
{
return [
'group_name' => [
'title' => 'Nama',
'width' => '35%'
],
'created_at' => [
'title' => 'Ditulis',
'width' => '25%'
],
'updated_at' => [
'title' => 'Diubah',
'width' => '25%'
],
];
}
/**
* Get filename for export.
*
* @return string
*/
protected function filename()
{
return 'groupsdatatables_' . time();
}
}
<file_sep>/readme.md
# Test App
Panduan instalsi
------------
- Donwload Project dengan git command [git clone https://github.com/Abdulhmid/article-api.git]
- edit setingan database di file .env [sesuaikan dengan serve database lokal]
- jalankan migration
```{.bash}
$ php artisan migrate --seed
```
Contoh Pengguna
------------
- admin => u : <EMAIL> ; p : 12345
- editor => u : <EMAIL> ; p : 123456
Available API
------------
- API Login
- API Daftar Artikel
- API Ambil Artikel
Penggunaan Api API
------------
- Buat virtual server di laravel [masuk ke directory project laravel]
```{.bash}
$ php artisan serve
```
API Login
------------
- Path :
```
$url/api/v1/login
```
- Contoh Penggunaan

- Response
```{.json}
{
"token": "<KEY>",
"data": {
"id": 1,
"username": "superadmin",
"name": "<NAME>",
"email": "<EMAIL>",
"photo": null,
"group_id": 1,
"created_at": "2016-10-25 01:31:40",
"updated_at": "2016-10-25 01:41:39"
}
}
```
API Daftar Artikel
------------
- Path :
```
$url/api/v1/article
```
- Contoh Penggunaan

- Response
```{.json}
[
{
"articles": [
{
"id": 1,
"title": "Dolores enim ut culpa labore",
"slug": "dolores-enim-ut-culpa-labore",
"content": "Nisi dolore aut sunt quaerat et ut tempore, dolore quo dolor asperiores aut.",
"user_id": 1
},
{
"id": 2,
"title": "Quas facilis voluptatem enim nisi enim et",
"slug": "quas-facilis-voluptatem-enim-nisi-enim-et",
"content": "Sint voluptates atque ab esse quia dolore voluptate officia quos autem quo odit tempora.",
"user_id": 2
}
],
"count": 2
}
]
```
API Ambil Artikel Berdasarkan ID
------------
- Path :
```
$url/api/v1/article/{$id}
```
- Contoh Penggunaan

- Response
```{.json}
{
"data": {
"id": 1,
"title": "Dolores enim ut culpa labore",
"slug": "dolores-enim-ut-culpa-labore",
"tag": "Aliquip veritatis ut sed sit est culpa non deleniti deserunt magna facere vel tempore nulla eos vitae enim",
"image": "photos/bullyingjpg.jpg",
"meta_title": "RER",
"meta_keyword": "SRRER",
"meta_description": "Aut eiusmod ducimus, ea adipisicing aperiam dolor minim sed et commodi officia temporibus amet, veniam, aliquam quasi quia.",
"content": "Nisi dolore aut sunt quaerat et ut tempore, dolore quo dolor asperiores aut.",
"user_id": 1,
"status": 1,
"created_by": "system",
"created_at": "2016-10-25 01:40:22",
"updated_at": "2016-10-25 01:40:22"
}
}
```<file_sep>/app/Http/Controllers/Backend/NewsController.php
<?php
namespace App\Http\Controllers\Backend;
use Illuminate\Http\Request;
use App\DataTables\NewsDataTables;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Kris\LaravelFormBuilder\FormBuilder;
use App\Forms\NewsForm;
use App\Models as Md;
class NewsController extends Controller
{
use AccessCheckerTrait;
protected $model;
protected $title = "Berita";
protected $url = "news";
protected $folder = "modules.news";
protected $form;
public function __construct(
Md\News $model,
Md\Modules $modules
)
{
$this->model = $model;
$this->modules = $modules;
$this->form = NewsForm::class;
$this->info = $this->modules->makeInfo($this->url);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(NewsDataTables $dataTable)
{
$this->checkAccess('index');
$data['title'] = $this->title;
$data['breadcrumb'] = $this->url;
return $dataTable->render($this->folder . '.index', $data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(FormBuilder $formBuilder)
{
$this->checkAccess('create');
$form = $formBuilder->create($this->form, [
'method' => 'POST',
'route' => $this->url . '.store'
]);
return view($this->folder . '.form', [
'title' => $this->title,
'form' => $form,
'breadcrumb' => 'new-' . $this->url
]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Requests\NewsRequest $request)
{
$this->checkAccess('create');
$input = $request->except(['save_continue','photo']);
$input['slug'] = str_slug($request->get('title'));
$input['user_id'] = \Auth::user()->id;
if ($request->hasFile('photo')) {
$input['image'] = (new \ImageUpload($request))->upload();
}
$query = $this->model->create($input);
$result = $query->id;
$save_continue = \Input::get('save_continue');
$redirect = empty($save_continue) ? $this->url :
$this->url.'/'.$result.'/edit';
return redirect()->to($redirect)->with(
'message', $this->title.' berhasil dibuat.'
);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id){}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(FormBuilder $formBuilder, $id)
{
$this->checkAccess('edit');
$model = $this->model->find($id);
$form = $formBuilder->create($this->form, [
'method' => 'PUT',
'url' => route($this->url . '.update', $id),
'model' => $model
]);
return view($this->folder . '.form', [
'title' => $this->title,
'form' => $form,
'row' => $model,
'breadcrumb' => 'new-' . $this->url
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Requests\NewsRequest $request, $id)
{
$this->checkAccess('edit');
$input = $request->except(['save_continue','photo']);
$input['slug'] = str_slug($request->get('title'));
$input['user_id'] = \Auth::user()->id;
if($request->hasFile('photo')) {
$input['image'] = (new \ImageUpload($request))->upload();
}
$query = $this->model->find($id)->update($input);
$result = $id;
$save_continue = \Input::get('save_continue');
$redirect = empty($save_continue) ? $this->url :
$this->url.'/'.$result.'/edit';
return redirect()->to($redirect)->with(
'message', $this->title.' berhasil diubah.'
);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->checkAccess('delete');
$find = $this->model->find($id);
$find->delete();
return response()->json([
'message' => $this->title.' Berhasil dihapus.'
]);
}
}
<file_sep>/app/Transformers/ArticlesTransformer.php
<?php
namespace App\Transformers;
use App\Models\News;
use League\Fractal\TransformerAbstract;
class ArticlesTransformer extends TransformerAbstract
{
public function transform(News $articles)
{
return [
'id' => $articles->id,
'title' => $articles->title,
'slug' => $articles->slug,
'content' => $articles->content,
'user_id' => $articles->user_id
];
}
}<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
$data = [
[
'id' => 1,
'name' => 'Admin'
],
[
'id' => 2,
'name' => 'Editor'
]
];
foreach ($data as $item) {
\DB::table('groups')->insert(
[
'group_id' => $item['id'],
'group_name' => $item['name'],
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]
);
}
\DB::table('users')->insert([
[
'username' => 'superadmin',
'password' => <PASSWORD>('<PASSWORD>'),
'email' => '<EMAIL>',
'name' => 'Programmer Superadmin',
'group_id' => 1,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]
]);
\DB::table('users')->insert([
[
'username' => 'editor',
'password' => <PASSWORD>'),
'email' => '<EMAIL>',
'name' => 'Editor App',
'group_id' => 2,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]
]);
$dataModules = [
[
'module_name' => 'groups',
'module_name_alias' => 'Kelompok',
'module_db' => 'groups',
'function' => 'index,create,edit,delete',
'function_alias' => 'index,tambah,ubah,hapus',
'description' => 'Group Desc'
],
[
'module_name' => 'news',
'module_name_alias' => 'Artikel',
'module_db' => 'news',
'function' => 'index,create,edit,delete',
'function_alias' => 'index,tambah,ubah,hapus',
'description' => 'News Desc'
],
[
'module_name' => 'users',
'module_name_alias' => 'Pengguna',
'module_db' => 'users',
'function' => 'index,create,edit,delete',
'function_alias' => 'index,tambah,ubah,hapus',
'description' => 'Users Desc'
],
[
'module_name' => 'modules',
'module_name_alias' => 'Module',
'module_db' => 'modules',
'function' => 'index,create,edit,access,delete',
'function_alias' => 'index,tambah,ubah,acl,hapus',
'description' => 'Users Desc'
]
];
foreach ($dataModules as $item) {
\DB::table('modules')->insert(
[
'module_name' => $item['module_name'],
'module_name_alias' => $item['module_name_alias'],
'module_db' => $item['module_db'],
'function' => $item['function'],
'function_alias' => $item['function_alias'],
'description' => $item['description'],
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]
);
}
}
}
<file_sep>/app/Http/Controllers/Api/ApiController.php
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\JWTAuth;
use App\Library\Token;
use App\Models as Md;
use App\User;
class ApiController extends Controller
{
use Token;
private $user, $jwtAuth;
public function __construct(
User $user,
JWTAuth $jwtAuth
)
{
$this->middleware(
'auth.jwt.api',
['except' => ['postLogin']]
);
$this->user = $user;
$this->jwtAuth = $jwtAuth;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return response()->json([
'messages' => 'Api Testing'
]);
}
/**
* Auth Api.
*
* @return \Illuminate\Http\Response
*/
public function postLogin(Requests\ApiLoginRequest $request)
{
if (!Auth::attempt(['username' => $request['username'], 'password' => $request['<PASSWORD>']])) {
return response()->json(['messages' => 'Username dan Password Tidak Cocok']);
}
$select = $this->user->whereUsername($request['username']);
$token = $this->createToken($select->first()->toArray());
return response()->json([
'token' => $token,
'data' => $select->first()->toArray()
]);
}
public function getLogout()
{
$token = $this->jwtAuth->getToken();
$this->jwtAuth->invalidate($token);
return response()->json(['messages' => 'Berhasil Keluar']);
}
}
<file_sep>/app/Http/Controllers/Backend/GroupsController.php
<?php
namespace App\Http\Controllers\Backend;
use Illuminate\Http\Request;
use App\DataTables\GroupsDataTables;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Kris\LaravelFormBuilder\FormBuilder;
use App\Forms\GroupsForm;
use App\Models as Md;
class GroupsController extends Controller
{
use AccessCheckerTrait;
protected $model;
protected $title = "Grup Pengguna";
protected $url = "groups";
protected $folder = "modules.groups";
protected $form;
public function __construct(
Md\Groups $model,
Md\Modules $modules
)
{
$this->model = $model;
$this->modules = $modules;
$this->form = GroupsForm::class;
/* For Acl */
$this->info = $this->modules->makeInfo($this->url);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(GroupsDataTables $dataTable)
{
$this->checkAccess('index');
$data['title'] = $this->title;
$data['breadcrumb'] = $this->url;
return $dataTable->render($this->folder . '.index', $data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(FormBuilder $formBuilder)
{
$this->checkAccess('create');
$form = $formBuilder->create($this->form, [
'method' => 'POST',
'route' => $this->url . '.store'
]);
return view($this->folder . '.form', [
'title' => $this->title,
'form' => $form,
'breadcrumb' => 'new-' . $this->url
]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Requests\GroupsRequest $request)
{
$this->checkAccess('create');
$query = $this->model->create($request->except(['save_continue']));
$result = $query->id;
$save_continue = \Input::get('save_continue');
$redirect = empty($save_continue) ? $this->url :
$this->url.'/'.$result.'/edit';
return redirect()->to($redirect)->with(
'message', $this->title.' berhasil dibuat.'
);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id){}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(FormBuilder $formBuilder, $id)
{
$this->checkAccess('edit');
$model = $this->model->find($id);
$form = $formBuilder->create($this->form, [
'method' => 'PUT',
'url' => route($this->url . '.update', $id),
'model' => $model
]);
return view($this->folder . '.form', [
'title' => $this->title,
'form' => $form,
'breadcrumb' => 'new-' . $this->url
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Requests\GroupsRequest $request, $id)
{
$this->checkAccess('edit');
$query = $this->model->find($id)->update($request->except(['save_continue']));
$result = $id;
$save_continue = \Input::get('save_continue');
$redirect = empty($save_continue) ? $this->url :
$this->url.'/'.$result.'/edit';
return redirect()->to($redirect)->with(
'message', $this->title.' berhasil diubah.'
);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->checkAccess('delete');
$find = $this->model->find($id);
$find->delete();
return response()->json([
'message' => $this->title.' Berhasil dihapus.'
]);
}
}
<file_sep>/app/Helpers/AclHelper.php
<?php
class AclHelper {
public static function takeFunction($module_id = "", $origin = ""){
$module = App\Models\Modules::where('module_id',$module_id)->first();
$listfunction = ($origin <> ""
? explode(',', $module->function)
: explode(',', $module->function_alias) );
return $listfunction;
}
public static function takeNumberFunction($module_id= "", $keyOut=""){
$takeList = self::takeFunction($module_id, "origin");
foreach ($takeList as $key => $value) {
if($key == $keyOut)
$valueFunction = $value;
}
return $valueFunction;
}
public static function takePermissionFunction(
$groupId,
$module_id,
$valuefunction,
$acl = ""
)
{
$data = App\Models\Modules_access::where('module_id',$module_id)
->where('group_id',$groupId)
->get();
$listaccess = ($data->count() > 0 ? json_decode($data->first()->access_data, true) : 0) ;
if ($listaccess > 0) :
$valueacces = isset($listaccess[''.$valuefunction.'']) ?
$listaccess[''.$valuefunction.''] : "0" ;
if ($valueacces == "1") :
return "checked";
else :
return "";
endif;
else :
return "";
endif;
}
/* Menu Addons */
public static function menuHeadAddOns($module){
$idModuel = App\Models\Modules::where('module_name',$module);
if ($idModuel->count() > 0 ) {
$moduleAddOns = App\Models\Modules_addons::where(
'module_id',$idModuel->first()->module_id
);
if ($moduleAddOns->count() > 0) {
if ($moduleAddOns->first()->active==1) {
return 1;
}else{
return 0;
}
}else{
return 0;
}
}else{
return 0;
}
}
}<file_sep>/app/Forms/UsersForm.php
<?php namespace App\Forms;
use Kris\LaravelFormBuilder\Form;
class UsersForm extends Form
{
public function buildForm()
{
$this
->add('username','text')
->add('name','text')
->add('email','text')
->add('password','<PASSWORD>')
->add('password_confirmation','<PASSWORD>')
->add('photo','file',[
'attr' => [
'id' => 'file',
'onchange' => 'readUrl(this)'
]
]);
$this->add('group_id', 'select', [
'attr' => ['class' => 'frm-e form-control', 'id' => 'groupInput'],
'choices' => \App\Models\Groups::pluck("group_name", "group_id")
->toArray(),
'empty_value' => '- Pilih Grup -',
'label' => 'Pengguna Untuk Grup'
]);
}
}<file_sep>/app/Http/Controllers/Api/ArticlesController.php
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Serializers\ArticlesSerializer;
use App\Transformers\ArticlesTransformer;
use Tymon\JWTAuth\JWTAuth;
use App\Models as Md;
use League\Fractal\Manager;
use League\Fractal\Resource\Collection;
class ArticlesController extends Controller
{
public function __construct(
Md\News $news,
JWTAuth $jwtAuth
)
{
$this->middleware(
'auth.jwt.api',
['except' => ['']]
);
$this->news = $news;
$this->jwtAuth = $jwtAuth;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$articles = $this->news->whereStatus('1')->get(['id', 'title', 'slug', 'content','user_id']);
$resource = new Collection($articles, new ArticlesTransformer());
$array = $this->serializeOutput($resource);
return response()->json([
// $request,
$array
]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$articles = $this->news->find($id);
return response()->json([
'data' => $articles
]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$articles = $this->news->find($id)->delete();
return response()->json([
'message' => "Article Berhasil Dihapus"
]);
}
public function serializeOutput($resource)
{
$manager = new Manager();
$manager->setSerializer(new ArticlesSerializer());
$articles = $manager->createData($resource)->toArray();
$count = count($articles['articles']);
return array_add($articles, "count", $count);
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => 'auth'], function () {
Route::post('modules/storeAcl', 'Backend\\ModulesController@accessPost');
Route::get('modules/access', 'Backend\\ModulesController@access');
Route::resource('modules', 'Backend\\ModulesController');
Route::resource('/groups', 'Backend\GroupsController');
Route::resource('/users', 'Backend\UsersController');
Route::resource('/news', 'Backend\NewsController');
});
Auth::routes();
Route::get('/home', 'HomeController@index');
<file_sep>/app/Library/Token.php
<?php
namespace App\Library;
use JWTAuth;
use JWTFactory;
trait Token
{
protected function createToken($array)
{
$payload = JWTFactory::make($array);
return JwtAuth::encode($payload)->get();
}
protected function getAuthenticatedUser()
{
$token = JWTAuth::getToken();
return JWTAuth::decode($token)->get();
}
}<file_sep>/app/Http/Controllers/Backend/UsersController.php
<?php
namespace App\Http\Controllers\Backend;
use Illuminate\Http\Request;
use App\DataTables\UsersDataTables;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Kris\LaravelFormBuilder\FormBuilder;
use App\Forms\UsersForm;
use App\User;
use App\Models as Md;
class UsersController extends Controller
{
use AccessCheckerTrait;
protected $model;
protected $title = "User ";
protected $url = "users";
protected $folder = "modules.users";
protected $form;
public function __construct(
User $model,
Md\Modules $modules
)
{
$this->model = $model;
$this->modules = $modules;
$this->form = UsersForm::class;
/* For Acl */
$this->info = $this->modules->makeInfo($this->url);
}
/**
* Display a listing of the resource.
* type user : {admin,country,state,city,operator}
* @return \Illuminate\Http\Response
*/
public function index(UsersDataTables $dataTable)
{
$this->checkAccess('index');
$data['title'] = $this->title;
$data['breadcrumb'] = $this->url;
return $dataTable->render($this->folder . '.index', $data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(FormBuilder $formBuilder)
{
$this->checkAccess('create');
$form = $formBuilder->create($this->form, [
'method' => 'POST',
'route' => $this->url . '.store'
])->modify('group_id', 'select', [
'attr' => ['class' => 'frm-e form-control', 'id' => 'groupInput'],
'choices' => \App\Models\Groups::pluck("group_name", "group_id")->toArray(),
'selected' => \Auth::user()->group_id,
'empty_value' => '- Pilih Grup -',
'label' => 'Pengguna Untuk Grup'
]);
return view($this->folder . '.form', [
'title' => $this->title,
'form' => $form,
'breadcrumb' => 'new-' . $this->url
]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Requests\UsersRequest $request)
{
$this->checkAccess('create');
$input = $request->only([
'username','name','email','photo','group_id'
]);
$input['password'] = <PASSWORD>($request->get['password']);
if ($request->hasFile('photo')) {
$input['photo'] = (new \ImageUpload($request))->upload();
}
$query = $this->model->create($input);
$result = $query->id;
$save_continue = \Input::get('save_continue');
$redirect = empty($save_continue) ? $this->url :
$this->url.'/'.$result.'/edit';
return redirect()->to($redirect)->with('message',
$this->title.' berhasil dibuat.'
);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(FormBuilder $formBuilder, $id)
{
$this->checkAccess('edit');
$model = $this->model->find($id);
$form = $formBuilder->create($this->form, [
'method' => 'PUT',
'url' => route($this->url . '.update', $id),
'model' => $model
])->modify('group_id', 'select', [
'attr' => ['class' => 'frm-e form-control', 'id' => 'groupInput'],
'choices' => \App\Models\Groups::pluck("group_name", "group_id")->toArray(),
'selected' => $model->group_id,
'empty_value' => '- Pilih Grup -',
'label' => 'Pengguna Untuk Grup'
]);
return view($this->folder . '.form', [
'title' => $this->title,
'row' => $model,
'form' => $form,
'breadcrumb' => 'new-' . $this->url
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Requests\UsersRequest $request, $id)
{
$this->checkAccess('edit');
$input = $request->only([
'username','name','email','group_id'
]);
$inputPass = $request->only('password');
if($request->hasFile('photo')) {
$input['photo'] = (new \ImageUpload($request))->upload();
}
if(isset($inputPass['password']) && $inputPass['password'] != "")
$input['password'] = bcrypt($inputPass['password']);
$query = $this->model->find($id)->update($input);
$result = $id;
$save_continue = \Input::get('save_continue');
$redirect = empty($save_continue) ? $this->url :
$this->url.'/'.$result.'/edit';
return redirect()->to($redirect)->with('message',
$this->title.' berhasil diubah.'
);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->checkAccess('delete');
$find = $this->model->find($id);
$find->delete();
return response()->json([
'message' => $this->title.' Berhasil dihapus.'
]);
}
}
<file_sep>/app/Helpers/QueryHelper.php
<?php
class QueryHelper {
public static function resultProduct() {
return App\Models\Products::all();
}
}
<file_sep>/app/DataTables/NewsDataTables.php
<?php
namespace App\DataTables;
use App\Models\News;
use Yajra\Datatables\Services\DataTable;
class NewsDataTables extends DataTable
{
/**
* Display ajax response.
*
* @return \Illuminate\Http\JsonResponse
*/
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->editColumn('image','<img src="{!! GLobalHelper::checkImage($image) !!}" style="max-height:100px" class="thumbnail"> ')
->editColumn('content', function ($row) {
return str_limit($row->content,125);
})
->editColumn('created_at', function ($row) {
return \GLobalHelper::formatDate($row->created_at);
})
->editColumn('updated_at', function ($row) {
return \GLobalHelper::formatDate($row->updated_at);
})
->addColumn('action', function ($row) {
$column = "<a href=\"" . route('news.edit', $row->id) . "\" class=\"btn btn-flat btn-default btn-sm\" data-toggle=\"tooltip\" data-original-title=\"Edit\">
<i class=\"fa fa-pencil\"></i> Edit
</a>
<a href=\"" . route('news.destroy', $row->id) . "\" class=\"btn btn-flat btn-danger btn-sm btn-delete\" data-toggle=\"tooltip\" data-original-title=\"Delete\" onclick=\"swal_alert(this,null,'delete','" . csrf_token() . "'); return false;\">
<i class=\"fa fa-trash-o\"></i> Hapus
</a>";
return $column;
})
->make(true);
}
/**
* Get the query object to be processed by dataTables.
*
* @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Support\Collection
*/
public function query()
{
$query = News::query();
return $this->applyScopes($query);
}
/**
* Optional method if you want to use html builder.
*
* @return \Yajra\Datatables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->ajax('')
->addAction(['width' => '80px'])
->parameters($this->getBuilderParameters());
}
/**
* Get columns.
*
* @return array
*/
protected function getColumns()
{
return [
'title' => [
'title' => 'Judul',
'width' => '35%'
],
'image' => [
'title' => 'Image',
'width' => '15%'
],
'content' => [
'title' => 'Konten',
'width' => '25%'
],
'created_at' => [
'title' => 'Ditulis',
'width' => '15%'
],
'updated_at' => [
'title' => 'Diubah',
'width' => '15%'
],
];
}
/**
* Get filename for export.
*
* @return string
*/
protected function filename()
{
return 'groupsdatatables_' . time();
}
}
<file_sep>/app/Http/Controllers/Backend/ModulesController.php
<?php
namespace App\Http\Controllers\Backend;
use Illuminate\Http\Request;
use App\DataTables\ModulesDatatables;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Modules;
use Kris\LaravelFormBuilder\FormBuilder;
use App\Forms\ModulesForm;
use App\Models as Model;
class ModulesController extends Controller
{
use AccessCheckerTrait;
protected $model;
protected $title = "Modul";
protected $url = "modules";
protected $folder = "modules.module";
protected $form;
public function __construct(
Modules $modules,
Model\Groups $groups,
Model\Modules_access $modules_access
)
{
$this->model = $modules;
$this->modules = $modules;
$this->groups = $groups;
$this->modules_access = $modules_access;
$this->form = ModulesForm::class;
/* For Acl */
$this->info = $this->modules->makeInfo($this->url);
}
public function index(ModulesDatatables $dataTable)
{
$this->checkAccess('index');
$data['title'] = $this->title;
$data['breadcrumb'] = $this->url;
return $dataTable->render($this->folder . '.index', $data);
}
public function create(FormBuilder $formBuilder)
{
$this->checkAccess('create');
$form = $formBuilder->create($this->form, [
'method' => 'POST',
'route' => $this->url . '.store'
]);
return view($this->folder . '.form', [
'title' => $this->title,
'form' => $form,
'breadcrumb' => 'new-' . $this->url
]);
}
public function store(Requests\ModulesRequest $request)
{
$this->checkAccess('create');
$query = $this->model->create($request->only(['module_name', 'module_name_alias',
'function','function_alias', 'description']));
$result = $query->module_id;
$save_continue = \Input::get('save_continue');
$redirect = empty($save_continue) ? $this->url : $this->url.'/'.$result.'/edit';
return redirect()->to($redirect)->with('message', 'Modul berhasil dibuat.');
}
public function edit(FormBuilder $formBuilder, $id)
{
$this->checkAccess('edit');
$model = $this->model->find($id);
$form = $formBuilder->create($this->form, [
'method' => 'PUT',
'url' => route($this->url . '.update', $id),
'model' => $model
]);
return view($this->folder . '.form', [
'title' => $this->title,
'form' => $form,
'breadcrumb' => 'new-' . $this->url
]);
}
public function update(Requests\ModulesRequest $request, $id)
{
$this->checkAccess('edit');
$this->model->find($id)->update($request->only(['module_name', 'module_name_alias',
'function','function_alias', 'description']));
$save_continue = \Input::get('save_continue');
$redirect = empty($save_continue) ? $this->url : $this->url.'/'.$id.'/edit';
return redirect()->to($redirect)->with('message', 'Modul berhasil diubah.');
}
public function destroy($id)
{
$this->checkAccess('delete');
$find = $this->model->find($id);
$find->delete();
return response()->json(['message' => 'Modul Berhasil dihapus.']);
}
public function access(){
$this->checkAccess('access');
$data['title'] = $this->title;
$data['groups'] = $this
->groups
->where('group_id','<>',0)
->get();
$data['modules'] = $this->model->all();
$data['breadcrumb'] = $this->url;
return view($this->folder . '.acl', $data);
}
public function accessPost(Request $request){
$this->checkAccess('access');
$groupLoop = $this->groups->pluck('group_id')->toArray();
try {
\DB::beginTransaction();
foreach ($groupLoop as $valueGroups) {
$modules = $this->model->get()->toArray();
foreach ($modules as $value) {
$array = [];
/* Check Is Selected Function */
foreach (\AclHelper::takeFunction($value['module_id'], "origin") as $function) {
$field = 'function' . $valueGroups . $value['module_id'] . $function;
$getField = $request->get($field);
$array[$function] = (isset($getField) && "on" == $getField ? "1" : "0");
}
/* Encode From Array */
$dummy = json_encode($array);
$accessData = preg_replace('/\s/', '', $dummy);
$checkExist = $this->modules_access->where([
'group_id' => $valueGroups,
'module_id' => $value['module_id'],
])->first();
if (!is_null($checkExist)) {
$checkExist->update(['access_data' => $accessData]);
} else {
$this->modules_access->create([
'group_id' => $valueGroups,
'module_id' => $value['module_id'],
'access_data' => $accessData,
]);
}
}
}
\DB::commit();
} catch (\Exception $e) {
\DB::rollback();
\Log::info($e);
return redirect($this->url.'/access')->with('error',
'Terjadi kesalahan, silahkan ulangi beberapa saat lagi.');
}
return redirect($this->url.'/access')->with('message', 'Data Berhasil Disimpan!');
}
}
|
ad4bb2d066f52aba3b2733caf5918d4a1db42ea9
|
[
"Markdown",
"PHP"
] | 20
|
PHP
|
Abdulhmid/article-api
|
086c9af218cbc32452e8f37eb696aa5f852ca225
|
ac9913cd60caad4a3db1bc00d2ebe6a920fab4b9
|
refs/heads/master
|
<repo_name>gabrielrubens/struts2-base<file_sep>/README.md
struts2-base
============
Projeto de base do Struts 2 com o Jetty Embarcado, Testes de Unidade e em breve com Selenium
Depois de fazer o fork e clonar o projeto é só seguir os seguintes passos:
1 - Instalar o ant http://ant.apache.org/
2 - Entrar no projeto e rodar o comando ant jetty.run
Para rodar os testes pela linha de comando: ant test
<file_sep>/src/main/java/br/com/gabrielrubens/base/action/PessoaAction.java
package br.com.gabrielrubens.base.action;
import java.util.List;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import br.com.gabrielrubens.base.dao.PessoaDao;
import br.com.gabrielrubens.base.model.Pessoa;
@Namespace(value="/pessoa")
public class PessoaAction {
private PessoaDao dao;
private List<Pessoa> pessoas;
public PessoaAction(PessoaDao dao) {
this.dao = dao;
}
@Action(value="/",
results=@Result(name="ok", location="pessoa/lista.jsp"))
public String index(){
this.pessoas = dao.getPessoas();
return "ok";
}
public List<Pessoa> getPessoas() {
return pessoas;
}
}
<file_sep>/src/test/java/br/com/gabrielrubens/unit/base/action/PessoaActionTest.java
package br.com.gabrielrubens.unit.base.action;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import br.com.gabrielrubens.base.action.PessoaAction;
import br.com.gabrielrubens.base.dao.PessoaDao;
import br.com.gabrielrubens.base.model.Pessoa;
public class PessoaActionTest {
@Mock
private PessoaDao dao;
private PessoaAction pessoaAction;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
pessoaAction = new PessoaAction(dao);
}
@Test
public void deveTrazerAListaDePessoas(){
Mockito.when(dao.getPessoas()).thenReturn(Arrays.asList(new Pessoa()));
String retorno = pessoaAction.index();
Assert.assertEquals("ok", retorno);
}
}
|
5d3c22aac9471e3b7250a2b7f5546e587988d5b9
|
[
"Markdown",
"Java"
] | 3
|
Markdown
|
gabrielrubens/struts2-base
|
d91f80e660eb0b30fb2687ea55b9d554804fb87e
|
371f7436b2bbb5f0bbff40e9173b3ae27d7949c0
|
refs/heads/master
|
<repo_name>sebastianhutter/docker-swarm<file_sep>/README.md
# docker-swarm
Experiment with docker-swarm and glusterfs
The goal of the environment is to automatically setup and configure a docker environment with swarm and persistent storage with glusterfs<file_sep>/salt/stack/convoy/files/etc/docker/plugins/convoy.spec
unix:///var/run/convoy/convoy.sock" > /etc/docker/plugins/convoy.spec<file_sep>/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
#
# setup a docker and glusterfs environment
#
# srv-gluster-01 - gluster server (+ salt master + consul server (with ui) + swarm master) + nomad master)
# srv-gluster-02 - gluster server (+ consul server + swarm master + nomad master)
# srv-docker-01 - docker node
# srv-docker-02 - docker node
# srv-docker-03 - docker node
# Requirements:
# - hostmanager plugin installed: https://github.com/devopsgroup-io/vagrant-hostmanager
# - vbox guest plugin installed: https://github.com/dotless-de/vagrant-vbguest
#
# globals
#
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
# get the vagrant root folder
vagrant_root = File.dirname(__FILE__)
# get the vb machine folder
line = `VBoxManage list systemproperties | grep "Default machine folder"`
machine_folder = line.split(':')[1].strip()
if machine_folder.to_s == ''
abort("could not get virtualbox machinefolder. aborting.")
end
# set the path to the pillar and saltstack
stack = File.join(vagrant_root, 'salt', 'stack')
pillar = File.join(vagrant_root, 'salt', 'pillar')
keys = File.join(vagrant_root, 'salt', 'keys')
etc = File.join(vagrant_root, 'salt', 'etc')
grains = File.join(vagrant_root, 'salt', 'grains')
nomad = File.join(vagrant_root, 'nomad')
#
# setup
#
# lets start configuring the machines
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
## hostmanager plugin
# automatically creates entries in /etc/hosts
config.hostmanager.enabled = true
# manage the vagrant host
config.hostmanager.manage_host = true
# manage the vagrant guests
config.hostmanager.manage_guest = true
# add private network ips
config.hostmanager.ignore_private_ip = false
# also add the offline vagrant hosts
config.hostmanager.include_offline = true
## setup srv-gluster-01
# the machine is also our salt master
config.vm.define "srv-gluster-01" do |node|
node.vm.box = "debian/jessie64"
node.vm.hostname = "srv-gluster-01"
node.vm.network :private_network, ip: "192.168.56.101"
node.hostmanager.aliases = "salt consul swarm"
node.vm.synced_folder stack, "/srv/salt"
node.vm.synced_folder pillar, "/srv/pillar"
node.vm.synced_folder nomad, "/srv/nomad"
node.vm.provision :salt do |salt|
salt.master_config = File.join(etc, 'master')
salt.minion_config = File.join(etc, 'minion')
salt.grains_config = File.join(grains, "srv-gluster-01")
salt.master_key = File.join(keys, "srv-gluster-01" + '.pem')
salt.master_pub = File.join(keys, "srv-gluster-01" + '.pub')
salt.minion_key = File.join(keys, "srv-gluster-01" + '.pem')
salt.minion_pub = File.join(keys, "srv-gluster-01" + '.pub')
salt.seed_master = {
"srv-gluster-01" => File.join(keys, 'srv-gluster-01.pub'),
"srv-gluster-02" => File.join(keys, 'srv-gluster-02.pub'),
"srv-docker-01" => File.join(keys, 'srv-docker-01.pub'),
"srv-docker-02" => File.join(keys, 'srv-docker-02.pub'),
"srv-docker-03" => File.join(keys, 'srv-docker-03.pub')
}
salt.install_type = "stable"
salt.install_master = true
salt.no_minion = false
salt.verbose = true
salt.colorize = true
salt.bootstrap_options = "-P -c /tmp"
salt.run_highstate = true
end
# write correct resolve.conf
#config.vm.provision "shell", inline: $script, run: "always"
node.vm.provider :virtualbox do |v|
v.customize ["modifyvm", :id, "--memory", 1024]
v.customize ["modifyvm", :id, "--cpus", 2]
v.customize ['modifyvm', :id, '--natdnshostresolver1', 'off']
v.customize ['modifyvm', :id, '--natdnsproxy1', 'off']
v.customize ['modifyvm', :id, '--natdnspassdomain1', 'off']
# add second disk for bricks
diskfile = File.join(machine_folder, "srv-gluster-01", 'disk2.vdi')
# Create and attach disk
unless File.exist?(diskfile)
v.customize ['createhd', '--filename', diskfile, '--format', 'VDI', '--size', 50 * 1024]
end
v.customize ['storagectl', :id, '--name', 'SATA Controller', '--portcount', 2]
v.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', diskfile]
end
end
## setup srv-gluster-02
config.vm.define "srv-gluster-02" do |node|
node.vm.box = "debian/jessie64"
node.vm.hostname = "srv-gluster-02"
node.vm.network :private_network, ip: "192.168.56.102"
node.vm.provision :salt do |salt|
salt.minion_config = File.join(etc, 'minion')
salt.grains_config = File.join(grains, "srv-gluster-02")
salt.minion_key = File.join(keys, "srv-gluster-02" + '.pem')
salt.minion_pub = File.join(keys, "srv-gluster-02" + '.pub')
salt.install_type = "stable"
salt.verbose = true
salt.colorize = true
salt.bootstrap_options = "-P -c /tmp"
salt.run_highstate = true
end
# write correct resolve.conf
#config.vm.provision "shell", inline: $script, run: "always"
node.vm.provider :virtualbox do |v|
v.customize ["modifyvm", :id, "--memory", 1024]
v.customize ["modifyvm", :id, "--cpus", 2]
v.customize ['modifyvm', :id, '--natdnshostresolver1', 'off']
v.customize ['modifyvm', :id, '--natdnsproxy1', 'off']
v.customize ['modifyvm', :id, '--natdnspassdomain1', 'off']
# add second disk for bricks
diskfile = File.join(machine_folder, "srv-gluster-02", 'disk2.vdi')
# Create and attach disk
unless File.exist?(diskfile)
v.customize ['createhd', '--filename', diskfile, '--format', 'VDI', '--size', 50 * 1024]
end
v.customize ['storagectl', :id, '--name', 'SATA Controller', '--portcount', 2]
v.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', diskfile]
end
end
## setup 3 docker engines
config.vm.define "srv-docker-01" do |node|
node.vm.box = "debian/jessie64"
node.vm.hostname = "srv-docker-01"
node.vm.network :private_network, ip: "192.168.56.111"
node.vm.provision :salt do |salt|
salt.minion_config = File.join(etc, 'minion')
salt.grains_config = File.join(grains, "srv-docker-01")
salt.minion_key = File.join(keys, "srv-docker-01" + '.pem')
salt.minion_pub = File.join(keys, "srv-docker-01" + '.pub')
salt.install_type = "stable"
salt.verbose = true
salt.colorize = true
salt.bootstrap_options = "-P -c /tmp"
salt.run_highstate = true
end
# write correct resolve.conf
#config.vm.provision "shell", inline: $script, run: "always"
node.vm.provider :virtualbox do |v|
v.customize ["modifyvm", :id, "--memory", 512]
v.customize ["modifyvm", :id, "--cpus", 1]
v.customize ['modifyvm', :id, '--natdnshostresolver1', 'off']
v.customize ['modifyvm', :id, '--natdnsproxy1', 'off']
v.customize ['modifyvm', :id, '--natdnspassdomain1', 'off']
# add second disk for bricks
diskfile = File.join(machine_folder, "srv-docker-01", 'disk2.vdi')
# Create and attach disk
unless File.exist?(diskfile)
v.customize ['createhd', '--filename', diskfile, '--format', 'VDI', '--size', 50 * 1024]
end
v.customize ['storagectl', :id, '--name', 'SATA Controller', '--portcount', 2]
v.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', diskfile]
end
end
config.vm.define "srv-docker-02" do |node|
node.vm.box = "debian/jessie64"
node.vm.hostname = "srv-docker-02"
node.vm.network :private_network, ip: "192.168.56.112"
node.vm.provision :salt do |salt|
salt.minion_config = File.join(etc, 'minion')
salt.grains_config = File.join(grains, "srv-docker-02")
salt.minion_key = File.join(keys, "srv-docker-02" + '.pem')
salt.minion_pub = File.join(keys, "srv-docker-02" + '.pub')
salt.install_type = "stable"
salt.verbose = true
salt.colorize = true
salt.bootstrap_options = "-P -c /tmp"
salt.run_highstate = true
end
# write correct resolve.conf
#config.vm.provision "shell", inline: $script, run: "always"
node.vm.provider :virtualbox do |v|
v.customize ["modifyvm", :id, "--memory", 512]
v.customize ["modifyvm", :id, "--cpus", 1]
v.customize ['modifyvm', :id, '--natdnshostresolver1', 'off']
v.customize ['modifyvm', :id, '--natdnsproxy1', 'off']
v.customize ['modifyvm', :id, '--natdnspassdomain1', 'off']
# add second disk for bricks
diskfile = File.join(machine_folder, "srv-docker-02", 'disk2.vdi')
# Create and attach disk
unless File.exist?(diskfile)
v.customize ['createhd', '--filename', diskfile, '--format', 'VDI', '--size', 50 * 1024]
end
v.customize ['storagectl', :id, '--name', 'SATA Controller', '--portcount', 2]
v.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', diskfile]
end
end
config.vm.define "srv-docker-03" do |node|
node.vm.box = "debian/jessie64"
node.vm.hostname = "srv-docker-03"
node.vm.network :private_network, ip: "192.168.56.113"
node.vm.provision :salt do |salt|
salt.minion_config = File.join(etc, 'minion')
salt.grains_config = File.join(grains, "srv-docker-03")
salt.minion_key = File.join(keys, "srv-docker-03" + '.pem')
salt.minion_pub = File.join(keys, "srv-docker-03" + '.pub')
salt.install_type = "stable"
salt.verbose = true
salt.colorize = true
salt.bootstrap_options = "-P -c /tmp"
salt.run_highstate = true
end
# write correct resolve.conf
#config.vm.provision "shell", inline: $script, run: "always"
node.vm.provider :virtualbox do |v|
v.customize ["modifyvm", :id, "--memory", 512]
v.customize ["modifyvm", :id, "--cpus", 1]
v.customize ['modifyvm', :id, '--natdnshostresolver1', 'off']
v.customize ['modifyvm', :id, '--natdnsproxy1', 'off']
v.customize ['modifyvm', :id, '--natdnspassdomain1', 'off']
# add second disk for bricks
diskfile = File.join(machine_folder, "srv-docker-03", 'disk2.vdi')
# Create and attach disk
unless File.exist?(diskfile)
v.customize ['createhd', '--filename', diskfile, '--format', 'VDI', '--size', 50 * 1024]
end
v.customize ['storagectl', :id, '--name', 'SATA Controller', '--portcount', 2]
v.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', diskfile]
end
end
end
|
74fca4a7e2253b6a5cb51460dce2f9f01deacdac
|
[
"Markdown",
"Ruby"
] | 3
|
Markdown
|
sebastianhutter/docker-swarm
|
d0f3445f383e5151b6ca4e0a3dc5f85bc8c6270d
|
0cebf2c1e71b935c00e1015374284fc8c252be32
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react'
const RoomContext = React.createContext();
export default class RoomProvider extends Component {
state = {
rooms:[],
sortedRooms:[],
featuredRooms:[],
loading: true,
type:'all',
capacity:'all',
price:0,
minPrice:0,
maxPrice:0,
minSize:0,
maxSize:0,
breakfast: false,
pets: false
};
componentDidMount(){
fetch('https://cors-anywhere.herokuapp.com/https://www.jayphan.fi/beachresort/rooms?_format=json')
.then(response => response.json())
.then(data => {
let rooms = this.formatData(data)
let featuredRooms = rooms.filter( room => room.field_featured === true)
let maxPrice = Math.max(...rooms.map(item => item.field_price))
let maxSize = Math.max(...rooms.map(item => item.field_size))
this.setState({
rooms,
featuredRooms,
sortedRooms: rooms,
loading: false,
price: maxPrice,
maxPrice,
maxSize,
})
});
};
formatData(data){
let rooms = data.map(x => {
let allowed = Object.keys(x).filter(y => y.match(/^field_/) && !y.match(/^field_images/) && !y.match(/^field_extra/))
let extras = x.field_extra.map(a => a=a.value);
let images = x.field_images.map(a => a=a.url);
const filtered = Object.keys(x)
.filter(key => allowed.includes(key))
.reduce((obj, key) => {
obj[key] = x[key][0].value;
return obj;
}, {});
filtered.extras=extras;
filtered.images=images;
return filtered
})
return rooms
};
getRoom = slug => {
let tempRooms = [...this.state.rooms];
const room = tempRooms.find(room => room.field_slug === slug);
return room;
};
handleChange = event => {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = event.target.name;
this.setState({
[name]: value
},
this.filterRoom
)
};
filterRoom = () => {
let{rooms,
type,
capacity,
price,
maxPrice,
minSize,
maxSize,
breakfast,
pets}= this.state
let tempRooms = [...rooms];
tempRooms = tempRooms.filter(room => room.field_size >= minSize && room.field_size <= maxSize)
if(type !== 'all'){
tempRooms = tempRooms.filter(room => room.field_type === type)
}
if(capacity !== 'all'){
tempRooms = tempRooms.filter(room => room.field_capacity >= capacity)
}
if(price !== maxPrice){
tempRooms = tempRooms.filter(room => room.field_price <= price)
}
if(breakfast) {
tempRooms = tempRooms.filter(room => room.field_breakfast===true)
}
if(pets) {
tempRooms = tempRooms.filter(room => room.field_pets===true)
}
this.setState({
sortedRooms: tempRooms
})
}
render() {
return (
<RoomContext.Provider value={{...this.state, getRoom: this.getRoom, handleChange: this.handleChange}}>
{this.props.children}
</RoomContext.Provider>
)
}
}
const RoomConsumer = RoomContext.Consumer;
export{RoomProvider, RoomConsumer, RoomContext};
<file_sep>import React, { Component } from 'react'
import RoomFilter from '../components/RoomFilter'
import Roomlist from '../components/Roomlist'
import {RoomConsumer} from '../context'
import Loading from './Loading'
export default class RoomContainer extends Component {
render() {
return(
<RoomConsumer>
{
value => {
const {loading,sortedRooms,rooms} = value
if (loading) {
return <Loading></Loading>
}
return (
<>
<RoomFilter rooms={rooms}></RoomFilter>
<Roomlist rooms={sortedRooms}></Roomlist>
</>
);
}}
</RoomConsumer>
)
}
}
|
453351dc28a6d8b66dffc6a4f910e24ec6085663
|
[
"JavaScript"
] | 2
|
JavaScript
|
leopark9497/drupalheadless-react
|
cc661703e7d45f21c2cff99880435dd66da5bad8
|
32186722df34c5982a5825e77943563aaee6348e
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
from __future__ import print_function
import sys, gym
from pyglet.window import key
import gym_gridworld
from gym_gridworld.envs.gridworld_env import UP, DOWN, LEFT, RIGHT, NOOP
#
# Test yourself as a learning agent! Pass environment name as a command-line argument.
#
env = gym.make('SequentialGridworldStochastic-v0' if len(sys.argv) < 2 else sys.argv[1])
if not hasattr(env.action_space, 'n'):
raise Exception('Keyboard agent only supports discrete action spaces')
ACTIONS = env.action_space.n
ROLLOUT_TIME = 1000
SKIP_CONTROL = 0 # Use previous control decision SKIP_CONTROL times, that's how you
# can test what skip is still usable.
human_action = 0
human_wants_restart = False
human_sets_pause = False
def key_press(k, mod):
global human_action, human_wants_restart, human_sets_pause
human_action = NOOP
if k == key.R: human_wants_restart = True
if k == key.LEFT: human_action = LEFT
if k == key.RIGHT: human_action = RIGHT
if k == key.UP: human_action = UP
if k == key.DOWN: human_action = DOWN
def key_release(k, mod):
global human_action
human_action = NOOP
# if k == key.LEFT: human_action = LEFT
# if k == key.RIGHT: human_action = RIGHT
# if k == key.UP: human_action = UP
# if k == key.DOWN: human_action = DOWN
env.render()
env.unwrapped.viewer.window.on_key_press = key_press
env.unwrapped.viewer.window.on_key_release = key_release
def rollout(env):
global human_action, human_wants_restart, human_sets_pause
human_wants_restart = False
obser = env.reset()
skip = 0
for t in range(ROLLOUT_TIME):
if not skip:
# print("taking action {}".format(human_agent_action))
a = human_action
skip = SKIP_CONTROL
else:
skip -= 1
obser, r, done, info = env.step(human_action)
print('Reward = {}'.format(r))
env.render()
if done: break
if human_wants_restart: break
while human_sets_pause:
env.render()
import time
time.sleep(0.1)
print("ACTIONS={}".format(ACTIONS))
print("Press keys 1 2 3 ... to take actions 1 2 3 ...")
print("No keys pressed is taking action 0")
while 1:
rollout(env)
<file_sep>import time
import gym
import gym_gridworld
import matplotlib.pyplot as plt
from gym_gridworld.envs.gridworld_env import NOOP, UP, DOWN, LEFT, RIGHT
plt.interactive(True)
# env = gym.make('Gridworld4-v0')
env = gym.make('Gridworld1Stochastic-v0')
# env = gym.make('SequentialGridworldStochastic-v0')
state = env.reset()
env.seed(0)
# actions = [RIGHT, RIGHT, RIGHT, RIGHT, DOWN, DOWN, DOWN, LEFT, LEFT, LEFT, LEFT, ]
start = time.time()
for i in range(10000):
# state, reward, done, info = env.step(actions[i % len(actions)])
state, reward, done, info = env.step(env.action_space.sample())
env.render('human')
if done or i % 60 == 0:
end = time.time()
print('avg_episode time = {}'.format(end - start))
start = time.time()
state = env.reset()
<file_sep># gym-gridworld
Basic implementation of gridworld game
for reinforcement learning research.
## Install gym-gridworld
install virtual environment for gridworld
cd gym-gridworld
conda env create -f environment.yml
source gridworld
pip install -e .
## Use gym-gridworld
import gym
import gym_gridworld
env = gym.make('gridworld-v0')
_ = env.reset()
_ = env.step(env.action_space.sample())
## Visualize gym-gridworld
In order to visualize the gridworld, you need to set `env.verbose` to `True`
env.verbose = True
_ = env.reset()
|
dc29fe1f62023d53717c02aa7deb339457a8c883
|
[
"Markdown",
"Python"
] | 3
|
Python
|
nadavbh12/gym-gridworld
|
02a3d1cf1bf9fb7379328d90a71478f8f7184333
|
6b4ac82cef6f2dedbc9f2f8874d0b43685872fbf
|
refs/heads/master
|
<repo_name>RasmusTraeholt/jokeservice<file_sep>/controllers/controller.js
"use strict";
const Joke = require('../models/joke');
const RegistryURL = require('../config').jokeRegistry;
const fetch = require('node-fetch');
// Returns a promise that resolves when the joke is created
exports.createJoke = function (setup, punchline) {
const joke = new Joke({
setup,
punchline
});
return joke.save();
};
// Returns a promise that resolves when a joke is found with the specified id
exports.getJoke = function (id) {
return Joke.findOne({ _id: id }).exec();
};
// Returns a promise that resolves with an array of all jokes
exports.getJokes = function () {
return Joke.find().exec();
};
// Returns a promise that resolves when a joke is found and deleted with specified id
exports.deleteJoke = function (id) {
return Joke.findOneAndDelete({ _id: id }).exec();
};
// Function to edit a Joke with new setup and punchline through specific id
exports.editJoke = function (id, setup, punchline) {
return Joke.findOneAndUpdate(
{ _id: id },
{ setup: setup, punchline: punchline },
{ new: true }).exec();
};
// Function to post new joke to selected Site. expexted return: json with the deleted joke.
exports.postJokeToSite = async function(id, setup, punchline) {
try {
const data = {setup: setup, punchline: punchline};
const site = await exports.findService(id);
const response = await fetch(exports.checkUrl(site.address) + 'api/jokes/', {
method: "POST",
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json' }
})
return await response.json();
} catch (err) {
console.log(err);
}
};
// Function to post a joke to another Site. Expected return: json with the updated joke.
exports.editOtherSiteJoke = async function(siteid, id, setup, punchline) {
try {
const data = {setup: setup, punchline: punchline};
const site = await exports.findService(siteid);
const response = await fetch(exports.checkUrl(site.address) + 'api/jokes/' + id, {
method: "PUT",
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json' }
})
return await response.json();
} catch (err) {
console.log(err);
}
}
// Returns JSON with all registered services from RegistryURL
exports.getOthersites = async function () {
const response = await fetch(RegistryURL + '/api/services');
const json = await response.json();
return json;
};
// returns JSON with jokes from other site through id
exports.getOtherSiteJokes = async function (id) {
const site = await exports.findService(id);
const response = await fetch(exports.checkUrl(site.address) + 'api/jokes');
const json = await response.json();
return json;
};
// delete a joke from selected site. Expected return: json with the deleted joke
exports.deleteOtherSiteJoke = async function(siteid, id) {
try {
const site = await exports.findService(siteid);
const response = await fetch(exports.checkUrl(site.address) + 'api/jokes/' + id, {
method: "DELETE",
headers: { 'Content-Type': 'application/json' }
})
return await response.json();
} catch (err) {
console.log(err);
}
}
// returns site found with id
exports.findService = async function(id) {
const sites = await exports.getOthersites();
const site = sites.find(site => site._id == id);
return site;
};
// deletes a service from https://krdo-joke-registry.herokuapp.com/api/services and returns the deleted site
exports.deleteService = async function (address, secret) {
const data = { address: address, secret: secret };
const response = await fetch('https://krdo-joke-registry.herokuapp.com/api/services', {
method: "DELETE",
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json' }
})
const json = await response.json();
return json;
};
// returns a string with a new url, where it has been tested if the original url has / at the end or not
exports.checkUrl = function(url) {
const regex = /\/$/;
if (!regex.test(url)) {
url += '/';
}
return url
};<file_sep>/readme.txt
Heroku app: https://jokeservice69.herokuapp.com/
- Start med at vælge en jokeservice side i dropdown menuen.
- Hvis valgte side har oprettet deres end-points korrekt, skulle den gerne fremvise de seneste 50 jokes (nyeste øverst) fra valgte, derudover vil man også kunne slette/rette og poste jokes til valgte, hvis de har opsat disse end-points korrekt.
- Vores egen side hedder: Dad jokes (Her kan du fx teste slet/ret og post funktionerne uden problemer).
- Der er brugt contenteditable på html elementerne der holder setup og punchline, så det er muligt at rette direkte i teksten i browseren ud for hver joke, selvom det ikke ligger i et input felt.
Mvh. Rasmus og <NAME>
|
1ffce99c92a54ee6aad720058959fc0f29713c40
|
[
"JavaScript",
"Text"
] | 2
|
JavaScript
|
RasmusTraeholt/jokeservice
|
23fb83604ea82f6d8f13454722fe58eb86b07f65
|
6765a38bcbb11b1ae3ac89b781647d2ea3b24fcd
|
refs/heads/master
|
<repo_name>fouad3/ShoppingList<file_sep>/www/js/services.js
angular.module('shoppingApp.services', [])
.factory('Categories', function($http) {
return {
fetch: function() {
return $http.get('https://www.bringmeister.de/api/categories')
.then(function(response) {
return response.data['categories'];
});
}
};
})
.factory('Products', function($http) {
var AddedProducts = [];
return {
fetch: function (category) {
return $http.get(' https://www.bringmeister.de/api/products?limit=30&offset=0&q=' + category)
.then(function (response) {
return response.data['products'];
});
},
addProduct: function (product) {
AddedProducts.push(product);
},
getAddedProducts: function () {
return AddedProducts;
}
}
});
<file_sep>/README.md
# Project : ShoppingList
## By <NAME>
## Table of contents
- [Description](#description)
- [Technologies](#technologies)
- [Required Libraries and Dependencies](#required-libraries-and-dependencies)
- [How to Run Project](#how-to-run-project)
- [Copyright and license](#copyright-and-license)
## Description
Hybrid application featuring shopping list for users to search for items and add them to the shopping list.
## Technologies
* [Ionic 1](https://ionicframework.com/docs/v1/)
* [Cordova](https://cordova.apache.org/docs/en/latest/)
* [AngularJS 1.5.3](https://code.angularjs.org/1.5.3/docs/guide)
* [Angular Ui-Router](https://ui-router.github.io/ng1/)
## Required Libraries and Dependencies
* Ionic CLI and Cordova:
* install them globally by using the following command:
```
npm install -g ionic cordova
```
## How to Run Project
1. clone or download this repository.
2. run the app on the browser by using the following commands:
1. Navigate to the project folder:
```
cd ShoppingList
```
2. Install app dependancies:
```
npm i
```
3. Start the app:
```
ionic serve
```
4. run and build the app for android and ios by using the following commands:
.
1. Navigate to the project folder:
```
cd ShoppingList
```
2. run and build for android:
```
ionic cordova platform add android
```
```
ionic cordova run android
```
3. run and build for ios:
```
ionic cordova platform add ios
```
```
ionic cordova build ios
```
```
ionic cordova emulate ios
```
## Copyright and License
- supplied without rights information.
|
091f30b5919a49d377e01aa534c69476017eccfd
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
fouad3/ShoppingList
|
bd0562373c788ff8486503f9077f1274587572b3
|
66e89166399a3329abb64f4e08f43a89c91d649e
|
refs/heads/master
|
<repo_name>stevendejongnl/todo-en-uno<file_sep>/src/store/getters.js
export const notes = state => state.notes;
<file_sep>/src/newtab/newtab.js
import 'vuetify/dist/vuetify.min.css';
import '@mdi/font/css/materialdesignicons.css';
import Vue from 'vue';
import App from './App';
import store from '../store';
import router from './router';
import Vuetify from 'vuetify';
global.browser = require('webextension-polyfill');
Vue.prototype.$browser = global.browser;
const vuetifyOptions = {
icons: {
iconfont: 'mdi', // default - only for display purposes
},
};
Vue.use(Vuetify);
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
router,
vuetify: new Vuetify(vuetifyOptions),
render: h => h(App),
});
<file_sep>/src/store/mutation-types.js
export const UPDATE_NOTES = 'UPDATE_NOTES';
<file_sep>/src/store/actions.js
import * as types from './mutation-types';
export const setNOTE = ({ commit }, payload) => {
commit(types.UPDATE_NOTES, payload);
};
<file_sep>/src/background.js
import store from './store';
global.browser = require('webextension-polyfill');
// alert(`Hello ${store.getters.foo}!`);
chrome.runtime.onInstalled.addListener(function() {
/**
* lets add a default domain
* for our options page
*/
chrome.storage.sync.set(
{
config: [
{
domain: 'docker',
color: '#2496ed',
},
],
},
null
);
});
|
bb037d755841edd83a408132ff267cc159fc8fbe
|
[
"JavaScript"
] | 5
|
JavaScript
|
stevendejongnl/todo-en-uno
|
54cb7e02a4cfdc8f47ed4ebee7abd439992e7280
|
cbbfced9d38ca73c1be6b15b2013910dec4495f3
|
refs/heads/master
|
<file_sep>#!/bin/bash
#
# Nagios plugin to monitor Java JMX (http://java.sun.com/jmx)attributes.
#
RDIR=`dirname $0`
export JAVA_OPTS="-Djava.util.logging.manager=java.util.logging.LogManager -Djava.util.logging.config.file=logging.properties"
/usr/bin/java $JAVA_OPTS -jar $RDIR/jmxMultiQuery.jar "$@"
<file_sep>#!/bin/bash
#
# Nagios plugin to monitor Java JMX (http://java.sun.com/jmx)attributes.
#
RDIR=`dirname $0`
#export JAVA_OPTS="-Djava.util.logging.manager=java.util.logging.LogManager -Djava.util.logging.config.file=logging.properties"
#export CLASSPATH="$CLASSPATH:$RDIR/jmxMultiQuery_lib/jboss-client.jar"
java $JAVA_OPTS -jar $RDIR/jmxMultiQuery.jar "$@"
<file_sep>package eapMonitor;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.jboss.dmr.*;
import org.jboss.as.controller.client.*;
import org.jboss.as.controller.client.helpers.*;
import javax.management.ObjectName;
import javax.management.OperationsException;
import javax.management.openmbean.CompositeDataSupport;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.RealmCallback;
public class eapClient {
private ModelControllerClient client = null;
private String [] Attributes;
private String [] samples;
private Long totalTime;
public eapClient(String addr, Integer port, String user, String password, String securityRealmName) throws Exception {
try {
this.client = createClient(addr, port, user, password, securityRealmName);
}
catch (IOException e1) {
e1.printStackTrace();
}
//return client;
}
static ModelControllerClient createClient(final String addr, final int port, final String username, final String password, final String securityRealmName) throws UnknownHostException {
final CallbackHandler callbackHandler = new CallbackHandler() {
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback current : callbacks) {
if (current instanceof NameCallback) {
NameCallback ncb = (NameCallback) current;
ncb.setName(username);
} else if (current instanceof PasswordCallback) {
PasswordCallback pcb = (PasswordCallback) current;
pcb.setPassword(<PASSWORD>());
} else if (current instanceof RealmCallback) {
RealmCallback rcb = (RealmCallback) current;
rcb.setText(rcb.getDefaultText());
} else {
throw new UnsupportedCallbackException(current);
}
}
}
};
return ModelControllerClient.Factory.create(InetAddress.getByName(addr), port, callbackHandler);
}
public void getJBossVersion() throws Exception {
ModelNode op = new ModelNode();
op.get(ClientConstants.OP).set("read-resource");
ModelNode returnVal = client.execute(op);
System.out.println("release-version: " + returnVal.get("result").get("release-version").asString());
System.out.println("release-codename: " + returnVal.get("result").get("release-codename").asString());
}
public List<Property> getObjectList(String object, String property, boolean includeRuntime, boolean recursive) throws Exception {
ModelNode op = new ModelNode();
op.get(ClientConstants.OP).set("read-resource");
op.get("recursive").set(recursive);
op.get("include-runtime").set(includeRuntime);
ModelNode response = new ModelNode();
List<Property> objectList = null;
Attributes = object.split("/");
if (Attributes != null && Attributes.length > 0){
for(int i=0; i<Attributes.length; i++){
if (Attributes[i].split("=").length == 2) {
String [] op_addr = Attributes[i].split("=");
op.get(ClientConstants.OP_ADDR).add(op_addr[0],op_addr[1]);
}
}
}
response = client.execute(new OperationBuilder(op).build());
reportFailure(response);
try {
ModelNode test = response.get(ClientConstants.RESULT).get(property);
if (test.isDefined()){
objectList = test.asPropertyList();
}
}
catch (Exception e){
e.printStackTrace();
}
return objectList;
}
@SuppressWarnings("static-access")
public Map<String,String> getAttribute(String object, String attribute, String attributeKey, String [] samples, boolean recursive, boolean runtime) throws IOException, InterruptedException {
/*String command = "-O "+object+" -A "+attribute;
if(attributeKey != null)
command = command+" -C "+attributeKey;
if(samples != null)
command = command+" samples "+samples.toString();
System.out.println(command);
*/
final ModelNode request = new ModelNode();
Map<String,String> eapAttr = new HashMap<String,String>();
ModelNode response = null;
ModelNode attr = null;
Object value = null;
request.get(ClientConstants.OP).set("read-resource");
Attributes = object.split("/");
if (Attributes != null && Attributes.length > 0){
for(int i=0; i<Attributes.length; i++){
if (Attributes[i].split("=").length == 2) {
//System.out.println("object: "+Attributes[i]);
String [] op_addr = Attributes[i].split("=");
//System.out.println("op_addr: "+op_addr[0]+" = "+op_addr[1]);
request.get(ClientConstants.OP_ADDR).add(op_addr[0],op_addr[1]);
}
}
}
request.get("recursive").set(recursive);
request.get("include-runtime").set(runtime);
try {
if (samples != null && samples.length == 3){
totalTime = (long) 0;
int sample = Integer.parseInt(samples[0]);
int delay = Integer.parseInt(samples[1]);
String algorithm = samples[2];
List<Long> values = new ArrayList();
for(int i=0; i<sample; i++){
Long startTime = System.nanoTime();
response = client.execute(new OperationBuilder(request).build());
value = response.get(ClientConstants.RESULT).get(attribute).asLong();
Thread.currentThread().sleep(delay);
Long endTime = System.nanoTime();
totalTime = endTime - startTime + totalTime;
values.add((Long) value);
}
if(algorithm.matches("getDiffOverTime")){
value = getDiffOverTime(values, totalTime);
}
} else {
response = client.execute(new OperationBuilder(request).build());
if (attributeKey != null)
value = response.get(ClientConstants.RESULT).get(attribute).get(attributeKey).toString().replaceAll("^\"|\"$|L$", "");
else
value = response.get(ClientConstants.RESULT).get(attribute).toString().replaceAll("^\"|\"$|L$", "");
if (value.toString().matches("undefined")){
value = 0;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (NullPointerException e) {
value = "0";
//e.printStackTrace();
}
eapAttr.put("Attribute", attribute);
eapAttr.put("Value", value.toString());
return eapAttr;
}
public Map<String,String> getAttributes(String object, boolean recursive, boolean runtime) throws IOException, InterruptedException {
final ModelNode request = new ModelNode();
Map<String,String> eapAttr = new HashMap<String,String>();
ModelNode response = null;
ModelNode attr = null;
Object value = null;
request.get(ClientConstants.OP).set("read-resource");
Attributes = object.split("/");
if (Attributes != null && Attributes.length > 0){
for(int i=0; i<Attributes.length; i++){
if (Attributes[i].split("=").length == 2) {
//System.out.println("object: "+Attributes[i]);
String [] op_addr = Attributes[i].split("=");
//System.out.println("op_addr: "+op_addr[0]+" = "+op_addr[1]);
request.get(ClientConstants.OP_ADDR).add(op_addr[0],op_addr[1]);
}
}
}
request.get("recursive").set(recursive);
request.get("include-runtime").set(runtime);
try {
response = client.execute(new OperationBuilder(request).build());
value = response.get(ClientConstants.RESULT);
} catch (IOException e) {
e.printStackTrace();
}
eapAttr.put("Attribute", object);
eapAttr.put("Value", value.toString());
return eapAttr;
}
public ModelNode getDSAttributes(String attribute) throws IOException {
final ModelNode request = new ModelNode();
request.get(ClientConstants.OP).set("read-resource");
request.get(ClientConstants.OP_ADDR).add("subsystem", "datasources");
request.get(ClientConstants.OP_ADDR).add("data-source", attribute);
request.get(ClientConstants.OP_ADDR).add("statistics", "pool");
request.get("recursive").set(true);
request.get("include-runtime").set(true);
final ModelNode response = client.execute(new OperationBuilder(request).build());
reportFailure(response);
return response.get(ClientConstants.RESULT);
}
public List<Property> getDataSources() throws IOException {
ModelNode request = new ModelNode();
ModelNode response = new ModelNode();
List<Property> dsList = null;
request.get(ClientConstants.OP).set("read-resource");
//request.get("recursive").set(true);
request.get(ClientConstants.OP_ADDR).add("subsystem", "datasources");
response = client.execute(new OperationBuilder(request).build());
reportFailure(response);
dsList = response.get(ClientConstants.RESULT).get("data-source").asPropertyList();
return dsList;
}
public List<Property> getXADataSources() throws IOException {
ModelNode request = new ModelNode();
ModelNode response = new ModelNode();
List<Property> dsList = null;
request.get(ClientConstants.OP).set("read-resource");
//request.get("recursive").set(true);
request.get(ClientConstants.OP_ADDR).add("subsystem", "datasources");
response = client.execute(new OperationBuilder(request).build());
reportFailure(response);
dsList = (response.get(ClientConstants.RESULT).get("xa-data-source").asPropertyList());
return dsList;
}
private static void reportFailure(final ModelNode node) {
if (!node.get(ClientConstants.OUTCOME).asString().equals(ClientConstants.SUCCESS)) {
final String msg;
if (node.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) {
if (node.hasDefined(ClientConstants.OP)) {
msg = String.format("Operation '%s' at address '%s' failed: %s", node.get(ClientConstants.OP), node.get(ClientConstants.OP_ADDR), node.get(ClientConstants.FAILURE_DESCRIPTION));
} else {
msg = String.format("Operation failed: %s", node.get(ClientConstants.FAILURE_DESCRIPTION));
}
} else {
msg = String.format("Operation failed: %s", node);
}
throw new RuntimeException(msg);
}
}
public void close() {
if(client != null){
try {
client.close();
client = null;
}
catch(Exception e) {}
}
}
private double getDiffOverTime(List<Long> values, Long time){
Float value = null;
value = (float) (values.get(values.size()-1) - values.get(0));
value = value/time;
return Double.parseDouble(decimalPlaces(value));
}
private String decimalPlaces(Float num){
DecimalFormat df = new DecimalFormat("###.##");
return df.format(num);
}
}
<file_sep>package eapMonitor;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jboss.dmr.*;
public class customMonitor {
private eapClient client = null;
public customMonitor(eapClient c){
this.client = c;
}
public List<String> getChildResourceNames(String appObject, String propertyList) throws Exception {
List<String> appList = new ArrayList <String>();
try {
List<Property> objects = client.getObjectList(appObject, propertyList, false, false);
if(objects != null){
for (Property obj : objects){
appList.add(obj.getName());
}
}
return appList;
} catch (Exception e){
e.printStackTrace();
return appList;
}
}
public List<String> getChildResourceNames(String appObject, String propertyList, boolean runtime, boolean recursive) throws Exception {
List<String> appList = new ArrayList <String>();
try {
List<Property> objects = client.getObjectList(appObject, propertyList, runtime, recursive);
if(objects != null){
for (Property obj : objects){
appList.add(obj.getName());
}
}
return appList;
} catch (Exception e){
e.printStackTrace();
return appList;
}
}
public List<Map<String,String>> buildMonitor(String object) throws Exception, InterruptedException {
Map<String,String> appAttr = new HashMap <String,String>();
List<Map<String,String>> appList = new ArrayList <Map<String,String>>();
eapMonitor monitor = null;
try {
monitor = new eapMonitor(false);
String monArgs = object;
monitor.parseArgs(monArgs.split(" "));
appAttr = client.getAttribute(monitor.getObject(), monitor.getAttribute(), monitor.getAttributeKey(), monitor.getSamples(), true, true);
appList.add(monitor.validate(appAttr));
return appList;
} catch (IOException e){
e.printStackTrace();
return appList;
} catch (InterruptedException e) {
e.printStackTrace();
return appList;
}
}
public List<Map<String,String>> buildMonitor(List<Map<String,String>> eapAttributeList, String object) throws Exception, InterruptedException {
Map<String,String> appAttr = new HashMap <String,String>();
List<Map<String,String>> appList = new ArrayList <Map<String,String>>();
eapMonitor monitor = null;
try {
monitor = new eapMonitor(eapAttributeList);
String monArgs = object;
monitor.parseArgs(monArgs.split(" "));
appAttr = client.getAttribute(monitor.getObject(), monitor.getAttribute(), monitor.getAttributeKey(), monitor.getSamples(), true, true);
appList.add(monitor.validate(appAttr));
return appList;
} catch (IOException e){
e.printStackTrace();
return appList;
} catch (InterruptedException e) {
e.printStackTrace();
return appList;
}
}
}
|
ac30a2ea81754555ea2e8361f2f9bc8cb03ef00f
|
[
"Java",
"Shell"
] | 4
|
Shell
|
ppresto/org.ctl.eap.Monitor
|
76a7989855bcf1f6508ad5fb8a6449dd940675ba
|
53e80427364caa37d4b8e9a94a059a95c257c8f6
|
refs/heads/master
|
<repo_name>strjahilev/reactbasenew<file_sep>/src/Menu/products-router.js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Products from "./products";
import Product from "./product";
class ProductsRouter extends React.Component{
render(){
return <div>
<Switch>
<Route exact path="/products" component={Products} />
<Route path="/products/:id" component={Product} />
</Switch>
</div>
}
}
export default ProductsRouter
|
badb2edbfe28dae374b3b42e891201c1fb431c11
|
[
"JavaScript"
] | 1
|
JavaScript
|
strjahilev/reactbasenew
|
2582366afa7594673b52172d9f2b54ec7fb05d7d
|
fc5511060bf12b0ff52f4d061d2a04afa9e5b99f
|
refs/heads/master
|
<file_sep># How to Setup the PsychGH Project
## Getting the Project
To get the latest, stable version of the PsychGH project, just run
`git clone https://github.com/TostySSB/psychgh.git`.
## Project Layout
After cloning the repository, you will see that we have three primary folders
in our project: `public`, `src`, and `docs`.
- `public` contains all of the bootstrapping code for the React application.
- `src` contains all of PsychGH's logic, components, and style sheets.
- `docs` contains all of the files for the user and developer documentation.
<file_sep>import React, { Component } from 'react';
import NavBar from '../components/NavBar'
//This is the Home view, it acts as a home page for our app and is a react component
export default class Home extends Component {
state = {
}
render () {
return (
<div id='container'>
<div>
<NavBar />
</div>
<p>Disclaimer: This is a Zero Feature Release, meaning that none of the final features of the product have been released yet.</p>
<p>For more information about Psych432 and how to obtain the current release view our documentation or our github page below.</p>
<a href="https://github.com/TostySSB/psychgh">GitHub</a>
<br />
<a href="Docs">View Documentation</a>
</div>
)
}
}<file_sep>
# Welcome to PsychGH!
PsychGH is an application for navigating and storing patient specific treatment
plans. To use PsychGH, please visit our [site](#).
To report a bug for PsychGH, please go to our [issues site](https://github.com/TostySSB/psychgh/issues) and follow our template for reporting an issue:
```
What happened?
What did you expect to happen?
What was the URL for the page where the bug occured?
```
A developer for PsychGH? Visit our [Developer documentation](#)!
|
a891de317545442a659a979d6043d902e5500ba3
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
TostySSB/psychgh
|
2fa77a22345d894ec25d34bc278efe8e1ee9dbb1
|
4d2fb1d32119dca70dadfb3ffc1548dfc35a5421
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.